From b29f105a7fa026b53389c8b5d14ee3c60cfaa0a9 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Fri, 17 Jul 2026 10:06:52 +0800
Subject: [PATCH] fix(gateApi): 解决网格交易止盈订单重复挂单问题

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |  184 ++++++++++++++++++++++++++++++---------------
 1 files changed, 122 insertions(+), 62 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 4e2f21b..5249c57 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -398,7 +398,8 @@
             return;
         }
 
-        checkProfitAndReset();
+        // 异步检查盈亏,避免 REST 调用阻塞 WS 心跳导致 Socket closed
+        executor.submitTask(this::checkProfitAndReset);
 
         if (state == StrategyState.ACTIVE &&
                 longActive == false &&
@@ -674,9 +675,11 @@
                 for (int i = 0; i < shortTpCount; i++) {
                     int tpGridId = shortGridElement.getId() - 2 * (i + 1);
                     GridElement tpElem = GridElement.findById(tpGridId);
-                    if (tpElem == null || tpElem.getShortTakeProfitOrderId() != null) {
+                    // 用 takeProfitPlaced 做同步标记,避免异步回调未执行时重复挂单
+                    if (tpElem == null || tpElem.getShortTraderParam().isTakeProfitPlaced()) {
                         continue;
                     }
+                    tpElem.getShortTraderParam().setTakeProfitPlaced(true);
                     BigDecimal tpPrice = tpElem.getGridPrice();
                     int finalTpGridId = tpGridId;
                     executor.placeTakeProfit(
@@ -740,9 +743,11 @@
                 for (int i = 0; i < longTpCount; i++) {
                     int tpGridId = longGridElement.getId() + 2 * (i + 1);
                     GridElement tpElem = GridElement.findById(tpGridId);
-                    if (tpElem == null || tpElem.getLongTakeProfitOrderId() != null) {
+                    // 用 takeProfitPlaced 做同步标记,避免异步回调未执行时重复挂单
+                    if (tpElem == null || tpElem.getLongTraderParam().isTakeProfitPlaced()) {
                         continue;
                     }
+                    tpElem.getLongTraderParam().setTakeProfitPlaced(true);
                     BigDecimal tpPrice = tpElem.getGridPrice();
                     int finalTpGridId = tpGridId;
                     executor.placeTakeProfit(
@@ -1203,17 +1208,20 @@
 
                     if (newEntryGrid != null) {
 
-                        GridElement cancelGridElement = GridElement.findById(newEntryGrid.getUpId());
-                        String quantity = cancelGridElement != null
-                                ? cancelGridElement.getLongTraderParam().getQuantity()
-                                : config.getBaseQuantity();
-                        if (cancelGridElement != null && cancelGridElement.isHasLongOrder()) {
-                            for (String longOrderId : new ArrayList<>(cancelGridElement.getLongOrderIds())) {
-                                executor.cancelConditionalOrder(longOrderId, oid -> {
-                                    longEntryTraderIdParam(cancelGridElement, longOrderId, false);
-                                    log.info("[Gate] 多仓仓位归零, 取消gridId:{}的多单,{}", cancelGridElement.getId(), longOrderId);
-                                });
+                        String quantity = String.valueOf((accumulatedLongLossCount + 1) * Integer.parseInt(config.getQuantity()));
+                        // 向上遍历取消所有遗留多单(跳过基础入场网格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);
+                                    });
+                                }
                             }
+                            cancelCursor = GridElement.findById(cancelCursor.getUpId());
                         }
 //                        log.info("[Gate-2] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                         if (!newEntryGrid.isHasLongOrder()) {
@@ -1254,21 +1262,20 @@
 
                     if (newEntryGrid != null) {
 
-                        GridElement cancelGridElement = GridElement.findById(newEntryGrid.getDownId());
-
-                        String quantity = cancelGridElement != null
-                                ? cancelGridElement.getShortTraderParam().getQuantity()
-                                : config.getBaseQuantity();
-                        /**
-                         * 看是否有空仓挂单,有就取消
-                         */
-                        if (cancelGridElement != null && cancelGridElement.isHasShortOrder()) {
-                            for (String shortOrderId : new ArrayList<>(cancelGridElement.getShortOrderIds())) {
-                                executor.cancelConditionalOrder(shortOrderId, oid -> {
-                                    shortEntryTraderIdParam(cancelGridElement, shortOrderId, false);
-                                    log.info("[Gate] 空仓仓位归零, 取消gridId:{}的多单{}", cancelGridElement.getId(), shortOrderId);
-                                });
+                        String quantity = String.valueOf((accumulatedShortLossCount + 1) * Integer.parseInt(config.getQuantity()));
+                        // 向下遍历取消所有遗留空单(跳过基础入场网格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);
+                                    });
+                                }
                             }
+                            cancelCursor = GridElement.findById(cancelCursor.getDownId());
                         }
 //                        log.info("[Gate-4] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                         if (!newEntryGrid.isHasShortOrder()){
@@ -1589,6 +1596,7 @@
         for (GridElement e : config.getGridElements()) {
             String tpId = e.getLongTakeProfitOrderId();
             if (tpId != null) {
+                e.getLongTraderParam().setTakeProfitPlaced(false);
                 e.setLongTakeProfitOrderId(null);
                 executor.cancelConditionalOrder(tpId, oid -> {});
             }
@@ -1608,6 +1616,7 @@
         for (GridElement e : config.getGridElements()) {
             String tpId = e.getShortTakeProfitOrderId();
             if (tpId != null) {
+                e.getShortTraderParam().setTakeProfitPlaced(false);
                 e.setShortTakeProfitOrderId(null);
                 executor.cancelConditionalOrder(tpId, oid -> {});
             }
@@ -1646,56 +1655,107 @@
     // ========== 止损追单(新逻辑:3 个固定位置,每个位置挂多个 1 张止损单) ==========
 
     /**
-     * 多仓止损追单 — 3 个固定位置,从近到远分配合约。
-     * A(gridId-2): (filledQty/qty - 2) 个独立止损单,每个 qty 张
-     * B(gridId-3): 1 个止损单,qty 张
-     * C(gridId-4): 1 个止损单,qty 张
-     * 注意:多仓止损在 gridId 负方向,触发价 ≤ 网格价。
+     * 多仓止损追单 — 网格数量 = baseQuantity/quantity,从近到远分配。
+     * aCount<0跳过, aCount=0→主=2, aCount=1→主=2,辅0=1, aCount>=2→主=aCount,辅依次填1
      */
     private void extendLongStopLoss(int filledQty, int gridId) {
         int qty = Integer.parseInt(config.getQuantity());
-        int aCount = Math.max(0, filledQty / qty - 2);
-        if (aCount < 0) return;
+        int baseQty = Integer.parseInt(config.getBaseQuantity());
+        int gridCount = baseQty / qty;
+        if (gridCount <= 0 || filledQty < qty) {
+            return;
+        }
 
-        int a, b, c;
-        if (aCount == 0) { a = 2; b = 0; c = 0; }
-        else if (aCount == 1) { a = 2; b = 1; c = 0; }
-        else { a = aCount; b = 1; c = 1; }
+        int totalOrders = filledQty / qty;
+        int[] orders = new int[gridCount];
 
-        log.info("[Gate] 多仓追挂止损, 成交{}张, gridId:{}, A({})x{}  B({})x{}  C({})x{}",
-                filledQty, gridId, gridId - 2, a, gridId - 3, b, gridId - 4, c);
+        if (gridCount == 1) {
+            // 只有1个网格,全量放在上面
+            orders[0] = totalOrders;
+        } else {
+            int aCount = Math.max(0, totalOrders - 2);
+            if (aCount == 0) {
+                orders[0] = 2;
+            } else if (aCount == 1) {
+                orders[0] = 2;
+                orders[1] = 1;
+            } else {
+                orders[0] = aCount;
+                int remainder = totalOrders - aCount;
+                for (int i = 1; i < gridCount && remainder > 0; i++) {
+                    orders[i] = 1;
+                    remainder--;
+                }
+            }
+        }
 
-        if (a > 0) placeStopLossOrders(gridId - 2, a, qty, FuturesPriceTrigger.RuleEnum.NUMBER_2,
-                ORDER_TYPE_CLOSE_LONG, true);
-        if (b > 0) placeStopLossOrders(gridId - 3, b, qty, FuturesPriceTrigger.RuleEnum.NUMBER_2,
-                ORDER_TYPE_CLOSE_LONG, true);
-        if (c > 0) placeStopLossOrders(gridId - 4, c, qty, FuturesPriceTrigger.RuleEnum.NUMBER_2,
-                ORDER_TYPE_CLOSE_LONG, true);
+        StringBuilder detail = new StringBuilder();
+        for (int i = 0; i < gridCount; i++) {
+            if (orders[i] > 0) {
+                int sgId = gridId - 2 - i;
+                placeStopLossOrders(sgId, orders[i], qty, FuturesPriceTrigger.RuleEnum.NUMBER_2,
+                        ORDER_TYPE_CLOSE_LONG, true);
+                if (detail.length() > 0) {
+                    detail.append("  ");
+                }
+                detail.append(sgId).append("x").append(orders[i]);
+            }
+        }
+
+        log.info("[Gate] 多仓追挂止损, 成交{}张, gridId:{}, 网格数:{}, 分配:{}",
+                filledQty, gridId, gridCount, detail);
     }
 
     /**
-     * 空仓止损追单 — 3 个固定位置,从近到远分配合约。
-     * aCount<0跳过, aCount=0→A=2, aCount=1→A=2,B=1, aCount>=2→A=aCount,B=1,C=1
+     * 空仓止损追单 — 网格数量 = baseQuantity/quantity,从近到远分配。
+     * aCount<0跳过, aCount=0→主=2, aCount=1→主=2,辅0=1, aCount>=2→主=aCount,辅依次填1
      */
     private void extendShortStopLoss(int filledQty, int gridId) {
         int qty = Integer.parseInt(config.getQuantity());
-        int aCount = Math.max(0, filledQty / qty - 2);
-        if (aCount < 0) return;
+        int baseQty = Integer.parseInt(config.getBaseQuantity());
+        int gridCount = baseQty / qty;
+        if (gridCount <= 0 || filledQty < qty) {
+            return;
+        }
 
-        int a, b, c;
-        if (aCount == 0) { a = 2; b = 0; c = 0; }
-        else if (aCount == 1) { a = 2; b = 1; c = 0; }
-        else { a = aCount; b = 1; c = 1; }
+        int totalOrders = filledQty / qty;
+        int[] orders = new int[gridCount];
 
-        log.info("[Gate] 空仓追挂止损, 成交{}张, gridId:{}, A({})x{}  B({})x{}  C({})x{}",
-                filledQty, gridId, gridId + 2, a, gridId + 3, b, gridId + 4, c);
+        if (gridCount == 1) {
+            // 只有1个网格,全量放在上面
+            orders[0] = totalOrders;
+        } else {
+            int aCount = Math.max(0, totalOrders - 2);
+            if (aCount == 0) {
+                orders[0] = 2;
+            } else if (aCount == 1) {
+                orders[0] = 2;
+                orders[1] = 1;
+            } else {
+                orders[0] = aCount;
+                int remainder = totalOrders - aCount;
+                for (int i = 1; i < gridCount && remainder > 0; i++) {
+                    orders[i] = 1;
+                    remainder--;
+                }
+            }
+        }
 
-        if (a > 0) placeStopLossOrders(gridId + 2, a, qty, FuturesPriceTrigger.RuleEnum.NUMBER_1,
-                ORDER_TYPE_CLOSE_SHORT, false);
-        if (b > 0) placeStopLossOrders(gridId + 3, b, qty, FuturesPriceTrigger.RuleEnum.NUMBER_1,
-                ORDER_TYPE_CLOSE_SHORT, false);
-        if (c > 0) placeStopLossOrders(gridId + 4, c, qty, FuturesPriceTrigger.RuleEnum.NUMBER_1,
-                ORDER_TYPE_CLOSE_SHORT, false);
+        StringBuilder detail = new StringBuilder();
+        for (int i = 0; i < gridCount; i++) {
+            if (orders[i] > 0) {
+                int sgId = gridId + 2 + i;
+                placeStopLossOrders(sgId, orders[i], qty, FuturesPriceTrigger.RuleEnum.NUMBER_1,
+                        ORDER_TYPE_CLOSE_SHORT, false);
+                if (detail.length() > 0) {
+                    detail.append("  ");
+                }
+                detail.append(sgId).append("x").append(orders[i]);
+            }
+        }
+
+        log.info("[Gate] 空仓追挂止损, 成交{}张, gridId:{}, 网格数:{}, 分配:{}",
+                filledQty, gridId, gridCount, detail);
     }
 
     /**

--
Gitblit v1.9.1