From 9eeb93bef2fca3583b03e27d83b19bb0126d6258 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Tue, 24 Nov 2026 11:29:39 +0800
Subject: [PATCH] fix(grid): 调整减仓模式递减追单数量计算逻辑

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java |  181 ++++++++++++++++++++++++++++++++++++++++-----
 1 files changed, 161 insertions(+), 20 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 0c08771..05389fb 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -12,6 +12,7 @@
 import java.net.URISyntaxException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 import java.util.concurrent.*;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -45,10 +46,12 @@
  *   <li>TCP 层:Java-WebSocket 自带 ping/pong 保活({@code connectionLostTimeout = 30s}),
  *       半开连接(对端静默丢包、无 FIN/RST)会被库判定丢失并触发 onClose。</li>
  *   <li>应用层:{@code futures.ping}/{@code futures.pong}。
- *       静默 10 秒 → 发 futures.ping 探测(可重置服务端关闭计数,官方文档语义);
- *       静默 20 秒(ping 也无任何回应)→ 判定连接不健康,主动 close → onClose → 重连。</li>
- *   <li>主动换线:连接存活满 55 分钟主动优雅重连,绕开链路中间设备约 1 小时的强制断连,
- *       把被动盲区变为计划内切换。</li>
+ *       静默 5 秒 → 发 futures.ping 探测(官方文档:客户端 ping 可重置服务端关闭计数);
+ *       静默 15 秒(ping 也无任何回应)→ 判定连接不健康,主动 close → onClose → 重连。</li>
+ *   <li>主动换线(默认关闭):连接存活满 MAX_CONNECTION_AGE_SECONDS 时才主动重连,
+ *       仅用于确认存在固定时长强制断连的网络环境。</li>
+ *   <li>周期状态确认:每 PERIODIC_PING_INTERVAL_SECONDS 秒主动发一次 futures.ping,
+ *       用于固定频率的存活确认/保活,不触发断开。</li>
  * </ol>
  *
  * <h3>重连策略</h3>
@@ -68,20 +71,28 @@
     private static final String FUTURES_PING = "futures.ping";
     private static final String FUTURES_PONG = "futures.pong";
     /** 静默超过该秒数 → 发送 futures.ping 探测(官方文档:客户端 ping 可重置服务端关闭计数) */
-    private static final int HEARTBEAT_TIMEOUT = 10;
+    private static final int HEARTBEAT_TIMEOUT = 5;
     /**
      * 静默超过该秒数(且已发出过探测 ping)→ 判定连接不健康,主动断开重连。
-     * 即:10s 静默发 ping,再等 10s 仍无任何消息(连 pong 都没有)→ 判定死亡。
+     * 即:5s 静默发 ping,再等 10s 仍无任何消息(连 pong 都没有)→ 判定死亡。
+     * 缩短该阈值可尽快发现"假活"(半开 TCP)连接,重连只作为兜底而非常态。
      */
-    private static final int DEAD_TIMEOUT_SECONDS = 20;
+    private static final int DEAD_TIMEOUT_SECONDS = 15;
+    /** 心跳检查周期(秒):原 25s 太长,假活连接最坏要 45s 才被发现,缩短到 10s */
+    private static final int HEARTBEAT_CHECK_INTERVAL_SECONDS = 10;
+    /** 周期状态确认间隔(秒):即使有数据流也定期发一次 futures.ping 做存活确认/保活,不触发断开 */
+    private static final int PERIODIC_PING_INTERVAL_SECONDS = 3600;
+    /** 订阅全部完成后链路活性验证窗口(秒):窗口内无任何消息 → 判定假活,立即断开重连 */
+    private static final int POST_SUBSCRIBE_ALIVE_CHECK_SECONDS = 10;
     /** Java-WebSocket 库层 ping/pong 保活超时(秒),用于检测半开 TCP 连接(兜底) */
     private static final int CONNECTION_LOST_TIMEOUT_SECONDS = 30;
     /**
-     * 连接最大存活时长(秒):到达后主动优雅断开重连("主动换线")。
-     * 用于绕开链路中间设备(腾讯云出口 NAT / 国际出口)约 1 小时的连接强制断连,
-     * 把被动盲区变成计划内换线。设为 0 可禁用。
+     * 连接最大存活时长(秒),设为 0 表示禁用"主动换线"。
+     * 默认禁用:主动换线会人为制造数据盲区,重连应只作为断线兜底。
+     * 仅当确认所在网络链路存在固定时长的强制断连(历史:腾讯云出口 NAT / 国际出口约 1 小时)
+     * 时,才把该值设为 > 0 重新启用。
      */
