Code Reference
AccountBalance
Account balance
buy_power
instance-attribute
Buy power
cash_infos
instance-attribute
Cash details
currency
instance-attribute
Currency
init_margin
instance-attribute
Initial margin
maintenance_margin
instance-attribute
Maintenance margin
margin_call
instance-attribute
Margin call
max_finance_amount
instance-attribute
Maximum financing amount
net_assets
instance-attribute
Net assets
remaining_finance_amount
instance-attribute
Remaining financing amount
risk_level
instance-attribute
Risk control level
total_cash
instance-attribute
Total cash
AdjustType
Candlestick adjustment type
ForwardAdjust
NoAdjust
Brokers
Brokers
broker_ids
instance-attribute
Broker IDs
position
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
instance-attribute
Close price
high
instance-attribute
High price
low
instance-attribute
Low price
open
instance-attribute
Open price
timestamp
instance-attribute
Timestamp
turnover
instance-attribute
Turnover
volume
instance-attribute
Volume
CapitalDistribution
Capital distribution
large
instance-attribute
Large order
medium
instance-attribute
Medium order
small
instance-attribute
Small order
CapitalDistributionResponse
Capital distribution response
capital_in
instance-attribute
Inflow capital data
capital_out
instance-attribute
Outflow capital data
timestamp
instance-attribute
Time
CapitalFlowLine
Capital flow line
inflow
instance-attribute
Inflow capital data
timestamp
instance-attribute
Time
CashFlow
Cash flow
balance
instance-attribute
Cash amount
business_time
instance-attribute
Business time
business_type
instance-attribute
Balance type
currency
instance-attribute
Cash currency
description
instance-attribute
Cash flow description
direction
instance-attribute
Outflow direction
symbol
instance-attribute
Associated Stock code information
transaction_flow_name
instance-attribute
Cash flow name
CashFlowDirection
Cash flow direction
In
Out
Unknown
CashInfo
CashInfo
available_cash
instance-attribute
Available cash
currency
instance-attribute
Currency
frozen_cash
instance-attribute
Frozen cash
settling_cash
instance-attribute
Cash to be settled
withdraw_cash
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
instance-attribute
Number of orders
position
instance-attribute
Position
price
instance-attribute
Price
volume
instance-attribute
Volume
DerivativeType
Derivative type
Option
Warrant
EstimateMaxPurchaseQuantityResponse
Response for estimate maximum purchase quantity
cash_max_qty
instance-attribute
Cash available quantity
margin_max_qty
instance-attribute
Margin available quantity
Execution
Execution
order_id
instance-attribute
Order ID
price
instance-attribute
Executed price
quantity
instance-attribute
Executed quantity
symbol
instance-attribute
Security code
trade_done_at
instance-attribute
Trade done time
trade_id
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
instance-attribute
Net cost
currency
instance-attribute
Currency
current_net_asset_value
instance-attribute
Current equity
holding_units
instance-attribute
Holding units
net_asset_value_day
instance-attribute
Current equity PyDecimal
symbol
instance-attribute
Fund ISIN code
symbol_name
instance-attribute
Fund name
FundPositionChannel
Fund position channel
account_channel
instance-attribute
Account type
positions
instance-attribute
Fund positions
FundPositionsResponse
Fund positions response
channels
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
instance-attribute
Average price
price
instance-attribute
Close price of the minute
timestamp
instance-attribute
Start time of the minute
turnover
instance-attribute
Turnover
volume
instance-attribute
Volume
IssuerInfo
Issuer info
issuer_id
instance-attribute
Issuer ID
name_cn
instance-attribute
Issuer name (zh-CN)
name_en
instance-attribute
Issuer name (en)
name_hk
instance-attribute
Issuer name (zh-HK)
Language
MarginRatio
Margin ratio
fm_factor
instance-attribute
Forced close-out margin ratio
im_factor
instance-attribute
Initial margin ratio
mm_factor
instance-attribute
Maintain the initial margin ratio
Market
MarketTradingSession
Market trading session
market
instance-attribute
Market
trade_sessions
instance-attribute
Trading session
OpenApiException
Bases: Exception
OpenAPI exception
code
instance-attribute
Error code
message
instance-attribute
Error message
OptionDirection
Option direction
Call
Put
Unknown
OptionQuote
Quote of option
contract_multiplier
instance-attribute
Contract multiplier
contract_size
instance-attribute
Contract size
contract_type
instance-attribute
Option type
direction
instance-attribute
Option direction
expiry_date
instance-attribute
Exprity date
high
instance-attribute
High
historical_volatility
instance-attribute
Underlying security historical volatility of the option
implied_volatility
instance-attribute
Implied volatility
last_done
instance-attribute
Latest price
low
instance-attribute
Low
open
instance-attribute
Open
open_interest
instance-attribute
Number of open positions
prev_close
instance-attribute
Yesterday's close
strike_price
instance-attribute
Strike price
symbol
instance-attribute
Security code
timestamp
instance-attribute
Time of latest price
trade_status
instance-attribute
Security trading status
turnover
instance-attribute
Turnover
underlying_symbol
instance-attribute
Underlying security symbol of the option
volume
instance-attribute
Volume
OptionType
Option type
American
Europe
Unknown
Order
Order
currency
instance-attribute
Currency
executed_price
instance-attribute
Executed price
executed_quantity
instance-attribute
Executed quantity
expire_date
instance-attribute
Long term order expire date
last_done
instance-attribute
Last done
limit_offset
instance-attribute
TSLPAMT
/ TSLPPCT
order limit offset amount
msg
instance-attribute
Rejected Message or remark
order_id
instance-attribute
Order ID
order_type
instance-attribute
Order type
outside_rth
instance-attribute
Enable or disable outside regular trading hours
price
instance-attribute
Submitted price
quantity
instance-attribute
Submitted quantity
remark
instance-attribute
Remark
side
instance-attribute
Order side
status
instance-attribute
Order status
stock_name
instance-attribute
Stock name
submitted_at
instance-attribute
Submitted time
symbol
instance-attribute
Security code
tag
instance-attribute
Order tag
time_in_force
instance-attribute
Time in force type
trailing_amount
instance-attribute
TSMAMT
/ TSLPAMT
order trailing amount
trailing_percent
instance-attribute
TSMPCT
/ TSLPPCT
order trailing percent
trigger_at
instance-attribute
Conditional order trigger time
trigger_price
instance-attribute
LIT
/ MIT
Order Trigger Price
trigger_status
instance-attribute
Conditional order trigger status
updated_at
instance-attribute
Last updated time
OrderChargeDetail
Order charge detail
currency
instance-attribute
Settlement currency
items
instance-attribute
Order charge items
total_amount
instance-attribute
Total charges amount
OrderChargeFee
Order charge fee
amount
instance-attribute
Charge amount
code
instance-attribute
Charge code
currency
instance-attribute
Charge currency
name
instance-attribute
Charge name
OrderChargeItem
Order charge item
code
instance-attribute
Charge category code
fees
instance-attribute
Charge details
name
instance-attribute
Charge category name
OrderDetail
Order detail
charge_detail
instance-attribute
Order charges
currency
instance-attribute
Currency
deductions_amount
instance-attribute
Deduction amount
deductions_currency
instance-attribute
Deduction currency
deductions_status
instance-attribute
Deduction status
executed_price
instance-attribute
Executed price
executed_quantity
instance-attribute
Executed quantity
expire_date
instance-attribute
Long term order expire date
free_amount
instance-attribute
Commission-free amount
free_currency
instance-attribute
Commission-free currency
free_status
instance-attribute
Commission-free Status
history
instance-attribute
Order history details
last_done
instance-attribute
Last done
limit_offset
instance-attribute
TSLPAMT
/ TSLPPCT
order limit offset amount
msg
instance-attribute
Rejected Message or remark
order_id
instance-attribute
Order ID
order_type
instance-attribute
Order type
outside_rth
instance-attribute
Enable or disable outside regular trading hours
platform_deducted_amount
instance-attribute
Platform deduction amount
platform_deducted_currency
instance-attribute
Platform deduction currency
platform_deducted_status
instance-attribute
Platform fee deduction status
price
instance-attribute
Submitted price
quantity
instance-attribute
Submitted quantity
remark
instance-attribute
Remark
side
instance-attribute
Order side
status
instance-attribute
Order status
stock_name
instance-attribute
Stock name
submitted_at
instance-attribute
Submitted time
symbol
instance-attribute
Security code
tag
instance-attribute
Order tag
time_in_force
instance-attribute
Time in force type
trailing_amount
instance-attribute
TSMAMT
/ TSLPAMT
order trailing amount
trailing_percent
instance-attribute
TSMPCT
/ TSLPPCT
order trailing percent
trigger_at
instance-attribute
Conditional order trigger time
trigger_price
instance-attribute
LIT
/ MIT
Order Trigger Price
trigger_status
instance-attribute
Conditional order trigger status
updated_at
instance-attribute
Last updated time
OrderHistoryDetail
Order history detail
msg
instance-attribute
Execution or error message
price
instance-attribute
Executed price for executed orders, submitted price for expired, canceled, rejected orders, etc.
quantity
instance-attribute
Executed quantity for executed orders, remaining quantity for expired, canceled, rejected orders, etc.
status
instance-attribute
Order status
time
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
instance-attribute
Broker IDs
name_cn
instance-attribute
Participant name (zh-CN)
name_en
instance-attribute
Participant name (en)
name_hk
instance-attribute
Participant name (zh-HK)
Period
Candlestick period
Day
Min_1
Min_10
Min_120
Min_15
Min_180
Min_2
Min_20
Min_240
Min_3
Min_30
Min_45
Min_5
Min_60
Month
Quarter
Unknown
Week
Year
PrePostQuote
Quote of US pre/post market
high
instance-attribute
High
last_done
instance-attribute
Latest price
low
instance-attribute
Low
prev_close
instance-attribute
Close of the last trade session
timestamp
instance-attribute
Time of latest price
turnover
instance-attribute
Turnover
volume
instance-attribute
Volume
PushBrokers
Brokers message
ask_brokers
instance-attribute
Ask brokers
bid_brokers
instance-attribute
Bid brokers
PushCandlestick
Candlestick updated event
candlestick
instance-attribute
Candlestick
is_confirmed
instance-attribute
Is confirmed
period
instance-attribute
Period type
PushCandlestickMode
Push candlestick mode
Confirmed
Realtime
PushDepth
Depth message
asks
instance-attribute
Ask depth
bids
instance-attribute
Bid depth
PushOrderChanged
Order changed message
account_no
instance-attribute
Account no
currency
instance-attribute
Currency
executed_price
instance-attribute
Executed price
executed_quantity
instance-attribute
Executed quantity
last_price
instance-attribute
Last price
last_share
instance-attribute
Last share
limit_offset
instance-attribute
Limit offset amount
msg
instance-attribute
Rejected message or remark
order_id
instance-attribute
Order ID
order_type
instance-attribute
Order type
remark
instance-attribute
Remark message
side
instance-attribute
Order side
status
instance-attribute
Order status
stock_name
instance-attribute
Stock name
submitted_at
instance-attribute
Submitted time
submitted_price
instance-attribute
Submitted price
submitted_quantity
instance-attribute
Submitted quantity
symbol
instance-attribute
Order symbol
tag
instance-attribute
Order tag
trailing_amount
instance-attribute
Trailing amount
trailing_percent
instance-attribute
Trailing percent
trigger_at
instance-attribute
Conditional order trigger time
trigger_price
instance-attribute
Order trigger price
trigger_status
instance-attribute
Conditional order trigger status
updated_at
instance-attribute
Last updated time
PushQuote
Quote message
current_turnover
instance-attribute
Increase turnover between pushes
current_volume
instance-attribute
Increase volume between pushes
high
instance-attribute
High
last_done
instance-attribute
Latest price
low
instance-attribute
Low
open
instance-attribute
Open
timestamp
instance-attribute
Time of latest price
trade_session
instance-attribute
Trade session
trade_status
instance-attribute
Security trading status
turnover
instance-attribute
Turnover
volume
instance-attribute
Volume
PushTrades
Trades message
trades
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
instance-attribute
Description
end_at
instance-attribute
End time
key
instance-attribute
Key
name
instance-attribute
Name
start_at
instance-attribute
Start time
RealtimeQuote
Real-time quote
high
instance-attribute
High
last_done
instance-attribute
Latest price
low
instance-attribute
Low
open
instance-attribute
Open
symbol
instance-attribute
Security code
timestamp
instance-attribute
Time of latest price
trade_status
instance-attribute
Security trading status
turnover
instance-attribute
Turnover
volume
instance-attribute
Volume
SecuritiesUpdateMode
Securities update mode
Add
Remove
Replace
Security
Security
name_cn
instance-attribute
Security name (zh-CN)
name_en
instance-attribute
Security name (en)
name_hk
instance-attribute
Security name (zh-HK)
symbol
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
instance-attribute
Ask brokers
bid_brokers
instance-attribute
Bid brokers
SecurityCalcIndex
Security calc index response
amplitude
instance-attribute
Amplitude
balance_point
instance-attribute
Breakeven point
call_price
instance-attribute
Call price
capital_flow
instance-attribute
Capital flow
change_rate
instance-attribute
Change ratio
change_value
instance-attribute
Change value
conversion_ratio
instance-attribute
Conversion ratio
delta
instance-attribute
Delta
dividend_ratio_ttm
instance-attribute
Dividend ratio (TTM)
effective_leverage
instance-attribute
Effective leverage
expiry_date
instance-attribute
Expiry date
five_day_change_rate
instance-attribute
Five days change ratio
five_minutes_change_rate
instance-attribute
Five minutes change ratio
gamma
instance-attribute
Gamma
half_year_change_rate
instance-attribute
Half year change ratio
implied_volatility
instance-attribute
Implied volatility
itm_otm
instance-attribute
In/out of the bound
last_done
instance-attribute
Latest price
leverage_ratio
instance-attribute
Leverage ratio
lower_strike_price
instance-attribute
Lower bound price
open_interest
instance-attribute
Open interest
outstanding_qty
instance-attribute
Outstanding quantity
outstanding_ratio
instance-attribute
Outstanding ratio
pb_ratio
instance-attribute
PB
pe_ttm_ratio
instance-attribute
PE (TTM)
premium
instance-attribute
Premium
rho
instance-attribute
Rho
strike_price
instance-attribute
Strike price
symbol
instance-attribute
Security symbol
ten_day_change_rate
instance-attribute
Ten days change ratio
theta
instance-attribute
Theta
to_call_price
instance-attribute
Price interval from the call price
total_market_value
instance-attribute
Total market value
turnover
instance-attribute
Turnover
turnover_rate
instance-attribute
turnover_rate
upper_strike_price
instance-attribute
Upper bound price
vega
instance-attribute
Vega
volume
instance-attribute
Volume
volume_ratio
instance-attribute
Volume ratio
warrant_delta
instance-attribute
Warrant delta
ytd_change_rate
instance-attribute
Year-to-date change ratio
SecurityDepth
Security depth
asks
instance-attribute
Ask depth
bids
instance-attribute
Bid depth
SecurityListCategory
Security list category
Overnight
SecurityQuote
Quote of securitity
high
instance-attribute
High
last_done
instance-attribute
Latest price
low
instance-attribute
Low
open
instance-attribute
Open
overnight_quote
instance-attribute
Quote of US overnight market
post_market_quote
instance-attribute
Quote of US post market
pre_market_quote
instance-attribute
Quote of US pre market
prev_close
instance-attribute
Yesterday's close
symbol
instance-attribute
Security code
timestamp
instance-attribute
Time of latest price
trade_status
instance-attribute
Security trading status
turnover
instance-attribute
Turnover
volume
instance-attribute
Volume
SecurityStaticInfo
The basic information of securities
board
instance-attribute
Board
bps
instance-attribute
Net assets per share
circulating_shares
instance-attribute
Circulating shares
currency
instance-attribute
Trading currency
dividend_yield
instance-attribute
Dividend yield
eps
instance-attribute
Earnings per share
eps_ttm
instance-attribute
Earnings per share (TTM)
exchange
instance-attribute
Exchange which the security belongs to
hk_shares
instance-attribute
HK shares (only HK stocks)
lot_size
instance-attribute
Lot size
name_cn
instance-attribute
Security name (zh-CN)
name_en
instance-attribute
Security name (en)
name_hk
instance-attribute
Security name (zh-HK)
stock_derivatives
instance-attribute
Types of supported derivatives
symbol
instance-attribute
Security code
total_shares
instance-attribute
Total shares
SortOrderType
Sort order type
Ascending
Descending
StockPosition
Stock position
available_quantity
instance-attribute
Available quantity
cost_price
instance-attribute
Cost Price(According to the client's choice of average purchase or diluted cost)
currency
instance-attribute
Currency
init_quantity
instance-attribute
Initial position before market opening
market
instance-attribute
Market
quantity
instance-attribute
The number of holdings
symbol
instance-attribute
Stock code
symbol_name
instance-attribute
Stock name
StockPositionChannel
Stock position channel
account_channel
instance-attribute
Account type
positions
instance-attribute
Stock positions
StockPositionsResponse
Stock positions response
channels
instance-attribute
Channels
StrikePriceInfo
Strike price info
call_symbol
instance-attribute
Security code of call option
price
instance-attribute
Strike price
put_symbol
instance-attribute
Security code of put option
standard
instance-attribute
Is standard
SubType
SubmitOrderResponse
Response for submit order request
order_id
instance-attribute
Order id
Subscription
Subscription
candlesticks
instance-attribute
Candlesticks
sub_types
instance-attribute
Subscription types
symbol
instance-attribute
Security code
TimeInForceType
Time in force type
Day
GoodTilCanceled
GoodTilDate
Unknown
TopicType
Topic type
Private
Trade
Trade
direction
instance-attribute
Trade direction
price
instance-attribute
Price
timestamp
instance-attribute
Time of trading
trade_session
instance-attribute
Trade session
trade_type
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
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
instance-attribute
Being trading time
end_time
instance-attribute
End trading time
trade_session
instance-attribute
Trading sessions
TriggerStatus
Trigger status
Active
Deactive
Released
Unknown
WarrantInfo
Warrant info
balance_point
instance-attribute
Breakeven point
call_price
instance-attribute
Call price
change_rate
instance-attribute
Quote change rate
change_value
instance-attribute
Quote change
conversion_ratio
instance-attribute
Conversion ratio
delta
instance-attribute
Greek value delta
effective_leverage
instance-attribute
Effective leverage
expiry_date
instance-attribute
Expiry date
implied_volatility
instance-attribute
Implied volatility
itm_otm
instance-attribute
In/out of the bound
last_done
instance-attribute
Latest price
leverage_ratio
instance-attribute
Leverage ratio
lower_strike_price
instance-attribute
Lower strike price
name
instance-attribute
Security name
outstanding_qty
instance-attribute
Outstanding quantity
outstanding_ratio
instance-attribute
Outstanding ratio
premium
instance-attribute
Premium
status
instance-attribute
Status
strike_price
instance-attribute
Strike price
symbol
instance-attribute
Security code
to_call_price
instance-attribute
Price interval from the call price
turnover
instance-attribute
Turnover
upper_strike_price
instance-attribute
Upper strike price
volume
instance-attribute
Volume
warrant_type
instance-attribute
Warrant type
WarrantQuote
Quote of warrant
call_price
instance-attribute
Call price
category
instance-attribute
Warrant type
conversion_ratio
instance-attribute
Conversion ratio
expiry_date
instance-attribute
Exprity date
high
instance-attribute
High
implied_volatility
instance-attribute
Implied volatility
last_done
instance-attribute
Latest price
last_trade_date
instance-attribute
Last tradalbe date
low
instance-attribute
Low
lower_strike_price
instance-attribute
Lower bound price
open
instance-attribute
Open
outstanding_quantity
instance-attribute
Outstanding quantity
outstanding_ratio
instance-attribute
Outstanding ratio
prev_close
instance-attribute
Yesterday's close
strike_price
instance-attribute
Strike price
symbol
instance-attribute
Security code
timestamp
instance-attribute
Time of latest price
trade_status
instance-attribute
Security trading status
turnover
instance-attribute
Turnover
underlying_symbol
instance-attribute
Underlying security symbol of the warrant
upper_strike_price
instance-attribute
Upper bound price
volume
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
instance-attribute
Group id
name
instance-attribute
Group name
securities
instance-attribute
Securities
WatchlistSecurity
Watchlist security
market
instance-attribute
Market
name
instance-attribute
Security name
symbol
instance-attribute
Security symbol
watched_at
instance-attribute
Watched time
watched_price
instance-attribute
Watched price