From 377012b130a26728bed009a228076e72cd01f2f8 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 11 May 2026 16:57:34 +0800
Subject: [PATCH] refactor(gateApi): 优化网格交易逻辑和止盈策略

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |   88 ++++++++++++++++-------------
 src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md          |   52 +++++++++--------
 2 files changed, 76 insertions(+), 64 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 ee9b68d..feb3fa0 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -354,7 +354,7 @@
      *   <li><b>有仓位 (size ≠ 0)</b>:
      *     <ul>
      *       <li>首次开仓(基底):标记 baseOpened=true,记录基底入场价,双基底都成交后生成网格队列</li>
-     *       <li>仓位净增加(size > 之前记录值):说明网格触发了新开仓 → 设止盈条件单</li>
+     *       <li>仓位净增加(size > 之前记录值):说明网格触发了新开仓 → 取对应方向队列首元素为止盈价,设止盈条件单</li>
      *       <li>仓位减少或不变(止盈平仓后):仅更新 positionSize,不重复设止盈</li>
      *     </ul>
      *   </li>
@@ -386,10 +386,14 @@
                     tryGenerateQueues();
                 } else if (size.compareTo(longPositionSize) > 0) {
                     longPositionSize = size;
-                    BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.add(config.getGridRate())).setScale(1, RoundingMode.HALF_UP);
-                    executor.placeTakeProfit(tpPrice,
-                            FuturesPriceTrigger.RuleEnum.NUMBER_1, ORDER_TYPE_CLOSE_LONG, negate(config.getQuantity()));
-                    log.info("[Gate] 多单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, negate(config.getQuantity()));
+                    if (longPriceQueue.isEmpty()) {
+                        log.warn("[Gate] 多仓队列为空,无法设止盈");
+                    } else {
+                        BigDecimal tpPrice = longPriceQueue.get(0);
+                        executor.placeTakeProfit(tpPrice,
+                                FuturesPriceTrigger.RuleEnum.NUMBER_1, ORDER_TYPE_CLOSE_LONG, negate(config.getQuantity()));
+                        log.info("[Gate] 多单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, negate(config.getQuantity()));
+                    }
                 } else {
                     longPositionSize = size;
                 }
@@ -409,10 +413,14 @@
                     tryGenerateQueues();
                 } else if (size.abs().compareTo(shortPositionSize) > 0) {
                     shortPositionSize = size.abs();
-                    BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate())).setScale(1, RoundingMode.HALF_UP);
-                    executor.placeTakeProfit(tpPrice,
-                            FuturesPriceTrigger.RuleEnum.NUMBER_2, ORDER_TYPE_CLOSE_SHORT, config.getQuantity());
-                    log.info("[Gate] 空单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, config.getQuantity());
+                    if (shortPriceQueue.isEmpty()) {
+                        log.warn("[Gate] 空仓队列为空,无法设止盈");
+                    } else {
+                        BigDecimal tpPrice = shortPriceQueue.get(0);
+                        executor.placeTakeProfit(tpPrice,
+                                FuturesPriceTrigger.RuleEnum.NUMBER_2, ORDER_TYPE_CLOSE_SHORT, config.getQuantity());
+                        log.info("[Gate] 空单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, config.getQuantity());
+                    }
                 } else {
                     shortPositionSize = size.abs();
                 }
@@ -512,10 +520,10 @@
      * <h3>执行流程</h3>
      * <ol>
      *   <li>匹配队列元素 → 为空则直接返回</li>
-     *   <li>保证金检查 → 安全则开空一次</li>
-     *   <li>额外反向开多:若多仓均价 > 空仓均价 且 当前价夹在中间且远离多仓均价</li>
      *   <li>空仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 − gridRate) 循环递减)</li>
      *   <li>多仓队列:以多仓队列首元素(最小价)为种子,生成 matched.size() 个递减元素加入</li>
+     *   <li>保证金检查 → 安全则开空一次</li>
+     *   <li>额外反向开多:若多仓均价 > 空仓均价 且 当前价夹在中间且远离多仓均价</li>
      * </ol>
      *
      * <h3>多仓队列转移过滤</h3>
@@ -538,19 +546,6 @@
             return;
         }
         log.info("[Gate] 空仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice);
-        if (!isMarginSafe()) {
-            log.warn("[Gate] 保证金超限,跳过空单开仓");
-        } else {
-            executor.openShort(negate(config.getQuantity()), null, null);
-            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
-                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
-                    && longEntryPrice.compareTo(shortEntryPrice) > 0
-                    && currentPrice.compareTo(shortEntryPrice) > 0
-                    && currentPrice.compareTo(longEntryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate()))) < 0) {
-                executor.openLong(config.getQuantity(), null, null);
-                log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", currentPrice);
-            }
-        }
 
         synchronized (shortPriceQueue) {
             shortPriceQueue.removeAll(matched);
@@ -586,6 +581,20 @@
             }
             log.info("[Gate] 现多队列:{}", longPriceQueue);
         }
