From 415aee6d5f8fbeb4e3e083ea36afddb3ed3255c1 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Tue, 24 Nov 2026 11:26:46 +0800
Subject: [PATCH] fix(grid): 修复网格止损追单持仓超限问题

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |  157 +++++++++++++++++++++++++++++++++++++++++++++++-----
 1 files changed, 141 insertions(+), 16 deletions(-)

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 1bc55ae..fd383dc 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -189,6 +189,14 @@
     private final Map<String, Integer> reduceReplenishLongOrderMap = new ConcurrentHashMap<>();
     /** 原始仓位减仓:空头补仓单 orderId → 张数(补仓单挂在多头第一止损位) */
     private final Map<String, Integer> reduceReplenishShortOrderMap = new ConcurrentHashMap<>();
+    /** 多头止损事件待处理标记:仓位已归零、autoorders finished 尚未到达时置位,阻止价格驱动抢先挂单 */
+    private volatile boolean longStopLossPending = false;
+    /** 空头止损事件待处理标记:同上 */
+    private volatile boolean shortStopLossPending = false;
+    /** 多头止损待处理置位时间戳(0=未置位),用于兜底超时复位 */
+    private volatile long longStopLossPendingSince = 0L;
+    /** 空头止损待处理置位时间戳(0=未置位),用于兜底超时复位 */
+    private volatile long shortStopLossPendingSince = 0L;
 
     private volatile BigDecimal lastKlinePrice;
     private volatile BigDecimal markPrice = BigDecimal.ZERO;
@@ -219,7 +227,7 @@
         // 修复 gate-api SDK finishAs 枚举不完整导致的反序列化失败(见 buildLenientJson)
         apiClient.setJSON(buildLenientJson());
         this.futuresApi = new FuturesApi(apiClient);
-        this.executor = new GateTradeExecutor(apiClient, config.getContract());
+        this.executor = new GateTradeExecutor(apiClient, config.getContract(), config.getPriceScale());
     }
 
     /**
@@ -459,6 +467,10 @@
         tpReplenishShortOrderMap.clear();
         currentLongChaseQty = 0;
         currentShortChaseQty = 0;
+        longStopLossPending = false;
+        shortStopLossPending = false;
+        longStopLossPendingSince = 0L;
+        shortStopLossPendingSince = 0L;
         reduceReplenishLongOrderMap.clear();
         reduceReplenishShortOrderMap.clear();
         shortPriceQueue.clear();
@@ -578,10 +590,14 @@
             executor.submitMaintenanceTask(this::syncPositionsFromExchange);
         }
 
+        // 止损事件兜底:置位超时仍未收到 finished(事件丢失且对账补触发未生效),解除拦截让价格驱动接管
+        releaseExpiredStopLossPending();
+
         if (state == StrategyState.ACTIVE &&
                 config.isPriceDriveEnabled() &&
                 longActive == false &&
-                    longPositionSize.compareTo(BigDecimal.ZERO) == 0){
+                    longPositionSize.compareTo(BigDecimal.ZERO) == 0 &&
+                    !longStopLossPending){
             processLongGrid(closePrice);
         }
 
@@ -589,8 +605,31 @@
         if (state == StrategyState.ACTIVE &&
                 config.isPriceDriveEnabled() &&
                 shortActive == false &&
-                        shortPositionSize.compareTo(BigDecimal.ZERO) == 0){
+                        shortPositionSize.compareTo(BigDecimal.ZERO) == 0 &&
+                        !shortStopLossPending){
             processShortGrid(closePrice);
+        }
+    }
+
+    /** 止损事件兜底超时:置位超过该时长仍未收到 autoorders finished,自动解除价格驱动拦截 */
+    private static final long STOP_LOSS_PENDING_TIMEOUT_MS = 30_000L;
+
+    /**
+     * 止损事件兜底:pending 置位超过 {@link #STOP_LOSS_PENDING_TIMEOUT_MS} 仍无 autoorders finished,
+     * 说明止损事件已丢失且对账补触发未生效(如无 trade_id 的幽灵单),主动解除拦截,
+     * 让价格驱动接管重挂,避免永久停摆。每次 onKline 进入价格驱动判定前调用。
+     */
+    private void releaseExpiredStopLossPending() {
+        long now = System.currentTimeMillis();
+        if (longStopLossPending && now - longStopLossPendingSince >= STOP_LOSS_PENDING_TIMEOUT_MS) {
+            longStopLossPending = false;
+            longStopLossPendingSince = 0L;
+            log.warn("[Gate] 多头止损事件{}秒未达, 兜底解除价格驱动拦截", STOP_LOSS_PENDING_TIMEOUT_MS / 1000);
+        }
+        if (shortStopLossPending && now - shortStopLossPendingSince >= STOP_LOSS_PENDING_TIMEOUT_MS) {
+            shortStopLossPending = false;
+            shortStopLossPendingSince = 0L;
+            log.warn("[Gate] 空头止损事件{}秒未达, 兜底解除价格驱动拦截", STOP_LOSS_PENDING_TIMEOUT_MS / 1000);
         }
     }
 
