Account Changes
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)
Argument | Type | Required | Description |
---|---|---|---|
account | string | No | If the value is null, all accounts will be subscribed, including paper account |
subject | Subject | Yes | Subject |
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
Name | Type | Description |
---|---|---|
id | string | ID 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
Name | Type | Description |
---|---|---|
account | String | user account |
currency | String | currency. USD, HKD, etc. |
segType | String | Securities Category C: (Commodities Futures), S: (Securities Stocks) |
availableFunds | double | available funds, overnight liquidity |
excessLiquidity | double | Excess liquidity, used to represent intraday risk value. |
netLiquidation | double | Total Assets (Net Liquidation Value) - Securities Segment: Cash Value + Stock Value + Stock Option Value - Futures Segment: Cash Value + Mark-to-Market Profit and Loss |
equityWithLoan | double | Equity with loan value (asset with loan value) - Securities Segment: Cash Value + Stock Value - Futures Segment: Cash Value - Maintenance Margin |
buyingPower | double | Buying power. An estimation of how many more dollars you can buy in stock assets. Only apply to stock segment |
cashBalance | double | Total amount of cash, other currencies will be converted to USD |
grossPositionValue | double | Total value of securities |
initMarginReq | double | Initial margin requirement |
maintMarginReq | double | Maintenance margin requirement |
timestamp | long | timestamp |
Callbacks for change of positions
Name | Type | Description |
---|---|---|
account | String | user account |
symbol | String | Stock ticker symbol, exmaple: 'AAPL', '00700', 'ES', 'CN' |
expiry | String | for options, warrant, CBBC |
strike | String | for options, warrant, CBBC |
right | String | for options, warrant, CBBC |
identifier | String | asset identifier. The identifier of stocks is identical to its symbol. Futures contracts will also includes their month code. Example: 'CN2201' |
multiplier | int | multiplier for futures, options, warrants and CBBC |
market | String | market. US, HK, etc. |
currency | String | Currency. USD, HKD, etc. |
segType | String | Securities Category C: (Commodities Futures), S: (Securities Stocks) |
secType | String | STK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options |
positionQty | double | total position quantity |
salableQty | double | saleable quantity |
position | long | total position(Deprecated) |
positionScale | int | total position scale(Deprecated), For example, the position value is 2135, the positionScale is 2, and the actual number of positions is 21.35 |
saleable | long | can sell quantity(Only supports A-shares in mainland China)(Deprecated) |
averageCost | double | average holding cost |
latestPrice | double | last price of the asset |
marketValue | double | market value of the asset |
unrealizedPnl | double | unrealized profit and loss |
name | String | symbol name |
timestamp | long | timestamp |
Callbacks for change of order status
Name | Type | Description |
---|---|---|
id | long | unique order id |
account | String | user account |
symbol | String | Stock ticker symbol, exmaple: 'AAPL', '00700', 'ES', 'CN' |
expiry | String | for options, warrant, CBBC |
strike | String | for options, warrant, CBBC |
right | String | for options, warrant, CBBC |
identifier | String | asset identifier. The identifier of stocks is identical to its symbol. Futures contracts will also includes their month code. Example: 'CN2201' |
multiplier | int | multiplier for futures, options, warrants and CBBC |
action | String | BUY or SELL |
market | String | market. US, HK, etc. |
currency | String | Currency. USD, HKD, etc. |
segType | String | Securities Category C: (Commodities Futures), S: (Securities Stocks) |
secType | String | STK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options |
orderType | String | Order Types,'MKT'-Market Order / 'LMT'-Limit Order / 'STP'-Stop Order / 'STP_LMT'-Stop-Limit Order / 'TRAIL'-Trailing Stop Order |
isLong | boolean | is long |
totalQuantity | long | Order's quantity |
totalQuantityScale | int | The 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 |
filledQuantity | long | filled quantity |
filledQuantityScale | int | filled quantity scale |
avgFillPrice | double | average price at which the orders got filled |
limitPrice | double | Limit price, required if placing a limit order (inluding LMT and STP_LMT) |
stopPrice | double | Stop price, required if placing a stop order (inluding STP and STP_LMT) |
realizedPnl | double | realized profit and loss |
status | String | Order status |
replaceStatus | String | Order replace status |
cancelStatus | String | Order cancel status |
outsideRth | boolean | if trade outside regular trading hours (only applicable to U.S. market) |
canModify | boolean | can modify |
canCancel | boolean | can cancel |
liquidation | boolean | Is it a liquidation order |
name | String | symbol name |
source | String | order source(from 'OpenApi', or not) |
errorMsg | String | error message |
attrDesc | String | order description |
commissionAndFee | float | commission and fee |
openTime | long | timestamp when the order is placed |
timestamp | long | last update timestamp of order status |
userMark | String | Custom Remarks |
totalCashAmount | double | The total cash amount of the order (only for amount orders) |
filledCashAmount | double | The filled cash amount of the order (only for amount orders) |
Callbacks for transaction of order
Name | Type | Description |
---|---|---|
id | long | transaction ID |
orderId | long | unique order id |
account | String | user account |
symbol | String | Stock ticker symbol, exmaple: 'AAPL', '00700', 'ES', 'CN' |
identifier | String | asset identifier. The identifier of stocks is identical to its symbol. Futures contracts will also includes their month code. Example: 'CN2201' |
multiplier | int | multiplier for futures, options, warrants and CBBC |
action | String | BUY or SELL |
market | String | market. US、HK |
currency | String | Currency. USD, HKD, etc. |
segType | String | Securities Category C: (Commodities Futures), S: (Securities Stocks) |
secType | String | Security type. STK Stocks, OPT Options, WAR Warrants, IOPT CBBC, CASH FOREX, FUT Futures, FOP Future Options |
filledPrice | double | filled price |
filledQuantity | Long | filled quantity |
createTime | long | create time |
updateTime | long | update time |
transactTime | long | transaction time |
timestamp | long | timestamp |
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)
Argument | Type | Required | Description |
---|---|---|---|
subject | com.tigerbrokers.stock.openapi.client.struct.enums.Subject | Yes | subject |
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);