From b7e21f850f899813f397f5d2c35659bd48437990 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Fri, 08 May 2026 10:02:44 +0800
Subject: [PATCH] refactor(gateApi): 重构网格交易服务为持续循环模式
---
src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java | 286 ++++++++++++++++++++++++++++++++++++--------------------
1 files changed, 182 insertions(+), 104 deletions(-)
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
index ca59116..6b900e6 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -1,41 +1,48 @@
package com.xcong.excoin.modules.gateApi;
-import cn.hutool.core.collection.CollUtil;
-import cn.hutool.json.JSONException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcong.excoin.modules.blackchain.service.DateUtil;
import com.xcong.excoin.modules.okxNewPrice.celue.CaoZuoService;
-import com.xcong.excoin.modules.okxNewPrice.indicator.macdAndMatrategy.MacdEmaStrategy;
-import com.xcong.excoin.modules.okxNewPrice.indicator.macdAndMatrategy.MacdMaStrategy;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.InstrumentsWs;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.TradeOrderWs;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.CoinEnums;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.param.Kline;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.param.TradeRequestParam;
import com.xcong.excoin.modules.okxNewPrice.okxWs.wanggeList.WangGeListService;
-import com.xcong.excoin.modules.okxNewPrice.okxpi.config.ExchangeInfoEnum;
-import com.xcong.excoin.modules.okxNewPrice.okxpi.config.ExchangeLoginService;
import com.xcong.excoin.modules.okxNewPrice.utils.SSLConfig;
-import com.xcong.excoin.modules.okxNewPrice.utils.WsParamBuild;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.*;
+import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
-import java.util.stream.Collectors;
/**
- * Gate K线 WebSocket 客户端类,用于连接 Gate 的 WebSocket 接口,
- * 实时获取并处理 K线(candlestick)数据。
- * 同时支持心跳检测、自动重连以及异常恢复机制。
+ * Gate WebSocket 客户端,通过 Java-WebSocket 库连接 Gate.io 的 WebSocket 接口。
+ *
+ * <h3>订阅频道</h3>
+ * <ul>
+ * <li>{@code futures.candlesticks} — 1m K 线数据(公开频道)</li>
+ * <li>{@code futures.positions} — 用户仓位更新(私有频道,需 HMAC-SHA512 签名认证)</li>
+ * <li>{@code futures.ping} — 应用层心跳</li>
+ * </ul>
+ *
+ * <h3>数据流</h3>
+ * <pre>
+ * onMessage → handleWebSocketMessage → 按 channel 分流:
+ * futures.pong → 取消心跳超时
+ * subscribe/unsubscribe/error → 日志
+ * futures.candlesticks → processPushDataV2 → GateGridTradeService.onKline()
+ * futures.positions → processPositionData → GateGridTradeService.onPositionUpdate()
+ * </pre>
+ *
+ * <h3>连接管理</h3>
+ * 支持心跳检测、指数退避重连(最多 3 次)、优雅关闭。
+ *
* @author Administrator
*/
@Slf4j
@@ -47,18 +54,38 @@
private WebSocketClient webSocketClient;
private ScheduledExecutorService heartbeatExecutor;
private volatile ScheduledFuture<?> pongTimeoutFuture;
+ /** 最后收到消息的时间戳,用于心跳超时检测 */
private final AtomicReference<Long> lastMessageTime = new AtomicReference<>(System.currentTimeMillis());
- // 连接状态标志
+ /** 连接状态 */
private final AtomicBoolean isConnected = new AtomicBoolean(false);
+ /** 连接中标记,防止重复连接 */
private final AtomicBoolean isConnecting = new AtomicBoolean(false);
+ /** 初始化标记,防止重复初始化 */
private final AtomicBoolean isInitialized = new AtomicBoolean(false);
+ /** K 线频道 */
private static final String CHANNEL = "futures.candlesticks";
+ /** 仓位频道(私有,需认证) */
+ private static final String POSITIONS_CHANNEL = "futures.positions";
+ /** 应用层 ping 频道 */
private static final String FUTURES_PING = "futures.ping";
+ /** 应用层 pong 频道 */
private static final String FUTURES_PONG = "futures.pong";
+ /** K 线周期 */
private static final String GATE_INTERVAL = "1m";
- private static final String GATE_CONTRACT = "BTC_USDT";
+ /** 订阅合约 */
+ private static final String GATE_CONTRACT = "XAUT_USDT";
+
+ /** 网格交易策略实例 */
+ private GateGridTradeService gridTradeService;
+
+ /** API 密钥,用于私有频道签名 */
+ private final String apiKey;
+ /** API 密钥 */
+ private final String apiSecret;
+
+ private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
// 心跳超时时间(秒),小于30秒
private static final int HEARTBEAT_TIMEOUT = 10;
@@ -72,11 +99,16 @@
public GateKlineWebSocketClient(CaoZuoService caoZuoService,
GateWebSocketClientManager clientManager,
- WangGeListService wangGeListService
+ WangGeListService wangGeListService,
+ GateGridTradeService gridTradeService,
+ String apiKey, String apiSecret
) {
this.caoZuoService = caoZuoService;
this.clientManager = clientManager;
this.wangGeListService = wangGeListService;
+ this.gridTradeService = gridTradeService;
+ this.apiKey = apiKey;
+ this.apiSecret = apiSecret;
}
/**
@@ -99,6 +131,7 @@
if (webSocketClient != null && webSocketClient.isOpen()) {
unsubscribeKlineChannels();
+ unsubscribePositionsChannels();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
@@ -179,6 +212,7 @@
if (sharedExecutor != null && !sharedExecutor.isShutdown()) {
resetHeartbeatTimer();
subscribeKlineChannels();
+ subscribePositionsChannels();
subscribePingChannels();
} else {
log.warn("应用正在关闭,忽略WebSocket连接成功回调");
@@ -248,6 +282,10 @@
webSocketClient.send(subscribeMsg.toJSONString());
log.info("已发送 K线频道订阅请求,合约: {}, 周期: {}", GATE_CONTRACT, GATE_INTERVAL);
}
+ /**
+ * 发送应用层 ping 请求。
+ * 用于探测连接状态,服务器会返回 futures.pong。
+ */
private void subscribePingChannels() {
JSONObject subscribeMsg = new JSONObject();
subscribeMsg.put("time", System.currentTimeMillis() / 1000);
@@ -256,6 +294,63 @@
log.info("已发送 futures.ping");
}
+ /**
+ * 订阅仓位频道(私有频道,需 HMAC-SHA512 签名认证)。
+ * 签名算法: Hex(HmacSHA512(secret, "channel={channel}&event={event}&time={time}"))
+ */
+ private void subscribePositionsChannels() {
+ JSONObject subscribeMsg = new JSONObject();
+ long timeSec = System.currentTimeMillis() / 1000;
+ subscribeMsg.put("time", timeSec);
+ subscribeMsg.put("channel", POSITIONS_CHANNEL);
+ subscribeMsg.put("event", "subscribe");
+ JSONArray payload = new JSONArray();
+ payload.add("user_id");
+ payload.add(GATE_CONTRACT);
+ subscribeMsg.put("payload", payload);
+
+ JSONObject auth = new JSONObject();
+ auth.put("method", "api_key");
+ auth.put("KEY", apiKey);
+ auth.put("SIGN", hs512Sign(POSITIONS_CHANNEL, "subscribe", timeSec));
+ subscribeMsg.put("auth", auth);
+
+ webSocketClient.send(subscribeMsg.toJSONString());
+ log.info("已发送仓位频道订阅请求(含认证),合约: {}", GATE_CONTRACT);
+ }
+
+ /**
+ * 计算 Gate API v4 的 HMAC-SHA512 签名。
+ *
+ * @param channel 频道名
+ * @param event 事件名(subscribe/unsubscribe)
+ * @param timeSec 时间戳(秒)
+ * @return 十六进制签名字符串
+ */
+ private String hs512Sign(String channel, String event, long timeSec) {
+ try {
+ String message = "channel=" + channel + "&event=" + event + "&time=" + timeSec;
+ Mac mac = Mac.getInstance("HmacSHA512");
+ SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA512");
+ mac.init(spec);
+ byte[] hash = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
+ StringBuilder hex = new StringBuilder(hash.length * 2);
+ for (byte b : hash) {
+ hex.append(HEX_ARRAY[(b >> 4) & 0xF]);
+ hex.append(HEX_ARRAY[b & 0xF]);
+ }
+ String sign = hex.toString();
+ log.debug("签名计算, message: {}, sign: {}", message, sign);
+ return sign;
+ } catch (Exception e) {
+ log.error("签名计算失败", e);
+ return "";
+ }
+ }
+
+ /**
+ * 取消订阅 K 线频道。
+ */
private void unsubscribeKlineChannels() {
JSONObject unsubscribeMsg = new JSONObject();
unsubscribeMsg.put("time", System.currentTimeMillis() / 1000);
@@ -267,6 +362,21 @@
unsubscribeMsg.put("payload", payload);
webSocketClient.send(unsubscribeMsg.toJSONString());
log.info("已发送 K线频道取消订阅请求,合约: {}, 周期: {}", GATE_CONTRACT, GATE_INTERVAL);
+ }
+
+ /**
+ * 取消订阅仓位频道。
+ */
+ private void unsubscribePositionsChannels() {
+ JSONObject unsubscribeMsg = new JSONObject();
+ unsubscribeMsg.put("time", System.currentTimeMillis() / 1000);
+ unsubscribeMsg.put("channel", POSITIONS_CHANNEL);
+ unsubscribeMsg.put("event", "unsubscribe");
+ JSONArray payload = new JSONArray();
+ payload.add(GATE_CONTRACT);
+ unsubscribeMsg.put("payload", payload);
+ webSocketClient.send(unsubscribeMsg.toJSONString());
+ log.info("已发送仓位频道取消订阅请求,合约: {}", GATE_CONTRACT);
}
/**
@@ -295,7 +405,11 @@
error != null ? error.getInteger("code") : "N/A",
error != null ? error.getString("message") : response.getString("msg"));
} else if ("update".equals(event) || "all".equals(event)) {
- processPushDataV2(response);
+ if (POSITIONS_CHANNEL.equals(channel)) {
+ processPositionData(response);
+ } else if (CHANNEL.equals(channel)) {
+ processPushDataV2(response);
+ }
}
} catch (Exception e) {
log.error("处理WebSocket消息失败: {}", message, e);
@@ -355,96 +469,60 @@
boolean windowClosed = data.getBooleanValue("w");
String time = DateUtil.TimeStampToDateTime(t);
- System.out.println("========== Gate K线数据 ==========");
- System.out.println("名称(n): " + name);
- System.out.println("时间 : " + time);
- System.out.println("开盘(o): " + openPx);
- System.out.println("最高(h): " + highPx);
- System.out.println("最低(l): " + lowPx);
- System.out.println("收盘(c): " + closePx);
- System.out.println("成交量(v): " + vol);
- System.out.println("成交额(a): " + baseVol);
- System.out.println("K线完结(w): " + windowClosed);
- System.out.println("==================================");
+ log.info("========== Gate K线数据 ==========");
+ log.info("名称(n): " + name);
+ log.info("时间 : " + time);
+ log.info("开盘(o): " + openPx);
+ log.info("最高(h): " + highPx);
+ log.info("最低(l): " + lowPx);
+ log.info("收盘(c): " + closePx);
+ log.info("成交量(v): " + vol);
+ log.info("成交额(a): " + baseVol);
+ log.info("K线完结(w): " + windowClosed);
+ log.info("==================================");
+
+ if (gridTradeService != null) {
+ gridTradeService.onKline(closePx);
+ }
} catch (Exception e) {
log.error("处理 K线频道推送数据失败", e);
}
}
- private void doOpen(WebSocketClient webSocketClient, String accountName, MacdEmaStrategy.TradingOrder tradingOrderOpenOpen, BigDecimal closePx) {
- // 根据信号执行交易操作
- TradeRequestParam tradeRequestParam = new TradeRequestParam();
-
- String posSide = tradingOrderOpenOpen.getPosSide();
- tradeRequestParam.setPosSide(posSide);
- String currentPrice = String.valueOf(closePx);
- tradeRequestParam = caoZuoService.caoZuoStrategy(accountName, currentPrice, posSide);
-
- String side = tradingOrderOpenOpen.getSide();
- tradeRequestParam.setSide(side);
-
- String clOrdId = WsParamBuild.getOrderNum(side);
- tradeRequestParam.setClOrdId(clOrdId);
-
- String sz = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.BUY_CNT_INIT.name());
- tradeRequestParam.setSz(sz);
- TradeOrderWs.orderEvent(webSocketClient, tradeRequestParam);
- }
-
- private List<Kline> getKlineDataByInstIdAndBar(String instId, String bar) {
- List<Kline> klineList = new ArrayList<>();
- try {
- LinkedHashMap<String, Object> requestParam = new LinkedHashMap<>();
- requestParam.put("instId", instId);
- requestParam.put("bar", bar);
- requestParam.put("limit", "200");
- String result = ExchangeLoginService.getInstance(ExchangeInfoEnum.OKX_UAT.name()).lineHistory(requestParam);
- JSONObject json = JSON.parseObject(result);
- String data = json.getString("data");
-
- if (data != null) {
- List<String[]> klinesList = JSON.parseArray(data, String[].class);
- if (!CollUtil.isEmpty(klinesList)) {
- for (String[] s : klinesList) {
- // 确保数组有足够的元素
- if (s != null && s.length >= 9) {
- String s1 = s[8];
- try {
- if ("1".equals(s1)){
- Kline kline = new Kline();
- kline.setTs(s[0]);
- kline.setO(new BigDecimal(s[1]));
- kline.setH(new BigDecimal(s[2]));
- kline.setL(new BigDecimal(s[3]));
- kline.setC(new BigDecimal(s[4]));
- kline.setVol(new BigDecimal(s[5]));
- kline.setConfirm(s[8]);
- klineList.add(kline);
- }
- } catch (NumberFormatException e) {
- log.error("K线数据转换为BigDecimal失败: {}", Arrays.toString(s), e);
- }
- } else {
- log.warn("K线数据数组长度不足: {}", Arrays.toString(s));
- }
- }
- }
- } else {
- log.warn("K线数据为空");
- }
- } catch (JSONException e) {
- log.error("K线数据解析失败", e);
- } catch (Exception e) {
- log.error("获取K线数据异常", e);
- }
- return klineList;
- }
-
/**
- * 构建 Redis Key
+ * 解析仓位推送数据,提取目标合约的仓位信息并回调交易服务。
+ * 推送字段: contract, mode(dual_long/dual_short), size, entry_price, history_pnl, realised_pnl
+ *
+ * @param response 仓位推送的 JSON 对象
*/
- private String buildRedisKey(String instId) {
- return "PRICE_" + instId.replace("-", "");
+ private void processPositionData(JSONObject response) {
+ try {
+ JSONArray resultArray = response.getJSONArray("result");
+ if (resultArray == null || resultArray.isEmpty()) {
+ return;
+ }
+ for (int i = 0; i < resultArray.size(); i++) {
+ JSONObject pos = resultArray.getJSONObject(i);
+ String contract = pos.getString("contract");
+ if (!GATE_CONTRACT.equals(contract)) {
+ continue;
+ }
+ String mode = pos.getString("mode");
+ BigDecimal size = new BigDecimal(pos.getString("size"));
+ BigDecimal entryPrice = new BigDecimal(pos.getString("entry_price"));
+ BigDecimal historyPnl = new BigDecimal(pos.getString("history_pnl"));
+ BigDecimal realisedPnl = new BigDecimal(pos.getString("realised_pnl"));
+
+ log.info("仓位推送: contract={}, mode={}, size={}, entry_price={}, history_pnl={}, realised_pnl={}",
+ contract, mode, size, entryPrice, historyPnl, realisedPnl);
+
+ if (gridTradeService != null) {
+ gridTradeService.onPositionUpdate(contract, mode, size, entryPrice, historyPnl, realisedPnl);
+ }
+ }
+ } catch (Exception e) {
+ log.error("处理仓位推送数据失败", e);
+ }
}
/**
--
Gitblit v1.9.1