中文

Query Account Information

get_managed_accounts Get List of Managed Accounts

TradeClient.get_managed_accounts(account=None)

Description

Get associated funding accounts. For institutional accounts, returns the main account and all sub-accounts.

Parameters

ParameterTypeRequiredDescription
accountstrNoAccount ID, optional, if not provided, returns all associated accounts

Returns

A list of AccountProfile (tigeropen.trade.domain.profile.AccountProfile) objects

Each object has the following attributes:

ParameterTypeDescription
accountIntegrated account: 50129912, Global: U5755619, Simulation account: 20191221901212121Trading funding account, where integrated accounts are 5-10 digit numbers, simulation accounts are 17 digit numbers, global accounts start with letter U
capabilityRegTMarginAccount type (CASH: Cash account, RegTMargin: Reg T Margin account, PMGRN: Portfolio margin)
statusFundedAccount status, most scenarios return Funded status. Status includes: Funded (funded), Open (opened), Pending (pending opening), Rejected (opening rejected), Closed (closed)
account_typeSTANDARDAccount category: GLOBAL (Global account), STANDARD (Integrated account), PAPER (Simulation account)

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')
trade_client = TradeClient(client_config)

accounts = trade_client.get_managed_accounts()
# View attributes of the first account
account1 = accounts[0]
print(account1.account)  # Account number
print(account1.account_type)  # Account category (integrated/simulation)
print(account1.capability)  # Account capability (cash/margin)

Return Example

[AccountProfile({'account': 'DU575569', 'capability': None, 'status': 'Funded'})]

get_prime_assets Get Integrated/Simulation Account Asset Information

TradeClient.get_prime_assets(account=None, base_currency=None, consolidated=True)

Description

Get asset information, applicable to integrated/simulation accounts

Parameters

ParameterTypeRequiredDescription
accountstrNoAccount ID, if not specified, uses the default account in client_config
base_currencystrNoCurrency
consolidatedboolNoWhether to display aggregated Segment asset metrics, only SEC and FUND category assets will be aggregated. Default is true

Returns

list

Each element in the list is a PortfolioAccount object. If there is only one account, the list contains only one element. The structure of the PortfolioAccount object is as follows.

For detailed explanations of fields in PortfolioAccount and Segment, please refer to Object Information

PortfolioAccount Object
├── account: Account ID
├── update_timestamp: Update time, timestamp in milliseconds
├── segments: Account information by product category, a dict with security category as key, value is Segment object
│   ├── 'S' represents Securities account, value is Segment object
│   │    ├── currency: Currency, such as USD, HKD
│   │    ├── capability: Account type, margin account: RegTMargin, cash account: Cash.
│   │    ├── category: Trading product category C: (Commodities futures), S: (Securities stocks)
│   │    ├── cash_balance: Cash amount.
│   │    ├── cash_available_for_trade: Available funds, including cash and financing limit, used as reference for maximum trading purchasing power.
│   │    ├── cash_available_for_withdrawal: Cash amount currently available for withdrawal from the account
│   │    ├── gross_position_value: Total securities value
│   │    ├── equity_with_loan: Total equity with loan value
│   │    ├── net_liquidation: Total assets; net liquidation value
│   │    ├── init_margin: Initial margin
│   │    ├── maintain_margin: Maintenance margin
│   │    ├── overnight_margin: Overnight margin
│   │    ├── unrealized_pl: Unrealized P&L
│   │    ├── realized_pl: Realized P&L
│   │    ├── excess_liquidation: Current excess liquidity
│   │    ├── overnight_liquidation: Overnight excess liquidity
│   │    ├── buying_power: Buying power
│   │    ├── leverage: Current leverage ratio used
│   │    ├── locked_funds: Locked funds
│   │    ├── uncollected: Funds in transit
│   │    ├── currency_assets: Account asset information by trading currency, a dict with currency as key
│   │    │   ├── 'USD' represents US Dollar, value is CurrencyAsset object
│   │    │   │   ├── currency: Current currency, common currencies include: USD-US Dollar, HKD-Hong Kong Dollar, SGD-Singapore Dollar, CNH-Renminbi
│   │    │   │   ├── cash_balance: Cash available for trading, plus locked cash portion (such as stocks purchased but not yet settled, and other situations that may have locked cash)
│   │    │   │   ├── cash_available_for_trade: Cash amount currently available for trading in the account
│   │    │   ├── 'HKD' represents Hong Kong Dollar, value is CurrencyAsset object
│   │    └─  └── 'CNH' represents Renminbi, value is CurrencyAsset object
│   └── 'C' represents Futures account, value is Segment object
│   └── 'F' represents Fund account, value is Segment object


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')
trade_client = TradeClient(client_config)

portfolio_account = trade_client.get_prime_assets(base_currency='USD')  # Can set base currency
print(portfolio_account)

# Example of viewing account attributes
print(portfolio_account.account)   # Account ID
print(portfolio_account.segments['S'].buying_power)  # Securities account buying power
print(portfolio_account.segments['S'].cash_balance)  # Securities account cash value
print(portfolio_account.segments['S'].unrealized_pl)   # Unrealized P&L
print(portfolio_account.segments['S'].currency_assets['USD'].gross_position_value)  # Total securities value in USD
print(portfolio_account.segments['S'].currency_assets['HKD'].gross_position_value)  # Total securities value in HKD
print(portfolio_account.segments['S'].currency_assets['HKD'].cash_balance)  # Cash value in HKD