+
+        if (!isMarginSafe()) {
+            log.warn("[Gate] 保证金超限,跳过空单开仓");
+        } else {
+            executor.openShort(negate(config.getQuantity()), null, null);
+            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
+                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
+                    && longEntryPrice.compareTo(shortEntryPrice) > 0
+                    && currentPrice.compareTo(shortEntryPrice) > 0
+                    && currentPrice.compareTo(longEntryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate()))) < 0) {
+                executor.openLong(config.getQuantity(), null, null);
+                log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", currentPrice);
+            }
+        }
     }
 
     /**
@@ -598,10 +607,10 @@
      * <h3>执行流程</h3>
      * <ol>
      *   <li>匹配队列元素 → 为空则直接返回</li>
-     *   <li>保证金检查 → 安全则开多一次</li>
-     *   <li>额外反向开空:若多仓均价 > 空仓均价 且 当前价夹在中间且远离空仓均价</li>
      *   <li>多仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 + gridRate) 循环递增)</li>
      *   <li>空仓队列:以空仓队列首元素(最高价)为种子,生成 matched.size() 个递增元素加入</li>
+     *   <li>保证金检查 → 安全则开多一次</li>
+     *   <li>额外反向开空:若多仓均价 > 空仓均价 且 当前价夹在中间且远离空仓均价</li>
      * </ol>
      *
      * <h3>空仓队列转移过滤</h3>
@@ -625,19 +634,6 @@
         }
 
         log.info("[Gate] 多仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice);
-        if (!isMarginSafe()) {
-            log.warn("[Gate] 保证金超限,跳过多单开仓");
-        } else {
-            executor.openLong(config.getQuantity(), null, null);
-            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
-                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
-                    && longEntryPrice.compareTo(shortEntryPrice) > 0
-                    && currentPrice.compareTo(shortEntryPrice.multiply(BigDecimal.ONE.add(config.getGridRate()))) > 0
-                    && currentPrice.compareTo(longEntryPrice) < 0) {
-                executor.openShort(negate(config.getQuantity()), null, null);
-                log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", currentPrice);
-            }
-        }
 
         synchronized (longPriceQueue) {
             longPriceQueue.removeAll(matched);
@@ -673,6 +669,20 @@
             }
             log.info("[Gate] 现空队列:{}", shortPriceQueue);
         }
+
+        if (!isMarginSafe()) {
+            log.warn("[Gate] 保证金超限,跳过多单开仓");
+        } else {
+            executor.openLong(config.getQuantity(), null, null);
+            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
+                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
+                    && longEntryPrice.compareTo(shortEntryPrice) > 0
+                    && currentPrice.compareTo(shortEntryPrice.multiply(BigDecimal.ONE.add(config.getGridRate()))) > 0
+                    && currentPrice.compareTo(longEntryPrice) < 0) {
+                executor.openShort(negate(config.getQuantity()), null, null);
+                log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", currentPrice);
+            }
+        }
     }
 
     // ---- 保证金安全阀 ----
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md b/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
index 8a1dfb1..744c890 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
@@ -186,29 +186,31 @@
 │
 ├─ processShortGrid: 当前价 < 空仓队列元素(价格跌破了队列中的高价)
 │   ├─ 匹配: 收集所有 > 当前价的空仓队列元素(降序,一旦遇≤即停止)
-│   ├─ 保证金检查: positionInitialMargin / initialPrincipal < marginRatioLimit(20%)
-│   │   ├─ 安全 → openShort 开空单
-│   │   │   └─ 额外条件: 多>空 且 空仓均价 < 当前价 < 多仓均价×(1−gridRate) → openLong 额外开多一次
-│   │   └─ 超限 → 跳过开仓,队列照常更新
 │   ├─ 空仓队列: 移除 matched,尾部补充新元素(尾价 × (1−gridRate) 循环递减)
-│   └─ 多仓队列转移:
-│       ├─ 以多仓队列首元素(最小价)为种子
-│       ├─ 生成 matched.size() 个递减元素: seed × (1 − gridRate × i)
-│       ├─ 贴近过滤: |currentPrice − longEntryPrice| < longEntryPrice × gridRate → 跳过
-│       └─ 升序排列,截断到 gridQueueSize
+│   ├─ 多仓队列转移:
+│   │   ├─ 以多仓队列首元素(最小价)为种子
+│   │   ├─ 生成 matched.size() 个递减元素: seed × (1 − gridRate × i)
+│   │   ├─ 贴近过滤: |currentPrice − longEntryPrice| < longEntryPrice × gridRate → 跳过
+│   │   └─ 升序排列,截断到 gridQueueSize
+│   └─ 下单(队列已更新,避免竞态):
+│       ├─ 保证金检查: positionInitialMargin / initialPrincipal < marginRatioLimit(20%)
+│       │   ├─ 安全 → openShort 开空单
+│       │   │   └─ 额外条件: 多>空 且 空仓均价 < 当前价 < 多仓均价×(1−gridRate) → openLong 额外开多一次
+│       │   └─ 超限 → 跳过开仓
 │
 └─ processLongGrid: 当前价 > 多仓队列元素(价格涨超了队列中的低价)
     ├─ 匹配: 收集所有 < 当前价的多仓队列元素(升序,一旦遇≥即停止)
-    ├─ 保证金检查: 同上
-    │   ├─ 安全 → openLong 开多单
-    │   │   └─ 额外条件: 多>空 且 空仓均价×(1+gridRate) < 当前价 < 多仓均价 → openShort 额外开空一次
-    │   └─ 超限 → 跳过开仓
     ├─ 多仓队列: 移除 matched,尾部补充新元素(尾价 × (1+gridRate) 循环递增)
-    └─ 空仓队列转移:
-        ├─ 以空仓队列首元素(最高价)为种子
-        ├─ 生成 matched.size() 个递增元素: seed × (1 + gridRate × i)
-        ├─ 贴近过滤: |currentPrice − shortEntryPrice| < shortEntryPrice × gridRate → 跳过
-        └─ 降序排列,截断到 gridQueueSize
+    ├─ 空仓队列转移:
+    │   ├─ 以空仓队列首元素(最高价)为种子
+    │   ├─ 生成 matched.size() 个递增元素: seed × (1 + gridRate × i)
+    │   ├─ 贴近过滤: |currentPrice − shortEntryPrice| < shortEntryPrice × gridRate → 跳过
+    │   └─ 降序排列,截断到 gridQueueSize
+    └─ 下单(队列已更新,避免竞态):
+        ├─ 保证金检查: 同上
+        │   ├─ 安全 → openLong 开多单
+        │   │   └─ 额外条件: 多>空 且 空仓均价×(1+gridRate) < 当前价 < 多仓均价 → openShort 额外开空一次
+        │   └─ 超限 → 跳过开仓
 ```
 
 ### 队列转移规则(新)
@@ -316,10 +318,10 @@
 每根K线 → onKline → updateUnrealizedPnl → processShortGrid + processLongGrid
 
 仓位推送(每次开仓成交后自动触发):
-  → DUAL_LONG, size>0, 非基底 → 设多头止盈单:止盈价=entryPrice×(1+gridRate),
-      使用 plan-close-long-position,平仓张数=-quantity(负=平多)
-  → DUAL_SHORT, size<0, 非基底 → 设空头止盈单:止盈价=entryPrice×(1−gridRate),
-      使用 plan-close-short-position,平仓张数=+quantity(正=平空)
+  → DUAL_LONG, size>0, 非基底 → 设多头止盈单:止盈价=longPriceQueue[0](多仓队列首元素),
+      使用 plan-close-long-position,平仓张数=-quantity(负=平多),rule=NUMBER_1(≥)
+  → DUAL_SHORT, size<0, 非基底 → 设空头止盈单:止盈价=shortPriceQueue[0](空仓队列首元素),
+      使用 plan-close-short-position,平仓张数=+quantity(正=平空),rule=NUMBER_2(≤)
 
 额外反向开仓(多>空倒挂时):
   → 空仓队列触发 + 条件满足 → 额外开多一次
@@ -473,10 +475,10 @@
 
 | 方向 | 公式 | order_type | size(平仓张数) | rule |
 |------|------|------------|-----------|------|
-| 多头 TP | entry × (1+gridRate) | `plan-close-long-position` | `-quantity`(负=平多) | NUMBER_1(≥触发价) |
-| 空头 TP | entry × (1−gridRate) | `plan-close-short-position` | `+quantity`(正=平空) | NUMBER_2(≤触发价) |
+| 多头 TP | longPriceQueue[0](多仓队列首元素) | `plan-close-long-position` | `-quantity`(负=平多) | NUMBER_1(≥触发价) |
+| 空头 TP | shortPriceQueue[0](空仓队列首元素) | `plan-close-short-position` | `+quantity`(正=平空) | NUMBER_2(≤触发价) |
 
-> 止盈单使用显式张数而非 autoSize。每次网格触发开仓 quantity 张,只为该批张数创建独立的条件单,多个止盈单之间互不覆盖。
+> 止盈价取自对应方向队列的首元素(多仓队列升序首=最小价,空仓队列降序首=最高价)。止盈单使用显式张数而非 autoSize。每次网格触发开仓 quantity 张,只为该批张数创建独立的条件单,多个止盈单之间互不覆盖。
 
 **REST API 调用**:
 

--
Gitblit v1.9.1