Account Changes

About 6 min

The following are all asynchronous APIs, you need to specify a method to respond to the returned result

push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'))

Subscribe asset change

Subscribe method

PushClient.subscribe_asset(account=None)

Cancel method

PushClient.unsubscribe_asset()

Parameters

Parameter nametypedescription
accountstraccount id to subscribe to, or all associated accounts if not passed

Return

Need to use PushClient.asset_changed to return the result of the response. The return result is tigeropen.push.pb.AssetData_pb2.AssetData object

Callback Data Field Meaning
Asset Change Callback

FieldTypeDescription
accountstrmoney account number
currencystrCurrency. USD US dollar, HKD Hong Kong dollar
segTypestrSegmentation by trading species. s for equities, c for futures
availableFundsfloatavailable funds, overnight residual liquidity
excessLiquidityfloatcurrent residual liquidity
netLiquidationfloattotal assets (net liquidation value). Total equity is the sum of the net liquidation cash balance and the total market value of the securities in our account
equityWithLoanfloatcontains the total equity of the loan value. Equals Total Equity - U.S. Equity Options
buyingPowerfloatpurchasing power. Only applicable to equity varieties, i.e. meaningful when segment is S
cashBalancefloatCash amount. The sum of the current cash balance in all currencies
grossPositionValuefloatthe total value of the security
initMarginReqfloatinitial margin
maintMarginReqfloatmaintenance margin
timestampinttimestamp

Example

from tigeropen.push.pb.AssetData_pb2 import AssetData
from tigeropen.push.push_client import PushClient
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')

protocol, host, port = client_config.socket_host_port
push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'), use_protobuf=True)

def on_asset_changed(frame: AssetData):
    """"""
    print(f'asset change. {frame}')
    print(frame.availableFunds)
    print(frame.grossPositionValue)

push_client.asset_changed = on_asset_changed
push_client.connect(client_config.tiger_id, client_config.private_key)

push_client.subscribe_asset(account=client_config.account)
push_client.unsubscribe_asset()

Callback data example

account: "111111"
currency: "USD"
segType: "S"
availableFunds: 1593.1191893
excessLiquidity: 1730.5666908
netLiquidation: 2856.1016998
equityWithLoan: 2858.1016998
buyingPower: 6372.4767571
cashBalance: 484.1516697
grossPositionValue: 2373.95003
initMarginReq: 1264.9825105
maintMarginReq: 1127.535009
timestamp: 1677745420121

Subscribe Position change

Subscribe method

PushClient.subscribe_position(account=None)

Cancel method

PushClient.unsubscribe_position()

Parameters

Parameter nametypedescription
accountstrthe account id to subscribe to, or all associated accounts if not passed

Examples

from tigeropen.push.pb.PositionData_pb2 import PositionData
from tigeropen.push.push_client import PushClient
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')

protocol, host, port = client_config.socket_host_port
push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'), use_protobuf=True)

# Define the callback method
def on_position_changed(frame: PositionData).
    print(f'position change. {frame}')
    # Position underlying
    print(frame.symbol)
    # The cost of the position
    print(frame.averageCost)
    
# Bind callback method
push_client.position_changed = on_position_changed
# Connect
push_client.connect(client_config.tiger_id, client_config.private_key)

# Subscribe to position changes
PushClient.subscribe_position(account=client_config.account)
# Unsubscribe from position changes
PushClient.unsubscribe_position()