-    private static final int MAX_CONNECTION_AGE_SECONDS = 55 * 60;
+    private static final int MAX_CONNECTION_AGE_SECONDS = 0;
     /** 重连初始延迟(毫秒) */
     private static final long INITIAL_RECONNECT_DELAY_MS = 5000;
     /** 重连最大延迟(毫秒),指数退避封顶值 */
@@ -116,6 +127,21 @@
 
     /** 频道处理器列表,通过 addChannelHandler 注册 */
     private final List<GateChannelHandler> channelHandlers = new ArrayList<>();
+    /** 全部频道订阅完成后的回调(首次连接与重连后都会触发,供持仓对账等逻辑使用) */
+    private volatile Runnable onAllSubscribedCallback;
+    /** 设置全部频道订阅完成回调(由 GateGridTradeService 挂接,重连后触发持仓对账) */
+    public void setOnAllSubscribedCallback(Runnable callback) { this.onAllSubscribedCallback = callback; }
+
+    /** 订阅确认超时(秒):连接建立后超过该时长仍未全部订阅成功 → 判定订阅失败,断开重连 */
+    private static final int SUBSCRIBE_TIMEOUT_SECONDS = 20;
+    /** 单频道订阅失败后的重新订阅延迟(秒) */
+    private static final int RESUBSCRIBE_DELAY_SECONDS = 2;
+    /** 单频道订阅失败重试次数上限(超过则整体断开重连,重订阅全部频道) */
+    private static final int MAX_RESUBSCRIBE_RETRIES = 3;
+    /** 订阅确认超时 Future(连接建立后启动,全部订阅成功或断开时取消) */
+    private volatile ScheduledFuture<?> subscribeTimeoutFuture;
+    /** 各频道重新订阅重试计数(channelName → 次数),连接成功后清空 */
+    private final Map<String, AtomicInteger> resubscribeRetryCount = new ConcurrentHashMap<>();
 
     /** 重连等异步任务的缓存线程池(daemon 线程) */
     private final ExecutorService sharedExecutor = Executors.newCachedThreadPool(r -> {
@@ -188,6 +214,7 @@
         if (pongTimeoutFuture != null) {
             pongTimeoutFuture.cancel(true);
         }
+        cancelSubscribeTimeout();
         shutdownExecutorGracefully(heartbeatExecutor);
         shutdownExecutorGracefully(sharedExecutor);
 
@@ -246,7 +273,23 @@
                         for (GateChannelHandler handler : channelHandlers) {
                             handler.subscribe(webSocketClient);
                         }
-                        sendPing();
+                        try {
+                            if (webSocketClient != null && webSocketClient.isOpen()) {
+                                JSONObject pingMsg = new JSONObject();
+                                pingMsg.put("time", System.currentTimeMillis() / 1000);
+                                pingMsg.put("channel", FUTURES_PING);
+                                webSocketClient.send(pingMsg.toJSONString());
+                                log.debug("[WS] 发送 ping 请求");
+                            }
+                        } catch (Exception e) { log.warn("[WS] 发送 ping 失败", e); }
+                        // 订阅确认超时保护:若服务器既不回 subscribe 确认、也不回 error,
+                        // 超时后判定订阅失败断开重连,避免策略永久卡在 WAITING_KLINE
+                        cancelSubscribeTimeout();
+                        resubscribeRetryCount.clear();
+                        if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
+                            subscribeTimeoutFuture = heartbeatExecutor.schedule(
+                                    () -> checkSubscriptionTimeout(), SUBSCRIBE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
+                        }
                     } else {
                         log.warn("[WS] 应用正在关闭,忽略连接成功回调");
                     }
@@ -265,6 +308,7 @@
                     isConnected.set(false);
                     isConnecting.set(false);
                     cancelPongTimeout();
+                    cancelSubscribeTimeout();
                     scheduleReconnect();
                 }
 
