Skip to Content

Getting Started

Foreword

LongPort OpenAPI SDK is implemented based on Rust we have released SDK for Python, Node.js, Rust, C++/C and Java ..., and support for other languages will be launched in the future.

API Host

  • HTTP API - https://openapi.longportapp.com
  • WebSocket Quote - wss://openapi-quote.longportapp.com
  • WebSocket Trade - wss://openapi-trade.longportapp.com
💡Tip

For access in mainland China, you can use .cn domains for better connectivity:

  • HTTP API - https://openapi.longport.cn
  • WebSocket Quote - wss://openapi-quote.longport.cn
  • WebSocket Trade - wss://openapi-trade.longport.cn

The SDK automatically selects the access point by network. If the SDK selects incorrectly, set the environment variable LONGPORT_REGION (e.g. cn or hk).

Time Format

All API response are used Unix Timestamp, timezone is UTC.

Environment Requirements

Install SDK

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 authentication credentials from LongPort Developers official website

Authentication Methods

LongPort OpenAPI supports two authentication methods:

OAuth 2.0 is the modern authentication method that uses Bearer tokens without requiring HMAC signatures, making it more secure and convenient.

Step 1: Register OAuth Client

Run the following command to register an OAuth client and get your client_id:

Response example:

json
{
  "client_id": "72d9caaf-0bd4-4000-85a7-8c7978c74544",
  "client_id_issued_at": 1773311221,
  "client_secret_expires_at": 1773314821,
  "client_name": "My LongPort OpenAPI",
  "redirect_uris": ["http://localhost:60355/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "token_endpoint_auth_method": "none",
  "response_types": ["code"],
  "registration_access_token": "BVlMLEtNUUu4FoRFNItC2FfeR/rLpqLNyEuCJNNTCWE=",
  "registration_client_uri": "https://openapi.longportapp.com/oauth2/register/72d9caaf-0bd4-4000-85a7-8c7978c74544"
}

Save the client_id for later use.

Step 2: Authorize and Get Token

The SDK provides built-in OAuth support. Use OAuthBuilder to run the browser flow; after authorization, use Config.from_oauth() to create the configuration. The token is persisted automatically and refreshed when expired.

Token storage path: ~/.longport/openapi/tokens/<client_id> (macOS/Linux), or %USERPROFILE%\.longport\openapi\tokens\<client_id> on Windows.

💡OAuth Benefits
  • More secure (no shared secret)
  • Simpler integration (no signature calculation)
  • Token-based modern authentication
  • Better suited for modern applications
⚠️Token Security

OAuth tokens should be stored securely in your application (e.g., encrypted file, secure keychain), not in environment variables for security reasons.

Method 2: Legacy API Key (Compatible)

Get App Key, App Secret, Access Token and other information

Log in at https://open.longport.com/ and open User Center.

The application credential (App Key, App Secret, Access Token) is shown on that page. This Access Token is the legacy API Key credential; it is not the same as the access token obtained via OAuth or the Refresh Token API. Set these as environment variables for development.

Environment Variables

⚠️Caution

Please pay attention to protect your Access Token information, anyone who gets it can trade your account through OpenAPI!

API Key credentials (required for legacy API Key):

Environment VariableDescription
LONGPORT_APP_KEYApp key from developer center
LONGPORT_APP_SECRETApp secret from developer center
LONGPORT_ACCESS_TOKENLegacy Access Token from https://open.longport.com/ (User Center → application credential). Not the OAuth access token.

Other environment variables:

NameDescription
LONGPORT_LANGUAGELanguage identifier, zh-CN, zh-HK or en (Default: en)
LONGPORT_HTTP_URLHTTP endpoint url (Default: https://openapi.longportapp.com)
LONGPORT_QUOTE_WS_URLQuote websocket endpoint url (Default: wss://openapi-quote.longportapp.com/v2)
LONGPORT_TRADE_WS_URLTrade websocket endpoint url (Default: wss://openapi-trade.longportapp.com/v2)
LONGPORT_REGIONOverride API region; SDK auto-selects by network. Set to cn or hk if incorrect.
LONGPORT_ENABLE_OVERNIGHTEnable overnight quote, true or false (Default: false). Overnight quotes are included free in US LV1. US stocks only.
LONGPORT_PUSH_CANDLESTICK_MODErealtime or confirmed (Default: realtime)
LONGPORT_PRINT_QUOTE_PACKAGESPrint quote packages when connected, true or false (Default: true)
LONGPORT_LOG_PATHSet the path of the log files (Default: no logs)
ℹ️Info

The SDK also accepts the legacy LONGPORT_* variable names for backward compatibility.

We recommend that you set the environment variables. For the convenience of demonstration, these environment variables will be used in the sample code in the documents in the following chapters.

💡About ENV

The ENV variables are not necessary conditions, if it is inconvenient to set the ENV variables or encounter problems that are difficult to solve, you can not set the ENV variables, but directly use the parameters in the code to initialize.

The Config in LongPort OpenAPI SDK can be created with Config.from_apikey_env() (or Config.fromApikeyEnv() in Node/Java) when using environment variables, or Config.from_apikey(app_key, app_secret, access_token) when passing parameters directly. See the comments in the example code below for "Init config without ENV".

Set Environment for macOS / Linux

Open the terminal and enter the following command:

bash
export LONGPORT_APP_KEY="App Key from user center"
export LONGPORT_APP_SECRET="App Secret from user center"
export LONGPORT_ACCESS_TOKEN="Access Token from user center"

Set Environment for Windows

Windows is a little more complicated, we provide two methods to set the environment variables.

  1. Through the GUI: Right click on "My Computer" on the desktop, select "Properties", click "Advanced system settings" in the pop-up window.

    • Click "Environment Variables" in the pop-up window.

    • Click "New" in the pop-up window, then enter the environment variable name, such as LONGPORT_APP_KEY, Value respectively fill in the App Key, App Secret, Access Token obtained from the page.

  2. Through the CMD: Press the Win + R shortcut keys and enter the cmd command to start the command line (it is recommended to use Windows Terminal for a better development experience).

    Enter the following command in the command line to set the environment variable:

    bash
    C:\Users\jason> setx LONGPORT_APP_KEY "App Key from user center"
    Success: the specified value has been saved.
    
    C:\Users\jason> setx LONGPORT_APP_SECRET "App Secret from user center"
    Success: the specified value has been saved.
    
    C:\Users\jason> setx LONGPORT_ACCESS_TOKEN "Access Token from user center"
    Success: the specified value has been saved.
    ⚠️Windows ENV Restrictions

    Windows ENV Restrictions, when the above commands are executed successfully, you need to restart Windows or log out and log in again before you can read it.

    After logging out or restarting, open the command line again and enter the following command to verify that the environment variables are set correctly:

    bash
    C:\Users\jason> set LONGPORT
    LONGPORT_APP_KEY=xxxxxxx
    LONGPORT_APP_SECRET=xxxxxx
    LONGPORT_ACCESS_TOKEN=xxxxxxx

    If it prints the value you just set correctly, then the environment variable is right.

Refresh Access Token

ℹ️Info

This applies to Legacy API Key authentication only. OAuth 2.0 tokens are refreshed automatically by the SDK.

The Legacy API Key Access Token expires after 90 days by default. Call Config.refresh_access_token() to obtain a new token before it expires, then update your stored LONGPORT_ACCESS_TOKEN with the returned value.

The expired_at parameter sets when the new token expires (default: 90 days from now).

Scene Demonstration

Get Account Balance

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 - "Quote authority" is correct

  • HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
  • US Market - US LV1 (Only OpenAPI).

Before running, visit the Developer Center and ensure that the account has the correct quote level.

ℹ️Info

If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app.

https://longport.com/download

When you have the correct Quote authority, it might look like this:

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 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.

After running, the output is as follows:

SubmitOrderResponse { order_id: "718437534753550336" }

Get Today Orders

After running, the output is as follows:

Order {
  order_id: "718437534753550336",
  status: NotReported,
  stock_name: "腾讯控股 1",
  quantity: 200,
  executed_quantity: None,
  price: Some(50.000),
  executed_price: None,
  submitted_at: 2022-06-06T12:14:16Z,
  side: Buy,
  symbol: "700.HK",
  order_type: LO,
  last_done: None,
  trigger_price: Some(0.000),
  msg: "",
  tag: Normal,
  time_in_force: Day,
  expire_date: Some(NaiveDate(Date { year: 2022, ordinal: 158 })),
  updated_at: Some(2022-06-06T12:14:16Z),
  trigger_at: None,
  trailing_amount: None,
  trailing_percent: None,
  limit_offset: None,
  trigger_status: None,
  currency: "HKD",
  outside_rth: nonce
}

The above example has fully demonstrated how to use the SDK to access the OpenAPI interface. For more interfaces, please read the LongPort Developers Documentation in detail and use them according to different interfaces.

More Examples

We provide the complete code of the above examples in the GitHub repository of LongPort OpenAPI Python SDK, and we will continue to add or update it later.

https://github.com/longportapp/openapi/tree/master/examples

SDK API Document

For detailed SDK API document, please visit:

https://longportapp.github.io/openapi/

Contact & Feedback

If there are any questions or suggestions, please feel free to post an issue on GitHub, we will reply as soon as possible.

Or there have a lot old discussion in the GitHub issue, you can search the issue to find the answer.