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