print(portfolio_account.segments['C'].init_margin)  # Futures account initial margin
print(portfolio_account.segments['C'].maintain_margin)  # Futures account maintenance margin
print(portfolio_account.segments['C'].currency_assets['USD'].cash_balance)  # Futures account cash value in USD

Return Example

 PortfolioAccount(
  {
	'account': '1234567',
	'update_timestamp': 1638949616442,
	'segments': {
		'S': Segment({
			'currency': 'USD',
			'capability': 'RegTMargin',
			'category': 'S',
			'cash_balance': 111978.7160247,
			'cash_available_for_trade': 123905.775195,
			'cash_available_for_withdrawal': 123905.775195,
			'gross_position_value': 22113.5652986,
			'equity_with_loan': 134092.2813233,
			'net_liquidation': 135457.2802984,
			'init_margin': 9992.3764097,
			'maintain_margin': 8832.4423281,
			'overnight_margin': 11607.5876493,
			'unrealized_pl': -1121.0821891,
			'realized_pl': -3256.0,
			'excess_liquidation': 125259.8389952,
			'overnight_liquidation': 122484.693674,
			'buying_power': 495623.1007801,
			'leverage': 0.164693,
			'currency_assets': {
				'USD': CurrencyAsset({
					'currency': 'USD',
					'cash_balance': 123844.77,
					'cash_available_for_trade': 123792.77
				}),
				'HKD': CurrencyAsset({
					'currency': 'HKD',
					'cash_balance': -92554.07,
					'cash_available_for_trade': -93664.15
				}),
				'CNH': CurrencyAsset({
					'currency': 'CNH',
					'cash_balance': 0.0,
					'cash_available_for_trade': 0.0
				})
			}
		}),
		'C': Segment({
			'currency': 'USD',
			'capability': 'RegTMargin',
			'category': 'C',
			'cash_balance': 3483681.32,
			'cash_available_for_trade': 3481701.32,
			'cash_available_for_withdrawal': 3481701.32,
			'gross_position_value': 1000000.0,
			'equity_with_loan': 3481881.32,
			'net_liquidation': 3483681.32,
			'init_margin': 1980.0,
			'maintain_margin': 1800.0,
			'overnight_margin': 1800.0,
			'unrealized_pl': 932722.41,
			'realized_pl': -30.7,
			'excess_liquidation': 3481881.32,
			'overnight_liquidation': 3481881.32,
			'buying_power': 0.0,
			'leverage': 0.0,
			'currency_assets': {
				'USD': CurrencyAsset({
					'currency': 'USD',
					'cash_balance': 3483681.32,
					'cash_available_for_trade': 3483681.32
				}),
				'HKD': CurrencyAsset({
					'currency': 'HKD',
					'cash_balance': 0.0,
					'cash_available_for_trade': 0.0
				}),
				'CNH': CurrencyAsset({
					'currency': 'CNH',
					'cash_balance': 0.0,
					'cash_available_for_trade': 0.0
				})
			}
		})
	}
})

get_assets Get Global Account Assets

TradeClient.get_assets(account=None, sub_accounts=None, segment=False, market_value=False)

Description

Get account asset information. The return structure is mainly applicable to Global accounts. Although integrated/simulation accounts can also use this interface, many fields will be empty. It is recommended to use get_prime_assets to query integrated/simulation account assets.

Parameters

ParameterTypeRequiredDescription
accountstrNoAccount ID, if not specified, uses the default account in client_config
sub_accountslist[str]NoSub-account list, default is None
segmentboolNoWhether to return data classified by product category (securities, futures), default False. When True, returns a dict where C represents futures, S represents stocks
market_valueboolNoWhether to return data classified by currency (USD, HKD, CNH), default False
secret_keystrNoInstitutional trader key, exclusive to institutional users, required for institutional users, needs to be configured in client_config

Returns

list

Each element in the list is a PortfolioAccount object. If there is only one account, the list contains only one element. The structure of the PortfolioAccount (tigeropen.trade.domain.account.PortfolioAccount) object is as follows.

For information about Account, SecuritySegment, CommoditySegment, please refer to Object Information

PortfolioAccount Object
├── account: Account ID
├── summary: Summary statistics for the current account. The value inside is an Account object
├── segments: Account information by product category, a dict
│   ├── 'S' represents Securities account, value is SecuritySegment object
│   └── 'C' represents Futures account, value is CommoditySegment object
├── market_value: Account statistics by currency, a dict
│   ├── 'USD' represents US Dollar, value is MarketValue object
│   ├── 'HKD' represents Hong Kong Dollar, value is MarketValue object
└─  └── 'CNH' represents Renminbi, value is MarketValue object

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')
trade_client = TradeClient(client_config)

portfolio_account = trade_client.get_assets(segment=True, market_value=True)
print(portfolio_account)

# View attributes of the first portfolio
portfolio1 = portfolio_account[0]
print(portfolio1.account)  # Account ID
print(portfolio1.segments['S'].available_funds)  # Available funds in securities account
print(portfolio1.segments['S'].gross_position_value)  # Market value of securities account
print(portfolio1.segments['C'].available_funds)  # Available funds in futures account (only has value if futures account is opened)
print(portfolio1.summary.buying_power)  # Buying power
print(portfolio1.summary.cash)  # Cash

Return Example

