Skip to main content

Longbridge OpenAPI SDK for Python

longbridge provides an easy-to-use interface for invoking Longbridge OpenAPI.

Context Types

Context Description
QuoteContext Real-time quotes, candlesticks, options, warrants, watchlists, push subscriptions
TradeContext Orders, positions, account balance, executions, cash flow
AssetContext Account statement download
ContentContext News, community topics
FundamentalContext Financial reports, analyst ratings, dividends, valuation, company overview, shareholders
MarketContext Market status, broker holdings, A/H premium, trade statistics, anomaly alerts, index constituents
CalendarContext Financial calendar (earnings, dividends, splits, IPOs, macro data, market closures)
PortfolioContext Exchange rates, portfolio P&L analysis
AlertContext Price alert management (add/enable/disable/delete)
DCAContext Dollar-cost averaging plan management
SharelistContext Community sharelist management

Documentation

Examples

Runnable examples live in examples/python/, grouped as follows.

Synchronous API (same as the snippets in this README):

  • examples/python/account_asset.py
  • examples/python/history_candlesticks.py
  • examples/python/http_client.py
  • examples/python/subscribe_candlesticks.py
  • examples/python/subscribe_quote.py
  • examples/python/submit_order.py
  • examples/python/today_orders.py

Asynchronous API (AsyncQuoteContext, AsyncTradeContext, HttpClient.request_async):

  • examples/python/account_asset_async.py
  • examples/python/history_candlesticks_async.py
  • examples/python/http_client_async.py
  • examples/python/subscribe_candlesticks_async.py
  • examples/python/subscribe_quote_async.py
  • examples/python/submit_order_async.py
  • examples/python/today_orders_async.py

References

  • Config

    The configuration of the SDK.

  • QuoteContext

    The Quote API part of the SDK, e.g.: get basic information of securities, subscribe quotes...

  • TradeContext

    The Trade API part of the SDK, e.g.: submit order, get order status...

Quickstart

Install Longbridge OpenAPI SDK

pip install longbridge

Authentication

Longbridge OpenAPI supports two authentication methods:

OAuth 2.0 is the modern authentication method that uses Bearer tokens without requiring HMAC signatures.

Step 1: Register OAuth Client

First, register an OAuth client to get your client_id:

bash / macOS / Linux

curl -X POST https://openapi.longbridge.com/oauth2/register \
  -H "Content-Type: application/json" \
  -d '{
    "client_name": "My Application",
    "redirect_uris": ["http://localhost:60355/callback"],
    "grant_types": ["authorization_code", "refresh_token"]
  }'

PowerShell (Windows)

