Code Reference

OpenApiException

Bases: Exception

OpenAPI exception

code instance-attribute

code: Optional[int]

Error code

message instance-attribute

message: str

Error message

__init__

__init__(code: int, message: str) -> None

HttpClient

A HTTP client for longPort open api

Parameters:
  • http_url (str) –

    HTTP API url

  • app_key (str) –

    App Key

  • app_secret (str) –

    App Secret

  • access_token (str) –

    Access Token

__init__

__init__(http_url: str, app_key: str, app_secret: str, access_token: str) -> None

from_env classmethod

from_env() -> HttpClient

Create a new HttpClient from the given environment variables

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

Variables

  • LONGPORT_HTTP_URL - HTTP endpoint url
  • LONGPORT_APP_KEY - App key
  • LONGPORT_APP_SECRET - App secret
  • LONGPORT_ACCESS_TOKEN - Access token

request

request(method: str, path: str, headers: Optional[dict[str, str]] = None, body: Optional[Any] = None) -> Any

Performs a HTTP reqest

Examples:

::

from longport.openapi import HttpClient

client = HttpClient(http_url, app_key,
                    app_secret, access_token);

# get
resp = client.request("get", "/foo/bar");
print(resp)

# post
client.request("get", "/foo/bar", { "foo": 1, "bar": 2 });

PushCandlestickMode

Push candlestick mode

Realtime

Bases: PushCandlestickMode

Real-time

Confirmed

Bases: PushCandlestickMode

Confirmed

Config

Configuration options for LongPort sdk

Parameters:
  • app_key (str) –

    App Key

  • app_secret (str) –

    App Secret

  • access_token (str) –

    Access Token

  • http_url (Optional[str], default: None ) –

    HTTP API url

  • quote_ws_url (Optional[str], default: None ) –

    Websocket url for quote API

  • trade_ws_url (Optional[str], default: None ) –

    Websocket url for trade API

  • language (Optional[Type[Language]], default: None ) –

    Language identifier

  • enable_overnight (bool, default: False ) –

    Enable overnight quote

  • push_candlestick_mode (Type[PushCandlestickMode], default: Realtime ) –

    Push candlestick mode

  • enable_print_quote_packages (bool, default: True ) –

    Enable printing the opened quote packages when connected to the server

  • log_path (Optional[str], default: None ) –

    Set the path of the log files

__init__

__init__(app_key: str, app_secret: str, access_token: str, http_url: Optional[str] = None, quote_ws_url: Optional[str] = None, trade_ws_url: Optional[str] = None, language: Optional[Type[Language]] = None, enable_overnight: bool = False, push_candlestick_mode: Type[PushCandlestickMode] = PushCandlestickMode.Realtime, enable_print_quote_packages: bool = True, log_path: Optional[str] = None) -> None

from_env classmethod

from_env() -> Config

Create a new Config from the given environment variables

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

Variables

  • LONGPORT_APP_KEY - App 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)
  • LONGPORT_PUSH_CANDLESTICK_MODE - realtime or confirmed (Default: realtime)
  • LONGPORT_PRINT_QUOTE_PACKAGES - Print quote packages when connected, true or false (Default: true)
  • LONGPORT_LOG_PATH - Set the path of the log files (Default: no logs)

refresh_access_token

refresh_access_token(expired_at: Optional[datetime] = None) -> str

Gets a new access_token

Parameters:
  • expired_at (Optional[datetime], default: None ) –

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

Returns:
  • str

    Access token

Language

Language identifier

ZH_CN

Bases: Language

zh-CN

ZH_HK

Bases: Language

zh-HK

EN

Bases: Language

en

Market

Market

Unknown

Bases: Market

Unknown

US

Bases: Market

US market

HK

Bases: Market

HK market

CN

Bases: Market

CN market

SG

Bases: Market

SG market

PushQuote

Quote message

last_done instance-attribute

last_done: Decimal

Latest price

open instance-attribute

open: Decimal

Open

high instance-attribute

high: Decimal

High

low instance-attribute

low: Decimal

Low

timestamp instance-attribute

timestamp: datetime

Time of latest price

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

trade_status instance-attribute

trade_status: Type[TradeStatus]

Security trading status

trade_session instance-attribute

trade_session: Type[TradeSession]

Trade session

current_volume instance-attribute

current_volume: int

Increase volume between pushes

current_turnover instance-attribute

current_turnover: Decimal

Increase turnover between pushes

PushDepth

Depth message

asks instance-attribute

asks: List[Depth]

Ask depth

bids instance-attribute

bids: List[Depth]

Bid depth

PushBrokers

Brokers message

ask_brokers instance-attribute

ask_brokers: List[Brokers]

Ask brokers

bid_brokers instance-attribute

bid_brokers: List[Brokers]

Bid brokers

PushTrades

Trades message

trades instance-attribute

trades: List[Trade]

Trades data

PushCandlestick

Candlestick updated event

period instance-attribute

period: Period

Period type

candlestick instance-attribute

candlestick: Candlestick

Candlestick

is_confirmed instance-attribute

is_confirmed: bool

Is confirmed

SubType

Subscription flags

Quote

Bases: SubType

Quote

Depth

Bases: SubType

Depth

Brokers

Bases: SubType

Broker

Trade

Bases: SubType

Trade

DerivativeType

Derivative type

Option

Bases: DerivativeType

US stock options

Warrant

Bases: DerivativeType

HK warrants

SecurityBoard

Security board

Unknown

Bases: SecurityBoard

Unknown

USMain

Bases: SecurityBoard

US Pink Board

USPink

Bases: SecurityBoard

US Pink Board

USDJI

Bases: SecurityBoard

Dow Jones Industrial Average

USNSDQ

Bases: SecurityBoard

Nasdsaq Index

USSector

Bases: SecurityBoard

US Industry Board

USOption

Bases: SecurityBoard

US Option

USOptionS

Bases: SecurityBoard

US Sepecial Option

HKEquity

Bases: SecurityBoard

Hong Kong Equity Securities

HKPreIPO

Bases: SecurityBoard

HK PreIPO Security

HKWarrant

Bases: SecurityBoard

HK Warrant

HKHS

Bases: SecurityBoard

Hang Seng Index

HKSector

Bases: SecurityBoard

HK 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

CNIX

Bases: SecurityBoard

CN Index

CNSector

Bases: SecurityBoard

CN Industry Board

SZMainConnect

Bases: SecurityBoard

SZ Main Board(Connect)

SZMainNonConnect

Bases: SecurityBoard

SZ Main Board(Non Connect)

SZGEMConnect

Bases: SecurityBoard

SZ Gem Board(Connect)

SZGEMNonConnect

Bases: SecurityBoard

SZ Gem Board(Non Connect)

SGMain

Bases: SecurityBoard

SG Main Board

STI

Bases: SecurityBoard

Singapore Straits Index

SGSector

Bases: SecurityBoard

SG Industry Board

Security

Security

symbol instance-attribute

symbol: str

Security code

name_cn instance-attribute

name_cn: str

Security name (zh-CN)

name_en instance-attribute

name_en: str

Security name (en)

name_hk instance-attribute

name_hk: str

Security name (zh-HK)

SecurityListCategory

Security list category

Overnight

Bases: SecurityListCategory

Overnight

SecurityStaticInfo

The basic information of securities

symbol instance-attribute

symbol: str

Security code

name_cn instance-attribute

name_cn: str

Security name (zh-CN)

name_en instance-attribute

name_en: str

Security name (en)

name_hk instance-attribute

name_hk: str

Security name (zh-HK)

exchange instance-attribute

exchange: str

Exchange which the security belongs to

currency instance-attribute

currency: str

Trading currency

lot_size instance-attribute

lot_size: int

Lot size

total_shares instance-attribute

total_shares: int

Total shares

circulating_shares instance-attribute

circulating_shares: int

Circulating shares

hk_shares instance-attribute

hk_shares: int

HK shares (only HK stocks)

eps instance-attribute

eps: Decimal

Earnings per share

eps_ttm instance-attribute

eps_ttm: Decimal

Earnings per share (TTM)

bps instance-attribute

bps: Decimal

Net assets per share

dividend_yield instance-attribute

dividend_yield: Decimal

Dividend yield

stock_derivatives instance-attribute

stock_derivatives: List[Type[DerivativeType]]

Types of supported derivatives

board instance-attribute

board: Type[SecurityBoard]

Board

TradeStatus

Security Status

Normal

Bases: TradeStatus

Normal

Halted

Bases: TradeStatus

Suspension

Delisted

Bases: TradeStatus

Delisted

Fuse

Bases: TradeStatus

Fuse

PrepareList

Bases: TradeStatus

Prepare List

CodeMoved

Bases: TradeStatus

Code Moved

ToBeOpened

Bases: TradeStatus

