Account Changes

About 7 min

String subscribe(Subject subject) Subscribe

Description

Besides the APIs that allows you to actively pull your account information data from the server, we offer data streaming services which let the server push relevent data, such as change of total assets, positions, etc., to clients Our push services are implemented with asynchronous functions. Implement the callback functions in ApiComposeCallback, to process the data. The data pushed by the server, See below for a list of specific callback methods.

Argument(Subjects)

ArgumentTypeRequiredDescription
accountstringNoIf the value is null, all accounts will be subscribed, including paper account
subjectSubjectYesSubject

There are 4 types of subjects: OrderStatus, Asset, Position, and OrderTransaction :

  • OrderStatus,the server will push data to a client when their is a change of status of his/her orders. Possible status are: Submitted, Cancelled, Inactive, Filled. There are other status exist, but they will not be pushed.
  • Asset,the server will push data to a client when there is a change in his/her asset.
  • Position, the server will push data to a client when there is a change in his/her positions.
  • OrderTransaction, the server will push data to a client when order is filled.

By default, the data of all accounts will be pushed, including paper account, which can be distinguished by the account of the returned data, or the account can be specified when subscribing using subscribe(String account, Subject subject) method.

CAUTION

Subscribing to any of the above four types of topics will push all four types of topic data, and canceling any one of the four types of topics will cancel the subscription of all four types of topic data.

Return Value

NameTypeDescription
idstringID generated locally when the sdk sends a subscription request, and the sequence is incremented. In the subscribeEnd(int id, String subject, String result) callback method, return the request id and the result of whether the subscription is successful

Pushed Data
Callbacks for change of asset

NameTypeDescription
accountStringuser account
currencyStringcurrency. USD, HKD, etc.
segTypeStringSecurities Category C: (Commodities Futures), S: (Securities Stocks)
availableFundsdoubleavailable funds, overnight liquidity
excessLiquiditydoubleExcess liquidity, used to represent intraday risk value.
netLiquidationdoubleTotal Assets (Net Liquidation Value) - Securities Segment: Cash Value + Stock Value + Stock Option Value - Futures Segment: Cash Value + Mark-to-Market Profit and Loss
equityWithLoandoubleEquity with loan value (asset with loan value) - Securities Segment: Cash Value + Stock Value - Futures Segment: Cash Value - Maintenance Margin
buyingPowerdoubleBuying power. An estimation of how many more dollars you can buy in stock assets. Only apply to stock segment
cashBalancedoubleTotal amount of cash, other currencies will be converted to USD
grossPositionValuedoubleTotal value of securities
initMarginReqdoubleInitial margin requirement
maintMarginReqdoubleMaintenance margin requirement
timestamplongtimestamp

Callbacks for change of positions

NameTypeDescription
accountStringuser account
symbolStringStock ticker symbol, exmaple: 'AAPL', '00700', 'ES', 'CN'
expiryStringfor options, warrant, CBBC
strikeStringfor options, warrant, CBBC
rightStringfor options, warrant, CBBC
identifierStringasset identifier. The identifier of stocks is identical to its symbol. Futures contracts will also includes their month code. Example: 'CN2201'
multiplierintmultiplier for futures, options, warrants and CBBC
marketStringmarket. US, HK, etc.
currencyStringCurrency. USD, HKD, etc.
segTypeStringSecurities Category C: (Commodities Futures), S: (Securities Stocks)
secTypeStringSTK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
positionQtydoubletotal position quantity
salableQtydoublesaleable quantity
positionlongtotal position(Deprecated)
positionScaleinttotal position scale(Deprecated), For example, the position value is 2135, the positionScale is 2, and the actual number of positions is 21.35
saleablelongcan sell quantity(Only supports A-shares in mainland China)(Deprecated)
averageCostdoubleaverage holding cost
latestPricedoublelast price of the asset
marketValuedoublemarket value of the asset
unrealizedPnldoubleunrealized profit and loss
nameStringsymbol name
timestamplongtimestamp

Callbacks for change of order status

