Administrator
2026-08-12 e129a02db0b655d97806ddb3c55297ede56e6a6f
feat(gate): 添加超额止盈功能配置选项

- 在前端配置界面增加超额止盈开关选择器
- 在后端配置类中添加 placeExcessTakeProfit 属性及相关构建器方法
- 实现超额止盈功能的条件判断逻辑
- 新增 placeExcessTakeProfit 方法处理超出基础仓位的止盈挂单
- 更新配置持久化服务以支持新功能开关
- 添加详细的超额止盈功能实现注释说明
5 files modified
88 ■■■■■ 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/GateConfigDTO.java 3 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateConfigPersistenceService.java 1 ●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java 68 ●●●●● patch | view | raw | blame | history
src/main/resources/static/gate-config.html 7 ●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
@@ -121,6 +121,8 @@
    private final int maxPositionPerSide;
    /** 加仓启动阈值:前N次止损不触发加仓,默认 1(第1次止损不加仓,第2次起按公式计算) */
    private final int addPositionStartThreshold;
    /** 超额止盈开关:true=挂单成交后将超出基础仓位的部分挂止盈单(挂在对手第一止损位),默认 false */
    private final boolean placeExcessTakeProfit;
    /** 网格绝对步长(shortBaseEntryPrice × gridRate),运行时由队列生成逻辑设置 */
    private BigDecimal step;
    /** 网格元素列表,由队列初始化时同步填充,包含完整的多空仓挂单状态 */
@@ -161,6 +163,7 @@
        this.addPositionQuantity = builder.addPositionQuantity;
        this.maxPositionPerSide = builder.maxPositionPerSide;
        this.addPositionStartThreshold = builder.addPositionStartThreshold;
        this.placeExcessTakeProfit = builder.placeExcessTakeProfit;
    }
    // ==================== REST/WS 地址 ====================
@@ -266,6 +269,8 @@
    public int getMaxPositionPerSide() { return maxPositionPerSide; }
    /** @return 加仓启动阈值:前N次止损不触发加仓 */
    public int getAddPositionStartThreshold() { return addPositionStartThreshold; }
    /** @return 超额止盈开关:true=挂单成交后将超出基础仓位的部分挂止盈单 */
    public boolean isPlaceExcessTakeProfit() { return placeExcessTakeProfit; }
    // ==================== 运行时参数 ====================
@@ -376,6 +381,8 @@
        private int maxPositionPerSide = 0;
        /** 加仓启动阈值:前N次止损不触发加仓,调整后的 effectiveCount = max(0, count - threshold)。默认 1 */
        private int addPositionStartThreshold = 1;
        /** 超额止盈开关:true=挂单成交后将超出基础仓位的部分挂止盈单,默认 false */
        private boolean placeExcessTakeProfit = false;
        /** 设置 API Key */
        public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; }
