From 240d90f2a3833ccaa98648870af7c12e906773f8 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 03 Aug 2026 17:03:35 +0800
Subject: [PATCH] 3.设定初始仓位为任务的最大仓位,仓位按百分比进行分配,当获利时依次按比例在条件(对手盘的止损订单)满足挂出盈利
---
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java | 333 ++++++++++++++++++++++++++++++++++++++++---------------
1 files changed, 240 insertions(+), 93 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..c7f9bb4 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -676,6 +676,10 @@
// placeExcessTakeProfit(posSize, false);
log.info("[Gate] 空单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize);
+
+
+ checkShortStopLongProfit(accumulatedShortLossCount, shortGridElement.getId() + 2);
+
}
}
GridElement longGridElement = GridElement.findByLongOrderId(orderId);
@@ -695,7 +699,6 @@
}
longGridElement.setExtendStopLossInProgress(true);
- accumulatedLongLossCount = 0;
lastLongStopLossGridId = Integer.MAX_VALUE;
// [Gate-需求2] 加仓后先撤多仓所有止盈+止损,再查交易所持仓后重挂
cancelAllLongTakeProfitsAndStopLosses();
@@ -705,6 +708,9 @@
// [Gate] 止盈挂单:超出基础仓位的部分,挂在空仓第一止损位
// placeExcessTakeProfit(posSize, true);
log.info("[Gate] 多单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize);
+
+
+ checkLongStopShortProfit(accumulatedLongLossCount, longGridElement.getId() -2);
}
}
@@ -1282,6 +1288,7 @@
}
lastLongStopLossGridId = gridId;
+ accumulatedLongLossCount++;
log.info("[Gate] 多仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
gridId, accumulatedLongLossCount, sameGrid ? "(同网格)" : "");
int newEntryGridId = gridId + 1;
@@ -1315,6 +1322,171 @@
}
+ // ========== 止损触发操作表 ==========
+ /**
+ * value = int[2]: {对手满仓止盈%, 基础仓位阈值%}
+ * <ul>
+ * <li>[0] 对手满仓:挂对手仓位此%做止盈;0=不挂</li>
+ * <li>[1] 基础仓位阈值(占maxPos的%):对手/己方仓位超出此阈值部分做止盈;0=不挂</li>
+ * </ul>
+ */
+ private static final Map<Integer, int[]> STOP_LOSS_RULES = new LinkedHashMap<>();
+
+ static {
+ // times {满仓%, 阈值%}
+ put(1, new int[]{0, 0});
+ put(2, new int[]{0, 0});
+ put(3, new int[]{30, 0});
+ put(4, new int[]{0, 0});
+ put(5, new int[]{0, 0});
+ put(6, new int[]{40, 40});
+ put(7, new int[]{0, 0});
+ put(8, new int[]{0, 0});
+ put(9, new int[]{50, 50});
+ put(10, new int[]{0, 0});
+ put(11, new int[]{0, 0});
+ put(12, new int[]{55, 60});
+ put(13, new int[]{0, 0});
+ put(14, new int[]{0, 0});
+ put(15, new int[]{60, 60});
+ put(16, new int[]{0, 0});
+ put(17, new int[]{0, 0});
+ put(18, new int[]{65, 65});
+ put(19, new int[]{0, 0});
+ put(20, new int[]{0, 0});
+ put(21, new int[]{70, 70});
+ put(22, new int[]{0, 0});
+ put(23, new int[]{0, 0});
+ put(24, new int[]{75, 75});
+ put(25, new int[]{0, 0});
+ put(26, new int[]{0, 0});
+ put(27, new int[]{80, 80});
+ put(28, new int[]{0, 0});
+ put(29, new int[]{0, 0});
+ put(30, new int[]{85, 85});
+ put(31, new int[]{0, 0});
+ put(32, new int[]{0, 0});
+ }
+
+ private static void put(int times, int[] rule) { STOP_LOSS_RULES.put(times, rule); }
+
+ private static int[] ruleOf(int times) {
+ int[] r = STOP_LOSS_RULES.get(times);
+ return r != null ? r : STOP_LOSS_RULES.get(32);
+ }
+
+ /**
+ * 多仓止损触发后,查表处理对手盘(空仓)盈止 + 己方盈止 + 激活。
+ */
+ private void checkLongStopShortProfit(int times, int gridId) {
+ int[] r = ruleOf(times);
+ int maxPos = config.getMaxPositionSize();
+ if (maxPos <= 0) {
+ return;
+ }
+
+ int fullTpPct = r[0]; // 对手满仓 → 止盈%
+ int fullTpPctNum = maxPos * (100- fullTpPct)/ 100;
+ int thresholdPct = r[1]; // 基础仓位阈值%
+ int thresholdPosNum = maxPos * (100- thresholdPct)/ 100;
+
+ // ---------- 对手盘(空仓)盈止 ----------
+ int oppPos = Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue());
+ boolean isFullTp = oppPos > fullTpPctNum;
+ if (isFullTp) {
+ // 对手仓位超出阈值:超额整个挂一笔止盈,位置在触发格 - 1
+ int excess = oppPos - fullTpPctNum;
+ GridElement tpElem = GridElement.findById(gridId);
+ if (tpElem != null) {
+ placeTakeProfitAtGrid(tpElem, false, excess, times);
+ }
+ }
+
+ // ---------- 己方(多仓)盈止(≥6次) ----------
+ if (times >= 6 && thresholdPct > 0) {
+ int selfPos = Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue());
+ int excess = selfPos - thresholdPosNum;
+ if (excess > 0) {
+ int perOrderQty = maxPos * 5 / 100;
+ if (perOrderQty <= 0) {
+ perOrderQty = 1;
+ }
+ int totalOrders = excess / perOrderQty;
+ if (totalOrders <= 0) {
+ totalOrders = 1;
+ }
+ int entryGridId = 0; // 多仓建仓格
+ for (int i = 0; i < totalOrders; i++) {
+ int tpGridId = entryGridId + 2 * (i + 1); // 朝盈利方向(向上)间隔2格
+ GridElement tpElem = GridElement.findById(tpGridId);
+ if (tpElem == null) {
+ break;
+ }
+ placeTakeProfitAtGrid(tpElem, true, perOrderQty, times);
+ }
+ log.info("[Gate] 止损{}→己方多仓止盈, excess:{}, 挂{}单, 每单{}张",
+ times, excess, totalOrders, perOrderQty);
+ }
+ }
+
+ }
+
+ /**
+ * 空仓止损触发后,查表处理对手盘(多仓)盈止 + 己方盈止。
+ */
+ private void checkShortStopLongProfit(int times, int gridId) {
+ int[] r = ruleOf(times);
+ int maxPos = config.getMaxPositionSize();
+ if (maxPos <= 0) {
+ return;
+ }
+
+ int fullTpPct = r[0]; // 对手满仓 → 止盈%
+ int fullTpPctNum = maxPos * (100 - fullTpPct) / 100;
+ int thresholdPct = r[1]; // 基础仓位阈值%
+ int thresholdPosNum = maxPos * (100 - thresholdPct) / 100;
+
+ // ---------- 对手盘(多仓)盈止 ----------
+ int oppPos = Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue());
+ boolean isFullTp = oppPos > fullTpPctNum;
+ if (isFullTp) {
+ // 对手仓位超出阈值:超额整个挂一笔止盈,位置在触发格
+ int excess = oppPos - fullTpPctNum;
+ GridElement tpElem = GridElement.findById(gridId);
+ if (tpElem != null) {
+ placeTakeProfitAtGrid(tpElem, true, excess, times);
+ }
+ }
+
+ // ---------- 己方(空仓)盈止(≥6次) ----------
+ if (times >= 6 && thresholdPct > 0) {
+ int selfPos = Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue());
+ int excess = selfPos - thresholdPosNum;
+ if (excess > 0) {
+ int perOrderQty = maxPos * 5 / 100;
+ if (perOrderQty <= 0) {
+ perOrderQty = 1;
+ }
+ int totalOrders = excess / perOrderQty;
+ if (totalOrders <= 0) {
+ totalOrders = 1;
+ }
+ int entryGridId = 0; // 空仓建仓格
+ for (int i = 0; i < totalOrders; i++) {
+ int tpGridId = entryGridId - 2 * (i + 1); // 朝盈利方向(向下)间隔2格
+ GridElement tpElem = GridElement.findById(tpGridId);
+ if (tpElem == null) {
+ break;
+ }
+ placeTakeProfitAtGrid(tpElem, false, perOrderQty, times);
+ }
+ log.info("[Gate] 止损{}→己方空仓止盈, excess:{}, 挂{}单, 每单{}张",
+ times, excess, totalOrders, perOrderQty);
+ }
+ }
+
+ }
+
private void handleShortStopLossTriggered(GridElement gridElement, String orderId) {
gridElement.removeShortStopLossOrderId(orderId);
@@ -1325,6 +1497,7 @@
return;
}
lastShortStopLossGridId = gridId;
+ accumulatedShortLossCount++;
log.info("[Gate] 空仓止损触发 gridId:{}, 止损次数:{}{}, 开始追单",
gridId, accumulatedShortLossCount, sameGrid ? "(同网格)" : "");
int newEntryGridId = gridId - 1;
@@ -1690,98 +1863,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 +2077,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