To Be Opened

SplitStockHalts

Bases: TradeStatus

Split Stock Halts

Expired

Bases: TradeStatus

Expired

WarrantPrepareList

Bases: TradeStatus

Warrant To BeListed

Suspend

Bases: TradeStatus

Suspend

PrePostQuote

Quote of US pre/post market

last_done instance-attribute

last_done: Decimal

Latest price

timestamp instance-attribute

timestamp: datetime

Time of latest price

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

high instance-attribute

high: Decimal

High

low instance-attribute

low: Decimal

Low

prev_close instance-attribute

prev_close: Decimal

Close of the last trade session

SecurityQuote

Quote of securitity

symbol instance-attribute

symbol: str

Security code

last_done instance-attribute

last_done: Decimal

Latest price

prev_close instance-attribute

prev_close: Decimal

Yesterday's close

open instance-attribute

open: Decimal

Open

high instance-attribute

high: Decimal

High

low instance-attribute

low: Decimal

Low

timestamp instance-attribute

timestamp: datetime

Time of latest price

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

trade_status instance-attribute

trade_status: Type[TradeStatus]

Security trading status

pre_market_quote instance-attribute

pre_market_quote: Optional[PrePostQuote]

Quote of US pre market

post_market_quote instance-attribute

post_market_quote: Optional[PrePostQuote]

Quote of US post market

overnight_quote instance-attribute

overnight_quote: Optional[PrePostQuote]

Quote of US overnight market

OptionType

Option type

Unknown

Bases: OptionType

Unknown

American

Bases: OptionType

American

Europe

Bases: OptionType

Europe

OptionDirection

Option direction

Unknown

Bases: OptionDirection

Unknown

Put

Bases: OptionDirection

Put

Call

Bases: OptionDirection

Call

OptionQuote

Quote of option

symbol instance-attribute

symbol: str

Security code

last_done instance-attribute

last_done: Decimal

Latest price

prev_close instance-attribute

prev_close: Decimal

Yesterday's close

open instance-attribute

open: Decimal

Open

high instance-attribute

high: Decimal

High

low instance-attribute

low: Decimal

Low

timestamp instance-attribute

timestamp: datetime

Time of latest price

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

trade_status instance-attribute

trade_status: Type[TradeStatus]

Security trading status

implied_volatility instance-attribute

implied_volatility: Decimal

Implied volatility

open_interest instance-attribute

open_interest: int

Number of open positions

expiry_date instance-attribute

expiry_date: date

Exprity date

strike_price instance-attribute

strike_price: Decimal

Strike price

contract_multiplier instance-attribute

contract_multiplier: Decimal

Contract multiplier

contract_type instance-attribute

contract_type: Type[OptionType]

Option type

contract_size instance-attribute

contract_size: Decimal

Contract size

direction instance-attribute

direction: Type[OptionDirection]

Option direction

historical_volatility instance-attribute

historical_volatility: Decimal

Underlying security historical volatility of the option

underlying_symbol instance-attribute

underlying_symbol: str

Underlying security symbol of the option

WarrantType

Warrant type

Unknown

Bases: WarrantType

Unknown

Call

Bases: WarrantType

Call

Put

Bases: WarrantType

Put

Bull

Bases: WarrantType

Bull

Bear

Bases: WarrantType

Bear

Inline

Bases: WarrantType

Inline

WarrantQuote

Quote of warrant

symbol instance-attribute

symbol: str

Security code

last_done instance-attribute

last_done: Decimal

Latest price

prev_close instance-attribute

prev_close: Decimal

Yesterday's close

open instance-attribute

open: Decimal

Open

high instance-attribute

high: Decimal

High

low instance-attribute

low: Decimal

Low

timestamp instance-attribute

timestamp: datetime

Time of latest price

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

trade_status instance-attribute

trade_status: Type[TradeStatus]

Security trading status

implied_volatility instance-attribute

implied_volatility: Decimal

Implied volatility

expiry_date instance-attribute

expiry_date: date

Exprity date

last_trade_date instance-attribute

last_trade_date: date

Last tradalbe date

outstanding_ratio instance-attribute

outstanding_ratio: Decimal

Outstanding ratio

outstanding_quantity instance-attribute

outstanding_quantity: int

Outstanding quantity

conversion_ratio instance-attribute

conversion_ratio: Decimal

Conversion ratio

category instance-attribute

category: Type[WarrantType]

Warrant type

strike_price instance-attribute

strike_price: Decimal

Strike price

upper_strike_price instance-attribute

upper_strike_price: Decimal

Upper bound price

lower_strike_price instance-attribute

lower_strike_price: Decimal

Lower bound price

call_price instance-attribute

call_price: Decimal

Call price

underlying_symbol instance-attribute

underlying_symbol: str

Underlying security symbol of the warrant

Depth

Depth

position instance-attribute

position: int

Position

price instance-attribute

price: Optional[Decimal]

Price

volume instance-attribute

volume: int

Volume

order_num instance-attribute

order_num: int

Number of orders

SecurityDepth

Security depth

asks instance-attribute

asks: List[Depth]

Ask depth

bids instance-attribute

bids: List[Depth]

Bid depth

Brokers

Brokers

position instance-attribute

position: int

Position

broker_ids instance-attribute

broker_ids: List[int]

Broker IDs

SecurityBrokers

Security brokers

ask_brokers instance-attribute

ask_brokers: List[Brokers]

Ask brokers

bid_brokers instance-attribute

bid_brokers: List[Brokers]

Bid brokers

ParticipantInfo

Participant info

broker_ids instance-attribute

broker_ids: List[int]

Broker IDs

name_cn instance-attribute

name_cn: str

Participant name (zh-CN)

name_en instance-attribute

name_en: str

Participant name (en)

name_hk instance-attribute

name_hk: str

Participant name (zh-HK)

TradeDirection

Trade direction

Neutral

Bases: TradeDirection

Neutral

Down

Bases: TradeDirection

Down

Up

Bases: TradeDirection

Up

TradeSession

Trade session

Normal

Bases: TradeSession

Trading

Pre

Bases: TradeSession

Pre-Trading

Post

Bases: TradeSession

Post-Trading

Overnight

Bases: TradeSession

Overnight

Trade

Trade

price instance-attribute

price: Decimal

Price

volume instance-attribute

volume: int

Volume

timestamp instance-attribute

timestamp: datetime

Time of trading

trade_type instance-attribute

trade_type: str

Trade type

HK

  • * - Overseas 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)

direction instance-attribute

direction: Type[TradeDirection]

Trade direction

trade_session instance-attribute

trade_session: Type[TradeSession]

Trade session

IntradayLine

Intraday line

price instance-attribute

price: Decimal

Close price of the minute

timestamp instance-attribute

timestamp: datetime

Start time of the minute

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

avg_price instance-attribute

avg_price: Decimal

Average price

Candlestick

Candlestick

close instance-attribute

close: Decimal

Close price

open instance-attribute

open: Decimal

Open price

low instance-attribute

low: Decimal

Low price

high instance-attribute

high: Decimal

High price

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

timestamp instance-attribute

timestamp: datetime

Timestamp

AdjustType

Candlestick adjustment type

NoAdjust

Bases: AdjustType

Actual

ForwardAdjust

Bases: AdjustType

Adjust forward

Period

Candlestick period

Unknown

Bases: Period

Unknown

Min_1

Bases: Period

One Minute

Min_2

Bases: Period

Two Minutes

Min_3

Bases: Period

Three Minutes

Min_5

Bases: Period

Five Minutes

Min_10

Bases: Period

Ten Minutes

Min_15

Bases: Period

Fifteen Minutes

Min_20

Bases: Period

Twenty Minutes

Min_30

Bases: Period

Thirty Minutes

Min_45

Bases: Period

Forty-Five Minutes

Min_60

Bases: Period

Sixty Minutes

Min_120

Bases: Period

Two Hours

Min_180

Bases: Period

Three Hours

Min_240

Bases: Period

Four Hours

Day

Bases: Period

Daily

Week

Bases: Period

Weekly

Month

Bases: Period

Monthly

Quarter

Bases: Period

Quarterly

Year

Bases: Period

Yearly

StrikePriceInfo

Strike price info

price instance-attribute

price: Decimal

Strike price

call_symbol instance-attribute

call_symbol: str

Security code of call option

put_symbol instance-attribute

put_symbol: str

Security code of put option

standard instance-attribute

standard: bool

Is standard

IssuerInfo

Issuer info

issuer_id instance-attribute

issuer_id: int

Issuer ID

name_cn instance-attribute

name_cn: str

Issuer name (zh-CN)

name_en instance-attribute

name_en: str

Issuer name (en)

name_hk instance-attribute

name_hk: str

Issuer name (zh-HK)

WarrantStatus