@@ -737,24 +776,32 @@
                     longActive = true;
                     longPositionSize = size;
                     longEntryPrice = entryPrice;
+                    longStopLossPending = false;
+                    longStopLossPendingSince = 0L;
                 } else {
 
                     log.info("[Gate-0]多仓: {}", longBaseEntryPrice);
                     longActive = false;
                     longPositionSize = BigDecimal.ZERO;
                     longEntryPrice = BigDecimal.ZERO;
+                    longStopLossPendingSince = System.currentTimeMillis();
+                    longStopLossPending = true;
                 }
             } else if (Position.ModeEnum.DUAL_SHORT == mode) {
                 if (hasPosition) {
                     shortActive = true;
                     shortPositionSize = size.abs();
                     shortEntryPrice = entryPrice;
+                    shortStopLossPending = false;
+                    shortStopLossPendingSince = 0L;
                 } else {
 
                     log.info("[Gate-0]空仓: {}", shortBaseEntryPrice);
                     shortActive = false;
                     shortPositionSize = BigDecimal.ZERO;
                     shortEntryPrice = BigDecimal.ZERO;
+                    shortStopLossPendingSince = System.currentTimeMillis();
+                    shortStopLossPending = true;
                 }
             }
         }
@@ -1780,14 +1827,21 @@
             log.warn("[Gate] 生成多仓止盈止损失败:无多仓持仓");
             return;
         }
-        extendLongStopLoss(posSize, 0);
+        // 锚点按"当前价下方最近网格"取:多仓止损触发价必须 < 最新价,
+        // 固定用 grid 0 在行情远离基底时会导致触发价在现价上方被交易所拒绝(AUTO_TRIGGER_PRICE_LESS_LAST)
+        int anchor = findValidRebuildAnchor(true);
+        if (anchor == Integer.MIN_VALUE) {
+            log.warn("[Gate] 多仓止盈止损重建失败:当前价完全脱离网格范围, 现价:{}", lastKlinePrice);
+            return;
+        }
+        extendLongStopLoss(posSize, anchor);
         if (GateConfig.EXCESS_TP_CONCENTRATED.equals(config.getPlaceExcessTakeProfit())) {
             placeExcessTakeProfit(posSize, true);
         } else if (GateConfig.EXCESS_TP_DISPERSED.equals(config.getPlaceExcessTakeProfit())) {
-            placeDispersedTakeProfit(posSize, true, 0);
+            placeDispersedTakeProfit(posSize, true, anchor);
         }
