Account Changes
uint 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 IApiComposeCallback, 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 | TigerOpenAPI.Common.Enum.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(Subject subject, string? account)
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 | int | 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 funtions in IApiComposeCallback
/**
* 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
using System;
using System.Text.Json.Nodes;
using Newtonsoft.Json;
using TigerOpenAPI.Common;
using TigerOpenAPI.Common.Util;
using TigerOpenAPI.Push;
using TigerOpenAPI.Push.Model;
using TigerOpenAPI.Quote.Pb;
namespace Test
{
public class DefaultApiComposeCallback : IApiComposeCallback
{
public DefaultApiComposeCallback()
{
}
void IApiComposeCallback.ConnectionAck()
{
ApiLogger.Info("connect success.");
}
void IApiComposeCallback.ConnectionAck(int serverSendInterval, int serverReceiveInterval)
{
ApiLogger.Info($"connect success. serverSendInterval:{serverSendInterval}," +
$" serverReceiveInterval:{serverReceiveInterval}");
}
void IApiComposeCallback.HearBeat(string heartBeatContent)
{
ApiLogger.Info("HearBeat:" + heartBeatContent);
}
void IApiComposeCallback.ServerHeartBeatTimeOut(string channelId)
{
ApiLogger.Warn("ServerHeartBeatTimeOut:" + channelId);
}
void IApiComposeCallback.ConnectionClosed()
{
ApiLogger.Info("connection closed.");
}
void IApiComposeCallback.ConnectionKickout(int errorCode, string errorMsg)
{
ApiLogger.Info($"ConnectionKickout, errorCode:{errorCode}, errorMsg:{errorMsg}");
}
void IApiComposeCallback.Error(string errorMsg)
{
ApiLogger.Error("receive error:" + errorMsg);
}
void IApiComposeCallback.Error(int id, int errorCode, string errorMsg)
{
ApiLogger.Error($"receive error, id:{id}, errorCode:{errorCode}, errorMsg:{errorMsg}");
}
void ISubscribeApiCallback.GetSubscribedSymbolEnd(SubscribedSymbol subscribedSymbol)
{
ApiLogger.Info("GetSubscribedSymbolEnd:"
+ JsonConvert.SerializeObject(subscribedSymbol, TigerClient.JsonSet));
}
void ISubscribeApiCallback.SubscribeEnd(int id, string subject, string result)
{
ApiLogger.Info($"SubscribeEnd, {subject}, id:{id}, result:{result}");
}
void ISubscribeApiCallback.CancelSubscribeEnd(int id, string subject, string result)
{
ApiLogger.Info($"CancelSubscribeEnd, {subject}, id:{id}, result:{result}");
}
void ISubscribeApiCallback.AssetChange(AssetData data)
{
ApiLogger.Info("AssetChange:" + data);
}
void ISubscribeApiCallback.PositionChange(PositionData data)
{
ApiLogger.Info("PositionChange:" + data);
}
void ISubscribeApiCallback.OrderStatusChange(OrderStatusData data)
{
ApiLogger.Info("OrderStatusChange:" + data);
}
void ISubscribeApiCallback.OrderTransactionChange(OrderTransactionData data)
{
ApiLogger.Info("OrderTransactionChange:" + data);
}
void ISubscribeApiCallback.QuoteAskBidChange(QuoteBBOData data)
{
ApiLogger.Info("QuoteAskBidChange:" + data);
}
void ISubscribeApiCallback.QuoteChange(QuoteBasicData data)
{
ApiLogger.Info("QuoteChange:" + data);
}
void ISubscribeApiCallback.TradeTickChange(TradeTick data)
{
ApiLogger.Info("TradeTickChange:"
+ JsonConvert.SerializeObject(data, TigerClient.JsonSet));
}
void ISubscribeApiCallback.DepthQuoteChange(QuoteDepthData data)
{
ApiLogger.Info("DepthQuoteChange:" + data);
}
void ISubscribeApiCallback.FutureAskBidChange(QuoteBBOData data)
{
ApiLogger.Info("FutureAskBidChange:" + data);
}
void ISubscribeApiCallback.FutureChange(QuoteBasicData data)
{
ApiLogger.Info("FutureChange:" + data);
}
void ISubscribeApiCallback.OptionAskBidChange(QuoteBBOData data)
{
ApiLogger.Info("OptionAskBidChange:" + data);
}
void ISubscribeApiCallback.OptionChange(QuoteBasicData data)
{
ApiLogger.Info("OptionChange:" + data);
}
}
}
Subscripion
using System;
using Newtonsoft.Json;
using TigerOpenAPI.Common;
using TigerOpenAPI.Common.Enum;
using TigerOpenAPI.Common.Util;
using TigerOpenAPI.Config;
using TigerOpenAPI.Model;
using TigerOpenAPI.Push;
using TigerOpenAPI.Quote;
using TigerOpenAPI.Quote.Model;
namespace Test
{
public class SubscribeDemo
{
private static TigerConfig config;
static SubscribeDemo()
{
TigerConfig.LogDir = "/data0/logs/tiger-openapi-cs";
config = new TigerConfig()
{
// The tiger_openapi_config.properties file is stored in your local directory.
ConfigFilePath = "/data0/tiger_config",
FailRetryCounts = 2, // (optional) range:[1, 5], default is 2
Language = Language.en_US, // (optional) default is en_US
TimeZone = CustomTimeZone.HK_ZONE // (optional) default is HK_ZONE
};
}
static async Task Main(string[] args)
{
IApiComposeCallback callback = new DefaultApiComposeCallback();
PushClient client = PushClient.GetInstance().Config(config)
.ApiComposeCallback(callback);
ApiLogger.Info($"======================{client.GetUrl()}");
//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
Thread.Sleep(TimeSpan.FromSeconds(60));
// Cancel subscription
client.CancelSubscribe(Subject.Asset);
client.CancelSubscribe(Subject.Position);
client.CancelSubscribe(Subject.OrderStatus);
client.CancelSubscribe(Subject.OrderTransaction);
}
}
}
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}
uint CancelSubscribe(Subject subject) Cancel Subscription
Description
Cancel the subscription of the selected subject
Argument(Subject)
Argument | Type | Required | Description |
---|---|---|---|
subject | TigerOpenAPI.Common.Enum.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);