Invoke-RestMethod -Method Post -Uri https://openapi.longbridge.com/oauth2/register `
  -ContentType "application/json" `
  -Body '{
    "client_name": "My Application",
    "redirect_uris": ["http://localhost:60355/callback"],
    "grant_types": ["authorization_code", "refresh_token"]
  }'

Response:

{
  "client_id": "your-client-id-here",
  "client_secret": null,
  "client_name": "My Application",
  "redirect_uris": ["http://localhost:60355/callback"]
}

Save the client_id for use in your application.

Step 2: Build an OAuth client and create Config

OAuthBuilder loads a cached token from ~/.longbridge/openapi/tokens/<client_id> (%USERPROFILE%\.longbridge\openapi\tokens\<client_id> on Windows) if one exists and is still valid, or starts the browser authorization flow automatically. The token is persisted to the same path after a successful authorization or refresh.

from longbridge.openapi import OAuthBuilder, Config

oauth = OAuthBuilder("your-client-id").build(
    lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)

For async code use build_async:

import asyncio
from longbridge.openapi import OAuthBuilder, Config

async def main():
    oauth = await OAuthBuilder("your-client-id").build_async(
        lambda url: print(f"Open this URL to authorize: {url}")
    )
    config = Config.from_oauth(oauth)

asyncio.run(main())

2. Legacy API Key (Environment Variables)

Setting environment variables (macOS/Linux)

export LONGBRIDGE_APP_KEY="App Key get from user center"
export LONGBRIDGE_APP_SECRET="App Secret get from user center"
export LONGBRIDGE_ACCESS_TOKEN="Access Token get from user center"

Setting environment variables (Windows)

setx LONGBRIDGE_APP_KEY "App Key get from user center"
setx LONGBRIDGE_APP_SECRET "App Secret get from user center"
setx LONGBRIDGE_ACCESS_TOKEN "Access Token get from user center"

Other environment variables

Name Description
LONGBRIDGE_LANGUAGE Language identifier, zh-CN, zh-HK or en (Default: en)
LONGBRIDGE_HTTP_URL HTTP endpoint url (Default: https://openapi.longbridge.com)
LONGBRIDGE_QUOTE_WS_URL Quote websocket endpoint url (Default: wss://openapi-quote.longbridge.com/v2)
LONGBRIDGE_TRADE_WS_URL Trade websocket endpoint url (Default: wss://openapi-trade.longbridge.com/v2)
LONGBRIDGE_ENABLE_OVERNIGHT Enable overnight quote, true or false (Default: false)
LONGBRIDGE_PUSH_CANDLESTICK_MODE realtime or confirmed (Default: realtime)
LONGBRIDGE_QUOTE_TRANSPORT Transport for quote pull APIs, ws or http (Default: ws)
LONGBRIDGE_PRINT_QUOTE_PACKAGES Print quote packages when connected, true or false (Default: true)
LONGBRIDGE_LOG_PATH Set the path of the log files (Default: no logs)
LONGBRIDGE_PAPERTRADING Enable paper trading mode, true or false (Default: false). See Paper Trading.

Then create a config from the environment:

from longbridge.openapi import Config

config = Config.from_apikey_env()

Quote API (Get basic information of securities)

from longbridge.openapi import Config, QuoteContext, OAuthBuilder

oauth = OAuthBuilder("your-client-id").build(
    lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)

# Create a context for quote APIs
ctx = QuoteContext(config)

# Get basic information of securities
resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)

Quote API (Subscribe quotes)

from time import sleep
from longbridge.openapi import Config, QuoteContext, SubType, PushQuote, OAuthBuilder

oauth = OAuthBuilder("your-client-id").build(
    lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)

# A callback to receive quote data
def on_quote(symbol: str, event: PushQuote):
    print(symbol, event)

# Create a context for quote APIs
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)

# Subscribe
ctx.subscribe(["700.HK"], [SubType.Quote])

# Receive push for 30 seconds
sleep(30)

Trade API (Submit order)

from decimal import Decimal
from longbridge.openapi import TradeContext, Config, OrderType, OrderSide, TimeInForceType, OAuthBuilder

oauth = OAuthBuilder("your-client-id").build(
    lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)

# Create a context for trade APIs
ctx = TradeContext(config)

# Submit order
resp = ctx.submit_order(
    "700.HK", OrderType.LO, OrderSide.Buy,
    Decimal("500"), TimeInForceType.Day,
    submitted_price=Decimal("50"),
    remark="Hello from Python SDK",
)
print(resp)

Asynchronous API

The SDK provides async contexts and an async HTTP client for use with Python's asyncio. All I/O methods return awaitables; callbacks (e.g. for push events) are set the same way as in the sync API. Async quote/trade contexts support async callbacks: if a set_on_quote, set_on_candlestick, or set_on_order_changed callback is an async function (returns a coroutine), it is scheduled on the event loop. When using async callbacks, pass the loop so the SDK can schedule them: AsyncQuoteContext.create(config, loop_=asyncio.get_running_loop()).

  • Async quote: create with ctx = AsyncQuoteContext.create(config) (synchronous, no await), then e.g. await ctx.quote(["700.HK"]), await ctx.subscribe(...).
  • Async trade: create with ctx = AsyncTradeContext.create(config) (synchronous, no await), then e.g. await ctx.today_orders(), await ctx.submit_order(...).
  • Async HTTP: resp = await http_cli.request_async("get", "/v1/trade/execution/today").

Example (async quote):

import asyncio
from longbridge.openapi import Config, AsyncQuoteContext, SubType, PushQuote, OAuthBuilder

def on_quote(symbol: str, event: PushQuote):
    print(symbol, event)

async def main():
    oauth = await OAuthBuilder("your-client-id").build_async(
        lambda url: print(f"Open this URL to authorize: {url}")
    )
    config = Config.from_oauth(oauth)
    ctx = AsyncQuoteContext.create(config, loop_=asyncio.get_running_loop())
    ctx.set_on_quote(on_quote)
    await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
    quotes = await ctx.quote(["700.HK"])
    print(quotes)
    await asyncio.sleep(10)

asyncio.run(main())

See the *_async.py examples in examples/python/ for full async flows.

Paper Trading

If your account is a paper trading (simulation) account and you want to place orders, you must explicitly enable paper trading mode. When enabled, all API calls target the paper trading environment and the server validates the token — if the token belongs to a real-money account the server returns an error.

By default this option is off: the server imposes no restrictions and accepts requests from both paper trading and real-money accounts.

Via environment variable (applies automatically to all constructor methods):

export LONGBRIDGE_PAPERTRADING=true   # macOS / Linux
$env:LONGBRIDGE_PAPERTRADING = "true"   # Windows PowerShell

Programmatically:

from longbridge.openapi import Config

config = Config.from_apikey(
    "app-key", "app-secret", "access-token",
    enable_papertrading=True,
)

Troubleshooting

  • Windows setx requires a new terminal; use set for the current cmd.exe session.
  • If the program exits, you won't receive push events; keep the process alive (e.g. sleep(...)).
  • For debugging, set LONGBRIDGE_LOG_PATH to enable SDK logs.

License

Licensed under either of

Metadata

Release files for longbridge 5.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for longbridge 5.3.0
File
longbridge-5.3.0-cp311-cp311-macosx_10_12_x86_64.whl CPython 3.11 CPython 3.11 macOS 10.12+ x86-64 Details
longbridge-5.3.0-cp310-cp310-win_amd64.whl CPython 3.10 CPython 3.10 Windows x86-64 Details
longbridge-5.3.0-cp310-cp310-musllinux_1_2_x86_64.whl CPython 3.10 CPython 3.10 Linux musl 1.2+ x86-64 Details
longbridge-5.3.0-cp310-cp310-musllinux_1_2_aarch64.whl CPython 3.10 CPython 3.10 Linux musl 1.2+ ARM64 Details
longbridge-5.3.0-cp310-cp310-manylinux_2_28_x86_64.whl CPython 3.10 CPython 3.10 Linux glibc 2.28+ x86-64 Details
longbridge-5.3.0-cp310-cp310-manylinux_2_28_aarch64.whl CPython 3.10 CPython 3.10 Linux glibc 2.28+ ARM64 Details
longbridge-5.3.0-cp310-cp310-macosx_11_0_arm64.whl CPython 3.10 CPython 3.10 macOS 11.0+ ARM64 Details
longbridge-5.3.0-cp310-cp310-macosx_10_12_x86_64.whl CPython 3.10 CPython 3.10 macOS 10.12+ x86-64 Details

Total release size: 109.1 MB

Release files / longbridge-5.3.0-cp311-cp311-macosx_10_12_x86_64.whl

Download URL longbridge-5.3.0-cp311-cp311-macosx_10_12_x86_64.whl
Size 13.4 MB
Tags CPython 3.11 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
1313c944276eb34788b73d4ad4618f9d20cad62268804b14eb9559a2661f249a
BLAKE2b-256 checksum
How to use checksums
fcd64c9c7e06ba7917fcf1e083d984402a903cad0d6b34dcfcdf7dbdf5874ee6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / longbridge-5.3.0-cp310-cp310-win_amd64.whl

Download URL longbridge-5.3.0-cp310-cp310-win_amd64.whl
Size 14.8 MB
Tags CPython 3.10 Windows x86-64
SHA-256 checksum
How to use checksums
506a96444a10ce153095a0933d6f7f0d05b9f93f4c76cbf783472c1611d0e1df
BLAKE2b-256 checksum
How to use checksums
2bcfa248146a3dbb2f4613769b141fcd55b5926049f10dc5c243676bab81aa7d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / longbridge-5.3.0-cp310-cp310-musllinux_1_2_x86_64.whl

Download URL longbridge-5.3.0-cp310-cp310-musllinux_1_2_x86_64.whl
Size 13.9 MB
Tags CPython 3.10 Linux musl 1.2+ x86-64
SHA-256 checksum
How to use checksums
256a32992133a88d9cc8d10032d6f55e4273d0aacc76b4dd7f1418754bcb25de
BLAKE2b-256 checksum
How to use checksums
50a98e341356d86d1cc21a1012d5eeae723299d144a524d675b07b6593448f6b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / longbridge-5.3.0-cp310-cp310-musllinux_1_2_aarch64.whl

Download URL longbridge-5.3.0-cp310-cp310-musllinux_1_2_aarch64.whl
Size 13.6 MB
Tags CPython 3.10 Linux musl 1.2+ ARM64
SHA-256 checksum
How to use checksums
b241c22bf09e50d1333a14ff6fb1d2e7c1ce48d35cc39229994fd85fb056194c
BLAKE2b-256 checksum
How to use checksums
bc8097aecd44f8d3929e7723a3ada91fdb6dfdaa145ceee3bb5a443e66e5e5ae
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / longbridge-5.3.0-cp310-cp310-manylinux_2_28_x86_64.whl

Download URL longbridge-5.3.0-cp310-cp310-manylinux_2_28_x86_64.whl
Size 13.7 MB
Tags CPython 3.10 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
ed6f6a441ad67fc5cfa3f75502b8cf2d00c1f38b4a9f8b5aeb96e7a0bdcd3c29
BLAKE2b-256 checksum
How to use checksums
69a727aeffc822702262472b2fbeb5339b827373e18d59233eca5149e6e37c97
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / longbridge-5.3.0-cp310-cp310-manylinux_2_28_aarch64.whl

Download URL longbridge-5.3.0-cp310-cp310-manylinux_2_28_aarch64.whl
Size 13.5 MB
Tags CPython 3.10 Linux glibc 2.28+ ARM64
SHA-256 checksum
How to use checksums
620cfcf0a8c8252399c619a5a914894eb4b0e01214e453567c9d3e773fa4f2cb
BLAKE2b-256 checksum
How to use checksums
7a573d55460c6428a777084c782d23ed923538f1db796a2585f95deed121526f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / longbridge-5.3.0-cp310-cp310-macosx_11_0_arm64.whl

Download URL longbridge-5.3.0-cp310-cp310-macosx_11_0_arm64.whl
Size 12.8 MB
Tags CPython 3.10 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
6f8350f833af6bfffd4a6251d0807a2d96d88ca96051f5d313aa44486e4ea6d9
BLAKE2b-256 checksum
How to use checksums
0ebf7b8e98edcda0f7a293d68cd6330e7bb43079a8520516b8b82665d8e2d710
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / longbridge-5.3.0-cp310-cp310-macosx_10_12_x86_64.whl

Download URL longbridge-5.3.0-cp310-cp310-macosx_10_12_x86_64.whl
Size 13.4 MB
Tags CPython 3.10 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
19733ea0314c9ff837f64e6aa5409cdc0073c866f6e8ef9da707ad01be39c735
BLAKE2b-256 checksum
How to use checksums
02590b7247ff37f815ff1dc52e7472d564ba4dcfc348818059e8fc646f297d97
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Security for longbridge 5.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 8 files in this release have been uploaded with provenance metadata.

Select from 8 files

Attestation for longbridge-5.3.0-cp311-cp311-macosx_10_12_x86_64.whl

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

5.3.0 This release

8 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page