From 6d213ed49218afbf8b83e440eba41f642a4695f2 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Fri, 08 May 2026 10:30:23 +0800
Subject: [PATCH] feat(gateApi): 添加用户ID获取和WebSocket私有频道订阅功能
---
src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java | 84 +++++++++++++++++++++++++++++++++++++----
1 files changed, 75 insertions(+), 9 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 f210f05..6fe824a 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -16,14 +16,33 @@
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
+import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
- * 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
@@ -35,23 +54,35 @@
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 = "XAUT_USDT";
+ /** 网格交易策略实例 */
private GateGridTradeService gridTradeService;
+ /** API 密钥,用于私有频道签名 */
private final String apiKey;
+ /** API 密钥 */
private final String apiSecret;
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
@@ -251,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);
@@ -259,14 +294,23 @@
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("id", timeSec * 1000000 + (System.currentTimeMillis() % 1000));
subscribeMsg.put("time", timeSec);
subscribeMsg.put("channel", POSITIONS_CHANNEL);
subscribeMsg.put("event", "subscribe");
+
+ String uid = gridTradeService != null && gridTradeService.getUserId() != null
+ ? String.valueOf(gridTradeService.getUserId()) : "";
+
JSONArray payload = new JSONArray();
- payload.add("user_id");
+ payload.add(uid);
payload.add(GATE_CONTRACT);
subscribeMsg.put("payload", payload);
@@ -277,28 +321,41 @@
subscribeMsg.put("auth", auth);
webSocketClient.send(subscribeMsg.toJSONString());
- log.info("已发送仓位频道订阅请求(含认证),合约: {}", GATE_CONTRACT);
+ log.info("已发送仓位频道订阅请求(含认证),userId:{}, 合约: {}", uid, 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(), "HmacSHA512");
+ SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA512");
mac.init(spec);
- byte[] hash = mac.doFinal(message.getBytes());
+ 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]);
}
- return hex.toString();
+ 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);
@@ -312,6 +369,9 @@
log.info("已发送 K线频道取消订阅请求,合约: {}, 周期: {}", GATE_CONTRACT, GATE_INTERVAL);
}
+ /**
+ * 取消订阅仓位频道。
+ */
private void unsubscribePositionsChannels() {
JSONObject unsubscribeMsg = new JSONObject();
unsubscribeMsg.put("time", System.currentTimeMillis() / 1000);
@@ -434,6 +494,12 @@
}
}
+ /**
+ * 解析仓位推送数据,提取目标合约的仓位信息并回调交易服务。
+ * 推送字段: contract, mode(dual_long/dual_short), size, entry_price, history_pnl, realised_pnl
+ *
+ * @param response 仓位推送的 JSON 对象
+ */
private void processPositionData(JSONObject response) {
try {
JSONArray resultArray = response.getJSONArray("result");
--
Gitblit v1.9.1