Code Reference

AccountBalance

Account balance

buy_power: Decimal instance-attribute

Buy power

cash_infos: List[CashInfo] instance-attribute

Cash details

currency: str instance-attribute

Currency

init_margin: Decimal instance-attribute

Initial margin

maintenance_margin: Decimal instance-attribute

Maintenance margin

margin_call: Decimal instance-attribute

Margin call

max_finance_amount: Decimal instance-attribute

Maximum financing amount

net_assets: Decimal instance-attribute

Net assets

remaining_finance_amount: Decimal instance-attribute

Remaining financing amount

risk_level: int instance-attribute

Risk control level

total_cash: Decimal instance-attribute

Total cash

AdjustType

Candlestick adjustment type

ForwardAdjust

Bases: AdjustType

Adjust forward

NoAdjust

Bases: AdjustType

Actual

Brokers

Brokers

broker_ids: List[int] instance-attribute

Broker IDs

position: int 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: Decimal instance-attribute

Close price

high: Decimal instance-attribute

High price

low: Decimal instance-attribute

Low price

open: Decimal instance-attribute

Open price

timestamp: datetime instance-attribute

Timestamp

turnover: Decimal instance-attribute

Turnover

volume: int instance-attribute

Volume

CapitalDistribution

Capital distribution

large: Decimal instance-attribute

Large order

medium: Decimal instance-attribute

Medium order

small: Decimal instance-attribute

Small order

CapitalDistributionResponse

Capital distribution response

capital_in: CapitalDistribution instance-attribute

Inflow capital data

capital_out: CapitalDistribution instance-attribute

Outflow capital data

timestamp: datetime instance-attribute

Time

CapitalFlowLine

Capital flow line

inflow: Decimal instance-attribute

Inflow capital data

timestamp: datetime instance-attribute

Time

CashFlow

Cash flow

balance: Decimal instance-attribute

Cash amount

business_time: datetime instance-attribute

Business time

business_type: Type[BalanceType] instance-attribute

Balance type

currency: str instance-attribute

Cash currency

description: str instance-attribute

Cash flow description

direction: Type[CashFlowDirection] instance-attribute

Outflow direction

symbol: Optional[str] instance-attribute

Associated Stock code information

transaction_flow_name: str instance-attribute

Cash flow name

CashFlowDirection

Cash flow direction

In

Bases: CashFlowDirection

In

Out

Bases: CashFlowDirection

Out

Unknown

Bases: CashFlowDirection

Unknown

CashInfo

CashInfo

available_cash: Decimal instance-attribute

Available cash

currency: str instance-attribute

Currency

frozen_cash: Decimal instance-attribute

Frozen cash

settling_cash: Decimal instance-attribute

Cash to be settled

withdraw_cash: Decimal instance-attribute

Withdraw cash

ChargeCategoryCode

Charge category code

Broker

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: int instance-attribute

Number of orders

position: int instance-attribute

Position

price: Optional[Decimal] instance-attribute

Price

volume: int instance-attribute

Volume

DerivativeType

Derivative type

Option

Bases: DerivativeType

US stock options

Warrant

Bases: DerivativeType

HK warrants

EstimateMaxPurchaseQuantityResponse

Response for estimate maximum purchase quantity

cash_max_qty: int instance-attribute

Cash available quantity

margin_max_qty: int instance-attribute

Margin available quantity

Execution

Execution

order_id: str instance-attribute

Order ID

price: Decimal instance-attribute

Executed price

quantity: int instance-attribute

Executed quantity

symbol: str instance-attribute

Security code

trade_done_at: datetime instance-attribute

Trade done time

trade_id: str instance-attribute

Execution ID

FilterWarrantExpiryDate

Filter warrant expiry date type

Between_3_6

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: Decimal instance-attribute

Net cost

currency: str instance-attribute

Currency

current_net_asset_value: Decimal instance-attribute

Current equity

holding_units: Decimal instance-attribute

Holding units

net_asset_value_day: datetime instance-attribute

Current equity PyDecimal

symbol: str instance-attribute

Fund ISIN code

symbol_name: str instance-attribute

Fund name

FundPositionChannel

Fund position channel

account_channel: str instance-attribute

Account type

positions: List[FundPosition] instance-attribute

Fund positions

FundPositionsResponse

Fund positions response

channels: List[FundPositionChannel] instance-attribute

Channels

HttpClient

A HTTP client for longPort open api

Parameters:

Name Type Description Default
http_url str

HTTP API url

required
app_key str

App Key

required
app_secret str

App Secret

required
access_token str

Access Token

required

from_env() classmethod

Create a new HttpClient from the given environment variables

It first gets the environment variables from the .env file in the current directory.

Variables

  • LONGPORT_HTTP_URL - HTTP endpoint 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: Decimal instance-attribute

Average price

price: Decimal instance-attribute

Close price of the minute

timestamp: datetime instance-attribute

Start time of the minute

turnover: Decimal instance-attribute

Turnover

volume: int instance-attribute

Volume

IssuerInfo

Issuer info

issuer_id: int instance-attribute

Issuer ID

name_cn: str instance-attribute

Issuer name (zh-CN)

name_en: str instance-attribute

Issuer name (en)

name_hk: str instance-attribute

Issuer name (zh-HK)

Language

Language identifier

EN

Bases: Language

en

ZH_CN

Bases: Language

zh-CN

ZH_HK

Bases: Language

zh-HK

MarginRatio

Margin ratio

fm_factor: Decimal instance-attribute

Forced close-out margin ratio

im_factor: Decimal instance-attribute

Initial margin ratio

mm_factor: Decimal instance-attribute

Maintain the initial margin ratio

Market

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: Type[Market] instance-attribute

Market

trade_sessions: List[TradingSessionInfo] instance-attribute

Trading session

OpenApiException

Bases: Exception

OpenAPI exception

code: Optional[int] instance-attribute

Error code

message: str instance-attribute

Error message

OptionDirection

Option direction

Call

Bases: OptionDirection

Call

Put

Bases: OptionDirection

Put

Unknown

Bases: OptionDirection

Unknown

OptionQuote

Quote of option

contract_multiplier: Decimal instance-attribute

Contract multiplier

contract_size: Decimal instance-attribute

Contract size

contract_type: Type[OptionType] instance-attribute

Option type

direction: Type[OptionDirection] instance-attribute

Option direction

expiry_date: date instance-attribute

Exprity date

high: Decimal instance-attribute

High

historical_volatility: Decimal instance-attribute

Underlying security historical volatility of the option

implied_volatility: Decimal instance-attribute

Implied volatility

last_done: Decimal instance-attribute

Latest price

low: Decimal instance-attribute

Low

open: Decimal instance-attribute

Open

open_interest: int instance-attribute

Number of open positions

prev_close: Decimal instance-attribute

Yesterday's close

strike_price: Decimal instance-attribute

Strike price

symbol: str instance-attribute

Security code

timestamp: datetime instance-attribute

Time of latest price

trade_status: Type[TradeStatus] instance-attribute

Security trading status

turnover: Decimal instance-attribute

Turnover

underlying_symbol: str instance-attribute

Underlying security symbol of the option

volume: int instance-attribute

Volume

OptionType

Option type

American

Bases: OptionType

American

Europe

Bases: OptionType

Europe

Unknown

Bases: OptionType

Unknown

Order

Order

currency: str instance-attribute

Currency

executed_price: Optional[Decimal] instance-attribute

Executed price

executed_quantity: int instance-attribute

Executed quantity

expire_date: Optional[date] instance-attribute

Long term order expire date

last_done: Optional[Decimal] instance-attribute

Last done

limit_offset: Optional[Decimal] instance-attribute

TSLPAMT / TSLPPCT order limit offset amount

msg: str instance-attribute

Rejected Message or remark

order_id: str instance-attribute

Order ID

order_type: Type[OrderType] instance-attribute

Order type

outside_rth: Optional[Type[OutsideRTH]] instance-attribute