NameTypeDescription
idlongunique order id
accountStringuser account
symbolStringStock ticker symbol, exmaple: 'AAPL', '00700', 'ES', 'CN'
expiryStringfor options, warrant, CBBC
strikeStringfor options, warrant, CBBC
rightStringfor options, warrant, CBBC
identifierStringasset identifier. The identifier of stocks is identical to its symbol. Futures contracts will also includes their month code. Example: 'CN2201'
multiplierintmultiplier for futures, options, warrants and CBBC
actionStringBUY or SELL
marketStringmarket. US, HK, etc.
currencyStringCurrency. USD, HKD, etc.
segTypeStringSecurities Category C: (Commodities Futures), S: (Securities Stocks)
secTypeStringSTK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
orderTypeStringOrder Types,'MKT'-Market Order / 'LMT'-Limit Order / 'STP'-Stop Order / 'STP_LMT'-Stop-Limit Order / 'TRAIL'-Trailing Stop Order
isLongbooleanis long
totalQuantitylongOrder's quantity
totalQuantityScaleintThe offset of the order quantity, default is 0. The combination of 'totalQuantity' and 'totalQuantityScale' of odd lot orders represents the actual order quantity. For example, totalQuantity=111 totalQuantityScale=2, then the real quantity=111*10^(-2)=1.11
filledQuantitylongfilled quantity
filledQuantityScaleintfilled quantity scale
avgFillPricedoubleaverage price at which the orders got filled
limitPricedoubleLimit price, required if placing a limit order (inluding LMT and STP_LMT)
stopPricedoubleStop price, required if placing a stop order (inluding STP and STP_LMT)
realizedPnldoublerealized profit and loss
statusStringOrder status
replaceStatusStringOrder replace status
cancelStatusStringOrder cancel status
outsideRthbooleanif trade outside regular trading hours (only applicable to U.S. market)
canModifybooleancan modify
canCancelbooleancan cancel
liquidationbooleanIs it a liquidation order
nameStringsymbol name
sourceStringorder source(from 'OpenApi', or not)
errorMsgStringerror message
attrDescStringorder description
commissionAndFeefloatcommission and fee
openTimelongtimestamp when the order is placed
timestamplonglast update timestamp of order status
userMarkStringCustom Remarks
totalCashAmountdoubleThe total cash amount of the order (only for amount orders)
filledCashAmountdoubleThe filled cash amount of the order (only for amount orders)

Callbacks for transaction of order

NameTypeDescription
idlongtransaction ID
orderIdlongunique order id
accountStringuser account
symbolStringStock ticker symbol, exmaple: 'AAPL', '00700', 'ES', 'CN'
identifierStringasset identifier. The identifier of stocks is identical to its symbol. Futures contracts will also includes their month code. Example: 'CN2201'
multiplierintmultiplier for futures, options, warrants and CBBC
actionStringBUY or SELL
marketStringmarket. US、HK
currencyStringCurrency. USD, HKD, etc.
segTypeStringSecurities Category C: (Commodities Futures), S: (Securities Stocks)
secTypeStringSecurity type. STK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options
filledPricedoublefilled price
filledQuantityLongfilled quantity
createTimelongcreate time
updateTimelongupdate time
transactTimelongtransaction time
timestamplongtimestamp

Callback

Implement the corresponding callback functions in ApiComposeCallback

/** 
* Callbacks: 
* Implement different callback functions according to different subject
*/
void assetChange(AssetData data)  //subject = asset
void positionChange(PositionData data) //subject = position
void orderStatusChange(OrderStatusData data) //subject = orderstatus
void orderTransactionChange(OrderTransactionData data) //subject = OrderTransaction

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);
  }
}

Subscription

public class WebSocketDemo {

//You need to provide your tigerId and privateKey, also you need to implement your own callback function if you want the program to actually run
  private static ClientConfig clientConfig = TigerOpenClientConfig.getDefaultClientConfig();
  private static WebSocketClient client;
  static {
    // The tiger_openapi_config.properties file is stored in your local directory.
    clientConfig.configFilePath = "your local directory";
    // clientConfig.secretKey = "xxxxxx";// institutional trader private key
    client = WebSocketClient.getInstance().clientConfig(clientConfig).apiComposeCallback(new DefaultApiComposeCallback());
  }

  public static void subscribe() {
    //Establish connection
    client.connect();

    //Subscribe to account information
    client.subscribe(Subject.OrderStatus);    
    client.subscribe(Subject.Asset);
    client.subscribe(Subject.Position);
    client.subscribe(Subject.OrderTransaction);

    //Wait to receive the data
    TimeUnit.SECONDS.sleep(60000);
    
    // Cancel subscription
    client.cancelSubscribe(Subject.Asset);
    client.cancelSubscribe(Subject.Position);
    client.cancelSubscribe(Subject.OrderStatus);
    client.cancelSubscribe(Subject.OrderTransaction);
    
    //It's recommended that you disconnect from the server if you are no longer using the data feed
    //client.disconnect();
  }
}

Response Example

// asset change
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"}

// position change
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"}

// order change
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 Oil2312","source":"android","commissionAndFee":4.0,"openTime":"1669200792000","timestamp":"1669200782221"}

// OrderTransaction
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"}

If an order is filled in multiple times, 'filledQuantity' is the cumulative number of transactions, and the returned data is 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 subscription of the selected subject

Argument(Subject)

ArgumentTypeRequiredDescription
subjectcom.tigerbrokers.stock.openapi.client.struct.enums.SubjectYessubject

There are 4 types of subjects: OrderStatus, Asset, Position, and OrderTransaction See subscription for detail

CAUTION

Cancelling any of the four subscriptions, OrderStatus, Asset, Position, and OrderTransaction, will cancel the four subscriptions

Example

// Cancel Subscription
client.cancelSubscribe(Subject.Asset);
client.cancelSubscribe(Subject.Position);
client.cancelSubscribe(Subject.OrderStatus);
client.cancelSubscribe(Subject.OrderTransaction);
Last update: