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

Bases: AdjustType

Adjust forward

NoAdjust

Bases: AdjustType

Actual

Brokers

Brokers

broker_ids instance-attribute

Broker IDs

position instance-attribute

Position

CalcIndex

Calc index

Amplitude

Bases: CalcIndex

Amplitude

BalancePoint

Bases: CalcIndex

Breakeven point

CallPrice

Bases: CalcIndex

Call price

CapitalFlow

Bases: CalcIndex

Capital flow

ChangeRate

Bases: CalcIndex

Change rate

ChangeValue

Bases: CalcIndex

Change value

ConversionRatio

Bases: CalcIndex

Conversion ratio

Delta

Bases: CalcIndex

Delta

DividendRatioTtm

Bases: CalcIndex

Dividend ratio (TTM)

EffectiveLeverage

Bases: CalcIndex

Effective leverage

ExpiryDate

Bases: CalcIndex

Expiry date

FiveDayChangeRate

Bases: CalcIndex

Five days change ratio

FiveMinutesChangeRate

Bases: CalcIndex

Five minutes change ratio

Gamma

Bases: CalcIndex

Gamma

HalfYearChangeRate

Bases: CalcIndex

Half year change ratio

ImpliedVolatility

Bases: CalcIndex

Implied volatility

ItmOtm

Bases: CalcIndex

In/out of the bound

LastDone

Bases: CalcIndex

Latest price

LeverageRatio

Bases: CalcIndex

Leverage ratio

LowerStrikePrice

Bases: CalcIndex

Lower bound price

OpenInterest

Bases: CalcIndex

Open interest

OutstandingQty

Bases: CalcIndex

Outstanding quantity

OutstandingRatio

Bases: CalcIndex

Outstanding ratio

PbRatio

Bases: CalcIndex

PB

PeTtmRatio

Bases: CalcIndex

PE (TTM)

Premium

Bases: CalcIndex

Premium

Rho

Bases: CalcIndex

Rho

StrikePrice

Bases: CalcIndex

Strike price

TenDayChangeRate

Bases: CalcIndex

Ten days change ratio

Theta

Bases: CalcIndex

Theta

ToCallPrice

Bases: CalcIndex

Price interval from the call price

TotalMarketValue

Bases: CalcIndex

Total market value

Turnover

Bases: CalcIndex

Turnover

TurnoverRate

Bases: CalcIndex

Turnover rate

UpperStrikePrice

Bases: CalcIndex

Upper bound price

Vega

Bases: CalcIndex

Vega

Volume

Bases: CalcIndex

Volume

VolumeRatio

Bases: CalcIndex

Volume ratio

WarrantDelta

Bases: CalcIndex

Warrant delta

YtdChangeRate

Bases: CalcIndex

Year-to-date change ratio

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

Bases: CashFlowDirection

In

Out

Bases: CashFlowDirection

Out

Unknown

Bases: CashFlowDirection

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

Bases: ChargeCategoryCode

Broker

Third

Bases: ChargeCategoryCode

Third

Unknown

Bases: ChargeCategoryCode

Unknown

CommissionFreeStatus

Commission-free Status

Calculated

Bases: CommissionFreeStatus

Commission-free amount to be calculated

None_

Bases: CommissionFreeStatus

None

Pending

Bases: CommissionFreeStatus

Pending commission-free

Ready

Bases: CommissionFreeStatus

Commission-free applied

Unknown

Bases: CommissionFreeStatus

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 key
  • LONGPORT_APP_SECRET - App secret
  • LONGPORT_ACCESS_TOKEN - Access token
  • LONGPORT_HTTP_URL - HTTP endpoint url
  • LONGPORT_QUOTE_WS_URL - Quote websocket endpoint url
  • LONGPORT_TRADE_WS_URL - Trade websocket endpoint url
  • LONGPORT_ENABLE_OVERNIGHT - Enable overnight quote, true or false (Default: false)

refresh_access_token(expired_at=None)

Gets a new access_token

Parameters:

Name Type Description Default
expired_at Optional[datetime]

The expiration time of the access token, defaults to 90 days.

None

Returns:

Type Description
str

Access token

DeductionStatus

Deduction status

Done

Bases: DeductionStatus

Settled and distributed

NoData

Bases: DeductionStatus

Settled with no data

None_

Bases: DeductionStatus

None

Pending

Bases: DeductionStatus

Settled and pending distribution

Unknown

Bases: DeductionStatus

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

Bases: DerivativeType