[PortfolioAccount({'account': 'DU111111', 
                    'summary': Account({'accrued_cash': 0, 'accrued_dividend': 0, 'available_funds': 948.69, 
                                        'buying_power': 948.69, 'cash': 948.81, 'currency': 'USD', 'cushion': 0.5944, 
                                        'day_trades_remaining': 3, 'equity_with_loan': 1255.69, 'excess_liquidity': 948.81, 
                                        'gross_position_value': 647.53, 'initial_margin_requirement': 307, 
                                        'maintenance_margin_requirement': 307, 'net_liquidation': 1596.34, 
                                        'realized_pnl': 0, 'regt_equity': 1255.81, 
                                        'regt_margin': 153.5, 'sma': 3512.56, 
                                        'timestamp': 1561529631, 'unrealized_pnl': -885.36}), 

                    'segments': defaultdict(<class 'tigeropen.trade.domain.account.Account'>, 
                            {'C': CommoditySegment({'accrued_cash': 0, 'accrued_dividend': 0, 
                                                    'available_funds': 0, 'cash': 0, 'equity_with_loan': 0, 'excess_liquidity': 0, 
                                                    'initial_margin_requirement': 0, 'maintenance_margin_requirement': 0, 
                                                    'net_liquidation': 0, 'timestamp': 1544393719}), 
                            'S': SecuritySegment({'accrued_cash': 0, 'accrued_dividend': 0, 
                                                'available_funds': 120.73, 'cash': 120.73, 'equity_with_loan': 1292.04, 
                                                'excess_liquidity': 120.73, 'gross_position_value': 1171.31, 
                                                'initial_margin_requirement': 1171.31, 'leverage': 0.91, 
                                                'maintenance_margin_requirement': 1171.31, 'net_liquidation': 1292.04, 
                                                'regt_equity': 1292.04, 'regt_margin': 585.66, 'sma': 1973.39, 'timestamp': 1545206069})
                            }), 

                    'market_values': defaultdict(<class 'tigeropen.trade.domain.account.MarketValue'>, 
                            {'CNH': MarketValue({'currency': 'CNH', 'net_liquidation': 0, 'cash_balance': 0, 
                                '               stock_market_value': 0, 'option_market_value': 0, 
                                                'warrant_value': 0, 'futures_pnl': 0, 'unrealized_pnl': 0, 
                                                'realized_pnl': 0, 'exchange_rate': 0.14506, 
                                                'net_dividend': 0, 'timestamp': 1544078822}), 
                            'HKD': MarketValue({'currency': 'HKD', 'net_liquidation': 0, 'cash_balance': 0, 
                                                'stock_market_value': 0, 'option_market_value': 0, 
                                                'warrant_value': 0, 'futures_pnl': 0, 'unrealized_pnl': 0, 
                                                'realized_pnl': 0, 'exchange_rate': 0.12743, 
                                                'net_dividend': 0, 'timestamp': 1550158606}), 
                            'USD': MarketValue({'currency': 'USD', 'net_liquidation': 1596.34, 
                                                'cash_balance': 948.81, 'stock_market_value': 307, 
                                                'option_market_value': 340.53, 'warrant_value': 0, 
                                                'futures_pnl': 0, 'unrealized_pnl': -885.36, 
                                                'realized_pnl': 0, 'exchange_rate': 1, 
                                                'net_dividend': 0, 'timestamp': 1561519773})}
                            )}
                    )]

get_positions Get Position Data

TradeClient.get_positions(account=None, sec_type=SecurityType.STK, currency=Currency.ALL, market=Market.ALL, symbol=None, sub_accounts=None, expiry=None, strike=None, put_call=None)

Description

Get account position information

Parameters

ParameterTypeRequiredDescription
accountstrNoAccount ID, if not specified, use the default account from client_config
sec_typeSecurityTypeNoSecurity type, including STK/OPT/FUT etc., default STK, can be imported from tigeropen.common.consts.SecurityType
currencyCurrencyNoCurrency, including ALL/USD/HKD/CNH etc., default ALL, can be imported from tigeropen.common.consts.Currency
marketMarketNoMarket, including ALL/US/HK/CN etc., default ALL, can be imported from tigeropen.common.consts.Market
symbolstrNoSecurity symbol
sub_accountslist[str]NoSub-account list
expirystrNoExpiry date (for options). Format 'yyyyMMdd', e.g., '220121'
strikefloatNoStrike price (for options). e.g., 100.5
put_callstrNoPut or call (for options). 'PUT' or 'CALL'

Returns

List of position objects, type: list

Structure as follows:

Each element is a Position object. Position(tigeropen.trade.domain.position.Position) object has the following attributes:

ParameterTypeDescription
accountstrAccount
contractContractContract object, tigeropen.trade.domain.contract.Contract
quantityintPosition quantity
average_costfloatPosition cost
average_cost_by_averagefloatAverage price cost
average_cost_of_carryfloatAverage position cost calculated in A-share style (object)
market_pricefloatLatest price (during trading hours, market price. For US stocks during non-trading hours, integrated account shows after-hours closing price, global account shows intraday closing price)
market_valuefloatMarket value
realized_pnlfloatRealized P&L
realized_pnl_by_averagefloatRealized P&L by average cost
unrealized_pnlfloatUnrealized P&L
unrealized_pnl_by_averagefloatUnrealized P&L by average cost
unrealized_pnl_percentfloatUnrealized P&L percentage
unrealized_pnl_percent_by_averagefloatUnrealized P&L percentage by average cost
salable_qtyfloatSalable quantity

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

positions = trade_client.get_positions(sec_type=SecurityType.STK, currency=Currency.ALL, market=Market.ALL)