Warrant status

Suspend

Bases: WarrantStatus

Suspend

PrepareList

Bases: WarrantStatus

Prepare List

Normal

Bases: WarrantStatus

Normal

SortOrderType

Sort order type

Ascending

Bases: SortOrderType

Ascending

Descending

Bases: SortOrderType

Descending

WarrantSortBy

Warrant sort by

LastDone

Bases: WarrantSortBy

LastDone

ChangeRate

Bases: WarrantSortBy

Change rate

ChangeValue

Bases: WarrantSortBy

Change value

Volume

Bases: WarrantSortBy

Volume

Turnover

Bases: WarrantSortBy

Turnover

ExpiryDate

Bases: WarrantSortBy

Expiry date

StrikePrice

Bases: WarrantSortBy

Strike price

UpperStrikePrice

Bases: WarrantSortBy

Upper strike price

LowerStrikePrice

Bases: WarrantSortBy

Lower strike price

OutstandingQuantity

Bases: WarrantSortBy

Outstanding quantity

OutstandingRatio

Bases: WarrantSortBy

Outstanding ratio

Premium

Bases: WarrantSortBy

Premium

ItmOtm

Bases: WarrantSortBy

In/out of the bound

ImpliedVolatility

Bases: WarrantSortBy

Implied volatility

Delta

Bases: WarrantSortBy

Greek value delta

CallPrice

Bases: WarrantSortBy

Call price

ToCallPrice

Bases: WarrantSortBy

Price interval from the call price

EffectiveLeverage

Bases: WarrantSortBy

Effective leverage

LeverageRatio

Bases: WarrantSortBy

Leverage ratio

ConversionRatio

Bases: WarrantSortBy

Conversion ratio

BalancePoint

Bases: WarrantSortBy

Breakeven point

Status

Bases: WarrantSortBy

Status

FilterWarrantExpiryDate

Filter warrant expiry date type

LT_3

Bases: FilterWarrantExpiryDate

Less than 3 months

Between_3_6

Bases: FilterWarrantExpiryDate

3 - 6 months

Between_6_12

Bases: FilterWarrantExpiryDate

6 - 12 months

GT_12

Bases: FilterWarrantExpiryDate

Greater than 12 months

FilterWarrantInOutBoundsType

Filter warrant in/out of the bounds type

In

Bases: FilterWarrantInOutBoundsType

In bounds

Out

Bases: FilterWarrantInOutBoundsType

Out bounds

WarrantInfo

Warrant info

symbol instance-attribute

symbol: str

Security code

warrant_type instance-attribute

warrant_type: Type[WarrantType]

Warrant type

name instance-attribute

name: str

Security name

last_done instance-attribute

last_done: Decimal

Latest price

change_rate instance-attribute

change_rate: Decimal

Quote change rate

change_value instance-attribute

change_value: Decimal

Quote change

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

expiry_date instance-attribute

expiry_date: date

Expiry date

strike_price instance-attribute

strike_price: Optional[Decimal]

Strike price

upper_strike_price instance-attribute

upper_strike_price: Optional[Decimal]

Upper strike price

lower_strike_price instance-attribute

lower_strike_price: Optional[Decimal]

Lower strike price

outstanding_qty instance-attribute

outstanding_qty: int

Outstanding quantity

outstanding_ratio instance-attribute

outstanding_ratio: Decimal

Outstanding ratio

premium instance-attribute

premium: Decimal

Premium

itm_otm instance-attribute

itm_otm: Optional[Decimal]

In/out of the bound

implied_volatility instance-attribute

implied_volatility: Optional[Decimal]

Implied volatility

delta instance-attribute

delta: Optional[Decimal]

Greek value delta

call_price instance-attribute

call_price: Optional[Decimal]

Call price

to_call_price instance-attribute

to_call_price: Optional[Decimal]

Price interval from the call price

effective_leverage instance-attribute

effective_leverage: Optional[Decimal]

Effective leverage

leverage_ratio instance-attribute

leverage_ratio: Decimal

Leverage ratio

conversion_ratio instance-attribute

conversion_ratio: Optional[Decimal]

Conversion ratio

balance_point instance-attribute

balance_point: Optional[Decimal]

Breakeven point

status instance-attribute

status: Type[WarrantStatus]

Status

TradingSessionInfo

The information of trading session

begin_time instance-attribute

begin_time: time

Being trading time

end_time instance-attribute

end_time: time

End trading time

trade_session instance-attribute

trade_session: Type[TradeSession]

Trading sessions

MarketTradingSession

Market trading session

market instance-attribute

market: Type[Market]

Market

trade_sessions instance-attribute

trade_sessions: List[TradingSessionInfo]

Trading session

MarketTradingDays

trading_days instance-attribute

trading_days: List[date]

half_trading_days instance-attribute

half_trading_days: List[date]

CapitalFlowLine

Capital flow line

inflow instance-attribute

inflow: Decimal

Inflow capital data

timestamp instance-attribute

timestamp: datetime

Time

CapitalDistribution

Capital distribution

large instance-attribute

large: Decimal

Large order

medium instance-attribute

medium: Decimal

Medium order

small instance-attribute

small: Decimal

Small order

CapitalDistributionResponse

Capital distribution response

timestamp instance-attribute

timestamp: datetime

Time

capital_in instance-attribute

capital_in: CapitalDistribution

Inflow capital data

capital_out instance-attribute

capital_out: CapitalDistribution

Outflow capital data

WatchlistSecurity

Watchlist security

symbol instance-attribute

symbol: str

Security symbol

market instance-attribute

market: Market

Market

name instance-attribute

name: str

Security name

watched_price instance-attribute

watched_price: Optional[Decimal]

Watched price

watched_at instance-attribute

watched_at: datetime

Watched time

WatchlistGroup

id instance-attribute

id: int

Group id

name instance-attribute

name: str

Group name

securities instance-attribute

securities: List[WatchlistSecurity]

Securities

SecuritiesUpdateMode

Securities update mode

Add

Bases: SecuritiesUpdateMode

Add securities

Remove

Bases: SecuritiesUpdateMode

Remove securities

Replace

Bases: SecuritiesUpdateMode

Replace securities

RealtimeQuote

Real-time quote

symbol instance-attribute

symbol: str

Security code

last_done instance-attribute

last_done: Decimal

Latest price

open instance-attribute

open: Decimal

Open

high instance-attribute

high: Decimal

High

low instance-attribute

low: Decimal

Low

timestamp instance-attribute

timestamp: datetime

Time of latest price

volume instance-attribute

volume: int

Volume

turnover instance-attribute

turnover: Decimal

Turnover

trade_status instance-attribute

trade_status: Type[TradeStatus]

Security trading status

Subscription

Subscription

symbol instance-attribute

symbol: str

Security code

sub_types instance-attribute

sub_types: List[Type[SubType]]

Subscription types

candlesticks instance-attribute

candlesticks: List[Type[Period]]

Candlesticks

CalcIndex

Calc index

LastDone

Bases: CalcIndex

Latest price

ChangeValue

Bases: CalcIndex

Change value

ChangeRate

Bases: CalcIndex

Change rate

Volume

Bases: CalcIndex

Volume

Turnover

Bases: CalcIndex

Turnover

YtdChangeRate

Bases: CalcIndex

Year-to-date change ratio

TurnoverRate

Bases: CalcIndex

Turnover rate

TotalMarketValue

Bases: CalcIndex

Total market value

CapitalFlow

Bases: CalcIndex

Capital flow

Amplitude

Bases: CalcIndex

Amplitude

VolumeRatio

Bases: CalcIndex

Volume ratio

PeTtmRatio

Bases: CalcIndex

PE (TTM)

PbRatio

Bases: CalcIndex

PB

DividendRatioTtm

Bases: CalcIndex

Dividend ratio (TTM)

FiveDayChangeRate

Bases: CalcIndex

Five days change ratio

TenDayChangeRate

Bases: CalcIndex

Ten days change ratio

HalfYearChangeRate

Bases: CalcIndex

Half year change ratio

FiveMinutesChangeRate

Bases: CalcIndex

Five minutes change ratio

ExpiryDate

Bases: CalcIndex

Expiry date

StrikePrice

Bases: CalcIndex

Strike price

UpperStrikePrice

Bases: CalcIndex

Upper bound price

LowerStrikePrice

Bases: CalcIndex

Lower bound price

OutstandingQty

Bases: CalcIndex

Outstanding quantity

OutstandingRatio

Bases: CalcIndex

Outstanding ratio

Premium

Bases: CalcIndex

Premium

ItmOtm

Bases: CalcIndex

In/out of the bound

ImpliedVolatility

Bases: CalcIndex

Implied volatility

WarrantDelta

Bases: CalcIndex

Warrant delta

CallPrice

Bases: CalcIndex

