From 32a91277cdcbfb060b53cce20314664dbf29698f Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Tue, 24 Nov 2026 11:29:56 +0800
Subject: [PATCH] fix(gate): 修复止损追单与价格驱动挂单竞态问题

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |  205 +++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 197 insertions(+), 8 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 d00e2d9..4ead873 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -166,6 +166,10 @@
     private volatile int lastLongStopLossGridId = Integer.MAX_VALUE;
     /** 最近触发止损的空头网格ID */
     private volatile int lastShortStopLossGridId = Integer.MAX_VALUE;
+    /** 止损追单所在网格(多仓):价格驱动接管仲裁用,无追单 = Integer.MIN_VALUE */
+    private volatile int longSlReentryGridId = Integer.MIN_VALUE;
+    /** 止损追单所在网格(空仓):价格驱动接管仲裁用,无追单 = Integer.MIN_VALUE */
+    private volatile int shortSlReentryGridId = Integer.MIN_VALUE;
     /** 自定义止损模式激活标记:true=尚未发生第一次止损触发,第一次触发后置 false(触发未触发侧重挂默认) */
     private final AtomicBoolean dualStopLossModeActive = new AtomicBoolean(false);
 
@@ -866,6 +870,7 @@
                 }
                 int filledQty = Integer.parseInt(shortGridElement.getShortTraderParam().getQuantity());
                 shortEntryTraderIdParam(shortGridElement, orderId, false);
