### Build and Run Java HTTP Client Example Source: https://github.com/longbridge/openapi/blob/main/README.md Build and run the Java HTTP client example from the example module directory to verify your environment and credentials. ```bash cd examples/java/http_client mvn -q -DskipTests package mvn -q -DskipTests exec:java ``` -------------------------------- ### Run Python HTTP Client Example Source: https://github.com/longbridge/openapi/blob/main/README.md Execute the Python HTTP client example to verify your environment and credentials. ```bash python examples/python/http_client.py ``` -------------------------------- ### Run Node.js HTTP Client Example Source: https://github.com/longbridge/openapi/blob/main/README.md Execute the Node.js HTTP client example to verify your environment and credentials. ```bash node examples/nodejs/http_client.js ``` -------------------------------- ### Run Rust HTTP Client Example Source: https://github.com/longbridge/openapi/blob/main/README.md Execute the Rust HTTP client example using Cargo to verify your environment and credentials. ```bash cargo run --manifest-path examples/rust/Cargo.toml -p http_client ``` -------------------------------- ### C/C++ HTTP Client Example Location Source: https://github.com/longbridge/openapi/blob/main/README.md Locate the C/C++ HTTP client example sources. Build instructions depend on your toolchain; refer to the corresponding language SDK README. ```text Use the sources in `examples/c/http_client/main.c` and `examples/cpp/http_client/main.cpp`. ``` -------------------------------- ### Install Longbridge OpenAPI SDK Source: https://github.com/longbridge/openapi/blob/main/nodejs/README.md Install the SDK using npm. This is the first step before using any Longbridge OpenAPI functionalities. ```bash npm install longbridge ``` -------------------------------- ### Subscribe to Real-time Quotes with Java Source: https://github.com/longbridge/openapi/blob/main/java/README.md This example shows how to subscribe to real-time quote updates for specified securities. The program will print updates to the console. Ensure the program remains active to receive updates, for example, using Thread.sleep. ```java import com.longbridge.*; import com.longbridge.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open this URL to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { ctx.setOnQuote((symbol, quote) -> System.out.printf("%s\t%s\n", symbol, quote)); ctx.subscribe( new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }, SubFlags.Quote).get(); Thread.sleep(30000); } } } ``` -------------------------------- ### Install Longbridge OpenAPI SDK Source: https://github.com/longbridge/openapi/blob/main/nodejs/README.md Install the Longbridge OpenAPI SDK for Node.js using npm. ```APIDOC ## Install Longbridge OpenAPI SDK ```bash npm install longbridge ``` ``` -------------------------------- ### Install Longbridge OpenAPI SDK Source: https://github.com/longbridge/openapi/blob/main/python/docs/index.md Use pip to install the Longbridge OpenAPI SDK for Python. ```bash pip install longbridge ``` -------------------------------- ### OAuth 2.0 Authentication Setup Source: https://context7.com/longbridge/openapi/llms.txt Register an OAuth client to obtain credentials for API access. This is the recommended authentication method. ```APIDOC ## POST /oauth2/register ### Description Register an OAuth client to obtain credentials for API access. ### Method POST ### Endpoint https://openapi.longbridge.com/oauth2/register ### Request Body - **client_name** (string) - Required - The name of your application. - **redirect_uris** (array of strings) - Required - A list of valid redirect URIs for your application. - **grant_types** (array of strings) - Required - The grant types supported by your application (e.g., "authorization_code", "refresh_token"). ### Request Example ```json { "client_name": "My Application", "redirect_uris": ["http://localhost:60355/callback"], "grant_types": ["authorization_code", "refresh_token"] } ``` ### Response #### Success Response (200) - **client_id** (string) - The unique identifier for your OAuth client. - **client_secret** (string) - The client secret (may be null if not applicable). - **client_name** (string) - The name of your application. - **redirect_uris** (array of strings) - The registered redirect URIs. #### Response Example ```json { "client_id": "your-client-id-here", "client_secret": null, "client_name": "My Application", "redirect_uris": ["http://localhost:60355/callback"] } ``` ``` -------------------------------- ### Trade API - Submit Order Source: https://github.com/longbridge/openapi/blob/main/python/README.md This example demonstrates how to submit a new trade order for a specified security. ```APIDOC ## Trade API - Submit Order This endpoint allows you to place a new order in the market. ### Method POST ### Endpoint `/v1/trade/order` ### Parameters #### Request Body - **symbol** (string) - Required - The symbol of the security to trade (e.g., `"700.HK"`). - **order_type** (string) - Required - Type of order. Enum: `LO` (Limit Order), `MO` (Market Order), `SL` (Stop Limit Order), `SM` (Stop Market Order). - **order_side** (string) - Required - Side of the order. Enum: `Buy`, `Sell`. - **quantity** (number) - Required - The number of shares to trade. - **time_in_force** (string) - Required - Duration the order remains active. Enum: `Day`, `GTC` (Good Till Cancelled), `IOC` (Immediate Or Cancel). - **submitted_price** (number) - Optional - The price for limit or stop limit orders. Required if `order_type` is `LO` or `SL`. - **remark** (string) - Optional - A custom remark for the order. ### Request Example ```python 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) ``` ### Response #### Success Response (200) - **order_id** (string) - The unique identifier for the submitted order. - **symbol** (string) - The symbol of the security traded. - **order_type** (string) - The type of order placed. - **order_side** (string) - The side of the order (Buy/Sell). - **quantity** (number) - The quantity of the order. - **price** (number) - The price of the order. - **time_in_force** (string) - The time in force for the order. - **status** (string) - The current status of the order. - **created_at** (string) - Timestamp when the order was created. #### Response Example ```json { "order_id": "1234567890", "symbol": "700.HK", "order_type": "LO", "order_side": "Buy", "quantity": 500, "price": 50.0, "time_in_force": "Day", "status": "New", "created_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Trade API - Submit Order Source: https://github.com/longbridge/openapi/blob/main/python/docs/index.md Provides an example of how to submit a trade order for a security. ```APIDOC ## Trade API - Submit Order ### Description This endpoint allows you to submit a trade order, specifying details such as symbol, order type, side, quantity, and price. ### Method POST (Implicit via SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (string) - Required - The trading symbol of the security. - **order_type** (OrderType) - Required - The type of order (e.g., LO, IOC). - **order_side** (OrderSide) - Required - The side of the order (Buy or Sell). - **quantity** (Decimal) - Required - The number of shares to trade. - **time_in_force** (TimeInForceType) - Required - The duration for which the order is valid. - **submitted_price** (Decimal) - Optional - The price at which to submit the order. - **remark** (string) - Optional - A remark for the order. ### Request Example ```python 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) ``` ### Response #### Success Response (200) - **order_id** (string) - The unique identifier for the submitted order. - **status** (string) - The current status of the order. #### Response Example ```json { "order_id": "1234567890", "status": "New" } ``` ``` -------------------------------- ### Subscribe to Real-time Quotes with C++ Source: https://github.com/longbridge/openapi/blob/main/cpp/README.md This example demonstrates how to subscribe to real-time quote updates for specified securities. It requires OAuth authentication and sets up a callback for incoming quote events. ```c++ #include #include #ifdef WIN32 #include #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 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 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; } ``` -------------------------------- ### QuoteContext.static_info Source: https://context7.com/longbridge/openapi/llms.txt Get static security information including lot size, exchange, and derivatives support. ```APIDOC ## QuoteContext.static_info ### Description Get static security information including lot size, exchange, and derivatives support. ### Method GET ### Endpoint /v1/quote/static_info ### Parameters #### Query Parameters - **symbols** (list of strings) - Required - A list of trading symbols. ### Request Example ```python from longbridge.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = QuoteContext(config) info_list = ctx.static_info(["700.HK", "AAPL.US"]) for info in info_list: print(f"Symbol: {info.symbol}") print(f" Name (EN): {info.name_en}") print(f" Exchange: {info.exchange}") print(f" Currency: {info.currency}") print(f" Lot Size: {info.lot_size}") print(f" Total Shares: {info.total_shares}") print(f" EPS: {info.eps}, BPS: {info.bps}") ``` ### Response #### Success Response (200) - **info_list** (list) - A list of static information objects for each symbol. - **symbol** (string) - The trading symbol. - **name_en** (string) - The security name in English. - **exchange** (string) - The exchange where the security is listed. - **currency** (string) - The currency of the security. - **lot_size** (integer) - The lot size for trading. - **total_shares** (float) - The total number of shares outstanding. - **eps** (float) - Earnings Per Share. - **bps** (float) - Book Value Per Share. #### Response Example ```json [ { "symbol": "700.HK", "name_en": "Tencent Holdings", "exchange": "HKEX", "currency": "HKD", "lot_size": 100, "total_shares": 9.6e9, "eps": 2.5, "bps": 10.0 } ] ``` ``` -------------------------------- ### Quote API - Get Basic Information Source: https://github.com/longbridge/openapi/blob/main/python/docs/index.md Demonstrates how to retrieve basic information for a list of securities. ```APIDOC ## Quote API - Get Basic Information ### Description This endpoint retrieves basic information for a given list of securities. ### Method GET (Implicit via SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python 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) ``` ### Response #### Success Response (200) - **symbol** (string) - The security symbol. - **name** (string) - The name of the security. - **exchange** (string) - The exchange where the security is listed. - **currency** (string) - The currency of the security. #### Response Example ```json [ { "symbol": "700.HK", "name": "Tencent Holdings", "exchange": "HKEX", "currency": "HKD" } ] ``` ``` -------------------------------- ### OAuth Client Registration Response Source: https://github.com/longbridge/openapi/blob/main/java/README.md This is an example of the JSON response received after successfully registering an OAuth client. It contains the client ID and other registration details. ```json { "client_id": "your-client-id-here", "client_secret": null, "client_name": "My Application", "redirect_uris": ["http://localhost:60355/callback"] } ``` -------------------------------- ### Submit a Limit Order Source: https://github.com/longbridge/openapi/blob/main/rust/README.md Submit a limit order for a security. This example shows how to configure order options including symbol, type, side, quantity, price, and time-in-force. API keys must be set in environment variables. ```rust use std::sync::Arc; use longbridge::{ decimal, trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType}, Config, TradeContext, }; #[tokio::main] async fn main() -> Result<(), Box> { // Load configuration from environment variables let config = Arc::new(Config::from_apikey_env()?); // Create a context for trade APIs let (ctx, _) = TradeContext::new(config); // Submit order let opts = SubmitOrderOptions::new( "700.HK", OrderType::LO, OrderSide::Buy, decimal!(500), TimeInForceType::Day, ) .submitted_price(decimal!(50i32)) .remark("Hello from Rust SDK".to_string()); let resp = ctx.submit_order(opts).await?; println!("{:?}", resp); Ok(()) } ``` -------------------------------- ### Subscribe to Real-time Quotes Source: https://github.com/longbridge/openapi/blob/main/rust/README.md Subscribe to real-time quote data for specified securities. This example demonstrates setting up the QuoteContext and receiving push events. Ensure API keys are configured via environment variables. ```rust use std::sync::Arc; use longbridge::{quote::SubFlags, Config, QuoteContext}; #[tokio::main] async fn main() -> Result<(), Box> { // Load configuration from environment variables let config = Arc::new(Config::from_apikey_env()?); // Create a context for quote APIs let (ctx, mut receiver) = QuoteContext::new(config); // Subscribe ctx.subscribe(["700.HK"], SubFlags::QUOTE).await?; // Receive push events while let Some(event) = receiver.recv().await { println!("{:?}", event); } Ok(()) } ``` -------------------------------- ### Subscribe to Real-time Security Quotes with Longbridge OpenAPI Source: https://github.com/longbridge/openapi/blob/main/c/README.md This example demonstrates how to subscribe to live quote updates for securities. It involves setting up OAuth, a quote context, and registering a callback function `on_quote` to handle incoming quote data. Use `LB_SUBFLAGS_QUOTE` for quote subscriptions. ```c #include #include #ifdef WIN32 #include #endif static void on_quote(const struct lb_quote_context_t* ctx, const struct lb_push_quote_t* quote, void* userdata) { printf("%s timestamp=%lld last_done=%f open=%f high=%f low=%f volume=%lld " "turnover=%f\n", quote->symbol, quote->timestamp, lb_decimal_to_double(quote->last_done), lb_decimal_to_double(quote->open), lb_decimal_to_double(quote->high), lb_decimal_to_double(quote->low), quote->volume, lb_decimal_to_double(quote->turnover)); } static void on_subscribe(const struct lb_async_result_t* res) { if (res->error) { printf("failed to subscribe: %s\n", lb_error_message(res->error)); } } static void on_oauth_ready(const struct lb_async_result_t* res) { if (res->error) { printf("OAuth failed: %s\n", lb_error_message(res->error)); return; } lb_oauth_t* oauth = (lb_oauth_t*)res->data; lb_config_t* config = lb_config_from_oauth(oauth); const lb_quote_context_t* ctx = lb_quote_context_new(config); lb_config_free(config); lb_oauth_free(oauth); lb_quote_context_set_on_quote(ctx, on_quote, NULL, NULL); const char* symbols[] = { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }; lb_quote_context_subscribe(ctx, symbols, 4, LB_SUBFLAGS_QUOTE, on_subscribe, NULL); } static void on_open_url(const char* url, void* userdata) { printf("Open this URL to authorize: %s\n", url); } int main(int argc, char const* argv[]) { #ifdef WIN32 SetConsoleOutputCP(CP_UTF8); #endif lb_oauth_new("your-client-id", 0, on_open_url, NULL, on_oauth_ready, NULL); getchar(); return 0; } ``` -------------------------------- ### Get Real-time Quotes (Python) Source: https://context7.com/longbridge/openapi/llms.txt Retrieve real-time quotes for multiple securities, including price, volume, and trading status. Requires an initialized QuoteContext. ```python 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) ctx = QuoteContext(config) resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) for quote in resp: print(f"Symbol: {quote.symbol}") print(f" Last Done: {quote.last_done}") print(f" Open: {quote.open}, High: {quote.high}, Low: {quote.low}") print(f" Volume: {quote.volume}, Turnover: {quote.turnover}") print(f" Trade Status: {quote.trade_status}") ``` -------------------------------- ### QuoteContext for Quotes (Rust) Source: https://context7.com/longbridge/openapi/llms.txt Fetch stock quotes asynchronously in Rust applications using QuoteContext. Requires OAuth setup and Tokio runtime. ```rust use std::sync::Arc; use longbridge::{Config, QuoteContext, oauth::OAuthBuilder}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {{url}}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); let (ctx, _) = QuoteContext::new(config); let resp = ctx .quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) .await?; println!("{:?}", resp); Ok(()) } ``` -------------------------------- ### Get Basic Security Quotes with Java Source: https://github.com/longbridge/openapi/blob/main/java/README.md Use this snippet to fetch basic quote information for a list of securities. Ensure you have your client ID for authentication. ```java import com.longbridge.*; import com.longbridge.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open this URL to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { SecurityQuote[] resp = ctx.getQuote( new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }).get(); for (SecurityQuote obj : resp) { System.out.println(obj); } } } } ``` -------------------------------- ### Get Account Balance Information (Python) Source: https://context7.com/longbridge/openapi/llms.txt Retrieves detailed account balance information, including cash, margin, and buying power. Requires an authenticated TradeContext. ```python from longbridge.openapi import TradeContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = TradeContext(config) balances = ctx.account_balance() for balance in balances: print(f"Currency: {balance.currency}") print(f" Total Cash: {balance.total_cash}") print(f" Net Assets: {balance.net_assets}") print(f" Buy Power: {balance.buy_power}") print(f" Margin Call: {balance.margin_call}") print(f" Risk Level: {balance.risk_level}") ``` -------------------------------- ### Get static security information Source: https://context7.com/longbridge/openapi/llms.txt Fetch static information for one or more securities, including lot size, exchange, and currency. Requires QuoteContext initialization. ```python from longbridge.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = QuoteContext(config) info_list = ctx.static_info(["700.HK", "AAPL.US"]) for info in info_list: print(f"Symbol: {info.symbol}") print(f" Name (EN): {info.name_en}") print(f" Exchange: {info.exchange}") print(f" Currency: {info.currency}") print(f" Lot Size: {info.lot_size}") print(f" Total Shares: {info.total_shares}") print(f" EPS: {info.eps}, BPS: {info.bps}") ``` -------------------------------- ### Get Basic Security Info with OAuth 2.0 Source: https://github.com/longbridge/openapi/blob/main/rust/README.md Use this snippet to fetch basic information for specified securities using OAuth 2.0 authentication. Ensure you have obtained a client ID and completed the authorization flow. ```rust use std::sync::Arc; use longbridge::{Config, QuoteContext, oauth::OAuthBuilder}; #[tokio::main] async fn main() -> Result<(), Box> { let oauth = OAuthBuilder::new("your-client-id") .build(|url| println!("Open this URL to authorize: {url}")) .await?; let config = Arc::new(Config::from_oauth(oauth)); // Create a context for quote APIs let (ctx, _) = QuoteContext::new(config); // Get basic information of securities let resp = ctx .quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) .await?; println!("{:?}", resp); Ok(()) } ``` -------------------------------- ### Get Basic Security Info with API Key Source: https://github.com/longbridge/openapi/blob/main/rust/README.md Fetch basic security information by loading configuration from environment variables using a legacy API key. Ensure LONGBRIDGE_API_KEY and LONGBRIDGE_SECRET_KEY are set. ```rust use std::sync::Arc; use longbridge::{Config, QuoteContext}; #[tokio::main] async fn main() -> Result<(), Box> { // Load configuration from environment variables let config = Arc::new(Config::from_apikey_env()?); // Create a context for quote APIs let (ctx, _) = QuoteContext::new(config.clone()); // Get basic information of securities let resp = ctx .quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]) .await?; println!("{:?}", resp); Ok(()) } ``` -------------------------------- ### Java QuoteContext - Get Quotes Source: https://context7.com/longbridge/openapi/llms.txt Get security quotes using the Java SDK. ```APIDOC ## Java QuoteContext Get security quotes using the Java SDK. ### Request Example ```java import com.longbridge.*; import com.longbridge.quote.*; class Main { public static void main(String[] args) throws Exception { try (OAuth oauth = new OAuthBuilder("your-client-id") .build(url -> System.out.println("Open this URL to authorize: " + url)) .get(); Config config = Config.fromOAuth(oauth); QuoteContext ctx = QuoteContext.create(config)) { SecurityQuote[] resp = ctx.getQuote( new String[] { "700.HK", "AAPL.US", "TSLA.US" }).get(); for (SecurityQuote quote : resp) { System.out.println(quote); } } } } ``` ``` -------------------------------- ### Configure SDK from API Key Environment Variables Source: https://github.com/longbridge/openapi/blob/main/python/docs/index.md Initialize the SDK configuration using API keys from environment variables. ```python from longbridge.openapi import Config config = Config.from_apikey_env() ``` -------------------------------- ### Build OAuth Client and Create Config Source: https://github.com/longbridge/openapi/blob/main/cpp/README.md This C++ code demonstrates how to build an OAuth client, handle authorization, and create a configuration object. It automatically loads cached tokens or initiates a browser-based authorization flow. The token is persisted for future use. ```c++ #include #include 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 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; } ``` -------------------------------- ### Initialize Config from Environment Variables (Python) Source: https://context7.com/longbridge/openapi/llms.txt Create configuration from environment variables for legacy API key authentication. Ensure all required environment variables are set before calling this function. ```python from longbridge.openapi import Config # Set environment variables first: # export LONGBRIDGE_APP_KEY="your-app-key" # export LONGBRIDGE_APP_SECRET="your-app-secret" # export LONGBRIDGE_ACCESS_TOKEN="your-access-token" config = Config.from_apikey_env() # Optional environment variables: # LONGBRIDGE_LANGUAGE - "zh-CN", "zh-HK", or "en" (default: "en") # LONGBRIDGE_HTTP_URL - HTTP endpoint (default: https://openapi.longbridge.com) # LONGBRIDGE_QUOTE_WS_URL - Quote WebSocket URL # LONGBRIDGE_TRADE_WS_URL - Trade WebSocket URL # LONGBRIDGE_ENABLE_OVERNIGHT - "true" or "false" (default: "false") # LONGBRIDGE_LOG_PATH - Log file directory ``` -------------------------------- ### Configuration from Environment Variables Source: https://github.com/longbridge/openapi/blob/main/python/README.md This snippet shows how to create a configuration object by loading API keys from environment variables. ```APIDOC ## Configuration from Environment Variables This section details the environment variables that can be used to configure the Longbridge OpenAPI client. These variables allow for customization of language, API endpoints, and other operational parameters. ### 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_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`) | ### Python Example ```python from longbridge.openapi import Config config = Config.from_apikey_env() ``` ``` -------------------------------- ### Build Node.js SDK Native Binary Source: https://github.com/longbridge/openapi/blob/main/AGENTS.md Run this command from the `nodejs/` directory to build the native `.node` binary for the Node.js SDK. The `index.d.ts` and `index.js` files are auto-generated and should not be edited manually. ```bash npm run build:debug ``` -------------------------------- ### QuoteContext.option_chain_expiry_date_list Source: https://context7.com/longbridge/openapi/llms.txt Get available expiry dates for options chains on a security. ```APIDOC ## QuoteContext.option_chain_expiry_date_list ### Description Get available expiry dates for options chains on a security. ### Method GET ### Endpoint /v1/quote/option_chain_expiry_date_list ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol of the underlying security. ### Request Example ```python from datetime import date from longbridge.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = QuoteContext(config) # Get expiry dates for AAPL options expiry_dates = ctx.option_chain_expiry_date_list("AAPL.US") print("Available expiry dates:") for d in expiry_dates: print(f" {d}") # Get strike prices for a specific expiry date if expiry_dates: strikes = ctx.option_chain_info_by_date("AAPL.US", expiry_dates[0]) for strike in strikes: print(f"Strike: {strike.price}, Call: {strike.call_symbol}, Put: {strike.put_symbol}") ``` ### Response #### Success Response (200) - **expiry_dates** (list of dates) - A list of available expiry dates for the options chain. #### Response Example ```json [ "2024-07-19", "2024-08-16", "2024-09-20" ] ``` ``` -------------------------------- ### QuoteContext.trading_days Source: https://context7.com/longbridge/openapi/llms.txt Get trading and half-day trading dates for a market within a date range. ```APIDOC ## QuoteContext.trading_days ### Description Get trading and half-day trading dates for a market within a date range. ### Method GET ### Endpoint /v1/quote/trading_days ### Parameters #### Query Parameters - **market** (string) - Required - The market identifier (e.g., "HK", "US", "SH", "SZ"). - **start_date** (date) - Required - The start date of the range. - **end_date** (date) - Required - The end date of the range. (Interval must be less than one month). ### Request Example ```python from datetime import date from longbridge.openapi import QuoteContext, Config, OAuthBuilder, Market oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = QuoteContext(config) # Get trading days for HK market (interval must be less than one month) trading_days = ctx.trading_days( Market.HK, date(2024, 1, 1), date(2024, 1, 31) ) print("Trading days:", trading_days.trading_days) print("Half trading days:", trading_days.half_trading_days) ``` ### Response #### Success Response (200) - **trading_days** (list of dates) - A list of full trading days. - **half_trading_days** (list of dates) - A list of half trading days. #### Response Example ```json { "trading_days": ["2024-01-02", "2024-01-03", ...], "half_trading_days": ["2024-01-01"] } ``` ``` -------------------------------- ### Configure C++ Project Build Source: https://github.com/longbridge/openapi/blob/main/examples/c/today_orders/CMakeLists.txt Sets up include directories, defines an executable, and links necessary libraries for the C++ project. Links ncurses on non-Windows systems. ```cmake include_directories(../../../c/csrc/include) add_executable(today_orders_c main.c) target_link_libraries(today_orders_c longbridge_c) if(NOT CMAKE_HOST_WIN32) target_link_libraries(today_orders_c ncurses) endif() ``` -------------------------------- ### QuoteContext.depth Source: https://context7.com/longbridge/openapi/llms.txt Get market depth (order book) showing bid and ask levels. ```APIDOC ## QuoteContext.depth ### Description Get market depth (order book) showing bid and ask levels. ### Method GET ### Endpoint /v1/quote/depth ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol of the security. ### Request Example ```python from longbridge.openapi import QuoteContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = QuoteContext(config) depth = ctx.depth("700.HK") print("Ask levels:") for ask in depth.asks: print(f" Position {ask.position}: Price={ask.price}, Volume={ask.volume}") print("Bid levels:") for bid in depth.bids: print(f" Position {bid.position}: Price={bid.price}, Volume={bid.volume}") ``` ### Response #### Success Response (200) - **asks** (list) - A list of ask levels. - **position** (integer) - The position in the order book. - **price** (float) - The price of the ask. - **volume** (float) - The volume at this price. - **bids** (list) - A list of bid levels. - **position** (integer) - The position in the order book. - **price** (float) - The price of the bid. - **volume** (float) - The volume at this price. #### Response Example ```json { "asks": [ {"position": 1, "price": 105.0, "volume": 500.0}, {"position": 2, "price": 105.1, "volume": 300.0} ], "bids": [ {"position": 1, "price": 104.9, "volume": 400.0}, {"position": 2, "price": 104.8, "volume": 600.0} ] } ``` ``` -------------------------------- ### Initialize Config with OAuth (Python) Source: https://context7.com/longbridge/openapi/llms.txt Create a configuration object from OAuth authentication for initializing API contexts. The token is cached and automatically refreshed. ```python from longbridge.openapi import OAuthBuilder, Config # Build OAuth client (opens browser for authorization if no cached token) oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) # Create config from OAuth config = Config.from_oauth(oauth) # Token is cached at ~/.longbridge/openapi/tokens/ # and automatically refreshed on subsequent requests ``` -------------------------------- ### Config.from_apikey_env (Python) Source: https://context7.com/longbridge/openapi/llms.txt Create configuration from environment variables for legacy API key authentication. Ensure all required environment variables are set before calling this function. ```APIDOC ## Config.from_apikey_env (Python) ### Description Create configuration from environment variables for legacy API key authentication. Ensure all required environment variables are set before calling this function. ### Method Python function call ### Endpoint N/A (Client-side configuration) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from longbridge.openapi import Config # Set environment variables first: # export LONGBRIDGE_APP_KEY="your-app-key" # export LONGBRIDGE_APP_SECRET="your-app-secret" # export LONGBRIDGE_ACCESS_TOKEN="your-access-token" config = Config.from_apikey_env() # Optional environment variables: # LONGBRIDGE_LANGUAGE - "zh-CN", "zh-HK", or "en" (default: "en") # LONGBRIDGE_HTTP_URL - HTTP endpoint (default: https://openapi.longbridge.com) # LONGBRIDGE_QUOTE_WS_URL - Quote WebSocket URL # LONGBRIDGE_TRADE_WS_URL - Trade WebSocket URL # LONGBRIDGE_ENABLE_OVERNIGHT - "true" or "false" (default: "false") # LONGBRIDGE_LOG_PATH - Log file directory ``` ### Response N/A (This is a configuration step, not an API call with a direct response.) ``` -------------------------------- ### Content API - Get News and Topics Source: https://github.com/longbridge/openapi/blob/main/python/docs/index.md Demonstrates how to retrieve news and discussion topics for a specific security. ```APIDOC ## Content API - Get News and Topics ### Description This endpoint allows you to fetch news articles and discussion topics related to a particular security. ### Method GET (Implicit via SDK methods) ### Endpoint N/A (SDK methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from longbridge.openapi import Config, ContentContext config = Config.from_apikey_env() # Create a context for content APIs ctx = ContentContext(config) # Get news for a security news = ctx.news("700.HK") print(news) # Get discussion topics for a security topics = ctx.topics("700.HK") print(topics) ``` ### Response #### Success Response (200) - **news** (list) - A list of news articles. - **topics** (list) - A list of discussion topics. #### Response Example ```json { "news": [ { "title": "Tencent reports strong earnings", "publish_time": "2023-10-26T10:00:00Z" } ], "topics": [ { "title": "Discussion on Tencent's future growth", "author": "AnalystX" } ] } ``` ``` -------------------------------- ### Python ContentContext - Topics and News Source: https://context7.com/longbridge/openapi/llms.txt Get discussion topics and news for securities from the community platform using the Python SDK. ```APIDOC ## ContentContext.topics (Python) Get discussion topics and news for securities from the community platform. ### Request Example ```python from longbridge.openapi import ContentContext, Config, OAuthBuilder oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) config = Config.from_oauth(oauth) ctx = ContentContext(config) # Get discussion topics for a symbol topics = ctx.topics("700.HK") for topic in topics: print(f"Topic: {topic.id} - {topic.title}") # Get news for a symbol news = ctx.news("700.HK") for item in news: print(f"News: {item.id} - {item.title}") ``` ``` -------------------------------- ### Authentication - Legacy API Key Source: https://github.com/longbridge/openapi/blob/main/python/docs/index.md Explains how to authenticate using legacy API keys via environment variables. ```APIDOC ## Authentication - Legacy API Key ### Description This section details how to authenticate using legacy API keys by setting environment variables. ### Method API Key ### Environment Variables _macOS/Linux_ ```bash 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" ``` _Windows_ ```powershell 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" ``` ### Request Example ```python from longbridge.openapi import Config config = Config.from_apikey_env() ``` ### Response Example ```json { "message": "Authentication successful" } ``` ``` -------------------------------- ### Quote API - Get Basic Information of Securities Source: https://github.com/longbridge/openapi/blob/main/nodejs/README.md Fetch basic information for a list of securities using the Quote API. ```APIDOC ## Quote API - Get Basic Information of Securities ### Description Retrieve basic information for a list of securities using the Quote API. This example demonstrates how to use the `QuoteContext` with an OAuth-configured `Config`. ### Method GET (Implicitly called by the SDK method) ### Endpoint (Internal SDK endpoint, not directly exposed) ### Parameters #### Query Parameters - **symbols** (array of strings) - Required - A list of security symbols (e.g., `"700.HK"`, `"AAPL.US"`). ### Request Example ```javascript const { OAuth, Config, QuoteContext } = require('longbridge'); async function main() { const oauth = await OAuth.build( "your-client-id", (_, url) => console.log("Open this URL to authorize: " + url) ); const config = Config.fromOAuth(oauth); const ctx = QuoteContext.new(config); const resp = await ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]); for (let obj of resp) { console.log(obj.toString()); } } main(); ``` ### Response #### Success Response (200) An array of objects, where each object contains quote information for a requested security. The exact fields depend on the security type and available data. #### Response Example (Output of `obj.toString()` will vary based on the security data) ``` -------------------------------- ### Environment Variables Reference Source: https://context7.com/longbridge/openapi/llms.txt Configure SDK behavior through environment variables. ```APIDOC ## Environment Variables Reference Configure SDK behavior through environment variables. ### Configuration ```bash # Required for API Key authentication export LONGBRIDGE_APP_KEY="your-app-key" export LONGBRIDGE_APP_SECRET="your-app-secret" export LONGBRIDGE_ACCESS_TOKEN="your-access-token" # Optional configuration export LONGBRIDGE_LANGUAGE="en" # "zh-CN", "zh-HK", or "en" export LONGBRIDGE_HTTP_URL="https://openapi.longbridge.com" export LONGBRIDGE_QUOTE_WS_URL="wss://openapi-quote.longbridge.com/v2" export LONGBRIDGE_TRADE_WS_URL="wss://openapi-trade.longbridge.com/v2" export LONGBRIDGE_ENABLE_OVERNIGHT="false" # Enable overnight quotes export LONGBRIDGE_PUSH_CANDLESTICK_MODE="realtime" # "realtime" or "confirmed" export LONGBRIDGE_PRINT_QUOTE_PACKAGES="true" # Print quote packages on connect export LONGBRIDGE_LOG_PATH="/path/to/logs" # Enable SDK logging ``` ``` -------------------------------- ### Config.from_oauth (Python) Source: https://context7.com/longbridge/openapi/llms.txt Create a configuration object from OAuth authentication for initializing API contexts. This method handles token caching and automatic refreshing. ```APIDOC ## Config.from_oauth (Python) ### Description Create a configuration object from OAuth authentication for initializing API contexts. This method handles token caching and automatic refreshing. ### Method Python function call ### Endpoint N/A (Client-side configuration) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from longbridge.openapi import OAuthBuilder, Config # Build OAuth client (opens browser for authorization if no cached token) oauth = OAuthBuilder("your-client-id").build( lambda url: print(f"Open this URL to authorize: {url}") ) # Create config from OAuth config = Config.from_oauth(oauth) # Token is cached at ~/.longbridge/openapi/tokens/ # and automatically refreshed on subsequent requests ``` ### Response N/A (This is a configuration step, not an API call with a direct response.) ```