# LongPort Developers Documentation # SDK
## LongPort Developers 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 ## LongPort Developers 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 ## LongPort Developers 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 = "3.0.17" ``` [https://crates.io/crates/longport](https://crates.io/crates/longport) ### API Documents - https://longportapp.github.io/openapi/rust/longport/index.html ## LongPort Developers 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.longportapp openapi-sdk LATEST ``` [https://search.maven.org/artifact/io.github.longportapp/openapi](https://search.maven.org/artifact/io.github.longportapp/openapi) ### API Documents - https://longportapp.github.io/openapi/java/index.html ## LongPort Developers SDK for Go [https://github.com/longportapp/openapi-go](https://github.com/longportapp/openapi-go) ### Get SDK for Go Go version >= 1.17 ```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) ## LongPort Developers SDK for C/C++ [https://github.com/longportapp/openapi/tree/master/cpp](https://github.com/longportapp/openapi/tree/master/cpp) ### Download - [3.0.17](https://static.lbctrl.com/openapi-sdk/openapi-cpp-sdk-3.0.17.tar.gz) ### API Documents - https://longportapp.github.io/openapi/cpp/index.html
# Introduction LongPort Developers provides OpenAPI, SDKs, MCP, Skill, and LLM-readable documentation for building market data, portfolio, trading, and AI-agent workflows. Use the platform directly through HTTP / WebSocket APIs, integrate through SDKs, or connect AI tools through LongPort Skill, MCP, and LLMs Text. ## What You Can Build LongPort Developers provides programmatic quote and trading interfaces for investors and developers. The capabilities include: - **Trading** - Create, amend, cancel orders, query today's/past orders and transaction details, etc. - **Quotes** - Real-time quotes, acquisition of historical quotes, etc. - **Portfolio** - Real-time query of the account assets, positions, funds - **Real-time subscription** - Provides real-time quotes and push notifications for order status changes ## Access Methods | Method | Best for | Entry | | --- | --- | --- | | OpenAPI | Direct HTTP and WebSocket integration for market data, account, and trading systems | [Getting Started](/docs/getting-started) | | SDK | Application development in supported languages without hand-writing protocol details | [SDK](/sdk) | | Skill | Giving AI assistants reusable LongPort workflow knowledge and safe setup guidance | [Skill](/skill) | | MCP | Connecting MCP-compatible AI clients to 140+ LongPort Developers tools over HTTP | [MCP](/docs/mcp) | | LLMs Text | Feeding docs to AI tools through `llms.txt`, `llms-full.txt`, and page-level Markdown | [LLMs Text](/docs/llm) | ## How to Enable OpenAPI 1. Log in to the [LongPort App](https://longportapp.com/download) to complete the account opening process; 2. Log in to the [longportapp.com](https://longportapp.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.longportapp.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 and get OpenAPI service permissions to use it for free. 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 Developers 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, it is recommended to use `openapi.longportapp.cn`, `openapi-quote.longportapp.cn`, `openapi-trade.longportapp.cn` to improve access speed. If you are use our SDK, the `LONGPORT_REGION=cn` env variable can to use to setup the API region (Current only support: `cn`, `hk`). ::: ## Time Format All API response are used [Unix Timestamp](https://en.wikipedia.org/wiki/Unix_time), timezone is UTC. ## Environment Requirements
  • Python 3
  • Pip
  • Node.js
  • Yarn
  • Rust
  • JDK
  • Maven
  • Go
  • Go Docs
  • ## Install SDK ```bash pip3 install longport ``` ```bash yarn install longport ``` ```toml [dependencies] longport = "3.0.17" tokio = { version = "1", features = "rt-multi-thread" } ``` ```xml io.github.longportapp openapi-sdk LATEST ``` ```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 and open an account. 2. Get App Key, App Secret, Access Token and other information from [LongPort Developers](https://open.longportapp.com) official website **_Get App Key, App Secret, Access Token and other information_** Login the [LongPort Developers](https://open.longportapp.com) website, and enter the "User Center". The "application credential" credential information will be given on the page. After we get it, we will set the environment variable, which is convenient for later development and use. ### Environment Variables :::caution Please pay attention to protect your **Access Token** information, anyone who gets it can trade your account through OpenAPI! ::: | 环境变量 | 说明 | 值范围 | |-----------------------------|--------------------------------------------------------------------|-----------------| | `LONGPORT_APP_KEY` | App Key get from developer center | | | `LONGPORT_APP_SECRET` | App Secret get from developer center | | | `LONGPORT_ACCESS_TOKEN` | Access Token get from developer center | | | `LONGPORT_REGION` | The region of the API, `cn` for mainland China, `hk` for Hong Kong | `cn`, `hk` | | `LONGPORT_ENABLE_OVERNIGHT` | Set `true` to enable overnight quote | `true`, `false` | 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 Developers SDK can be directly passed in parameters such as `app_key`, `app_secret`, `access_token` to initialize, pay attention to the comments in the example code below `Init config without ENV`. ::: #### Set Environment for macOS / Linux Open the terminal and enter the following command: ```bash export LONGPORT_APP_KEY="App Key get from user center" export LONGPORT_APP_SECRET="App Secret get from user center" export LONGPORT_ACCESS_TOKEN="Access Token get 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, Region 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 get from user center" Success: the specified value has been saved. C:\Users\jason> setx LONGPORT_APP_SECRET "App Secret get from user center" Success: the specified value has been saved. C:\Users\jason> setx LONGPORT_ACCESS_TOKEN "Access Token get 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. ## Scene Demonstration ### Get Account Balance Cteate `account_asset.py` and paste the code below: ```python from longport.openapi import TradeContext, Config config = Config.from_env() # Init config without ENV # config = Config(app_key = "YOUR_APP_KEY", app_secret = "YOUR_APP_SECRET", access_token = "YOUR_ACCESS_TOKEN") ctx = TradeContext(config) resp = ctx.account_balance() print(resp) ``` Run it ```bash python account_asset.py ``` Cteate `account_asset.js` and paste the code below: ```javascript const { Config, TradeContext } = require('longport') let config = Config.fromEnv() // Init config without ENV // let config = new Config({ appKey: "YOUR_APP_KEY", appSecret: "YOUR_APP_SECRET", accessToken: "YOUR_ACCESS_TOKEN" }) TradeContext.new(config) .then((ctx) => ctx.accountBalance()) .then((resp) => { for (let obj of resp) { console.log(obj.toString()) } }) ``` Run it ```bash nodejs account_asset.js ``` Cteate `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{trade::TradeContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Arc::new(Config::from_env()?); // Init config without ENV // let config = Arc::new(Config::new("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")?); let (ctx, _) = TradeContext::try_new(config).await?; let resp = ctx.account_balance().await?; println!("{:?}", resp); Ok(()) } ``` Run it ```bash cargo run ``` Cteate `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 { Config config = Config.fromEnv(); // Init config without ENV // https://longportapp.github.io/openapi/java/com/longport/ConfigBuilder.html // Config config = ConfigBuilder("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN").build(); try (TradeContext ctx = TradeContext.create(config).get()) { 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/trade" ) func main() { conf, err := config.New() // Init config without ENV // https://github.com/longportapp/openapi-go/blob/v0.9.2/config/config_test.go#L11 // conf, err := 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() // Get AccountBalance infomation ab, err := tradeContext.AccountBalance(ctx) if err != nil { log.Fatal(err) } fmt.Printf("%+v", ab) } ``` Run: ```shell go mod tidy go run ./ ``` 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.longportapp.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 - LV1 Nasdaq Basic (Only OpenAPI). Before running, visit the [Developer Center](https://open.longportapp.com/account) 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://longportapp.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, SubType, PushQuote def on_quote(symbol: str, quote: PushQuote): print(symbol, quote) config = Config.from_env() ctx = QuoteContext(config) ctx.set_on_quote(on_quote) symbols = ["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"] ctx.subscribe(symbols, [SubType.Quote], True) sleep(30) ``` Run it ```bash python subscribe_quote.py ``` Create `subscribe_quote.js` and paste the code below: ```javascript const { Config, QuoteContext, SubType } = require('longport') let config = Config.fromEnv() QuoteContext.new(config).then((ctx) => { ctx.setOnQuote((_, event) => console.log(event.toString())) ctx.subscribe(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US'], [SubType.Quote], true) }) ``` Run it ```bash nodejs subscribe_quote.js ``` Create `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{ quote::{QuoteContext, SubFlags}, Config, }; #[tokio::main] async fn main() -> Result<(), Box> { let config = Arc::new(Config::from_env()?); let (ctx, mut receiver) = QuoteContext::try_new(config).await?; ctx.subscribe( ["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"], SubFlags::QUOTE, true, ) .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 { try (Config config = Config.fromEnv(); QuoteContext ctx = QuoteContext.create(config).get()) { 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, true).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 ./ ``` 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.longportapp.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, OrderSide, OrderType, TimeInForceType config = Config.from_env() 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.js` and paste the code below: ```javascript const { Config, TradeContext, OrderType, OrderSide, Decimal, TimeInForceType } = require('longport') let config = Config.fromEnv() TradeContext.new(config) .then((ctx) => ctx.submitOrder({ symbol: '700.HK', orderType: OrderType.LO, side: OrderSide.Buy, timeInForce: TimeInForceType.Day, submittedQuantity: new Decimal(200), submittedPrice: new Decimal(300), }) ) .then((resp) => console.log(resp.toString())) ``` Run it ```bash nodejs submit_order.js ``` Create `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{ decimal, trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext}, Config, }; #[tokio::main] async fn main() -> Result<(), Box> { let config = Arc::new(Config::from_env()?); let (ctx, _) = TradeContext::try_new(config).await?; let opts = SubmitOrderOptions::new( "700.HK", OrderType::LO, OrderSide::Buy, decimal!(200i32), 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 { try (Config config = Config.fromEnv(); TradeContext ctx = TradeContext.create(config).get()) { 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 ``` 创建 `main.go`,贴入一下内容: ```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 ./ ``` After running, the output is as follows: ``` SubmitOrderResponse { order_id: "718437534753550336" } ``` ### Get Today Order Create `today_orders.py` and paste the code below: ```python from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) resp = ctx.today_orders() print(resp) ``` Run it ```bash python today_orders.py ``` Create `today_orders.js` and paste the code below: ```javascript const { Config, TradeContext } = require('longport') let config = Config.fromEnv() TradeContext.new(config) .then((ctx) => ctx.todayOrders()) .then((resp) => { for (let obj of resp) { console.log(obj.toString()) } }) ``` Run it ```bash nodejs today_orders.js ``` Create `main.rs` and paste the code below: ```rust use std::sync::Arc; use longport::{trade::TradeContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Arc::new(Config::from_env()?); let (ctx, _) = TradeContext::try_new(config).await?; 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 { try (Config config = Config.fromEnv(); TradeContext ctx = TradeContext.create(config).get()) { Order[] orders = ctx.getTodayOrders(null).get(); for (Order order : orders) { System.out.println(order); } } } } ``` Run it ```bash mvn compile exec:exec ``` Create file `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 ./ ``` 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.longportapp.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 Developers 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/openapi/issues ## Changelog ## 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.longportapp.com/en/docs/trade/trade-definition#websocket-notification). ## 2024-04-13 - Add `remark` field to [Trade push](https://open.longportapp.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" } } } ``` ### 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`. - SG Market: `region` is `SG`, for example: `D05.SG`. ## 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.longportapp.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). ### 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 | #### Subscribe #### Subscription Information 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 config = Config.from_env() ctx = QuoteContext(config) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) resp = ctx.subscriptions() print(resp) ``` ## 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 Quote 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 # Unsubscribe Quote # # To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct. # https://open.longportapp.com/account # # - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. # - US Market - LV1 Nasdaq Basic (Only OpenAPI). # # 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, SubType config = Config.from_env() ctx = QuoteContext(config) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) ctx.unsubscribe(["AAPL.US"], [SubType.Quote]) ``` ## 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 # Subscribe Quote # # To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct. # https://open.longportapp.com/account # # - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. # - US Market - LV1 Nasdaq Basic (Only OpenAPI). # # 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 time import sleep from longport.openapi import QuoteContext, Config, SubType, PushQuote def on_quote(symbol: str, event: PushQuote): print(symbol, event) config = Config.from_env() ctx = QuoteContext(config) ctx.set_on_quote(on_quote) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote]) sleep(30) ``` ## 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` | #### Push #### Push Real-time 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 # Push Real-time Depth # https://open.longportapp.com/docs/quote/push/push-depth # To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct. # https://open.longportapp.com/account # # - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. # - US Market - LV1 Nasdaq Basic (Only OpenAPI). # # 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 time import sleep from longport.openapi import QuoteContext, Config, SubType, PushDepth def on_depth(symbol: str, event: PushDepth): print(symbol, event) config = Config.from_env() 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 } ] } ``` #### Push Real-time 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 # Push Real-time Trades # https://open.longportapp.com/docs/quote/push/push-trade # To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct. # https://open.longportapp.com/account # # - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. # - US Market - LV1 Nasdaq Basic (Only OpenAPI). # # 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 time import sleep from longport.openapi import QuoteContext, Config, SubType, PushTrades def on_trades(symbol: str, event: PushTrades): print(symbol, event) config = Config.from_env() 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 } ] } ``` #### Push Real-time 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 # Push Real-time Quote # https://open.longportapp.com/docs/quote/push/push-quote # To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct. # https://open.longportapp.com/account # # - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. # - US Market - LV1 Nasdaq Basic (Only OpenAPI). # # 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 time import sleep from longport.openapi import QuoteContext, Config, SubType, PushQuote def on_quote(symbol: str, event: PushQuote): print(symbol, event) config = Config.from_env() 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 } ``` #### Push Real-time 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 # Push Real-time Brokers # https://open.longportapp.com/docs/quote/push/push-brokers # To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct. # https://open.longportapp.com/account # # - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. # - US Market - LV1 Nasdaq Basic (Only OpenAPI). # # 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 time import sleep from longport.openapi import QuoteContext, Config, SubType, PushBrokers def on_brokers(symbol: str, event: PushBrokers): print(symbol, event) config = Config.from_env() 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 #### Retrieve the List of Securities Retrieve the List 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.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 config = Config.from_env() ctx = QuoteContext(config) resp = ctx.security_list(Market.US, SecurityListCategory.Overnight) print(resp) ``` ### 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 | #### 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 | #### 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 | #### 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 | ### 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 def on_order_changed(event: PushOrderChanged): print(event) config = Config.from_env() 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 #### Get 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 config = Config.from_env() ctx = TradeContext(config) resp = ctx.today_executions(symbol = "700.HK") print(resp) ``` ## 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 | #### Get 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 config = Config.from_env() ctx = TradeContext(config) resp = ctx.history_executions( symbol = "700.HK", start_at = datetime(2022, 5, 9), end_at = datetime(2022, 5, 12), ) print(resp) ``` ## 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 #### Get Account Balance 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 # Get Account Balance # https://open.longportapp.com/docs/trade/asset/account from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) resp = ctx.account_balance() print(resp) ``` ## 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 | #### Get 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 # Get Stock Positions # https://open.longportapp.com/docs/trade/asset/stock from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) resp = ctx.stock_positions() print(resp) ``` ## 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 | #### Get 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 # Get Fund Position # https://open.longportapp.com/docs/trade/asset/fund from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) resp = ctx.fund_positions() print(resp) ``` ## 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 | #### Get 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 config = Config.from_env() ctx = TradeContext(config) resp = ctx.margin_ratio("700.HK") print(resp) ``` ## 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 | #### Get 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 # Get Cash Flow # https://open.longportapp.com/docs/trade/asset/cashflow from datetime import datetime from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) resp = ctx.cash_flow( start_at = datetime(2022, 5, 9), end_at = datetime(2022, 5, 12), ) print(resp) ``` ## 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 #### Withdraw 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 config = Config.from_env() ctx = TradeContext(config) ctx.cancel_order("709043056541253632") ``` ## 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 | #### Get History Order 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 config = Config.from_env() 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) ``` ## 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 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 | #### 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 | | 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) | ### Request Example ```python from decimal import Decimal from longport.openapi import TradeContext, Config, OrderType, OrderSide, TimeInForceType # Load configuration from environment variables config = Config.from_env() # 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) ``` ## 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, OrderStatus, OrderType, OrderSide config = Config.from_env() ctx = TradeContext(config) resp = ctx.estimate_max_purchase_quantity( symbol = "700.HK", order_type = OrderType.LO, side = OrderSide.Buy, ) print(resp) ``` ## 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. | #### Get Today Order 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 config = Config.from_env() ctx = TradeContext(config) resp = ctx.today_orders( symbol = "700.HK", status = [OrderStatus.Filled, OrderStatus.New], side = OrderSide.Buy, market = Market.HK, ) print(resp) ``` ## 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 | #### 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 | | 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) | ### Request Example ```python from decimal import Decimal from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) ctx.replace_order( order_id = "709043056541253632", quantity = Decimal(100), price = Decimal(50), ) ``` ## 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 config = Config.from_env() ctx = TradeContext(config) resp = ctx.order_detail( order_id = "701276261045858304", ) print(resp) ``` ## 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": "", "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 | ### Qa ### Trade ## Q1: What types of orders are supported? A: 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? A: 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? A: 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? A: Paper accounts currently support trading in Hong Kong and U.S. stocks, ETFs, and Hong Kong warrants. Short selling is supported for U.S. stocks. However, OTC trading, pre & post market trading, and options 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? A: 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? A: After placing orders through the OpenAPI, you can check the real-time status of orders by calling the order inquiry API. Alternatively, you can receive order update information through WebSocket push. You can also view orders and their statuses directly through the App/PC or other terminal products. ## Q7: How can I know if my account has sufficient funds for trading? A: 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"? A: 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. ### General ## Q1: Do I need to open a live account to call LongPort Developers? A: We provide a paper account, you can use it to complete the debugging of the OpenAPI quote and trading interfaces. ## Q2: How to open a paper account for debugging? A: Please visit [Development Center](https://open.longportapp.com/account/) 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? A: 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? A: 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, and Hong Kong warrant trading. Short selling is supported for US stocks. OTC stocks, pre & post market trading, and options trading are not supported in paper accounts. ## Q5: Interface call frequency limits A: Please visit [Rate Limit](docs/#rate-limit) for specific descriptions. ## Q6: How are interface call frequency limits applied in the case of multiple accounts? A: 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? A: 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? A: You can set the environment variable `LONGPORT_PRINT_QUOTE_PACKAGES` to `false`, 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. ### 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? A: 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? A: 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? A: The security code uses the `ticker.region` format, `ticker` represents the code. Aavailable subscribing securities are as followes.
    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
    You can also use LongPort App to find the symbol of security ## Q4: What is the quote authority of OpenAPI? How to buy quote cards? A: - 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 A: - 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 A: - The night market quotation needs to be actively enabled 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 A: - Create `Config` from environment variables Set environment variable `LONGPORT_ENABLE_OVERNIGHT` to `true` - 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) ``` ### 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 | ### 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) ### 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.longportapp.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) ### 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.longportapp.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 ``` ## Assets ### Chunks ## Zh-HK ### Docs #### Quote ##### Subscribe ##### Push ##### Security ##### Individual ##### Pull #### Trade ##### Execution ##### Asset ##### Order #### Qa #### Socket ##### Protocol ### 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 #### Quote ##### Subscribe ##### Push ##### Security ##### Individual ##### Pull #### Trade ##### Execution ##### Asset ##### Order #### Qa #### Socket ##### Protocol ### Skill