基本功能示例
大约 5 分钟
老虎Open API SDK提供了丰富的接口来调用老虎的服务,本章节将对老虎API的核心功能进行一一演示:包括查询行情,订阅行情,以及调用API进行交易
查询行情
以下为一个最简单的调用老虎API的示例,演示了如何调用Open API来主动查询股票行情。接下来的例子分别演示了如何调用Open API来进行交易与订阅行情。除上述基础功能外,Open API还支持查询、交易多个市场的不同标的,以及其他复杂请求。对于其他Open API支持的接口和请求,请在快速入门后阅读文档正文获取列表及使用方法,并参考快速入门以及文档中的例子进行调用
为方便直接复制运行,以下的说明采用注释的形式
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.License;
import com.tigerbrokers.stock.openapi.client.struct.enums.RightOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class QuoteDemo {
private static ClientConfig clientConfig = ClientConfig.DEFAULT_CONFIG;
private static TigerHttpClient client;
static {
//从开发者信息页面导出的配置文件tiger_openapi_config.properties、tiger_openapi_token.properties存放路径
clientConfig.configFilePath = "/data/tiger_config";
// clientConfig.secretKey = "xxxxxx"; // 机构账号交易员必填字段 secret key
client = TigerHttpClient.getInstance().clientConfig(clientConfig);
}
public static void main(String[] args) {
new Demo().kline();
}
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());
}
}
}
订阅行情
除了选择主动查询的方式(见快速入门-查询行情部分),Open API还支持订阅-接受推送的方式来接收行情等信息,具体见下例。需要注意的是,订阅推送相关的请求均为异步处理,故需要用户自定义回调函数,与中间函数进行绑定。某个事件发生,或有最新信息更新被服务器推送时,程序会自动调用用户自定义的回调函数并传入返回接口返回的数据,由用户自定义的回调函数来处理数据。
- 定义回调接口
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));
}
/*全量逐笔成交行情回调*/
@Override
public void fullTickChange(TickData data) {
ApiLogger.info("fullTickChange:" + ProtoMessageUtil.toJson(data));
}
/*分钟K线数据回调*/
@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);
}
}
- 进行订阅
import com.tigerbrokers.stock.openapi.client.config.ClientConfig;
import com.tigerbrokers.stock.openapi.client.socket.WebSocketClient;
import com.tigerbrokers.stock.openapi.client.struct.enums.License;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SubscribeDemo {
//实际订阅时需要读取tiger_openapi_token.properties文件来填充tigerId和privateKey,并实现ApiComposeCallback接口,本示例中为DefaultApiComposeCallback,实现参考以上代码,仅将返回数据简单输出。实际可根据需要调整@Override下方的回调函数
private static ClientConfig clientConfig = ClientConfig.DEFAULT_CONFIG;
private static WebSocketClient client;
static {
//从开发者信息页面导出的配置文件tiger_openapi_config.properties、tiger_openapi_token.properties存放路径
clientConfig.configFilePath = "/data/tiger_config";
// clientConfig.secretKey = "xxxxxx";// 机构账号交易员必填
client = WebSocketClient.getInstance().clientConfig(clientConfig).apiComposeCallback(new DefaultApiComposeCallback());
}
public static void main(String[] args) {
WebSocketDemo webSocketDemo = new WebSocketDemo();
webSocketDemo.subscribe();
}
public void subscribe() {
client.connect();
Set<String> symbols = new HashSet<>();
//股票订阅
symbols.add("AAPL");
symbols.add("SPY");
client.subscribeQuote(symbols);
//期货订阅
symbols.add("ESmain");
symbols.add("ES1906");
client.subscribeFuture(symbols);
//期权的一种形式
symbols.add("TSLA 20190614 200.0 CALL");
//期权另外一种形式(21位)
symbols.add("SPY 190508C00290000");
client.subscribeOption(symbols);
//订阅深度数据
client.subscribeDepthQuote(symbols);
//订阅逐笔数据
client.subscribeTradeTick(symbols);
//订阅期权榜单
Market market = Market.US;
Set<Indicator> indicators = new HashSet<>();
//期权当日大单指标
indicators.add(OptionRankingIndicator.BigOrder);
//期权当日累计成交额指标
indicators.add(OptionRankingIndicator.Amount);
client.subscribeOptionTop(market, indicators));
//查询订阅详情
client.getSubscribedSymbols();
//建议交易时间过后断开连接,断开连接时会自动注销之前的订阅记录
//client.disconnect();
}
}
下单
交易是Open API的另一个主要功能。此例展示了如何使用Open API对美股AAPL下限价单:
import com.alibaba.fastjson.JSONObject;
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 TradeDemo {
private static ClientConfig clientConfig = ClientConfig.DEFAULT_CONFIG;
private static TigerHttpClient client;
static {
//从开发者信息页面导出的配置文件tiger_openapi_config.properties、tiger_openapi_token.properties存放路径
clientConfig.configFilePath = "/data/tiger_config";
// clientConfig.secretKey = "xxxxxx";// institutional trader private key
client = TigerHttpClient.getInstance().clientConfig(clientConfig);
}
public static void main(String[] args) {
new TradeDemo().placeUSStockOrder();
}
public void placeUSStockOrder() {
TigerHttpRequest request = new TigerHttpRequest(MethodName.PLACE_ORDER);
String bizContent = TradeParamBuilder.instance()
.symbol("AAPL")
.secType(SecType.STK)
.market(Market.US)
.currency(Currency.USD)
.action(ActionType.BUY)
.orderType(OrderType.LMT)
.limitPrice(160.0)
.totalQuantity(1)
.timeInForce(TimeInForce.DAY)
.buildJson();
request.setBizContent(bizContent);
TigerHttpResponse response = client.execute(request);
System.out.println(JSONObject.toJSONString(response));
}
}