### Bash: Example API Requests with cURL Source: https://open.longbridge.com/zh-CN/docs/how-to-access-api These code snippets provide examples of how to make API requests using the cURL command-line tool. They demonstrate GET and POST requests, including how to pass headers and parameters. ```bash curl -v https://openapi.longportapp.com/v1/test \ -H "X-Api-Signature: {签名}" -H "X-Api-Key: {Appkey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ``` ```bash curl -v https://openapi.longportapp.com/v1/asset/stock?symbol=700.HK&symbol=BABA.US \ -H "X-Api-Signature: {签名}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ``` ```bash curl -v -XPOST https://openapi.longportapp.com/v1/trade/order \ -d '{ "side": "Buy", symbol": "700.HK", "order_type": "LO", "submitted_price": "50", "submitted_quantity": "200", "time_in_force": "Day", remark": "Hello from Shell"}' \ -H "X-Api-Signature: {签名}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" \ -H "Content-Type: application/json; charset=utf-8" ``` -------------------------------- ### API Endpoints Examples Source: https://open.longbridge.com/zh-CN/docs/how-to-access-api Examples of how to call specific REST API endpoints using cURL. ```APIDOC ## API Endpoint Examples ### Test Endpoint ```bash curl -v https://openapi.longportapp.com/v1/test \ -H "X-Api-Signature: {签名}" -H "X-Api-Key: {Appkey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ``` ### Get Stock Holdings (GET) ```bash curl -v https://openapi.longportapp.com/v1/asset/stock?symbol=700.HK&symbol=BABA.US \ -H "X-Api-Signature: {签名}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ``` ### Submit Order (POST) ```bash curl -v -XPOST https://openapi.longportapp.com/v1/trade/order \ -d '{ "side": "Buy", "symbol": "700.HK", "order_type": "LO", "submitted_price": "50", "submitted_quantity": "200", "time_in_force": "Day", "remark": "Hello from Shell"}' \ -H "X-Api-Signature: {签名}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" \ -H "Content-Type: application/json; charset=utf-8" ``` ``` -------------------------------- ### Signature Generation (Python Example) Source: https://open.longbridge.com/zh-CN/docs/how-to-access-api A Python code example demonstrating how to generate the request signature. ```APIDOC ## Signature Generation Example (Python) ```python import time import hashlib import hmac import json def sign(method, uri, headers, params, body, secret): ts = headers["X-Timestamp"] access_token = headers["Authorization"] app_key = headers["X-Api-Key"] mtd = method.upper() # Construct canonical request string canonical_request = mtd + "|" + uri + "|" + params + "|authorization:" + access_token + "\nx-api-key:" + app_key + "\nx-timestamp:" + ts + "|authorization;x-api-key;x-timestamp|" if body != "": payload_hash = hashlib.sha1(body.encode("utf-8")).hexdigest() canonical_request = canonical_request + payload_hash sign_str = "HMAC-SHA256|" + hashlib.sha1(canonical_request.encode("utf-8")).hexdigest() signature = hmac.new(secret.encode('utf-8'), sign_str.encode('utf-8'), digestmod=hashlib.sha256).hexdigest() return "HMAC-SHA256 SignedHeaders=authorization;x-api-key;x-timestamp, Signature=" + signature # Example Usage: secret = "YOUR_APP_SECRET" headers = {} headers['X-Api-Key'] = 'YOUR_APP_KEY' headers['Authorization'] = 'YOUR_ACCESS_TOKEN' headers['X-Timestamp'] = str(time.time()) headers['Content-Type'] = 'application/json; charset=utf-8' method = "POST" uri = "/v1/trade/order/submit" params = "" body = json.dumps({ "order_id": '683615454870679552' }) headers['X-Api-Signature'] = sign(method, uri, headers, params, body, secret) print(headers) ``` ``` -------------------------------- ### Subscribe to Trade Push (JSON Example) Source: https://open.longbridge.com/zh-CN/docs/socket/subscribe_trade This example shows the JSON payload structure for subscribing to trade push notifications. The actual request should be serialized using protobuf. ```json { "topics": ["private"] } ``` -------------------------------- ### Python Example for Querying Security History Candlesticks Source: https://open.longbridge.com/zh-CN/docs/quote/pull/history-candlestick Provides Python code examples using the longport.openapi library to fetch historical candlestick data. It demonstrates how to query data by offset (before or after a specific date) and by date range. Ensure you have the necessary行情 (market data) permissions. ```python # 获取标的历史 K 线 # # 运行前请访问“开发者中心”确保账户有正确的行情权限。 # 如没有开通行情权限,可以通过“Longbridge”手机客户端,并进入“我的 - 我的行情 - 行情商城”购买开通行情权限。 from datetime import datetime, date from longport.openapi import QuoteContext, Config, Period, AdjustType config = Config.from_env() ctx = QuoteContext(config) # Query after 2023-01-01 resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, True, 10, datetime(2023, 1, 1)) print(resp) # Query before 2023-01-01 resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, False, 10, datetime(2023, 1, 1)) print(resp) # Query 2023-01-01 to 2023-02-01 resp = ctx.history_candlesticks_by_date("700.HK", Period.Day, AdjustType.NoAdjust, date(2023, 1, 1), date(2023, 2, 1)) print(resp) ``` -------------------------------- ### Example JSON Response for Security Static Info Source: https://open.longbridge.com/zh-CN/docs/quote/pull/static Illustrates the JSON structure for a successful response containing static security information. This example shows typical data for Tencent and Apple, including their names in Chinese and English, exchange, currency, lot size, share counts, and financial indicators. ```json { "secu_static_info": [ { "symbol": "700.HK", "name_cn": "腾讯控股", "name_en": "TENCENT", "name_hk": "騰訊控股", "exchange": "SEHK", "currency": "HKD", "lot_size": 100, "total_shares": 9612464038, "circulating_shares": 9612464038, "hk_shares": 9612464038, "eps": "28.4394", "eps_ttm": "28.4394", "bps": "103.40413", "dividend_yield": "1.6", "stock_derivatives": [2], "board": "HKEquity" }, { "symbol": "AAPL.US", "name_cn": "苹果", "name_en": "Apple Inc.", "exchange": "NASD", "currency": "USD", "lot_size": 1, "total_shares": 1631944100, "circulating_shares": 16302661350, "eps": "5.669", "eps_ttm": "6.0771", "bps": "4.40197", "dividend_yield": "0.85", "stock_derivatives": [1], "board": "USMain" } ] } ``` -------------------------------- ### JSON Example for Security Quote Response Source: https://open.longbridge.com/zh-CN/docs/quote/pull/quote Illustrates the structure of a JSON response containing security quote data, conforming to the defined Protobuf schema. It includes examples for multiple securities and demonstrates how pre-market and post-market data are nested. This format is useful for integrating with systems that consume JSON. ```json { "secu_quote": [ { "symbol": "700.HK", "last_done": "338.000", "prev_close": "334.800", "open": "340.600", "high": "340.600", "low": "333.000", "timestamp": 1651115955, "volume": 7310881, "turnover": "2461463161.000" }, { "symbol": "AAPL.US", "last_done": "156.570", "prev_close": "156.800", "open": "155.910", "high": "159.790", "low": "155.380", "timestamp": 1651089600, "volume": 88063191, "turnover": "13865092584.000", "pre_market_quote": { "last_done": "155.880", "timestamp": 1651066201, "volume": 1575504, "turnover": "246653442.000", "high": "158.400", "low": "155.100", "prev_close": "156.800" }, "post_market_quote": { "last_done": "158.770", "timestamp": 1651103995, "volume": 6188441, "turnover": "970874184.759", "high": "159.400", "low": "156.400", "prev_close": "156.570" } } ] } ``` -------------------------------- ### GET /v1/watchlist/groups - New Watchlist Groups Interface Source: https://open.longbridge.com/zh-CN/docs/changelog A new endpoint '/v1/watchlist/groups' has been added to fetch watchlist groups. ```APIDOC ## GET /v1/watchlist/groups ### Description Retrieves the user's watchlist groups. ### Method GET ### Endpoint /v1/watchlist/groups ### Response #### Success Response (200) - **groups** (array) - An array of watchlist group objects. #### Response Example { "example": "{\"groups\": []}" } ``` -------------------------------- ### GET /quote/brokers Source: https://open.longbridge.com/zh-CN/docs/quote/pull/brokers Fetches the real-time broker queue data for a given security symbol. ```APIDOC ## GET /quote/brokers ### Description This endpoint retrieves the real-time broker queue data for a specific security. ### Method GET ### Endpoint `/quote/brokers` ### Parameters #### Query Parameters - **symbol** (string) - Required - The security code in `ticker.region` format, e.g., `700.HK`. ### Request Example ```http GET /quote/brokers?symbol=700.HK ``` ### Response #### Success Response (200) - **symbol** (string) - The security code. - **ask_brokers** (object[]) - An array of ask broker queues. Each object contains: - **position** (int32) - The queue position. - **broker_ids** (int32[]) - An array of broker seat IDs. These IDs can be obtained from the 'Get Broker Seat IDs' interface. - **bid_brokers** (object[]) - An array of bid broker queues. Each object contains: - **position** (int32) - The queue position. - **broker_ids** (int32[]) - An array of broker seat IDs. These IDs can be obtained from the 'Get Broker Seat IDs' interface. #### Response Example ```json { "symbol": "700.HK", "ask_brokers": [ { "position": 1, "broker_ids": [7358, 9057, 9028, 7364] }, { "position": 2, "broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997] } ], "bid_brokers": [ { "position": 1, "broker_ids": [6996, 5465, 8026, 8304, 4978] }, { "position": 2 } ] } ``` ### Error Handling - **301600 (Invalid request)**: Indicates an error in request parameters or deserialization. - **301606 (Rate limit exceeded)**: Suggests reducing the request frequency. - **301602 (Server internal error)**: Points to a server-side issue; consider retrying or contacting support. - **301600 (Security does not exist)**: Occurs when the requested `symbol` is incorrect. - **301603 (Security has no market data)**: Indicates that the security does not have the requested market data. - **301604 (No permission)**: Signifies a lack of permission to access the security's market data. ``` -------------------------------- ### Supported Symbols and Format Source: https://open.longbridge.com/zh-CN/docs/qa/broker Details on the supported asset symbols, including their format and specific examples for different markets. ```APIDOC ## Supported Symbols and Format ### Symbol Format Asset codes use the format `ticker.region`, where `ticker` is the asset's code. ### Supported Assets and Regions | Market | Asset Type | Ticker | Region | |--------------|----------------------------------------------------------|------------------------------|------------| | Hong Kong | Securities (Stocks, ETFs, Warrants, Callable Bull/Bear Contracts, Retail Callable Warrants) | Official exchange code | HK | | | Hang Seng Index | HSI | HK | | | Hang Seng China Enterprises Index | HSCEI | HK | | | Hang Seng TECH Index | HSTECH | HK | | US Stocks | Securities (NYSE, AMEX, NASDAQ listed Stocks, ETFs) | Official exchange code | US | | | NASDAQ Composite Index | .IXIC | US | | | Dow Jones Industrial Average | .DJI | US | | A Shares | Securities (Stocks, ETFs) | Official exchange code | SH or SZ | | | Indices | Official exchange code | SH or SZ | Note: You can view asset symbols in the Longbridge App. ``` -------------------------------- ### GET /v1/trade/order - New Order Details Interface Source: https://open.longbridge.com/zh-CN/docs/changelog A new endpoint '/v1/trade/order' has been added to retrieve detailed information about orders. ```APIDOC ## GET /v1/trade/order ### Description Retrieves detailed information for a specific order. ### Method GET ### Endpoint /v1/trade/order ### Parameters #### Query Parameters - **order_id** (string) - Required - The unique identifier of the order. ### Response #### Success Response (200) - **order_details** (object) - An object containing the detailed information of the order. #### Response Example { "example": "{\"order_details\": {}}" } ``` -------------------------------- ### GET /v1/risk/margin-ratio - New Margin Ratio Interface Source: https://open.longbridge.com/zh-CN/docs/changelog A new endpoint '/v1/risk/margin-ratio' is available to retrieve margin ratio information. ```APIDOC ## GET /v1/risk/margin-ratio ### Description Retrieves the margin ratio information. ### Method GET ### Endpoint /v1/risk/margin-ratio ### Response #### Success Response (200) - **margin_ratio_details** (object) - An object containing the margin ratio details. #### Response Example { "example": "{\"margin_ratio_details\": {}}" } ``` -------------------------------- ### GET /v1/trade/execution/history Source: https://open.longbridge.com/zh-CN/docs/trade/execution/history_executions Retrieves historical trade details for past orders. This endpoint supports filtering by stock symbol, start time, and end time. It does not support querying for same-day trade details. ```APIDOC ## GET /v1/trade/execution/history ### Description This endpoint retrieves historical trade details for past orders, including both buy and sell transactions. It does not support querying for same-day trade details. ### Method GET ### Endpoint /v1/trade/execution/history ### Parameters #### Query Parameters - **symbol** (string) - Optional - Stock code, in the format `ticker.region`, e.g., `AAPL.US`. - **start_at** (string) - Optional - Start time, in Unix timestamp (seconds) format, e.g., `1650410999`. If the start time is empty, it defaults to ninety days before the end time or current time. - **end_at** (string) - Optional - End time, in Unix timestamp (seconds) format, e.g., `1650410999`. If the end time is empty, it defaults to ninety days after the start time or current time. ### Request Example ```python from datetime import datetime from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) resp = ctx.history_executions( symbol = "700.HK", start_at = datetime(2022, 5, 9), end_at = datetime(2022, 5, 12), ) print(resp) ``` ### Response #### Success Response (200) - **has_more** (boolean) - Indicates if there is more data. The maximum number of orders per query is 1000; if the query result exceeds 1000, `has_more` will be true. - **trades** (object[]) - Trade detail information. - **order_id** (string) - Order ID. - **trade_id** (string) - Trade ID. - **symbol** (string) - Stock code, in the format `ticker.region`, e.g., `AAPL.US`. - **trade_done_at** (string) - Trade time, in Unix timestamp (seconds) format. - **quantity** (string) - Trade quantity. - **price** (string) - Trade price. #### Response Example ```json { "code": 0, "message": "success", "data": { "has_more": false, "trades": [ { "order_id": "693664675163312128", "price": "388", "quantity": "100", "symbol": "700.HK", "trade_done_at": "1648611351", "trade_id": "693664675163312128-1648611351433741210" } ] } } ``` ``` -------------------------------- ### GET /quote/trade-day Source: https://open.longbridge.com/zh-CN/docs/quote/pull/trade-day Fetches market trading days based on the provided market, start date, and end date. Supports US, HK, CN, and SG markets. Date range is limited to one month and within the last year. ```APIDOC ## GET /quote/trade-day ### Description Fetches market trading days based on the provided market, start date, and end date. Supports US, HK, CN, and SG markets. Date range is limited to one month and within the last year. ### Method GET ### Endpoint /quote/trade-day ### Parameters #### Query Parameters - **market** (string) - Required - Market. Optional values: `US`, `HK`, `CN`, `SG`. - **beg_day** (string) - Required - Start date in `YYMMDD` format (e.g., `20220401`). - **end_day** (string) - Required - End date in `YYMMDD` format (e.g., `20220420`). The interval between start and end dates cannot exceed one month. Only data within the last year can be queried. ### Request Example ```json { "market": "HK", "beg_day": "20220101", "end_day": "20220201" } ``` ### Response #### Success Response (200) - **trade_day** (string[]) - Trading days in `YYMMDD` format. - **half_trade_day** (string[]) - Half trading days in `YYMMDD` format. #### Response Example ```json { "trade_day": [ "20220120", "20220121", "20220124", "20220125", "20220126", "20220127", "20220128", "20220204", "20220207", "20220208", "20220209", "20220210" ], "half_trade_day": ["20220131"] } ``` ### Error Handling - **301600**: Invalid request. Request parameters are incorrect or unpacking failed. - **301606**: Rate limiting. Please reduce request frequency. - **301602**: Server internal error. Please retry or contact technical support. - **301600**: Illegally requested data. Check if the requested market and dates are within the correct range. ``` -------------------------------- ### Get Account Balance in Java Source: https://open.longbridge.com/zh-CN/docs/getting-started Retrieves account balance details using the Longbridge OpenAPI in Java. This example uses the 'com.longport' library. It demonstrates initializing the configuration, creating a trade context, and iterating through the returned account balances. ```java import com.longport.*; import com.longport.trade.*; class Main { public static void main(String[] args) throws Exception { Config config = Config.fromEnv(); // Init config without ENV // https://longportapp.github.io/openapi/java/com/longport/ConfigBuilder.html // Config config = ConfigBuilder("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN").build(); try (TradeContext ctx = TradeContext.create(config).get()) { for (AccountBalance obj : ctx.getAccountBalance().get()) { System.out.println(obj); } } } } ``` -------------------------------- ### Security Calculation Response Example (JSON) Source: https://open.longbridge.com/zh-CN/docs/quote/pull/calc-index This JSON object demonstrates the structure of a successful response for security calculations. It includes various financial metrics for different security types such as stocks and options. No specific dependencies are mentioned, and the output format is JSON. ```json { "securityCalcIndex": [ { "symbol": "AAPL.US", "lastDone": "131.880", "changeVal": "-5.2500", "changeRate": "-3.83", "volume": "122207099", "turnover": "16269088361.000", "ytdChangeRate": "-25.63", "turnoverRate": "0.76", "totalMarketValue": "2134501670280.00", "capitalFlow": "14664053535.556", "amplitude": "2.74", "volumeRatio": "3.22", "peTtmRatio": "21.26", "pbRatio": "31.71", "dividendRatioTtm": "0.64", "fiveDayChangeRate": "-9.76", "tenDayChangeRate": "-11.87", "halfYearChangeRate": "-7.01", "fiveMinutesChangeRate": "0.00" }, { "symbol": "69672.HK", "lastDone": "0.010", "changeRate": "0.00", "expiryDate": "20221024", "strikePrice": "379.880", "outstandingQty": "6090000", "outstandingRatio": "7.61", "premium": "0.67", "itmOtm": "0.65", "callPrice": "375.880", "toCallPrice": "-100.00", "leverageRatio": "75.48", "balancePoint": "374.880" }, { "symbol": "AAPL220617C137000.US", "lastDone": "1.17", "changeVal": "-2.04", "changeRate": "-63.55", "volume": "23499", "turnover": "3903660.00", "expiryDate": "20220617", "strikePrice": "137.00", "premium": "11709.40", "impliedVolatility": "43.54", "openInterest": "5210", "delta": "0.263", "gamma": "0.043", "theta": "-1.266", "vega": "5.660", "rho": "0.580" }, { "symbol": "HSI.HK", "lastDone": "21119.650", "changeVal": "52.070", "changeRate": "0.25", "volume": "96449546281", "turnover": "96449546281.000", "ytdChangeRate": "-9.74", "amplitude": "1.86", "volumeRatio": "0.59", "fiveDayChangeRate": "-1.91", "tenDayChangeRate": "-0.02", "halfYearChangeRate": "-11.83", "fiveMinutesChangeRate": "0.00" } ] } ``` -------------------------------- ### Protobuf: CalcIndex - 计算指标枚举 Source: https://open.longbridge.com/zh-CN/docs/quote/objects 定义了用于计算的指标的Protobuf枚举。涵盖了最新价、涨跌幅、成交量、市值、波动率等多种技术指标和衍生品相关指标。部分指标仅适用于特定标的类型。 ```protobuf enum CalcIndex { CALCINDEX_UNKNOWN = 0; CALCINDEX_LAST_DONE = 1; CALCINDEX_CHANGE_VAL = 2; CALCINDEX_CHANGE_RATE = 3; CALCINDEX_VOLUME = 4; CALCINDEX_TURNOVER = 5; CALCINDEX_YTD_CHANGE_RATE = 6; CALCINDEX_TURNOVER_RATE = 7; CALCINDEX_TOTAL_MARKET_VALUE = 8; CALCINDEX_CAPITAL_FLOW = 9; CALCINDEX_AMPLITUDE = 10; CALCINDEX_VOLUME_RATIO = 11; CALCINDEX_PE_TTM_RATIO = 12; CALCINDEX_PB_RATIO = 13; CALCINDEX_DIVIDEND_RATIO_TTM = 14; CALCINDEX_FIVE_DAY_CHANGE_RATE = 15; CALCINDEX_TEN_DAY_CHANGE_RATE = 16; CALCINDEX_HALF_YEAR_CHANGE_RATE = 17; CALCINDEX_FIVE_MINUTES_CHANGE_RATE = 18; CALCINDEX_EXPIRY_DATE = 19; CALCINDEX_STRIKE_PRICE = 20; CALCINDEX_UPPER_STRIKE_PRICE = 21; CALCINDEX_LOWER_STRIKE_PRICE = 22; CALCINDEX_OUTSTANDING_QTY = 23; CALCINDEX_OUTSTANDING_RATIO = 24; CALCINDEX_PREMIUM = 25; CALCINDEX_ITM_OTM = 26; CALCINDEX_IMPLIED_VOLATILITY = 27; CALCINDEX_WARRANT_DELTA = 28; CALCINDEX_CALL_PRICE = 29; CALCINDEX_TO_CALL_PRICE = 30; CALCINDEX_EFFECTIVE_LEVERAGE = 31; CALCINDEX_LEVERAGE_RATIO = 32; CALCINDEX_CONVERSION_RATIO = 33; CALCINDEX_BALANCE_POINT = 34; CALCINDEX_OPEN_INTEREST = 35; CALCINDEX_DELTA = 36; CALCINDEX_GAMMA = 37; CALCINDEX_THETA = 38; CALCINDEX_VEGA = 39; CALCINDEX_RHO = 40; } ``` -------------------------------- ### Response Example for Security List Source: https://open.longbridge.com/zh-CN/docs/quote/security/security_list This JSON structure represents a successful response when requesting a security list. It includes a 'code' indicating success and a 'data' object containing a 'list' of securities. Each security object provides its symbol and names in Chinese, Traditional Chinese, and English. ```json { "code": 0, "data": { "list": [ { "symbol": "BAC.US", "name_cn": "美国银行", "name_hk": "美國銀行", "name_en": "Bank of America" }, { "symbol": "RDDT.US", "name_cn": "REDDIT INC", "name_hk": "REDDIT INC", "name_en": "REDDIT INC" }, { "symbol": "GOOGL.US", "name_cn": "谷歌-A", "name_hk": "谷歌-A", "name_en": "Alphabet" } ] } } ``` -------------------------------- ### Python SDK Configuration for Overnight Quotes Source: https://open.longbridge.com/zh-CN/docs/qa/broker Demonstrates how to configure the OpenAPI SDK in Python to enable overnight quotes, either via environment variables or directly in the Config constructor. ```python # Set environment variable LONGPORT_ENABLE_OVERNIGHT to "true" # config = Config.from_env() ``` ```python config = Config(app_key="your_app_key", app_secret="your_app_secret", access_token="your_access_token", enable_overnight=True) ``` -------------------------------- ### Protobuf: SubType - 订阅数据类型枚举 Source: https://open.longbridge.com/zh-CN/docs/quote/objects 定义了订阅数据类型的Protobuf枚举。包括价格、买卖盘口、经纪队列和逐笔明细。此枚举用于指定需要订阅的市场数据种类。 ```protobuf enum SubType { UNKNOWN_TYPE = 0; QUOTE = 1; DEPTH = 2; BROKERS = 3; TRADE = 4; } ``` -------------------------------- ### Get Security List using HTTP Request Source: https://open.longbridge.com/zh-CN/docs/quote/security/security_list This illustrates how to fetch a security list via an HTTP GET request to the `/v1/quote/get_security_list` endpoint. The request requires 'market' and 'category' query parameters. The response is a JSON object containing a list of securities, each with a symbol and localized names. ```http GET /v1/quote/get_security_list?market=US&category=Overnight HTTP/1.1 Host: api.longportapp.com Content-Type: application/json; charset=utf-8 ``` -------------------------------- ### Protobuf: AdjustType - K线复权类型枚举 Source: https://open.longbridge.com/zh-CN/docs/quote/objects 定义了K线复权类型的Protobuf枚举。包括不复权(除权)和前复权。此枚举用于指定K线数据是否需要进行价格调整。 ```protobuf enum AdjustType { NO_ADJUST = 0; FORWARD_ADJUST = 1; } ``` -------------------------------- ### GET /v1/asset/account Source: https://open.longbridge.com/zh-CN/docs/trade/asset/account Fetches the user's account funds, providing a breakdown of available, withdrawable, frozen, and settling amounts for each currency. ```APIDOC ## GET /v1/asset/account ### Description This endpoint retrieves the user's account funds, providing a breakdown of available, withdrawable, frozen, and settling amounts for each currency, including funds in transit. ### Method GET ### Endpoint /v1/asset/account ### Parameters #### Query Parameters - **currency** (string) - Optional - The currency code (e.g., HKD, USD, CNH). ### Request Example ```json { "currency": "HKD" } ``` ### Response #### Success Response (200) - **code** (integer) - Response code. - **data** (object) - Response data. - **list** (array) - List of account fund details per currency. - **total_cash** (string) - Total cash balance. - **max_finance_amount** (string) - Maximum financing amount. - **remaining_finance_amount** (string) - Remaining financing amount. - **risk_level** (string) - Risk level. - **margin_call** (string) - Margin call amount. - **currency** (string) - Currency code. - **net_assets** (string) - Net assets. - **init_margin** (string) - Initial margin. - **maintenance_margin** (string) - Maintenance margin. - **buy_power** (string) - Buying power. - **cash_infos** (array) - Details of cash information per currency. - **withdraw_cash** (string) - Withdrawable cash. - **available_cash** (string) - Available cash. - **frozen_cash** (string) - Frozen cash. - **settling_cash** (string) - Settling cash. - **currency** (string) - Currency code. - **frozen_transaction_fees** (array) - Frozen transaction fees. - **currency** (string) - Currency code. - **frozen_transaction_fee** (string) - Frozen transaction fee amount. #### Response Example ```json { "code": 0, "data": { "list": [ { "total_cash": "1759070010.72", "max_finance_amount": "977582000", "remaining_finance_amount": "0", "risk_level": "1", "margin_call": "2598051051.50", "currency": "HKD", "net_assets": "24145.90", "init_margin": "1540.09", "maintenance_margin": "1540.09", "buy_power": "1759070.12", "cash_infos": [ { "withdraw_cash": "97592.30", "available_cash": "195902464.37", "frozen_cash": "11579339.13", "settling_cash": "207288537.81", "currency": "HKD" }, { "withdraw_cash": "199893416.74", "available_cash": "199893416.74", "frozen_cash": "28723.76", "settling_cash": "-276806.51", "currency": "USD" } ], "frozen_transaction_fees": [ { "currency": "USD", "frozen_transaction_fee": "6.51" } ] } ] } } ``` #### Error Responses - **400**: Internal Server Error. ``` -------------------------------- ### GET /v1/quote/get_security_list Source: https://open.longbridge.com/zh-CN/docs/quote/security/security_list Retrieves a list of securities for a specified market and category. This endpoint is useful for obtaining trading symbols, their Chinese, Traditional Chinese, and English names. ```APIDOC ## GET /v1/quote/get_security_list ### Description Retrieves a list of securities for a specified market and category. This endpoint is useful for obtaining trading symbols, their Chinese, Traditional Chinese, and English names. ### Method GET ### Endpoint /v1/quote/get_security_list ### Parameters #### Query Parameters - **market** (string) - Required - The market for which to fetch securities. Currently only 'US' is supported. - **category** (string) - Required - The category within the market. Currently only 'Overnight' is supported. ### Request Example ```python # Example using Python SDK (replace with actual SDK usage) from longport.openapi import QuoteContext, Config, Market, SecurityListCategory config = Config.from_env() ctx = QuoteContext(config) resp = ctx.security_list(Market.US, SecurityListCategory.Overnight) print(resp) ``` ### Response #### Success Response (200) - **code** (integer) - Response code, 0 for success. - **data** (object) - Contains the list of securities. - **list** (object[]) - An array of security objects. - **symbol** (string) - Required - The security's symbol. - **name_cn** (string) - Required - The security's name in Chinese. - **name_hk** (string) - Required - The security's name in Traditional Chinese. - **name_en** (string) - Required - The security's name in English. #### Response Example ```json { "code": 0, "data": { "list": [ { "symbol": "BAC.US", "name_cn": "美国银行", "name_hk": "美國銀行", "name_en": "Bank of America" }, { "symbol": "RDDT.US", "name_cn": "REDDIT INC", "name_hk": "REDDIT INC", "name_en": "REDDIT INC" }, { "symbol": "GOOGL.US", "name_cn": "谷歌-A", "name_hk": "谷歌-A", "name_en": "Alphabet" } ] } } ``` #### Error Responses - **400** - Bad Request: Indicates an issue with the provided parameters. ``` -------------------------------- ### Protobuf: TradeSession - 交易时段枚举 Source: https://open.longbridge.com/zh-CN/docs/quote/objects 定义了交易时段的Protobuf枚举。包括盘中交易、盘前交易、盘后交易和夜盘交易。此枚举用于区分不同交易时段的数据。 ```protobuf enum TradeSession { NORMAL_TRADE = 0; PRE_TRADE = 1; POST_TRADE = 2; NIGHT_TRADE = 3; } ``` -------------------------------- ### Install Longbridge MCP CLI (macOS/Linux) Source: https://open.longbridge.com/zh-CN/docs/llm Installs the Longbridge MCP command-line interface tool on macOS or Linux systems using a curl script. This tool is essential for integrating with the MCP protocol. ```bash curl -sSL https://raw.githubusercontent.com/longportapp/openapi/refs/heads/main/mcp/install | bash ``` -------------------------------- ### GET /v1/asset/fund Source: https://open.longbridge.com/zh-CN/docs/trade/asset/fund Retrieves a list of fund holdings associated with the authenticated account. The response includes details such as account channel, fund symbol, holding units, cost, and net asset value. ```APIDOC ## GET /v1/asset/fund ### Description Retrieves a list of fund holdings associated with the authenticated account. The response includes details such as account channel, fund symbol, holding units, cost, and net asset value. ### Method GET ### Endpoint /v1/asset/fund ### Parameters #### Query Parameters - **symbol** (string[]) - Optional - Fund code in ISIN format, e.g., `HK0000676327`. See [ISIN explanation](https://en.wikipedia.org/wiki/International_Securities_Identification_Number). ### Request Example ```python # Get fund positions # https://open.longbridge.com/docs/trade/asset/fund from longport.openapi import TradeContext, Config config = Config.from_env() ctx = TradeContext(config) resp = ctx.fund_positions() print(resp) ``` ### Response #### Success Response (200) - **code** (integer) - Response code. - **data** (object) - Response data. - **list** (object[]) - Fund holding information. - **account_channel** (string) - Account type. - **fund_info** (object[]) - Fund details. - **symbol** (string) - Fund ISIN code. - **symbol_name** (string) - Fund name. - **currency** (string) - Currency. - **holding_units** (string) - Holding units. - **cost_net_asset_value** (string) - Cost net asset value. - **current_net_asset_value** (string) - Current net asset value. - **net_asset_value_day** (string) - Current net asset value timestamp. #### Response Example ```json { "code": 0, "data": { "list": [ { "account_channel": "lb", "fund_info": [ { "symbol": "HK0000447943", "symbol_name": "高腾亚洲收益基金", "currency": "USD", "holding_units": "5.000", "current_net_asset_value": "0", "cost_net_asset_value": "0.00", "net_asset_value_day": "1649865600" } ] } ] } } ``` #### Error Response (400) - **code** (integer) - Error code. - **message** (string) - Error message. ``` -------------------------------- ### Enabling Overnight Market Data Source: https://open.longbridge.com/zh-CN/docs/qa/broker Instructions on how to enable and receive overnight market data through the OpenAPI. ```APIDOC ## Enabling Overnight Market Data ### Enabling Overnight Market Data via Authentication To enable overnight market data, you need to actively activate it. This is done by including the key `need_over_night_quote` with the value `true` in the `metadata` field of the authentication interface. ```protobuf message AuthRequest { string token = 1; map metadata = 2; } message ReconnectRequest { string session_id = 1; map metadata = 2; } ``` Once overnight market data is enabled, both pull and push interfaces will provide overnight market data during the relevant trading hours. ### Enabling Overnight Market Data in OpenAPI SDK (Python Example) **Option 1: From environment variables** Set the environment variable `LONGPORT_ENABLE_OVERNIGHT` to `true`. **Option 2: From the constructor** ```python config = Config(app_key="your_app_key", app_secret="your_app_secret", access_token="your_access_token", enable_overnight=True) ``` ```