@@ -437,6 +444,8 @@
        public Builder maxPositionPerSide(int maxPositionPerSide) { this.maxPositionPerSide = maxPositionPerSide; return this; }
        /** 设置加仓启动阈值:前N次止损不触发加仓,0=立即启动 */
        public Builder addPositionStartThreshold(int addPositionStartThreshold) { this.addPositionStartThreshold = addPositionStartThreshold; return this; }
        /** 设置超额止盈开关:true=挂单成交后将超出基础仓位的部分挂止盈单 */
        public Builder placeExcessTakeProfit(boolean placeExcessTakeProfit) { this.placeExcessTakeProfit = placeExcessTakeProfit; return this; }
        public GateConfig build() {
            return new GateConfig(this);
src/main/java/com/xcong/excoin/modules/gateApi/GateConfigDTO.java
@@ -67,6 +67,8 @@
    private int maxPositionPerSide;
    /** 加仓启动阈值:前N次止损不触发加仓,默认 1 */
    private int addPositionStartThreshold;
    /** 超额止盈开关:true=挂单成交后将超出基础仓位的部分挂止盈单,默认 false */
    private boolean placeExcessTakeProfit;
    /**
     * 从 GateConfig 构建 DTO(不暴露 apiSecret)。
@@ -99,6 +101,7 @@
                .addPositionQuantity(config.getAddPositionQuantity())
                .maxPositionPerSide(config.getMaxPositionPerSide())
                .addPositionStartThreshold(config.getAddPositionStartThreshold())
                .placeExcessTakeProfit(config.isPlaceExcessTakeProfit())
                .build();
    }
}
src/main/java/com/xcong/excoin/modules/gateApi/GateConfigPersistenceService.java
@@ -111,6 +111,7 @@
                .addPositionQuantity(dto.getAddPositionQuantity() > 0 ? dto.getAddPositionQuantity() : 1)
                .maxPositionPerSide(dto.getMaxPositionPerSide())
                .addPositionStartThreshold(dto.getAddPositionStartThreshold() >= 0 ? dto.getAddPositionStartThreshold() : 1)
                .placeExcessTakeProfit(dto.isPlaceExcessTakeProfit())
                .build();
    }
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -672,7 +672,9 @@
                int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue());
                extendShortStopLoss(posSize, shortGridElement.getId());
                // [Gate] 止盈挂单:超出基础仓位的部分,挂在多仓第一止损位
//                placeExcessTakeProfit(posSize, false);
                if (config.isPlaceExcessTakeProfit()) {
                    placeExcessTakeProfit(posSize, false);
                }
                log.info("[Gate] 空单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize);
@@ -703,7 +705,9 @@
                int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue());
                extendLongStopLoss(posSize, longGridElement.getId());
                // [Gate] 止盈挂单:超出基础仓位的部分,挂在空仓第一止损位
//                placeExcessTakeProfit(posSize, true);
                if (config.isPlaceExcessTakeProfit()) {
                    placeExcessTakeProfit(posSize, true);
                }
                log.info("[Gate] 多单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize);
            }
@@ -1986,6 +1990,66 @@
    }
    /**
     * 挂单成交后,将超出基础仓位的部分挂止盈单,挂在对向仓位的第一止损位上。
     *
     * <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);
                }
        );
    }
    /**
     * 在指定网格挂一笔对手止盈单(非满仓超额止盈,挂在止损触发位的下一格)。
     */
    private void placeTakeProfitAtGrid(GridElement tpElem, boolean isLong, int qty, int times) {
src/main/resources/static/gate-config.html
@@ -132,6 +132,7 @@
            <div class="form-group"><label>加仓数量(张)</label><input id="addPositionQuantity" type="number" placeholder="1"></div>
            <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="false" selected>关闭</option><option value="true">开启</option></select></div>
        </form>
    </div>
@@ -208,7 +209,7 @@
        // 文件不存在 → 用默认值填充,用户可编辑后保存
        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 });
            stopLossCountMode:'dual', addPositionInterval:3, addPositionQuantity:1, maxPositionPerSide:0, addPositionStartThreshold:1, placeExcessTakeProfit: false });
        toast('未找到配置,已加载默认值,编辑后请保存', 'success');
    }
    currentApiKey = key;
@@ -233,6 +234,7 @@
    byId('addPositionQuantity').value = d.addPositionQuantity ?? 1;
    byId('maxPositionPerSide').value = d.maxPositionPerSide ?? 0;
    byId('addPositionStartThreshold').value = d.addPositionStartThreshold ?? 1;
    byId('placeExcessTakeProfit').value = (d.placeExcessTakeProfit === true || d.placeExcessTakeProfit === 'true') ? 'true' : 'false';
}
function collectForm() {
@@ -252,7 +254,8 @@
        addPositionInterval: intVal(byId('addPositionInterval').value, 3),
        addPositionQuantity: intVal(byId('addPositionQuantity').value, 1),
        maxPositionPerSide: intVal(byId('maxPositionPerSide').value, 0),
        addPositionStartThreshold: intVal(byId('addPositionStartThreshold').value, 1)
        addPositionStartThreshold: intVal(byId('addPositionStartThreshold').value, 1),
        placeExcessTakeProfit: byId('placeExcessTakeProfit').value === 'true'
    };
}
function intVal(str, fallback) {