From 5a2c3b8966269f77b60a698af602ffcfefc459ce Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 10 Aug 2026 13:53:01 +0800
Subject: [PATCH] feat(gate): 添加加仓止损配置功能

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |  235 +++++++++++++++++++++++++++++++++-------------------------
 1 files changed, 132 insertions(+), 103 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 5270f84..11b3e00 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -376,7 +376,7 @@
      */
     public void onKline(BigDecimal closePrice) {
 
-        log.info("当前价:{}", closePrice);
+//        log.info("当前价:{}", closePrice);
 
         lastKlinePrice = closePrice;
 
@@ -665,7 +665,6 @@
                 }
                 shortGridElement.setExtendStopLossInProgress(true);
 
-                accumulatedShortLossCount = 0;
                 lastShortStopLossGridId = Integer.MAX_VALUE;
                 // [Gate-需求2] 加仓后先撤空仓所有止盈+止损,再查交易所持仓后重挂
                 cancelAllShortTakeProfitsAndStopLosses();
@@ -675,6 +674,8 @@
                 // [Gate] 止盈挂单:超出基础仓位的部分,挂在多仓第一止损位
 //                placeExcessTakeProfit(posSize, false);
                 log.info("[Gate] 空单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize);
+
+
 
             }
         }
@@ -695,7 +696,6 @@
                 }
                 longGridElement.setExtendStopLossInProgress(true);
 
-                accumulatedLongLossCount = 0;
                 lastLongStopLossGridId = Integer.MAX_VALUE;
                 // [Gate-需求2] 加仓后先撤多仓所有止盈+止损,再查交易所持仓后重挂
                 cancelAllLongTakeProfitsAndStopLosses();
@@ -1152,8 +1152,8 @@
 
                     if (newEntryGrid != null) {
 
-                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
-
+//                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
+                        String quantity = String.valueOf(config.getBaseQuantity());
                         // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
                         boolean hasLongOrderBelow = false;
                         GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
@@ -1223,8 +1223,8 @@
                     if (newEntryGrid != null) {
 
 //                        String quantity = String.valueOf((accumulatedShortLossCount + 1) * Integer.parseInt(config.getQuantity()));
-                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
-
+//                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
+                        String quantity = String.valueOf(config.getBaseQuantity());
                         // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
                         boolean hasShortOrderAbove = false;
                         GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
@@ -1271,6 +1271,56 @@
         }
     }
 
+    // ========== 加仓计算 ==========
+
+    /**
+     * 根据 {@code stopLossCountMode} 计算当前有效的止损次数。
+     * <ul>
+     *   <li>{@code "single"}(单向):返回该方向的累计止损次数</li>
+     *   <li>{@code "dual"}(双向):返回多空双向累计总次数</li>
+     * </ul>
+     *
+     * @param isLong {@code true}=多仓方向,{@code false}=空仓方向
+     * @return 有效止损次数
+     */
+    private int getEffectiveStopLossCount(boolean isLong) {
+        if ("single".equals(config.getStopLossCountMode())) {
+            return isLong ? accumulatedLongLossCount : accumulatedShortLossCount;
+        }
+        // "dual" — 双向总次数
+        return accumulatedLongLossCount + accumulatedShortLossCount;
+    }
+
+    /**
+     * 根据加仓配置计算止损追单时的实际下单量。
+     * <p>公式:</p>
+     * <pre>
+     * addMultiplier = floor(effectiveStopLossCount / addPositionInterval)
+     * addQty = addMultiplier × addPositionQuantity
+     * finalQty = min(baseQuantity + addQty, maxPositionPerSide > 0 ? maxPositionPerSide : ∞)
+     * </pre>
+     *
+     * @param isLong {@code true}=多仓方向,{@code false}=空仓方向
+     * @return 实际下单张数(字符串)
+     */
+    private String calculateEntryQuantity(boolean isLong) {
+        int baseQty = Integer.parseInt(config.getBaseQuantity());
+        int interval = config.getAddPositionInterval();
+        int addQtyPerUnit = config.getAddPositionQuantity();
+        int maxPerSide = config.getMaxPositionPerSide();
+
+        int effectiveCount = getEffectiveStopLossCount(isLong);
+        int addMultiplier = interval > 0 ? effectiveCount / interval : 0;
+        int addQty = addMultiplier * addQtyPerUnit;
+        int totalQty = baseQty + addQty;
+
+        if (maxPerSide > 0 && totalQty > maxPerSide) {
+            totalQty = maxPerSide;
+        }
+
+        return String.valueOf(totalQty);
+    }
+
     private void handleLongStopLossTriggered(GridElement gridElement, String orderId) {
         gridElement.removeLongStopLossOrderId(orderId);
 
@@ -1282,6 +1332,8 @@
         }
 
         lastLongStopLossGridId = gridId;
+
+        accumulatedLongLossCount++;
         log.info("[Gate] 多仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
                 gridId, accumulatedLongLossCount, sameGrid ? "(同网格)" : "");
         int newEntryGridId = gridId + 1;
@@ -1295,8 +1347,9 @@
 
         // 止损追单:同一网格可有多笔挂单,不判断 isHasLongOrder,直接挂单
         BigDecimal triggerPrice = newEntryGrid.getGridPrice();