US stock options

Warrant

Bases: DerivativeType

HK warrants

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

Bases: FilterWarrantExpiryDate

3 - 6 months

Between_6_12

Bases: FilterWarrantExpiryDate

6 - 12 months

GT_12

Bases: FilterWarrantExpiryDate

Greater than 12 months

LT_3

Bases: FilterWarrantExpiryDate

Less than 3 months

FilterWarrantInOutBoundsType

Filter warrant in/out of the bounds type

In

Bases: FilterWarrantInOutBoundsType

In bounds

Out

Bases: FilterWarrantInOutBoundsType

Out bounds

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 url
  • LONGPORT_APP_KEY - App key
  • LONGPORT_APP_SECRET - App secret
  • LONGPORT_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

Language identifier

EN

Bases: Language

en

ZH_CN

Bases: Language

zh-CN

ZH_HK

Bases: Language

zh-HK

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

Market

CN

Bases: Market

CN market

HK

Bases: Market

HK market

SG

Bases: Market

SG market

US

Bases: Market

US market

Unknown

Bases: Market

Unknown

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

Bases: OptionDirection

Call

Put

Bases: OptionDirection

Put

Unknown

Bases: OptionDirection

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

Bases: OptionType

American

Europe

Bases: OptionType

Europe

Unknown

Bases: OptionType

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

Order side

Buy

Bases: OrderSide

Buy

Sell

Bases: OrderSide

Sell

Unknown

Bases: OrderSide

Unknown

OrderStatus

Order status

Canceled

Bases: OrderStatus

Canceled

Expired

Bases: OrderStatus

ExpiredStatus

Filled

Bases: OrderStatus

Filled

New

Bases: OrderStatus

New

NotReported

Bases: OrderStatus

Not reported

PartialFilled

Bases: OrderStatus

Partial Filled

PartialWithdrawal

Bases: OrderStatus

PartialWithdrawal

PendingCancel

Bases: OrderStatus

Pending Cancel

PendingReplace

Bases: OrderStatus

Pending Replace

ProtectedNotReported

Bases: OrderStatus

Not reported (Protected Order)

Rejected

Bases: OrderStatus

Rejected

Replaced

Bases: OrderStatus

Replaced

ReplacedNotReported

Bases: OrderStatus

Not reported (Replaced Order)

Unknown

Bases: OrderStatus

Unknown

VarietiesNotReported

Bases: OrderStatus

Not reported (Conditional Order)

WaitToCancel

Bases: OrderStatus

Wait To Cancel

WaitToNew

Bases: OrderStatus

Wait To New

WaitToReplace

Bases: OrderStatus

Wait To Replace

OrderTag

Order tag

AllocatedSub

Bases: OrderTag

Trade Allocation

Creditor

Bases: OrderTag

Option Exercise Long

Debtor

Bases: OrderTag

Option Exercise Short

Grey

Bases: OrderTag

Grey Order

LongTerm

Bases: OrderTag

Long term Order

MarginCall

Bases: OrderTag

Force Selling

NonExercise

Bases: OrderTag

Wavier Of Option Exercise

Normal

Bases: OrderTag

Normal Order

Offline

Bases: OrderTag

OTC

Unknown

Bases: OrderTag

Unknown

OrderType

Order type

ALO

Bases: OrderType

At-auction Limit Order

AO

Bases: OrderType

At-auction Order

ELO

Bases: OrderType

Enhanced Limit Order

LIT

Bases: OrderType

Limit If Touched

LO

Bases: OrderType

Limit Order

MIT

Bases: OrderType

Market If Touched

MO

Bases: OrderType

Market Order

ODD

Bases: OrderType

Odd Lots

SLO

Bases: OrderType

Special Limit Order

TSLPAMT

Bases: OrderType

Trailing Limit If Touched (Trailing Amount)

TSLPPCT

Bases: OrderType

Trailing Limit If Touched (Trailing Percent)

TSMAMT

Bases: OrderType

Trailing Market If Touched (Trailing Amount)

TSMPCT

Bases: OrderType

Trailing Market If Touched (Trailing Percent)

Unknown

Bases: OrderType

Unknown

OutsideRTH

Enable or disable outside regular trading hours

AnyTime

Bases: OutsideRTH

Any time

Overnight

Bases: OutsideRTH

Overnight

RTHOnly

Bases: OutsideRTH

Regular trading hour only

Unknown

Bases: OutsideRTH

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

Bases: Period

Daily

Min_1