Call price

ToCallPrice

Bases: CalcIndex

Price interval from the call price

EffectiveLeverage

Bases: CalcIndex

Effective leverage

LeverageRatio

Bases: CalcIndex

Leverage ratio

ConversionRatio

Bases: CalcIndex

Conversion ratio

BalancePoint

Bases: CalcIndex

Breakeven point

OpenInterest

Bases: CalcIndex

Open interest

Delta

Bases: CalcIndex

Delta

Gamma

Bases: CalcIndex

Gamma

Theta

Bases: CalcIndex

Theta

Vega

Bases: CalcIndex

Vega

Rho

Bases: CalcIndex

Rho

SecurityCalcIndex

Security calc index response

symbol instance-attribute

symbol: str

Security symbol

last_done instance-attribute

last_done: Optional[Decimal]

Latest price

change_value instance-attribute

change_value: Optional[Decimal]

Change value

change_rate instance-attribute

change_rate: Optional[Decimal]

Change ratio

volume instance-attribute

volume: Optional[int]

Volume

turnover instance-attribute

turnover: Optional[Decimal]

Turnover

ytd_change_rate instance-attribute

ytd_change_rate: Optional[Decimal]

Year-to-date change ratio

turnover_rate instance-attribute

turnover_rate: Optional[Decimal]

turnover_rate

total_market_value instance-attribute

total_market_value: Optional[Decimal]

Total market value

capital_flow instance-attribute

capital_flow: Optional[Decimal]

Capital flow

amplitude instance-attribute

amplitude: Optional[Decimal]

Amplitude

volume_ratio instance-attribute

volume_ratio: Optional[Decimal]

Volume ratio

pe_ttm_ratio instance-attribute

pe_ttm_ratio: Optional[Decimal]

PE (TTM)

pb_ratio instance-attribute

pb_ratio: Optional[Decimal]

PB

dividend_ratio_ttm instance-attribute

dividend_ratio_ttm: Optional[Decimal]

Dividend ratio (TTM)

five_day_change_rate instance-attribute

five_day_change_rate: Optional[Decimal]

Five days change ratio

ten_day_change_rate instance-attribute

ten_day_change_rate: Optional[Decimal]

Ten days change ratio

half_year_change_rate instance-attribute

half_year_change_rate: Optional[Decimal]

Half year change ratio

five_minutes_change_rate instance-attribute

five_minutes_change_rate: Optional[Decimal]

Five minutes change ratio

expiry_date instance-attribute

expiry_date: Optional[date]

Expiry date

strike_price instance-attribute

strike_price: Optional[Decimal]

Strike price

upper_strike_price instance-attribute

upper_strike_price: Optional[Decimal]

Upper bound price

lower_strike_price instance-attribute

lower_strike_price: Optional[Decimal]

Lower bound price

outstanding_qty instance-attribute

outstanding_qty: Optional[int]

Outstanding quantity

outstanding_ratio instance-attribute

outstanding_ratio: Optional[Decimal]

Outstanding ratio

premium instance-attribute

premium: Optional[Decimal]

Premium

itm_otm instance-attribute

itm_otm: Optional[Decimal]

In/out of the bound

implied_volatility instance-attribute

implied_volatility: Optional[Decimal]

Implied volatility

warrant_delta instance-attribute

warrant_delta: Optional[Decimal]

Warrant delta

call_price instance-attribute

call_price: Optional[Decimal]

Call price

to_call_price instance-attribute

to_call_price: Optional[Decimal]

Price interval from the call price

effective_leverage instance-attribute

effective_leverage: Optional[Decimal]

Effective leverage

leverage_ratio instance-attribute

leverage_ratio: Optional[Decimal]

Leverage ratio

conversion_ratio instance-attribute

conversion_ratio: Optional[Decimal]

Conversion ratio

balance_point instance-attribute

balance_point: Optional[Decimal]

Breakeven point

open_interest instance-attribute

open_interest: Optional[int]

Open interest

delta instance-attribute

delta: Optional[Decimal]

Delta

gamma instance-attribute

gamma: Optional[Decimal]

Gamma

theta instance-attribute

theta: Optional[Decimal]

Theta

vega instance-attribute

vega: Optional[Decimal]

Vega

rho instance-attribute

rho: Optional[Decimal]

Rho

QuotePackageDetail

Quote package detail

key instance-attribute

key: str

Key

name instance-attribute

name: str

Name

description instance-attribute

description: str

Description

start_at instance-attribute

start_at: datetime

Start time

end_at instance-attribute

end_at: datetime

End time

QuoteContext

Quote context

Parameters:
  • config (Config) –

    Configuration object

__init__

__init__(config: Config) -> None

member_id

member_id() -> int

Returns the member ID

quote_level

quote_level() -> str

Returns the quote level

quote_package_details

quote_package_details() -> List[QuotePackageDetail]

Returns the quote package details

set_on_quote

set_on_quote(callback: Callable[[str, PushQuote], None]) -> None

Set quote callback, after receiving the quote data push, it will call back to this function.

set_on_depth

set_on_depth(callback: Callable[[str, PushDepth], None]) -> None

Set depth callback, after receiving the depth data push, it will call back to this function.

set_on_brokers

set_on_brokers(callback: Callable[[str, PushBrokers], None]) -> None

Set brokers callback, after receiving the brokers data push, it will call back to this function.

set_on_trades

set_on_trades(callback: Callable[[str, PushTrades], None]) -> None

Set trades callback, after receiving the trades data push, it will call back to this function.

set_on_candlestick

set_on_candlestick(callback: Callable[[str, PushCandlestick], None]) -> None

Set candlestick callback, after receiving the candlestick updated event, it will call back to this function.

subscribe

subscribe(symbols: List[str], sub_types: List[Type[SubType]], is_first_push: bool = False) -> None

Subscribe

Parameters:
  • symbols (List[str]) –

    Security codes

  • sub_types (List[Type[SubType]]) –

    Subscribe types

  • is_first_push (bool, default: False ) –

    Whether to perform a data push immediately after subscribing. (trade not supported)

Examples:

::

from time import sleep
from longport.openapi import QuoteContext, Config, SubType, PushQuote

def on_quote(symbol: str, event: PushQuote):
    print(symbol, event)

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

ctx.subscribe(["700.HK", "AAPL.US"], [
              SubType.Quote], is_first_push = True)
sleep(30)

unsubscribe

unsubscribe(symbols: List[str], sub_types: List[Type[SubType]]) -> None

Unsubscribe

Parameters:

Examples:

::

from longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
ctx.unsubscribe(["AAPL.US"], [SubType.Quote])

subscribe_candlesticks

subscribe_candlesticks(symbol: str, period: Type[Period]) -> List[Candlestick]

Subscribe security candlesticks

Parameters:
  • symbol (str) –

    Security code

  • period (Type[Period]) –

    Period type

Examples:

::

from longport.openapi import QuoteContext, Config, PushCandlestick
config = Config.from_env()
ctx = QuoteContext(config)

def on_candlestick(symbol: str, event: PushCandlestick):
    print(symbol, event)

ctx.set_on_candlestick(on_candlestick)
ctx.subscribe_candlesticks("700.HK", Period.Min_1)
sleep(30)

unsubscribe_candlesticks

unsubscribe_candlesticks(symbol: str, period: Type[Period]) -> None

Subscribe security candlesticks

Parameters:
  • symbol (str) –

    Security code

  • period (Type[Period]) –

    Period type

subscriptions

subscriptions() -> List[Subscription]

Get subscription information

Examples:

::

from longport.openapi import QuoteContext, Config, SubType
config = Config.from_env()
ctx = QuoteContext(config)

ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
resp = ctx.subscriptions()
print(resp)

static_info

static_info(symbols: List[str]) -> List[SecurityStaticInfo]

Get basic information of securities

