互聯(lián)網(wǎng)網(wǎng)站建設(shè)公司做個(gè)電商平臺(tái)要多少錢
Java腳好用的庫很多,開發(fā)效率一點(diǎn)不輸Python。如果是日內(nèi)策略,需要更實(shí)時(shí)的行情數(shù)據(jù),不然策略滑點(diǎn)太大,容易跑偏結(jié)果。
之前爬行情網(wǎng)站提供的level1行情接口,實(shí)測平均更新延遲達(dá)到了6秒,超過10只股票并發(fā)請求頻率過快很容易封IP。后面又嘗試了買代理IP來請求,成本太高而且不穩(wěn)定。
在Github上看到一個(gè)行情包,對接的是WebSocket協(xié)議,找到了一個(gè)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));}@Overridepublic void onOpen(ServerHandshake shake) {//發(fā)送訂閱命令this.send("add=lv1_600519,lv2_600519");}/*** 命令返回文本消息*/@Overridepublic void onMessage(String paramString) {System.out.println(sdf.format(new Date()) + " Text響應(yīng):" + paramString);}@Overridepublic void onClose(int paramInt, String paramString, boolean paramBoolean) {System.out.println("連接關(guān)閉");}@Overridepublic void onError(Exception e) {System.out.println("連接異常" + e);}/*** 行情接收處理*/@Overridepublic void onMessage(ByteBuffer bytes) {super.onMessage(bytes);String s="";try {//二進(jìn)制解壓縮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響應(yīng):" + 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://<服務(wù)器地址>?token=<token>";Client fd = new Client(wsUrl);fd.connect();}
}
引用地址:https://github.com/freevolunteer/bondTrader/blob/main/pyscript/jvUtil/HanqQing.py