Bases: Period

One Minute

Min_10

Bases: Period

Ten Minutes

Min_120

Bases: Period

Two Hours

Min_15

Bases: Period

Fifteen Minutes

Min_180

Bases: Period

Three Hours

Min_2

Bases: Period

Two Minutes

Min_20

Bases: Period

Twenty Minutes

Min_240

Bases: Period

Four Hours

Min_3

Bases: Period

Three Minutes

Min_30

Bases: Period

Thirty Minutes

Min_45

Bases: Period

Forty-Five Minutes

Min_5

Bases: Period

Five Minutes

Min_60

Bases: Period

Sixty Minutes

Month

Bases: Period

Monthly

Quarter

Bases: Period

Quarterly

Unknown

Bases: Period

Unknown

Week

Bases: Period

Weekly

Year

Bases: Period

Yearly

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

Bases: PushCandlestickMode

Confirmed

Realtime

Bases: PushCandlestickMode

Real-time

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 1000)

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)

Get security history candlesticks by date

Parameters:

Name Type Description Default
symbol str

Security code

required
period Type[Period]

Period type

required
adjust_type Type[AdjustType]

Adjust type

required
start Optional[date]

Start date

required
end Optional[date]

End date

required

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 True, query the latest from the specified time

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 1000)

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)

Subscribe security candlesticks

Parameters:

Name Type Description Default
symbol str

Security code

required
period Type[Period]

Period type

required

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

Bases: SecuritiesUpdateMode

Add securities

Remove

Bases: SecuritiesUpdateMode

Remove securities

Replace

Bases: SecuritiesUpdateMode

Replace securities

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

Bases: SecurityBoard

CN Index

CNSector

Bases: SecurityBoard

CN Industry Board

HKEquity

Bases: SecurityBoard

Hong Kong Equity Securities

HKHS

Bases: SecurityBoard

Hang Seng Index

HKPreIPO

Bases: SecurityBoard

HK PreIPO Security

HKSector

Bases: SecurityBoard

HK Industry Board

HKWarrant

Bases: SecurityBoard

HK Warrant

SGMain

Bases: SecurityBoard

SG Main Board

SGSector

Bases: SecurityBoard

SG Industry Board

SHMainConnect

Bases: SecurityBoard

SH Main Board(Connect)

SHMainNonConnect

Bases: SecurityBoard

SH Main Board(Non Connect)

SHSTAR

Bases: SecurityBoard

SH Science and Technology Innovation Board

STI

Bases: SecurityBoard

Singapore Straits Index

SZGEMConnect

Bases: SecurityBoard

SZ Gem Board(Connect)

SZGEMNonConnect

Bases: SecurityBoard

SZ Gem Board(Non Connect)

SZMainConnect

Bases: SecurityBoard

SZ Main Board(Connect)

SZMainNonConnect

Bases: SecurityBoard

SZ Main Board(Non Connect)

USDJI

Bases: SecurityBoard

Dow Jones Industrial Average

USMain

Bases: SecurityBoard

US Pink Board

USNSDQ

Bases: SecurityBoard

Nasdsaq Index

USOption

Bases: SecurityBoard

US Option

USOptionS

Bases: SecurityBoard

US Sepecial Option

USPink

Bases: SecurityBoard

US Pink Board

USSector

Bases: SecurityBoard

US Industry Board

Unknown

Bases: SecurityBoard

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

Bases: SecurityListCategory

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

Bases: SortOrderType

Ascending

Descending

Bases: SortOrderType

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

Subscription flags

Brokers

Bases: SubType

Broker

Depth

Bases: SubType

Depth

Quote

Bases: SubType

Quote

Trade

Bases: SubType

Trade

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

Bases: TimeInForceType

Day Order

GoodTilCanceled

Bases: TimeInForceType

Good Til Canceled Order

GoodTilDate

Bases: TimeInForceType

Good Til Date Order

Unknown

Bases: TimeInForceType

Unknown

TopicType

Topic type

Private

Bases: TopicType

Private notification for trade

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 trade
  • D - Odd-lot trade
  • M - Non-direct off-exchange trade
  • P - Late trade (Off-exchange previous day)
  • U - Auction trade
  • X - Direct off-exchange trade
  • Y - Automatch internalized
  • <empty string> - Automatch normal

US

  • <empty string> - Regular sale
  • A - Acquisition
  • B - Bunched trade
  • D - Distribution
  • F - Intermarket sweep
  • G - Bunched sold trades
  • H - Price variation trade
  • I - Odd lot trade
  • K - Rule 155 trde(NYSE MKT)
  • M - Market center close price
  • P - Prior reference price
  • Q - Market center open price
  • S - Split trade
  • V - Contingent trade
  • W - Average price trade
  • X - Cross trade
  • 1 - 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: 700.HK, AAPL.US

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 (LIT / MIT Order Required)

None
limit_offset Optional[Decimal]

Limit offset amount (TSLPAMT / TSLPPCT Required)

None
trailing_amount Optional[Decimal]

Trailing amount (TSLPAMT / TSMAMT Required)

None
trailing_percent Optional[Decimal]

Trailing percent (TSLPPCT / TSMAPCT Required)

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 (LIT / MIT Required)

None
limit_offset Optional[Decimal]

Limit offset amount (TSLPAMT / TSLPPCT Required)

None
trailing_amount Optional[Decimal]

Trailing amount (TSLPAMT / TSMAMT Required)

None
trailing_percent Optional[Decimal]

Trailing percent (TSLPPCT / TSMAPCT Required)

None
expire_date Optional[date]

Long term order expire date (Required when time_in_force is GoodTilDate)

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)

unsubscribe(topics)

Unsubscribe

Parameters:

Name Type Description Default
topics List[Type[TopicType]]

Topic list

required

TradeDirection

Trade direction

Down

Bases: TradeDirection

Down

Neutral

Bases: TradeDirection

Neutral

Up

Bases: TradeDirection

Up

TradeSession

Trade session

Normal

Bases: TradeSession

Trading

Post

Bases: TradeSession

Post-Trading

Pre

Bases: TradeSession

Pre-Trading

TradeStatus

Security Status

CodeMoved

Bases: TradeStatus

Code Moved

Delisted

Bases: TradeStatus

Delisted

Expired

Bases: TradeStatus

Expired

Fuse

Bases: TradeStatus

Fuse

Halted

Bases: TradeStatus

Suspension

Normal

Bases: TradeStatus

Normal

PrepareList

Bases: TradeStatus

Prepare List

SplitStockHalts

Bases: TradeStatus

Split Stock Halts

Suspend

Bases: TradeStatus

Suspend

ToBeOpened

Bases: TradeStatus

To Be Opened

WarrantPrepareList

Bases: TradeStatus

Warrant To BeListed

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

Bases: TriggerStatus

Active

Deactive

Bases: TriggerStatus

Deactive

Released

Bases: TriggerStatus

Released

Unknown

Bases: TriggerStatus

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

Bases: WarrantSortBy

Breakeven point

CallPrice

Bases: WarrantSortBy

Call price

ChangeRate

Bases: WarrantSortBy

Change rate

ChangeValue

Bases: WarrantSortBy

Change value

ConversionRatio

Bases: WarrantSortBy

Conversion ratio

Delta

Bases: WarrantSortBy

Greek value delta

EffectiveLeverage

Bases: WarrantSortBy

Effective leverage

ExpiryDate

Bases: WarrantSortBy

Expiry date

ImpliedVolatility

Bases: WarrantSortBy

Implied volatility

ItmOtm

Bases: WarrantSortBy

In/out of the bound

LastDone

Bases: WarrantSortBy

LastDone

LeverageRatio

Bases: WarrantSortBy

Leverage ratio

LowerStrikePrice

Bases: WarrantSortBy

Lower strike price

OutstandingQuantity

Bases: WarrantSortBy

Outstanding quantity

OutstandingRatio

Bases: WarrantSortBy

Outstanding ratio

Premium

Bases: WarrantSortBy

Premium

Status

Bases: WarrantSortBy

Status

StrikePrice

Bases: WarrantSortBy

Strike price

ToCallPrice

Bases: WarrantSortBy

Price interval from the call price

Turnover

Bases: WarrantSortBy

Turnover

UpperStrikePrice

Bases: WarrantSortBy

Upper strike price

Volume

Bases: WarrantSortBy

Volume

WarrantStatus

Warrant status

Normal

Bases: WarrantStatus

Normal

PrepareList

Bases: WarrantStatus

Prepare List

Suspend

Bases: WarrantStatus

Suspend

WarrantType

Warrant type

Bear

Bases: WarrantType

Bear

Bull

Bases: WarrantType

Bull

Call

Bases: WarrantType

Call

Inline

Bases: WarrantType

Inline

Put

Bases: WarrantType

Put

Unknown

Bases: WarrantType

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