-//        String size = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
-        String size = String.valueOf(config.getBaseQuantity());
+        String size = calculateEntryQuantity(true);
+        log.info("[Gate] 多仓止损追单 有效次数:{}, 基础:{}张 → 实际:{}张, 模式:{}",
+                getEffectiveStopLossCount(true), config.getBaseQuantity(), size, config.getStopLossCountMode());
         newEntryGrid.getLongTraderParam().setQuantity(size);
         placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
                 FuturesPriceTrigger.RuleEnum.NUMBER_1, size);
@@ -1325,6 +1378,7 @@
             return;
         }
         lastShortStopLossGridId = gridId;
+        accumulatedShortLossCount++;
         log.info("[Gate] 空仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
                 gridId, accumulatedShortLossCount, sameGrid ? "(同网格)" : "");
         int newEntryGridId = gridId - 1;
@@ -1338,8 +1392,9 @@
 
         // 止损追单:同一网格可有多笔挂单,不判断 isHasShortOrder,直接挂单
         BigDecimal triggerPrice = newEntryGrid.getGridPrice();
-//        String size = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
-        String size = String.valueOf(config.getBaseQuantity());
+        String size = calculateEntryQuantity(false);
+        log.info("[Gate] 空仓止损追单 有效次数:{}, 基础:{}张 → 实际:{}张, 模式:{}",
+                getEffectiveStopLossCount(false), config.getBaseQuantity(), size, config.getStopLossCountMode());
         newEntryGrid.getShortTraderParam().setQuantity(size);
         placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
                 FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size));
@@ -1690,98 +1745,6 @@
     }
 
     /**
-     * 挂单成交后,将超出基础仓位的部分挂止盈单,挂在对向仓位的第一止损位上。
-     *
-     * <p>遍历所有 GridElement,找到对向仓位第一个有止损单的网格作为止盈挂单位置。
-     *
-     * <p>例:空仓成交后持仓 8 张,基础 4 张 → 超出 4 张,
-     * 找到多仓第一止损位(如 gridId=-2)→ 在该位置挂空仓止盈单。
-     *
-     * @param posSize  当前总持仓张数
-     * @param isLong   true=多仓成交,false=空仓成交
-     */
-    private void placeExcessTakeProfit(int posSize, boolean isLong) {
-        int baseQty = Integer.parseInt(config.getBaseQuantity());
-        int excessQty = posSize - baseQty;
-        if (excessQty <= 0) {
-            return;
-        }
-
-        // 遍历找到对向仓位第一个有止损单的网格
-        GridElement tpElem = isLong ? findFirstShortStopLossGrid() : findFirstLongStopLossGrid();
-        if (tpElem == null) {
-            log.warn("[Gate] {}止盈挂单失败:未找到对向仓止损位", isLong ? "多仓" : "空仓");
-            return;
-        }
-        int tpGridId = tpElem.getId();
-
-        BigDecimal triggerPrice = tpElem.getGridPrice();
-        String orderType = isLong ? ORDER_TYPE_CLOSE_LONG : ORDER_TYPE_CLOSE_SHORT;
-        // 多仓止盈:价格≥触发价时平仓(NUMBER_1);空仓止盈:价格≤触发价时平仓(NUMBER_2)
-        FuturesPriceTrigger.RuleEnum rule = isLong ? FuturesPriceTrigger.RuleEnum.NUMBER_1
-                : FuturesPriceTrigger.RuleEnum.NUMBER_2;
-        String size = isLong ? negate(String.valueOf(excessQty)) : String.valueOf(excessQty);
-
-//        if (isLong && tpElem.getLongTakeProfitOrderId() != null) {
-//            executor.cancelConditionalOrder(tpElem.getLongTakeProfitOrderId(), oid -> {
-//                longTakeProfitTraderIdParam(tpElem, null, false);
-//                log.info("[Gate] 取消旧止盈, gridId:{}, orderId:{}", tpGridId, oid);
-//            });
-//        } else if (!isLong && tpElem.getShortTakeProfitOrderId() != null) {
-//            executor.cancelConditionalOrder(tpElem.getShortTakeProfitOrderId(), oid -> {
-//                shortTakeProfitTraderIdParam(tpElem, null, false);
-//                log.info("[Gate] 取消旧止盈, gridId:{}, orderId:{}", tpGridId, oid);
-//            });
-//        }
-
-        String finalSize = size;
-        int finalTpGridId = tpGridId;
-        executor.placeTakeProfit(triggerPrice, rule, orderType, size,
-                profitId -> {
-                    if (isLong) {
-                        longTakeProfitTraderIdParam(tpElem, profitId, true);
-                    } else {
-                        shortTakeProfitTraderIdParam(tpElem, profitId, true);
-                    }
-                    log.info("[Gate] {}止盈挂单, gridId:{}, 触发价:{}, 数量:{}, takeProfitId:{}",
-                            isLong ? "多仓" : "空仓", finalTpGridId, triggerPrice, finalSize, profitId);
-                }
-        );
-    }
-
-    /**
-     * 找到有长仓止损单且离 0 最近的网格(第一个多仓止损位)。
-     */
-    private GridElement findFirstLongStopLossGrid() {
-        GridElement first = null;
-        for (GridElement e : config.getGridElements()) {
-            if (!e.getLongStopLossOrderIds().isEmpty()) {
-                // 多仓止损在负数区,取 id 最大(最靠近 0)的
-                if (first == null || e.getId() > first.getId()) {
-                    first = e;
-                }
-            }
-        }
-        return first;
-    }
-
-    /**
-     * 找到有空仓止损单且离 0 最近的网格(第一个空仓止损位)。
-     */
-    private GridElement findFirstShortStopLossGrid() {
-        GridElement first = null;
-        for (GridElement e : config.getGridElements()) {
-            if (!e.getShortStopLossOrderIds().isEmpty()) {
-                // 空仓止损在正数区,取 id 最小(最靠近 0)的
-                if (first == null || e.getId() < first.getId()) {
-                    first = e;
-                }
-            }
-        }
-        return first;
-    }
-
-    /**
      * 延展完成后重挂止损(处理被跳过的入场单成交)。
      * 取消已有止损单并用最新仓位重新挂单,确保止损覆盖最新持仓数。
      */
