Code Reference
ErrorKind
OpenApiException
Bases: Exception
OpenAPI exception
kind
instance-attribute
kind: ErrorKind
Error kind
code
instance-attribute
code: int
Error code
message
instance-attribute
message: str
Error message
__init__
__init__(code: int, message: str) -> None
HttpClient
A HTTP client for Longbridge OpenAPI.
from_apikey
staticmethod
from_apikey(app_key: str, app_secret: str, access_token: str, http_url: Optional[str] = None) -> HttpClient
Create a new HttpClient using API Key authentication.
LONGBRIDGE_HTTP_URL is read from the environment automatically.
Passing http_url overrides that value.
| Parameters: |
|---|
from_apikey_env
classmethod
from_apikey_env() -> HttpClient
Create a new HttpClient from environment variables (API Key
authentication).
Variables:
LONGBRIDGE_HTTP_URL- HTTP endpoint urlLONGBRIDGE_APP_KEY- App keyLONGBRIDGE_APP_SECRET- App secretLONGBRIDGE_ACCESS_TOKEN- Access token
from_oauth
classmethod
from_oauth(oauth: OAuth, http_url: Optional[str] = None) -> HttpClient
Create a new HttpClient from an OAuth handle.
LONGBRIDGE_HTTP_URL is read from the environment automatically.
Passing http_url overrides that value.
| Parameters: |
|---|
request
request(method: str, path: str, headers: Optional[dict[str, str]] = None, body: Optional[Any] = None) -> Any
Performs a HTTP reqest
Examples:
::
from longbridge.openapi import OAuthBuilder, HttpClient
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
client = HttpClient.from_oauth(oauth)
# get
resp = client.request("get", "/foo/bar")
print(resp)
# post
client.request("post", "/foo/bar", body={ "foo": 1, "bar": 2 })
request_async
request_async(method: str, path: str, headers: Optional[dict[str, str]] = None, body: Optional[Any] = None) -> Awaitable[Any]
Performs an async HTTP request. Returns an awaitable; must be awaited inside asyncio.
| Parameters: |
|---|
| Returns: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, HttpClient
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
http_cli = HttpClient.from_oauth(oauth)
resp = await http_cli.request_async(
"get",
"/v1/trade/execution/today",
)
print(resp)
asyncio.run(main())
PushCandlestickMode
Push candlestick mode
Realtime
Confirmed
OAuth
OAuth 2.0 client handle for Longbridge OpenAPI.
Obtain an instance via :meth:OAuthBuilder.build (blocking) or
:meth:AsyncOAuthBuilder.build (async). Pass it to
:meth:Config.from_oauth or :meth:HttpClient.from_oauth.
OAuthBuilder
Builder for the OAuth 2.0 authorization flow.
| Parameters: |
|---|
Example (blocking)::
from longbridge.openapi import OAuthBuilder, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Open:", url)
)
config = Config.from_oauth(oauth)
Example (async)::
import asyncio
from longbridge.openapi import OAuthBuilder, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Open:", url)
)
config = Config.from_oauth(oauth)
asyncio.run(main())
__init__
__init__(client_id: str, callback_port: Optional[int] = None) -> None
build
build(on_open_url: Callable[[str], None]) -> OAuth
Build an OAuth 2.0 client (blocking).
If a valid token is already cached on disk
(~/.longbridge/openapi/tokens/<client_id>) it is reused;
otherwise the browser authorization flow is started and
on_open_url is called with the authorization URL.
| Parameters: |
|---|
| Returns: |
|
|---|
build_async
async
build_async(on_open_url: Callable[[str], None]) -> OAuth
Build an OAuth 2.0 client (async).
If a valid token is already cached on disk
(~/.longbridge/openapi/tokens/<client_id>) it is reused;
otherwise the browser authorization flow is started and
on_open_url is called with the authorization URL.
| Parameters: |
|---|
| Returns: |
|
|---|
Config
Configuration options for Longbridge SDK
| Parameters: |
|
|---|
from_apikey
staticmethod
from_apikey(app_key: str, app_secret: str, access_token: str, http_url: Optional[str] = None, quote_ws_url: Optional[str] = None, trade_ws_url: Optional[str] = None, language: Optional[Type[Language]] = None, enable_overnight: bool = False, push_candlestick_mode: Type[PushCandlestickMode] = PushCandlestickMode.Realtime, enable_print_quote_packages: bool = True, log_path: Optional[str] = None) -> Config
Create a new Config using API Key authentication.
Optional environment variables are read automatically
(LONGBRIDGE_HTTP_URL, LONGBRIDGE_LANGUAGE,
LONGBRIDGE_QUOTE_WS_URL, LONGBRIDGE_TRADE_WS_URL,
LONGBRIDGE_ENABLE_OVERNIGHT, LONGBRIDGE_PUSH_CANDLESTICK_MODE,
LONGBRIDGE_PRINT_QUOTE_PACKAGES, LONGBRIDGE_LOG_PATH).
Any explicit parameter overrides the corresponding env variable.
| Parameters: |
|
|---|
from_apikey_env
classmethod
from_apikey_env() -> Config
Create a new Config from environment variables (API Key
authentication).
It first gets the environment variables from the .env file in the
current directory.
Variables:
LONGBRIDGE_APP_KEY- App keyLONGBRIDGE_APP_SECRET- App secretLONGBRIDGE_ACCESS_TOKEN- Access tokenLONGBRIDGE_LANGUAGE-zh-CN,zh-HKoren(Default:en)LONGBRIDGE_HTTP_URL- HTTP endpoint urlLONGBRIDGE_QUOTE_WS_URL- Quote websocket endpoint urlLONGBRIDGE_TRADE_WS_URL- Trade websocket endpoint urlLONGBRIDGE_ENABLE_OVERNIGHT-trueorfalse(Default:false)LONGBRIDGE_PUSH_CANDLESTICK_MODE-realtimeorconfirmed(Default:realtime)LONGBRIDGE_PRINT_QUOTE_PACKAGES-trueorfalse(Default:true)LONGBRIDGE_LOG_PATH- Log file directory (Default: no logs)
from_oauth
classmethod
from_oauth(oauth: OAuth, http_url: Optional[str] = None, quote_ws_url: Optional[str] = None, trade_ws_url: Optional[str] = None, language: Optional[Type[Language]] = None, enable_overnight: Optional[bool] = None, push_candlestick_mode: Optional[Type[PushCandlestickMode]] = None, enable_print_quote_packages: Optional[bool] = None, log_path: Optional[str] = None) -> Config
Create a new Config for OAuth 2.0 authentication.
OAuth 2.0 is the recommended authentication method — no app_secret or HMAC signatures required.
Optional environment variables are read automatically
(LONGBRIDGE_HTTP_URL, LONGBRIDGE_LANGUAGE,
LONGBRIDGE_QUOTE_WS_URL, LONGBRIDGE_TRADE_WS_URL,
LONGBRIDGE_ENABLE_OVERNIGHT, LONGBRIDGE_PUSH_CANDLESTICK_MODE,
LONGBRIDGE_PRINT_QUOTE_PACKAGES, LONGBRIDGE_LOG_PATH).
Any explicit parameter overrides the corresponding env variable.
| Parameters: |
|
|---|
| Returns: |
|
|---|
refresh_access_token
refresh_access_token(expired_at: Optional[datetime] = None) -> str
Gets a new access_token.
This method is only available when using Legacy API Key
authentication (i.e. :meth:Config.from_apikey). It is not supported
for OAuth 2.0 mode.
| Parameters: |
|---|
| Returns: |
|
|---|
refresh_access_token_async
async
refresh_access_token_async(expired_at: Optional[datetime] = None) -> str
Async version of :meth:Config.refresh_access_token. Returns an
awaitable; must be awaited inside asyncio.
This method is only available when using Legacy API Key
authentication (i.e. :meth:Config.from_apikey). It is not supported
for OAuth 2.0 mode.
| Parameters: |
|---|
| Returns: |
|
|---|
Language
Market
PushQuote
Quote message
last_done
instance-attribute
last_done: Decimal
Latest price
open
instance-attribute
open: Decimal
Open
high
instance-attribute
high: Decimal
High
low
instance-attribute
low: Decimal
Low
timestamp
instance-attribute
timestamp: datetime
Time of latest price
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
trade_status
instance-attribute
trade_status: Type[TradeStatus]
Security trading status
trade_session
instance-attribute
trade_session: Type[TradeSession]
Trade session
current_volume
instance-attribute
current_volume: int
Increase volume between pushes
current_turnover
instance-attribute
current_turnover: Decimal
Increase turnover between pushes
PushDepth
Depth message
asks
instance-attribute
asks: List[Depth]
Ask depth
bids
instance-attribute
bids: List[Depth]
Bid depth
PushBrokers
Brokers message
ask_brokers
instance-attribute
ask_brokers: List[Brokers]
Ask brokers
bid_brokers
instance-attribute
bid_brokers: List[Brokers]
Bid brokers
PushTrades
Trades message
trades
instance-attribute
trades: List[Trade]
Trades data
PushCandlestick
Candlestick updated event
period
instance-attribute
period: Period
Period type
candlestick
instance-attribute
candlestick: Candlestick
Candlestick
is_confirmed
instance-attribute
is_confirmed: bool
Is confirmed
SubType
DerivativeType
Derivative type
Option
Warrant
SecurityBoard
Security board
Unknown
USMain
USPink
USDJI
USNSDQ
USSector
USOption
USOptionS
HKEquity
HKPreIPO
HKWarrant
HKHS
HKSector
SHMainConnect
SHMainNonConnect
SHSTAR
CNIX
CNSector
SZMainConnect
SZMainNonConnect
SZGEMConnect
SZGEMNonConnect
SGMain
STI
SGSector
SPXIndex
VIXIndex
Security
Security
symbol
instance-attribute
symbol: str
Security code
name_cn
instance-attribute
name_cn: str
Security name (zh-CN)
name_en
instance-attribute
name_en: str
Security name (en)
name_hk
instance-attribute
name_hk: str
Security name (zh-HK)
SecurityListCategory
Security list category
Overnight
SecurityStaticInfo
The basic information of securities
symbol
instance-attribute
symbol: str
Security code
name_cn
instance-attribute
name_cn: str
Security name (zh-CN)
name_en
instance-attribute
name_en: str
Security name (en)
name_hk
instance-attribute
name_hk: str
Security name (zh-HK)
exchange
instance-attribute
exchange: str
Exchange which the security belongs to
currency
instance-attribute
currency: str
Trading currency
lot_size
instance-attribute
lot_size: int
Lot size
total_shares
instance-attribute
total_shares: int
Total shares
circulating_shares
instance-attribute
circulating_shares: int
Circulating shares
hk_shares
instance-attribute
hk_shares: int
HK shares (only HK stocks)
eps
instance-attribute
eps: Decimal
Earnings per share
eps_ttm
instance-attribute
eps_ttm: Decimal
Earnings per share (TTM)
bps
instance-attribute
bps: Decimal
Net assets per share
dividend_yield
instance-attribute
dividend_yield: Decimal
Dividend (per share), not the dividend yield (ratio).
stock_derivatives
instance-attribute
stock_derivatives: List[Type[DerivativeType]]
Types of supported derivatives
board
instance-attribute
board: Type[SecurityBoard]
Board
TradeStatus
Security Status
Normal
Halted
Delisted
Fuse
PrepareList
CodeMoved
ToBeOpened
SplitStockHalts
Expired
WarrantPrepareList
Suspend
PrePostQuote
Quote of US pre/post market
last_done
instance-attribute
last_done: Decimal
Latest price
timestamp
instance-attribute
timestamp: datetime
Time of latest price
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
high
instance-attribute
high: Decimal
High
low
instance-attribute
low: Decimal
Low
prev_close
instance-attribute
prev_close: Decimal
Close of the last trade session
SecurityQuote
Quote of securitity
symbol
instance-attribute
symbol: str
Security code
last_done
instance-attribute
last_done: Decimal
Latest price
prev_close
instance-attribute
prev_close: Decimal
Yesterday's close
open
instance-attribute
open: Decimal
Open
high
instance-attribute
high: Decimal
High
low
instance-attribute
low: Decimal
Low
timestamp
instance-attribute
timestamp: datetime
Time of latest price
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
trade_status
instance-attribute
trade_status: Type[TradeStatus]
Security trading status
pre_market_quote
instance-attribute
pre_market_quote: Optional[PrePostQuote]
Quote of US pre market
post_market_quote
instance-attribute
post_market_quote: Optional[PrePostQuote]
Quote of US post market
overnight_quote
instance-attribute
overnight_quote: Optional[PrePostQuote]
Quote of US overnight market
OptionType
Option type
Unknown
American
Europe
OptionDirection
Option direction
Unknown
Put
Call
OptionQuote
Quote of option
symbol
instance-attribute
symbol: str
Security code
last_done
instance-attribute
last_done: Decimal
Latest price
prev_close
instance-attribute
prev_close: Decimal
Yesterday's close
open
instance-attribute
open: Decimal
Open
high
instance-attribute
high: Decimal
High
low
instance-attribute
low: Decimal
Low
timestamp
instance-attribute
timestamp: datetime
Time of latest price
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
trade_status
instance-attribute
trade_status: Type[TradeStatus]
Security trading status
implied_volatility
instance-attribute
implied_volatility: Decimal
Implied volatility
open_interest
instance-attribute
open_interest: int
Number of open positions
expiry_date
instance-attribute
expiry_date: date
Exprity date
strike_price
instance-attribute
strike_price: Decimal
Strike price
contract_multiplier
instance-attribute
contract_multiplier: Decimal
Contract multiplier
contract_type
instance-attribute
contract_type: Type[OptionType]
Option type
contract_size
instance-attribute
contract_size: Decimal
Contract size
direction
instance-attribute
direction: Type[OptionDirection]
Option direction
historical_volatility
instance-attribute
historical_volatility: Decimal
Underlying security historical volatility of the option
underlying_symbol
instance-attribute
underlying_symbol: str
Underlying security symbol of the option
WarrantType
Warrant type
Unknown
Call
Put
Bull
Bear
Inline
WarrantQuote
Quote of warrant
symbol
instance-attribute
symbol: str
Security code
last_done
instance-attribute
last_done: Decimal
Latest price
prev_close
instance-attribute
prev_close: Decimal
Yesterday's close
open
instance-attribute
open: Decimal
Open
high
instance-attribute
high: Decimal
High
low
instance-attribute
low: Decimal
Low
timestamp
instance-attribute
timestamp: datetime
Time of latest price
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
trade_status
instance-attribute
trade_status: Type[TradeStatus]
Security trading status
implied_volatility
instance-attribute
implied_volatility: Decimal
Implied volatility
expiry_date
instance-attribute
expiry_date: date
Exprity date
last_trade_date
instance-attribute
last_trade_date: date
Last tradalbe date
outstanding_ratio
instance-attribute
outstanding_ratio: Decimal
Outstanding ratio
outstanding_quantity
instance-attribute
outstanding_quantity: int
Outstanding quantity
conversion_ratio
instance-attribute
conversion_ratio: Decimal
Conversion ratio
category
instance-attribute
category: Type[WarrantType]
Warrant type
strike_price
instance-attribute
strike_price: Decimal
Strike price
upper_strike_price
instance-attribute
upper_strike_price: Decimal
Upper bound price
lower_strike_price
instance-attribute
lower_strike_price: Decimal
Lower bound price
call_price
instance-attribute
call_price: Decimal
Call price
underlying_symbol
instance-attribute
underlying_symbol: str
Underlying security symbol of the warrant
Depth
Depth
position
instance-attribute
position: int
Position
price
instance-attribute
price: Optional[Decimal]
Price
volume
instance-attribute
volume: int
Volume
order_num
instance-attribute
order_num: int
Number of orders
SecurityDepth
Security depth
asks
instance-attribute
asks: List[Depth]
Ask depth
bids
instance-attribute
bids: List[Depth]
Bid depth
Brokers
Brokers
position
instance-attribute
position: int
Position
broker_ids
instance-attribute
broker_ids: List[int]
Broker IDs
SecurityBrokers
Security brokers
ask_brokers
instance-attribute
ask_brokers: List[Brokers]
Ask brokers
bid_brokers
instance-attribute
bid_brokers: List[Brokers]
Bid brokers
ParticipantInfo
Participant info
broker_ids
instance-attribute
broker_ids: List[int]
Broker IDs
name_cn
instance-attribute
name_cn: str
Participant name (zh-CN)
name_en
instance-attribute
name_en: str
Participant name (en)
name_hk
instance-attribute
name_hk: str
Participant name (zh-HK)
TradeDirection
Trade direction
TradeSession
Trade session
Intraday
Pre
Post
Overnight
Trade
Trade
price
instance-attribute
price: Decimal
Price
volume
instance-attribute
volume: int
Volume
timestamp
instance-attribute
timestamp: datetime
Time of trading
trade_type
instance-attribute
trade_type: str
Trade type
HK
*- Overseas tradeD- Odd-lot tradeM- Non-direct off-exchange tradeP- Late trade (Off-exchange previous day)U- Auction tradeX- Direct off-exchange tradeY- Automatch internalized<empty string>- Automatch normal
US
<empty string>- Regular saleA- AcquisitionB- Bunched tradeD- DistributionF- Intermarket sweepG- Bunched sold tradesH- Price variation tradeI- Odd lot tradeK- Rule 155 trde(NYSE MKT)M- Market center close priceP- Prior reference priceQ- Market center open priceS- Split tradeV- Contingent tradeW- Average price tradeX- Cross trade1- Stopped stock(Regular trade)
direction
instance-attribute
direction: Type[TradeDirection]
Trade direction
trade_session
instance-attribute
trade_session: Type[TradeSession]
Trade session
IntradayLine
Intraday line
price
instance-attribute
price: Decimal
Close price of the minute
timestamp
instance-attribute
timestamp: datetime
Start time of the minute
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
avg_price
instance-attribute
avg_price: Decimal
Average price
Candlestick
Candlestick
close
instance-attribute
close: Decimal
Close price
open
instance-attribute
open: Decimal
Open price
low
instance-attribute
low: Decimal
Low price
high
instance-attribute
high: Decimal
High price
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
timestamp
instance-attribute
timestamp: datetime
Timestamp
trade_session
instance-attribute
trade_session: TradeSession
Trade session
AdjustType
Candlestick adjustment type
NoAdjust
ForwardAdjust
Period
Candlestick period
Unknown
Min_1
Min_2
Min_3
Min_5
Min_10
Min_15
Min_20
Min_30
Min_45
Min_60
Min_120
Min_180
Min_240
Day
Week
Month
Quarter
Year
StrikePriceInfo
Strike price info
price
instance-attribute
price: Decimal
Strike price
call_symbol
instance-attribute
call_symbol: str
Security code of call option
put_symbol
instance-attribute
put_symbol: str
Security code of put option
standard
instance-attribute
standard: bool
Is standard
IssuerInfo
Issuer info
issuer_id
instance-attribute
issuer_id: int
Issuer ID
name_cn
instance-attribute
name_cn: str
Issuer name (zh-CN)
name_en
instance-attribute
name_en: str
Issuer name (en)
name_hk
instance-attribute
name_hk: str
Issuer name (zh-HK)
WarrantStatus
Warrant status
Suspend
PrepareList
Normal
SortOrderType
Sort order type
Ascending
Descending
WarrantSortBy
Warrant sort by
LastDone
ChangeRate
ChangeValue
Volume
Turnover
ExpiryDate
StrikePrice
UpperStrikePrice
LowerStrikePrice
OutstandingQuantity
OutstandingRatio
Premium
ItmOtm
ImpliedVolatility
Delta
CallPrice
ToCallPrice
EffectiveLeverage
LeverageRatio
ConversionRatio
BalancePoint
Status
FilterWarrantExpiryDate
Filter warrant expiry date type
LT_3
Between_3_6
Between_6_12
GT_12
FilterWarrantInOutBoundsType
Filter warrant in/out of the bounds type
In
Out
WarrantInfo
Warrant info
symbol
instance-attribute
symbol: str
Security code
warrant_type
instance-attribute
warrant_type: Type[WarrantType]
Warrant type
name
instance-attribute
name: str
Security name
last_done
instance-attribute
last_done: Decimal
Latest price
change_rate
instance-attribute
change_rate: Decimal
Quote change rate
change_value
instance-attribute
change_value: Decimal
Quote change
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
expiry_date
instance-attribute
expiry_date: date
Expiry date
strike_price
instance-attribute
strike_price: Optional[Decimal]
Strike price
upper_strike_price
instance-attribute
upper_strike_price: Optional[Decimal]
Upper strike price
lower_strike_price
instance-attribute
lower_strike_price: Optional[Decimal]
Lower strike price
outstanding_qty
instance-attribute
outstanding_qty: int
Outstanding quantity
outstanding_ratio
instance-attribute
outstanding_ratio: Decimal
Outstanding ratio
premium
instance-attribute
premium: Decimal
Premium
itm_otm
instance-attribute
itm_otm: Optional[Decimal]
In/out of the bound
implied_volatility
instance-attribute
implied_volatility: Optional[Decimal]
Implied volatility
delta
instance-attribute
delta: Optional[Decimal]
Greek value delta
call_price
instance-attribute
call_price: Optional[Decimal]
Call price
to_call_price
instance-attribute
to_call_price: Optional[Decimal]
Price interval from the call price
effective_leverage
instance-attribute
effective_leverage: Optional[Decimal]
Effective leverage
leverage_ratio
instance-attribute
leverage_ratio: Decimal
Leverage ratio
conversion_ratio
instance-attribute
conversion_ratio: Optional[Decimal]
Conversion ratio
balance_point
instance-attribute
balance_point: Optional[Decimal]
Breakeven point
status
instance-attribute
status: Type[WarrantStatus]
Status
TradingSessionInfo
The information of trading session
begin_time
instance-attribute
begin_time: time
Being trading time
end_time
instance-attribute
end_time: time
End trading time
trade_session
instance-attribute
trade_session: Type[TradeSession]
Trading sessions
MarketTradingSession
Market trading session
market
instance-attribute
market: Type[Market]
Market
trade_sessions
instance-attribute
trade_sessions: List[TradingSessionInfo]
Trading session
MarketTradingDays
trading_days
instance-attribute
trading_days: List[date]
half_trading_days
instance-attribute
half_trading_days: List[date]
CapitalFlowLine
Capital flow line
inflow
instance-attribute
inflow: Decimal
Inflow capital data
timestamp
instance-attribute
timestamp: datetime
Time
CapitalDistribution
Capital distribution
large
instance-attribute
large: Decimal
Large order
medium
instance-attribute
medium: Decimal
Medium order
small
instance-attribute
small: Decimal
Small order
CapitalDistributionResponse
Capital distribution response
timestamp
instance-attribute
timestamp: datetime
Time
capital_in
instance-attribute
capital_in: CapitalDistribution
Inflow capital data
capital_out
instance-attribute
capital_out: CapitalDistribution
Outflow capital data
WatchlistSecurity
Watchlist security
symbol
instance-attribute
symbol: str
Security symbol
market
instance-attribute
market: Market
Market
name
instance-attribute
name: str
Security name
watched_price
instance-attribute
watched_price: Optional[Decimal]
Watched price
watched_at
instance-attribute
watched_at: datetime
Watched time
WatchlistGroup
id
instance-attribute
id: int
Group id
name
instance-attribute
name: str
Group name
securities
instance-attribute
securities: List[WatchlistSecurity]
Securities
SecuritiesUpdateMode
Securities update mode
Add
Remove
Replace
PinnedMode
Pinned mode for watchlist securities.
Add
Remove
RealtimeQuote
Real-time quote
symbol
instance-attribute
symbol: str
Security code
last_done
instance-attribute
last_done: Decimal
Latest price
open
instance-attribute
open: Decimal
Open
high
instance-attribute
high: Decimal
High
low
instance-attribute
low: Decimal
Low
timestamp
instance-attribute
timestamp: datetime
Time of latest price
volume
instance-attribute
volume: int
Volume
turnover
instance-attribute
turnover: Decimal
Turnover
trade_status
instance-attribute
trade_status: Type[TradeStatus]
Security trading status
Subscription
Subscription
symbol
instance-attribute
symbol: str
Security code
sub_types
instance-attribute
sub_types: List[Type[SubType]]
Subscription types
candlesticks
instance-attribute
candlesticks: List[Type[Period]]
Candlesticks
CalcIndex
Calc index
LastDone
ChangeValue
ChangeRate
Volume
Turnover
YtdChangeRate
TurnoverRate
TotalMarketValue
CapitalFlow
Amplitude
VolumeRatio
PeTtmRatio
PbRatio
DividendRatioTtm
FiveDayChangeRate
TenDayChangeRate
HalfYearChangeRate
FiveMinutesChangeRate
ExpiryDate
StrikePrice
UpperStrikePrice
LowerStrikePrice
OutstandingQty
OutstandingRatio
Premium
ItmOtm
ImpliedVolatility
WarrantDelta
CallPrice
ToCallPrice
EffectiveLeverage
LeverageRatio
ConversionRatio
BalancePoint
OpenInterest
Delta
Gamma
Theta
Vega
Rho
SecurityCalcIndex
Security calc index response
symbol
instance-attribute
symbol: str
Security symbol
last_done
instance-attribute
last_done: Optional[Decimal]
Latest price
change_value
instance-attribute
change_value: Optional[Decimal]
Change value
change_rate
instance-attribute
change_rate: Optional[Decimal]
Change ratio
volume
instance-attribute
volume: Optional[int]
Volume
turnover
instance-attribute
turnover: Optional[Decimal]
Turnover
ytd_change_rate
instance-attribute
ytd_change_rate: Optional[Decimal]
Year-to-date change ratio
turnover_rate
instance-attribute
turnover_rate: Optional[Decimal]
turnover_rate
total_market_value
instance-attribute
total_market_value: Optional[Decimal]
Total market value
capital_flow
instance-attribute
capital_flow: Optional[Decimal]
Capital flow
amplitude
instance-attribute
amplitude: Optional[Decimal]
Amplitude
volume_ratio
instance-attribute
volume_ratio: Optional[Decimal]
Volume ratio
pe_ttm_ratio
instance-attribute
pe_ttm_ratio: Optional[Decimal]
PE (TTM)
pb_ratio
instance-attribute
pb_ratio: Optional[Decimal]
PB
dividend_ratio_ttm
instance-attribute
dividend_ratio_ttm: Optional[Decimal]
Dividend ratio (TTM)
five_day_change_rate
instance-attribute
five_day_change_rate: Optional[Decimal]
Five days change ratio
ten_day_change_rate
instance-attribute
ten_day_change_rate: Optional[Decimal]
Ten days change ratio
half_year_change_rate
instance-attribute
half_year_change_rate: Optional[Decimal]
Half year change ratio
five_minutes_change_rate
instance-attribute
five_minutes_change_rate: Optional[Decimal]
Five minutes change ratio
expiry_date
instance-attribute
expiry_date: Optional[date]
Expiry date
strike_price
instance-attribute
strike_price: Optional[Decimal]
Strike price
upper_strike_price
instance-attribute
upper_strike_price: Optional[Decimal]
Upper bound price
lower_strike_price
instance-attribute
lower_strike_price: Optional[Decimal]
Lower bound price
outstanding_qty
instance-attribute
outstanding_qty: Optional[int]
Outstanding quantity
outstanding_ratio
instance-attribute
outstanding_ratio: Optional[Decimal]
Outstanding ratio
premium
instance-attribute
premium: Optional[Decimal]
Premium
itm_otm
instance-attribute
itm_otm: Optional[Decimal]
In/out of the bound
implied_volatility
instance-attribute
implied_volatility: Optional[Decimal]
Implied volatility
warrant_delta
instance-attribute
warrant_delta: Optional[Decimal]
Warrant delta
call_price
instance-attribute
call_price: Optional[Decimal]
Call price
to_call_price
instance-attribute
to_call_price: Optional[Decimal]
Price interval from the call price
effective_leverage
instance-attribute
effective_leverage: Optional[Decimal]
Effective leverage
leverage_ratio
instance-attribute
leverage_ratio: Optional[Decimal]
Leverage ratio
conversion_ratio
instance-attribute
conversion_ratio: Optional[Decimal]
Conversion ratio
balance_point
instance-attribute
balance_point: Optional[Decimal]
Breakeven point
open_interest
instance-attribute
open_interest: Optional[int]
Open interest
delta
instance-attribute
delta: Optional[Decimal]
Delta
gamma
instance-attribute
gamma: Optional[Decimal]
Gamma
theta
instance-attribute
theta: Optional[Decimal]
Theta
vega
instance-attribute
vega: Optional[Decimal]
Vega
rho
instance-attribute
rho: Optional[Decimal]
Rho
QuotePackageDetail
Quote package detail
key
instance-attribute
key: str
Key
name
instance-attribute
name: str
Name
description
instance-attribute
description: str
Description
start_at
instance-attribute
start_at: datetime
Start time
end_at
instance-attribute
end_at: datetime
End time
TradeSessions
Trade sessions
Intraday
All
MarketTemperature
Market temperature
temperature
instance-attribute
temperature: int
Temperature value
description
instance-attribute
description: str
Temperature description
valuation
instance-attribute
valuation: int
Market valuation
sentiment
instance-attribute
sentiment: int
Market sentiment
timestamp
instance-attribute
timestamp: datetime
Time
Granularity
Data granularity
Unknown
Daily
Weekly
Monthly
HistoryMarketTemperatureResponse
History market temperature response
granularity
instance-attribute
granularity: Type[Granularity]
Granularity
records
instance-attribute
records: List[MarketTemperature]
Records
QuoteContext
Quote context
| Parameters: |
|
|---|
__init__
__init__(config: Config) -> None
member_id
member_id() -> int
Returns the member ID
quote_level
quote_level() -> str
Returns the quote level
quote_package_details
quote_package_details() -> List[QuotePackageDetail]
Returns the quote package details
set_on_quote
set_on_quote(callback: Callable[[str, PushQuote], None]) -> None
Set quote callback, after receiving the quote data push, it will call back to this function.
set_on_depth
set_on_depth(callback: Callable[[str, PushDepth], None]) -> None
Set depth callback, after receiving the depth data push, it will call back to this function.
set_on_brokers
set_on_brokers(callback: Callable[[str, PushBrokers], None]) -> None
Set brokers callback, after receiving the brokers data push, it will call back to this function.
set_on_trades
set_on_trades(callback: Callable[[str, PushTrades], None]) -> None
Set trades callback, after receiving the trades data push, it will call back to this function.
set_on_candlestick
set_on_candlestick(callback: Callable[[str, PushCandlestick], None]) -> None
Set candlestick callback, after receiving the candlestick updated event, it will call back to this function.
subscribe
subscribe(symbols: List[str], sub_types: List[Type[SubType]]) -> None
Subscribe
| Parameters: |
|---|
Examples:
::
from time import sleep
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SubType, PushQuote
def on_quote(symbol: str, event: PushQuote):
print(symbol, event)
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
sleep(30)
unsubscribe
unsubscribe(symbols: List[str], sub_types: List[Type[SubType]]) -> None
Unsubscribe
| Parameters: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SubType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
ctx.unsubscribe(["AAPL.US"], [SubType.Quote])
subscribe_candlesticks
subscribe_candlesticks(symbol: str, period: Type[Period], trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> List[Candlestick]
Subscribe security candlesticks
| Parameters: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, PushCandlestick, TradeSessions
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
def on_candlestick(symbol: str, event: PushCandlestick):
print(symbol, event)
ctx.set_on_candlestick(on_candlestick)
ctx.subscribe_candlesticks("700.HK", Period.Min_1, TradeSessions.Intraday)
sleep(30)
unsubscribe_candlesticks
unsubscribe_candlesticks(symbol: str, period: Type[Period]) -> None
subscriptions
subscriptions() -> List[Subscription]
Get subscription information
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SubType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
resp = ctx.subscriptions()
print(resp)
static_info
static_info(symbols: List[str]) -> List[SecurityStaticInfo]
Get basic information of securities
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.static_info(
["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
quote
quote(symbols: List[str]) -> List[SecurityQuote]
Get quote of securities
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
option_quote
option_quote(symbols: List[str]) -> List[OptionQuote]
Get quote of option securities
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_quote(["AAPL230317P160000.US"])
print(resp)
warrant_quote
warrant_quote(symbols: List[str]) -> List[WarrantQuote]
Get quote of warrant securities
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.warrant_quote(["21125.HK"])
print(resp)
depth
depth(symbol: str) -> SecurityDepth
Get security depth
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.depth("700.HK")
print(resp)
brokers
brokers(symbol: str) -> SecurityBrokers
Get security brokers
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.brokers("700.HK")
print(resp)
participants
participants() -> List[ParticipantInfo]
Get participants
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.participants()
print(resp)
trades
trades(symbol: str, count: int) -> List[Trade]
Get security trades
| Parameters: |
|---|
| Returns: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.trades("700.HK", 10)
print(resp)
intraday
intraday(symbol: str, trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> List[IntradayLine]
Get security intraday lines
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, TradeSessions
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.intraday("700.HK", TradeSessions.Intraday)
print(resp)
candlesticks
candlesticks(symbol: str, period: Type[Period], count: int, adjust_type: Type[AdjustType], trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> List[Candlestick]
Get security candlesticks
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, Period, AdjustType, TradeSessions
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.candlesticks(
"700.HK", Period.Day, 10, AdjustType.NoAdjust, TradeSessions.Intraday)
print(resp)
history_candlesticks_by_offset
history_candlesticks_by_offset(symbol: str, period: Type[Period], adjust_type: Type[AdjustType], forward: bool, count: int, time: Optional[datetime] = None, trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> List[Candlestick]
Get security history candlesticks by offset
| Parameters: |
|
|---|
history_candlesticks_by_date
history_candlesticks_by_date(symbol: str, period: Type[Period], adjust_type: Type[AdjustType], start: Optional[date], end: Optional[date], trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> List[Candlestick]
Get security history candlesticks by date
| Parameters: |
|---|
option_chain_expiry_date_list
option_chain_expiry_date_list(symbol: str) -> List[date]
Get option chain expiry date list
| Parameters: |
|
|---|
| Returns: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_chain_expiry_date_list("AAPL.US")
print(resp)
option_chain_info_by_date
option_chain_info_by_date(symbol: str, expiry_date: date) -> List[StrikePriceInfo]
Get option chain info by date
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from datetime import date
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_chain_info_by_date(
"AAPL.US", date(2023, 1, 20))
print(resp)
warrant_issuers
warrant_issuers() -> List[IssuerInfo]
Get warrant issuers
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.warrant_issuers()
print(resp)
warrant_list
warrant_list(symbol: str, sort_by: Type[WarrantSortBy], sort_order: Type[SortOrderType], warrant_type: Optional[List[Type[WarrantType]]] = None, issuer: Optional[List[int]] = None, expiry_date: Optional[List[Type[FilterWarrantExpiryDate]]] = None, price_type: Optional[List[Type[FilterWarrantInOutBoundsType]]] = None, status: Optional[List[Type[WarrantStatus]]] = None) -> List[WarrantInfo]
Get warrant list
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, WarrantSortBy, SortOrderType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)
print(resp)
trading_session
trading_session() -> List[MarketTradingSession]
Get trading session of the day
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.trading_session()
print(resp)
trading_days
trading_days(market: Type[Market], begin: date, end: date) -> MarketTradingDays
Get trading session of the day
The interval must be less than one month, and only the most recent year is supported.
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from datetime import date
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, Market
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.trading_days(
Market.HK, date(2022, 1, 1), date(2022, 2, 1))
print(resp)
capital_flow
capital_flow(symbol: str) -> List[CapitalFlowLine]
Get capital flow intraday
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.capital_flow("700.HK")
print(resp)
capital_distribution
capital_distribution(symbol: str) -> CapitalDistributionResponse
Get capital distribution
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.capital_distribution("700.HK")
print(resp)
calc_indexes
calc_indexes(symbols: List[str], indexes: List[Type[CalcIndex]]) -> List[SecurityCalcIndex]
Get calc indexes
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, CalcIndex
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.calc_indexes(["700.HK", "APPL.US"], [CalcIndex.LastDone, CalcIndex.ChangeRate])
print(resp)
watchlist
watchlist() -> List[WatchlistGroup]
Get watch list
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.watchlist()
print(resp)
create_watchlist_group
create_watchlist_group(name: str, securities: Optional[List[str]] = None) -> int
Create watchlist group
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
group_id = ctx.create_watchlist_group(name = "Watchlist1", securities = ["700.HK", "AAPL.US"])
print(group_id)
delete_watchlist_group
delete_watchlist_group(id: int, purge: bool = False)
Delete watchlist group
| Parameters: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.delete_watchlist_group(10086)
update_watchlist_group
update_watchlist_group(id: int, name: Optional[str] = None, securities: Optional[List[str]] = None, mode: Optional[Type[SecuritiesUpdateMode]] = None)
Update watchlist group
| Parameters: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SecuritiesUpdateMode
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace)
update_pinned
update_pinned(mode: Type[PinnedMode], symbols: List[str]) -> None
Pin or unpin watchlist securities.
| Parameters: |
|
|---|
security_list
security_list(market: Type[Market], category: Optional[Type[SecurityListCategory]] = None) -> List[Security]
Get security list
| Parameters: |
|
|---|
| Returns: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, Market, SecurityListCategory
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.security_list(Market.HK, SecurityListCategory.Overnight)
print(resp)
market_temperature
market_temperature(market: Type[Market]) -> MarketTemperature
Get current market temperature
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, Market
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.market_temperature(Market.HK)
print(resp)
history_market_temperature
history_market_temperature(market: Type[Market], start_date: date, end_date: date) -> HistoryMarketTemperatureResponse
Get historical market temperature
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from datetime import date
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, Market
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.history_market_temperature(Market.HK, date(2023, 1, 1), date(2023, 1, 31))
print(resp)
realtime_quote
realtime_quote(symbols: List[str]) -> List[RealtimeQuote]
Get real-time quote
Get real-time quotes of the subscribed symbols, it always returns the data in the local storage.
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from time import sleep
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SubType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
sleep(5)
resp = ctx.realtime_quote(["700.HK", "AAPL.US"])
print(resp)
realtime_depth
realtime_depth(symbol: str) -> SecurityDepth
Get real-time depth
Get real-time depth of the subscribed symbols, it always returns the data in the local storage.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from time import sleep
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SubType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Depth])
sleep(5)
resp = ctx.realtime_depth("700.HK")
print(resp)
realtime_brokers
realtime_brokers(symbol: str) -> SecurityBrokers
Get real-time brokers
Get real-time brokers of the subscribed symbols, it always returns the data in the local storage.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from time import sleep
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SubType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Brokers])
sleep(5)
resp = ctx.realtime_brokers("700.HK")
print(resp)
realtime_trades
realtime_trades(symbol: str, count: int = 500) -> List[Trade]
Get real-time trades
Get real-time trades of the subscribed symbols, it always returns the data in the local storage.
| Parameters: |
|---|
| Returns: |
|---|
Examples:
::
from time import sleep
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, SubType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Trade])
sleep(5)
resp = ctx.realtime_trades("700.HK", 10)
print(resp)
realtime_candlesticks
realtime_candlesticks(symbol: str, period: Type[Period], count: int = 500) -> List[Candlestick]
Get real-time candlesticks
Get Get real-time candlesticks of the subscribed symbols, it always returns the data in the local storage.
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from time import sleep
from longbridge.openapi import OAuthBuilder, QuoteContext, Config, Period
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe_candlesticks("AAPL.US", Period.Min_1)
sleep(5)
resp = ctx.realtime_candlesticks("AAPL.US", Period.Min_1, 10)
print(resp)
short_positions
short_positions(symbol: str, count: int = 20) -> ShortPositionsResponse
Get short interest / position data for a US or HK security.
Market is inferred from the symbol suffix: .HK → HK endpoint,
otherwise US endpoint.
| Parameters: |
|---|
| Returns: |
|
|---|
short_trades
short_trades(symbol: str, count: int = 20) -> ShortTradesResponse
Get short trade records for a HK or US security.
Market is inferred from the symbol suffix: .HK → HK endpoint,
otherwise US endpoint.
| Parameters: |
|---|
| Returns: |
|
|---|
AsyncQuoteContext
Async quote context for use with asyncio. Create via AsyncQuoteContext.create(config) and await inside asyncio.
Callbacks (set_on_quote, set_on_depth, etc.) are set the same way as the sync QuoteContext; all I/O methods return awaitables.
create
classmethod
create(config: Config, loop_: Optional[Any] = None) -> AsyncQuoteContext
Create an async quote context.
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, Config, AsyncQuoteContext
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.quote(["700.HK", "AAPL.US"])
print(resp)
asyncio.run(main())
member_id
async
member_id() -> int
Returns the member ID.
quote_level
async
quote_level() -> str
Returns the quote level.
quote_package_details
async
quote_package_details() -> List[QuotePackageDetail]
Returns the quote package details.
set_on_quote
set_on_quote(callback: Callable[[str, PushQuote], None] | Callable[[str, PushQuote], Coroutine[Any, Any, None]]) -> None
Set quote callback; called when quote push is received. Callback may be sync or async (async is scheduled on the event loop).
set_on_depth
set_on_depth(callback: Callable[[str, PushDepth], None] | Callable[[str, PushDepth], Coroutine[Any, Any, None]]) -> None
Set depth callback; called when depth push is received. Callback may be sync or async (async is scheduled on the event loop).
set_on_brokers
set_on_brokers(callback: Callable[[str, PushBrokers], None] | Callable[[str, PushBrokers], Coroutine[Any, Any, None]]) -> None
Set brokers callback; called when brokers push is received. Callback may be sync or async (async is scheduled on the event loop).
set_on_trades
set_on_trades(callback: Callable[[str, PushTrades], None] | Callable[[str, PushTrades], Coroutine[Any, Any, None]]) -> None
Set trades callback; called when trades push is received. Callback may be sync or async (async is scheduled on the event loop).
set_on_candlestick
set_on_candlestick(callback: Callable[[str, PushCandlestick], None] | Callable[[str, PushCandlestick], Coroutine[Any, Any, None]]) -> None
Set candlestick callback; called when candlestick push is received. Callback may be sync or async (async is scheduled on the event loop).
subscribe
subscribe(symbols: List[str], sub_types: List[Type[SubType]]) -> Awaitable[None]
Subscribe to symbols and sub types. Returns an awaitable; must be awaited in asyncio.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SubType, PushQuote
def on_quote(symbol: str, event: PushQuote):
print(symbol, event)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
ctx.set_on_quote(on_quote)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
await asyncio.sleep(30)
asyncio.run(main())
unsubscribe
unsubscribe(symbols: List[str], sub_types: List[Type[SubType]]) -> Awaitable[None]
Unsubscribe from symbols and sub types. Returns an awaitable.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SubType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
await ctx.unsubscribe(["AAPL.US"], [SubType.Quote])
asyncio.run(main())
subscribe_candlesticks
subscribe_candlesticks(symbol: str, period: Type[Period], trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> Awaitable[List[Candlestick]]
Subscribe security candlesticks. Returns an awaitable that resolves to initial candlesticks.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, (
AsyncQuoteContext,
Config,
Period,
PushCandlestick,
TradeSessions,
)
def on_candlestick(symbol: str, event: PushCandlestick):
print(symbol, event)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
ctx.set_on_candlestick(on_candlestick)
await ctx.subscribe_candlesticks(
"700.HK",
Period.Min_1,
TradeSessions.Intraday,
)
await asyncio.sleep(30)
asyncio.run(main())
unsubscribe_candlesticks
unsubscribe_candlesticks(symbol: str, period: Type[Period]) -> Awaitable[None]
Unsubscribe security candlesticks. Returns an awaitable.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, (
AsyncQuoteContext,
Config,
Period,
TradeSessions,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe_candlesticks(
"700.HK",
Period.Min_1,
TradeSessions.Intraday,
)
await ctx.unsubscribe_candlesticks("700.HK", Period.Min_1)
asyncio.run(main())
subscriptions
subscriptions() -> Awaitable[List[Subscription]]
Get subscription information. Returns an awaitable that resolves to subscription list.
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SubType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
resp = await ctx.subscriptions()
print(resp)
asyncio.run(main())
static_info
static_info(symbols: List[str]) -> Awaitable[List[SecurityStaticInfo]]
Get basic information of securities. Returns an awaitable that resolves to security info list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.static_info(
["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"],
)
print(resp)
asyncio.run(main())
quote
quote(symbols: List[str]) -> Awaitable[List[SecurityQuote]]
Get quote of securities. Returns an awaitable that resolves to security quote list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
asyncio.run(main())
option_quote
option_quote(symbols: List[str]) -> Awaitable[List[OptionQuote]]
Get quote of option securities. Returns an awaitable that resolves to option quote list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_quote(["AAPL230317P160000.US"])
print(resp)
asyncio.run(main())
warrant_quote
warrant_quote(symbols: List[str]) -> Awaitable[List[WarrantQuote]]
Get quote of warrant securities. Returns an awaitable that resolves to warrant quote list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.warrant_quote(["21125.HK"])
print(resp)
asyncio.run(main())
depth
depth(symbol: str) -> Awaitable[SecurityDepth]
Get security depth. Returns an awaitable that resolves to security depth.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.depth("700.HK")
print(resp)
asyncio.run(main())
brokers
brokers(symbol: str) -> Awaitable[SecurityBrokers]
Get security brokers. Returns an awaitable that resolves to security brokers.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.brokers("700.HK")
print(resp)
asyncio.run(main())
participants
participants() -> Awaitable[List[ParticipantInfo]]
Get participants. Returns an awaitable that resolves to participant list.
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.participants()
print(resp)
asyncio.run(main())
trades
trades(symbol: str, count: int) -> Awaitable[List[Trade]]
Get security trades. Returns an awaitable that resolves to trades list (max count 1000).
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.trades("700.HK", 10)
print(resp)
asyncio.run(main())
intraday
intraday(symbol: str, trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> Awaitable[List[IntradayLine]]
Get security intraday lines. Returns an awaitable that resolves to intraday line list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, TradeSessions
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.intraday("700.HK", TradeSessions.Intraday)
print(resp)
asyncio.run(main())
candlesticks
candlesticks(symbol: str, period: Type[Period], count: int, adjust_type: Type[AdjustType], trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> Awaitable[List[Candlestick]]
Get security candlesticks. Returns an awaitable that resolves to candlesticks list (max count 1000).
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, (
AsyncQuoteContext,
Config,
Period,
AdjustType,
TradeSessions,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.candlesticks(
"700.HK",
Period.Day,
10,
AdjustType.NoAdjust,
TradeSessions.Intraday,
)
print(resp)
asyncio.run(main())
history_candlesticks_by_offset
history_candlesticks_by_offset(symbol: str, period: Type[Period], adjust_type: Type[AdjustType], forward: bool, count: int, time: Optional[datetime] = None, trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> Awaitable[List[Candlestick]]
Get security history candlesticks by offset. Returns an awaitable that resolves to candlesticks list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
import datetime
from longbridge.openapi import OAuthBuilder, (
AsyncQuoteContext,
Config,
Period,
AdjustType,
TradeSessions,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.history_candlesticks_by_offset(
"700.HK",
Period.Day,
AdjustType.NoAdjust,
False,
10,
datetime.datetime(2023, 8, 18),
TradeSessions.Intraday,
)
print(resp)
asyncio.run(main())
history_candlesticks_by_date
history_candlesticks_by_date(symbol: str, period: Type[Period], adjust_type: Type[AdjustType], start: Optional[date], end: Optional[date], trade_sessions: Type[TradeSessions] = TradeSessions.Intraday) -> Awaitable[List[Candlestick]]
Get security history candlesticks by date. Returns an awaitable that resolves to candlesticks list.
| Parameters: |
|---|
Examples:
::
import asyncio
import datetime
from longbridge.openapi import OAuthBuilder, (
AsyncQuoteContext,
Config,
Period,
AdjustType,
TradeSessions,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.history_candlesticks_by_date(
"700.HK",
Period.Day,
AdjustType.NoAdjust,
datetime.date(2022, 5, 5),
datetime.date(2022, 6, 23),
TradeSessions.Intraday,
)
print(resp)
asyncio.run(main())
option_chain_expiry_date_list
option_chain_expiry_date_list(symbol: str) -> Awaitable[List[date]]
Get option chain expiry date list. Returns an awaitable that resolves to date list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_chain_expiry_date_list("AAPL.US")
print(resp)
asyncio.run(main())
option_chain_info_by_date
option_chain_info_by_date(symbol: str, expiry_date: date) -> Awaitable[List[StrikePriceInfo]]
Get option chain info by date. Returns an awaitable that resolves to strike price info list.
| Parameters: |
|---|
Examples:
::
import asyncio
from datetime import date
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_chain_info_by_date(
"AAPL.US",
date(2023, 1, 20),
)
print(resp)
asyncio.run(main())
warrant_issuers
warrant_issuers() -> Awaitable[List[IssuerInfo]]
Get warrant issuers. Returns an awaitable that resolves to issuer list.
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.warrant_issuers()
print(resp)
asyncio.run(main())
warrant_list
warrant_list(symbol: str, sort_by: Type[WarrantSortBy], sort_order: Type[SortOrderType], warrant_type: Optional[List[Type[WarrantType]]] = None, issuer: Optional[List[int]] = None, expiry_date: Optional[List[Type[FilterWarrantExpiryDate]]] = None, price_type: Optional[List[Type[FilterWarrantInOutBoundsType]]] = None, status: Optional[List[Type[WarrantStatus]]] = None) -> Awaitable[List[WarrantInfo]]
Get warrant list with optional filters. Returns an awaitable that resolves to warrant info list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, (
AsyncQuoteContext,
Config,
WarrantSortBy,
SortOrderType,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.warrant_list(
"700.HK",
WarrantSortBy.LastDone,
SortOrderType.Ascending,
)
print(resp)
asyncio.run(main())
trading_session
trading_session() -> Awaitable[List[MarketTradingSession]]
Get trading session of the day. Returns an awaitable that resolves to market trading session list.
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.trading_session()
print(resp)
asyncio.run(main())
trading_days
trading_days(market: Type[Market], begin: date, end: date) -> Awaitable[MarketTradingDays]
Get trading days in the given market and date range. Returns an awaitable (interval must be less than one month).
| Parameters: |
|---|
Examples:
::
import asyncio
from datetime import date
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, Market
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.trading_days(
Market.HK,
date(2022, 1, 1),
date(2022, 2, 1),
)
print(resp)
asyncio.run(main())
capital_flow
capital_flow(symbol: str) -> Awaitable[List[CapitalFlowLine]]
Get capital flow intraday. Returns an awaitable that resolves to capital flow line list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.capital_flow("700.HK")
print(resp)
asyncio.run(main())
capital_distribution
capital_distribution(symbol: str) -> Awaitable[CapitalDistributionResponse]
Get capital distribution. Returns an awaitable that resolves to capital distribution response.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.capital_distribution("700.HK")
print(resp)
asyncio.run(main())
calc_indexes
calc_indexes(symbols: List[str], indexes: List[Type[CalcIndex]]) -> Awaitable[List[SecurityCalcIndex]]
Get calc indexes for symbols. Returns an awaitable that resolves to security calc index list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, CalcIndex
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.calc_indexes(
["700.HK", "APPL.US"],
[CalcIndex.LastDone, CalcIndex.ChangeRate],
)
print(resp)
asyncio.run(main())
watchlist
watchlist() -> Awaitable[List[WatchlistGroup]]
Get watch list. Returns an awaitable that resolves to watchlist group list.
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.watchlist()
print(resp)
asyncio.run(main())
create_watchlist_group
create_watchlist_group(name: str, securities: Optional[List[str]] = None) -> Awaitable[int]
Create watchlist group. Returns an awaitable that resolves to group ID.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
group_id = await ctx.create_watchlist_group(
name="Watchlist1",
securities=["700.HK", "AAPL.US"],
)
print(group_id)
asyncio.run(main())
delete_watchlist_group
delete_watchlist_group(id: int, purge: bool = False) -> Awaitable[None]
Delete watchlist group. Returns an awaitable.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.delete_watchlist_group(10086)
asyncio.run(main())
update_watchlist_group
update_watchlist_group(id: int, name: Optional[str] = None, securities: Optional[List[str]] = None, mode: Optional[Type[SecuritiesUpdateMode]] = None) -> Awaitable[None]
Update watchlist group. Returns an awaitable.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SecuritiesUpdateMode
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.update_watchlist_group(
10086,
name="Watchlist2",
securities=["700.HK", "AAPL.US"],
mode=SecuritiesUpdateMode.Replace,
)
asyncio.run(main())
update_pinned
update_pinned(mode: Type[PinnedMode], symbols: List[str]) -> Awaitable[None]
Pin or unpin watchlist securities. Returns an awaitable.
| Parameters: |
|
|---|
security_list
security_list(market: Type[Market], category: Optional[Type[SecurityListCategory]] = None) -> Awaitable[List[Security]]
Get security list. Returns an awaitable that resolves to security list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, Market, SecurityListCategory
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.security_list(
Market.HK,
SecurityListCategory.Overnight,
)
print(resp)
asyncio.run(main())
market_temperature
market_temperature(market: Type[Market]) -> Awaitable[MarketTemperature]
Get current market temperature. Returns an awaitable that resolves to market temperature.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, Market
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.market_temperature(Market.HK)
print(resp)
asyncio.run(main())
history_market_temperature
history_market_temperature(market: Type[Market], start_date: date, end_date: date) -> Awaitable[HistoryMarketTemperatureResponse]
Get historical market temperature. Returns an awaitable that resolves to history market temperature response.
| Parameters: |
|---|
Examples:
::
import asyncio
import datetime
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, Market
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.history_market_temperature(
Market.HK,
datetime.date(2023, 1, 1),
datetime.date(2023, 1, 31),
)
print(resp)
asyncio.run(main())
realtime_quote
realtime_quote(symbols: List[str]) -> Awaitable[List[RealtimeQuote]]
Get real-time quote of subscribed symbols from local storage. Returns an awaitable that resolves to realtime quote list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SubType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
await asyncio.sleep(5)
resp = await ctx.realtime_quote(["700.HK", "AAPL.US"])
print(resp)
asyncio.run(main())
realtime_depth
realtime_depth(symbol: str) -> Awaitable[SecurityDepth]
Get real-time depth of subscribed symbol from local storage. Returns an awaitable that resolves to security depth.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SubType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Depth])
await asyncio.sleep(5)
resp = await ctx.realtime_depth("700.HK")
print(resp)
asyncio.run(main())
realtime_brokers
realtime_brokers(symbol: str) -> Awaitable[SecurityBrokers]
Get real-time brokers of subscribed symbol from local storage. Returns an awaitable that resolves to security brokers.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SubType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Brokers])
await asyncio.sleep(5)
resp = await ctx.realtime_brokers("700.HK")
print(resp)
asyncio.run(main())
realtime_trades
realtime_trades(symbol: str, count: int = 500) -> Awaitable[List[Trade]]
Get real-time trades of subscribed symbol from local storage. Returns an awaitable that resolves to trade list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, SubType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Trade])
await asyncio.sleep(5)
resp = await ctx.realtime_trades("700.HK", 10)
print(resp)
asyncio.run(main())
realtime_candlesticks
realtime_candlesticks(symbol: str, period: Type[Period], count: int = 500) -> Awaitable[List[Candlestick]]
Get real-time candlesticks of subscribed symbol from local storage. Returns an awaitable that resolves to candlestick list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncQuoteContext, Config, Period
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe_candlesticks(
"AAPL.US",
Period.Min_1,
)
await asyncio.sleep(5)
resp = await ctx.realtime_candlesticks(
"AAPL.US",
Period.Min_1,
10,
)
print(resp)
asyncio.run(main())
short_positions
short_positions(symbol: str, count: int = 20) -> Awaitable[ShortPositionsResponse]
Get short interest / position data for a US or HK security. Returns awaitable.
Market is inferred from the symbol suffix: .HK → HK endpoint,
otherwise US endpoint.
| Parameters: |
|---|
| Returns: |
|
|---|
short_trades
short_trades(symbol: str, count: int = 20) -> Awaitable[ShortTradesResponse]
Get short trade records for a HK or US security. Returns awaitable.
Market is inferred from the symbol suffix: .HK → HK endpoint,
otherwise US endpoint.
| Parameters: |
|---|
| Returns: |
|
|---|
OrderSide
OrderType
Order type
Unknown
LO
ELO
MO
AO
ALO
ODD
LIT
MIT
TSLPAMT
TSLPPCT
TSMAMT
TSMPCT
SLO
OrderStatus
Order status
Unknown
NotReported
ReplacedNotReported
ProtectedNotReported
VarietiesNotReported
Filled
WaitToNew
New
WaitToReplace
PendingReplace
Replaced
PartialFilled
WaitToCancel
PendingCancel
Rejected
Canceled
Expired
PartialWithdrawal
OrderTag
Order tag
Unknown
Normal
LongTerm
Grey
MarginCall
Offline
Creditor
Debtor
NonExercise
AllocatedSub
TriggerStatus
Trigger status
Unknown
Deactive
Active
Released
Execution
Execution
order_id
instance-attribute
order_id: str
Order ID
trade_id
instance-attribute
trade_id: str
Execution ID
symbol
instance-attribute
symbol: str
Security code
trade_done_at
instance-attribute
trade_done_at: datetime
Trade done time
quantity
instance-attribute
quantity: Decimal
Executed quantity
price
instance-attribute
price: Decimal
Executed price
PushOrderChanged
Order changed message
side
instance-attribute
side: Type[OrderSide]
Order side
stock_name
instance-attribute
stock_name: str
Stock name
submitted_quantity
instance-attribute
submitted_quantity: Decimal
Submitted quantity
symbol
instance-attribute
symbol: str
Order symbol
order_type
instance-attribute
order_type: Type[OrderType]
Order type
submitted_price
instance-attribute
submitted_price: Decimal
Submitted price
executed_quantity
instance-attribute
executed_quantity: Decimal
Executed quantity
executed_price
instance-attribute
executed_price: Optional[Decimal]
Executed price
order_id
instance-attribute
order_id: str
Order ID
currency
instance-attribute
currency: str
Currency
status
instance-attribute
status: Type[OrderStatus]
Order status
submitted_at
instance-attribute
submitted_at: datetime
Submitted time
updated_at
instance-attribute
updated_at: datetime
Last updated time
trigger_price
instance-attribute
trigger_price: Optional[Decimal]
Order trigger price
msg
instance-attribute
msg: str
Rejected message or remark
tag
instance-attribute
tag: Type[OrderTag]
Order tag
trigger_status
instance-attribute
trigger_status: Optional[Type[TriggerStatus]]
Conditional order trigger status
trigger_at
instance-attribute
trigger_at: Optional[datetime]
Conditional order trigger time
trailing_amount
instance-attribute
trailing_amount: Optional[Decimal]
Trailing amount
trailing_percent
instance-attribute
trailing_percent: Optional[Decimal]
Trailing percent
limit_offset
instance-attribute
limit_offset: Optional[Decimal]
Limit offset amount
account_no
instance-attribute
account_no: str
Account no
last_share
instance-attribute
last_share: Optional[Decimal]
Last share
last_price
instance-attribute
last_price: Optional[Decimal]
Last price
remark
instance-attribute
remark: str
Remark message
TimeInForceType
Time in force type
Unknown
Day
GoodTilCanceled
GoodTilDate
OutsideRTH
Enable or disable outside regular trading hours
Unknown
RTHOnly
AnyTime
Overnight
Order
Order
order_id
instance-attribute
order_id: str
Order ID
status
instance-attribute
status: Type[OrderStatus]
Order status
stock_name
instance-attribute
stock_name: str
Stock name
quantity
instance-attribute
quantity: Decimal
Submitted quantity
executed_quantity
instance-attribute
executed_quantity: Decimal
Executed quantity
price
instance-attribute
price: Optional[Decimal]
Submitted price
executed_price
instance-attribute
executed_price: Optional[Decimal]
Executed price
submitted_at
instance-attribute
submitted_at: datetime
Submitted time
side
instance-attribute
side: Type[OrderSide]
Order side
symbol
instance-attribute
symbol: str
Security code
order_type
instance-attribute
order_type: Type[OrderType]
Order type
last_done
instance-attribute
last_done: Optional[Decimal]
Last done
trigger_price
instance-attribute
trigger_price: Optional[Decimal]
LIT / MIT Order Trigger Price
msg
instance-attribute
msg: str
Rejected Message or remark
tag
instance-attribute
tag: Type[OrderTag]
Order tag
time_in_force
instance-attribute
time_in_force: Type[TimeInForceType]
Time in force type
expire_date
instance-attribute
expire_date: Optional[date]
Long term order expire date
updated_at
instance-attribute
updated_at: Optional[datetime]
Last updated time
trigger_at
instance-attribute
trigger_at: Optional[datetime]
Conditional order trigger time
trailing_amount
instance-attribute
trailing_amount: Optional[Decimal]
TSMAMT / TSLPAMT order trailing amount
trailing_percent
instance-attribute
trailing_percent: Optional[Decimal]
TSMPCT / TSLPPCT order trailing percent
limit_offset
instance-attribute
limit_offset: Optional[Decimal]
TSLPAMT / TSLPPCT order limit offset amount
trigger_status
instance-attribute
trigger_status: Optional[Type[TriggerStatus]]
Conditional order trigger status
currency
instance-attribute
currency: str
Currency
outside_rth
instance-attribute
outside_rth: Optional[Type[OutsideRTH]]
Enable or disable outside regular trading hours
limit_depth_level
instance-attribute
limit_depth_level: Optional[int]
Limit depth level
trigger_count
instance-attribute
trigger_count: Optional[int]
Trigger count
monitor_price
instance-attribute
monitor_price: Optional[Decimal]
Monitor price
remark
instance-attribute
remark: str
Remark
CommissionFreeStatus
Commission-free Status
Unknown
None_
Calculated
Pending
Ready
DeductionStatus
Deduction status
Unknown
None_
NoData
Pending
Done
ChargeCategoryCode
Charge category code
Unknown
Broker
Third
OrderHistoryDetail
Order history detail
price
instance-attribute
price: Decimal
Executed price for executed orders, submitted price for expired, canceled, rejected orders, etc.
quantity
instance-attribute
quantity: Decimal
Executed quantity for executed orders, remaining quantity for expired, canceled, rejected orders, etc.
status
instance-attribute
status: Type[OrderStatus]
Order status
msg
instance-attribute
msg: str
Execution or error message
time
instance-attribute
time: datetime
Occurrence time
OrderChargeFee
Order charge fee
code
instance-attribute
code: str
Charge code
name
instance-attribute
name: str
Charge name
amount
instance-attribute
amount: Decimal
Charge amount
currency
instance-attribute
currency: str
Charge currency
OrderChargeItem
Order charge item
code
instance-attribute
code: Type[ChargeCategoryCode]
Charge category code
name
instance-attribute
name: str
Charge category name
fees
instance-attribute
fees: List[OrderChargeFee]
Charge details
OrderChargeDetail
Order charge detail
total_amount
instance-attribute
total_amount: Decimal
Total charges amount
currency
instance-attribute
currency: str
Settlement currency
items
instance-attribute
items: List[OrderChargeItem]
Order charge items
OrderDetail
Order detail
order_id
instance-attribute
order_id: str
Order ID
status
instance-attribute
status: Type[OrderStatus]
Order status
stock_name
instance-attribute
stock_name: str
Stock name
quantity
instance-attribute
quantity: Decimal
Submitted quantity
executed_quantity
instance-attribute
executed_quantity: Decimal
Executed quantity
price
instance-attribute
price: Optional[Decimal]
Submitted price
executed_price
instance-attribute
executed_price: Optional[Decimal]
Executed price
submitted_at
instance-attribute
submitted_at: datetime
Submitted time
side
instance-attribute
side: Type[OrderSide]
Order side
symbol
instance-attribute
symbol: str
Security code
order_type
instance-attribute
order_type: Type[OrderType]
Order type
last_done
instance-attribute
last_done: Optional[Decimal]
Last done
trigger_price
instance-attribute
trigger_price: Optional[Decimal]
LIT / MIT Order Trigger Price
msg
instance-attribute
msg: str
Rejected Message or remark
tag
instance-attribute
tag: Type[OrderTag]
Order tag
time_in_force
instance-attribute
time_in_force: Type[TimeInForceType]
Time in force type
expire_date
instance-attribute
expire_date: Optional[date]
Long term order expire date
updated_at
instance-attribute
updated_at: Optional[datetime]
Last updated time
trigger_at
instance-attribute
trigger_at: Optional[datetime]
Conditional order trigger time
trailing_amount
instance-attribute
trailing_amount: Optional[Decimal]
TSMAMT / TSLPAMT order trailing amount
trailing_percent
instance-attribute
trailing_percent: Optional[Decimal]
TSMPCT / TSLPPCT order trailing percent
limit_offset
instance-attribute
limit_offset: Optional[Decimal]
TSLPAMT / TSLPPCT order limit offset amount
trigger_status
instance-attribute
trigger_status: Optional[Type[TriggerStatus]]
Conditional order trigger status
currency
instance-attribute
currency: str
Currency
outside_rth
instance-attribute
outside_rth: Optional[Type[OutsideRTH]]
Enable or disable outside regular trading hours
limit_depth_level
instance-attribute
limit_depth_level: Optional[int]
Limit depth level
trigger_count
instance-attribute
trigger_count: Optional[int]
Trigger count
monitor_price
instance-attribute
monitor_price: Optional[Decimal]
Monitor price
remark
instance-attribute
remark: str
Remark
free_status
instance-attribute
free_status: Type[CommissionFreeStatus]
Commission-free Status
free_amount
instance-attribute
free_amount: Optional[Decimal]
Commission-free amount
free_currency
instance-attribute
free_currency: Optional[str]
Commission-free currency
deductions_status
instance-attribute
deductions_status: Type[DeductionStatus]
Deduction status
deductions_amount
instance-attribute
deductions_amount: Optional[Decimal]
Deduction amount
deductions_currency
instance-attribute
deductions_currency: Optional[str]
Deduction currency
platform_deducted_status
instance-attribute
platform_deducted_status: Type[DeductionStatus]
Platform fee deduction status
platform_deducted_amount
instance-attribute
platform_deducted_amount: Optional[Decimal]
Platform deduction amount
platform_deducted_currency
instance-attribute
platform_deducted_currency: Optional[str]
Platform deduction currency
history
instance-attribute
history: List[OrderHistoryDetail]
Order history details
charge_detail
instance-attribute
charge_detail: OrderChargeDetail
Order charges
SubmitOrderResponse
Response for submit order request
order_id
instance-attribute
order_id: str
Order id
CashInfo
CashInfo
withdraw_cash
instance-attribute
withdraw_cash: Decimal
Withdraw cash
available_cash
instance-attribute
available_cash: Decimal
Available cash
frozen_cash
instance-attribute
frozen_cash: Decimal
Frozen cash
settling_cash
instance-attribute
settling_cash: Decimal
Cash to be settled
currency
instance-attribute
currency: str
Currency
FrozenTransactionFee
currency
instance-attribute
currency: str
Currency
frozen_transaction_fee
instance-attribute
frozen_transaction_fee: Decimal
Frozen transaction fee
AccountBalance
Account balance
total_cash
instance-attribute
total_cash: Decimal
Total cash
max_finance_amount
instance-attribute
max_finance_amount: Decimal
Maximum financing amount
remaining_finance_amount
instance-attribute
remaining_finance_amount: Decimal
Remaining financing amount
risk_level
instance-attribute
risk_level: int
Risk control level
margin_call
instance-attribute
margin_call: Decimal
Margin call
currency
instance-attribute
currency: str
Currency
cash_infos
instance-attribute
cash_infos: List[CashInfo]
Cash details
net_assets
instance-attribute
net_assets: Decimal
Net assets
init_margin
instance-attribute
init_margin: Decimal
Initial margin
maintenance_margin
instance-attribute
maintenance_margin: Decimal
Maintenance margin
buy_power
instance-attribute
buy_power: Decimal
Buy power
frozen_transaction_fees
instance-attribute
frozen_transaction_fees: List[FrozenTransactionFee]
Frozen transaction fees
BalanceType
CashFlowDirection
Cash flow direction
Unknown
Out
In
CashFlow
Cash flow
transaction_flow_name
instance-attribute
transaction_flow_name: str
Cash flow name
direction
instance-attribute
direction: Type[CashFlowDirection]
Outflow direction
business_type
instance-attribute
business_type: Type[BalanceType]
Balance type
balance
instance-attribute
balance: Decimal
Cash amount
currency
instance-attribute
currency: str
Cash currency
business_time
instance-attribute
business_time: datetime
Business time
symbol
instance-attribute
symbol: Optional[str]
Associated Stock code information
description
instance-attribute
description: str
Cash flow description
FundPosition
Fund position
symbol
instance-attribute
symbol: str
Fund ISIN code
current_net_asset_value
instance-attribute
current_net_asset_value: Decimal
Current equity
net_asset_value_day
instance-attribute
net_asset_value_day: datetime
Current equity PyDecimal
symbol_name
instance-attribute
symbol_name: str
Fund name
currency
instance-attribute
currency: str
Currency
cost_net_asset_value
instance-attribute
cost_net_asset_value: Decimal
Net cost
holding_units
instance-attribute
holding_units: Decimal
Holding units
FundPositionChannel
Fund position channel
account_channel
instance-attribute
account_channel: str
Account type
positions
instance-attribute
positions: List[FundPosition]
Fund positions
FundPositionsResponse
Fund positions response
channels
instance-attribute
channels: List[FundPositionChannel]
Channels
StockPosition
Stock position
symbol
instance-attribute
symbol: str
Stock code
symbol_name
instance-attribute
symbol_name: str
Stock name
quantity
instance-attribute
quantity: Decimal
The number of holdings
available_quantity
instance-attribute
available_quantity: Decimal
Available quantity
currency
instance-attribute
currency: str
Currency
cost_price
instance-attribute
cost_price: Decimal
Cost Price(According to the client's choice of average purchase or diluted cost)
market
instance-attribute
market: Market
Market
init_quantity
instance-attribute
init_quantity: Optional[Decimal]
Initial position before market opening
StockPositionChannel
Stock position channel
account_channel
instance-attribute
account_channel: str
Account type
positions
instance-attribute
positions: List[StockPosition]
Stock positions
StockPositionsResponse
Stock positions response
channels
instance-attribute
channels: List[StockPositionChannel]
Channels
TopicType
Topic type
Private
MarginRatio
Margin ratio
im_factor
instance-attribute
im_factor: Decimal
Initial margin ratio
mm_factor
instance-attribute
mm_factor: Decimal
Maintain the initial margin ratio
fm_factor
instance-attribute
fm_factor: Decimal
Forced close-out margin ratio
EstimateMaxPurchaseQuantityResponse
Response for estimate maximum purchase quantity
cash_max_qty
instance-attribute
cash_max_qty: Decimal
Cash available quantity
margin_max_qty
instance-attribute
margin_max_qty: Decimal
Margin available quantity
TradeContext
Trade context
| Parameters: |
|
|---|
__init__
__init__(config: Config) -> None
set_on_order_changed
set_on_order_changed(callback: Callable[[PushOrderChanged], None]) -> None
Set order changed callback, after receiving the order changed event, it will call back to this function.
subscribe
subscribe(topics: List[Type[TopicType]]) -> None
Subscribe
| Parameters: |
|---|
Examples:
::
from time import sleep
from decimal import Decimal
from longbridge.openapi import OAuthBuilder, TradeContext, Config, OrderSide, OrderType, TimeInForceType, PushOrderChanged, TopicType
def on_order_changed(event: PushOrderChanged):
print(event)
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
ctx.set_on_order_changed(on_order_changed)
ctx.subscribe([TopicType.Private])
resp = ctx.submit_order(
side = OrderSide.Buy,
symbol = "700.HK",
order_type = OrderType.LO,
submitted_price = Decimal(50),
submitted_quantity = Decimal(200),
time_in_force = TimeInForceType.Day,
remark = "Hello from Python SDK",
)
print(resp)
sleep(5) # waiting for push event
unsubscribe
unsubscribe(topics: List[Type[TopicType]]) -> None
history_executions
history_executions(symbol: Optional[str] = None, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> List[Execution]
Get history executions
| Parameters: |
|---|
| Returns: |
|---|
Examples:
::
from datetime import datetime
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.history_executions(
symbol = "700.HK",
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
today_executions
today_executions(symbol: Optional[str] = None, order_id: Optional[str] = None) -> List[Execution]
Get today executions
| Parameters: |
|---|
| Returns: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.today_executions(symbol = "700.HK")
print(resp)
history_orders
history_orders(symbol: Optional[str] = None, status: Optional[List[Type[OrderStatus]]] = None, side: Optional[Type[OrderSide]] = None, market: Optional[Type[Market]] = None, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> List[Order]
Get history orders
| Parameters: |
|
|---|
| Returns: |
|---|
Examples:
::
from datetime import datetime
from longbridge.openapi import OAuthBuilder, TradeContext, Config, OrderStatus, OrderSide, Market
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.history_orders(
symbol = "700.HK",
status = [OrderStatus.Filled, OrderStatus.New],
side = OrderSide.Buy,
market = Market.HK,
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
today_orders
today_orders(symbol: Optional[str] = None, status: Optional[List[Type[OrderStatus]]] = None, side: Optional[Type[OrderSide]] = None, market: Optional[Type[Market]] = None, order_id: Optional[str] = None) -> List[Order]
Get today orders
| Parameters: |
|
|---|
| Returns: |
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config, OrderStatus, OrderSide, Market
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.today_orders(
symbol = "700.HK",
status = [OrderStatus.Filled, OrderStatus.New],
side = OrderSide.Buy,
market = Market.HK,
)
print(resp)
replace_order
replace_order(order_id: str, quantity: Decimal, price: Optional[Decimal] = None, trigger_price: Optional[Decimal] = None, limit_offset: Optional[Decimal] = None, trailing_amount: Optional[Decimal] = None, trailing_percent: Optional[Decimal] = None, limit_depth_level: Optional[int] = None, trigger_count: Optional[int] = None, monitor_price: Optional[Decimal] = None, remark: Optional[str] = None) -> None
Replace order
| Parameters: |
|
|---|
Examples:
::
from decimal import Decimal
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
ctx.replace_order(
order_id = "709043056541253632",
quantity = Decimal(100),
price = Decimal(100),
)
submit_order
submit_order(symbol: str, order_type: Type[OrderType], side: Type[OrderSide], submitted_quantity: Decimal, time_in_force: Type[TimeInForceType], submitted_price: Optional[Decimal] = None, trigger_price: Optional[Decimal] = None, limit_offset: Optional[Decimal] = None, trailing_amount: Optional[Decimal] = None, trailing_percent: Optional[Decimal] = None, expire_date: Optional[date] = None, outside_rth: Optional[Type[OutsideRTH]] = None, limit_depth_level: Optional[int] = None, trigger_count: Optional[int] = None, monitor_price: Optional[Decimal] = None, remark: Optional[str] = None) -> SubmitOrderResponse
Submit order
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from decimal import Decimal
from longbridge.openapi import OAuthBuilder, TradeContext, Config, OrderSide, OrderType, TimeInForceType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.submit_order(
side = OrderSide.Buy,
symbol = "700.HK",
order_type = OrderType.LO,
submitted_price = Decimal(50),
submitted_quantity = Decimal(200),
time_in_force = TimeInForceType.Day,
remark = "Hello from Python SDK",
)
print(resp)
cancel_order
cancel_order(order_id: str) -> None
Cancel order
| Parameters: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
ctx.cancel_order("709043056541253632")
account_balance
account_balance(currency: Optional[str] = None) -> List[AccountBalance]
Get account balance
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.account_balance()
print(resp)
cash_flow
cash_flow(start_at: datetime, end_at: datetime, business_type: Optional[Type[BalanceType]] = None, symbol: Optional[str] = None, page: Optional[int] = None, size: Optional[int] = None) -> List[CashFlow]
Get cash flow
| Parameters: |
|
|---|
| Returns: |
|---|
Examples:
::
from datetime import datetime
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.cash_flow(
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
fund_positions
fund_positions(symbols: Optional[List[str]] = None) -> FundPositionsResponse
Get fund positions
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.fund_positions()
print(resp)
stock_positions
stock_positions(symbols: Optional[List[str]] = None) -> StockPositionsResponse
Get stock positions
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.stock_positions()
print(resp)
margin_ratio
margin_ratio(symbol: str) -> MarginRatio
Get margin ratio
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.margin_ratio("700.HK")
print(resp)
order_detail
order_detail(order_id: str) -> OrderDetail
Get order detail
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.order_detail("701276261045858304")
print(resp)
estimate_max_purchase_quantity
estimate_max_purchase_quantity(symbol: str, order_type: Type[OrderType], side: Type[OrderSide], price: Optional[Decimal] = None, currency: Optional[str] = None, order_id: Optional[str] = None, fractional_shares: bool = False) -> EstimateMaxPurchaseQuantityResponse
Estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, TradeContext, Config, OrderType, OrderSide
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.estimate_max_purchase_quantity(
symbol = "700.HK",
order_type = OrderType.LO,
side = OrderSide.Buy,
)
print(resp)
AsyncTradeContext
Async trade context for use with asyncio. Create via AsyncTradeContext.create(config) and await inside asyncio.
Callbacks (set_on_order_changed) are set the same way as the sync TradeContext; all I/O methods return awaitables.
create
classmethod
create(config: Config, loop_: Optional[Any] = None) -> AsyncTradeContext
Create an async trade context.
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, Config, AsyncTradeContext
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.today_orders()
print(resp)
asyncio.run(main())
set_on_order_changed
set_on_order_changed(callback: Callable[[PushOrderChanged], None] | Callable[[PushOrderChanged], Coroutine[Any, Any, None]]) -> None
Set order changed callback; called when order changed event is received. Callback may be sync or async (async is scheduled on the event loop).
subscribe
subscribe(topics: List[Type[TopicType]]) -> Awaitable[None]
Subscribe to topics (e.g. TopicType.Private). Returns an awaitable; must be awaited in asyncio.
| Parameters: |
|---|
Examples:
::
import asyncio
from decimal import Decimal
from longbridge.openapi import OAuthBuilder, (
AsyncTradeContext,
Config,
OrderSide,
OrderType,
TimeInForceType,
PushOrderChanged,
TopicType,
)
def on_order_changed(event: PushOrderChanged):
print(event)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
ctx.set_on_order_changed(on_order_changed)
await ctx.subscribe([TopicType.Private])
resp = await ctx.submit_order(
symbol="700.HK",
order_type=OrderType.LO,
side=OrderSide.Buy,
submitted_quantity=Decimal(200),
time_in_force=TimeInForceType.Day,
submitted_price=Decimal(50),
remark="Hello from Python SDK",
)
print(resp)
await asyncio.sleep(5)
asyncio.run(main())
unsubscribe
unsubscribe(topics: List[Type[TopicType]]) -> Awaitable[None]
Unsubscribe from topics. Returns an awaitable.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config, TopicType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
await ctx.subscribe([TopicType.Private])
await ctx.unsubscribe([TopicType.Private])
asyncio.run(main())
history_executions
history_executions(symbol: Optional[str] = None, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> Awaitable[List[Execution]]
Get history executions. Optional filters: symbol, start_at, end_at. Returns an awaitable that resolves to execution list.
| Parameters: |
|---|
Examples:
::
import asyncio
import datetime
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.history_executions(
symbol="700.HK",
start_at=datetime.datetime(2022, 5, 9),
end_at=datetime.datetime(2022, 5, 12),
)
print(resp)
asyncio.run(main())
today_executions
today_executions(symbol: Optional[str] = None, order_id: Optional[str] = None) -> Awaitable[List[Execution]]
Get today executions. Optional filters: symbol, order_id. Returns an awaitable that resolves to execution list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.today_executions(symbol="700.HK")
print(resp)
asyncio.run(main())
history_orders
history_orders(symbol: Optional[str] = None, status: Optional[List[Type[OrderStatus]]] = None, side: Optional[Type[OrderSide]] = None, market: Optional[Type[Market]] = None, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> Awaitable[List[Order]]
Get history orders with optional filters. Returns an awaitable that resolves to order list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
import datetime
from longbridge.openapi import OAuthBuilder, (
AsyncTradeContext,
Config,
OrderStatus,
OrderSide,
Market,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.history_orders(
symbol="700.HK",
status=[OrderStatus.Filled, OrderStatus.New],
side=OrderSide.Buy,
market=Market.HK,
start_at=datetime.datetime(2022, 5, 9),
end_at=datetime.datetime(2022, 5, 12),
)
print(resp)
asyncio.run(main())
today_orders
today_orders(symbol: Optional[str] = None, status: Optional[List[Type[OrderStatus]]] = None, side: Optional[Type[OrderSide]] = None, market: Optional[Type[Market]] = None, order_id: Optional[str] = None) -> Awaitable[List[Order]]
Get today orders with optional filters. Returns an awaitable that resolves to order list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, (
AsyncTradeContext,
Config,
OrderStatus,
OrderSide,
Market,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.today_orders(
symbol="700.HK",
status=[OrderStatus.Filled, OrderStatus.New],
side=OrderSide.Buy,
market=Market.HK,
)
print(resp)
asyncio.run(main())
replace_order
replace_order(order_id: str, quantity: Decimal, price: Optional[Decimal] = None, trigger_price: Optional[Decimal] = None, limit_offset: Optional[Decimal] = None, trailing_amount: Optional[Decimal] = None, trailing_percent: Optional[Decimal] = None, limit_depth_level: Optional[int] = None, trigger_count: Optional[int] = None, monitor_price: Optional[Decimal] = None, remark: Optional[str] = None) -> Awaitable[None]
Replace order. Returns an awaitable. Same parameters as sync TradeContext.replace_order.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from decimal import Decimal
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
await ctx.replace_order(
order_id="709043056541253632",
quantity=Decimal(100),
price=Decimal(100),
)
asyncio.run(main())
submit_order
submit_order(symbol: str, order_type: Type[OrderType], side: Type[OrderSide], submitted_quantity: Decimal, time_in_force: Type[TimeInForceType], submitted_price: Optional[Decimal] = None, trigger_price: Optional[Decimal] = None, limit_offset: Optional[Decimal] = None, trailing_amount: Optional[Decimal] = None, trailing_percent: Optional[Decimal] = None, expire_date: Optional[date] = None, outside_rth: Optional[Type[OutsideRTH]] = None, limit_depth_level: Optional[int] = None, trigger_count: Optional[int] = None, monitor_price: Optional[Decimal] = None, remark: Optional[str] = None) -> Awaitable[SubmitOrderResponse]
Submit order. Returns an awaitable that resolves to SubmitOrderResponse. Same parameters as sync TradeContext.submit_order.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from decimal import Decimal
from longbridge.openapi import OAuthBuilder, (
AsyncTradeContext,
Config,
OrderSide,
OrderType,
TimeInForceType,
)
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.submit_order(
symbol="700.HK",
order_type=OrderType.LO,
side=OrderSide.Buy,
submitted_quantity=Decimal(500),
time_in_force=TimeInForceType.Day,
submitted_price=Decimal(50),
remark="Hello from Python SDK",
)
print(resp)
asyncio.run(main())
cancel_order
cancel_order(order_id: str) -> Awaitable[None]
Cancel order by order_id. Returns an awaitable.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
await ctx.cancel_order("709043056541253632")
asyncio.run(main())
account_balance
account_balance(currency: Optional[str] = None) -> Awaitable[List[AccountBalance]]
Get account balance. Optional currency filter. Returns an awaitable that resolves to account balance list.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.account_balance()
print(resp)
asyncio.run(main())
cash_flow
cash_flow(start_at: datetime, end_at: datetime, business_type: Optional[Type[BalanceType]] = None, symbol: Optional[str] = None, page: Optional[int] = None, size: Optional[int] = None) -> Awaitable[List[CashFlow]]
Get cash flow. Required: start_at, end_at. Optional: business_type, symbol, page, size. Returns an awaitable that resolves to cash flow list.
| Parameters: |
|
|---|
Examples:
::
import asyncio
import datetime
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.cash_flow(
start_at=datetime.datetime(2022, 5, 9),
end_at=datetime.datetime(2022, 5, 12),
)
print(resp)
asyncio.run(main())
fund_positions
fund_positions(symbols: Optional[List[str]] = None) -> Awaitable[FundPositionsResponse]
Get fund positions. Optional filter: symbols. Returns an awaitable that resolves to fund positions response.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.fund_positions()
print(resp)
asyncio.run(main())
stock_positions
stock_positions(symbols: Optional[List[str]] = None) -> Awaitable[StockPositionsResponse]
Get stock positions. Optional filter: symbols. Returns an awaitable that resolves to stock positions response.
| Parameters: |
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.stock_positions()
print(resp)
asyncio.run(main())
margin_ratio
margin_ratio(symbol: str) -> Awaitable[MarginRatio]
Get margin ratio for symbol. Returns an awaitable that resolves to margin ratio.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.margin_ratio("700.HK")
print(resp)
asyncio.run(main())
order_detail
order_detail(order_id: str) -> Awaitable[OrderDetail]
Get order detail by order_id. Returns an awaitable that resolves to order detail.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.order_detail("701276261045858304")
print(resp)
asyncio.run(main())
estimate_max_purchase_quantity
estimate_max_purchase_quantity(symbol: str, order_type: Type[OrderType], side: Type[OrderSide], price: Optional[Decimal] = None, currency: Optional[str] = None, order_id: Optional[str] = None, fractional_shares: bool = False) -> Awaitable[EstimateMaxPurchaseQuantityResponse]
Estimate maximum purchase quantity. Returns an awaitable that resolves to estimate response. order_id required when estimating for replace order.
| Parameters: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncTradeContext, Config, OrderType, OrderSide
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.estimate_max_purchase_quantity(
symbol="700.HK",
order_type=OrderType.LO,
side=OrderSide.Buy,
)
print(resp)
asyncio.run(main())
StatementType
Statement type
Daily
Monthly
StatementItem
Statement item
dt
instance-attribute
dt: int
Statement date (integer, e.g. 20250301)
file_key
instance-attribute
file_key: str
File key used to request the download URL
GetStatementListResponse
Response for get statement list
list
instance-attribute
list: List[StatementItem]
List of statement items
GetStatementResponse
Response for get statement download URL
url
instance-attribute
url: str
Presigned download URL
AssetContext
Asset context
| Parameters: |
|
|---|
__init__
__init__(config: Config) -> None
statements
statements(statement_type: Type[StatementType], start_date: int = 1, limit: int = 20) -> GetStatementListResponse
Get statement data list
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, AssetContext, Config, StatementType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AssetContext(config)
resp = ctx.statements(StatementType.Daily)
for item in resp.list:
print(item.dt, item.file_key)
statement_download_url
statement_download_url(file_key: str) -> GetStatementResponse
Get statement data download URL
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, AssetContext, Config, StatementType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AssetContext(config)
resp = ctx.statements(StatementType.Daily)
if resp.list:
url_resp = ctx.statement_download_url(resp.list[0].file_key)
print(url_resp.url)
AsyncAssetContext
Async asset context for use with asyncio. Create via AsyncAssetContext.create(config) and await inside asyncio.
All I/O methods return awaitables.
create
classmethod
create(config: Config) -> AsyncAssetContext
Create an async asset context.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, Config, AsyncAssetContext, StatementType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncAssetContext.create(config)
resp = await ctx.statements(StatementType.Daily)
for item in resp.list:
print(item.dt, item.file_key)
asyncio.run(main())
statements
statements(statement_type: Type[StatementType], start_date: int = 1, limit: int = 20) -> Awaitable[GetStatementListResponse]
Get statement data list. Returns an awaitable.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, Config, AsyncAssetContext, StatementType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncAssetContext.create(config)
resp = await ctx.statements(StatementType.Daily, limit=5)
for item in resp.list:
print(item.dt, item.file_key)
asyncio.run(main())
statement_download_url
statement_download_url(file_key: str) -> Awaitable[GetStatementResponse]
Get statement data download URL. Returns an awaitable.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, Config, AsyncAssetContext, StatementType
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncAssetContext.create(config)
resp = await ctx.statements(StatementType.Daily)
if resp.list:
url_resp = await ctx.statement_download_url(resp.list[0].file_key)
print(url_resp.url)
asyncio.run(main())
TopicAuthor
Topic author
member_id
instance-attribute
member_id: str
Member ID
name
instance-attribute
name: str
Display name
avatar
instance-attribute
avatar: str
Avatar URL
TopicImage
Topic image
url
instance-attribute
url: str
Original image URL
sm
instance-attribute
sm: str
Small thumbnail URL
lg
instance-attribute
lg: str
Large image URL
OwnedTopic
Topic created by the current authenticated user
id
instance-attribute
id: str
Topic ID
title
instance-attribute
title: str
Title
description
instance-attribute
description: str
Plain text excerpt
body
instance-attribute
body: str
Markdown body
author
instance-attribute
author: TopicAuthor
Author
tickers
instance-attribute
tickers: List[str]
Related stock tickers
hashtags
instance-attribute
hashtags: List[str]
Hashtag names
images
instance-attribute
images: List[TopicImage]
Images
likes_count
instance-attribute
likes_count: int
Likes count
comments_count
instance-attribute
comments_count: int
Comments count
views_count
instance-attribute
views_count: int
Views count
shares_count
instance-attribute
shares_count: int
Shares count
topic_type
instance-attribute
topic_type: str
Content type: "article" or "post"
detail_url
instance-attribute
detail_url: str
URL to the full topic page
created_at
instance-attribute
created_at: datetime
Created time
updated_at
instance-attribute
updated_at: datetime
Updated time
TopicReply
A reply on a topic
id
instance-attribute
id: str
Reply ID
topic_id
instance-attribute
topic_id: str
Topic ID this reply belongs to
body
instance-attribute
body: str
Reply body (plain text)
reply_to_id
instance-attribute
reply_to_id: str
ID of the parent reply ("0" means top-level)
author
instance-attribute
author: TopicAuthor
Author info
images
instance-attribute
images: List[TopicImage]
Attached images
likes_count
instance-attribute
likes_count: int
Likes count
comments_count
instance-attribute
comments_count: int
Nested replies count
created_at
instance-attribute
created_at: datetime
Created time
ContentContext
Content context
| Parameters: |
|
|---|
__init__
__init__(config: Config) -> None
my_topics
my_topics(page: Optional[int] = None, size: Optional[int] = None, topic_type: Optional[str] = None) -> List[OwnedTopic]
Get topics created by the current authenticated user
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, ContentContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
topics = ctx.my_topics(size=20)
for t in topics:
print(t.id, t.title)
create_topic
create_topic(title: str, body: str, topic_type: Optional[str] = None, tickers: Optional[List[str]] = None, hashtags: Optional[List[str]] = None) -> str
Create a new community topic
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, ContentContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
topic_id = ctx.create_topic(
title="My Article",
body="Hello world",
topic_type="article",
tickers=["700.HK"],
)
print(topic_id)
topics
topics(symbol: str) -> List[TopicItem]
Get discussion topics list for a symbol
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, ContentContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
topics = ctx.topics("700.HK")
for t in topics:
print(t.id, t.title)
news
news(symbol: str) -> List[NewsItem]
Get news list for a symbol
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, ContentContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
news = ctx.news("700.HK")
for n in news:
print(n.id, n.title)
topic_detail
topic_detail(id: str) -> OwnedTopic
Get full details of a topic by its ID
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, ContentContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
topic = ctx.topic_detail("123456")
print(topic.title, topic.body)
list_topic_replies
list_topic_replies(topic_id: str, page: Optional[int] = None, size: Optional[int] = None) -> List[TopicReply]
List replies on a topic
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, ContentContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
replies = ctx.list_topic_replies("123456")
for r in replies:
print(r.id, r.body)
create_topic_reply
create_topic_reply(topic_id: str, body: str, reply_to_id: Optional[str] = None) -> TopicReply
Post a reply to a community topic
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
from longbridge.openapi import OAuthBuilder, ContentContext, Config
oauth = OAuthBuilder("your-client-id").build(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
reply = ctx.create_topic_reply("123456", "Great post!")
print(reply.id)
AsyncContentContext
Async content context. Create via AsyncContentContext.create(config) and
await inside asyncio. All I/O methods return awaitables.
create
classmethod
create(config: Config) -> AsyncContentContext
my_topics
async
my_topics(page: Optional[int] = None, size: Optional[int] = None, topic_type: Optional[str] = None) -> List[OwnedTopic]
Get topics created by the current authenticated user
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncContentContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
topics = await ctx.my_topics(size=20)
for t in topics:
print(t.id, t.title)
asyncio.run(main())
create_topic
async
create_topic(title: str, body: str, topic_type: Optional[str] = None, tickers: Optional[List[str]] = None, hashtags: Optional[List[str]] = None) -> str
Create a new community topic
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncContentContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
topic_id = await ctx.create_topic(
title="My Article",
body="Hello world",
topic_type="article",
tickers=["700.HK"],
)
print(topic_id)
asyncio.run(main())
topics
async
topics(symbol: str) -> List[TopicItem]
Get discussion topics list for a symbol
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncContentContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
topics = await ctx.topics("700.HK")
for t in topics:
print(t.id, t.title)
asyncio.run(main())
news
async
news(symbol: str) -> List[NewsItem]
Get news list for a symbol
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncContentContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
news = await ctx.news("700.HK")
for n in news:
print(n.id, n.title)
asyncio.run(main())
topic_detail
async
topic_detail(id: str) -> OwnedTopic
Get full details of a topic by its ID
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncContentContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
topic = await ctx.topic_detail("123456")
print(topic.title, topic.body)
asyncio.run(main())
list_topic_replies
async
list_topic_replies(topic_id: str, page: Optional[int] = None, size: Optional[int] = None) -> List[TopicReply]
List replies on a topic
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncContentContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
replies = await ctx.list_topic_replies("123456")
for r in replies:
print(r.id, r.body)
asyncio.run(main())
create_topic_reply
async
create_topic_reply(topic_id: str, body: str, reply_to_id: Optional[str] = None) -> TopicReply
Post a reply to a community topic
| Parameters: |
|---|
| Returns: |
|
|---|
Examples:
::
import asyncio
from longbridge.openapi import OAuthBuilder, AsyncContentContext, Config
async def main():
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print("Visit:", url)
)
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
reply = await ctx.create_topic_reply("123456", "Great post!")
print(reply.id)
asyncio.run(main())
FinancialReports
Financial reports response.
list contains raw nested data keyed by report kind
("IS", "BS", "CF").
list
instance-attribute
list: object
Raw financial data dict (IS/BS/CF indicators)
DividendItem
One dividend or distribution event.
symbol
instance-attribute
symbol: str
Security symbol, e.g. "700.HK"
id
instance-attribute
id: str
Internal record ID
desc
instance-attribute
desc: str
Human-readable description, e.g. "每股派息 5.3 HKD"
record_date
instance-attribute
record_date: str
Record / book-close date
ex_date
instance-attribute
ex_date: str
Ex-dividend date
payment_date
instance-attribute
payment_date: str
Payment date
DividendList
Dividend history response.
list
instance-attribute
list: list[DividendItem]
List of dividend events
RatingEvaluate
Analyst rating distribution counts.
buy
instance-attribute
buy: int
Number of Buy ratings
over
instance-attribute
over: int
Number of Strong Buy / Outperform ratings
hold
instance-attribute
hold: int
Number of Hold ratings
under
instance-attribute
under: int
Number of Underperform ratings
sell
instance-attribute
sell: int
Number of Sell ratings
no_opinion
instance-attribute
no_opinion: int
Number of No Opinion ratings
total
instance-attribute
total: int
Total analyst count
start_date
instance-attribute
start_date: str
Window start (unix timestamp string)
end_date
instance-attribute
end_date: str
Window end (unix timestamp string)
RatingTarget
Analyst target price range.
highest_price
instance-attribute
highest_price: str
Highest price target
lowest_price
instance-attribute
lowest_price: str
Lowest price target
prev_close
instance-attribute
prev_close: str
Previous close price
start_date
instance-attribute
start_date: str
Window start
end_date
instance-attribute
end_date: str
Window end
InstitutionRatingLatest
Latest analyst rating snapshot.
evaluate
instance-attribute
evaluate: RatingEvaluate
Rating distribution counts
target
instance-attribute
target: RatingTarget
Target price range
industry_id
instance-attribute
industry_id: int
Industry classification ID
industry_name
instance-attribute
industry_name: str
Industry name
industry_rank
instance-attribute
industry_rank: int
Rank within the industry (1 = highest)
industry_total
instance-attribute
industry_total: int
Total securities in the industry
industry_mean
instance-attribute
industry_mean: int
Mean analyst count in the industry
industry_median
instance-attribute
industry_median: int
Median analyst count in the industry
RatingSummaryEvaluate
Simplified rating distribution for consensus summary.
buy
instance-attribute
buy: int
Number of Buy ratings
date
instance-attribute
date: str
Date of the update
hold
instance-attribute
hold: int
Number of Hold ratings
sell
instance-attribute
sell: int
Number of Sell ratings
strong_buy
instance-attribute
strong_buy: int
Number of Strong Buy ratings
under
instance-attribute
under: int
Number of Underperform ratings
InstitutionRecommend
Institutional analyst recommendation.
Unknown
Bases: InstitutionRecommend
StrongBuy
Bases: InstitutionRecommend
Buy
Bases: InstitutionRecommend
Hold
Bases: InstitutionRecommend
Sell
Bases: InstitutionRecommend
StrongSell
Bases: InstitutionRecommend
Underperform
Bases: InstitutionRecommend
NoOpinion
Bases: InstitutionRecommend
InstitutionRatingSummary
Analyst consensus summary.
ccy_symbol
instance-attribute
ccy_symbol: str
Currency symbol, e.g. "HK$"
change
instance-attribute
change: str
Change vs previous period
evaluate
instance-attribute
evaluate: RatingSummaryEvaluate
Simplified rating distribution
recommend
instance-attribute
recommend: InstitutionRecommend
Consensus recommendation
target
instance-attribute
target: str
Consensus target price
updated_at
instance-attribute
updated_at: str
Last updated display string
InstitutionRating
Combined analyst rating response (latest + consensus summary).
latest
instance-attribute
latest: InstitutionRatingLatest
Latest rating snapshot
summary
instance-attribute
summary: InstitutionRatingSummary
Consensus summary
InstitutionRatingDetailEvaluateItem
One weekly rating distribution snapshot.
buy
instance-attribute
buy: int
Number of Buy ratings
date
instance-attribute
date: str
Date in "2021/05/14" format
hold
instance-attribute
hold: int
Number of Hold ratings
sell
instance-attribute
sell: int
Number of Sell ratings
strong_buy
instance-attribute
strong_buy: int
Number of Strong Buy / Outperform ratings
no_opinion
instance-attribute
no_opinion: int
Number of No Opinion ratings
under
instance-attribute
under: int
Number of Underperform ratings
InstitutionRatingDetailEvaluate
Historical rating distribution time-series.
list
instance-attribute
list: list[InstitutionRatingDetailEvaluateItem]
Weekly rating distribution snapshots
InstitutionRatingDetailTargetItem
One weekly target price snapshot.
avg_target
instance-attribute
avg_target: str
Average target price
date
instance-attribute
date: str
Date string
max_target
instance-attribute
max_target: str
Highest target price
min_target
instance-attribute
min_target: str
Lowest target price
meet
instance-attribute
meet: bool
Whether the stock price reached the target
price
instance-attribute
price: str
Actual stock price at this date
timestamp
instance-attribute
timestamp: str
Unix timestamp string
InstitutionRatingDetailTarget
Historical target price time-series.
data_percent
instance-attribute
data_percent: str | None
Prediction accuracy ratio, e.g. "0.9934" (may be None)
prediction_accuracy
instance-attribute
prediction_accuracy: str
Overall prediction accuracy percentage
updated_at
instance-attribute
updated_at: str
Last updated display string
list
instance-attribute
list: list[InstitutionRatingDetailTargetItem]
Weekly target price snapshots
InstitutionRatingDetail
Historical analyst rating detail response.
ccy_symbol
instance-attribute
ccy_symbol: str
Currency symbol
evaluate
instance-attribute
evaluate: InstitutionRatingDetailEvaluate
Historical rating distribution time-series
target
instance-attribute
target: InstitutionRatingDetailTarget
Historical target price time-series
ForecastEpsItem
One EPS forecast snapshot.
forecast_eps_median
instance-attribute
forecast_eps_median: str
Median EPS estimate
forecast_eps_mean
instance-attribute
forecast_eps_mean: str
Mean EPS estimate
forecast_eps_lowest
instance-attribute
forecast_eps_lowest: str
Lowest EPS estimate
forecast_eps_highest
instance-attribute
forecast_eps_highest: str
Highest EPS estimate
institution_total
instance-attribute
institution_total: int
Total number of forecasting institutions
institution_up
instance-attribute
institution_up: int
Institutions that raised their estimate
institution_down
instance-attribute
institution_down: int
Institutions that lowered their estimate
forecast_start_date
instance-attribute
forecast_start_date: datetime
Forecast window start
forecast_end_date
instance-attribute
forecast_end_date: datetime
Forecast window end
ForecastEps
EPS forecast response.
items
instance-attribute
items: list[ForecastEpsItem]
EPS forecast snapshots
ConsensusDetail
Consensus estimate for one financial metric.
key
instance-attribute
key: str
Metric key, e.g. "revenue"
name
instance-attribute
name: str
Display name
description
instance-attribute
description: str
Metric description
actual
instance-attribute
actual: str
Actual reported value (empty if not yet released)
estimate
instance-attribute
estimate: str
Consensus estimate value
comp_value
instance-attribute
comp_value: str
Actual minus estimate
comp_desc
instance-attribute
comp_desc: str
Beat/miss description
comp
instance-attribute
comp: str
Comparison result code
is_released
instance-attribute
is_released: bool
Whether actual results have been published
ConsensusReport
Consensus report for one fiscal period.
fiscal_year
instance-attribute
fiscal_year: int
Fiscal year, e.g. 2025
fiscal_period
instance-attribute
fiscal_period: str
Fiscal period code
period_text
instance-attribute
period_text: str
Human-readable period label, e.g. "Q4 FY2025"
details
instance-attribute
details: list[ConsensusDetail]
Per-metric consensus details
FinancialConsensus
Financial consensus estimates response.
list
instance-attribute
list: list[ConsensusReport]
Per-period consensus reports
current_index
instance-attribute
current_index: int
Index of the most recently released period
currency
instance-attribute
currency: str
Reporting currency
opt_periods
instance-attribute
opt_periods: list[str]
Available period types
current_period
instance-attribute
current_period: str
Currently returned period type
ValuationPoint
One valuation data point.
timestamp
instance-attribute
timestamp: datetime
Date of the data point
value
instance-attribute
value: str
Metric value
ValuationMetricData
Historical time-series for one valuation metric.
desc
instance-attribute
desc: str
Human-readable description with current value and percentile
high
instance-attribute
high: str
Historical high
low
instance-attribute
low: str
Historical low
median
instance-attribute
median: str
Historical median
list
instance-attribute
list: list[ValuationPoint]
Historical data points
ValuationMetricsData
Container for valuation metrics.
pe
instance-attribute
pe: ValuationMetricData | None
Price-to-Earnings ratio history
pb
instance-attribute
pb: ValuationMetricData | None
Price-to-Book ratio history
ps
instance-attribute
ps: ValuationMetricData | None
Price-to-Sales ratio history
dvd_yld
instance-attribute
dvd_yld: ValuationMetricData | None
Dividend yield history
ValuationData
Valuation metrics response.
metrics
instance-attribute
metrics: ValuationMetricsData
Valuation metrics (PE / PB / PS / dividend yield)
ValuationHistoryMetric
Historical data for one valuation metric.
desc
instance-attribute
desc: str
Human-readable description
high
instance-attribute
high: str
Historical high over the period
low
instance-attribute
low: str
Historical low over the period
median
instance-attribute
median: str
Historical median over the period
list
instance-attribute
list: list[ValuationPoint]
Historical data points
ValuationHistoryMetrics
Historical valuation metrics container.
pe
instance-attribute
pe: ValuationHistoryMetric | None
Price-to-Earnings history
pb
instance-attribute
pb: ValuationHistoryMetric | None
Price-to-Book history
ps
instance-attribute
ps: ValuationHistoryMetric | None
Price-to-Sales history
ValuationHistoryData
Historical valuation data container.
metrics
instance-attribute
metrics: ValuationHistoryMetrics
Historical metrics
ValuationHistoryResponse
Historical valuation response.
history
instance-attribute
history: ValuationHistoryData
Historical valuation data
IndustryValuationHistory
Historical valuation snapshot for one peer security.
date
instance-attribute
date: str
Unix timestamp string
pe
instance-attribute
pe: str
Price-to-Earnings ratio
pb
instance-attribute
pb: str
Price-to-Book ratio
ps
instance-attribute
ps: str
Price-to-Sales ratio
IndustryValuationItem
Valuation data for one peer security.
symbol
instance-attribute
symbol: str
Security symbol
name
instance-attribute
name: str
Company name
currency
instance-attribute
currency: str
Reporting currency
assets
instance-attribute
assets: str
Total assets
bps
instance-attribute
bps: str
Book value per share
eps
instance-attribute
eps: str
Earnings per share
dps
instance-attribute
dps: str
Dividends per share
div_yld
instance-attribute
div_yld: str
Dividend yield
div_payout_ratio
instance-attribute
div_payout_ratio: str
Dividend payout ratio
five_y_avg_dps
instance-attribute
five_y_avg_dps: str
5-year average dividends per share
pe
instance-attribute
pe: str
Current PE ratio
history
instance-attribute
history: list[IndustryValuationHistory]
Historical PE/PB/PS snapshots
IndustryValuationList
Industry peer valuation comparison response.
list
instance-attribute
list: list[IndustryValuationItem]
List of peer securities with valuation data
ValuationDist
Distribution statistics for one valuation metric.
low
instance-attribute
low: str
Minimum value in the industry
high
instance-attribute
high: str
Maximum value in the industry
median
instance-attribute
median: str
Median value in the industry
value
instance-attribute
value: str
Current value of the queried security
ranking
instance-attribute
ranking: str
Percentile ranking (0–1 range)
rank_index
instance-attribute
rank_index: str
Ordinal rank index
rank_total
instance-attribute
rank_total: str
Total securities in the industry
IndustryValuationDist
Industry valuation distribution response.
pe
instance-attribute
pe: ValuationDist | None
PE ratio distribution
pb
instance-attribute
pb: ValuationDist | None
PB ratio distribution
ps
instance-attribute
ps: ValuationDist | None
PS ratio distribution
CompanyOverview
Company overview response.
name
instance-attribute
name: str
Short name, e.g. "腾讯控股"
company_name
instance-attribute
company_name: str
Full legal name
founded
instance-attribute
founded: str
Founding date
listing_date
instance-attribute
listing_date: str
Listing date
market
instance-attribute
market: str
Primary listing market display name
region
instance-attribute
region: str
Market region code, e.g. "HK"
address
instance-attribute
address: str
Registered address
office_address
instance-attribute
office_address: str
Principal office address
website
instance-attribute
website: str
Company website
issue_price
instance-attribute
issue_price: str
IPO issue price
shares_offered
instance-attribute
shares_offered: str
Number of shares offered at IPO
chairman
instance-attribute
chairman: str
Chairman name
secretary
instance-attribute
secretary: str
Company secretary
audit_inst
instance-attribute
audit_inst: str
Auditing institution
category
instance-attribute
category: str
Company classification category
year_end
instance-attribute
year_end: str
Fiscal year end
employees
instance-attribute
employees: str
Number of employees
phone
instance-attribute
phone: str
Phone number
fax
instance-attribute
fax: str
Fax number
email
instance-attribute
email: str
Investor relations email
legal_repr
instance-attribute
legal_repr: str
Legal representative
manager
instance-attribute
manager: str
CEO / Managing Director
ticker
instance-attribute
ticker: str
Exchange ticker code
icon
instance-attribute
icon: str
Logo icon URL
profile
instance-attribute
profile: str
Business profile / description
sector
instance-attribute
sector: int
Industry sector code
Professional
One executive / board member.
id
instance-attribute
id: str
Internal wiki person ID
name
instance-attribute
name: str
Full name
name_zhcn
instance-attribute
name_zhcn: str
Full name in Simplified Chinese
name_en
instance-attribute
name_en: str
Full name in English
title
instance-attribute
title: str
Job title
biography
instance-attribute
biography: str
Biography text
photo
instance-attribute
photo: str
Photo URL
wiki_url
instance-attribute
wiki_url: str
Wiki profile URL
ExecutiveGroup
Executives for one security.
symbol
instance-attribute
symbol: str
Security symbol
forward_url
instance-attribute
forward_url: str
Link to company wiki page
total
instance-attribute
total: int
Total number of executives
professionals
instance-attribute
professionals: list[Professional]
Individual executive entries
ExecutiveList
Executive list response.
professional_list
instance-attribute
professional_list: list[ExecutiveGroup]
Groups of executives per security
ShareholderStock
A security in an institutional shareholder's cross-holdings.
symbol
instance-attribute
symbol: str
Security symbol of the cross-held stock
code
instance-attribute
code: str
Ticker code
market
instance-attribute
market: str
Market
chg
instance-attribute
chg: str
Day change percentage
Shareholder
One major shareholder.
shareholder_id
instance-attribute
shareholder_id: str
Internal shareholder ID
shareholder_name
instance-attribute
shareholder_name: str
Shareholder name
institution_type
instance-attribute
institution_type: str
Institution type
percent_of_shares
instance-attribute
percent_of_shares: str
Percentage of shares held
shares_changed
instance-attribute
shares_changed: str
Change in shares held
report_date
instance-attribute
report_date: str
Most recent filing date
stocks
instance-attribute
stocks: list[ShareholderStock]
Other securities held by this shareholder (cross-holdings)
ShareholderList
Shareholder list response.
shareholder_list
instance-attribute
shareholder_list: list[Shareholder]
List of major shareholders
forward_url
instance-attribute
forward_url: str
Link to full shareholder page
total
instance-attribute
total: int
Total number returned
FundHolder
A fund or ETF that holds the queried security.
code
instance-attribute
code: str
Fund/ETF ticker code
symbol
instance-attribute
symbol: str
Fund/ETF symbol
currency
instance-attribute
currency: str
Reporting currency
name
instance-attribute
name: str
Fund/ETF full name
position_ratio
instance-attribute
position_ratio: str
Position ratio percentage string
report_date
instance-attribute
report_date: str
Report date
FundHolders
Fund/ETF holders response.
lists
instance-attribute
lists: list[FundHolder]
Funds and ETFs holding the queried security
CorpActionLive
Live stream associated with a corporate action.
id
instance-attribute
id: str
Live stream ID
status
instance-attribute
status: str
Status: "1"=preview, "2"=live, "3"=ended, "4"=replay
started_at
instance-attribute
started_at: str
Start time
name
instance-attribute
name: str
Stream title
icon
instance-attribute
icon: str
Icon URL
CorpActionItem
One corporate action event.
id
instance-attribute
id: str
Internal event ID
date
instance-attribute
date: str
Date in YYYYMMDD format
date_str
instance-attribute
date_str: str
Short display date
date_type
instance-attribute
date_type: str
Date type label
date_zone
instance-attribute
date_zone: str
Time zone description
act_type
instance-attribute
act_type: str
Event category
act_desc
instance-attribute
act_desc: str
Human-readable event description
action
instance-attribute
action: str
Machine-readable action code
recent
instance-attribute
recent: bool
Whether this is a recent event
is_delay
instance-attribute
is_delay: bool
Whether publication was delayed
delay_content
instance-attribute
delay_content: str
Delay announcement content
live
instance-attribute
live: CorpActionLive | None
Associated live stream (if any)
CorpActions
Corporate actions response.
items
instance-attribute
items: list[CorpActionItem]
Corporate action events
InvestSecurity
A security in which the company has an investment stake.
company_id
instance-attribute
company_id: str
Internal company ID
company_name
instance-attribute
company_name: str
Company name
company_name_en
instance-attribute
company_name_en: str
Company name in English
company_name_zhcn
instance-attribute
company_name_zhcn: str
Company name in Simplified Chinese
symbol
instance-attribute
symbol: str
Security symbol
currency
instance-attribute
currency: str
Reporting currency
percent_of_shares
instance-attribute
percent_of_shares: str
Percentage of shares held
shares_rank
instance-attribute
shares_rank: str
Shareholder rank
shares_value
instance-attribute
shares_value: str
Market value of the holding
InvestRelations
Investor relations response.
forward_url
instance-attribute
forward_url: str
Link to investor relations page
invest_securities
instance-attribute
invest_securities: list[InvestSecurity]
Securities in which the company has a stake
OperatingIndicator
One financial indicator from an operating report.
field_name
instance-attribute
field_name: str
Field name key, e.g. "operating_revenue"
indicator_name
instance-attribute
indicator_name: str
Display name
indicator_value
instance-attribute
indicator_value: str
Formatted value, e.g. "8217 亿"
yoy
instance-attribute
yoy: str
Year-over-year change as decimal string
OperatingFinancial
Key financial metrics from an operating report.
code
instance-attribute
code: str
Ticker code
symbol
instance-attribute
symbol: str
Symbol in CODE.MARKET format (e.g. AAPL.US)
currency
instance-attribute
currency: str
Reporting currency
name
instance-attribute
name: str
Company name
region
instance-attribute
region: str
Market region
report
instance-attribute
report: str
Report period code
indicators
instance-attribute
indicators: list[OperatingIndicator]
Financial indicators
OperatingItem
One operating summary report (annual / quarterly).
id
instance-attribute
id: str
Internal report ID
report
instance-attribute
report: str
Report period code, e.g. "af" (annual)
title
instance-attribute
title: str
Report title
txt
instance-attribute
txt: str
Management discussion text
latest
instance-attribute
latest: bool
Whether this is the most recent report
web_url
instance-attribute
web_url: str
URL to the full community report page
financial
instance-attribute
financial: OperatingFinancial
Key financial metrics
OperatingList
Operating metrics response.
list
instance-attribute
list: list[OperatingItem]
Operating summary reports
RecentBuybacks
TTM (trailing twelve months) buyback summary.
currency
instance-attribute
currency: str
Reporting currency
net_buyback_ttm
instance-attribute
net_buyback_ttm: str
Net buyback amount TTM
net_buyback_yield_ttm
instance-attribute
net_buyback_yield_ttm: str
Net buyback yield TTM
BuybackHistoryItem
Historical annual buyback data item.
fiscal_year
instance-attribute
fiscal_year: str
Fiscal year label, e.g. "FY2024"
fiscal_year_range
instance-attribute
fiscal_year_range: str
Fiscal year date range string
net_buyback
instance-attribute
net_buyback: str
Net buyback amount
net_buyback_yield
instance-attribute
net_buyback_yield: str
Net buyback yield
net_buyback_growth_rate
instance-attribute
net_buyback_growth_rate: str
Year-over-year net buyback growth rate
currency
instance-attribute
currency: str
Reporting currency
BuybackRatios
Buyback payout and cash-flow ratios.
net_buyback_payout_ratio
instance-attribute
net_buyback_payout_ratio: str
Net buyback payout ratio
net_buyback_to_cashflow_ratio
instance-attribute
net_buyback_to_cashflow_ratio: str
Net buyback to free cash-flow ratio
BuybackData
Response for :meth:FundamentalContext.buyback.
recent_buybacks
instance-attribute
recent_buybacks: RecentBuybacks | None
Most recent TTM buyback summary
buyback_history
instance-attribute
buyback_history: list[BuybackHistoryItem]
Historical annual buyback data
buyback_ratios
instance-attribute
buyback_ratios: list[BuybackRatios]
Buyback payout and cash-flow ratios
StockRatings
Response for :meth:FundamentalContext.ratings.
The ratings_json field contains the full nested ratings structure as a
JSON string (too complex to type fully).
style_txt_name
instance-attribute
style_txt_name: str
Style display name
scale_txt_name
instance-attribute
scale_txt_name: str
Scale display name
report_period_txt
instance-attribute
report_period_txt: str
Report period display text
multi_score
instance-attribute
multi_score: str
Composite score (string representation)
multi_letter
instance-attribute
multi_letter: str
Composite score letter grade
multi_score_change
instance-attribute
multi_score_change: int
Score change vs previous period
industry_name
instance-attribute
industry_name: str
Industry name
industry_rank
instance-attribute
industry_rank: int
Industry rank
ratings_json
instance-attribute
ratings_json: str
Full ratings array as a JSON string
FinancialReportKind
Financial report kind.
IncomeStatement
Bases: FinancialReportKind
BalanceSheet
Bases: FinancialReportKind
CashFlow
Bases: FinancialReportKind
All
Bases: FinancialReportKind
FinancialReportPeriod
Financial report period type.
Annual
Bases: FinancialReportPeriod
SemiAnnual
Bases: FinancialReportPeriod
Q1
Bases: FinancialReportPeriod
Q2
Bases: FinancialReportPeriod
Q3
Bases: FinancialReportPeriod
QuarterlyFull
Bases: FinancialReportPeriod
ThreeQ
Bases: FinancialReportPeriod
FundamentalContext
Fundamental data context.
Provides access to financial reports, analyst ratings, dividends, valuation metrics, company overview, and more.
Examples:
::
from longbridge.openapi import Config, FundamentalContext, FinancialReportKind
config = Config.from_env()
ctx = FundamentalContext(config)
overview = ctx.company("700.HK")
print(overview.name, overview.employees)
dividends = ctx.dividend("700.HK")
for d in dividends.list:
print(d.desc, d.payment_date)
__init__
__init__(config: Config) -> None
Create a FundamentalContext.
financial_report
financial_report(symbol: str, kind: FinancialReportKind = ..., period: FinancialReportPeriod | None = None) -> FinancialReports
Get financial reports.
| Parameters: |
|
|---|
| Returns: |
|
|---|
institution_rating
institution_rating(symbol: str) -> InstitutionRating
Get analyst ratings (latest snapshot + consensus summary).
| Parameters: |
|
|---|
| Returns: |
|
|---|
institution_rating_detail
institution_rating_detail(symbol: str) -> InstitutionRatingDetail
Get historical analyst rating details.
dividend
dividend(symbol: str) -> DividendList
Get dividend history.
dividend_detail
dividend_detail(symbol: str) -> DividendList
Get detailed dividend information.
forecast_eps
forecast_eps(symbol: str) -> ForecastEps
Get EPS forecasts.
consensus
consensus(symbol: str) -> FinancialConsensus
Get financial consensus estimates.
valuation
valuation(symbol: str) -> ValuationData
Get valuation metrics (PE / PB / PS / dividend yield).
valuation_history
valuation_history(symbol: str) -> ValuationHistoryResponse
Get historical valuation data.
industry_valuation
industry_valuation(symbol: str) -> IndustryValuationList
Get industry peer valuation comparison.
industry_valuation_dist
industry_valuation_dist(symbol: str) -> IndustryValuationDist
Get industry valuation distribution.
company
company(symbol: str) -> CompanyOverview
Get company overview.
executive
executive(symbol: str) -> ExecutiveList
Get executive and board member information.
shareholder
shareholder(symbol: str) -> ShareholderList
Get major shareholders.
fund_holder
fund_holder(symbol: str) -> FundHolders
Get funds and ETFs that hold the security.
corp_action
corp_action(symbol: str) -> CorpActions
Get corporate actions (dividends, splits, buybacks, etc.).
invest_relation
invest_relation(symbol: str) -> InvestRelations
Get investor relations / investment holdings.
operating
operating(symbol: str) -> OperatingList
Get operating metrics and financial report summaries.
buyback
buyback(symbol: str) -> BuybackData
Get buyback data for a security.
| Parameters: |
|
|---|
| Returns: |
|
|---|
ratings
ratings(symbol: str) -> StockRatings
Get stock ratings for a security.
| Parameters: |
|
|---|
| Returns: |
|
|---|
shareholder_top
shareholder_top(symbol: str) -> ShareholderTopResponse
Get ranked list of top shareholders.
| Parameters: |
|
|---|
| Returns: |
|
|---|
shareholder_detail
shareholder_detail(symbol: str, object_id: int) -> ShareholderDetailResponse
Get holding history and detail for one shareholder.
| Parameters: |
|---|
| Returns: |
|
|---|
valuation_comparison
valuation_comparison(symbol: str, currency: str, comparison_symbols: Optional[List[str]] = None) -> ValuationComparisonResponse
Get valuation comparison between a security and optional peers.
| Parameters: |
|---|
| Returns: |
|
|---|
ShareholderTopResponse
Top-shareholder list response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw top-shareholder data (JSON object / list)
ShareholderDetailResponse
Shareholder detail response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw shareholder detail data (JSON object / list)
ValuationHistoryPoint
One historical valuation data point.
date
instance-attribute
date: str
Date (RFC 3339, converted from Unix timestamp)
pe
instance-attribute
pe: str
P/E ratio
pb
instance-attribute
pb: str
P/B ratio
ps
instance-attribute
ps: str
P/S ratio
ValuationComparisonItem
One security's valuation comparison item.
symbol
instance-attribute
symbol: str
Symbol (e.g. "AAPL.US")
name
instance-attribute
name: str
Security name
currency
instance-attribute
currency: str
Currency
market_value
instance-attribute
market_value: str
Market capitalisation
price_close
instance-attribute
price_close: str
Latest closing price
pe
instance-attribute
pe: str
P/E ratio
pb
instance-attribute
pb: str
P/B ratio
ps
instance-attribute
ps: str
P/S ratio
roe
instance-attribute
roe: str
Return on equity
eps
instance-attribute
eps: str
Earnings per share
bps
instance-attribute
bps: str
Book value per share
dps
instance-attribute
dps: str
Dividends per share
div_yld
instance-attribute
div_yld: str
Dividend yield
assets
instance-attribute
assets: str
Total assets
history
instance-attribute
history: List[ValuationHistoryPoint]
Historical valuation points
ValuationComparisonResponse
Valuation comparison response.
list
instance-attribute
list: List[ValuationComparisonItem]
Valuation comparison items
MarketTimeItem
Trading status for one market.
market
instance-attribute
market: Market
Market
trade_status
instance-attribute
trade_status: int
Raw trade status code (101=PreOpen, 102/105=Trading, 104=LunchBreak, 106=PostTrading, 108=Closed, 201=PreMarket, 204=PostMarket)
timestamp
instance-attribute
timestamp: str
Current market time (unix timestamp string)
delay_trade_status
instance-attribute
delay_trade_status: int
Delayed-quote trade status code
delay_timestamp
instance-attribute
delay_timestamp: str
Delayed-quote market time (unix timestamp string)
sub_status
instance-attribute
sub_status: int
Sub-status code
delay_sub_status
instance-attribute
delay_sub_status: int
Delayed-quote sub-status code
MarketStatusResponse
Market trading status response.
market_time
instance-attribute
market_time: list[MarketTimeItem]
Per-market trading status items
BrokerHoldingEntry
One broker entry in a top-holding list.
name
instance-attribute
name: str
Broker name
parti_number
instance-attribute
parti_number: str
Participant number / broker code
chg
instance-attribute
chg: str
Net change in shares held
strong
instance-attribute
strong: bool
Whether this is a strengthening broker
BrokerHoldingTop
Top broker holdings response.
buy
instance-attribute
buy: list[BrokerHoldingEntry]
Top buying brokers
sell
instance-attribute
sell: list[BrokerHoldingEntry]
Top selling brokers
updated_at
instance-attribute
updated_at: str
Last updated string
BrokerHoldingChanges
Broker holding changes over multiple periods.
value
instance-attribute
value: str
Current value
chg_1
instance-attribute
chg_1: str
1-day change
chg_5
instance-attribute
chg_5: str
5-day change
chg_20
instance-attribute
chg_20: str
20-day change
chg_60
instance-attribute
chg_60: str
60-day change
BrokerHoldingDetailItem
One broker's full holding detail.
name
instance-attribute
name: str
Broker name
parti_number
instance-attribute
parti_number: str
Participant number
ratio
instance-attribute
ratio: BrokerHoldingChanges
Holding ratio changes over various periods
shares
instance-attribute
shares: BrokerHoldingChanges
Share count changes over various periods
strong
instance-attribute
strong: bool
Whether this is a strengthening broker
BrokerHoldingDetail
Full broker holding detail response.
list
instance-attribute
list: list[BrokerHoldingDetailItem]
Full broker list
updated_at
instance-attribute
updated_at: str
Last updated string
BrokerHoldingDailyItem
One day's broker holding record.
date
instance-attribute
date: str
Date in "2026.05.05" format
holding
instance-attribute
holding: str
Total shares held
ratio
instance-attribute
ratio: str
Holding ratio
chg
instance-attribute
chg: str
Daily change
BrokerHoldingDailyHistory
Daily broker holding history response.
list
instance-attribute
list: list[BrokerHoldingDailyItem]
Daily records
AhPremiumKline
One A/H premium data point.
aprice
instance-attribute
aprice: str
A-share price
apreclose
instance-attribute
apreclose: str
A-share previous close
hprice
instance-attribute
hprice: str
H-share price
hpreclose
instance-attribute
hpreclose: str
H-share previous close
currency_rate
instance-attribute
currency_rate: str
CNY/HKD exchange rate
ahpremium_rate
instance-attribute
ahpremium_rate: str
A/H premium rate (negative = H-share at premium)
price_spread
instance-attribute
price_spread: str
Price spread
timestamp
instance-attribute
timestamp: datetime
Data point timestamp
AhPremiumKlines
A/H premium K-line response.
klines
instance-attribute
klines: list[AhPremiumKline]
K-line data points
AhPremiumIntraday
A/H premium intraday response.
klines
instance-attribute
klines: list[AhPremiumKline]
Intraday data points
TradePriceLevel
Trade volume at one price level.
buy_amount
instance-attribute
buy_amount: str
Buy volume at this price
neutral_amount
instance-attribute
neutral_amount: str
Neutral (unknown direction) volume
price
instance-attribute
price: str
Price level
sell_amount
instance-attribute
sell_amount: str
Sell volume at this price
TradeStatistics
Summary trade statistics.
avgprice
instance-attribute
avgprice: str
Volume-weighted average price
buy
instance-attribute
buy: str
Total buy volume (shares)
neutral
instance-attribute
neutral: str
Total neutral / unknown-direction volume
preclose
instance-attribute
preclose: str
Previous close price
sell
instance-attribute
sell: str
Total sell volume (shares)
timestamp
instance-attribute
timestamp: str
Data timestamp (unix timestamp string)
total_amount
instance-attribute
total_amount: str
Total trading volume (shares)
trade_date
instance-attribute
trade_date: list[str]
Unix timestamps for the last 5 trading days
trades_count
instance-attribute
trades_count: str
Total number of trades
TradeStatsResponse
Trade statistics response.
statistics
instance-attribute
statistics: TradeStatistics
Summary statistics
trades
instance-attribute
trades: list[TradePriceLevel]
Per-price-level breakdown
AnomalyItem
One market anomaly event.
symbol
instance-attribute
symbol: str
Security symbol
name
instance-attribute
name: str
Security name
alert_name
instance-attribute
alert_name: str
Anomaly type name, e.g. "大宗交易"
alert_time
instance-attribute
alert_time: int
Time of the anomaly (unix timestamp in milliseconds)
change_values
instance-attribute
change_values: list[str]
Change value strings
emotion
instance-attribute
emotion: int
Sentiment direction: 1=positive/up, 2=negative/down
AnomalyResponse
Market anomaly response.
all_off
instance-attribute
all_off: bool
Whether anomaly alerts are globally disabled
changes
instance-attribute
changes: list[AnomalyItem]
List of market anomaly events
ConstituentStock
One constituent stock of an index.
symbol
instance-attribute
symbol: str
Security symbol
name
instance-attribute
name: str
Security name
last_done
instance-attribute
last_done: str
Latest price
prev_close
instance-attribute
prev_close: str
Previous close
inflow
instance-attribute
inflow: str
Net capital inflow today
balance
instance-attribute
balance: str
Turnover amount
amount
instance-attribute
amount: str
Trading volume (shares)
total_shares
instance-attribute
total_shares: str
Total shares outstanding
tags
instance-attribute
tags: list[str]
Tags, e.g. ["领涨龙头"]
intro
instance-attribute
intro: str
Brief description
market
instance-attribute
market: str
Market, e.g. "HK"
circulating_shares
instance-attribute
circulating_shares: str
Circulating shares
delay
instance-attribute
delay: bool
Whether this is a delayed quote
chg
instance-attribute
chg: str
Day change percentage
trade_status
instance-attribute
trade_status: int
Raw trade status code
IndexConstituents
Index constituents response.
fall_num
instance-attribute
fall_num: int
Number of constituent stocks that fell today
flat_num
instance-attribute
flat_num: int
Number of constituent stocks unchanged today
rise_num
instance-attribute
rise_num: int
Number of constituent stocks that rose today
stocks
instance-attribute
stocks: list[ConstituentStock]
Constituent stock details
BrokerHoldingPeriod
Broker holding lookback period.
Rct1
Bases: BrokerHoldingPeriod
Rct5
Bases: BrokerHoldingPeriod
Rct20
Bases: BrokerHoldingPeriod
Rct60
Bases: BrokerHoldingPeriod
AhPremiumPeriod
A/H premium K-line period.
Min1
Bases: AhPremiumPeriod
Min5
Bases: AhPremiumPeriod
Min15
Bases: AhPremiumPeriod
Min30
Bases: AhPremiumPeriod
Min60
Bases: AhPremiumPeriod
Day
Bases: AhPremiumPeriod
Week
Bases: AhPremiumPeriod
Month
Bases: AhPremiumPeriod
Year
Bases: AhPremiumPeriod
MarketContext
Market data context.
Provides broker holdings, A/H premium, trade statistics, market anomaly alerts, and index constituents.
Examples:
::
from longbridge.openapi import Config, MarketContext
config = Config.from_env()
ctx = MarketContext(config)
status = ctx.market_status()
for item in status.market_time:
print(item.market, item.trade_status)
__init__
__init__(config: Config) -> None
Create a MarketContext.
market_status
market_status() -> MarketStatusResponse
Get current trading status for all markets.
broker_holding
broker_holding(symbol: str, period: BrokerHoldingPeriod = ...) -> BrokerHoldingTop
Get top broker holdings (buy/sell leaders) for a security.
| Parameters: |
|
|---|
broker_holding_detail
broker_holding_detail(symbol: str) -> BrokerHoldingDetail
Get full broker holding details for a security.
broker_holding_daily
broker_holding_daily(symbol: str, broker_id: str) -> BrokerHoldingDailyHistory
ah_premium
ah_premium(symbol: str, period: AhPremiumPeriod = ..., count: int = 100) -> AhPremiumKlines
Get A/H premium K-line data for a dual-listed security.
| Parameters: |
|
|---|
ah_premium_intraday
ah_premium_intraday(symbol: str) -> AhPremiumIntraday
Get A/H premium intraday data for a dual-listed security.
trade_stats
trade_stats(symbol: str) -> TradeStatsResponse
Get buy/sell/neutral trade statistics for a security.
anomaly
anomaly(market: str) -> AnomalyResponse
Get market anomaly alerts (unusual price/volume events).
| Parameters: |
|
|---|
constituent
constituent(symbol: str) -> IndexConstituents
Get constituent stocks for an index.
| Parameters: |
|
|---|
top_movers
top_movers(markets: List[str], sort: int = 0, date: Optional[str] = None, limit: int = 20) -> TopMoversResponse
Get top movers (stocks with unusual price movements) across one or more markets.
| Parameters: |
|---|
| Returns: |
|
|---|
rank_categories
rank_categories() -> RankCategoriesResponse
Get all available rank category keys and labels.
| Returns: |
|
|---|
rank_list
rank_list(key: str, need_article: bool = False) -> RankListResponse
Get a ranked list of securities for the given category key.
| Parameters: |
|---|
| Returns: |
|
|---|
TopMoversStock
Stock information within a top-movers event.
symbol
instance-attribute
symbol: str
Symbol (e.g. "NVDA.US")
code
instance-attribute
code: str
Ticker code
name
instance-attribute
name: str
Security name
full_name
instance-attribute
full_name: str
Full name
change
instance-attribute
change: str
Price change (decimal ratio)
last_done
instance-attribute
last_done: str
Latest price
market
instance-attribute
market: str
Market code
labels
instance-attribute
labels: List[str]
Labels / tags
logo
instance-attribute
logo: str
Logo URL
TopMoversEvent
One top-movers event entry.
timestamp
instance-attribute
timestamp: str
Event time (RFC 3339)
alert_reason
instance-attribute
alert_reason: str
Alert reason description
alert_type
instance-attribute
alert_type: int
Alert type code
stock
instance-attribute
stock: TopMoversStock
Stock information
post
instance-attribute
post: object
Associated news post (raw JSON object)
TopMoversResponse
Top movers response.
events
instance-attribute
events: List[TopMoversEvent]
Top-mover events
next_params
instance-attribute
next_params: object
Pagination cursor for next page (raw JSON object)
RankCategoriesResponse
Rank categories response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw rank categories data (JSON object / list)
RankListItem
One ranked security item.
symbol
instance-attribute
symbol: str
Symbol (e.g. "MU.US")
code
instance-attribute
code: str
Ticker code
name
instance-attribute
name: str
Security name
last_done
instance-attribute
last_done: str
Latest price
chg
instance-attribute
chg: str
Price change ratio
change
instance-attribute
change: str
Absolute price change
inflow
instance-attribute
inflow: str
Net inflow
market_cap
instance-attribute
market_cap: str
Market cap
industry
instance-attribute
industry: str
Industry name
pre_post_price
instance-attribute
pre_post_price: str
Pre/post market price
pre_post_chg
instance-attribute
pre_post_chg: str
Pre/post market change
amplitude
instance-attribute
amplitude: str
Amplitude
five_day_chg
instance-attribute
five_day_chg: str
5-day change
turnover_rate
instance-attribute
turnover_rate: str
Turnover rate
volume_rate
instance-attribute
volume_rate: str
Volume ratio
pb_ttm
instance-attribute
pb_ttm: str
P/B ratio (TTM)
RankListResponse
Rank list response.
bmp
instance-attribute
bmp: bool
Whether delayed / BMP data
lists
instance-attribute
lists: List[RankListItem]
Ranked security items
ScreenerCondition
A filter condition for :meth:ScreenerContext.screener_search Mode B.
key
instance-attribute
key: str
Indicator key without filter_ prefix, e.g. "pettm", "roe", "macd_day"
min
instance-attribute
min: str
Lower bound (empty string = no lower bound)
max
instance-attribute
max: str
Upper bound (empty string = no upper bound)
tech_values
instance-attribute
tech_values: str
Technical indicator params as JSON string. Use "{}" for fundamental indicators.
Example: '{"category": "goldenfork", "period": "day"}'
__init__
__init__(key: str, min: str = '', max: str = '', tech_values: str = '{}') -> None
ScreenerRecommendStrategiesResponse
Recommended screener strategies response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw recommended strategies data (JSON object / list)
ScreenerUserStrategiesResponse
User screener strategies response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw user strategies data (JSON object / list)
ScreenerStrategyResponse
Single screener strategy response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw strategy detail data (JSON object / list)
ScreenerSearchResponse
Screener search results response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw search results data (JSON object / list)
ScreenerIndicatorsResponse
Screener indicator definitions response. data is a Python dict/list from JSON.
data
instance-attribute
data: object
Raw indicator definitions data (JSON object / list)
ScreenerContext
Stock screener context — strategies, search, and indicators.
__init__
__init__(config: Config) -> None
screener_recommend_strategies
screener_recommend_strategies(market: str) -> ScreenerRecommendStrategiesResponse
Get preset built-in screener strategies.
screener_user_strategies
screener_user_strategies(market: str) -> ScreenerUserStrategiesResponse
Get the current user's saved screener strategies.
screener_strategy
screener_strategy(id: int) -> ScreenerStrategyResponse
Get detail for one screener strategy by ID.
screener_search
screener_search(market: str, strategy_id: Optional[int] = None, conditions: List[ScreenerCondition] = [], show: List[str] = [], page: int = 0, size: int = 20) -> ScreenerSearchResponse
Search / screen securities using a strategy or custom conditions.
When strategy_id is given (Mode A), the strategy is fetched from the AI
endpoint and its filters are forwarded to the search request. The
market is taken from the strategy response.
When strategy_id is None (Mode B), conditions must be provided as
:class:ScreenerCondition objects and market is used directly.
filter_ is stripped from every items[].indicators[].key in the
response before it is returned.
screener_indicators
screener_indicators() -> ScreenerIndicatorsResponse
Get all available screener indicator definitions.
AsyncScreenerContext
Async screener context for use with asyncio.
create
classmethod
create(config: Config) -> AsyncScreenerContext
screener_recommend_strategies
screener_recommend_strategies(market: str) -> Awaitable[ScreenerRecommendStrategiesResponse]
Get preset built-in screener strategies. Returns awaitable.
screener_user_strategies
screener_user_strategies(market: str) -> Awaitable[ScreenerUserStrategiesResponse]
Get the current user's saved screener strategies. Returns awaitable.
screener_strategy
screener_strategy(id: int) -> Awaitable[ScreenerStrategyResponse]
Get detail for one screener strategy by ID. Returns awaitable.
screener_search
screener_search(market: str, strategy_id: Optional[int] = None, conditions: List[ScreenerCondition] = [], show: List[str] = [], page: int = 0, size: int = 20) -> Awaitable[ScreenerSearchResponse]
Search / screen securities using a strategy or custom conditions. Returns awaitable.
When strategy_id is given (Mode A), the strategy is fetched from the AI
endpoint and its filters are forwarded to the search request. The
market is taken from the strategy response.
When strategy_id is None (Mode B), conditions must be provided as
:class:ScreenerCondition objects and market is used directly.
filter_ is stripped from every items[].indicators[].key in the
response before it is returned.
screener_indicators
screener_indicators() -> Awaitable[ScreenerIndicatorsResponse]
Get all available screener indicator definitions. Returns awaitable.
CalendarDataKv
One key-value data pair in a calendar event.
key
instance-attribute
key: str
Key (may be empty)
value
instance-attribute
value: str
Formatted display value
value_type
instance-attribute
value_type: str
Value type code, e.g. "estimate_eps"
value_raw
instance-attribute
value_raw: str
Raw numeric value
CalendarEventInfo
One financial calendar event.
symbol
instance-attribute
symbol: str
Security symbol
market
instance-attribute
market: str
Market, e.g. "HK"
content
instance-attribute
content: str
Event content description
counter_name
instance-attribute
counter_name: str
Security name
date_type
instance-attribute
date_type: str
Date type label, e.g. "盘前"
date
instance-attribute
date: str
Event date string, e.g. "2025.05.02"
chart_uid
instance-attribute
chart_uid: str
Chart UID (may be empty)
data_kv
instance-attribute
data_kv: list[CalendarDataKv]
Structured data key-value pairs
event_type
instance-attribute
event_type: str
Event type code, e.g. "financial"
datetime
instance-attribute
datetime: str
Event datetime (unix timestamp string)
icon
instance-attribute
icon: str
Icon URL
star
instance-attribute
star: int
Importance star rating (0–3)
id
instance-attribute
id: str
Internal event ID
financial_market_time
instance-attribute
financial_market_time: str
Financial market session time string
currency
instance-attribute
currency: str
Currency
activity_type
instance-attribute
activity_type: str
Activity type code
CalendarDateGroup
Events for one calendar date.
date
instance-attribute
date: str
Date string, e.g. "2025-05-02"
count
instance-attribute
count: int
Total event count for this date
infos
instance-attribute
infos: list[CalendarEventInfo]
Event details
CalendarEventsResponse
Finance calendar response.
date
instance-attribute
date: str
Start date of the query window
list
instance-attribute
list: list[CalendarDateGroup]
Per-day event groups
next_date
instance-attribute
next_date: str
Pagination cursor; pass as start to fetch the next page, empty when there are no more pages
CalendarCategory
Calendar event category.
Report
Bases: CalendarCategory
Dividend
Bases: CalendarCategory
Split
Bases: CalendarCategory
Ipo
Bases: CalendarCategory
MacroData
Bases: CalendarCategory
Closed
Bases: CalendarCategory
Meeting
Bases: CalendarCategory
Merge
Bases: CalendarCategory
CalendarContext
Financial calendar context.
Examples:
::
from longbridge.openapi import Config, CalendarContext, CalendarCategory
config = Config.from_env()
ctx = CalendarContext(config)
resp = ctx.finance_calendar(
CalendarCategory.Report, "2025-05-01", "2025-05-31", "HK"
)
for group in resp.list:
print(group.date, group.count)
__init__
__init__(config: Config) -> None
Create a CalendarContext.
finance_calendar
finance_calendar(category: CalendarCategory, start: str, end: str, market: str | None = None) -> CalendarEventsResponse
Get financial calendar events.
| Parameters: |
|
|---|
ExchangeRate
One currency exchange rate.
average_rate
instance-attribute
average_rate: float
Average rate (base_currency per other_currency)
base_currency
instance-attribute
base_currency: str
Base currency, e.g. "USD"
bid_rate
instance-attribute
bid_rate: float
Bid rate
offer_rate
instance-attribute
offer_rate: float
Offer rate
other_currency
instance-attribute
other_currency: str
Other currency, e.g. "HKD"
ExchangeRates
Exchange rates response.
exchanges
instance-attribute
exchanges: list[ExchangeRate]
List of exchange rates
AssetType
FlowDirection
Trade flow direction.
ProfitSummaryInfo
P&L summary for one asset category.
asset_type
instance-attribute
asset_type: AssetType
Asset type
profit_max
instance-attribute
profit_max: str
Security with the maximum profit
profit_max_name
instance-attribute
profit_max_name: str
Name of the max-profit security
loss_max
instance-attribute
loss_max: str
Security with the maximum loss
loss_max_name
instance-attribute
loss_max_name: str
Name of the max-loss security
ProfitSummaryBreakdown
P&L breakdown by asset type.
stock
instance-attribute
stock: str
Stock P&L
fund
instance-attribute
fund: str
Fund P&L
crypto
instance-attribute
crypto: str
Crypto P&L
mmf
instance-attribute
mmf: str
Money market fund P&L
other
instance-attribute
other: str
Other P&L
cumulative_transaction_amount
instance-attribute
cumulative_transaction_amount: str
Cumulative transaction amount
trade_order_num
instance-attribute
trade_order_num: str
Total number of orders
trade_stock_num
instance-attribute
trade_stock_num: str
Total number of traded securities
ipo
instance-attribute
ipo: str
IPO P&L
ipo_hit
instance-attribute
ipo_hit: int
IPO hits
ipo_subscription
instance-attribute
ipo_subscription: int
IPO subscriptions
summary_info
instance-attribute
summary_info: list[ProfitSummaryInfo]
Per-category summary
ProfitAnalysisSummary
Account-level P&L summary.
currency
instance-attribute
currency: str
Account currency
current_total_asset
instance-attribute
current_total_asset: str
Current total asset value
start_date
instance-attribute
start_date: str
Query start date
end_date
instance-attribute
end_date: str
Query end date
start_time
instance-attribute
start_time: str
Start time (unix timestamp string)
end_time
instance-attribute
end_time: str
End time (unix timestamp string)
ending_asset_value
instance-attribute
ending_asset_value: str
Ending asset value
initial_asset_value
instance-attribute
initial_asset_value: str
Initial asset value
invest_amount
instance-attribute
invest_amount: str
Total invested amount
is_traded
instance-attribute
is_traded: bool
Whether any trades occurred
sum_profit
instance-attribute
sum_profit: str
Total profit/loss
sum_profit_rate
instance-attribute
sum_profit_rate: str
Total profit/loss rate
profits
instance-attribute
profits: ProfitSummaryBreakdown
Per-asset-type breakdown
ProfitAnalysisItem
P&L for one security.
name
instance-attribute
name: str
Security name
market
instance-attribute
market: str
Market
is_holding
instance-attribute
is_holding: bool
Whether still holding
profit
instance-attribute
profit: str
Profit/loss amount
profit_rate
instance-attribute
profit_rate: str
Profit/loss rate
clearance_times
instance-attribute
clearance_times: int
Number of completed trades
item_type
instance-attribute
item_type: AssetType
Asset type
currency
instance-attribute
currency: str
Currency
symbol
instance-attribute
symbol: str
Security symbol
holding_period
instance-attribute
holding_period: str
Holding period display string
security_code
instance-attribute
security_code: str
Ticker code
isin
instance-attribute
isin: str
ISIN (for funds)
underlying_profit
instance-attribute
underlying_profit: str
Underlying stock P&L
derivatives_profit
instance-attribute
derivatives_profit: str
Derivatives P&L
order_profit
instance-attribute
order_profit: str
P&L in order currency
ProfitAnalysisSublist
Per-security P&L breakdown.
start
instance-attribute
start: str
Start time (unix timestamp string)
end
instance-attribute
end: str
End time (unix timestamp string)
start_date
instance-attribute
start_date: str
Start date string
end_date
instance-attribute
end_date: str
End date string
updated_at
instance-attribute
updated_at: str
Last updated time
updated_date
instance-attribute
updated_date: str
Last updated date
items
instance-attribute
items: list[ProfitAnalysisItem]
Per-security items
ProfitAnalysis
Combined portfolio P&L analysis response.
summary
instance-attribute
summary: ProfitAnalysisSummary
Account-level summary
sublist
instance-attribute
sublist: ProfitAnalysisSublist
Per-security breakdown
ProfitDetailEntry
One P&L detail line item.
describe
instance-attribute
describe: str
Description
amount
instance-attribute
amount: str
Amount
ProfitDetails
Detailed P&L breakdown for one asset class.
holding_value
instance-attribute
holding_value: str
Current holding market value
profit
instance-attribute
profit: str
Total profit/loss
cumulative_credited_amount
instance-attribute
cumulative_credited_amount: str
Cumulative credited amount
credited_details
instance-attribute
credited_details: list[ProfitDetailEntry]
Credit detail entries
cumulative_debited_amount
instance-attribute
cumulative_debited_amount: str
Cumulative debited amount
debited_details
instance-attribute
debited_details: list[ProfitDetailEntry]
Debit detail entries
cumulative_fee_amount
instance-attribute
cumulative_fee_amount: str
Cumulative fee amount
fee_details
instance-attribute
fee_details: list[ProfitDetailEntry]
Fee detail entries
short_holding_value
instance-attribute
short_holding_value: str
Short position holding value
long_holding_value
instance-attribute
long_holding_value: str
Long position holding value
holding_value_at_beginning
instance-attribute
holding_value_at_beginning: str
Opening position market value at period start
holding_value_at_ending
instance-attribute
holding_value_at_ending: str
Closing position market value at period end
ProfitAnalysisDetail
P&L detail for one security.
profit
instance-attribute
profit: str
Total profit/loss
underlying_details
instance-attribute
underlying_details: ProfitDetails
Underlying stock P&L details
derivative_pnl_details
instance-attribute
derivative_pnl_details: ProfitDetails
Derivative P&L details
name
instance-attribute
name: str
Security name
updated_at
instance-attribute
updated_at: str
Last updated time
updated_date
instance-attribute
updated_date: str
Last updated date
currency
instance-attribute
currency: str
Currency
default_tag
instance-attribute
default_tag: int
Default detail tab: 0=underlying, 1=derivative
start
instance-attribute
start: int
Query start time (unix timestamp)
end
instance-attribute
end: int
Query end time (unix timestamp)
start_date
instance-attribute
start_date: str
Query start date
end_date
instance-attribute
end_date: str
Query end date
PortfolioContext
Portfolio analytics context.
Examples:
::
from longbridge.openapi import Config, PortfolioContext
config = Config.from_env()
ctx = PortfolioContext(config)
rates = ctx.exchange_rate()
for r in rates.exchanges:
print(r.base_currency, r.other_currency, r.average_rate)
__init__
__init__(config: Config) -> None
Create a PortfolioContext.
exchange_rate
exchange_rate() -> ExchangeRates
Get exchange rates for supported currencies.
profit_analysis
profit_analysis(start: str | None = None, end: str | None = None) -> ProfitAnalysis
profit_analysis_detail
profit_analysis_detail(symbol: str, start: str | None = None, end: str | None = None) -> ProfitAnalysisDetail
profit_analysis_by_market
profit_analysis_by_market(page: int = 1, size: int = 20, market: str | None = None, start: str | None = None, end: str | None = None, currency: str | None = None) -> ProfitAnalysisByMarket
Get P&L grouped by market with per-security breakdown.
| Parameters: |
|
|---|
profit_analysis_flows
profit_analysis_flows(symbol: str, page: int, size: int, derivative: bool, start: str | None = None, end: str | None = None) -> ProfitAnalysisFlows
Get paginated P&L flow records for a security.
| Parameters: |
|
|---|
ProfitAnalysisByMarketItem
One security entry in a by-market P&L response.
code
instance-attribute
code: str
Security symbol (ticker code)
name
instance-attribute
name: str
Security name
market
instance-attribute
market: str
Market, e.g. "HK" or "US"
profit
instance-attribute
profit: str
Profit/loss amount
ProfitAnalysisByMarket
Response for :meth:PortfolioContext.profit_analysis_by_market.
profit
instance-attribute
profit: str
Total P&L across all returned items
has_more
instance-attribute
has_more: bool
Whether more pages are available
stock_items
instance-attribute
stock_items: list[ProfitAnalysisByMarketItem]
Per-security P&L items
FlowItem
One profit-analysis flow record.
executed_date
instance-attribute
executed_date: str
Execution date string, e.g. "2024-01-15"
executed_timestamp
instance-attribute
executed_timestamp: str
Execution timestamp (string representation)
code
instance-attribute
code: str
Security code / ticker
direction
instance-attribute
direction: FlowDirection
Direction of the flow
executed_quantity
instance-attribute
executed_quantity: str
Executed quantity
executed_price
instance-attribute
executed_price: str
Executed price
executed_cost
instance-attribute
executed_cost: str
Executed cost
describe
instance-attribute
describe: str
Human-readable description
ProfitAnalysisFlows
Response for :meth:PortfolioContext.profit_analysis_flows.
flows_list
instance-attribute
flows_list: list[FlowItem]
Paginated list of flow items
has_more
instance-attribute
has_more: bool
Whether there are more pages
AlertItem
One price alert.
id
instance-attribute
id: str
Alert ID
indicator_id
instance-attribute
indicator_id: str
Condition: "1"=price_rise, "2"=price_fall, "3"=pct_rise, "4"=pct_fall
enabled
instance-attribute
enabled: bool
Whether the alert is active
frequency
instance-attribute
frequency: int
Frequency: 1=daily, 2=every_time, 3=once
scope
instance-attribute
scope: int
Scope
text
instance-attribute
text: str
Display text, e.g. "价格涨到 600"
state
instance-attribute
state: list[int]
Trigger state flags
AlertSymbolGroup
Alert items for one security.
symbol
instance-attribute
symbol: str
Security symbol
code
instance-attribute
code: str
Ticker code (without market)
market
instance-attribute
market: str
Market, e.g. "HK"
name
instance-attribute
name: str
Security name
price
instance-attribute
price: str
Latest price
chg
instance-attribute
chg: str
Day change amount
p_chg
instance-attribute
p_chg: str
Day change percentage
product
instance-attribute
product: str
Product type
indicators
instance-attribute
indicators: list[AlertItem]
Alert items
AlertList
Alert list response.
lists
instance-attribute
lists: list[AlertSymbolGroup]
Alert groups per security
AlertCondition
Alert trigger condition.
PriceRise
Bases: AlertCondition
PriceFall
Bases: AlertCondition
PercentRise
Bases: AlertCondition
PercentFall
Bases: AlertCondition
AlertFrequency
Alert trigger frequency.
AlertContext
Price alert management context.
Examples:
::
from longbridge.openapi import Config, AlertContext, AlertCondition, AlertFrequency
config = Config.from_env()
ctx = AlertContext(config)
ctx.add("700.HK", AlertCondition.PriceRise, "600", AlertFrequency.Once)
alerts = ctx.list()
for group in alerts.lists:
print(group.symbol, len(group.indicators), "alerts")
__init__
__init__(config: Config) -> None
Create an AlertContext.
list
list() -> AlertList
List all price alerts.
add
add(symbol: str, condition: AlertCondition, trigger_value: str, frequency: AlertFrequency) -> None
Add a price alert.
| Parameters: |
|
|---|
enable
enable(alert_id: str) -> None
Enable a price alert.
disable
disable(alert_id: str) -> None
Disable a price alert.
delete
delete(alert_ids: list[str]) -> None
Delete price alerts.
DcaPlan
One DCA (dollar-cost averaging) investment plan.
plan_id
instance-attribute
plan_id: str
Plan ID
status
instance-attribute
status: DCAStatus
Plan status
symbol
instance-attribute
symbol: str
Security symbol
member_id
instance-attribute
member_id: str
Member ID
aaid
instance-attribute
aaid: str
Account ID
account_channel
instance-attribute
account_channel: str
Account channel
display_account
instance-attribute
display_account: str
Display account
market
instance-attribute
market: Market
Market
per_invest_amount
instance-attribute
per_invest_amount: str
Investment amount per period
invest_frequency
instance-attribute
invest_frequency: DCAFrequency
Investment frequency
invest_day_of_week
instance-attribute
invest_day_of_week: str
Day of week for weekly plans
invest_day_of_month
instance-attribute
invest_day_of_month: str
Day of month for monthly plans
allow_margin_finance
instance-attribute
allow_margin_finance: bool
Whether margin finance is allowed
alter_hours
instance-attribute
alter_hours: str
Reminder time
created_at
instance-attribute
created_at: str
Creation time
updated_at
instance-attribute
updated_at: str
Last updated time
next_trd_date
instance-attribute
next_trd_date: str
Next investment date
stock_name
instance-attribute
stock_name: str
Security name
cum_amount
instance-attribute
cum_amount: str
Cumulative invested amount
issue_number
instance-attribute
issue_number: int
Number of completed investment periods
average_cost
instance-attribute
average_cost: str
Average cost
cum_profit
instance-attribute
cum_profit: str
Cumulative profit/loss
DcaList
DCA plan list response.
plans
instance-attribute
plans: list[DcaPlan]
DCA plans
DcaStats
DCA statistics response.
active_count
instance-attribute
active_count: str
Number of active plans
finished_count
instance-attribute
finished_count: str
Number of finished plans
suspended_count
instance-attribute
suspended_count: str
Number of suspended plans
nearest_plans
instance-attribute
nearest_plans: list[DcaPlan]
Nearest upcoming plans
rest_days
instance-attribute
rest_days: str
Days until next investment
total_amount
instance-attribute
total_amount: str
Total invested amount
total_profit
instance-attribute
total_profit: str
Total profit/loss
DcaSupportInfo
DCA support info for one security.
symbol
instance-attribute
symbol: str
Security symbol
support_regular_saving
instance-attribute
support_regular_saving: bool
Whether DCA is supported for this security
DcaSupportList
DCA support check response.
infos
instance-attribute
infos: list[DcaSupportInfo]
Support info per security
DcaHistoryRecord
One DCA execution record.
created_at
instance-attribute
created_at: str
Execution time
order_id
instance-attribute
order_id: str
Associated order ID
status
instance-attribute
status: str
Status
action
instance-attribute
action: str
Action type
order_type
instance-attribute
order_type: str
Order type
executed_qty
instance-attribute
executed_qty: str
Executed quantity
executed_price
instance-attribute
executed_price: str
Executed price
executed_amount
instance-attribute
executed_amount: str
Executed amount
rejected_reason
instance-attribute
rejected_reason: str
Rejection reason (if any)
symbol
instance-attribute
symbol: str
Security symbol
DcaHistoryResponse
DCA execution history response.
records
instance-attribute
records: list[DcaHistoryRecord]
Execution history records
has_more
instance-attribute
has_more: bool
Whether more records exist
DcaCalcDateResult
Result for :meth:DCAContext.calc_date.
trade_date
instance-attribute
trade_date: str
Next projected trade date (unix timestamp string)
DCAFrequency
DCA investment frequency.
Daily
Bases: DCAFrequency
Weekly
Bases: DCAFrequency
Fortnightly
Bases: DCAFrequency
Monthly
Bases: DCAFrequency
DCAStatus
DCAContext
Dollar-cost averaging (DCA) plan management context.
Examples:
::
from longbridge.openapi import Config, DCAContext, DCAFrequency
config = Config.from_env()
ctx = DCAContext(config)
# Check support
support = ctx.check_support(["AAPL.US", "700.HK"])
for info in support.infos:
print(info.symbol, info.support_regular_saving)
# Get stats
stats = ctx.stats()
print("Active plans:", stats.active_count)
__init__
__init__(config: Config) -> None
Create a DCAContext.
list
list(status: DCAStatus | None = None, symbol: str | None = None) -> DcaList
create
create(symbol: str, amount: str, frequency: DCAFrequency, day_of_week: str | None = None, day_of_month: int | None = None, allow_margin: bool = False) -> DcaList
Create a new DCA plan.
| Parameters: |
|
|---|
pause
pause(plan_id: str) -> DcaList
Pause (suspend) a DCA plan.
resume
resume(plan_id: str) -> DcaList
Resume a suspended DCA plan.
stop
stop(plan_id: str) -> DcaList
Permanently stop a DCA plan.
history
history(plan_id: str, page: int = 1, limit: int = 20) -> DcaHistoryResponse
stats
stats(symbol: str | None = None) -> DcaStats
Get DCA statistics.
| Parameters: |
|
|---|
check_support
check_support(symbols: list[str]) -> DcaSupportList
calc_date
calc_date(symbol: str, frequency: DCAFrequency, day_of_week: str | None = None, day_of_month: int | None = None) -> DcaCalcDateResult
Calculate the next projected trade date for a DCA plan.
| Parameters: |
|
|---|
set_reminder
set_reminder(hours: str) -> None
Update the advance reminder time for DCA plans.
| Parameters: |
|
|---|
SharelistStock
A stock in a community sharelist.
symbol
instance-attribute
symbol: str
Security symbol
name
instance-attribute
name: str
Security name
market
instance-attribute
market: str
Market, e.g. "HK"
code
instance-attribute
code: str
Ticker code
intro
instance-attribute
intro: str
Brief description
unread_change_log_category
instance-attribute
unread_change_log_category: str
Unread change log category
change
instance-attribute
change: str | None
Day change percentage
last_done
instance-attribute
last_done: str | None
Latest price
trade_status
instance-attribute
trade_status: int | None
Trade status code
latency
instance-attribute
latency: bool | None
Whether delayed quote
SharelistScopes
Sharelist subscription scopes.
subscription
instance-attribute
subscription: bool
Whether the current user is subscribed
is_self
instance-attribute
is_self: bool
Whether the current user is the creator
SharelistInfo
Sharelist information.
id
instance-attribute
id: int
Sharelist ID
name
instance-attribute
name: str
Name
description
instance-attribute
description: str
Description
cover
instance-attribute
cover: str
Cover image URL
subscribers_count
instance-attribute
subscribers_count: int
Number of subscribers
this_year_chg
instance-attribute
this_year_chg: str
YTD change percentage
stocks
instance-attribute
stocks: list[SharelistStock]
Constituent stocks
subscribed
instance-attribute
subscribed: bool
Whether the current user is subscribed
chg
instance-attribute
chg: str
Day change percentage
sharelist_type
instance-attribute
sharelist_type: int
Type: 0=regular, 3=official, 4=industry
industry_code
instance-attribute
industry_code: str
Industry code (for industry sharelists)
SharelistList
Sharelist list response.
sharelists
instance-attribute
sharelists: list[SharelistInfo]
User's own and followed sharelists
subscribed_sharelists
instance-attribute
subscribed_sharelists: list[SharelistInfo]
Subscribed sharelists
tail_mark
instance-attribute
tail_mark: str
Pagination cursor for subscribed list
SharelistDetail
Sharelist detail response.
sharelist
instance-attribute
sharelist: SharelistInfo
Sharelist info
scopes
instance-attribute
scopes: SharelistScopes
Subscription scopes
SharelistContext
Community sharelist management context.
Examples:
::
from longbridge.openapi import Config, SharelistContext
config = Config.from_env()
ctx = SharelistContext(config)
lists = ctx.list(20)
for sl in lists.sharelists:
print(sl.name, len(sl.stocks), "stocks")
__init__
__init__(config: Config) -> None
Create a SharelistContext.
list
list(count: int = 20) -> SharelistList
List user's own and subscribed sharelists.
| Parameters: |
|
|---|
detail
detail(id: int) -> SharelistDetail
Get sharelist detail with constituent stocks.
| Parameters: |
|
|---|
popular
popular(count: int = 20) -> SharelistList
Get popular / trending sharelists.
| Parameters: |
|
|---|
create
create(name: str, description: str | None = None) -> SharelistDetail
add_securities
add_securities(id: int, symbols: list[str]) -> None
remove_securities
remove_securities(id: int, symbols: list[str]) -> None
ShortPositionsItem
One short-position data point (unified for US and HK markets).
timestamp
instance-attribute
timestamp: str
Trading date (RFC 3339)
rate
instance-attribute
rate: str
Short ratio (both markets)
close
instance-attribute
close: str
Closing price (both markets)
current_shares_short
instance-attribute
current_shares_short: str
[US] Number of short shares outstanding
avg_daily_share_volume
instance-attribute
avg_daily_share_volume: str
[US] Average daily share volume
days_to_cover
instance-attribute
days_to_cover: str
[US] Days to cover ratio
amount
instance-attribute
amount: str
[HK] Short sale amount (HKD)
balance
instance-attribute
balance: str
[HK] Short position balance
cost
instance-attribute
cost: str
[HK] Cost / closing price
ShortPositionsResponse
Short interest / positions response (HK or US).
data
instance-attribute
data: List[ShortPositionsItem]
Short position data points
ShortTradesItem
One short-trade data point (unified for US and HK markets).
timestamp
instance-attribute
timestamp: str
Trading date (RFC 3339)
rate
instance-attribute
rate: str
Short ratio
close
instance-attribute
close: str
Closing price
nus_amount
instance-attribute
nus_amount: str
[US] NYSE short amount
ny_amount
instance-attribute
ny_amount: str
[US] NY short amount
total_amount
instance-attribute
total_amount: str
[US] Total short amount
amount
instance-attribute
amount: str
[HK] Short sale amount
balance
instance-attribute
balance: str
[HK] Short position balance
ShortTradesResponse
Short trade records response (HK or US).
data
instance-attribute
data: List[ShortTradesItem]
Short trade data points
OptionVolumeStats
Real-time option call/put volume response.
c
instance-attribute
c: str
Total call volume
p
instance-attribute
p: str
Total put volume
OptionVolumeDailyStat
One day's option volume statistics.
symbol
instance-attribute
symbol: str
Underlying security symbol
timestamp
instance-attribute
timestamp: str
Settlement date (unix timestamp string)
total_volume
instance-attribute
total_volume: int
Total option volume (calls + puts)
total_put_volume
instance-attribute
total_put_volume: int
Total put volume
total_call_volume
instance-attribute
total_call_volume: int
Total call volume
put_call_volume_ratio
instance-attribute
put_call_volume_ratio: str
Put/call volume ratio
total_open_interest
instance-attribute
total_open_interest: int
Total open interest
total_put_open_interest
instance-attribute
total_put_open_interest: int
Total put open interest
total_call_open_interest
instance-attribute
total_call_open_interest: int
Total call open interest
put_call_open_interest_ratio
instance-attribute
put_call_open_interest_ratio: str
Put/call open interest ratio
OptionVolumeDaily
Daily historical option volume response.
stats
instance-attribute
stats: list[OptionVolumeDailyStat]
Daily option volume statistics