Administrator
7 days ago dfd143f7f90f697db1731cf2c653556593786bbf
feat(gateApi): 添加网格策略重启跨度阈值功能

- 在GateConfig中新增restartGridSpan配置项用于设置策略重启跨度阈值
- 实现checkLastTakeProfitAndRestart方法检查止盈触发后的跨度条件
- 支持多空双边持仓、仅多仓、仅空仓三种情况的跨度计算逻辑
- 达到跨度阈值时自动执行策略重启流程:取消条件单→平仓→延迟重启
- 在WebSocketClientManager中设置默认重启跨度为5
3 files modified
91 ■■■■■ changed files
src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java 9 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java 81 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java 1 ●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
@@ -101,6 +101,8 @@
    private final PnLPriceMode unrealizedPnlPriceMode;
    /** 最大持仓张数(单方向),0=不限制 */
    private final int maxPositionSize;
    /** 策略重启跨度阈值:多空两边止盈触发数量均达到此值后触发重启,0=禁用 */
    private final int restartGridSpan;
    /** 网格绝对步长(shortBaseEntryPrice × gridRate),运行时由队列生成逻辑设置 */
    private BigDecimal step;
    /** 网格元素列表,由队列初始化时同步填充,包含完整的多空仓挂单状态 */
@@ -131,6 +133,7 @@
        this.priceScale = builder.priceScale;
        this.unrealizedPnlPriceMode = builder.unrealizedPnlPriceMode;
        this.maxPositionSize = builder.maxPositionSize;
        this.restartGridSpan = builder.restartGridSpan;
    }
    // ==================== REST/WS 地址 ====================
@@ -216,6 +219,8 @@
    public PnLPriceMode getUnrealizedPnlPriceMode() { return unrealizedPnlPriceMode; }
    /** @return 最大持仓张数(单方向),0=不限制 */
    public int getMaxPositionSize() { return maxPositionSize; }
    /** @return 策略重启跨度阈值:多空两边止盈触发数均达到此值后触发重启,0=禁用 */
    public int getRestartGridSpan() { return restartGridSpan; }
    // ==================== 运行时参数 ====================
@@ -306,6 +311,8 @@
        private PnLPriceMode unrealizedPnlPriceMode = PnLPriceMode.LAST_PRICE;
        /** 最大持仓张数(单方向),默认 0=不限制 */
        private int maxPositionSize = 0;
        /** 策略重启跨度阈值:多空两边止盈触发数量均达到此值后触发重启,默认 0=禁用 */
        private int restartGridSpan = 0;
        /** 设置 API Key */
        public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; }
@@ -347,6 +354,8 @@
        public Builder unrealizedPnlPriceMode(PnLPriceMode mode) { this.unrealizedPnlPriceMode = mode; return this; }
        /** 设置最大持仓张数(单方向),0=不限制 */
        public Builder maxPositionSize(int maxPositionSize) { this.maxPositionSize = maxPositionSize; return this; }
        /** 设置策略重启跨度阈值:多空两边止盈触发数均达到此值后触发重启,0=禁用 */
        public Builder restartGridSpan(int restartGridSpan) { this.restartGridSpan = restartGridSpan; return this; }
        public GateConfig build() {
            return new GateConfig(this);
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -597,20 +597,22 @@
            return;
        }
        // [Gate-需求1] 多仓止盈触发:清空止盈状态 + 取消最远多仓止损
        // [Gate-需求1] 多仓止盈触发:清空止盈状态 + 取消最远多仓止损 + 检查是否最后一个止盈
        GridElement longTpElem = GridElement.findByLongTakeProfitOrderId(orderId);
        if (longTpElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
            longTakeProfitTraderIdParam(longTpElem, null, false);
            log.info("[Gate] 多仓止盈触发 gridId:{}, orderId:{}", longTpElem.getId(), orderId);
            cancelFarthestLongStopLoss();
            checkLastTakeProfitAndRestart();
            return;
        }
        // [Gate-需求1] 空仓止盈触发:清空止盈状态 + 取消最远空仓止损
        // [Gate-需求1] 空仓止盈触发:清空止盈状态 + 取消最远空仓止损 + 检查是否最后一个止盈
        GridElement shortTpElem = GridElement.findByShortTakeProfitOrderId(orderId);
        if (shortTpElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) {
            shortTakeProfitTraderIdParam(shortTpElem, null, false);
            log.info("[Gate] 空仓止盈触发 gridId:{}, orderId:{}", shortTpElem.getId(), orderId);
            cancelFarthestShortStopLoss();
            checkLastTakeProfitAndRestart();
            return;
        }