Enable or disable outside regular trading hours

price: Optional[Decimal] instance-attribute

Submitted price

quantity: int instance-attribute

Submitted quantity

remark: str instance-attribute

Remark

side: Type[OrderSide] instance-attribute

Order side

status: Type[OrderStatus] instance-attribute

Order status

stock_name: str instance-attribute

Stock name

submitted_at: datetime instance-attribute

Submitted time

symbol: str instance-attribute

Security code

tag: Type[OrderTag] instance-attribute

Order tag

time_in_force: Type[TimeInForceType] instance-attribute

Time in force type

trailing_amount: Optional[Decimal] instance-attribute

TSMAMT / TSLPAMT order trailing amount

trailing_percent: Optional[Decimal] instance-attribute

TSMPCT / TSLPPCT order trailing percent

trigger_at: Optional[datetime] instance-attribute

Conditional order trigger time

trigger_price: Optional[Decimal] instance-attribute

LIT / MIT Order Trigger Price

trigger_status: Optional[Type[TriggerStatus]] instance-attribute

Conditional order trigger status

updated_at: Optional[datetime] instance-attribute

Last updated time

OrderChargeDetail

Order charge detail

currency: str instance-attribute

Settlement currency

items: List[OrderChargeItem] instance-attribute

Order charge items

total_amount: Decimal instance-attribute

Total charges amount

OrderChargeFee

Order charge fee

amount: Decimal instance-attribute

Charge amount

code: str instance-attribute

Charge code

currency: str instance-attribute

Charge currency

name: str instance-attribute

Charge name

OrderChargeItem

Order charge item

code: Type[ChargeCategoryCode] instance-attribute

Charge category code

fees: List[OrderChargeFee] instance-attribute

Charge details

name: str instance-attribute

Charge category name

OrderDetail

Order detail

charge_detail: OrderChargeDetail instance-attribute

Order charges

currency: str instance-attribute

Currency

deductions_amount: Optional[Decimal] instance-attribute

Deduction amount

deductions_currency: Optional[str] instance-attribute

Deduction currency

deductions_status: Type[DeductionStatus] instance-attribute

Deduction status

executed_price: Optional[Decimal] instance-attribute

Executed price

executed_quantity: int instance-attribute

Executed quantity

expire_date: Optional[date] instance-attribute

Long term order expire date

free_amount: Optional[Decimal] instance-attribute

Commission-free amount

free_currency: Optional[str] instance-attribute

Commission-free currency

free_status: Type[CommissionFreeStatus] instance-attribute

Commission-free Status

history: List[OrderHistoryDetail] instance-attribute

Order history details

last_done: Optional[Decimal] instance-attribute

Last done

limit_offset: Optional[Decimal] instance-attribute

TSLPAMT / TSLPPCT order limit offset amount

msg: str instance-attribute

Rejected Message or remark

order_id: str instance-attribute

Order ID

order_type: Type[OrderType] instance-attribute

Order type

outside_rth: Optional[Type[OutsideRTH]] instance-attribute

Enable or disable outside regular trading hours

platform_deducted_amount: Optional[Decimal] instance-attribute

Platform deduction amount

platform_deducted_currency: Optional[str] instance-attribute

Platform deduction currency

platform_deducted_status: Type[DeductionStatus] instance-attribute

Platform fee deduction status

price: Optional[Decimal] instance-attribute

Submitted price

quantity: int instance-attribute

Submitted quantity

remark: str instance-attribute

Remark

side: Type[OrderSide] instance-attribute

Order side

status: Type[OrderStatus] instance-attribute

Order status

stock_name: str instance-attribute

Stock name

submitted_at: datetime instance-attribute

Submitted time

symbol: str instance-attribute

Security code

tag: Type[OrderTag] instance-attribute

Order tag

time_in_force: Type[TimeInForceType] instance-attribute

Time in force type

trailing_amount: Optional[Decimal] instance-attribute

TSMAMT / TSLPAMT order trailing amount

trailing_percent: Optional[Decimal] instance-attribute

