Account Streaming Updates

Subscribe to streaming updates for assets, positions, orders, and executions with the Java SDK.

Subscribe to account updates (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)

ParameterTypeRequiredDescription
accountstringNoTrading account to subscribe to. If omitted, the subscription covers all trading accounts, including paper trading accounts.
subjectSubjectYesSubscription topic

Subject identifies the subscription topic:

  • OrderStatus sends updates for Submitted, Cancelled, Inactive, and Filled. Intermediate states do not generate updates.
  • Asset sends a full asset snapshot every five seconds by default. Live and paper trading accounts use the same interval.
  • Position sends a full position snapshot every five seconds by default. Live and paper trading accounts use the same interval.
  • OrderTransaction sends 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

FieldTypeDescription
idstringID 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

FieldTypeDescription
accountStringFunding account
currencyStringCurrency. USD for US dollars, HKD for Hong Kong dollars
segTypeStringClassification by trading type. S for stocks, C for futures, D for cryptocurrencies, F for funds, CONSOLIDATED for the aggregation of stocks and funds.
availableFundsdoubleAvailable funds, overnight remaining liquidity
excessLiquiditydoubleCurrent remaining liquidity
netLiquidationdoubleTotal assets (net liquidation value). Total assets are the sum of net liquidation cash balance and total securities market value
equityWithLoandoubleTotal equity with loan value. Equals total assets - US stock options
buyingPowerdoubleBuying power. Only applicable to stock types, meaningful when segment is S
cashBalancedoubleCash amount. Sum of current cash balances in all currencies
grossPositionValuedoubleTotal securities value
initMarginReqdoubleInitial margin requirement
maintMarginReqdoubleMaintenance margin requirement
timestamplongTimestamp

Position Change Callback

FieldTypeDescription
accountStringFunding account
symbolStringPosition symbol code, e.g., 'AAPL', '00700', 'ES', 'CN'
expiryStringFor options, warrants, CBBC only
strikeStringFor options, warrants, CBBC only
rightStringFor options, warrants, CBBC only
identifierStringSymbol identifier. For stocks, identifier is same as symbol. For futures, includes contract month, e.g., 'CN2201'
multiplierintQuantity per lot, for futures, options, warrants, CBBC only
marketStringMarket. US, HK
currencyStringCurrency. USD for US dollars, HKD for Hong Kong dollars
segTypeStringClassification by trading type. S for stocks, C for futures, D for cryptocurrencies, F for funds, CONSOLIDATED for the aggregation of stocks and funds.
secTypeStringSTK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
positionQtydoublePosition quantity
salableQtydoubleSellable quantity
positionlongPosition quantity (deprecated)
positionScaleintPosition quantity offset (deprecated), e.g., if position value is 2135 and positionScale is 2, actual position is 21.35
saleablelongA-share sellable quantity (deprecated)
averageCostdoubleAverage cost of position
latestPricedoubleCurrent price of underlying
marketValuedoubleMarket value of position
unrealizedPnldoubleUnrealized P&L of position
nameStringUnderlying name
timestamplongTimestamp

Order Change Callback

FieldTypeDescription
idlongOrder ID
accountStringFunding account
symbolStringPosition symbol code, e.g., 'AAPL', '00700', 'ES', 'CN'
expiryStringFor options, warrants, CBBC only
strikeStringFor options, warrants, CBBC only
rightStringFor options, warrants, CBBC only
identifierStringSymbol identifier. For stocks, identifier is same as symbol. For futures, includes contract month, e.g., 'CN2201'
multiplierintQuantity per lot, for futures, options, warrants, CBBC only
actionStringBuy/sell direction. BUY for buy, SELL for sell
marketStringMarket. US, HK
currencyStringCurrency. USD for US dollars, HKD for Hong Kong dollars
segTypeStringClassification by trading type. S for stocks, C for futures
secTypeStringSTK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
orderTypeStringOrder type. 'MKT' market order/'LMT' limit order/'STP' stop order/'STP_LMT' stop limit order/'TRAIL' trailing stop order
isLongbooleanWhether the position is long
totalQuantitylongOrder quantity
totalQuantityScaleintOrder quantity offset, e.g., if totalQuantity=111, totalQuantityScale=2, then actual totalQuantity=111*10^(-2)=1.11
filledQuantitylongTotal filled quantity (for orders filled in multiple transactions, filledQuantity is cumulative total filled)
filledQuantityScaleintTotal filled quantity offset
avgFillPricedoubleAverage fill price
limitPricedoubleLimit order price
stopPricedoubleStop price
realizedPnldoubleRealized P&L (only for prime accounts)
statusStringOrder status
replaceStatusStringOrder modify status
cancelStatusStringOrder cancel status
outsideRthbooleanWhether to allow pre-market and after-hours trading, applicable to US stocks only
canModifybooleanWhether the order can be modified
canCancelbooleanWhether the order can be canceled
liquidationbooleanWhether this is a liquidation order
nameStringUnderlying name
sourceStringOrder source (from 'OpenApi', or other)
errorMsgStringError message
attrDescStringOrder description information
commissionAndFeefloatTotal commission and fees
openTimelongOrder time
timestamplongLast update time of order status
userMarkStringCustom annotation information
totalCashAmountdoubleTotal order amount (for cash amount orders only)
filledCashAmountdoubleFilled amount (for cash amount orders only)
attrListList<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
timeInForcestringOrder validity time. DAY: valid for day, GTC: good till canceled, GTD: good till date

Order Transaction Detail Report Callback

FieldTypeDescription
idlongOrder execution ID
orderIdlongOrder ID
accountStringFunding account
symbolStringPosition symbol code, e.g., 'AAPL', '00700', 'ES', 'CN'
identifierStringSymbol identifier. For stocks, identifier is same as symbol. For futures, includes contract month, e.g., 'CN2201'
multiplierintQuantity per lot (options, futures specific)
actionStringBuy/sell direction. BUY for buy, SELL for sell
marketStringMarket. US, HK
currencyStringCurrency. USD for US dollars, HKD for Hong Kong dollars
segTypeStringClassification by trading type. S for stocks, C for futures
secTypeStringTrading type, underlying type. STK for stocks, FUT for futures
filledPricedoublePrice
filledQuantitylongFilled quantity
createTimelongCreate time
updateTimelongUpdate time
transactTimelongTransaction time
timestamplongTimestamp

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 = OrderTransaction

Example

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)

ParameterTypeRequiredDescription
subjectcom.tigerbrokers.stock.openapi.client.struct.enums.SubjectYesSubscription 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);

Did this page help you?