@@ -1257,6 +1259,81 @@
    // ========== 止盈/止损取消辅助方法 ==========
    /**
     * 止盈触发后检查跨度是否达至要求,满足条件则重启策略。
     *
     * <h3>跨度定义</h3>
     * {@code restartGridSpan} 表示多少倍的绝对步长 step(= 短基价 × gridRate)。
     *
     * <h3>判断逻辑</h3>
     * <ol>
     *   <li>多空双边均有持仓:longEntryPrice − shortEntryPrice > span × step</li>
     *   <li>仅持多仓:currentPrice − longEntryPrice > span × step</li>
     *   <li>仅持空仓:shortEntryPrice − currentPrice > span × step</li>
     * </ol>
     * restartGridSpan=0 时禁用此功能。重启复用仓位归零模式:取消全部条件单 → 平仓 → 延迟启动。
     */
    private void checkLastTakeProfitAndRestart() {
        int span = config.getRestartGridSpan();
        if (span <= 0) {
            return;
        }
        BigDecimal step = config.getStep();
        if (step == null || step.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        BigDecimal threshold = step.multiply(new BigDecimal(span));
        BigDecimal currentPrice = lastKlinePrice;
        if (currentPrice == null || currentPrice.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        boolean shouldRestart = false;
        String reason = "";
        if (longActive && shortActive) {
            // 多空双边持仓:多均价 − 空均价 > span × step
            BigDecimal gap = longEntryPrice.subtract(shortEntryPrice);
            if (gap.compareTo(threshold) > 0) {
                shouldRestart = true;
                reason = StrUtil.format("双边跨度 多均价:{} − 空均价:{} = {} > {} (span:{}×step:{})",
                        longEntryPrice, shortEntryPrice, gap, threshold, span, step);
            }
        } else if (longActive) {
            // 仅持多仓:当前价 − 多均价 > span × step
            BigDecimal gap = currentPrice.subtract(longEntryPrice);
            if (gap.compareTo(threshold) > 0) {
                shouldRestart = true;
                reason = StrUtil.format("多仓跨度 当前价:{} − 多均价:{} = {} > {} (span:{}×step:{})",
                        currentPrice, longEntryPrice, gap, threshold, span, step);
            }
        } else if (shortActive) {
            // 仅持空仓:空均价 − 当前价 > span × step
            BigDecimal gap = shortEntryPrice.subtract(currentPrice);
            if (gap.compareTo(threshold) > 0) {
                shouldRestart = true;
                reason = StrUtil.format("空仓跨度 空均价:{} − 当前价:{} = {} > {} (span:{}×step:{})",
                        shortEntryPrice, currentPrice, gap, threshold, span, step);
            }
        }
        if (shouldRestart) {
            log.info("[Gate] 跨度已达要求 → {},最后一个止盈触发策略重启", reason);
            try {
                futuresApi.cancelPriceTriggeredOrderList(SETTLE, config.getContract());
            } catch (ApiException ex) {
                log.warn("[Gate] 重启前清理条件单失败", ex);
            }
            closeExistingPositions();
            state = StrategyState.STOPPED;
            executor.submitTask(() -> {
                try { Thread.sleep(3000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); }
                startGrid();
            });
        }
    }
    /**
     * 取消最远的多仓止损订单。
     * 多仓止损在 gridId 负方向,最远 = id 最小。
     */
src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
@@ -69,6 +69,7 @@
                    .maxLoss(new BigDecimal("1.5"))
                    .baseQuantity("1")
                    .quantity("1")
                    .restartGridSpan(5)
                    .maxPositionSize(2)
                    .priceScale(2)
                    .contractMultiplier(new BigDecimal("0.01"))