Skip to main 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, 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, timezone is UTC.

Environment Requirements

Install SDK

pip3 install longport

Let's take obtaining assets as an example to demonstrate how to use the SDK.

Configure Developer Account

  1. Download App and open an account.
  2. Complete the Python 3 environment installation and install Pip
  3. Get App Key, App Secret, Access Token and other information from LongPort OpenAPI official website

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

Login the LongPort OpenAPI 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.

Setting Environment Variables In macOS / Linux Environment

Open the terminal and enter the following command:

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"
About ENV

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

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

Setting Environment Variables In Windows Environment

Windows is a little more complicated, 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:

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.
Windows ENV Restrictions

Windows ENV Restrictions, when the above 3 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:

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.

caution

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

Scene Demonstration

Get Account Balance

Cteate account_asset.py and paste the code below:

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

python account_asset.py

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 - LV1 Nasdaq Basic (Only Open API).

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://longportapp.com/download

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

Create subscribe_quote.py and paste the code below:

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

python subscribe_quote.py

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.

Create submit_order.py and paste the code below:

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=200,
time_in_force=TimeInForceType.Day,
remark="Hello from Python SDK",
)
print(resp)

Run it

python submit_order.py

After running, the output is as follows:

SubmitOrderResponse { order_id: "718437534753550336" }

Get Today Order

Create today_orders.py and paste the code below:

from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.today_orders()
print(resp)

Run it

python today_orders.py

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 OpenAPI 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-sdk/tree/master/examples

SDK API Document

For detailed SDK API document, please visit:

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

Contact & Feedback