@@ -1996,4 +1959,70 @@
     public StrategyState getState() { return state; }
     /** 注入WS客户端,用于订阅状态检查 */
     public void setWsClient(GateKlineWebSocketClient wsClient) { this.wsClient = wsClient; }
+
+    // ========== 止损查表辅助方法 ==========
+
+    /** 找到第一个有多仓止损单的网格(首个匹配即返回) */
+    private GridElement findFirstLongStopLossGrid() {
+        for (GridElement e : config.getGridElements()) {
+            if (!e.getLongStopLossOrderIds().isEmpty()) return e;
+        }
+        return null;
+    }
+
+    /** 找到第一个有空仓止损单的网格(首个匹配即返回) */
+    private GridElement findFirstShortStopLossGrid() {
+        for (GridElement e : config.getGridElements()) {
+            if (!e.getShortStopLossOrderIds().isEmpty()) return e;
+        }
+        return null;
+    }
+
+    /**
+     * 在指定网格挂一笔对手止盈单(非满仓超额止盈,挂在止损触发位的下一格)。
+     */
+    private void placeTakeProfitAtGrid(GridElement tpElem, boolean isLong, int qty, int times) {
+        BigDecimal triggerPrice = tpElem.getGridPrice();
+        String orderType = isLong ? ORDER_TYPE_CLOSE_LONG : ORDER_TYPE_CLOSE_SHORT;
+        FuturesPriceTrigger.RuleEnum rule = isLong ? FuturesPriceTrigger.RuleEnum.NUMBER_1
+                : FuturesPriceTrigger.RuleEnum.NUMBER_2;
+        String size = isLong ? negate(String.valueOf(qty)) : String.valueOf(qty);
+        int gridId = tpElem.getId();
+        executor.placeTakeProfit(triggerPrice, rule, orderType, size,
+                profitId -> {
+                    if (isLong) {
+                        longTakeProfitTraderIdParam(tpElem, profitId, true);
+                    } else {
+                        shortTakeProfitTraderIdParam(tpElem, profitId, true);
+                    }
+                    log.info("[Gate] 止损{}→对手超额止盈 gridId:{}, 量:{}, tpId:{}", times, gridId, qty, profitId);
+                }
+        );
+    }
+
+    /**
+     * 挂对手盘止盈单:在对向仓位第一止损位挂止盈。
+     * @param isLong true=挂多仓止盈(对空仓), false=挂空仓止盈(对多仓)
+     */
+    private void placeOpponentTakeProfit(boolean isLong, int tpQty, int times, int gridId) {
+        GridElement tpElem = GridElement.findById(isLong ? gridId + 1 : gridId - 1);
+        if (tpElem == null) {
+            log.warn("[Gate] 对手止盈挂单失败:未找到止损位");
+            return;
+        }
+        int tpGridId = tpElem.getId();
+        BigDecimal triggerPrice = tpElem.getGridPrice();
+        String orderType = isLong ? ORDER_TYPE_CLOSE_LONG : ORDER_TYPE_CLOSE_SHORT;
+        FuturesPriceTrigger.RuleEnum rule = isLong ? FuturesPriceTrigger.RuleEnum.NUMBER_1
+                : FuturesPriceTrigger.RuleEnum.NUMBER_2;
+        String size = isLong ? negate(String.valueOf(tpQty)) : String.valueOf(tpQty);
+        executor.placeTakeProfit(triggerPrice, rule, orderType, size,
+                profitId -> {
+                    if (isLong) longTakeProfitTraderIdParam(tpElem, profitId, true);
+                    else        shortTakeProfitTraderIdParam(tpElem, profitId, true);
+                    log.info("[Gate] 止损次数{}→对手{}止盈 gridId:{}, 量:{}, tpId:{}",
+                            times, isLong ? "多仓" : "空仓", tpGridId, size, profitId);
+                }
+        );
+    }
 }

--
Gitblit v1.9.1