Parameters:
  • symbols (List[str]) –

    Security codes

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.static_info(
    ["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)

quote

quote(symbols: List[str]) -> List[SecurityQuote]

Get quote of securities

Parameters:
  • symbols (List[str]) –

    Security codes

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)

option_quote

option_quote(symbols: List[str]) -> List[OptionQuote]

Get quote of option securities

Parameters:
  • symbols (List[str]) –

    Security codes

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.option_quote(["AAPL230317P160000.US"])
print(resp)

warrant_quote

warrant_quote(symbols: List[str]) -> List[WarrantQuote]

Get quote of warrant securities

Parameters:
  • symbols (List[str]) –

    Security codes

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.warrant_quote(["21125.HK"])
print(resp)

depth

depth(symbol: str) -> SecurityDepth

Get security depth

Parameters:
  • symbol (str) –

    Security code

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

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

brokers

brokers(symbol: str) -> SecurityBrokers

Get security brokers

Parameters:
  • symbol (str) –

    Security code

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

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

participants

participants() -> List[ParticipantInfo]

Get participants

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.participants()
print(resp)

trades

trades(symbol: str, count: int) -> List[Trade]

Get security trades

Parameters:
  • symbol (str) –

    Security code

  • count (int) –

    Count of trades (Maximum is 1000)

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.trades("700.HK", 10)
print(resp)

intraday

intraday(symbol: str) -> List[IntradayLine]

Get security intraday lines

Parameters:
  • symbol (str) –

    Security code

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

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

candlesticks

candlesticks(symbol: str, period: Type[Period], count: int, adjust_type: Type[AdjustType]) -> List[Candlestick]

Get security candlesticks

Parameters:
  • symbol (str) –

    Security code

  • period (Type[Period]) –

    Candlestick period

  • count (int) –

    Count of cancdlestick (Maximum is 1000)

  • adjust_type (Type[AdjustType]) –

    Adjustment type

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config, Period, AdjustType

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

resp = ctx.candlesticks(
    "700.HK", Period.Day, 10, AdjustType.NoAdjust)
print(resp)

history_candlesticks_by_offset

history_candlesticks_by_offset(symbol: str, period: Type[Period], adjust_type: Type[AdjustType], forward: bool, count: int, time: Optional[datetime] = None) -> List[Candlestick]

Get security history candlesticks by offset

Parameters:
  • symbol (str) –

    Security code

  • period (Type[Period]) –

    Period type

  • adjust_type (Type[AdjustType]) –

    Adjust type

  • forward (bool) –

    If True, query the latest from the specified time

  • count (int) –

    Count of candlesticks

  • time (Optional[datetime], default: None ) –

    Datetime

history_candlesticks_by_date

history_candlesticks_by_date(symbol: str, period: Type[Period], adjust_type: Type[AdjustType], start: Optional[date], end: Optional[date]) -> List[Candlestick]

Get security history candlesticks by date

Parameters:

option_chain_expiry_date_list

option_chain_expiry_date_list(symbol: str) -> List[date]

Get option chain expiry date list

Parameters:
  • symbol (str) –

    Security code

Returns:
  • 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

option_chain_info_by_date(symbol: str, expiry_date: date) -> List[StrikePriceInfo]

Get option chain info by date

Parameters:
  • symbol (str) –

    Security code

  • expiry_date (date) –

    Expiry date

Returns:

Examples:

::

from datetime import date
from longport.openapi import QuoteContext, Config

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

resp = ctx.option_chain_info_by_date(
    "AAPL.US", date(2023, 1, 20))
print(resp)

warrant_issuers

warrant_issuers() -> List[IssuerInfo]

Get warrant issuers

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.warrant_issuers()
print(resp)

warrant_list

warrant_list(symbol: str, sort_by: Type[WarrantSortBy], sort_order: Type[SortOrderType], warrant_type: Optional[List[Type[WarrantType]]] = None, issuer: Optional[List[int]] = None, expiry_date: Optional[List[Type[FilterWarrantExpiryDate]]] = None, price_type: Optional[List[Type[FilterWarrantInOutBoundsType]]] = None, status: Optional[List[Type[WarrantStatus]]] = None) -> List[WarrantInfo]

Get warrant list

Parameters:
Returns:

Examples:

::

from longport.openapi import QuoteContext, Config, WarrantSortBy, SortOrderType

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

resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)
print(resp)

trading_session

trading_session() -> List[MarketTradingSession]

Get trading session of the day

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.trading_session()
print(resp)

trading_days

trading_days(market: Type[Market], begin: date, end: date) -> MarketTradingDays

Get trading session of the day

The interval must be less than one month, and only the most recent year is supported.

Parameters:
Returns:

Examples:

::

from datetime import date
from longport.openapi import QuoteContext, Config, Market

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

resp = ctx.trading_days(
    Market.HK, date(2022, 1, 1), date(2022, 2, 1))
print(resp)

capital_flow

capital_flow(symbol: str) -> List[CapitalFlowLine]

Get capital flow intraday

Parameters:
  • symbol (str) –

    Security code

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

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

capital_distribution

capital_distribution(symbol: str) -> CapitalDistributionResponse

Get capital distribution

Parameters:
  • symbol (str) –

    Security code

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

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

calc_indexes

calc_indexes(symbols: List[str], indexes: List[Type[CalcIndex]]) -> List[SecurityCalcIndex]

Get calc indexes

Parameters:
Returns:

Examples:

::

from longport.openapi import QuoteContext, Config, CalcIndex

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

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

watchlist

watchlist() -> List[WatchlistGroup]

Get watch list

Returns:

Examples:

::

from longport.openapi import QuoteContext, Config

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

resp = ctx.watchlist()
print(resp)

create_watchlist_group

create_watchlist_group(name: str, securities: Optional[List[str]] = None) -> int

Create watchlist group

Parameters:
  • name (str) –

    Group name

  • securities (Optional[List[str]], default: None ) –

    Securities

Returns:
  • 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

delete_watchlist_group(id: int, purge: bool = False)

Delete watchlist group

Parameters:
  • id (int) –

    Group ID

  • purge (bool, default: False ) –

    Move securities in this group to the default group

Examples:

::

from longport.openapi import QuoteContext, Config

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

update_watchlist_group

update_watchlist_group(id: int, name: Optional[str] = None, securities: Optional[List[str]] = None, mode: Optional[Type[SecuritiesUpdateMode]] = None)

Update watchlist group

Parameters:

Examples:

::

from longport.openapi import QuoteContext, Config, SecuritiesUpdateMode

config = Config.from_env()
ctx = QuoteContext(config)
ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace)

security_list

security_list(market: Type[Market], category: Type[SecurityListCategory]) -> List[Security]

Get security list

Parameters:
Returns:

Examples:

::

from longport.openapi import QuoteContext, Config, Market, SecurityListCategory

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

resp = ctx.security_list(Market.HK, SecurityListCategory.Overnight)
print(resp)

realtime_quote

realtime_quote(symbols: List[str]) -> List[RealtimeQuote]

Get real-time quote

Get real-time quotes of the subscribed symbols, it always returns the data in the local storage.

Parameters:
  • symbols (List[str]) –

    Security codes

Returns:

Examples:

::

from time import sleep
from longport.openapi import QuoteContext, Config, SubType

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

ctx.subscribe(["700.HK", "AAPL.US"], [
              SubType.Quote], is_first_push = True)
sleep(5)
resp = ctx.realtime_quote(["700.HK", "AAPL.US"])
print(resp)

realtime_depth

realtime_depth(symbol: str) -> SecurityDepth

Get real-time depth

Get real-time depth of the subscribed symbols, it always returns the data in the local storage.

Parameters:
  • symbol (str) –

    Security code

Returns:

Examples:

::

from time import sleep
from longport.openapi import QuoteContext, Config, SubType

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

ctx.subscribe(["700.HK", "AAPL.US"], [
              SubType.Depth], is_first_push = True)
sleep(5)
resp = ctx.realtime_depth("700.HK")
print(resp)

realtime_brokers

realtime_brokers(symbol: str) -> SecurityBrokers

Get real-time brokers

Get real-time brokers of the subscribed symbols, it always returns the data in the local storage.

Parameters:
  • symbol (str) –

    Security code

Returns:

Examples:

::

from time import sleep
from longport.openapi import QuoteContext, Config, SubType

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

ctx.subscribe(["700.HK", "AAPL.US"], [
              SubType.Brokers], is_first_push = True)
sleep(5)
resp = ctx.realtime_brokers("700.HK")
print(resp)

realtime_trades

realtime_trades(symbol: str, count: int) -> List[Trade]

Get real-time trades

Get real-time trades of the subscribed symbols, it always returns the data in the local storage.

Parameters:
  • symbol (str) –

    Security code

  • count (int) –

    Count of trades

Returns:

Examples:

::

from time import sleep
from longport.openapi import QuoteContext, Config, SubType

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

ctx.subscribe(["700.HK", "AAPL.US"], [
              SubType.Trade], is_first_push = False)
sleep(5)
resp = ctx.realtime_trades("700.HK", 10)
print(resp)

realtime_candlesticks

realtime_candlesticks(symbol: str, period: Type[Period], count: int) -> List[Candlestick]

Get real-time candlesticks

Get Get real-time candlesticks of the subscribed symbols, it always returns the data in the local storage.

Parameters:
  • symbol (str) –

    Security code

  • period (Type[Period]) –

    Period type

  • count (int) –

    Count of candlesticks

Returns:

Examples:

::

from time import sleep
from longport.openapi import QuoteContext, Config, Period

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

ctx.subscribe_candlesticks("AAPL.US", Period.Min_1)
sleep(5)
resp = ctx.realtime_candlesticks("AAPL.US", Period.Min_1, 10)
print(resp)

