Java脚好用的库很多,开发效率一点不输Python。如果是日内策略,需要更实时的行情数据,不然策略滑点太大,容易跑偏结果。
之前爬行情网站提供的level1行情接口,实测平均更新延迟达到了6秒,超过10只股票并发请求频率过快很容易封IP。后面又尝试了买代理IP来请求,成本太高而且不稳定。
在Github上看到一个行情包,对接的是WebSocket协议,找到了一个Java版本封装的包,记录一下:
package com.client;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Inflater;
import java.util.zip.DataFormatException;
public class Client extends WebSocketClient {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public Client(String url) throws URISyntaxException {
super(new URI(url));
}
@Override
public void onOpen(ServerHandshake shake) {
//发送订阅命令
this.send("add=lv1_600519,lv2_600519");
}
/**
* 命令返回文本消息
*/
@Override
public void onMessage(String paramString) {
System.out.println(sdf.format(new Date()) + " Text响应:" + paramString);
}
@Override
public void onClose(int paramInt, String paramString, boolean paramBoolean) {
System.out.println("连接关闭");
}
@Override
public void onError(Exception e) {
System.out.println("连接异常" + e);
}
/**
* 行情接收处理
*/
@Override
public void onMessage(ByteBuffer bytes) {
super.onMessage(bytes);
String s="";
try {
//二进制解压缩
byte[] dec=decompress(bytes.array());
s = new String(dec, "UTF-8");
}catch (IOException e){
System.err.println("Binary解析IO异常:"+e.getMessage());
return;
}
catch (DataFormatException e){
System.err.println("Binary解析格式异常:"+e.getMessage());
return;
}
System.out.println(sdf.format(new Date()) + " Binary响应:" + s);
}
/**
* 解压缩方法
*/
public static byte[] decompress(byte[] compressedData) throws DataFormatException {
Inflater inflater = new Inflater(true);
inflater.setInput(compressedData);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(compressedData.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
inflater.end();
return outputStream.toByteArray();
}
}
使用:
package com.client;
import java.net.URISyntaxException;
public class Main {
public static void main(String[] args) throws URISyntaxException {
String wsUrl = "ws://<服务器地址>?token=<token>";
Client fd = new Client(wsUrl);
fd.connect();
}
}
引用地址:https://github.com/freevolunteer/bondTrader/blob/main/pyscript/jvUtil/HanqQing.py
订阅指令参考:JAVA量化之WebScoket行情接入