Account Streaming Updates
Subscribe to streaming updates for assets, positions, orders, and executions with the Java SDK.
Subscribe to account updates (subscribe)
subscribe)Description
The Trading API can stream changes to assets, positions, orders, and executions. These updates are asynchronous. Implement ApiComposeCallback to process subscription results and incoming data.
Parameters (subscription topics)
| Parameter | Type | Required | Description |
|---|---|---|---|
| account | string | No | Trading account to subscribe to. If omitted, the subscription covers all trading accounts, including paper trading accounts. |
| subject | Subject | Yes | Subscription topic |
Subject identifies the subscription topic:
OrderStatussends updates forSubmitted,Cancelled,Inactive, andFilled. Intermediate states do not generate updates.Assetsends a full asset snapshot every five seconds by default. Live and paper trading accounts use the same interval.Positionsends a full position snapshot every five seconds by default. Live and paper trading accounts use the same interval.OrderTransactionsends execution details.
By default, the client receives updates for every trading account, including paper trading accounts. Use the returned account field to identify the account, or call subscribe(String account, Subject subject) to subscribe to one account.
Caution
Subscribing to any one of these topics enables all four topics. Canceling any one topic cancels all four subscriptions.
Response
| Field | Type | Description |
|---|---|---|
| id | string | ID generated locally by the SDK during subscription request, incrementally sequenced. Returns request ID and subscription success result in the subscribeEnd(int id, String subject, String result) callback method |
Callback fields
Asset Change Callback
| Field | Type | Description |
|---|---|---|
| account | String | Funding account |
| currency | String | Currency. USD for US dollars, HKD for Hong Kong dollars |
| segType | String | Classification by trading type. S for stocks, C for futures, D for cryptocurrencies, F for funds, CONSOLIDATED for the aggregation of stocks and funds. |
| availableFunds | double | Available funds, overnight remaining liquidity |
| excessLiquidity | double | Current remaining liquidity |
| netLiquidation | double | Total assets (net liquidation value). Total assets are the sum of net liquidation cash balance and total securities market value |
| equityWithLoan | double | Total equity with loan value. Equals total assets - US stock options |
| buyingPower | double | Buying power. Only applicable to stock types, meaningful when segment is S |
| cashBalance | double | Cash amount. Sum of current cash balances in all currencies |
| grossPositionValue | double | Total securities value |
| initMarginReq | double | Initial margin requirement |
| maintMarginReq | double | Maintenance margin requirement |
| timestamp | long | Timestamp |
Position Change Callback
| Field | Type | Description |
|---|---|---|
| account | String | Funding account |
| symbol | String | Position symbol code, e.g., 'AAPL', '00700', 'ES', 'CN' |
| expiry | String | For options, warrants, CBBC only |
| strike | String | For options, warrants, CBBC only |
| right | String | For options, warrants, CBBC only |
| identifier | String | Symbol identifier. For stocks, identifier is same as symbol. For futures, includes contract month, e.g., 'CN2201' |
| multiplier | int | Quantity per lot, for futures, options, warrants, CBBC only |
| market | String | Market. US, HK |
| currency | String | Currency. USD for US dollars, HKD for Hong Kong dollars |
| segType | String | Classification by trading type. S for stocks, C for futures, D for cryptocurrencies, F for funds, CONSOLIDATED for the aggregation of stocks and funds. |
| secType | String | STK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options |
| positionQty | double | Position quantity |
| salableQty | double | Sellable quantity |
| position | long | Position quantity (deprecated) |
| positionScale | int | Position quantity offset (deprecated), e.g., if position value is 2135 and positionScale is 2, actual position is 21.35 |
| saleable | long | A-share sellable quantity (deprecated) |
| averageCost | double | Average cost of position |
| latestPrice | double | Current price of underlying |
| marketValue | double | Market value of position |
| unrealizedPnl | double | Unrealized P&L of position |
| name | String | Underlying name |
| timestamp | long | Timestamp |
Order Change Callback
| Field | Type | Description |
|---|---|---|
| id | long | Order ID |
| account | String | Funding account |
| symbol | String | Position symbol code, e.g., 'AAPL', '00700', 'ES', 'CN' |
| expiry | String | For options, warrants, CBBC only |
| strike | String | For options, warrants, CBBC only |
| right | String | For options, warrants, CBBC only |
| identifier | String | Symbol identifier. For stocks, identifier is same as symbol. For futures, includes contract month, e.g., 'CN2201' |
| multiplier | int | Quantity per lot, for futures, options, warrants, CBBC only |
| action | String | Buy/sell direction. BUY for buy, SELL for sell |
| market | String | Market. US, HK |
| currency | String | Currency. USD for US dollars, HKD for Hong Kong dollars |
| segType | String | Classification by trading type. S for stocks, C for futures |
| secType | String | STK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options |
| orderType | String | Order type. 'MKT' market order/'LMT' limit order/'STP' stop order/'STP_LMT' stop limit order/'TRAIL' trailing stop order |
| isLong | boolean | Whether the position is long |
| totalQuantity | long | Order quantity |
| totalQuantityScale | int | Order quantity offset, e.g., if totalQuantity=111, totalQuantityScale=2, then actual totalQuantity=111*10^(-2)=1.11 |
| filledQuantity | long | Total filled quantity (for orders filled in multiple transactions, filledQuantity is cumulative total filled) |
| filledQuantityScale | int | Total filled quantity offset |
| avgFillPrice | double | Average fill price |
| limitPrice | double | Limit order price |
| stopPrice | double | Stop price |
| realizedPnl | double | Realized P&L (only for prime accounts) |
| status | String | Order status |
| replaceStatus | String | Order modify status |
| cancelStatus | String | Order cancel status |
| outsideRth | boolean | Whether to allow pre-market and after-hours trading, applicable to US stocks only |
| canModify | boolean | Whether the order can be modified |
| canCancel | boolean | Whether the order can be canceled |
| liquidation | boolean | Whether this is a liquidation order |
| name | String | Underlying name |
| source | String | Order source (from 'OpenApi', or other) |
| errorMsg | String | Error message |
| attrDesc | String | Order description information |
| commissionAndFee | float | Total commission and fees |
| openTime | long | Order time |
| timestamp | long | Last update time of order status |
| userMark | String | Custom annotation information |
| totalCashAmount | double | Total order amount (for cash amount orders only) |
| filledCashAmount | double | Filled amount (for cash amount orders only) |
| attrList | List<String> | Order attribute list, meanings of attributes: LIQUIDATION forced liquidation, FRACTIONAL_SHARE fractional shares order, EXERCISE exercise, EXPIRE expiry, ASSIGNMENT assignment, CASH_SETTLE cash settlement, KNOCK_OUT knock out, RECALL recall order, ODD_LOT odd lot order, DEALER dealer order, GREY_MARKET HK grey market order, BLOCK_TRADE block trade, ATTACHED_ORDER attached order, OCA OCA order |
| timeInForce | string | Order validity time. DAY: valid for day, GTC: good till canceled, GTD: good till date |
Order Transaction Detail Report Callback
| Field | Type | Description |
|---|---|---|
| id | long | Order execution ID |
| orderId | long | Order ID |
| account | String | Funding account |
| symbol | String | Position symbol code, e.g., 'AAPL', '00700', 'ES', 'CN' |
| identifier | String | Symbol identifier. For stocks, identifier is same as symbol. For futures, includes contract month, e.g., 'CN2201' |
| multiplier | int | Quantity per lot (options, futures specific) |
| action | String | Buy/sell direction. BUY for buy, SELL for sell |
| market | String | Market. US, HK |
| currency | String | Currency. USD for US dollars, HKD for Hong Kong dollars |
| segType | String | Classification by trading type. S for stocks, C for futures |
| secType | String | Trading type, underlying type. STK for stocks, FUT for futures |
| filledPrice | double | Price |
| filledQuantity | long | Filled quantity |
| createTime | long | Create time |
| updateTime | long | Update time |
| transactTime | long | Transaction time |
| timestamp | long | Timestamp |
Callback Interface
Implement corresponding methods of ApiComposeCallback
/**
* Callback interface:
* Invoke different callback methods for different subjects
*/
void assetChange(AssetData data) //Corresponds to subject = Asset
void positionChange(PositionData data) //Corresponds to subject = Position
void orderStatusChange(OrderStatusData data) //Corresponds to subject = OrderStatus
void orderTransactionChange(OrderTransactionData data) //Corresponds to subject = OrderTransactionExample
Implementing callback interface example
package com.tigerbrokers.stock.openapi.demo;
import com.tigerbrokers.stock.openapi.client.socket.ApiComposeCallback;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.AssetData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.OrderStatusData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.OrderTransactionData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.PositionData;
import com.tigerbrokers.stock.openapi.client.util.ApiLogger;
import com.tigerbrokers.stock.openapi.client.util.ProtoMessageUtil;
public class DefaultApiComposeCallback implements ApiComposeCallback {
@Override
public void orderStatusChange(OrderStatusData data) {
ApiLogger.info("orderStatusChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void orderTransactionChange(OrderTransactionData data) {
ApiLogger.info("orderTransactionChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void positionChange(PositionData data) {
ApiLogger.info("positionChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void assetChange(AssetData data) {
ApiLogger.info("assetChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void subscribeEnd(int id, String subject, String result) {
ApiLogger.info("subscribe " + subject + " end. id:" + id + ", " + result);
}
@Override
public void cancelSubscribeEnd(int id, String subject, String result) {
ApiLogger.info("cancel subscribe " + subject + " end. id:" + id + ", " + result);
}
}Performing subscription
public class WebSocketDemo {
//When actually subscribing, need to fill in tigerId and privateKey, and implement callback interface
private static ClientConfig clientConfig = ClientConfig.DEFAULT_CONFIG;
private static WebSocketClient client;
static {
//Path for configuration files tiger_openapi_config.properties and tiger_openapi_token.properties exported from developer information page
clientConfig.configFilePath = "your_config_directory_path";
// clientConfig.secretKey = "xxxxxx";// institutional trader private key
// Original usage (not using tiger_openapi_config.properties file), must configure tigerId, defaultAccount, privateKey. If configFilePath is also configured, properties file configuration takes priority
// clientConfig.tigerId = "your tiger id";
// clientConfig.defaultAccount = "your account";
// clientConfig.privateKey = ConfigUtil.readPrivateKey("/Users/tiger/rsa_private_key_pkcs8.pem");
client = WebSocketClient.getInstance().clientConfig(clientConfig).apiComposeCallback(new DefaultApiComposeCallback());
}
public static void subscribe() {
//Create connection
client.connect();
//Subscribe to orders/assets/positions/order execution reports
client.subscribe(Subject.OrderStatus);
client.subscribe(Subject.Asset);
client.subscribe(Subject.Position);
client.subscribe(Subject.OrderTransaction);
//Wait
TimeUnit.SECONDS.sleep(60000);
// Cancel subscription
client.cancelSubscribe(Subject.Asset);
client.cancelSubscribe(Subject.Position);
client.cancelSubscribe(Subject.OrderStatus);
client.cancelSubscribe(Subject.OrderTransaction);
//During non-trading hours, it's recommended to close the connection. Calling disconnect() will automatically cancel all previous subscription information
//client.disconnect();
}
}Example Responses
assetChange:
{
"account": "13810712",
"currency": "USD",
"segment": "S",
"availableFunds": 2285040.5475322,
"excessLiquidity": 2284942.0475322,
"netLiquidation": 2285529.3735322,
"equityWithLoan": 2285418.2835322,
"buyingPower": 9140162.1901287,
"cashBalance": 2284275.2435322,
"grossPositionValue": 1143.04,
"initMarginReq": 377.736,
"maintMarginReq": 476.236,
"timestamp": "1669888806020"
}positionChange:
{
"account": "13810712",
"symbol": "AAPL",
"identifier": "AAPL",
"multiplier": 1,
"market": "US",
"currency": "USD",
"segment": "S",
"secType": "STK",
"position": "4",
"averageCost": 75.0,
"latestPrice": 147.23,
"marketValue": 588.92,
"unrealizedPnl": 288.92,
"timestamp": "1669888802018"
}orderStatusChange:
{
"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"
}orderTransactionChange:
{
"id": "28875370482237440",
"orderId": "28875370355884032",
"account": "736845",
"symbol": "CL",
"identifier": "CL2312",
"multiplier": 1000,
"action": "BUY",
"market": "US",
"currency": "USD",
"segment": "C",
"secType": "FUT",
"filledPrice": 77.76,
"filledQuantity": "1",
"createTime": "1669200793664",
"updateTime": "1669200793664",
"transactTime": "1669200793593",
"timestamp": "1669200782233"
}For order status notification data with multiple fills, filledQuantity represents the cumulative total filled quantity. The data is returned sequentially as follows:
{
"id": 28557131062709999,
"symbol": "CN",
"market": "SI",
"currency": "USD",
"secType": "FUT",
"action": "BUY",
"isLong": true,
"totalQuantity": 9,
"totalQuantityScale": 0,
"filledQuantity": 1,
"filledQuantityScale": 0,
"orderType": "MKT",
"avgFillPrice": 11824.0,
"status": "PendingSubmit",
"subStatusList": [],
"subStatusDescList": [],
"realizedPnl": 0.0,
"commissionAndFee": 3.09,
"gst": 0.22,
"replaceStatus": "NONE",
"cancelStatus": "NONE",
"source": "OpenApi",
"canModify": true,
"canCancel": true,
"multiplier": 1.0,
"stockId": 15433673,
"attr": 0,
"type": "orderstatus",
"outsideRth": false,
"limitPrice": 0.0,
"errorMsg": "",
"openTime": 1666772819000,
"updateTime": 1666772819000,
"latestTime": 1666772819000,
"userMark": "",
"name": "FTSE China A50 Index - Nov 2022",
"identifier": "CN2211",
"account": "1234567",
"timestamp": 1666772819780,
"segment": "C"
}
{id=28557131062709999, symbol=CN, market=SI, currency=USD, secType=FUT, action=BUY, isLong=true, totalQuantity=9, totalQuantityScale=0, filledQuantity=3, filledQuantityScale=0, orderType=MKT, avgFillPrice=11824.0, status=PendingSubmit, subStatusList=[], subStatusDescList=[], realizedPnl=0.0, commissionAndFee=9.27, gst=0.65, replaceStatus=NONE, cancelStatus=NONE, source=OpenApi, canModify=true, canCancel=true, multiplier=1.0, stockId=15433673, attr=0, type=orderstatus, outsideRth=false, limitPrice=0.0, errorMsg=, openTime=1666772819000, updateTime=1666772819000, latestTime=1666772819000, userMark=, name=FTSE China A50 Index - Nov 2022, identifier=CN2211, account=1234567, timestamp=1666772819797, segment=C}
{id=28557131062709999, symbol=CN, market=SI, currency=USD, secType=FUT, action=BUY, isLong=true, totalQuantity=9, totalQuantityScale=0, filledQuantity=8, filledQuantityScale=0, orderType=MKT, avgFillPrice=11824.625, status=PendingSubmit, subStatusList=[], subStatusDescList=[], realizedPnl=0.0, commissionAndFee=24.72, gst=1.73, replaceStatus=NONE, cancelStatus=NONE, source=OpenApi, canModify=true, canCancel=true, multiplier=1.0, stockId=15433673, attr=0, type=orderstatus, outsideRth=false, limitPrice=0.0, errorMsg=, openTime=1666772819000, updateTime=1666772819000, latestTime=1666772819000, userMark=, name=FTSE China A50 Index - Nov 2022, identifier=CN2211, account=1234567, timestamp=1666772819808, segment=C}
{id=28557131062709999, symbol=CN, market=SI, currency=USD, secType=FUT, action=BUY, isLong=true, totalQuantity=9, totalQuantityScale=0, filledQuantity=9, filledQuantityScale=0, orderType=MKT, avgFillPrice=11824.6666666667, status=Filled, subStatusList=[], subStatusDescList=[], realizedPnl=0.0, commissionAndFee=27.81, gst=1.95, replaceStatus=NONE, cancelStatus=NONE, source=OpenApi, canModify=false, canCancel=false, multiplier=1.0, stockId=15433673, attr=0, type=orderstatus, outsideRth=false, limitPrice=0.0, errorMsg=, openTime=1666772819000, updateTime=1666772819000, latestTime=1666772819000, userMark=, name=FTSE China A50 Index - Nov 2022, identifier=CN2211, account=1234567, timestamp=1666772819816, segment=C}String cancelSubscribe(Subject subject) Cancel Subscription
Description
Cancel the account-update subscription.
Input Parameters (Unsubscribe Topics)
| Parameter | Type | Required | Description |
|---|---|---|---|
| subject | com.tigerbrokers.stock.openapi.client.struct.enums.Subject | Yes | Subscription topic |
Subject is the topic to cancel subscription for, which mainly includes four types: OrderStatus (orders), Asset (assets), Position (positions), OrderTransaction (order execution). The meanings are the same as subscription topics.
NOTE
Cancelling any one subscription will cancel all four subscriptions: OrderStatus (orders), Asset (assets), Position (positions), and OrderTransaction (order execution).
Example
// Cancel subscription
client.cancelSubscribe(Subject.Asset);
client.cancelSubscribe(Subject.Position);
client.cancelSubscribe(Subject.OrderStatus);
client.cancelSubscribe(Subject.OrderTransaction);Updated 2 days ago