TSMPCT / TSLPPCT order trailing percent

trigger_at: Optional[datetime] instance-attribute

Conditional order trigger time

trigger_price: Optional[Decimal] instance-attribute

LIT / MIT Order Trigger Price

trigger_status: Optional[Type[TriggerStatus]] instance-attribute

Conditional order trigger status

updated_at: Optional[datetime] instance-attribute

Last updated time

OrderHistoryDetail

Order history detail

msg: str instance-attribute

Execution or error message

price: Decimal instance-attribute

Executed price for executed orders, submitted price for expired, canceled, rejected orders, etc.

quantity: int instance-attribute

Executed quantity for executed orders, remaining quantity for expired, canceled, rejected orders, etc.

status: Type[OrderStatus] instance-attribute

Order status

time: datetime instance-attribute

Occurrence time

OrderSide

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: List[int] instance-attribute

Broker IDs

name_cn: str instance-attribute

Participant name (zh-CN)

name_en: str instance-attribute

Participant name (en)

name_hk: str instance-attribute

Participant name (zh-HK)

Period

Candlestick period

Day

Bases: Period

One Day

Min_1

Bases: Period

One Minute

Min_15

Bases: Period

Fifteen Minutes

Min_30

Bases: Period

Thirty Minutes

Min_5

Bases: Period

Five Minutes

Min_60

Bases: Period

Sixty Minutes

Month

Bases: Period

One Month

Unknown

Bases: Period

Unknown

Week

Bases: Period

One Week

Year

Bases: Period

One Year

PrePostQuote

Quote of US pre/post market

high: Decimal instance-attribute

High

last_done: Decimal instance-attribute

Latest price

low: Decimal instance-attribute

Low

prev_close: Decimal instance-attribute

Close of the last trade session

timestamp: datetime instance-attribute

Time of latest price

turnover: Decimal instance-attribute

Turnover

volume: int instance-attribute

Volume

PushBrokers

Brokers message

ask_brokers: List[Brokers] instance-attribute

Ask brokers

bid_brokers: List[Brokers] instance-attribute

Bid brokers

PushCandlestick

Candlestick updated event

candlestick: Candlestick instance-attribute

Candlestick

period: Period instance-attribute

Period type

PushCandlestickMode

Push candlestick mode

Confirmed

Bases: PushCandlestickMode

Confirmed

Realtime

Bases: PushCandlestickMode

Real-time

PushDepth

Depth message

asks: List[Depth] instance-attribute

Ask depth

bids: List[Depth] instance-attribute

Bid depth

PushOrderChanged

Order changed message

account_no: str instance-attribute

Account no

currency: str instance-attribute

Currency

executed_price: Optional[Decimal] instance-attribute

Executed price

executed_quantity: int instance-attribute

Executed quantity

last_price: Optional[Decimal] instance-attribute

Last price

last_share: Optional[Decimal] instance-attribute

Last share

limit_offset: Optional[Decimal] instance-attribute

Limit offset amount

msg: str instance-attribute

Rejected message or remark

order_id: str instance-attribute

Order ID

order_type: Type[OrderType] instance-attribute

Order type

remark: str instance-attribute

Remark message

side: Type[OrderSide] instance-attribute

Order side

status: Type[OrderStatus] instance-attribute

Order status

stock_name: str instance-attribute

Stock name

submitted_at: datetime instance-attribute

Submitted time

submitted_price: Decimal instance-attribute

Submitted price

submitted_quantity: int instance-attribute

Submitted quantity

symbol: str instance-attribute

Order symbol

tag: Type[OrderTag] instance-attribute

Order tag

trailing_amount: Optional[Decimal] instance-attribute

Trailing amount

trailing_percent: Optional[Decimal] instance-attribute

Trailing percent

trigger_at: Optional[datetime] instance-attribute

Conditional order trigger time

trigger_price: Optional[Decimal] instance-attribute

Order trigger price

trigger_status: Optional[Type[TriggerStatus]] instance-attribute

Conditional order trigger status