# View position attributes
print(len(positions))  # Number of position securities
# First position contract
position1 = positions[0]
print(position1.contract.symbol)  # Contract symbol, e.g., AAPL, CL2303
print(position1.contract.sec_type)  # Contract type, e.g., STK, FUT
print(position1.contract.multiplier)  # Contract multiplier
print(position1.average_cost)  # Position cost
print(position1.quantity)  # Position quantity
# Second position security
position2 = positions[1]
print(position2.unrealized_pnl)  # Unrealized P&L
print(position2.market_value) # Position market value

Return Example

[contract: BABA/STK/USD, quantity: 1, average_cost: 178.99, market_price: 176.77,
contract: BIDU/STK/USD, quantity: 3, average_cost: 265.4633, market_price: 153.45,
contract: SPY/STK/USD, quantity: 7, average_cost: 284.9243, market_price: 284.97]

get_analytics_asset Get Historical Asset Analysis

TradeClient.get_analytics_asset(account=None, start_date=None, end_date=None, seg_type=None, currency=None, sub_account=None)

Description

Get account historical asset analysis

Parameters

ParameterTypeRequiredDescription
accountstrNoAccount ID, if not specified, use the default account from client_config
start_datestrNoStart date, format yyyy-MM-dd, e.g., '2022-01-01'. If not provided, uses 30 days before end_date
end_datestrNoEnd date, format yyyy-MM-dd, e.g., '2022-02-01'. If not provided, uses current date
seg_typeSegmentTypeNoAccount segment type, options: SegmentType.SEC for securities; SegmentType.FUT for futures, can be imported from tigeropen.common.consts.SegmentType
currencyCurrencyNoCurrency, including ALL/USD/HKD/CNH etc., can be imported from tigeropen.common.consts.Currency
sub_accountstrNoSub-account (for institutional accounts only), if provided, returns assets for this sub-account

Returns

dict

summary corresponds to asset analysis summary, type dict, field meanings:

ParameterTypeDescription
pnlfloatP&L amount
pnl_percentagefloatReturn rate
annualized_returnfloatAnnualized return (estimated)
over_user_percentagefloatPercentage above users overUserPercentage%

history corresponds to historical asset list, each item is dict, field meanings:

ParameterTypeDescription
dateintDate timestamp in milliseconds
pnlfloatP&L amount compared to previous day
pnl_percentagefloatReturn rate compared to previous day
assetfloatTotal asset amount
cash_balancefloatCash balance
gross_position_valuefloatMarket value
depositfloatDeposit amount
withdrawalfloatWithdrawal amount

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

result = trade_client.get_analytics_asset(start_date='2021-12-01', end_date='2021-12-07', seg_type=SegmentType.SEC)

# View attributes
print(result['summary']['pnl'])  # P&L amount
print(result['summary']['pnl_percentage'])  # P&L percentage
for data in result['history']:  # Historical assets
    print(data['date'])  # Historical asset date
    print(data['pnl'])  # P&L

Return Example

