Code Reference
AccountBalance
Account balance
buy_power: Decimal
instance-attribute
Buy power
cash_infos: List[CashInfo]
instance-attribute
Cash details
currency: str
instance-attribute
Currency
init_margin: Decimal
instance-attribute
Initial margin
maintenance_margin: Decimal
instance-attribute
Maintenance margin
margin_call: Decimal
instance-attribute
Margin call
max_finance_amount: Decimal
instance-attribute
Maximum financing amount
net_assets: Decimal
instance-attribute
Net assets
remaining_finance_amount: Decimal
instance-attribute
Remaining financing amount
risk_level: int
instance-attribute
Risk control level
total_cash: Decimal
instance-attribute
Total cash
AdjustType
Candlestick adjustment type
ForwardAdjust
NoAdjust
Brokers
Brokers
broker_ids: List[int]
instance-attribute
Broker IDs
position: int
instance-attribute
Position
CalcIndex
Calc index
Amplitude
BalancePoint
CallPrice
CapitalFlow
ChangeRate
ChangeValue
ConversionRatio
Delta
DividendRatioTtm
EffectiveLeverage
ExpiryDate
FiveDayChangeRate
FiveMinutesChangeRate
Gamma
HalfYearChangeRate
ImpliedVolatility
ItmOtm
LastDone
LeverageRatio
LowerStrikePrice
OpenInterest
OutstandingQty
OutstandingRatio
PbRatio
PeTtmRatio
Premium
Rho
StrikePrice
TenDayChangeRate
Theta
ToCallPrice
TotalMarketValue
Turnover
TurnoverRate
UpperStrikePrice
Vega
Volume
VolumeRatio
WarrantDelta
YtdChangeRate
Candlestick
Candlestick
close: Decimal
instance-attribute
Close price
high: Decimal
instance-attribute
High price
low: Decimal
instance-attribute
Low price
open: Decimal
instance-attribute
Open price
timestamp: datetime
instance-attribute
Timestamp
turnover: Decimal
instance-attribute
Turnover
volume: int
instance-attribute
Volume
CapitalDistribution
Capital distribution
large: Decimal
instance-attribute
Large order
medium: Decimal
instance-attribute
Medium order
small: Decimal
instance-attribute
Small order
CapitalDistributionResponse
Capital distribution response
capital_in: CapitalDistribution
instance-attribute
Inflow capital data
capital_out: CapitalDistribution
instance-attribute
Outflow capital data
timestamp: datetime
instance-attribute
Time
CapitalFlowLine
Capital flow line
inflow: Decimal
instance-attribute
Inflow capital data
timestamp: datetime
instance-attribute
Time
CashFlow
Cash flow
balance: Decimal
instance-attribute
Cash amount
business_time: datetime
instance-attribute
Business time
business_type: Type[BalanceType]
instance-attribute
Balance type
currency: str
instance-attribute
Cash currency
description: str
instance-attribute
Cash flow description
direction: Type[CashFlowDirection]
instance-attribute
Outflow direction
symbol: Optional[str]
instance-attribute
Associated Stock code information
transaction_flow_name: str
instance-attribute
Cash flow name
CashFlowDirection
Cash flow direction
In
Out
Unknown
CashInfo
CashInfo
available_cash: Decimal
instance-attribute
Available cash
currency: str
instance-attribute
Currency
frozen_cash: Decimal
instance-attribute
Frozen cash
settling_cash: Decimal
instance-attribute
Cash to be settled
withdraw_cash: Decimal
instance-attribute
Withdraw cash
ChargeCategoryCode
Charge category code
Broker
Third
Unknown
CommissionFreeStatus
Commission-free Status
Calculated
None_
Pending
Ready
Unknown
Config
Configuration options for LongPort sdk
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app_key
|
str
|
App Key |
required |
app_secret
|
str
|
App Secret |
required |
access_token
|
str
|
Access Token |
required |
http_url
|
Optional[str]
|
HTTP API url |
None
|
quote_ws_url
|
Optional[str]
|
Websocket url for quote API |
None
|
trade_ws_url
|
Optional[str]
|
Websocket url for trade API |
None
|
language
|
Optional[Type[Language]]
|
Language identifier |
None
|
enable_overnight
|
bool
|
Enable overnight quote |
False
|
push_candlestick_mode
|
Type[PushCandlestickMode]
|
Push candlestick mode |
Realtime
|
from_env()
classmethod
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
)
DeductionStatus
Deduction status
Done
NoData
None_
Pending
Unknown
Depth
Depth
order_num: int
instance-attribute
Number of orders
position: int
instance-attribute
Position
price: Optional[Decimal]
instance-attribute
Price
volume: int
instance-attribute
Volume
DerivativeType
Derivative type
Option
Warrant
EstimateMaxPurchaseQuantityResponse
Response for estimate maximum purchase quantity
cash_max_qty: int
instance-attribute
Cash available quantity
margin_max_qty: int
instance-attribute
Margin available quantity
Execution
Execution
order_id: str
instance-attribute
Order ID
price: Decimal
instance-attribute
Executed price
quantity: int
instance-attribute
Executed quantity
symbol: str
instance-attribute
Security code
trade_done_at: datetime
instance-attribute
Trade done time
trade_id: str
instance-attribute
Execution ID
FilterWarrantExpiryDate
Filter warrant expiry date type
Between_3_6
Between_6_12
GT_12
LT_3
FilterWarrantInOutBoundsType
Filter warrant in/out of the bounds type
In
Out
FundPosition
Fund position
cost_net_asset_value: Decimal
instance-attribute
Net cost
currency: str
instance-attribute
Currency
current_net_asset_value: Decimal
instance-attribute
Current equity
holding_units: Decimal
instance-attribute
Holding units
net_asset_value_day: datetime
instance-attribute
Current equity PyDecimal
symbol: str
instance-attribute
Fund ISIN code
symbol_name: str
instance-attribute
Fund name
FundPositionChannel
Fund position channel
account_channel: str
instance-attribute
Account type
positions: List[FundPosition]
instance-attribute
Fund positions
FundPositionsResponse
Fund positions response
channels: List[FundPositionChannel]
instance-attribute
Channels
HttpClient
A HTTP client for longPort open api
Parameters:
Name | Type | Description | Default |
---|---|---|---|
http_url
|
str
|
HTTP API url |
required |
app_key
|
str
|
App Key |
required |
app_secret
|
str
|
App Secret |
required |
access_token
|
str
|
Access Token |
required |
from_env()
classmethod
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(method, path, headers=None, body=None)
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 });
IntradayLine
Intraday line
avg_price: Decimal
instance-attribute
Average price
price: Decimal
instance-attribute
Close price of the minute
timestamp: datetime
instance-attribute
Start time of the minute
turnover: Decimal
instance-attribute
Turnover
volume: int
instance-attribute
Volume
IssuerInfo
Issuer info
issuer_id: int
instance-attribute
Issuer ID
name_cn: str
instance-attribute
Issuer name (zh-CN)
name_en: str
instance-attribute
Issuer name (en)
name_hk: str
instance-attribute
Issuer name (zh-HK)
Language
MarginRatio
Margin ratio
fm_factor: Decimal
instance-attribute
Forced close-out margin ratio
im_factor: Decimal
instance-attribute
Initial margin ratio
mm_factor: Decimal
instance-attribute
Maintain the initial margin ratio
Market
MarketTradingSession
Market trading session
market: Type[Market]
instance-attribute
Market
trade_sessions: List[TradingSessionInfo]
instance-attribute
Trading session
OpenApiException
Bases: Exception
OpenAPI exception
code: Optional[int]
instance-attribute
Error code
message: str
instance-attribute
Error message
OptionDirection
Option direction
Call
Put
Unknown
OptionQuote
Quote of option
contract_multiplier: Decimal
instance-attribute
Contract multiplier
contract_size: Decimal
instance-attribute
Contract size
contract_type: Type[OptionType]
instance-attribute
Option type
direction: Type[OptionDirection]
instance-attribute
Option direction
expiry_date: date
instance-attribute
Exprity date
high: Decimal
instance-attribute
High
historical_volatility: Decimal
instance-attribute
Underlying security historical volatility of the option
implied_volatility: Decimal
instance-attribute
Implied volatility
last_done: Decimal
instance-attribute
Latest price
low: Decimal
instance-attribute
Low
open: Decimal
instance-attribute
Open
open_interest: int
instance-attribute
Number of open positions
prev_close: Decimal
instance-attribute
Yesterday's close
strike_price: Decimal
instance-attribute
Strike price
symbol: str
instance-attribute
Security code
timestamp: datetime
instance-attribute
Time of latest price
trade_status: Type[TradeStatus]
instance-attribute
Security trading status
turnover: Decimal
instance-attribute
Turnover
underlying_symbol: str
instance-attribute
Underlying security symbol of the option
volume: int
instance-attribute
Volume
OptionType
Option type
American
Europe
Unknown
Order
Order
currency: str
instance-attribute
Currency
executed_price: Optional[Decimal]
instance-attribute
Executed price
executed_quantity: int
instance-attribute
Executed quantity
expire_date: Optional[date]
instance-attribute
Long term order expire date
last_done: Optional[Decimal]
instance-attribute
Last done
limit_offset: Optional[Decimal]
instance-attribute
TSLPAMT
/ TSLPPCT
order limit offset amount
msg: str
instance-attribute
Rejected Message or remark
order_id: str
instance-attribute
Order ID
order_type: Type[OrderType]
instance-attribute
Order type
outside_rth: Optional[Type[OutsideRTH]]
instance-attribute
Enable or disable outside regular trading hours
price: Optional[Decimal]
instance-attribute
Submitted price
quantity: int
instance-attribute
Submitted quantity
remark: str
instance-attribute
Remark
side: Type[OrderSide]
instance-attribute
Order side
status: Type[OrderStatus]
instance-attribute
Order status
stock_name: str
instance-attribute
Stock name
submitted_at: datetime
instance-attribute
Submitted time
symbol: str
instance-attribute
Security code
tag: Type[OrderTag]
instance-attribute
Order tag
time_in_force: Type[TimeInForceType]
instance-attribute
Time in force type
trailing_amount: Optional[Decimal]
instance-attribute
TSMAMT
/ TSLPAMT
order trailing amount
trailing_percent: Optional[Decimal]
instance-attribute
TSMPCT
/ TSLPPCT
order trailing percent
trigger_at: Optional[datetime]
instance-attribute
Conditional order trigger time
trigger_price: Optional[Decimal]
instance-attribute
LIT
/ MIT
Order Trigger Price
trigger_status: Optional[Type[TriggerStatus]]
instance-attribute
Conditional order trigger status
updated_at: Optional[datetime]
instance-attribute
Last updated time
OrderChargeDetail
Order charge detail
currency: str
instance-attribute
Settlement currency
items: List[OrderChargeItem]
instance-attribute
Order charge items
total_amount: Decimal
instance-attribute
Total charges amount
OrderChargeFee
Order charge fee
amount: Decimal
instance-attribute
Charge amount
code: str
instance-attribute
Charge code
currency: str
instance-attribute
Charge currency
name: str
instance-attribute
Charge name
OrderChargeItem
Order charge item
code: Type[ChargeCategoryCode]
instance-attribute
Charge category code
fees: List[OrderChargeFee]
instance-attribute
Charge details
name: str
instance-attribute
Charge category name
OrderDetail
Order detail
charge_detail: OrderChargeDetail
instance-attribute
Order charges
currency: str
instance-attribute
Currency
deductions_amount: Optional[Decimal]
instance-attribute
Deduction amount
deductions_currency: Optional[str]
instance-attribute
Deduction currency
deductions_status: Type[DeductionStatus]
instance-attribute
Deduction status
executed_price: Optional[Decimal]
instance-attribute
Executed price
executed_quantity: int
instance-attribute
Executed quantity
expire_date: Optional[date]
instance-attribute
Long term order expire date
free_amount: Optional[Decimal]
instance-attribute
Commission-free amount
free_currency: Optional[str]
instance-attribute
Commission-free currency
free_status: Type[CommissionFreeStatus]
instance-attribute
Commission-free Status
history: List[OrderHistoryDetail]
instance-attribute
Order history details
last_done: Optional[Decimal]
instance-attribute
Last done
limit_offset: Optional[Decimal]
instance-attribute
TSLPAMT
/ TSLPPCT
order limit offset amount
msg: str
instance-attribute
Rejected Message or remark
order_id: str
instance-attribute
Order ID
order_type: Type[OrderType]
instance-attribute
Order type
outside_rth: Optional[Type[OutsideRTH]]
instance-attribute
Enable or disable outside regular trading hours
platform_deducted_amount: Optional[Decimal]
instance-attribute
Platform deduction amount
platform_deducted_currency: Optional[str]
instance-attribute
Platform deduction currency
platform_deducted_status: Type[DeductionStatus]
instance-attribute
Platform fee deduction status
price: Optional[Decimal]
instance-attribute
Submitted price
quantity: int
instance-attribute
Submitted quantity
remark: str
instance-attribute
Remark
side: Type[OrderSide]
instance-attribute
Order side
status: Type[OrderStatus]
instance-attribute
Order status
stock_name: str
instance-attribute
Stock name
submitted_at: datetime
instance-attribute
Submitted time
symbol: str
instance-attribute
Security code
tag: Type[OrderTag]
instance-attribute
Order tag
time_in_force: Type[TimeInForceType]
instance-attribute
Time in force type
trailing_amount: Optional[Decimal]
instance-attribute
TSMAMT
/ TSLPAMT
order trailing amount
trailing_percent: Optional[Decimal]
instance-attribute
TSMPCT
/ TSLPPCT
order trailing percent
trigger_at: Optional[datetime]
instance-attribute
Conditional order trigger time
trigger_price: Optional[Decimal]
instance-attribute
LIT
/ MIT
Order Trigger Price
trigger_status: Optional[Type[TriggerStatus]]
instance-attribute
Conditional order trigger status
updated_at: Optional[datetime]
instance-attribute
Last updated time
OrderHistoryDetail
Order history detail
msg: str
instance-attribute
Execution or error message
price: Decimal
instance-attribute
Executed price for executed orders, submitted price for expired, canceled, rejected orders, etc.
quantity: int
instance-attribute
Executed quantity for executed orders, remaining quantity for expired, canceled, rejected orders, etc.
status: Type[OrderStatus]
instance-attribute
Order status
time: datetime
instance-attribute
Occurrence time
OrderSide
OrderStatus
Order status
Canceled
Expired
Filled
New
NotReported
PartialFilled
PartialWithdrawal
PendingCancel
PendingReplace
ProtectedNotReported
Rejected
Replaced
ReplacedNotReported
Unknown
VarietiesNotReported
WaitToCancel
WaitToNew
WaitToReplace
OrderTag
Order tag
AllocatedSub
Creditor
Debtor
Grey
LongTerm
MarginCall
NonExercise
Normal
Offline
Unknown
OrderType
Order type
ALO
AO
ELO
LIT
LO
MIT
MO
ODD
SLO
TSLPAMT
TSLPPCT
TSMAMT
TSMPCT
Unknown
OutsideRTH
Enable or disable outside regular trading hours
AnyTime
Overnight
RTHOnly
Unknown
ParticipantInfo
Participant info
broker_ids: List[int]
instance-attribute
Broker IDs
name_cn: str
instance-attribute
Participant name (zh-CN)
name_en: str
instance-attribute
Participant name (en)
name_hk: str
instance-attribute
Participant name (zh-HK)
Period
Candlestick period
Day
Min_1
Min_15
Min_30
Min_5
Min_60
Month
Unknown
Week
Year
PrePostQuote
Quote of US pre/post market
high: Decimal
instance-attribute
High
last_done: Decimal
instance-attribute
Latest price
low: Decimal
instance-attribute
Low
prev_close: Decimal
instance-attribute
Close of the last trade session
timestamp: datetime
instance-attribute
Time of latest price
turnover: Decimal
instance-attribute
Turnover
volume: int
instance-attribute
Volume
PushBrokers
Brokers message
ask_brokers: List[Brokers]
instance-attribute
Ask brokers
bid_brokers: List[Brokers]
instance-attribute
Bid brokers
PushCandlestick
Candlestick updated event
candlestick: Candlestick
instance-attribute
Candlestick
period: Period
instance-attribute
Period type
PushCandlestickMode
Push candlestick mode
Confirmed
Realtime
PushDepth
Depth message
asks: List[Depth]
instance-attribute
Ask depth
bids: List[Depth]
instance-attribute
Bid depth
PushOrderChanged
Order changed message
account_no: str
instance-attribute
Account no
currency: str
instance-attribute
Currency
executed_price: Optional[Decimal]
instance-attribute
Executed price
executed_quantity: int
instance-attribute
Executed quantity
last_price: Optional[Decimal]
instance-attribute
Last price
last_share: Optional[Decimal]
instance-attribute
Last share
limit_offset: Optional[Decimal]
instance-attribute
Limit offset amount
msg: str
instance-attribute
Rejected message or remark
order_id: str
instance-attribute
Order ID
order_type: Type[OrderType]
instance-attribute
Order type
remark: str
instance-attribute
Remark message
side: Type[OrderSide]
instance-attribute
Order side
status: Type[OrderStatus]
instance-attribute
Order status
stock_name: str
instance-attribute
Stock name
submitted_at: datetime
instance-attribute
Submitted time
submitted_price: Decimal
instance-attribute
Submitted price
submitted_quantity: int
instance-attribute
Submitted quantity
symbol: str
instance-attribute
Order symbol
tag: Type[OrderTag]
instance-attribute
Order tag
trailing_amount: Optional[Decimal]
instance-attribute
Trailing amount
trailing_percent: Optional[Decimal]
instance-attribute
Trailing percent
trigger_at: Optional[datetime]
instance-attribute
Conditional order trigger time
trigger_price: Optional[Decimal]
instance-attribute
Order trigger price
trigger_status: Optional[Type[TriggerStatus]]
instance-attribute
Conditional order trigger status
updated_at: datetime
instance-attribute
Last updated time
PushQuote
Quote message
high: Decimal
instance-attribute
High
last_done: Decimal
instance-attribute
Latest price
low: Decimal
instance-attribute
Low
open: Decimal
instance-attribute
Open
timestamp: datetime
instance-attribute
Time of latest price
trade_session: Type[TradeSession]
instance-attribute
Trade session
trade_status: Type[TradeStatus]
instance-attribute
Security trading status
turnover: Decimal
instance-attribute
Turnover
volume: int
instance-attribute
Volume
PushTrades
Trades message
trades: List[Trade]
instance-attribute
Trades data
QuoteContext
Quote context
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
Config
|
Configuration object |
required |
brokers(symbol)
Get security brokers
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
SecurityBrokers
|
Security brokers |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.brokers("700.HK")
print(resp)
calc_indexes(symbols, indexes)
Get calc indexes
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
indexes
|
List[Type[CalcIndex]]
|
Calc indexes |
required |
Returns:
Type | Description |
---|---|
List[SecurityCalcIndex]
|
Calc indexes of the symbols |
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)
candlesticks(symbol, period, count, adjust_type)
Get security candlesticks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
period
|
Type[Period]
|
Candlestick period |
required |
count
|
int
|
Count of cancdlestick (Maximum is |
required |
adjust_type
|
Type[AdjustType]
|
Adjustment type |
required |
Returns:
Type | Description |
---|---|
List[Candlestick]
|
Candlesticks |
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)
capital_distribution(symbol)
Get capital distribution
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
CapitalDistributionResponse
|
Capital distribution |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.capital_distribution("700.HK")
print(resp)
capital_flow(symbol)
Get capital flow intraday
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
List[CapitalFlowLine]
|
Capital flow list |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.capital_flow("700.HK")
print(resp)
create_watchlist_group(name, securities=None)
Create watchlist group
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Group name |
required |
securities
|
Optional[List[str]]
|
Securities |
None
|
Returns:
Type | Description |
---|---|
int
|
Group ID |
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(id, purge=False)
Delete watchlist group
Parameters:
Name | Type | Description | Default |
---|---|---|---|
id
|
int
|
Group ID |
required |
purge
|
bool
|
Move securities in this group to the default group |
False
|
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
ctx.delete_watchlist_group(10086)
depth(symbol)
Get security depth
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
SecurityDepth
|
Security depth |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.depth("700.HK")
print(resp)
history_candlesticks_by_date(symbol, period, adjust_type, start, end)
history_candlesticks_by_offset(symbol, period, adjust_type, forward, time, count)
Get security history candlesticks by offset
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
period
|
Type[Period]
|
Period type |
required |
adjust_type
|
Type[AdjustType]
|
Adjust type |
required |
forward
|
bool
|
If |
required |
time
|
datetime
|
Datetime |
required |
count
|
int
|
Count of candlesticks |
required |
intraday(symbol)
Get security intraday lines
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
List[IntradayLine]
|
Intraday lines |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.intraday("700.HK")
print(resp)
member_id()
Returns the member ID
option_chain_expiry_date_list(symbol)
Get option chain expiry date list
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
List[date]
|
Option chain expiry date list |
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(symbol, expiry_date)
Get option chain info by date
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
expiry_date
|
date
|
Expiry date |
required |
Returns:
Type | Description |
---|---|
List[StrikePriceInfo]
|
Option chain info |
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)
option_quote(symbols)
Get quote of option securities
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
Returns:
Type | Description |
---|---|
List[OptionQuote]
|
Option quote list |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.option_quote(["AAPL230317P160000.US"])
print(resp)
participants()
Get participants
Returns:
Type | Description |
---|---|
List[ParticipantInfo]
|
Participants |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.participants()
print(resp)
quote(symbols)
Get quote of securities
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
Returns:
Type | Description |
---|---|
List[SecurityQuote]
|
Security quote list |
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)
quote_level()
Returns the quote level
quote_package_details()
Returns the quote package details
realtime_brokers(symbol)
Get real-time brokers
Get real-time brokers of the subscribed symbols, it always returns the data in the local storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
SecurityBrokers
|
Security brokers |
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_candlesticks(symbol, period, count)
Get real-time candlesticks
Get Get real-time candlesticks of the subscribed symbols, it always returns the data in the local storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
period
|
Type[Period]
|
Period type |
required |
count
|
int
|
Count of candlesticks |
required |
Returns:
Type | Description |
---|---|
List[Candlestick]
|
Security candlesticks |
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)
realtime_depth(symbol)
Get real-time depth
Get real-time depth of the subscribed symbols, it always returns the data in the local storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
Returns:
Type | Description |
---|---|
SecurityDepth
|
Security depth |
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_quote(symbols)
Get real-time quote
Get real-time quotes of the subscribed symbols, it always returns the data in the local storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
Returns:
Type | Description |
---|---|
List[RealtimeQuote]
|
Quote list |
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_trades(symbol, count)
Get real-time trades
Get real-time trades of the subscribed symbols, it always returns the data in the local storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
count
|
int
|
Count of trades |
required |
Returns:
Type | Description |
---|---|
List[Trade]
|
Security trades |
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)
security_list(market, category)
Get security list
Parameters:
Name | Type | Description | Default |
---|---|---|---|
market
|
Type[Market]
|
Market |
required |
category
|
Type[SecurityListCategory]
|
Security list category |
required |
Returns:
Type | Description |
---|---|
List[Security]
|
Security list |
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)
set_on_brokers(callback)
Set brokers callback, after receiving the brokers data push, it will call back to this function.
set_on_candlestick(callback)
Set candlestick callback, after receiving the candlestick updated event, it will call back to this function.
set_on_depth(callback)
Set depth callback, after receiving the depth data push, it will call back to this function.
set_on_quote(callback)
Set quote callback, after receiving the quote data push, it will call back to this function.
set_on_trades(callback)
Set trades callback, after receiving the trades data push, it will call back to this function.
static_info(symbols)
Get basic information of securities
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
Returns:
Type | Description |
---|---|
List[SecurityStaticInfo]
|
Security info list |
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)
subscribe(symbols, sub_types, is_first_push=False)
Subscribe
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
sub_types
|
List[Type[SubType]]
|
Subscribe types |
required |
is_first_push
|
bool
|
Whether to perform a data push immediately after subscribing. (trade not supported) |
False
|
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)
subscribe_candlesticks(symbol, period)
Subscribe security candlesticks
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
period
|
Type[Period]
|
Period type |
required |
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)
subscriptions()
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)
trades(symbol, count)
Get security trades
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
count
|
int
|
Count of trades (Maximum is |
required |
Returns:
Type | Description |
---|---|
List[Trade]
|
Trades |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.trades("700.HK", 10)
print(resp)
trading_days(market, begin, end)
Get trading session of the day
The interval must be less than one month, and only the most recent year is supported.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
market
|
Type[Market]
|
Market |
required |
begin
|
date
|
Begin date |
required |
end
|
date
|
End date |
required |
Returns:
Type | Description |
---|---|
MarketTradingDays
|
Trading days |
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)
trading_session()
Get trading session of the day
Returns:
Type | Description |
---|---|
List[MarketTradingSession]
|
Trading session of the day |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.trading_session()
print(resp)
unsubscribe(symbols, sub_types)
Unsubscribe
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
sub_types
|
List[Type[SubType]]
|
Subscribe types |
required |
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])
unsubscribe_candlesticks(symbol, period)
update_watchlist_group(id, name=None, securities=None, mode=None)
Update watchlist group
Parameters:
Name | Type | Description | Default |
---|---|---|---|
id
|
int
|
Group ID |
required |
name
|
Optional[str]
|
Group name |
None
|
securities
|
Optional[List[str]]
|
Securities |
None
|
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)
warrant_issuers()
Get warrant issuers
Returns:
Type | Description |
---|---|
List[IssuerInfo]
|
Warrant issuers |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.warrant_issuers()
print(resp)
warrant_list(symbol, sort_by, sort_order, warrant_type=None, issuer=None, expiry_date=None, price_type=None, status=None)
Get warrant list
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
sort_by
|
Type[WarrantSortBy]
|
Sort by field |
required |
sort_order
|
Type[SortOrderType]
|
Sort order |
required |
warrant_type
|
Optional[List[Type[WarrantType]]]
|
Filter by warrant type |
None
|
issuer
|
Optional[List[int]]
|
Filter by issuer |
None
|
expiry_date
|
Optional[List[Type[FilterWarrantExpiryDate]]]
|
Filter by expiry date |
None
|
price_type
|
Optional[List[Type[FilterWarrantInOutBoundsType]]]
|
Filter by price type |
None
|
status
|
Optional[List[Type[WarrantStatus]]]
|
Filter by status |
None
|
Returns:
Type | Description |
---|---|
List[WarrantInfo]
|
Warrant list |
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)
warrant_quote(symbols)
Get quote of warrant securities
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
List[str]
|
Security codes |
required |
Returns:
Type | Description |
---|---|
List[WarrantQuote]
|
Warrant quote list |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.warrant_quote(["21125.HK"])
print(resp)
watchlist()
Get watch list
Returns:
Type | Description |
---|---|
List[WatchlistGroup]
|
Watch list groups |
Examples:
::
from longport.openapi import QuoteContext, Config
config = Config.from_env()
ctx = QuoteContext(config)
resp = ctx.watchlist()
print(resp)
QuotePackageDetail
Quote package detail
description: str
instance-attribute
Description
end_at: datetime
instance-attribute
End time
key: str
instance-attribute
Key
name: str
instance-attribute
Name
start_at: datetime
instance-attribute
Start time
RealtimeQuote
Real-time quote
high: Decimal
instance-attribute
High
last_done: Decimal
instance-attribute
Latest price
low: Decimal
instance-attribute
Low
open: Decimal
instance-attribute
Open
symbol: str
instance-attribute
Security code
timestamp: datetime
instance-attribute
Time of latest price
trade_status: Type[TradeStatus]
instance-attribute
Security trading status
turnover: Decimal
instance-attribute
Turnover
volume: int
instance-attribute
Volume
SecuritiesUpdateMode
Securities update mode
Add
Remove
Replace
Security
Security
name_cn: str
instance-attribute
Security name (zh-CN)
name_en: str
instance-attribute
Security name (en)
name_hk: str
instance-attribute
Security name (zh-HK)
symbol: str
instance-attribute
Security code
SecurityBoard
Security board
CNIX
CNSector
HKEquity
HKHS
HKPreIPO
HKSector
HKWarrant
SGMain
SGSector
SHMainConnect
SHMainNonConnect
SHSTAR
STI
SZGEMConnect
SZGEMNonConnect
SZMainConnect
SZMainNonConnect
USDJI
USMain
USNSDQ
USOption
USOptionS
USPink
USSector
Unknown
SecurityBrokers
Security brokers
ask_brokers: List[Brokers]
instance-attribute
Ask brokers
bid_brokers: List[Brokers]
instance-attribute
Bid brokers
SecurityCalcIndex
Security calc index response
amplitude: Optional[Decimal]
instance-attribute
Amplitude
balance_point: Optional[Decimal]
instance-attribute
Breakeven point
call_price: Optional[Decimal]
instance-attribute
Call price
capital_flow: Optional[Decimal]
instance-attribute
Capital flow
change_rate: Optional[Decimal]
instance-attribute
Change ratio
change_value: Optional[Decimal]
instance-attribute
Change value
conversion_ratio: Optional[Decimal]
instance-attribute
Conversion ratio
delta: Optional[Decimal]
instance-attribute
Delta
dividend_ratio_ttm: Optional[Decimal]
instance-attribute
Dividend ratio (TTM)
effective_leverage: Optional[Decimal]
instance-attribute
Effective leverage
expiry_date: Optional[date]
instance-attribute
Expiry date
five_day_change_rate: Optional[Decimal]
instance-attribute
Five days change ratio
five_minutes_change_rate: Optional[Decimal]
instance-attribute
Five minutes change ratio
gamma: Optional[Decimal]
instance-attribute
Gamma
half_year_change_rate: Optional[Decimal]
instance-attribute
Half year change ratio
implied_volatility: Optional[Decimal]
instance-attribute
Implied volatility
itm_otm: Optional[Decimal]
instance-attribute
In/out of the bound
last_done: Optional[Decimal]
instance-attribute
Latest price
leverage_ratio: Optional[Decimal]
instance-attribute
Leverage ratio
lower_strike_price: Optional[Decimal]
instance-attribute
Lower bound price
open_interest: Optional[int]
instance-attribute
Open interest
outstanding_qty: Optional[int]
instance-attribute
Outstanding quantity
outstanding_ratio: Optional[Decimal]
instance-attribute
Outstanding ratio
pb_ratio: Optional[Decimal]
instance-attribute
PB
pe_ttm_ratio: Optional[Decimal]
instance-attribute
PE (TTM)
premium: Optional[Decimal]
instance-attribute
Premium
rho: Optional[Decimal]
instance-attribute
Rho
strike_price: Optional[Decimal]
instance-attribute
Strike price
symbol: str
instance-attribute
Security symbol
ten_day_change_rate: Optional[Decimal]
instance-attribute
Ten days change ratio
theta: Optional[Decimal]
instance-attribute
Theta
to_call_price: Optional[Decimal]
instance-attribute
Price interval from the call price
total_market_value: Optional[Decimal]
instance-attribute
Total market value
turnover: Optional[Decimal]
instance-attribute
Turnover
turnover_rate: Optional[Decimal]
instance-attribute
turnover_rate
upper_strike_price: Optional[Decimal]
instance-attribute
Upper bound price
vega: Optional[Decimal]
instance-attribute
Vega
volume: Optional[int]
instance-attribute
Volume
volume_ratio: Optional[Decimal]
instance-attribute
Volume ratio
warrant_delta: Optional[Decimal]
instance-attribute
Warrant delta
ytd_change_rate: Optional[Decimal]
instance-attribute
Year-to-date change ratio
SecurityDepth
Security depth
asks: List[Depth]
instance-attribute
Ask depth
bids: List[Depth]
instance-attribute
Bid depth
SecurityListCategory
Security list category
Overnight
SecurityQuote
Quote of securitity
high: Decimal
instance-attribute
High
last_done: Decimal
instance-attribute
Latest price
low: Decimal
instance-attribute
Low
open: Decimal
instance-attribute
Open
overnight_quote: Optional[PrePostQuote]
instance-attribute
Quote of US overnight market
post_market_quote: Optional[PrePostQuote]
instance-attribute
Quote of US post market
pre_market_quote: Optional[PrePostQuote]
instance-attribute
Quote of US pre market
prev_close: Decimal
instance-attribute
Yesterday's close
symbol: str
instance-attribute
Security code
timestamp: datetime
instance-attribute
Time of latest price
trade_status: Type[TradeStatus]
instance-attribute
Security trading status
turnover: Decimal
instance-attribute
Turnover
volume: int
instance-attribute
Volume
SecurityStaticInfo
The basic information of securities
board: Type[SecurityBoard]
instance-attribute
Board
bps: Decimal
instance-attribute
Net assets per share
circulating_shares: int
instance-attribute
Circulating shares
currency: str
instance-attribute
Trading currency
dividend_yield: Decimal
instance-attribute
Dividend yield
eps: Decimal
instance-attribute
Earnings per share
eps_ttm: Decimal
instance-attribute
Earnings per share (TTM)
exchange: str
instance-attribute
Exchange which the security belongs to
hk_shares: int
instance-attribute
HK shares (only HK stocks)
lot_size: int
instance-attribute
Lot size
name_cn: str
instance-attribute
Security name (zh-CN)
name_en: str
instance-attribute
Security name (en)
name_hk: str
instance-attribute
Security name (zh-HK)
stock_derivatives: List[Type[DerivativeType]]
instance-attribute
Types of supported derivatives
symbol: str
instance-attribute
Security code
total_shares: int
instance-attribute
Total shares
SortOrderType
Sort order type
Ascending
Descending
StockPosition
Stock position
available_quantity: int
instance-attribute
Available quantity
cost_price: Decimal
instance-attribute
Cost Price(According to the client's choice of average purchase or diluted cost)
currency: str
instance-attribute
Currency
init_quantity: Optional[int]
instance-attribute
Initial position before market opening
market: Market
instance-attribute
Market
quantity: int
instance-attribute
The number of holdings
symbol: str
instance-attribute
Stock code
symbol_name: str
instance-attribute
Stock name
StockPositionChannel
Stock position channel
account_channel: str
instance-attribute
Account type
positions: List[StockPosition]
instance-attribute
Stock positions
StockPositionsResponse
Stock positions response
channels: List[StockPositionChannel]
instance-attribute
Channels
StrikePriceInfo
Strike price info
call_symbol: str
instance-attribute
Security code of call option
price: Decimal
instance-attribute
Strike price
put_symbol: str
instance-attribute
Security code of put option
standard: bool
instance-attribute
Is standard
SubType
SubmitOrderResponse
Response for submit order request
order_id: str
instance-attribute
Order id
Subscription
Subscription
candlesticks: List[Type[Period]]
instance-attribute
Candlesticks
sub_types: List[Type[SubType]]
instance-attribute
Subscription types
symbol: str
instance-attribute
Security code
TimeInForceType
Time in force type
Day
GoodTilCanceled
GoodTilDate
Unknown
TopicType
Topic type
Private
Trade
Trade
direction: Type[TradeDirection]
instance-attribute
Trade direction
price: Decimal
instance-attribute
Price
timestamp: datetime
instance-attribute
Time of trading
trade_session: Type[TradeSession]
instance-attribute
Trade session
trade_type: str
instance-attribute
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)
volume: int
instance-attribute
Volume
TradeContext
Trade context
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
Config
|
Configuration object |
required |
account_balance(currency=None)
Get account balance
Parameters:
Name | Type | Description | Default |
---|---|---|---|
currency
|
Optional[str]
|
Currency |
None
|
Returns:
Type | Description |
---|---|
List[AccountBalance]
|
Account list |
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.account_balance()
print(resp)
cancel_order(order_id)
Cancel order
Parameters:
Name | Type | Description | Default |
---|---|---|---|
order_id
|
str
|
Order ID |
required |
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
ctx.cancel_order("709043056541253632")
cash_flow(start_at, end_at, business_type=None, symbol=None, page=None, size=None)
Get cash flow
Parameters:
Name | Type | Description | Default |
---|---|---|---|
start_at
|
datetime
|
Start time |
required |
end_at
|
datetime
|
End time |
required |
business_type
|
Optional[Type[BalanceType]]
|
Balance type |
None
|
symbol
|
Optional[str]
|
Target security code |
None
|
page
|
Optional[int]
|
Start page (Default: 1) |
None
|
size
|
Optional[int]
|
Page size (Default: 50) |
None
|
Returns:
Type | Description |
---|---|
List[CashFlow]
|
Cash flow list |
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)
estimate_max_purchase_quantity(symbol, order_type, side, price=None, currency=None, order_id=None)
Estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security symbol |
required |
order_type
|
Type[OrderType]
|
Order type |
required |
side
|
Type[OrderSide]
|
Order side |
required |
price
|
Optional[Decimal]
|
Estimated order price, |
None
|
currency
|
Optional[str]
|
Settlement currency |
None
|
order_id
|
Optional[str]
|
Order ID, required when estimating the maximum purchase quantity for a modified order |
None
|
Returns:
Type | Description |
---|---|
EstimateMaxPurchaseQuantityResponse
|
Response |
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)
fund_positions(symbols=None)
Get fund positions
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
Optional[List[str]]
|
Filter by fund codes |
None
|
Returns:
Type | Description |
---|---|
FundPositionsResponse
|
Fund positions |
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.fund_positions()
print(resp)
history_executions(symbol=None, start_at=None, end_at=None)
Get history executions
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
Optional[str]
|
Filter by security code, example: |
None
|
start_at
|
Optional[datetime]
|
Start time |
None
|
end_at
|
Optional[datetime]
|
End time |
None
|
Returns:
Type | Description |
---|---|
List[Execution]
|
Execution list |
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)
history_orders(symbol=None, status=None, side=None, market=None, start_at=None, end_at=None)
Get history orders
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
Optional[str]
|
Filter by security code |
None
|
status
|
Optional[List[Type[OrderStatus]]]
|
Filter by order status |
None
|
side
|
Optional[Type[OrderSide]]
|
Filter by order side |
None
|
market
|
Optional[Type[Market]]
|
Filter by market type |
None
|
start_at
|
Optional[datetime]
|
Start time |
None
|
end_at
|
Optional[datetime]
|
End time |
None
|
Returns:
Type | Description |
---|---|
List[Order]
|
Order list |
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)
margin_ratio(symbol)
Get margin ratio
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security symbol |
required |
Returns:
Type | Description |
---|---|
MarginRatio
|
Margin ratio |
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_id)
Get order detail
Parameters:
Name | Type | Description | Default |
---|---|---|---|
order
|
id
|
Order id |
required |
Returns:
Type | Description |
---|---|
OrderDetail
|
Order detail |
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.order_detail("701276261045858304")
print(resp)
replace_order(order_id, quantity, price=None, trigger_price=None, limit_offset=None, trailing_amount=None, trailing_percent=None, remark=None)
Replace order
Parameters:
Name | Type | Description | Default |
---|---|---|---|
quantity
|
int
|
Replaced quantity |
required |
price
|
Optional[Decimal]
|
Replaced price |
None
|
trigger_price
|
Optional[Decimal]
|
Trigger price ( |
None
|
limit_offset
|
Optional[Decimal]
|
Limit offset amount ( |
None
|
trailing_amount
|
Optional[Decimal]
|
Trailing amount ( |
None
|
trailing_percent
|
Optional[Decimal]
|
Trailing percent ( |
None
|
remark
|
Optional[str]
|
Remark (Maximum 64 characters) |
None
|
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 = 100,
price = Decimal("100"),
)
set_on_order_changed(callback)
Set order changed callback, after receiving the order changed event, it will call back to this function.
stock_positions(symbols=None)
Get stock positions
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbols
|
Optional[List[str]]
|
Filter by stock codes |
None
|
Returns:
Type | Description |
---|---|
StockPositionsResponse
|
Stock positions |
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.stock_positions()
print(resp)
submit_order(symbol, order_type, side, submitted_quantity, time_in_force, submitted_price=None, trigger_price=None, limit_offset=None, trailing_amount=None, trailing_percent=None, expire_date=None, outside_rth=None, remark=None)
Submit order
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
str
|
Security code |
required |
order_type
|
Type[OrderType]
|
Order type |
required |
side
|
Type[OrderSide]
|
Order Side |
required |
submitted_quantity
|
int
|
Submitted quantity |
required |
time_in_force
|
Type[TimeInForceType]
|
Time in force type |
required |
submitted_price
|
Optional[Decimal]
|
Submitted price |
None
|
trigger_price
|
Optional[Decimal]
|
Trigger price ( |
None
|
limit_offset
|
Optional[Decimal]
|
Limit offset amount ( |
None
|
trailing_amount
|
Optional[Decimal]
|
Trailing amount ( |
None
|
trailing_percent
|
Optional[Decimal]
|
Trailing percent ( |
None
|
expire_date
|
Optional[date]
|
Long term order expire date (Required when |
None
|
outside_rth
|
Optional[Type[OutsideRTH]]
|
Enable or disable outside regular trading hours |
None
|
remark
|
Optional[str]
|
Remark (Maximum 64 characters) |
None
|
Returns:
Type | Description |
---|---|
SubmitOrderResponse
|
Response |
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 = 200,
time_in_force = TimeInForceType.Day,
remark = "Hello from Python SDK",
)
print(resp)
subscribe(topics)
Subscribe
Parameters:
Name | Type | Description | Default |
---|---|---|---|
topics
|
List[Type[TopicType]]
|
Topic list |
required |
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=200,
time_in_force=TimeInForceType.Day,
remark="Hello from Python SDK",
)
print(resp)
sleep(5) # waiting for push event
today_executions(symbol=None, order_id=None)
Get today executions
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
Optional[str]
|
Filter by security code |
None
|
order_id
|
Optional[str]
|
Filter by Order ID |
None
|
Returns:
Type | Description |
---|---|
List[Execution]
|
Execution list |
Examples:
::
from longport.openapi import TradeContext, Config
config = Config.from_env()
ctx = TradeContext(config)
resp = ctx.today_executions(symbol = "700.HK")
print(resp)
today_orders(symbol=None, status=None, side=None, market=None, order_id=None)
Get today orders
Parameters:
Name | Type | Description | Default |
---|---|---|---|
symbol
|
Optional[str]
|
Filter by security code |
None
|
status
|
Optional[List[Type[OrderStatus]]]
|
Filter by order status |
None
|
side
|
Optional[Type[OrderSide]]
|
Filter by order side |
None
|
market
|
Optional[Type[Market]]
|
Filter by market type |
None
|
order_id
|
Optional[str]
|
Filter by order id |
None
|
Returns:
Type | Description |
---|---|
List[Order]
|
Order list |
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)
TradeDirection
Trade direction
TradeSession
Trade session
Normal
Post
Pre
TradeStatus
Security Status
CodeMoved
Delisted
Expired
Fuse
Halted
Normal
PrepareList
SplitStockHalts
Suspend
ToBeOpened
WarrantPrepareList
TradingSessionInfo
The information of trading session
begin_time: time
instance-attribute
Being trading time
end_time: time
instance-attribute
End trading time
trade_session: Type[TradeSession]
instance-attribute
Trading sessions
TriggerStatus
Trigger status
Active
Deactive
Released
Unknown
WarrantInfo
Warrant info
balance_point: Optional[Decimal]
instance-attribute
Breakeven point
call_price: Optional[Decimal]
instance-attribute
Call price
change_rate: Decimal
instance-attribute
Quote change rate
change_value: Decimal
instance-attribute
Quote change
conversion_ratio: Optional[Decimal]
instance-attribute
Conversion ratio
delta: Optional[Decimal]
instance-attribute
Greek value delta
effective_leverage: Optional[Decimal]
instance-attribute
Effective leverage
expiry_date: date
instance-attribute
Expiry date
implied_volatility: Optional[Decimal]
instance-attribute
Implied volatility
itm_otm: Optional[Decimal]
instance-attribute
In/out of the bound
last_done: Decimal
instance-attribute
Latest price
leverage_ratio: Decimal
instance-attribute
Leverage ratio
lower_strike_price: Optional[Decimal]
instance-attribute
Lower strike price
name: str
instance-attribute
Security name
outstanding_qty: int
instance-attribute
Outstanding quantity
outstanding_ratio: Decimal
instance-attribute
Outstanding ratio
premium: Decimal
instance-attribute
Premium
status: Type[WarrantStatus]
instance-attribute
Status
strike_price: Optional[Decimal]
instance-attribute
Strike price
symbol: str
instance-attribute
Security code
to_call_price: Optional[Decimal]
instance-attribute
Price interval from the call price
turnover: Decimal
instance-attribute
Turnover
upper_strike_price: Optional[Decimal]
instance-attribute
Upper strike price
volume: int
instance-attribute
Volume
warrant_type: Type[WarrantType]
instance-attribute
Warrant type
WarrantQuote
Quote of warrant
call_price: Decimal
instance-attribute
Call price
category: Type[WarrantType]
instance-attribute
Warrant type
conversion_ratio: Decimal
instance-attribute
Conversion ratio
expiry_date: date
instance-attribute
Exprity date
high: Decimal
instance-attribute
High
implied_volatility: Decimal
instance-attribute
Implied volatility
last_done: Decimal
instance-attribute
Latest price
last_trade_date: date
instance-attribute
Last tradalbe date
low: Decimal
instance-attribute
Low
lower_strike_price: Decimal
instance-attribute
Lower bound price
open: Decimal
instance-attribute
Open
outstanding_quantity: int
instance-attribute
Outstanding quantity
outstanding_ratio: Decimal
instance-attribute
Outstanding ratio
prev_close: Decimal
instance-attribute
Yesterday's close
strike_price: Decimal
instance-attribute
Strike price
symbol: str
instance-attribute
Security code
timestamp: datetime
instance-attribute
Time of latest price
trade_status: Type[TradeStatus]
instance-attribute
Security trading status
turnover: Decimal
instance-attribute
Turnover
underlying_symbol: str
instance-attribute
Underlying security symbol of the warrant
upper_strike_price: Decimal
instance-attribute
Upper bound price
volume: int
instance-attribute
Volume
WarrantSortBy
Warrant sort by
BalancePoint
CallPrice
ChangeRate
ChangeValue
ConversionRatio
Delta
EffectiveLeverage
ExpiryDate
ImpliedVolatility
ItmOtm
LastDone
LeverageRatio
LowerStrikePrice
OutstandingQuantity
OutstandingRatio
Premium
Status
StrikePrice
ToCallPrice
Turnover
UpperStrikePrice
Volume
WarrantStatus
Warrant status
Normal
PrepareList
Suspend
WarrantType
Warrant type
Bear
Bull
Call
Inline
Put
Unknown
WatchlistGroup
id: int
instance-attribute
Group id
name: str
instance-attribute
Group name
securities: List[WatchlistSecurity]
instance-attribute
Securities
WatchlistSecurity
Watchlist security
market: Market
instance-attribute
Market
name: str
instance-attribute
Security name
symbol: str
instance-attribute
Security symbol
watched_at: datetime
instance-attribute
Watched time
watched_price: Optional[Decimal]
instance-attribute
Watched price