From bd6b336a68ff0355936c4026f5e39d2375c273ac Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Fri, 31 Jul 2026 10:47:03 +0800
Subject: [PATCH] feat(gateApi): 添加止盈挂单功能并优化盈亏计算

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |  116 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 files changed, 114 insertions(+), 2 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 a734d97..3671ea1 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -435,12 +435,28 @@
             BigDecimal target = initialPrincipal.add(config.getExpectedProfit());
 
             FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
-            BigDecimal totalEquity = new BigDecimal(account.getTotal()).add(new BigDecimal(account.getUnrealisedPnl()));
+            // 预估平仓手续费 = 持仓量 × 合约乘数 × 入场价 × taker费率
+            BigDecimal multiplier = config.getContractMultiplier();
+            BigDecimal longCloseFee = BigDecimal.ZERO;
+            if (longPositionSize.compareTo(BigDecimal.ZERO) > 0 && longEntryPrice.compareTo(BigDecimal.ZERO) > 0) {
+                longCloseFee = longPositionSize.multiply(multiplier).multiply(longEntryPrice).multiply(TAKER_FEE_RATE);
+            }
+            BigDecimal shortCloseFee = BigDecimal.ZERO;
+            if (shortPositionSize.compareTo(BigDecimal.ZERO) > 0 && shortEntryPrice.compareTo(BigDecimal.ZERO) > 0) {
+                shortCloseFee = shortPositionSize.multiply(multiplier).multiply(shortEntryPrice).multiply(TAKER_FEE_RATE);
+            }
+            BigDecimal estimatedCloseFee = longCloseFee.add(shortCloseFee);
+
+            BigDecimal totalEquity = new BigDecimal(account.getTotal())
+                    .add(new BigDecimal(account.getUnrealisedPnl()))
+                    .subtract(estimatedCloseFee);
 
             if (totalEquity.compareTo(target) > 0) {
                 currentRound++;
                 int maxRounds = config.getRounds();
-                log.info("[Gate] 盈亏达标(净权益{}>目标{}),第{}轮完成", totalEquity, target, currentRound);
+                log.info("[Gate] 盈亏达标(净权益{}→含手续费-{}=实际{}>目标{}),第{}轮完成",
+                        new BigDecimal(account.getTotal()).add(new BigDecimal(account.getUnrealisedPnl())),
+                        estimatedCloseFee, totalEquity, target, currentRound);
 
                 if (maxRounds > 0 && currentRound >= maxRounds) {
                     log.info("[Gate] 已达到运行轮数上限({}),策略停止", maxRounds);
@@ -656,6 +672,8 @@
                 // REST 查询可能因交易所延迟返回旧值,与 WS 本地缓存取最大值兜底
                 int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue());
                 extendShortStopLoss(posSize, shortGridElement.getId());
+                // [Gate] 止盈挂单:超出基础仓位的部分,挂在多仓第一止损位
+                placeExcessTakeProfit(posSize, false);
                 log.info("[Gate] 空单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize);
 
             }
@@ -684,6 +702,8 @@
                 // REST 查询可能因交易所延迟返回旧值,与 WS 本地缓存取最大值兜底
                 int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue());
                 extendLongStopLoss(posSize, longGridElement.getId());
+                // [Gate] 止盈挂单:超出基础仓位的部分,挂在空仓第一止损位
+                placeExcessTakeProfit(posSize, true);
                 log.info("[Gate] 多单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize);
 
             }
@@ -1668,6 +1688,98 @@
     }
 
     /**
+     * 挂单成交后,将超出基础仓位的部分挂止盈单,挂在对向仓位的第一止损位上。
+     *
+     * <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;
+    }
+
+    /**
      * 延展完成后重挂止损(处理被跳过的入场单成交)。
      * 取消已有止损单并用最新仓位重新挂单,确保止损覆盖最新持仓数。
      */

--
Gitblit v1.9.1