Administrator
2026-09-20 816bef9a27736fabeae4c3549565fe3e14964692
feat(gate): 添加自定义止损功能

- 在前端界面添加自定义止损开关及多空仓止损触发价输入框
- 扩展 GateConfig 类增加自定义止损相关字段和构建器方法
- 更新 GateConfigDTO 添加自定义止损参数的数据传输对象
- 实现自定义止损挂单逻辑,支持按触发价匹配最近网格挂单
- 添加自定义止损与默认阶梯止损的切换机制
- 实现自定义止损首次触发后的策略调整和订单管理
- 完善配置持久化服务支持新增的自定义止损参数
5 files modified
279 ■■■■■ changed files
src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java 27 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateConfigDTO.java 15 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateConfigPersistenceService.java 3 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java 216 ●●●●● patch | view | raw | blame | history
src/main/resources/static/gate-config.html 18 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
@@ -130,6 +130,12 @@
    /** 止盈挂单模式:off=关闭 / concentrated=集中止盈 / dispersed=分散止盈,默认 off */
    private final String placeExcessTakeProfit;
    /** 自定义止损开关:true=启用自定义止损触发价(多空各挂一单),false=使用默认阶梯止损。默认 false */
    private final boolean customStopLossEnabled;
    /** 多仓自定义止损触发价(价格跌至该值触发平多),null/0=未设置 */
    private final BigDecimal longCustomStopLossPrice;
    /** 空仓自定义止损触发价(价格涨至该值触发平空),null/0=未设置 */
    private final BigDecimal shortCustomStopLossPrice;
    /** 网格绝对步长(shortBaseEntryPrice × gridRate),运行时由队列生成逻辑设置 */
    private BigDecimal step;
    /** 网格元素列表,由队列初始化时同步填充,包含完整的多空仓挂单状态 */
@@ -171,6 +177,9 @@
        this.maxPositionPerSide = builder.maxPositionPerSide;
        this.addPositionStartThreshold = builder.addPositionStartThreshold;
        this.placeExcessTakeProfit = builder.placeExcessTakeProfit;
        this.customStopLossEnabled = builder.customStopLossEnabled;
        this.longCustomStopLossPrice = builder.longCustomStopLossPrice;
        this.shortCustomStopLossPrice = builder.shortCustomStopLossPrice;
    }
    // ==================== REST/WS 地址 ====================
@@ -278,6 +287,12 @@
    public int getAddPositionStartThreshold() { return addPositionStartThreshold; }
    /** @return 止盈挂单模式:off=关闭 / concentrated=集中止盈 / dispersed=分散止盈 */
    public String getPlaceExcessTakeProfit() { return placeExcessTakeProfit; }
    /** @return 自定义止损开关:true=启用自定义止损触发价,false=使用默认阶梯止损 */
    public boolean isCustomStopLossEnabled() { return customStopLossEnabled; }
    /** @return 多仓自定义止损触发价,null/0=未设置 */
    public BigDecimal getLongCustomStopLossPrice() { return longCustomStopLossPrice; }
    /** @return 空仓自定义止损触发价,null/0=未设置 */
    public BigDecimal getShortCustomStopLossPrice() { return shortCustomStopLossPrice; }
    // ==================== 运行时参数 ====================
@@ -390,6 +405,12 @@
        private int addPositionStartThreshold = 1;
        /** 止盈挂单模式:off=关闭 / concentrated=集中止盈 / dispersed=分散止盈,默认 off */
        private String placeExcessTakeProfit = EXCESS_TP_OFF;
        /** 自定义止损开关:true=启用自定义止损触发价,false=使用默认阶梯止损。默认 false */
        private boolean customStopLossEnabled = false;
        /** 多仓自定义止损触发价,null=未设置 */
        private BigDecimal longCustomStopLossPrice;
        /** 空仓自定义止损触发价,null=未设置 */
        private BigDecimal shortCustomStopLossPrice;
        /** 设置 API Key */
        public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; }