OrderSide

Order side

Unknown

Bases: OrderSide

Unknown

Buy

Bases: OrderSide

Buy

Sell

Bases: OrderSide

Sell

OrderType

Order type

Unknown

Bases: OrderType

Unknown

LO

Bases: OrderType

Limit Order

ELO

Bases: OrderType

Enhanced Limit Order

MO

Bases: OrderType

Market Order

AO

Bases: OrderType

At-auction Order

ALO

Bases: OrderType

At-auction Limit Order

ODD

Bases: OrderType

Odd Lots

LIT

Bases: OrderType

Limit If Touched

MIT

Bases: OrderType

Market If Touched

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)

SLO

Bases: OrderType

Special Limit Order

OrderStatus

Order status

Unknown

Bases: OrderStatus

Unknown

NotReported

Bases: OrderStatus

Not reported

ReplacedNotReported

Bases: OrderStatus

Not reported (Replaced Order)

ProtectedNotReported

Bases: OrderStatus

Not reported (Protected Order)

VarietiesNotReported

Bases: OrderStatus

Not reported (Conditional Order)

Filled

Bases: OrderStatus

Filled

WaitToNew

Bases: OrderStatus

Wait To New

New

Bases: OrderStatus

New

WaitToReplace

Bases: OrderStatus

Wait To Replace

PendingReplace

Bases: OrderStatus

Pending Replace

Replaced

Bases: OrderStatus

Replaced

PartialFilled

Bases: OrderStatus

Partial Filled

WaitToCancel

Bases: OrderStatus

Wait To Cancel

PendingCancel

Bases: OrderStatus

Pending Cancel

Rejected

Bases: OrderStatus

Rejected

Canceled

Bases: OrderStatus

Canceled

Expired

Bases: OrderStatus

ExpiredStatus

PartialWithdrawal

Bases: OrderStatus

PartialWithdrawal

OrderTag

Order tag

Unknown

Bases: OrderTag

Unknown

Normal

Bases: OrderTag

Normal Order

LongTerm

Bases: OrderTag

Long term Order

Grey

Bases: OrderTag

Grey Order

MarginCall

Bases: OrderTag

Force Selling

Offline

Bases: OrderTag

OTC

Creditor

Bases: OrderTag

Option Exercise Long

Debtor

Bases: OrderTag

Option Exercise Short

NonExercise

Bases: OrderTag

Wavier Of Option Exercise

AllocatedSub

Bases: OrderTag

Trade Allocation

TriggerStatus

Trigger status

Unknown

Bases: TriggerStatus

Unknown

Deactive

Bases: TriggerStatus

Deactive

Active

Bases: TriggerStatus

Active

Released

Bases: TriggerStatus

Released

Execution

Execution

order_id instance-attribute

order_id: str

Order ID

trade_id instance-attribute

trade_id: str

Execution ID

symbol instance-attribute

symbol: str

Security code

trade_done_at instance-attribute

trade_done_at: datetime

Trade done time

quantity instance-attribute

quantity: Decimal

Executed quantity

price instance-attribute

price: Decimal

Executed price

PushOrderChanged

Order changed message

side instance-attribute

side: Type[OrderSide]

Order side

stock_name instance-attribute

stock_name: str

Stock name

submitted_quantity instance-attribute

submitted_quantity: Decimal

Submitted quantity

symbol instance-attribute

symbol: str

Order symbol

order_type instance-attribute

order_type: Type[OrderType]

Order type

submitted_price instance-attribute

submitted_price: Decimal

Submitted price

executed_quantity instance-attribute

executed_quantity: Decimal

Executed quantity

executed_price instance-attribute

executed_price: Optional[Decimal]

Executed price

order_id instance-attribute

order_id: str

Order ID

currency instance-attribute

currency: str

Currency

status instance-attribute

status: Type[OrderStatus]

Order status

submitted_at instance-attribute

submitted_at: datetime

Submitted time

updated_at instance-attribute

updated_at: datetime

Last updated time

trigger_price instance-attribute

trigger_price: Optional[Decimal]

Order trigger price

msg instance-attribute

msg: str

Rejected message or remark

tag instance-attribute

tag: Type[OrderTag]

Order tag

trigger_status instance-attribute

trigger_status: Optional[Type[TriggerStatus]]

Conditional order trigger status

trigger_at instance-attribute

trigger_at: Optional[datetime]

Conditional order trigger time

trailing_amount instance-attribute

trailing_amount: Optional[Decimal]

Trailing amount

trailing_percent instance-attribute

trailing_percent: Optional[Decimal]

Trailing percent

limit_offset instance-attribute

limit_offset: Optional[Decimal]

Limit offset amount

account_no instance-attribute

account_no: str

Account no

last_share instance-attribute

last_share: Optional[Decimal]

Last share

last_price instance-attribute

last_price: Optional[Decimal]

Last price

remark instance-attribute

remark: str

Remark message

TimeInForceType

Time in force type

Unknown

Bases: TimeInForceType

Unknown

Day

Bases: TimeInForceType

Day Order

GoodTilCanceled

Bases: TimeInForceType

Good Til Canceled Order

GoodTilDate

Bases: TimeInForceType

Good Til Date Order

OutsideRTH

Enable or disable outside regular trading hours

Unknown

Bases: OutsideRTH

Unknown

RTHOnly

Bases: OutsideRTH

Regular trading hour only

AnyTime

Bases: OutsideRTH

Any time

Overnight

Bases: OutsideRTH

Overnight

Order

Order

order_id instance-attribute

order_id: str

Order ID

status instance-attribute

status: Type[OrderStatus]

Order status

stock_name instance-attribute

stock_name: str

Stock name

quantity instance-attribute

quantity: Decimal

Submitted quantity

executed_quantity instance-attribute

executed_quantity: Decimal

Executed quantity

price instance-attribute

price: Optional[Decimal]

Submitted price

executed_price instance-attribute

executed_price: Optional[Decimal]

Executed price

submitted_at instance-attribute

submitted_at: datetime

Submitted time

side instance-attribute

side: Type[OrderSide]

Order side

symbol instance-attribute

symbol: str

Security code

order_type instance-attribute

order_type: Type[OrderType]

Order type

last_done instance-attribute

last_done: Optional[Decimal]

Last done

trigger_price instance-attribute

trigger_price: Optional[Decimal]

LIT / MIT Order Trigger Price

msg instance-attribute

msg: str

Rejected Message or remark

tag instance-attribute

tag: Type[OrderTag]

Order tag

time_in_force instance-attribute

time_in_force: Type[TimeInForceType]

Time in force type

expire_date instance-attribute

expire_date: Optional[date]

Long term order expire date

updated_at instance-attribute

updated_at: Optional[datetime]

Last updated time

trigger_at instance-attribute

trigger_at: Optional[datetime]

Conditional order trigger time

trailing_amount instance-attribute

trailing_amount: Optional[Decimal]

TSMAMT / TSLPAMT order trailing amount

trailing_percent instance-attribute

trailing_percent: Optional[Decimal]

TSMPCT / TSLPPCT order trailing percent

limit_offset instance-attribute

limit_offset: Optional[Decimal]

TSLPAMT / TSLPPCT order limit offset amount

trigger_status instance-attribute

trigger_status: Optional[Type[TriggerStatus]]

Conditional order trigger status

currency instance-attribute

currency: str

Currency

outside_rth instance-attribute

outside_rth: Optional[Type[OutsideRTH]]

Enable or disable outside regular trading hours

remark instance-attribute

remark: str

Remark

CommissionFreeStatus

Commission-free Status

Unknown

Bases: CommissionFreeStatus

Unknown

None_

Bases: CommissionFreeStatus

None

Calculated

Bases: CommissionFreeStatus

Commission-free amount to be calculated

Pending

Bases: CommissionFreeStatus

Pending commission-free

Ready

Bases: CommissionFreeStatus

Commission-free applied

DeductionStatus

Deduction status

Unknown

Bases: DeductionStatus

Unknown

None_

Bases: DeductionStatus

None

NoData

Bases: DeductionStatus

Settled with no data

Pending

Bases: DeductionStatus

Settled and pending distribution

Done

Bases: DeductionStatus

Settled and distributed

ChargeCategoryCode

Charge category code

Unknown

Bases: ChargeCategoryCode

Unknown

Broker

Bases: ChargeCategoryCode

Broker

Third

Bases: ChargeCategoryCode

Third

OrderHistoryDetail

Order history detail

price instance-attribute

price: Decimal

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

quantity instance-attribute

quantity: Decimal

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

status instance-attribute

status: Type[OrderStatus]

Order status

msg instance-attribute

msg: str

Execution or error message

time instance-attribute

time: datetime

Occurrence time

OrderChargeFee

Order charge fee

code instance-attribute