updated_at: datetime instance-attribute

Last updated time

PushQuote

Quote message

high: Decimal instance-attribute

High

last_done: Decimal instance-attribute

Latest price

low: Decimal instance-attribute

Low

open: Decimal instance-attribute

Open

timestamp: datetime instance-attribute

Time of latest price

trade_session: Type[TradeSession] instance-attribute

Trade session

trade_status: Type[TradeStatus] instance-attribute

Security trading status

turnover: Decimal instance-attribute

Turnover

volume: int instance-attribute

Volume

PushTrades

Trades message

trades: List[Trade] instance-attribute

Trades data

QuoteContext

Quote context

Parameters:

Name Type Description Default
config Config

Configuration object

required

brokers(symbol)

Get security brokers

Parameters:

Name Type Description Default
symbol str

Security code

required

Returns:

Type Description
SecurityBrokers

Security brokers

Examples:

::

from longport.openapi import QuoteContext, Config

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.brokers("700.HK")
print(resp)

calc_indexes(symbols, indexes)

Get calc indexes

Parameters:

Name Type Description Default
symbols List[str]

Security codes

required
indexes List[Type[CalcIndex]]

Calc indexes

required

Returns:

Type Description
List[SecurityCalcIndex]

Calc indexes of the symbols

Examples:

::

from longport.openapi import QuoteContext, Config, CalcIndex

config = Config.from_env()
ctx = QuoteContext(config)

resp = ctx.calc_indexes(["700.HK", "APPL.US"], [CalcIndex.LastDone, CalcIndex.ChangeRate])
print(resp)

candlesticks(symbol, period, count, adjust_type)

Get security candlesticks

Parameters:

Name Type Description Default
symbol str

Security code

required
period Type[Period]

Candlestick period

required
count int

