Basic Function
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 with JUnit
import com.tigerbrokers.stock.openapi.client.config.ClientConfig;
import com.tigerbrokers.stock.openapi.client.https.client.TigerHttpClient;
import com.tigerbrokers.stock.openapi.client.https.request.quote.QuoteKlineRequest;
import com.tigerbrokers.stock.openapi.client.https.response.quote.QuoteKlineResponse;
import com.tigerbrokers.stock.openapi.client.struct.enums.KType;
import com.tigerbrokers.stock.openapi.client.struct.enums.RightOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Demo {
private static ClientConfig clientConfig = ClientConfig.DEFAULT_CONFIG;
private static TigerHttpClient client;
static {
// tiger_openapi_config.properties、tiger_openapi_token.properties stored directory
clientConfig.configFilePath = "/data/tiger_config";
// clientConfig.secretKey = "xxxxxx";// institutional trader private key
client = TigerHttpClient.getInstance().clientConfig(clientConfig);
}
public void kline() {
List<String> symbols = new ArrayList<>();
symbols.add("AAPL");
QuoteKlineResponse response =
client.execute(QuoteKlineRequest.newRequest(symbols, KType.day, "2018-10-01", "2018-12-25")
.withLimit(1000)
.withRight(RightOption.br));
if (response.isSuccess()) {
System.out.println(Arrays.toString(response.getKlineItems().toArray()));
} else {
System.out.println("response error:" + response.getMessage());
}
}
}
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.
package com.tigerbrokers.stock.openapi.demo;
import com.alibaba.fastjson.JSONObject;
import com.tigerbrokers.stock.openapi.client.socket.ApiComposeCallback;
import com.tigerbrokers.stock.openapi.client.socket.data.TradeTick;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.AssetData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.KlineData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.OptionTopData;
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.socket.data.pb.QuoteBBOData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.QuoteBasicData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.QuoteDepthData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.StockTopData;
import com.tigerbrokers.stock.openapi.client.socket.data.pb.TickData;
import com.tigerbrokers.stock.openapi.client.struct.SubscribedSymbol;
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 quoteChange(QuoteBasicData data) {
ApiLogger.info("quoteChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void quoteAskBidChange(QuoteBBOData data) {
ApiLogger.info("quoteAskBidChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void tradeTickChange(TradeTick data) {
ApiLogger.info("tradeTickChange:" + JSONObject.toJSONString(data));
}
/*Callback for full trade tick updates*/
@Override
public void fullTickChange(TickData data) {
ApiLogger.info("fullTickChange:" + ProtoMessageUtil.toJson(data));
}
/*Callback for minute kline data updates*/
@Override
public void klineChange(KlineData data) {
ApiLogger.info("klineChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void optionChange(QuoteBasicData data) {
ApiLogger.info("optionChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void optionAskBidChange(QuoteBBOData data) {
ApiLogger.info("optionAskBidChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void futureChange(QuoteBasicData data) {
ApiLogger.info("futureChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void futureAskBidChange(QuoteBBOData data) {
ApiLogger.info("futureAskBidChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void depthQuoteChange(QuoteDepthData data) {
ApiLogger.info("depthQuoteChange:" + ProtoMessageUtil.toJson(data));
}
@Override
public void stockTopPush(StockTopData data) {
ApiLogger.info("stockTopPush, market:" + data.getMarket());
for (StockTopData.TopData topData : data.getTopDataList()) {
ApiLogger.info("stockTopPush, targetName:" + topData.getTargetName()
+ ", topList:" + ProtoMessageUtil.toJson(topData));
}
}
@Override
public void optionTopPush(OptionTopData data) {
ApiLogger.info("optionTopPush, market:" + data.getMarket());
for (OptionTopData.TopData topData : data.getTopDataList()) {
ApiLogger.info("optionTopPush, targetName:" + topData.getTargetName()
+ ", topList:" + ProtoMessageUtil.toJson(topData));
}
}
@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);
}
@Override
public void getSubscribedSymbolEnd(SubscribedSymbol subscribedSymbol) {
ApiLogger.info("getSubscribedSymbolEnd:" + JSONObject.toJSONString(subscribedSymbol));
}
@Override
public void error(String errorMsg) {
ApiLogger.info("receive error:" + errorMsg);
}
@Override
public void error(int id, int errorCode, String errorMsg) {
ApiLogger.info("receive error id:" + id + ",errorCode:" + errorCode + ",errorMsg:" + errorMsg);
}
@Override
public void connectionClosed() {
ApiLogger.info("connection closed.");
}
@Override
public void connectionKickout(int errorCode, String errorMsg) {
ApiLogger.info(errorMsg + " and the connection is closed.");
}
@Override
public void connectionAck() {
ApiLogger.info("connect success.");
}
@Override
public void connectionAck(int serverSendInterval, int serverReceiveInterval) {
ApiLogger.info(
"connect success,send interval:" + serverSendInterval + ",receive interval:" + serverReceiveInterval);
}
@Override
public void hearBeat(String heartBeatContent) {
ApiLogger.info(heartBeatContent);
}
@Override
public void serverHeartBeatTimeOut(String channelId) {
ApiLogger.info("serverHeartBeatTimeOut,channelId=" + channelId);
}
}
Subscription
import com.tigerbrokers.stock.openapi.client.config.ClientConfig;
import com.tigerbrokers.stock.openapi.client.socket.ApiAuthentication;
import com.tigerbrokers.stock.openapi.client.socket.WebSocketClient;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class WebSocketDemo {
//The subscription requires filling tigerId and privateKey, and implementing the ApiComposeCallback interface, which is DefaultApiComposeCallback in this example, with reference to the above code, and simply outputting the returned data.
private static ClientConfig clientConfig = ClientConfig.DEFAULT_CONFIG;
private static WebSocketClient client;
static {
// tiger_openapi_config.properties、tiger_openapi_token.properties stored directory
clientConfig.configFilePath = "/data/tiger_config";
// clientConfig.secretKey = "xxxxxx";// institutional trader private key
client = WebSocketClient.getInstance().clientConfig(clientConfig).apiComposeCallback(new DefaultApiComposeCallback());
}
public static void subscribe() {
client.connect();
Set<String> symbols = new HashSet<>();
//Stock Subscription
symbols.add("AAPL");
symbols.add("SPY");
client.subscribeQuote(symbols);
//Futures Subscription
symbols.add("ESmain");
symbols.add("ES1906");
client.subscribeFuture(symbols);
//Options Subscription
//Option Format I
symbols.add("TSLA 20190614 200.0 CALL");
//Option Format II(21 characters)
symbols.add("SPY 190508C00290000");
client.subscribeOption(symbols);
//subscribe symbols
client.subscribeQuote(symbols);
//subscribe depth quote
client.subscribeDepthQuote(symbols);
//subscribe trade tick
client.subscribeTradeTick(symbols);
//subscribe option quote top list
Market market = Market.US;
Set<Indicator> indicators = new HashSet<>();
//big order indicator
indicators.add(OptionRankingIndicator.BigOrder);
//big order indicator
//cumulative turnover indicator
indicators.add(OptionRankingIndicator.Amount);
client.subscribeOptionTop(market, indicators));
//query subscribed symbols
client.getSubscribedSymbols();
//It is recommended to disconnect after the transaction time, disconnection will automatically cancel the previous subscription records
//client.disconnect();
}
}
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
import com.tigerbrokers.stock.openapi.client.config.ClientConfig;
import com.tigerbrokers.stock.openapi.client.struct.enums.MethodName;
import com.tigerbrokers.stock.openapi.client.https.client.TigerHttpClient;
import com.tigerbrokers.stock.openapi.client.https.request.TigerHttpRequest;
import com.tigerbrokers.stock.openapi.client.https.response.TigerHttpResponse;
import com.tigerbrokers.stock.openapi.client.struct.enums.*;
import com.tigerbrokers.stock.openapi.client.util.builder.TradeParamBuilder;
public class Demo {
private static ClientConfig clientConfig = ClientConfig.DEFAULT_CONFIG;
private static TigerHttpClient client;
static {
// tiger_openapi_config.properties、tiger_openapi_token.properties stored directory
clientConfig.configFilePath = "/data/tiger_config";
// clientConfig.secretKey = "xxxxxx";// institutional trader private key
client = TigerHttpClient.getInstance().clientConfig(clientConfig);
}
public static void main(String[] args) {
new Demo().placeUSStockOrder();
}
public void placeUSStockOrder() {
TigerHttpRequest request = new TigerHttpRequest(MethodName.PLACE_ORDER);
String bizContent = TradeParamBuilder.instance()
.account("DU575569")
.symbol("AAPL")
.secType(SecType.STK)
.market(Market.US)
.currency(Currency.USD)
.action(ActionType.BUY)
.orderType(OrderType.LMT)
.limitPrice(182.0)
.totalQuantity(100)
.timeInForce(TimeInForce.DAY)
.buildJson();
request.setBizContent(bizContent);
TigerHttpResponse response = client.execute(request);
System.out.println(response)
}
}