# LongPort Developers Documentation # SDK
## LongPort OpenAPI SDK for Python [https://github.com/longportapp/openapi/tree/master/python](https://github.com/longportapp/openapi/tree/master/python) ### Install SDK You can install the SDK via Pip, or directly visit the [PyPI](https://pypi.org/project/longport/) page to download. ```bash $ pip install longport ``` > NOTE: In macOS system, the `pip` command default is Python 2. You may use `pip3` for use Python 3 version of PyPI. ### API Documents - https://longportapp.github.io/openapi/python/index.html ### Examples - https://github.com/longportapp/openapi/tree/master/examples/python ## LongPort OpenAPI SDK for Node.js [https://github.com/longportapp/openapi/tree/master/nodejs](https://github.com/longportapp/openapi/tree/master/nodejs) ### Install SDK You can install the SDK via Npm. ```bash $ npm install longport --save ``` [https://www.npmjs.com/package/longport](https://www.npmjs.com/package/longport) ### API Documents - https://longportapp.github.io/openapi/nodejs/index.html ### Examples - https://github.com/longportapp/openapi/tree/master/examples/nodejs ## LongPort OpenAPI SDK for Rust [https://github.com/longportapp/openapi/tree/master/rust](https://github.com/longportapp/openapi/tree/master/rust) ### Install SDK Add the following line to your `Cargo.toml` file ```toml [dependencies] longport = "4.0.5" ``` [https://crates.io/crates/longport](https://crates.io/crates/longport) ### API Documents - https://longportapp.github.io/openapi/rust/longport/index.html ### Examples - https://github.com/longportapp/openapi/tree/master/examples/rust ## LongPort OpenAPI SDK for Java [https://github.com/longportapp/openapi/tree/master/java](https://github.com/longportapp/openapi/tree/master/java) ### Install SDK Add the following line to your `pom.xml` file ```xml io.github.longport openapi-sdk 4.0.5 ``` [https://search.maven.org/artifact/io.github.longport/openapi](https://search.maven.org/artifact/io.github.longport/openapi) ### API Documents - https://longportapp.github.io/openapi/java/index.html ### Examples - https://github.com/longportapp/openapi/tree/master/examples/java ## LongPort OpenAPI SDK for Go [https://github.com/longportapp/openapi-go](https://github.com/longportapp/openapi-go) ### Install SDK - Go version >= 1.17 In your project directory, run: ```bash $ go get github.com/longportapp/openapi-go ``` [https://pkg.go.dev/github.com/longportapp/openapi-go](https://pkg.go.dev/github.com/longportapp/openapi-go) ### Examples - https://github.com/longportapp/openapi-go/tree/main/examples ## LongPort OpenAPI SDK for C/C++ [https://github.com/longportapp/openapi/tree/master/cpp](https://github.com/longportapp/openapi/tree/master/cpp) ### Download - [4.0.5](https://static.lbctrl.com/openapi-sdk/openapi-cpp-sdk-4.0.5.tar.gz) ### API Documents - https://longportapp.github.io/openapi/cpp/index.html ### Examples - https://github.com/longportapp/openapi/tree/master/examples/cpp
# Overview LongPort Developers provides programmatic interfaces for investors with research and development capabilities, enabling them to build trading or market analysis tools based on their own investment strategies. The platform covers the following categories: - **Quote** — Real-time and historical quotes, market depth, candlesticks, options/warrants data, subscriptions - **Fundamental** — Company profiles, financials, valuations, analyst ratings, market data, calendars - **News & Contents** — Market news, community topics, sharelist management - **Trade** — Create, amend, and cancel orders; query orders, executions, and assets - **Account** — Portfolio analysis, price alerts, DCA plans, watchlist - **MCP** — Model Context Protocol integration for AI assistant workflows ## Interface Type LongPort provides diversified access methods such as HTTP / WebSockets interfaces for accessing the underlying services and SDK (Python / C++, etc.) encapsulated in the upper layer, allowing flexible choices. ## How to Enable OpenAPI 1. Log in to the [LongPort App](https://longport.com/download) to complete the account opening process; 2. Log in to the [longport.com](https://longport.com) and enter the developer platform, complete the developer verification (OpenAPI permission application), and obtain a token. ## Quote Coverage
Market Symbol
HK Market Securities (including equities, ETFs, Warrants, CBBCs)
Hang Seng Index
US Market Securities (including stocks, ETFs)
Nasdsaq Index
OPRA Options
CN Market Securities (including stocks, ETFs)
Index
## Trading Supported trading functions include: | Market | Stock and ETF | Warrant & CBBC | Options | | --------- | ------------- | -------------- | ------- | | HK Market | ✓ | ✓ | | | US Market | ✓ | ✓ | ✓ | ## Rate Limit {#rate-limit} | Category | Limitation | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Quote API | | | Trade API | | :::success The [OpenAPI SDK](https://open.longport.com/sdk) has done effective frequency control internally: - Quote: The methods under `QuoteContext` will be actively controlled by the SDK according to the server's rate limit. When the request is too fast, the SDK will automatically delay the request. Therefore, you do not need to implement the frequency control details separately. - Trade: The methods under `TradeContext` are not limited by the SDK. Due to the special nature of the trading order placement scenario, this is left to the user to handle. ::: ## Pricing {#pricing} LongPort does not charge any additional fees for activating or using interface services. You only need to [open a LongPort Integrated A/C](https://longport.com/hk/download) and get OpenAPI service permissions to use it for free. For quote data subscription fees, please enter "Me - My Quotes - Quote Store" in the "LongPort" mobile app. For actual transaction fees, please contact the brokerage firm where you have opened your securities account. ## Other The OpenAPI services are provided by LongPort and the applicable affiliates (subject to the agreement). openapi-trade.longportapp.com # Index ## Docs ## 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 } } ``` ## Error Codes ### Error Codes | HTTP Status | Code | Message | Description | | ----------- | ------ | ---------------------- | ------------------------------------------------------------------ | | 403 | 403201 | signature invalid | signature is invalid | | 403 | 403202 | duplicate request | Repeat request, same request without replacement `x-timestamp` | | 403 | 403203 | apikey illegal | `App Key` is illegal | | 403 | 403205 | ip is not allowed | IP address is not authorized to access | | 401 | 401003 | token expired | `Access Token` expired, please refresh the Token | | 429 | 429001 | ip request ratelimit | Too frequent requests as a same IP address, please try again later | | 429 | 429002 | api request is limited | Too frequent requests on an API, please try again later | | 500 | 500000 | internal error | server internal error, please contact customer support | ## Llm # LLM Documentation Access LongPort Developers documentation is available in text formats that are easy for AI tools to ingest. Use the compact index for lightweight context, the full text bundle for complete ingestion, or fetch a single page by adding `.md` to its URL. ## llms.txt Use `llms.txt` as the default entry point when an AI client asks for an LLMs Text URL. - https://open.longportapp.com/llms.txt - Best for: quick indexing, custom docs in AI editors, and discovering relevant pages. ## llms-full.txt Use `llms-full.txt` when the AI tool can ingest a larger context or you need the full documentation text in one file. - https://open.longportapp.com/llms-full.txt - Best for: offline ingestion, full-project context, and building a local retrieval index. ## Markdown Pages Every documentation page also has a Markdown version. Add `.md` to the page URL. Examples: - https://open.longportapp.com/docs/getting-started.md - https://open.longportapp.com/docs/quote/overview.md - https://open.longportapp.com/skill/install.md Use page Markdown when you want to give an AI model one precise source instead of the full documentation set. ## LongPort MCP # LongPort MCP LongPort provides a hosted HTTP MCP (Model Context Protocol) service that lets AI coding assistants and chat tools use OpenAPI market data, account, portfolio, and trading capabilities without manually managing API keys. ## LongPort MCP Endpoint ```text https://mcp.longportapp.com ``` If your AI client asks for a transport type, choose HTTP or Streamable HTTP. ## Available Capabilities LongPort MCP exposes over 140+ MCP tools across OpenAPI workflows. Your client discovers available tools automatically on connect. | Capability | Coverage | | --- | --- | | Real-time market data | Quotes, candlesticks, depth, broker queues, trades, intraday capital flow | | Fundamentals and research | Company profiles, dividends, valuations, executive holdings, A/H premium | | Derivatives | Option chains, warrant filters, issuers, warrant quotes | | Account and portfolio | Balances, positions, cash flow, watchlists and groups | | Trading | Place, modify, and cancel orders, estimate max purchase quantity | | Automation | Price alerts and scheduled DCA plans | Actual tool availability depends on your region, account level, and granted OAuth scopes. ## Prerequisites - An active LongPort account with onboarding completed, or a paper trading account. - An AI client that supports HTTP MCP and OAuth authorization. ## Client Setup Configuration format can vary across client versions. Treat your client's official MCP documentation as the source of truth. The core parameter you need is the server URL: ```text https://mcp.longportapp.com ``` ### ChatGPT Enable Developer Mode, then add LongPort MCP as a custom app. Use these values: - Name: `LongPort` - Description: `LongPort Developers MCP Server.` - Connection / Server URL: `https://mcp.longportapp.com` - Authentication: OAuth ### Claude Code Run this command in your terminal: ```bash claude mcp add --transport http longport https://mcp.longportapp.com ``` Then open the `claude` terminal interface, type `/mcp`, select `longport`, and choose Authenticate to complete OAuth authorization. ### Codex Run this command in your terminal: ```bash codex mcp add longport --url https://mcp.longportapp.com ``` Then follow the OAuth authorization flow in Codex when prompted. ### Codex Desktop 1. Open Settings. 2. Go to MCP Servers. 3. Click Add Server. 4. Fill in: - Name: `longport` - Type: Streamable HTTP - URL: `https://mcp.longportapp.com` 5. Leave other fields empty. 6. Save, then click Authenticate on the `longport` entry. ## OAuth Authorization Flow LongPort MCP uses OAuth. You do not need to paste API keys or tokens into the client. 1. Add the LongPort MCP configuration and call a tool for the first time. 2. The client opens a browser tab with the LongPort login and consent page. 3. Sign in and approve the requested permission scopes. 4. After approval, the client receives credentials and MCP tools become available. 5. Credentials are refreshed automatically by the client. ## Client Compatibility LongPort MCP requires clients that support HTTP MCP and OAuth authorization. Clients with incomplete OAuth support can fail during the authorization flow. If a client fails to connect, check its version and MCP support documentation. ## Security Recommendations - Approve only the scopes required for your current task. - For order placement, explicitly instruct the AI to ask for human confirmation before executing. - Avoid copying OAuth credentials into untrusted environments. - Periodically review and revoke unused authorizations in your LongPort account security settings. ## Recommended Usage Pattern 1. Start with read-only tools, such as market data, account overview, and position queries. 2. Enable order placement only after verifying scope configuration and your own risk controls. 3. Add guardrails in prompts, such as "always confirm with me before placing an order". ## Troubleshooting ### OAuth Sign-in Failed - Confirm your LongPort account is in good standing and identity verification is complete. - Remove the existing MCP configuration from the client and re-add it to trigger a fresh authorization. - Check whether the requested scopes are supported for your account type. ### Connected But Some Tools Are Missing - Account or regional restrictions can limit certain markets or features. - If tool capabilities have been updated, re-authorize to receive the new scopes. ### Permission Denied On Trading Actions - Verify trading permissions and market eligibility on your account. - Confirm that the current MCP session's OAuth scopes include trading-related permissions. ## Overview This section mainly introduces the basic information of LongPort Developers, including how to access the API, how to use the API, how to obtain the API interface document, etc., the content is relatively primitive. :::success Tip It is recommended to directly use the SDK to access the API, the SDK has encapsulated the API call method, which is more convenient to use. https://open.longportapp.com/sdk ::: ## Notes | Precautions | Reference Documents | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | It is recommended to use the SDK of the respective language, instead of calling the native interface | [SDK Quick Start Page](../docs/getting-started) | | Read the OpenAPI introduction to enable the corresponding service | [How to enable OpenAPI](../docs/#how-to-enable-openapi) | | Read about OpenAPI access and restrictions in OpenAPI Introduction | [OpenAPI's permissions and restrictions](../docs/#permissions-and-restrictions) | | Common Error Codes for finding errors in interface calls | [Common Error Codes](../docs/error-codes) | ## REST API documentation convention format The main format of the server REST API documentation is as follows. ``` Request: Request Info Parameters Request Example Response: Response Headers Response Example Response Status Response Status ``` ### Request Info This section introduces the request method and path required to call the API. - HTTP URL: The URL of the server API. - HTTP Method: The server API only supports HTTP protocol methods, such as GET, POST, etc. ### Parameters Introduces the request headers, query parameters or request body to be passed to call the API. :::tip Parameters are query parameters by default for GET API, parameters are request bodies by default for not GET API, and the request body format is JSON. ::: ### Request Example Detailed example of calling an interface using the SDK. ### Response - Response Headers: Returns content header information. - Response Example: Returns a text example of the content. - Response Status: Interface returns a specific explanation of the `status` of the content. ## API access process ### 1. Enable OpenAPI service Refer to [Introduction to OpenAPI](../docs#how-to-enable) to enable the corresponding services. ### 2. Get App Key and Access Token information Get **Access Token**, **App Key** and **App Secret** on the [Developer Website](https://open.longportapp.com/account). **Access Token** will expires in three months. Token can be reset in Developer Website after expiration. Also token can be refresh through invoking [Refresh Token](./refresh-token-api) API before token expired. ### 3. Calculate signature :::tip Most of the content introduced on this page has been fully implemented in our OpenAPI SDK. If you are an SDK user, you can directly ignore the signature authentication part. This section is intended as a reference for non-SDK users. ::: After constructing a request based on an corresponding API documentation, call the API directly through the OpenAPI SDK, which will help generate a signature, or create a signature through the following process. #### Add `X-Api-Key`、`X-Timestamp`、`Authorization` on headers Set the request parameter header information, and `X-Api-Key`, `Authorization`, `X-Timestamp` will be used in the signature function. ```python import time headers = {} headers['X-Api-Key'] = '${app_key}' headers['Authorization'] = '${access_token}' headers['X-Timestamp' = str(time.time()) # Unix Timestamp, eg: 1539095200.123 headers['Content-Type'] = 'application/json; charset=utf-8', ``` #### Sign requests The example of signature function: ```py # signature function on python3 def sign(method, uri, headers, params, body, secret): ts = headers["X-Timestamp"] access_token = headers["Authorization"] app_key = headers["X-Api-Key"] mtd = method.upper() canonical_request = mtd + "|" + uri + "|" + params + "|authorization:" + access_token + "\nx-api-key:" + app_key + "\nx-timestamp:" + ts + "\n|authorization;x-api-key;x-timestamp|" if body != "": payload_hash = hashlib.sha1(body.encode("utf-8")).hexdigest() canonical_request = canonical_request + payload_hash sign_str = "HMAC-SHA256|" + hashlib.sha1(canonical_request.encode("utf-8")).hexdigest() signature = hmac.new(secret.encode('utf-8'), sign_str.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() return "HMAC-SHA256 SignedHeaders=authorization;x-api-key;x-timestamp, Signature=" + signature ``` Sign the request and set the signature in the request header `X-Api-Signature`. ```py # request method method = "POST" # request path uri = "/v1/trade/order/submit" # request params, for example member_id=1&account_channel=2 params = "" # request body body = json.dumps({ "order_id": '683615454870679552' }) # signing requests and set signature it on the X-Api-Signature headers['X-Api-Signature'] = sign(method, uri, headers, params, body, secret) ``` ### 4. Call API Use the HTTP client to send signed requests. ## API Path All API paths start with [https://openapi.longportapp.com](https://openapi.longportapp.com). > TIP: You can also use https://openapi.longportapp.com ## API Request The call to the server-side interface needs to be in HTTPS protocol, JSON format, and encoded in `UTF-8`. For a test example: ```bash curl -v https://openapi.longportapp.com/v1/test \ -H "X-Api-Signature: {signature}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ``` The method of Get Stock Positions interface is `GET` and needs to set query parameters. The example is as follows: ```bash curl -v https://openapi.longportapp.com/v1/asset/stock?symbol=700.HK&symbol=BABA.US \ -H "X-Api-Signature: {Signature}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ``` The method of Submit Order interface is `POST` and needs to set the request body. The example is as follows: ```bash curl -v -XPOST https://openapi.longportapp.com/v1/trade/order \ -d '{ "side": "Buy", symbol": "700.HK", "order_type": "LO", "submitted_price": "50", "submitted_quantity": "200", "time_in_force": " Day", remark": "Hello from Shell"}' \ -H "X-Api-Signature: {Signature}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" -H "Content-Type: application/json; charset=utf-8" ``` ## API Response All API corresponding body structures consist of `code`, `message`, `data`. `code` is the business code, `message` is the error message, and `data` is the request result. :::tip HTTP Status follows [RESTFull style](https://restfulapi.net/http-status-codes) and `code = 0` if the request succeeds, otherwise `code` will describe the specific error code. ::: ### HTTP Status - 1xx: Informational – Communicates transfer protocol-level information. - 2xx: Success – Indicates that the client's request was accepted successfully. - 3xx: Redirection – Indicates that the client must take some additional action in order to complete their request. - 4xx: Client Error – This category of error status codes points the finger at clients. - 5xx: Server Error – The server takes responsibility for these error status codes. For example, the response body of a successful request: ```json { "code": 0, "msg": "success", "data": { // ... } } ``` the response body of a failed request: ```json { "code": 403201, "msg": "signature invalid" } ``` ## A code demo to call the API ```py import requests import json import time import hashlib import hmac # request information # request method method = "POST" # request path uri = "/v1/trade/order/submit" # request params, for example member_id=1&account_channel=2 params = "" # request body body = json.dumps({ "order_id": '683615454870679552' }) # request headers headers = {} headers['X-Api-Key'] = '${app_key}' headers['Authorization'] = '${access_token}' headers['X-Timestamp'] = str(time.time()) # Unix TimeStamp, eg. 1539095200.123 headers['Content-Type'] = 'application/json; charset=utf-8' # App Secret app_secret = "${app_secret}" ## signature function def sign(method, uri, headers, params, body, secret): ts = headers["X-Timestamp"] access_token = headers["Authorization"] app_key = headers["X-Api-Key"] mtd = method.upper() canonical_request = mtd + "|" + uri + "|" + params + "|authorization:" + access_token + "\nx-api-key:" + app_key + "\nx-timestamp:" + ts + "\n|authorization;x-api-key;x-timestamp|" if body != "": payload_hash = hashlib.sha1(body.encode("utf-8")).hexdigest() canonical_request = canonical_request + payload_hash sign_str = "HMAC-SHA256|" + hashlib.sha1(canonical_request.encode("utf-8")).hexdigest() signature = hmac.new(secret.encode('utf-8'), sign_str.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() return "HMAC-SHA256 SignedHeaders=authorization;x-api-key;x-timestamp, Signature=" + signature # set signature header headers['X-Api-Signature'] = sign(method, uri, headers, params, body, app_secret) # call an API response = requests.request(method, "https://openapi.longportapp.com" + uri + '?' + params, headers=headers, data=body) print(response.text) ``` ## Getting Started ## Foreword LongPort 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.longportapp.com` - WebSocket Quote - `wss://openapi-quote.longportapp.com` - WebSocket Trade - `wss://openapi-trade.longportapp.com` :::tip For access in mainland China, you can use `.cn` domains for better connectivity: - HTTP API - `https://openapi.longport.cn` - WebSocket Quote - `wss://openapi-quote.longport.cn` - WebSocket Trade - `wss://openapi-trade.longport.cn` The SDK automatically selects the access point by network. If the SDK selects incorrectly, set the environment variable `LONGPORT_REGION` (e.g. `cn` or `hk`). ::: ## Time Format All API response are used [Unix Timestamp](https://en.wikipedia.org/wiki/Unix_time), timezone is UTC. ## Environment Requirements ## Install SDK ```bash pip3 install longport ``` ```bash yarn add longport ``` ```toml [dependencies] longport = "4.0.5" tokio = { version = "1", features = "rt-multi-thread" } ``` ```xml io.github.longport openapi-sdk 4.0.5 ``` ```shell go get github.com/longportapp/openapi-go ``` Let's take obtaining assets as an example to demonstrate how to use the SDK. ## Configuration 1. [Download App](https://longport.com/hk/download) and open an account. 2. Get authentication credentials from [LongPort Developers](https://open.longport.com) official website ### Authentication Methods LongPort OpenAPI supports two authentication methods: #### Method 1: OAuth 2.0 (Recommended) ⭐ OAuth 2.0 is the modern authentication method that uses Bearer tokens without requiring HMAC signatures, making it more secure and convenient. **Step 1: Register OAuth Client** Run the following command to register an OAuth client and get your `client_id`: ```bash curl -X POST https://openapi.longportapp.com/oauth2/register \ -H "Content-Type: application/json" \ -d '{ "redirect_uris": ["http://localhost:60355/callback"], "token_endpoint_auth_method": "none", "grant_types": ["authorization_code","refresh_token"], "response_types": ["code"], "client_name": "My LongPort OpenAPI" }' ``` ```powershell $body = @{ redirect_uris = @("http://localhost:60355/callback") token_endpoint_auth_method = "none" grant_types = @("authorization_code", "refresh_token") response_types = @("code") client_name = "My LongPort OpenAPI" } | ConvertTo-Json Invoke-RestMethod -Method POST ` -Uri "https://openapi.longportapp.com/oauth2/register" ` -ContentType "application/json" ` -Body $body ``` Response example: ```json { "client_id": "72d9caaf-0bd4-4000-85a7-8c7978c74544", "client_id_issued_at": 1773311221, "client_secret_expires_at": 1773314821, "client_name": "My LongPort OpenAPI", "redirect_uris": ["http://localhost:60355/callback"], "grant_types": ["authorization_code", "refresh_token"], "token_endpoint_auth_method": "none", "response_types": ["code"], "registration_access_token": "BVlMLEtNUUu4FoRFNItC2FfeR/rLpqLNyEuCJNNTCWE=", "registration_client_uri": "https://openapi.longportapp.com/oauth2/register/72d9caaf-0bd4-4000-85a7-8c7978c74544" } ``` Save the `client_id` for later use. **Step 2: Authorize and Get Token** The SDK provides built-in OAuth support. Use `OAuthBuilder` to run the browser flow; after authorization, use `Config.from_oauth()` to create the configuration. The token is persisted automatically and refreshed when expired. **Token storage path:** `~/.longport/openapi/tokens/` (macOS/Linux), or `%USERPROFILE%\.longport\openapi\tokens\` on Windows. ```python from longport.openapi import Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ``` ```python import asyncio from longport.openapi import Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, OAuth } = require('longport') const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) ``` ```rust use std::sync::Arc; use longport::{Config, oauth::OAuthBuilder}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); Ok(()) } ``` ```java import com.longport.*; public class Main { public static void main(String[] args) throws Exception { String clientId = "your-client-id"; OAuth oauth = new OAuthBuilder(clientId) .build(url -> System.out.println("Open to authorize: " + url)) .get(); try (oauth) { Config config = Config.fromOAuth(oauth); } } } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } _ = conf // use conf for TradeContext or QuoteContext } ``` ```cpp #include #include using namespace longport; int main(int argc, char const* argv[]) { const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } Config config = Config::from_oauth(*res); // Use config to create QuoteContext or TradeContext }); std::cin.get(); return 0; } ``` :::tip OAuth Benefits - More secure (no shared secret) - Simpler integration (no signature calculation) - Token-based modern authentication - Better suited for modern applications ::: :::caution Token Security OAuth tokens should be stored securely in your application (e.g., encrypted file, secure keychain), **not in environment variables** for security reasons. ::: #### Method 2: Legacy API Key (Compatible) **_Get App Key, App Secret, Access Token and other information_** Log in at [https://open.longport.com/](https://open.longport.com/) and open **User Center**. The **application credential** (App Key, App Secret, Access Token) is shown on that page. This Access Token is the **legacy** API Key credential; it is **not** the same as the access token obtained via OAuth or the Refresh Token API. Set these as environment variables for development. ### Environment Variables :::caution Please pay attention to protect your **Access Token** information, anyone who gets it can trade your account through OpenAPI! ::: **API Key credentials (required for legacy API Key):** | Environment Variable | Description | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LONGPORT_APP_KEY` | App key from developer center | | `LONGPORT_APP_SECRET` | App secret from developer center | | `LONGPORT_ACCESS_TOKEN` | Legacy Access Token from [https://open.longport.com/](https://open.longport.com/) (User Center → application credential). Not the OAuth access token. | **Other environment variables:** | Name | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `LONGPORT_LANGUAGE` | Language identifier, `zh-CN`, `zh-HK` or `en` (Default: `en`) | | `LONGPORT_HTTP_URL` | HTTP endpoint url (Default: `https://openapi.longportapp.com`) | | `LONGPORT_QUOTE_WS_URL` | Quote websocket endpoint url (Default: `wss://openapi-quote.longportapp.com/v2`) | | `LONGPORT_TRADE_WS_URL` | Trade websocket endpoint url (Default: `wss://openapi-trade.longportapp.com/v2`) | | `LONGPORT_REGION` | Override API region; SDK auto-selects by network. Set to `cn` or `hk` if incorrect. | | `LONGPORT_ENABLE_OVERNIGHT` | Enable overnight quote, `true` or `false` (Default: `false`). Overnight quotes are included free in US LV1. US stocks only. | | `LONGPORT_PUSH_CANDLESTICK_MODE` | `realtime` or `confirmed` (Default: `realtime`) | | `LONGPORT_PRINT_QUOTE_PACKAGES` | Print quote packages when connected, `true` or `false` (Default: `true`) | | `LONGPORT_LOG_PATH` | Set the path of the log files (Default: no logs) | :::info The SDK also accepts the legacy `LONGPORT_*` variable names for backward compatibility. ::: We recommend that you set the environment variables. For the convenience of demonstration, these environment variables will be used in the sample code in the documents in the following chapters. :::tip About ENV The ENV variables are **not necessary** conditions, if it is inconvenient to set the ENV variables or encounter problems that are difficult to solve, you can not set the ENV variables, but directly use the parameters in the code to initialize. The `Config` in LongPort OpenAPI SDK can be created with `Config.from_apikey_env()` (or `Config.fromApikeyEnv()` in Node/Java) when using environment variables, or `Config.from_apikey(app_key, app_secret, access_token)` when passing parameters directly. See the comments in the example code below for "Init config without ENV". ::: #### Set Environment for macOS / Linux Open the terminal and enter the following command: ```bash export LONGPORT_APP_KEY="App Key from user center" export LONGPORT_APP_SECRET="App Secret from user center" export LONGPORT_ACCESS_TOKEN="Access Token from user center" ``` #### Set Environment for Windows Windows is a little more complicated, we provide two methods to set the environment variables. 1. **Through the GUI**: Right click on "My Computer" on the desktop, select "Properties", click "Advanced system settings" in the pop-up window. - Click "Environment Variables" in the pop-up window. - Click "New" in the pop-up window, then enter the environment variable name, such as `LONGPORT_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 LONGPORT_APP_KEY "App Key from user center" Success: the specified value has been saved. C:\Users\jason> setx LONGPORT_APP_SECRET "App Secret from user center" Success: the specified value has been saved. C:\Users\jason> setx LONGPORT_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 LONGPORT LONGPORT_APP_KEY=xxxxxxx LONGPORT_APP_SECRET=xxxxxx LONGPORT_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 `LONGPORT_ACCESS_TOKEN` with the returned value. ```python from datetime import datetime, timedelta from longport.openapi import Config config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN") # Expire 3 years from now new_token = config.refresh_access_token(expired_at=datetime.now() + timedelta(days=365 * 3)) print("New access token:", new_token) # Use the new token to build a new Config, or persist it as LONGPORT_ACCESS_TOKEN new_config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", new_token) ``` ```javascript const { Config } = require('longport') const config = Config.fromApikey('YOUR_APP_KEY', 'YOUR_APP_SECRET', 'YOUR_ACCESS_TOKEN') // Expire 3 years from now const expiredAt = new Date() expiredAt.setFullYear(expiredAt.getFullYear() + 3) const newToken = await config.refreshAccessToken(expiredAt) console.log('New access token:', newToken) // Use the new token to build a new Config, or persist it as LONGPORT_ACCESS_TOKEN const newConfig = Config.fromApikey('YOUR_APP_KEY', 'YOUR_APP_SECRET', newToken) ``` ```rust use longport::Config; use time::{Duration, OffsetDateTime}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")?; // Expire 3 years from now let expired_at = OffsetDateTime::now_utc() + Duration::days(365 * 3); let new_token = config.refresh_access_token(Some(expired_at)).await?; println!("New access token: {}", new_token); // Use the new token to build a new Config, or persist it as LONGPORT_ACCESS_TOKEN let new_config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", &new_token)?; Ok(()) } ``` ```java import com.longport.Config; import java.time.OffsetDateTime; public class Main { public static void main(String[] args) throws Exception { Config config = Config.fromApikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN"); // Expire 3 years from now OffsetDateTime expiredAt = OffsetDateTime.now().plusYears(3); String newToken = config.refreshAccessToken(expiredAt).get(); System.out.println("New access token: " + newToken); // Use the new token to build a new Config, or persist it as LONGPORT_ACCESS_TOKEN Config newConfig = Config.fromApikey("YOUR_APP_KEY", "YOUR_APP_SECRET", newToken); } } ``` ```cpp #include #include #include using namespace longport; int main() { Config config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN"); // Expire 3 years from now (Unix timestamp) int64_t expired_at = static_cast(std::time(nullptr)) + 3LL * 365 * 24 * 3600; config.refresh_access_token(expired_at, [](auto res) { if (!res) { std::cerr << "Error: " << *res.status().message() << std::endl; return; } std::cout << "New access token: " << *res << std::endl; // Use the new token to build a new Config, or persist it as LONGPORT_ACCESS_TOKEN Config new_config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", *res); }); std::cin.get(); return 0; } ``` The `expired_at` parameter sets when the new token expires (default: **90 days** from now). ## Scene Demonstration ### Get Account Balance Create `account_asset.py` and paste the code below: ```python from longport.openapi import TradeContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) # Or use API Key: config = Config.from_apikey_env() # Or without ENV: config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN") ctx = TradeContext(config) resp = ctx.account_balance() print(resp) ``` Run it ```bash python account_asset.py ``` Create `account_asset_async.py` and paste the code below: ```python import asyncio from longport.openapi import AsyncTradeContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = AsyncTradeContext.create(config) resp = await ctx.account_balance() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` Run it ```bash python account_asset_async.py ``` Create `account_asset.js` and paste the code below: ```javascript const { Config, TradeContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) // Or use API Key: const config = Config.fromApikeyEnv() const ctx = TradeContext.new(config) const resp = await ctx.accountBalance() for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` Run it ```bash node account_asset.js ``` Create `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, trade::TradeContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); // Or use API Key: let config = Arc::new(Config::from_apikey_env()?); // Or without ENV: let config = Arc::new(Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")?); let (ctx, _) = TradeContext::new(config); let resp = ctx.account_balance(None).await?; println!("{:?}", resp); Ok(()) } ``` Run it ```bash cargo run ``` Create `Main.java` and paste the code below: ```java import com.longport.*; import com.longport.trade.*; class Main { public static void main(String[] args) throws Exception { String clientId = "your-client-id"; OAuth oauth = new OAuthBuilder(clientId) .build(url -> System.out.println("Open to authorize: " + url)) .get(); try (oauth; Config config = Config.fromOAuth(oauth); TradeContext ctx = TradeContext.create(config)) { // Or use API Key: Config.fromApikeyEnv(); TradeContext.create(config) for (AccountBalance obj : ctx.getAccountBalance().get()) { System.out.println(obj); } } } } ``` Run it ```bash mvn compile exec:exec ``` Create `main.go` and paste the code below: ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/trade" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) // Or use API Key from ENV: config.New() // Or without ENV: config.New(config.WithConfigKey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")) if err != nil { log.Fatal(err) } tradeContext, err := trade.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer tradeContext.Close() ctx := context.Background() ab, err := tradeContext.AccountBalance(ctx, &trade.GetAccountBalance{}) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", ab[0]) } ``` Run: ```shell go mod tidy go run ./ ``` Create `account_asset.cpp` and paste the code below: ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::trade; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); TradeContext ctx = TradeContext::create(config); ctx.account_balance([](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& b : *res) { std::cout << b.currency << " " << (double)b.available_cash << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` Run it ```bash g++ -std=c++17 account_asset.cpp -o account_asset -llongport && ./account_asset ``` After running, the output is as follows: ``` [ AccountBalance { total_cash: 503898884.81, max_finance_amount: 0.00, remaining_finance_amount: 501403229.49, risk_level: Some(1), margin_call: 0, currency: "HKD", cash_infos: [ CashInfo { withdraw_cash: 501214985.15, available_cash: 501214985.15, frozen_cash: 584438.25, settling_cash: -3897793.90, currency: "HKD", }, CashInfo { withdraw_cash: -25546.89, available_cash: -25546.89, frozen_cash: 295768.57, settling_cash: 2326.60, currency: "USD", } ] } ] ``` ### Subscribe Quote To subscribe to market data, please check the [Developer Center](https://open.longport.com/account) - "Quote authority" is correct - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. - US Market - US LV1 (Only OpenAPI). Before running, visit the [Developer Center](https://open.longport.com/dashboard) and ensure that the account has the correct quote level. :::info If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. https://longport.com/download ::: When you have the correct Quote authority, it might look like this: Create `subscribe_quote.py` and paste the code below: ```python from time import sleep from longport.openapi import QuoteContext, Config, OAuthBuilder, SubType, PushQuote def on_quote(symbol: str, quote: PushQuote): print(symbol, quote) oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.set_on_quote(on_quote) ctx.subscribe(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"], [SubType.Quote]) sleep(30) ``` Run it ```bash python subscribe_quote.py ``` Create `subscribe_quote_async.py` and paste the code below: ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder, SubType, PushQuote async def on_quote(symbol: str, quote: PushQuote) -> None: print(symbol, quote) async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config, loop_=asyncio.get_running_loop()) ctx.set_on_quote(on_quote) await ctx.subscribe(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"], [SubType.Quote]) await asyncio.sleep(30) if __name__ == "__main__": asyncio.run(main()) ``` Run it ```bash python subscribe_quote_async.py ``` Create `subscribe_quote.js` and paste the code below: ```javascript const { Config, QuoteContext, SubType, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) ctx.setOnQuote((_, event) => console.log(event.toString())) await ctx.subscribe(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US'], [SubType.Quote]) await new Promise(() => {}) } main().catch(console.error) ``` Run it ```bash node subscribe_quote.js ``` Create `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{ oauth::OAuthBuilder, quote::{QuoteContext, SubFlags}, Config, }; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, mut receiver) = QuoteContext::new(config); ctx.subscribe(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"], SubFlags::QUOTE) .await?; while let Some(event) = receiver.recv().await { println!("{:?}", event); } Ok(()) } ``` Run it ```bash cargo run ``` Create `Main.java` and paste the code below: ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { String clientId = "your-client-id"; OAuth oauth = new OAuthBuilder(clientId) .build(url -> System.out.println("Open to authorize: " + url)) .get(); try (oauth; Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ctx.setOnQuote((symbol, quote) -> { System.out.printf("%s\t%s\n", symbol, quote); }); ctx.subscribe(new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }, SubFlags.Quote).get(); Thread.sleep(30000); } } } ``` Run it ```bash mvn compile exec:exec ``` Create file `main.go` and paste the code below: ```go package main import ( "context" "encoding/json" "fmt" "log" "os" "os/signal" "syscall" "time" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/quote" ) func main() { // create quote context from environment variables conf, err := config.New() if err != nil { log.Fatal(err) } quoteContext, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) return } defer quoteContext.Close() ctx := context.Background() quoteContext.OnQuote(func(pe *quote.PushQuote) { bytes, _ := json.Marshal(pe) fmt.Println(string(bytes)) }) quoteContext.OnDepth(func(d *quote.PushDepth) { bytes, _ := json.Marshal(d) if d.Sequence != 0 { fmt.Print(time.UnixMicro(d.Sequence/1000).Format(time.RFC3339) + " ") } fmt.Println(string(bytes)) }) // Subscribe some symbols err = quoteContext.Subscribe(ctx, []string{"700.HK", "AAPL.US", "NFLX.US"}, []quote.SubType{quote.SubTypeDepth}, true) if err != nil { log.Fatal(err) return } quitChannel := make(chan os.Signal, 1) signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM) <-quitChannel } ``` Run: ```shell go run ./ ``` Create `subscribe_quote.cpp` and paste the code below: ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static QuoteContext g_ctx; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); g_ctx = QuoteContext::create(config); g_ctx.set_on_quote([](auto event) { std::cout << event->symbol << " last_done=" << (double)event->last_done << " volume=" << event->volume << std::endl; }); std::vector symbols = {"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"}; g_ctx.subscribe(symbols, SubFlags::QUOTE(), [](auto res) { if (!res) { std::cout << "failed to subscribe: " << *res.status().message() << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` Run it ```bash g++ -std=c++17 subscribe_quote.cpp -o subscribe_quote -llongport && ./subscribe_quote ``` After running, the output is as follows: ``` 700.HK PushQuote { last_done: 367.000, open: 362.000, high: 369.400, low: 356.000, timestamp: "2022-06-06T08:10:00Z", volume: 22377421, turnover: 8081883405.000, trade_status: Normal, trade_session: Normal } AAPL.US PushQuote { last_done: 147.350, open: 150.700, high: 151.000, low: 146.190, timestamp: "2022-06-06T11:57:36Z", volume: 3724407, turnover: 550606662.815, trade_status: Normal, trade_session: Pre } NFLX.US PushQuote { last_done: 201.250, open: 205.990, high: 205.990, low: 200.110, timestamp: "2022-06-06T11:57:26Z", volume: 137821, turnover: 27888085.590, trade_status: Normal, trade_session: Pre } ``` ### Submit Order Next, we will do a [submit order](https://open.longport.com/docs/trade/order/submit) action, we assume that to buy `700.HK` at 50 HKD and quantity is `100`. > NOTE: In order to prevent a successful test buy, the demo here gives a lower price and avoids the transaction. OpenAPI operations are equivalent to online transactions, please operate with caution, and pay attention to parameter details during development and debugging. Create `submit_order.py` and paste the code below: ```python from decimal import Decimal from longport.openapi import TradeContext, Config, OAuthBuilder, OrderSide, OrderType, TimeInForceType oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = TradeContext(config) resp = ctx.submit_order( side=OrderSide.Buy, symbol="700.HK", order_type=OrderType.LO, submitted_price=Decimal(50), submitted_quantity=Decimal(200), time_in_force=TimeInForceType.Day, remark="Hello from Python SDK", ) print(resp) ``` Run it ```bash python submit_order.py ``` Create `submit_order_async.py` and paste the code below: ```python import asyncio from decimal import Decimal from longport.openapi import AsyncTradeContext, Config, OAuthBuilder, OrderSide, OrderType, TimeInForceType async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = AsyncTradeContext.create(config) resp = await ctx.submit_order( side=OrderSide.Buy, symbol="700.HK", order_type=OrderType.LO, submitted_price=Decimal(50), submitted_quantity=Decimal(200), time_in_force=TimeInForceType.Day, remark="Hello from Python SDK", ) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` Run it ```bash python submit_order_async.py ``` Create `submit_order.js` and paste the code below: ```javascript const { Config, TradeContext, OrderType, OrderSide, Decimal, TimeInForceType, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = TradeContext.new(config) const resp = await ctx.submitOrder({ symbol: '700.HK', orderType: OrderType.LO, side: OrderSide.Buy, timeInForce: TimeInForceType.Day, submittedPrice: new Decimal(50), submittedQuantity: new Decimal(200), }) console.log(resp.toString()) } main().catch(console.error) ``` Run it ```bash node submit_order.js ``` Create `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{ decimal, oauth::OAuthBuilder, trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext}, Config, }; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = TradeContext::new(config); let opts = SubmitOrderOptions::new( "700.HK", OrderType::LO, OrderSide::Buy, decimal!(200), TimeInForceType::Day, ) .submitted_price(decimal!(50i32)); let resp = ctx.submit_order(opts).await?; println!("{:?}", resp); Ok(()) } ``` Run it ```bash cargo run ``` Create `Main.java` and paste the code below: ```java import com.longport.*; import com.longport.trade.*; import java.math.BigDecimal; public class Main { public static void main(String[] args) throws Exception { String clientId = "your-client-id"; OAuth oauth = new OAuthBuilder(clientId) .build(url -> System.out.println("Open to authorize: " + url)) .get(); try (oauth; Config config = Config.fromOAuth(oauth); TradeContext ctx = TradeContext.create(config)) { SubmitOrderOptions opts = new SubmitOrderOptions("700.HK", OrderType.LO, OrderSide.Buy, new BigDecimal(200), TimeInForceType.Day).setSubmittedPrice(new BigDecimal(50)); SubmitOrderResponse resp = ctx.submitOrder(opts).get(); System.out.println(resp); } } } ``` Run it ```bash mvn compile exec:exec ``` Create `main.go` and paste the code below: ```go package main import ( "context" "fmt" "log" "os" "os/signal" "syscall" "github.com/shopspring/decimal" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/trade" ) func main() { // create trade context from environment variables conf, err := config.New() if err != nil { log.Fatal(err) } tradeContext, err := trade.NewFromCfg(conf) if err != nil { log.Fatal(err) return } defer tradeContext.Close() // subscribe order status tradeContext.OnTrade(func(ev *trade.PushEvent) { // handle order changing event }) ctx := context.Background() // submit order order := &trade.SubmitOrder{ Symbol: "700.HK", OrderType: trade.OrderTypeLO, Side: trade.OrderSideBuy, SubmittedQuantity: 200, TimeInForce: trade.TimeTypeDay, SubmittedPrice: decimal.NewFromFloat(12), } orderId, err := tradeContext.SubmitOrder(ctx, order) if err != nil { log.Fatal(err) return } fmt.Printf("orderId: %v\n", orderId) quitChannel := make(chan os.Signal, 1) signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM) <-quitChannel } ``` 运行: ```shell go run ./ ``` Create `submit_order.cpp` and paste the code below: ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::trade; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); TradeContext ctx = TradeContext::create(config); SubmitOrderOptions opts{ "700.HK", OrderType::LO, OrderSide::Buy, Decimal(200), TimeInForceType::Day, Decimal(50.0), std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, }; ctx.submit_order(opts, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "order id: " << res->order_id << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` Run it ```bash g++ -std=c++17 submit_order.cpp -o submit_order -llongport && ./submit_order ``` After running, the output is as follows: ``` SubmitOrderResponse { order_id: "718437534753550336" } ``` ### Get Today Orders Create `today_orders.py` and paste the code below: ```python from longport.openapi import TradeContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = TradeContext(config) resp = ctx.today_orders() print(resp) ``` Run it ```bash python today_orders.py ``` Create `today_orders_async.py` and paste the code below: ```python import asyncio from longport.openapi import AsyncTradeContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = AsyncTradeContext.create(config) resp = await ctx.today_orders() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` Run it ```bash python today_orders_async.py ``` Create `today_orders.js` and paste the code below: ```javascript const { Config, TradeContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = TradeContext.new(config) const resp = await ctx.todayOrders() for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` Run it ```bash node today_orders.js ``` Create `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, trade::TradeContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = TradeContext::new(config); let resp = ctx.today_orders(None).await?; for obj in resp { println!("{:?}", obj); } Ok(()) } ``` Run it ```bash cargo run ``` Create `Main.java` and paste the code below: ```java import com.longport.*; import com.longport.trade.*; class Main { public static void main(String[] args) throws Exception { String clientId = "your-client-id"; OAuth oauth = new OAuthBuilder(clientId) .build(url -> System.out.println("Open to authorize: " + url)) .get(); try (oauth; Config config = Config.fromOAuth(oauth); TradeContext ctx = TradeContext.create(config)) { Order[] orders = ctx.getTodayOrders(null).get(); for (Order order : orders) { System.out.println(order); } } } } ``` Run it ```bash mvn compile exec:exec ``` Create `main.go` and paste the code below: ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/trade" ) func main() { // create trade context from environment variables conf, err := config.New() if err != nil { log.Fatal(err) } tradeContext, err := trade.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer tradeContext.Close() ctx := context.Background() // today orders orders, err := tradeContext.TodayOrders(ctx, &trade.GetTodayOrders{}) if err != nil { log.Fatal(err) } for _, order := range orders { fmt.Printf("%+v\n", order) } } ``` Run: ```shell go run ./ ``` Create `today_orders.cpp` and paste the code below: ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::trade; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); TradeContext ctx = TradeContext::create(config); ctx.today_orders(std::nullopt, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (auto it = res->cbegin(); it != res->cend(); ++it) { std::cout << "order_id=" << it->order_id << " quantity=" << it->quantity << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` Run it ```bash g++ -std=c++17 today_orders.cpp -o today_orders -llongport && ./today_orders ``` After running, the output is as follows: ``` Order { order_id: "718437534753550336", status: NotReported, stock_name: "腾讯控股 1", quantity: 200, executed_quantity: None, price: Some(50.000), executed_price: None, submitted_at: 2022-06-06T12:14:16Z, side: Buy, symbol: "700.HK", order_type: LO, last_done: None, trigger_price: Some(0.000), msg: "", tag: Normal, time_in_force: Day, expire_date: Some(NaiveDate(Date { year: 2022, ordinal: 158 })), updated_at: Some(2022-06-06T12:14:16Z), trigger_at: None, trailing_amount: None, trailing_percent: None, limit_offset: None, trigger_status: None, currency: "HKD", outside_rth: nonce } ``` The above example has fully demonstrated how to use the SDK to access the OpenAPI interface. For more interfaces, please read the [LongPort Developers Documentation](https://open.longport.com/docs) in detail and use them according to different interfaces. ## More Examples We provide the complete code of the above examples in the GitHub repository of LongPort OpenAPI Python SDK, and we will continue to add or update it later. https://github.com/longportapp/openapi/tree/master/examples ## SDK API Document For detailed SDK API document, please visit: https://longportapp.github.io/openapi/ ## Contact & Feedback If there are any questions or suggestions, please feel free to post an issue on GitHub, we will reply as soon as possible. Or there have a lot old discussion in the GitHub issue, you can search the issue to find the answer. - GitHub: https://github.com/longportapp/developers/issues ## API Reference ## Changelog ## 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 ## 2026-06-02 ### SDK v4.2.0 - **FundamentalContext** — `shareholder_top`, `shareholder_detail`, `valuation_comparison` - **QuoteContext** — `short_positions` unified for US and HK; new `short_trades` - **MarketContext** — `top_movers`, `rank_categories`, `rank_list` - **New ScreenerContext** — `screener_recommend_strategies`, `screener_user_strategies`, `screener_strategy`, `screener_search`, `screener_indicators` - Languages: Rust / Python / Node.js / Java / C / C++ / Go ## 2026-05-13 ### SDK v4.1.0 - **7 new context types, 66 methods** — `FundamentalContext` (20 methods: financial reports, analyst ratings, dividends, EPS forecasts, consensus estimates, valuation), `MarketContext` (9 methods: market status, broker holdings, A/H premium, trade stats), `CalendarContext` (7 methods: earnings / dividends / splits / IPO calendar), `PortfolioContext` (5 methods: exchange rates, P&L analysis), `AlertContext` (4 methods: price alerts), `DCAContext` (12 methods: DCA plans lifecycle), `SharelistContext` (9 methods: community sharelists) - **QuoteContext** — 4 new methods: `short_positions`, `option_volume`, `option_volume_daily`, `update_pinned` - **ContentContext** — new `topic_detail` and topic reply methods - **Rust SDK** — `Config::header()` to inject custom HTTP/WebSocket headers - Parameters now use typed enums instead of raw integers; monetary fields use `Decimal` type ### Docs - Sidebar restructured: **News & Contents** section consolidates News, Topics, and Sharelist; Quote **Watchlist** replaces Individual; **Appendix** replaces Socket Feed (collapsed by default) - **Fundamental** and **News & Contents** sections added to the docs overview ## 2026-03-30 - Add Statement API: - `GET /v1/statement/list` — list daily or monthly account statements - `GET /v1/statement/download` — get presigned download URL for a statement file ## 2026-03-25 - Add Community API: - `GET /content/topics/mine` — list my published topics - `POST /content/topics` — create a new community topic - `GET /content/topics/{id}` — get topic detail - `GET /content/topics/{topic_id}/comments` — list topic replies - `POST /content/topics/{topic_id}/comments` — create a topic reply ## 2025-06-17 - Update the interface for Get Account Balance - `GET /v1/asset/account` Add response field (frozen_transaction_fees) ## 2024-10-09 ### SDK 2.0.0 - Print the opened quote packages when connected to the server. - The quantity type in the trading API has changed from `int` to `Decimal`. ## 2024-09-11 - Updated Get Security List API - The `GET /v1/quote/get_security_list` now returns the name in the corresponding language based on the `accept-language` request header, instead of returning all three languages at once. ## 2024-08-28 - Change the `Depth.price` field in the SDK from `Decimal` type to `Optional[Decimal]` type ## 2024-05-17 - Expand `outside_rth` field to support overnight trading in order placement and query APIs ## 2024-05-06 - Update the interface for Get Account Balance - `GET /v1/asset/account` Add response field (buy_power) ## 2024-04-29 - Remove `TSMPCT`, `TSMAMT` Order type ## 2024-04-15 - Add `last_share`, `last_price` field to [Trade push](https://open.longport.com/en/docs/trade/trade-definition#websocket-notification). ## 2024-04-13 - Add `remark` field to [Trade push](https://open.longport.com/en/docs/trade/trade-definition#websocket-notification). ## 2023-11-03 - Add quote history candlestick interface - Long connection `Business Command:27`, obtain the history candlestick of security ## 2023-08-17 - Update the interface for Get Account Balance - `GET /v1/asset/account` Add parameter (currency) ## 2023-04-12 - Update the interface for Get Stock Positions - `GET /v1/asset/stock` Add response field (init_quantity) ## 2023-04-11 - Added order details query interface - 'GET /v1/trade/order' Get the order details - Added the Estimate Maximum Purchase Quantity interface - 'GET /v1/trade/estimate/buy_limit' Get the estimated maximum purchase quantity - U.S. stock options add market order and condition order support ## 2022-07-18 - Update security static info interface - Long connection `Business Command:10`, response add `board` fields ## 2022-07-14 - Add get stock margin ratio interface - `GET /v1/risk/margin-ratio` Get stock margin ratio ## 2022-06-30 - Add get watched groups interface - `GET /v1/watchlist/groups` Get watched groups ## 2022-06-20 - Update account balance interface - `GET /v1/asset/account` Response to increase the net assets (net_assets), initial margin (init_margin), maintenance margin (maintenance_margin) fields - Update position interface - `GET /v1/asset/stock` Support users to obtain option positions ## 2022-06-15 - Add quote capital interface - Long connection `Business Command:24`, obtain the daily capital distribution of security - Long connection `Business Command:25`, obtain the daily capital flow intraday of security ## Refresh Token # Refresh Access Token Call this to get a new `access_token` before the old `access_token` expires. The old `access_token` will be invalidated after a successful call. > Lasted 2022-04-21 ## Request | Basic Information | | | ----------------- | ----------------- | | HTTP URL | /v1/token/refresh | | HTTP Method | GET | | Permission | Not required | ### Request Headers | Name | Type | Required | Description | | ------------- | ------ | -------- | ----------- | | Authorization | string | Yes | | ### Request Parameters | Name | Type | Required | Description | Example | | ---------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------ | ------------------------ | | expired_at | string | Yes | Expiration timestamp, formatted according to [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) specification | 2023-04-14T12:13:57.859Z | ## Response ### Response Body | Name | Type | Description | | ----------------- | ------ | ---------------------------------- | | code | int | Error code, non-zero means failure | | msg | string | Error message | | data | object | | | ∟token | string | new access_token | | ∟expired_at | string | access_token expired time | | ∟issued_at | string | issued time | | ∟account_info | object | user info | | ∟∟member_id | string | user id | | ∟∟aaid | string | aaid | | ∟∟account_channel | string | account_channel | ### Response Example ```json { "code": 0, "message": "", "data": { "token": "xxxxxx", "expired_at": "2022-05-14T12:13:57.859Z", "issued_at": "2022-04-14T12:13:57.859Z", "account_info": { "member_id": 123, "aaid": 13, "account_channel": "lb" } } } ``` ### Content #### Sharelist #### Create Sharelist Create a new community stock list with an optional initial set of securities. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.create_sharelist](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.create_sharelist) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.add_securities](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.add_securities) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | integer | YES | Sharelist ID | | symbols | string[] | YES | Security symbols to add | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Popular Sharelists Get popular/trending sharelists from the community. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.popular](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.popular) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## Parameters | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | count | integer | NO | Maximum number of results, default 20 | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Delete Sharelist Permanently delete a sharelist you own. This action cannot be undone. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.delete_sharelist](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.delete_sharelist) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | int64 | YES | Sharelist ID (path parameter) | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.list_sharelist](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.list_sharelist) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | type | string | NO | Filter: `mine` or `subscribed`. Omit for both. | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Update Sharelist Add, remove, or reorder securities in a sharelist, or rename it. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.update_sharelist](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.update_sharelist) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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. #### Sort Securities in Sharelist Reorder the securities in a sharelist. The symbols list defines the new order. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.sort_securities](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.sort_securities) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Sharelist Detail Get sharelist detail including name, description, and constituent stocks. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.detail) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## Parameters | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | integer | YES | Sharelist ID | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Remove Securities from Sharelist Remove one or more securities from a sharelist. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.sharelist._sharelist_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.sharelist._sharelist_context) | | Rust | [longport::::sharelist#_sharelist_context](https://longportapp.github.io/openapi/rust/longport//struct.sharelist.html#method._sharelist_context) | | Go | [sharelist.remove_securities](https://pkg.go.dev/github.com/longportapp/openapi-go/#sharelist.remove_securities) | | Node.js | [sharelist#SharelistContext](https://longportapp.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | integer | YES | Sharelist ID | | symbols | string[] | YES | Security symbols to remove | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### News #### Security News Get the news list for a specified security. Browse the full feed on [News](https://longport.com/news). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.content._content_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.content._content_context) | | Rust | [longport::::content#_content_context](https://longportapp.github.io/openapi/rust/longport//struct.content.html#method._content_context) | | Go | [content.news](https://pkg.go.dev/github.com/longportapp/openapi-go/#content.news) | | Node.js | [content#ContentContext](https://longportapp.github.io/openapi/nodejs/classes/content.html#contentcontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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://longport.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 | #### Topics #### Create Topic Reply Post a reply to a community topic. Supports nesting under an existing reply. Browse the community on [Topics](https://longport.com/topics). Only users who have opened a **[LongPort account](https://longport.com/hk/download) and hold assets** are allowed to publish community topics and replies via LongPort Developers API. 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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.content._content_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.content._content_context) | | Rust | [longport::::content#_content_context](https://longportapp.github.io/openapi/rust/longport//struct.content.html#method._content_context) | | Go | [content.create_topic_reply](https://pkg.go.dev/github.com/longportapp/openapi-go/#content.create_topic_reply) | | Node.js | [content#ContentContext](https://longportapp.github.io/openapi/nodejs/classes/content.html#contentcontext) | ## Request
HTTP MethodPOST
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 ```python from longport.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 longport.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/longportapp/openapi-go/config" "github.com/longportapp/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 longport::{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 LongPort 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) | #### Topic Replies Get a paginated list of replies for a specific topic. Browse the discussion on [Topics](https://longport.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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.content._content_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.content._content_context) | | Rust | [longport::::content#_content_context](https://longportapp.github.io/openapi/rust/longport//struct.content.html#method._content_context) | | Go | [content.list_topic_replies](https://pkg.go.dev/github.com/longportapp/openapi-go/#content.list_topic_replies) | | Node.js | [content#ContentContext](https://longportapp.github.io/openapi/nodejs/classes/content.html#contentcontext) | ## Request
HTTP MethodGET
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 ```python from longport.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 longport.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/longportapp/openapi-go/config" "github.com/longportapp/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 longport::{oauth::OAuthBuilder, content::{ContentContext, ListTopicRepliesOptions}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = ContentContext::new(config); let replies = ctx.list_topic_replies( "6993508780031016960", ListTopicRepliesOptions { page: Some(1), size: Some(20) }, ).await?; for r in &replies { println!("{}: {}", r.author.name, r.body); } Ok(()) } ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0, "message": "success", "data": { "items": [ { "id": "7001234567890123456", "topic_id": "6993508780031016960", "body": "Great analysis!", "reply_to_id": "0", "author": { "member_id": "10087", "name": "John Smith", "avatar": "https://example.com/avatar2.jpg" }, "images": [], "likes_count": 5, "comments_count": 2, "created_at": "1742001500" }, { "id": "7001234567890123457", "topic_id": "6993508780031016960", "body": "I disagree on the valuation part.", "reply_to_id": "7001234567890123456", "author": { "member_id": "10088", "name": "Alice Lee", "avatar": "https://example.com/avatar3.jpg" }, "images": [], "likes_count": 1, "comments_count": 0, "created_at": "1742001800" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ------------------------------------------------------- | | 200 | Success | [topic_replies_response](#schematopic_replies_response) | | 500 | Internal error | None | ## Schemas ### topic_replies_response | Name | Type | Required | Description | | ---------------- | -------- | -------- | ----------------------------------------- | | items | object[] | true | List of replies | | ∟ id | string | true | Reply ID | | ∟ topic_id | string | true | Parent topic ID | | ∟ body | string | false | Reply body (plain text) | | ∟ reply_to_id | string | false | Parent reply ID; `"0"` = top-level reply | | ∟ author | object | false | Author info | | ∟∟ member_id | string | false | Author member ID | | ∟∟ name | string | false | Author display name | | ∟∟ avatar | string | false | Author avatar URL | | ∟ images | object[] | false | Attached images | | ∟∟ url | string | false | Original image URL | | ∟∟ sm | string | false | Small thumbnail URL | | ∟∟ lg | string | false | Large image URL | | ∟ likes_count | int32 | false | Likes count | | ∟ comments_count | int32 | false | Nested replies count | | ∟ created_at | string | true | Creation time as Unix timestamp (seconds) | #### Topics by Symbol Get the topic/discussion list for a specified security. Browse the full community on [Topics](https://longport.com/topics). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.content._content_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.content._content_context) | | Rust | [longport::::content#_content_context](https://longportapp.github.io/openapi/rust/longport//struct.content.html#method._content_context) | | Go | [content.topics](https://pkg.go.dev/github.com/longportapp/openapi-go/#content.topics) | | Node.js | [content#ContentContext](https://longportapp.github.io/openapi/nodejs/classes/content.html#contentcontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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://longport.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 | #### 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://longport.com/topics). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.content._content_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.content._content_context) | | Rust | [longport::::content#_content_context](https://longportapp.github.io/openapi/rust/longport//struct.content.html#method._content_context) | | Go | [content.topic_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#content.topic_detail) | | Node.js | [content#ContentContext](https://longportapp.github.io/openapi/nodejs/classes/content.html#contentcontext) | ## Request
HTTP MethodGET
HTTP URL/v1/content/topics/:id
### Path Parameters | Name | Type | Required | Description | | ---- | ------ | -------- | ------------------------------------- | | id | string | YES | Topic ID (e.g. `6993508780031016960`) | ### Request Example ```python from longport.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 longport.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/longportapp/openapi-go/config" "github.com/longportapp/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 longport::{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.longport.com/img/abc.jpg", "sm": "https://cdn.longport.com/img/abc_sm.jpg", "lg": "https://cdn.longport.com/img/abc_lg.jpg" } ], "likes_count": 42, "comments_count": 7, "views_count": 1500, "shares_count": 3, "detail_url": "https://longport.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) | #### Create Topic Create a new community topic on [Topics](https://longport.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 **LongPort account and hold assets** are allowed to publish community topics and replies via LongPort Developers API. 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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.content._content_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.content._content_context) | | Rust | [longport::::content#_content_context](https://longportapp.github.io/openapi/rust/longport//struct.content.html#method._content_context) | | Go | [content.create_topic](https://pkg.go.dev/github.com/longportapp/openapi-go/#content.create_topic) | | Node.js | [content#ContentContext](https://longportapp.github.io/openapi/nodejs/classes/content.html#contentcontext) | ## Request
HTTP MethodPOST
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 ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 LongPort 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 | #### My Topics Get the list of topics I have published. View them on [Topics](https://longport.com/topics). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.content._content_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.content._content_context) | | Rust | [longport::::content#_content_context](https://longportapp.github.io/openapi/rust/longport//struct.content.html#method._content_context) | | Go | [content.topics_mine](https://pkg.go.dev/github.com/longportapp/openapi-go/#content.topics_mine) | | Node.js | [content#ContentContext](https://longportapp.github.io/openapi/nodejs/classes/content.html#contentcontext) | ## Request
HTTP MethodGET
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 ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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://longport.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 | ### Legal ### User Data Authorisation and Acknowledgement — HK Please read this Authorisation carefully before proceeding. **By completing and submitting this Authorisation, you acknowldge and confirm that you have read, understood, and agree to be bound by all terms set out below in connection with the LongPort Developers.** **1. Background** LongPort AI Technologies Limited and its relevant affiliates (collectivly, "**LongPort**") provides programmatic interfaces through which market data, account functionalities, and related services are encapsulated and made available to users in the form of Command-Line Interface tools, Model Context Protocol integrations, and other developer tools and services (collectively, "**LongPort Developers**"). Users may access and invoke the relevant interfaces based on their own needs and integrate them with third-party AI terminals or applications selected by the users (including, without limitation, OpenClaw, Claude Code, Cursor, and similar tools). Upon installation and successful connection, users may interact with the LongPort Platform and/or their platform or securities accounts (where applicable) through such third-party terminals or applications. This Authorisation governs: (a) the sharing of your selected account data among the relevant LongPort group entities and with relevant third-party AI terminal operators as you selected ("**Third-Party AI Terminals**"); and (b) the terms on which instructions you issue through Third-Party AI Terminals are treated as your own instructions for the purpose of executing securities transactions. **2. Data Sharing Authorisation and Purpose of Sharing** **2.1 Authorised Data Scope** The categories of data covered by this Authorisation are displayed below and/or under "Quotes Permission" section on the OAuth authorisation page, and are subject to your selection. Unless otherwise specified, data related to securities trading will generally be shared by Long Bridge HK Limited ("**LongPort Securities**"), while other data will be shared by LongPort Platform (as defined in the terms and conditions of LongPort Platform). The data categories authorised by you will be shared by LongPort with Third-Party AI Terminals solely for the purpose of enabling the function of the LongPort Developers described herein. The data categories that may be available are organized into the following capability groups, with access granted on a feature-by-feature basis depending on the functionality selected on the relevant page. The specific set of available tools and their read / create / update / delete permissions may be added, adjusted or retired from time to time as LongPort Developers evolves; the latest inventory is as published at [https://open.longport.com/docs/mcp](https://open.longport.com/docs/mcp) and on the OAuth authorization page: 1. **Real-time Market Data** --- Real-time market quotes and order-book data across markets. 2. **Fundamentals & Research** --- Company fundamentals and research data. 3. **Derivatives** --- Data relating to options, warrants and other derivatives. 4. **Account & Portfolio** --- Access to account, cash and position data, and the maintenance of portfolio constructs such as watchlists. 5. **Trading** --- Securities trade execution and the management of the order lifecycle. 6. **Automation** --- Management of automated tasks triggered by conditions you have pre-set. The specific functionality, coverage and read / write permissions within the categories above may be adjusted or expanded from time to time. Any newly added data capability category will be presented as a separately selectable item on the OAuth authorization page before being shared with any Third-Party AI Terminal, and the corresponding data will only be shared after you have actively selected it and completed the authorization. **2.2 Further Sharing with Third-Party AI Terminals** By granting authorization hereunder, you acknowledge and agree that the authorisation you hereby grant to LongPort may, to the extent necessary to fulfil the purposes of LongPort Developers, be further shared with Third-Party Terminals. **2.3 Purpose of Sharing** The data shared pursuant to your selections above will be used exclusively to enable the functionality of the LongPort Developers. No data will be shared for any other purpose without your separate consent. **2.4 Data Protection and Compliance** All data collection, storage, and processing activities are conducted in accordance with the Personal Data (Privacy) Ordinance ("**PDPO**") and other applicable data protection regulations. LongPort will only retain your data for as long as is necessary to fulfil the purposes set out in this Authorisation, or as required by applicable law. You have the right to withdraw your consent, access your data, and request correction of inaccurate data, in each case in accordance with the PDPO. You may withdraw this Authorisation at any time by updating your settings within the LongPort platform. Withdrawal will take effect prospectively and will not affect instructions already submitted or executed prior to the effective date of withdrawal. **3. Instructions Transmitted via Third-Party AI Terminals** **3.1 Nature and Effect of Instructions via Third-Party AI Terminals(when applicable)** You acknowledge and agree that when you issue instructions through Third-Party AI Terminals, which instructions shall be transmitted to and executed by LongPort Securities: LongPort acts solely as the developer of the LongPort Developers. LongPort and LongPort Securities do not control, review, endorse, or assume any responsibility or liability for the content, instructions, recommendations, or outputs generated by any Third-Party AI Terminal, including any trading decisions or outcomes arising therefrom. The Third-Party AI Terminal with which you interact is the responsible party for the AI services provided to you and you remain solely responsible for independently evaluating and verifying any information or recommendations provided by Third-Party AI Terminal before taking any action. The Third-Party AI Terminal transmits instructions on your behalf to LongPort Securities for execution, but does not itself initiate, modify, interpret, or exercise any discretion over any instruction. Each instruction transmitted via Third-Party AI Terminal must be initiated by you through an explicit and deliberate user action. No instruction will be automatically generated, triggered, or executed without your input and confirmation. No Third-Party AI Terminal has constituted/ currently constitutes /will constitute an agent, representative, investment adviser, or decision-making entity of any LongPort group entity or of you personally. LongPort Securities executes instructions strictly in accordance with your authorisation, on an execution-only basis, without providing investment advice or exercising discretion. **By granting this Authorisation, you expressly permit the Third-Party AI Terminal you deploy to submit order instructions to LongPort Securities on your behalf. Such instructions, once confirmed and transmitted, shall be treated as your own instructions to LongPort Securities and shall be binding upon execution. Each instruction originates from, and is solely attributable to, you as the account holder. You agree that LongPort Securities is entitled to act on such instructions without further verification of your identity beyond the authentication carried out at login.** **4. Risk Acknowledgement** You acknowledge and accept the following risks: The value of investments may rise or fall and past performance is not indicative of future results. Instructions transmitted via Third-Party AI Terminal on behalf of you to LongPort are binding upon execution. LongPort shall not be liable for any losses arising from instructions that you authorise, including instructions transmitted through any Third-Party AI Terminal. You are solely responsible for reviewing and verifying the accuracy of all instructions before they are submitted, regardless of the interface used. Third-Party AI Terminal may make errors in understanding or transmitting instructions. You should always confirm the details of any instruction before authorising it. Third-Party AI Terminal, as the entities responsible for AI terminal services, are obligated to comply with the PDPO and all other applicable Hong Kong laws in connection with the collection and processing of your data. You acknowledge that LongPort does not control Third-Party AI Terminal's data practices and that you should review the privacy policies of any third-party AI terminal before use. **5.** **Risk Warning --- Connecting Your Securities Account** Linking your brokerage or securities account to Third-Party Terminal grants the AI the ability to access account data and, depending on permissions, to place, modify, or cancel orders on your behalf. **This may result in partial or total loss of your assets.** By enabling this connection, you acknowledge and accept the following risks: **AI errors.** Third-Party Terminal may misinterpret instructions, hallucinate data, select the wrong ticker, quantity, price, or order side, or execute trades that do not match your intent. **Prompt injection attacks.** Malicious content hidden in emails, documents, websites, files, or other data sources may hijack the AI into executing unauthorized trades or transferring assets without your knowledge. **Rogue or compromised Third-Party Terminal servers.** Third-Party Terminal servers may not be audited. A malicious or breached server may intercept credentials, manipulate market data, or trigger unauthorized actions. **Scope creep in multi‑step workflows.** Agentic AI may take broader actions than you intended when chaining tools, documents, or accounts. **Credential and session risks.** API keys, OAuth tokens, or session credentials used to authenticate the MCP connection may be leaked, reused, or abused. **Market risk amplified by automation.** Even technically correct orders may incur losses due to slippage, volatility, or timing, and errors may be executed faster than you can intervene. **Limited audit trail.** AI agent actions may not be fully captured by your broker's or employer's standard monitoring systems, making detection and recovery of unauthorized trades difficult. **Legal and regulatory exposure.** Trades executed by an AI agent on your account are generally treated as *your* trades. You remain fully responsible for all resulting losses, taxes, margin calls, and regulatory consequences. **6. General Terms** This Authorisation is governed by, and construed in accordance with, the laws of Hong Kong. Any dispute arising out of or in connection with this Authorisation shall be subject to the exclusive jurisdiction of the Hong Kong courts. This Authorisation supplements, but does not replace, the terms and conditions of LongPort Platform, service rules including the Privacy Policy and other relevant terms or agreements. Please read carefully and thoroughly understand the foregoing documents and the contents of this Authorisation so as to make an informed authorization. LongPort reserves the right to amend this Authorisation form from time to time. Material changes will be notified to you in advance and, where required by applicable law, will require your re-confirmation. If any provision of this Authorisation is found to be invalid or unenforceable, the remaining provisions shall continue in full force and effect. ### LongPort Developers Platform Disclaimer — HK You have applied to the securities licensed corporation of this Platform (subject to the relevant page guidelines of this Platform, the "Securities Company") to use the Application Programming Interface ("API") service and entrust the Securities Company to trade with recognised exchange companies on your behalf. By entering into the transaction, you agree to be bound by these terms and conditions: **1.** This disclaimer is binding to your Account under the terms and conditions. You confirm that you have agreed to be bound by the operation of system and received the terms and conditions including but not limited to the Client Agreement, the term of services provided by the Securities Company, the related risk disclosure statement, any other relevant provisions, the relevant operation, rules and guidelines amended by the Stock Exchange of Hong Kong from time to time and the terms and conditions of the LongPort trading platform ("Terms and Conditions"). **2.** You confirm that you understand the risk of trading mentioned in the risk disclosure statement under the Terms and Conditions. **3.** The API access-in methods independently selected by you (including but not limited to self-developed systems, artificial intelligence applications and other technical interfaces, collectively referred to as "API Access-in Methods") and the API which you use is designed, developed or provided by natural persons, legal entities or other organizations ("Technology Provider") which is independent from the Securities Company. The Securities Company has no affiliation with such Technology Provider and makes no express or implied warranties regarding the Technology Provider's service quality, technical performance and security. You hereby irrevocably undertake that the selection of API Access-in Methods and utilization of the API constitute decisions made solely based on your independent judgement. You confirm that you possessed the requisite professional qualifications and operational capabilities to execute such transactions, and fully acknowledge the corresponding market risks, technical risks and operational risks that may consequently arise. **4.** You hereby irrevocably undertake that you shall bear the full responsibility for the following legal risks and losses, the Securities Company shall not bear any legal liability for including but not limited to: - a) Any loss arising from inherent defects in the API Access-in Methods selected by you independently and the API used, including trading errors, order delays, or the data discrepancies; - b) Trading anomalies caused by technical failures of the Technology Provider; - c) System interruptions resulting from force majeure, cyberattacks, or other causes not attributable to the Securities Company; - d) Abnormal trading outcomes due to your failure to comply with operational guidelines. **5.** Although the API is compatible with LongPort trading application ("Trading Application") as to proceed any trades, the Securities Company shall not be obliged to ensure compatibility between the API and Trading Application. The Securities Company is not liable for any loss or damage suffered as a result of any trading restrictions, obstacles or computing program errors which is caused by different network issues (including but not limited to disconnection, power outage, network congestion or system congestion), communications, trading mode selection, trading time settings, overnight trading, or system settings. The final outcome of every transaction is subject to the account statements provided by the Securities Company. **6.** You acknowledge and agree that the Securities Company has absolute discretion to decide the scope and content of any services provided through the API. The Securities Company also has the right to terminate such service at any time. The services provided by API is subject to the prevailing service provided by the Securities Company. **7.** You are responsible for sufficient protection of the personal account number, account password, transaction-related password and all other account security-related information and keeping your personal account secured from unauthorized use. You acknowledge and understand that you are the only user of your Account, Trading Application account, API and all relevant passwords and you are responsible for any instruction(s) or transaction(s) through the above-said account, API and all relevant passwords in any circumstances whatsoever. **8.** Regardless of the API Access-in Methods, you are responsible for all transaction instructions. You hereby confirm that each instruction genuinely reflects your trading intent, and the instruction generation process shall always remain under effective manual control. You may not claim that any instruction does not represent your true intention on grounds including but not limited to technical complexity, operational indirectness or system opacity ("black box" nature). **9.** You understand that any content and information such as market changes or real-time information obtained or provided by the API services shall not constitute an offer or solicitation to enter into any transaction. The Securities Company or the third party data provider provides the information on an "as is" and "as available" basis and is for general information only. You agree that while the Securities Company endeavours to ensure the accuracy and reliability of such information, the Securities Company does not warrant the accuracy, reliability, timeliness, completeness or correct sequencing of any such information and the Securities Company will not bear any liability for any loss arising from any inaccuracy, omission or incompleteness of the information or any reliance on such information. The Securities Company and the third party data provider will not be liable for any loss or damage resulting, directly or indirectly, from any error, delay or omission of information resulting from force majeure or other causes beyond the Securities Company's reasonable control. **10.** You understand that trading through the API may be different from trading through LongPort trading platform. If you trade through the API, you agree to bear the risks of using the API such as encountering possible malfunction of hardware or software. Your instruction(s) may not be executed due to the malfunction of the system. **11.** You are aware of the types of trading instruction(s), trading functions and the operation and risks of the trading process provided by the API. You have to understand the operational mechanisms and the risks involved in such trading before using API. You shall be responsible for any possible compliance and regulatory matters arising from the consequence or during the process of using the API. **12.** The use of the API / service is at your own risk while such service provided to you is without warranty of any kind, whether express or implied. The Securities Company does not guarantee the API services will operate/function without any interruption, failures or malfunctions. The Securities Company is not responsible for the outcome/consequence of the transaction by using the API service. You are solely responsible for any and all losses (including but not limited to, unlimited, special, incidental, consequential or punitive), directly or indirectly, from the use of or inability to use the services of the API. **13.** You agree to be bound by the trading rules provided by the Securities Company which govern the use of API from time to time. The extent of rules includes but not limited to the frequency of login/logout per minute, the frequency of placing orders and cancellations of orders, server usage limits, trading period and mechanisms. The Securities Company reserves the right to restrict or modify the use of an API according to the usage, risk management or other considerations. If there is any improper use of the API service, the Securities Company may restrict, cancel or terminate your access and connection to the API at any time without prior notice. **14.** The Securities Company absolutely prohibit you from engaging in any form of market manipulation or any suspicious activities with respect to any transaction. Subject to applicable laws and regulations, the Securities Company may, in its absolute discretion, take actions on any account(s) that is suspected of market manipulation or any suspicious activities including but not limited to investigate and review your profile, freeze or terminate the account(s) involved, approval before any instruction(s) took place and make any other necessary alterations or adjustments without prior notice. The Securities Company may, in its absolute discretion, report such those activities to any relevant regulatory and law enforcement authority where necessary. **15.** You acknowledge that you read and fully understand the terms and conditions set out above and agree to be bound by them. The Securities Company reserves the right to vary, amend, delete or replace any of the terms and conditions contained in these Terms and Conditions at any time. **16.** You acknowledge and agree that the Securities Company reserves the right to adjust the services abovementioned at any time without prior notice. ### LongPort Developers API Non-Commercial Licence Agreement — SG Whereas, (1) You intend to use the LongPort Developers application programming interface ("**API**") services provided by LongPort AI Technologies Pte. Ltd. ("**LongPort AI**" or "**Platform**"), which is associated with the entity licensed as a securities brokerage, being Long Bridge Securities Pte. Ltd. (the "**Securities Company**"). (2) In order to provide the API services to you, you acknowledge that you consent to be legally bound by this API Non-Commercial Licence Agreement ("**Agreement**"). This Agreement is between LongPort AI and you, in relation to your right and licence to use the API Code (as defined below) for Non-Commercial Purposes (as defined below). By clicking the "**I AGREE**" button, or downloading, installing, using or accessing API, you acknowledge that you consent to be legally bound by this Agreement. ## 1. Definitions and grant of Licence **1.1** Definitions "**Affiliate**" means, in relation to a party, an individual, corporation, a partnership or any other form of entity directly or indirectly controlling, controlled by, or under common control with, such party or any of such party's directors, officers or employees. A person is in "control" of a company, if: (a) the company acts in accordance with such person's directions or instructions; or (b) such person, either alone or with any associate, is entitled to exercise, or control the exercise of, more than 30% of the voting power at general meetings of the company; "**API**" or "**API Code**" means the user code and related documents developed by this Platform that is made available to you to develop platforms, tools, or interfaces for your personal use; and "**Account**" means any one or more accounts of any nature, including without limitation the securities accounts, margin accounts and fund accounts, howsoever integrated or separated, from time to time opened and maintained in your name with the Securities Company through which you may obtain services and/or effect transactions (as may be re-designated, re-numbered, re-located or otherwise modified from time to time); "**Non-Commercial Purposes**" means purposes that are solely relating to your personal use. **1.2** Subject to the terms of this Agreement, this Platform hereby grants you a personal, revocable, royalty-free, non-exclusive, non-sublicensable, non-transferable, restricted right and licence to install, modify and use the API Code solely for Non-Commercial Purposes ("**Licence**"). You shall not use the API Code for any application or service for any commercial purpose, regardless of whether you receive any consideration for such application or service. **1.3** The Licence shall only become effective on the date you accept all the terms and contents of this Agreement and when this Agreement becomes effective. **1.4** The Licence and the rights associated with such Licence will terminate automatically in the event: (1) you fail to comply with any term(s) of this Agreement; (2) you commit an act constituting the infringement of any right owned by the Platform; (3) you cancel your relevant account on this Platform and/or your Account; (4) this Platform sends you a notice of unilateral termination; or (5) there is the presence of any other circumstances that may adversely affect the Platform's rights and interests. **1.5** Upon termination of this Agreement, you shall immediately cease all use of the API Code, destroy all copies of the API Code completely, and shall not retain the API Code or the copies of API Code in any form after such destruction. ## 2. Restrictions **2.1** You acknowledge and agree that you shall only use API Code in compliance with the terms of the Agreement and for Non-Commercial Purposes. Any other uses of API Code are expressly prohibited. **2.2** This Platform shall own all rights, title and interest in and to the API Code granted hereunder. You agree not to use, copy, replace, adapt, modify, regenerate, displace, distribute, transmit, broadcast, sell, authorize, publish, lease, sublicense, convert, translate, de-engineer, decompile, disassemble, create derivatives of, or disclose the API Code or any part thereof in any way and for any purpose whatsoever to any third party. **2.3** Unless otherwise authorized by this Platform in writing, you shall not provide any assistance to any third party to engage in any matter which violates this Agreement, or engage in or agree with any third party to engage in the following actions (including but not limited to): (1) using API Code to interrupt, damage or limit the use of API Code or other software, hardware, platforms, applications, web pages and systems belonging to the Platform; (2) engaging in any mining of personal information and data; (3) bypassing or making unavailable the blocking or restriction of copying behavior in API Code, or interfering with the security-related characteristics of API Code; (4) moving, replacing, or obscuring of any trademark, copyright, legal, or patent notice of API Code; (5) using API Code in any software or program that may contain viruses, trojan, software, worms, time bombs, autopilot viruses, or any other computer code or documentation designed to interrupt, damage or limit the API Code or its use in any of the Platform's software, hardware, platforms, applications, web pages and systems. **2.4** You agree and confirm that you will, during the licence period, continue to use the Licence hereunder in accordance with applicable local laws and in accordance with any applicable user agreement or service rules as updated by this Platform from time to time. **2.5** You agree not to use the API Code for any purpose that violates any law, regulation, or any rights of any person (including but not limited to intellectual property rights and privacy rights). ## 3. Intellectual Property Except as expressly set forth herein, this Platform shall own all rights, title and interest in and to the API and API Code, including but not limited to any code or documentation written by this Platform relating to the API Code, and any intellectual property rights in and to any modifications, replacements, translations or derivatives thereof. ## 4. Disclaimer of Warranties **4.1** You expressly acknowledge and agree that the API Code granted hereunder, is provided on an "as-is" and "as-available" basis, and may contain in whole or in part pre-release, untested, or not fully tested work. You acknowledge that the API Code may contain errors that could cause failures or loss of data, and may be incomplete or contain inaccuracies. **4.2** You understand and agree that the API Code granted hereunder is provided without warranty of any kind, either express or implied, including but not limited to: warranties that the API Code is free of defects, merchantable, non-infringing or fit for a particular purpose. This disclaimer of warranties constitutes an essential part of this Licence. You hereby agree and accept the foregoing disclaimer and that all risk resulting from your use of the API Code or applications developed using the API Code is at your sole risk. ## 5. Warranty and Guarantee You undertake and shall use all reasonable efforts to indemnify, defend and hold harmless the Platform, its affiliates and their representatives, directors, employees and agents from and against any claim, action, suit or proceeding, and any loss, liability, damage, cost and expense arising out of: (1) Your actions and/or omissions in connection with your use of API Code; (2) Your use of API Code to develop relevant applications, or any of your actions that infringes upon any rights and interests of a third party (including copyright, trademark, trade secret, trade dress, patent and other intellectual property rights or other interests); and/or (3) any action in violation of this Agreement. ## 6. Dispute Resolution **6.1** The Agreement and all rights, obligations and liabilities of the parties shall be governed by and construed in accordance with the laws of Singapore. **6.2** The courts of Singapore have exclusive jurisdiction to settle any dispute arising out of or in connection with the Agreement (including any dispute regarding the existence, validity or termination of the Agreement) (a "**Dispute**"). The parties agree that the courts of Singapore are the most appropriate and convenient courts to settle any Dispute. Notwithstanding the aforesaid, the Platform shall not be prevented from settling proceedings relating to a Dispute in any other courts with jurisdiction. To the extent allowed by applicable regulations, this Platform may take concurrent proceedings in any number of jurisdictions. ## 7. Miscellaneous **7.1** You agree that if the Platform does not exercise or enforce any legal right or remedy which is contained in this Agreement under any applicable law, it will not be taken to be a formal waiver of the Platform's rights and those rights or remedies will still be available to the Platform. **7.2** This Agreement constitutes the whole legal agreement between you and the Platform governing your use of the API services. **7.3** You may not assign, transfer, grant or sublicense any rights and authorizations under this Agreement. However, this Platform may assign, transfer, grant or sublicense any rights and authorizations under this Agreement to its affiliates or other applicable entities without restriction. **7.4** If you are entering into this Agreement on behalf of your employer or a corporate entity, you represent and warrant that you have full legal authority to bind your employer or such entity to this Agreement. **7.5** All risks and adverse consequences arising from your violation of this Agreement shall be borne by you. ### User Data Authorisation and Acknowledgement — SG Please read this Authorisation carefully before proceeding. **By completing and submitting this Authorisation, you acknowledge and confirm that you have read, understood, and agree to be bound by all terms set out below in connection with the LongPort Developers.** **1. Background** LongPort AI Technology Pte. Ltd. and its affiliates (collectively, "**LongPort**") provide programmatic interfaces through which market data, account functionalities, and related services are encapsulated and made available to users in the form of Command-Line Interface tools, Model Context Protocol integrations, and other developer tools and services (collectively, "**LongPort Developers**"). You may access and invoke the relevant interfaces based on your own needs and integrate them with third-party AI terminals or applications you select (including, without limitation, OpenClaw, Claude Code, Cursor, and similar tools) ("**Third-Party AI Terminals**"). Upon installation and successful connection, users may interact with the LongPort Platform and/or their platform or securities accounts (where applicable) through such third-party terminals or applications. This Authorisation governs: (a) the sharing of your selected account data among the relevant LongPort group entities and with relevant Third-Party AI Terminals ; and (b) the terms on which instructions you issue through Third-Party AI Terminals are treated as your own instructions for the purpose of executing securities transactions. **2. Data Sharing Authorisation and Purpose of Sharing** **2.1 Authorised Data Scope** The categories of data covered by this Authorisation are displayed below and/or under "Quotes Permission" section on the OAuth authorisation page, and are subject to your selection. Unless otherwise specified, data related to securities trading will generally be shared by Long Bridge Securities Pte. Ltd. ("**LongPort Securities**"), while other data will be shared by LongPort Platform (as defined in the LongPort Platform Terms and Conditions), to LongPort. The data categories that may be available are organized into the following capability groups, with access granted on a feature-by-feature basis depending on the functionality selected on the relevant page. The specific set of available tools and their read / create / update / delete permissions may be added, adjusted or retired from time to time as LongPort Developers evolves; the latest inventory is as published at [https://open.longport.com/docs/mcp](https://open.longport.com/docs/mcp) and on the OAuth authorization page: 1. **Real-time Market Data** --- Real-time market quotes and order-book data across markets. 2. **Fundamentals & Research** --- Company fundamentals and research data. 3. **Derivatives** --- Data relating to options, warrants and other derivatives. 4. **Account & Portfolio** --- Access to account, cash and position data, and the maintenance of portfolio constructs such as watchlists. 5. **Trading** --- Securities trade execution and the management of the order lifecycle. 6. **Automation** --- Management of automated tasks triggered by conditions you have pre-set. The specific functionality, coverage and read / write permissions within the categories above may be adjusted or expanded from time to time. Any newly added data capability category will be presented as a separately selectable item on the OAuth authorization page before being shared with any Third-Party AI Terminal, and the corresponding data will only be shared after you have actively selected it and completed the authorization. **2.2 Further Sharing with Third-Party AI Terminals** By granting authorisation hereunder, you acknowledge and agree that the authorisation you hereby grant to LongPort may, to the extent necessary to fulfil the purposes of LongPort Developers and strictly in accordance with the PDPA, be further shared with Third-Party AI Terminals that you deploy. Each such Third-Party AI Terminals shall be responsible for the AI services they provide to you, and shall be independently responsible for their compliance with applicable laws and regulations, including the PDPA. You acknowledge that LongPort does not control Third-Party AI Terminals' data practices and that you should review the privacy policies of any Third-Party AI Terminals before use. **2.3 Purpose of Sharing** The data shared pursuant to your selections above will be used exclusively to enable the functionality of the LongPort Developer. No data will be shared for any other purpose without your separate consent. **2.4 Data Protection, Access Control and Compliance** All data collection, storage, and processing activities are conducted in accordance with the Personal Data Protection Act 2012 of Singapore ("**PDPA**") and other applicable data protection regulations. LongPort will only retain your data for as long as is necessary to fulfil the purposes set out in this Authorisation, or as required by applicable laws. You have the right to withdraw your consent, access your data, and request correction of inaccurate data, in each case in accordance with the PDPA. You may withdraw this Authorisation at any time by updating your settings within the LongPort platform. Withdrawal will take effect prospectively and will not affect instructions already submitted or executed prior to the effective date of withdrawal. You may revoke or disconnect Third-Party AI Terminal access at any time through the platform settings or other designated methods made available by LongPort. Certain access or functionality may be suspended, restricted, or terminated where reasonably necessary for security, system protection, operational, compliance, or risk management purposes. **3. Nature and Effect of Instructions via Third-Party AI Terminals(when applicable)** You acknowledge and agree that when you issue instructions through Third-Party AI Terminals, which instructions shall be transmitted to and executed by LongPort Securities: LongPort acts solely as the developer of the LongPort Developers. LongPort does not control, review, endorse, or assume any responsibility or liability for the content, instructions, recommendations, or outputs generated by any Third-Party AI Terminal, including any trading decisions or outcomes arising therefrom. The Third-Party AI Terminal you selectis the responsible party for the AI services provided to you and you remain solely responsible for independently evaluating and verifying any information or recommendations provided by Third-Party AI Terminal before taking any action. The Third-Party AI Terminal transmits instructions on your behalf to LongPort Securities for execution, but does not itself initiate, modify, interpret, or exercise any discretion over any instruction. Each instruction transmitted via Third-Party AI Terminal must be initiated by you through an explicit and deliberate user action. No instruction will be automatically generated, triggered, or executed without your input and confirmation. No Third-Party AI Terminal has constituted/ currently constitutes /will constitute an agent, representative, investment adviser, or decision-making entity of any LongPort group entity or of you personally. Securities services and brokerage functions referred to in this Authorisation are provided by LongPort Securities, a capital markets services licence holder regulated by the Monetary Authority of Singapore. LongPort Securities executes instructions strictly in accordance with your authorisation, on an execution-only basis, without providing investment advice or exercising discretion. **By granting this Authorisation, you expressly permit the Third-Party AI Terminal you select to submit trading instructions to LongPort Securities on your behalf. Such instructions, once confirmed and transmitted, shall be treated as your own instructions to LongPort Securities and shall be binding upon execution. Each instruction originates from, and is solely attributable to, you as the account holder. You agree that LongPort Securities is entitled to act on such instructions without further verification of your identity beyond the authentication carried out at login.** **4. Risk Acknowledgement** You acknowledge and accept the following risks: The value of investments may rise or fall and past performance is not indicative of future results. Instructions transmitted via Third-Party AI Terminal on behalf of you to LongPort are binding upon execution. LongPort shall not be liable for any losses arising from instructions that you authorise, including instructions transmitted through any Third-Party AI Terminal. You are solely responsible for reviewing and verifying the accuracy of all instructions before they are submitted, regardless of the interface used. Third-Party AI Terminal may make errors in understanding or transmitting instructions. You should always confirm the details of any instruction before authorising it. Third-Party Terminals, as the entities responsible for AI terminal services, are obligated to comply with the PDPA and all other applicable Singapore laws in connection with the collection and processing of your data. You acknowledge that LongPort does not control Third-Party Terminals' data practices and that you should review the privacy policies of any third-party AI terminal before use. **5. General Terms** This Authorisation is governed by, and construed in accordance with, the laws of Singapore. Any dispute arising out of or in connection with this Authorisation shall be subject to the exclusive jurisdiction of the Singapore courts. This Authorisation supplements, but does not replace, the [LongPort Platform Terms and Conditions](https://support.longport.sg/topics/us-trade/user-agreement?locale=en) , the [Privacy Policy](https://support.longport.sg/topics/Other/privacy-policy?locale=en) and other relevant terms or agreements. Please read carefully and understand thoroughly the foregoing documents and the contents of this Statement so as to make an informed authorization. LongPort reserves the right to amend this Authorisation form from time to time. Material changes will be notified to you in advance and, where required by applicable law, will require your re-confirmation. If any provision of this Authorisation is found to be invalid or unenforceable, the remaining provisions shall continue in full force and effect. ### LongPort API Non-Commercial Licence Agreement — HK Whereas, (1) You have applied to the securities licensed corporation of this Platform (subject to the relevant page guidelines of this Platform, the "Securities Company") to use the Application Programming Interface ("API") service; (2) In order to provide API service to you, you acknowledge that you consent to be legally bound by this API Code Non-Commercial License Agreement ("Agreement"). This Agreement is entered into by and between this Platform (as defined in the *LongPort Platform Service Agreement*) ("**we**", "**us**" or "**our**") and **you**, regarding the API which grants you a limited license to use the API Code solely for Non-Commercial Purposes (as defined below). Your download, installation, use or access of the API constitutes your acceptance of and agreement to be bound by the terms of this Agreement. ## 1. Definition and License Grant **1.1** Definitions "Affiliate" means, in relation to a party, an individual, corporation, a partnership or any other form of entity directly or indirectly controlling, controlled by or under common control with such party or any of such entities' directors, officers or employees. A person is in "control" of a company, if: (a) it is in accordance with such person's directions or instructions that the directors of the company or of another company of which it is a subsidiary are accustomed to act; or (b) such person, either alone or with any Associate, is entitled to exercise, or control the exercise of, more than 30% of the voting power at general meetings of the company or of another company of which it is a subsidiary. "API" or "API Code" means the user code and related documents developed by this Platform that is made available to you to develop platforms, tools, or interfaces for your personal use with this Platform's accounts or this Platform's systems; "Account" means any one or more accounts of any nature, including without limitation the securities accounts, margin accounts and fund accounts, howsoever integrated or separated, from time to time opened and maintained in the name of you with the securities licensed corporation (as may be subject to the notices and the relevant page guidelines of this Platform) under this Platform through which you may obtain services and/or effect transactions, as the same may be re-designated, re-numbered, re-located or otherwise modified from time to time. **1.2** Subject to the terms of this Agreement, this Platform hereby grants You a personal, revocable, royalty-free, non-exclusive, non-sublicensable, non-transferable, restricted right and license to install, modify and use the API Code solely for Non-Commercial Purposes ("License"). **1.3** "Non-Commercial Purposes" means your License under this Agreement is limited to develop platforms, tools, or interfaces for your personal use. You shall not use the API Code for any application or service for yourself or for anyone else for any commercial purpose, regardless of whether You receive any consideration for such application or service. **1.4** The License shall only become effective on the date you accept all the terms and contents of this Agreement and when this Agreement becomes effective. **1.5** The License and the right will terminate automatically: (1) if you fail to comply with any term(s) of this Agreement; (2) if you commit an action for right infringement against this Platform; (3) if you cancel your relevant this Platform's account and Account; (4) if this Platform sends you the notice of unilateral termination; (5) if any other circumstances occur in which to protect this Platform's legitimate rights and interests. **1.6** Upon termination of this Agreement, you shall immediately cease all use of API Code granted hereunder, destroy all copies of API Code completely and shall not retain API Code or the copies of API Code in any form after such destruction. ## 2. Restrictions **2.1** You acknowledge and agree that you shall only use API Code in compliance with the terms of the Agreement and for Non-Commercial Purposes. Any other uses of API Code are expressly prohibited. **2.2** This Platform shall own all right, title and interest in and to API Code granted hereunder. You agree not to use, copy, replace, adapt, modify, regenerate, displace, distribute, transmit, broadcast, sell, authorize, publish, lease, sublicense, convert, translate, de-engineer, decompile, disassemble, create derivatives of, or disclose API Code or any part thereof in any way and for any purpose whatsoever to any third party. **2.3** Unless otherwise authorized by this Platform in writing, you shall not engage in or agree with any third party to engage in the following actions, or provide any assistance to any third party to engage in any matter in violation of this Agreement, including but not limited to: (1) using API Code to interrupt, damage or limit the use of API Code or other LongPort software, hardware, platforms, applications, web pages and systems; (2) engaging in any mining of personal information and data; (3) bypassing or making unavailable the blocking or restriction of copying behavior in API Code, or interfering with the security-related characteristics of API Code; (4) moving, replacing, or obscuring of any trademark, copyright, legal, or patent notice of API Code; (5) using API Code in any software or program that may contain viruses, trojan, software, worms, time bombs, autopilot viruses, or any other computer code or documentation designed to interrupt, damage or limit the API Code or the use in any LongPort software, hardware, platforms, applications, web pages and systems. **2.4** You agree and confirm that you will, during the license period, continue to use the License hereunder in accordance with applicable local laws and in accordance with user agreement or service rules as updated by this Platform from time to time. **2.5** You agree not to use the API Code for any purpose that violates any law or regulation, any right of any person, including but not limited to intellectual property rights, rights of privacy, or rights of personality, or in any manner in violation of this Agreement or the privacy policy. ## 3. Intellectual Property Except as expressly set forth herein, this Platform shall own all right, title and interest in and to the API and API Code, including but not limited to any code or documentation written by this Platform relating to the API Code, and any intellectual property rights in and to any modifications, replacements, translations or derivatives thereof. This Platform shall, to the extent permitted by law, have all rights and interests in and to the foregoing results. ## 4. Disclaimer of Warranties **4.1** You expressly acknowledge and agree that the API Code granted hereunder, all provided "as is" and on an "as-available" basis, may contain in whole or in part pre-release, untested, or not fully tested works. The API Code may contain errors that could cause failures or loss of data, and may be incomplete or contain inaccuracies. **4.2** You understand and agree that the API Code granted hereunder is provided without warranty of any kind, either express or implied, including but not limited to, warranties that the API Code is free of defects, merchantable, non-infringing or fit for a particular purpose. This disclaimer of warranties constitutes an essential part of this License. You hereby agree and accept the foregoing disclaimer and that all risk resulting from Your use of the API Code or applications developed using the API Code is at Your sole and entire risk. ## 5. Warranty and Guarantee You undertake and shall use all reasonable efforts to indemnify, defend and hold harmless LongPort, its affiliates and their representatives, directors, employees and agents from and against any claim, action, suit or proceeding, and any loss, liability, damage, cost and expense arising out of: (1) Your action in connection with the use of API Code; (2) Your use of API Code to develop relevant applications, or any action that causes legitimate rights and interests of a third party (including copyright, trademark, trade secret, trade dress, patent and other intellectual property rights or other interests); (3) any action in violation of this Agreement. ## 6. Dispute Resolution **6.1** The Agreement and all rights, obligations and liabilities of the parties shall be governed by and construed in accordance with the laws of Hong Kong. **6.2** The courts of Hong Kong have exclusive jurisdiction to settle any dispute arising out of or in connection with the Agreement (including any dispute regarding the existence, validity or termination of the Agreement) (a "Dispute"). The parties agree that the courts of Hong Kong are the most appropriate and convenient courts to settle Disputes and accordingly, no party will argue to the contrary. Notwithstanding the aforesaid, this Platform shall not be prevented from taking proceedings relating to a Dispute in any other courts with jurisdiction. To the extent allowed by applicable regulations, this Platform may take concurrent proceedings in any number of jurisdictions. ## 7. Miscellaneous **7.1** You agree that if this Platform does not exercise or enforce any legal right or remedy which is contained in this Agreement or is available to this Platform under any applicable law, this will not be taken to be a formal waiver of LongPort's rights and that those rights or remedies will still be available to LongPort. **7.2** This Agreement constitutes the whole legal agreement between you and this Platform and governs your use of the API Code, and completely replaces any prior agreements between you and this Platform in relation to the API Code. **7.3** You may not assign, transfer, grant or sublicense this Agreement or any rights and authorizations hereunder, while this Platform may assign, transfer, grant or sublicense this Agreement or any rights and authorizations hereunder to its affiliates or other applicable entities without restriction. **7.4** If you are entering into this Agreement on behalf of your employer or other entity, you represent and warrant that you have full legal authority to bind your employer or such entity to this Agreement. **7.5** All risks and adverse consequences arising from your violation of this Agreement shall be borne by you. ### LongPort Developers Platform Disclaimer — SG You intend to use the LongPort Developers application programming interface ("**API**") services provided by LongPort AI Technologies Pte. Ltd. ("**LongPort AI**"), which is associated with the trading platform provided by the entity licensed as a securities brokerage, being Long Bridge Securities Pte. Ltd. (the "**Securities Company**"). By entering into the transaction, you agree to be bound by these terms and conditions: **1.** This disclaimer is binding with respect to your client account under the relevant terms and conditions. You confirm that you have agreed to be bound by the terms and conditions including but not limited to the customer agreement and term of services provided by the Securities Company, the related risk disclosure statements, any other relevant provisions, rules and guidelines amended by the Singapore Exchange from time to time and the terms and conditions associated with the LongPort trading platform ("**Terms and Conditions**"). **2.** You confirm that you understand the risk of trading mentioned in the risk disclosure statement under the Terms and Conditions. **3.** The API access-in methods independently selected by you, including but not limited to self-developed systems, artificial intelligence applications and other technical interfaces (collectively referred to as "**API Access-in Methods**"), and the API which you use is designed, developed or provided by LongPort AI or such other relevant legal entities ("**Technology Provider**"), which is independent from the Securities Company. The Securities Company makes no express or implied warranties regarding the Technology Provider's service quality, technical performance and security. You hereby irrevocably undertake that the selection of API Access-in Methods and utilization of the API constitute decisions made solely based on your independent judgment. You confirm that you possess the requisite professional qualifications and operational capabilities to execute such transactions, and fully acknowledge the corresponding market risks, technical risks and operational risks that may consequently arise. **4.** You hereby irrevocably undertake that you shall bear the full responsibility for the following legal risks and losses, and neither the Technology Provider nor the Securities Company shall bear any legal liability for the following, including but not limited to: - a) Any loss arising from inherent defects in the API Access-in Methods selected by you independently and the API used, including trading errors, order delays, or data discrepancies; - b) Trading anomalies caused by technical failures of the Technology Provider; - c) System interruptions resulting from force majeure, cyberattacks, or other causes not attributable to the Securities Company; or - d) Abnormal trading outcomes due to your failure to comply with operational guidelines. **5.** Although the API is compatible with the LongPort trading application ("**Trading Application**") to proceed any trades, the Securities Company shall not be obliged to ensure compatibility between the API and Trading Application. The Securities Company is not liable for any loss or damage suffered as a result of any trading restrictions, obstacles or computing program errors which is caused by different network issues (including but not limited to disconnection, power outage, network congestion or system congestion), communications, trading mode selection, trading time settings, overnight trading, or system settings. The final outcome of every transaction is subject to the account statements provided by the Securities Company. **6.** You acknowledge and agree that the Securities Company has absolute discretion to decide the scope and content of any services provided through the API. The Securities Company also has the right to terminate such service at any time. The services provided by API is subject to the prevailing terms of service provided by the Securities Company. **7.** You are responsible for ensuring the protection of your personal account number, account passwords, transaction-related passwords and all other account security-related information. You are also responsible for keeping your personal account secured from unauthorized use. You acknowledge and understand that you are the only user of your client account, Trading Application account, API and all relevant passwords, and you are responsible for any instruction(s) or transaction(s) through the above-said accounts and/or use of the API. **8.** Regardless of the API Access-in Methods, you are responsible for all transaction instructions. You hereby confirm that each instruction genuinely reflects your trading intent, and the instruction generation process shall always remain under your effective manual control. You may not claim that any instruction does not represent your true intention on grounds including but not limited to technical complexity, operational indirectness or system opacity. **9.** You understand that any content and information such as market changes or real-time information obtained or provided by the API services shall not constitute an offer or solicitation to enter into any transaction. The Securities Company or the third party data provider provides the information on an "as is" and "as available" basis and is for general information only. You agree that while the Securities Company endeavours to ensure the accuracy and reliability of such information, the Securities Company does not warrant the accuracy, reliability, timeliness, completeness or correct sequencing of any such information and the Securities Company will not bear any liability for any loss arising from any inaccuracy, omission or incompleteness of the information or any reliance on such information. The Securities Company and any third party data provider will not be liable for any loss or damage resulting, directly or indirectly, from any error, delay or omission of information resulting from force majeure or other causes beyond the Securities Company's reasonable control. **10.** You understand that trading through the API may be different from trading through the Trading Application. If you trade through the API, you agree to bear the risks of using the API such as encountering possible malfunction of hardware or software. Your instruction(s) may not be executed due to the malfunction of the system. **11.** You are aware of the types of trading instruction(s), trading functions and the operation and risks of the trading process provided by the API. You have to understand the operational mechanisms and the risks involved in such trading before using API. You shall be responsible for any possible compliance and regulatory matters arising from the consequence or during the process of using the API. **12.** The use of the API services is at your own risk and such services provided to you are without warranty of any kind, whether express or implied. The Securities Company does not guarantee the API services will operate/function without any interruption, failures or malfunctions. The Securities Company is not responsible for the outcome/consequence of the transaction by using the API service. You are solely responsible for any and all losses (including but not limited to, unlimited, special, incidental, consequential or punitive), directly or indirectly, from the use of or inability to use the services of the API. **13.** You agree to be bound by the trading rules provided by the Securities Company which govern the use of the API from time to time. The extent of rules includes but is not limited to the frequency of login/logout per minute, the frequency of placing orders and cancellations of orders, server usage limits, trading period and mechanisms. The Securities Company reserves the right to restrict or modify the use of an API according to the usage, risk management or other considerations. If there is any improper use of the API service, the Technology Provider and/or the Securities Company may restrict, cancel or terminate your access and connection to the API at any time without prior notice. **14.** The Securities Company absolutely prohibits you from engaging in any form of market manipulation or any suspicious activities with respect to any transaction. Subject to applicable laws and regulations, the Securities Company may, in its absolute discretion, take action on any account(s) that is suspected of market manipulation or any suspicious activities, including but not limited to investigating and reviewing your profile, freezing or terminating the account(s) involved, having to provide approval before any instruction(s) take place, and making any other necessary alterations or adjustments without prior notice. The Securities Company may, in its absolute discretion, report such activities to any relevant regulatory and law enforcement authorities where necessary. **15.** You acknowledge that you have read and fully understand the terms and conditions set out above and agree to be bound by them. The Technology Provider and/or Securities Company reserves the right to vary, amend, delete or replace any of the terms and conditions contained in these Terms and Conditions at any time. **16.** You acknowledge and agree that the Technology Provider and/or the Securities Company reserve the right to adjust the services abovementioned at any time without prior notice. ### Legal # Legal Legal agreements and disclaimers for LongPort Developers. Documents are provided separately for each operating region — please refer to the version applicable to your account. ## Singapore (SG) - [User Data Authorisation and Acknowledgement](./user-data-authorization-sg) - [Developers Platform Disclaimer](./developers-platform-disclaimer-sg) - [API Non-Commercial Licence Agreement](./api-license-agreement-sg) ## Hong Kong (HK) - [User Data Authorisation and Acknowledgement](./user-data-authorization-hk) - [Developers Platform Disclaimer](./developers-platform-disclaimer-hk) - [API Non-Commercial Licence Agreement](./api-license-agreement-hk) ### Quote ### Overview # Quote API Overview
Type Description
Pull Get Basic Information Of Securities
Get Real-time Quotes Of Securities
Get Real-time Quotes Of Option Securities
Get Real-time Quotes Of Warrant Securities
Get Security Depth
Get Security Brokers
Get Broker IDs
Get Security Trades
Get Security Intraday
Get Security Candlestick
Get Option Chain Expiry Date List
Get Option Chain Info By Date
Get Warrant Issuer IDs
Get Filtered Warrant
Get Trading Session Of The Day
Get Market Trading Days
Get Security Capital Flow Intraday
Get Security Capital Distribution
Get Calculate Indexes Of Securities
Get Security History Candlestick
Subscription Get Subscription Information
Subscribe Quote
Unsubscribe Quote
Push Push Real-time Quote
Push Real-time Depth
Push Real-time Brokers
Push Real-time Trades
Individual Create watched group
Delete watched group
Get watched groups
Update watched group
Security Get Security List
## Description Of Security Code The security code uses the `ticker.region` format, `ticker` represents the code, and example for each market: - US Market: `region` is `US`, for example: `AAPL.US`. - HK Market: `region` is `HK`, for example: `700.HK`. - CN Market: `region` is `SH` for Shanghai Stock Exchange and `SZ` for Shenzhen Stock Exchange, for example: `399001.SZ`, `600519.SH`. > **Singapore Market (SG):** Real-time quotes for Singapore securities are not currently available via LongPort Developers (API / MCP). Please use the [LongPort App or desktop client](https://longport.com/download) to check SG market quotes. ## Access Method 1. Use private protocol and long connection mode to access, please refer to Binary Communication Protocol for access method. 2. Use SDK for access, [SDK introduction and download address](https://open.longport.com/sdk). ## Business Data Serialization The market request, response and push data are stored as business data in the body part of the data package of the private protocol. We use the [Protobuf](https://developers.google.cn/protocol-buffers) protocol to serialize business data. Compared with common text protocols (such as JSON, XML, etc.), the Protobuf protocol has the following advantages: - Faster serialization time. - Smaller packet size. - Strongger version forward and backward compatibility. Quote Protobuf protocol document [download link](https://github.com/longportapp/openapi-protobufs/blob/main/quote/api.proto). ## Quote Permission Levels All Quote APIs require OpenAPI quote permissions. These are **separate from App/PC/Web permissions** and must be activated independently. | Level | What's Included | How to Get | | ---------------------- | ---------------------------------------------------- | ---------------------------------------------------------- | | **Basic** | LV1 US/CN real-time; HK BMP (~15 min delay, no push) | Included with OpenAPI activation | | **LV1 Real-time** (HK) | HK real-time quotes + WebSocket push support | Purchase "LV1 Real-time Quotes (OpenAPI)" via Quote Store | | **LV2 Subscription** | Level 2 order book (depth), HK broker queue | Purchase LV2 subscription via Quote Store | | **Overnight** (US) | US pre/post-market extended-hours data | Included free in US LV1; set `LONGPORT_ENABLE_OVERNIGHT=true` | Check your current permissions at [Developer Center](https://open.longport.com/dashboard). Purchase quote cards via **LongPort App → My → My Quotes → Quote Store**. ### Definition ## TradeStatus - Security Status Security Status | ID | Description | | --- | ------------------- | | 0 | Normal | | 1 | Suspension | | 2 | Delisted | | 3 | Fuse | | 4 | Papare List | | 5 | Code Moved | | 6 | To Be Opened | | 7 | Split Stock Halts | | 8 | Expired | | 9 | Warrant To BeListed | | 10 | Suspend | ### Protobuf ```protobuf enum TradeStatus { NORMAL = 0; HALTED = 1; DELISTED = 2; FUSE = 3; PREPARE_LIST = 4; CODE_MOVED = 5; TO_BE_OPENED = 6; SPLIT_STOCK_HALTS = 7; EXPIRED = 8; WARRANT_PREPARE_LIST = 9; SUSPEND_TRADE = 10; } ``` ## TradeSession - Trading Session Trading Session | ID | Description | | --- | ----------------- | | 0 | Trading | | 1 | Pre-Tradeing | | 2 | Post-Tradeing | | 3 | OverNight-Trading | ### Protobuf ```protobuf enum TradeSession { NORMAL_TRADE = 0; PRE_TRADE = 1; POST_TRADE = 2; } ``` ## Period - Candlestick Period | ID | Description | | ---- | ------------------ | | 1 | One Minute | | 2 | Two Minutes | | 3 | Three Minutes | | 5 | Five Minutes | | 10 | Ten Minutes | | 15 | Fifteen Minutes | | 20 | Twenty Minutes | | 30 | Thirty Minutes | | 45 | Forty-five Minutes | | 60 | Sixty Minutes | | 120 | Two Hours | | 180 | Three Hours | | 240 | Four Hours | | 1000 | One Days | | 2000 | One Week | | 3000 | One Month | | 3500 | One Quarter | | 4000 | One Year | ### Protobuf ```protobuf enum Period { UNKNOWN_PERIOD = 0; ONE_MINUTE = 1; FIVE_MINUTE = 5; FIFTEEN_MINUTE = 15; THIRTY_MINUTE = 30; SIXTY_MINUTE = 60; DAY = 1000; WEEK = 2000; MONTH = 3000; YEAR = 4000; } ``` ## AdjustType - Candlestick Adjustment Type | ID | Description | | --- | -------------- | | 0 | Actual | | 1 | Adjust forward | ### Protobuf ```protobuf enum AdjustType { NO_ADJUST = 0; FORWARD_ADJUST = 1; } ``` ## SubType - Quote Type Of Subscription | ID | Description | | --- | ----------- | | 1 | Quote | | 2 | Depth | | 3 | Broker | | 4 | Trade | ### Protobuf ```protobuf enum SubType { UNKNOWN_TYPE = 0; QUOTE = 1; DEPTH = 2; BROKERS = 3; TRADE = 4; } ``` ## CalcIndex - Calculate Index | ID | Description | Applicable Security Type | | --- | ---------------------------------- | ------------------------ | | 1 | Latest price | All | | 2 | Change value | All | | 3 | Change ratio | All | | 4 | Volume | All | | 5 | Turnover | All | | 6 | Year-to-date change ratio | Except Option, Warrant | | 7 | Turnover rate | Except Option, Warrant | | 8 | Total market value | Except Option, Warrant | | 9 | Capital flow | Except Option, Warrant | | 10 | Amplitude | Except Option, Warrant | | 11 | Volume ratio | Except Option, Warrant | | 12 | PE (TTM) | Except Option, Warrant | | 13 | PB | Except Option, Warrant | | 14 | Dividend ratio (TTM) | Except Option, Warrant | | 15 | Five days change ratio | Except Option, Warrant | | 16 | Ten days change ratio | Except Option, Warrant | | 17 | Half year change ratio | Except Option, Warrant | | 18 | Five minutes change ratio | Except Option, Warrant | | 19 | Expiry date | Only Option, Warrant | | 20 | Strike Price | Only Option, Warrant | | 21 | Upper bound price | Only Warrant | | 22 | Lower bound price | Only Warrant | | 23 | Outstanding quantity | Only Warrant | | 24 | Outstanding ratio | Only Warrant | | 25 | Premium | Only Option, Warrant | | 26 | In/out of the bound | Only Warrant | | 27 | Implied volatility | Only Option, Warrant | | 28 | Warrant delta | Only Warrant | | 29 | Call price | Only Warrant | | 30 | Price interval from the call price | Only Warrant | | 31 | Effective leverage | Only Warrant | | 32 | Leverage ratio | Only Warrant | | 33 | Conversion ratio | Only Warrant | | 34 | Breakeven point | Only Warrant | | 35 | Open interest | Only Option | | 36 | Delta | Only Option | | 37 | Gamma | Only Option | | 38 | Theta | Only Option | | 39 | Vega | Only Option | | 40 | Rho | Only Option | ### Protobuf ```protobuf enum CalcIndex { CALCINDEX_UNKNOWN = 0; CALCINDEX_LAST_DONE = 1; CALCINDEX_CHANGE_VAL = 2; CALCINDEX_CHANGE_RATE = 3; CALCINDEX_VOLUME = 4; CALCINDEX_TURNOVER = 5; CALCINDEX_YTD_CHANGE_RATE = 6; CALCINDEX_TURNOVER_RATE = 7; CALCINDEX_TOTAL_MARKET_VALUE = 8; CALCINDEX_CAPITAL_FLOW = 9; CALCINDEX_AMPLITUDE = 10; CALCINDEX_VOLUME_RATIO = 11; CALCINDEX_PE_TTM_RATIO = 12; CALCINDEX_PB_RATIO = 13; CALCINDEX_DIVIDEND_RATIO_TTM = 14; CALCINDEX_FIVE_DAY_CHANGE_RATE = 15; CALCINDEX_TEN_DAY_CHANGE_RATE = 16; CALCINDEX_HALF_YEAR_CHANGE_RATE = 17; CALCINDEX_FIVE_MINUTES_CHANGE_RATE = 18; CALCINDEX_EXPIRY_DATE = 19; CALCINDEX_STRIKE_PRICE = 20; CALCINDEX_UPPER_STRIKE_PRICE = 21; CALCINDEX_LOWER_STRIKE_PRICE = 22; CALCINDEX_OUTSTANDING_QTY = 23; CALCINDEX_OUTSTANDING_RATIO = 24; CALCINDEX_PREMIUM = 25; CALCINDEX_ITM_OTM = 26; CALCINDEX_IMPLIED_VOLATILITY = 27; CALCINDEX_WARRANT_DELTA = 28; CALCINDEX_CALL_PRICE = 29; CALCINDEX_TO_CALL_PRICE = 30; CALCINDEX_EFFECTIVE_LEVERAGE = 31; CALCINDEX_LEVERAGE_RATIO = 32; CALCINDEX_CONVERSION_RATIO = 33; CALCINDEX_BALANCE_POINT = 34; CALCINDEX_OPEN_INTEREST = 35; CALCINDEX_DELTA = 36; CALCINDEX_GAMMA = 37; CALCINDEX_THETA = 38; CALCINDEX_VEGA = 39; CALCINDEX_RHO = 40; } ``` ## Board - Security Board | Board | Description | | ---------------- | --------------------------------------------- | | USMain | US Main Board | | USPink | US Pink Board | | USDJI | Dow Jones Industrial Average | | USNSDQ | Nasdsaq Index | | USSector | US Industry Board | | USOption | US Option | | USOptionS | US Sepecial Option (market closed at 4:15 pm) | | HKEquity | Hong Kong Equity Securities | | HKPreIPO | HK PreIPO Security | | HKWarrant | HK Warrant | | HKHS | Hang Seng Index | | HKSector | HK Industry Board | | SHMainConnect | SH Main Board(Connect) | | SHMainNonConnect | SH Main Board(Non Connect) | | SHSTAR | SH Science and Technology Innovation Board | | CNIX | CN Index | | CNSector | CN Industry Board | | SZMainConnect | SZ Main Board(Connect) | | SZMainNonConnect | SZ Main Board(Non Connect) | | SZGEMConnect | SZ Gem Board(Connect) | | SZGEMNonConnect | SZ Gem Board(Non Connect) | | SGMain | SG Main Board | | STI | Singapore Straits Index | | SGSector | SG Industry Board | #### Warrants #### Screener This API is used to obtain the quotes of HK warrants, and supports sorting and filtering. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.warrant_list](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.warrant_list) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `23` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | filter_config | object | Yes | Filter conditions | | ∟ sort_by | int32 | Yes | Which data to sort by, for example: `0`, see the `OrderSequence` field of the response data for the sequence number. | | ∟ sort_order | int32 | Yes | Order, for example: `1`

**Optional value:**
`0` - Ascending
`1` - Descending | | ∟ sort_offset | int32 | Yes | The first data offset of paging, for example: `0` | | ∟ sort_count | int32 | Yes | Number of paginated pages per page, for example: `20`, no pagination when filling in `0` | | ∟ type | int32[] | No | Filter warrant type, for example: `[0,1]`

**Optional value:**
`0` - Call
`1` - Put
`2` - Bull
`3` - Bear
`4` - Inline | | ∟ issuer | int32[] | No | Filter issuer example: `[12,14]`, obtain [Issuer ID](./issuer) through API | | ∟ expiry_date | int32[] | No | Filter expiry date, example: `[1]`

**Optional value:**
`1` - Less than 3 months
`2` - 3 - 6 months
`3` - 6 - 12 months
`4` - greater than 12 months | | ∟ price_type | int32[] | No | Filter in/out of bounds, for example: `[2]`

**Optional value:**
`1` - In bounds
`2` - Out bounds | | ∟ status | int32[] | No | Filter status, for example: `[2]`

**Optional value:**
`2`- Suspend trading
`3` - Papare List
`4` - Normal | | language | int32 | Yes | Language, for example: `[1]`

**Optional value:**
`0` - zh-CN
`1` - en
`2` - zh-HK | ### Protobuf ```protobuf message WarrantFilterListRequest { string symbol = 1; FilterConfig filter_config = 2; int32 language = 3; } message FilterConfig { int32 sort_by = 1; int32 sort_order = 2; int32 sort_offset = 3; int32 sort_count = 4; repeated int32 type = 5; repeated int32 issuer = 6; repeated int32 expiry_date = 7; repeated int32 price_type = 8; repeated int32 status = 9; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, WarrantSortBy, SortOrderType, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, WarrantSortBy, SortOrderType, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, WarrantSortBy, SortOrderType } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.warrantList('700.HK', WarrantSortBy.LastDone, SortOrderType.Ascending) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { WarrantInfo[] resp = ctx.queryWarrantList(new QueryWarrantOptions("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)).get(); for (WarrantInfo w : resp) System.out.println(w); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::{QuoteContext, WarrantSortBy, SortOrderType}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.warrant_list("700.HK", WarrantSortBy::LastDone, SortOrderType::Ascending, None, None, None, None, None).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.warrant_list("700.HK", WarrantSortBy::Turnover, SortOrderType::Descending, {}, {}, {}, {}, {}, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "warrants: " << res->size() << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() list, err := qctx.WarrantList(context.Background(), "700.HK", quote.WarrantFilter{ SortBy: quote.WarrantVolume, SortOrder: quote.WarrantDesc, SortOffset: 0, SortCount: 10, }, quote.WarrantEN) if err != nil { log.Fatal(err) } fmt.Println("warrants:", len(list)) } ``` ## Response ### Response Properties | Name | Type | Description | OrderSequence | Support_Call/Put | Support_Bull/Bear | Support_Inline | | -------------------- | -------- | ---------------------------------------------------------------------------------------------------------- | ------------- | ---------------- | ----------------- | -------------- | | warrant_list | object[] | Filted warrant data list | | | | | | ∟ symbol | string | Security code | | true | true | true | | ∟ name | string | Security name | | true | true | true | | ∟ last_done | string | Latest price | 0 | true | true | true | | ∟ change_rate | string | Quote change rate | 1 | true | true | true | | ∟ change_val | string | Quote change | 2 | true | true | true | | ∟ volume | int64 | Volume | 3 | true | true | true | | ∟ turnover | string | Turnover | 4 | true | true | true | | ∟ expiry_date | string | Expiry date, in `YYMMDD` format | 5 | true | true | true | | ∟ strike_price | string | Strike price | 6 | true | true | false | | ∟ upper_strike_price | string | Upper bound price | 7 | false | false | true | | ∟ lower_strike_price | string | Lower bound price | 8 | false | false | true | | ∟ outstanding_qty | string | Outstanding quantity | 9 | true | true | true | | ∟ outstanding_ratio | string | Outstanding ratio | 10 | true | true | true | | ∟ premium | string | Premium | 11 | true | true | true | | ∟ itm_otm | string | In/out of the bound | 12 | true | true | false | | ∟ implied_volatility | string | Implied volatility | 13 | true | false | false | | ∟ delta | string | Greek value Delta | 14 | true | false | false | | ∟ call_price | string | Call price | 15 | false | true | false | | ∟ to_call_price | string | Price interval from the call price | 16 | false | true | false | | ∟ effective_leverage | string | Effective leverage | 17 | true | false | false | | ∟ leverage_ratio | string | Leverage ratio | 18 | true | true | true | | ∟ conversion_ratio | string | Conversion ratio | 19 | true | true | false | | ∟ balance_point | string | Breakeven point | 20 | true | true | false | | ∟ status | int32 | Status,

**Optional value:**
`2`- Suspend trading
`3` - Papare List
`4` - Normal | 21 | true | true | true | | total_count | int32 | Total number of eligible | | | | | ### Protobuf ```protobuf message WarrantFilterListResponse { repeated FilterWarrant warrant_list = 1; int32 total_count = 2; } message FilterWarrant { string symbol = 1; string name = 2; string last_done = 3; string change_rate = 4; string change_val = 5; int64 volume = 6; string turnover = 7; string expiry_date = 8; string strike_price = 9; string upper_strike_price = 10; string lower_strike_price = 11; string outstanding_qty = 12; string outstanding_ratio = 13; string premium = 14; string itm_otm = 15; string implied_volatility = 16; string delta = 17; string call_price = 18; string to_call_price = 19; string effective_leverage = 20; string leverage_ratio = 21; string conversion_ratio = 22; string balance_point = 23; int32 status = 24; } ``` ### Response JSON Example ```json { "warrant_list": [ { "symbol": "13157.HK", "name": "MBTENCT@EP2207A", "last_done": "2.26", "change_rate": "-0.0216450216450218", "change_val": "-0.050000000000000266", "turnover": "0", "expiry_date": "20220705", "strike_price": "442.233", "upper_strike_price": "0", "lower_strike_price": "0", "outstanding_qty": "5000", "outstanding_ratio": "0.0003", "premium": "0.016784269662921222", "itm_otm": "0.23524476916014864", "implied_volatility": "0.5275", "delta": "-0.8524", "call_price": "0", "effective_leverage": "-2.627683451852457", "leverage_ratio": "3.0826882353970637", "conversion_ratio": "48.544", "balance_point": "332.52356000000003", "status": 4 }, { "symbol": "13649.HK", "name": "MBTENCT@EP2205A", "last_done": "1.14", "change_rate": "0", "change_val": "0", "turnover": "0", "expiry_date": "20220518", "strike_price": "445.223", "upper_strike_price": "0", "lower_strike_price": "0", "outstanding_qty": "80000", "outstanding_ratio": "0.0004", "premium": "0.010810703725606", "itm_otm": "0.24038066317328624", "implied_volatility": "0.5997", "delta": "-0.7964", "call_price": "0", "effective_leverage": "-2.4335424241487873", "leverage_ratio": "3.055678583813144", "conversion_ratio": "97.087", "balance_point": "334.54382000000004", "status": 4 } ], "total_count": 1197 } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ---------------------------- | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Too many symbols in one page | Reduce the number of symbols in a page of request | #### Issuers This API is used to obtain the warrant issuer IDs data (which can be synchronized once a day). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.warrant_issuers](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.warrant_issuers) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `22` ::: ## Request ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.warrant_issuers() print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.warrant_issuers() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.warrantIssuers() for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { IssuerInfo[] resp = ctx.getWarrantIssuers().get(); for (IssuerInfo obj : resp) { System.out.println(obj); } } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.warrant_issuers().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.warrant_issuers([](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& i : *res) { std::cout << i.id << " " << i.name_cn << " " << i.name_en << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() issuers, err := qctx.WarrantIssuers(context.Background()) if err != nil { log.Fatal(err) } for _, i := range issuers { fmt.Println(i.Id, i.NameCn, i.NameEn) } } ``` ## Response ### Parameters | Name | Type | Description | | ----------- | -------- | ------------------- | | issuer_info | object[] | Issuer information | | ∟ id | int32 | Issuer ID | | ∟ name_cn | string | Issuer Name (zh-CN) | | ∟ name_en | string | Issuer Name (en) | | ∟ name_hk | string | Issuer Name (zh-HK) | ### Protobuf ```protobuf message IssuerInfoResponse { repeated IssuerInfo issuer_info = 1; } message IssuerInfo { int32 id = 1; string name_cn = 2; string name_en = 3; string name_hk = 4; } ``` ### Response JSON Example ```json { "issuer_info": [ { "id": 15, "name_cn": "瑞银", "name_en": "UB", "name_hk": "瑞銀" }, { "id": 14, "name_cn": "汇丰", "name_en": "HS", "name_hk": "滙豐" }, { "id": 12, "name_cn": "花旗", "name_en": "CT", "name_hk": "花旗" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | #### Quotes This API is used to obtain the real-time quotes of HK warrants, including the warrant-specific data. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.warrant_quote](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.warrant_quote) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `13` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[13447.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.warrant_quote(["21125.HK"]) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.warrant_quote(["21125.HK"]) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.warrantQuote(['21125.HK']) for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { WarrantQuote[] resp = ctx.getWarrantQuote(new String[] { "21125.HK" }).get(); for (WarrantQuote obj : resp) { System.out.println(obj); } } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.warrant_quote(["21125.HK"]).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); std::vector symbols = {"21926.HK"}; ctx.warrant_quote(symbols, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& q : *res) { std::cout << q.symbol << " " << (double)q.last_done << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() quotes, err := qctx.WarrantQuote(context.Background(), []string{"21926.HK"}) if err != nil { log.Fatal(err) } for _, q := range quotes { fmt.Println(q.Symbol, q.LastDone) } } ``` ## Response ### Response Properties | Name | Type | Description | | --------------------- | -------- | -------------------------------------------------------------------------------------------------------------- | | secu_quote | object[] | Warrants quote | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ prev_close | string | Yesterday's close | | ∟ open | string | Open | | ∟ high | string | High | | ∟ low | string | Low | | ∟ timestamp | int64 | Time of latest price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) | | ∟ warrant_extend | object | Warrant extend quote | | ∟∟ implied_volatility | string | Implied volatility | | ∟∟ expiry_date | string | Exprity date, in `YYMMDD` format | | ∟∟ last_trade_date | string | Last tradalbe date, in `YYMMDD` format | | ∟∟ outstanding_ratio | string | Outstanding ratio | | ∟∟ outstanding_qty | int64 | Outstanding quantity | | ∟∟ conversion_ratio | string | Conversion ratio | | ∟∟ category | string | Warrant type

**Optional value: **
`Call`
`Put`
`Bull`
`Bear`
`Inline` | | ∟∟ strike_price | string | Strike price | | ∟∟ upper_strike_price | string | Upper bound price | | ∟∟ lower_strike_price | string | Lower bound price | | ∟∟ call_price | string | Call price | | ∟∟ underlying_symbol | string | Underlying security symbol of the option | ### Protobuf ```protobuf message WarrantQuoteResponse { repeated WarrantQuote secu_quote = 2; } message WarrantQuote { string symbol = 1; string last_done = 2; string prev_close = 3; string open = 4; string high = 5; string low = 6; int64 timestamp = 7; int64 volume = 8; string turnover = 9; TradeStatus trade_status = 10; WarrantExtend warrant_extend = 11; } message WarrantExtend { string implied_volatility = 1; string expiry_date = 2; string last_trade_date = 3; string outstanding_ratio = 4; int64 outstanding_qty = 5; string conversion_ratio = 6; string category = 7; string strike_price = 8; string upper_strike_price = 9; string lower_strike_price = 10; string call_price = 11; string underlying_symbol = 12; } ``` ### Response JSON Example ```json { "secu_quote": [ { "symbol": "66642.HK", "last_done": "0.345", "prev_close": "0.365", "open": "0.345", "high": "0.345", "low": "0.345", "timestamp": 1651130421, "volume": 200000, "turnover": "69000.000", "warrant_extend": { "implied_volatility": "0.319", "expiry_date": "20220830", "last_trade_date": "20220829", "outstanding_ratio": "0.0001", "outstanding_qty": 20000, "conversion_ratio": "10000", "category": "Bear", "strike_price": "23200.000", "upper_strike_price": "0.000", "lower_strike_price": "0.000", "call_price": "23100.000", "underlying_symbol": "HSI.HK" } }, { "symbol": "14993.HK", "last_done": "0.073", "prev_close": "0.066", "open": "0.069", "high": "0.076", "low": "0.069", "timestamp": 1651130930, "volume": 320825000, "turnover": "23401125.000", "warrant_extend": { "implied_volatility": "0.404", "expiry_date": "20220927", "last_trade_date": "20220921", "outstanding_ratio": "0.0247", "outstanding_qty": 2465000, "conversion_ratio": "10", "category": "Call", "strike_price": "70.050", "upper_strike_price": "0.000", "lower_strike_price": "0.000", "call_price": "0.000", "underlying_symbol": "2318.HK" } } ] } ``` ## API Restrictions :::caution - The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP. ::: ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Subscribe #### Overview Streaming provides real-time market data via WebSocket subscriptions. Instead of polling, you subscribe to specific securities and data types, and the server pushes updates to your connection as they happen. ## How It Works 1. **Establish a connection** — Connect to the LongPort WebSocket endpoint using the SDK or the [binary protocol](../../socket/protocol/overview). 2. **Subscribe** — Call [Subscribe](./subscribe) with the securities and data types you want (quotes, depth, trades, brokers). 3. **Receive pushes** — The server sends real-time updates to your connection whenever there is a market change. 4. **Unsubscribe** — Call [Unsubscribe](./unsubscribe) to stop receiving updates for specific symbols or data types. ## Subscription Types | Type | Description | |------|-------------| | `Quote` | Real-time bid/ask and last-done price | | `Depth` | Level 2 order book | | `Brokers` | Broker queue data | | `Trade` | Real-time trade ticks | ## Pull vs. Subscribe Subscriptions push incremental updates in real time. For one-off or on-demand queries, use the pull APIs instead: | Data | Pull API | |------|----------| | Quotes | [Quotes](../stocks/quote) | | Depth | [Depth](../stocks/depth) | | Broker queue | [Broker Queue](../stocks/brokers) | | Trades | [Trades](../stocks/trade) | | Intraday | [Intraday](../stocks/intraday) | | Candlesticks | [Candlesticks](../stocks/candlestick) | ## Notes - Subscriptions are scoped to the current connection; they are cleared when the connection drops. - Use [Get Subscriptions](./subsciption) to inspect your active subscriptions at any time. - Quote permissions determine which data types are available. See [Quote Permission Levels](../overview#quote-permission-levels). #### Get Subscriptions This API is used to obtain the subscription information. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.subscriptions](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.subscriptions) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `5` ::: ## Request ### Protobuf ```protobuf message SubscriptionRequest { } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, SubType, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) resp = ctx.subscriptions() print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, SubType, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) resp = await ctx.subscriptions() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.subscriptions() console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { Subscription[] resp = ctx.getSubscriptions().get(); for (Subscription s : resp) System.out.println(s); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.subscriptions().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.subscriptions([](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& s : *res) std::cout << s.symbol << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() subs, err := qctx.Subscriptions(context.Background()) if err != nil { log.Fatal(err) } for symbol := range subs { fmt.Println(symbol) } } ``` ## Response ### Response Properties | Name | Type | Description | | ---------- | -------- | --------------------------------------------------------------------------------- | | sub_list | object[] | Subscribed data | | ∟ symbol | string | Security code | | ∟ sub_type | []int32 | Subscription type, see [SubType](../objects#subtype---quote-type-of-subscription) | ### Protobuf ```protobuf message SubscriptionResponse { repeated SubTypeList sub_list = 1; } message SubTypeList { string symbol = 1; repeated SubType sub_type = 2; } ``` ### Response JSON Example ```json { "sub_list": [ { "symbol": "700.HK", "sub_type": [1, 2, 3] }, { "symbol": "AAPL.US", "sub_type": [2] } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | #### Unsubscribe This API is used to unsubscribe quote. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.unsubscribe](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.unsubscribe) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `7` ::: ## Request ### Parameters | Name | Type | Required | Description | | --------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols that can be passed in each request is `500` | | sub_type | int32[] | Yes | Subscription type list, for example: `[1,2]`, see [SubType](../objects#subtype---quote-type-of-subscription) | | unsub_all | bool | Yes | Is unsubscribe all.
- When `symbol` is empty, unsubscribe all subscriptions
- When `symbol` is not empty, unsubscribe these all subscriptions of these symbols | ### Protobuf ```protobuf message UnsubscribeRequest { repeated string symbol = 1; repeated SubType sub_type = 2; bool unsub_all = 3; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, SubType, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) ctx.unsubscribe(["AAPL.US"], [SubType.Quote]) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, SubType, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) await ctx.unsubscribe(["AAPL.US"], [SubType.Quote]) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, SubType } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) await ctx.unsubscribe(['700.HK', 'AAPL.US'], [SubType.Quote]) console.log('unsubscribed') } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ctx.unsubscribe(new String[] { "700.HK", "AAPL.US" }, new SubType[] { SubType.Quote }).get(); System.out.println("unsubscribed"); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::SubFlags}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); ctx.unsubscribe(vec!["700.HK".to_string(), "AAPL.US".to_string()], SubFlags::quote()).await?; println!("unsubscribed"); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.unsubscribe(symbols, SubFlags::QUOTE(), [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "unsubscribed" << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() err = qctx.Unsubscribe(context.Background(), false, []string{"700.HK", "AAPL.US"}, []quote.SubType{quote.SubTypeQuote}) if err != nil { log.Fatal(err) } fmt.Println("unsubscribed") } ``` ## Response ### Protobuf ```protobuf message UnsubscribeResponse{ } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `sub_type` | #### Subscribe Quote This API is used to subscribe quote. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.subscriptions](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.subscriptions) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `6` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols that can be passed in each request is `500`
The maximum number of subscriptions per user is `500` | | sub_type | int32[] | Yes | Subscription type, for example: `[1,2]`, see [SubType](../objects#subtype---quote-type-of-subscription) | | is_first_push | bool | Yes | Whether to perform a data push immediately after subscribing. (trade not supported) | ### Protobuf ```protobuf message SubscribeRequest { repeated string symbol = 1; repeated SubType sub_type = 2; bool is_first_push = 3; } ``` ### Request Example ```python from time import sleep from longport.openapi import QuoteContext, Config, SubType, PushQuote, OAuthBuilder def on_quote(symbol: str, event: PushQuote): print(symbol, event) oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.set_on_quote(on_quote) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) sleep(30) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, SubType, PushQuote, OAuthBuilder async def main() -> None: async def on_quote(symbol: str, event: PushQuote) -> None: print(symbol, event) oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) ctx.set_on_quote(on_quote) await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) await asyncio.sleep(30) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, SubType } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) ctx.setOnQuote((event) => console.log(event)) await ctx.subscribe(['700.HK', 'AAPL.US'], [SubType.Quote], true) await new Promise((r) => setTimeout(r, 30000)) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ctx.setOnQuote(event -> System.out.println(event)); ctx.subscribe(new String[] { "700.HK", "AAPL.US" }, new SubType[] { SubType.Quote }, true).get(); Thread.sleep(30000); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::SubFlags}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); ctx.subscribe(vec!["700.HK".to_string(), "AAPL.US".to_string()], SubFlags::quote(), true).await?; tokio::time::sleep(std::time::Duration::from_secs(30)).await; Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.set_on_quote([](auto e) { std::cout << e->symbol << std::endl; }); ctx.subscribe(symbols, SubFlags::QUOTE(), true, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() qctx.OnQuote(func(e *quote.PushQuote) { fmt.Println(e.Symbol) }) err = qctx.Subscribe(context.Background(), []string{"700.HK", "AAPL.US"}, []quote.SubType{quote.SubTypeQuote}, true) if err != nil { log.Fatal(err) } // keep running to receive push select {} } ``` ## Response ### Response Properties Returns the securities and types of the successful subscription of this request. | Name | Type | Description | | ---------- | -------- | --------------------------------------------------------------------------------- | | sub_list | object[] | Subscription list | | ∟ symbol | string | Seurity code | | ∟ sub_type | int32[] | Subscription type, see [SubType](../objects#subtype---quote-type-of-subscription) | ### Protobuf ```protobuf message SubscriptionResponse { repeated SubTypeList sub_list = 1; } message SubTypeList { string symbol = 1; repeated SubType sub_type = 2; } ``` ### Response JSON Example ```json { "sub_list": [ { "symbol": "700.HK", "sub_type": [1, 2, 3] }, { "symbol": "AAPL.US", "sub_type": [2] } ] } ``` ## API Restrictions :::caution - HK BMP quote level does not support quote push. ::: ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301605 | Too many subscriptons | Unsubscribe some subscribed securities | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `sub_type` | #### Options #### Option Chain This API is used to obtain a list of option securities by the option chain expiry date. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_chain_info_by_date](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_chain_info_by_date) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `21` ::: ## Request ### Parameters | Name | Type | Required | Description | | ----------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | expiry_date | string | Yes | Option expiry date,in `YYMMDD` format, for example: `20220429`, obtained by [Option Expiry Date](./optionchain_date.md) API | ### Protobuf ```protobuf message OptionChainDateStrikeInfoRequest { string symbol = 1; string expiry_date = 2; } ``` ### Request Example ```python from datetime import date from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.option_chain_info_by_date("AAPL.US", date(2023, 1, 20)) print(resp) ``` ```python import asyncio from datetime import date from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.option_chain_info_by_date("AAPL.US", date(2023, 1, 20)) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, NaiveDate } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.optionChainInfoByDate('AAPL.US', new NaiveDate(2023, 1, 20)) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; import java.time.LocalDate; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { StrikePriceInfo[] resp = ctx.getOptionChainInfoByDate("AAPL.US", LocalDate.of(2023, 1, 20)).get(); for (StrikePriceInfo o : resp) System.out.println(o); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; use time::macros::date; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.option_chain_info_by_date("AAPL.US", date!(2023 - 01 - 20)).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.option_chain_info_by_date("AAPL.US", Date{2023, 1, 20}, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& o : *res) std::cout << o.price << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "time" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() expiry := time.Date(2023, 1, 20, 0, 0, 0, 0, time.UTC) list, err := qctx.OptionChainInfoByDate(context.Background(), "AAPL.US", &expiry) if err != nil { log.Fatal(err) } for _, o := range list { fmt.Println(o.Price) } } ``` ## Response ### Response Properties | Name | Type | Description | | ----------------- | -------- | ---------------------------- | | strike_price_info | object[] | Option security info | | ∟ price | string | Strike price | | ∟ call_symbol | string | Security code of call option | | ∟ put_symbol | string | Security code of put option | | ∟ standard | bool | Is standard | ### Protobuf ```protobuf message OptionChainDateStrikeInfoResponse { repeated StrikePriceInfo strike_price_info = 1; } message StrikePriceInfo { string price = 1; string call_symbol = 2; string put_symbol = 3; bool standard = 4; } ``` ### Response JSON Example ```json { "strike_price_info": [ { "price": "100", "call_symbol": "AAPL220429C100000.US", "put_symbol": "AAPL220429P100000.US", "standard": true }, { "price": "105", "call_symbol": "AAPL220429C105000.US", "put_symbol": "AAPL220429P105000.US", "standard": true }, { "price": "110", "call_symbol": "AAPL220429C110000.US", "put_symbol": "AAPL220429P110000.US", "standard": true }, { "price": "115", "call_symbol": "AAPL220429C115000.US", "put_symbol": "AAPL220429P115000.US", "standard": true } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`,`expiry_date` | #### Daily Volume Get historical daily call/put volume and open interest data for a US stock's options. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_volume_daily](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_volume_daily) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ------ | ------- | -------- | -------------------------------------------------- | | symbol | string | YES | US stock symbol, e.g. `AAPL.US`, `TSLA.US` | | count | integer | NO | Number of trading days to return (default: 20) | ## Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.option_volume_daily("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.option_volume_daily("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.optionVolumeDaily('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { var resp = ctx.getOptionVolumeDaily("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.option_volume_daily("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::quote; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); QuoteContext ctx = QuoteContext::create(config); ctx.option_volume_daily("AAPL.US", [](auto resp) { if (resp) std::cout << resp->size() << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() resp, err := qctx.OptionVolumeDaily(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "symbol": "AAPL.US", "list": [ { "date": "2026-05-07", "call_volume": 284512, "put_volume": 195830, "call_open_interest": 1824500, "put_open_interest": 1532100, "pc_vol": "0.6886", "pc_oi": "0.8398" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [option_volume_daily_rsp](#option_volume_daily_rsp) | | 400 | Bad request | None | ## Schemas ### option_volume_daily_rsp | Name | Type | Required | Description | | ------------------ | -------- | -------- | ---------------------------------------- | | symbol | string | true | Security symbol | | list | object[] | true | Daily volume records | | ∟ date | string | true | Date in `YYYY-MM-DD` format | | ∟ call_volume | int64 | true | Call volume on that day | | ∟ put_volume | int64 | true | Put volume on that day | | ∟ call_open_interest | int64 | true | Call open interest | | ∟ put_open_interest | int64 | true | Put open interest | | ∟ pc_vol | string | true | Put/call volume ratio | | ∟ pc_oi | string | true | Put/call open interest ratio | #### Option Quotes This API is used to obtain the real-time quotes of US stock options, including the option-specific data. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_quote](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_quote) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `12` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | symbol | string[] | Yes | Security code list. obtain the symbol of the options through the [optionchain](./optionchain-date-strike.md) API, for example: `[BABA230120C160000.US]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.option_quote(["AAPL230317P160000.US"]) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.option_quote(["AAPL230317P160000.US"]) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.optionQuote(['AAPL230317P160000.US']) for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { OptionQuote[] resp = ctx.getOptionQuote(new String[] { "AAPL230317P160000.US" }).get(); for (OptionQuote obj : resp) { System.out.println(obj); } } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.option_quote(["AAPL230317P160000.US"]).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); std::vector symbols = {"AAPL230317C160000.US"}; ctx.option_quote(symbols, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& q : *res) { std::cout << q.symbol << " " << (double)q.last_done << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() quotes, err := qctx.OptionQuote(context.Background(), []string{"AAPL230317C160000.US"}) if err != nil { log.Fatal(err) } for _, q := range quotes { fmt.Println(q.Symbol, q.LastDone) } } ``` ## Response ### Response Properties | Name | Type | Description | | ------------------------ | -------- | ------------------------------------------------------------------------------------ | | secu_quote | object[] | Options quote | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ prev_close | string | Yesterday's close | | ∟ open | string | Open | | ∟ high | string | High | | ∟ low | string | Low | | ∟ timestamp | int64 | Time of latest price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) | | ∟ option_extend | object | Option extend quote | | ∟∟ implied_volatility | string | Implied volatility | | ∟∟ open_interest | int64 | Number of open positions | | ∟∟ expiry_date | string | Exprity date, in `YYMMDD` format | | ∟∟ strike_price | string | Strike price | | ∟∟ contract_multiplier | string | Contract multiplier | | ∟∟ contract_type | string | Option type

**Optional value:**
`A` - American
`U` - Europe | | ∟∟ contract_size | string | Contract size | | ∟∟ direction | string | Direction

**Optional value:**
`P` - put
`C` - call | | ∟∟ historical_volatility | string | Underlying security historical volatility of the optionn | | ∟∟ underlying_symbol | string | Underlying security symbol of the option | ### Protobuf ```protobuf message OptionQuoteResponse { repeated OptionQuote secu_quote = 1; } message OptionQuote { string symbol = 1; string last_done = 2; string prev_close = 3; string open = 4; string high = 5; string low = 6; int64 timestamp = 7; int64 volume = 8; string turnover = 9; TradeStatus trade_status = 10; OptionExtend option_extend = 11; } message OptionExtend { string implied_volatility = 1; int64 open_interest = 2; string expiry_date = 3; string strike_price = 4; string contract_multiplier = 5; string contract_type = 6; string contract_size = 7; string direction = 8; string historical_volatility = 9; string underlying_symbol = 10; } ``` ### Response JSON Example ```json { "secu_quote": [ { "symbol": "AAPL220429P162500.US", "last_done": "7.78", "prev_close": "4.13", "open": "4.43", "high": "7.80", "low": "4.43", "timestamp": 1651003200, "volume": 3082, "turnover": "1813434.00", "option_extend": { "implied_volatility": "0.592", "open_interest": 11463, "expiry_date": "20220429", "strike_price": "162.50", "contract_multiplier": "100", "contract_type": "A", "contract_size": "100", "direction": "P", "historical_volatility": "0.2750", "underlying_symbol": "AAPL.US" } }, { "symbol": "AAPL220429C150000.US", "last_done": "9.25", "prev_close": "13.87", "open": "13.80", "high": "13.80", "low": "9.15", "timestamp": 1651003200, "volume": 413, "turnover": "436835.00", "option_extend": { "implied_volatility": "0.702", "open_interest": 800, "expiry_date": "20220429", "strike_price": "150.00", "contract_multiplier": "100", "contract_type": "A", "contract_size": "100", "direction": "C", "historical_volatility": "0.2750", "underlying_symbol": "AAPL.US" } } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Volume Get real-time call/put volume snapshot for today, including total volume, open interest, and put/call ratios. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_volume](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_volume) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ------ | ------ | -------- | ---------------------------------------------- | | symbol | string | YES | US stock symbol, e.g. `AAPL.US`, `TSLA.US` | ## Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.option_volume("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.option_volume("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.optionVolume('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { var resp = ctx.getOptionVolume("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.option_volume("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::quote; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); QuoteContext ctx = QuoteContext::create(config); ctx.option_volume("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() resp, err := qctx.OptionVolume(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "symbol": "AAPL.US", "call_volume": 284512, "put_volume": 195830, "call_open_interest": 1824500, "put_open_interest": 1532100, "pc_vol": "0.6886", "pc_oi": "0.8398" } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [option_volume_rsp](#option_volume_rsp) | | 400 | Bad request | None | ## Schemas ### option_volume_rsp | Name | Type | Required | Description | | ------------------ | ------ | -------- | ---------------------------------------- | | symbol | string | true | Security symbol | | call_volume | int64 | true | Total call volume for today | | put_volume | int64 | true | Total put volume for today | | call_open_interest | int64 | true | Total call open interest | | put_open_interest | int64 | true | Total put open interest | | pc_vol | string | true | Put/call volume ratio | | pc_oi | string | true | Put/call open interest ratio | #### Expiry Dates This API is used to obtain the the list of expiration dates of option chain ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_chain_expiry_date_list](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_chain_expiry_date_list) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `20` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.option_chain_expiry_date_list("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.option_chain_expiry_date_list("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.optionChainExpiryDateList('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { LocalDate[] resp = ctx.getOptionChainExpiryDateList("AAPL.US").get(); for (LocalDate d : resp) System.out.println(d); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.option_chain_expiry_date_list("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.option_chain_expiry_date_list("AAPL.US", [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& d : *res) std::cout << d.year << "-" << (int)d.month << "-" << (int)d.day << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() dates, err := qctx.OptionChainExpiryDateList(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } for _, d := range dates { fmt.Println(d.Format("2006-01-02")) } } ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | -------------------------------------------------- | | expiry_date | string[] | option chain expiry dates list,in `YYMMDD` format | ### Protobuf ```protobuf message OptionChainDateListResponse { repeated string expiry_date = 1; } ``` ### Response JSON Example ```json { "expiry_date": [ "20220422", "20220429", "20220506", "20220513", "20220520", "20220527", "20220603", "20220617", "20220715", "20220819", "20220916", "20221021", "20221118", "20230120", "20230317", "20230616", "20230915", "20240119", "20240621" ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | #### Analytics #### Capital Distribution This API is used to obtain the daily capital distribution of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.capital_distribution](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.capital_distribution) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command):`25` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | --------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.capital_distribution("700.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.capital_distribution("700.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.capitalDistribution('700.HK') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { CapitalDistributionResponse resp = ctx.getCapitalDistribution("700.HK").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.capital_distribution("700.HK").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.capital_distribution("700.HK", [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "capital_distribution: " << res->symbol << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() dist, err := qctx.CapitalDistribution(context.Background(), "700.HK") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", dist) } ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | -------------------- | | symbol | string | Security code | | timestamp | int64 | Data update time | | capital_in | object[] | Inflow capital data | | ∟ large | string | large order | | ∟ medium | string | medium order | | ∟ small | string | small order | | capital_out | object[] | Outflow capital data | | ∟ large | string | large order | | ∟ medium | string | medium order | | ∟ small | string | small order | ### Protobuf ```protobuf message CapitalDistributionResponse { message CapitalDistribution { string large = 1; string medium = 2; string small = 3; } string symbol = 1; int64 timestamp = 2; CapitalDistribution capital_in = 3; CapitalDistribution capital_out = 4; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "timestamp": "1655107800", "capital_in": { "large": "935389700.000", "medium": "2056032380.000", "small": "828715920.000" }, "capital_out": { "large": "1175331560.000", "medium": "2271829740.000", "small": "751648940.000" } } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Capital Flow This API is used to obtain the daily capital flow intraday of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.capital_flow](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.capital_flow) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command):`24` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | --------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` | ### Protobuf ```protobuf message CapitalFlowIntradayRequest { string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.capital_flow("700.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.capital_flow("700.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.capitalFlow('700.HK') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { CapitalFlowLine[] resp = ctx.getCapitalFlow("700.HK").get(); for (CapitalFlowLine line : resp) System.out.println(line); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.capital_flow("700.HK").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.capital_flow("700.HK", [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "capital_flow lines: " << res->size() << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() lines, err := qctx.CapitalFlow(context.Background(), "700.HK") if err != nil { log.Fatal(err) } fmt.Println("capital_flow lines:", len(lines)) } ``` ## Response ### Response Properties | Name | Type | Description | | ------------------ | -------- | ------------------------------ | | symbol | string | Security code | | capital_flow_lines | object[] | Capital flow data | | ∟ inflow | string | Inflow capital data | | ∟ timestamp | int64 | Start time stamp of the minute | ### Protobuf ```protobuf message CapitalFlowIntradayResponse { message CapitalFlowLine { string inflow = 1; int64 timestamp = 2; } string symbol = 1; repeated CapitalFlowLine capital_flow_lines = 2; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "capital_flow_lines": [ { "inflow": "-310255860.000", "timestamp": "1655106960" }, { "inflow": "-314011220.000", "timestamp": "1655107020" }, { "inflow": "-314011220.000", "timestamp": "1655107080" }, { "inflow": "-314011220.000", "timestamp": "1655107140" }, { "inflow": "-314011220.000", "timestamp": "1655107200" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Calc Index This API is used to obtain the calculate indexes of securities. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.calc_indexes](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.calc_indexes) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | | Java | [quote.getQuoteContext](https://longportapp.github.io/openapi/java/com/longport//quote.html#CalcIndex) | :::info [Business Command](../../socket/biz_command):`26` ::: ## Request ### Parameters | Name | Type | Required | Description | | ---------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbols | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | | calc_index | init32[] | Yes | Calc indexes, for example: `[1,2,3]`, see [CalcIndex](../objects#calcindex---calculate-index) | ### Protobuf ```protobuf message SecurityCalcQuoteRequest { repeated string symbols = 1; repeated CalcIndex calc_index = 2; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, CalcIndex, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.calc_indexes(["700.HK", "AAPL.US"], [CalcIndex.LastDone, CalcIndex.ChangeRate]) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, CalcIndex, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.calc_indexes(["700.HK", "AAPL.US"], [CalcIndex.LastDone, CalcIndex.ChangeRate]) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, CalcIndex } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.calcIndexes(['700.HK', 'AAPL.US'], [CalcIndex.LastDone, CalcIndex.ChangeRate]) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { SecurityCalcIndex[] resp = ctx.getCalcIndexes( new String[] { "700.HK", "AAPL.US" }, new CalcIndex[] { CalcIndex.LastDone, CalcIndex.ChangeRate } ).get(); for (SecurityCalcIndex o : resp) System.out.println(o); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::CalcIndex}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.calc_indexes( vec!["700.HK".to_string(), "AAPL.US".to_string()], vec![CalcIndex::LastDone, CalcIndex::ChangeRate], ).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.calc_indexes(symbols, indexes, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& o : *res) std::cout << o.symbol << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() indexes, err := qctx.CalcIndex(context.Background(), []string{"700.HK", "AAPL.US"}, []quote.CalcIndex{quote.CalcIndexLastDone, quote.CalcIndexChangeRate}) if err != nil { log.Fatal(err) } for _, o := range indexes { fmt.Println(o.Symbol) } } ``` ## Response ### Response Properties | Name | Type | Description | | -------------------------- | -------- | ----------------------------------------------------------------------------------------- | | security_calc_index | object[] | Security Index Data | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ change_val | string | Change value | | ∟ change_rate | string | Change ratio (This field is a ratio field, not include symbol `%`) | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ ytd_change_rate | string | Year-to-date change ratio (This field is a ratio field, not include symbol `%`) | | ∟ turnover_rate | string | Turnover rate (This field is a ratio field, not include symbol `%`) | | ∟ total_market_value | string | Total market value | | ∟ capital_flow | string | Capital flow | | ∟ amplitude | string | Amplitude (This field is a ratio field, not include symbol `%`) | | ∟ volume_ratio | string | Volume ratio | | ∟ pe_ttm_ratio | string | PE (TTM) | | ∟ pb_ratio | string | PB | | ∟ dividend_ratio_ttm | string | Dividend ratio (TTM) | | ∟ five_day_change_rate | string | Five days change ratio (This field is a ratio field, not include symbol `%`) | | ∟ ten_day_change_rate | string | Ten days change ratio (This field is a ratio field, not include symbol `%`) | | ∟ half_year_change_rate | string | Half year change ratio (This field is a ratio field, not include symbol `%`) | | ∟ five_minutes_change_rate | string | Five minutes change ratio (This field is a ratio field, not include symbol `%`) | | ∟ expiry_date | string | Expirt date | | ∟ strike_price | string | Strike price | | ∟ upper_strike_price | string | Upper bound price | | ∟ lower_strike_price | string | Lower bound price | | ∟ outstanding_qty | int64 | Outstanding quantity | | ∟ outstanding_ratio | string | Outstanding ratio (This field is a ratio field, not include symbol `%`) | | ∟ premium | string | Premium (This field is a ratio field, not include symbol `%`) | | ∟ itm_otm | string | In/out of the bound (This field is a ratio field, not include symbol `%`) | | ∟ implied_volatility | string | Implied volatility (This field is a ratio field, not include symbol `%`) | | ∟ warrant_delta | string | Warrant delta | | ∟ call_price | string | Call price | | ∟ to_call_price | string | Price interval from the call price (This field is a ratio field, not include symbol `%`) | | ∟ effective_leverage | string | Effective leverage | | ∟ leverage_ratio | string | Leverage ratio | | ∟ conversion_ratio | string | Conversion ratio | | ∟ balance_point | string | Breakeven point | | ∟ open_interest | int64 | Open interest | | ∟ delta | string | Delta | | ∟ gamma | string | Gamma | | ∟ theta | string | Theta. Raw value needs to be divided by 100 to get the standard per-share per-day value | | ∟ vega | string | Vega. Raw value needs to be divided by 100 to get the standard per-share per-1%-IV value | | ∟ rho | string | Rho. Raw value needs to be divided by 100 to get the standard per-share per-1%-rate value | ### Protobuf ```protobuf message SecurityCalcIndex { string symbol = 1; string last_done = 2; string change_val = 3; string change_rate = 4; int64 volume = 5; string turnover = 6; string ytd_change_rate = 7; string turnover_rate = 8; string total_market_value = 9; string capital_flow = 10; string amplitude = 11; string volume_ratio = 12; string pe_ttm_ratio = 13; string pb_ratio = 14; string dividend_ratio_ttm = 15; string five_day_change_rate = 16; string ten_day_change_rate = 17; string half_year_change_rate = 18; string five_minutes_change_rate = 19; string expiry_date = 20; string strike_price = 21; string upper_strike_price = 22; string lower_strike_price = 23; int64 outstanding_qty = 24; string outstanding_ratio = 25; string premium = 26; string itm_otm = 27; string implied_volatility = 28; string warrant_delta = 29; string call_price = 30; string to_call_price = 31; string effective_leverage = 32; string leverage_ratio = 33; string conversion_ratio = 34; string balance_point = 35; int64 open_interest = 36; string delta = 37; string gamma = 38; string theta = 39; string vega = 40; string rho = 41; } message SecurityCalcQuoteResponse { repeated SecurityCalcIndex security_calc_index = 1; } ``` ### Response JSON Example ```json { "securityCalcIndex": [ { "symbol": "AAPL.US", "lastDone": "131.880", "changeVal": "-5.2500", "changeRate": "-3.83", "volume": "122207099", "turnover": "16269088361.000", "ytdChangeRate": "-25.63", "turnoverRate": "0.76", "totalMarketValue": "2134501670280.00", "capitalFlow": "14664053535.556", "amplitude": "2.74", "volumeRatio": "3.22", "peTtmRatio": "21.26", "pbRatio": "31.71", "dividendRatioTtm": "0.64", "fiveDayChangeRate": "-9.76", "tenDayChangeRate": "-11.87", "halfYearChangeRate": "-7.01", "fiveMinutesChangeRate": "0.00" }, { "symbol": "69672.HK", "lastDone": "0.010", "changeRate": "0.00", "expiryDate": "20221024", "strikePrice": "379.880", "outstandingQty": "6090000", "outstandingRatio": "7.61", "premium": "0.67", "itmOtm": "0.65", "callPrice": "375.880", "toCallPrice": "-100.00", "leverageRatio": "75.48", "balancePoint": "374.880" }, { "symbol": "AAPL220617C137000.US", "lastDone": "1.17", "changeVal": "-2.04", "changeRate": "-63.55", "volume": "23499", "turnover": "3903660.00", "expiryDate": "20220617", "strikePrice": "137.00", "premium": "11709.40", "impliedVolatility": "43.54", "openInterest": "5210", "delta": "0.263", "gamma": "0.043", "theta": "-1.266", "vega": "5.660", "rho": "0.580" }, { "symbol": "HSI.HK", "lastDone": "21119.650", "changeVal": "52.070", "changeRate": "0.25", "volume": "96449546281", "turnover": "96449546281.000", "ytdChangeRate": "-9.74", "amplitude": "1.86", "volumeRatio": "0.59", "fiveDayChangeRate": "-1.91", "tenDayChangeRate": "-0.02", "halfYearChangeRate": "-11.83", "fiveMinutesChangeRate": "0.00" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Push #### Depth Real-time depth data push of the subscribed security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.set_on_depth](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.set_on_depth) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | | Java | [quote.getQuoteContext](https://longportapp.github.io/openapi/java/com/longport//quote.html#OnDepth) | :::info [Business Command](../../socket/protocol/push): `102` ::: ## Data Format ### Properties | Name | Type | Description | |-------------|----------|---------------------------------------| | symbol | string | Security code, for example: `AAPL.US` | | sequence | int64 | Sequence number | | ask | object[] | Ask depth | | ∟ position | int32 | Position | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ order_num | int64 | Number of orders | | bid | object[] | Bid depth | | ∟ position | int32 | Position | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ order_num | int64 | Number of orders | ### Protobuf ```protobuf message PushDepth { string symbol = 1; int64 sequence = 2; repeated Depth ask = 3; repeated Depth bid = 4; } message Depth { int32 position = 1; string price = 2; int64 volume = 3; int64 order_num = 4; } ``` ### Example ```python from time import sleep from longport.openapi import QuoteContext, Config, SubType, PushDepth, OAuthBuilder def on_depth(symbol: str, event: PushDepth): print(symbol, event) oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.set_on_depth(on_depth) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Depth]) sleep(30) ``` ### JSON Example ```json { "symbol": "700.HK", "sequence": 160808750000000, "ask": [ { "position": 1, "price": "335.000", "volume": 500, "order_num": 1 }, { "position": 2, "price": "335.200", "volume": 400, "order_num": 1 }, { "position": 3, "price": "335.400", "volume": 500, "order_num": 2 }, { "position": 4, "price": "335.600", "volume": 1200, "order_num": 3 }, { "position": 5, "price": "335.800", "volume": 14000, "order_num": 8 } ], "bid": [ { "position": 1, "price": "334.800", "volume": 69400, "order_num": 13 }, { "position": 2, "price": "334.600", "volume": 266600, "order_num": 27 }, { "position": 3, "price": "334.400", "volume": 61300, "order_num": 29 }, { "position": 4, "price": "334.200", "volume": 125900, "order_num": 31 }, { "position": 5, "price": "334.000", "volume": 194600, "order_num": 94 } ] } ``` #### Trades Real-time trades data push of the subscribed security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.set_on_trades](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.set_on_trades) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | | Java | [quote.getQuoteContext](https://longportapp.github.io/openapi/java/com/longport//quote.html#OnTrade) | :::info [Business Command](../../socket/protocol/push): `104` ::: ## Data Format ### Properties | Name | Type | Description | |-----------------|----------|--------------------------------------------------------------------------------------------------| | symbol | string | Security code, for example: `AAPL.US` | | sequence | int64 | Sequence number | | trades | object[] | Trades data | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ timestamp | int64 | Time of trading | | ∟ trade_type | string | [Trade type](#trade-type) | | ∟ direction | int32 | Trade direction

**Optional value:**
`0` - neutral
`1` - down
`2` - up | | ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | #### Trade Type HK - `*` - Overseas trade - `D` - Odd-lot trade - `M` - Non-direct off-exchange trade - `P` - Late trade (Off-exchange previous day) - `U` - Auction trade - `X` - Direct off-exchange trade - `Y` - Automatch internalized - ` ` - Automatch normal US - ` ` - Regular sale - `A` - Acquisition - `B` - Bunched trade - `D` - Distribution - `F` - Intermarket sweep - `G` - Bunched sold trades - `H` - Price variation trade - `I` - Odd lot trade - `K` - Rule 155 trde(NYSE MKT) - `M` - Market center close price - `P` - Prior reference price - `Q` - Market center open price - `S` - Split trade - `V` - Contingent trade - `W` - Average price trade - `X` - Cross trade - `1` - Stopped stock(Regular trade) ### Protobuf ```protobuf message PushTrade { string symbol = 1; int64 sequence = 2; repeated Trade trade = 3; } message Trade { string price = 1; int64 volume = 2; int64 timestamp = 3; string trade_type = 4; int32 direction = 5; TradeSession trade_session = 6; } ``` ### Example ```python from time import sleep from longport.openapi import QuoteContext, Config, SubType, PushTrades, OAuthBuilder def on_trades(symbol: str, event: PushTrades): print(symbol, event) oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.set_on_trades(on_trades) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Trade]) sleep(30) ``` ### JSON Example ```json { "symbol": "700.HK", "sequence": 160808750000000, "trades": [ { "price": "158.760", "volume": 1, "timestamp": 1651103979, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.745", "volume": 1, "timestamp": 1651103985, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.800", "volume": 1, "timestamp": 1651103995, "trade_type": "I", "direction": 0, "trade_session": 2 } ] } ``` #### Quote Real-time quote push of the subscribed security. In the pushed data structure, only the fields that have changed will be filled with data. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.set_on_quote](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.set_on_quote) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | | Java | [quote.getQuoteContext](https://longportapp.github.io/openapi/java/com/longport//quote.html#OnQuote) | :::info [Business Command](../../socket/protocol/push): `101` ::: ## Data Format ### Properties | Name | Type | Description | | ---------------- | ------ | --------------------------------------------------------------------------------------------------------------- | | symbol | string | Security code, for example: `AAPL.US` | | sequence | int64 | Sequence number | | last_done | string | Latest price | | open | string | Open | | high | string | High | | low | string | Low | | timestamp | int64 | Time of latest price | | volume | int64 | Volume | | turnover | string | Turnover | | trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) | | trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | | current_volume | int32 | Increase volume between pushes | | current_turnover | string | Increase turnover between pushes | | tag | int32 | Price tag

**Optional value:**
`0` - Real-time quote
`1` - Revised data after market close | ### Protobuf ```protobuf message PushQuote { string symbol = 1; int64 sequence = 2; string last_done = 3; string open = 4; string high = 5; string low = 6; int64 timestamp = 7; int64 volume = 8; string turnover = 9; TradeStatus trade_status = 10; TradeSession trade_session = 11; } ``` ### Example ```python from time import sleep from longport.openapi import QuoteContext, Config, SubType, PushQuote, OAuthBuilder def on_quote(symbol: str, event: PushQuote): print(symbol, event) oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.set_on_quote(on_quote) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote], is_first_push=True) sleep(30) ``` ### JSON Example ```json { "symbol": "AAPL.US", "sequence": 160808750000000, "last_done": "156.570", "open": "155.910", "high": "159.790", "low": "155.380", "timestamp": 1651089600, "volume": 88063191, "turnover": "13865092584.000", "trade_status": 0, "trade_session": 0, "current_volume": 111234, "current_turnover": "23234343454.000", "tag": 0 } ``` #### Brokers Real-time brokers data push of the subscribed security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.set_on_brokers](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.set_on_brokers) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | | Java | [quote.getQuoteContext](https://longportapp.github.io/openapi/java/com/longport//quote.html#OnBrokers) | :::info [Business Command](../../socket/protocol/push): `103` ::: ## Data Format ### Properties | Name | Type | Description | |--------------|----------|---------------------------------------| | symbol | string | Security code, for example: `AAPL.US` | | sequence | int64 | Sequence number | | ask_brokers | object[] | Ask brokers | | ∟ position | int32 | Position | | ∟ broker_ids | int32[] | [Broker ID](../pull/broker-ids) | | bid_brokers | object[] | Bid brokers | | ∟ position | int32 | Position | | ∟ broker_ids | int32[] | [Broker ID](../pull/broker-ids) | ### Protobuf ```protobuf message PushBrokers { string symbol = 1; int64 sequence = 2; repeated Brokers ask_brokers = 3; repeated Brokers bid_brokers = 4; } message Brokers { int32 position = 1; repeated int32 broker_ids = 2; } ``` ### Example ```python from time import sleep from longport.openapi import QuoteContext, Config, SubType, PushBrokers, OAuthBuilder def on_brokers(symbol: str, event: PushBrokers): print(symbol, event) oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.set_on_brokers(on_brokers) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Brokers]) sleep(30) ``` ### JSON Example ```json { "symbol": "700.HK", "sequence": 160808750000000, "ask_brokers": [ { "position": 1, "broker_ids": [7358, 9057, 9028, 7364] }, { "position": 2, "broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997] } ], "bid_brokers": [ { "position": 1, "broker_ids": [6996, 5465, 8026, 8304, 4978] }, { "position": 2, "broker_ids": [7358, 9057, 9028, 7364] } ] } ``` #### Security #### Overnight Eligible Securities Get the list of US stocks eligible for overnight trading. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.security_list](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.security_list) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ### Request
HTTP MethodGET
HTTP URL/v1/quote/get_security_list
#### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | -------- | ------ | -------- | ------------------------------------------- | | market | string | YES | Market, currently only supports US | | category | string | YES | Market subcategory, only supports Overnight | #### Request Example ```python from longport.openapi import QuoteContext, Config, Market, SecurityListCategory, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.security_list(Market.US, SecurityListCategory.Overnight) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, Market, SecurityListCategory, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.security_list(Market.US, SecurityListCategory.Overnight) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, SecurityListCategory } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.securityList(SecurityListCategory.Overnight) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { Security[] resp = ctx.getSecurityList(SecurityListCategory.Overnight).get(); for (Security s : resp) System.out.println(s); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::SecurityListCategory}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.security_list(SecurityListCategory::Overnight).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.security_list(SecurityListCategory::Overnight, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "securities: " << res->size() << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() list, err := qctx.SecurityList(context.Background(), quote.MarketUS, quote.Overnight) if err != nil { log.Fatal(err) } fmt.Println("securities:", len(list)) } ``` ### Response #### Response Headers - Content-Type: application/json #### Response Example ```json { "code": 0, "data": { "list": [ { "symbol": "BAC.US", "name_cn": "美国银行", "name_hk": "美國銀行", "name_en": "Bank of America" }, { "symbol": "RDDT.US", "name_cn": "REDDIT INC", "name_hk": "REDDIT INC", "name_en": "REDDIT INC" }, { "symbol": "GOOGL.US", "name_cn": "谷歌-A", "name_hk": "谷歌-A", "name_en": "Alphabet" } ] } } ``` #### Response Status | Status | Description | Schema | | ------ | ----------------- | ------------------------------------------- | | 200 | Successful return | [security_response](#get_security_list_rsp) | | 400 | Parameter error | None | ## Schemas ### security_response | Name | Type | Required | Description | | --------- | -------- | -------- | ------------------------ | | list | object[] | false | List | | ∟ symbol | integer | true | Security code | | ∟ name_cn | string | true | Chinese name | | ∟ name_hk | string | true | Traditional Chinese name | | ∟ name_en | string | true | English name | ## Error Code | Business Error Code | Description | Troubleshooting Suggestion | | ------------------- | --------------------- | ----------------------------------------- | | 310010 | Invalid request | Check the request parameters | | 310011 | Internal server error | Please retry or contact technical support | #### Stocks #### Broker Queue This API is used to obtain the real-time broker queue data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.brokers](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.brokers) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `15` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | --------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.brokers("700.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.brokers("700.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.brokers('700.HK') console.log(resp.toString()) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { SecurityBrokers resp = ctx.getBrokers("700.HK").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.brokers("700.HK").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.brokers("700.HK", [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "brokers: " << res->symbol << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() brokers, err := qctx.Brokers(context.Background(), "700.HK") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", brokers) } ``` ## Response ### Response Properties | Name | Type | Description | | ------------ | -------- | ------------------------------------------------------------------ | | symbol | string | Security code | | ask_brokers | object[] | Ask brokers | | ∟ position | int32 | Position | | ∟ broker_ids | int32[] | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API | | bid_brokers | object[] | Bid brokers | | ∟ position | int32 | Postition | | ∟ broker_ids | int32[] | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API | ### Protobuf ```protobuf message SecurityBrokersResponse { string symbol = 1; repeated Brokers ask_brokers = 2; repeated Brokers bid_brokers = 3; } message Brokers { int32 position = 1; repeated int32 broker_ids = 2; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "ask_brokers": [ { "position": 1, "broker_ids": [7358, 9057, 9028, 7364] }, { "position": 2, "broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997] } ], "bid_brokers": [ { "position": 1, "broker_ids": [6996, 5465, 8026, 8304, 4978] }, { "position": 2 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Depth This API is used to obtain the depth data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.depth](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.depth) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `14` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.depth("700.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.depth("700.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.depth('700.HK') console.log(resp.toString()) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { SecurityDepth resp = ctx.getDepth("700.HK").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.depth("700.HK").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.depth("700.HK", [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "depth: " << res->symbol << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() depth, err := qctx.Depth(context.Background(), "700.HK") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", depth) } ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | ---------------- | | symbol | string | Security code | | ask | object[] | Ask depth | | ∟ position | int32 | Position | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ order_num | int64 | Number of orders | | bid | object[] | Bid depth | | ∟ position | int32 | Position | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ order_num | int64 | Number of orders | ### Protobuf ```protobuf message SecurityDepthResponse { string symbol = 1; repeated Depth ask = 2; repeated Depth bid = 3; } message Depth { int32 position = 1; string price = 2; int64 volume = 3; int64 order_num = 4; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "ask": [ { "position": 1, "price": "335.000", "volume": 500, "order_num": 1 }, { "position": 2, "price": "335.200", "volume": 400, "order_num": 1 }, { "position": 3, "price": "335.400", "volume": 500, "order_num": 2 }, { "position": 4, "price": "335.600", "volume": 1200, "order_num": 3 }, { "position": 5, "price": "335.800", "volume": 14000, "order_num": 8 } ], "bid": [ { "position": 1, "price": "334.800", "volume": 69400, "order_num": 13 }, { "position": 2, "price": "334.600", "volume": 266600, "order_num": 27 }, { "position": 3, "price": "334.400", "volume": 61300, "order_num": 29 }, { "position": 4, "price": "334.200", "volume": 125900, "order_num": 31 }, { "position": 5, "price": "334.000", "volume": 194600, "order_num": 94 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Trades This API is used to obtain the trades data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.trades](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.trades) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `17` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | count | int32 | Yes | Count of trades

**Check rules:**
The maximum number of trades in each request is `1000` | ### Protobuf ```protobuf message SecurityTradeRequest { string symbol = 1; int32 count = 2; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.trades("700.HK", 10) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.trades("700.HK", 10) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.trades('700.HK', 10) for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { Trade[] resp = ctx.getTrades("700.HK", 10).get(); for (Trade obj : resp) { System.out.println(obj); } } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.trades("700.HK", 10).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.trades("700.HK", 10, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& t : *res) { std::cout << t.price << " " << t.quantity << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() trades, err := qctx.Trades(context.Background(), "700.HK", 10) if err != nil { log.Fatal(err) } for _, t := range trades { fmt.Println(t.Price, t.Volume) } } ``` ## Response ### Response Properties | Name | Type | Description | | --------------- | -------- | ------------------------------------------------------------------------------------------------ | | symbol | string | Security code | | trades | object[] | Trades data | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ timestamp | int64 | Time of trading | | ∟ trade_type | string | [Trade type](#trade-type) | | ∟ direction | int32 | Trade direction

**Optional value:**
`0` - neutral
`1` - down
`2` - up | | ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | #### Trade Type HK - `*` - Overseas trade - `D` - Odd-lot trade - `M` - Non-direct off-exchange trade - `P` - Late trade (Off-exchange previous day) - `U` - Auction trade - `X` - Direct off-exchange trade - `Y` - Automatch internalized - ` ` - Automatch normal US - ` ` - Regular sale - `A` - Acquisition - `B` - Bunched trade - `D` - Distribution - `F` - Intermarket sweep - `G` - Bunched sold trades - `H` - Price variation trade - `I` - Odd lot trade - `K` - Rule 155 trde(NYSE MKT) - `M` - Market center close price - `P` - Prior reference price - `Q` - Market center open price - `S` - Split trade - `V` - Contingent trade - `W` - Average price trade - `X` - Cross trade - `1` - Stopped stock(Regular trade) ### Protobuf ```protobuf message SecurityTradeResponse { string symbol = 1; repeated Trade trades = 2; } message Trade { string price = 1; int64 volume = 2; int64 timestamp = 3; string trade_type = 4; int32 direction = 5; TradeSession trade_session = 6; } ``` ### Response JSON Example ```json { "symbol": "AAPL.US", "trades": [ { "price": "158.760", "volume": 1, "timestamp": 1651103979, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.745", "volume": 1, "timestamp": 1651103985, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.800", "volume": 1, "timestamp": 1651103995, "trade_type": "I", "direction": 0, "trade_session": 2 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Too many trades requeted | Reduce the amount of trades in each request | #### Static Info This API is used to obtain the basic information of securities. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.static_info](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.static_info) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `10` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.staticInfo(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US']) for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { SecurityStaticInfo[] resp = ctx.getStaticInfo(new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }).get(); for (SecurityStaticInfo obj : resp) { System.out.println(obj); } } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); std::vector symbols = {"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"}; ctx.static_info(symbols, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& obj : *res) { std::cout << obj.symbol << " " << obj.name_cn << " " << obj.name_en << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() infos, err := qctx.StaticInfo(context.Background(), []string{"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"}) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", infos[0]) } ``` ## Response ### Response Properties | Name | Type | Description | | -------------------- | -------- | ---------------------------------------------------------------------------------------------------- | | secu_static_info | object[] | Securities Basic Information | | ∟ symbol | string | Security code | | ∟ name_cn | string | Security name (zh-CN) | | ∟ name_en | string | Security name (en) | | ∟ name_hk | string | Security name (zh-HK) | | ∟ exchange | string | Exchange which the security belongs to | | ∟ currency | string | Trading currency

**Optional value: **
`CNY`
`USD`
`SGD`
`HKD` | | ∟ lot_size | int32 | Lot size | | ∟ total_shares | int64 | Total shares | | ∟ circulating_shares | int64 | Circulating shares | | ∟ hk_shares | int64 | HK shares (only HK stocks) | | ∟ eps | string | Earnings per share | | ∟ eps_ttm | string | Earnings per share (TTM) | | ∟ bps | string | Net assets per share | | ∟ dividend_yield | string | Dividend yield | | ∟ stock_derivatives | int32[] | Types of supported derivatives

**Optional value:**
`1` - Option
`2` - Warrant | | ∟ board | string | The board to whitch the security belongs, see [Board](../objects#board---security-board) for details | ### Protobuf ```protobuf message SecurityStaticInfoResponse { repeated StaticInfo secu_static_info = 1; } message StaticInfo { string symbol = 1; string name_cn = 2; string name_en = 3; string name_hk = 4; string listing_date = 5; string exchange = 6; string currency = 7; int32 lot_size = 8; int64 total_shares = 9; int64 circulating_shares = 10; int64 hk_shares = 11; string eps = 12; string eps_ttm = 13; string bps = 14; string dividend_yield = 15; repeated int32 stock_derivatives = 16; string board = 17; } ``` ### Response JSON Example ```json { "secu_static_info": [ { "symbol": "700.HK", "name_cn": "腾讯控股", "name_en": "TENCENT", "name_hk": "騰訊控股", "exchange": "SEHK", "currency": "HKD", "lot_size": 100, "total_shares": 9612464038, "circulating_shares": 9612464038, "hk_shares": 9612464038, "eps": "28.4394", "eps_ttm": "28.4394", "bps": "103.40413", "dividend_yield": "1.6", "stock_derivatives": [2], "board": "HKEquity" }, { "symbol": "AAPL.US", "name_cn": "苹果", "name_en": "Apple Inc.", "exchange": "NASD", "currency": "USD", "lot_size": 1, "total_shares": 1631944100, "circulating_shares": 16302661350, "eps": "5.669", "eps_ttm": "6.0771", "bps": "4.40197", "dividend_yield": "0.85", "stock_derivatives": [1], "board": "USMain" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Quotes This API is used to obtain the real-time quotes of securities, and supports all types of securities. To view these real-time data streams aggregated into live indices, sector heatmaps, and macro market overviews, you can reference the ["Global Markets"](https://longport.com/markets). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.quote](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.quote) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `11` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.quote(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US']) for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { SecurityQuote[] resp = ctx.getQuote(new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }).get(); for (SecurityQuote obj : resp) { System.out.println(obj); } } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); std::vector symbols = {"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"}; ctx.quote(symbols, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& it : *res) { std::cout << it.symbol << " last_done=" << (double)it.last_done << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() quotes, err := qctx.Quote(context.Background(), []string{"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"}) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", quotes[0]) } ``` ## Response ### Response Properties | Name | Type | Description | | ------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | secu_quote | object[] | Securities quote | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ prev_close | string | Yesterday's close | | ∟ open | string | Open | | ∟ high | string | High | | ∟ low | string | Low | | ∟ timestamp | int64 | Time of latest price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) | | ∟ pre_market_quote | object | Quote of US pre market | | ∟∟ last_done | string | Latest price | | ∟∟ timestamp | int64 | Time of latest price | | ∟∟ volume | int64 | Volume | | ∟∟ turnover | string | Turnover | | ∟∟ high | string | High | | ∟∟ low | string | Low | | ∟∟ prev_close | string | Close of the last trade session | | ∟ post_market_quote | object | Quote of US post market | | ∟∟ last_done | string | Latest price | | ∟∟ timestamp | int64 | Time of latest price | | ∟∟ volume | int64 | Volume | | ∟∟ turnover | string | Turnover | | ∟∟ high | string | High | | ∟∟ low | string | Low | | ∟∟ prev_close | string | Close of the last trade session | | ∟ over_night_quote | object | Quote of US overnight market

Note: Enable the `enable_overnight` parameter to receive it; returns null otherwise. (Overnight quotes are included free in US LV1, US stocks only.) | | ∟∟ last_done | string | Latest price | | ∟∟ timestamp | int64 | Time of latest price | | ∟∟ volume | int64 | Volume | | ∟∟ turnover | string | Turnover | | ∟∟ high | string | High | | ∟∟ low | string | Low | | ∟∟ prev_close | string | Close of the last trade session | ### Protobuf ```protobuf message SecurityQuoteResponse { repeated SecurityQuote secu_quote = 1; } message SecurityQuote { string symbol = 1; string last_done = 2; string prev_close = 3; string open = 4; string high = 5; string low = 6; int64 timestamp = 7; int64 volume = 8; string turnover = 9; TradeStatus trade_status = 10; PrePostQuote pre_market_quote = 11; PrePostQuote post_market_quote = 12; } message PrePostQuote { string last_done = 1; int64 timestamp = 2; int64 volume = 3; string turnover = 4; string high = 5; string low = 6; string prev_close = 7; } ``` ### Response JSON Example ```json { "secu_quote": [ { "symbol": "700.HK", "last_done": "338.000", "prev_close": "334.800", "open": "340.600", "high": "340.600", "low": "333.000", "timestamp": 1651115955, "volume": 7310881, "turnover": "2461463161.000" }, { "symbol": "AAPL.US", "last_done": "156.570", "prev_close": "156.800", "open": "155.910", "high": "159.790", "low": "155.380", "timestamp": 1651089600, "volume": 88063191, "turnover": "13865092584.000", "pre_market_quote": { "last_done": "155.880", "timestamp": 1651066201, "volume": 1575504, "turnover": "246653442.000", "high": "158.400", "low": "155.100", "prev_close": "156.800" }, "post_market_quote": { "last_done": "158.770", "timestamp": 1651103995, "volume": 6188441, "turnover": "970874184.759", "high": "159.400", "low": "156.400", "prev_close": "156.570" } } ] } ``` ## API Restrictions :::caution - The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP. ::: ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Intraday This API is used to obtain the intraday data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.intraday](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.intraday) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `18` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | ### Protobuf ```protobuf message SecurityIntradayRequest { string symbol = 1; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.intraday("700.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.intraday("700.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, TradeSessions } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.intraday('700.HK', TradeSessions.Intraday) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { IntradayLine[] resp = ctx.getIntraday("700.HK", TradeSessions.Intraday).get(); for (IntradayLine line : resp) System.out.println(line); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::{QuoteContext, TradeSessions}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.intraday("700.HK", TradeSessions::Intraday).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.intraday("700.HK", TradeSessions::Intraday, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "intraday lines: " << res->size() << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() lines, err := qctx.Intraday(context.Background(), "700.HK") if err != nil { log.Fatal(err) } fmt.Println("intraday lines:", len(lines)) } ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | ------------------------------------- | | symbol | string | Security code, for example: `AAPL.US` | | lines | object[] | Intraday line data | | ∟ price | string | Close price of the minute | | ∟ timestamp | int64 | Start time stamp of the minute | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ avg_price | string | Average price | ### Protobuf ``` message SecurityIntradayResponse{ string symbol = 1; repeated Line lines = 2; } message Line { string price = 1; int64 timestamp = 2; int64 volume = 3; string turnover = 4; string avg_price = 5; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "lines": [ { "price": "330.400", "timestamp": 1651023000, "volume": 375870, "turnover": "123949699.000", "avg_price": "329.767470" }, { "price": "331.200", "timestamp": 1651023060, "volume": 233095, "turnover": "77269032.800", "avg_price": "330.427416" }, { "price": "330.400", "timestamp": 1651023120, "volume": 192565, "turnover": "63711556.000", "avg_price": "330.530719" }, { "price": "330.800", "timestamp": 1651023180, "volume": 143397, "turnover": "47471072.400", "avg_price": "330.608989" }, { "price": "330.800", "timestamp": 1651023240, "volume": 141834, "turnover": "46890605.600", "avg_price": "330.608078" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Broker IDs This API is used to obtain participant IDs data (which can be synchronized once a day). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.participants](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.participants) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `16` ::: ## Request ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.participants() print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.participants() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.participants() for (const obj of resp) { console.log(obj.toString()) } } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ParticipantInfo[] resp = ctx.getParticipants().get(); for (ParticipantInfo obj : resp) { System.out.println(obj); } } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.participants().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.participants([](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } for (const auto& p : *res) { std::cout << p.broker_ids[0] << " " << p.name << std::endl; } }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() participants, err := qctx.Participants(context.Background()) if err != nil { log.Fatal(err) } for _, p := range participants { fmt.Printf("%v %s\n", p.BrokerIds, p.ParticipantNameEn) } } ``` ## Response ### Response Properties | Name | Type | Description | | -------------------------- | -------- | ------------------------ | | participant_broker_numbers | object[] | participant data | | ∟ broker_ids | int32[] | broker IDs | | ∟ participant_name_cn | string | participant name (zh-CN) | | ∟ participant_name_en | string | participant name (en) | | ∟ participant_name_hk | string | participant name (zh-HK) | ### Protobuf ```protobuf message ParticipantBrokerIdsResponse { repeated ParticipantInfo participant_broker_numbers = 1; } message ParticipantInfo { repeated int32 broker_ids = 1; string participant_name_cn = 2; string participant_name_en = 3; string participant_name_hk = 4; } ``` ### Response JSON Example ```json { "participant_broker_numbers": [ { "broker_ids": [7738, 7739], "participant_name_cn": "华兴金融 (香港)", "participant_name_en": "China Renaissance(HK)", "participant_name_hk": "華興金融 (香港)" }, { "broker_ids": [6390, 6396, 6398, 6399], "participant_name_cn": "国信 (香港)", "participant_name_en": "Guosen(HK)", "participant_name_hk": "國信 (香港)" }, { "broker_ids": [3168, 3169], "participant_name_cn": "泰嘉", "participant_name_en": "Tiger", "participant_name_hk": "泰嘉" } ] } ``` ## Error Code | Proto Error Code | Business Error Code | Descrption | Troubleshooting Suggestions | | ---------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | #### Candlesticks This API is used to obtain the candlestick data of security. :::info Note: This interface can only retrieve the last 1000 candlesticks. To obtain longer historical data, please visit the interface: Get Security History Candlesticks. ::: ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.candlesticks](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.candlesticks) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `19` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | period | int32 | Yes | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period) | | count | int32 | Yes | Count of cancdlestick, for example: `100`

**Check rules:**
maximum count is `1000` | | adjust_type | int32 | Yes | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type) | | trade_session | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight)

Note: Overnight data is included free in US LV1, US stocks only; enable the `enable_overnight` parameter to receive it. | ### Protobuf ```protobuf message SecurityCandlestickRequest { string symbol = 1; Period period = 2; int32 count = 3; AdjustType adjust_type = 4; int32 trade_session = 5; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, Period, AdjustType, TradeSessions, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) # Get intraday candlestick data for 700.HK resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust) print(resp) # Get all candlestick data for 700.HK resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, trade_session=TradeSessions.All) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, Period, AdjustType, TradeSessions, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) # Get intraday candlestick data for 700.HK resp = await ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust) print(resp) # Get all candlestick data for 700.HK resp = await ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, trade_session=TradeSessions.All) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, Period, AdjustType, TradeSessions } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.candlesticks('700.HK', Period.Day, 10, AdjustType.NoAdjust, TradeSessions.Intraday) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { Candlestick[] resp = ctx.getCandlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, TradeSessions.Intraday).get(); for (Candlestick c : resp) System.out.println(c); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::{Period, AdjustType, TradeSessions}}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.candlesticks("700.HK", Period::Day, 10, AdjustType::NoAdjust, TradeSessions::Intraday).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.candlesticks("700.HK", Period::Day, 10, AdjustType::NoAdjust, TradeSessions::Intraday, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "candlesticks: " << res->size() << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() sticks, err := qctx.Candlesticks(context.Background(), "700.HK", quote.PeriodDay, 10, quote.AdjustTypeNo) if err != nil { log.Fatal(err) } fmt.Println("candlesticks:", len(sticks)) } ``` ## Response ### Response Properties | Name | Type | Description | | --------------- | -------- | ---------------------------------------------------------------------------- | | symbol | string | Security code, for example: `AAPL.US` | | candlesticks | object[] | Candlestick data | | ∟ close | string | Close price | | ∟ open | string | Open price | | ∟ low | string | Low price | | ∟ high | string | High price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ timestamp | int64 | Timestamp | | ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | ### Protobuf ```protobuf message SecurityCandlestickResponse { string symbol = 1; repeated Candlestick candlesticks = 2; } message Candlestick { string close = 1; string open = 2; string low = 3; string high = 4; int64 volume = 5; string turnover = 6; int64 timestamp = 7; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "candlesticks": [ { "close": "362.000", "open": "364.600", "low": "361.600", "high": "368.800", "volume": 10853604, "turnover": "3954556819.000", "timestamp": 1650384000 }, { "close": "348.000", "open": "352.000", "low": "343.000", "high": "356.200", "volume": 25738562, "turnover": "8981529950.000", "timestamp": 1650470400 }, { "close": "340.600", "open": "334.800", "low": "334.200", "high": "343.000", "volume": 28031299, "turnover": "9492674293.000", "timestamp": 1650556800 }, { "close": "327.400", "open": "332.200", "low": "325.200", "high": "338.600", "volume": 25788422, "turnover": "8541441823.000", "timestamp": 1650816000 }, { "close": "335.800", "open": "332.200", "low": "330.600", "high": "341.600", "volume": 27288328, "turnover": "9166022626.000", "timestamp": 1650902400 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------------ | ------------------------------------------------------------------------------ | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period` | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Too many candlesticks requeted | Reduce the amount of candlestick in each request | #### Historical Candlesticks This API is used to obtain the history candlestick data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.history_candlesticks_by_offset](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.history_candlesticks_by_offset) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command):`27` ::: ## Request ### Parameters | Name | Type | Required | Description | | -------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | period | int32 | Yes | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period) | | adjust_type | int32 | Yes | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type) | | query_type | int32 | Yes | Type of query

**Optional value:**
`1` - query by offset
`2` - query by date | | date_request | object | No | Required when querying by date | | ∟ start_date | string | No | Date of query begin, in `YYYYMMDD` format, for example: 20231016

**Parameter description:**
1. Leave both start_date and end_date blank: return the latest 1000 candlesticks;
2. Fill only start_date: return the candlesticks between start_date and the latest trading day. If there are more than 1000 candlesticks in this interval, the candlesticks close to start_date will be returned first;
3. Fill in only end_date: return end_date and the previous 1000 candlesticks;
4. Fill in both start_date and end_date: return candlesticks data within this interval. If there are more than 1000 candlesticks in the interval, the candlesticks close to end_date will be returned first. | | ∟ end_date | string | No | Date of query end, in `YYYYMMDD` format, for example: 20231016 | | offset_request | object | No | Required when querying by offset | | ∟ direction | int32 | Yes | Query direction

**Optional value:**
`0` - query in the direction of historical data
`1` - query in the direction of latest data | | ∟ date | string | No | Query date, in `YYYYMMDD` format, for example: 20231016. Default value: latest trading day of the underlying market. | | ∟ minute | string | No | Query time, in `HHMM` format, for example: 09:35, only valid when querying minute-level data | | ∟ count | int32 | No | Count of cancdlestick, valid range:`[1,1000]`. Default value: `10` | | trade_session | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight)

Note: Overnight data is included free in US LV1, US stocks only; enable the `enable_overnight` parameter to receive it. | ### Protobuf ```protobuf message SecurityHistoryCandlestickRequest { message OffsetQuery { Direction direction = 1; string date = 2; string minute = 3; int32 count = 4; } message DateQuery { string start_date = 1; string end_date = 2; } string symbol = 1; Period period = 2; AdjustType adjust_type = 3; HistoryCandlestickQueryType query_type = 4; OffsetQuery offset_request = 5; DateQuery date_request = 6; } ``` ### Request Example ```python from datetime import datetime, date from longport.openapi import QuoteContext, Config, Period, AdjustType, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) # Query after 2023-01-01 resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, True, 10, datetime(2023, 1, 1)) print(resp) # Query before 2023-01-01 resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, False, 10, datetime(2023, 1, 1)) print(resp) # Query 2023-01-01 to 2023-02-01 resp = ctx.history_candlesticks_by_date("700.HK", Period.Day, AdjustType.NoAdjust, date(2023, 1, 1), date(2023, 2, 1)) print(resp) ``` ```python import asyncio from datetime import datetime, date from longport.openapi import AsyncQuoteContext, Config, Period, AdjustType, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) # Query after 2023-01-01 resp = await ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, True, 10, datetime(2023, 1, 1)) print(resp) # Query before 2023-01-01 resp = await ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, False, 10, datetime(2023, 1, 1)) print(resp) # Query 2023-01-01 to 2023-02-01 resp = await ctx.history_candlesticks_by_date("700.HK", Period.Day, AdjustType.NoAdjust, date(2023, 1, 1), date(2023, 2, 1)) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth, Period, AdjustType, TradeSessions, NaiveDatetime, NaiveDate, Time, } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const datetime = new NaiveDatetime(new NaiveDate(2023, 1, 1), new Time(0, 0, 0)) const resp = await ctx.historyCandlesticksByOffset( '700.HK', Period.Day, AdjustType.NoAdjust, true, datetime, 10, TradeSessions.Intraday ) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; import java.time.LocalDateTime; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { Candlestick[] resp = ctx.getHistoryCandlesticksByOffset("700.HK", Period.Day, AdjustType.NoAdjust, true, LocalDateTime.of(2023, 1, 1, 0, 0), 10, TradeSessions.Intraday).get(); for (Candlestick c : resp) System.out.println(c); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::{Period, AdjustType, TradeSessions}}; use time::macros::datetime; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let dt = datetime!(2023-01-01 00:00); let resp = ctx.history_candlesticks_by_offset("700.HK", Period::Day, AdjustType::NoAdjust, true, Some(dt), 10, TradeSessions::Intraday).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.history_candlesticks_by_offset("700.HK", Period::Day, AdjustType::NoAdjust, true, std::nullopt, 10, TradeSessions::Intraday, [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "candlesticks: " << res->size() << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "time" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() dt := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC) sticks, err := qctx.HistoryCandlesticksByOffset(context.Background(), "700.HK", quote.PeriodDay, quote.AdjustTypeNo, true, &dt, 10) if err != nil { log.Fatal(err) } fmt.Println("candlesticks:", len(sticks)) } ``` ## Response ### Response Properties | Name | Type | Description | | --------------- | -------- | ---------------------------------------------------------------------------- | | symbol | string | Security code, for example: `AAPL.US` | | candlesticks | object[] | Candlestick data | | ∟ close | string | Close price | | ∟ open | string | Open price | | ∟ low | string | Low price | | ∟ high | string | High price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ timestamp | int64 | Timestamp | | ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | ### Protobuf ```protobuf message SecurityCandlestickResponse { string symbol = 1; repeated Candlestick candlesticks = 2; } message Candlestick { string close = 1; string open = 2; string low = 3; string high = 4; int64 volume = 5; string turnover = 6; int64 timestamp = 7; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "candlesticks": [ { "close": "362.000", "open": "364.600", "low": "361.600", "high": "368.800", "volume": 10853604, "turnover": "3954556819.000", "timestamp": 1650384000 }, { "close": "348.000", "open": "352.000", "low": "343.000", "high": "356.200", "volume": 25738562, "turnover": "8981529950.000", "timestamp": 1650470400 }, { "close": "340.600", "open": "334.800", "low": "334.200", "high": "343.000", "volume": 28031299, "turnover": "9492674293.000", "timestamp": 1650556800 }, { "close": "327.400", "open": "332.200", "low": "325.200", "high": "338.600", "volume": 25788422, "turnover": "8541441823.000", "timestamp": 1650816000 }, { "close": "335.800", "open": "332.200", "low": "330.600", "high": "341.600", "volume": 27288328, "turnover": "9166022626.000", "timestamp": 1650902400 } ] } ``` ## Permission description According to the user’s assets and transactions, the number of targets that different types of users can query historical data on each month is as follows: - The quota is calculated based on the natural month. The quota is topped up at the beginning of each month. The remaining quota from the previous month will not be accumulated to this month. If you repeatedly request the historical K-line of the same target within a natural month, it will only be counted once. - For newly deposited accounts, the limit will automatically take effect on the next trading day; when the account's total assets or number of transactions increase and reaches a higher level, the limit will take effect on the next trading day. - Total assets: The total assets of the user's Hong Kong stocks, U.S. stocks, A-shares and other securities accounts are converted into Hong Kong dollars according to the exchange rate. Take the larger value of the user's total assets on the last trading day of the previous calendar month and the total assets on the most recent complete trading day. - Number of transactions per month: The number of orders that the user has completed. Partial completion of one order, complete completion of multiple transactions, or all transactions at one time are counted as 1 transaction. Take the larger value of the user's number of transactions in the last natural month and the number of transactions in the current natural month.
User Type The maximum number of targets that can be queried per month
User account opening
100
Total assets reach HKD 10,000
400
Total assets reach HKD 80,000
600
Total assets reach 400,000 HKD or the number of transactions per month is greater than 160
1000
Total assets reach 4 million HKD or the number of transactions per month is greater than 1,600
2000
Total assets reach 6 million HKD or the number of transactions per month is greater than 2,500
3000
## Description of historical candlesticks range | Market | Daily/Weekly/Monthly/Year period candlesticks | Minute candlesticks | Description | | ------------------ | --------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------- | | Hong Kong stocks | 2004-6-1 to present | 2022-09-28 to present | | | U.S. stocks | 2010-6-1 to present | 2023-12-4 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 | | A shares | 1999-11-1 to present | 2022-08-25 to present | | ## Rate limite :::caution - The api can be requested up to 60 times every 30 seconds. ::: ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | -------------------------- | ----------------------------------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period` | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Permission limit | Exceeds the upper limit of the number of targets that can be queried in the current month | #### Watchlist #### Create Group Create watched group ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.create_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.create_watchlist_group) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodPOST
HTTP URL/v1/watchlist/groups
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | ---------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | name | string | YES | Group name, for example `Information Technology Group`. | | securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`. Display order of securities in the group, in the same order as this list. If this parameter is not passed, create an empty group. | ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) group_id = ctx.create_watchlist_group(name = "Watchlist1", securities = ["700.HK", "AAPL.US"]) print(group_id) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) group_id = ctx.create_watchlist_group(name = "Watchlist1", securities = ["700.HK", "AAPL.US"]) print(group_id) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.createWatchlistGroup('My Group', ['700.HK', 'AAPL.US']) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { WatchlistGroup resp = ctx.createWatchlistGroup("My Group", new String[] { "700.HK", "AAPL.US" }).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.create_watchlist_group("My Group", vec!["700.HK".to_string(), "AAPL.US".to_string()]).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.create_watchlist_group("My Group", symbols, [](auto res) { if (!res) { std::cout << "failed" << std::endl; return; } std::cout << "created: " << res->name << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() gid, err := qctx.CreateWatchlistGroup(context.Background(), "My Group", []string{"700.HK", "AAPL.US"}) if err != nil { log.Fatal(err) } fmt.Println("created:", gid) } ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0, "data": { "id": 10086 } } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ----------------------------------------------------- | | 200 | Success | [create_group_response](#schemacreate_group_response) | | 500 | Internal error | None | ## Schemas ### create_group_response | Name | Type | Required | Description | | ---- | ------- | -------- | ----------- | | id | integer | false | Group ID | #### Delete Group Delete watched group ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.delete_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.delete_watchlist_group) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodDELETE
HTTP URL/v1/watchlist/groups
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | ----- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | id | integer | YES | Group ID, for example `10086`. | | purge | boolean | YES | Whether to clear the securities in the group. If set to `true`, the securities in the group will be unfollowed. If set to `false`, the securities in the group will remain in the `All` group. | ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.delete_watchlist_group(10086) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) ctx.delete_watchlist_group(10086) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) await ctx.deleteWatchlistGroup(1) console.log('deleted') } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ctx.deleteWatchlistGroup(1).get(); System.out.println("deleted"); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); ctx.delete_watchlist_group(1).await?; println!("deleted"); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.delete_watchlist_group(1, [](auto res) { if (!res) { std::cout << "failed" << std::endl; return; } std::cout << "deleted" << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() err = qctx.DeleteWatchlistGroup(context.Background(), 1, false) if err != nil { log.Fatal(err) } fmt.Println("deleted") } ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0 } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ------ | | 200 | Success | None | | 500 | Internal error | None | #### Manage Group Securities Update watched group ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.update_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.update_watchlist_group) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodPUT
HTTP URL/v1/watchlist/groups
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | id | integer | YES | Group ID, for example `10086`. | | name | string | NO | Group name, for example `Information Technology Group`.
If this parameter is not passed, the group name will not be updated. | | securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`.
Combined with the `mode` parameter below, it can be used to add securities, remove securities, and sort the watchlist. | | mode | string | NO | Operation method
**optional values:**
`add` - Add securities
`remove` - Remove securities
`replace` - Update securities

When selecting `add`, the securities in the above list will be added to this group in order.

When selecting `remove`, the securities in the above list will be removed from this group.

When selecting `update`, the securities in the above list will completely replace the securities in this group.
For example, if the original group contains `APPL.US, BABA.US, TSLA.US`, and it is updated with `["BABA.US", "AAPL.US", "MSFT.US"]`, it will become `BABA.US, AAPL.US, MSFT.US`, removing `TSLA.US` and adding `MSFT.US`, while adjusting the order of `BABA.US and AAPL.US`. | ### Request Example ```python from longport.openapi import QuoteContext, Config, SecuritiesUpdateMode, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, SecuritiesUpdateMode, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) await ctx.updateWatchlistGroup(1, 'New Name', ['700.HK']) console.log('updated') } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ctx.updateWatchlistGroup(1, "New Name", new String[] { "700.HK" }).get(); System.out.println("updated"); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); ctx.update_watchlist_group(1, "New Name", vec!["700.HK".to_string()]).await?; println!("updated"); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.update_watchlist_group(1, "New Name", symbols, [](auto res) { if (!res) { std::cout << "failed" << std::endl; return; } std::cout << "updated" << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() err = qctx.UpdateWatchlistGroup(context.Background(), 1, "New Name", []string{"700.HK"}, quote.AddWatchlist) if err != nil { log.Fatal(err) } fmt.Println("updated") } ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0 } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ------ | | 200 | Success | None | | 500 | Internal error | None | #### Update Pinned Pin or unpin a security within a watchlist group to control its display order. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.update_pinned](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.update_pinned) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodPUT
HTTP URL/watchlist/groups
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | --------- | ------ | -------- | -------------------------------------------------------- | | id | string | YES | Watchlist group ID | | symbol | string | YES | Security symbol to pin or unpin, e.g. `AAPL.US` | | is_pinned | bool | YES | Set to `true` to pin the security, `false` to unpin it | ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) ctx.update_pinned(group_id="2630", symbol="AAPL.US", is_pinned=True) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) await ctx.update_pinned(group_id="2630", symbol="AAPL.US", is_pinned=True) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) await ctx.updatePinned('2630', 'AAPL.US', true) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ctx.updatePinned("2630", "AAPL.US", true).get(); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); ctx.update_pinned("2630", "AAPL.US", true).await?; Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::quote; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); QuoteContext ctx = QuoteContext::create(config); ctx.update_pinned("2630", "AAPL.US", true, [](auto) {}); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() if err := qctx.UpdatePinned(context.Background(), "2630", "AAPL.US", true); err != nil { log.Fatal(err) } fmt.Println("OK") } ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0, "message": "success", "data": {} } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | None | | 400 | Bad request | None | ## Schemas No response schemas. The endpoint returns an empty `data` object on success. #### Watchlist Groups Get Watchlist groups ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.watchlist](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.watchlist) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodGET
HTTP URL/v1/watchlist/groups
### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.watchlist() print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.watchlist() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.watchlist() console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { WatchlistGroup[] resp = ctx.getWatchlist().get(); for (WatchlistGroup g : resp) System.out.println(g); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.watchlist().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.watchlist([](auto res) { if (!res) { std::cout << "failed" << std::endl; return; } for (const auto& g : *res) std::cout << g.name << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() groups, err := qctx.WatchedGroups(context.Background()) if err != nil { log.Fatal(err) } for _, g := range groups { fmt.Println(g.Name) } } ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0, "data": { "groups": [ { "id": 28020, "name": "all", "securities": [ { "symbol": "700.HK", "market": "HK", "name": "Tencent", "watched_price": "364.4", "watched_at": 1652855022, "is_pinned": true } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ----------------------------------------- | | 200 | Success | [groups_response](#schemagroups_response) | | 500 | Internal error | None | ## Schemas ### groups_response | Name | Type | Required | Description | | ---------------- | -------- | -------- | ------------------------------ | | groups | object[] | false | Groups | | ∟ id | integer | true | Group ID | | ∟ name | string | true | Name | | ∟ securities | object[] | true | Security | | ∟∟ symbol | string | true | Symbol | | ∟∟ market | string | true | Market | | ∟∟ name | string | true | Name | | ∟∟ watched_price | string | true | Watched price | | ∟∟ watched_at | integer | true | Watched time | | ∟∟ is_pinned | boolean | true | Whether the security is pinned | #### Individual #### Create Watchlist Group Create watched group ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.create_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.create_watchlist_group) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodPOST
HTTP URL/v1/watchlist/groups
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | ---------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | name | string | YES | Group name, for example `Information Technology Group`. | | securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`. Display order of securities in the group, in the same order as this list. If this parameter is not passed, create an empty group. | ### Request Example ```python from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) group_id = ctx.create_watchlist_group(name = "Watchlist1", securities = ["700.HK", "AAPL.US"]) print(group_id) ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0, "data": { "id": 10086 } } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ----------------------------------------------------- | | 200 | Success | [create_group_response](#schemacreate_group_response) | | 500 | Internal error | None | ## Schemas ### create_group_response | Name | Type | Required | Description | | ---- | ------- | -------- | ----------- | | id | integer | false | Group ID | #### Delete Watchlist Group Delete watched group ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.delete_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.delete_watchlist_group) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodDELETE
HTTP URL/v1/watchlist/groups
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | ----- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | id | integer | YES | Group ID, for example `10086`. | | purge | boolean | YES | Whether to clear the securities in the group. If set to `true`, the securities in the group will be unfollowed. If set to `false`, the securities in the group will remain in the `All` group. | ### Request Example ```python from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) ctx.delete_watchlist_group(10086) ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0 } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ------ | | 200 | Success | None | | 500 | Internal error | None | #### Update Watchlist Group Update watched group ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.update_watchlist_group](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.update_watchlist_group) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodPUT
HTTP URL/v1/watchlist/groups
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | id | integer | YES | Group ID, for example `10086`. | | name | string | NO | Group name, for example `Information Technology Group`.
If this parameter is not passed, the group name will not be updated. | | securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`.
Combined with the `mode` parameter below, it can be used to add securities, remove securities, and sort the watchlist. | | mode | string | NO | Operation method
**optional values:**
`add` - Add securities
`remove` - Remove securities
`replace` - Update securities

When selecting `add`, the securities in the above list will be added to this group in order.

When selecting `remove`, the securities in the above list will be removed from this group.

When selecting `update`, the securities in the above list will completely replace the securities in this group.
For example, if the original group contains `APPL.US, BABA.US, TSLA.US`, and it is updated with `["BABA.US", "AAPL.US", "MSFT.US"]`, it will become `BABA.US, AAPL.US, MSFT.US`, removing `TSLA.US` and adding `MSFT.US`, while adjusting the order of `BABA.US and AAPL.US`. | ### Request Example ```python from longport.openapi import QuoteContext, Config, SecuritiesUpdateMode config = Config.from_env() ctx = QuoteContext(config) ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace) ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0 } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ------ | | 200 | Success | None | | 500 | Internal error | None | #### Watchlist Group Get watched groups ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.watchlist](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.watchlist) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodGET
HTTP URL/v1/watchlist/groups
### Request Example ```python from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.watchlist() print(resp) ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0, "data": { "groups": [ { "id": 28020, "name": "all", "securities": [ { "symbol": "700.HK", "market": "HK", "name": "Tencent", "watched_price": "364.4", "watched_at": 1652855022 } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ----------------------------------------- | | 200 | Success | [groups_response](#schemagroups_response) | | 500 | Internal error | None | ## Schemas ### groups_response | Name | Type | Required | Description | | ---------------- | -------- | -------- | ------------- | | groups | object[] | false | Groups | | ∟ id | integer | true | Group ID | | ∟ name | string | true | Name | | ∟ securities | object[] | true | Security | | ∟∟ symbol | string | true | Symbol | | ∟∟ market | string | true | Market | | ∟∟ name | string | true | Name | | ∟∟ watched_price | string | true | Watched price | | ∟∟ watched_at | integer | true | Watched time | #### Pull #### Current Market Temperature Get Current Market Temperature ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.market_temperature](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.market_temperature) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodGET
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 longport.openapi import QuoteContext, Config, Market config = Config.from_env() ctx = QuoteContext(config) resp = ctx.market_temperature(Market.US) print(resp) ``` ## 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 | #### Security Brokers This API is used to obtain the real-time broker queue data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.brokers](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.brokers) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `15` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | --------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python # 获取标的经纪队列 # https://open.longportapp.com/docs/quote/pull/brokers # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.brokers("700.HK") print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | ------------ | -------- | ------------------------------------------------------------------ | | symbol | string | Security code | | ask_brokers | object[] | Ask brokers | | ∟ position | int32 | Position | | ∟ broker_ids | int32[] | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API | | bid_brokers | object[] | Bid brokers | | ∟ position | int32 | Postition | | ∟ broker_ids | int32[] | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API | ### Protobuf ```protobuf message SecurityBrokersResponse { string symbol = 1; repeated Brokers ask_brokers = 2; repeated Brokers bid_brokers = 3; } message Brokers { int32 position = 1; repeated int32 broker_ids = 2; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "ask_brokers": [ { "position": 1, "broker_ids": [7358, 9057, 9028, 7364] }, { "position": 2, "broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997] } ], "bid_brokers": [ { "position": 1, "broker_ids": [6996, 5465, 8026, 8304, 4978] }, { "position": 2 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Security Depth This API is used to obtain the depth data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.depth](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.depth) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `14` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python # Get Security Depth # https://open.longportapp.com/docs/quote/pull/depth # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.depth("700.HK") print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | ---------------- | | symbol | string | Security code | | ask | object[] | Ask depth | | ∟ position | int32 | Position | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ order_num | int64 | Number of orders | | bid | object[] | Bid depth | | ∟ position | int32 | Position | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ order_num | int64 | Number of orders | ### Protobuf ```protobuf message SecurityDepthResponse { string symbol = 1; repeated Depth ask = 2; repeated Depth bid = 3; } message Depth { int32 position = 1; string price = 2; int64 volume = 3; int64 order_num = 4; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "ask": [ { "position": 1, "price": "335.000", "volume": 500, "order_num": 1 }, { "position": 2, "price": "335.200", "volume": 400, "order_num": 1 }, { "position": 3, "price": "335.400", "volume": 500, "order_num": 2 }, { "position": 4, "price": "335.600", "volume": 1200, "order_num": 3 }, { "position": 5, "price": "335.800", "volume": 14000, "order_num": 8 } ], "bid": [ { "position": 1, "price": "334.800", "volume": 69400, "order_num": 13 }, { "position": 2, "price": "334.600", "volume": 266600, "order_num": 27 }, { "position": 3, "price": "334.400", "volume": 61300, "order_num": 29 }, { "position": 4, "price": "334.200", "volume": 125900, "order_num": 31 }, { "position": 5, "price": "334.000", "volume": 194600, "order_num": 94 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Filings Get the filings list for a specified security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.filings](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.filings) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodGET
HTTP URL/v1/quote/filings
### Query Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------- | | symbol | string | YES | Stock symbol, use `ticker.region` format, e.g. `AAPL.US` | ### Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.filings("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.filings("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.filings('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { FilingItem[] resp = ctx.getFilings("AAPL.US").get(); for (FilingItem item : resp) System.out.println(item); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.filings("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include #ifdef WIN32 #include #endif using namespace longport; using namespace longport::quote; static void run(const OAuth& oauth) { Config config = Config::from_oauth(oauth); QuoteContext ctx = QuoteContext::create(config); ctx.filings("AAPL.US", [](auto res) { if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; } std::cout << "filings: " << res->size() << std::endl; }); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif const std::string client_id = "your-client-id"; OAuthBuilder(client_id).build( [](const std::string& url) { std::cout << "Open this URL to authorize: " << url << std::endl; }, [](auto res) { if (!res) { std::cout << "authorization failed: " << *res.status().message() << std::endl; return; } run(*res); }); std::cin.get(); return 0; } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() items, err := qctx.Filings(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Println("filings:", len(items)) } ``` ## Response ### Response Headers - Content-Type: application/json ### Response Example ```json { "code": 0, "message": "success", "data": { "items": [ { "id": "627391979864985729", "title": "Apple | (4) Statement of changes in beneficial ownership", "description": "", "file_name": "4 - Apple Inc. (0000320193) (Issuer)", "file_urls": [ "https://www.sec.gov/Archives/edgar/data/320193/000178052526000005/xslF345X05/wk-form4_1773786674.xml" ], "publish_at": "1773786677" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | -------------- | ------------------------------------------- | | 200 | Success | [filings_response](#schemafilings_response) | | 500 | Internal error | None | ## Schemas ### filings_response | Name | Type | Required | Description | | ------------- | -------- | -------- | -------------------------------------- | | items | object[] | true | Filings list | | ∟ id | string | true | Filing ID | | ∟ title | string | true | Title | | ∟ description | string | true | Summary | | ∟ file_name | string | true | File name | | ∟ file_urls | string[] | true | List of file URLs | | ∟ publish_at | string | true | Publish time, Unix timestamp (seconds) | #### Security Trades This API is used to obtain the trades data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.trades](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.trades) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `17` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | count | int32 | Yes | Count of trades

**Check rules:**
The maximum number of trades in each request is `1000` | ### Protobuf ```protobuf message SecurityTradeRequest { string symbol = 1; int32 count = 2; } ``` ### Request Example ```python # Get Security Trades # https://open.longportapp.com/docs/quote/pull/trade # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.trades("700.HK", 10) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | --------------- | -------- | ------------------------------------------------------------------------------------------------ | | symbol | string | Security code | | trades | object[] | Trades data | | ∟ price | string | Price | | ∟ volume | int64 | Volume | | ∟ timestamp | int64 | Time of trading | | ∟ trade_type | string | [Trade type](#trade-type) | | ∟ direction | int32 | Trade direction

**Optional value:**
`0` - neutral
`1` - down
`2` - up | | ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | #### Trade Type HK - `*` - Overseas trade - `D` - Odd-lot trade - `M` - Non-direct off-exchange trade - `P` - Late trade (Off-exchange previous day) - `U` - Auction trade - `X` - Direct off-exchange trade - `Y` - Automatch internalized - ` ` - Automatch normal US - ` ` - Regular sale - `A` - Acquisition - `B` - Bunched trade - `D` - Distribution - `F` - Intermarket sweep - `G` - Bunched sold trades - `H` - Price variation trade - `I` - Odd lot trade - `K` - Rule 155 trde(NYSE MKT) - `M` - Market center close price - `P` - Prior reference price - `Q` - Market center open price - `S` - Split trade - `V` - Contingent trade - `W` - Average price trade - `X` - Cross trade - `1` - Stopped stock(Regular trade) ### Protobuf ```protobuf message SecurityTradeResponse { string symbol = 1; repeated Trade trades = 2; } message Trade { string price = 1; int64 volume = 2; int64 timestamp = 3; string trade_type = 4; int32 direction = 5; TradeSession trade_session = 6; } ``` ### Response JSON Example ```json { "symbol": "AAPL.US", "trades": [ { "price": "158.760", "volume": 1, "timestamp": 1651103979, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.745", "volume": 1, "timestamp": 1651103985, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.800", "volume": 1, "timestamp": 1651103995, "trade_type": "I", "direction": 0, "trade_session": 2 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Too many trades requeted | Reduce the amount of trades in each request | #### Warrant Filter This API is used to obtain the quotes of HK warrants, and supports sorting and filtering. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.warrant_list](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.warrant_list) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `23` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | filter_config | object | Yes | Filter conditions | | ∟ sort_by | int32 | Yes | Which data to sort by, for example: `0`, see the `OrderSequence` field of the response data for the sequence number. | | ∟ sort_order | int32 | Yes | Order, for example: `1`

**Optional value:**
`0` - Ascending
`1` - Descending | | ∟ sort_offset | int32 | Yes | The first data offset of paging, for example: `0` | | ∟ sort_count | int32 | Yes | Number of paginated pages per page, for example: `20`, no pagination when filling in `0` | | ∟ type | int32[] | No | Filter warrant type, for example: `[0,1]`

**Optional value:**
`0` - Call
`1` - Put
`2` - Bull
`3` - Bear
`4` - Inline | | ∟ issuer | int32[] | No | Filter issuer example: `[12,14]`, obtain [Issuer ID](./issuer) through API | | ∟ expiry_date | int32[] | No | Filter expiry date, example: `[1]`

**Optional value:**
`1` - Less than 3 months
`2` - 3 - 6 months
`3` - 6 - 12 months
`4` - greater than 12 months | | ∟ price_type | int32[] | No | Filter in/out of bounds, for example: `[2]`

**Optional value:**
`1` - In bounds
`2` - Out bounds | | ∟ status | int32[] | No | Filter status, for example: `[2]`

**Optional value:**
`2`- Suspend trading
`3` - Papare List
`4` - Normal | | language | int32 | Yes | Language, for example: `[1]`

**Optional value:**
`0` - zh-CN
`1` - en
`2` - zh-HK | ### Protobuf ```protobuf message WarrantFilterListRequest { string symbol = 1; FilterConfig filter_config = 2; int32 language = 3; } message FilterConfig { int32 sort_by = 1; int32 sort_order = 2; int32 sort_offset = 3; int32 sort_count = 4; repeated int32 type = 5; repeated int32 issuer = 6; repeated int32 expiry_date = 7; repeated int32 price_type = 8; repeated int32 status = 9; } ``` ### Request Example ```python from longport.openapi import QuoteContext, Config, WarrantSortBy, SortOrderType config = Config.from_env() ctx = QuoteContext(config) resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | OrderSequence | Support_Call/Put | Support_Bull/Bear | Support_Inline | | -------------------- | -------- | ---------------------------------------------------------------------------------------------------------- | ------------- | ---------------- | ----------------- | -------------- | | warrant_list | object[] | Filted warrant data list | | | | | | ∟ symbol | string | Security code | | true | true | true | | ∟ name | string | Security name | | true | true | true | | ∟ last_done | string | Latest price | 0 | true | true | true | | ∟ change_rate | string | Quote change rate | 1 | true | true | true | | ∟ change_val | string | Quote change | 2 | true | true | true | | ∟ volume | int64 | Volume | 3 | true | true | true | | ∟ turnover | string | Turnover | 4 | true | true | true | | ∟ expiry_date | string | Expiry date, in `YYMMDD` format | 5 | true | true | true | | ∟ strike_price | string | Strike price | 6 | true | true | false | | ∟ upper_strike_price | string | Upper bound price | 7 | false | false | true | | ∟ lower_strike_price | string | Lower bound price | 8 | false | false | true | | ∟ outstanding_qty | string | Outstanding quantity | 9 | true | true | true | | ∟ outstanding_ratio | string | Outstanding ratio | 10 | true | true | true | | ∟ premium | string | Premium | 11 | true | true | true | | ∟ itm_otm | string | In/out of the bound | 12 | true | true | false | | ∟ implied_volatility | string | Implied volatility | 13 | true | false | false | | ∟ delta | string | Greek value Delta | 14 | true | false | false | | ∟ call_price | string | Call price | 15 | false | true | false | | ∟ to_call_price | string | Price interval from the call price | 16 | false | true | false | | ∟ effective_leverage | string | Effective leverage | 17 | true | false | false | | ∟ leverage_ratio | string | Leverage ratio | 18 | true | true | true | | ∟ conversion_ratio | string | Conversion ratio | 19 | true | true | false | | ∟ balance_point | string | Breakeven point | 20 | true | true | false | | ∟ status | int32 | Status,

**Optional value:**
`2`- Suspend trading
`3` - Papare List
`4` - Normal | 21 | true | true | true | | total_count | int32 | Total number of eligible | | | | | ### Protobuf ```protobuf message WarrantFilterListResponse { repeated FilterWarrant warrant_list = 1; int32 total_count = 2; } message FilterWarrant { string symbol = 1; string name = 2; string last_done = 3; string change_rate = 4; string change_val = 5; int64 volume = 6; string turnover = 7; string expiry_date = 8; string strike_price = 9; string upper_strike_price = 10; string lower_strike_price = 11; string outstanding_qty = 12; string outstanding_ratio = 13; string premium = 14; string itm_otm = 15; string implied_volatility = 16; string delta = 17; string call_price = 18; string to_call_price = 19; string effective_leverage = 20; string leverage_ratio = 21; string conversion_ratio = 22; string balance_point = 23; int32 status = 24; } ``` ### Response JSON Example ```json { "warrant_list": [ { "symbol": "13157.HK", "name": "MBTENCT@EP2207A", "last_done": "2.26", "change_rate": "-0.0216450216450218", "change_val": "-0.050000000000000266", "turnover": "0", "expiry_date": "20220705", "strike_price": "442.233", "upper_strike_price": "0", "lower_strike_price": "0", "outstanding_qty": "5000", "outstanding_ratio": "0.0003", "premium": "0.016784269662921222", "itm_otm": "0.23524476916014864", "implied_volatility": "0.5275", "delta": "-0.8524", "call_price": "0", "effective_leverage": "-2.627683451852457", "leverage_ratio": "3.0826882353970637", "conversion_ratio": "48.544", "balance_point": "332.52356000000003", "status": 4 }, { "symbol": "13649.HK", "name": "MBTENCT@EP2205A", "last_done": "1.14", "change_rate": "0", "change_val": "0", "turnover": "0", "expiry_date": "20220518", "strike_price": "445.223", "upper_strike_price": "0", "lower_strike_price": "0", "outstanding_qty": "80000", "outstanding_ratio": "0.0004", "premium": "0.010810703725606", "itm_otm": "0.24038066317328624", "implied_volatility": "0.5997", "delta": "-0.7964", "call_price": "0", "effective_leverage": "-2.4335424241487873", "leverage_ratio": "3.055678583813144", "conversion_ratio": "97.087", "balance_point": "334.54382000000004", "status": 4 } ], "total_count": 1197 } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ---------------------------- | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Too many symbols in one page | Reduce the number of symbols in a page of request | #### Basic Information of Securities This API is used to obtain the basic information of securities. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.static_info](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.static_info) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `10` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python # Get Basic Information Of Securities # https://open.longportapp.com/docs/quote/pull/static # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | -------------------- | -------- | ---------------------------------------------------------------------------------------------------- | | secu_static_info | object[] | Securities Basic Information | | ∟ symbol | string | Security code | | ∟ name_cn | string | Security name (zh-CN) | | ∟ name_en | string | Security name (en) | | ∟ name_hk | string | Security name (zh-HK) | | ∟ exchange | string | Exchange which the security belongs to | | ∟ currency | string | Trading currency

**Optional value: **
`CNY`
`USD`
`SGD`
`HKD` | | ∟ lot_size | int32 | Lot size | | ∟ total_shares | int64 | Total shares | | ∟ circulating_shares | int64 | Circulating shares | | ∟ hk_shares | int64 | HK shares (only HK stocks) | | ∟ eps | string | Earnings per share | | ∟ eps_ttm | string | Earnings per share (TTM) | | ∟ bps | string | Net assets per share | | ∟ dividend_yield | string | Dividend yield | | ∟ stock_derivatives | int32[] | Types of supported derivatives

**Optional value:**
`1` - Option
`2` - Warrant | | ∟ board | string | The board to whitch the security belongs, see [Board](../objects#board---security-board) for details | ### Protobuf ```protobuf message SecurityStaticInfoResponse { repeated StaticInfo secu_static_info = 1; } message StaticInfo { string symbol = 1; string name_cn = 2; string name_en = 3; string name_hk = 4; string listing_date = 5; string exchange = 6; string currency = 7; int32 lot_size = 8; int64 total_shares = 9; int64 circulating_shares = 10; int64 hk_shares = 11; string eps = 12; string eps_ttm = 13; string bps = 14; string dividend_yield = 15; repeated int32 stock_derivatives = 16; string board = 17; } ``` ### Response JSON Example ```json { "secu_static_info": [ { "symbol": "700.HK", "name_cn": "腾讯控股", "name_en": "TENCENT", "name_hk": "騰訊控股", "exchange": "SEHK", "currency": "HKD", "lot_size": 100, "total_shares": 9612464038, "circulating_shares": 9612464038, "hk_shares": 9612464038, "eps": "28.4394", "eps_ttm": "28.4394", "bps": "103.40413", "dividend_yield": "1.6", "stock_derivatives": [2], "board": "HKEquity" }, { "symbol": "AAPL.US", "name_cn": "苹果", "name_en": "Apple Inc.", "exchange": "NASD", "currency": "USD", "lot_size": 1, "total_shares": 1631944100, "circulating_shares": 16302661350, "eps": "5.669", "eps_ttm": "6.0771", "bps": "4.40197", "dividend_yield": "0.85", "stock_derivatives": [1], "board": "USMain" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Real-time Quotes Of Securities This API is used to obtain the real-time quotes of securities, and supports all types of securities. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.quote](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.quote) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `11` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python # Get Real-time Quotes Of Securities # https://open.longportapp.com/docs/quote/pull/quote # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | ------------------- | -------- | ------------------------------------------------------------------------------------ | | secu_quote | object[] | Securities quote | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ prev_close | string | Yesterday's close | | ∟ open | string | Open | | ∟ high | string | High | | ∟ low | string | Low | | ∟ timestamp | int64 | Time of latest price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) | | ∟ pre_market_quote | object | Quote of US pre market | | ∟∟ last_done | string | Latest price | | ∟∟ timestamp | int64 | Time of latest price | | ∟∟ volume | int64 | Volume | | ∟∟ turnover | string | Turnover | | ∟∟ high | string | High | | ∟∟ low | string | Low | | ∟∟ prev_close | string | Close of the last trade session | | ∟ post_market_quote | object | Quote of US post market | | ∟∟ last_done | string | Latest price | | ∟∟ timestamp | int64 | Time of latest price | | ∟∟ volume | int64 | Volume | | ∟∟ turnover | string | Turnover | | ∟∟ high | string | High | | ∟∟ low | string | Low | | ∟∟ prev_close | string | Close of the last trade session | | ∟ over_night_quote | object | Quote of US overnight market | | ∟∟ last_done | string | Latest price | | ∟∟ timestamp | int64 | Time of latest price | | ∟∟ volume | int64 | Volume | | ∟∟ turnover | string | Turnover | | ∟∟ high | string | High | | ∟∟ low | string | Low | | ∟∟ prev_close | string | Close of the last trade session | ### Protobuf ```protobuf message SecurityQuoteResponse { repeated SecurityQuote secu_quote = 1; } message SecurityQuote { string symbol = 1; string last_done = 2; string prev_close = 3; string open = 4; string high = 5; string low = 6; int64 timestamp = 7; int64 volume = 8; string turnover = 9; TradeStatus trade_status = 10; PrePostQuote pre_market_quote = 11; PrePostQuote post_market_quote = 12; } message PrePostQuote { string last_done = 1; int64 timestamp = 2; int64 volume = 3; string turnover = 4; string high = 5; string low = 6; string prev_close = 7; } ``` ### Response JSON Example ```json { "secu_quote": [ { "symbol": "700.HK", "last_done": "338.000", "prev_close": "334.800", "open": "340.600", "high": "340.600", "low": "333.000", "timestamp": 1651115955, "volume": 7310881, "turnover": "2461463161.000" }, { "symbol": "AAPL.US", "last_done": "156.570", "prev_close": "156.800", "open": "155.910", "high": "159.790", "low": "155.380", "timestamp": 1651089600, "volume": 88063191, "turnover": "13865092584.000", "pre_market_quote": { "last_done": "155.880", "timestamp": 1651066201, "volume": 1575504, "turnover": "246653442.000", "high": "158.400", "low": "155.100", "prev_close": "156.800" }, "post_market_quote": { "last_done": "158.770", "timestamp": 1651103995, "volume": 6188441, "turnover": "970874184.759", "high": "159.400", "low": "156.400", "prev_close": "156.570" } } ] } ``` ## API Restrictions :::caution - The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP. ::: ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Warrant Issuer IDs This API is used to obtain the warrant issuer IDs data (which can be synchronized once a day). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.warrant_issuers](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.warrant_issuers) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `22` ::: ## Request ### Request Example ```python # Get Warrant Issuer IDs # https://open.longportapp.com/docs/quote/pull/issuer # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.warrant_issuers() print(resp) ``` ## Response ### Parameters | Name | Type | Description | | ----------- | -------- | ------------------- | | issuer_info | object[] | Issuer information | | ∟ id | int32 | Issuer ID | | ∟ name_cn | string | Issuer Name (zh-CN) | | ∟ name_en | string | Issuer Name (en) | | ∟ name_hk | string | Issuer Name (zh-HK) | ### Protobuf ```protobuf message IssuerInfoResponse { repeated IssuerInfo issuer_info = 1; } message IssuerInfo { int32 id = 1; string name_cn = 2; string name_en = 3; string name_hk = 4; } ``` ### Response JSON Example ```json { "issuer_info": [ { "id": 15, "name_cn": "瑞银", "name_en": "UB", "name_hk": "瑞銀" }, { "id": 14, "name_cn": "汇丰", "name_en": "HS", "name_hk": "滙豐" }, { "id": 12, "name_cn": "花旗", "name_en": "CT", "name_hk": "花旗" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | #### Option Chain By Date This API is used to obtain a list of option securities by the option chain expiry date. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_chain_info_by_date](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_chain_info_by_date) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `21` ::: ## Request ### Parameters | Name | Type | Required | Description | | ----------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | expiry_date | string | Yes | Option expiry date,in `YYMMDD` format, for example: `20220429`, obtained by [Option Expiry Date](./optionchain_date.md) API | ### Protobuf ```protobuf message OptionChainDateStrikeInfoRequest { string symbol = 1; string expiry_date = 2; } ``` ### Request Example ```python # Get Option Chain Info By Date # https://open.longportapp.com/docs/quote/pull/optionchain-date-strike # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from datetime import date from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.option_chain_info_by_date("AAPL.US", date(2023, 1, 20)) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | ----------------- | -------- | ---------------------------- | | strike_price_info | object[] | Option security info | | ∟ price | string | Strike price | | ∟ call_symbol | string | Security code of call option | | ∟ put_symbol | string | Security code of put option | | ∟ standard | bool | Is standard | ### Protobuf ```protobuf message OptionChainDateStrikeInfoResponse { repeated StrikePriceInfo strike_price_info = 1; } message StrikePriceInfo { string price = 1; string call_symbol = 2; string put_symbol = 3; bool standard = 4; } ``` ### Response JSON Example ```json { "strike_price_info": [ { "price": "100", "call_symbol": "AAPL220429C100000.US", "put_symbol": "AAPL220429P100000.US", "standard": true }, { "price": "105", "call_symbol": "AAPL220429C105000.US", "put_symbol": "AAPL220429P105000.US", "standard": true }, { "price": "110", "call_symbol": "AAPL220429C110000.US", "put_symbol": "AAPL220429P110000.US", "standard": true }, { "price": "115", "call_symbol": "AAPL220429C115000.US", "put_symbol": "AAPL220429P115000.US", "standard": true } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`,`expiry_date` | #### Security Capital Distribution This API is used to obtain the daily capital distribution of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.capital_distribution](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.capital_distribution) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command):`25` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | --------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python # Get Security Capital Distribution # https://open.longportapp.com/docs/quote/pull/capital-distribution # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | -------------------- | | symbol | string | Security code | | timestamp | int64 | Data update time | | capital_in | object[] | Inflow capital data | | ∟ large | string | large order | | ∟ medium | string | medium order | | ∟ small | string | small order | | capital_out | object[] | Outflow capital data | | ∟ large | string | large order | | ∟ medium | string | medium order | | ∟ small | string | small order | ### Protobuf ```protobuf message CapitalDistributionResponse { message CapitalDistribution { string large = 1; string medium = 2; string small = 3; } string symbol = 1; int64 timestamp = 2; CapitalDistribution capital_in = 3; CapitalDistribution capital_out = 4; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "timestamp": "1655107800", "capital_in": { "large": "935389700.000", "medium": "2056032380.000", "small": "828715920.000" }, "capital_out": { "large": "1175331560.000", "medium": "2271829740.000", "small": "751648940.000" } } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Real-time Quotes of Option This API is used to obtain the real-time quotes of US stock options, including the option-specific data. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_quote](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_quote) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `12` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | symbol | string[] | Yes | Security code list. obtain the symbol of the options through the [optionchain](./optionchain-date-strike.md) API, for example: `[BABA230120C160000.US]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python # Get Real-time Quotes Of Option Securities # https://open.longportapp.com/docs/quote/pull/option-quote # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.option_quote(["AAPL230317P160000.US"]) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | ------------------------ | -------- | ------------------------------------------------------------------------------------ | | secu_quote | object[] | Options quote | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ prev_close | string | Yesterday's close | | ∟ open | string | Open | | ∟ high | string | High | | ∟ low | string | Low | | ∟ timestamp | int64 | Time of latest price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) | | ∟ option_extend | object | Option extend quote | | ∟∟ implied_volatility | string | Implied volatility | | ∟∟ open_interest | int64 | Number of open positions | | ∟∟ expiry_date | string | Exprity date, in `YYMMDD` format | | ∟∟ strike_price | string | Strike price | | ∟∟ contract_multiplier | string | Contract multiplier | | ∟∟ contract_type | string | Option type

**Optional value:**
`A` - American
`U` - Europe | | ∟∟ contract_size | string | Contract size | | ∟∟ direction | string | Direction

**Optional value:**
`P` - put
`C` - call | | ∟∟ historical_volatility | string | Underlying security historical volatility of the optionn | | ∟∟ underlying_symbol | string | Underlying security symbol of the option | ### Protobuf ```protobuf message OptionQuoteResponse { repeated OptionQuote secu_quote = 1; } message OptionQuote { string symbol = 1; string last_done = 2; string prev_close = 3; string open = 4; string high = 5; string low = 6; int64 timestamp = 7; int64 volume = 8; string turnover = 9; TradeStatus trade_status = 10; OptionExtend option_extend = 11; } message OptionExtend { string implied_volatility = 1; int64 open_interest = 2; string expiry_date = 3; string strike_price = 4; string contract_multiplier = 5; string contract_type = 6; string contract_size = 7; string direction = 8; string historical_volatility = 9; string underlying_symbol = 10; } ``` ### Response JSON Example ```json { "secu_quote": [ { "symbol": "AAPL220429P162500.US", "last_done": "7.78", "prev_close": "4.13", "open": "4.43", "high": "7.80", "low": "4.43", "timestamp": 1651003200, "volume": 3082, "turnover": "1813434.00", "option_extend": { "implied_volatility": "0.592", "open_interest": 11463, "expiry_date": "20220429", "strike_price": "162.50", "contract_multiplier": "100", "contract_type": "A", "contract_size": "100", "direction": "P", "historical_volatility": "0.2750", "underlying_symbol": "AAPL.US" } }, { "symbol": "AAPL220429C150000.US", "last_done": "9.25", "prev_close": "13.87", "open": "13.80", "high": "13.80", "low": "9.15", "timestamp": 1651003200, "volume": 413, "turnover": "436835.00", "option_extend": { "implied_volatility": "0.702", "open_interest": 800, "expiry_date": "20220429", "strike_price": "150.00", "contract_multiplier": "100", "contract_type": "A", "contract_size": "100", "direction": "C", "historical_volatility": "0.2750", "underlying_symbol": "AAPL.US" } } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Security Intraday This API is used to obtain the intraday data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.intraday](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.intraday) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `18` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | ### Protobuf ```protobuf message SecurityIntradayRequest { string symbol = 1; } ``` ### Request Example ```python # Get Security Intraday # https://open.longportapp.com/docs/quote/pull/intraday # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.intraday("700.HK") print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | ------------------------------------- | | symbol | string | Security code, for example: `AAPL.US` | | lines | object[] | Intraday line data | | ∟ price | string | Close price of the minute | | ∟ timestamp | int64 | Start time stamp of the minute | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ avg_price | string | Average price | ### Protobuf ``` message SecurityIntradayResponse{ string symbol = 1; repeated Line lines = 2; } message Line { string price = 1; int64 timestamp = 2; int64 volume = 3; string turnover = 4; string avg_price = 5; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "lines": [ { "price": "330.400", "timestamp": 1651023000, "volume": 375870, "turnover": "123949699.000", "avg_price": "329.767470" }, { "price": "331.200", "timestamp": 1651023060, "volume": 233095, "turnover": "77269032.800", "avg_price": "330.427416" }, { "price": "330.400", "timestamp": 1651023120, "volume": 192565, "turnover": "63711556.000", "avg_price": "330.530719" }, { "price": "330.800", "timestamp": 1651023180, "volume": 143397, "turnover": "47471072.400", "avg_price": "330.608989" }, { "price": "330.800", "timestamp": 1651023240, "volume": 141834, "turnover": "46890605.600", "avg_price": "330.608078" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Historical Market Temperature This interface is used to get historical market temperature. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.history_market_temperature](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.history_market_temperature) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodGET
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 longport.openapi import QuoteContext, Config, Market config = Config.from_env() ctx = QuoteContext(config) resp = ctx.history_market_temperature(Market.US, datetime.date(2024, 1, 1), datetime.date(2025, 1, 1)) print(resp) ``` ## 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 | #### Security Capital Flow Intraday This API is used to obtain the daily capital flow intraday of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.capital_flow](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.capital_flow) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command):`24` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | --------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` | ### Protobuf ```protobuf message CapitalFlowIntradayRequest { string symbol = 1; } ``` ### Request Example ```python # Get Security Capital Flow Intraday # https://open.longportapp.com/docs/quote/pull/capital-flow-intraday # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. ``` ## Response ### Response Properties | Name | Type | Description | | ------------------ | -------- | ------------------------------ | | symbol | string | Security code | | capital_flow_lines | object[] | Capital flow data | | ∟ inflow | string | Inflow capital data | | ∟ timestamp | int64 | Start time stamp of the minute | ### Protobuf ```protobuf message CapitalFlowIntradayResponse { message CapitalFlowLine { string inflow = 1; int64 timestamp = 2; } string symbol = 1; repeated CapitalFlowLine capital_flow_lines = 2; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "capital_flow_lines": [ { "inflow": "-310255860.000", "timestamp": "1655106960" }, { "inflow": "-314011220.000", "timestamp": "1655107020" }, { "inflow": "-314011220.000", "timestamp": "1655107080" }, { "inflow": "-314011220.000", "timestamp": "1655107140" }, { "inflow": "-314011220.000", "timestamp": "1655107200" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | #### Broker IDs This API is used to obtain participant IDs data (which can be synchronized once a day). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.participants](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.participants) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `16` ::: ## Request ### Request Example ```python # Get Broker IDs # https://open.longportapp.com/docs/quote/pull/broker-ids # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.participants() print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | -------------------------- | -------- | ------------------------ | | participant_broker_numbers | object[] | participant data | | ∟ broker_ids | int32[] | broker IDs | | ∟ participant_name_cn | string | participant name (zh-CN) | | ∟ participant_name_en | string | participant name (en) | | ∟ participant_name_hk | string | participant name (zh-HK) | ### Protobuf ```protobuf message ParticipantBrokerIdsResponse { repeated ParticipantInfo participant_broker_numbers = 1; } message ParticipantInfo { repeated int32 broker_ids = 1; string participant_name_cn = 2; string participant_name_en = 3; string participant_name_hk = 4; } ``` ### Response JSON Example ```json { "participant_broker_numbers": [ { "broker_ids": [7738, 7739], "participant_name_cn": "华兴金融 (香港)", "participant_name_en": "China Renaissance(HK)", "participant_name_hk": "華興金融 (香港)" }, { "broker_ids": [6390, 6396, 6398, 6399], "participant_name_cn": "国信 (香港)", "participant_name_en": "Guosen(HK)", "participant_name_hk": "國信 (香港)" }, { "broker_ids": [3168, 3169], "participant_name_cn": "泰嘉", "participant_name_en": "Tiger", "participant_name_hk": "泰嘉" } ] } ``` ## Error Code | Proto Error Code | Business Error Code | Descrption | Troubleshooting Suggestions | | ---------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | #### Short Positions (US & HK) # Short Positions (US & HK) Get short interest data for US or HK securities. Market is auto-detected from the symbol suffix: `.HK` → HKEX short position data (daily); others → US FINRA short interest data (bi-monthly). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.short_positions](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.short_positions) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ------ | ------- | -------- | ----------------------------------------------------------------- | | symbol | string | YES | Security symbol, e.g. `TSLA.US` or `700.HK` | | count | integer | NO | Number of records to return (1–100, default: 20) | ## Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) # US example resp = ctx.short_positions("TSLA.US", 20) print(resp) # HK example resp = ctx.short_positions("700.HK", 20) print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) # US example resp = await ctx.short_positions("TSLA.US", 20) print(resp) # HK example resp = await ctx.short_positions("700.HK", 20) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.shortPositions('TSLA.US', 20) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { var resp = ctx.getShortPositions("TSLA.US", 20).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.short_positions("TSLA.US", 20).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::quote; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); QuoteContext ctx = QuoteContext::create(config); ctx.short_positions("TSLA.US", 20, [](auto resp) { if (resp) std::cout << resp->size() << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() resp, err := qctx.ShortPositions(context.Background(), "TSLA.US", 20) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": [ { "timestamp": "2022-03-15T04:00:00Z", "current_shares_short": "111286790", "avg_daily_share_volume": "95077016", "days_to_cover": "1.17", "rate": "0.0068", "close": "" } ] } ``` ```json { "code": 0, "message": "success", "data": [ { "timestamp": "2024-06-13T16:00:00Z", "amount": "53677721", "balance": "20386798436", "cost": "379.800", "rate": "0.0057" } ] } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | See schemas below | | 400 | Bad request | None | ## Schemas ### US Response (`.US` symbols) | Name | Type | Required | Description | | ------------------------ | -------- | -------- | ---------------------------------------------- | | data | object[] | false | Short position records | | ∟ timestamp | string | false | Settlement date (RFC 3339, e.g. `2022-03-15T04:00:00Z`) | | ∟ current_shares_short | string | false | Number of shares sold short | | ∟ avg_daily_share_volume | string | false | Average daily share volume | | ∟ days_to_cover | string | false | Days to cover (short shares ÷ avg daily vol) | | ∟ rate | string | false | Short ratio | | ∟ close | string | false | Closing price for the day | ### HK Response (`.HK` symbols) | Name | Type | Required | Description | | ----------- | -------- | -------- | ----------------------------------------- | | data | object[] | false | Short position records | | ∟ timestamp | string | false | Trade date (RFC 3339, e.g. `2022-03-15T04:00:00Z`) | | ∟ amount | string | false | Short selling amount (HKD) | | ∟ balance | string | false | Short position balance | | ∟ cost | string | false | Closing price for the day | | ∟ rate | string | false | Short ratio | #### Security Candlesticks This API is used to obtain the candlestick data of security. :::info Note: This interface can only retrieve the last 1000 candlesticks. To obtain longer historical data, please visit the interface: Get Security History Candlesticks. ::: ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.candlesticks](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.candlesticks) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `19` ::: ## Request ### Parameters | Name | Type | Required | Description | |---------------|--------|----------|----------------------------------------------------------------------------------------------------------| | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | period | int32 | Yes | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period) | | count | int32 | Yes | Count of cancdlestick, for example: `100`

**Check rules:**
maximum count is `1000` | | adjust_type | int32 | Yes | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type) | | trade_session | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight) | ### Protobuf ```protobuf message SecurityCandlestickRequest { string symbol = 1; Period period = 2; int32 count = 3; AdjustType adjust_type = 4; int32 trade_session = 5; } ``` ### Request Example ```python # Get Security Candlesticks # https://open.longportapp.com/docs/quote/pull/candlestick # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config, Period, AdjustType, TradeSessions config = Config.from_env() ctx = QuoteContext(config) # Get intraday candlestick data for 700.HK resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust) print(resp) # Get all candlestick data for 700.HK resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, trade_session=TradeSessions.All) ``` ## Response ### Response Properties | Name | Type | Description | |-----------------|----------|------------------------------------------------------------------------------| | symbol | string | Security code, for example: `AAPL.US` | | candlesticks | object[] | Candlestick data | | ∟ close | string | Close price | | ∟ open | string | Open price | | ∟ low | string | Low price | | ∟ high | string | High price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ timestamp | int64 | Timestamp | | ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | ### Protobuf ```protobuf message SecurityCandlestickResponse { string symbol = 1; repeated Candlestick candlesticks = 2; } message Candlestick { string close = 1; string open = 2; string low = 3; string high = 4; int64 volume = 5; string turnover = 6; int64 timestamp = 7; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "candlesticks": [ { "close": "362.000", "open": "364.600", "low": "361.600", "high": "368.800", "volume": 10853604, "turnover": "3954556819.000", "timestamp": 1650384000 }, { "close": "348.000", "open": "352.000", "low": "343.000", "high": "356.200", "volume": 25738562, "turnover": "8981529950.000", "timestamp": 1650470400 }, { "close": "340.600", "open": "334.800", "low": "334.200", "high": "343.000", "volume": 28031299, "turnover": "9492674293.000", "timestamp": 1650556800 }, { "close": "327.400", "open": "332.200", "low": "325.200", "high": "338.600", "volume": 25788422, "turnover": "8541441823.000", "timestamp": 1650816000 }, { "close": "335.800", "open": "332.200", "low": "330.600", "high": "341.600", "volume": 27288328, "turnover": "9166022626.000", "timestamp": 1650902400 } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | |---------------------|---------------------|--------------------------------|--------------------------------------------------------------------------------| | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period` | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Too many candlesticks requeted | Reduce the amount of candlestick in each request | #### Real-time Quotes of Warrant This API is used to obtain the real-time quotes of HK warrants, including the warrant-specific data. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.warrant_quote](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.warrant_quote) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `13` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[13447.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | ### Protobuf ```protobuf message MultiSecurityRequest { repeated string symbol = 1; } ``` ### Request Example ```python # Get Real-time Quotes Of Warrant Securities # https://open.longportapp.com/docs/quote/pull/warrant-quote # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.warrant_quote(["21125.HK"]) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | --------------------- | -------- | -------------------------------------------------------------------------------------------------------------- | | secu_quote | object[] | Warrants quote | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ prev_close | string | Yesterday's close | | ∟ open | string | Open | | ∟ high | string | High | | ∟ low | string | Low | | ∟ timestamp | int64 | Time of latest price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) | | ∟ warrant_extend | object | Warrant extend quote | | ∟∟ implied_volatility | string | Implied volatility | | ∟∟ expiry_date | string | Exprity date, in `YYMMDD` format | | ∟∟ last_trade_date | string | Last tradalbe date, in `YYMMDD` format | | ∟∟ outstanding_ratio | string | Outstanding ratio | | ∟∟ outstanding_qty | int64 | Outstanding quantity | | ∟∟ conversion_ratio | string | Conversion ratio | | ∟∟ category | string | Warrant type

**Optional value: **
`Call`
`Put`
`Bull`
`Bear`
`Inline` | | ∟∟ strike_price | string | Strike price | | ∟∟ upper_strike_price | string | Upper bound price | | ∟∟ lower_strike_price | string | Lower bound price | | ∟∟ call_price | string | Call price | | ∟∟ underlying_symbol | string | Underlying security symbol of the option | ### Protobuf ```protobuf message WarrantQuoteResponse { repeated WarrantQuote secu_quote = 2; } message WarrantQuote { string symbol = 1; string last_done = 2; string prev_close = 3; string open = 4; string high = 5; string low = 6; int64 timestamp = 7; int64 volume = 8; string turnover = 9; TradeStatus trade_status = 10; WarrantExtend warrant_extend = 11; } message WarrantExtend { string implied_volatility = 1; string expiry_date = 2; string last_trade_date = 3; string outstanding_ratio = 4; int64 outstanding_qty = 5; string conversion_ratio = 6; string category = 7; string strike_price = 8; string upper_strike_price = 9; string lower_strike_price = 10; string call_price = 11; string underlying_symbol = 12; } ``` ### Response JSON Example ```json { "secu_quote": [ { "symbol": "66642.HK", "last_done": "0.345", "prev_close": "0.365", "open": "0.345", "high": "0.345", "low": "0.345", "timestamp": 1651130421, "volume": 200000, "turnover": "69000.000", "warrant_extend": { "implied_volatility": "0.319", "expiry_date": "20220830", "last_trade_date": "20220829", "outstanding_ratio": "0.0001", "outstanding_qty": 20000, "conversion_ratio": "10000", "category": "Bear", "strike_price": "23200.000", "upper_strike_price": "0.000", "lower_strike_price": "0.000", "call_price": "23100.000", "underlying_symbol": "HSI.HK" } }, { "symbol": "14993.HK", "last_done": "0.073", "prev_close": "0.066", "open": "0.069", "high": "0.076", "low": "0.069", "timestamp": 1651130930, "volume": 320825000, "turnover": "23401125.000", "warrant_extend": { "implied_volatility": "0.404", "expiry_date": "20220927", "last_trade_date": "20220921", "outstanding_ratio": "0.0247", "outstanding_qty": 2465000, "conversion_ratio": "10", "category": "Call", "strike_price": "70.050", "upper_strike_price": "0.000", "lower_strike_price": "0.000", "call_price": "0.000", "underlying_symbol": "2318.HK" } } ] } ``` ## API Restrictions :::caution - The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP. ::: ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Trading Session of The Day This API is used to obtain the daily trading hours of each market. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.trading_session](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.trading_session) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `8` ::: ## Request ### Request Example ```python # Get Trading Session Of The Day # https://open.longportapp.com/docs/quote/pull/trade-session # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.trading_session() print(resp) ``` ## 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 | #### Security History Candlesticks This API is used to obtain the history candlestick data of security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.history_candlesticks_by_offset](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.history_candlesticks_by_offset) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command):`27` ::: ## Request ### Parameters | Name | Type | Required | Description | |----------------|--------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | | period | int32 | Yes | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period) | | adjust_type | int32 | Yes | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type) | | query_type | int32 | Yes | Type of query

**Optional value:**
`1` - query by offset
`2` - query by date | | date_request | object | No | Required when querying by date | | ∟ start_date | string | No | Date of query begin, in `YYYYMMDD` format, for example: 20231016

**Parameter description:**
1. Leave both start_date and end_date blank: return the latest 1000 candlesticks;
2. Fill only start_date: return the candlesticks between start_date and the latest trading day. If there are more than 1000 candlesticks in this interval, the candlesticks close to start_date will be returned first;
3. Fill in only end_date: return end_date and the previous 1000 candlesticks;
4. Fill in both start_date and end_date: return candlesticks data within this interval. If there are more than 1000 candlesticks in the interval, the candlesticks close to end_date will be returned first. | | ∟ end_date | string | No | Date of query end, in `YYYYMMDD` format, for example: 20231016 | | offset_request | object | No | Required when querying by offset | | ∟ direction | int32 | Yes | Query direction

**Optional value:**
`0` - query in the direction of historical data
`1` - query in the direction of latest data | | ∟ date | string | No | Query date, in `YYYYMMDD` format, for example: 20231016. Default value: latest trading day of the underlying market. | | ∟ minute | string | No | Query time, in `HHMM` format, for example: 09:35, only valid when querying minute-level data | | ∟ count | int32 | No | Count of cancdlestick, valid range:`[1,1000]`. Default value: `10` | | trade_session | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight) | ### Protobuf ```protobuf message SecurityHistoryCandlestickRequest { message OffsetQuery { Direction direction = 1; string date = 2; string minute = 3; int32 count = 4; } message DateQuery { string start_date = 1; string end_date = 2; } string symbol = 1; Period period = 2; AdjustType adjust_type = 3; HistoryCandlestickQueryType query_type = 4; OffsetQuery offset_request = 5; DateQuery date_request = 6; } ``` ### Request Example ```python # Get Security History Candlesticks # https://open.longportapp.com/docs/quote/pull/candlestick # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from datetime import datetime, date from longport.openapi import QuoteContext, Config, Period, AdjustType config = Config.from_env() ctx = QuoteContext(config) # Query after 2023-01-01 resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, True, 10, datetime(2023, 1, 1)) print(resp) # Query before 2023-01-01 resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, False, 10, datetime(2023, 1, 1)) print(resp) # Query 2023-01-01 to 2023-02-01 resp = ctx.history_candlesticks_by_date("700.HK", Period.Day, AdjustType.NoAdjust, date(2023, 1, 1), date(2023, 2, 1)) print(resp) ``` ## Response ### Response Properties | Name | Type | Description | |-----------------|----------|------------------------------------------------------------------------------| | symbol | string | Security code, for example: `AAPL.US` | | candlesticks | object[] | Candlestick data | | ∟ close | string | Close price | | ∟ open | string | Open price | | ∟ low | string | Low price | | ∟ high | string | High price | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ timestamp | int64 | Timestamp | | ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) | ### Protobuf ```protobuf message SecurityCandlestickResponse { string symbol = 1; repeated Candlestick candlesticks = 2; } message Candlestick { string close = 1; string open = 2; string low = 3; string high = 4; int64 volume = 5; string turnover = 6; int64 timestamp = 7; } ``` ### Response JSON Example ```json { "symbol": "700.HK", "candlesticks": [ { "close": "362.000", "open": "364.600", "low": "361.600", "high": "368.800", "volume": 10853604, "turnover": "3954556819.000", "timestamp": 1650384000 }, { "close": "348.000", "open": "352.000", "low": "343.000", "high": "356.200", "volume": 25738562, "turnover": "8981529950.000", "timestamp": 1650470400 }, { "close": "340.600", "open": "334.800", "low": "334.200", "high": "343.000", "volume": 28031299, "turnover": "9492674293.000", "timestamp": 1650556800 }, { "close": "327.400", "open": "332.200", "low": "325.200", "high": "338.600", "volume": 25788422, "turnover": "8541441823.000", "timestamp": 1650816000 }, { "close": "335.800", "open": "332.200", "low": "330.600", "high": "341.600", "volume": 27288328, "turnover": "9166022626.000", "timestamp": 1650902400 } ] } ``` ## Permission description According to the user’s assets and transactions, the number of targets that different types of users can query historical data on each month is as follows: - The quota is calculated based on the natural month. The quota is topped up at the beginning of each month. The remaining quota from the previous month will not be accumulated to this month. If you repeatedly request the historical K-line of the same target within a natural month, it will only be counted once. - For newly deposited accounts, the limit will automatically take effect on the next trading day; when the account's total assets or number of transactions increase and reaches a higher level, the limit will take effect on the next trading day. - Total assets: The total assets of the user's Hong Kong stocks, U.S. stocks, A-shares and other securities accounts are converted into Hong Kong dollars according to the exchange rate. Take the larger value of the user's total assets on the last trading day of the previous calendar month and the total assets on the most recent complete trading day. - Number of transactions per month: The number of orders that the user has completed. Partial completion of one order, complete completion of multiple transactions, or all transactions at one time are counted as 1 transaction. Take the larger value of the user's number of transactions in the last natural month and the number of transactions in the current natural month.
User Type The maximum number of targets that can be queried per month
User account opening
100
Total assets reach HKD 10,000
400
Total assets reach HKD 80,000
600
Total assets reach 400,000 HKD or the number of transactions per month is greater than 160
1000
Total assets reach 4 million HKD or the number of transactions per month is greater than 1,600
2000
Total assets reach 6 million HKD or the number of transactions per month is greater than 2,500
3000
## Description of historical candlesticks range | Market | Daily/Weekly/Monthly/Year period candlesticks | Minute candlesticks | Description | |--------------------|-----------------------------------------------|-----------------------|-------------------------------------------------------------------------------------------------------------------| | Hong Kong stocks | 2004-6-1 to present | 2022-09-28 to present | | | U.S. stocks | 2010-6-1 to present | 2023-12-4 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 | | A shares | 1999-11-1 to present | 2022-08-25 to present | | ## Rate limite :::caution - The api can be requested up to 60 times every 30 seconds. ::: ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | |---------------------|---------------------|----------------------------|-------------------------------------------------------------------------------------------| | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period` | | 7 | 301603 | No quotes | Security no quote | | 7 | 301604 | No access | No access to security quote | | 7 | 301607 | Permission limit | Exceeds the upper limit of the number of targets that can be queried in the current month | #### Option Chain Expiry Date List This API is used to obtain the the list of expiration dates of option chain ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.option_chain_expiry_date_list](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.option_chain_expiry_date_list) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz-command): `20` ::: ## Request ### Parameters | Name | Type | Required | Description | | ------ | ------ | -------- | -------------------------------------------------------------- | | symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` | ### Protobuf ```protobuf message SecurityRequest { string symbol = 1; } ``` ### Request Example ```python # Get Option Chain Expiry Date List # https://open.longportapp.com/docs/quote/pull/optionchain-date # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.option_chain_expiry_date_list("AAPL.US") print(resp) ``` ## Response ### Response Properties | Name | Type | Description | | ----------- | -------- | -------------------------------------------------- | | expiry_date | string[] | option chain expiry dates list,in `YYMMDD` format | ### Protobuf ```protobuf message OptionChainDateListResponse { repeated string expiry_date = 1; } ``` ### Response JSON Example ```json { "expiry_date": [ "20220422", "20220429", "20220506", "20220513", "20220520", "20220527", "20220603", "20220617", "20220715", "20220819", "20220916", "20221021", "20221118", "20230120", "20230317", "20230616", "20230915", "20240119", "20240621" ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct | #### Market Trading Days This API is used to obtain the trading days of the market. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.trading_days](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.trading_days) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::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 # Get Market Trading Days # https://open.longportapp.com/docs/quote/pull/trade-day # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from datetime import date from longport.openapi import QuoteContext, Config, Market config = Config.from_env() ctx = QuoteContext(config) resp = ctx.trading_days(Market.HK, date(2022, 1, 1), date(2022, 2, 1)) print(resp) ``` ## 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` | #### Calculate Indexes Of Securities This API is used to obtain the calculate indexes of securities. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.calc_indexes](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.calc_indexes) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | | Java | [quote.getQuoteContext](https://longportapp.github.io/openapi/java/com/longport//quote.html#CalcIndex) | :::info [Business Command](../../socket/biz-command):`26` ::: ## Request ### Parameters | Name | Type | Required | Description | | ---------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | symbols | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`

**Check rules:**
The maximum number of symbols in each request is `500` | | calc_index | init32[] | Yes | Calc indexes, for example: `[1,2,3]`, see [CalcIndex](../objects#calcindex---calculate-index) | ### Protobuf ```protobuf message SecurityCalcQuoteRequest { repeated string symbols = 1; repeated CalcIndex calc_index = 2; } ``` ### Request Example ```python # Get Security Calc Index # https://open.longportapp.com/docs/quote/pull/calc-index # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. ``` ## Response ### Response Properties | Name | Type | Description | | -------------------------- | -------- | ---------------------------------------------------------------------------------------- | | security_calc_index | object[] | Security Index Data | | ∟ symbol | string | Security code | | ∟ last_done | string | Latest price | | ∟ change_val | string | Change value | | ∟ change_rate | string | Change ratio (This field is a ratio field, not include symbol `%`) | | ∟ volume | int64 | Volume | | ∟ turnover | string | Turnover | | ∟ ytd_change_rate | string | Year-to-date change ratio (This field is a ratio field, not include symbol `%`) | | ∟ turnover_rate | string | Turnover rate (This field is a ratio field, not include symbol `%`) | | ∟ total_market_value | string | Total market value | | ∟ capital_flow | string | Capital flow | | ∟ amplitude | string | Amplitude (This field is a ratio field, not include symbol `%`) | | ∟ volume_ratio | string | Volume ratio | | ∟ pe_ttm_ratio | string | PE (TTM) | | ∟ pb_ratio | string | PB | | ∟ dividend_ratio_ttm | string | Dividend ratio (TTM) | | ∟ five_day_change_rate | string | Five days change ratio (This field is a ratio field, not include symbol `%`) | | ∟ ten_day_change_rate | string | Ten days change ratio (This field is a ratio field, not include symbol `%`) | | ∟ half_year_change_rate | string | Half year change ratio (This field is a ratio field, not include symbol `%`) | | ∟ five_minutes_change_rate | string | Five minutes change ratio (This field is a ratio field, not include symbol `%`) | | ∟ expiry_date | string | Expirt date | | ∟ strike_price | string | Strike price | | ∟ upper_strike_price | string | Upper bound price | | ∟ lower_strike_price | string | Lower bound price | | ∟ outstanding_qty | int64 | Outstanding quantity | | ∟ outstanding_ratio | string | Outstanding ratio (This field is a ratio field, not include symbol `%`) | | ∟ premium | string | Premium (This field is a ratio field, not include symbol `%`) | | ∟ itm_otm | string | In/out of the bound (This field is a ratio field, not include symbol `%`) | | ∟ implied_volatility | string | Implied volatility (This field is a ratio field, not include symbol `%`) | | ∟ warrant_delta | string | Warrant delta | | ∟ call_price | string | Call price | | ∟ to_call_price | string | Price interval from the call price (This field is a ratio field, not include symbol `%`) | | ∟ effective_leverage | string | Effective leverage | | ∟ leverage_ratio | string | Leverage ratio | | ∟ conversion_ratio | string | Conversion ratio | | ∟ balance_point | string | Breakeven point | | ∟ open_interest | int64 | Open interest | | ∟ delta | string | Delta | | ∟ gamma | string | Gamma | | ∟ theta | string | Theta | | ∟ vega | string | Vega | | ∟ rho | string | Rho | ### Protobuf ```protobuf message SecurityCalcIndex { string symbol = 1; string last_done = 2; string change_val = 3; string change_rate = 4; int64 volume = 5; string turnover = 6; string ytd_change_rate = 7; string turnover_rate = 8; string total_market_value = 9; string capital_flow = 10; string amplitude = 11; string volume_ratio = 12; string pe_ttm_ratio = 13; string pb_ratio = 14; string dividend_ratio_ttm = 15; string five_day_change_rate = 16; string ten_day_change_rate = 17; string half_year_change_rate = 18; string five_minutes_change_rate = 19; string expiry_date = 20; string strike_price = 21; string upper_strike_price = 22; string lower_strike_price = 23; int64 outstanding_qty = 24; string outstanding_ratio = 25; string premium = 26; string itm_otm = 27; string implied_volatility = 28; string warrant_delta = 29; string call_price = 30; string to_call_price = 31; string effective_leverage = 32; string leverage_ratio = 33; string conversion_ratio = 34; string balance_point = 35; int64 open_interest = 36; string delta = 37; string gamma = 38; string theta = 39; string vega = 40; string rho = 41; } message SecurityCalcQuoteResponse { repeated SecurityCalcIndex security_calc_index = 1; } ``` ### Response JSON Example ```json { "securityCalcIndex": [ { "symbol": "AAPL.US", "lastDone": "131.880", "changeVal": "-5.2500", "changeRate": "-3.83", "volume": "122207099", "turnover": "16269088361.000", "ytdChangeRate": "-25.63", "turnoverRate": "0.76", "totalMarketValue": "2134501670280.00", "capitalFlow": "14664053535.556", "amplitude": "2.74", "volumeRatio": "3.22", "peTtmRatio": "21.26", "pbRatio": "31.71", "dividendRatioTtm": "0.64", "fiveDayChangeRate": "-9.76", "tenDayChangeRate": "-11.87", "halfYearChangeRate": "-7.01", "fiveMinutesChangeRate": "0.00" }, { "symbol": "69672.HK", "lastDone": "0.010", "changeRate": "0.00", "expiryDate": "20221024", "strikePrice": "379.880", "outstandingQty": "6090000", "outstandingRatio": "7.61", "premium": "0.67", "itmOtm": "0.65", "callPrice": "375.880", "toCallPrice": "-100.00", "leverageRatio": "75.48", "balancePoint": "374.880" }, { "symbol": "AAPL220617C137000.US", "lastDone": "1.17", "changeVal": "-2.04", "changeRate": "-63.55", "volume": "23499", "turnover": "3903660.00", "expiryDate": "20220617", "strikePrice": "137.00", "premium": "11709.40", "impliedVolatility": "43.54", "openInterest": "5210", "delta": "0.263", "gamma": "0.043", "theta": "-1.266", "vega": "5.660", "rho": "0.580" }, { "symbol": "HSI.HK", "lastDone": "21119.650", "changeVal": "52.070", "changeRate": "0.25", "volume": "96449546281", "turnover": "96449546281.000", "ytdChangeRate": "-9.74", "amplitude": "1.86", "volumeRatio": "0.59", "fiveDayChangeRate": "-1.91", "tenDayChangeRate": "-0.02", "halfYearChangeRate": "-11.83", "fiveMinutesChangeRate": "0.00" } ] } ``` ## Error Code | Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions | | ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- | | 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed | | 3 | 301606 | Request rate limit | Reduce the frequency of requests | | 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue | | 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request | #### Daily Short Sale Volume Get daily short sale volume data for a security. Supports US stocks (FINRA/NASDAQ) and HK stocks (HKEX). US data is updated bi-weekly; HK data is updated each trading day. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.short_trades](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.short_trades) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ------ | ------- | -------- | --------------------------------------------------------------- | | symbol | string | YES | Security symbol; supports US (e.g. `TSLA.US`) and HK (e.g. `700.HK`) | | count | integer | NO | Number of records to return (1–100, default 20) | ## Request Example ```python from longport.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = QuoteContext(config) resp = ctx.short_trades("TSLA.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncQuoteContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncQuoteContext.create(config) resp = await ctx.short_trades("TSLA.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, QuoteContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = QuoteContext.new(config) const resp = await ctx.shortTrades('TSLA.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { var resp = ctx.getShortTrades("TSLA.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, quote::QuoteContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx.short_trades("TSLA.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::quote; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); QuoteContext ctx = QuoteContext::create(config); ctx.short_trades("TSLA.US", [](auto resp) { if (resp) std::cout << resp->size() << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } qctx, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer qctx.Close() resp, err := qctx.ShortTrades(context.Background(), "TSLA.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example US stocks (`.US` suffix): ```json { "code": 0, "message": "success", "data": [ { "timestamp": "2026-05-15T04:00:00Z", "nus_amount": "5748485", "ny_amount": "0", "total_amount": "15778974", "rate": "0.3643", "close": "300.230" } ] } ``` HK stocks (`.HK` suffix): ```json { "code": 0, "message": "success", "data": [ { "timestamp": "2026-05-17T16:00:00Z", "amount": "2926000", "balance": "1318056100.00", "total_amount": "29497076", "rate": "0.0992", "close": "449.2" } ] } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ShortTradesResponse](#ShortTradesResponse) | | 400 | Bad request | None | ## Schemas ### US Response (`.US` symbols) | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | data | object[] | false | Daily short trade volume records | | ∟ timestamp | string | false | Trading date (RFC 3339, e.g. `2026-05-15T04:00:00Z`) | | ∟ nus_amount | string | false | NASDAQ short sale volume (shares) | | ∟ ny_amount | string | false | NYSE short sale volume (shares) | | ∟ total_amount | string | false | Total trading volume for the day | | ∟ rate | string | false | Short ratio (short volume ÷ total volume) | | ∟ close | string | false | Closing price | ### HK Response (`.HK` symbols) | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | data | object[] | false | Daily short trade volume records | | ∟ timestamp | string | false | Trading date (RFC 3339, e.g. `2026-05-15T04:00:00Z`) | | ∟ amount | string | false | Short sale turnover amount (HKD) | | ∟ balance | string | false | Short position balance | | ∟ total_amount | string | false | Total trading turnover for the day | | ∟ rate | string | false | Short ratio (short turnover ÷ total turnover) | | ∟ close | string | false | Closing price | ### Screener ### Screener Search Filter stocks by strategy ID or custom indicator conditions, with pagination support. Endpoint: `POST /v1/quote/ai/screener/search` > **Note on JSON output format:** The response uses a flat `items[]` array (not `stocks[]`), all numeric fields are JSON numbers (not strings), and indicator keys do not carry the `filter_` prefix. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.screener._screener_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.screener._screener_context) | | Rust | [longport::::screener#_screener_context](https://longportapp.github.io/openapi/rust/longport//struct.screener.html#method._screener_context) | | Go | [screener.screener_search](https://pkg.go.dev/github.com/longportapp/openapi-go/#screener.screener_search) | | Node.js | [screener#ScreenerContext](https://longportapp.github.io/openapi/nodejs/classes/screener.html#screenercontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | market | string | YES | Market: `US`, `HK`, `CN`, `SG` | | strategy_id | integer | NO | Strategy ID; use alone or combined with custom conditions | | conditions | ScreenerCondition[] | NO | Custom filter conditions (Mode B, when strategy_id is omitted) | | show | string[] | NO | Extra indicator keys to include in the response beyond the 7 default columns | | page | integer | NO | 0-based page number, default 0 | | size | integer | NO | Page size, default 20 | ## Request Example ```python from longport.openapi import ScreenerContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = ScreenerContext(config) # Filter by strategy ID resp = ctx.screener_search("US", strategy_id=42) print(resp) ``` ```python import asyncio from longport.openapi import AsyncScreenerContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncScreenerContext.create(config) resp = await ctx.screener_search("US", strategy_id=42, page=1, size=20) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, ScreenerContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = ScreenerContext.new(config) const resp = await ctx.screenerSearch('US', { strategyId: 42, page: 1, size: 20 }) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.screener.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); ScreenerContext ctx = ScreenerContext.create(config)) { var resp = ctx.screenerSearch("US", 19L, null, List.of(), 0, 20).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, screener::ScreenerContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = ScreenerContext::new(config); // Mode A: run a strategy let resp = ctx.screener_search("", Some(19), vec![], vec![], 0, 20).await?; println!("{:?}", resp); // Mode B: custom conditions use longport::screener::ScreenerCondition; let conditions = vec![ScreenerCondition { key: "pettm".into(), min: "10".into(), max: "50".into(), tech_values: serde_json::json!({}) }]; let resp = ctx.screener_search("HK", None, conditions, vec![], 0, 20).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::screener; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); ScreenerContext ctx = ScreenerContext::create(config); ctx.screener_search("US", 42, 1, 20, [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/screener" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := screener.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() // Mode A: run a strategy stratID := int64(19) resp, err := c.ScreenerSearch(context.Background(), "", &stratID, nil, nil, 0, 20) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) // Mode B: custom conditions conditions := []screener.ScreenerCondition{ {Key: "pettm", Min: "10", Max: "50"}, {Key: "roe", Min: "5"}, } resp2, err := c.ScreenerSearch(context.Background(), "HK", nil, conditions, []string{"roe"}, 0, 20) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp2) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "total": 88, "page": 0, "market": "US", "items": [ { "symbol": "AAPL.US", "name": "Apple Inc.", "prevchg": 0.62, "marketcap": 3241500000000, "pettm": 32.15, "pbmrq": 50.21, "salesgrowthyoy": 8.04 }, { "symbol": "MSFT.US", "name": "Microsoft", "prevchg": 1.05, "marketcap": 3085000000000, "pettm": 35.42, "pbmrq": 12.87, "salesgrowthyoy": 12.61 } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ScreenerSearchResponse](#ScreenerSearchResponse) | | 400 | Bad request | None | ## Schemas ### ScreenerSearchResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | total | integer | false | Total number of matching stocks | | page | integer | false | Current page number (zero-based) | | market | string | false | Market of the result set | | items | object[] | false | Filtered stock list | | ∟ symbol | string | false | Security symbol | | ∟ name | string | false | Security name | | ∟ prevchg | number | false | Previous day price change ratio (e.g. `1.24` = 1.24%) | | ∟ marketcap | number | false | Market capitalisation (numeric) | | ∟ pettm | number | false | P/E ratio (TTM, numeric) | | ∟ pbmrq | number | false | P/B ratio (MRQ, numeric) | | ∟ salesgrowthyoy | number | false | Revenue growth YoY (%) | | ∟ industry | string | false | Industry classification | > All numeric indicator fields are JSON numbers. Additional indicator fields depend on the strategy or filter used. Indicator keys do not carry the `filter_` prefix. ### Preset Screener Strategies Get the list of platform-preset stock screener strategies, including recent average daily change and constituent stocks. Endpoint: `GET /v1/quote/ai/screener/strategies/recommend` ## SDK | Language | Link | |---|---| | Python | [longport.openapi.screener._screener_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.screener._screener_context) | | Rust | [longport::::screener#_screener_context](https://longportapp.github.io/openapi/rust/longport//struct.screener.html#method._screener_context) | | Go | [screener.screener_recommend_strategies](https://pkg.go.dev/github.com/longportapp/openapi-go/#screener.screener_recommend_strategies) | | Node.js | [screener#ScreenerContext](https://longportapp.github.io/openapi/nodejs/classes/screener.html#screenercontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | market | string | NO | Market filter: `US`, `HK`, `CN`, `SG`. Default: `US` | ## Request Example ```python from longport.openapi import ScreenerContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = ScreenerContext(config) # Default market (US) resp = ctx.screener_recommend_strategies() print(resp) # Hong Kong market resp = ctx.screener_recommend_strategies(market="HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncScreenerContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncScreenerContext.create(config) resp = await ctx.screener_recommend_strategies(market="HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, ScreenerContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = ScreenerContext.new(config) const resp = await ctx.screenerRecommendStrategies() console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.screener.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); ScreenerContext ctx = ScreenerContext.create(config)) { var resp = ctx.getScreenerRecommendStrategies().get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, screener::ScreenerContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = ScreenerContext::new(config); let resp = ctx.screener_recommend_strategies().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::screener; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); ScreenerContext ctx = ScreenerContext::create(config); ctx.screener_recommend_strategies([](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/screener" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := screener.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ScreenerRecommendStrategies(context.Background(), "US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "strategys": [ { "id": 19, "name": "今日大涨股票", "type": "platform", "market": "US" }, { "id": 20, "name": "今年增长冠军", "type": "platform", "market": "US" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ScreenerStrategiesResponse](#ScreenerStrategiesResponse) | | 400 | Bad request | None | ## Schemas ### ScreenerStrategiesResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | strategys | object[] | false | Strategy list | | ∟ id | integer | false | Strategy ID (pass to `screener_strategy` or `screener_search`) | | ∟ name | string | false | Strategy name | | ∟ type | string | false | `"platform"` for preset strategies | | ∟ market | string | false | Target market (e.g. `"US"`, `"HK"`) | ### Screener Strategy Detail Get the full configuration of a single stock screener strategy by strategy ID, including all indicator groups and the filter range for each indicator. Endpoint: `GET /v1/quote/ai/screener/strategy/{id}` (strategy ID as path parameter) ## SDK | Language | Link | |---|---| | Python | [longport.openapi.screener._screener_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.screener._screener_context) | | Rust | [longport::::screener#_screener_context](https://longportapp.github.io/openapi/rust/longport//struct.screener.html#method._screener_context) | | Go | [screener.screener_strategy](https://pkg.go.dev/github.com/longportapp/openapi-go/#screener.screener_strategy) | | Node.js | [screener#ScreenerContext](https://longportapp.github.io/openapi/nodejs/classes/screener.html#screenercontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | integer | YES | Strategy ID from `screener_recommend_strategies` or `screener_user_strategies` | ## Request Example ```python from longport.openapi import ScreenerContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = ScreenerContext(config) resp = ctx.screener_strategy(42) print(resp) ``` ```python import asyncio from longport.openapi import AsyncScreenerContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncScreenerContext.create(config) resp = await ctx.screener_strategy(42) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, ScreenerContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = ScreenerContext.new(config) const resp = await ctx.screenerStrategy(42) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.screener.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); ScreenerContext ctx = ScreenerContext.create(config)) { var resp = ctx.getScreenerStrategy(42L).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, screener::ScreenerContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = ScreenerContext::new(config); let resp = ctx.screener_strategy(42).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::screener; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); ScreenerContext ctx = ScreenerContext::create(config); ctx.screener_strategy(42, [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/screener" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := screener.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ScreenerStrategy(context.Background(), 42) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "id": 19, "name": "今日大涨股票", "market": "US", "type": "platform", "filter": { "filters": [ { "key": "prevchg", "min": "2", "max": "", "tech_values": {} } ] } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ScreenerStrategyDetail](#ScreenerStrategyDetail) | | 400 | Bad request | None | ## Schemas ### ScreenerStrategyDetail | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | integer | false | Strategy ID | | name | string | false | Strategy name | | market | string | false | Target market | | type | string | false | Strategy type | | filter | object | false | Filter configuration | | ∟ filters | object[] | false | Filter conditions | | ∟ ∟ key | string | false | Indicator key (no `filter_` prefix) | | ∟ ∟ min | string | false | Lower bound | | ∟ ∟ max | string | false | Upper bound | | ∟ ∟ tech_values | object | false | Technical indicator params | ### My Screener Strategies Get the list of custom stock screener strategies created by the currently logged-in user. Endpoint: `GET /v1/quote/ai/screener/strategies/mine` ## SDK | Language | Link | |---|---| | Python | [longport.openapi.screener._screener_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.screener._screener_context) | | Rust | [longport::::screener#_screener_context](https://longportapp.github.io/openapi/rust/longport//struct.screener.html#method._screener_context) | | Go | [screener.screener_user_strategies](https://pkg.go.dev/github.com/longportapp/openapi-go/#screener.screener_user_strategies) | | Node.js | [screener#ScreenerContext](https://longportapp.github.io/openapi/nodejs/classes/screener.html#screenercontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | market | string | NO | Market filter: `US`, `HK`, `CN`, `SG`. Default: `US` | Login required. ## Request Example ```python from longport.openapi import ScreenerContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = ScreenerContext(config) resp = ctx.screener_user_strategies() print(resp) ``` ```python import asyncio from longport.openapi import AsyncScreenerContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncScreenerContext.create(config) resp = await ctx.screener_user_strategies() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, ScreenerContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = ScreenerContext.new(config) const resp = await ctx.screenerUserStrategies() console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.screener.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); ScreenerContext ctx = ScreenerContext.create(config)) { var resp = ctx.getScreenerUserStrategies().get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, screener::ScreenerContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = ScreenerContext::new(config); let resp = ctx.screener_user_strategies().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::screener; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); ScreenerContext ctx = ScreenerContext::create(config); ctx.screener_user_strategies([](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/screener" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := screener.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ScreenerUserStrategies(context.Background(), "US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "strategys": [ { "id": 42, "name": "My Growth Strategy", "type": "user", "market": "US" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ScreenerStrategiesResponse](#ScreenerStrategiesResponse) | | 400 | Bad request | None | ## Schemas ### ScreenerStrategiesResponse The response structure is identical to [screener_recommend_strategies](./screener_recommend_strategies). Please refer to that document for the Schema definition. ### Screener Indicators Get all indicator definitions supported by the stock screener, including keys, names, units, and available ranges. Use these to build custom filter conditions. Endpoint: `GET /v1/quote/ai/screener/indicators` ## SDK | Language | Link | |---|---| | Python | [longport.openapi.screener._screener_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.screener._screener_context) | | Rust | [longport::::screener#_screener_context](https://longportapp.github.io/openapi/rust/longport//struct.screener.html#method._screener_context) | | Go | [screener.screener_indicators](https://pkg.go.dev/github.com/longportapp/openapi-go/#screener.screener_indicators) | | Node.js | [screener#ScreenerContext](https://longportapp.github.io/openapi/nodejs/classes/screener.html#screenercontext) | ## Parameters > **SDK method parameters.** This method takes no parameters. ## Request Example ```python from longport.openapi import ScreenerContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = ScreenerContext(config) resp = ctx.screener_indicators() print(resp) ``` ```python import asyncio from longport.openapi import AsyncScreenerContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncScreenerContext.create(config) resp = await ctx.screener_indicators() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, ScreenerContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = ScreenerContext.new(config) const resp = await ctx.screenerIndicators() console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.screener.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); ScreenerContext ctx = ScreenerContext.create(config)) { var resp = ctx.getScreenerIndicators().get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, screener::ScreenerContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = ScreenerContext::new(config); let resp = ctx.screener_indicators().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::screener; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); ScreenerContext ctx = ScreenerContext::create(config); ctx.screener_indicators([](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/screener" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := screener.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ScreenerIndicators(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "groups": [ { "group_name": "公司规模与财务", "indicators": [ { "id": "1", "key": "marketcap", "name": "市值", "unit": "亿", "min": null, "max": null } ] } ] } } ``` > The `filter_` prefix is stripped from all `key` values. The `id` field is a string. ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ScreenerIndicatorsResponse](#ScreenerIndicatorsResponse) | | 400 | Bad request | None | ## Schemas ### ScreenerIndicatorsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | groups | object[] | false | Indicator groups | | ∟ group_name | string | false | Group name | | ∟ indicators | object[] | false | Indicators in this group | | ∟ ∟ id | string | false | Indicator ID (string) | | ∟ ∟ key | string | false | Indicator key for building filter conditions (no `filter_` prefix) | | ∟ ∟ name | string | false | Indicator display name | | ∟ ∟ unit | string | false | Unit (e.g. `%`, `亿`) | | ∟ ∟ min | string | false | Global lower bound; null means no lower bound | | ∟ ∟ max | string | false | Global upper bound; null means no upper bound | ### Trade ### Trade Push Client can get real-time trade updates from trade gateway. ## Example ```python from time import sleep from decimal import Decimal from longport.openapi import TradeContext, Config, OrderSide, OrderType, TimeInForceType, PushOrderChanged, TopicType, OAuthBuilder def on_order_changed(event: PushOrderChanged): print(event) oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = TradeContext(config) ctx.set_on_order_changed(on_order_changed) ctx.subscribe([TopicType.Private]) resp = ctx.submit_order( side=OrderSide.Buy, symbol="700.HK", order_type=OrderType.LO, submitted_price=Decimal(50), submitted_quantity=Decimal(200), time_in_force=TimeInForceType.Day, remark="Hello from Python SDK", ) print(resp) sleep(5) # waiting for push event # Finally, unsubscribe ctx.unsubscribe([TopicType.Private]) ``` ## Subscribe :::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; } ``` ### 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
Type Introduction
Trade Submit Order
Replace Order
Withdraw Order
Get Today Orders
Get History Orders
Get Today Executions
Get History Executions
Asset Get Account Balance
Get Cash Flow
Get Fund Positions
Get Stock Positions
#### Execution #### Today Executions This API is used to get today executions. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.today_executions](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.today_executions) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.history_executions](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.history_executions) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 #### 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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.account_balance](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.account_balance) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.stock_positions](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.stock_positions) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### 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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.fund_positions](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.fund_positions) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Margin Ratio This API is used to obtain the initial margin ratio, maintain the margin ratio and strengthen the margin ratio of stocks. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.margin_ratio](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.margin_ratio) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### 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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.cash_flow](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.cash_flow) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Order #### Cancel Order This API is used to withdraw an open order. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.cancel_order](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.cancel_order) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodDELETE
HTTP URL/v1/trade/order
### Parameters > Content-Type: application/json; charset=utf-8 | Name | Type | Required | Description | | -------- | ------ | -------- | ----------- | | order_id | string | YES | Order ID | ### Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### History Orders This API is used to get history order. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.history_orders](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.history_orders) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 } ] } } ``` ### 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 | #### Submit Order This API is used to submit order for HK and US stocks, warrant and option. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.submit_order](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.submit_order) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodPOST
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. | ### Request Example ```python from decimal import Decimal from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Estimate Maximum Purchase Quantity This API is used for estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.estimate_max_purchase_quantity](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.estimate_max_purchase_quantity) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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. | #### Today Orders This API is used to get today order or get order by order id. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.today_orders](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.today_orders) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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` | ### Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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": "" } ] } } ``` ### 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 | #### Replace Order This API is used to replace order, modify quantity or price. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.replace_order](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.replace_order) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodPUT
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 | ### Request Example ```python from decimal import Decimal from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Order Details This API is used for order detail query ## SDK | Language | Link | |---|---| | Python | [longport.openapi.trade._trade_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.trade._trade_context) | | Rust | [longport::::trade#_trade_context](https://longportapp.github.io/openapi/rust/longport//struct.trade.html#method._trade_context) | | Go | [trade.order_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#trade.order_detail) | | Node.js | [trade#TradeContext](https://longportapp.github.io/openapi/nodejs/classes/trade.html#tradecontext) | ## Request
HTTP MethodGET
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` | ### Request Example ```python from longport.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", ) print(resp) ``` ```python import asyncio from longport.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", ) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, TradeContext, OAuth } = require('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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" } } } ``` ### 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 | ### 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 - **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. ### General ## Q1: Do I need to open a live account to call LongPort 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.longport.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 LongPort 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 `LONGPORT_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 LongPort Developers platform? The platform offers one way to access stock data without writing any code: **MCP (AI Tool Integration)** If you use AI tools like Claude, Cursor, or ChatGPT, connect the [LongPort MCP service](/docs/mcp). Once configured, simply ask in plain language and the AI will query market data on your behalf. This method requires a LongPort account. ### 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. LongPort 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 LongPort. - How to buy quote cards LongPort users can choose the market cards they want to buy through the "Quote Store" in the LongPort 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 `LONGPORT_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) ``` ### 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 | #### Alert #### Create Alert Create a new price alert for a security. The alert fires when the specified condition is met. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.alert._alert_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.alert._alert_context) | | Rust | [longport::::alert#_alert_context](https://longportapp.github.io/openapi/rust/longport//struct.alert.html#method._alert_context) | | Go | [alert.add](https://pkg.go.dev/github.com/longportapp/openapi-go/#alert.add) | | Node.js | [alert#AlertContext](https://longportapp.github.io/openapi/nodejs/classes/alert.html#alertcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `TSLA.US` | | condition | AlertCondition | YES | Trigger condition: `PriceRise`, `PriceFall`, `PercentRise`, `PercentFall` | | trigger_value | string | YES | Threshold value, e.g. `"600"` (price) or `"5"` (percentage) | | frequency | AlertFrequency | YES | How often to trigger: `Daily`, `EveryTime`, `Once` | ## Request Example ```python from longport.openapi import AlertContext, AlertCondition, AlertFrequency, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AlertContext(config) ctx.add("TSLA.US", AlertCondition.PriceRise, "600", AlertFrequency.Once) ``` ```python import asyncio from longport.openapi import AsyncAlertContext, AlertCondition, AlertFrequency, 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) await ctx.add("TSLA.US", AlertCondition.PriceRise, "600", AlertFrequency.Once) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, AlertContext, AlertCondition, AlertFrequency, OAuth } = require('longport') 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) await ctx.add("TSLA.US", AlertCondition.PriceRise, "600", AlertFrequency.Once) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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 opts = new AddAlertOptions(); opts.symbol = "TSLA.US"; opts.condition = AlertCondition.PriceRise; opts.triggerValue = "600"; opts.frequency = AlertFrequency.Once; ctx.add(opts).get(); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, alert::{AlertContext, AlertCondition, AlertFrequency}, 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); ctx.add("TSLA.US", AlertCondition::PriceRise, "600", AlertFrequency::Once).await?; Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::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.add("TSLA.US", AlertCondition::PriceRise, "600", AlertFrequency::Once, [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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() if err = c.Add(context.Background(), "TSLA.US", alert.AlertConditionPriceRise, "600", alert.AlertFrequencyOnce); err != nil { log.Fatal(err) } fmt.Println("OK") } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": {} } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | None | | 400 | Bad request | None | #### Delete Alert Delete one or more price alerts by ID. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.alert._alert_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.alert._alert_context) | | Rust | [longport::::alert#_alert_context](https://longportapp.github.io/openapi/rust/longport//struct.alert.html#method._alert_context) | | Go | [alert.delete](https://pkg.go.dev/github.com/longportapp/openapi-go/#alert.delete) | | Node.js | [alert#AlertContext](https://longportapp.github.io/openapi/nodejs/classes/alert.html#alertcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | alert_ids | string[] | YES | List of alert IDs to delete (from `list()` response `indicators[].id`) | ## Request Example ```python from longport.openapi import AlertContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AlertContext(config) ctx.delete(["486469"]) ``` ```python import asyncio from longport.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) await ctx.delete(["486469"]) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, AlertContext, OAuth } = require('longport') 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) await ctx.delete(["486469"]) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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 opts = new DeleteAlertOptions(); opts.ids = java.util.Arrays.asList("486469"); ctx.delete(opts).get(); } } } ``` ```rust use std::sync::Arc; use longport::{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); ctx.delete(vec!["486469".to_string()]).await?; Ok(()) } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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() err = c.Delete(context.Background(), []string{"486469"}) if err != nil { log.Fatal(err) } } ``` ## 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. #### Update Alert Enable or disable a price alert. Python and Java expose `enable(alert_id)` / `disable(alert_id)`; other languages use `update(item)` after setting `item.enabled = true` or `false`. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.alert._alert_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.alert._alert_context) | | Rust | [longport::::alert#_alert_context](https://longportapp.github.io/openapi/rust/longport//struct.alert.html#method._alert_context) | | Go | [alert.enable](https://pkg.go.dev/github.com/longportapp/openapi-go/#alert.enable) | | Node.js | [alert#AlertContext](https://longportapp.github.io/openapi/nodejs/classes/alert.html#alertcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | alert_id | string | YES | Alert ID (from `list()` response `indicators[].id`) | ## Request Example ```python from longport.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 ID from list() alerts = ctx.list() alert_id = alerts.lists[0].indicators[0].id # Enable the alert ctx.enable(alert_id) # Disable the alert ctx.disable(alert_id) ``` ```python import asyncio from longport.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() alert_id = alerts.lists[0].indicators[0].id await ctx.enable(alert_id) # await ctx.disable(alert_id) # to disable if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, AlertContext, OAuth } = require('longport') 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 // set false to disable await ctx.update(item) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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.getList().get(); String alertId = alerts.getLists().get(0).getIndicators().get(0).getId(); ctx.enable(alertId).get(); // ctx.disable(alertId).get(); // to disable } } } ``` ```rust use std::sync::Arc; use longport::{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 list = ctx.list().await?; let mut item = list.lists[0].indicators[0].clone(); item.enabled = true; // set false to disable ctx.update(&item).await?; Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::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) { if (!list_resp) return; auto item = (*list_resp).lists[0].indicators[0]; item.enabled = true; // set false to disable ctx.update(item, [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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) } alertID := list.Lists[0].Indicators[0].ID if err = c.Enable(context.Background(), alertID); err != nil { log.Fatal(err) } fmt.Println("OK") } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": {} } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | None | | 400 | Bad request | None | #### List Alerts Get all price alerts for the current user, with optional filtering by symbol. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.alert._alert_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.alert._alert_context) | | Rust | [longport::::alert#_alert_context](https://longportapp.github.io/openapi/rust/longport//struct.alert.html#method._alert_context) | | Go | [alert.list](https://pkg.go.dev/github.com/longportapp/openapi-go/#alert.list) | | Node.js | [alert#AlertContext](https://longportapp.github.io/openapi/nodejs/classes/alert.html#alertcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | NO | Filter by security symbol, e.g. `TSLA.US` | ## Request Example ```python from longport.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() print(resp) ``` ```python import asyncio from longport.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() print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, AlertContext, OAuth } = require('longport') 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() console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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.getList().get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{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().await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::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([](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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.List(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"}`) | #### Portfolio #### Profit Analysis Summary Get a P&L summary for the account including total asset, total P&L, and yield metrics. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.portfolio._portfolio_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.portfolio._portfolio_context) | | Rust | [longport::::portfolio#_portfolio_context](https://longportapp.github.io/openapi/rust/longport//struct.portfolio.html#method._portfolio_context) | | Go | [portfolio.profit_analysis_summary](https://pkg.go.dev/github.com/longportapp/openapi-go/#portfolio.profit_analysis_summary) | | Node.js | [portfolio#PortfolioContext](https://longportapp.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Profit Analysis Flows Query account cash flow history including deposits, withdrawals, dividends, and settlements. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.portfolio._portfolio_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.portfolio._portfolio_context) | | Rust | [longport::::portfolio#_portfolio_context](https://longportapp.github.io/openapi/rust/longport//struct.portfolio.html#method._portfolio_context) | | Go | [portfolio.profit_analysis_flows](https://pkg.go.dev/github.com/longportapp/openapi-go/#portfolio.profit_analysis_flows) | | Node.js | [portfolio#PortfolioContext](https://longportapp.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Exchange Rates Get current foreign exchange rates for all currency pairs used in your account. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.portfolio._portfolio_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.portfolio._portfolio_context) | | Rust | [longport::::portfolio#_portfolio_context](https://longportapp.github.io/openapi/rust/longport//struct.portfolio.html#method._portfolio_context) | | Go | [portfolio.exchange_rates](https://pkg.go.dev/github.com/longportapp/openapi-go/#portfolio.exchange_rates) | | Node.js | [portfolio#PortfolioContext](https://longportapp.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | base | string | NO | Base currency, e.g. `USD`. Omit for all pairs. | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 Detail Get detailed P&L for a specific security including transaction flow and cost breakdown. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.portfolio._portfolio_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.portfolio._portfolio_context) | | Rust | [longport::::portfolio#_portfolio_context](https://longportapp.github.io/openapi/rust/longport//struct.portfolio.html#method._portfolio_context) | | Go | [portfolio.profit_analysis_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#portfolio.profit_analysis_detail) | | Node.js | [portfolio#PortfolioContext](https://longportapp.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 by Market Get P&L breakdown grouped by market (US, HK, CN, SG). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.portfolio._portfolio_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.portfolio._portfolio_context) | | Rust | [longport::::portfolio#_portfolio_context](https://longportapp.github.io/openapi/rust/longport//struct.portfolio.html#method._portfolio_context) | | Go | [portfolio.profit_analysis_by_market](https://pkg.go.dev/github.com/longportapp/openapi-go/#portfolio.profit_analysis_by_market) | | Node.js | [portfolio#PortfolioContext](https://longportapp.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 #### DCA Trade History Get the execution history for a specific DCA plan including trade dates, amounts, and prices. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.history](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.history) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Set DCA Reminder Set the advance reminder time for DCA plans. Supported values: `1`, `6`, or `12` hours. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.set_reminder](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.set_reminder) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | hours | string | YES | Reminder advance hours: `1`, `6`, or `12` | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Update DCA Plan Pause or resume an existing recurring investment plan. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.update](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.update) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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. #### Create DCA Plan Create a new recurring investment plan for a security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.create](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.create) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Resume DCA Plan Resume a previously paused DCA plan. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.resume](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.resume) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## Parameters | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | plan_id | string | YES | DCA plan ID | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Pause DCA Plan Temporarily pause a DCA plan. The plan can be resumed later. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.pause](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.pause) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## Parameters | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | plan_id | string | YES | DCA plan ID | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### DCA Statistics Get DCA statistics summary including total invested amount and profit/loss. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.stats](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.stats) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## Parameters | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | NO | Filter by symbol | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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). #### Calculate DCA Date Calculate the next projected trade date for given DCA plan parameters. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.calc_date](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.calc_date) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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) | #### Check DCA Support Check whether the given securities support DCA recurring investment. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.check_support](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.check_support) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## Parameters | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbols | string[] | YES | List of security symbols to check | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Stop DCA Plan Permanently stop a DCA plan. This action cannot be undone. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.stop](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.stop) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## Parameters | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | plan_id | string | YES | DCA plan ID | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### List DCA Plans Get all recurring investment (DCA) plans for the current user. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.dca._d_c_a_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.dca._d_c_a_context) | | Rust | [longport::::dca#_d_c_a_context](https://longportapp.github.io/openapi/rust/longport//struct.dca.html#method._d_c_a_context) | | Go | [dca.list](https://pkg.go.dev/github.com/longportapp/openapi-go/#dca.list) | | Node.js | [dca#DCAContext](https://longportapp.github.io/openapi/nodejs/classes/dca.html#dcacontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | ### Socket ### Subscribe Real-Time Trading Data Client can access trade feed by `WebSocket` and `TCP`. After client subscribing, trade gateway can push real-time trade changings of user. :::info WebSocket Endpoint: `wss://openapi-trade.longportapp.com` TCP Endpoint: `openapi-trade.longportapp.com` ::: Flow: ```mermaid sequenceDiagram autonumber Client ->> Server: Handshake Server -->> Client: Establish Connection Client -->> Server: Auth Request Server -->> Client: Auth Response par Subscribe Client -->> Server: Subscribe request,req_id: 10, cmd: 16 Server -->> Client: Subscribe response ,req_id: 10, cmd: 16 Server -->> Client: Push order updating,cmd: 18 Server -->> Client: Push order updating,cmd: 18 end ``` ## Subscribe Subscribe [protobuf defination](../trade/trade-push) Example: ```json { "topics": ["private"] } ``` > Here is `JSON` for easy showing case, actually need using protobuf encoding. ## Pushing Example ```json { "topic": "private", "content_type": 2, "dispatch_type": 1, "data": "eyJldmVudCI6Im9yZGVyX2NoYW5nZWRfbGIiLCJkYXRhIjp7InNpZGUiOiJCdXkiLCJzdG9ja19uYW1lIjoi6IW+6K6v5o6n6IKhIiwicXVhbnRpdHkiOiIxMDAwIiwic3ltYm9sIjoiNzAwLkhLIiwib3JkZXJfdHlwZSI6IkxPIiwicHJpY2UiOiIyMTMuMiIsImV4ZWN1dGVkX3F1YW50aXR5IjoiMTAwMCIsImV4ZWN1dGVkX3ByaWNlIjoiMjEzLjIiLCJvcmRlcl9pZCI6IjI3IiwiY3VycmVuY3kiOiJIS0QiLCJzdGF0dXMiOiJOZXdTdGF0dXMiLCJzdWJtaXR0ZWRfYXQiOiIxNTYyNzYxODkzIiwidXBkYXRlZF9hdCI6IjE1NjI3NjE4OTMiLCJ0cmlnZ2VyX3ByaWNlIjoiMjEzLjAiLCJtc2ciOiJJbnN1ZmZpY2llbnQgUXR5IC0gMTAwMCIsInRhZyI6IkdUQyIsInRyaWdnZXJfc3RhdHVzIjoiQUNUSVZFIiwidHJpZ2dlcl9hdCI6IjE1NjI3NjE4OTMiLCJ0YWlsaW5nX2Ftb3VudCI6IjUiLCJ0YWlsaW5nX3BlcmNlbnQiOiIxIiwibGltaXRfb2Zmc2V0IjoiMC4wMSIsImFjY291bnRfbm8iOiJISzEyMzQ0NSJ9fQ==" } ``` :::info `data` is binary(Base64) content of `JSON` string ::: The real `JSON` format of `data`: ```json { "event": "order_changed_lb", "data": { "side": "Buy", "stock_name": "Tecent", "quantity": "1000", "symbol": "700.HK", "order_type": "LO", "price": "213.2", "executed_quantity": "1000", "executed_price": "213.2", "order_id": "27", "currency": "HKD", "status": "NewStatus", "submitted_at": "1562761893", "updated_at": "1562761893", "trigger_price": "213.0", "msg": "Insufficient Qty - 1000", "tag": "GTC", "trigger_status": "ACTIVE", "trigger_at": "1562761893", "trailing_amount": "5", "trailing_percent": "1", "limit_offset": "0.01", "account_no": "HK123445", "last_share": "100", "last_price": "234", "remark": "abc" } } ``` Field description is [here](../trade/trade-definition#websocket-push-notification) ## Feed Protocol If you want subscribe trading data from socket, you must know more details of our [protocol](./protocol/overview) ### Endpoints LongPort split Market Quote and Trading real-time pushing endpoints. ## Market Quote | Endpoint | Access Type | | --------------------------------------- | ----------- | | tcp://openapi-quote.longportapp.com:2020 | TCP | | wss://openapi-quote.longportapp.com | WebSocket | ## Trading | Endpoint | Access Type | | --------------------------------------- | ----------- | | tcp://openapi-trade.longportapp.com:2020 | TCP | | wss://openapi-trade.longportapp.com | WebSocket | ## Mainland China Users in mainland China can use the following endpoints for better connectivity: ### Market Quote | Endpoint | Access Type | | -------------------------------------- | ----------- | | tcp://openapi-quote.longport.cn:2020 | TCP | | wss://openapi-quote.longport.cn | WebSocket | ### Trading | Endpoint | Access Type | | -------------------------------------- | ----------- | | tcp://openapi-trade.longport.cn:2020 | TCP | | wss://openapi-trade.longport.cn | WebSocket | ### Subscribe Real-Time Market Data :::success NOTE Our OpenAPI SDK has fully implemented the function of subscribing to quotes, and you can use the SDK directly. https://open.longport.com/sdk The documentation in this chapter provides API details for your reference. ::: Client can access market quote feed by `WebSocket` and `TCP`. After client subscribing stock quote, quote gateway can push real-time quote data to client. :::info WebSocket Endpoint: `wss://openapi-quote.longportapp.com` TCP Endpoint: `openapi-quote.longportapp.com:2020` ::: Flow: ```mermaid sequenceDiagram autonumber Client ->> Server: Handshake Server -->> Client: Establish connection Client -->> Server: Auth request Server -->> Client: Auth response par Subscribe Market Quote Client -->> Server: Subscribe request,req_id: 10, cmd: 6 Server -->> Client: Subscribe response,req_id: 10, cmd: 6 Server -->> Client: price pushing,cmd: 101 Server -->> Client: depth pushing,cmd: 102 Server -->> Client: broker pushing,cmd: 103 Server -->> Client: transaction pushing,cmd: 104 end ``` ## Subscribe Client can subscribe different quote type through subscribe commmand. Subscribe command [protobuf defination](../quote/subscribe/subscribe) Example: ```json { "symbol": ["700.HK", "AAPL.US"] "sub_type": [1, 2] "is_first_push": true } ``` > Here is `JSON` for easy showing case, actually need using protobuf encoding. Client can also check quote topics already subscribing, [protobuf defination](../quote/subscribe/subscription). After client success subscribing quote, server will push real-time quote data to client, data [protobuf defination](../quote/overview). ## Other Quote APIs All quote all should be fetched by our quote gateway, more details can be found in [quote overview](../quote/overview). ## Feed Protocol If you want subscribe quote data from socket, you must know more details of our [protocol](./protocol/overview) ### Data Commands Socket Feed providers real-time stock quote data updates and trade updates. And stock quote and order have difference endpoints, [check here](./hosts). ## Stock Quote Overview
Type Description
Pull Get Basic Information Of Securities
Get Real-time Quotes Of Securities
Get Real-time Quotes Of Option Securities
Get Real-time Quotes Of Warrant Securities
Get Security Depth
Get Security Brokers
Get Broker IDs
Get Security Trades
Get Security Intraday
Get Security Candlestick
Get Option Chain Expiry Date List
Get Option Chain Info By Date
Get Warrant Issuer IDs
Get Filtered Warrant
Get Trading Session Of The Day
Get Market Trading Days
Get Security Capital Flow Intraday
Get Security Capital Distribution
Get Calculate Indexes Of Securities
Get Security History Candlestick
Subscription Get Subscription Information
Subscribe Quote
Unsubscribe Quote
Push Push Real-time Quote
Push Real-time Depth
Push Real-time Brokers
Push Real-time Trades
More detail can check [here](../quote/overview#quote-api-overview) ## Trade | Type | Functional | | --------- | -------------------------------------------------------------------------------------------------------------- | | Subscribe | [Subscribe](../trade/trade-push#subscribe)

[Cancel Subscribe](../trade/trade-push#cancel-subscribe) | | Notify | [Notification](../trade/trade-push#notification) | More detail check [here](../trade/trade-push) ### Control commands Control Commands are basic commands, using for create connection and keep connection alive. Control Commands: | cmd_code | description | | -------- | ------------------------------------------------------------------------------------------ | | 0 | close - before server close the connection between client, server will send a close packet | | 1 | heartbeat - keep connection alive | | 2 | auth - auth connection | | 3 | reconnect - use session to auth | ## Close :::info Cmd:`0` ::: Before server close the connection between client, server will send a close packet. > close packet is push type packet, no need response Cases server will close the connection: 1. heartbeat timeout 2. server internal error 3. server shutdown 4. client send invalid packet(can't parse by server) 5. auth failed 6. session expired when reconnect 7. duplicate connection have been created The reason why server close the connection will send by close packet, protobuf defination: ```protobuf message Close { enum Code { HeartbeatTimeout = 0; // Heartbeat timeout ServerError = 1; // Server internal error ServerShutdown = 2; // Server shutdown UnpackError = 3; // Server can't paser client packet AuthError = 4; // Auth failed SessExpired = 5; // Session expired ConnectDuplicate = 6; // create duplicated connection } Code code = 1; string reason = 2; } ``` ## Heartbeat :::info Cmd:`1` ::: Oner peer and send heartbeat to another peer to known health of another peer. Heartbeat do not limit body structure, one peer receive a heartbeat packet, only need send the `body` back. > Heartbeat not only can keep connection alive, but also can detect latency of the network between two peers. One peer can set current timestamp in heartbeat body, when receive the response, use current timestamp minus timestamp in the body to get lantency of network. ```mermaid sequenceDiagram par peer-a to peer-b peer-a -->> peer-b: heartbeat request, req_id: 1 peer-b -->> peer-a: heartbeat response, req_id: 1 end par peer-b to peer-a peer-b -->> peer-a: heartbeat request, req_id: 1 peer-a -->> peer-b: heartbeat response, req_id: 1 end ``` Example of heartbeat `body` : ```protobuf message Heartbeat { int64 timestamp = 1; } ``` ## Auth :::info Cmd:`2` ::: Client need prove connection is legal. After handshake with server, client send auth packet as first packet. ```mermaid sequenceDiagram Client -->> Server: auth request, req_id: 1, token: xxx Server -->> Client: auth response, req_id: 1, session: xxx ``` > Auth `token` can be created through [HTTP API](./socket-token-api) After auth success, server will set session in auth response, client can use the session to reconnect and no need to request a new `token`. Auth Request and Response protobuf: ```protobuf message AuthRequest { string token = 1; } message AuthResponse { string session_id = 1; int64 expires = 2; } ``` ## Reconnect :::info Cmd:`3` ::: After client disconnect from server, client can use session to reconnect to server when session is not expired. After reconnect success, server will set new session in reconnect response body. Reconnect Request and Response: ```protobuf message ReconnectRequest { string session_id = 1; } message ReconnectResponse { string session_id = 1; int64 expires = 2; } ``` ## Protobuf All control command protobuf definations are opensource in [GitHub](https://github.com/longportapp/openapi-protobufs/blob/main/control/control.proto) ### Access differences between WebSocket and TCP LongPort support `WebSocket` and `TCP` feed, the differences: - Data of `TCP` is streaming, so coding client is hard than `WebSocket`. - `WebSocket` using URL Query to [Handshake](./protocol/handshake#websocket-how-to-handshake) - `WebSocket` using [ping-pong](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#pings_and_pongs_the_heartbeat_of_websockets) to do Heartbeating, instead of sending heartbeat packet. - `WebSocket` using `TLS` to secure connection, but `TCP` do not. User can choice `TCP` or `WebSocket` on self demand. > Advice: Using `WebSocket` first, it is more simple. If want more quick stock quote real-time pushing, using `TCP` to access stock quote gateway. #### Protocol #### Protocol Overview We use binary format data for communication, protocol support both `WebSocket` and `TCP`. :::info Endianness is `BigEndian` ::: If your are familiar with `Python` or `C++`, we provider [SDK](https://open.longport.com/en/sdk) for you. If you want parse protocol by self, you can check our [Go Implemetation](https://github.com/longportapp/openapi-protocol/tree/main/go). The endponts of `WebSocket` and `TCP` can be found [here](../hosts). Before start parse protocol, you should know our [Communication Model](./connect), we split to three type of communication: - Handshake - For establishing connection - Request and Response - Pairing data packet for handle api request - Push - One peer send data to another, no need response Depends on communication model, there are out typs of packet: - [Handkeshake](./handshake) - [Request](./request) - [Response](./response) - [Push](./push) Data is in the `body` of the packet, current we only support [`Protobuf`](https://developers.google.com/protocol-buffers) for codec. `Protobuf` definition can be found in: - [Control command](../control-command) - [Data command](../biz_command) #### Parse Request Packet Request packet is used for invoke apis: send api request and get api response. :::info Packet type is `1` ::: Structure: ``` 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | type=1|v|g|re.| cmd_code | request_id | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | timeout | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | body_len | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | body(by body_len) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + nonce(optional) + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + + | | + signature(optional) + | | + + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` Fields Descriptions: | Field | Length in bit | Length in byte | description | | ---------- | ------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------- | | cmd_code | 8 | 1 | Command | | request_id | 32(uint32) | 4 | Request id, it should be unique for one connection.
Can start from 1, when reach 4294967295 start over | | timeout | 16(uint16) | 2 | `timeout` in millisecond
max: 60000(60s) | | body_len | 24(uint32) | 3 | Then length of `body` in bytes.
Max: 16 MB
If gzip is enabled, the value is after compress | | body | Variable length, decide by `body_len` | variable length | `body`,max size: 16 MB | | nonce | 64 | 8 | exists when `verify` is `1` | | signature | 128 | 16 | exists when `verify` is `1` | :::info Using specific protobuf defination to encode/decode body data ::: #### Parse Handshake Handshake is first thing before client and server establish connection. Handshake negotiate thress things: - protocol version - right now only version `1` - data codec type - right now only support `protobuf`, value is `1` - client platform - value is `9` as `OpenAPI` So handshake is always fixed contents. ## How `TCP` do handshaking Client need send two bytes handshake to server. ### Data structure ``` 0 1 2 3 4 5 6 7 +-+-+-+-+-+-+-+-+ | ver | codec | +-+-+-+-+-+-+-+-+ |platfo.|reserve| +-+-+-+-+-+-+-+-+ ``` Fields Explain: | field | length in bit | description | | -------- | ------------- | ----------------------------------------- | | ver | 4 | protocol version: only value `1` | | codec | 4 | data codec: only value `1` for `protobuf` | | platform | 4 | client platform: 0b1001 - OpenAPI | | reserve | 4 | reserved | ### Example - ver - 0b0001 - codec - 0b0001 - platform - 0b1001 - reserve - 0b0000 Two bytes contents: ``` 0b00010001, 0b00001001 ``` ## How `WebSocket` do handshaking `WebSocket` send handshake info by `URL Query` ### Query Parameters | Field | Type | Description | | -------- | ---- | ----------------------------------------- | | version | 4 | protocol version: only value `1` | | codec | 4 | data codec: only value `1` for `protobuf` | | platform | 4 | client platform: `9` - OpenAPI | ### Example ``` wss://openapi-quote.longportapp.com?version=1&codec=1&platform=9 ``` #### Communication Model There are three type packet will client and server send to each other: - handshake - start establish connection - request - client send request to server - response - server send response to client - push - server push real-time data to client ## Handshake Flow: ```mermaid sequenceDiagram client ->> server: 1. handshake server ->> server: 1.1 check handshake alt handshake invalid server --x client: 2. disconnect else is valid server -->> client: 2. build connection end ``` After client sending handshake packet server, the connection has been established. If handshake packet is invalid, server will push a close data to client. If access by `TCP`, client can send handshake packet and first data packet(auth) for accelerating communication. ## Request and Response `Request <--> Response`: Client send a request packet, server will send back a response packet. Flow: ```mermaid sequenceDiagram autonumber par request 1 client -->> server: request, req_id: 1 server -->> client: response, req_id: 1 end par request 100 client -->> server: request, req_id: 100 server -->> client: response: req_id: 100 end par request n client -->> server: request, req_id: n server -->> client: response, req_id: n end ``` After client and server sucess handshaking, peers can use `Request <--> Response` to communicate. `Request` and `Response` are paired by `request_id`. > Client and Server can send heartbeat request to each other. ## Push Push is one peer send data to another peer, and no need response. ```mermaid sequenceDiagram server -->> client: push, data 1 server -->> client: push, data 2 ``` > Right now, we only support server push data to client. #### Parse Push Packet Push is one side send data to another side, no need response. :::info Packet `type` value is `3` ::: ``` 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | type=3|v|g|re.| cmd_code | body_len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | body_len | body(by body_len) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + nonce(optional) + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + + | | + signature(optional) + | | + + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` Fields Descriptions: | Field | length in bit | Length in byte | description | | --------- | ------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------- | | cmd_code | 8 | 1 | Comand | | body_len | 24(uint32) | 3 | Then length of `body` in bytes.
Max: 16 MB
If gzip is enabled, the value is after compress | | body | Variable length, decide by `body_len` | variable length | `body`,max size: 16 MB | | nonce | 64 | 8 | exists when `verify` is `1` | | signature | 128 | 16 | exists when `verify` is `1` | #### Parse Response Packet One peer need send back a response packet after receiving and handlding request packet. :::info Packet type is `2` ::: ## Structure ``` 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | type=2|v|g|re.| cmd_code | request_id | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | status_code | body_len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | body_len | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | body(by body_len) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + nonce(optional) + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + + | | + signature(optional) + | | + + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` Fields Descriptions: | Field | Length in bit | Length in byte | description | | ---------- | ------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------- | | cmd_code | 8 | 1 | Command | | request_id | 32(uint32) | 4 | Request id, need to be same as request packet for pairing | | status | 8(uint8) | 1 | status code: `0` - success; others show in [status code table](#status-code-table) | | body_len | 24(uint32) | 3 | Then length of `body` in bytes.
Max: 16 MB
If gzip is enabled, the value is after compress | | body | Variable length, decide by `body_len` | variable length | `body`,max size: 16 MB | | nonce | 64 | 8 | exists when `verify` is `1` | | signature | 128 | 16 | exists when `verify` is `1` | ## Status Code Table | value | flag | description | | ----- | --------------------- | ----------------------------- | | 0 | SUCCESS | Success like HTTP status 200 | | 1 | SERVER_TIMEOUT | Timeout like HTTP status 408 | | 3 | BAD_REQUEST | Bad Request like HTTP 400 | | 5 | UNAUTHENTICATED | Unauthorized like HTTP 401 | | 7 | SERVER_INTERNAL_ERROR | Internal server like HTTP 500 | #### Parse Header of Packet We have three type packet: - request - response - push The type of packet and some other info can decide the length of packet. Then length of Header is 1 byte. :::info The length of Header is 1 byte. ::: ## Structure ``` 0 1 2 3 4 5 6 7 +-+-+-+-+-+-+-+-+ | type |v|g|re.| +-+-+-+-+-+-+-+-+ ``` | Field | Length in bit | description | | ------- | ------------- | ----------------------------------------------------------------- | | type | 4 | packet type:
`1` - request
`2` - resopnse
`3` - push | | verify | 1 | if have signature data

`0` - Yes
`1` - No | | gzip | 1 | if use `gzip` to compress data:

`1` - Yes
`0` - No | | reserve | 2 | reversed | ## Example ``` // reserve - 0, gzip - 0, verify - 0, type - 1 0b 0000 0001 // reserve - 0, gzip - 1, verify - 0, type - 2 0b 0011 0010 // reserve - 0, gzip - 1, verify - 1, type - 3 0b 0001 0011 // reserve - 3, gzip - 1, verify - 0, type - 3 0b 1110 0011 ``` ### Market ### Rank Categories Get the tag category configuration for the popularity leaderboard. `second_tags[].key` can be passed to `rank_list`. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.rank_categories](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.rank_categories) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** This method takes no parameters. ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.RankCategories(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "first_tags": [ { "key": "ib_hot", "name": "Hotness Rank", "second_tags": [ { "key": "ib_hot_all-us", "name": "US Total Hotness", "market": "US" }, { "key": "ib_hot_all-hk", "name": "HK Total Hotness", "market": "HK" }, { "key": "ib_hot_all-cn", "name": "A-share Total Hotness", "market": "CN" } ] }, { "key": "ib_change", "name": "Price Change Rank", "second_tags": [ { "key": "ib_change_top-us", "name": "US Top Gainers", "market": "US" }, { "key": "ib_change_top-hk", "name": "HK Top Gainers", "market": "HK" } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [RankCategoriesResponse](#RankCategoriesResponse) | | 400 | Bad request | None | ## Schemas ### RankCategoriesResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | first_tags | object[] | false | Top-level category list | | ∟ key | string | false | Top-level category key | | ∟ name | string | false | Top-level category name | | ∟ second_tags | object[] | false | Second-level category list | | ∟ ∟ key | string | false | Second-level category key; pass to `rank_list` as the `key` parameter | | ∟ ∟ name | string | false | Second-level category name | | ∟ ∟ market | string | false | Associated market: `US`, `HK`, `CN`, `SG` | ### Popularity Leaderboard 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). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.rank_list](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.rank_list) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.RankList(context.Background(), "hot_all-us", false) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "bmp": false, "lists": [ { "code": "MU", "symbol": "MU.US", "name": "Micron Technology", "last_done": "698.740", "chg": "0.0252", "change": "17.200", "inflow": "-347041642", "market_cap": "787992890796", "industry": "Semiconductor Manufacturers", "pre_post_price": "726.600", "pre_post_chg": "0.0399", "amplitude": "0.1082", "five_day_chg": "-0.0885", "turnover_rate": "0.0550", "volume_rate": "1.11", "pb_ttm": "32.68" } ] } } ``` > Note: The response contains many additional fields; the above are the main ones. ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [RankListResponse](#RankListResponse) | | 400 | Bad request | None | ## Schemas ### RankListResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | bmp | boolean | false | Whether the response is a market preview (before open) | | lists | object[] | false | Leaderboard stock list | | ∟ code | string | false | Ticker code (e.g. `MU`) | | ∟ symbol | string | false | Symbol in `CODE.MARKET` format (e.g. `MU.US`) | | ∟ name | string | false | Security name | | ∟ last_done | string | false | Latest trade price | | ∟ chg | string | false | Price change ratio as decimal (e.g. `0.0252` = 2.52%) | | ∟ change | string | false | Absolute price change (e.g. `17.200`) | | ∟ inflow | string | false | Net capital inflow (in the market's currency) | | ∟ market_cap | string | false | Market capitalisation | | ∟ industry | string | false | Industry classification | | ∟ pre_post_price | string | false | Pre/post-market price | | ∟ pre_post_chg | string | false | Pre/post-market price change ratio (decimal) | | ∟ amplitude | string | false | Amplitude / intraday range ratio (decimal) | | ∟ five_day_chg | string | false | 5-day price change ratio (decimal) | | ∟ turnover_rate | string | false | Turnover rate (decimal) | | ∟ volume_rate | string | false | Volume ratio (vs average) | | ∟ pb_ttm | string | false | Price-to-book ratio (TTM) | > Note: The response contains many additional fields; the above are the main ones. ### Top Movers Get stocks whose price movement exceeds the 20-trading-day standard deviation, with automatically correlated news to explain the move. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.top_movers](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.top_movers) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | ### Unusual Items Detect unusual market movements — price spikes, volume surges, and other abnormal trading activity. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.unusual_items](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.unusual_items) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | market | string | YES | Market code: `US`, `HK`, `SH`, `SZ`, `SG` | ## Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | ### Market Status Get the current open/close status for each exchange. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.market_status](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.market_status) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | ### Trading Sessions This API is used to obtain the daily trading hours of each market. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.trading_session](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.trading_session) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::info [Business Command](../../socket/biz_command): `8` ::: ## Request ### Request Example ```python from longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | ### Trading Days This API is used to obtain the trading days of the market. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.trading_days](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.trading_days) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | :::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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/quote" openapi "github.com/longportapp/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` | ### Market Temperature Get Current Market Temperature ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.market_temperature](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.market_temperature) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | ### Historical Temperature This interface is used to get historical market temperature. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.quote._quote_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.quote._quote_context) | | Rust | [longport::::quote#_quote_context](https://longportapp.github.io/openapi/rust/longport//struct.quote.html#method._quote_context) | | Go | [quote.history_market_temperature](https://pkg.go.dev/github.com/longportapp/openapi-go/#quote.history_market_temperature) | | Node.js | [quote#QuoteContext](https://longportapp.github.io/openapi/nodejs/classes/quote.html#quotecontext) | ## Request
HTTP MethodGET
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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 longport::{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 longport; using namespace longport::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/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/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 | #### Calendar #### Meeting Calendar Browse upcoming shareholder meetings and company events. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.calendar._calendar_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.calendar._calendar_context) | | Rust | [longport::::calendar#_calendar_context](https://longportapp.github.io/openapi/rust/longport//struct.calendar.html#method._calendar_context) | | Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longportapp/openapi-go/#calendar.finance_calendar) | | Node.js | [calendar#CalendarContext](https://longportapp.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 opts = new FinanceCalendarOptions(); opts.category = CalendarCategory.Meeting; opts.start = "2024-01-01"; opts.end = "2024-03-31"; var resp = ctx.getFinanceCalendar(opts).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{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/longportapp/openapi-go/calendar" "github.com/longportapp/openapi-go/config" "github.com/longportapp/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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.calendar._calendar_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.calendar._calendar_context) | | Rust | [longport::::calendar#_calendar_context](https://longportapp.github.io/openapi/rust/longport//struct.calendar.html#method._calendar_context) | | Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longportapp/openapi-go/#calendar.finance_calendar) | | Node.js | [calendar#CalendarContext](https://longportapp.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) | ## 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 longport.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = CalendarContext(config) resp = ctx.finance_calendar(CalendarCategory.Split, "2026-01-01", "2026-12-31") print(resp) ``` ```python import asyncio from longport.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncCalendarContext.create(config) resp = await ctx.finance_calendar(CalendarCategory.Split, "2026-01-01", "2026-12-31") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, CalendarContext, CalendarCategory, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = CalendarContext.new(config) const resp = await ctx.financeCalendar(CalendarCategory.Split, "2026-01-01", "2026-12-31") console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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 opts = new FinanceCalendarOptions(); opts.category = CalendarCategory.Split; opts.start = "2026-01-01"; opts.end = "2026-12-31"; var resp = ctx.getFinanceCalendar(opts).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = CalendarContext::new(config); let resp = ctx.finance_calendar(CalendarCategory::Split, "2026-01-01", "2026-12-31").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::calendar; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); CalendarContext ctx = CalendarContext::create(config); ctx.finance_calendar(CalendarCategory::Split, "2026-01-01", "2026-12-31", "", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/calendar" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := calendar.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FinanceCalendar(context.Background(), "Split", "2026-01-01", "2026-12-31") 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 | | next_date | string | false | Pagination cursor; pass as `start` to fetch next page, empty when no more pages | | list | object[] | true | List of calendar date groups, see [CalendarDateGroup](#CalendarDateGroup) | ### CalendarDateGroup | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | date | string | true | Date | | count | integer | false | Number of events on this date | | infos | object[] | true | List of calendar events, see [CalendarEventInfo](#CalendarEventInfo) | ### CalendarEventInfo | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | string | false | Event ID | | symbol | string | false | Security symbol | | market | string | false | Market | | counter_name | string | false | Security name | | event_type | string | false | Event type | | activity_type | string | false | Activity type | | date | string | false | Event date | | datetime | string | false | Event datetime | | date_type | string | false | Date type | | content | string | false | Event content description | | currency | string | false | Currency | | star | integer | false | Importance rating (1-3) | | icon | string | false | Icon URL | | chart_uid | string | false | Chart identifier | | financial_market_time | string | false | Financial market time | | data_kv | object[] | false | Key-value data pairs | #### IPO Calendar Get upcoming and recent IPO listings with expected offer price and listing date. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.calendar._calendar_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.calendar._calendar_context) | | Rust | [longport::::calendar#_calendar_context](https://longportapp.github.io/openapi/rust/longport//struct.calendar.html#method._calendar_context) | | Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longportapp/openapi-go/#calendar.finance_calendar) | | Node.js | [calendar#CalendarContext](https://longportapp.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) | ## 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 longport.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = CalendarContext(config) resp = ctx.finance_calendar(CalendarCategory.Ipo, "2026-01-01", "2026-12-31") print(resp) ``` ```python import asyncio from longport.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncCalendarContext.create(config) resp = await ctx.finance_calendar(CalendarCategory.Ipo, "2026-01-01", "2026-12-31") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, CalendarContext, CalendarCategory, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = CalendarContext.new(config) const resp = await ctx.financeCalendar(CalendarCategory.Ipo, "2026-01-01", "2026-12-31") console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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 opts = new FinanceCalendarOptions(); opts.category = CalendarCategory.Ipo; opts.start = "2026-01-01"; opts.end = "2026-12-31"; var resp = ctx.getFinanceCalendar(opts).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = CalendarContext::new(config); let resp = ctx.finance_calendar(CalendarCategory::Ipo, "2026-01-01", "2026-12-31").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::calendar; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); CalendarContext ctx = CalendarContext::create(config); ctx.finance_calendar(CalendarCategory::Ipo, "2026-01-01", "2026-12-31", "", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/calendar" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := calendar.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FinanceCalendar(context.Background(), "Ipo", "2026-01-01", "2026-12-31") 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 | | next_date | string | false | Pagination cursor; pass as `start` to fetch next page, empty when no more pages | | 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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.calendar._calendar_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.calendar._calendar_context) | | Rust | [longport::::calendar#_calendar_context](https://longportapp.github.io/openapi/rust/longport//struct.calendar.html#method._calendar_context) | | Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longportapp/openapi-go/#calendar.finance_calendar) | | Node.js | [calendar#CalendarContext](https://longportapp.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) | ## 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 longport.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = CalendarContext(config) resp = ctx.finance_calendar(CalendarCategory.Dividend, "2026-01-01", "2026-12-31") print(resp) ``` ```python import asyncio from longport.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncCalendarContext.create(config) resp = await ctx.finance_calendar(CalendarCategory.Dividend, "2026-01-01", "2026-12-31") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, CalendarContext, CalendarCategory, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = CalendarContext.new(config) const resp = await ctx.financeCalendar(CalendarCategory.Dividend, "2026-01-01", "2026-12-31") console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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 opts = new FinanceCalendarOptions(); opts.category = CalendarCategory.Dividend; opts.start = "2026-01-01"; opts.end = "2026-12-31"; var resp = ctx.getFinanceCalendar(opts).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = CalendarContext::new(config); let resp = ctx.finance_calendar(CalendarCategory::Dividend, "2026-01-01", "2026-12-31").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::calendar; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); CalendarContext ctx = CalendarContext::create(config); ctx.finance_calendar(CalendarCategory::Dividend, "2026-01-01", "2026-12-31", "", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/calendar" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := calendar.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FinanceCalendar(context.Background(), "Dividend", "2026-01-01", "2026-12-31") 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 | | next_date | string | false | Pagination cursor; pass as `start` to fetch next page, empty when no more pages | | 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 release events such as CPI, GDP, and Fed meetings. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.calendar._calendar_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.calendar._calendar_context) | | Rust | [longport::::calendar#_calendar_context](https://longportapp.github.io/openapi/rust/longport//struct.calendar.html#method._calendar_context) | | Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longportapp/openapi-go/#calendar.finance_calendar) | | Node.js | [calendar#CalendarContext](https://longportapp.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) | ## 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 longport.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = CalendarContext(config) resp = ctx.finance_calendar(CalendarCategory.MacroData, "2026-01-01", "2026-12-31") print(resp) ``` ```python import asyncio from longport.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncCalendarContext.create(config) resp = await ctx.finance_calendar(CalendarCategory.MacroData, "2026-01-01", "2026-12-31") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, CalendarContext, CalendarCategory, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = CalendarContext.new(config) const resp = await ctx.financeCalendar(CalendarCategory.MacroData, "2026-01-01", "2026-12-31") console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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 opts = new FinanceCalendarOptions(); opts.category = CalendarCategory.MacroData; opts.start = "2026-01-01"; opts.end = "2026-12-31"; var resp = ctx.getFinanceCalendar(opts).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = CalendarContext::new(config); let resp = ctx.finance_calendar(CalendarCategory::MacroData, "2026-01-01", "2026-12-31").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::calendar; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); CalendarContext ctx = CalendarContext::create(config); ctx.finance_calendar(CalendarCategory::MacroData, "2026-01-01", "2026-12-31", "", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/calendar" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := calendar.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FinanceCalendar(context.Background(), "MacroData", "2026-01-01", "2026-12-31") 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 | | next_date | string | false | Pagination cursor; pass as `start` to fetch next page, empty when no more pages | | 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. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.calendar._calendar_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.calendar._calendar_context) | | Rust | [longport::::calendar#_calendar_context](https://longportapp.github.io/openapi/rust/longport//struct.calendar.html#method._calendar_context) | | Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longportapp/openapi-go/#calendar.finance_calendar) | | Node.js | [calendar#CalendarContext](https://longportapp.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) | ## 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 longport.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = CalendarContext(config) resp = ctx.finance_calendar(CalendarCategory.Report, "2026-01-01", "2026-12-31") print(resp) ``` ```python import asyncio from longport.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncCalendarContext.create(config) resp = await ctx.finance_calendar(CalendarCategory.Report, "2026-01-01", "2026-12-31") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, CalendarContext, CalendarCategory, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = CalendarContext.new(config) const resp = await ctx.financeCalendar(CalendarCategory.Report, "2026-01-01", "2026-12-31") console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.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 opts = new FinanceCalendarOptions(); opts.category = CalendarCategory.Report; opts.start = "2026-01-01"; opts.end = "2026-12-31"; var resp = ctx.getFinanceCalendar(opts).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = CalendarContext::new(config); let resp = ctx.finance_calendar(CalendarCategory::Report, "2026-01-01", "2026-12-31").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::calendar; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); CalendarContext ctx = CalendarContext::create(config); ctx.finance_calendar(CalendarCategory::Report, "2026-01-01", "2026-12-31", "", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/calendar" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := calendar.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FinanceCalendar(context.Background(), "Report", "2026-01-01", "2026-12-31") 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 | | next_date | string | false | Pagination cursor; pass as `start` to fetch next page, empty when no more pages | | 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 | [longport.openapi.calendar._calendar_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.calendar._calendar_context) | | Rust | [longport::::calendar#_calendar_context](https://longportapp.github.io/openapi/rust/longport//struct.calendar.html#method._calendar_context) | | Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longportapp/openapi-go/#calendar.finance_calendar) | | Node.js | [calendar#CalendarContext](https://longportapp.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) | ## 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 longport.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 longport.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('longport') 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.longport.*; import com.longport.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 opts = new FinanceCalendarOptions(); opts.category = CalendarCategory.Merge; opts.start = "2024-01-01"; opts.end = "2024-03-31"; var resp = ctx.getFinanceCalendar(opts).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{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/longportapp/openapi-go/calendar" "github.com/longportapp/openapi-go/config" "github.com/longportapp/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 | ### Fundamental ### Overview # Fundamental API Overview Research and market data APIs covering company fundamentals, market structure, and financial calendars. All methods are read-only and available through the SDK. ## FundamentalContext Company-level financial data and corporate information. | Method | Description | |---|---| | [company_profile](./fundamental/company-profile) | Company overview, industry, and key facts | | [financial_report](./fundamental/financial-report) | Income statement, balance sheet, and cash flow | | [valuations](./fundamental/valuations) | PE, PB, PS, EV/EBITDA and other valuation metrics | | [ratings](./fundamental/ratings) | Analyst ratings and price targets | | [dividends](./fundamental/dividends) | Historical dividend records | | [fund_holdings](./fundamental/fund-holdings) | Institutional and fund ownership | | [shareholders](./fundamental/shareholders) | Major shareholders | | [executives](./fundamental/executives) | Executive team and board members | | [corporate_actions](./fundamental/corporate-actions) | Splits, bonus issues, rights offerings | ## MarketContext Market-level data including index components, broker positions, and anomaly scanning. | Method | Description | |---|---| | [market_status](./market/market-status) | Current trading session status for each market | | [trading_stats](./market/trading-stats) | Intraday trading statistics for a symbol | | [index_components](./market/index-components) | Constituents of a market index | | [ah_premium](./market/ah-premium) | A/H share premium ratio for dual-listed stocks | | [broker_positions](./market/broker-positions) | HK broker participant holdings (CCASS) | | [unusual_items](./market/unusual-items) | Unusual price or volume movements | ## CalendarContext Financial event calendars for planning around earnings, dividends, and macro releases. | Method | Description | |---|---| | [earnings_calendar](./calendar/earnings-calendar) | Upcoming and recent earnings release dates | | [dividend_calendar](./calendar/dividend-calendar) | Ex-dividend and payment dates | | [ipo_calendar](./calendar/ipo-calendar) | IPO subscription and listing dates | | [split_calendar](./calendar/split-calendar) | Stock split effective dates | | [macro_calendar](./calendar/macro-calendar) | Economic data release schedule | #### Market #### Index Components Get the constituent stocks of an index or ETF with sorting options and rise/fall statistics. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.index_components](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.index_components) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Index or ETF symbol, e.g. `HSI.HK`, `SPY.US` | ## Request Example ```python from longport.openapi import MarketContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = MarketContext(config) resp = ctx.index_components("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncMarketContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncMarketContext.create(config) resp = await ctx.index_components("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, MarketContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = MarketContext.new(config) const resp = await ctx.index_components('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.market.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); MarketContext ctx = MarketContext.create(config)) { var resp = ctx.getIndexComponents("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, market::MarketContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = MarketContext::new(config); let resp = ctx.index_components("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::market; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); MarketContext ctx = MarketContext::create(config); ctx.index_components("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.IndexComponents(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "fall_num": 10, "flat_num": 3, "rise_num": 7, "stocks": [ { "symbol": "9988.HK", "name": "BABA-W", "market": "HK", "last_done": "140.90", "prev_close": "132.80", "chg": "0.0610", "amount": "93828577", "inflow": "18483450", "balance": "13320299492", "circulating_shares": "19192403958", "total_shares": "19192403958", "trade_status": 105, "intro": "China's largest e-commerce platform", "delay": false, "tags": [ "Top gainers" ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [IndexConstituentsResponse](#IndexConstituentsResponse) | | 400 | Bad request | None | ## Schemas ### IndexConstituentsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | rise_num | integer | false | Number of rising stocks | | fall_num | integer | false | Number of falling stocks | | flat_num | integer | false | Number of flat stocks | | stocks | object[] | true | List of constituent stocks | | ∟ symbol | string | true | Security symbol | | ∟ name | string | true | Security name | | ∟ market | string | false | Market | | ∟ last_done | string | false | Last trade price | | ∟ prev_close | string | false | Previous close | | ∟ chg | string | false | Price change percentage | | ∟ amount | string | false | Trading volume amount | | ∟ inflow | string | false | Capital inflow | | ∟ circulating_shares | string | false | Circulating shares | | ∟ total_shares | string | false | Total shares | | ∟ balance | string | false | Market cap | | ∟ trade_status | integer | false | Trading status code | | ∟ intro | string | false | Brief description | | ∟ delay | boolean | false | Whether data is delayed | | ∟ tags | string[] | false | Tags | #### A/H Premium Get the A/H premium ratio for dual-listed stocks comparing A-share and H-share prices. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.ah_premium](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.ah_premium) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | H-share symbol of a dual-listed stock, e.g. `939.HK` | ## Request Example ```python from longport.openapi import MarketContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = MarketContext(config) resp = ctx.ah_premium("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncMarketContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncMarketContext.create(config) resp = await ctx.ah_premium("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, MarketContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = MarketContext.new(config) const resp = await ctx.ah_premium('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.market.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); MarketContext ctx = MarketContext.create(config)) { var resp = ctx.getAhPremium("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, market::MarketContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = MarketContext::new(config); let resp = ctx.ah_premium("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::market; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); MarketContext ctx = MarketContext::create(config); ctx.ah_premium("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.AhPremium(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "klines": [ { "ahpremium_rate": "0.1523", "apreclose": "24.80", "aprice": "25.10", "currency_rate": "0.8920", "hpreclose": "19.20", "hprice": "19.50", "price_spread": "1.23", "timestamp": "1778198400" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [AhPremiumResponse](#AhPremiumResponse) | | 400 | Bad request | None | ## Schemas ### AhPremiumResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | klines | object[] | true | A/H premium daily kline records | | ∟ timestamp | string | false | Unix timestamp | | ∟ ahpremium_rate | string | false | A/H premium rate | | ∟ aprice | string | false | A-share price (CNY) | | ∟ apreclose | string | false | A-share previous close (CNY) | | ∟ hprice | string | false | H-share price (HKD) | | ∟ hpreclose | string | false | H-share previous close (HKD) | | ∟ currency_rate | string | false | CNH/HKD exchange rate | | ∟ price_spread | string | false | Price spread | #### Broker Positions View broker holding positions for HK-listed stocks, including top buyers/sellers and full detail. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.broker_positions](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.broker_positions) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | HK security symbol, e.g. `700.HK` | ## Request Example ```python from longport.openapi import MarketContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = MarketContext(config) resp = ctx.broker_positions("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncMarketContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncMarketContext.create(config) resp = await ctx.broker_positions("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, MarketContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = MarketContext.new(config) const resp = await ctx.broker_positions('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.market.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); MarketContext ctx = MarketContext.create(config)) { var resp = ctx.getBrokerPositions("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, market::MarketContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = MarketContext::new(config); let resp = ctx.broker_positions("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::market; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); MarketContext ctx = MarketContext::create(config); ctx.broker_positions("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.BrokerPositions(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "buy": [ { "parti_number": "B01224", "name": "HSBC", "chg": "5000000", "strong": true } ], "sell": [ { "parti_number": "B01274", "name": "Goldman Sachs HK", "chg": "-3000000", "strong": false } ], "updated_at": "2026.05.13" } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [BrokerHoldingResponse](#BrokerHoldingResponse) | | 400 | Bad request | None | ## Schemas ### BrokerHoldingResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | buy | object[] | false | Top buying brokers | | ∟ parti_number | string | true | Broker participant number | | ∟ name | string | false | Broker name | | ∟ chg | string | false | Position change | | ∟ strong | boolean | false | Whether marked as strong holder | | sell | object[] | false | Top selling brokers | | ∟ parti_number | string | true | Broker participant number | | ∟ name | string | false | Broker name | | ∟ chg | string | false | Position change | | ∟ strong | boolean | false | Whether marked as strong holder | | updated_at | string | false | Last update timestamp | #### Broker Holding Detail Get full broker holding detail list for an HK-listed security (all brokers and their positions). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.broker_holding_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.broker_holding_detail) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | HK security symbol, e.g. `700.HK` | ## Request Example ```python from longport.openapi import MarketContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = MarketContext(config) resp = ctx.broker_holding_detail("700.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncMarketContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncMarketContext.create(config) resp = await ctx.broker_holding_detail("700.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, MarketContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = MarketContext.new(config) const resp = await ctx.brokerHoldingDetail('700.HK') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.market.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); MarketContext ctx = MarketContext.create(config)) { var resp = ctx.getBrokerHoldingDetail("700.HK").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, market::MarketContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = MarketContext::new(config); let resp = ctx.broker_holding_detail("700.HK").await?; println!("{:?}", resp); Ok(()) } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.BrokerHoldingDetail(context.Background(), "700.HK") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "updated_at": "2026.05.13", "list": [ { "parti_number": "B01224", "name": "HSBC Securities", "strong": false, "shares": { "value": "25100", "chg_1": "4000.0000", "chg_5": "6100.0000", "chg_20": "12600.0000", "chg_60": "8800.0000" }, "ratio": { "value": "0.0025", "chg_1": "0.0004", "chg_5": "0.0006", "chg_20": "0.0012", "chg_60": "0.0009" } } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [BrokerHoldingDetailResponse](#BrokerHoldingDetailResponse) | | 400 | Bad request | None | ## Schemas ### BrokerHoldingDetailResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | updated_at | string | false | Last update date | | list | object[] | true | Broker holding detail records, see [BrokerHoldingItem](#BrokerHoldingItem) | ### BrokerHoldingItem | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | parti_number | string | true | Broker participant number | | name | string | false | Broker name | | strong | boolean | false | Whether marked as strong holder | | shares | object | false | Holding share counts | | shares.value | string | false | Current shares held | | shares.chg_1 | string | false | 1-day change | | shares.chg_5 | string | false | 5-day change | | shares.chg_20 | string | false | 20-day change | | shares.chg_60 | string | false | 60-day change | | ratio | object | false | Holding ratio | | ratio.value | string | false | Current ratio | | ratio.chg_1 | string | false | 1-day ratio change | | ratio.chg_5 | string | false | 5-day ratio change | | ratio.chg_20 | string | false | 20-day ratio change | | ratio.chg_60 | string | false | 60-day ratio change | #### Broker Holding Daily Get daily holding history for a specific broker in an HK-listed security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.broker_holding_daily](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.broker_holding_daily) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | HK security symbol, e.g. `700.HK` | | broker_id | string | YES | Broker participant ID, e.g. `B01224` | ## Request Example ```python from longport.openapi import MarketContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = MarketContext(config) resp = ctx.broker_holding_daily("700.HK", "B01224") print(resp) ``` ```python import asyncio from longport.openapi import AsyncMarketContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncMarketContext.create(config) resp = await ctx.broker_holding_daily("700.HK", "B01224") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, MarketContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = MarketContext.new(config) const resp = await ctx.brokerHoldingDaily('700.HK', 'B01224') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.market.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); MarketContext ctx = MarketContext.create(config)) { var resp = ctx.getBrokerHoldingDaily("700.HK", "B01224").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, market::MarketContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = MarketContext::new(config); let resp = ctx.broker_holding_daily("700.HK", "B01224").await?; println!("{:?}", resp); Ok(()) } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.BrokerHoldingDaily(context.Background(), "700.HK", "B01224") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "list": [ { "date": "2026.05.13", "holding": "22903430", "chg": "7029132.0000", "ratio": "0.0025" }, { "date": "2026.05.12", "holding": "15874298", "chg": "-2150000.0000", "ratio": "0.0017" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [BrokerHoldingDailyResponse](#BrokerHoldingDailyResponse) | | 400 | Bad request | None | ## Schemas ### BrokerHoldingDailyHistoryResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | object[] | true | Daily holding history records | | ∟ date | string | true | Date (e.g. `2026.05.13`) | | ∟ holding | string | false | Total shares held | | ∟ chg | string | false | Daily change in shares | | ∟ ratio | string | false | Holding ratio | #### A/H Premium Intraday Get intraday A/H premium timeseries data for a dual-listed security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.ah_premium_intraday](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.ah_premium_intraday) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | HK-side symbol of a dual-listed stock, e.g. `939.HK` | ## Request Example ```python from longport.openapi import MarketContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = MarketContext(config) resp = ctx.ah_premium_intraday("939.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncMarketContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncMarketContext.create(config) resp = await ctx.ah_premium_intraday("939.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, MarketContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = MarketContext.new(config) const resp = await ctx.ahPremiumIntraday('939.HK') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.market.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); MarketContext ctx = MarketContext.create(config)) { var resp = ctx.getAhPremiumIntraday("939.HK").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, market::MarketContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = MarketContext::new(config); let resp = ctx.ah_premium_intraday("939.HK").await?; println!("{:?}", resp); Ok(()) } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.AhPremiumIntraday(context.Background(), "939.HK") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "klines": [ { "ahpremium_rate": "0.1523", "apreclose": "24.80", "aprice": "25.10", "currency_rate": "0.8920", "hpreclose": "19.20", "hprice": "19.50", "price_spread": "1.23", "timestamp": "1778198400" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [AhPremiumIntradayResponse](#AhPremiumIntradayResponse) | | 400 | Bad request | None | ## Schemas ### AhPremiumIntradayResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | klines | object[] | true | Intraday A/H premium kline data, see [AhPremiumKline](#AhPremiumKline) | | ∟ timestamp | string | false | Unix timestamp | | ∟ ahpremium_rate | string | false | A/H premium rate | | ∟ aprice | string | false | A-share price (CNY) | | ∟ apreclose | string | false | A-share previous close (CNY) | | ∟ hprice | string | false | H-share price (HKD) | | ∟ hpreclose | string | false | H-share previous close (HKD) | | ∟ currency_rate | string | false | CNH/HKD exchange rate | | ∟ price_spread | string | false | Price spread | #### Trading Stats Get trade statistics showing price distribution by volume for a security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.market._market_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.market._market_context) | | Rust | [longport::::market#_market_context](https://longportapp.github.io/openapi/rust/longport//struct.market.html#method._market_context) | | Go | [market.trading_stats](https://pkg.go.dev/github.com/longportapp/openapi-go/#market.trading_stats) | | Node.js | [market#MarketContext](https://longportapp.github.io/openapi/nodejs/classes/market.html#marketcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `700.HK` | ## Request Example ```python from longport.openapi import MarketContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = MarketContext(config) resp = ctx.trading_stats("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncMarketContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncMarketContext.create(config) resp = await ctx.trading_stats("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, MarketContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = MarketContext.new(config) const resp = await ctx.trading_stats('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.market.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); MarketContext ctx = MarketContext.create(config)) { var resp = ctx.getTradingStats("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, market::MarketContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = MarketContext::new(config); let resp = ctx.trading_stats("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::market; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); MarketContext ctx = MarketContext::create(config); ctx.trading_stats("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/market" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := market.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.TradingStats(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "statistics": { "avgprice": "210.50", "buy": "45000000", "sell": "38000000", "neutral": "12000000", "total_amount": "95000000", "trades_count": "125000", "preclose": "208.20", "timestamp": "1778198400", "trade_date": [ "2026-05-13" ] }, "trades": [ { "price": "210.00", "buy_amount": "5000000", "sell_amount": "4000000", "neutral_amount": "1000000" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [TradeStatsResponse](#TradeStatsResponse) | | 400 | Bad request | None | ## Schemas ### TradeStatsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | statistics | object | true | Aggregate trade statistics | | statistics.avgprice | string | false | Average trade price | | statistics.buy | string | false | Total buy volume | | statistics.sell | string | false | Total sell volume | | statistics.neutral | string | false | Total neutral volume | | statistics.total_amount | string | false | Total traded amount | | statistics.trades_count | string | false | Total trade count | | statistics.preclose | string | false | Previous close price | | statistics.timestamp | string | false | Statistics timestamp | | statistics.trade_date | string[] | false | Trading dates included | | trades | object[] | false | Price-level trade distribution | | ∟ price | string | true | Price level | | ∟ buy_amount | string | false | Buy amount at this price | | ∟ sell_amount | string | false | Sell amount at this price | | ∟ neutral_amount | string | false | Neutral amount at this price | #### Fundamental #### Macroeconomic Historical Data Get historical releases for a specific macroeconomic indicator — actual values, forecasts, previous values, and next release dates. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.macroeconomic](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.macroeconomic) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | indicator_code | string | YES | Indicator code from `macroeconomic_indicators` | | start_date | string | NO | Start date in `YYYY-MM-DD` format | | end_date | string | NO | End date in `YYYY-MM-DD` format | | limit | int | NO | Max records. Default: 100, max: 100 | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.macroeconomic("62267", start_date="2024-01-01", end_date="2024-12-31") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.macroeconomic("62267", start_date="2024-01-01", end_date="2024-12-31") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.macroeconomic('62267', { startDate: '2024-01-01', endDate: '2024-12-31' }) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getMacroeconomic("62267", "2024-01-01", "2024-12-31", null, null).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.macroeconomic("62267", Some("2024-01-01"), Some("2024-12-31"), None, None).await?; println!("{:?}", resp); Ok(()) } ``` ## Response ### Response Example ```json { "count": 24, "info": { "indicator_code": "62267", "country": "US", "name": "Non-Farm Payroll", "periodicity": "Monthly", "describe": "...", "importance": 3 }, "data": [ { "period": "2024-12-01", "release_at": 1735900200, "actual_value": "256000", "previous_value": "212000", "forecast_value": "165000" } ] } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [MacroeconomicResponse](#MacroeconomicResponse) | | 400 | Bad request | None | ## Schemas ### MacroeconomicResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | info | MacroeconomicIndicator | true | Indicator metadata | | data | Macroeconomic[] | true | Historical data points | | count | int | true | Total number of data points | ### Macroeconomic | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | period | string | true | Statistical period (e.g. `2024-12-01`, `2024-Q4`) | | release_at | int | false | Unix timestamp of release datetime | | actual_value | string | true | Actual released value | | previous_value | string | true | Previous period value | | forecast_value | string | true | Market consensus forecast | #### Analyst Ratings Get analyst institution ratings and consensus data for a security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.ratings](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.ratings) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.ratings("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.ratings("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.ratings('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getRatings("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.ratings("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.ratings("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Ratings(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "industry_name": "Technology Hardware, Storage and Peripherals", "industry_rank": 2, "multi_letter": "B", "multi_score": "0.32", "multi_score_change": -1, "scale_txt_name": "Large", "style_txt_name": "Blend", "report_period_txt": "Rating based on Fiscal Year 2026 s.a.", "ratings_json": "[]" } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [StockRatingsResponse](#StockRatingsResponse) | | 400 | Bad request | None | ## Schemas ### StockRatingsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | industry_name | string | false | Industry name | | industry_rank | integer | false | Rank within industry | | multi_letter | string | false | Rating letter grade | | multi_score | string | false | Composite score | | multi_score_change | integer | false | Score change vs previous period | | report_period_txt | string | false | Report period description | | scale_txt_name | string | false | Rating scale name | | style_txt_name | string | false | Rating style name | | ratings_json | string | false | Raw rating detail JSON | #### Forecast EPS Get EPS forecasts and analyst consensus estimates. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.forecast_eps](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.forecast_eps) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `TSLA.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.forecast_eps("TSLA.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.forecast_eps("TSLA.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.forecastEps('TSLA.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getForecastEps("TSLA.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.forecast_eps("TSLA.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.forecast_eps("TSLA.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ForecastEps(context.Background(), "TSLA.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "items": [ { "forecast_end_date": "1727827200", "forecast_eps_highest": "3.71", "forecast_eps_lowest": "2.37", "forecast_eps_mean": "2.998", "forecast_eps_median": "3.02", "forecast_start_date": "1727827200", "institution_down": 0, "institution_total": 0, "institution_up": 0 } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ForecastEps](#ForecastEps) | | 400 | Bad request | None | ## Schemas ### ForecastEps | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | items | object[] | true | List of EPS forecast periods | | ∟ forecast_start_date | string | false | Forecast period start date | | ∟ forecast_end_date | string | false | Forecast period end date | | ∟ forecast_eps_mean | string | false | Mean EPS estimate | | ∟ forecast_eps_median | string | false | Median EPS estimate | | ∟ forecast_eps_highest | string | false | Highest EPS estimate | | ∟ forecast_eps_lowest | string | false | Lowest EPS estimate | | ∟ institution_total | integer | false | Total contributing institutions | | ∟ institution_up | integer | false | Institutions revising up | | ∟ institution_down | integer | false | Institutions revising down | #### Dividends Get dividend history and upcoming dividend announcements for a security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.dividends](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.dividends) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | start_date | string | NO | Start date in `YYYY-MM-DD` format | | end_date | string | NO | End date in `YYYY-MM-DD` format | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.dividends("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.dividends("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.dividends('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getDividends("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.dividends("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.dividends("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Dividends(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "list": [ { "id": "12345", "symbol": "AAPL.US", "ex_date": "2026-02-07", "payment_date": "2026-02-13", "record_date": "2026-02-10", "desc": "Cash dividend 0.25 USD" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [DividendsResponse](#DividendsResponse) | | 400 | Bad request | None | ## Schemas ### DividendsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | object[] | true | Dividend records | | ∟ id | string | false | Dividend event ID | | ∟ symbol | string | false | Security symbol | | ∟ desc | string | false | Dividend description | | ∟ ex_date | string | false | Ex-dividend date | | ∟ payment_date | string | false | Payment date | | ∟ record_date | string | false | Record date | #### Valuation Comparison Compare valuation metrics (PE/PB/PS/market cap/close price) across multiple stocks. When no comparison symbols are provided, the server automatically selects peers from the same industry. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.valuation_comparison](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.valuation_comparison) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Primary security symbol, e.g. `AAPL.US` | | currency | string | YES | Result currency: `USD`, `HKD`, or `CNY` | | comparison_symbols | string[] | NO | Symbols to compare against; if omitted, the server auto-selects industry peers | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) # Auto-select peers resp = ctx.valuation_comparison("AAPL.US", "USD") # Specify comparison symbols resp = ctx.valuation_comparison("AAPL.US", "USD", ["MSFT.US", "GOOGL.US"]) print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.valuation_comparison("AAPL.US", "USD", ["MSFT.US", "GOOGL.US"]) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.valuationComparison('AAPL.US', 'USD', ['MSFT.US', 'GOOGL.US']) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; import java.util.Arrays; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getValuationComparison("AAPL.US", "USD", Arrays.asList("MSFT.US", "GOOGL.US")).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.valuation_comparison("AAPL.US", "USD", Some(vec!["MSFT.US", "GOOGL.US"])).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.valuation_comparison("AAPL.US", "USD", {"MSFT.US", "GOOGL.US"}, [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ValuationComparison(context.Background(), "AAPL.US", "USD", []string{"MSFT.US", "GOOGL.US"}) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "list": [ { "counter_id": "ST/US/AAPL", "name": "Apple Inc.", "currency": "USD", "market_value": "3241500000000", "price_close": "213.49", "pe": "32.15", "pb": "50.21", "ps": "8.04", "roe": "136.45", "eps": "6.43", "bps": "4.38", "dps": "0.99", "div_yld": "0.46", "assets": "371082000000", "history": [ { "date": "1622520000", "pe": "37.56", "pb": "30.16", "ps": "6.41" }, { "date": "1625112000", "pe": "41.49", "pb": "35.64", "ps": "6.60" } ] }, { "counter_id": "ST/US/MSFT", "name": "Microsoft", "currency": "USD", "market_value": "3085000000000", "price_close": "415.32", "pe": "35.42", "pb": "12.87", "ps": "12.61", "roe": "38.21", "eps": "11.72", "bps": "32.28", "dps": "3.32", "div_yld": "0.80", "assets": "512163000000", "history": [ { "date": "1622520000", "pe": "33.12", "pb": "11.94", "ps": "11.84" } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ValuationComparisonResponse](#ValuationComparisonResponse) | | 400 | Bad request | None | ## Schemas ### ValuationComparisonResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | object[] | false | Valuation comparison list | | ∟ counter_id | string | false | Counter ID (e.g. `ST/US/AAPL`) | | ∟ name | string | false | Security name | | ∟ currency | string | false | Currency of the values | | ∟ market_value | string | false | Market capitalisation | | ∟ price_close | string | false | Latest closing price | | ∟ pe | string | false | P/E ratio (TTM) | | ∟ pb | string | false | P/B ratio | | ∟ ps | string | false | P/S ratio (TTM) | | ∟ roe | string | false | Return on equity (%) | | ∟ eps | string | false | Earnings per share (TTM) | | ∟ bps | string | false | Book value per share | | ∟ dps | string | false | Dividends per share (TTM) | | ∟ div_yld | string | false | Dividend yield (%) | | ∟ assets | string | false | Total assets | | ∟ history | object[] | false | Historical valuation time series | | ∟ ∟ date | string | false | Date as Unix timestamp (seconds) | | ∟ ∟ pe | string | false | Historical PE | | ∟ ∟ pb | string | false | Historical PB | | ∟ ∟ ps | string | false | Historical PS | #### Shareholder Detail Get holding history and trade details for a specific shareholder. The `object_id` comes from the `shareholder_top` response. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.shareholder_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.shareholder_detail) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | object_id | integer | YES | Shareholder ID from `shareholder_top` `object_id` field | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.shareholder_detail("AAPL.US", 19463) print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.shareholder_detail("AAPL.US", 19463) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.shareholderDetail('AAPL.US', 19463) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getShareholderDetail("AAPL.US", 19463L).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.shareholder_detail("AAPL.US", 19463).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.shareholder_detail("AAPL.US", 19463, [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ShareholderDetail(context.Background(), "AAPL.US", 19463) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "name": "The Vanguard Group, Inc.", "title": "", "avatar": "", "owner_source": "Institution", "holding_periods": [], "holding_details": [], "holding_summary": [], "trading_periods": ["Past 1 Month", "Past 3 Months", "Past 1 Year", "Past 3 Years"], "tradings": [ { "period": "Past 1 Month", "accum_buy": "8500000.00", "accum_sell": "2687264.00", "net_buy": "5812736.00", "trading_details": [ { "trading_date": "2025-12-18", "trading_shares": "5200000", "trading_price": "248.12", "trading_type": "Buy" } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ShareholderDetailResponse](#ShareholderDetailResponse) | | 400 | Bad request | None | ## Schemas ### ShareholderDetailResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | name | string | false | Shareholder name | | title | string | false | Shareholder title / type | | avatar | string | false | Avatar URL | | owner_source | string | false | Shareholder type: `Company`, `Institution`, `Person`, `Insider` | | holding_periods | string[] | false | Available holding periods | | holding_details | object[] | false | Holding detail records | | holding_summary | object[] | false | Holding summary records | | trading_periods | string[] | false | Available trading periods (e.g. `Past 1 Month`, `Past 3 Months`) | | tradings | object[] | false | Trade aggregates per period | | ∟ period | string | false | Period label (e.g. `Past 1 Month`) | | ∟ accum_buy | string | false | Cumulative shares bought in this period | | ∟ accum_sell | string | false | Cumulative shares sold in this period | | ∟ net_buy | string | false | Net shares bought (buy minus sell) in this period | | ∟ trading_details | object[] | false | Individual transactions within the period | | ∟ ∟ trading_date | string | false | Trade date | | ∟ ∟ trading_shares | string | false | Number of shares traded | | ∟ ∟ trading_price | string | false | Trade price | | ∟ ∟ trading_type | string | false | Trade direction: `Buy` or `Sell` | > Note: Some fields return an empty string or empty array when data is unavailable. #### Corporate Actions Get corporate action history (splits, mergers, spin-offs, rights issues) for a security. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.corporate_actions](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.corporate_actions) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | start_date | string | NO | Start date in `YYYY-MM-DD` format | | end_date | string | NO | End date in `YYYY-MM-DD` format | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.corporate_actions("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.corporate_actions("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.corporate_actions('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getCorporateActions("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.corporate_actions("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.corporate_actions("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.CorporateActions(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "items": [ { "id": "622620", "action": "DividendExDate", "act_type": "Distribution Plan", "act_desc": "Cash dividend 0.27 USD", "date": "20260514", "date_str": "05.14", "date_type": "Payment Date", "date_zone": "EST", "delay_content": "", "is_delay": false, "recent": false, "live": null } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [CorporateActionsResponse](#CorporateActionsResponse) | | 400 | Bad request | None | ## Schemas ### CorporateActionsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | items | object[] | true | Corporate action list | | ∟ id | string | false | Action ID | | ∟ act_desc | string | false | Action description | | ∟ act_type | string | false | Action type category | | ∟ action | string | false | Action code (e.g. `DividendExDate`) | | ∟ date | string | false | Event date (YYYYMMDD) | | ∟ date_str | string | false | Short display date (MM.DD) | | ∟ date_type | string | false | Date type label (e.g. Payment Date) | | ∟ date_zone | string | false | Time zone (e.g. EST) | | ∟ delay_content | string | false | Delay content description | | ∟ is_delay | boolean | false | Whether the event is delayed | | ∟ live | boolean | false | Whether currently live | | ∟ recent | boolean | false | Whether this is a recent event | #### Institution Rating Get analyst institution rating snapshot (rating distribution and average target price). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.institution_rating](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.institution_rating) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `TSLA.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.institution_rating("TSLA.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.institution_rating("TSLA.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.institutionRating('TSLA.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getInstitutionRating("TSLA.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.institution_rating("TSLA.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.institution_rating("TSLA.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.InstitutionRating(context.Background(), "TSLA.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "latest": { "evaluate": { "buy": 18, "hold": 17, "sell": 4, "no_opinion": 4, "over": 5, "under": 3, "total": 51, "start_date": "1778198400", "end_date": "0" }, "industry_id": 87676, "industry_mean": 10, "industry_median": 4, "industry_name": "Automobiles", "industry_rank": 1, "industry_total": 30, "target": { "highest_price": "600.000", "lowest_price": "123.000", "prev_close": "428.35", "start_date": "1778198400", "end_date": "0" } }, "summary": { "ccy_symbol": "$", "change": "0", "recommend": "Buy", "updated_at": "1778198400", "evaluate": { "buy": 18, "hold": 17, "sell": 4 }, "target": { "average_target": "350.00", "highest_price": "600.000", "lowest_price": "123.000" } } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [InstitutionRatingResponse](#InstitutionRatingResponse) | | 400 | Bad request | None | ## Schemas ### InstitutionRatingResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | latest | object | true | Latest analyst rating snapshot | | latest.evaluate | object | true | Rating distribution | | latest.evaluate.buy | integer | false | Buy ratings count | | latest.evaluate.hold | integer | false | Hold ratings count | | latest.evaluate.sell | integer | false | Sell ratings count | | latest.evaluate.over | integer | false | Outperform count | | latest.evaluate.under | integer | false | Underperform count | | latest.evaluate.no_opinion | integer | false | No opinion count | | latest.evaluate.total | integer | false | Total analyst count | | latest.evaluate.start_date | string | false | Period start date | | latest.evaluate.end_date | string | false | Period end date | | latest.industry_id | integer | false | Industry ID | | latest.industry_name | string | false | Industry name | | latest.industry_rank | integer | false | Rank within industry | | latest.industry_total | integer | false | Total stocks in industry | | latest.industry_mean | integer | false | Industry mean rating | | latest.industry_median | integer | false | Industry median rating | | latest.target | object | false | Price target range | | latest.target.highest_price | string | false | Highest target price | | latest.target.lowest_price | string | false | Lowest target price | | latest.target.prev_close | string | false | Previous close price | | latest.target.start_date | string | false | Period start date | | latest.target.end_date | string | false | Period end date | | summary | object | false | Consensus rating snapshot | | summary.recommend | object | false | Recommendation distribution mapping | | summary.change | string | false | Price change value | | summary.ccy_symbol | string | false | Currency symbol | | summary.evaluate | object | false | Rating distribution counts | | summary.evaluate.buy | integer | false | Buy count | | summary.evaluate.strong_buy | integer | false | Strong buy count | | summary.evaluate.hold | integer | false | Hold count | | summary.evaluate.sell | integer | false | Sell count | | summary.evaluate.under | integer | false | Underperform count | | summary.target | string | false | Consensus average target price | | summary.updated_at | string | false | Last update date string | #### ETF Asset Allocation Get ETF asset allocation including holdings, regional distribution, asset class, and industry breakdown. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.etf_asset_allocation](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.etf_asset_allocation) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | ETF security symbol, e.g. `QQQ.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.etf_asset_allocation("QQQ.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.etf_asset_allocation("QQQ.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.etf_asset_allocation('QQQ.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getEtfAssetAllocation("QQQ.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.etf_asset_allocation("QQQ.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.etf_asset_allocation("QQQ.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.EtfAssetAllocation(context.Background(), "QQQ.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "info": [ { "report_date": "20260601", "asset_type": "Holdings", "lists": [ { "name": "NVIDIA Corp", "code": "NVDA", "position_ratio": "0.0861114", "symbol": "NVDA.US", "name_locales": { "zh-CN": "英伟达" }, "holding_detail": { "industry_id": "10101010", "industry_name": "Semiconductors", "index": "BK/US/CP99000", "index_name": "S&P 500" } } ] }, { "report_date": "20260601", "asset_type": "Regional", "lists": [ { "name": "United States", "code": "", "position_ratio": "0.9823", "symbol": "", "name_locales": {} } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [AssetAllocationResponse](#AssetAllocationResponse) | | 400 | Bad request | None | ## Schemas ### AssetAllocationResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | info | object[] | true | Asset allocation groups, see [AssetAllocationGroup](#AssetAllocationGroup) | ### AssetAllocationGroup | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | report_date | string | false | Report date (e.g. `20260601`) | | asset_type | string | false | Element type: `Holdings`, `Regional`, `AssetClass`, `Industry` | | lists | object[] | true | Allocation items, see [AssetAllocationItem](#AssetAllocationItem) | ### AssetAllocationItem | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | name | string | false | Element name | | code | string | false | Security code (holdings only, e.g. `NVDA`) | | position_ratio | string | false | Position ratio (e.g. `0.0861114`) | | symbol | string | false | Security symbol (holdings only, e.g. `NVDA.US`) | | name_locales | object | false | Localized names (locale → name) | | holding_detail | object | false | Holding detail (holdings only), see [HoldingDetail](#HoldingDetail) | ### HoldingDetail | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | industry_id | string | false | Industry ID | | industry_name | string | false | Industry name | | index | string | false | Index counter ID (e.g. `BK/US/CP99000`) | | index_name | string | false | Index name | #### Business Segments History Get historical business segment revenue trends across reporting periods. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.business_segments_history](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.business_segments_history) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | report | string | NO | Report type: `qf` (quarterly) / `saf` (semi-annual) / `af` (annual) | | cate | string | NO | Segment category filter | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.business_segments_history("AAPL.US", report="qf") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.business_segments_history("AAPL.US", report="qf") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.businessSegmentsHistory('AAPL.US', { report: 'qf' }) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getBusinessSegmentsHistory("AAPL.US", "qf", null).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.business_segments_history("AAPL.US", Some("qf"), None).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.business_segments_history("AAPL.US", "qf", "", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.BusinessSegmentsHistory(context.Background(), "AAPL.US", "qf", "") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "historical": [ { "date": "20260331", "total": "124300000000", "currency": "USD", "business": [ {"name": "美洲", "percent": "40.80", "value": "31968000000"}, {"name": "欧洲", "percent": "23.64", "value": "18521000000"}, {"name": "大中华区", "percent": "20.72", "value": "16233000000"} ], "regionals": [] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [BusinessSegmentsHistoryResponse](#BusinessSegmentsHistoryResponse) | | 400 | Bad request | None | ## Schemas ### BusinessSegmentsHistoryResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | historical | object[] | false | Historical period snapshots | | ∟ date | string | false | Report period in YYYYMMDD format, e.g. `20260331` | | ∟ total | string | false | Total revenue for the period | | ∟ currency | string | false | Currency code | | ∟ business | object[] | false | Business segment list | | ∟ ∟ name | string | false | Segment name | | ∟ ∟ percent | string | false | Revenue share percentage, e.g. `40.80` | | ∟ ∟ value | string | false | Absolute revenue value | | ∟ regionals | object[] | false | Regional segment list (typically empty) | | ∟ ∟ name | string | false | Region name | | ∟ ∟ percent | string | false | Revenue share percentage | | ∟ ∟ value | string | false | Absolute revenue value | #### Dividend Detail Get detailed dividend information including declared, ex-dividend, and payment dates. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.dividend_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.dividend_detail) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.dividend_detail("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.dividend_detail("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.dividendDetail('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getDividendDetail("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.dividend_detail("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.dividend_detail("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.DividendDetail(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "list": [ { "id": "12345", "symbol": "AAPL.US", "ex_date": "2026-02-07", "payment_date": "2026-02-13", "record_date": "2026-02-10", "desc": "Cash dividend 0.25 USD" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [DividendList](#DividendList) | | 400 | Bad request | None | ## Schemas ### DividendList | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | object[] | true | List of dividend records | | ∟ id | string | false | Dividend event ID | | ∟ symbol | string | false | Security symbol | | ∟ desc | string | false | Dividend description | | ∟ ex_date | string | false | Ex-dividend date (YYYY-MM-DD) | | ∟ record_date | string | false | Record date (YYYY-MM-DD) | | ∟ payment_date | string | false | Payment date (YYYY-MM-DD) | #### Financial Report Snapshot Get an AI-generated earnings summary, revenue/EBIT/EPS forecast vs actual (beat/miss analysis), and key financial ratios. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.financial_report_snapshot](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.financial_report_snapshot) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | report | string | NO | Report type: `qf` (quarterly) / `saf` (semi-annual) / `af` (annual) | | fiscal_year | uint32 | NO | Fiscal year, e.g. `2024` | | fiscal_period | string | NO | Fiscal period, e.g. `1` / `2` / `3` / `4` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.financial_report_snapshot("AAPL.US", report="qf", fiscal_year=2024, fiscal_period="4") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.financial_report_snapshot("AAPL.US", report="qf", fiscal_year=2024, fiscal_period="4") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.financialReportSnapshot('AAPL.US', { report: 'qf', fiscalYear: 2024, fiscalPeriod: '4' }) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getFinancialReportSnapshot("AAPL.US", "qf", 2024, "4").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.financial_report_snapshot("AAPL.US", Some("qf"), Some(2024), Some("4")).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.financial_report_snapshot("AAPL.US", "qf", 2024, "4", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FinancialReportSnapshot(context.Background(), "AAPL.US", "qf", 2024, "4") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "name": "苹果", "ticker": "AAPL", "fp_start": "2025.12.28", "fp_end": "2026.03.28", "currency": "USD", "report_desc": "概要:苹果(AAPL)的营业收入是 1112 亿(+16.6%);每股收益是 2.01(+21.82%)。", "fo_revenue": {"value": "111184000000.0000", "yoy": "16.6", "cmp_desc": "", "est_value": ""}, "fo_ebit": {"value": "35885000000.0000", "yoy": "21.28", "cmp_desc": "", "est_value": ""}, "fo_eps": {"value": "2.0100", "yoy": "21.82", "cmp_desc": "", "est_value": ""}, "fr_revenue": {"value": "111184000000.0000", "yoy": "16.6"}, "fr_profit": {"value": "29578000000.0000", "yoy": "19.36"}, "fr_roe_ttm": "141.4705", "fr_profit_margin": "26.6027", "fr_debt_assets_ratio": "71.3025" } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [FinancialReportSnapshotResponse](#FinancialReportSnapshotResponse) | | 400 | Bad request | None | ## Schemas ### FinancialReportSnapshotResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | name | string | false | Company name | | ticker | string | false | Ticker symbol without market suffix, e.g. `AAPL` | | fp_start | string | false | Fiscal period start date in `YYYY.MM.DD` format | | fp_end | string | false | Fiscal period end date in `YYYY.MM.DD` format | | currency | string | false | Currency code | | report_desc | string | false | AI-generated earnings summary | | fo_revenue | object | false | Revenue forecast vs actual, see [ForecastMetric](#ForecastMetric) | | fo_ebit | object | false | EBIT forecast vs actual, see [ForecastMetric](#ForecastMetric) | | fo_eps | object | false | EPS forecast vs actual, see [ForecastMetric](#ForecastMetric) | | fr_revenue | object | false | Reported revenue, see [ReportedMetric](#ReportedMetric) | | fr_profit | object | false | Reported net profit, see [ReportedMetric](#ReportedMetric) | | fr_operate_cash | object | false | Operating cash flow, see [ReportedMetric](#ReportedMetric) | | fr_invest_cash | object | false | Investing cash flow, see [ReportedMetric](#ReportedMetric) | | fr_finance_cash | object | false | Financing cash flow, see [ReportedMetric](#ReportedMetric) | | fr_total_assets | object | false | Total assets, see [ReportedMetric](#ReportedMetric) | | fr_total_liability | object | false | Total liabilities, see [ReportedMetric](#ReportedMetric) | | fr_roe_ttm | string | false | ROE TTM as percentage, e.g. `141.47` | | fr_profit_margin | string | false | Net profit margin as percentage | | fr_profit_margin_ttm | string | false | Net profit margin TTM as percentage | | fr_asset_turn_ttm | string | false | Asset turnover TTM as percentage | | fr_leverage_ttm | string | false | Leverage TTM as percentage | | fr_debt_assets_ratio | string | false | Debt-to-assets ratio as percentage | ### ForecastMetric | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | value | string | false | Actual value | | yoy | string | false | Year-over-year growth as percentage, e.g. `16.6` | | cmp_desc | string | false | Beat/miss description (may be empty) | | est_value | string | false | Consensus estimate (may be empty) | ### ReportedMetric | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | value | string | false | Value | | yoy | string | false | Year-over-year growth as percentage | #### Business Segments Get the current-period revenue segment breakdown for a listed company. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.business_segments](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.business_segments) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.business_segments("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.business_segments("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.businessSegments('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getBusinessSegments("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.business_segments("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.business_segments("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.BusinessSegments(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "date": "20260331", "total": "124300000000", "currency": "USD", "business": [ {"name": "iPhone", "percent": "56.19"}, {"name": "Services", "percent": "21.96"}, {"name": "Mac", "percent": "8.04"}, {"name": "iPad", "percent": "7.00"}, {"name": "Wearables", "percent": "6.81"} ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [BusinessSegmentsResponse](#BusinessSegmentsResponse) | | 400 | Bad request | None | ## Schemas ### BusinessSegmentsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | date | string | false | Report period in YYYYMMDD format, e.g. `20260331` | | total | string | false | Total revenue for the period | | currency | string | false | Currency code, e.g. `USD` | | business | object[] | false | Business segment list | | ∟ name | string | false | Segment name | | ∟ percent | string | false | Revenue share percentage, e.g. `40.56` | #### Valuation History Get historical valuation metric time series (PE, PB, PS, dividend yield). ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.valuation_history](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.valuation_history) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.valuation_history("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.valuation_history("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.valuationHistory('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getValuationHistory("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.valuation_history("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.valuation_history("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ValuationHistory(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "history": { "metrics": { "pe": { "desc": "P/E Ratio", "high": "35.2", "low": "18.1", "median": "26.5", "list": [ { "timestamp": "1622520000", "value": "28.5" } ] }, "pb": null, "ps": null } } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ValuationHistoryResponse](#ValuationHistoryResponse) | | 400 | Bad request | None | ## Schemas ### ValuationHistoryResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | history | object | true | Valuation history data | | history.metrics | object | false | Valuation metrics | | history.metrics.pe | object | false | P/E ratio history | | history.metrics.pb | object | false | P/B ratio history | | history.metrics.ps | object | false | P/S ratio history | ### ValuationMetric | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | desc | string | false | Description of current valuation | | high | string | false | Historical high value | | low | string | false | Historical low value | | median | string | false | Median value | | list | object[] | false | Time series data points, see [ValuationMetric](#ValuationMetric) | | list[].date | string | false | Date (YYYY-MM-DD) | | list[].value | string | false | Valuation value | #### Institution Rating Detail Get historical analyst rating and target price details. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.institution_rating_detail](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.institution_rating_detail) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `TSLA.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.institution_rating_detail("TSLA.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.institution_rating_detail("TSLA.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.institutionRatingDetail('TSLA.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getInstitutionRatingDetail("TSLA.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.institution_rating_detail("TSLA.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.institution_rating_detail("TSLA.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.InstitutionRatingDetail(context.Background(), "TSLA.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "ccy_symbol": "$", "evaluate": { "list": [ { "date": "2021/05/14", "buy": 3, "hold": 11, "sell": 2, "strong_buy": 9, "under": 6 } ] }, "target": { "list": [ { "broker_name": "Goldman Sachs", "date": "2026-04-30", "rating": "Buy", "target_price": "250.00" } ] } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [InstitutionRatingDetail](#InstitutionRatingDetail) | | 400 | Bad request | None | ## Schemas ### InstitutionRatingDetail | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | ccy_symbol | string | false | Currency symbol | | evaluate | object | false | Rating distribution history | | evaluate.list | object[] | false | List of historical rating snapshots | | target | object | false | Target price history | | target.list | object[] | false | List of historical target price data | | target.data_percent | string | false | Data coverage percentage | | target.prediction_accuracy | string | false | Prediction accuracy percentage | | target.updated_at | string | false | Last update date string | ### EvaluateHistoryItem | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | date | string | false | Date | | buy | integer | false | Buy count | | strong_buy | integer | false | Strong buy count | | hold | integer | false | Hold count | | sell | integer | false | Sell count | | no_opinion | integer | false | No opinion count | | under | integer | false | Underperform count | ### TargetHistoryItem | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | date | string | false | Date | | avg_target | string | false | Average target price | | max_target | string | false | Highest target price | | min_target | string | false | Lowest target price | | price | string | false | Closing price on that date | | meet | boolean | false | Whether price met target | | timestamp | string | false | Unix timestamp | #### Valuations Get current valuation metrics (P/E, P/B, P/S, dividend yield) with 5-year historical context. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.valuations](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.valuations) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | indicator | string | NO | Indicator filter: `pe`, `pb`, `ps`, `dvd_yld` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.valuations("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.valuations("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.valuations('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getValuations("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.valuations("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.valuations("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Valuations(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "metrics": { "pe": { "current": "29.5", "high": "35.2", "low": "18.0", "median": "26.0" }, "pb": { "current": "45.1", "high": "50.0", "low": "30.0", "median": "42.0" } } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ValuationsResponse](#ValuationsResponse) | | 400 | Bad request | None | ## Schemas ### ValuationsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | metrics | object | true | Valuation metrics map | | ∟ pe | object | false | P/E ratio data | | ∟∟ current | string | true | Current value | | ∟∟ high | string | true | 5-year high | | ∟∟ low | string | true | 5-year low | | ∟∟ median | string | true | 5-year median | #### Fund Holdings Get the list of funds that hold a given security, with the number of shares and ownership percentage. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.fund_holdings](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.fund_holdings) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.fund_holdings("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.fund_holdings("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.fund_holdings('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getFundHoldings("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.fund_holdings("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.fund_holdings("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FundHoldings(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "lists": [ { "symbol": "TSLT.US", "code": "TSLT", "name": "2x Long TSLA ETF", "position_ratio": "101.02", "report_date": "2026-05-07", "currency": "USD" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [FundHoldersResponse](#FundHoldersResponse) | | 400 | Bad request | None | ## Schemas ### FundHoldersResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | lists | object[] | true | List of fund holders | | ∟ symbol | string | true | Fund symbol | | ∟ code | string | false | Fund code | | ∟ name | string | false | Fund name | | ∟ position_ratio | string | false | Position ratio (%) | | ∟ report_date | string | false | Report date | | ∟ currency | string | false | Currency | #### Company Profile Get a company's profile information including founding year, employee count, headquarters, and description. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.company_profile](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.company_profile) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.company_profile("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.company_profile("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.company_profile('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getCompanyProfile("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.company_profile("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.company_profile("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.CompanyProfile(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "company_name": "Apple Inc.", "name": "Apple", "ticker": "AAPL", "market": "NasdaqGS", "founded": "1976", "employees": "166000", "manager": "Timothy D. Cook", "website": "www.apple.com", "phone": "(408) 996-1010", "address": "One Apple Park Way, Cupertino, California, United States", "profile": "Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, a...", "region": "US", "sector": 0, "year_end": "September 27", "icon": "https://assets.lbkrs.com/ticker/ST/US/AAPL.png" } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [CompanyProfileResponse](#CompanyProfileResponse) | | 400 | Bad request | None | ## Schemas ### CompanyProfileResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | name | string | false | Chinese name | | company_name | string | false | Full company name | | ticker | string | false | Ticker symbol | | market | string | false | Listing exchange | | sector | integer | false | Industry sector | | category | string | false | Company category | | founded | string | false | Founding year | | listing_date | string | false | IPO listing date | | employees | string | false | Number of employees | | chairman | string | false | Chairman | | manager | string | false | CEO / General manager | | secretary | string | false | Company secretary | | address | string | false | Registered address | | office_address | string | false | Office address | | email | string | false | Contact email | | website | string | false | Company website | | profile | string | false | Business description | | icon | string | false | Stock icon URL | | region | string | false | Region | | shares_offered | string | false | Total shares offered | | issue_price | string | false | IPO issue price | | year_end | string | false | Fiscal year-end | | zip_code | string | false | Postal code | | phone | string | false | Phone number | | fax | string | false | Fax number | | legal_repr | string | false | Legal representative | | legal_counsel | string | false | Legal counsel | | accounting_firm | string | false | Accounting firm | | audit_inst | string | false | Audit institution | | securities_rep | string | false | Securities representative | | bus_license | string | false | Business license number | | ads_ratio | string | false | ADS ratio | #### Industry Valuation Distribution Get the valuation distribution histogram for the symbol's industry. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.industry_valuation_dist](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.industry_valuation_dist) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.industry_valuation_dist("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.industry_valuation_dist("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.industryValuationDist('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getIndustryValuationDist("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.industry_valuation_dist("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.industry_valuation_dist("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.IndustryValuationDist(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "pe": { "value": "28.5", "high": "120.0", "low": "5.0", "median": "22.0", "ranking": "35", "rank_index": "12", "rank_total": "30" }, "pb": { "value": "45.2", "high": "200.0", "low": "1.0", "median": "8.0", "ranking": "85", "rank_index": "25", "rank_total": "30" }, "ps": { "value": "7.8", "high": "30.0", "low": "0.5", "median": "4.0", "ranking": "70", "rank_index": "21", "rank_total": "30" } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [IndustryValuationDist](#IndustryValuationDist) | | 400 | Bad request | None | ## Schemas ### IndustryValuationDist | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | pe | object | false | P/E ratio distribution | | pb | object | false | P/B ratio distribution | | ps | object | false | P/S ratio distribution | #### Investment Relations Get investment relations including parent company, subsidiaries, and major holdings. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.invest_relation](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.invest_relation) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `700.HK` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.invest_relation("700.HK") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.invest_relation("700.HK") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.investRelation('700.HK') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getInvestRelation("700.HK").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.invest_relation("700.HK").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.invest_relation("700.HK", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.InvestRelation(context.Background(), "700.HK") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "forward_url": "https://longport.com/wiki/stocks/ST.HK.700#invest", "invest_securities": [ { "symbol": "HUYA.US", "company_id": "12345", "company_name": "虎牙直播", "company_name_en": "Huya Inc.", "company_name_zhcn": "虎牙直播", "currency": "USD", "percent_of_shares": "19.00", "shares_rank": "1", "shares_value": "19000000" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [InvestRelations](#InvestRelations) | | 400 | Bad request | None | ## Schemas ### InvestRelations | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | forward_url | string | false | Company investment relations page URL | | invest_securities | object[] | false | List of investment holdings | | ∟ symbol | string | false | Security symbol | | ∟ company_id | string | false | Company ID | | ∟ company_name | string | false | Display company name | | ∟ company_name_en | string | false | English company name | | ∟ company_name_zhcn | string | false | Chinese company name | | ∟ currency | string | false | Currency | | ∟ percent_of_shares | string | false | Ownership percentage | | ∟ shares_rank | string | false | Rank by shares held | | ∟ shares_value | string | false | Value of shares held | #### Macroeconomic Indicators List macroeconomic indicators available through LongPort, optionally filtered by country. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.macroeconomic_indicators](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.macroeconomic_indicators) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | country | MacroeconomicCountry | NO | Filter by country. Omit for all countries. | | keyword | string | NO | Fuzzy search by indicator name (case-insensitive) | | offset | int | NO | Pagination offset. Default: 0 | | limit | int | NO | Max records per page. Default: 100, max: 1000 | ### MacroeconomicCountry | Value | Country | | ----- | ------- | | HK | Hong Kong SAR | | CN | China (Mainland) | | US | United States | | EU | Euro Zone | | JP | Japan | | SG | Singapore | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder, MacroeconomicCountry oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) # All indicators resp = ctx.macroeconomic_indicators() print(resp) # US only resp = ctx.macroeconomic_indicators(country=MacroeconomicCountry.UnitedStates, limit=50) print(resp) # Search by keyword resp = ctx.macroeconomic_indicators(keyword="payroll") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder, MacroeconomicCountry async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.macroeconomic_indicators(country=MacroeconomicCountry.UnitedStates) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth, MacroeconomicCountry } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.macroeconomicIndicators({ country: MacroeconomicCountry.UnitedStates }) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getMacroeconomicIndicators(null, null, null).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.macroeconomic_indicators(None, None, None).await?; println!("{:?}", resp); Ok(()) } ``` ## Response ### Response Example ```json { "count": 619, "list": [ { "indicator_code": "62267", "country": "US", "name": "Non-Farm Payroll", "periodicity": "Monthly", "describe": "Employment situation report...", "importance": 3 } ] } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [MacroeconomicIndicatorListResponse](#MacroeconomicIndicatorListResponse) | | 400 | Bad request | None | ## Schemas ### MacroeconomicIndicatorListResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | MacroeconomicIndicator[] | true | Indicator list | | count | int | true | Total number of matching indicators | ### MacroeconomicIndicator | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | indicator_code | string | true | Indicator code (use as input to `macroeconomic`) | | country | string | true | Country name | | name | string | true | Indicator name | | periodicity | string | true | Release periodicity (e.g. `Monthly`, `Quarterly`) | | describe | string | true | Indicator description | | importance | int | true | Importance level (1 = Low, 2 = Medium, 3 = High) | #### Financial Report Fetch income statement, balance sheet, and cash flow statement for any public company. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.financial_report](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.financial_report) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | kind | string | YES | Report type: `IncomeStatement`, `BalanceSheet`, `CashFlow`, `All` | | period | string | YES | Report period: `Annual`, `SemiAnnual`, `Q1`, `Q2`, `Q3`, `ThreeQ`, `QuarterlyFull` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.financial_report("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.financial_report("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.financial_report('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getFinancialReport("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.financial_report("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.financial_report("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.FinancialReport(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "list": { "IS": { "indicators": [ { "title": "Income Statement", "short_title": "IS", "currency": "USD", "has_yoy": true, "entry": "IS", "periods": [ "FY2025", "FY2024" ], "accounts": [ { "field": "EPS", "name": "Earnings Per Share(USD)", "percent": false, "tip": "", "values": [ { "period": "FY 2025", "year": 2025, "fp_end": "1758945600", "value": "7.46", "ratio": "", "yoy": "0.227" } ] } ] } ] } } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [FinancialReportsResponse](#FinancialReportsResponse) | | 400 | Bad request | None | ## Schemas ### FinancialReportsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | object | true | Report data grouped by kind (key: report type code, e.g. `IS`, `BS`, `CF`) | ### FinancialReportIndicator | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | title | string | false | Indicator title | | short_title | string | false | Short title | | currency | string | false | Currency | | has_yoy | boolean | false | Whether year-over-year data is available | | entry | string | false | Entry identifier | | periods | string[] | false | Available reporting periods | | accounts | object[] | false | List of financial line items, see [FinancialAccount](#FinancialAccount) | ### FinancialAccount | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | field | string | true | Field identifier | | name | string | false | Field display name | | percent | boolean | false | Whether the value is a percentage | | tip | string | false | Tooltip description | | values | object[] | false | Historical values by period, see [FinancialValue](#FinancialValue) | ### FinancialValue | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | period | string | true | Period label (e.g. `FY 2024`) | | year | integer | false | Fiscal year | | fp_end | string | false | Period end timestamp | | value | string | false | Reported value | | ratio | string | false | Ratio value | | yoy | string | false | Year-over-year growth rate | #### Industry Valuation Get peer valuation comparison within the same industry. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.industry_valuation](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.industry_valuation) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `TSLA.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.industry_valuation("TSLA.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.industry_valuation("TSLA.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.industryValuation('TSLA.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getIndustryValuation("TSLA.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.industry_valuation("TSLA.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.industry_valuation("TSLA.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.IndustryValuation(context.Background(), "TSLA.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "list": [ { "symbol": "AAPL.US", "name": "Apple Inc.", "market": "US", "currency": "USD", "pe": "28.50", "pb": "45.2", "ps": "7.8", "eps": "6.08", "bps": "4.50" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [IndustryValuationList](#IndustryValuationList) | | 400 | Bad request | None | ## Schemas ### IndustryValuationList | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | object[] | true | List of peer companies | | ∟ symbol | string | false | Security symbol | | ∟ name | string | false | Company name | | ∟ currency | string | false | Reporting currency | | ∟ pe | string | false | Price-to-Earnings ratio | | ∟ bps | string | false | Book value per share | | ∟ eps | string | false | Earnings per share | | ∟ dps | string | false | Dividends per share | | ∟ div_yld | string | false | Dividend yield | | ∟ div_payout_ratio | string | false | Dividend payout ratio | | ∟ five_y_avg_dps | string | false | 5-year average DPS | | ∟ assets | string | false | Total assets | | ∟ history | object[] | false | Historical valuation data | #### Financial Consensus Get financial consensus estimates including revenue, EPS, and net income forecasts. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.consensus](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.consensus) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `TSLA.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.consensus("TSLA.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.consensus("TSLA.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.consensus('TSLA.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getConsensus("TSLA.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.consensus("TSLA.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.consensus("TSLA.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Consensus(context.Background(), "TSLA.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "currency": "USD", "current_index": 3, "current_period": "qf", "opt_periods": [ "qf", "af", "saf" ], "list": [ { "fiscal_year": 2026, "fiscal_period": "Q2 FY2026", "period_text": "Q2 FY2026", "details": [ { "key": "revenue", "name": "Revenue", "estimate": "95000000000", "actual": "", "comp": "", "comp_value": null, "comp_desc": "", "description": "", "is_released": false } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [FinancialConsensus](#FinancialConsensus) | | 400 | Bad request | None | ## Schemas ### FinancialConsensus | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | currency | string | false | Reporting currency | | current_index | integer | false | Index of the current period in opt_periods | | current_period | string | false | Current period code (e.g. `qf`) | | list | object[] | true | List of consensus forecast periods, see [ConsensusListItem](#ConsensusListItem) | | opt_periods | string[] | false | Available period options | ### ConsensusListItem | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | fiscal_period | string | false | Fiscal period number within the fiscal year | | fiscal_year | integer | false | Fiscal year | | period_text | string | false | Display period label (e.g. Q1 2027) | | details | object[] | false | List of financial indicator details, see [ConsensusDetail](#ConsensusDetail) | ### ConsensusDetail | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | key | string | false | Indicator key (e.g. `eps`, `revenue`) | | name | string | false | Indicator display name | | description | string | false | Full description | | actual | string | false | Actual reported value | | estimate | string | false | Consensus estimate | | comp | string | false | Comparison result (e.g. `beat`, `miss`) | | comp_desc | string | false | Comparison description | | comp_value | string | false | Comparison percentage value | | is_released | boolean | false | Whether actual has been released | #### Top Shareholders Get the top 20 major shareholders (institutional, individual, and insider) for a listed company, with support for multi-period comparison. `object_id` can be passed to `shareholder_detail` to retrieve full holding history. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.shareholder_top](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.shareholder_top) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.shareholder_top("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.shareholder_top("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.shareholderTop('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getShareholderTop("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.shareholder_top("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.shareholder_top("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.ShareholderTop(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "info": [ { "period": "Latest", "share_holders": [ { "object_id": "148057", "name": "The Vanguard Group, Inc.", "title": "", "shares_held": "1426283914.00", "percent_shares_held": "9.71%", "percent_shares_changed": "0.01%", "shares_changed": "0.00", "period": "Latest", "filing_date": "2025/12/31" }, { "object_id": "452583", "name": "BlackRock, Inc.", "title": "", "shares_held": "1138572603.00", "percent_shares_held": "7.75%", "percent_shares_changed": "-0.06%", "shares_changed": "-10565359.00", "period": "Latest", "filing_date": "2026/03/31" } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ShareholderTopResponse](#ShareholderTopResponse) | | 400 | Bad request | None | ## Schemas ### ShareholderTopResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | info | object[] | false | Shareholder data per reporting period | | ∟ period | string | false | Reporting period label (e.g. `Latest`) | | ∟ share_holders | object[] | false | List of shareholders (up to 20) | | ∟ ∟ object_id | string | false | Unique shareholder ID; pass to `shareholder_detail` | | ∟ ∟ name | string | false | Shareholder name | | ∟ ∟ title | string | false | Shareholder type (Institution / Individual / Insider) | | ∟ ∟ shares_held | string | false | Number of shares held | | ∟ ∟ percent_shares_held | string | false | Ownership percentage, including `%` sign (e.g. `9.71%`) | | ∟ ∟ percent_shares_changed | string | false | Change in ownership percentage, including `%` sign | | ∟ ∟ shares_changed | string | false | Net share count change (positive = bought, negative = sold) | | ∟ ∟ period | string | false | Period label for this entry | | ∟ ∟ filing_date | string | false | Filing date | #### Shareholders Get the top institutional and individual shareholders of a company. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.shareholders](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.shareholders) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.shareholders("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.shareholders("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.shareholders('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getShareholders("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.shareholders("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.shareholders("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Shareholders(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "forward_url": "", "total": 33, "shareholder_list": [ { "shareholder_name": "Timothy D. Cook", "percent_of_shares": "2.84", "institution_type": "", "report_date": "2026-04-21", "shareholder_id": "0", "shares_changed": "0", "stocks": [] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ShareholderResponse](#ShareholderResponse) | | 400 | Bad request | None | ## Schemas ### ShareholderResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | shareholder_list | object[] | true | List of shareholders | | ∟ shareholder_name | string | true | Shareholder name | | ∟ percent_of_shares | string | true | Percentage of shares held | | ∟ institution_type | string | false | Institution type | | ∟ report_date | string | false | Report date | | ∟ shareholder_id | string | false | Shareholder ID | | ∟ shares_changed | string | false | Change in shares held | | ∟ stocks | object[] | false | Associated stocks | | forward_url | string | false | Link to full shareholder page | | total | integer | true | Total number of shareholders | #### Industry Ranking Get the industry ranking list by market and indicator. The returned Counter ID can be passed directly to `industry_peers` to explore the sub-sector hierarchy. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.industry_rank](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.industry_rank) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | market | string | YES | Market code: `US` / `HK` / `CN` / `SG` | | indicator | string | YES | Ranking indicator: `leading-gainer` / `today-trend` / `popularity` / `market-cap` / `revenue` / `revenue-growth` / `net-profit` / `net-profit-growth` | | sort_type | string | YES | Sort mode: `single` / `multi` | | limit | uint32 | YES | Number of results to return, default 20 | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.industry_rank("US", "leading-gainer", "single", 20) print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.industry_rank("US", "leading-gainer", "single", 20) print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.industryRank('US', 'leading-gainer', 'single', 20) console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getIndustryRank("US", "leading-gainer", "single", 20).get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.industry_rank("US", "leading-gainer", "single", 20).await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.industry_rank("US", "leading-gainer", "single", 20, [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.IndustryRank(context.Background(), "US", "leading-gainer", "single", 20) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "items": [ { "lists": [ { "name": "Technology", "counter_id": "BK/US/IN00258", "chg": "0.0231", "leading_name": "NVIDIA", "leading_ticker": "NVDA.US", "leading_chg": "0.0512", "value_name": "", "value_data": "" } ] } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [IndustryRankResponse](#IndustryRankResponse) | | 400 | Bad request | None | ## Schemas ### IndustryRankResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | items | object[] | false | Ranked group list | | ∟ lists | object[] | false | Industry item list | | ∟ ∟ name | string | false | Industry name | | ∟ ∟ counter_id | string | false | Industry counter ID (`BK/MARKET/ID` format), usable in `industry_peers` | | ∟ ∟ chg | string | false | Daily change (decimal) | | ∟ ∟ leading_name | string | false | Leading stock name | | ∟ ∟ leading_ticker | string | false | Leading stock ticker | | ∟ ∟ leading_chg | string | false | Leading stock daily change (decimal) | | ∟ ∟ value_name | string | false | Indicator label (may be empty depending on indicator type) | | ∟ ∟ value_data | string | false | Indicator value (may be empty) | #### Buyback Get share buyback data including historical buyback amounts and ratios. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.buyback](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.buyback) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.buyback("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.buyback("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.buyback('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getBuyback("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.buyback("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.buyback("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Buyback(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "buyback_history": [ { "fiscal_year": "FY2024", "fiscal_year_range": "2024-01-01~2024-12-31", "net_buyback": "94949000000", "net_buyback_yield": "0.0241", "net_buyback_growth_rate": "-0.1233" } ], "buyback_ratios": [ { "net_buyback_payout_ratio": "0.9502", "net_buyback_to_cashflow_ratio": "0.8821" } ], "recent_buybacks": { "currency": "USD", "net_buyback_ttm": "94949000000", "net_buyback_yield_ttm": "0.0241" } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [BuybackDataResponse](#BuybackDataResponse) | | 400 | Bad request | None | ## Schemas ### BuybackDataResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | buyback_history | object[] | false | Annual buyback history, see [BuybackHistoryItem](#BuybackHistoryItem) | | buyback_ratios | object[] | false | Buyback ratio history, see [BuybackRatios](#BuybackRatios) | | recent_buybacks | object | false | Trailing 12-month buyback summary | ### BuybackHistoryItem | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | fiscal_year | string | false | Fiscal year | | fiscal_year_range | string | false | Fiscal year date range | | currency | string | false | Currency | | net_buyback | string | false | Net buyback amount | | net_buyback_growth_rate | string | false | Buyback growth rate | | net_buyback_yield | string | false | Buyback yield | ### BuybackRatios | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | net_buyback_payout_ratio | string | false | Buyback payout ratio | | net_buyback_to_cashflow_ratio | string | false | Buyback to free cash flow ratio | ### RecentBuybacks | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | currency | string | false | Currency | | net_buyback_ttm | string | false | Net buyback (trailing 12 months) | | net_buyback_yield_ttm | string | false | Buyback yield (trailing 12 months) | #### Executives Get the list of key executives (CEO, CFO, etc.) for a company. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.executives](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.executives) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.executives("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.executives("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.executives('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getExecutives("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.executives("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.executives("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Executives(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "professional_list": [ { "forward_url": "https://longport.com/wiki/stocks/ST.US.AAPL#company-manager", "professionals": [ { "biography": "Tim Cook is the CEO of Apple Inc.", "id": "12345", "name": "Timothy D. Cook", "name_en": "Timothy D. Cook", "name_zhcn": "蒂姆·库克", "photo": "https://cdn.example.com/timcook.jpg", "title": "Chief Executive Officer", "wiki_url": "https://en.wikipedia.org/wiki/Tim_Cook" } ], "symbol": "AAPL.US", "total": 9 } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [ExecutiveResponse](#ExecutiveResponse) | | 400 | Bad request | None | ## Schemas ### ExecutiveResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | professional_list | object[] | true | List of executive groups, see [ExecutiveGroup](#ExecutiveGroup) | ### ExecutiveGroup | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | true | Security symbol | | forward_url | string | false | Company executives page URL | | total | integer | false | Total number of executives | | professionals | object[] | true | List of executives, see [Executive](#Executive) | ### Executive | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | string | false | Executive ID | | name | string | true | Display name | | name_en | string | false | English name | | name_zhcn | string | false | Chinese name | | title | string | false | Job title | | biography | string | false | Biography | | photo | string | false | Photo URL | | wiki_url | string | false | Wikipedia URL | #### Institutional Rating Views Timeline Get the monthly institutional rating (buy/hold/sell) distribution timeline, newest first. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.institution_rating_views](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.institution_rating_views) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.institution_rating_views("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.institution_rating_views("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.institutionRatingViews('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getInstitutionRatingViews("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.institution_rating_views("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.institution_rating_views("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.InstitutionRatingViews(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "elist": [ { "date": 1746057600, "buy": "18", "over": "5", "hold": "17", "under": "3", "sell": "4", "total": "51" }, { "date": 1743379200, "buy": "17", "over": "6", "hold": "18", "under": "3", "sell": "5", "total": "53" } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [InstitutionRatingViewsResponse](#InstitutionRatingViewsResponse) | | 400 | Bad request | None | ## Schemas ### InstitutionRatingViewsResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | elist | object[] | false | Monthly rating distribution list, newest first | | ∟ date | integer | false | Unix timestamp (seconds) | | ∟ buy | string | false | Number of Buy ratings | | ∟ over | string | false | Number of Outperform ratings | | ∟ hold | string | false | Number of Hold ratings | | ∟ under | string | false | Number of Underperform ratings | | ∟ sell | string | false | Number of Sell ratings | | ∟ total | string | false | Total analyst count | #### Operating Metrics Get operating metrics and financial indicator summaries by report period. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.operating](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.operating) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | symbol | string | YES | Security symbol, e.g. `AAPL.US` | | period | string | NO | Report period filter, e.g. `q1`, `q2`, `q3`, `q4`, `annual` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.operating("AAPL.US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.operating("AAPL.US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.operating('AAPL.US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getOperating("AAPL.US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.operating("AAPL.US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.operating("AAPL.US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.Operating(context.Background(), "AAPL.US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "list": [ { "id": "12345", "report": "af", "title": "FY2025 Annual Report Summary", "txt": "Management discussion...", "latest": true, "web_url": "https://longport.com/wiki/...", "financial": { "code": "700", "currency": "HKD", "name": "Tencent", "region": "HK", "report": "af", "indicators": [ { "field_name": "operating_revenue", "indicator_name": "Revenue", "indicator_value": "6786 亿", "yoy": "0.0800" } ] } } ] } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [OperatingList](#OperatingList) | | 400 | Bad request | None | ## Schemas ### OperatingListResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | list | object[] | true | List of operating summary reports, see [OperatingItem](#OperatingItem) | ### OperatingItem | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | id | string | false | Internal report ID | | report | string | false | Report period code (e.g. `af` = annual) | | title | string | false | Report title | | txt | string | false | Management discussion text | | latest | boolean | false | Whether this is the most recent report | | web_url | string | false | URL to the full report page | | financial | object | false | Key financial metrics | ### OperatingFinancial | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | code | string | false | Ticker code | | name | string | false | Company name | | currency | string | false | Reporting currency | | region | string | false | Market region | | report | string | false | Report period code | | indicators | object[] | false | Financial indicators, see [OperatingIndicator](#OperatingIndicator) | ### OperatingIndicator | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | field_name | string | true | Field name key (e.g. `operating_revenue`) | | indicator_name | string | false | Display name | | indicator_value | string | false | Formatted value | | yoy | string | false | Year-over-year change rate | #### Industry Peer Hierarchy Get the hierarchical sub-sector tree for an industry group, including stock count, daily change, and YTD change at each node. Counter IDs come from `industry_rank`. ## SDK | Language | Link | |---|---| | Python | [longport.openapi.fundamental._fundamental_context](https://longportapp.github.io/openapi/python/reference_all/#longport.openapi.fundamental._fundamental_context) | | Rust | [longport::::fundamental#_fundamental_context](https://longportapp.github.io/openapi/rust/longport//struct.fundamental.html#method._fundamental_context) | | Go | [fundamental.industry_peers](https://pkg.go.dev/github.com/longportapp/openapi-go/#fundamental.industry_peers) | | Node.js | [fundamental#FundamentalContext](https://longportapp.github.io/openapi/nodejs/classes/fundamental.html#fundamentalcontext) | ## Parameters > **SDK method parameters.** | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | counter_id | string | YES | Industry unique identifier (BK/MARKET/ID format) from `industry_rank` | | market | string | YES | Market code: `US` / `HK` / `CN` / `SG` | ## Request Example ```python from longport.openapi import FundamentalContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = FundamentalContext(config) resp = ctx.industry_peers("BK/US/IN00258", "US") print(resp) ``` ```python import asyncio from longport.openapi import AsyncFundamentalContext, Config, OAuthBuilder async def main() -> None: oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url)) config = Config.from_oauth(oauth) ctx = AsyncFundamentalContext.create(config) resp = await ctx.industry_peers("BK/US/IN00258", "US") print(resp) if __name__ == "__main__": asyncio.run(main()) ``` ```javascript const { Config, FundamentalContext, OAuth } = require('longport') async function main() { const oauth = await OAuth.build('your-client-id', (_, url) => { console.log('Open this URL to authorize: ' + url) }) const config = Config.fromOAuth(oauth) const ctx = FundamentalContext.new(config) const resp = await ctx.industryPeers('BK/US/IN00258', 'US') console.log(resp) } main().catch(console.error) ``` ```java import com.longport.*; import com.longport.fundamental.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get(); Config config = Config.fromOAuth(oauth); FundamentalContext ctx = FundamentalContext.create(config)) { var resp = ctx.getIndustryPeers("BK/US/IN00258", "US").get(); System.out.println(resp); } } } ``` ```rust use std::sync::Arc; use longport::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?; let config = Arc::new(Config::from_oauth(oauth)); let ctx = FundamentalContext::new(config); let resp = ctx.industry_peers("BK/US/IN00258", "US").await?; println!("{:?}", resp); Ok(()) } ``` ```cpp #include #include using namespace longport; using namespace longport::fundamental; int main() { OAuthBuilder("your-client-id").build( [](const std::string& url) { std::cout << "Open: " << url << std::endl; }, [](auto res) { if (!res) return; Config config = Config::from_oauth(*res); FundamentalContext ctx = FundamentalContext::create(config); ctx.industry_peers("BK/US/IN00258", "US", [](auto resp) { if (resp) std::cout << "OK" << std::endl; }); }); std::cin.get(); } ``` ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/oauth" "github.com/longportapp/openapi-go/fundamental" ) func main() { o := oauth.New("your-client-id"). OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) }) if err := o.Build(context.Background()); err != nil { log.Fatal(err) } conf, err := config.New(config.WithOAuthClient(o)) if err != nil { log.Fatal(err) } c, err := fundamental.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer c.Close() resp, err := c.IndustryPeers(context.Background(), "BK/US/IN00258", "US") if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", resp) } ``` ## Response ### Response Example ```json { "code": 0, "message": "success", "data": { "top": {"name": "All Industries", "market": "US"}, "chain": { "name": "Technology", "counter_id": "BK/US/IN00258", "stock_num": 542, "chg": "0.0231", "ytd_chg": "0.0875", "next": [ { "name": "在线消费电子产品零售", "counter_id": "", "stock_num": 4, "chg": "0.0268", "ytd_chg": "-0.1869", "next": [] } ] } } } ``` ### Response Status | Status | Description | Schema | | ------ | ----------- | ------ | | 200 | Success | [IndustryPeersResponse](#IndustryPeersResponse) | | 400 | Bad request | None | ## Schemas ### IndustryPeersResponse | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | top | object | false | Top-level industry info, see [IndustryPeersTop](#IndustryPeersTop) | | chain | object | false | Industry hierarchy root node, see [IndustryPeerNode](#IndustryPeerNode) | ### IndustryPeersTop | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | name | string | false | Top-level industry name | | market | string | false | Market code | ### IndustryPeerNode | Name | Type | Required | Description | | ---- | ---- | -------- | ----------- | | name | string | false | Sector name | | counter_id | string | false | Sector counter ID (present on root node; empty string on child nodes) | | stock_num | integer | false | Number of stocks in this sector | | chg | string | false | Daily change (decimal; may be empty string) | | ytd_chg | string | false | Year-to-date change (decimal; may be empty string) | | next | object[] | false | Child sector list with the same structure (recursive) | ## Assets ### Chunks ## Zh-HK ### Docs #### Content ##### Sharelist ##### News ##### Topics #### Legal #### Quote ##### Warrants ##### Subscribe ##### Options ##### Analytics ##### Push ##### Security ##### Stocks ##### Watchlist ##### Individual ##### Pull #### Screener #### Trade ##### Execution ##### Asset ##### Order #### Qa #### Account ##### Alert ##### Portfolio ##### Dca #### Socket ##### Protocol #### Market ##### Calendar #### Fundamental ##### Market ##### Fundamental ### Skill ## Skill ## LongPort Skill Installation Guide # LongPort Skill Installation Guide Once installed, you can say things like this to your AI assistant and get real answers: - _"Screen US and HK stocks: market cap above $50B, P/E below 25, recent MACD golden cross — ranked by market cap"_ - _"NVDA just reported — compare actuals vs analyst estimates, break down revenue by segment, and check if valuation is reasonable"_ - _"Set a trailing stop on TSLA: trigger a sell if it drops more than 8%, show me the order details before executing"_ - _"Review my portfolio this month: P&L trend, biggest winner, worst drag, US vs HK allocation"_ - _"Analyze my account and quantify its exposure to AI, semiconductors, and internet-related stocks."_ - _"Based on my 5-year long-term DCA plan, I'm due to buy this month's QQQ and SPY within the next two days. Can you check the recent market conditions and let me know if the timing looks reasonable?"_ --- The quickest way to get started is to connect your AI tool to LongPort MCP or use the Connect AI page to generate an authorization snippet. Then install the Skill: a set of instruction files that tells your AI what LongPort can do and how to use it. --- ## Step 1 — Connect to the LongPort platform Use hosted LongPort MCP to access the LongPort Developers platform. No local software is required. ### Method A — Connect AI Open [Connect AI](https://open.longportapp.com/connect), sign in, and copy the authorization snippet for your AI assistant. The assistant can use that snippet to complete the connection flow. ### Method B — MCP Works with any AI tool that supports HTTP MCP and OAuth authorization. Add the following as a remote MCP server in your AI tool: ```text https://mcp.longportapp.com ``` For clients that use a JSON config file, add this to your MCP config: ```json { "mcpServers": { "longport": { "url": "https://mcp.longportapp.com" } } } ``` Where to find the MCP configuration in each client: | Client | Where to configure | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | Claude Desktop | Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows) | | Cursor | Settings → MCP Servers → Add Remote MCP Server | | Zed | `context_servers` key in `~/.config/zed/settings.json` | | Warp | Settings → AI → MCP Servers → Add | The first time you ask a LongPort question, your client will open a browser tab for OAuth authorization — no API key required. --- ## Step 2 — Install the Skill The Skill is a set of instruction files that tell your AI assistant what LongPort can do. **Via npx / bunx (recommended):** ```bash # Node.js npx skill add longportapp/developers # Bun bunx skill add longportapp/developers ``` > Requires [Node.js](https://nodejs.org) or [Bun](https://bun.sh). This installs the LongPort Skill from the `skills/longport` directory in the `longportapp/developers` repository. **Via Claude Code or Codex plugin:** If your AI tool supports installing Skills from a repository source, use: ```text longportapp/developers ``` The Skill directory is: ```text skills/longport ``` **Or install manually:** Open [github.com/longportapp/developers/tree/main/skills/longport](https://github.com/longportapp/developers/tree/main/skills/longport), copy the Skill files, then place them in your AI tool's Skill directory. For Claude Code, use `.claude/skills/longport/`. For Cursor, paste the relevant instructions into the Rules editor. **OpenClaw** — send this message in chat and it handles everything automatically: ```text Install the LongPort Developers Skill from this repository: https://github.com/longportapp/developers/tree/main/skills/longport ``` --- ## Known restrictions by tool Some environments have network whitelists or sandboxing that block MCP server connections. If things aren't working, check here first. ### Claude Desktop — use the Code tab **Chat and Cowork modes** in Claude Desktop have network restrictions that prevent MCP server connections. Do not try to connect from either of these modes. It will not work no matter how many times you retry. Switch to the **Code** tab in Claude Desktop. From the Code tab, you can connect MCP and install the Skill in one session. ### Codex — select "Work locally" Codex in **Cloud** mode has the same network whitelist restrictions. When starting a new session, select **Work locally** instead of Cloud. This gives the agent full access to your shell and network. ### Claude.ai and ChatGPT.com (web) Browser-based interfaces may not be able to connect to external MCP servers directly. For Claude, use [Claude Desktop](https://claude.ai/download) and switch to the **Code** tab. --- ## Verify installation After installing, ask your AI assistant: ```text Use LongPort 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 `/longport` to force it. For example: `/longport get the current quote for AAPL`. --- ## Troubleshooting **AI says it can't find the LongPort 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** Reconnect the LongPort MCP server and complete the OAuth flow again. **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 LongPort account → Security Settings → manage authorized apps. ## LongPort Skill # LongPort Skill LongPort Skill gives AI tools reusable OpenAPI instructions, MCP connection guidance, symbol conventions, and safety checks. Use it when your AI client supports Skill files or custom reusable instructions. ## Install With AI Authorization happens upfront. Grab a code on the Connect page, hand it to your AI, and it takes care of the rest: 1. Sign in on the Connect page to get a one-time auth code. 2. Send the authorization snippet to your AI assistant. 3. Your AI redeems the code and plugs into LongPort — no browser hops along the way. Connect AI Send this prompt to your AI tool: ```text Install LongPort AI toolkit following the guide: https://open.longportapp.com/skill/install.md And complete login and test with a market data query. ``` Supplemental details: [Install guide](/skill/install) ## What It Provides - OpenAPI workflow guidance for quote, portfolio, and trading tasks. - MCP connection guidance and symbol format. - Read-only-first verification prompts. - Links to LLM-readable documentation. ## Example Usage After installing the Skill, ask your AI tool questions like: ```text Show the recent 5-day performance of NVDA.US and TSLA.US. ``` The Skill guides AI to use LongPort MCP to retrieve market data or your account asset information from OpenAPI. ## Zh-CN ### Docs #### Content ##### Sharelist ##### News ##### Topics #### Legal #### Quote ##### Warrants ##### Subscribe ##### Options ##### Analytics ##### Push ##### Security ##### Stocks ##### Watchlist ##### Individual ##### Pull #### Screener #### Trade ##### Execution ##### Asset ##### Order #### Qa #### Account ##### Alert ##### Portfolio ##### Dca #### Socket ##### Protocol #### Market ##### Calendar #### Fundamental ##### Market ##### Fundamental ### Skill