code: str

Charge code

name instance-attribute

name: str

Charge name

amount instance-attribute

amount: Decimal

Charge amount

currency instance-attribute

currency: str

Charge currency

OrderChargeItem

Order charge item

code instance-attribute

code: Type[ChargeCategoryCode]

Charge category code

name instance-attribute

name: str

Charge category name

fees instance-attribute

fees: List[OrderChargeFee]

Charge details

OrderChargeDetail

Order charge detail

total_amount instance-attribute

total_amount: Decimal

Total charges amount

currency instance-attribute

currency: str

Settlement currency

items instance-attribute

items: List[OrderChargeItem]

Order charge items

OrderDetail

Order detail

order_id instance-attribute

order_id: str

Order ID

status instance-attribute

status: Type[OrderStatus]

Order status

stock_name instance-attribute

stock_name: str

Stock name

quantity instance-attribute

quantity: Decimal

Submitted quantity

executed_quantity instance-attribute

executed_quantity: Decimal

Executed quantity

price instance-attribute

price: Optional[Decimal]

Submitted price

executed_price instance-attribute

executed_price: Optional[Decimal]

Executed price

submitted_at instance-attribute

submitted_at: datetime

Submitted time

side instance-attribute

side: Type[OrderSide]

Order side

symbol instance-attribute

symbol: str

Security code

order_type instance-attribute

order_type: Type[OrderType]

Order type

last_done instance-attribute

last_done: Optional[Decimal]

Last done

trigger_price instance-attribute

trigger_price: Optional[Decimal]

LIT / MIT Order Trigger Price

msg instance-attribute

msg: str

Rejected Message or remark

tag instance-attribute

tag: Type[OrderTag]

Order tag

time_in_force instance-attribute

time_in_force: Type[TimeInForceType]

Time in force type

expire_date instance-attribute

expire_date: Optional[date]

Long term order expire date

updated_at instance-attribute

updated_at: Optional[datetime]

Last updated time

trigger_at instance-attribute

trigger_at: Optional[datetime]

Conditional order trigger time

trailing_amount instance-attribute

trailing_amount: Optional[Decimal]

TSMAMT / TSLPAMT order trailing amount

trailing_percent instance-attribute

trailing_percent: Optional[Decimal]

TSMPCT / TSLPPCT order trailing percent

limit_offset instance-attribute

limit_offset: Optional[Decimal]

TSLPAMT / TSLPPCT order limit offset amount

trigger_status instance-attribute

trigger_status: Optional[Type[TriggerStatus]]

Conditional order trigger status

currency instance-attribute

currency: str

Currency

outside_rth instance-attribute

outside_rth: Optional[Type[OutsideRTH]]

Enable or disable outside regular trading hours

remark instance-attribute

remark: str

Remark

free_status instance-attribute

free_status: Type[CommissionFreeStatus]

Commission-free Status

free_amount instance-attribute

free_amount: Optional[Decimal]

Commission-free amount

free_currency instance-attribute

free_currency: Optional[str]

Commission-free currency

deductions_status instance-attribute

deductions_status: Type[DeductionStatus]

Deduction status

deductions_amount instance-attribute

deductions_amount: Optional[Decimal]

Deduction amount

deductions_currency instance-attribute

deductions_currency: Optional[str]

Deduction currency

platform_deducted_status instance-attribute

platform_deducted_status: Type[DeductionStatus]

Platform fee deduction status

platform_deducted_amount instance-attribute

platform_deducted_amount: Optional[Decimal]

Platform deduction amount

platform_deducted_currency instance-attribute

platform_deducted_currency: Optional[str]

Platform deduction currency

history instance-attribute

history: List[OrderHistoryDetail]

Order history details

charge_detail instance-attribute

charge_detail: OrderChargeDetail

Order charges

SubmitOrderResponse

Response for submit order request

order_id instance-attribute

order_id: str

Order id

CashInfo

CashInfo

withdraw_cash instance-attribute

withdraw_cash: Decimal

Withdraw cash

available_cash instance-attribute

available_cash: Decimal

Available cash

frozen_cash instance-attribute

frozen_cash: Decimal

Frozen cash

settling_cash instance-attribute

settling_cash: Decimal

Cash to be settled

currency instance-attribute

currency: str

Currency

AccountBalance

Account balance

total_cash instance-attribute

total_cash: Decimal

Total cash

max_finance_amount instance-attribute

max_finance_amount: Decimal

Maximum financing amount

remaining_finance_amount instance-attribute

remaining_finance_amount: Decimal

Remaining financing amount

risk_level instance-attribute

risk_level: int

Risk control level

margin_call instance-attribute

margin_call: Decimal

Margin call

currency instance-attribute

currency: str

Currency

cash_infos instance-attribute

cash_infos: List[CashInfo]

Cash details

net_assets instance-attribute

net_assets: Decimal

Net assets

init_margin instance-attribute

init_margin: Decimal

Initial margin

maintenance_margin instance-attribute

maintenance_margin: Decimal

Maintenance margin

buy_power instance-attribute

buy_power: Decimal

Buy power

BalanceType

Unknown

Bases: BalanceType

Cash

Bases: BalanceType

Stock

Bases: BalanceType

Fund

Bases: BalanceType

CashFlowDirection

Cash flow direction

Unknown

Bases: CashFlowDirection

Unknown

Out

Bases: CashFlowDirection

Out

In

Bases: CashFlowDirection

In

CashFlow

Cash flow

transaction_flow_name instance-attribute

transaction_flow_name: str

Cash flow name

direction instance-attribute

direction: Type[CashFlowDirection]

Outflow direction

business_type instance-attribute

business_type: Type[BalanceType]

Balance type

balance instance-attribute

balance: Decimal

Cash amount

currency instance-attribute

currency: str

Cash currency

business_time instance-attribute

business_time: datetime

Business time

symbol instance-attribute

symbol: Optional[str]

Associated Stock code information

description instance-attribute

description: str

Cash flow description

FundPosition

Fund position

symbol instance-attribute

symbol: str

Fund ISIN code

current_net_asset_value instance-attribute

current_net_asset_value: Decimal

Current equity

net_asset_value_day instance-attribute

net_asset_value_day: datetime

Current equity PyDecimal

symbol_name instance-attribute

symbol_name: str

Fund name

currency instance-attribute

currency: str

Currency

cost_net_asset_value instance-attribute

cost_net_asset_value: Decimal

Net cost

holding_units instance-attribute

holding_units: Decimal

Holding units

FundPositionChannel

Fund position channel

account_channel instance-attribute

account_channel: str

Account type

positions instance-attribute

positions: List[FundPosition]

Fund positions

FundPositionsResponse

Fund positions response

channels instance-attribute

channels: List[FundPositionChannel]

Channels

StockPosition

Stock position

symbol instance-attribute

symbol: str

Stock code

symbol_name instance-attribute

symbol_name: str

Stock name

quantity instance-attribute

quantity: Decimal

The number of holdings

available_quantity instance-attribute

available_quantity: Decimal

Available quantity

currency instance-attribute

currency: str

Currency

cost_price instance-attribute

cost_price: Decimal

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

market instance-attribute

market: Market

Market

init_quantity instance-attribute

init_quantity: Optional[Decimal]

Initial position before market opening

StockPositionChannel

Stock position channel

account_channel instance-attribute

account_channel: str

Account type

positions instance-attribute

positions: List[StockPosition]

Stock positions

StockPositionsResponse

Stock positions response

channels instance-attribute

channels: List[StockPositionChannel]

Channels

TopicType

Topic type

Private

Bases: TopicType

Private notification for trade

MarginRatio

Margin ratio

im_factor instance-attribute

im_factor: Decimal

Initial margin ratio

mm_factor instance-attribute

mm_factor: Decimal

Maintain the initial margin ratio

fm_factor instance-attribute

fm_factor: Decimal

Forced close-out margin ratio

EstimateMaxPurchaseQuantityResponse

Response for estimate maximum purchase quantity

cash_max_qty instance-attribute

cash_max_qty: Decimal

Cash available quantity

margin_max_qty instance-attribute

margin_max_qty: Decimal

Margin available quantity

TradeContext

Trade context

Parameters:
  • config (Config) –

    Configuration object

__init__

__init__(config: Config) -> None

set_on_order_changed

set_on_order_changed(callback: Callable[[PushOrderChanged], None]) -> None

Set order changed callback, after receiving the order changed event, it will call back to this function.

subscribe

subscribe(topics: List[Type[TopicType]]) -> None

Subscribe

Parameters:

Examples:

::

from time import sleep
from decimal import Decimal
from longport.openapi import TradeContext, Config, OrderSide, OrderType, TimeInForceType, PushOrderChanged, TopicType


def on_order_changed(event: PushOrderChanged):
    print(event)