-        placeBaseTakeProfit(posSize, true, 0);
-        log.info("[Gate] 多仓止盈止损已按默认位重建, 仓位:{}张", posSize);
+        placeBaseTakeProfit(posSize, true, anchor);
+        log.info("[Gate] 多仓止盈止损已重建, 仓位:{}张, 锚点gridId:{}, 现价:{}", posSize, anchor, lastKlinePrice);
     }
 
     /**
@@ -1801,14 +1855,68 @@
             log.warn("[Gate] 生成空仓止盈止损失败:无空仓持仓");
             return;
         }
-        extendShortStopLoss(posSize, 0);
+        // 锚点按"当前价上方最近网格"取:空仓止损触发价必须 > 最新价,
+        // 固定用 grid 0 在行情远离基底时会导致触发价在现价下方被交易所拒绝
+        int anchor = findValidRebuildAnchor(false);
+        if (anchor == Integer.MIN_VALUE) {
+            log.warn("[Gate] 空仓止盈止损重建失败:当前价完全脱离网格范围, 现价:{}", lastKlinePrice);
+            return;
+        }
+        extendShortStopLoss(posSize, anchor);
         if (GateConfig.EXCESS_TP_CONCENTRATED.equals(config.getPlaceExcessTakeProfit())) {
             placeExcessTakeProfit(posSize, false);
         } else if (GateConfig.EXCESS_TP_DISPERSED.equals(config.getPlaceExcessTakeProfit())) {
-            placeDispersedTakeProfit(posSize, false, 0);
+            placeDispersedTakeProfit(posSize, false, anchor);
         }
-        placeBaseTakeProfit(posSize, false, 0);
-        log.info("[Gate] 空仓止盈止损已按默认位重建, 仓位:{}张", posSize);
+        placeBaseTakeProfit(posSize, false, anchor);
+        log.info("[Gate] 空仓止盈止损已重建, 仓位:{}张, 锚点gridId:{}, 现价:{}", posSize, anchor, lastKlinePrice);
+    }
+
+    /**
+     * 为"按当前价重建止盈止损"寻找有效锚点:
+     * 多仓取当前价<b>下方</b>最近网格(止损触发价 &lt; 最新价),
+     * 空仓取当前价<b>上方</b>最近网格(止损触发价 &gt; 最新价)。
+     * 找不到(现价完全脱离网格范围)返回 {@link Integer#MIN_VALUE}。
+     * <p>返回值为"入场锚点"口径:extend 时止损会挂在 anchor∓2 处。</p>
+     */
+    private int findValidRebuildAnchor(boolean isLong) {
+        BigDecimal current = lastKlinePrice;
+        if (current == null || current.compareTo(BigDecimal.ZERO) <= 0) {
+            return Integer.MIN_VALUE;
+        }
+        if (isLong) {
+            synchronized (totalLongPriceQueue) {
+                BigDecimal best = null;
+                for (BigDecimal p : totalLongPriceQueue) {   // 升序
+                    if (p.compareTo(current) <= 0) {
+                        best = p;
+                    } else {
+                        break;
+                    }
+                }
+                if (best == null) {
+                    return Integer.MIN_VALUE;
+                }
+                GridElement g = GridElement.findByPrice(best);
+                return g != null ? g.getId() + 2 : Integer.MIN_VALUE;
+            }
+        } else {
+            synchronized (totalShortPriceQueue) {
+                BigDecimal best = null;
+                for (BigDecimal p : totalShortPriceQueue) {   // 降序
+                    if (p.compareTo(current) >= 0) {
+                        best = p;
+                    } else {
+                        break;
+                    }
+                }
+                if (best == null) {
+                    return Integer.MIN_VALUE;
+                }
+                GridElement g = GridElement.findByPrice(best);
+                return g != null ? g.getId() - 2 : Integer.MIN_VALUE;
+            }
+        }
     }
 
     /**
@@ -2388,7 +2496,7 @@
                     .build();
             elements.add(GridElement.builder()
                     .id(0)
-                    .gridPrice(price)
+                    .gridPrice(price.setScale(prec, RoundingMode.HALF_UP))
                     .upId(longSize > 0 ? 1 : null)
                     .downId(shortSize > 0 ? -1 : null)
                     .longTraderParam(longParam)
@@ -2878,14 +2986,13 @@
     /**
      * 计算原始仓位减仓模式下的递减追单数量。
      * 每次止损(含首次)→ 追单 = 本次被平数量 - 步长;
-     * 若结果 < 步长 → 重置为原始仓位(最大仓位),形成循环。
+     * 一旦被平数量 ≤ 步长(追单量会降到非正数)→ 钉在本次被平数量,不再递减、不再重置。
      */
     private int computeReducedChaseQty(int stoppedQty) {
-        int baseQty = Integer.parseInt(config.getBaseQuantity());
         int reduceStep = config.getOriginalPositionReduce();
         int chase = stoppedQty - reduceStep;
-        if (chase < reduceStep) {
-            chase = baseQty;
+        if (chase <= 0) {
+            chase = stoppedQty;
         }
         return chase;
     }
@@ -3005,6 +3112,8 @@
         }
 
         lastLongStopLossGridId = gridId;
+        longStopLossPending = false;
+        longStopLossPendingSince = 0L;
 
         accumulatedLongLossCount++;
         log.info("[Gate] 多仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
@@ -3090,6 +3199,8 @@
             return;
         }
         lastShortStopLossGridId = gridId;
+        shortStopLossPending = false;
+        shortStopLossPendingSince = 0L;
         accumulatedShortLossCount++;
         log.info("[Gate] 空仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
                 gridId, accumulatedShortLossCount, sameGrid ? "(同网格)" : "");
@@ -3527,6 +3638,20 @@
                                 }
                             }
                         }
+                    },
+                    () -> {
+                        // 挂单最终失败(已取消市价兜底):重置防重入标记,避免卡死后续重挂;
+                        // 对账兜底/下一轮业务触发会重新挂单
+                        log.warn("[Gate] {}止损挂单失败(放弃), gridId:{}, 等待后续重挂",
+                                isLong ? "多仓" : "空仓", gridId);
+                        if (remainCount != null) {
+                            remainCount.decrementAndGet();
+                            if (remainCount.get() <= 0 && entryElement != null) {
+                                entryElement.setExtendStopLossInProgress(false);
+                                log.warn("[Gate] {}止损追单失败, entryGridId:{}, 防重入标记已重置",
+                                        isLong ? "多仓" : "空仓", entryElement.getId());
+                            }
+                        }
                     }
             );
         }

--
Gitblit v1.9.1