### Install LongPort SDK for Go Source: https://open.longportapp.com/docs/getting-started.md Use this command to get the LongPort SDK for Go projects. ```shell go get github.com/longportapp/openapi-go ``` -------------------------------- ### Get Account Balance in JavaScript Source: https://open.longportapp.com/docs/getting-started.md This JavaScript example shows how to fetch account balance using environment variables for configuration. Alternatively, you can initialize the config directly. ```javascript const { Config, TradeContext } = require('longport') let config = Config.fromEnv() // Init config without ENV // let config = new Config({ appKey: "YOUR_APP_KEY", appSecret: "YOUR_APP_SECRET", accessToken: "YOUR_ACCESS_TOKEN" }) TradeContext.new(config) .then((ctx) => ctx.accountBalance()) .then((resp) => { for (let obj of resp) { console.log(obj.toString()) } }) ``` -------------------------------- ### Get Today's Orders in Go Source: https://open.longportapp.com/docs/getting-started.md Fetch today's orders using Go. This example initializes the trade context from environment variables and handles potential errors. ```go package main import ( "context" "fmt" "log" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/trade" ) func main() { // create trade context from environment variables conf, err := config.New() if err != nil { log.Fatal(err) } tradeContext, err := trade.NewFromCfg(conf) if err != nil { log.Fatal(err) } defer tradeContext.Close() ctx := context.Background() // today orders orders, err := tradeContext.TodayOrders(ctx, &trade.GetTodayOrders{}) if err != nil { log.Fatal(err) } for _, order := range orders { fmt.Printf("%+v\n", order) } } ``` ```shell go run ./ ``` -------------------------------- ### Python SDK Example for Security Capital Distribution Source: https://open.longportapp.com/docs/quote/pull/capital-distribution.md Example of how to get security capital distribution using the Python SDK. Ensure you have the correct quotes authority. ```python # Get Security Capital Distribution # https://open.longportapp.com/docs/quote/pull/capital-distribution # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. ``` -------------------------------- ### Get Account Balance in Java Source: https://open.longportapp.com/docs/getting-started.md This Java example retrieves account balance information. It supports configuration via environment variables or direct initialization. ```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); } } } } ``` -------------------------------- ### Subscribe to Quotes and Depth in Go Source: https://open.longportapp.com/docs/getting-started.md This Go example subscribes to both quote and depth data for specified symbols. It includes setup for handling signals and uses environment variables for configuration. ```go package main import ( "context" "encoding/json" "fmt" "log" "os" "os/signal" "syscall" "time" "github.com/longportapp/openapi-go/config" "github.com/longportapp/openapi-go/quote" ) func main() { // create quote context from environment variables conf, err := config.New() if err != nil { log.Fatal(err) } quoteContext, err := quote.NewFromCfg(conf) if err != nil { log.Fatal(err) return } defer quoteContext.Close() ctx := context.Background() quoteContext.OnQuote(func(pe *quote.PushQuote) { bytes, _ := json.Marshal(pe) fmt.Println(string(bytes)) }) quoteContext.OnDepth(func(d *quote.PushDepth) { bytes, _ := json.Marshal(d) if d.Sequence != 0 { fmt.Print(time.UnixMicro(d.Sequence/1000).Format(time.RFC3339) + " ") } fmt.Println(string(bytes)) }) // Subscribe some symbols err = quoteContext.Subscribe(ctx, []string{"700.HK", "AAPL.US", "NFLX.US"}, []quote.SubType{quote.SubTypeDepth}, true) if err != nil { log.Fatal(err) return } quitChannel := make(chan os.Signal, 1) signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM) <-quitChannel } ``` ```shell go run ./ ``` -------------------------------- ### cURL Example: Get Stock Positions Source: https://open.longportapp.com/docs/how-to-access-api.md Example of a GET request to retrieve stock positions. This demonstrates how to pass query parameters like 'symbol' in the URL. ```bash curl -v https://openapi.longportapp.com/v1/asset/stock?symbol=700.HK&symbol=BABA.US \ -H "X-Api-Signature: {Signature}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ``` -------------------------------- ### Install LongPort SDK for Python Source: https://open.longportapp.com/docs/getting-started.md Use this command to install the LongPort SDK for Python projects. ```bash pip3 install longport ``` -------------------------------- ### Install LongPort SDK for JavaScript Source: https://open.longportapp.com/docs/getting-started.md Use this command to install the LongPort SDK for JavaScript projects. ```bash yarn install longport ``` -------------------------------- ### Example Order Output Source: https://open.longportapp.com/docs/getting-started.md This is an example of the output format for a single order retrieved using the LongPort OpenAPI. ```text Order { order_id: "718437534753550336", status: NotReported, stock_name: "腾讯控股 1", quantity: 200, executed_quantity: None, price: Some(50.000), executed_price: None, submitted_at: 2022-06-06T12:14:16Z, side: Buy, symbol: "700.HK", order_type: LO, last_done: None, trigger_price: Some(0.000), msg: "", tag: Normal, time_in_force: Day, expire_date: Some(NaiveDate(Date { year: 2022, ordinal: 158 })), updated_at: Some(2022-06-06T12:14:16Z), trigger_at: None, trailing_amount: None, trailing_percent: None, limit_offset: None, trigger_status: None, currency: "HKD", outside_rth: nonce } ``` -------------------------------- ### Get OTP API Response Example Source: https://open.longportapp.com/docs/api-reference/socket/socket-otp-api This is an example of a successful response when requesting an OTP. The 'otp' field contains the token needed for subsequent connections. ```json { "code": 0, "message": "", "data": { "otp": "xxxxxxxx" } } } ``` -------------------------------- ### Response JSON Example Source: https://open.longportapp.com/docs/quote/pull/optionchain-date-strike.md Example JSON output for the Option Chain By Date API, showing strike price details for call and put options. ```json { "strike_price_info": [ { "price": "100", "call_symbol": "AAPL220429C100000.US", "put_symbol": "AAPL220429P100000.US", "standard": true }, { "price": "105", "call_symbol": "AAPL220429C105000.US", "put_symbol": "AAPL220429P105000.US", "standard": true }, { "price": "110", "call_symbol": "AAPL220429C110000.US", "put_symbol": "AAPL220429P110000.US", "standard": true }, { "price": "115", "call_symbol": "AAPL220429C115000.US", "put_symbol": "AAPL220429P115000.US", "standard": true } ] } ``` -------------------------------- ### Packet Header Binary Examples Source: https://open.longportapp.com/docs/api-reference/socket/protocol/how-to-parse-header Examples illustrating different combinations of packet header fields (type, verify, gzip, reserve) in binary format. ```plaintext // reserve - 0, gzip - 0, verify - 0, type - 1 0b 0000 0001 ``` ```plaintext // reserve - 0, gzip - 1, verify - 0, type - 2 0b 0011 0010 ``` ```plaintext // reserve - 0, gzip - 1, verify - 1, type - 3 0b 0001 0011 ``` ```plaintext // reserve - 3, gzip - 1, verify - 0, type - 3 0b 1110 0011 ``` -------------------------------- ### Subscription Response Example (JSON) Source: https://open.longportapp.com/docs/quote/subscribe/subsciption Provides an example of the subscription response in JSON format. It shows a list of subscribed symbols, each with an array of subscription types indicated by integer codes. ```json { "sub_list": [ { "symbol": "700.HK", "sub_type": [1, 2, 3] }, { "symbol": "AAPL.US", "sub_type": [2] } ] } ``` -------------------------------- ### Response JSON Example Source: https://open.longportapp.com/docs/quote/pull/trade-day.md Example JSON response showing trading days and half trading days for a given period. ```json { "trade_day": [ "20220120", "20220121", "20220124", "20220125", "20220126", "20220127", "20220128", "20220204", "20220207", "20220208", "20220209", "20220210" ], "half_trade_day": ["20220131"] } ``` -------------------------------- ### Response JSON Example Source: https://open.longportapp.com/docs/quote/pull/optionchain_date Example JSON response containing a list of option chain expiry dates in YYMMDD format. ```json { "expiry_date": [ "20220422", "20220429", "20220506", "20220513", "20220520", "20220527", "20220603", "20220617", "20220715", "20220819", "20220916", "20221021", "20221118", "20230120", "20230317", "20230616", "20230915", "20240119", "20240621" ] } ``` -------------------------------- ### cURL Example: Submit Order (POST) Source: https://open.longportapp.com/docs/how-to-access-api.md Example of a POST request to submit an order. This shows how to include a JSON request body and set the 'Content-Type' header. ```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: {Signature}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" \ -H "Content-Type: application/json; charset=utf-8" ``` -------------------------------- ### Order Detail Response Example Source: https://open.longportapp.com/docs/trade/order/order_detail.md This is an example of a successful response when querying order details. It includes information about the order's status, execution, and associated costs. ```json { "code": 0, "message": "success", "data": { "order_id": "828940451093708800", "status": "FilledStatus", "stock_name": "Apple", "quantity": "10", "executed_quantity": "10", "price": "200.000", "executed_price": "164.660", "submitted_at": "1680863604", "side": "Buy", "symbol": "AAPL.US", "order_type": "LO", "last_done": "164.660", "trigger_price": "0.0000", "msg": "", "tag": "Normal", "time_in_force": "Day", "expire_date": "2023-04-10", "updated_at": "1681113000", "trigger_at": "0", "trailing_amount": "", "trailing_percent": "", "limit_offset": "", "trigger_status": "NOT_USED", "outside_rth": "ANY_TIME", "currency": "USD", "remark": "1680863603.927165", "free_status": "None", "free_amount": "", "free_currency": "", "deductions_status": "NONE", "deductions_amount": "", "deductions_currency": "", "platform_deducted_status": "NONE", "platform_deducted_amount": "", "platform_deducted_currency": "", "history": [ { "price": "164.6600", "quantity": "10", "status": "FilledStatus", "msg": "Execution of 10", "time": "1681113000" }, { "price": "200.0000", "quantity": "10", "status": "NewStatus", "msg": "", "time": "1681113000" } ], "charge_detail": { "items": [ { "code": "BROKER_FEES", "name": "Broker Fees", "fees": [] }, { "code": "THIRD_FEES", "name": "Third-party Fees", "fees": [] } ], "total_amount": "0", "currency": "USD" } } } ``` -------------------------------- ### Today Executions Response Example Source: https://open.longportapp.com/docs/trade/execution/today_executions.md This is an example of the JSON response structure for a successful retrieval of today's executions. ```json { "code": 0, "message": "success", "data": { "trades": [ { "order_id": "693664675163312128", "price": "388", "quantity": "100", "symbol": "700.HK", "trade_done_at": "1648611351", "trade_id": "693664675163312128-1648611351433741210" } ] } } ``` -------------------------------- ### Response JSON Example Source: https://open.longportapp.com/docs/quote/pull/trade.md This is an example of a successful JSON response for a trade data request. ```json { "symbol": "AAPL.US", "trades": [ { "price": "158.760", "volume": 1, "timestamp": 1651103979, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.745", "volume": 1, "timestamp": 1651103985, "trade_type": "I", "direction": 0, "trade_session": 2 }, { "price": "158.800", "volume": 1, "timestamp": 1651103995, "trade_type": "I", "direction": 0, "trade_session": 2 } ] } ``` -------------------------------- ### Python Request Example for Security Calc Index Source: https://open.longportapp.com/docs/quote/pull/calc-index.md Example of how to request security calculation indexes using Python. Ensure you have the correct quotes authority before running. ```python # Get Security Calc Index # https://open.longportapp.com/docs/quote/pull/calc-index # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. ``` -------------------------------- ### Response JSON Example Source: https://open.longportapp.com/docs/quote/pull/broker-ids.md An example of the JSON response containing participant data, including broker IDs and names in different languages. ```json { "participant_broker_numbers": [ { "broker_ids": [7738, 7739], "participant_name_cn": "华兴金融 (香港)", "participant_name_en": "China Renaissance(HK)", "participant_name_hk": "華興金融 (香港)" }, { "broker_ids": [6390, 6396, 6398, 6399], "participant_name_cn": "国信 (香港)", "participant_name_en": "Guosen(HK)", "participant_name_hk": "國信 (香港)" }, { "broker_ids": [3168, 3169], "participant_name_cn": "泰嘉", "participant_name_en": "Tiger", "participant_name_hk": "泰嘉" } ] } ``` -------------------------------- ### Python Request Signing Example Source: https://open.longportapp.com/docs/how-to-access-api.md Example of how to sign a POST request and add the signature to the request headers. This snippet demonstrates setting up the request details and calling the `sign` function. ```python # request method method = "POST" # request path uri = "/v1/trade/order/submit" # request params, for example member_id=1&account_channel=2 params = "" # request body body = json.dumps({ "order_id": '683615454870679552' }) # signing requests and set signature it on the X-Api-Signature headers['X-Api-Signature'] = sign(method, uri, headers, params, body, secret) ``` -------------------------------- ### Market Temperature Response Example Source: https://open.longportapp.com/docs/quote/pull/history-market-temp This is an example of the JSON response structure for historical market temperature data. ```json { "code": 0, "data": { "type": "month" "list": [ { "timestamp": 1580486400, "temperature": 36, "valuation": 12, "sentiment": 46 }, { "timestamp": 1582992000, "temperature": 36, "valuation": 12, "sentiment": 46 } ] } } ``` -------------------------------- ### Response JSON Example for Trading Session Source: https://open.longportapp.com/docs/quote/pull/trade-session.md Example JSON response illustrating the daily trading hours for US, HK, CN, and SG markets, including specific session times. ```json { "market_trade_session": [ { "market": "US", "trade_session": [ { "beg_time": 930, "end_time": 1600 }, { "beg_time": 400, "end_time": 930, "trade_session": 1 }, { "beg_time": 1600, "end_time": 2000, "trade_session": 2 } ] }, { "market": "HK", "trade_session": [ { "beg_time": 930, "end_time": 1200 }, { "beg_time": 1300, "end_time": 1600 } ] }, { "market": "CN", "trade_session": [ { "beg_time": 930, "end_time": 1130 }, { "beg_time": 1300, "end_time": 1457 } ] }, { "market": "SG", "trade_session": [ { "beg_time": 900, "end_time": 1200 }, { "beg_time": 1300, "end_time": 1700 } ] } ] } ``` -------------------------------- ### Response Example for Estimate Max Purchase Quantity Source: https://open.longportapp.com/docs/trade/order/estimate_available_buy_limit.md This is an example of the JSON response received after successfully estimating the maximum purchase quantity. It includes cash and margin available quantities. ```json { "code": 0, "message": "success", "data": { "cash_max_qty": "100", "margin_max_qty": "100" } } ``` -------------------------------- ### Account Balance Response Example Source: https://open.longportapp.com/docs/trade/asset/account.md This is an example of the JSON response structure for account balance information, detailing various cash and transaction fee statuses per currency. ```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" } ] } ] } } ``` -------------------------------- ### Market Temperature Response Example Source: https://open.longportapp.com/docs/quote/pull/market-temp This is an example of the JSON response received when querying the market temperature. It includes the temperature, a descriptive text, valuation, sentiment, and the last update time. ```json { "code": 0, "data": { "temperature": 50, "description": "Temperature is moderate, maintaining stability", "valuation": 23, "sentiment": 78, "updated_at": 1744616612 } } ``` -------------------------------- ### Warrant Filter Request Example (Python) Source: https://open.longportapp.com/docs/quote/pull/warrant-filter.md Demonstrates how to fetch warrant quotes using the QuoteContext in Python. Ensure you have configured your API access, for example, using `Config.from_env()`. ```python from longport.openapi import QuoteContext, Config, WarrantSortBy, SortOrderType config = Config.from_env() ctx = QuoteContext(config) resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending) print(resp) ``` -------------------------------- ### Fund Position Response Example Source: https://open.longportapp.com/docs/trade/asset/fund.md Example JSON response structure for fund position data, including account channel and fund details like symbol, name, currency, and equity. ```json { "code": 0, "data": { "list": [ { "account_channel": "lb", "fund_info": [ { "symbol": "HK0000447943", "symbol_name": "GAOTENG EMERGING MARKETS PLUS LONG/SHORT FIXED INCOME ALPHA FUND", "currency": "USD", "holding_units": "5.000", "current_net_asset_value": "0", "cost_net_asset_value": "0.00", "net_asset_value_day": "1649865600" } ] } ] } } ``` -------------------------------- ### Get Today's Orders in Rust Source: https://open.longportapp.com/docs/getting-started.md Retrieve today's orders using Rust. This example requires the 'tokio' runtime and proper environment variable setup for the LongPort SDK. ```rust use std::sync::Arc; use longport::{trade::TradeContext, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Arc::new(Config::from_env()?); let (ctx, _) = TradeContext::try_new(config).await?; let resp = ctx.today_orders(None).await?; for obj in resp { println!("{:?}", obj); } Ok(()) } ``` ```bash cargo run ``` -------------------------------- ### Real-time Brokers Data JSON Example Source: https://open.longportapp.com/docs/quote/push/broker.md Illustrates the JSON structure for real-time broker data push, including ask and bid broker information with positions and broker IDs. ```json { "symbol": "700.HK", "sequence": 160808750000000, "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, "broker_ids": [7358, 9057, 9028, 7364] } ] } ``` -------------------------------- ### Get Security Candlesticks Python Example Source: https://open.longportapp.com/docs/quote/pull/candlestick.md Retrieves intraday or all candlestick data for a given security. Ensure you have the correct quotes authority. ```python # Get Security Candlesticks # https://open.longportapp.com/docs/quote/pull/candlestick # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config, Period, AdjustType, TradeSessions config = Config.from_env() ctx = QuoteContext(config) # Get intraday candlestick data for 700.HK resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust) print(resp) # Get all candlestick data for 700.HK resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, trade_session=TradeSessions.All) ``` -------------------------------- ### Subscribe to Quotes in JavaScript Source: https://open.longportapp.com/docs/getting-started.md This JavaScript example shows how to subscribe to real-time quote data. It requires setting up environment variables for configuration and uses a callback to process incoming quote events. ```javascript const { Config, QuoteContext, SubType } = require('longport') let config = Config.fromEnv() QuoteContext.new(config).then((ctx) => { ctx.setOnQuote((_, event) => console.log(event.toString())) ctx.subscribe(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US'], [SubType.Quote], true) }) ``` ```bash nodejs subscribe_quote.js ``` -------------------------------- ### Get History Executions in Python Source: https://open.longportapp.com/docs/trade/execution/history_executions.md Use this snippet to fetch historical trade executions. Ensure you have configured your API access via environment variables. The function accepts stock symbol, start time, and end time as parameters. ```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) ``` -------------------------------- ### Install LongPort MCP CLI (macOS/Linux) Source: https://open.longportapp.com/docs/llm.md Installs the LongPort MCP command-line interface directly in the terminal. Ensure you have the necessary LongPort credentials before installation. ```bash curl -sSL https://raw.githubusercontent.com/longportapp/openapi/refs/heads/main/mcp/install | bash ``` -------------------------------- ### Get Security Trades using Python SDK Source: https://open.longportapp.com/docs/quote/pull/trade.md Example of how to retrieve security trades using the LongPort Python SDK. Ensure you have the necessary quotes authority. Before running, please visit the "Developers to ensure that the account has the correct quotes authority. If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. ```python # Get Security Trades # https://open.longportapp.com/docs/quote/pull/trade # Before running, please visit the "Developers to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from longport.openapi import QuoteContext, Config config = Config.from_env() ctx = QuoteContext(config) resp = ctx.trades("700.HK", 10) print(resp) ``` -------------------------------- ### WebSocket Notification Example Source: https://open.longportapp.com/docs/trade/definition Example JSON payload for a WebSocket order update notification. ```APIDOC ### example JSON ```json { "event": "order_changed_lb", "data": { "side": "Buy", "stock_name": "Tencent Holdings Ltd.", "submitted_quantity": "1000", "symbol": "700.HK", "order_type": "LO", "submitted_price": "213.2", "executed_quantity": "1000", "executed_price": "213.2", "order_id": "27", "currency": "HKD", "status": "NewStatus", "submitted_at": "1562761893", "updated_at": "1562761893", "trigger_price": "213.0", "msg": "Insufficient Qty - 1000", "tag": "GTC", "trigger_status": "ACTIVE", "trigger_at": "1562761893", "trailing_amount": "5", "trailing_percent": "1", "limit_offset": "0.01", "account_no": "HK123445", "last_share": "100", "last_price": "234", "remark": "abc" } } ``` ``` -------------------------------- ### Initialize Longport TradeContext with Environment Variables (Python) Source: https://open.longportapp.com/docs/getting-started.md This Python snippet demonstrates initializing the `TradeContext` using configuration loaded from environment variables. Ensure the `longport` library is installed. ```python from longport.openapi import TradeContext, Config config = Config.from_env() # Init config without ENV ``` -------------------------------- ### Python API Call Setup Source: https://open.longportapp.com/docs/how-to-access-api.md This Python snippet sets up the necessary variables and headers for making an API call, including API keys, tokens, timestamps, and content type. It imports required libraries for hashing and time. ```python import requests import json import time import hashlib import hmac # request information # request method method = "POST" # request path uri = "/v1/trade/order/submit" # request params, for example member_id=1&account_channel=2 params = "" # request body body = json.dumps({ "order_id": '683615454870679552' }) # request headers headers = {} headers['X-Api-Key'] = '${app_key}' headers['Authorization'] = '${access_token}' headers['X-Timestamp'] = str(time.time()) # Unix TimeStamp, eg. 1539095200.123 headers['Content-Type'] = 'application/json; charset=utf-8' # App Secret app_secret = "${app_secret}" ``` -------------------------------- ### Warrant Issuer IDs Response Example (JSON) Source: https://open.longportapp.com/docs/quote/pull/issuer.md An example of the JSON response when requesting warrant issuer IDs. ```json { "issuer_info": [ { "id": 15, "name_cn": "瑞银", "name_en": "UB", "name_hk": "瑞銀" }, { "id": 14, "name_cn": "汇丰", "name_en": "HS", "name_hk": "滙豐" }, { "id": 12, "name_cn": "花旗", "name_en": "CT", "name_hk": "花旗" } ] } ``` -------------------------------- ### Initialize Trade Context in Python Source: https://open.longportapp.com/docs/trade/order/submit.md Loads configuration from environment variables and creates a TradeContext for interacting with trade APIs. Ensure your environment variables are set up correctly. ```python from decimal import Decimal from longport.openapi import TradeContext, Config, OrderType, OrderSide, TimeInForceType # Load configuration from environment variables config = Config.from_env() # Create a context for trade APIs ctx = TradeContext(config) ``` -------------------------------- ### Verify LongPort MCP Installation Source: https://open.longportapp.com/docs/llm.md Confirms that the LongPort MCP CLI has been successfully installed and is accessible in your system's PATH. ```bash longport-mcp -h ``` -------------------------------- ### Example JSON Response for Security Static Info Source: https://open.longportapp.com/docs/quote/pull/static.md Illustrates the JSON structure for a successful response containing security static information for multiple symbols. ```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" } ] } ``` -------------------------------- ### Cash Flow Response Example Source: https://open.longportapp.com/docs/trade/asset/cashflow.md This is an example of the JSON response structure for a successful cash flow request, showing transaction details. ```json { "code": 0, "data": { "list": [ { "transaction_flow_name": "BuyContract-Stocks", "direction": 1, "balance": "-248.60", "currency": "USD", "business_time": "1621507957", "symbol": "AAPL.US", "description": "AAPL" }, { "transaction_flow_name": "BuyContract-Stocks", "direction": 1, "balance": "-125.16", "currency": "USD", "business_time": "1621504824", "symbol": "AAPL.US", "description": "AAPL" } ] } } ``` -------------------------------- ### Subscribe to Real-time Brokers Data (Python) Source: https://open.longportapp.com/docs/quote/push/broker.md Example demonstrating how to subscribe to real-time broker data for specified symbols using the LongPort Python SDK. Ensure you have the correct quote authority configured in your account settings. ```python # Push Real-time Brokers # https://open.longportapp.com/docs/quote/push/push-brokers # To subscribe quotes data, please check whether "Developers" - "Quote authority" is correct. # https://open.longportapp.com/account # # - HK Market - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push. # - US Market - LV1 Nasdaq Basic (Only OpenAPI). # # Before running, please visit the "Developers" to ensure that the account has the correct quotes authority. # If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "LongPort" mobile app. from time import sleep from longport.openapi import QuoteContext, Config, SubType, PushBrokers def on_brokers(symbol: str, event: PushBrokers): print(symbol, event) config = Config.from_env() ctx = QuoteContext(config) ctx.set_on_brokers(on_brokers) ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Brokers]) sleep(30) ``` -------------------------------- ### cURL Example: Basic API Call Source: https://open.longportapp.com/docs/how-to-access-api.md A basic cURL command to test API connectivity. This example shows how to include essential headers like X-Api-Signature, X-Api-Key, Authorization, and X-Timestamp. ```bash curl -v https://openapi.longportapp.com/v1/test \ -H "X-Api-Signature: {signature}" -H "X-Api-Key: {AppKey}" \ -H "Authorization: {AccessToken}" -H "X-Timestamp: 1539095200.123" ```