longbridge provides an easy-to-use interface for invoking Longbridge OpenAPI.
| 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 |
- SDK docs: https://longbridge.github.io/openapi/cpp/index.html
- Longbridge OpenAPI: https://open.longbridge.com/en/
Runnable examples live in examples/cpp/:
examples/cpp/get_quote/main.cppexamples/cpp/history_candlesticks_by_offset/main.cppexamples/cpp/http_client/main.cppexamples/cpp/subscribe_candlesticks/main.cppexamples/cpp/subscribe_quote/main.cppexamples/cpp/submit_order/main.cppexamples/cpp/today_orders/main.cpp
Install Longbridge OpenAPI SDK
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 OAuth client and create a Config
OAuthBuilder::build 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. The resulting OAuth handle is passed directly to
Config::from_oauth.
#include <iostream>
#include <longbridge.hpp>
using namespace longbridge;
int
main(int argc, char const* argv[])
{
OAuthBuilder("your-client-id")
.build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](AsyncResult<void*, OAuth> res) {
if (!res) {
std::cout << "OAuth failed: " << *res.status().message() << std::endl;
return;
}
Config config = Config::from_oauth(*res);
// Use config to create contexts...
});
std::cin.get();
return 0;
}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"| 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_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. |
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 PowerShellProgrammatically:
Config config = Config::from_apikey("app-key", "app-secret", "access-token")
.enable_papertrading();#include <iostream>
#include <longbridge.hpp>
#ifdef WIN32
#include <windows.h>
#endif
using namespace longbridge;
using namespace longbridge::quote;
int
main(int argc, char const* argv[])
{
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
OAuthBuilder("your-client-id")
.build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](AsyncResult<void*, OAuth> res) {
if (!res) {
std::cout << "OAuth failed: " << *res.status().message() << std::endl;
return;
}
Config config = Config::from_oauth(*res);
QuoteContext ctx = QuoteContext::create(config);
std::vector<std::string> symbols = {
"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"
};
ctx.quote(symbols, [](auto res) {
if (!res) {
std::cout << "failed to get quote: " << *res.status().message()
<< std::endl;
return;
}
for (auto it = res->cbegin(); it != res->cend(); ++it) {
std::cout << it->symbol << " timestamp=" << it->timestamp
<< " last_done=" << (double)it->last_done
<< " prev_close=" << (double)it->prev_close
<< " open=" << (double)it->open
<< " high=" << (double)it->high
<< " low=" << (double)it->low
<< " volume=" << it->volume
<< " turnover=" << it->turnover << std::endl;
}
});
});
std::cin.get();
return 0;
}#include <iostream>
#include <longbridge.hpp>
#ifdef WIN32
#include <windows.h>
#endif
using namespace longbridge;
using namespace longbridge::quote;
int
main(int argc, char const* argv[])
{
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
OAuthBuilder("your-client-id")
.build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](AsyncResult<void*, OAuth> res) {
if (!res) {
std::cout << "OAuth failed: " << *res.status().message() << std::endl;
return;
}
Config config = Config::from_oauth(*res);
QuoteContext ctx = QuoteContext::create(config);
ctx.set_on_quote([](auto event) {
std::cout << event->symbol << " timestamp=" << event->timestamp
<< " last_done=" << (double)event->last_done
<< " open=" << (double)event->open
<< " high=" << (double)event->high
<< " low=" << (double)event->low
<< " volume=" << event->volume
<< " turnover=" << event->turnover << std::endl;
});
std::vector<std::string> symbols = {
"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"
};
ctx.subscribe(symbols, SubFlags::QUOTE(), [](auto res) {
if (!res) {
std::cout << "failed to subscribe: " << *res.status().message()
<< std::endl;
}
});
});
std::cin.get();
return 0;
}#include <iostream>
#include <longbridge.hpp>
#ifdef WIN32
#include <windows.h>
#endif
using namespace longbridge;
using namespace longbridge::trade;
int
main(int argc, char const* argv[])
{
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
OAuthBuilder("your-client-id")
.build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](AsyncResult<void*, OAuth> res) {
if (!res) {
std::cout << "OAuth failed: " << *res.status().message() << std::endl;
return;
}
Config config = Config::from_oauth(*res);
TradeContext ctx = TradeContext::create(config);
SubmitOrderOptions opts{
"700.HK", OrderType::LO, OrderSide::Buy,
Decimal(200), TimeInForceType::Day, Decimal(50.0),
std::nullopt, std::nullopt, std::nullopt,
std::nullopt, std::nullopt, std::nullopt,
std::nullopt,
};
ctx.submit_order(opts, [](auto res) {
if (!res) {
std::cout << "failed to submit order: " << *res.status().message()
<< std::endl;
return;
}
std::cout << "order id: " << res->order_id << std::endl;
});
});
std::cin.get();
return 0;
}- Windows
setxrequires a new terminal; usesetfor the currentcmd.exesession. - If you don't see push events, keep the process alive (examples use
std::cin.get()). - If building on Linux/macOS, ensure
ncursesis installed (examples link it on non-Windows). - For debugging, set
LONGBRIDGE_LOG_PATHto enable SDK logs.
Licensed under either of
- Apache License, Version 2.0,(LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT) at your option.