config = Config.from_env()
ctx = TradeContext(config)
ctx.set_on_order_changed(on_order_changed)
ctx.subscribe([TopicType.Private])

resp = ctx.submit_order(
    side = OrderSide.Buy,
    symbol = "700.HK",
    order_type = OrderType.LO,
    submitted_price = Decimal(50),
    submitted_quantity = Decimal(200),
    time_in_force = TimeInForceType.Day,
    remark = "Hello from Python SDK",
)
print(resp)
sleep(5)  # waiting for push event

unsubscribe

unsubscribe(topics: List[Type[TopicType]]) -> None

Unsubscribe

Parameters:

history_executions

history_executions(symbol: Optional[str] = None, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> List[Execution]

Get history executions

Parameters:
Returns:

Examples:

::

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

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

resp = ctx.history_executions(
    symbol = "700.HK",
    start_at = datetime(2022, 5, 9),
    end_at = datetime(2022, 5, 12),
)
print(resp)

today_executions

today_executions(symbol: Optional[str] = None, order_id: Optional[str] = None) -> List[Execution]

Get today executions

Parameters:
  • symbol (Optional[str], default: None ) –

    Filter by security code

  • order_id (Optional[str], default: None ) –

    Filter by Order ID

Returns:

Examples:

::

from longport.openapi import TradeContext, Config

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

resp = ctx.today_executions(symbol = "700.HK")
print(resp)

history_orders

history_orders(symbol: Optional[str] = None, status: Optional[List[Type[OrderStatus]]] = None, side: Optional[Type[OrderSide]] = None, market: Optional[Type[Market]] = None, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> List[Order]

Get history orders

Parameters:
Returns:

Examples:

::

from datetime import datetime
from longport.openapi import TradeContext, Config, OrderStatus, OrderSide, Market

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

resp = ctx.history_orders(
    symbol = "700.HK",
    status = [OrderStatus.Filled, OrderStatus.New],
    side = OrderSide.Buy,
    market = Market.HK,
    start_at = datetime(2022, 5, 9),
    end_at = datetime(2022, 5, 12),
)
print(resp)

today_orders

today_orders(symbol: Optional[str] = None, status: Optional[List[Type[OrderStatus]]] = None, side: Optional[Type[OrderSide]] = None, market: Optional[Type[Market]] = None, order_id: Optional[str] = None) -> List[Order]

Get today orders

Parameters:
Returns:

Examples:

::

from longport.openapi import TradeContext, Config, OrderStatus, OrderSide, Market

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

resp = ctx.today_orders(
    symbol = "700.HK",
    status = [OrderStatus.Filled, OrderStatus.New],
    side = OrderSide.Buy,
    market = Market.HK,
)
print(resp)

replace_order

replace_order(order_id: str, quantity: Decimal, price: Optional[Decimal] = None, trigger_price: Optional[Decimal] = None, limit_offset: Optional[Decimal] = None, trailing_amount: Optional[Decimal] = None, trailing_percent: Optional[Decimal] = None, remark: Optional[str] = None) -> None

Replace order

Parameters:
  • quantity (Decimal) –

    Replaced quantity

  • price (Optional[Decimal], default: None ) –

    Replaced price

  • trigger_price (Optional[Decimal], default: None ) –

    Trigger price (LIT / MIT Order Required)

  • limit_offset (Optional[Decimal], default: None ) –

    Limit offset amount (TSLPAMT / TSLPPCT Required)

  • trailing_amount (Optional[Decimal], default: None ) –

    Trailing amount (TSLPAMT / TSMAMT Required)

  • trailing_percent (Optional[Decimal], default: None ) –

    Trailing percent (TSLPPCT / TSMAPCT Required)

  • remark (Optional[str], default: None ) –

    Remark (Maximum 64 characters)

Examples:

::

from decimal import Decimal
from longport.openapi import TradeContext, Config

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

ctx.replace_order(
    order_id = "709043056541253632",
    quantity = Decimal(100),
    price = Decimal(100),
)

submit_order

submit_order(symbol: str, order_type: Type[OrderType], side: Type[OrderSide], submitted_quantity: Decimal, time_in_force: Type[TimeInForceType], submitted_price: Optional[Decimal] = None, trigger_price: Optional[Decimal] = None, limit_offset: Optional[Decimal] = None, trailing_amount: Optional[Decimal] = None, trailing_percent: Optional[Decimal] = None, expire_date: Optional[date] = None, outside_rth: Optional[Type[OutsideRTH]] = None, remark: Optional[str] = None) -> SubmitOrderResponse

Submit order

Parameters:
  • symbol (str) –

    Security code

  • order_type (Type[OrderType]) –

    Order type

  • side (Type[OrderSide]) –

    Order Side

  • submitted_quantity (Decimal) –

    Submitted quantity

  • time_in_force (Type[TimeInForceType]) –

    Time in force type

  • submitted_price (Optional[Decimal], default: None ) –

    Submitted price

  • trigger_price (Optional[Decimal], default: None ) –

    Trigger price (LIT / MIT Required)

  • limit_offset (Optional[Decimal], default: None ) –

    Limit offset amount (TSLPAMT / TSLPPCT Required)

  • trailing_amount (Optional[Decimal], default: None ) –

    Trailing amount (TSLPAMT / TSMAMT Required)

  • trailing_percent (Optional[Decimal], default: None ) –

    Trailing percent (TSLPPCT / TSMAPCT Required)

  • expire_date (Optional[date], default: None ) –

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

  • outside_rth (Optional[Type[OutsideRTH]], default: None ) –

    Enable or disable outside regular trading hours

  • remark (Optional[str], default: None ) –

    Remark (Maximum 64 characters)

Returns:

Examples:

::

from decimal import Decimal
from longport.openapi import TradeContext, Config, OrderSide, OrderType, TimeInForceType

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

resp = ctx.submit_order(
    side = OrderSide.Buy,
    symbol = "700.HK",
    order_type = OrderType.LO,
    submitted_price = Decimal(50),
    submitted_quantity = Decimal(200),
    time_in_force = TimeInForceType.Day,
    remark = "Hello from Python SDK",
)
print(resp)

cancel_order

cancel_order(order_id: str) -> None

Cancel order

Parameters:
  • order_id (str) –

    Order ID

Examples:

::

from longport.openapi import TradeContext, Config

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

ctx.cancel_order("709043056541253632")

account_balance

account_balance(currency: Optional[str] = None) -> List[AccountBalance]

Get account balance

Parameters:
  • currency (Optional[str], default: None ) –

    Currency

Returns:

Examples:

::

from longport.openapi import TradeContext, Config

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

resp = ctx.account_balance()
print(resp)

cash_flow

cash_flow(start_at: datetime, end_at: datetime, business_type: Optional[Type[BalanceType]] = None, symbol: Optional[str] = None, page: Optional[int] = None, size: Optional[int] = None) -> List[CashFlow]

Get cash flow

Parameters:
Returns:

Examples:

::

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

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

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

fund_positions

fund_positions(symbols: Optional[List[str]] = None) -> FundPositionsResponse

Get fund positions

Parameters:
Returns:

Examples:

::

from longport.openapi import TradeContext, Config

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

resp = ctx.fund_positions()
print(resp)

stock_positions

stock_positions(symbols: Optional[List[str]] = None) -> StockPositionsResponse

Get stock positions

Parameters:
Returns:

Examples:

::

from longport.openapi import TradeContext, Config

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

resp = ctx.stock_positions()
print(resp)

margin_ratio

margin_ratio(symbol: str) -> MarginRatio

Get margin ratio

Parameters:
  • symbol (str) –

    Security symbol

Returns:

Examples:

::

from longport.openapi import TradeContext, Config

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

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

order_detail

order_detail(order_id: str) -> OrderDetail

Get order detail

Parameters:
  • order_id (str) –

    Order id

Returns:

Examples:

::

from longport.openapi import TradeContext, Config

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

resp = ctx.order_detail("701276261045858304")
print(resp)

estimate_max_purchase_quantity

estimate_max_purchase_quantity(symbol: str, order_type: Type[OrderType], side: Type[OrderSide], price: Optional[Decimal] = None, currency: Optional[str] = None, order_id: Optional[str] = None, fractional_shares: bool = False) -> EstimateMaxPurchaseQuantityResponse

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

Parameters:
  • symbol (str) –

    Security symbol

  • order_type (Type[OrderType]) –

    Order type

  • side (Type[OrderSide]) –

    Order side

  • price (Optional[Decimal], default: None ) –

    Estimated order price,

  • currency (Optional[str], default: None ) –

    Settlement currency

  • order_id (Optional[str], default: None ) –

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

  • fractional_shares (bool, default: False ) –

    Get the maximum fractional share buying power

Returns:

Examples:

::

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

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

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