This is an unofficial SDK, currently for personal use only. Some functions in the Trade module have not been tested yet. Issues are welcome.
See NEWS.md for detailed release notes.
Latest release: v0.17.0 — sync with upstream openapi v5.6.0.
- Adds nine read-only
AssetContextmethods for AP accounts: bank cards, eDDA, stock transfers, rewards, coupons, deposits and withdrawals. CashInfo.redemption_cashexposes redeemable cash.business_segmentsincludes regional revenue, fiscal-period fields and segment values, IDs and year-on-year changes.- Grid and multi-leg order requests send zero-padded HK symbols in canonical form (
00700.HK→700.HK). Other markets are unchanged. finance_calendardocuments how to recover truncated date groups.fundsaccepts Julia values or raw JSON forfilterand rejects invalid JSON before sending a request.
References:
using Pkg
Pkg.add(url="https://github.com/rzhli/LongBridge.jl")LongBridge supports two authentication methods:
OAuth 2.0 uses Bearer tokens without requiring HMAC signatures. Tokens are persisted locally and refreshed automatically.
Step 1: Register an OAuth client
curl -X POST https://openapi.longbridgeapp.com/oauth2/register \
-H "Content-Type: application/json" \
-d '{
"client_name": "My Application",
"redirect_uris": ["http://localhost:60355/callback"],
"grant_types": ["authorization_code", "refresh_token"]
}'Step 2: Build OAuth handle and create config
using LongBridge
oauth = OAuthBuilder("your-client-id") |> build(url -> run(`xdg-open $url`))
cfg = Config.from_oauth(oauth)On first run, this opens the browser for authorization. Subsequent runs use the cached token automatically.
Browser authorization uses PKCE (S256), including for dynamically registered public clients. The authorization-code exchange has a 10-second connect timeout and a 35-second total timeout; refresh and revocation requests are bounded to 30 seconds. Token requests do not follow redirects or retry automatically.
To disconnect the OAuth application completely:
revoke!(oauth) # Revoke on the server; keep the local token.
clear!(oauth) # Delete the cached file, then clear the in-memory token.revoke! prefers the refresh token, falling back to the access token. clear! only
acts locally; a missing cache file is harmless, and a deletion failure keeps the
in-memory token. These operations share the token lock with refresh. Token storage
remains $LONGBRIDGE_TOKEN_DIR/<client_id> when set, otherwise
~/.longbridge/tokens/<client_id>. Existing Contexts retain the same OAuth handle;
use close(ctx) to stop their background tasks and WebSocket connections.
The local callback server only acts on the redirect that carries the pending
authorization's state. Any other request to it, including an error redirect, is
answered with an error page and ignored, and the flow keeps waiting, up to 5 minutes.
When the server reports an error, the exception and the callback page include its
error_description, for example
OAuth authorization failed: internal_server_error: validate client err:oauth client not found
for an unknown or placeholder client ID. In that text, control and invisible
characters are replaced with spaces, each field is capped at 512 characters, and the
page HTML-escapes it.
OAuth failures, including failure to obtain a token for an API request, now throw
OAuthError instead of LongBridgeError(401, ...) or a raw HTTP exception. Use
err.code and OAuthErrorCode instead of parsing messages; err.cause retains
underlying transport or storage errors. For example:
try
revoke!(oauth)
clear!(oauth)
catch err
if err isa OAuthError
@warn "OAuth operation failed" code=err.code exception=err
else
rethrow()
end
end| Code | OAuthErrorCode |
|---|---|
| 0 | Other |
| 1 / 2 | NoTokenAvailable / NoRefreshToken |
| 3 / 4 | RefreshTokenFailed / RevokeFailed |
| 5 / 6 / 7 | AuthorizationFailed / AuthorizationTimeout / ExchangeCodeFailed |
| 8 / 9 / 10 / 11 | CsrfTokenMismatch / BindCallbackFailed / LocalAddressFailed / CallbackChannelClosed |
| 12 | NoHomeDir |
| 13 / 14 / 15 / 16 | TokenFileRead / TokenFileParse / TokenFileWrite / TokenFileDelete |
| 17 / 18 | CreateDirFailed / SerializeToken |
The codes match upstream v5.5.0. For example, compare
err.code == Int(OAuthErrorCode.RevokeFailed). CsrfTokenMismatch (8) is kept for
compatibility but no longer raised: a callback with a mismatched state is ignored,
so the flow ends with AuthorizationTimeout (6) if no valid redirect follows.
Cached-token load failures are still logged and ignored so that build can start a
new authorization flow.
Create a config.toml file:
# Required
app_key = "your_app_key"
app_secret = "your_app_secret"
access_token = "your_access_token"
token_expire_time = "2025-07-22T00:00:00" # ISO8601 format, UTC time
# Optional (uses China endpoints by default)
# http_url = "https://openapi.longportapp.com"
# quote_ws_url = "wss://openapi-quote.longportapp.com"
# trade_ws_url = "wss://openapi-trade.longportapp.com"
# enable_papertrading = false
# quote_transport = "http" # optional; "ws" by default, or LONGBRIDGE_QUOTE_TRANSPORT
# enable_overnight = false # optional; true by default in this Julia SDKusing LongBridge
cfg = Config.from_toml()Credentials prefixed with us_ automatically use the US data center. To route
requests to a paper-trading account, set enable_papertrading = true in TOML or
call enable_papertrading!(cfg) before creating a context. US-only endpoints,
such as us_company_overview, us_crypto_overview, us_query_orders, and
us_asset_overview, reject non-US credentials with a clear error.
The SDK pins no certificate roots. REST, OAuth and WebSocket connections are verified
against NetworkOptions.ca_roots_path(): the operating system's certificate bundle on
Linux and BSD, and the roots shipped with Julia on macOS and Windows, where the system
keychain / certificate store is not read. Behind a TLS-inspecting corporate proxy,
install the proxy's root CA in the OS store on Linux; on macOS and Windows point
SSL_CERT_FILE (or JULIA_SSL_CA_ROOTS_PATH) at a PEM bundle that contains it before
starting Julia. That variable replaces the root set rather than adding to it.
Set quote_transport = "http" in TOML or use
Config.from_oauth(oauth; quote_transport=QuoteTransport.Http, enable_overnight=false)
to pull over HTTP without opening a WebSocket. Do not query member_id,
quote_level, or other quote-profile fields if you want HTTP-only usage: profile
queries and subscriptions connect to WS on demand. realtime_* still reads the
push cache, not HTTP snapshots.
using LongBridge
cfg = Config.from_toml()
# Create QuoteContext (connects eagerly only with the default WS transport)
ctx = QuoteContext(cfg)
# Get basic static information for securities
resp = static_info(ctx, ["700.HK", "AAPL.US", "TSLA.US"])
# Get real-time quotes for securities (one-shot server snapshot)
quotes = quote_snapshot(ctx, ["GOOGL.US", "AAPL.US", "TSLA.US"])
# Get real-time option quotes
resp = option_quote(ctx, ["AAPL230317P160000.US"])
# Get real-time warrant quotes
resp = warrant_quote(ctx, ["14993.HK", "66642.HK"])
# Get market depth for a security
resp = depth(ctx, "700.HK")
# Get candlestick data
candlesticks_data = candlesticks(ctx, "GOOGL.US", CandlePeriod.SIXTY_MINUTE, 365)
# Get trade details for a security
trades_data = trades(ctx, "AAPL.US", 10)
# Get intraday data for a security
intraday_data = intraday(ctx, "700.HK")
# Get historical K-line data
using Dates
history_data = history_candlesticks_by_date(
ctx, "700.HK", CandlePeriod.DAY, AdjustType.NO_ADJUST; start_date=Date(2023, 1, 1), end_date=Date(2023, 2, 1)
)
# Candlestick timestamps are UTC-semantic DateTime values. To retain the raw
# Unix seconds alongside the converted column:
history_data = history_candlesticks_by_date(
ctx, "COHR.US", CandlePeriod.ONE_MINUTE, AdjustType.NO_ADJUST;
start_date=Date(2026, 6, 17), end_date=Date(2026, 6, 18),
include_timestamp_unix=true,
)
# Optional timezone-aware display (install TimeZones.jl once if needed):
# using Pkg; Pkg.add("TimeZones")
# using TimeZones
# to_market_time(history_data.timestamp[1], "America/New_York")
# Get the list of expiry dates for an option chain
expiry_dates = option_chain_expiry_date_list(ctx, "AAPL.US")
# Get trading days for a market
trading_days_df = trading_days(ctx, Market.HK, Date(2025, 8, 1), Date(2025, 8, 30))
# Get capital flow for a security
capital_flow_data = capital_flow(ctx, "700.HK")
# Get market temperature
temp = market_temperature(ctx, Market.US)
# Get historical market temperature
history_temp = history_market_temperature(ctx, Market.US, Date(2025, 7, 1), Date(2025, 7, 31))
# Disconnect
disconnect!(ctx)close(ctx) is equivalent. Context finalizers perform best-effort automatic
cleanup, but call close or disconnect! explicitly when deterministic
connection teardown matters.
using LongBridge, Dates
cfg = Config.from_toml()
# Create and connect to TradeContext
ctx = TradeContext(cfg)
# Get account balance
resp = account_balance(ctx)
# Get stock positions (optionally filter by symbol)
resp = stock_positions(ctx)
resp = stock_positions(ctx; symbol = "700.HK") # "00700.HK" works too
# Get the risk assessment (suitability questionnaire) result
assessment = risk_assessment(ctx)
assessment.risk # e.g. "A5"
get(assessment.approvals, "risk_audit", "") # e.g. "pass"; values are strings
# Get today's orders
resp = today_orders(ctx)
# Get historical orders (date range via keyword args; every page is fetched)
resp = history_orders(ctx; start_at = Date(2024, 1, 1), end_at = Date(2024, 2, 1))
# Get today's executions
resp = today_executions(ctx)
# Get historical executions
resp = history_executions(ctx; start_at = Date(2024, 1, 1), end_at = Date(2024, 2, 1))
# Submit an order via SubmitOrderOptions
resp = submit_order(
ctx, SubmitOrderOptions(
symbol = "700.HK",
order_type = OrderType.LO,
side = OrderSide.Buy,
submitted_quantity = 100,
time_in_force = TimeInForceType.Day,
submitted_price = 300.0,
)
)
# Modify an order
resp = replace_order(
ctx, ReplaceOrderOptions(
order_id = "709043056541253632",
submitted_quantity = 100,
submitted_price = 301.0,
)
)
# Cancel an order
resp = cancel_order(ctx, "709043056541253632")
# Disconnect
disconnect!(ctx)Trade and asset calls accept the zero-padded HK symbols the Longbridge apps display:
00700.HK is sent as 700.HK, while other markets (000001.SZ included) are sent
unchanged. history_orders walks the endpoint's 1000-record pages until the server
reports no more, one request per page; with no dates the server uses a 90-day window.
RiskAssessment mirrors the server response without interpreting it: the risk scale
and the professional-investor code pi are undocumented, pi_end_at and deadlines
are raw integers of an undocumented unit, and approvals values are strings
("true" / "false", not booleans). Unexpected encodings decode to 0, "" or an
empty collection instead of failing the call.
AP / US identify the credentials' data center. AP accounts trading US stocks still use AP methods; US accounts use the alternatives below.
| AP-only query | US-account alternative |
|---|---|
account_balance |
us_cash_and_buy_power / us_asset_overview |
cash_flow |
us_transaction_history |
stock_positions |
us_asset_overview(...).stock_list |
fund_positions(::TradeContext) |
No equivalent |
margin_ratio |
No per-security equivalent; account margin is in us_cash_and_buy_power(...).margin_status |
all_executions |
history_executions |
order_detail |
us_order_detail |
exchange_rate(::PortfolioContext) |
us_exchange_rates(::TradeContext) |
Read-only examples, with us_cfg created from US credentials:
using LongBridge, Dates
us_ctx = TradeContext(us_cfg)
cash = us_cash_and_buy_power(us_ctx; currency="USD")
holding = us_available_holding(us_ctx, GetUSAvailableHoldingOptions(
symbol="BTCUSD.BKKT", equity_type="CRYPTO", position_side="LONG"))
page = us_transaction_history(us_ctx, GetUSTransactionHistoryOptions(
start_at=DateTime(2026, 10, 1), end_at=DateTime(2026, 10, 24),
page=1, size=20, types=["TT_CRYPTO_TRADING"], currency="USD"))
rates = us_exchange_rates(us_ctx).exchanges
close(us_ctx)Amounts and holding quantities remain strings to preserve backend precision; available_qty can be negative for shorts.
Empty equity_type / position_side use STOCK / LONG; nonpositive transaction page / size use 1 / 20, and empty filters are omitted.
A page shorter than the requested size is the last page. Transaction timestamps are UTC; missing/invalid times become nothing.
Exchange rates retain both map keys and are ordered by universal_key / spec_key; numeric rates become strings, and absent rates become "".
Constructing options does not place an order. The write calls below are commented out; review the account, price, quantity and trading hours before using them. Compute the future UTC time immediately before submitting.
using LongBridge, Dates
options = SubmitOrderOptions(
symbol = "700.HK", order_type = OrderType.LO, side = OrderSide.Buy,
submitted_quantity = 100, time_in_force = TimeInForceType.Day,
submitted_price = 300.0, delayed_until = now(Dates.UTC) + Hour(1),
)
# submitted = submit_order(trade_ctx, options)
# Reschedule; use the actual order ID and quantity:
# replace_order(trade_ctx, ReplaceOrderOptions(
# order_id = "<order-id>", submitted_quantity = 100,
# delayed_until = now(Dates.UTC) + Hour(2),
# ))
# OR clear the condition (not a cancellation; may submit immediately):
# replace_order(trade_ctx, ReplaceOrderOptions(
# order_id = "<order-id>", submitted_quantity = 100, clear_delayed_until = true,
# ))
# Read-only examples with an existing TradeContext:
# pending = today_orders(trade_ctx; status = [OrderStatus.DelayedNotReported])
# pending[:, ["Order ID", "Status", "Delayed Until"]] # UTC+8, nothing when unset
# detail = order_detail(trade_ctx, "<order-id>")
# detail.delayed_until # UTC+8; subtract Hour(8) before reusing in a UTC requestFor multi-leg orders, explicitly import
using LongBridge.TradeProtocol: SubmitMultiLegOrderOptions, SubmitMultiLegOrderLeg, MultiLegStrategy
and pass delayed_until in SubmitMultiLegOrderOptions. Time conditions support
only LO / MO for multi-leg orders. Choose valid, unexpired contracts. All time
conditions must be later than now and at most 90 days ahead (server validation).
Constructing options sends no request. Write calls below are commented out; review the account, prices, quantities, order IDs and trading hours before use. Depth levels apply to LIT orders and are validated by the server.
using LongBridge
using DecFP: Dec64
attached = SubmitAttachedParams(
attached_order_type = AttachedOrderType.Bracket,
profit_taker_price = Dec64("330"), stop_loss_price = Dec64("280"),
activate_order_type = OrderType.LIT,
profit_taker_depth_level = 2, stop_loss_depth_level = 5,
)
options = SubmitOrderOptions(
symbol = "700.HK", order_type = OrderType.LO, side = OrderSide.Buy,
submitted_quantity = 100, time_in_force = TimeInForceType.Day,
submitted_price = 300.0, attached_params = attached,
)
# submit_order(trade_ctx, options)
replacement = ReplaceOrderOptions(
order_id = "<order-id>", submitted_quantity = 100,
attached_params = ReplaceAttachedParams(
attached_order_type = AttachedOrderType.Bracket,
activate_order_type = OrderType.LIT,
profit_taker_depth_level = 3, stop_loss_depth_level = 5,
),
)
# replace_order(trade_ctx, replacement)
# detail = order_detail(trade_ctx, "<order-id>")
# detail.attached_orders # Vector{AttachedOrderDetail}
# today_orders(trade_ctx)[!, "Attached Orders"]To modify existing attached orders, set profit_taker_id / stop_loss_id (Int64).
cancel_all_attached=true requests cancellation of all attached orders;
omitting it does not cancel them. Unset optional fields are omitted; explicit
zero/false are preserved. expire_time uses Unix seconds.
# 1. Define a callback function
function on_quote_callback(symbol::String, event::PushQuote)
println(symbol, event)
end
# 2. Set the callback
set_on_quote(ctx, on_quote_callback)
# 3. Subscribe to quotes (can choose different types: QUOTE, DEPTH, BROKERS, TRADE)
Quote.subscribe(ctx, ["GOOGL.US"], [SubType.DEPTH]; is_first_push=true)
# 4. Unsubscribe from quotes
Quote.unsubscribe(ctx, ["GOOGL.US"], [SubType.QUOTE, SubType.DEPTH])Config.from_toml(): Load configuration fromconfig.tomlfileConfig.from_oauth(oauth_handle): Create configuration from an OAuth handleOAuthBuilder(client_id) |> build(open_url_fn): Build an OAuth handle with browser-based authorizationrevoke!(oauth)/clear!(oauth): Revoke the token on the server / remove it locallyQuoteContext(config): Create a quote context; HTTP pulls are socket-free, while WS-only operations connect on demand in HTTP modeTradeContext(config): Create and connect toTradeContextdisconnect!(ctx)/close(ctx): Disconnect and stop the Context background tasks
static_info(ctx, symbols): Get basic static information for securitiesquote_snapshot(ctx, symbols): Get a one-shot snapshot of real-time stock quotes (server query)realtime_quote(ctx, symbol_or_symbols): Read the latest pushed quote from the local cache (requires priorsubscribe)option_quote(ctx, symbols): Get real-time option quoteswarrant_quote(ctx, symbols): Get real-time warrant quotesdepth(ctx, symbol): Get market depth data for a securitybrokers(ctx, symbol): Get broker queue for a securityparticipants(ctx): Get a list of broker seat IDstrades(ctx, symbol, count): Get trade details for a securityintraday(ctx, symbol): Get intraday data for a securityhistory_candlesticks_by_date(ctx, ...): Get historical K-line data by dateoption_chain_expiry_date_list(ctx, symbol): Get a list of expiry dates for an option chainwarrant_issuers(ctx): Get a list of warrant issuer IDswarrant_list(ctx, ...): Get a filtered list of warrantstrading_session(ctx): Get the trading session for each market for the current daytrading_days(ctx, market, start_date, end_date): Get trading days for a marketcapital_flow(ctx, symbol): Get capital flow for a security for the current daycapital_distribution(ctx, symbol): Get capital distribution for a security for the current daycandlesticks(ctx, symbol, period, count): Get candlestick datahistory_candlesticks_by_offset(ctx, ...): Get historical K-line data by offsetoption_chain_info_by_date(ctx, symbol, expiry_date; standard_only=false): Get the option chain contracts for a specific expiry date (returnsVector{OptionChainContract}; filter ondirection)subscriptions(ctx): Query currently subscribed securitiescalc_indexes(ctx, symbols): Get calculated indexesmarket_temperature(ctx, market): Get market temperaturehistory_market_temperature(ctx, market, start_date, end_date): Get historical market temperaturesecurity_list(ctx, market, category): Get a list of securities
set_on_quote(ctx, callback): Set the callback function for quote pushesset_on_depth(ctx, callback): Set the callback function for market depth pushesset_on_brokers(ctx, callback): Set the callback function for broker queue pushesset_on_trades(ctx, callback): Set the callback function for trade detail pushesset_on_candlestick(ctx, callback): Set the callback function for candlestick pushessubscribe(ctx, symbols, sub_types): Subscribe to quotesunsubscribe(ctx, symbols, sub_types): Unsubscribe from quotes
realtime_depth(ctx, symbol): Get cached depth data for subscribed symbolrealtime_brokers(ctx, symbol): Get cached broker queue for subscribed symbolrealtime_trades(ctx, symbol; count): Get cached trades for subscribed symbolrealtime_candlesticks(ctx, symbol, period; count): Get cached K-line data
subscribe_candlesticks(ctx, symbol, period; count): Subscribe and get initial K-line dataunsubscribe_candlesticks(ctx, symbol, period): Unsubscribe and clear cached data
create_watchlist_group(ctx, name; securities): Create a watchlist groupwatchlist(ctx): View watchlist groupsdelete_watchlist_group(ctx, group_id, with_securities): Delete a watchlistupdate_watchlist_group(ctx, group_id; name, securities, mode): Update a watchlist group
account_balance(ctx): Get account balance (AP only)stock_positions(ctx; symbol): Get stock positions (AP only; optional symbol filter)fund_positions(ctx): Get fund positions (AP only)today_orders(ctx; symbol, status, side): Get today's ordershistory_orders(ctx; symbol, status, side, start_at, end_at): Get historical orders (auto-paged, returns aDataFrame)today_executions(ctx; symbol): Get today's executionshistory_executions(ctx; symbol, start_at, end_at): Get all historical executions (auto-paged, returnsVector{Execution})all_executions(ctx; symbol, order_id, start_at, end_at, page): Get all executions (AP only;AllExecutionsResponse)order_detail(ctx, order_id): Get order detail (AP only; includesmulti_leg, optionaldelayed_untilandattached_orders)submit_order(ctx, ::SubmitOrderOptions): Submit an order; optionaldelayed_untilschedules submission andattached_paramsconfigures attached orderssubmit_multileg(ctx, ::SubmitMultiLegOrderOptions): Submit a multi-leg option combination order; time conditions require LO / MOreplace_order(ctx, ::ReplaceOrderOptions): Modify an order; reschedule withdelayed_untilor clear it withclear_delayed_until=true;attached_paramsmodifies attached orderscancel_order(ctx, order_id): Cancel an orderestimate_max_purchase_quantity(ctx, ::EstimateMaxPurchaseQuantityOptions): Estimate max purchase quantitycash_flow(ctx; start_at, end_at): Get cash flow records (AP only)margin_ratio(ctx, symbol): Get margin ratio for a security (AP only)risk_assessment(ctx): Get the member's risk assessment result (RiskAssessment)set_on_order_changed(ctx, callback): Set the callback function for order status change pushesTrade.subscribe(ctx, topics::Vector{TopicType.T}): Subscribe to trade pushes (e.g.[TopicType.Private])Trade.unsubscribe(ctx, topics::Vector{TopicType.T}): Unsubscribe from trade pushes
These methods require US credentials. See US Assets and Region Restrictions for AP alternatives and examples.
us_asset_overview(ctx): Get the asset overview, including stock and crypto holdingsus_cash_and_buy_power(ctx; currency): Get buying power, cash balances and account margin status (USCashAndBuyPower)us_available_holding(ctx, ::GetUSAvailableHoldingOptions): Get the quantity available to trade (USAvailableHolding)us_transaction_history(ctx, ::GetUSTransactionHistoryOptions): Get one transaction page with UTC timestamps (USTransactionHistory)us_exchange_rates(ctx): Get exchange rates, preserving and sorting both map keys (USExchangeRates)
FundamentalContext(config): Create context (HTTP-only, no disconnect needed)financial_report(ctx, symbol; kind, period): Full financial statements (IS/BS/CF/All)institution_rating(ctx, symbol): Analyst ratings (latest + summary, parallel fan-out)institution_rating_detail(ctx, symbol): Historical rating distributiondividend(ctx, symbol)/dividend_detail(ctx, symbol): Dividend history / detailsforecast_eps(ctx, symbol): Analyst EPS forecastsconsensus(ctx, symbol): Revenue / profit / EPS consensus vs actualvaluation(ctx, symbol)/valuation_history(ctx, symbol): PE/PB/PS/dividend yieldindustry_valuation(ctx, symbol)/industry_valuation_dist(ctx, symbol): Peer comparisoncompany(ctx, symbol)/executive(ctx, symbol)/shareholder(ctx, symbol)/fund_holder(ctx, symbol)corp_action(ctx, symbol): Corporate actions (dividends, splits, buybacks)invest_relation(ctx, symbol),operating(ctx, symbol),buyback(ctx, symbol),ratings(ctx, symbol)
market_status(ctx): Market open/close status across regions; status fields useMarketTradeStatusbroker_holding(ctx, symbol, period)/broker_holding_detail(ctx, symbol)/broker_holding_daily(ctx, symbol, broker_id)ah_premium(ctx, symbol, period, count)/ah_premium_intraday(ctx, symbol): A/H premium klines & intradaytrade_stats(ctx, symbol): Buy/sell/neutral trade statisticsanomaly(ctx, market): Market anomaly eventsconstituent(ctx, symbol): Index constituents (e.g."HSI.HK")
finance_calendar(ctx, category, start, end_; market, count, offset, next):countlimits events per date;offsetskips events within a date.nextisCalendarPageDirection.Later/Earlier.- If
length(group.infos) < group.count, fetch that date again withstart = end_ = Date(group.date)andoffsetset to the number already received.next_dateskips past truncated groups. Filter dates afterend_locally if you need a hard cutoff. CalendarCategory:Report/Dividend/Split/Ipo/MacroData/Closed/Meeting/Merge
- If
Create fund_ctx = FundContext(cfg). All 28 methods are synchronous HTTP calls. Pass a full counter_id from funds or fund_positions, e.g. "UT/FD/HK0000384492".
| Area | Methods |
|---|---|
| Catalog | hot_funds, funds, fund_filters, fund_detail |
| Analysis | fund_analysis, fund_analysis_detail, fund_trend, fund_performance_comparison |
| Returns | fund_annual_returns, fund_quarterly_returns, fund_performance |
| NAV and holdings | fund_nav, fund_nav_history, fund_nav_range, fund_holdings, fund_stock_holdings |
| Account positions | fund_positions, fund_position, fund_position_performance, fund_position_profits, fund_position_nav, fund_position_dividends |
| Orders | fund_orders, fund_order, fund_transactions, fund_validate_order, fund_submit_order, fund_cancel_order |
fund_ctx = FundContext(cfg)
catalog = funds(fund_ctx, GetFundsOptions())
if !isempty(catalog)
counter_id = first(catalog).counter_id
nav = fund_nav(fund_ctx, counter_id) # Vector{FundNavValue}
history = fund_nav_history(fund_ctx, counter_id, FundPageOptions(page=1, size=20))
end
positions = fund_positions(fund_ctx, FundPositionsOptions()) # FundPositions
orders = fund_orders(fund_ctx, GetFundOrdersOptions(page=1, size=20))Optional settings use positional keyword-constructed option structs, as in the examples. Date-range option fields use end_ (sent as end). Monetary values remain strings; timestamps and order IDs are Int64. Dynamic JSON fields remain decoded objects/arrays. asset_allocation, contrast_performances on FundTrend, detail_values, and order on FundOrderDetail may be nothing.
The fund-channel holding type is FundHoldingPosition and its overview options are FundPositionsOptions. The existing trade holding remains TradeProtocol.FundPosition; fund_positions(::TradeContext; symbol=...) still uses its existing endpoint and filter. Submission requires SubmitFundOrderOptions(counter_id=..., action="buy", currency="USD", amount="100.00"); cancellation takes the returned numeric order ID. Commented order examples are in trade_test.jl.
exchange_rate(ctx): Current rates for all supported currencies (AP only; US accounts useus_exchange_rates(::TradeContext))profit_analysis(ctx; start, end_): Account P&L (summary + sublist parallel fan-out)profit_analysis_by_market(ctx; page, size, market, ...): Paginated by marketprofit_analysis_detail(ctx, symbol; ...): Per-security P&L breakdownprofit_analysis_flows(ctx, symbol; page, size, derivative, ...): Per-security flows
list_alerts(ctx): List all alerts grouped by securityadd_alert(ctx, symbol, condition, trigger_value, frequency): Add alertAlertCondition:PriceRise/PriceFall/PercentRise/PercentFallAlertFrequency:Daily/EveryTime/Once
update_alert(ctx, item::AlertItem): Update alert (toggle enabled etc.)delete_alerts(ctx, ids::Vector{String}): Delete alerts
list_sharelists(ctx; count)/popular_sharelists(ctx; count)/sharelist_detail(ctx, id)create_sharelist(ctx, name; description)/delete_sharelist(ctx, id)add_sharelist_securities(ctx, id, symbols)/remove_sharelist_securities(ctx, id, symbols)/sort_sharelist_securities(ctx, id, symbols)
list_dca(ctx; status, symbol)/dca_stats(ctx; symbol)create_dca(ctx, symbol, amount, frequency; day_of_week, day_of_month, allow_margin)DCAFrequency:Daily/Weekly/Fortnightly/MonthlyDCAStatus:Active/Suspended/Finished
update_dca(ctx, plan_id; amount, frequency, ...)pause_dca(ctx, plan_id)/resume_dca(ctx, plan_id)/stop_dca(ctx, plan_id)dca_history(ctx, plan_id; page, limit)/dca_check_support(ctx, symbols)/dca_calc_date(ctx, symbol, frequency; ...)/dca_set_reminder(ctx, hours)
news(ctx, symbol): News for a securitytopics_by_symbol(ctx, symbol)/topic_detail(ctx, id)/topic_replies(ctx, topic_id; page, size)my_topics(ctx; page, size, topic_type): List topics you've publishedcreate_topic(ctx, title, body; topic_type, tickers, hashtags): Publish a topic, returns IDcreate_topic_reply(ctx, topic_id, body; reply_to_id): Post a reply (plain text)
option_volume(ctx, symbol)/option_volume_daily(ctx, symbol, timestamp, count): Option volume statsupdate_pinned(ctx, mode::PinnedMode.T, symbols): Pin/unpin watchlist securities
quote_snapshot(ctx, symbols): One-shot quote snapshot via WebSocketrealtime_quote(ctx, symbol_or_symbols): Read latest pushed quote from local cache (subscribe first); aligned withrealtime_depth/brokers/tradesfilings(ctx, symbol): Company filings list (REST/v1/quote/filings), returnsVector{FilingItem}member_id(ctx)/quote_level(ctx)/quote_package_details(ctx): Account profile values retrieved throughQueryUserQuoteProfileon connectsubscribe_limit(ctx)/history_candlestick_limit(ctx): Account limits reported byQueryUserQuoteProfile; returnnothinguntil the profile has loaded
Historical candlestick timestamp columns are timezone-naive DateTime values
with UTC semantics. Use utc_iso8601 to render an explicit Z suffix, or load
TimeZones.jl and call to_market_time(timestamp, "America/New_York") for a
market-local representation. include_timestamp_unix=true adds the original
Unix-seconds value as timestamp_unix without changing the default columns.
AssetContext(config): Create context (HTTP-only, no disconnect needed)statements(ctx, type::StatementType.T; page, page_size): Paginated list of statement records (type=Daily/Monthly)statement_download_url(ctx, file_key): Resolve a statement record's download URLbank_cards(ctx)/edda_applications(ctx, card_id, currency): Linked cards and eDDA applications; use the numericBankCard.id.stock_transfers_in(ctx, GetStockTransfersInOptions(...))/stock_transfers_out(ctx, GetStockTransfersOutOptions(...)): Transfer applications with direction-specific state filters.reward_records(ctx, GetRewardRecordsOptions(...)): Reward history. There is no date filter; page and filter locally.coupons(ctx, GetCouponsOptions(...))/coupon_orders(ctx, card_id, order_type): Unexpired coupons by default; useexpired=truefor expired coupons. For orders use the 32-character hexCoupon.card_idandCouponOrderType.Locked/Settled.deposits(ctx, GetDepositsOptions(...))/withdrawals(ctx, GetWithdrawalsOptions(...)): Usepage(starts at 1) andsize(default 20, capped at 20 for deposits and 50 for withdrawals).has_moremeans the requested page was full; the next page can still be empty.
The nine account-record methods are read-only and require AP credentials. Their
date filters and returned DateTime values use UTC. Unknown server status codes
decode as Unknown; raw numeric codes are available in companion *_raw fields.
ScreenerContext(config): Create context (HTTP-only, no disconnect needed)screener_recommend_strategies(ctx, market): Preset built-in screener strategies for a market (e.g."US"/"HK")screener_user_strategies(ctx, market): Current user's saved screener strategies for a marketscreener_strategy(ctx, id): Detail of one strategy (path-param id);filter_prefix is stripped from filter keysscreener_search(ctx, market; strategy_id=nothing, conditions=ScreenerCondition[], show=String[], page=0, size=20): Mode A (whenstrategy_idis given — fetches strategy and forwards filters) or Mode B (typedScreenerConditionobjects).DEFAULT_RETURNSalways included;filter_prefix is stripped from response indicator keys.screener_indicators(ctx): Available indicator definitions;filter_prefix stripped +tech_valuesrebuilt fromtech_indicators
business_segments(ctx, symbol): Latest business and regional revenue breakdown, with issuer fiscal period (report_txt,fp_start,fp_end) and server-formattedyoybusiness_segments_history(ctx, symbol; report, cate): Historical business + regional segment snapshotsinstitution_rating_views(ctx, symbol): Historical analyst rating distribution time seriesindustry_rank(ctx, market, indicator, sort_type, limit): Industry rank in a marketindustry_peers(ctx, counter_or_symbol, market; industry_id): Recursive industry peer chainfinancial_report_snapshot(ctx, symbol; report, fiscal_year, fiscal_period): Earnings snapshot (actual vs estimate, key ratios)shareholder_top(ctx, symbol): Top-shareholder ranking (raw JSON)shareholder_detail(ctx, symbol, object_id): Holding history for one shareholder object (raw JSON)valuation_comparison(ctx, symbol, currency; comparison_symbols): Valuation comparison (PE/PB/PS) with historical curveetf_asset_allocation(ctx, symbol): ETF asset allocation (holdings / regional / asset class / industry groups)macroeconomic_indicators(ctx; country, keyword, offset, limit): List macroeconomic indicators, optionalMacroeconomicCountryand fuzzy keyword filtersmacroeconomic(ctx, id; start_date, end_date, offset, limit, sort): Historical data for one macroeconomic indicator, newest-first by default
top_movers(ctx, markets, sort, limit; date): Top movers across one or more marketsrank_categories(ctx): Available rank category keys/labels (raw JSON)rank_list(ctx, key; need_article): Ranked securities for one category
short_positions(ctx, symbol; count=20): HK/US short-position data withShortPositionsItementries and UTCDateTimetimestamps.short_trades(ctx, symbol; count=20): HK/US short-trade records, endpoint auto-selected by.HKsuffix.
SignalContext(config): Create context (HTTP-only, no disconnect needed)signals(ctx, ::SignalsOptions): Query signals, filtered by symbol/strategy/catalyst/time, paged withlimit/offsetsignal(ctx, signal_id): One signal including the full analysis injson_datasecurity_facts(ctx, ::SecurityFactsOptions): A security's catalyst-fact events (anomaly detections, factor readings, sources, NL summaries)
GridContext(config): Create context (HTTP-only, no disconnect needed)grid_submit(ctx, ::SubmitGridOrderOptions): Submit a grid ordergrid_replace(ctx, ::ReplaceGridOrderOptions): Modify a grid ordergrid_list(ctx, GetGridOrdersOptions(; page, limit, market, status, symbol, sort_by, sort_order)): List grid ordersgrid_list_by_ids(ctx, ::GetGridOrdersByIdsOptions): List grid orders by IDsgrid_detail(ctx, ::GetGridOrderDetailOptions): Grid order detailgrid_trigger_history(ctx, ::GetGridTriggerHistoryOptions): Grid trigger historygrid_cancel/grid_suspend/grid_restart(ctx, order_id): Cancel / suspend / restart a grid ordergrid_symbol_info(ctx, symbol): Grid symbol info
MIT License