@@ -316,6 +360,29 @@
                         break;
                     }
                 }
+                // 全部频道订阅完成(含重连后的重新订阅)→ 通知持仓对账等逻辑
+                if (areAllSubscribed()) {
+                    cancelSubscribeTimeout();
+                    resubscribeRetryCount.clear();
+                    // 订阅确认 ≠ 链路健康(半开连接可能在确认后立刻假死):
+                    // 立即发 futures.ping,并安排一次活性验证——窗口内无任何消息则判假活重连
+                    sendPing();
+                    if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
+                        heartbeatExecutor.schedule(() -> {
+                            if (!destroyed.get() && isConnected.get()
+                                    && System.currentTimeMillis() - lastMessageTime.get()
+                                    >= POST_SUBSCRIBE_ALIVE_CHECK_SECONDS * 1000L) {
+                                log.warn("[WS] 订阅完成后 {} 秒无任何消息,判定链路假活,断开重连",
+                                        POST_SUBSCRIBE_ALIVE_CHECK_SECONDS);
+                                closeSocket();
+                            }
+                        }, POST_SUBSCRIBE_ALIVE_CHECK_SECONDS, TimeUnit.SECONDS);
+                    }
+                    Runnable cb = onAllSubscribedCallback;
+                    if (cb != null) {
+                        cb.run();
+                    }
+                }
                 return;
             }
             if ("unsubscribe".equals(event)) {
@@ -323,11 +390,12 @@
                 return;
             }
             if ("error".equals(event)) {
-                JSONObject error = response.getJSONObject("error");
+                // 官方格式:code/message 在顶层(非嵌套 error 对象)
                 log.error("[WS] {} 错误, code:{}, msg:{}",
                         channel,
-                        error != null ? error.getInteger("code") : "N/A",
-                        error != null ? error.getString("message") : response.getString("msg"));
+                        response.getInteger("code"),
+                        response.getString("message"));
+                handleChannelSubscribeError(channel);
                 return;
             }
             if ("update".equals(event) || "all".equals(event)) {
@@ -355,16 +423,20 @@
 
     /**
      * 启动心跳检测器。
-     * 使用单线程 ScheduledExecutor,每 25 秒检查一次心跳超时。
+     * 使用单线程 ScheduledExecutor:每 10 秒检查一次心跳超时,并按固定间隔发送周期 ping。
      */
     private void startHeartbeat() {
         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);
+        heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout,
+                HEARTBEAT_CHECK_INTERVAL_SECONDS, HEARTBEAT_CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS);
+        // 周期性主动探测:数据流正常时也按固定间隔 ping 一次,确认链路存活(不触发重连)
+        heartbeatExecutor.scheduleWithFixedDelay(this::sendPing,
+                PERIODIC_PING_INTERVAL_SECONDS, PERIODIC_PING_INTERVAL_SECONDS, TimeUnit.SECONDS);
     }
 
     /**
-     * 重置心跳计时器:取消旧超时任务,提交新的 10 秒超时检测。
+     * 重置心跳计时器:取消旧超时任务,提交新的 HEARTBEAT_TIMEOUT 秒超时检测。
      */
     private synchronized void resetHeartbeatTimer() {
         cancelPongTimeout();
@@ -374,12 +446,13 @@
     }
 
     /**
-     * 心跳检查(由 25s 周期任务 + 每次收到消息后 10s 的一次性任务触发)。
+     * 心跳检查(由 {@link #HEARTBEAT_CHECK_INTERVAL_SECONDS} 秒周期任务 + 每次收到消息后
+     * {@link #HEARTBEAT_TIMEOUT} 秒的一次性任务触发)。
      * 主动健康检查逻辑(依据 Gate.io 官方文档 ping/pong 语义):
      * <ol>
      *   <li>连接存活 ≥ {@link #MAX_CONNECTION_AGE_SECONDS} 秒 → 主动优雅断开重连(主动换线,
      *       绕开链路中间设备约 1 小时的强制断连,把被动盲区变为计划内切换);</li>
-     *   <li>静默 ≥ {@link #HEARTBEAT_TIMEOUT} 秒 → 发送 futures.ping 探测,并安排 10 秒后复查;</li>
+     *   <li>静默 ≥ {@link #HEARTBEAT_TIMEOUT} 秒 → 发送 futures.ping 探测,并安排复查;</li>
      *   <li>静默 ≥ {@link #DEAD_TIMEOUT_SECONDS} 秒(探测 ping 也得不到任何回应,包括 pong)→
      *       判定连接不健康,主动断开触发重连。</li>
      * </ol>
@@ -442,6 +515,74 @@
         if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) pongTimeoutFuture.cancel(true);
     }
 
+    /**
+     * 订阅确认超时检查:连接建立后超过 {@link #SUBSCRIBE_TIMEOUT_SECONDS} 秒仍未全部订阅成功
+     * (服务器既不回 subscribe 确认、也不回 error),判定订阅失败,主动断开触发整体重连。
+     */
+    private void checkSubscriptionTimeout() {
+        if (destroyed.get() || !isConnected.get()) {
+            return;
+        }
+        if (!areAllSubscribed()) {
+            StringBuilder sb = new StringBuilder();
+            for (GateChannelHandler h : channelHandlers) {
+                if (!h.isSubscribed()) {
+                    if (sb.length() > 0) sb.append(',');
+                    sb.append(h.getChannelName());
+                }
+            }
+            log.warn("[WS] 连接建立 {} 秒后仍有频道未订阅成功({}), 判定订阅失败,断开重连",
+                    SUBSCRIBE_TIMEOUT_SECONDS, sb);
+            closeSocket();
+        }
+    }
+
+    /** 取消订阅确认超时任务。 */
+    private void cancelSubscribeTimeout() {
+        if (subscribeTimeoutFuture != null && !subscribeTimeoutFuture.isDone()) {
+            subscribeTimeoutFuture.cancel(true);
+        }
+        subscribeTimeoutFuture = null;
+    }
+
+    /**
+     * 频道订阅失败处理:先按频道延迟重新订阅(有限次数),超过上限则整体断开重连。
+     * 覆盖"鉴权失败/订阅参数错误"等 error 场景,避免订阅失败后策略永久卡在 WAITING_KLINE。
+     */
+    private void handleChannelSubscribeError(String channel) {
+        if (destroyed.get()) {
+            return;
+        }
+        GateChannelHandler target = null;
+        for (GateChannelHandler h : channelHandlers) {
+            if (channel.equals(h.getChannelName())) {
+                target = h;
+                break;
+            }
+        }
+        if (target == null) {
+            return;
+        }
+        target.setSubscribed(false);
+        int retries = resubscribeRetryCount.computeIfAbsent(channel, k -> new AtomicInteger()).incrementAndGet();
+        if (retries > MAX_RESUBSCRIBE_RETRIES) {
+            log.warn("[WS] {} 重新订阅失败已达 {} 次,断开整体重连", channel, retries - 1);
+            closeSocket();
+            return;
+        }
+        log.warn("[WS] {} 订阅失败(第{}次),{} 秒后重新订阅", channel, retries, RESUBSCRIBE_DELAY_SECONDS);
+        if (heartbeatExecutor == null || heartbeatExecutor.isShutdown()) {
+            return;
+        }
+        // target 在查找循环中被赋值,非 effectively final,须用 final 变量捕获进 lambda
+        final GateChannelHandler handlerToResubscribe = target;
+        heartbeatExecutor.schedule(() -> {
+            if (!destroyed.get() && isConnected.get() && webSocketClient != null && webSocketClient.isOpen()) {
+                handlerToResubscribe.subscribe(webSocketClient);
+            }
+        }, RESUBSCRIBE_DELAY_SECONDS, TimeUnit.SECONDS);
+    }
+
     // ---- reconnect ----
 
     /**

--
Gitblit v1.9.1