{'summary': {'pnl': 691.18, 'pnl_percentage': 0.0, 'annualized_return': 0.0, 'over_user_percentage': 0.0}, 
 'history': [{'date': 1638334800000, 'asset': 48827609.65, 'pnl': 0.0, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 15911.06, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-01'},
             {'date': 1638421200000, 'asset': 48827687.69, 'pnl': 78.04, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 15989.1, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-02'},
             {'date': 1638507600000, 'asset': 48827583.18, 'pnl': -26.47, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 15884.58, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-03'}, 
             {'date': 1638766800000, 'asset': 48827804.28, 'pnl': 194.63, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 16105.68, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-06'}, 
             {'date': 1638853200000, 'asset': 48828300.83, 'pnl': 691.18, 'pnl_percentage': 0.0, 'cash_balance': 48811723.0, 'gross_position_value': 16577.82, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-07'}]}

get_segment_fund_available Get Available Transfer Funds

TradeClient.get_segment_fund_available(from_segment=None, currency=None)

Description

Get available transfer funds under the corresponding Segment of the account (applicable to integrated or simulation accounts)

Parameters

ParameterTypeRequiredDescription
from_segmentstrYesTransfer from segment, FUT or SEC
currencystrNoTransfer currency, USD or HKD

Returns

List[SegmentFundAvailableItem] List of available transfer fund amounts for each Segment. Each item is tigeropen.trade.domain.account.SegmentFundAvailableItem

SegmentFundAvailableItem Description:

NameTypeDescription
from_segmentstringTransfer from segment, FUT or SEC
currencystringTransfer currency, USD or HKD
amountfloatAvailable funds, unit: corresponding currency

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

available = trade_client.get_segment_fund_available(from_segment='SEC', currency='HKD')
print(available)

# Get amount
print(available[0].amount)

Return Example

[SegmentFundAvailableItem({'from_segment': 'SEC', 'currency': 'HKD', 'amount': 718859.79})]

transfer_segment_fund Internal Account Fund Transfer

TradeClient.transfer_segment_fund(from_segment=None, to_segment=None, amount=None, currency=None)

Description

Transfer funds between different Segments of the account, such as from Securities Segment to Futures Segment (applicable to integrated or simulation accounts)

Parameters

ParameterTypeRequiredDescription
from_segmentstrYesTransfer from segment, FUT or SEC
to_segmentstrYesTransfer to segment, FUT or SEC, must be different from from_segment
currencystrYesTransfer currency, USD or HKD
amountfloatYesTransfer amount, unit: corresponding currency

Returns

tigeropen.trade.domain.account.SegmentFundItem

SegmentFundItem Description:

NameTypeDescription
idintTransfer record ID
from_segmentstrTransfer from segment, FUT or SEC
to_segmentstrTransfer to segment, FUT or SEC
currencystrTransfer currency, USD or HKD
amountfloatTransfer amount, unit: corresponding currency
statusstrStatus (NEW/PROC/SUCC/FAIL/CANC)
status_descstrStatus description (Submitted/Processing/Received/Transfer Failed/Cancelled)
messagestrFailure message
settled_atintSettlement timestamp
updated_atintUpdate timestamp
created_atintCreation timestamp

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

res = trade_client.transfer_segment_fund(from_segment='SEC', to_segment='FUT', amount=100, currency='USD')
print(res)

Return Example

SegmentFundItem({'id': 30322815980011520, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD',
 'amount': 100.0, 'status': 'NEW', 'status_desc': 'Submitted', 'message': None, 'settled_at': None,
  'updated_at': 1680243926131, 'created_at': 1680243926131})

cancel_segment_fund Cancel Internal Account Fund Transfer

TradeClient.cancel_segment_fund(id=None)

Description

Cancel submitted fund transfer (applicable to integrated or simulation accounts) If the transfer has already succeeded, it cannot be cancelled. You can reverse transfer by swapping Segments.

Parameters

ParameterTypeRequiredDescription
idintYesTransfer record ID

Returns tigeropen.trade.domain.account.SegmentFundItem

SegmentFundItem Description:

NameTypeDescription
idintTransfer record ID
from_segmentstrTransfer from segment, FUT or SEC
to_segmentstrTransfer to segment, FUT or SEC
currencystrTransfer currency, USD or HKD
amountfloatTransfer amount, unit: corresponding currency
statusstrStatus (NEW/PROC/SUCC/FAIL/CANC)
status_descstrStatus description (Submitted/Processing/Received/Transfer Failed/Cancelled)
messagestrFailure message
settled_atintSettlement timestamp
updated_atintUpdate timestamp
created_atintCreation timestamp

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

res = trade_client.cancel_segment_fund(id='transfer request id')
print(res)

Return Example

SegmentFundItem({'id': 30322815980011520, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD',
 'amount': 100.0, 'status': 'CANC', 'message': None, 'settled_at': None, 'updated_at': 1680243926131, 'created_at': 1680243926131})

get_positions Get Position Data

TradeClient.get_positions(account=None, sec_type=SecurityType.STK, currency=Currency.ALL, market=Market.ALL, symbol=None, sub_accounts=None, expiry=None, strike=None, put_call=None)

Description

Get position information for the account

Parameters

ParameterTypeRequiredDescription
accountstrNoAccount ID, if not specified, uses the default account in client_config
sec_typeSecurityTypeNoSecurity type, including STK/OPT/FUT etc., default STK, can be imported from tigeropen.common.consts.SecurityType
currencyCurrencyNoCurrency, including ALL/USD/HKD/CNH etc., default ALL, can be imported from tigeropen.common.consts.Currency
marketMarketNoMarket, including ALL/US/HK/CN etc., default ALL, can be imported from tigeropen.common.consts.Market
symbolstrNoSecurity symbol
sub_accountslist[str]NoSub-account list
expirystrNoExpiration date (for options). Format 'yyyyMMdd', e.g., '220121'
strikefloatNoStrike price (for options). e.g., 100.5
put_callstrNoPut or Call (for options). 'PUT' or 'CALL'

Returns

List of position objects, type: list

Structure as follows:

Each element is a Position object. Position(tigeropen.trade.domain.position.Position) object has the following attributes:

ParameterTypeDescription
accountstrAccount
contractContractContract object, tigeropen.trade.domain.contract.Contract
quantityintPosition quantity
average_costfloatPosition cost
average_cost_by_averagefloatAverage cost
average_cost_of_carryfloatA-share method calculated average position cost (object)
market_pricefloatLatest price (during trading hours, market price. For US stocks during non-trading hours, comprehensive account shows after-hours closing price, global account shows intraday closing price)
market_valuefloatMarket value
realized_pnlfloatRealized P&L
realized_pnl_by_averagefloatAverage cost realized P&L
unrealized_pnlfloatUnrealized P&L
unrealized_pnl_by_averagefloatAverage cost unrealized P&L
unrealized_pnl_percentfloatUnrealized P&L percentage
unrealized_pnl_percent_by_averagefloatAverage cost unrealized P&L percentage
salable_qtyfloatSellable quantity

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

positions = trade_client.get_positions(sec_type=SecurityType.STK, currency=Currency.ALL, market=Market.ALL)

# View position attributes
print(len(positions))  # Number of position instruments
# First position contract
position1 = positions[0]
print(position1.contract.symbol)  # Contract symbol, e.g., AAPL, CL2303
print(position1.contract.sec_type)  # Contract type, e.g., STK, FUT
print(position1.contract.multiplier)  # Contract multiplier
print(position1.average_cost)  # Position cost
print(position1.quantity)  # Position quantity
# Second position instrument
position2 = positions[1]
print(position2.unrealized_pnl)  # Unrealized P&L
print(position2.market_value) # Position market value

Return Example

[contract: BABA/STK/USD, quantity: 1, average_cost: 178.99, market_price: 176.77,
contract: BIDU/STK/USD, quantity: 3, average_cost: 265.4633, market_price: 153.45,
contract: SPY/STK/USD, quantity: 7, average_cost: 284.9243, market_price: 284.97]

get_analytics_asset Get Historical Asset Analysis

TradeClient.get_analytics_asset(account=None, start_date=None, end_date=None, seg_type=None, currency=None, sub_account=None)

Description

Get historical asset analysis for the account

Parameters

ParameterTypeRequiredDescription
accountstrNoAccount ID, if not specified, uses the default account in client_config
start_datestrNoStart date, format yyyy-MM-dd, e.g., '2022-01-01'. If not provided, uses end_date minus 30 days
end_datestrNoEnd date, format yyyy-MM-dd, e.g., '2022-02-01'. If not provided, uses current date
seg_typeSegmentTypeNoAccount segment type, options: SegmentType.SEC for securities; SegmentType.FUT for futures, can be imported from tigeropen.common.consts.SegmentType
currencyCurrencyNoCurrency, including ALL/USD/HKD/CNH etc., can be imported from tigeropen.common.consts.Currency
sub_accountstrNoSub-account (for institutional accounts only), if provided, returns assets for this sub-account

Returns

dict

summary corresponds to asset analysis summary, type dict, field meanings:

ParameterTypeDescription
pnlfloatP&L amount
pnl_percentagefloatReturn rate
annualized_returnfloatAnnualized return (estimated)
over_user_percentagefloatPercentage above users overUserPercentage%

history corresponds to historical asset list, each item is dict, field meanings:

ParameterTypeDescription
dateintDate timestamp in milliseconds
pnlfloatP&L amount compared to previous day
pnl_percentagefloatReturn rate compared to previous day
assetfloatTotal asset amount
cash_balancefloatCash balance
gross_position_valuefloatMarket value
depositfloatDeposit amount
withdrawalfloatWithdrawal amount

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

result = trade_client.get_analytics_asset(start_date='2021-12-01', end_date='2021-12-07', seg_type=SegmentType.SEC)

# View attributes
print(result['summary']['pnl'])  # P&L amount
print(result['summary']['pnl_percentage'])  # P&L percentage
for data in result['history']:  # Historical assets
    print(data['date'])  # Historical asset date
    print(data['pnl'])  # P&L

Return Example

{'summary': {'pnl': 691.18, 'pnl_percentage': 0.0, 'annualized_return': 0.0, 'over_user_percentage': 0.0}, 
 'history': [{'date': 1638334800000, 'asset': 48827609.65, 'pnl': 0.0, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 15911.06, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-01'},
             {'date': 1638421200000, 'asset': 48827687.69, 'pnl': 78.04, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 15989.1, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-02'},
             {'date': 1638507600000, 'asset': 48827583.18, 'pnl': -26.47, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 15884.58, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-03'}, 
             {'date': 1638766800000, 'asset': 48827804.28, 'pnl': 194.63, 'pnl_percentage': 0.0, 'cash_balance': 48811698.59, 'gross_position_value': 16105.68, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-06'}, 
             {'date': 1638853200000, 'asset': 48828300.83, 'pnl': 691.18, 'pnl_percentage': 0.0, 'cash_balance': 48811723.0, 'gross_position_value': 16577.82, 'deposit': 0.0, 'withdrawal': 0.0, 'dt': '2021-12-07'}]}

get_segment_fund_available Get Transferable Funds

TradeClient.get_segment_fund_available(from_segment=None, currency=None)

Description

Get transferable funds under the corresponding Segment of the account (applicable to comprehensive or demo accounts)

Parameters

ParameterTypeRequiredDescription
from_segmentstrYesTransfer from segment, FUT or SEC
currencystrNoTransfer currency, USD or HKD

Returns

List[SegmentFundAvailableItem] List of transferable fund amounts for each Segment. Each item is tigeropen.trade.domain.account.SegmentFundAvailableItem

SegmentFundAvailableItem Description:

NameTypeDescription
from_segmentstringTransfer from segment, FUT or SEC
currencystringTransfer currency, USD or HKD
amountfloatTransferable funds, unit: corresponding currency

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

available = trade_client.get_segment_fund_available(from_segment='SEC', currency='HKD')
print(available)

# Get amount
print(available[0].amount)

Return Example

[SegmentFundAvailableItem({'from_segment': 'SEC', 'currency': 'HKD', 'amount': 718859.79})]

transfer_segment_fund Internal Account Fund Transfer

TradeClient.transfer_segment_fund(from_segment=None, to_segment=None, amount=None, currency=None)

Description

Transfer funds between different Segments of the account, such as from Securities Segment to Futures Segment (applicable to comprehensive or demo accounts)

Parameters

ParameterTypeRequiredDescription
from_segmentstrYesTransfer from segment, FUT or SEC
to_segmentstrYesTransfer to segment, FUT or SEC, must be different from from_segment
currencystrYesTransfer currency, USD or HKD
amountfloatYesTransfer amount, unit: corresponding currency

Returns

tigeropen.trade.domain.account.SegmentFundItem

SegmentFundItem Description:

NameTypeDescription
idintTransfer record ID
from_segmentstrTransfer from segment, FUT or SEC
to_segmentstrTransfer to segment, FUT or SEC
currencystrTransfer currency, USD or HKD
amountfloatTransfer amount, unit: corresponding currency
statusstrStatus (NEW/PROC/SUCC/FAIL/CANC)
status_descstrStatus description (Submitted/Processing/Completed/Transfer Failed/Cancelled)
messagestrFailure message
settled_atintSettlement timestamp
updated_atintUpdate timestamp
created_atintCreation timestamp

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

res = trade_client.transfer_segment_fund(from_segment='SEC', to_segment='FUT', amount=100, currency='USD')
print(res)

Return Example

SegmentFundItem({'id': 30322815980011520, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD',
 'amount': 100.0, 'status': 'NEW', 'status_desc': 'Submitted', 'message': None, 'settled_at': None,
  'updated_at': 1680243926131, 'created_at': 1680243926131})

cancel_segment_fund Cancel Internal Account Fund Transfer

TradeClient.cancel_segment_fund(id=None)

Description

Cancel submitted fund transfer (applicable to comprehensive or demo accounts) If the transfer has already succeeded, it cannot be cancelled, you can exchange Segments and transfer back in reverse.

Parameters

ParameterTypeRequiredDescription
idintYesTransfer record ID

Returns tigeropen.trade.domain.account.SegmentFundItem

SegmentFundItem Description:

NameTypeDescription
idintTransfer record ID
from_segmentstrTransfer from segment, FUT or SEC
to_segmentstrTransfer to segment, FUT or SEC
currencystrTransfer currency, USD or HKD
amountfloatTransfer amount, unit: corresponding currency
statusstrStatus (NEW/PROC/SUCC/FAIL/CANC)
status_descstrStatus description (Submitted/Processing/Completed/Transfer Failed/Cancelled)
messagestrFailure message
settled_atintSettlement timestamp
updated_atintUpdate timestamp
created_atintCreation timestamp

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

res = trade_client.cancel_segment_fund(id='transfer_request_id')
print(res)

Return Example

SegmentFundItem({'id': 30322815980011520, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD',
 'amount': 100.0, 'status': 'CANC', 'message': None, 'settled_at': None, 'updated_at': 1680243926131, 'created_at': 1680243926131})

get_segment_fund_history Internal Account Fund Transfer History

TradeClient.get_segment_fund_history(limit=None)

Description

Query historical transfer records between different Segments of the account. Sorted by time in descending order (applicable to comprehensive or demo accounts)

Parameters

ParameterTypeRequiredDescription
limitintNoNumber of recent transfer records to return. Default is 100, maximum 500

Returns tigeropen.trade.domain.account.SegmentFundItem

SegmentFundItem Description:

NameTypeDescription
idintTransfer record ID
from_segmentstrTransfer from segment, FUT or SEC
to_segmentstrTransfer to segment, FUT or SEC
currencystrTransfer currency, USD or HKD
amountfloatTransfer amount, unit: corresponding currency
statusstrStatus (NEW/PROC/SUCC/FAIL/CANC)
status_descstrStatus description (Submitted/Processing/Completed/Transfer Failed/Cancelled)
messagestrFailure message
settled_atintSettlement timestamp
updated_atintUpdate timestamp
created_atintCreation timestamp

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)
history = trade_client.get_segment_fund_history()
print(history)

Return Example

[SegmentFundItem({'id': 16256385456537600, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD', 
'amount': 100000.0, 'status': 'SUCC', 'status_desc': 'Completed', 'message': None,
 'settled_at': 1572925581000, 'updated_at': 1572925578000, 'created_at': 1572925578000}), 
 SegmentFundItem({'id': 16256377863667712, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD', 
 'amount': 100000.0, 'status': 'SUCC', 'status_desc': 'Completed', 'message': None,
  'settled_at': 1572925525000, 'updated_at': 1572925520000, 'created_at': 1572925520000}), 
  SegmentFundItem({'id': 15554843128627200, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD',
   'amount': 100000.0, 'status': 'SUCC', 'status_desc': 'Completed', 'message': None, 'settled_at': 1567573240000, 
   'updated_at': 1567573235000, 'created_at': 1567573235000}), 
   SegmentFundItem({'id': 14039478715026432, 'from_segment': 'SEC', 'to_segment': 'FUT', 'currency': 'USD', 'amount': 10000.0, 'status': 'SUCC', 'status_desc': 'Completed', 'message': None, 'settled_at': 1556011922000, 'updated_at': 1556011922000, 'created_at': 1556011922000})]

get_estimate_tradable_quantity Get Maximum Tradable Quantity

TradeClient.get_estimate_tradable_quantity(order, seg_type=None)

Description

Query the maximum buyable/sellable quantity for a specific instrument in the account. Supports stocks and options, does not currently support futures.

Parameters

Order object (tigeropen.trade.domain.order.Order)

You can use utility functions from tigeropen.common.util.order_utils, such as limit_order(), market_order(), to generate order objects locally based on your specific order type and parameters. For creation methods, see Order Object - Construction Methods section

Only supports limit orders or stop orders

Returns tigeropen.trade.domain.position.TradableQuantityItem object with the following attributes:

FieldTypeDescription
tradable_quantityfloatCash buyable/sellable quantity (if action is buy, returns buyable quantity, otherwise sellable quantity)
financing_quantityfloatMargin buyable/sellable quantity (not applicable to cash accounts)
position_quantityfloatPosition quantity
tradable_position_quantityfloatTradable position quantity

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)


contract = stock_contract(symbol='MSFT', currency='USD')
order = limit_order(account=client_config.account, contract=contract, action='BUY', limit_price=50, quantity=1)
res = trade_client.get_estimate_tradable_quantity(order)
print(res)

Return Example

TradableQuantityItem<{'tradable_quantity': 28921.0, 'financing_quantity': 52657.0, 'position_quantity': 0.0, 'tradable_position_quantity': 0}>

get_funding_history Get Funding History

TradeClient.get_funding_history(seg_type=None)

Description

Query the account's funding history.

Parameters

ParameterTypeRequiredDescription
seg_typeSegmentTypeNoSegment type

Returns pandas.DataFrame with the following fields:

FieldTypeDescription
idlongID
refIdstringRelated business ID
typeintFund type (1: Deposit; 3: Withdrawal; 20: Withdrawal fee; 21: Withdrawal refund; 22: Withdrawal failure-refund; 23: Withdrawal fee-refund)
type_descstringFund type description
currencystringCurrency
amountdoubleAmount
business_datestringBusiness date
completed_statusboolWhether completed
created_atlongCreation timestamp
updated_atlongUpdate timestamp

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)

res = trade_client.get_funding_history()
print(res)

Return Example

        id           ref_id  type type_desc currency   amount business_date  completed_status     updated_at     created_at
0  3000000               26     1    Deposit      USD   484.88    2017/08/24              True  1503574430000  1503574430000
1  3000001              123     1    Deposit      USD  2000.00    2017/12/15              True  1513308908000  1513308908000

get_fund_details Get Fund Details

TradeClient.get_fund_details(self, seg_types, account=None, fund_type=None, currency=None, start=0, limit=None, start_date=None, end_date=None, secret_key=None, lang=None):

Description

Get fund details

Parameters

ParameterTypeRequiredDescription
seg_typeslist[str]YesAccount segment types, options: SegmentType.SEC for securities; SegmentType.FUT for futures, can be imported from tigeropen.common.consts.SegmentType. Available values: 'SEC', 'FUT', 'FUND'
accountstrNoAccount ID, if not provided, uses default account. Only supports comprehensive accounts
fund_typeintNoFund type, including: ALL (all), DEPOSIT_WITHDRAW (deposits/withdrawals), TRADE (trading), FEE (fees), FUNDS_TRANSFER (fund transfers), FOREX (currency exchange), CORPORATE_ACTION (corporate actions), ACTIVITY_AWARD (activities), OTHER (others). Default ALL
currencyCurrencyNoCurrency, including USD/HKD/CNH etc., can be imported from tigeropen.common.consts.Currency
startintNoStarting sequence number, starts from 0. For example, if each page has limit 50, and the first two pages returned 100 records, then for the 3rd page, start should be 100, continuing from the 101st record
limitintNoMaximum number of records to return, default 50, maximum 100
start_datestrNoStart date, format 'yyyy-MM-dd'
end_datestrNoEnd date, format 'yyyy-MM-dd'
secret_keystrNoInstitutional secret key (individual developers don't need to fill this)
langLanguageNoSupported language, can use enumeration constants provided in tigeropen.common.consts.Language, such as Language.zh_CN, default is Language.en_US, see enumeration parameter section

Returns pandas.DataFrame with the following fields:

FieldTypeDescription
idintRecord ID
descstrDescription
currencystrCurrency
seg_typestrSegmentType
typestrFund type
amountfloatAmount
business_datestrTiger-defined business date, all fund changes for the same trading day across all markets will be recorded under the same business date
updated_atintTransaction update timestamp
pageintCurrent page number
limitintRecords per page
item_countintTotal record count
page_countintTotal page count
timestampintTimestamp
contract_namestrContract name

Example

from tigeropen.trade.trade_client import TradeClient
from tigeropen.common.consts import SecurityType, Currency, Market
from tigeropen.tiger_open_config import TigerOpenClientConfig
client_config = TigerOpenClientConfig(props_path='/path/to/your/properties/file/')

trade_client = TradeClient(client_config)
result = trade_client.get_fund_details(
	seg_types=[SegmentType.SEC, SegmentType.FUT],
	start= 0,
	limit = 50,
	start_date='2025-03-28',
	end_date='2025-04-04',
	fund_type='ALL',
	# currency = Currency.USD,
	# lang = Language.en_US,
)
print(result)


# Paginated retrieval of all data
start = 0
limit = 50
final_result = pd.DataFrame()
while True:
    res = trade_client.get_fund_details(seg_types=[SegmentType.SEC, SegmentType.FUT], start=start, limit=limit,start_date='2025-01-01', end_date='2025-05-01')
    if res.empty:
        break
    start += limit
    final_result = pd.concat([final_result, res], ignore_index=True)
print(final_result)
	

Return Example

                  id currency          type               desc contract_name seg_type  amount business_date     updated_at  page  limit  item_count  page_count      timestamp
0  24924145889681231      USD  Corporate Action Fee  VFS-DIVIDEND                    SEC   -0.10    2025-04-04  1743762173000     1     50           8           1  1745581047814
1  24924145889681229      USD       Dividend  VFS-DIVIDEND                    SEC    0.10    2025-04-04  1743762173000     1     50           8           1  1745581047814
2  24924145889681217      USD  Corporate Action Fee  VFS-DIVIDEND                    SEC    0.09    2025-04-04  1743762171000     1     50           8           1  1745581047814
3  24924145889681215      USD      Dividend Tax  VFS-DIVIDEND                    SEC    0.01    2025-04-04  1743762171000     1     50           8           1  1745581047814
4  24924145889681213      USD       Dividend  VFS-DIVIDEND                    SEC   -0.10    2025-04-04  1743762171000     1     50           8           1  1745581047814
5  24924145889678880      USD  Corporate Action Fee  VFS-DIVIDEND                    SEC   -0.09    2025-03-28  1743392460000     1     50           8           1  1745581047814
6  24924145889678878      USD      Dividend Tax  VFS-DIVIDEND                    SEC   -0.01    2025-03-28  1743392460000     1     50           8           1  1745581047814
7  24924145889678876      USD       Dividend  VFS-DIVIDEND                    SEC    0.10    2025-03-28  1743392460000     1     50           8           1  1745581047814