| | |
| | | package com.xcong.excoin.modules.gateApi; |
| | | |
| | | 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.okxWs.wanggeList.WangGeListService; |
| | | import com.xcong.excoin.modules.gateApi.wsHandler.GateChannelHandler; |
| | | import com.xcong.excoin.modules.okxNewPrice.utils.SSLConfig; |
| | | 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.nio.charset.StandardCharsets; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | import java.util.concurrent.*; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | |
| | | /** |
| | | * Gate WebSocket 客户端,通过 Java-WebSocket 库连接 Gate.io 的 WebSocket 接口。 |
| | | * Gate 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> |
| | | * 负责 TCP 连接的建立、维持和恢复。频道逻辑(订阅/解析)全部委托给 {@link GateChannelHandler} 实现类。 |
| | | * |
| | | * <h3>数据流</h3> |
| | | * <h3>生命周期</h3> |
| | | * <pre> |
| | | * onMessage → handleWebSocketMessage → 按 channel 分流: |
| | | * futures.pong → 取消心跳超时 |
| | | * subscribe/unsubscribe/error → 日志 |
| | | * futures.candlesticks → processPushDataV2 → GateGridTradeService.onKline() |
| | | * futures.positions → processPositionData → GateGridTradeService.onPositionUpdate() |
| | | * init() → connect() → startHeartbeat() |
| | | * destroy() → unsubscribe 所有 handler → closeBlocking() → shutdown 线程池 |
| | | * onClose() → reconnectWithBackoff() (最多 3 次,指数退避) |
| | | * </pre> |
| | | * |
| | | * <h3>连接管理</h3> |
| | | * 支持心跳检测、指数退避重连(最多 3 次)、优雅关闭。 |
| | | * <h3>消息路由</h3> |
| | | * <pre> |
| | | * onMessage → handleMessage: |
| | | * 1. futures.pong → cancelPongTimeout |
| | | * 2. subscribe/unsubscribe → 日志 |
| | | * 3. error → 错误日志 |
| | | * 4. update/all → 遍历 channelHandlers → handler.handleMessage(response) |
| | | * </pre> |
| | | * |
| | | * <h3>心跳机制</h3> |
| | | * 采用双重检测:TCP 层的 WebSocket ping/pong + 应用层 futures.ping/futures.pong。 |
| | | * 10 秒未收到任何消息 → 发送 futures.ping;25 秒周期检查。 |
| | | * |
| | | * <h3>线程安全</h3> |
| | | * 连接状态用 AtomicBoolean(isConnected, isConnecting, isInitialized)。 |
| | | * 消息时间戳用 AtomicReference。心跳任务用 synchronized 保护。 |
| | | * |
| | | * @author Administrator |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | @Slf4j |
| | | public class GateKlineWebSocketClient { |
| | | private final CaoZuoService caoZuoService; |
| | | private final GateWebSocketClientManager clientManager; |
| | | private final WangGeListService wangGeListService; |
| | | |
| | | private static final String FUTURES_PING = "futures.ping"; |
| | | private static final String FUTURES_PONG = "futures.pong"; |
| | | private static final int HEARTBEAT_TIMEOUT = 10; |
| | | |
| | | /** WebSocket 地址,由 GateConfig 提供 */ |
| | | private final String wsUrl; |
| | | |
| | | /** Java-WebSocket 客户端实例 */ |
| | | private WebSocketClient webSocketClient; |
| | | /** 心跳检测调度器 */ |
| | | private ScheduledExecutorService heartbeatExecutor; |
| | | /** 心跳超时 Future */ |
| | | 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); |
| | | /** 初始化标记,防止重复初始化 */ |
| | | /** 初始化标记,防重复 init */ |
| | | 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"; |
| | | /** 频道处理器列表,通过 addChannelHandler 注册 */ |
| | | private final List<GateChannelHandler> channelHandlers = new ArrayList<>(); |
| | | |
| | | /** 网格交易策略实例 */ |
| | | 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; |
| | | |
| | | // 共享线程池用于重连等异步任务 |
| | | /** 重连等异步任务的缓存线程池(daemon 线程) */ |
| | | private final ExecutorService sharedExecutor = Executors.newCachedThreadPool(r -> { |
| | | Thread t = new Thread(r, "gate-kline-worker"); |
| | | Thread t = new Thread(r, "gate-ws-worker"); |
| | | t.setDaemon(true); |
| | | return t; |
| | | }); |
| | | |
| | | public GateKlineWebSocketClient(CaoZuoService caoZuoService, |
| | | GateWebSocketClientManager clientManager, |
| | | 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; |
| | | public GateKlineWebSocketClient(String wsUrl) { |
| | | this.wsUrl = wsUrl; |
| | | } |
| | | |
| | | /** |
| | | * 初始化方法,创建并初始化WebSocket客户端实例 |
| | | * 注册频道处理器。需在 init() 前调用。 |
| | | */ |
| | | public void addChannelHandler(GateChannelHandler handler) { |
| | | channelHandlers.add(handler); |
| | | } |
| | | |
| | | /** |
| | | * 初始化:建立 WebSocket 连接 → 启动心跳。 |
| | | */ |
| | | public void init() { |
| | | if (!isInitialized.compareAndSet(false, true)) { |
| | | log.warn("GateKlineWebSocketClient 已经初始化过,跳过重复初始化"); |
| | | log.warn("[WS] 已初始化过,跳过重复初始化"); |
| | | return; |
| | | } |
| | | connect(); |
| | |
| | | } |
| | | |
| | | /** |
| | | * 销毁方法,关闭WebSocket连接和相关资源 |
| | | * 销毁:取消订阅 → 关闭连接 → 关闭线程池。 |
| | | * <p>注意:先 closeBlocking 再 shutdown sharedExecutor, |
| | | * 避免 onClose 回调中的 reconnectWithBackoff 访问已关闭的线程池。 |
| | | */ |
| | | public void destroy() { |
| | | log.info("开始销毁GateKlineWebSocketClient"); |
| | | log.info("[WS] 开始销毁..."); |
| | | |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | unsubscribeKlineChannels(); |
| | | unsubscribePositionsChannels(); |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | | handler.unsubscribe(webSocketClient); |
| | | } |
| | | try { |
| | | Thread.sleep(500); |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | log.warn("取消订阅等待被中断"); |
| | | log.warn("[WS] 取消订阅等待被中断"); |
| | | } |
| | | } |
| | | |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown()) { |
| | | sharedExecutor.shutdown(); |
| | | } |
| | | |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | |
| | | webSocketClient.closeBlocking(); |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | log.warn("关闭WebSocket连接时被中断"); |
| | | log.warn("[WS] 关闭连接时被中断"); |
| | | } |
| | | } |
| | | |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown()) { |
| | | sharedExecutor.shutdown(); |
| | | } |
| | | |
| | | shutdownExecutorGracefully(heartbeatExecutor); |
| | |
| | | } |
| | | shutdownExecutorGracefully(sharedExecutor); |
| | | |
| | | log.info("GateKlineWebSocketClient销毁完成"); |
| | | log.info("[WS] 销毁完成"); |
| | | } |
| | | |
| | | private static final String WS_URL_MONIPAN = "wss://ws-testnet.gate.com/v4/ws/futures/usdt"; |
| | | private static final String WS_URL_SHIPAN = "wss://fx-ws.gateio.ws/v4/ws/usdt"; |
| | | private static final boolean isAccountType = false; |
| | | |
| | | /** |
| | | * 建立与 Gate WebSocket 服务器的连接。 |
| | | * 设置回调函数以监听连接打开、接收消息、关闭和错误事件。 |
| | | * 建立 WebSocket 连接。使用 SSLContext 配置 TLS 协议。 |
| | | * 连接成功后依次订阅所有已注册的频道处理器。 |
| | | */ |
| | | private void connect() { |
| | | // 避免重复连接 |
| | | if (isConnecting.get()) { |
| | | log.info("连接已在进行中,跳过重复连接请求"); |
| | | if (isConnecting.get() || !isConnecting.compareAndSet(false, true)) { |
| | | log.info("[WS] 连接进行中,跳过重复请求"); |
| | | return; |
| | | } |
| | | |
| | | if (!isConnecting.compareAndSet(false, true)) { |
| | | log.info("连接已在进行中,跳过重复连接请求"); |
| | | return; |
| | | } |
| | | |
| | | try { |
| | | SSLConfig.configureSSL(); |
| | | System.setProperty("https.protocols", "TLSv1.2,TLSv1.3"); |
| | | String WS_URL = WS_URL_MONIPAN; |
| | | if (isAccountType){ |
| | | WS_URL = WS_URL_SHIPAN; |
| | | } |
| | | URI uri = new URI(WS_URL); |
| | | |
| | | // 关闭之前的连接(如果存在) |
| | | URI uri = new URI(wsUrl); |
| | | if (webSocketClient != null) { |
| | | try { |
| | | webSocketClient.closeBlocking(); |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | log.warn("关闭之前连接时被中断"); |
| | | } |
| | | try { webSocketClient.closeBlocking(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } |
| | | } |
| | | |
| | | webSocketClient = new WebSocketClient(uri) { |
| | | @Override |
| | | public void onOpen(ServerHandshake handshake) { |
| | | log.info("Gate Kline WebSocket连接成功"); |
| | | log.info("[WS] 连接成功"); |
| | | isConnected.set(true); |
| | | isConnecting.set(false); |
| | | |
| | | // 检查应用是否正在关闭 |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown()) { |
| | | resetHeartbeatTimer(); |
| | | subscribeKlineChannels(); |
| | | subscribePositionsChannels(); |
| | | subscribePingChannels(); |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | | handler.subscribe(webSocketClient); |
| | | } |
| | | sendPing(); |
| | | } else { |
| | | log.warn("应用正在关闭,忽略WebSocket连接成功回调"); |
| | | log.warn("[WS] 应用正在关闭,忽略连接成功回调"); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void onMessage(String message) { |
| | | lastMessageTime.set(System.currentTimeMillis()); |
| | | handleWebSocketMessage(message); |
| | | handleMessage(message); |
| | | resetHeartbeatTimer(); |
| | | } |
| | | |
| | | @Override |
| | | public void onClose(int code, String reason, boolean remote) { |
| | | log.warn("Gate Kline WebSocket连接关闭: code={}, reason={}", code, reason); |
| | | log.warn("[WS] 连接关闭, code:{}, reason:{}", code, reason); |
| | | isConnected.set(false); |
| | | isConnecting.set(false); |
| | | cancelPongTimeout(); |
| | | |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown() && !sharedExecutor.isTerminated()) { |
| | | sharedExecutor.execute(() -> { |
| | | try { |
| | | reconnectWithBackoff(); |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | log.error("重连线程被中断", e); |
| | | } catch (Exception e) { |
| | | log.error("重连失败", e); |
| | | } |
| | | try { reconnectWithBackoff(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { log.error("[WS] 重连失败", e); } |
| | | }); |
| | | } else { |
| | | log.warn("共享线程池已关闭,无法执行重连任务"); |
| | | log.warn("[WS] 线程池已关闭,不执行重连"); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void onError(Exception ex) { |
| | | log.error("Gate Kline WebSocket发生错误", ex); |
| | | log.error("[WS] 发生错误", ex); |
| | | isConnected.set(false); |
| | | } |
| | | }; |
| | | |
| | | webSocketClient.connect(); |
| | | } catch (URISyntaxException e) { |
| | | log.error("WebSocket URI格式错误", e); |
| | | log.error("[WS] URI格式错误", e); |
| | | isConnecting.set(false); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 订阅K线频道。 |
| | | * 构造 Gate 格式的订阅请求并发送给服务端。 |
| | | * payload: ["1m", "BTC_USDT"] (间隔, 合约名) |
| | | * 消息分发:先处理系统事件(pong/subscribe/error), |
| | | * 再把 update/all 事件路由到各 channelHandler。 |
| | | * <p>每个 handler 内部通过 channel 名称做二次匹配,匹配成功返回 true 则停止遍历。 |
| | | */ |
| | | private void subscribeKlineChannels() { |
| | | JSONObject subscribeMsg = new JSONObject(); |
| | | subscribeMsg.put("time", System.currentTimeMillis() / 1000); |
| | | subscribeMsg.put("channel", CHANNEL); |
| | | subscribeMsg.put("event", "subscribe"); |
| | | |
| | | JSONArray payload = new JSONArray(); |
| | | payload.add(GATE_INTERVAL); |
| | | payload.add(GATE_CONTRACT); |
| | | subscribeMsg.put("payload", payload); |
| | | |
| | | 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); |
| | | subscribeMsg.put("channel", FUTURES_PING); |
| | | webSocketClient.send(subscribeMsg.toJSONString()); |
| | | 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(uid); |
| | | 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("已发送仓位频道订阅请求(含认证),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(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); |
| | | unsubscribeMsg.put("channel", CHANNEL); |
| | | unsubscribeMsg.put("event", "unsubscribe"); |
| | | JSONArray payload = new JSONArray(); |
| | | payload.add(GATE_INTERVAL); |
| | | payload.add(GATE_CONTRACT); |
| | | 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); |
| | | } |
| | | |
| | | /** |
| | | * 处理从 WebSocket 收到的消息。 |
| | | * 包括订阅确认、错误响应、心跳响应以及实际的数据推送。 |
| | | * |
| | | * @param message 来自 WebSocket 的原始字符串消息 |
| | | */ |
| | | private void handleWebSocketMessage(String message) { |
| | | private void handleMessage(String message) { |
| | | try { |
| | | JSONObject response = JSON.parseObject(message); |
| | | String channel = response.getString("channel"); |
| | | String event = response.getString("event"); |
| | | |
| | | if (FUTURES_PONG.equals(channel)) { |
| | | log.debug("收到futures.pong响应"); |
| | | log.debug("[WS] 收到 pong 响应"); |
| | | cancelPongTimeout(); |
| | | } else if ("subscribe".equals(event)) { |
| | | log.info("{} 频道订阅成功: {}", channel, response.getJSONObject("result")); |
| | | } else if ("unsubscribe".equals(event)) { |
| | | log.info("{} 频道取消订阅成功", channel); |
| | | } else if ("error".equals(event)) { |
| | | return; |
| | | } |
| | | if ("subscribe".equals(event)) { |
| | | log.info("[WS] {} 订阅成功: {}", channel, response.getJSONObject("result")); |
| | | return; |
| | | } |
| | | if ("unsubscribe".equals(event)) { |
| | | log.info("[WS] {} 取消订阅成功", channel); |
| | | return; |
| | | } |
| | | if ("error".equals(event)) { |
| | | JSONObject error = response.getJSONObject("error"); |
| | | log.error("{} 频道错误: code={}, msg={}", |
| | | log.error("[WS] {} 错误, code:{}, msg:{}", |
| | | channel, |
| | | error != null ? error.getInteger("code") : "N/A", |
| | | error != null ? error.getString("message") : response.getString("msg")); |
| | | } else if ("update".equals(event) || "all".equals(event)) { |
| | | if (POSITIONS_CHANNEL.equals(channel)) { |
| | | processPositionData(response); |
| | | } else if (CHANNEL.equals(channel)) { |
| | | processPushDataV2(response); |
| | | return; |
| | | } |
| | | if ("update".equals(event) || "all".equals(event)) { |
| | | for (GateChannelHandler handler : channelHandlers) { |
| | | if (handler.handleMessage(response)) return; |
| | | } |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("处理WebSocket消息失败: {}", message, e); |
| | | log.error("[WS] 处理消息失败: {}", message, e); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 解析并处理K线推送数据。 |
| | | * 控制台输出K线数据,并在K线完结时触发策略和量化操作。 |
| | | * |
| | | * @param response 包含K线数据的 JSON 对象 |
| | | */ |
| | | private void processPushDataV2(JSONObject response) { |
| | | try { |
| | | /** |
| | | * Gate K线推送格式: |
| | | * { |
| | | * "time": 1542162490, |
| | | * "time_ms": 1542162490123, |
| | | * "channel": "futures.candlesticks", |
| | | * "event": "update", |
| | | * "result": [ |
| | | * { |
| | | * "t": 1545129300, |
| | | * "v": "27525555", |
| | | * "c": "95.4", |
| | | * "h": "96.9", |
| | | * "l": "89.5", |
| | | * "o": "94.3", |
| | | * "n": "1m_BTC_USD", |
| | | * "a": "314732.87412", |
| | | * "w": false |
| | | * } |
| | | * ] |
| | | * } |
| | | */ |
| | | String channel = response.getString("channel"); |
| | | if (!CHANNEL.equals(channel)) { |
| | | return; |
| | | } |
| | | // ---- heartbeat ---- |
| | | |
| | | JSONArray resultArray = response.getJSONArray("result"); |
| | | if (resultArray == null || resultArray.isEmpty()) { |
| | | log.warn("K线频道数据为空"); |
| | | return; |
| | | } |
| | | |
| | | JSONObject data = resultArray.getJSONObject(0); |
| | | BigDecimal openPx = new BigDecimal(data.getString("o")); |
| | | BigDecimal highPx = new BigDecimal(data.getString("h")); |
| | | BigDecimal lowPx = new BigDecimal(data.getString("l")); |
| | | BigDecimal closePx = new BigDecimal(data.getString("c")); |
| | | BigDecimal vol = new BigDecimal(data.getString("v")); |
| | | BigDecimal baseVol = new BigDecimal(data.getString("a")); |
| | | String name = data.getString("n"); |
| | | long t = data.getLong("t"); |
| | | boolean windowClosed = data.getBooleanValue("w"); |
| | | String time = DateUtil.TimeStampToDateTime(t); |
| | | |
| | | 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); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 解析仓位推送数据,提取目标合约的仓位信息并回调交易服务。 |
| | | * 推送字段: 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"); |
| | | 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); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 启动心跳检测任务。 |
| | | * 使用 ScheduledExecutorService 定期检查是否需要发送 ping 请求来维持连接。 |
| | | */ |
| | | private void startHeartbeat() { |
| | | if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) { |
| | | heartbeatExecutor.shutdownNow(); |
| | | } |
| | | |
| | | heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> { |
| | | Thread t = new Thread(r, "gate-kline-heartbeat"); |
| | | t.setDaemon(true); |
| | | return t; |
| | | }); |
| | | |
| | | if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) heartbeatExecutor.shutdownNow(); |
| | | heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "gate-ws-heartbeat"); t.setDaemon(true); return t; }); |
| | | heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, 25, 25, TimeUnit.SECONDS); |
| | | } |
| | | |
| | | /** |
| | | * 重置心跳计时器。 |
| | | * 当收到新消息或发送 ping 后取消当前超时任务并重新安排下一次超时检查。 |
| | | */ |
| | | private synchronized void resetHeartbeatTimer() { |
| | | cancelPongTimeout(); |
| | | |
| | | if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) { |
| | | pongTimeoutFuture = heartbeatExecutor.schedule(this::checkHeartbeatTimeout, |
| | | HEARTBEAT_TIMEOUT, TimeUnit.SECONDS); |
| | | pongTimeoutFuture = heartbeatExecutor.schedule(this::checkHeartbeatTimeout, HEARTBEAT_TIMEOUT, TimeUnit.SECONDS); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 检查心跳超时情况。 |
| | | * 若长时间未收到任何消息则主动发送 ping 请求保持连接活跃。 |
| | | */ |
| | | private void checkHeartbeatTimeout() { |
| | | // 只有在连接状态下才检查心跳 |
| | | if (!isConnected.get()) { |
| | | return; |
| | | } |
| | | |
| | | long currentTime = System.currentTimeMillis(); |
| | | long lastTime = lastMessageTime.get(); |
| | | |
| | | if (currentTime - lastTime >= HEARTBEAT_TIMEOUT * 1000L) { |
| | | sendPing(); |
| | | } |
| | | if (!isConnected.get()) return; |
| | | if (System.currentTimeMillis() - lastMessageTime.get() >= HEARTBEAT_TIMEOUT * 1000L) sendPing(); |
| | | } |
| | | |
| | | /** |
| | | * 发送 ping 请求至 WebSocket 服务端。 |
| | | * 用于维持长连接有效性。 |
| | | */ |
| | | private void sendPing() { |
| | | try { |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | |
| | | pingMsg.put("time", System.currentTimeMillis() / 1000); |
| | | pingMsg.put("channel", FUTURES_PING); |
| | | webSocketClient.send(pingMsg.toJSONString()); |
| | | log.debug("发送futures.ping请求"); |
| | | log.debug("[WS] 发送 ping 请求"); |
| | | } |
| | | } catch (Exception e) { |
| | | log.warn("发送ping失败", e); |
| | | } |
| | | } catch (Exception e) { log.warn("[WS] 发送 ping 失败", e); } |
| | | } |
| | | |
| | | /** |
| | | * 取消当前的心跳超时任务。 |
| | | * 在收到 pong 或其他有效消息时调用此方法避免不必要的断开重连。 |
| | | */ |
| | | private synchronized void cancelPongTimeout() { |
| | | if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) { |
| | | pongTimeoutFuture.cancel(true); |
| | | } |
| | | if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) pongTimeoutFuture.cancel(true); |
| | | } |
| | | |
| | | /** |
| | | * 执行 WebSocket 重连操作。 |
| | | * 在连接意外中断后尝试重新建立连接。 |
| | | */ |
| | | // ---- reconnect ---- |
| | | |
| | | private void reconnectWithBackoff() throws InterruptedException { |
| | | int attempt = 0; |
| | | int maxAttempts = 3; |
| | | int attempt = 0, maxAttempts = 3; |
| | | long delayMs = 5000; |
| | | |
| | | while (attempt < maxAttempts) { |
| | | try { |
| | | Thread.sleep(delayMs); |
| | | connect(); |
| | | return; |
| | | } catch (Exception e) { |
| | | log.warn("第{}次重连失败", attempt + 1, e); |
| | | delayMs *= 2; |
| | | attempt++; |
| | | } |
| | | try { Thread.sleep(delayMs); connect(); return; } catch (Exception e) { log.warn("[WS] 第{}次重连失败", attempt + 1, e); delayMs *= 2; attempt++; } |
| | | } |
| | | |
| | | log.error("超过最大重试次数({})仍未连接成功", maxAttempts); |
| | | log.error("[WS] 超过最大重试次数({}),放弃重连", maxAttempts); |
| | | } |
| | | |
| | | /** |
| | | * 优雅关闭线程池 |
| | | */ |
| | | private void shutdownExecutorGracefully(ExecutorService executor) { |
| | | if (executor == null || executor.isTerminated()) { |
| | | return; |
| | | } |
| | | try { |
| | | executor.shutdown(); |
| | | if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { |
| | | executor.shutdownNow(); |
| | | } |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | executor.shutdownNow(); |
| | | } |
| | | if (executor == null || executor.isTerminated()) return; |
| | | try { executor.shutdown(); if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); } |
| | | catch (InterruptedException e) { Thread.currentThread().interrupt(); executor.shutdownNow(); } |
| | | } |
| | | } |
| | | } |