Count of cancdlestick (Maximum is 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: str instance-attribute

Description

end_at: datetime instance-attribute

End time

key: str instance-attribute

Key

name: str instance-attribute

Name

start_at: datetime instance-attribute

Start time

RealtimeQuote

Real-time quote

high: Decimal instance-attribute

High

last_done: Decimal instance-attribute

Latest price

low: Decimal instance-attribute

Low

open: Decimal instance-attribute

Open

symbol: str instance-attribute

Security code

timestamp: datetime instance-attribute

Time of latest price

trade_status: Type[TradeStatus] instance-attribute

Security trading status

turnover: Decimal instance-attribute

Turnover

volume: int instance-attribute

Volume

SecuritiesUpdateMode

Securities update mode

Add

Bases: SecuritiesUpdateMode

Add securities

Remove

Bases: SecuritiesUpdateMode

Remove securities

Replace

Bases: SecuritiesUpdateMode

Replace securities

Security

Security

name_cn: str instance-attribute

Security name (zh-CN)

name_en: str instance-attribute

Security name (en)

name_hk: str instance-attribute

Security name (zh-HK)

symbol: str instance-attribute

Security code

SecurityBoard

Security board

CNIX

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: List[Brokers] instance-attribute

Ask brokers

bid_brokers: List[Brokers] instance-attribute

Bid brokers

SecurityCalcIndex

Security calc index response

amplitude: Optional[Decimal] instance-attribute

Amplitude

balance_point: Optional[Decimal] instance-attribute

Breakeven point

call_price: Optional[Decimal] instance-attribute

Call price

capital_flow: Optional[Decimal] instance-attribute

Capital flow

change_rate: Optional[Decimal] instance-attribute

Change ratio

change_value: Optional[Decimal] instance-attribute

Change value

conversion_ratio: Optional[Decimal] instance-attribute

Conversion ratio

delta: Optional[Decimal] instance-attribute

Delta

dividend_ratio_ttm: Optional[Decimal] instance-attribute

Dividend ratio (TTM)

effective_leverage: Optional[Decimal] instance-attribute

Effective leverage

expiry_date: Optional[date] instance-attribute

Expiry date

five_day_change_rate: Optional[Decimal] instance-attribute

Five days change ratio

five_minutes_change_rate: Optional[Decimal] instance-attribute

Five minutes change ratio

gamma: Optional[Decimal] instance-attribute

Gamma

half_year_change_rate: Optional[Decimal] instance-attribute

Half year change ratio

implied_volatility: Optional[Decimal] instance-attribute

Implied volatility

itm_otm: Optional[Decimal] instance-attribute

In/out of the bound

last_done: Optional[Decimal] instance-attribute

Latest price

leverage_ratio: Optional[Decimal] instance-attribute

Leverage ratio

lower_strike_price: Optional[Decimal] instance-attribute

Lower bound price

open_interest: Optional[int] instance-attribute

Open interest

outstanding_qty: Optional[int] instance-attribute

Outstanding quantity

outstanding_ratio: Optional[Decimal] instance-attribute

Outstanding ratio

pb_ratio: Optional[Decimal] instance-attribute

PB

pe_ttm_ratio: Optional[Decimal] instance-attribute

PE (TTM)

premium: Optional[Decimal] instance-attribute

Premium

rho: Optional[Decimal] instance-attribute

Rho

strike_price: Optional[Decimal] instance-attribute

Strike price

symbol: str instance-attribute

Security symbol

ten_day_change_rate: Optional[Decimal] instance-attribute

Ten days change ratio

theta: Optional[Decimal] instance-attribute

Theta

to_call_price: Optional[Decimal] instance-attribute

Price interval from the call price

total_market_value: Optional[Decimal] instance-attribute

Total market value

turnover: Optional[Decimal] instance-attribute

Turnover

turnover_rate: Optional[Decimal] instance-attribute

turnover_rate

upper_strike_price: Optional[Decimal] instance-attribute

Upper bound price

vega: Optional[Decimal] instance-attribute

Vega

volume: Optional[int] instance-attribute

Volume

volume_ratio: Optional[Decimal] instance-attribute

Volume ratio

warrant_delta: Optional[Decimal] instance-attribute

Warrant delta

ytd_change_rate: Optional[Decimal] instance-attribute

Year-to-date change ratio

SecurityDepth

Security depth

asks: List[Depth] instance-attribute

Ask depth

bids: List[Depth] instance-attribute

Bid depth

SecurityListCategory

Security list category

Overnight

Bases: SecurityListCategory

Overnight

SecurityQuote

Quote of securitity

high: Decimal instance-attribute

High

last_done: Decimal instance-attribute

Latest price

low: Decimal instance-attribute

Low

open: Decimal instance-attribute

Open

overnight_quote: Optional[PrePostQuote] instance-attribute

Quote of US overnight market

post_market_quote: Optional[PrePostQuote] instance-attribute

Quote of US post market

pre_market_quote: Optional[PrePostQuote] instance-attribute

Quote of US pre market

prev_close: Decimal instance-attribute

Yesterday's close

symbol: str instance-attribute

Security code

timestamp: datetime instance-attribute

Time of latest price

trade_status: Type[TradeStatus] instance-attribute

Security trading status

turnover: Decimal instance-attribute

Turnover

volume: int instance-attribute

Volume

SecurityStaticInfo

The basic information of securities

board: Type[SecurityBoard] instance-attribute

Board

bps: Decimal instance-attribute

Net assets per share

circulating_shares: int instance-attribute

Circulating shares

currency: str instance-attribute

Trading currency

dividend_yield: Decimal instance-attribute

Dividend yield

eps: Decimal instance-attribute

Earnings per share

eps_ttm: Decimal instance-attribute

Earnings per share (TTM)

exchange: str instance-attribute

Exchange which the security belongs to

hk_shares: int instance-attribute

HK shares (only HK stocks)

lot_size: int instance-attribute

Lot size

name_cn: str instance-attribute

Security name (zh-CN)

name_en: str instance-attribute

Security name (en)

name_hk: str instance-attribute

Security name (zh-HK)

stock_derivatives: List[Type[DerivativeType]] instance-attribute

Types of supported derivatives

symbol: str instance-attribute

Security code

total_shares: int instance-attribute

Total shares

SortOrderType

Sort order type

Ascending

Bases: SortOrderType

Ascending

Descending

Bases: SortOrderType

Descending

StockPosition

Stock position

available_quantity: int instance-attribute

Available quantity

cost_price: Decimal instance-attribute

Cost Price(According to the client's choice of average purchase or diluted cost)

currency: str instance-attribute

Currency

init_quantity: Optional[int] instance-attribute

Initial position before market opening

market: Market instance-attribute

Market

quantity: int instance-attribute

The number of holdings

symbol: str instance-attribute

Stock code

symbol_name: str instance-attribute

Stock name

StockPositionChannel

Stock position channel

account_channel: str instance-attribute

Account type

positions: List[StockPosition] instance-attribute

Stock positions

StockPositionsResponse

Stock positions response

channels: List[StockPositionChannel] instance-attribute

Channels

StrikePriceInfo

Strike price info

call_symbol: str instance-attribute

Security code of call option

price: Decimal instance-attribute

Strike price

put_symbol: str instance-attribute

Security code of put option

standard: bool instance-attribute

Is standard

SubType

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: str instance-attribute

Order id

Subscription

Subscription

candlesticks: List[Type[Period]] instance-attribute

Candlesticks

sub_types: List[Type[SubType]] instance-attribute

Subscription types

symbol: str instance-attribute

Security code

TimeInForceType

Time in force type

Day

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: Type[TradeDirection] instance-attribute

Trade direction

price: Decimal instance-attribute

Price

timestamp: datetime instance-attribute

Time of trading

trade_session: Type[TradeSession] instance-attribute

Trade session

trade_type: str instance-attribute

Trade type

HK

  • * - Overseas 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: int instance-attribute

Volume

TradeContext

Trade context

Parameters:

Name Type Description Default
config Config

Configuration object

required

account_balance(currency=None)

Get account balance

Parameters:

Name Type Description Default
currency Optional[str]

Currency

None

Returns:

Type Description
List[AccountBalance]

Account list

Examples:

::

from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.account_balance()
print(resp)

cancel_order(order_id)

Cancel order

Parameters:

Name Type Description Default
order_id str

Order ID

required

Examples:

::

from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

ctx.cancel_order("709043056541253632")

cash_flow(start_at, end_at, business_type=None, symbol=None, page=None, size=None)

Get cash flow

Parameters:

Name Type Description Default
start_at datetime

Start time

required
end_at datetime

End time

required
business_type Optional[Type[BalanceType]]

Balance type

None
symbol Optional[str]

Target security code

None
page Optional[int]

Start page (Default: 1)

None
size Optional[int]

Page size (Default: 50)

None

Returns:

Type Description
List[CashFlow]

Cash flow list

Examples:

::

from datetime import datetime
from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.cash_flow(
    start_at = datetime(2022, 5, 9),
    end_at = datetime(2022, 5, 12),
)
print(resp)

estimate_max_purchase_quantity(symbol, order_type, side, price=None, currency=None, order_id=None)

Estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options

Parameters:

Name Type Description Default
symbol str

Security symbol

required
order_type Type[OrderType]

Order type

required
side Type[OrderSide]

Order side

required
price Optional[Decimal]

Estimated order price,

None
currency Optional[str]

Settlement currency

None
order_id Optional[str]

Order ID, required when estimating the maximum purchase quantity for a modified order

None

Returns:

Type Description
EstimateMaxPurchaseQuantityResponse

Response

Examples:

::

from longport.openapi import TradeContext, Config, OrderType, OrderSide

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.estimate_max_purchase_quantity(
    symbol = "700.HK",
    order_type = OrderType.LO,
    side = OrderSide.Buy,
)
print(resp)

fund_positions(symbols=None)

Get fund positions

Parameters:

Name Type Description Default
symbols Optional[List[str]]

Filter by fund codes

None

Returns:

Type Description
FundPositionsResponse

Fund positions

Examples:

::

from longport.openapi import TradeContext, Config

config = Config.from_env()
ctx = TradeContext(config)

resp = ctx.fund_positions()
print(resp)

history_executions(symbol=None, start_at=None, end_at=None)

Get history executions

Parameters:

Name Type Description Default
symbol Optional[str]

Filter by security code, example: 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: time instance-attribute

Being trading time

end_time: time instance-attribute

End trading time

trade_session: Type[TradeSession] instance-attribute

Trading sessions

TriggerStatus

Trigger status

Active

Bases: TriggerStatus

Active

Deactive

Bases: TriggerStatus

Deactive

Released

Bases: TriggerStatus

Released

Unknown

Bases: TriggerStatus

Unknown

WarrantInfo

Warrant info

balance_point: Optional[Decimal] instance-attribute

Breakeven point

call_price: Optional[Decimal] instance-attribute

Call price

change_rate: Decimal instance-attribute

Quote change rate

change_value: Decimal instance-attribute

Quote change

conversion_ratio: Optional[Decimal] instance-attribute

Conversion ratio

delta: Optional[Decimal] instance-attribute

Greek value delta

effective_leverage: Optional[Decimal] instance-attribute

Effective leverage

expiry_date: date instance-attribute

Expiry date

implied_volatility: Optional[Decimal] instance-attribute

Implied volatility

itm_otm: Optional[Decimal] instance-attribute

In/out of the bound

last_done: Decimal instance-attribute

Latest price

leverage_ratio: Decimal instance-attribute

Leverage ratio

lower_strike_price: Optional[Decimal] instance-attribute

Lower strike price

name: str instance-attribute

Security name

outstanding_qty: int instance-attribute

Outstanding quantity

outstanding_ratio: Decimal instance-attribute

Outstanding ratio

premium: Decimal instance-attribute

Premium

status: Type[WarrantStatus] instance-attribute

Status

strike_price: Optional[Decimal] instance-attribute

Strike price

symbol: str instance-attribute

Security code

to_call_price: Optional[Decimal] instance-attribute

Price interval from the call price

turnover: Decimal instance-attribute

Turnover

upper_strike_price: Optional[Decimal] instance-attribute

Upper strike price

volume: int instance-attribute

Volume

warrant_type: Type[WarrantType] instance-attribute

Warrant type

WarrantQuote

Quote of warrant

call_price: Decimal instance-attribute

Call price

category: Type[WarrantType] instance-attribute

Warrant type

conversion_ratio: Decimal instance-attribute

Conversion ratio

expiry_date: date instance-attribute

Exprity date

high: Decimal instance-attribute

High

implied_volatility: Decimal instance-attribute

Implied volatility

last_done: Decimal instance-attribute

Latest price

last_trade_date: date instance-attribute

Last tradalbe date

low: Decimal instance-attribute

Low

lower_strike_price: Decimal instance-attribute

Lower bound price

open: Decimal instance-attribute

Open

outstanding_quantity: int instance-attribute

Outstanding quantity

outstanding_ratio: Decimal instance-attribute

Outstanding ratio

prev_close: Decimal instance-attribute

Yesterday's close

strike_price: Decimal instance-attribute

Strike price

symbol: str instance-attribute

Security code

timestamp: datetime instance-attribute

Time of latest price

trade_status: Type[TradeStatus] instance-attribute

Security trading status

turnover: Decimal instance-attribute

Turnover

underlying_symbol: str instance-attribute

Underlying security symbol of the warrant

upper_strike_price: Decimal instance-attribute

Upper bound price

volume: int instance-attribute

Volume

WarrantSortBy

Warrant sort by

BalancePoint

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: int instance-attribute

Group id

name: str instance-attribute

Group name

securities: List[WatchlistSecurity] instance-attribute

Securities

WatchlistSecurity

Watchlist security

market: Market instance-attribute

Market

name: str instance-attribute

Security name

symbol: str instance-attribute

Security symbol

watched_at: datetime instance-attribute

Watched time

watched_price: Optional[Decimal] instance-attribute

Watched price