@@ -453,6 +474,12 @@
        public Builder addPositionStartThreshold(int addPositionStartThreshold) { this.addPositionStartThreshold = addPositionStartThreshold; return this; }
        /** 设置止盈挂单模式:off / concentrated / dispersed */
        public Builder placeExcessTakeProfit(String placeExcessTakeProfit) { this.placeExcessTakeProfit = placeExcessTakeProfit; return this; }
        /** 设置自定义止损开关:true=启用自定义止损触发价 */
        public Builder customStopLossEnabled(boolean customStopLossEnabled) { this.customStopLossEnabled = customStopLossEnabled; return this; }
        /** 设置多仓自定义止损触发价 */
        public Builder longCustomStopLossPrice(BigDecimal longCustomStopLossPrice) { this.longCustomStopLossPrice = longCustomStopLossPrice; return this; }
        /** 设置空仓自定义止损触发价 */
        public Builder shortCustomStopLossPrice(BigDecimal shortCustomStopLossPrice) { this.shortCustomStopLossPrice = shortCustomStopLossPrice; return this; }
        public GateConfig build() {
            return new GateConfig(this);
src/main/java/com/xcong/excoin/modules/gateApi/GateConfigDTO.java
@@ -71,6 +71,12 @@
    private int addPositionStartThreshold;
    /** 止盈挂单模式:off=关闭 / concentrated=集中止盈 / dispersed=分散止盈,默认 off */
    private String placeExcessTakeProfit;
    /** 自定义止损开关:true=启用自定义止损触发价,false=使用默认阶梯止损。null=未设置(默认false) */
    private Boolean customStopLossEnabled;
    /** 多仓自定义止损触发价(价格跌至该值触发平多),null=未设置 */
    private BigDecimal longCustomStopLossPrice;
    /** 空仓自定义止损触发价(价格涨至该值触发平空),null=未设置 */
    private BigDecimal shortCustomStopLossPrice;
    /**
     * 从 GateConfig 构建 DTO(不暴露 apiSecret)。
@@ -104,6 +110,9 @@
                .maxPositionPerSide(config.getMaxPositionPerSide())
                .addPositionStartThreshold(config.getAddPositionStartThreshold())
                .placeExcessTakeProfit(config.getPlaceExcessTakeProfit())
                .customStopLossEnabled(config.isCustomStopLossEnabled())
                .longCustomStopLossPrice(config.getLongCustomStopLossPrice())
                .shortCustomStopLossPrice(config.getShortCustomStopLossPrice())
                .build();
    }
@@ -131,6 +140,9 @@
        m.put("maxPositionPerSide", maxPositionPerSide);
        m.put("addPositionStartThreshold", addPositionStartThreshold);
        m.put("placeExcessTakeProfit", placeExcessTakeProfit);
        m.put("customStopLossEnabled", customStopLossEnabled);
        m.put("longCustomStopLossPrice", longCustomStopLossPrice);
        m.put("shortCustomStopLossPrice", shortCustomStopLossPrice);
        return m;
    }
@@ -165,6 +177,9 @@
                .maxPositionPerSide(0)
                .addPositionStartThreshold(1)
                .placeExcessTakeProfit("off")
                .customStopLossEnabled(false)
                .longCustomStopLossPrice(null)
                .shortCustomStopLossPrice(null)
                .build();
    }
}
src/main/java/com/xcong/excoin/modules/gateApi/GateConfigPersistenceService.java
@@ -112,6 +112,9 @@
                .maxPositionPerSide(dto.getMaxPositionPerSide())
                .addPositionStartThreshold(dto.getAddPositionStartThreshold() >= 0 ? dto.getAddPositionStartThreshold() : 1)
                .placeExcessTakeProfit(normalizeTakeProfitMode(dto.getPlaceExcessTakeProfit()))
                .customStopLossEnabled(nvl(dto.getCustomStopLossEnabled(), false))
                .longCustomStopLossPrice(dto.getLongCustomStopLossPrice())
                .shortCustomStopLossPrice(dto.getShortCustomStopLossPrice())
                .build();
    }
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -15,6 +15,7 @@
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import com.xcong.excoin.modules.gateApi.wsHandler.handler.CandlestickChannelHandler;
@@ -148,6 +149,8 @@
    private volatile int lastLongStopLossGridId = Integer.MAX_VALUE;
    /** 最近触发止损的空头网格ID */
    private volatile int lastShortStopLossGridId = Integer.MAX_VALUE;
    /** 自定义止损模式激活标记:true=尚未发生第一次止损触发,第一次触发后置 false(触发未触发侧重挂默认) */
    private final AtomicBoolean customStopLossModeActive = new AtomicBoolean(false);
    private volatile BigDecimal lastKlinePrice;
    private volatile BigDecimal markPrice = BigDecimal.ZERO;
@@ -362,6 +365,7 @@
        accumulatedShortLossCount = 0;
        lastLongStopLossGridId = Integer.MAX_VALUE;
        lastShortStopLossGridId = Integer.MAX_VALUE;
        customStopLossModeActive.set(false);
        shortPriceQueue.clear();
        longPriceQueue.clear();
        totalShortPriceQueue.clear();
@@ -974,56 +978,182 @@
//                );
//            }
            int shortTime = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1;
            for (int id = 2; id <= shortTime; id++) {
                GridElement elem = GridElement.findById(id);
                if (elem == null) {
                    continue;
                }
                BigDecimal triggerPrice = elem.getGridPrice();
                String size = config.getQuantity();
                int finalId = id;
                executor.placeTakeProfit(
                        triggerPrice,
                        FuturesPriceTrigger.RuleEnum.NUMBER_1,
                        ORDER_TYPE_CLOSE_SHORT,
                        size,
                        profitId -> {
                            elem.addShortStopLossOrderId(profitId);
                            GridElement.refreshIndices();
                            log.info("[Gate] 空仓止损已挂, gridId:{}, 触发价:{}, stopLossId:{}", finalId, triggerPrice, profitId);
                        }
                );
            if (config.isCustomStopLossEnabled()) {
                placeCustomStopLosses();
            } else {
                placeDefaultStopLossLadders();
            }
            state = StrategyState.ACTIVE;
        }
    }
    // ========== 自定义止损(按触发价各挂一单) ==========
            int longTime = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1;
            for (int id = -2; id >= -longTime; id--) {
                GridElement elem = GridElement.findById(id);
                if (elem == null) {
                    continue;
                }
                BigDecimal triggerPrice = elem.getGridPrice();
                String size = config.getQuantity();
                int finalId = id;
    /**
     * 自定义止损初始化:按多空止损触发价匹配最近网格,各挂一张覆盖全仓位(baseQuantity)的止损单。
     * 多仓止损:NUMBER_2(价格 ≤ 触发价平多),空仓止损:NUMBER_1(价格 ≥ 触发价平空)。
     */
    private void placeCustomStopLosses() {
        customStopLossModeActive.set(true);
        String baseQty = config.getBaseQuantity();
        BigDecimal longPrice = config.getLongCustomStopLossPrice();
        BigDecimal shortPrice = config.getShortCustomStopLossPrice();
        if (longPrice != null && longPrice.compareTo(BigDecimal.ZERO) > 0) {
            GridElement longElem = findNearestGridElementByPrice(longPrice);
            if (longElem != null) {
                BigDecimal triggerPrice = longElem.getGridPrice();
                executor.placeTakeProfit(
                        triggerPrice,
                        FuturesPriceTrigger.RuleEnum.NUMBER_2,
                        ORDER_TYPE_CLOSE_LONG,
                        negate(size),
                        negate(baseQty),
                        profitId -> {
                            elem.addLongStopLossOrderId(profitId);
                            longElem.addLongStopLossOrderId(profitId);
                            GridElement.refreshIndices();
                            log.info("[Gate] 多仓止损已挂, gridId:{}, 触发价:{}, stopLossId:{}", finalId, triggerPrice, profitId);
                            log.info("[Gate] 自定义多仓止损已挂, 目标价:{}, 匹配gridId:{}, 触发价:{}, stopLossId:{}",
                                    longPrice, longElem.getId(), triggerPrice, profitId);
                        }
                );
            } else {
                log.warn("[Gate] 自定义多仓止损价:{} 未匹配到任何网格", longPrice);
            }
            log.info("[Gate] 止损止盈单已全部挂完, 空仓止损:2~{}, 多仓止损:-2~-{}", shortTime, longTime);
            state = StrategyState.ACTIVE;
        }
        if (shortPrice != null && shortPrice.compareTo(BigDecimal.ZERO) > 0) {
            GridElement shortElem = findNearestGridElementByPrice(shortPrice);
            if (shortElem != null) {
                BigDecimal triggerPrice = shortElem.getGridPrice();
                executor.placeTakeProfit(
                        triggerPrice,
                        FuturesPriceTrigger.RuleEnum.NUMBER_1,
                        ORDER_TYPE_CLOSE_SHORT,
                        baseQty,
                        profitId -> {
                            shortElem.addShortStopLossOrderId(profitId);
                            GridElement.refreshIndices();
                            log.info("[Gate] 自定义空仓止损已挂, 目标价:{}, 匹配gridId:{}, 触发价:{}, stopLossId:{}",
                                    shortPrice, shortElem.getId(), triggerPrice, profitId);
                        }
                );
            } else {
                log.warn("[Gate] 自定义空仓止损价:{} 未匹配到任何网格", shortPrice);
            }
        }
        log.info("[Gate] 自定义止损初始化完成, 多仓止损价:{}, 空仓止损价:{}", longPrice, shortPrice);
    }
    /**
     * 默认止损阶梯(原有逻辑):空仓从 ID=2 向上、多仓从 ID=-2 向下,各挂 baseQuantity/quantity 格、每格 quantity 张。
     */
    private void placeDefaultStopLossLadders() {
        placeDefaultShortStopLossLadder();
        placeDefaultLongStopLossLadder();
        int shortTime = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1;
        int longTime = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1;
        log.info("[Gate] 止损止盈单已全部挂完, 空仓止损:2~{}, 多仓止损:-2~-{}", shortTime, longTime);
    }
    /**
     * 默认空仓止损阶梯:从 ID=2 向上挂,每格 quantity 张,NUMBER_1(价格 ≥ 触发价平空)。
     */
    private void placeDefaultShortStopLossLadder() {
        int shortTime = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1;
        for (int id = 2; id <= shortTime; id++) {
            GridElement elem = GridElement.findById(id);
            if (elem == null) {
                continue;
            }
            BigDecimal triggerPrice = elem.getGridPrice();
            String size = config.getQuantity();
            int finalId = id;
            executor.placeTakeProfit(
                    triggerPrice,
                    FuturesPriceTrigger.RuleEnum.NUMBER_1,
                    ORDER_TYPE_CLOSE_SHORT,
                    size,
                    profitId -> {
                        elem.addShortStopLossOrderId(profitId);
                        GridElement.refreshIndices();
                        log.info("[Gate] 空仓止损已挂, gridId:{}, 触发价:{}, stopLossId:{}", finalId, triggerPrice, profitId);
                    }
            );
        }
    }
    /**
     * 默认多仓止损阶梯:从 ID=-2 向下挂,每格 quantity 张,NUMBER_2(价格 ≤ 触发价平多)。
     */
    private void placeDefaultLongStopLossLadder() {
        int longTime = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1;
        for (int id = -2; id >= -longTime; id--) {
            GridElement elem = GridElement.findById(id);
            if (elem == null) {
                continue;
            }
            BigDecimal triggerPrice = elem.getGridPrice();
            String size = config.getQuantity();
            int finalId = id;
            executor.placeTakeProfit(
                    triggerPrice,
                    FuturesPriceTrigger.RuleEnum.NUMBER_2,
                    ORDER_TYPE_CLOSE_LONG,
                    negate(size),
                    profitId -> {
                        elem.addLongStopLossOrderId(profitId);
                        GridElement.refreshIndices();
                        log.info("[Gate] 多仓止损已挂, gridId:{}, 触发价:{}, stopLossId:{}", finalId, triggerPrice, profitId);
                    }
            );
        }
    }
    /**
     * 按「价格 → 最近网格」匹配:返回 gridPrice 与目标价绝对值差最小的网格元素。
     */
    private GridElement findNearestGridElementByPrice(BigDecimal price) {
        if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }
        GridElement nearest = null;
        BigDecimal minDiff = null;
        for (GridElement e : config.getGridElements()) {
            BigDecimal diff = e.getGridPrice().subtract(price).abs();
            if (minDiff == null || diff.compareTo(minDiff) < 0) {
                minDiff = diff;
                nearest = e;
            }
        }
        return nearest;
    }
    /**
     * 只取消空仓止损单(保留空仓止盈),用于自定义止损首次触发时重挂未触发侧。
     */
    private void cancelAllShortStopLossesOnly() {
        for (GridElement e : config.getGridElements()) {
            for (String slId : new ArrayList<>(e.getShortStopLossOrderIds())) {
                executor.cancelConditionalOrder(slId, oid -> {});
            }
            e.clearShortStopLossOrderIds();
        }
        GridElement.refreshIndices();
        log.info("[Gate] 已提交取消所有空仓止损(保留止盈)");
    }
    /**
     * 只取消多仓止损单(保留多仓止盈),用于自定义止损首次触发时重挂未触发侧。
     */
    private void cancelAllLongStopLossesOnly() {
        for (GridElement e : config.getGridElements()) {
            for (String slId : new ArrayList<>(e.getLongStopLossOrderIds())) {
                executor.cancelConditionalOrder(slId, oid -> {});
            }
            e.clearLongStopLossOrderIds();
        }
        GridElement.refreshIndices();
        log.info("[Gate] 已提交取消所有多仓止损(保留止盈)");
    }
    /**
@@ -1523,6 +1653,13 @@
            }
        }
        // 自定义止损模式:第一次止损触发时,取消未触发侧(空仓)自定义止损单并重挂默认阶梯
        if (config.isCustomStopLossEnabled() && customStopLossModeActive.compareAndSet(true, false)) {
            cancelAllShortStopLossesOnly();
            placeDefaultShortStopLossLadder();
            log.info("[Gate] 自定义止损首次触发(多仓), 已取消空仓自定义止损并重挂默认阶梯");
        }
    }
    private void handleShortStopLossTriggered(GridElement gridElement, String orderId) {
@@ -1574,6 +1711,13 @@
                });
            }
        }
        // 自定义止损模式:第一次止损触发时,取消未触发侧(多仓)自定义止损单并重挂默认阶梯
        if (config.isCustomStopLossEnabled() && customStopLossModeActive.compareAndSet(true, false)) {
            cancelAllLongStopLossesOnly();
            placeDefaultLongStopLossLadder();
            log.info("[Gate] 自定义止损首次触发(空仓), 已取消多仓自定义止损并重挂默认阶梯");
        }
    }
    // ========== 止盈/止损取消辅助方法 ==========
src/main/resources/static/gate-config.html
@@ -133,6 +133,13 @@
            <div class="form-group"><label>单边最大仓位量(张)</label><input id="maxPositionPerSide" type="number" placeholder="0(不限制)"></div>
            <div class="form-group"><label>加仓启动阈值(次)</label><input id="addPositionStartThreshold" type="number" placeholder="1(前N次止损不加仓)"></div>
            <div class="form-group"><label>止盈挂单</label><select id="placeExcessTakeProfit"><option value="off" selected>关闭</option><option value="concentrated">集中止盈</option><option value="dispersed">分散止盈</option></select></div>
            <!-- ===== 自定义止损配置 ===== -->
            <div class="form-group full" style="margin-top:6px;border-top:1px solid var(--border);padding-top:8px">
                <label style="font-size:13px;font-weight:600;color:var(--text)">自定义止损(开启后按触发价各挂一单,忽略默认阶梯)</label>
            </div>
            <div class="form-group"><label>自定义止损开关</label><select id="customStopLossEnabled"><option value="false" selected>关闭</option><option value="true">开启</option></select></div>
            <div class="form-group"><label>多仓止损触发价</label><input id="longCustomStopLossPrice" placeholder="如 2540(价格跌至触发平多)"></div>
            <div class="form-group"><label>空仓止损触发价</label><input id="shortCustomStopLossPrice" placeholder="如 2650(价格涨至触发平空)"></div>
        </form>
    </div>
@@ -209,7 +216,8 @@
        // 文件不存在 → 用默认值填充,用户可编辑后保存
        fillForm({ gridRate:0.005, expectedProfit:0.15, maxLoss:1.5,
            baseQuantity:'2', quantity:'2', maxPositionSize:4, stopLossCount:0, takeProfitGridSpan:2, priceDriveEnabled: true, rounds: 0,
            stopLossCountMode:'dual', addPositionInterval:3, addPositionQuantity:1, maxPositionPerSide:0, addPositionStartThreshold:1, placeExcessTakeProfit: 'off' });
            stopLossCountMode:'dual', addPositionInterval:3, addPositionQuantity:1, maxPositionPerSide:0, addPositionStartThreshold:1, placeExcessTakeProfit: 'off',
            customStopLossEnabled: false, longCustomStopLossPrice: null, shortCustomStopLossPrice: null });
        toast('未找到配置,已加载默认值,编辑后请保存', 'success');
    }
    currentApiKey = key;
@@ -235,6 +243,9 @@
    byId('maxPositionPerSide').value = d.maxPositionPerSide ?? 0;
    byId('addPositionStartThreshold').value = d.addPositionStartThreshold ?? 1;
    byId('placeExcessTakeProfit').value = normalizeTpMode(d.placeExcessTakeProfit);
    byId('customStopLossEnabled').value = (d.customStopLossEnabled === true || d.customStopLossEnabled === 'true') ? 'true' : 'false';
    byId('longCustomStopLossPrice').value = d.longCustomStopLossPrice || '';
    byId('shortCustomStopLossPrice').value = d.shortCustomStopLossPrice || '';
}
function collectForm() {
@@ -255,7 +266,10 @@
        addPositionQuantity: intVal(byId('addPositionQuantity').value, 1),
        maxPositionPerSide: intVal(byId('maxPositionPerSide').value, 0),
        addPositionStartThreshold: intVal(byId('addPositionStartThreshold').value, 1),
        placeExcessTakeProfit: byId('placeExcessTakeProfit').value
        placeExcessTakeProfit: byId('placeExcessTakeProfit').value,
        customStopLossEnabled: byId('customStopLossEnabled').value === 'true',
        longCustomStopLossPrice: parseFloat(byId('longCustomStopLossPrice').value) || null,
        shortCustomStopLossPrice: parseFloat(byId('shortCustomStopLossPrice').value) || null
    };
}
function intVal(str, fallback) {