中文

Objects

PortfolioAccount Assets (Comprehensive/Simulation Account)

Description

Account asset object, applicable to comprehensive/simulation accounts. Contains information about the account's total assets, profit and loss, position market value, cash, available funds, margin, leverage, and other related information.

Object Properties

Property NameTypeDescription
accountstrCorresponding account ID
update_timestampintUpdate time, 13-digit timestamp in milliseconds
segmentstigeropen.trade.domain.prime_account.SegmentAccount information classified by trading instrument. The content is a dict with two keys: 'S' for securities, 'C' for futures, with values being

Segment Assets by Category (Comprehensive/Simulation Account)

Description

Assets are divided by stock/futures trading instruments, with each part being a Segment.

Object Properties

Property NameTypeDescription
currencystrCurrency, such as USD, HKD
capabilitystrAccount type, margin account: RegTMargin, cash account: Cash. Margin accounts support margin trading, unlimited T+0 trading times, maximum buying power of up to 4x intraday and 2x overnight.
categorystrTrading instrument category C: (Commodities futures), S: (Securities stocks), F: (Funds)
cash_balancefloatCash amount. The cash amount is the sum of current cash balances in all currencies. If your current account has generated financing or borrowing, please note that interest is generally calculated daily and settled monthly, specifically calculated based on financing days. Accumulated daily, unified deduction around the 5th of the following month, so before deducting interest, the cash balance users see has not deducted interest. If the cash balance is zero before deducting interest, there may be a debt after deduction, i.e., the cash balance becomes negative.
cash_available_for_tradefloatAvailable funds. Available funds are used to check whether opening positions or IPO subscriptions are possible. Opening positions refers to trading behaviors such as buying stocks long, selling stocks short through margin lending, etc. Note that available funds do not equal available cash. It is a value calculated using total assets, option position market value, frozen funds, and initial margin. When available funds are greater than 0, it means the account can open positions. Available funds × 4 is the account's maximum available buying power. Algorithm: Available funds = Total assets - US stock option market value - Current total position initial margin - Frozen funds. The initial margin algorithm is ∑(Individual stock position market value × Current stock opening margin ratio). Example: Tiger's current account total assets are $10,000, holding $1,000 US stock options, holding Apple with total market value of $2,000, Apple's initial margin ratio is currently 45%, no frozen funds, Tiger's available funds = 10,000 - 1,000 - 2,000 × 45% = $8,100
cash_available_for_withdrawalfloatCash amount that can be withdrawn from the current account
buying_powerfloatMaximum buying power. Maximum buying power is the account's maximum available purchase amount. The maximum buying power value can be used to estimate how much stock the account can buy at most, but since each stock has different maximum leverage multiples, the actual buying power available when purchasing individual stocks must be calculated based on the specific stock's margin ratio. Algorithm: Maximum buying power = 4 × Available funds. Example: Tiger's available funds are $100,000, then Tiger's maximum buying power is $400,000. If Apple's current stock price is $250 per share and Apple's initial margin ratio is 30%, Tiger can buy at most $100,000/30% = $333,400 of Apple. If Apple's initial margin ratio is 25%, Tiger can buy at most $100,000/25% = $400,000 of Apple. Margin accounts have at most four times the buying power of funds (funds not used as margin) intraday and at most two times buying power overnight
gross_position_valuefloatTotal securities value, which is the sum of the total market value of securities held in the account, i.e., the total market value of all positions. Algorithm: Sum of all position market values; Note: All position market values are calculated in the main currency; Example 1: If Tiger simultaneously holds Apple worth $3,000 (i.e., long) and Google worth -$1,000 (i.e., short), Tiger's total securities value = $3,000 Apple + (-$1,000 Google) = $2,000; Example 2: Tiger holds Apple worth $10,000 and Apple long options worth $5,000, Tiger's total securities value = 10,000 + 5,000 = $15,000
equity_with_loanfloatTotal equity with loan value, i.e., ELV. ELV is a data indicator used to calculate opening and closing positions; Algorithm: Cash account = Cash balance, Margin account = Cash balance + Total securities market value - US stock option market value; ELV = Total assets - US stock options
net_liquidationfloatTotal assets (net liquidation value). Total assets is the sum of our account's net liquidation cash balance and total securities market value, usually used to indicate how many assets are currently in the account. Algorithm: Total assets = Total securities market value + Cash balance + Accrued dividends - Accrued interest; Example: Tiger's account has $1,000 cash, holds Apple positions worth $1,000 (i.e., long Apple), no pending dividends and financing interest and undeducted interest, then Tiger's total assets = Cash 1,000 + Position value 1,000 = $2,000. If Tiger's account has $1,000 cash and shorts Apple worth $1,000, at this time the total securities market value is -$1,000, cash is $2,000, user's total assets = Cash 2,000 + (Position market value -1,000), total account assets amount to $1,000.
init_marginfloatInitial margin. The sum of initial margin requirements for all current position contracts. When first executing trades, opening positions is only allowed when equity with loan is greater than initial margin. To meet regulatory margin requirements, we will increase initial margin and maintenance margin requirements to a minimum of 50% during the 15 minutes before market close.
maintain_marginfloatMaintenance margin. The sum of maintenance margin requirements for all current position contracts. When holding positions, forced liquidation will be triggered when equity with loan is less than maintenance margin. To meet regulatory margin requirements, we will increase initial margin and maintenance margin requirements to a minimum of 50% during the 15 minutes before market close.
overnight_marginfloatOvernight margin. Overnight margin is the margin required when checking accounts starting 15 minutes before market close. To meet regulatory margin requirements, we will increase initial margin and maintenance margin requirements to a minimum of 50% during the 15 minutes before market close. Tiger International's overnight margin ratios are all above 50%. If the account's equity with loan is below overnight margin, the account risks forced liquidation during the 15 minutes before market close. Algorithm: ∑(Individual stock overnight maintenance margin). Individual stock maintenance margin rates can be queried by users at "Stock Details Page - Quote Area - Click Margin Trading Symbol". Example: Tiger's account total assets are $100,000, Apple's opening margin ratio is 40%, intraday maintenance margin is 20%, intraday full position buying Apple totaling $250,000, during the 15 minutes before market close (overnight period) maintenance margin ratio will be raised to 50%, at this time the user's overnight margin is: $250,000 × 50% = $125,000, the user's equity with loan is $100,000, which is less than $125,000, the user will be liquidated for some stocks.
unrealized_plfloatPosition profit and loss. Definition: Unrealized profit and loss amount of held individual stocks and derivatives; Algorithm: Current price × Number of shares - Position cost
realized_plfloatRealized profit and loss is the sum of realized profit and loss of individual stocks and derivatives that have been reduced during the current holding cycle. Realized profit and loss = Σ[(Selling price - Buying price) × Number of shares sold - Commission
excess_liquidationfloatCurrent excess liquidity. Current excess liquidity is an indicator measuring the current account's potential liquidation risk. The lower the current excess liquidity, the higher the account's liquidation risk. When it is less than 0, some positions will be forcibly liquidated. The specific algorithm is: Current excess liquidity = Equity with loan - Account maintenance margin. To meet regulatory margin requirements, we will increase initial margin and maintenance margin requirements to a minimum of 50% during the 15 minutes before market close. Example: (1) Customer total assets $10,000, bought Apple $12,000 (assuming Apple's opening and maintenance margin ratio is 50%). Current excess liquidity = Total assets 10,000 - Account maintenance margin 6,000 = 4,000. (2) As the stock falls, assume the stock market value drops to 8,000, at this time current excess liquidity = Total assets (-2,000 + 8,000) - Account maintenance margin 4,000 = 2,000. (3) At this time the user bought another $1,000 US stock options, then the account's current excess liquidity remains 2,000 - 1,000 = 1,000. If your account is forcibly liquidated, it will be executed at market price during forced liquidation, and the liquidated stock targets are decided by the broker. Please pay attention to risk control values and leverage indicators.
overnight_liquidationfloatOvernight excess liquidity. Overnight excess liquidity refers to the value calculated by Equity with loan - Overnight margin. To meet regulatory margin requirements, we will increase initial margin and maintenance margin requirements to a minimum of 50% during the 15 minutes before market close. If the account's overnight excess liquidity is below 0, there is a risk of forced liquidation of some positions starting 15 minutes before market close. If your account is forcibly liquidated, it will be executed at market price during forced liquidation, and the liquidated stock targets are decided by the broker. Please pay attention to risk control values and leverage indicators.
leveragefloatLeverage. Leverage is an important indicator measuring account risk level, which can help users quickly understand account financing ratio and risk level; Algorithm: Leverage = Sum of absolute values of securities market values / Total assets; Note 1: Margin accounts have maximum leverage of 4x intraday and 2x overnight; Note 2: Tiger considers historical volatility, liquidity and risk factors, and not every stock can be bought with 4x leverage. Generally, long margin ratios range from 25%-100%. Stocks with margin ratio equal to 25% can be understood as 4x leverage buying, stocks with margin ratio equal to 100% can be understood as 0x leverage buying, i.e., buying entirely with cash. Note that short selling margin may exceed 100%. Note 3: Individual stock margin ratios can be queried by users at "Stock Details Page - Quote Area - Click Margin Trading Symbol"; Example: Tiger's account total assets $100,000, wants to buy Apple, Apple's current individual stock long initial margin ratio is 50% (1/50% = 2x leverage), Tiger can buy at most $200,000 market value of Apple stock; Tiger wants to short Google, Google's short selling margin ratio is 200%, Tiger can short at most 10/200% = $50,000 of Google stock; Tiger wants to buy Microsoft, Microsoft's initial margin is 100% (1/100% = 1x leverage), Tiger can buy at most $100,000 of Microsoft stock
currency_assetsdictAccount asset information classified by trading currency, is a dict with currency as key, value is CurrencyAsset object
uncollectedfloatFunds in transit
locked_fundsfloatLocked funds

CurrencyAsset Assets by Currency (Comprehensive/Simulation Account)

Description

Assets classified by currency.

Object Properties

Property NameTypeDescription
currencystrCurrent currency type, common currencies include: USD-US Dollar, HKD-Hong Kong Dollar, SGD-Singapore Dollar, CNH-Chinese Yuan
cash_balancefloatCash available for trading, plus locked cash portion (such as purchased but not yet executed stocks, and other situations that may have locked cash)
cash_available_for_tradefloatCash amount currently available for trading in the account

PortfolioAccount Assets (Global Account)

Description

Account asset object, applicable to global accounts. Contains information about the account's total assets, profit and loss, position market value, cash, available funds, margin, leverage, and other related information.

Object Properties

Property NameTypeDescription
accountstrCorresponding account ID
summarytigeropen.trade.domain.account.AccountAccount summary information, statistics of segments
segmentsdictAccount information classified by trading instrument. Has two keys: 'S' corresponds to securities, value is a

Account Summary Assets (Global Account)

Description

Account summary information for various trading instrument assets.

Object Properties

Property NameTypeDescription
accrued_cashfloatCurrent month's accumulated accrued interest payable, updated daily
accrued_dividendfloatAccrued dividends. Refers to the cumulative value of all executed but still unpaid dividends
available_fundsfloatAvailable funds (available for trading). Calculation method: equity_with_loan - initial_margin_requirement
∆ buying_powerfloatBuying power: Estimated how much more USD stock assets you can purchase. Margin accounts have at most four times the buying power of funds (funds not used as margin) intraday. At most two times buying power overnight
cashfloatCash amount
currencystrCurrency, meaning refers to enumeration parameters - Currency
cushionfloatRatio of excess liquidity to total assets, calculation method: excess_liquidity/net_liquidation
∆ day_trades_remainingintRemaining day trades for the day, -1 means unlimited
equity_with_loanfloatEquity with loan value (equity with loan value assets). Securities Segment: Cash value + Stock value. Futures Segment: Cash value - Maintenance margin
excess_liquidityfloatExcess liquidity - Securities Segment: Calculation method: equity_with_loan - maintenance_margin_requirement - Futures Segment: Calculation method: net_liquidation - maintenance_margin_requirement
∆ gross_position_valuefloatTotal securities value: Long stock value + Short stock value + Long option value + Short option value
initial_margin_requirementfloatInitial margin
maintenance_margin_requirementfloatMaintenance margin
realized_pnlfloatToday's realized profit and loss
unrealized_pnlfloatFloating profit and loss
net_liquidationfloatTotal assets (net liquidation value). Securities Segment: Cash value + Stock value + Stock option value. Futures Segment: Cash value + Mark-to-market profit and loss
∆ regt_equityfloatOnly for Securities Segment, i.e., equity with loan calculated according to Regulation T
∆ regt_marginfloatOnly for Securities Segment, i.e., initial margin requirements calculated according to Regulation T
∆ smafloatOnly for Securities Segment. Overnight risk control value, checks account overnight risk about 10 minutes before market close each trading day. Overnight risk control value needs to be greater than 0, otherwise some positions will be forcibly liquidated before market close. If overnight risk control value is below 0 during intraday trading but time hasn't reached 10 minutes before market close, the account will not trigger forced liquidation.
timestampintUpdate time

SecuritySegment Stock Assets (Global Account)

Description

Stock asset information.

Object Properties

Property NameTypeDescription
accrued_cashfloatCurrent month's accumulated accrued interest payable, updated daily
accrued_dividendfloatAccrued dividends. Refers to the cumulative value of all executed but still unpaid dividends
available_fundsfloatAvailable funds (available for trading). Calculation method: equity_with_loan - initial_margin_requirement
cashfloatCash
equity_with_loanfloatEquity with loan value (equity with loan value assets). Calculation method: Cash value + Stock value
excess_liquidityfloatExcess liquidity. Calculation method: equity_with_loan - maintenance_margin_requirement
gross_position_valuefloatTotal securities value: Long stock value + Short stock value + Long option value + Short option value
initial_margin_requirementfloatInitial margin
maintenance_margin_requirementfloatMaintenance margin
leveragefloatOnly for Securities Segment gross_position_value / net_liquidation
net_liquidationfloatTotal assets (net liquidation value). Calculation method: Cash value + Stock value + Stock option value
∆ regt_equityfloatOnly for Securities Segment, i.e., equity with loan calculated according to Regulation T
∆ regt_marginfloatOnly for Securities Segment, i.e., initial margin requirements calculated according to Regulation T
∆ smafloatOnly for Securities Segment. Overnight risk control value, checks account overnight risk about 10 minutes before market close each trading day. Overnight risk control value needs to be greater than 0, otherwise some positions will be forcibly liquidated before market close. If overnight risk control value is below 0 during intraday trading but time hasn't reached 10 minutes before market close, the account will not trigger forced liquidation.
timestampintUpdate time

CommoditySegment Futures Assets (Global Account)

Description

Futures asset information.

Object Properties

Property NameTypeDescription
accrued_cashfloatCurrent month's accumulated accrued interest payable, updated daily
accrued_dividendfloatAccrued dividends. Refers to the cumulative value of all executed but still unpaid dividends
available_fundsfloatAvailable funds (available for trading). Calculation method: equity_with_loan - initial_margin_requirement
cashfloatCash
equity_with_loanfloatEquity with loan value (equity with loan value assets) Calculation method: Cash value - Maintenance margin
excess_liquidityfloatExcess liquidity. Calculation method: net_liquidation - maintenance_margin_requirement
initial_margin_requirementfloatInitial margin
maintenance_margin_requirementfloatMaintenance margin
net_liquidationfloatTotal assets (net liquidation value). Calculation method: Cash value + Mark-to-market profit and loss
timestampintUpdate time

MarketValue Assets by Currency (Global Account)

Description

Asset information classified by currency.

Object Properties

Property NameTypeDescription
currencystrCurrency unit
net_liquidationfloatTotal assets (net liquidation value)
cash_balancefloatCash
stock_market_valuefloatStock market value
option_market_valuefloatOption market value
warrant_valuefloatWarrant market value
futures_pnlfloatMark-to-market profit and loss
unrealized_pnlfloatUnrealized profit and loss
realized_pnlfloatRealized profit and loss
exchange_ratefloatExchange rate to account base currency
net_dividendfloatNet value of dividends payable and receivable
timestampintUpdate time

Position

Description

Account position information. Includes contract, position quantity, cost, profit and loss, and other information.

Object Properties

Property NameTypeDescription
accountstrCorresponding account ID
contracttigeropen.trade.domain.contract.ContractContract object
position_qtyfloatPosition quantity
quantityintPosition quantity (deprecated). When actual position has decimals, need to combine with position_scale
position_scaleintPosition quantity decimal offset (deprecated). If position=11123, positionScale=2, then actual position=11123*10^(-2)=111.23
average_costfloatAverage cost including commission
market_valuefloatMarket value
salable_qtyfloatSellable quantity
average_cost_of_carryfloatCumulative position cost (A-share calculation method)
market_pricefloatMarket price
is_level0_pricebooleanWhether it is lv0 (delayed) quotes
realized_pnlfloatRealized P&L under FIFO mode
unrealized_pnlfloatUnrealized P&L
unrealized_pnl_by_cost_of_carryfloatUnrealized P&L (A-share calculation method)
unrealized_pnl_percent_by_cost_of_carryfloatUnrealized P&L percentage (A-share calculation method)
today_pnlfloatToday's P&L amount
today_pnl_percentfloatToday's P&L percentage
yesterday_pnlfloatFund yesterday's P&L
last_close_pricefloatLast intraday close price (forward adjusted), for US stocks intraday it's previous trading day's close price

Order

Description

Order object. Order queries will return this object, and placing/modifying orders also requires using this object.

Object Properties

Property NameTypeDescription
accountstrAccount to which the order belongs
idlongGlobal order ID
order_idintAccount auto-increment order number, deprecated
parent_idlongParent order ID, currently only used for attached orders in TigerTrade App
order_timeintOrder time, 13-digit timestamp in milliseconds
trade_timeintOrder status update time. For filled orders, represents fill time; for cancelled orders, represents successful cancellation time, 13-digit timestamp in milliseconds
update_timeintOrder update time. When order properties change (such as order modification), this time will be updated, 13-digit timestamp in milliseconds
expire_timeintGTD order expiration time, 13-digit timestamp in milliseconds
reasonstrWhen order placement fails, returns description of failure reason
actionstrTrade direction, 'BUY' / 'SELL'
quantityintOrder quantity
quantity_scaleintOrder quantity offset, default is 0. For fractional shares, quantity and quantity_scale combined represent actual order quantity, e.g., quantity=111 quantity_scale=2, then actual quantity=111*10^(-2)=1.11
total_cash_amountfloatTotal order amount, None when ordering by shares
filled_cash_amountfloatFilled amount, None when ordering by shares
refund_cash_amountfloatRefund amount, equals total order amount minus filled amount. None when ordering by shares or order is not terminated
filledintFilled quantity
avg_fill_pricefloatAverage fill price excluding commission
commissionfloatIncludes commission, stamp duty, regulatory fees and other charges
gstfloatTax - Goods and Service Tax
realized_pnlfloatRealized P&L
trail_stop_pricefloatTrailing stop price
limit_pricefloatLimit order price
aux_pricefloatIn stop orders, represents the trigger price for stop order. In trailing stop orders, represents the trailing spread
trailing_percentfloatTrailing stop order - percentage, range 0-100
percent_offsetfloat<This field is not used>
order_typestrOrder type, 'MKT' market order / 'LMT' limit order / 'STP' stop order / 'STP_LMT' stop limit order / 'TRAIL' trailing stop order
time_in_forcestrTime in force, 'DAY' day order / 'GTC' good till cancelled / 'GTD' good till date (requires additional expire_time)
outside_rthboolWhether to support pre-market and after-hours trading, US stocks only
trading_session_typestrNight trading session
contractContract

tigeropen.trade.domain.order.Charge Object Properties

PropertyTypeDescription
categorystrFee category (TIGER/THIRD_PARTY)
category_descstrFee category description: Tiger Charge; Third Parties
totalfloatTotal fees for current category
detailstigeropen.trade.domain.order.ChargeDetailFee details

tigeropen.trade.domain.order.ChargeDetail Object Properties

PropertyTypeDescription
typestrFee type: SETTLEMENT_FEE/STAMP_DUTY/TRANSACTION_LEVY/EXCHANGE_FEE/FRC_TRANSACTION_LEVY
type_descstrFee type description: Settlement Fee; Stamp Duty; Transaction Levy; Exchange Fee; AFRC Transaction Levy
original_amountfloatFee amount
after_discount_amountfloatFee amount after discount

Construction Method:

Generate order objects locally through tigeropen.common.util.order_utils in the SDK: order_utils only provides commonly used parameters. If additional parameters are needed, you can generate the order object first and then modify its properties.

from tigeropen.common.util.contract_utils import stock_contract
from tigeropen.common.util.order_utils import (market_order,        # Market order
                                            limit_order,         # Limit order
                                            stop_order,          # Stop order
                                            stop_limit_order,    # Stop limit order
                                            trail_order,         # Trailing stop order
                                            order_leg)           # Attached order
                        
contract = stock_contract('AAPL', currency='USD')
order = limit_order('your account', contract, 'BUY', 100, 150.5)
order.time_in_force = 'GTC' # Set order properties
     
# Subsequent operations...                                    

market_order Market Order

market_order(account, contract, action, quantity)

Parameters

ParameterTypeDescription
accountstrTrading account, can use integrated account, global account or paper account
contracttigeropen.trade.domain.contract.ContractContract to trade

Returns

Order object


limit_order Limit Order

limit_order(account, contract, action, quantity, limit_price)

Parameters

ParameterTypeDescription
accountstrTrading account, can use integrated account, global account or paper account
contracttigeropen.trade.domain.contract.ContractContract to trade

Returns

Order object


stop_order Stop Order

stop_order(account, contract, action, quantity, aux_price)

Parameters

ParameterTypeDescription
accountstrTrading account, can use integrated account, global account or paper account
contracttigeropen.trade.domain.contract.ContractContract to trade

Returns

Order object


stop_limit_order Stop Limit Order

stop_limit_order(account, contract, action, quantity, limit_price, aux_price)

Parameters

ParameterTypeDescription
accountstrTrading account, can use integrated account, global account or paper account
contracttigeropen.trade.domain.contract.ContractContract to trade

Returns

Order object


trail_order Trailing Stop Order

trail_order(account, contract, action, quantity, trailing_percent=None, aux_price=None)

Parameters

ParameterTypeDescription
accountstrTrading account, can use integrated account, global account or paper account
contracttigeropen.trade.domain.contract.ContractContract to trade

Returns

Order object


order_leg Additional Order

order_leg(leg_type, price, time_in_force='DAY', outside_rth=None)

Parameters

Parameter NameTypeDescription
leg_typestrAdditional order type. 'PROFIT' for take profit order, 'LOSS' for stop loss order
pricefloatAdditional order price
time_in_forcestrAdditional order time in force. 'DAY' (Day) and 'GTC' (Good-Til-Canceled)
outside_rthboolWhether additional order allows pre-market and after-hours trading (US stocks only). True allows, False disallows

Returns

OrderLeg object tigeropen.trade.domain.order.OrderLeg


auction_limit_order Auction Limit Order

auction_limit_order(account, contract, action, quantity, limit_price, time_in_force)

Parameters

Parameter NameTypeDescription
accountstrTrading account, can use integrated account or simulation account
contracttigeropen.trade.domain.contract.ContractContract to trade

Returns

Order object


auction_market_order Auction Market Order

auction_market_order(account, contract, action, quantity, time_in_force)

Parameters

Parameter NameTypeDescription
accountstrTrading account, can use integrated account or simulation account
contracttigeropen.trade.domain.contract.ContractContract to trade

Returns

Order object


Transaction Trade Record

tigeropen.trade.domain.order.Transaction

Description

Trade execution record of an order

Object Properties

PropertyTypeDescription
accountstrAccount
order_idintOrder ID
contractContract

OrderLeg Additional Order

tigeropen.trade.domain.order.OrderLeg

Description

Additional orders carried with the main order

Object Properties

PropertyTypeDescription
leg_typestrAdditional order type. 'PROFIT' for take profit order, 'LOSS' for stop loss order
pricefloatAdditional order price
time_in_forcestrAdditional order time in force. 'DAY' (Day) and 'GTC' (Good-Til-Canceled)
outside_rthboolWhether additional order allows pre-market and after-hours trading (US stocks only). True allows, False disallows

AlgoParams Algorithm Order Parameters

tigeropen.trade.domain.order.AlgoParams

Description

Algorithm order (VWAP/TWAP) parameter object

Object Properties

PropertyTypeDescription
start_timestr/intEffective start time (time string or timestamp, TWAP and VWAP only), e.g. '2020-11-19 23:00:00' or 1640159945678
end_timestr/intExpiry time (time string or timestamp, TWAP and VWAP only)
no_take_liqboolWhether to minimize trading frequency (VWAP orders only)
allow_past_end_timeboolWhether to allow completion of trades after expiry time (TWAP and VWAP only)
participation_ratefloatParticipation rate (VWAP only, 0.01-0.5)

Contract

tigeropen.trade.domain.contract.Contract source

Description

A contract refers to the trading object or underlying asset (such as a stock or an option), which is standardized by the exchange. For example, to purchase Tiger Brokers stock, it can be uniquely identified by the ticker symbol TIGR and market information (i.e., market='US', US market). Similarly, when purchasing options or futures products, other identifying fields may be needed. Through contract information, we can uniquely determine an underlying asset when placing orders or obtaining quotes. In the Open API Python SDK, contract information is stored through the tigeropen.trade.domain.contract.Contract object. The Contract object can be passed to utility functions for constructing Order objects, used for placing orders.

Common contracts include stock contracts, option contracts, futures contracts, etc. Most contracts include the following elements:

  • Symbol - Generally, US and UK contract codes are alphabetic, while Hong Kong and A-share contract codes are numeric, e.g., Tiger Brokers' symbol is TIGR.
  • Security Type - Common contract types include: STK (stock), OPT (option), FUT (futures), CASH (forex), e.g., Tiger Brokers stock contract type is STK.
  • Currency - Common currencies include USD (US Dollar), HKD (Hong Kong Dollar).
  • Exchange - STK type contracts generally don't use the exchange field as orders are automatically routed, futures contracts use the exchange field.

Most stocks, CFDs, indices, or forex pairs can be uniquely determined by these four attributes. Due to their nature, more complex contracts (such as options and futures) require some additional information. Here are several common contract types and their constituent elements:

Stocks:

from tigeropen.common.util.contract_utils import stock_contract
contract = stock_contract(symbol='TIGR', currency='USD')
contract1 = stock_contract(symbol='00700', currency='HKD')

Options

from tigeropen.common.util.contract_utils import option_contract, option_contract_by_symbol
contract = option_contract(identifier='AAPL  190118P00160000')
contract = option_contract_by_symbol('JD', expiry='20211015', strike=45.0, put_call='PUT', currency='USD')

Futures

from tigeropen.common.util.contract_utils import future_contract
contract = future_contract(symbol='CL', currency='USD', expiry='20190328', multiplier=1.0, exchange='SGX')

Hong Kong Warrants

from tigeropen.common.util.contract_utils import war_contract_by_symbol
contract = war_contract_by_symbol('01810', '20221116', 14.52, 'CALL', local_symbol='14759', multiplier=2000,
currency='HKD')

Hong Kong CBBC

from tigeropen.common.util.contract_utils import iopt_contract_by_symbol
contract = iopt_contract_by_symbol('02318', '20200420', 87.4, 'CALL', local_symbol='63379', currency='HKD')

See below for specific fields and construction methods

Object Properties

Property NameTypeDescription
identifierstrUnique identifier, stock identifier is same as symbol, option is 21-character identifier, e.g., 'AAPL 220729C00150000', futures identifier
symbolstrStock ticker, option contract symbol is the underlying asset code
sec_typestrSTK stock/OPT option/FUT futures/WAR warrant/IOPT CBBC etc., default STK
namestrContract name
currencystrCurrency, USD/HKD/CNH
exchangestrExchange
expirystrOptions and futures only, option or futures expiry date
strikefloatOptions only, option strike price
multiplierfloatQuantity per lot
put_callstrOptions only, option direction, CALL or PUT
local_symbolstrGlobal account only, Hong Kong stocks used to identify warrants and CBBC
short_marginfloatShort margin ratio (deprecated, please use short_initial_margin instead)
short_initial_marginfloatShort initial margin ratio
short_maintenance_marginfloatShort maintenance margin ratio (has value for integrated accounts, no value for global account contracts)
short_fee_ratefloatShort fee rate
shortableintShort pool remaining
long_initial_marginfloatLong initial margin
long_maintenance_marginfloatLong maintenance margin
contract_monthstrContract month, e.g., 202201, represents January 2022
primary_exchangestrStock listing exchange
marketstrMarket /US/HK/CN
min_tickfloatMinimum tick size
tickSizeslistStocks only, minimum tick size price ranges, i.e., when order price is in the begin and end range, must meet tickSize requirements, begin: left price range, end: right price range, type: range type OPEN/OPEN_CLOSED/CLOSED/CLOSED_OPEN (open/left open right closed/closed/left closed right open), tickSize: minimum price unit. Example: [{"begin":"0","end":"1","tickSize":1.0E-4,"type":"CLOSED"},{"begin":"1","end":"Infinity","tickSize":0.01,"type":"OPEN"}]
trading_classstrContract trading class name
statusstrContract status
continuousboolFutures only, whether it's a continuous contract
tradeboolFutures only, whether it's tradable
last_trading_datestrFutures only, last trading date, e.g., '20211220', represents December 20, 2021
first_notice_datestrFutures only, first notice date, contracts cannot open long positions after first notice date. Existing long positions will be forcibly closed before the first notice date (usually three trading days prior), e.g., '20211222', represents December 22, 2021
last_bidding_close_timeintFutures only, bidding close timestamp
is_etfboolWhether it's an ETF
etf_leverageintETF leverage multiple, exists only when contract is ETF
discounted_day_initial_marginfloatFutures only, Intraday initial margin discount
discounted_day_maintenance_marginfloatFutures only, Intraday maintenance margin discount
discounted_time_zone_codefloatFutures only, Intraday margin discount period time zone
discounted_start_atfloatFutures only, Intraday margin discount start time
discounted_end_atfloatFutures only, Intraday margin discount end time
lot_sizefloatMinimum quantity of assets that can be traded in a single transaction
support_overnight_tradingboolWhether supports overnight trading
⚠️

Warning

print will only display partial attributes, use print(contract.to_str()) to print all attributes

Get via API

Contract objects can be queried through the following methods:

Get contract information get_contract/get_contracts

Parameters:

ParameterRequiredDescription
symbolYesContract code e.g., 00700/AAPL
sec_typeYesContract type e.g., SecurityType.STK/SecurityType.OPT
currencyNoCurrency e.g., Currency.USD/Currency.HKD
exchangeNoExchange e.g., SMART/SEHK
expiryNoExpiry date, required when trading options yyyyMMdd
strikeNoStrike price, required when trading options
put_callNoCALL/PUT, required when trading options
secret_keyNoInstitutional trader key, for institutional users only, needs to be configured in client_config

Returns

get_contract returns Contract object; get_contracts returns list of Contract objects. Object properties see description section above

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import get_client_config
client_config = get_client_config(private_key_path='private key path', tiger_id='your tiger id', account='your account', secret_key='institutional trader exclusive key')
trade_client = TradeClient(client_config)

# Get stock contract
contract = trade_client.get_contract('FB', sec_type=SecurityType.STK)
contracts = trade_client.get_contracts(['AAPL', 'TSLA'], sec_type=SecurityType.STK)

# Get futures contract
fut_contract = trade_client.get_contract('CL', sec_type=SecurityType.FUT)

# Get option contract
opt_contract = trade_client.get_contract('SPY', sec_type=SecurityType.OPT, expiry='20231215', strike=435.0, put_call='CALL')

MarketStatus Market Status

tigeropen.quote.domain.market_status.MarketStatus

Description

Market trading status

Object Properties

PropertyTypeDescription
marketstrMarket. (US: US stocks, CN: Shanghai/Shenzhen, HK: Hong Kong stocks)
trading_statusstrMarket trading status code. Not yet open NOT_YET_OPEN; Pre-market trading PRE_HOUR_TRADING; Trading TRADING; Midday break MIDDLE_CLOSE; After-hours trading POST_HOUR_TRADING; Closed CLOSING; Early close EARLY_CLOSED; Market closed MARKET_CLOSED;
statusstrMarket status description (not yet open, trading, closed, etc.)
open_timedatetime.datetimeMost recent open time

OptionFilter Option Chain Filter

tigeropen.quote.domain.filter.OptionFilter

Description

Option filter parameter object

Object Properties

ParameterTypeRequiredDescription
implied_volatilityfloatNoImplied volatility, reflects market expectations of future stock price volatility, higher implied volatility indicates more expected stock price volatility
in_the_moneyboolNoWhether in the money
open_interestintNoOpen interest, number of uncleared contracts held by market participants at the end of each trading day. Reflects market depth and liquidity
deltafloatNoDelta, reflects the impact of stock price changes on option price changes. For every $1 change in stock price, option price changes approximately delta. Range -1.0 ~ 1.0
gammafloatNoGamma, reflects the impact of stock price changes on delta. For every $1 change in stock price, delta changes by gamma
thetafloatNoTheta, reflects the impact of time changes on option price changes. For every day reduction in time, option price changes approximately theta
vegafloatNoVega, reflects the impact of volatility on option price changes. For every 1% change in volatility, option price changes approximately vega
rhofloatNoRho, reflects the impact of risk-free interest rate on option price changes. For every 1% change in risk-free interest rate, option price changes approximately rho

Order Changes

FieldDescription
idOrder ID
accountAccount
symbolPosition symbol, e.g., 'AAPL', '00700', 'ES', 'CN'
expiryOptions, warrants, CBBC only
strikeOptions, warrants, CBBC only
rightOptions, warrants, CBBC only
identifierAsset identifier. Stock identifier is same as symbol. Futures include contract month, e.g., 'CN2201'
multiplierQuantity per lot, futures, options, warrants, CBBC only
actionBuy/sell direction. BUY for buy, SELL for sell
marketMarket. US, HK
currencyCurrency. USD US Dollar, HKD Hong Kong Dollar
segTypeClassification by trading type. S for stocks, C for futures
secTypeSTK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
orderTypeOrder type. 'MKT' market order/'LMT' limit order/'STP' stop order/'STP_LMT' stop limit order/'TRAIL' trailing stop order
isLongWhether long position
totalQuantityOrder quantity
totalQuantityScaleOrder quantity offset, e.g., totalQuantity=111, totalQuantityScale=2, then actual totalQuantity=111*10^(-2)=1.11
filledQuantityTotal filled quantity (for orders filled in multiple trades, filledQuantity is cumulative total filled)
filledQuantityScaleTotal filled quantity offset
avgFillPriceAverage fill price
limitPriceLimit order price
stopPriceStop price
realizedPnlRealized P&L (only integrated accounts have this field)
statusOrder Status
replaceStatusOrder Replace Status
cancelStatusOrder Cancel Status
outsideRthWhether allows pre-market and after-hours trading, US stocks only
canModifyWhether can modify
canCancelWhether can cancel
liquidationWhether it's a closing order
nameAsset name
sourceOrder source (from 'OpenApi', or other)
errorMsgError message
attrDescOrder description
commissionAndFeeTotal commission and fees
openTimeOrder time
timestampOrder status last update time

Position Changes

FieldDescription
accountUser account
symbolStock code
expiryExpiry date, options, warrants, CBBC only
strikeStrike price, options, warrants, CBBC only
rightOption direction PUT/CALL, options, warrants, CBBC only
identifierAsset identifier
multiplierLot size, options, warrants, CBBC only
marketTrading market
currencyCurrency type
segTypeClassification by trading type. S for stocks, C for futures
secTypeContract type
positionPosition
positionScalePosition quantity offset
averageCostAverage cost
latestPriceLatest price
marketValueMarket value
unrealizedPnlUnrealized P&L
nameAsset name
timestampServer time

Asset Changes

FieldDescription
accountUser account
currencyCurrency type
segTypeClassification by trading type. S for stocks, C for futures
availableFundsAvailable funds (loan value equity - initial margin)
excessLiquidityExcess liquidity (loan value equity - maintenance margin)
netLiquidationNet liquidation value
equityWithLoanEquity with loan value (loan value assets)
buyingPowerBuying power
cashBalanceAccount cash balance
grossPositionValuePosition market value
initMarginReqCurrent initial margin
maintMarginReqCurrent maintenance margin
timestampServer time

Quote Changes

  • Basic quotes
FieldSub-fieldDescription
symbolStock code
typeType
timestampQuote data time
serverTimestampServer time
avgPriceAverage price
latestPriceLatest price
latestPriceTimestampLatest price timestamp (no value in pre/post market)
latestTimeLatest price time
preClosePrevious close
volumeDaily cumulative volume
amountDaily cumulative turnover (options/futures not supported)
openOpen price
highHigh price
lowLow price
hourTradingTagPre/post market tag (no value during US market hours), values: Pre-market/After-hours
marketStatusMarket status
identifierAsset identifier (options only)
openIntOpen interest (options only)
tradeTimeTrade time (futures only)
preSettlementPrevious settlement price (futures only)
minTickMinimum tick size (futures only)
mipMinute price
miaMinute average price
mitMinute time
mivMinute volume
mioMinute open price (futures only)
mihMinute high price (futures only)
milMinute low price (futures only)
  • Best bid/ask quotes
FieldDescription
askPriceAsk price
askSizeAsk size
askTimestampAsk timestamp (Pre/Post-Mkt data not supported)
bidPriceBid price
bidSizeBid size
bidTimestampBid timestamp (Pre/Post-Mkt data not supported)