Basic Function

About 3 min

This section provides some complete examples about the core functions of Tiger Open API Java SDK. You are able to copy the example directly to your local directory to run the examples:

Get Market Quotes

Here is a simple example of using the Tiger Open API. It demonstrates how to use Open API to get the market data. Below this example, our next sample codes will show you how to use Open API to trade, and subscribe to market data.

Besides all the basic functions demonstrated below, you can also get different types of market data and trade various products with advanced order types by using Open API. For a complete list and demonstration of the full capability of the Open API, please read the other sections of this documentation.

*More explainations available in the comments. The examples can be run directly

using System;
using Newtonsoft.Json;
using TigerOpenAPI.Common;
using TigerOpenAPI.Common.Enum;
using TigerOpenAPI.Common.Util;
using TigerOpenAPI.Config;
using TigerOpenAPI.Model;
using TigerOpenAPI.Quote;
using TigerOpenAPI.Quote.Model;
using TigerOpenAPI.Quote.Response;

namespace Test
{
  public class Demo
  {
    private static TigerConfig config;
    private static QuoteClient quoteClient;

    static Demo ()
    {
      TigerConfig.LogDir = "/data0/logs/tiger-openapi-cs";
      config = new TigerConfig()
      {
        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
      };
      quoteClient = new QuoteClient(config);
    }

    static async Task Main(string[] args)
    {

      TigerRequest<QuoteKlineResponse> request = new TigerRequest<QuoteKlineResponse>()
      {
        ApiMethodName = QuoteApiService.KLINE,
        ModelValue = new QuoteKlineModel()
        {
          Symbols = new List<string> { "AAPL" },
          Period = KLineType.day.Value,
          BeginTime = DateUtil.ConvertTimestamp("2023-03-01", CustomTimeZone.NY_ZONE),
          EndTime = DateUtil.CurrentTimeMillis(),
          Rigth = RightOption.br
        }
      };
      QuoteKlineResponse? response = await quoteClient.ExecuteAsync(request);
      if (response is not null && response.IsSuccess())
      {
        ApiLogger.Info("request success:" + JsonConvert.SerializeObject(response));
      } else
      {
        ApiLogger.Info("request fail:" + JsonConvert.SerializeObject(response));
      }
    }
  }
}

Market Data Streaming

The Tiger Open API also supports receiving the market data by subscription, so you can get live streaming for market quotes via websocket. Please see the example for details. The basic idea of this example is to subscribe the market quotes for AAPL and AMD, print the results,

Please note that all APIs involved in this section is aschonynic. As a result, in most cases, you will need to implement your own callback function to handle the data being sent back.

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.FullTickChange(TickData data)
    {
      ApiLogger.Info("FullTickChange:" + data);
    }

    void ISubscribeApiCallback.KlineChange(KlineData data)
    {
      ApiLogger.Info("KlineChange:" + data);
    }

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

    void ISubscribeApiCallback.StockTopPush(StockTopData data)
    {
      ApiLogger.Info("StockTopPush, market:" + data.Market);
      foreach (StockTopData.Types.TopData topData in data.TopData)
      {
        ApiLogger.Info("StockTopPush, targetName:" + topData.TargetName
            + ", topList:" + topData);
      }
    }

    void ISubscribeApiCallback.OptionTopPush(OptionTopData data)
    {
      ApiLogger.Info("OptionTopPush, market:" + data.Market);
      foreach (OptionTopData.Types.TopData topData in data.TopData)
      {
        ApiLogger.Info("OptionTopPush, targetName:" + topData.TargetName
            + ", topList:" + topData);
      }
    }
  }
}

Subscription

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 path of 'tiger_openapi_config.properties' file
        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()}");

      client.Connect();

      ISet<string> symbols = new HashSet<string>();
      symbols.Add("AAPL");
      symbols.Add("TSLA");
      ApiLogger.Info($"SubscribeQuote:{client.SubscribeQuote(symbols)}");
      ApiLogger.Info($"GetSubscribedSymbols:{client.GetSubscribedSymbols()}");
      Thread.Sleep(TimeSpan.FromSeconds(60));
      ApiLogger.Info($"CancelSubscribeQuote:{client.CancelSubscribeQuote(symbols)}");
      Thread.Sleep(TimeSpan.FromSeconds(2));
      ApiLogger.Info($"GetSubscribedSymbols:{client.GetSubscribedSymbols()}");
    }
  }
}

Place Orders

Tradingg is another core funtion of Tiger Open API. This exmaple demonstrates how to place market order for AAPL (Apple) with Open API

using System;
using Newtonsoft.Json;
using TigerOpenAPI.Common;
using TigerOpenAPI.Common.Enum;
using TigerOpenAPI.Common.Util;
using TigerOpenAPI.Config;
using TigerOpenAPI.Model;
using TigerOpenAPI.Trade;
using TigerOpenAPI.Trade.Model;
using TigerOpenAPI.Trade.Response;

namespace Test
{
  public class TradeDemo
  {
    private static TigerConfig config;
    private static TradeClient tradeClient;

    static TradeDemo()
    {
      TigerConfig.LogDir = "/data0/logs/tiger-openapi-cs";
      config = new TigerConfig()
      {
        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
      };
      tradeClient = new TradeClient(config);
    }

    static async Task Main(string[] args)
    {
      ContractItem contract = ContractItem.buildStockContract("AAPL", Currency.USD.ToString());

      TigerRequest<PlaceOrderResponse> request = new TigerRequest<PlaceOrderResponse>()
      {
        ApiMethodName = TradeApiService.PLACE_ORDER,
        ModelValue = PlaceOrderModel.buildLimitOrder(
          "20200821144442583", // tradeClient.GetDefaultAccount,
          contract,
          ActionType.BUY,
          1, 120.0
        )
      };
      // set other parameter
      PlaceOrderModel model = (PlaceOrderModel)request.ModelValue;
      model.TimeInForce = TimeInForce.GTD;
      model.ExpireTime = DateUtil.ConvertTimestamp("2023-03-09 23:59:59",
        SymbolUtil.getZoneIdBySymbol("AAPL", tradeClient.GetConfigTimeZone));
      PlaceOrderResponse? response = await tradeClient.ExecuteAsync(request);
      if (response is not null && response.IsSuccess())
      {
        ApiLogger.Info("request success:" + JsonConvert.SerializeObject(response));
      }
      else
      {
        ApiLogger.Info("request fail:" + JsonConvert.SerializeObject(response));
      }
    }
  }
}
Last update: