Code Reference
OpenApiException
Bases: Exception
OpenAPI exception
code
instance-attribute
code: Optional[int]
Error code
message
instance-attribute
message: str
Error message
__init__
__init__(code: int, message: str) -> None
HttpClient
A HTTP client for longPort open api
Parameters: |
---|
__init__
__init__(http_url: str, app_key: str, app_secret: str, access_token: str) -> None
from_env
classmethod
from_env() -> HttpClient
Create a new HttpClient
from the given environment variables
It first gets the environment variables from the .env
file in the current directory.
Variables
LONGPORT_HTTP_URL
- HTTP endpoint urlLONGPORT_APP_KEY
- App keyLONGPORT_APP_SECRET
- App secretLONGPORT_ACCESS_TOKEN
- Access token
request
request(method: str, path: str, headers: Optional[dict[str, str]] = None, body: Optional[Any] = None) -> Any
Performs a HTTP reqest
Examples:
::
from longport.openapi import HttpClient
client = HttpClient(http_url, app_key,
app_secret, access_token);
# get
resp = client.request("get", "/foo/bar");
print(resp)
# post
client.request("get", "/foo/bar", { "foo": 1, "bar": 2 });
PushCandlestickMode
Push candlestick mode
Realtime
Confirmed
Config
Configuration options for LongPort sdk
Parameters: |
|
---|
__init__
__init__(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) -> None
from_env
classmethod
from_env() -> Config
Create a new Config
from the given environment variables
It first gets the environment variables from the .env
file in the current directory.
Variables
LONGPORT_APP_KEY
- App keyLONGPORT_APP_SECRET
- App secretLONGPORT_ACCESS_TOKEN
- Access tokenLONGPORT_HTTP_URL
- HTTP endpoint urlLONGPORT_QUOTE_WS_URL
- Quote websocket endpoint urlLONGPORT_TRADE_WS_URL
- Trade websocket endpoint urlLONGPORT_ENABLE_OVERNIGHT
- Enable overnight quote,true
orfalse
(Default:false
)LONGPORT_PUSH_CANDLESTICK_MODE
-realtime
orconfirmed
(Default:realtime
)LONGPORT_PRINT_QUOTE_PACKAGES
- Print quote packages when connected,true
orfalse
(Default:true
)LONGPORT_LOG_PATH
- Set the path of the log files (Default:no logs
)
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
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 yield
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
Normal
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
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
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
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]], is_first_push: bool = False) -> None
Subscribe
Parameters: |
---|
Examples:
::
from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushQuote
def on_quote(symbol: str, event: PushQuote):
print(symbol, event)
config = Config.from_env()
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)
ctx.subscribe(["700.HK", "AAPL.US"], [
SubType.Quote], is_first_push = True)
sleep(30)
unsubscribe
unsubscribe(symbols: List[str], sub_types: List[Type[SubType]]) -> None
Unsubscribe
Parameters: |
---|
Examples:
::
from longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
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]) -> List[Candlestick]
Subscribe security candlesticks
Parameters: |
---|
Examples:
::
from longport.openapi import QuoteContext, Config, PushCandlestick
config = Config.from_env()
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)
sleep(30)
unsubscribe_candlesticks
unsubscribe_candlesticks(symbol: str, period: Type[Period]) -> None
subscriptions
subscriptions() -> List[Subscription]
Get subscription information
Examples:
::
from longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.warrant_quote(["21125.HK"])
print(resp)
depth
depth(symbol: str) -> SecurityDepth
Get security depth
Parameters: |
|
---|
Returns: |
|
---|
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.depth("700.HK")
print(resp)
brokers
brokers(symbol: str) -> SecurityBrokers
Get security brokers
Parameters: |
|
---|
Returns: |
|
---|
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.brokers("700.HK")
print(resp)
participants
participants() -> List[ParticipantInfo]
Get participants
Returns: |
|
---|
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.participants()
print(resp)
trades
trades(symbol: str, count: int) -> List[Trade]
intraday
intraday(symbol: str) -> List[IntradayLine]
Get security intraday lines
Parameters: |
|
---|
Returns: |
|
---|
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.intraday("700.HK")
print(resp)
candlesticks
candlesticks(symbol: str, period: Type[Period], count: int, adjust_type: Type[AdjustType]) -> List[Candlestick]
Get security candlesticks
Parameters: |
---|
Returns: |
|
---|
Examples:
::
from longport.openapi import QuoteContext, Config, Period, AdjustType
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.candlesticks(
"700.HK", Period.Day, 10, AdjustType.NoAdjust)
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) -> 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]) -> List[Candlestick]
option_chain_expiry_date_list
option_chain_expiry_date_list(symbol: str) -> List[date]
Get option chain expiry date list
Parameters: |
|
---|
Returns: |
---|
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config, WarrantSortBy, SortOrderType
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)
print(resp)
trading_session
trading_session() -> List[MarketTradingSession]
Get trading session of the day
Returns: |
|
---|
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config, Market
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config, CalcIndex
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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 longport.openapi import QuoteContext, Config
config = Config.from_env()
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)
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 longport.openapi import QuoteContext, Config, SecuritiesUpdateMode
config = Config.from_env()
ctx = QuoteContext(config)
ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace)
security_list
security_list(market: Type[Market], category: Type[SecurityListCategory]) -> List[Security]
Get security list
Parameters: |
|
---|
Returns: |
---|
Examples:
::
from longport.openapi import QuoteContext, Config, Market, SecurityListCategory
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.security_list(Market.HK, SecurityListCategory.Overnight)
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 longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [
SubType.Quote], is_first_push = True)
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 longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [
SubType.Depth], is_first_push = True)
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 longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [
SubType.Brokers], is_first_push = True)
sleep(5)
resp = ctx.realtime_brokers("700.HK")
print(resp)
realtime_trades
realtime_trades(symbol: str, count: int) -> 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 longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [
SubType.Trade], is_first_push = False)
sleep(5)
resp = ctx.realtime_trades("700.HK", 10)
print(resp)
realtime_candlesticks
realtime_candlesticks(symbol: str, period: Type[Period], count: int) -> 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 longport.openapi import QuoteContext, Config, Period
config = Config.from_env()
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)
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
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
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
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
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 longport.openapi import TradeContext, Config, OrderSide, OrderType, TimeInForceType, PushOrderChanged, TopicType
def on_order_changed(event: PushOrderChanged):
print(event)
config = Config.from_env()
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 longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.history_executions(
symbol = "700.HK",
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
today_executions
today_executions(symbol: Optional[str] = None, order_id: Optional[str] = None) -> List[Execution]
Get today executions
Parameters: |
---|
Returns: |
---|
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
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 longport.openapi import TradeContext, Config, OrderStatus, OrderSide, Market
config = Config.from_env()
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 longport.openapi import TradeContext, Config, OrderStatus, OrderSide, Market
config = Config.from_env()
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, remark: Optional[str] = None) -> None
Replace order
Parameters: |
|
---|
Examples:
::
from decimal import Decimal
from longport.openapi import TradeContext, Config
config = Config.from_env()
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, remark: Optional[str] = None) -> SubmitOrderResponse
Submit order
Parameters: |
|
---|
Returns: |
|
---|
Examples:
::
from decimal import Decimal
from longport.openapi import TradeContext, Config, OrderSide, OrderType, TimeInForceType
config = Config.from_env()
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 longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
ctx.cancel_order("709043056541253632")
account_balance
account_balance(currency: Optional[str] = None) -> List[AccountBalance]
Get account balance
Parameters: |
---|
Returns: |
|
---|
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
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 longport.openapi import TradeContext, Config
config = Config.from_env()
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 longport.openapi import TradeContext, Config
config = Config.from_env()
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 longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.stock_positions()
print(resp)
margin_ratio
margin_ratio(symbol: str) -> MarginRatio
Get margin ratio
Parameters: |
|
---|
Returns: |
|
---|
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
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 longport.openapi import TradeContext, Config
config = Config.from_env()
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 longport.openapi import TradeContext, Config, OrderType, OrderSide
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.estimate_max_purchase_quantity(
symbol = "700.HK",
order_type = OrderType.LO,
side = OrderSide.Buy,
)
print(resp)