+                shortSlReentryGridId = Integer.MIN_VALUE;   // 追单已成交,仲裁登记失效
 
                 // 埋点: ENTRY_FILLED — 空仓加仓成交
                 emitStats("ENTRY_FILLED", mapOf(
@@ -927,6 +932,7 @@
                 }
                 int filledQty = Integer.parseInt(longGridElement.getLongTraderParam().getQuantity());
                 longEntryTraderIdParam(longGridElement, orderId, false);
+                longSlReentryGridId = Integer.MIN_VALUE;   // 追单已成交,仲裁登记失效
 
                 // 埋点: ENTRY_FILLED — 多仓加仓成交
                 emitStats("ENTRY_FILLED", mapOf(
@@ -1573,12 +1579,28 @@
             return;
         }
         int removed = 0;
+        boolean longSlCompensated = false;   // 每个方向每轮对账最多补触发一次
+        boolean shortSlCompensated = false;
         for (GridElement e : config.getGridElements()) {
             for (String id : new ArrayList<>(e.getLongStopLossOrderIds())) {
-                if (!openIds.contains(id)) { e.removeLongStopLossOrderId(id); removed++; }
+                if (!openIds.contains(id)) {
+                    if (!longSlCompensated) {
+                        longSlCompensated = true;
+                        compensateMissedStopLoss(true, e, id);
+                    }
+                    e.removeLongStopLossOrderId(id);
+                    removed++;
+                }
             }
             for (String id : new ArrayList<>(e.getShortStopLossOrderIds())) {
-                if (!openIds.contains(id)) { e.removeShortStopLossOrderId(id); removed++; }
+                if (!openIds.contains(id)) {
+                    if (!shortSlCompensated) {
+                        shortSlCompensated = true;
+                        compensateMissedStopLoss(false, e, id);
+                    }
+                    e.removeShortStopLossOrderId(id);
+                    removed++;
+                }
             }
             for (String id : new ArrayList<>(e.getLongTakeProfitOrderIds())) {
                 if (!openIds.contains(id)) { e.removeLongTakeProfitOrderId(id); removed++; }
@@ -1607,6 +1629,39 @@
         if (removed > 0) {
             GridElement.refreshIndices();
             log.warn("[Gate] 条件单对账: 移除 {} 个本地失效订单(交易所已不存在)", removed);
+        }
+    }
+
+    /**
+     * 止损成交补触发:对账发现止损单在交易所已消失时,REST 查该单详情。
+     * 若确已成交(trade_id &gt; 0),说明止损触发的 finished 推送被 positions/对账竞态吞掉
+     * (finished 晚于对账到达,本地索引已被清空),补执行止损触发逻辑:
+     * 累加止损次数、取消该方向开仓单、按止损格∓1 追单、延展止损。
+     * <p>追单量由 calculateEntryQuantity 的双重硬上限兜底(≤ 止损张数、≤ maxPerSide − REST持仓),
+     * 补触发不会造成重复追单/超仓。无成交记录(REQUEST_TIMEOUT 等)时仅清理 + WARN。</p>
+     */
+    private void compensateMissedStopLoss(boolean isLong, GridElement gridElement, String orderId) {
+        if (state == StrategyState.STOPPED) {
+            return;
+        }
+        try {
+            FuturesPriceTriggeredOrder detail = futuresApi.getPriceTriggeredOrder(config.getContract(), Long.parseLong(orderId));
+            Long tradeId = detail != null ? detail.getTradeId() : null;
+            if (detail == null || tradeId == null || tradeId <= 0) {
+                log.warn("[Gate] 条件单对账: {}止损单{}已消失但无成交记录(tradeId:{}), 仅清理不补触发",
+                        isLong ? "多仓" : "空仓", orderId, tradeId);
+                return;
+            }
+            log.warn("[Gate] 条件单对账: 检测到{}止损成交事件丢失, 补触发, gridId:{}, orderId:{}, tradeId:{}",
+                    isLong ? "多仓" : "空仓", gridElement.getId(), orderId, tradeId);
+            if (isLong) {
+                handleLongStopLossTriggered(gridElement, orderId);
+            } else {
+                handleShortStopLossTriggered(gridElement, orderId);
+            }
+        } catch (Exception e) {
+            log.warn("[Gate] 条件单对账: {}止损单{}补触发查询失败: {}",
+                    isLong ? "多仓" : "空仓", orderId, e.getMessage());
         }
     }
 
@@ -2426,6 +2481,27 @@
                 newEntryGrid = GridElement.findById(upId);
 
                 if (newEntryGrid != null) {
+                    // 止损追单接管(先撤后挂):价格继续下跌,目标格已低于追单格
+                    // (如追单在 grid-1、价格到 grid-3 → 目标格 grid-2)→ 撤掉落后追单,
+                    // 撤单成功后再挂新单,杜绝撤挂并发导致双单并存
+                    if (longSlReentryGridId != Integer.MIN_VALUE
+                            && newEntryGrid.getId() < longSlReentryGridId) {
+                        GridElement reentryElem = GridElement.findById(longSlReentryGridId);
+                        if (reentryElem != null && reentryElem.isHasLongOrder()) {
+                            final GridElement takeoverTarget = newEntryGrid;
+                            for (String oid : new ArrayList<>(reentryElem.getLongOrderIds())) {
+                                executor.cancelConditionalOrder(oid, o -> {
+                                    longEntryTraderIdParam(reentryElem, oid, false);
+                                    // 全部撤完后再挂新单(先撤后挂)
+                                    if (!reentryElem.hasLongOrderIds()) {
+                                        hangLongEntryWithVerify(takeoverTarget);
+                                    }
+                                });
+                            }
+                            return;   // 接管流程已启动,本轮不走常规挂单
+                        }
+                        longSlReentryGridId = Integer.MIN_VALUE;
+                    }
                     // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
                     GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
                     while (checkDownCursor != null) {
@@ -2493,6 +2569,72 @@
                 hasAdd ? pendingAddEntryOrderIds::add : null);
     }
 
+    /**
+     * 接管挂单(多仓):撤掉落后止损追单成功后,REST 核实持仓为 0 再占坑挂多开仓单。
+     * 核实失败(追单实际已成交)则跳过,避免重复建仓。
+     */
+    private void hangLongEntryWithVerify(GridElement entryGrid) {
+        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;
+        }
+        BigDecimal triggerPrice = entryGrid.getGridPrice();
+        String size = calculateEntryQuantity(true, false, 0);
+        if (Integer.parseInt(size) <= 0) {
+            log.warn("[Gate] 接管挂单: 已达单边上限({}), 跳过", config.getMaxPositionPerSide());
+            return;
+        }
+        entryGrid.getLongTraderParam().setQuantity(size);
+        boolean hasAdd = computeAddQty(true) > 0;
+        log.info("[Gate] 价格驱动接管: 多仓挂单 gridId:{}, {}张", entryGrid.getId(), size);
+        placeEntryOrderWithPreFlag(entryGrid, true, triggerPrice,
+                FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
+                hasAdd ? pendingAddEntryOrderIds::add : null);
+    }
+
+    /**
+     * 接管挂单(空仓):撤掉落后止损追单成功后,REST 核实持仓为 0 再占坑挂空开仓单。
+     * 核实失败(追单实际已成交)则跳过,避免重复建仓。
+     */
+    private void hangShortEntryWithVerify(GridElement entryGrid) {
+        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;
+        }
+        BigDecimal triggerPrice = entryGrid.getGridPrice();
+        String size = calculateEntryQuantity(false, false, 0);
+        if (Integer.parseInt(size) <= 0) {
+            log.warn("[Gate] 接管挂单: 已达单边上限({}), 跳过", config.getMaxPositionPerSide());
+            return;
+        }
+        entryGrid.getShortTraderParam().setQuantity(size);
+        boolean hasAdd = computeAddQty(false) > 0;
+        log.info("[Gate] 价格驱动接管: 空仓挂单 gridId:{}, {}张", entryGrid.getId(), size);
+        placeEntryOrderWithPreFlag(entryGrid, false, triggerPrice,
+                FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
+                hasAdd ? pendingAddEntryOrderIds::add : null);
+    }
+
     /** 空仓仓位归零后,在当前价下方最近网格重新挂空单(遍历 totalShortPriceQueue 降序)。 */
     private void processShortGrid(BigDecimal currentPrice) {
         GridElement newEntryGrid = null;
@@ -2516,6 +2658,27 @@
                 newEntryGrid = GridElement.findById(downId);
 
                 if (newEntryGrid != null) {
+                    // 止损追单接管(先撤后挂):价格继续上涨,目标格已高于追单格
+                    // (如追单在 grid1、价格到 grid3 → 目标格 grid2)→ 撤掉落后追单,
+                    // 撤单成功后再挂新单,杜绝撤挂并发导致双单并存
+                    if (shortSlReentryGridId != Integer.MIN_VALUE
+                            && newEntryGrid.getId() > shortSlReentryGridId) {
+                        GridElement reentryElem = GridElement.findById(shortSlReentryGridId);
+                        if (reentryElem != null && reentryElem.isHasShortOrder()) {
+                            final GridElement takeoverTarget = newEntryGrid;
+                            for (String oid : new ArrayList<>(reentryElem.getShortOrderIds())) {
+                                executor.cancelConditionalOrder(oid, o -> {
+                                    shortEntryTraderIdParam(reentryElem, oid, false);
+                                    // 全部撤完后再挂新单(先撤后挂)
+                                    if (!reentryElem.hasShortOrderIds()) {
+                                        hangShortEntryWithVerify(takeoverTarget);
+                                    }
+                                });
+                            }
+                            return;   // 接管流程已启动,本轮不走常规挂单
+                        }
+                        shortSlReentryGridId = Integer.MIN_VALUE;
+                    }
                     // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
                     GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
                     while (checkUpCursor != null) {
@@ -2750,6 +2913,14 @@
         // 避免旧单与新追单重复建仓(与价格驱动的扫荡口径一致)
         cancelAllLongEntryOrders();
 
+        // 登记止损追单网格:价格驱动以此仲裁优先级(追单优先,价格越过追单格后价格驱动接管)
+        longSlReentryGridId = newEntryGrid.getId();
+
+        // 占坑前移:撤单后立即在追单目标网格预留"有单"标记(同步、无I/O),再执行 REST 数量计算
+        // (耗时数百ms)。价格驱动的挂单判定(本格有单/游标检查)会看到该标记并跳过本轮,
+        // 消除"撤旧挂新"窗口期被价格驱动抢先挂单导致的双单竞态。
+        newEntryGrid.setHasLongOrder(true);
+
         // 止损追单:同一网格可有多笔挂单,不判断 isHasLongOrder,直接挂单
         BigDecimal triggerPrice = newEntryGrid.getGridPrice();
         String size = calculateEntryQuantity(true, true, gridStopLossSize);
@@ -2758,6 +2929,10 @@
                 config.getBaseQuantity(), size, config.getStopLossCountMode());
         if (Integer.parseInt(size) <= 0) {
             log.warn("[Gate] 多仓止损追单 当前持仓已达单边上限({}), 跳过挂单", config.getMaxPositionPerSide());
+            // 清理占坑标记与追单登记(未挂单)
+            newEntryGrid.setHasLongOrder(newEntryGrid.hasLongOrderIds());
+            longSlReentryGridId = Integer.MIN_VALUE;
+            GridElement.refreshIndices();
         } else {
             newEntryGrid.getLongTraderParam().setQuantity(size);
             // 含加仓量的单打标记:真正成交后才计入加仓执行次数(挂单后被取消的不算)
@@ -2811,6 +2986,14 @@
         // 避免旧单与新追单重复建仓(与价格驱动的扫荡口径一致)
         cancelAllShortEntryOrders();
 
+        // 登记止损追单网格:价格驱动以此仲裁优先级(追单优先,价格越过追单格后价格驱动接管)
+        shortSlReentryGridId = newEntryGrid.getId();
+
+        // 占坑前移:撤单后立即在追单目标网格预留"有单"标记(同步、无I/O),再执行 REST 数量计算
+        // (耗时数百ms)。价格驱动的挂单判定(本格有单/游标检查)会看到该标记并跳过本轮,
+        // 消除"撤旧挂新"窗口期被价格驱动抢先挂单导致的双单竞态。
+        newEntryGrid.setHasShortOrder(true);
+
         // 止损追单:同一网格可有多笔挂单,不判断 isHasShortOrder,直接挂单
         BigDecimal triggerPrice = newEntryGrid.getGridPrice();
         String size = calculateEntryQuantity(false, true, gridStopLossSize);
@@ -2819,6 +3002,10 @@
                 config.getBaseQuantity(), size, config.getStopLossCountMode());
         if (Integer.parseInt(size) <= 0) {
             log.warn("[Gate] 空仓止损追单 当前持仓已达单边上限({}), 跳过挂单", config.getMaxPositionPerSide());
+            // 清理占坑标记与追单登记(未挂单)
+            newEntryGrid.setHasShortOrder(newEntryGrid.hasShortOrderIds());
+            shortSlReentryGridId = Integer.MIN_VALUE;
+            GridElement.refreshIndices();
         } else {
             newEntryGrid.getShortTraderParam().setQuantity(size);
             // 含加仓量的单打标记:真正成交后才计入加仓执行次数(挂单后被取消的不算)
@@ -3507,10 +3694,11 @@
      * 取消所有多仓入场单(条件开仓单),并清空 GridElement 的多仓挂单记录。
      */
     private void cancelAllLongEntryOrders() {
+        longSlReentryGridId = Integer.MIN_VALUE;
         for (GridElement e : config.getGridElements()) {
-            if (e.getId() == 0) {
-                continue; // 基底网格 0 是市价单成交,非条件开仓单
-            }
+            // 注意:不再跳过 grid 0——价格驱动/补仓/对向加仓会在 grid 0 挂条件开仓单,
+            // 若跳过会导致止损全扫撤不掉 grid 0 的条件单,与追单并存形成双仓位。
+            // 基底市价单不注册在 *OrderIds 里,遍历无副作用。
             for (String oid : new ArrayList<>(e.getLongOrderIds())) {
                 // 同步清理对向加仓/补仓/加仓标记登记表,避免残留失效记录
                 tpOppositeLongOrderGridMap.remove(oid);
@@ -3531,10 +3719,11 @@
      * 取消所有空仓入场单(条件开仓单),并清空 GridElement 的空仓挂单记录。
      */
     private void cancelAllShortEntryOrders() {
+        shortSlReentryGridId = Integer.MIN_VALUE;
         for (GridElement e : config.getGridElements()) {
-            if (e.getId() == 0) {
-                continue; // 基底网格 0 是市价单成交,非条件开仓单
-            }
+            // 注意:不再跳过 grid 0——价格驱动/补仓/对向加仓会在 grid 0 挂条件开仓单,
+            // 若跳过会导致止损全扫撤不掉 grid 0 的条件单,与追单并存形成双仓位。
+            // 基底市价单不注册在 *OrderIds 里,遍历无副作用。
             for (String oid : new ArrayList<>(e.getShortOrderIds())) {
                 // 同步清理对向加仓/补仓/加仓标记登记表,避免残留失效记录
                 tpOppositeShortOrderGridMap.remove(oid);

--
Gitblit v1.9.1