return
Need to use PushClient.position_changed to respond to the returned result with data type tigeropen.push.pb.PositionData_pb2.PositionData . The fields in the list item can be cross-referenced to position in [Position](/en/python/appendix1/ object.md#position-position) object.

FieldTypeDescription
accountstrmoney account number
symbolstrThe symbol of the underlying position, such as 'AAPL', '00700', 'ES', 'CN'
expirystrOnly options, warrants, CBBCs are supported
strikestronly supports options, warrants, CBBCs
rightstrOnly options, warrants, CBBCs are supported
identifierstrThe identifier of the underlying. The identifier for stocks is the same as the symbol. For futures, it will have the contract month, e.g. 'CN2201'
multiplierintthe number of lots, futures, options, warrants, CBBC only
marketstrmarket. US, HK
currencystrcurrency. USD, HKD
segTypestrClassification by trading species. s for stocks, c for futures
secTypestrSTK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
positionintNumber of Positions
positionScaleintOffset of position size
averageCostfloatThe average price of a position
latestPricefloatthe current price of the underlying
marketValuefloatthe market value of the position
unrealizedPnlfloatP&L of the position
namestrthe name of the underlying
timestampinttimestamp

Callback data example Stock position change push

account: "1111111"
symbol: "BILI"
identifier: "BILI"
multiplier: 1
market: "US"
currency: "USD"
segType: "S"
secType: "STK"
position: 100
averageCost: 80
latestPrice: 19.83
marketValue: 1983
unrealizedPnl: -6017
timestamp: 1677745420121

Subscribe Order Status Change

Subscribe method

PushClient.subscribe_order(account=None)

Cancel method

PushClient.unsubscribe_order()

Parameters

Parameter nametypedescription
accountstrthe account id to subscribe to, or all associated accounts if not passed

Example

from tigeropen.push.pb.OrderStatusData_pb2 import OrderStatusData
from tigeropen.push.push_client import PushClient
from tigeropen.tiger_open_config import get_client_config
from tigeropen.common.consts import OrderStatus
from tigeropen.common.util.order_utils import get_order_status
client_config = get_client_config(private_key_path='private key path', tiger_id='your tiger id', account='your account')

protocol, host, port = client_config.socket_host_port
push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'), use_protobuf=True)

# Define the callback method
def on_order_changed(frame: OrderStatusData):
    print(f'order changed: {frame}')
    print(f'order status: {frame.status}')
    # convert status value to Enum
    status_enum = OrderStatus[frame.status]
    # or
    # status_enum = get_order_status(frame.status)
    
# Binding callback methods
push_client.order_changed = on_order_changed
# Connect
push_client.connect(client_config.tiger_id, client_config.private_key)

# Subscribe to order changes
PushClient.subscribe_order(account=client_config.account)
# Unsubscribe from order changes
PushClient.unsubscribe_order()

return
Need to use PushClient.order_changed response to return the results, data type tigeropen.push.pb.OrderStatusData_pb2.OrderStatusData

The meaning of the fields in the return result can be cross-referenced to Order in [Order](/en/python/appendix1/object.md#order -order) object

FieldTypeDescription
idintorder number
accountstrmoney account number
symbolstrThe symbol of the underlying position, such as 'AAPL', '00700', 'ES', 'CN'
expirystrOnly options, warrants, CBBCs are supported
strikestronly supports options, warrants, CBBCs
rightstrOnly options, warrants, CBBCs are supported
identifierstrThe identifier of the underlying. The identifier for stocks is the same as the symbol. For futures, it will have the contract month, e.g. 'CN2201'
multiplierintthe number of lots, futures, options, warrants, CBBC only
actionstrbuy and sell direction. BUY means buy, SELL means sell. market
marketstrmarket. US, HK
currencystrcurrency. USD US dollar, HKD Hong Kong dollar
segTypestrClassification by trading species. s means stock, c means futures
secTypestrSTK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
orderTypestrorder type.' MKT' Market Order / 'LMT' Limit Order / 'STP' Stop Loss Order / 'STP_LMT' Stop Loss Limit Order / 'TRAIL' Trailing Stop Order
isLongbooleanwhether the position is long
totalQuantityintthe number of orders placed
totalQuantityScaleintOffset of the number of orders placed, e.g. totalQuantity=111, totalQuantityScale=2, then true totalQuantity=111*10^(-2)=1.11
filledQuantityinttotalQuantity of transactions (if the order is divided into multiple transactions, filledQuantity is the cumulative total number of transactions)
filledQuantityScaleinttotal number of transactions offset
avgFillPricefloatthe average price of the transaction
limitPricefloatlimit order price
stopPricefloatstop price
realizedPnlfloatrealized profit/loss (only consolidated accounts have this field)
statusstrorderStatus
replaceStatusstr[order change status](/en/python/appendix2/overview.md#order change status)
cancelStatusstr[order withdrawal status](/en/python/appendix2/overview.md#order withdrawal status)
outsideRthboolwhether to allow pre and after hours trading, only for US stocks
canModifyboolwhether can modify
canCancelboolwhether it can be cancelled
liquidationboolwhether the order is closed
namestrthe name of the underlying
sourcestrThe source of the order (from 'OpenApi', or other)
errorMsgstrerror message
attrDescstrorder description information
commissionAndFeefloatcommission fee total
openTimeinttime of the order
timestampintorder status last update time
userMarkstrremark
totalCashAmountfloattotal cash amount
filledCashAmountfloatfilled cash amount
attrListlist[str]Order attribute list, The meanings of each attribute are as follows: LIQUIDATION, FRACTIONAL_SHARE Smashed stock order (non-whole shares), EXERCISE exercise, EXPIRE expiration, ASSIGNMENT passive exercise allocation, CASH_SETTLE cash delivery, KNOCK_OUT knock out, RECALL recall order, ODD_LOT Smashed stock order (non-whole shares), DEALER trader order, GREY_MARKET Hong Kong stock dark order, BLOCK_TRADE bulk trading, ATTACHED_ORDER additional order, OCA OCA order
timeInForcestrOrder validity period. DAY: Valid for the current trading day, GTC: Good 'Til Cancelled (valid until manually canceled), GTD: Good 'Til Date (valid until a specified date).

Callback data example Stock order push example


Example of futures order push

{"id": "28875370355884032", "account": "736845", "symbol": "CL", "identifier": "CL2312", "multiplier":1000, "action": "BUY".
"market": "US", "currency": "USD", "segment": "C", "secType": "FUT", "orderType": "LMT", "isLong":true, "totalQuantity": "1".
"filledQuantity": "1", "avgFillPrice":77.76, "limitPrice":77.76, "status": "Filled", "outsideRth":true, "name": "WTI Crude Oil 2312".
"source": "android", "commissionAndFee":4.0, "openTime": "1669200792000", "timestamp": "1669200782221"}

Order execution details subscription and cancellation

Subscribe method

PushClient.subscribe_transaction(account=client_config.account)

Cancel method

PushClient.unsubscribe_transaction()

Parameters

Parameter nametypedescription
accountstrthe account id to subscribe to, or all associated accounts if not passed

Example

from tigeropen.push.pb.OrderTransactionData_pb2 import OrderTransactionData
from tigeropen.push.push_client import PushClient
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')

protocol, host, port = client_config.socket_host_port
push_client = PushClient(host, port, use_ssl=(protocol == 'ssl'), use_protobuf=True)

# Define callback methods
def on_transaction_changed(frame: OrderTransactionData).
    print(f'transaction changed: {frame}')
    
# Bind the callback method
push_client.transaction_changed = on_transaction_changed
# Connect
push_client.connect(client_config.tiger_id, client_config.private_key)

# Subscribe
PushClient.subscribe_transaction(account=client_config.account)
# unsubscribe
PushClient.unsubscribe_transaction()

return
Need to use PushClient.transaction_changed response to return the results, data type tigeropen.push.pb.OrderTransactionData_pb2.OrderTransactionData
The meaning of the fields in the return result can be cross-referenced to get_transactions in [Transaction](/en/python/ appendix1/object.md#transaction-transactional-records)

fieldtypedescription
idintorderExecutionId
orderIdintorder number
accountstrfund account number
symbolstrThe code of the underlying position, e.g. 'AAPL', '00700', 'ES', 'CN'
identifierstrThe identifier of the underlying. The identifier of the stock is the same as the symbol. For futures, it will have the contract month, e.g. 'CN2201'
multiplierintnumber per lot (proprietary to options, futures)
BUY means BUY, SELL means SELL.market
marketstrmarket, US, HK
currencystrCurrency. USD, HKD
segTypestrSegmentation by trading instrument. s means stock, c means futures
secTypestrTrading variety, underlying type. STK denotes stock, FUT denotes futures.
filledPricefloatprice
The price of a stock is the same as the price of a futures contract.
createTimeintcreate time
updateTimeintupdate time
transactTimeinttransaction time
timestampinttimestamp

Callback data example


id: 2999543887211111111
orderId: 29995438111111111
account: "11111111"
symbol: "ZC"
identifier: "ZC2305"
multiplier: 5000
action: "BUY"
market: "US"
currency: "USD"
segType: "C"
secType: "FUT"
filledPrice: 6.385
filledQuantity: 1
createTime: 1677746237303
updateTime: 1677746237303
transactTime: 1677746237289
timestamp: 1677746237313

Last update: