From 5a7aa8f6aea33343cc1e2b192e8c9b832a4d74ca Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Fri, 17 Jul 2026 10:05:35 +0800
Subject: [PATCH] fix(gateApi): 解决网格交易止盈订单重复挂单问题
---
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java | 335 +++++++++++++++++++++++++++++++------------------------
1 files changed, 186 insertions(+), 149 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 19958f3..5249c57 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -134,13 +134,13 @@
/** 多头是否活跃(有仓位) */
private volatile boolean longActive = false;
- /** 多头累计止损次数(加仓订单成交后归零),同一网格多次止损不累加 */
+ /** 多头累计止损次数(始终递增,加仓订单成交后归零) */
private volatile int accumulatedLongLossCount = 0;
- /** 空头累计止损次数(加仓订单成交后归零),同一网格多次止损不累加 */
+ /** 空头累计止损次数(始终递增,加仓订单成交后归零) */
private volatile int accumulatedShortLossCount = 0;
- /** 最近触发止损的多头网格ID,用于判断是否是同一网格的连续止损 */
+ /** 最近触发止损的多头网格ID */
private volatile int lastLongStopLossGridId = Integer.MAX_VALUE;
- /** 最近触发止损的空头网格ID,用于判断是否是同一网格的连续止损 */
+ /** 最近触发止损的空头网格ID */
private volatile int lastShortStopLossGridId = Integer.MAX_VALUE;
private volatile BigDecimal lastKlinePrice;
@@ -398,7 +398,8 @@
return;
}
- checkProfitAndReset();
+ // 异步检查盈亏,避免 REST 调用阻塞 WS 心跳导致 Socket closed
+ executor.submitTask(this::checkProfitAndReset);
if (state == StrategyState.ACTIVE &&
longActive == false &&
@@ -633,7 +634,7 @@
if (StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0") ){
int filledQty = Integer.parseInt(shortGridElement.getShortTraderParam().getQuantity());
shortEntryTraderIdParam(shortGridElement, orderId, false);
- accumulatedShortLossCount = 0; // 空单成交,重置止损追单计数
+ accumulatedShortLossCount = 0;
lastShortStopLossGridId = Integer.MAX_VALUE;
// [Gate-需求2] 加仓后先撤空仓所有止盈+止损,再查交易所持仓后重挂
cancelAllShortTakeProfitsAndStopLosses();
@@ -666,43 +667,32 @@
// }
// );
- // 空仓持仓超过baseQuantity时,先找多仓第一个止损位置,从该位置向下挂止盈(间隔=1)
- BigDecimal shortBaseQty = new BigDecimal(config.getBaseQuantity());
- BigDecimal shortGridQty = new BigDecimal(config.getQuantity());
- if (BigDecimal.valueOf(posSize).compareTo(shortBaseQty) > 0) {
- BigDecimal shortExcess = BigDecimal.valueOf(posSize).subtract(shortBaseQty);
- int shortExcessCount = shortExcess.divide(shortGridQty, 0, RoundingMode.DOWN).intValue();
+ // 空仓止盈:超额部分挂止盈,从entry网格向下逐个挂
+ int shortBaseQty = Integer.parseInt(config.getBaseQuantity());
+ int shortGridQty = Integer.parseInt(config.getQuantity());
+ int shortTpCount = posSize > shortBaseQty ? (posSize - shortBaseQty) / shortGridQty : 0;
-// // 找多仓第一个(最近的)止损位置
-// int firstLongSlId = 0;
-// for (GridElement e : config.getGridElements()) {
-// if (e.hasLongStopLossOrders()) {
-// if (firstLongSlId == 0 || e.getId() > firstLongSlId) {
-// firstLongSlId = e.getId();
-// }
-// }
-// }
-
- for (int i = 0; i < shortExcessCount; i++) {
- int tpGridId = shortGridElement.getId() - 2 * (i + 1);
- GridElement tpElem = GridElement.findById(tpGridId);
- if (tpElem == null || tpElem.getShortTakeProfitOrderId() != null) {
- continue;
- }
- BigDecimal tpPrice = tpElem.getGridPrice();
- int finalTpGridId = tpGridId;
- executor.placeTakeProfit(
- tpPrice,
- FuturesPriceTrigger.RuleEnum.NUMBER_2,
- ORDER_TYPE_CLOSE_SHORT,
- config.getQuantity(),
- profitId -> {
- shortTakeProfitTraderIdParam(tpElem, profitId, true);
- log.info("[Gate] 空仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}",
- finalTpGridId, tpPrice, profitId);
- }
- );
+ for (int i = 0; i < shortTpCount; i++) {
+ int tpGridId = shortGridElement.getId() - 2 * (i + 1);
+ GridElement tpElem = GridElement.findById(tpGridId);
+ // 用 takeProfitPlaced 做同步标记,避免异步回调未执行时重复挂单
+ if (tpElem == null || tpElem.getShortTraderParam().isTakeProfitPlaced()) {
+ continue;
}
+ tpElem.getShortTraderParam().setTakeProfitPlaced(true);
+ BigDecimal tpPrice = tpElem.getGridPrice();
+ int finalTpGridId = tpGridId;
+ executor.placeTakeProfit(
+ tpPrice,
+ FuturesPriceTrigger.RuleEnum.NUMBER_2,
+ ORDER_TYPE_CLOSE_SHORT,
+ config.getQuantity(),
+ profitId -> {
+ shortTakeProfitTraderIdParam(tpElem, profitId, true);
+ log.info("[Gate] 空仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}",
+ finalTpGridId, tpPrice, profitId);
+ }
+ );
}
}
}
@@ -712,7 +702,7 @@
int filledQty = Integer.parseInt(longGridElement.getLongTraderParam().getQuantity());
longEntryTraderIdParam(longGridElement, orderId, false);
- accumulatedLongLossCount = 0; // 多单成交,重置止损追单计数
+ accumulatedLongLossCount = 0;
lastLongStopLossGridId = Integer.MAX_VALUE;
// [Gate-需求2] 加仓后先撤多仓所有止盈+止损,再查交易所持仓后重挂
cancelAllLongTakeProfitsAndStopLosses();
@@ -745,43 +735,32 @@
// }
// );
- // 多仓持仓超过baseQuantity时,先找空仓第一个止损位置,从该位置向上挂止盈(间隔=1)
- BigDecimal longBaseQty = new BigDecimal(config.getBaseQuantity());
- BigDecimal longGridQty = new BigDecimal(config.getQuantity());
- if (BigDecimal.valueOf(posSize).compareTo(longBaseQty) > 0) {
- BigDecimal longExcess = BigDecimal.valueOf(posSize).subtract(longBaseQty);
- int longExcessCount = longExcess.divide(longGridQty, 0, RoundingMode.DOWN).intValue();
+ // 多仓止盈:超额部分挂止盈,从entry网格向上逐个挂
+ int longBaseQty = Integer.parseInt(config.getBaseQuantity());
+ int longGridQty = Integer.parseInt(config.getQuantity());
+ int longTpCount = posSize > longBaseQty ? (posSize - longBaseQty) / longGridQty : 0;
-// // 找空仓第一个(最近的)止损位置
-// int firstShortSlId = 0;
-// for (GridElement e : config.getGridElements()) {
-// if (e.hasShortStopLossOrders()) {
-// if (firstShortSlId == 0 || e.getId() < firstShortSlId) {
-// firstShortSlId = e.getId();
-// }
-// }
-// }
-
- for (int i = 0; i < longExcessCount; i++) {
- int tpGridId = longGridElement.getId() + 2 * (i + 1);
- GridElement tpElem = GridElement.findById(tpGridId);
- if (tpElem == null || tpElem.getLongTakeProfitOrderId() != null) {
- continue;
- }
- BigDecimal tpPrice = tpElem.getGridPrice();
- int finalTpGridId = tpGridId;
- executor.placeTakeProfit(
- tpPrice,
- FuturesPriceTrigger.RuleEnum.NUMBER_1,
- ORDER_TYPE_CLOSE_LONG,
- negate(config.getQuantity()),
- profitId -> {
- longTakeProfitTraderIdParam(tpElem, profitId, true);
- log.info("[Gate] 多仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}",
- finalTpGridId, tpPrice, profitId);
- }
- );
+ for (int i = 0; i < longTpCount; i++) {
+ int tpGridId = longGridElement.getId() + 2 * (i + 1);
+ GridElement tpElem = GridElement.findById(tpGridId);
+ // 用 takeProfitPlaced 做同步标记,避免异步回调未执行时重复挂单
+ if (tpElem == null || tpElem.getLongTraderParam().isTakeProfitPlaced()) {
+ continue;
}
+ tpElem.getLongTraderParam().setTakeProfitPlaced(true);
+ BigDecimal tpPrice = tpElem.getGridPrice();
+ int finalTpGridId = tpGridId;
+ executor.placeTakeProfit(
+ tpPrice,
+ FuturesPriceTrigger.RuleEnum.NUMBER_1,
+ ORDER_TYPE_CLOSE_LONG,
+ negate(config.getQuantity()),
+ profitId -> {
+ longTakeProfitTraderIdParam(tpElem, profitId, true);
+ log.info("[Gate] 多仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}",
+ finalTpGridId, tpPrice, profitId);
+ }
+ );
}
}
}
@@ -1229,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()) {
@@ -1280,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()){
@@ -1317,12 +1298,11 @@
gridElement.removeLongStopLossOrderId(orderId);
int gridId = gridElement.getId();
- // 同一网格的多个止损单触发不累加计数,视为同一批次
- if (gridId != lastLongStopLossGridId) {
- accumulatedLongLossCount++;
- lastLongStopLossGridId = gridId;
- }
- log.info("[Gate] 多仓止损触发 gridId:{}, 止损次数:{}, 开始追单", gridId, accumulatedLongLossCount);
+ boolean sameGrid = (gridId == lastLongStopLossGridId);
+ accumulatedLongLossCount++;
+ lastLongStopLossGridId = gridId;
+ log.info("[Gate] 多仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
+ gridId, accumulatedLongLossCount, sameGrid ? "(同网格)" : "");
int newEntryGridId = gridId + 1;
GridElement newEntryGrid = GridElement.findById(newEntryGridId);
@@ -1336,7 +1316,7 @@
BigDecimal triggerPrice = newEntryGrid.getGridPrice();
int posSize = Math.min(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue());
int maxPos = config.getMaxPositionSize();
- int targetAmount = accumulatedLongLossCount + 1;
+ int targetAmount = sameGrid ? Integer.parseInt(config.getQuantity()) : (accumulatedLongLossCount + 1) * Integer.parseInt(config.getQuantity());
int addSize;
if (maxPos > 0) {
int remainingRoom = maxPos - posSize;
@@ -1394,12 +1374,11 @@
gridElement.removeShortStopLossOrderId(orderId);
int gridId = gridElement.getId();
- // 同一网格的多个止损单触发不累加计数,视为同一批次
- if (gridId != lastShortStopLossGridId) {
- accumulatedShortLossCount++;
- lastShortStopLossGridId = gridId;
- }
- log.info("[Gate] 空仓止损触发 gridId:{}, 止损次数:{}, 开始追单", gridId, accumulatedShortLossCount);
+ boolean sameGrid = (gridId == lastShortStopLossGridId);
+ accumulatedShortLossCount++;
+ lastShortStopLossGridId = gridId;
+ log.info("[Gate] 空仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
+ gridId, accumulatedShortLossCount, sameGrid ? "(同网格)" : "");
int newEntryGridId = gridId - 1;
GridElement newEntryGrid = GridElement.findById(newEntryGridId);
@@ -1413,7 +1392,7 @@
BigDecimal triggerPrice = newEntryGrid.getGridPrice();
int posSize = Math.min(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue());
int maxPos = config.getMaxPositionSize();
- int targetAmount = accumulatedShortLossCount + 1;
+ int targetAmount = sameGrid ? Integer.parseInt(config.getQuantity()) : (accumulatedShortLossCount + 1) * Integer.parseInt(config.getQuantity());
int addSize;
if (maxPos > 0) {
int remainingRoom = maxPos - posSize;
@@ -1617,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 -> {});
}
@@ -1636,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 -> {});
}
@@ -1674,51 +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);
- log.info("[Gate] 多仓追挂止损, 成交{}张, gridId:{}, A({})x{} B({})x1 C({})x1",
- filledQty, gridId, gridId - 2, aCount, gridId - 3, gridId - 4);
+ int baseQty = Integer.parseInt(config.getBaseQuantity());
+ int gridCount = baseQty / qty;
+ if (gridCount <= 0 || filledQty < qty) {
+ return;
+ }
- // A 位置:挂 aCount 个独立止损单
- placeStopLossOrders(gridId - 2, aCount, qty, FuturesPriceTrigger.RuleEnum.NUMBER_2,
- ORDER_TYPE_CLOSE_LONG, true);
- // B 位置:挂 1 个
- placeStopLossOrders(gridId - 3, 1, qty, FuturesPriceTrigger.RuleEnum.NUMBER_2,
- ORDER_TYPE_CLOSE_LONG, true);
- // C 位置:挂 1 个
- placeStopLossOrders(gridId - 4, 1, qty, FuturesPriceTrigger.RuleEnum.NUMBER_2,
- ORDER_TYPE_CLOSE_LONG, true);
+ int totalOrders = filledQty / qty;
+ int[] orders = new int[gridCount];
+
+ 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--;
+ }
+ }
+ }
+
+ 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 个固定位置,从近到远分配合约。
- * 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 extendShortStopLoss(int filledQty, int gridId) {
int qty = Integer.parseInt(config.getQuantity());
- int aCount = Math.max(0, filledQty / qty - 2);
- log.info("[Gate] 空仓追挂止损, 成交{}张, gridId:{}, A({})x{} B({})x1 C({})x1",
- filledQty, gridId, gridId + 2, aCount, gridId + 3, gridId + 4);
+ int baseQty = Integer.parseInt(config.getBaseQuantity());
+ int gridCount = baseQty / qty;
+ if (gridCount <= 0 || filledQty < qty) {
+ return;
+ }
- // A 位置:挂 aCount 个独立止损单
- placeStopLossOrders(gridId + 2, aCount, qty, FuturesPriceTrigger.RuleEnum.NUMBER_1,
- ORDER_TYPE_CLOSE_SHORT, false);
- // B 位置:挂 1 个
- placeStopLossOrders(gridId + 3, 1, qty, FuturesPriceTrigger.RuleEnum.NUMBER_1,
- ORDER_TYPE_CLOSE_SHORT, false);
- // C 位置:挂 1 个
- placeStopLossOrders(gridId + 4, 1, qty, FuturesPriceTrigger.RuleEnum.NUMBER_1,
- ORDER_TYPE_CLOSE_SHORT, false);
+ int totalOrders = filledQty / qty;
+ int[] orders = new int[gridCount];
+
+ 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--;
+ }
+ }
+ }
+
+ 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