From adcdcddb3e4a3d1bb22a1cec8f394d2f303ee6e2 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Fri, 06 Nov 2026 11:25:58 +0800
Subject: [PATCH] fix(grid): 修复网格并发修改异常与日志变量错误

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java     |  254 +++++++++++++-----------
 src/main/java/com/xcong/excoin/modules/gateApi/GateClosingApiClient.java     |   39 +++
 docs/策略运转逻辑.md                                                               |  189 ++++++++++++++++++
 src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java |   97 +++++++++
 4 files changed, 457 insertions(+), 122 deletions(-)

diff --git "a/docs/\347\255\226\347\225\245\350\277\220\350\275\254\351\200\273\350\276\221.md" "b/docs/\347\255\226\347\225\245\350\277\220\350\275\254\351\200\273\350\276\221.md"
new file mode 100644
index 0000000..7852c6b
--- /dev/null
+++ "b/docs/\347\255\226\347\225\245\350\277\220\350\275\254\351\200\273\350\276\221.md"
@@ -0,0 +1,189 @@
+# Gate 网格策略运转逻辑总览
+
+> 基于 gate-zhisun-v2-test 分支当前代码整理(2026-11-05)。
+> 策略 = 双向网格(多仓网格 + 空仓网格),止损触发后追单重建仓位,止盈网格收割利润,仓位归零/盈利达标自动重启轮次。
+
+---
+
+## 1. 架构与线程模型
+
+### 1.1 组成
+- **Station(站内面板)**:Web 看板 + RabbitMQ 指令(START/STOP/改参数/平仓/重置);
+- **Gate JAR(策略引擎)**:app.gate.enabled=true 时启用,核心类 GateGridTradeService;
+- **通信**:站↔JAR 走 RabbitMQ(direct exchange biue-exchange-gate);JAR↔交易所走 REST + WebSocket v4。
+
+### 1.2 WS 四频道(GateKlineWebSocketClient + 4 个 handler)
+| 频道 | 类型 | 驱动什么 |
+|---|---|---|
+| futures.candlesticks(1m) | 公开 | 唯一时间/价格驱动源 → onKline |
+| futures.positions | 私有 | 持仓推送 → onPositionUpdate |
+| futures.position_closes | 私有 | 平仓推送 → onPositionClose(盈亏累计/风控) |
+| futures.autoorders | 私有 | 条件单状态 → onAutoOrder(止损/止盈/开仓成交分发) |
+
+### 1.3 线程模型
+| 线程 | 职责 |
+|---|---|
+| WS ReadThread | 解析推送,直接调用服务方法(止损/止盈/成交/持仓处理) |
+| te-trade-worker(单线程池) | 所有 REST 下单/撤单/查询任务 FIFO 串行(回调也在该线程) |
+| gate-ws-worker | 重连循环 |
+| te-ws-heartbeat | 25s 周期心跳检查(静默探测/主动换线) |
+| 节流对账任务 | 提交到交易线程池,15s 一次 |
+
+并发安全:持仓字段 volatile;GridElement 订单 ID 列表 CopyOnWriteArrayList;size 映射 ConcurrentHashMap;tryGenerateQueues synchronized;轮次重置整体提交到 executor 队列末尾保证顺序。
+
+---
+
+## 2. 生命周期状态机
+
+```
+STOPPED →(startGrid)→ WAITING_KLINE →(首根K线)→ OPENING →(双基底成交+挂完止损止盈)→ ACTIVE
+ACTIVE →(仓位归零/盈利达标/轮数上限/手动)→ STOPPED →(自动/手动)→ WAITING_KLINE …
+```
+
+- **WAITING_KLINE**:等首根 K 线(顺带等四频道订阅完成)。
+- **OPENING**:市价 IOC 开多空基底各 baseQuantity 张;双基底成交后生成网格队列、首挂止损止盈 → ACTIVE。
+- **ACTIVE**:主循环(止损/止盈/价格驱动/风控/对账)。
+- **STOPPED**:全撤单+平仓后短暂停留(3 秒),自动 startGrid() 进入下一轮。
+
+---
+
+## 3. 启动与基底(onKline 首根K线)
+
+1. startGrid():清状态/计数器(**累计盈亏不清零,全局口径**)、加载配置;
+2. 首根 K 线到达 → 开基底:多仓 openLong(base)、空仓 openShort(-base)(市价 IOC);
+3. 双基底成交(WS 推送,丢失时由对账 REST 补齐)→ tryGenerateQueues();
+4. 生成双向网格队列 + 首挂止损:空仓止损挂入场格上方第 2 格、多仓挂下方第 2 格,各覆盖 base 张(1 张/单)。
+
+---
+
+## 4. 网格构建
+
+- 以基底成交价为基准(grid 0),按 gridStep 向上下各生成 N 个网格(totalLongPriceQueue 升序=多仓侧、totalShortPriceQueue 降序=空仓侧);
+- 每个 GridElement:价格、上下指针、多/空挂单 ID 列表与张数映射、止盈/止损订单 ID 与张数映射、TraderParam(张数/orderId/placed 标记)。
+
+---
+
+## 5. 止损体系(核心循环)
+
+### 5.1 首挂与延展
+- 止损单 order_type=plan-close-long/short-position,覆盖张数 = max(filledQty, baseQty)(**全仓覆盖**);
+- 开仓成交后 extendLong/ShortStopLoss(posSize, entryGrid) 在入场格 ±2 起逐格重挂,余数补在最外侧。
+
+### 5.2 止损触发 → 追单(handleXxxStopLossTriggered)
+1. 该网格止损单 finished(trade_id 有效)→ 记录止损次数 +1;
+2. calculateEntryQuantity(方向, respectCurrentPosition=true, 本网格止损张数) 计算追单张数:
+   - REST 查当前持仓并减去本网格止损张数(修正 REST 时序竞态);
+   - 张数 = 基础 + 加仓量,上限 maxPositionPerSide;
+3. 在入场格 ±1 挂条件开仓单,成交后走 ENTRY_FILLED → 延展止损。
+
+### 5.3 加仓公式(computeAddQty)
+```
+effectiveCount = max(0, 累计止损次数 - addPositionStartThreshold)
+divisor        = addPositionInterval + 1
+addMultiplier  = floor(effectiveCount / divisor)
+addQty         = addMultiplier × addPositionQuantity
+停止阈值:加仓执行次数 ≥ addPositionStopThreshold → addQty=0(回到基础张数)
+```
+- **加仓执行次数 = 含加仓量的开仓单「真正成交」后 +1**(挂单后被取消的不算);
+- 计数口径按 stopLossCountMode:single=单方向、dual=双向合计;
+- 价格驱动的仓位归零重入同样套用公式(挂单时打标记、成交才计数),对向加仓/补仓不计数。
+
+### 5.4 同网格防抖
+同一网格连续触发只处理第一次(lastLong/ShortStopLossGridId),其余忽略。
+
+---
+
+## 6. 止盈体系(handleXxxTakeProfitTriggered)
+
+| 类型 | 触发条件 | 行为 |
+|---|---|---|
+| 基础止盈 | 仓位 > 基础张数时,在入场格上方逐格挂 baseTakeProfitPerGrid 张(≤gridCount 格) | 成交即落袋 |
+| 超额止盈 | placeExcessTakeProfit=concentrated:全部超额挂在一个网格;dispersed:逐格分散 | 同上 |
+| 对向加仓止盈 | tpTriggerOppositeAdd 开:止盈成交后在相邻格反向挂一张 | 增加网格密度 |
+| 仓位止盈补仓 | tpPositionReplenishEnabled 开:止盈成交后补回原方向仓位 | 见下 |
+
+**仓位止盈补仓(专用分支)**:止盈平掉 N 张后,在相邻网格挂同方向 N 张开仓单;成交后(handleReplenishXxxAddFilled)**只取消该方向的全部止损并按原止损位置、以最新总持仓重挂**(不动止盈、不扩展新位置)。
+
+---
+
+## 7. 价格驱动(仓位归零重入,processLongGrid/processShortGrid)
+
+条件:state==ACTIVE && isPriceDriveEnabled && 本地该方向 active==false && 持仓==0,每根 K 线评估。
+1. 在价格队列中找当前价上(多)/下(空)方最近的网格;
+2. 该网格及以上(多)各网格已有挂单 → 跳过;否则向上遍历**取消所有遗留挂单**;
+3. **挂单前 REST 核实该方向真实持仓为 0**(防成交推送滞后导致重复建仓,历史出现过 68→136 张翻倍)——非 0 则刷新本地字段并跳过;
+4. 挂条件开仓单(张数同样走加仓公式,打标记,成交才计加仓执行次数)。
+
+---
+
+## 8. 轮次重置(三个入口)
+
+| 入口 | 触发条件 | 流程 |
+|---|---|---|
+| 仓位归零 | ACTIVE 下双方向持仓都变 0(持仓推送驱动) | 取消全部条件单 → 平仓 → STOPPED → 3s 后 startGrid |
+| 盈利达标 | 账户净值-预估平仓费 ≥ 初始本金+预期盈利(每根 K 线检查) | 同上 + currentRound+1;达 rounds 上限则永久停止 |
+| 手动指令 | 站内 STOP/重置 | stopGrid / restartWithConfig |
+
+重置任务整体提交到 executor 队列**末尾**(FIFO),保证上一轮排队的挂单先挂出、随后的 cancel 才能取消到。
+
+---
+
+## 9. 风控
+
+- **最大亏损**:onPositionClose 累加已实现盈亏 + 账户浮动盈亏,合计 ≤ -maxLoss 时钉钉告警(maxLossAlerted 闩锁:只在首次下穿阈值时提醒,回上后复位,防轰炸);
+- **累计盈亏(全局口径,不按轮次)**:推送逐笔累加;对账任务用 REST 校准(当前数据源为持仓 realised_pnl,**已发现口径不对,待改为 history_pnl 或 position_close 历史**);
+- **主动换线**:连接存活 55 分钟主动重连,绕开链路约 1 小时强制断连。
+
+---
+
+## 10. WS 连接管理(GateKlineWebSocketClient)
+
+- 心跳三层:10s 静默发应用层 futures.ping;20s 无任何回应(含 pong)判死重连;协议层 ping 由库自动回,30s lost-timeout 兜底;
+- 重连:指数退避 5s→10s→20s→40s→60s(封顶)无限重试,成功后重订阅四频道;
+- 重订阅完成后回调 → 立即触发一次持仓对账;
+- 订阅确认 event=subscribe + result.status=success 才置 subscribed=true(areAllSubscribed 全真才放行策略)。
+
+---
+
+## 11. 对账体系(15s 节流 + 事件触发)
+
+| 对账项 | 触发 | 行为 |
+|---|---|---|
+| 持仓 active/size/均价 | 15s 节流 + 重连订阅完成 | REST 权威值同步本地六字段,不一致打 WARN |
+| OPENING 基底 | 同上(OPENING 态) | 双基底 REST 已成交 → 补 baseOpened/entryPrice + 触发队列生成 |
+| 条件单幽灵清理 | 同上(ACTIVE 态) | 本地索引中不在交易所 open 列表的单 → 移除 + 修正标志 |
+| 累计盈亏 | 同上 | REST 校准(数据源待修,见 §9) |
+| 止损覆盖兜底 | 同上 | 有持仓但止损覆盖 < 持仓 → 按原位置重挂全持仓止损 |
+| 挂单前核实 | 价格驱动挂单瞬间 | REST 确认该方向持仓为 0 才挂(防翻倍) |
+
+---
+
+## 12. K 线处理(CandlestickChannelHandler)
+
+- 订阅快照/更新可能带多根烛线:取 t 最大的一根,同 t 优先 w=false(实时烛线);
+- 跨消息 t 单调过滤:t < 已处理最新 t 的历史烛线直接丢弃(防重连后快照逐条重放引发风暴);
+- 每根有效烛线 → onKline(close):WAITING_KLINE 开基底;ACTIVE 跑价格驱动 + 盈亏检查 + 节流对账。
+
+---
+
+## 13. 数据上报(station 看板)
+
+- 心跳 HEARTBEAT(状态/轮次/盈亏/持仓等);
+- STRATEGY_START/STOP、ROUND_COMPLETE、PNL_SNAPSHOT(60s:累计/浮动/总权益)、ENTRY_FILLED、STOP_LOSS_TRIGGERED、CMD_ACK;
+- 配置下发:/config、/alias、/strategy-status;指令:启动/停止/取消挂单/平仓/重建。
+
+---
+
+## 14. 关键配置项速查
+
+baseQuantity/quantity(基础/单笔张数)、gridStep(网格步长)、maxPositionPerSide(单边上限)、addPositionStartThreshold/Interval/Quantity/StopThreshold(加仓四件套)、stopLossCountMode(single/dual)、placeExcessTakeProfit(concentrated/dispersed)、baseTakeProfitPerGrid/GridCount、tpTriggerOppositeAdd、tpPositionReplenishEnabled、priceDriveEnabled、maxLoss、expectedProfit、rounds。
+
+---
+
+## 15. 已知遗留问题(待修清单)
+
+1. 累计盈亏对账数据源口径错误(realised_pnl → 应为 history_pnl/position_close 历史);
+2. WS error 事件解析读嵌套字段(官方是顶层 code/message)+ 订阅失败无重试;
+3. ~~挂单前核实跑在网格队列锁内 + 未同步 entryPrice~~(已修复:核实移出锁、一次 REST 同步 size/active/entryPrice);
+4. 基底开仓 REST 失败无回调重试(仅推送丢失可被对账救回);
+5. ~~OkHttp response body 未关闭(连接泄漏 WARN)~~(已修复:GateClosingApiClient 子类 try-with-resources 强制关闭响应,替换两处 new ApiClient())。
\ No newline at end of file
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateClosingApiClient.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateClosingApiClient.java
new file mode 100644
index 0000000..0201590
--- /dev/null
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateClosingApiClient.java
@@ -0,0 +1,39 @@
+package com.xcong.excoin.modules.gateApi;
+
+import io.gate.gateapi.ApiClient;
+import io.gate.gateapi.ApiException;
+import io.gate.gateapi.ApiResponse;
+import okhttp3.Call;
+import okhttp3.Response;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+/**
+ * 修复 gate-api SDK 同步请求 Response 未关闭导致 OkHttp 连接泄漏的 ApiClient 子类。
+ *
+ * <p>SDK 的 {@code ApiClient.execute(Call, Type)} 读取响应体后不调用 {@code response.close()},
+ * 触发 OkHttp 连接池 "A connection to ... was leaked. Did you forget to close a response body?" 告警
+ * (日志中已多次出现)。本类用 try-with-resources 保证响应在任意路径
+ * (成功 / 4xx / 反序列化失败 / IO 异常)都被关闭,行为与 SDK 内置执行完全一致
+ * ({@code handleResponse} 为 SDK 公开方法)。</p>
+ */
+public class GateClosingApiClient extends ApiClient {
+
+    /**
+     * 重写 SDK 执行逻辑:响应读取完成后强制 close。
+     * <ul>
+     *   <li>成功路径:反序列化后关闭;</li>
+     *   <li>异常路径(handleResponse 抛 ApiException / IOException):try-with-resources 兜底关闭。</li>
+     * </ul>
+     */
+    @Override
+    public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
+        try (Response response = call.execute()) {
+            T data = handleResponse(response, returnType);
+            return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
+        } catch (IOException e) {
+            throw new ApiException(e);
+        }
+    }
+}
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
index d36dbaa..9a7bed8 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -201,7 +201,7 @@
     public GateGridTradeService(GateConfig config, StatsEventProducer statsProducer) {
         this.config = config;
         this.statsProducer = statsProducer;
-        ApiClient apiClient = new ApiClient();
+        ApiClient apiClient = new GateClosingApiClient();
         apiClient.setBasePath(config.getRestBasePath());
         apiClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
         // 修复 gate-api SDK finishAs 枚举不完整导致的反序列化失败(见 buildLenientJson)
@@ -268,7 +268,7 @@
      */
     public void init() {
         try {
-            ApiClient detailClient = new ApiClient();
+            ApiClient detailClient = new GateClosingApiClient();
             detailClient.setBasePath(config.getRestBasePath());
             detailClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
             AccountDetail detail = new AccountApi(detailClient).getAccountDetail();
@@ -2302,166 +2302,182 @@
 
     /** 多仓仓位归零后,在当前价上方最近网格重新挂多单(遍历 totalLongPriceQueue 升序)。 */
     private void processLongGrid(BigDecimal currentPrice) {
-        BigDecimal matched = BigDecimal.ZERO;
+        GridElement newEntryGrid = null;
+        boolean hasLongOrderBelow = false;
+        // 阶段1(队列锁内):匹配价格 + 网格定位 + 本地挂单检查 + 提交撤单,全程无阻塞 IO
         synchronized (totalLongPriceQueue) {
+            BigDecimal matched = BigDecimal.ZERO;
             for (BigDecimal p : totalLongPriceQueue) {
                 if (p.compareTo(currentPrice) >= 0) {
-                    matched =  p;
+                    matched = p;
                     break;
                 }
             }
-//            log.info("[Gate-1] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
-            if (BigDecimal.ZERO.compareTo( matched) == 0) {
+            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                 return;
             }
 
             GridElement matchedUpGridElement = GridElement.findByPrice(matched);
-            if (matchedUpGridElement != null){
-                if (!matchedUpGridElement.isHasLongOrder()){
-                    Integer upId = matchedUpGridElement.getUpId();
-                    GridElement newEntryGrid = GridElement.findById(upId);
+            if (matchedUpGridElement != null && !matchedUpGridElement.isHasLongOrder()) {
+                Integer upId = matchedUpGridElement.getUpId();
+                newEntryGrid = GridElement.findById(upId);
 
-                    if (newEntryGrid != null) {
+                if (newEntryGrid != null) {
+                    // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
+                    GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
+                    while (checkDownCursor != null) {
+                        if (checkDownCursor.isHasLongOrder()) {
+                            hasLongOrderBelow = true;
+                            log.debug("[Gate] 多仓仓位归零 gridId:{}, 下方gridId:{}已有多单, 跳过本次挂单",
+                                    newEntryGrid.getId(), checkDownCursor.getId());
+                            break;
+                        }
+                        Integer nextDownId = checkDownCursor.getDownId();
+                        checkDownCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
+                    }
 
-                        String quantity = calculateEntryQuantity(true, false, 0);
-                        // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
-                        boolean hasLongOrderBelow = false;
-                        GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
-                        while (checkDownCursor != null) {
-                            if (checkDownCursor.isHasLongOrder()) {
-                                hasLongOrderBelow = true;
-                                log.debug("[Gate] 多仓仓位归零 gridId:{}, 下方gridId:{}已有多单, 跳过本次挂单",
-                                        newEntryGrid.getId(), checkDownCursor.getId());
-                                break;
+                    // 向上遍历取消所有遗留多单(跳过基础入场网格0)
+                    GridElement cancelCursor = GridElement.findById(newEntryGrid.getUpId());
+                    while (cancelCursor != null) {
+                        if (cancelCursor.isHasLongOrder()) {
+                            for (String longOrderId : new ArrayList<>(cancelCursor.getLongOrderIds())) {
+                                GridElement finalCancelCursor = cancelCursor;
+                                executor.cancelConditionalOrder(longOrderId, oid -> {
+                                    longEntryTraderIdParam(finalCancelCursor, longOrderId, false);
+                                    log.info("[Gate] 多仓仓位归零, 取消gridId:{}的多单,{}", finalCancelCursor.getId(), longOrderId);
+                                });
                             }
-                            Integer nextDownId = checkDownCursor.getDownId();
-                            checkDownCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                         }
-
-                        // 向上遍历取消所有遗留多单(跳过基础入场网格0)
-                        GridElement cancelCursor = GridElement.findById(newEntryGrid.getUpId());
-                        while (cancelCursor != null) {
-                            if (cancelCursor.isHasLongOrder()) {
-                                for (String longOrderId : new ArrayList<>(cancelCursor.getLongOrderIds())) {
-                                    GridElement finalCancelCursor = cancelCursor;
-                                    executor.cancelConditionalOrder(longOrderId, oid -> {
-                                        longEntryTraderIdParam(finalCancelCursor, longOrderId, false);
-                                        log.info("[Gate] 多仓仓位归零, 取消gridId:{}的多单,{}", finalCancelCursor.getId(), longOrderId);
-                                    });
-                                }
-                            }
-                            Integer nextUpId = cancelCursor.getUpId();
-                            cancelCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
-                        }
-//                        log.info("[Gate-2] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
-                        if (!newEntryGrid.isHasLongOrder() && !hasLongOrderBelow) {
-                            // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
-                            // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍(历史出现过 68→136 张)
-                            int realPos = queryPositionSize(Position.ModeEnum.DUAL_LONG);
-                            if (realPos > 0) {
-                                longActive = true;
-                                longPositionSize = BigDecimal.valueOf(realPos);
-                                log.warn("[Gate] 多仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
-                                return;
-                            }
-                            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
-                            String size = quantity;
-                            log.info("[Gate] 多仓仓位归零 gridId:{}, 挂{}张多单",
-                                    newEntryGrid.getId(), size);
-                            newEntryGrid.getLongTraderParam().setQuantity(size);
-                            // 含加仓量的单打标记:真正成交后才计入加仓执行次数
-                            boolean hasAdd = computeAddQty(true) > 0;
-                            placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
-                                    FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
-                                    hasAdd ? pendingAddEntryOrderIds::add : null);
-                        }
+                        Integer nextUpId = cancelCursor.getUpId();
+                        cancelCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                     }
                 }
             }
         }
 
+        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
+        if (newEntryGrid == null || newEntryGrid.isHasLongOrder() || hasLongOrderBelow) {
+            return;
+        }
+        // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
+        // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍(历史出现过 68→136 张);
+        // 顺带同步 entryPrice(此前核实只修 size/active,均价仍是旧值)
+        Position longPos = queryPosition(Position.ModeEnum.DUAL_LONG);
+        int realPos = longPos != null ? Math.abs(new BigDecimal(longPos.getSize()).intValue()) : 0;
+        if (realPos > 0) {
+            longActive = true;
+            longPositionSize = BigDecimal.valueOf(realPos);
+            if (longPos.getEntryPrice() != null) {
+                try {
+                    longEntryPrice = new BigDecimal(longPos.getEntryPrice());
+                } catch (NumberFormatException ignored) {
+                }
+            }
+            log.warn("[Gate] 多仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
+            return;
+        }
+
+        // 阶段3:挂单
+        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
+        String size = calculateEntryQuantity(true, false, 0);
+        log.info("[Gate] 多仓仓位归零 gridId:{}, 挂{}张多单",
+                newEntryGrid.getId(), size);
+        newEntryGrid.getLongTraderParam().setQuantity(size);
+        // 含加仓量的单打标记:真正成交后才计入加仓执行次数
+        boolean hasAdd = computeAddQty(true) > 0;
+        placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
+                FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
+                hasAdd ? pendingAddEntryOrderIds::add : null);
     }
 
     /** 空仓仓位归零后,在当前价下方最近网格重新挂空单(遍历 totalShortPriceQueue 降序)。 */
     private void processShortGrid(BigDecimal currentPrice) {
-        BigDecimal matched = BigDecimal.ZERO;
+        GridElement newEntryGrid = null;
+        boolean hasShortOrderAbove = false;
+        // 阶段1(队列锁内):匹配价格 + 网格定位 + 本地挂单检查 + 提交撤单,全程无阻塞 IO
         synchronized (totalShortPriceQueue) {
+            BigDecimal matched = BigDecimal.ZERO;
             for (BigDecimal p : totalShortPriceQueue) {
                 if (p.compareTo(currentPrice) <= 0) {
                     matched = p;
                     break;
                 }
             }
-//            log.info("[Gate-3] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
-            if (BigDecimal.ZERO.compareTo( matched) == 0) {
+            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                 return;
             }
 
             GridElement matchedUpGridElement = GridElement.findByPrice(matched);
-            if (matchedUpGridElement != null){
-                if(!matchedUpGridElement.isHasShortOrder()){
-                    Integer downId = matchedUpGridElement.getDownId();
-                    GridElement newEntryGrid = GridElement.findById(downId);
+            if (matchedUpGridElement != null && !matchedUpGridElement.isHasShortOrder()) {
+                Integer downId = matchedUpGridElement.getDownId();
+                newEntryGrid = GridElement.findById(downId);
 
-                    if (newEntryGrid != null) {
-
-                        String quantity = calculateEntryQuantity(false, false, 0);
-                        // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
-                        boolean hasShortOrderAbove = false;
-                        GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
-                        while (checkUpCursor != null) {
-                            if (checkUpCursor.isHasShortOrder()) {
-                                hasShortOrderAbove = true;
-                                log.debug("[Gate] 空仓仓位归零 gridId:{}, 上方gridId:{}已有空单, 跳过本次挂单",
-                                        newEntryGrid.getId(), checkUpCursor.getId());
-                                break;
-                            }
-                            Integer nextUpId = checkUpCursor.getUpId();
-                            checkUpCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
+                if (newEntryGrid != null) {
+                    // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
+                    GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
+                    while (checkUpCursor != null) {
+                        if (checkUpCursor.isHasShortOrder()) {
+                            hasShortOrderAbove = true;
+                            log.debug("[Gate] 空仓仓位归零 gridId:{}, 上方gridId:{}已有空单, 跳过本次挂单",
+                                    newEntryGrid.getId(), checkUpCursor.getId());
+                            break;
                         }
+                        Integer nextUpId = checkUpCursor.getUpId();
+                        checkUpCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
+                    }
 
-                        // 向下遍历取消所有遗留空单(跳过基础入场网格0)
-                        GridElement cancelCursor = GridElement.findById(newEntryGrid.getDownId());
-                        while (cancelCursor != null) {
-                            if (cancelCursor.isHasShortOrder()) {
-                                for (String shortOrderId : new ArrayList<>(cancelCursor.getShortOrderIds())) {
-                                    GridElement finalCancelCursor = cancelCursor;
-                                    executor.cancelConditionalOrder(shortOrderId, oid -> {
-                                        shortEntryTraderIdParam(finalCancelCursor, shortOrderId, false);
-                                        log.info("[Gate] 空仓仓位归零, 取消gridId:{}的空单{}", finalCancelCursor.getId(), shortOrderId);
-                                    });
-                                }
+                    // 向下遍历取消所有遗留空单(跳过基础入场网格0)
+                    GridElement cancelCursor = GridElement.findById(newEntryGrid.getDownId());
+                    while (cancelCursor != null) {
+                        if (cancelCursor.isHasShortOrder()) {
+                            for (String shortOrderId : new ArrayList<>(cancelCursor.getShortOrderIds())) {
+                                GridElement finalCancelCursor = cancelCursor;
+                                executor.cancelConditionalOrder(shortOrderId, oid -> {
+                                    shortEntryTraderIdParam(finalCancelCursor, shortOrderId, false);
+                                    log.info("[Gate] 空仓仓位归零, 取消gridId:{}的空单{}", finalCancelCursor.getId(), shortOrderId);
+                                });
                             }
-                            Integer nextDownId = cancelCursor.getDownId();
-                            cancelCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                         }
-//                        log.info("[Gate-4] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
-                        if (!newEntryGrid.isHasShortOrder() && !hasShortOrderAbove){
-                            // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
-                            // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍
-                            int realPos = queryPositionSize(Position.ModeEnum.DUAL_SHORT);
-                            if (realPos > 0) {
-                                shortActive = true;
-                                shortPositionSize = BigDecimal.valueOf(realPos);
-                                log.warn("[Gate] 空仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
-                                return;
-                            }
-                            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
-                            String size = quantity;
-                            log.info("[Gate] 空仓仓位归零 gridId:{}, 挂{}张空单",
-                                    newEntryGrid.getId(), size);
-                            newEntryGrid.getShortTraderParam().setQuantity(size);
-                            // 含加仓量的单打标记:真正成交后才计入加仓执行次数
-                            boolean hasAdd = computeAddQty(false) > 0;
-                            placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
-                                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
-                                    hasAdd ? pendingAddEntryOrderIds::add : null);
-                        }
-
+                        Integer nextDownId = cancelCursor.getDownId();
+                        cancelCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                     }
                 }
             }
         }
+
+        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
+        if (newEntryGrid == null || newEntryGrid.isHasShortOrder() || hasShortOrderAbove) {
+            return;
+        }
+        // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
+        // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍;
+        // 顺带同步 entryPrice(此前核实只修 size/active,均价仍是旧值)
+        Position shortPos = queryPosition(Position.ModeEnum.DUAL_SHORT);
+        int realPos = shortPos != null ? Math.abs(new BigDecimal(shortPos.getSize()).intValue()) : 0;
+        if (realPos > 0) {
+            shortActive = true;
+            shortPositionSize = BigDecimal.valueOf(realPos);
+            if (shortPos.getEntryPrice() != null) {
+                try {
+                    shortEntryPrice = new BigDecimal(shortPos.getEntryPrice());
+                } catch (NumberFormatException ignored) {
+                }
+            }
+            log.warn("[Gate] 空仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
+            return;
+        }
+
+        // 阶段3:挂单
+        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
+        String size = calculateEntryQuantity(false, false, 0);
+        log.info("[Gate] 空仓仓位归零 gridId:{}, 挂{}张空单",
+                newEntryGrid.getId(), size);
+        newEntryGrid.getShortTraderParam().setQuantity(size);
+        // 含加仓量的单打标记:真正成交后才计入加仓执行次数
+        boolean hasAdd = computeAddQty(false) > 0;
+        placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
+                FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
+                hasAdd ? pendingAddEntryOrderIds::add : null);
     }
 
     // ========== 加仓计算 ==========
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 ad5fc4b..1a8c23e 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;
@@ -121,6 +122,17 @@
     /** 设置全部频道订阅完成回调(由 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 -> {
         Thread t = new Thread(r, "gate-ws-worker");
@@ -192,6 +204,7 @@
         if (pongTimeoutFuture != null) {
             pongTimeoutFuture.cancel(true);
         }
+        cancelSubscribeTimeout();
         shutdownExecutorGracefully(heartbeatExecutor);
         shutdownExecutorGracefully(sharedExecutor);
 
@@ -251,6 +264,14 @@
                             handler.subscribe(webSocketClient);
                         }
                         sendPing();
+                        // 订阅确认超时保护:若服务器既不回 subscribe 确认、也不回 error,
+                        // 超时后判定订阅失败断开重连,避免策略永久卡在 WAITING_KLINE
+                        cancelSubscribeTimeout();
+                        resubscribeRetryCount.clear();
+                        if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
+                            subscribeTimeoutFuture = heartbeatExecutor.schedule(
+                                    this::checkSubscriptionTimeout, SUBSCRIBE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
+                        }
                     } else {
                         log.warn("[WS] 应用正在关闭,忽略连接成功回调");
                     }
@@ -269,6 +290,7 @@
                     isConnected.set(false);
                     isConnecting.set(false);
                     cancelPongTimeout();
+                    cancelSubscribeTimeout();
                     scheduleReconnect();
                 }
 
@@ -322,6 +344,8 @@
                 }
                 // 全部频道订阅完成(含重连后的重新订阅)→ 通知持仓对账等逻辑
                 if (areAllSubscribed()) {
+                    cancelSubscribeTimeout();
+                    resubscribeRetryCount.clear();
                     Runnable cb = onAllSubscribedCallback;
                     if (cb != null) {
                         cb.run();
@@ -334,11 +358,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)) {
@@ -453,6 +478,72 @@
         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;
+        }
+        heartbeatExecutor.schedule(() -> {
+            if (!destroyed.get() && isConnected.get() && webSocketClient != null && webSocketClient.isOpen()) {
+                target.subscribe(webSocketClient);
+            }
+        }, RESUBSCRIBE_DELAY_SECONDS, TimeUnit.SECONDS);
+    }
+
     // ---- reconnect ----
 
     /**

--
Gitblit v1.9.1