Account Changes

About 7 min

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)

ArgumentTypeRequiredDescription
accountstringNoIf the value is null, all accounts will be subscribed, including paper account
subjectTigerOpenAPI.Common.Enum.SubjectYesSubject

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

NameTypeDescription
idintID 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 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)

ArgumentTypeRequiredDescription
subjectTigerOpenAPI.Common.Enum.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: