Administrator
7 days ago 2179bdddc374fac1bedbe33dbf9d1e82e52a9c6b
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -166,6 +166,10 @@
    private volatile int lastLongStopLossGridId = Integer.MAX_VALUE;
    /** 最近触发止损的空头网格ID */
    private volatile int lastShortStopLossGridId = Integer.MAX_VALUE;
    /** 止损追单所在网格(多仓):价格驱动接管仲裁用,无追单 = Integer.MIN_VALUE */
    private volatile int longSlReentryGridId = Integer.MIN_VALUE;
    /** 止损追单所在网格(空仓):价格驱动接管仲裁用,无追单 = Integer.MIN_VALUE */
    private volatile int shortSlReentryGridId = Integer.MIN_VALUE;
    /** 自定义止损模式激活标记:true=尚未发生第一次止损触发,第一次触发后置 false(触发未触发侧重挂默认) */
    private final AtomicBoolean dualStopLossModeActive = new AtomicBoolean(false);
@@ -201,13 +205,13 @@
    public GateGridTradeService(GateConfig config, StatsEventProducer statsProducer) {
        this.config = config;
        this.statsProducer = statsProducer;
        ApiClient apiClient = new ApiClient();
        ApiClient apiClient = new GateClosingApiClient();
        apiClient.setBasePath(config.getRestBasePath());
        apiClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
        // 修复 gate-api SDK finishAs 枚举不完整导致的反序列化失败(见 buildLenientJson)
        apiClient.setJSON(buildLenientJson());
        this.futuresApi = new FuturesApi(apiClient);
        this.executor = new GateTradeExecutor(apiClient, config.getContract());
        this.executor = new GateTradeExecutor(apiClient, config.getContract(), config.getPriceScale());
    }
    /**
@@ -268,7 +272,7 @@
     */
    public void init() {
        try {
            ApiClient detailClient = new ApiClient();
            ApiClient detailClient = new GateClosingApiClient();
            detailClient.setBasePath(config.getRestBasePath());
            detailClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
            AccountDetail detail = new AccountApi(detailClient).getAccountDetail();
@@ -866,6 +870,7 @@
                }
                int filledQty = Integer.parseInt(shortGridElement.getShortTraderParam().getQuantity());
                shortEntryTraderIdParam(shortGridElement, orderId, false);
                shortSlReentryGridId = Integer.MIN_VALUE;   // 追单已成交,仲裁登记失效
                // 埋点: ENTRY_FILLED — 空仓加仓成交
                emitStats("ENTRY_FILLED", mapOf(
@@ -927,6 +932,7 @@
                }
                int filledQty = Integer.parseInt(longGridElement.getLongTraderParam().getQuantity());
                longEntryTraderIdParam(longGridElement, orderId, false);
                longSlReentryGridId = Integer.MIN_VALUE;   // 追单已成交,仲裁登记失效
                // 埋点: ENTRY_FILLED — 多仓加仓成交
                emitStats("ENTRY_FILLED", mapOf(
@@ -1573,12 +1579,28 @@
            return;
        }
        int removed = 0;
        boolean longSlCompensated = false;   // 每个方向每轮对账最多补触发一次
        boolean shortSlCompensated = false;
        for (GridElement e : config.getGridElements()) {
            for (String id : new ArrayList<>(e.getLongStopLossOrderIds())) {
                if (!openIds.contains(id)) { e.removeLongStopLossOrderId(id); removed++; }
                if (!openIds.contains(id)) {
                    if (!longSlCompensated) {
                        longSlCompensated = true;
                        compensateMissedStopLoss(true, e, id);
                    }
                    e.removeLongStopLossOrderId(id);
                    removed++;
                }
            }
            for (String id : new ArrayList<>(e.getShortStopLossOrderIds())) {
                if (!openIds.contains(id)) { e.removeShortStopLossOrderId(id); removed++; }
                if (!openIds.contains(id)) {
                    if (!shortSlCompensated) {
                        shortSlCompensated = true;
                        compensateMissedStopLoss(false, e, id);
                    }
                    e.removeShortStopLossOrderId(id);
                    removed++;
                }
            }
            for (String id : new ArrayList<>(e.getLongTakeProfitOrderIds())) {
                if (!openIds.contains(id)) { e.removeLongTakeProfitOrderId(id); removed++; }
@@ -1607,6 +1629,39 @@
        if (removed > 0) {
            GridElement.refreshIndices();
            log.warn("[Gate] 条件单对账: 移除 {} 个本地失效订单(交易所已不存在)", removed);
        }
    }
    /**
     * 止损成交补触发:对账发现止损单在交易所已消失时,REST 查该单详情。
     * 若确已成交(trade_id &gt; 0),说明止损触发的 finished 推送被 positions/对账竞态吞掉
     * (finished 晚于对账到达,本地索引已被清空),补执行止损触发逻辑:
     * 累加止损次数、取消该方向开仓单、按止损格∓1 追单、延展止损。
     * <p>追单量由 calculateEntryQuantity 的双重硬上限兜底(≤ 止损张数、≤ maxPerSide − REST持仓),
     * 补触发不会造成重复追单/超仓。无成交记录(REQUEST_TIMEOUT 等)时仅清理 + WARN。</p>
     */
    private void compensateMissedStopLoss(boolean isLong, GridElement gridElement, String orderId) {
        if (state == StrategyState.STOPPED) {
            return;
        }
        try {
            FuturesPriceTriggeredOrder detail = futuresApi.getPriceTriggeredOrder(config.getContract(), Long.parseLong(orderId));
            Long tradeId = detail != null ? detail.getTradeId() : null;
            if (detail == null || tradeId == null || tradeId <= 0) {
                log.warn("[Gate] 条件单对账: {}止损单{}已消失但无成交记录(tradeId:{}), 仅清理不补触发",
                        isLong ? "多仓" : "空仓", orderId, tradeId);
                return;
            }
            log.warn("[Gate] 条件单对账: 检测到{}止损成交事件丢失, 补触发, gridId:{}, orderId:{}, tradeId:{}",
                    isLong ? "多仓" : "空仓", gridElement.getId(), orderId, tradeId);
            if (isLong) {
                handleLongStopLossTriggered(gridElement, orderId);
            } else {
                handleShortStopLossTriggered(gridElement, orderId);
            }
        } catch (Exception e) {
            log.warn("[Gate] 条件单对账: {}止损单{}补触发查询失败: {}",
                    isLong ? "多仓" : "空仓", orderId, e.getMessage());
        }
    }
@@ -1641,7 +1696,11 @@
        int longPos = longPositionSize.intValue();
        if (longPos > 0) {
            GridElement anchor = findNearestLongStopLossGrid();
            if (anchor != null) {
            if (anchor == null) {
                // 止损位全部丢失(断线期间撤掉未重挂/幽灵被对账清空)→ 按默认位整补止盈+止损
                log.warn("[Gate] 多仓有持仓{}张但无任何止损位, 对账按默认位补挂止盈止损", longPos);
                rebuildLongProtection();
            } else {
                int covered = 0;
                for (GridElement e : config.getGridElements()) {
                    covered += e.getLongStopLossTotalSize();
@@ -1658,7 +1717,11 @@
        int shortPos = shortPositionSize.intValue();
        if (shortPos > 0) {
            GridElement anchor = findNearestShortStopLossGrid();
            if (anchor != null) {
            if (anchor == null) {
                // 止损位全部丢失(断线期间撤掉未重挂/幽灵被对账清空)→ 按默认位整补止盈+止损
                log.warn("[Gate] 空仓有持仓{}张但无任何止损位, 对账按默认位补挂止盈止损", shortPos);
                rebuildShortProtection();
            } else {
                int covered = 0;
                for (GridElement e : config.getGridElements()) {
                    covered += e.getShortStopLossTotalSize();
@@ -1670,6 +1733,109 @@
                    cancelAllShortStopLossesOnly();
                    extendShortStopLoss(shortPos, anchor.getId() - 2);
                }
            }
        }
    }
    /**
     * 按默认位(基底网格 ±2)重建多仓止盈+止损:撤旧 → 按最新持仓挂单位置全量止损 + 超额/基础止盈。
     * 供对账兜底(止损位全部丢失时)与手动重建共用。
     */
    private void rebuildLongProtection() {
        cancelAllLongTakeProfitsAndStopLosses();
        int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue());
        if (posSize <= 0) {
            log.warn("[Gate] 生成多仓止盈止损失败:无多仓持仓");
            return;
        }
        // 锚点按"当前价下方最近网格"取:多仓止损触发价必须 < 最新价,
        // 固定用 grid 0 在行情远离基底时会导致触发价在现价上方被交易所拒绝(AUTO_TRIGGER_PRICE_LESS_LAST)
        int anchor = findValidRebuildAnchor(true);
        if (anchor == Integer.MIN_VALUE) {
            log.warn("[Gate] 多仓止盈止损重建失败:当前价完全脱离网格范围, 现价:{}", lastKlinePrice);
            return;
        }
        extendLongStopLoss(posSize, anchor);
        if (GateConfig.EXCESS_TP_CONCENTRATED.equals(config.getPlaceExcessTakeProfit())) {
            placeExcessTakeProfit(posSize, true);
        } else if (GateConfig.EXCESS_TP_DISPERSED.equals(config.getPlaceExcessTakeProfit())) {
            placeDispersedTakeProfit(posSize, true, anchor);
        }
        placeBaseTakeProfit(posSize, true, anchor);
        log.info("[Gate] 多仓止盈止损已重建, 仓位:{}张, 锚点gridId:{}, 现价:{}", posSize, anchor, lastKlinePrice);
    }
    /**
     * 按默认位(基底网格 ±2)重建空仓止盈+止损:撤旧 → 按最新持仓挂单位置全量止损 + 超额/基础止盈。
     * 供对账兜底(止损位全部丢失时)与手动重建共用。
     */
    private void rebuildShortProtection() {
        cancelAllShortTakeProfitsAndStopLosses();
        int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue());
        if (posSize <= 0) {
            log.warn("[Gate] 生成空仓止盈止损失败:无空仓持仓");
            return;
        }
        // 锚点按"当前价上方最近网格"取:空仓止损触发价必须 > 最新价,
        // 固定用 grid 0 在行情远离基底时会导致触发价在现价下方被交易所拒绝
        int anchor = findValidRebuildAnchor(false);
        if (anchor == Integer.MIN_VALUE) {
            log.warn("[Gate] 空仓止盈止损重建失败:当前价完全脱离网格范围, 现价:{}", lastKlinePrice);
            return;
        }
        extendShortStopLoss(posSize, anchor);
        if (GateConfig.EXCESS_TP_CONCENTRATED.equals(config.getPlaceExcessTakeProfit())) {
            placeExcessTakeProfit(posSize, false);
        } else if (GateConfig.EXCESS_TP_DISPERSED.equals(config.getPlaceExcessTakeProfit())) {
            placeDispersedTakeProfit(posSize, false, anchor);
        }
        placeBaseTakeProfit(posSize, false, anchor);
        log.info("[Gate] 空仓止盈止损已重建, 仓位:{}张, 锚点gridId:{}, 现价:{}", posSize, anchor, lastKlinePrice);
    }
    /**
     * 为"按当前价重建止盈止损"寻找有效锚点:
     * 多仓取当前价<b>下方</b>最近网格(止损触发价 &lt; 最新价),
     * 空仓取当前价<b>上方</b>最近网格(止损触发价 &gt; 最新价)。
     * 找不到(现价完全脱离网格范围)返回 {@link Integer#MIN_VALUE}。
     * <p>返回值为"入场锚点"口径:extend 时止损会挂在 anchor∓2 处。</p>
     */
    private int findValidRebuildAnchor(boolean isLong) {
        BigDecimal current = lastKlinePrice;
        if (current == null || current.compareTo(BigDecimal.ZERO) <= 0) {
            return Integer.MIN_VALUE;
        }
        if (isLong) {
            synchronized (totalLongPriceQueue) {
                BigDecimal best = null;
                for (BigDecimal p : totalLongPriceQueue) {   // 升序
                    if (p.compareTo(current) <= 0) {
                        best = p;
                    } else {
                        break;
                    }
                }
                if (best == null) {
                    return Integer.MIN_VALUE;
                }
                GridElement g = GridElement.findByPrice(best);
                return g != null ? g.getId() + 2 : Integer.MIN_VALUE;
            }
        } else {
            synchronized (totalShortPriceQueue) {
                BigDecimal best = null;
                for (BigDecimal p : totalShortPriceQueue) {   // 降序
                    if (p.compareTo(current) >= 0) {
                        best = p;
                    } else {
                        break;
                    }
                }
                if (best == null) {
                    return Integer.MIN_VALUE;
                }
                GridElement g = GridElement.findByPrice(best);
                return g != null ? g.getId() - 2 : Integer.MIN_VALUE;
            }
        }
    }
@@ -1912,63 +2078,55 @@
    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);
        log.info("[Gate] 止损止盈单已全部挂完, 空仓止损:2, 多仓止损:-2");
    }
    /**
     * 默认空仓止损阶梯:从 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, Integer.parseInt(size));
                        GridElement.refreshIndices();
                        log.info("[Gate] 空仓止损已挂, gridId:{}, 触发价:{}, stopLossId:{}", finalId, triggerPrice, profitId);
                    }
            );
        // 单位置全量止损:全部基础仓位挂一张止损单(入场格上方第2格,价格≥触发价平空)
        GridElement elem = GridElement.findById(2);
        if (elem == null) {
            return;
        }
        BigDecimal triggerPrice = elem.getGridPrice();
        String size = config.getBaseQuantity();
        executor.placeTakeProfit(
                triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_1,
                ORDER_TYPE_CLOSE_SHORT,
                size,
                profitId -> {
                    elem.addShortStopLossOrderId(profitId, Integer.parseInt(size));
                    GridElement.refreshIndices();
                    log.info("[Gate] 空仓止损已挂, gridId:2, 触发价:{}, 张数:{}, stopLossId:{}", triggerPrice, size, 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, Integer.parseInt(size));
                        GridElement.refreshIndices();
                        log.info("[Gate] 多仓止损已挂, gridId:{}, 触发价:{}, stopLossId:{}", finalId, triggerPrice, profitId);
                    }
            );
        // 单位置全量止损:全部基础仓位挂一张止损单(入场格下方第2格,价格≤触发价平多)
        GridElement elem = GridElement.findById(-2);
        if (elem == null) {
            return;
        }
        BigDecimal triggerPrice = elem.getGridPrice();
        String size = config.getBaseQuantity();
        executor.placeTakeProfit(
                triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_2,
                ORDER_TYPE_CLOSE_LONG,
                negate(size),
                profitId -> {
                    elem.addLongStopLossOrderId(profitId, Integer.parseInt(size));
                    GridElement.refreshIndices();
                    log.info("[Gate] 多仓止损已挂, gridId:-2, 触发价:{}, 张数:{}, stopLossId:{}", triggerPrice, size, profitId);
                }
        );
    }
    /**
@@ -2259,7 +2417,7 @@
                    .build();
            elements.add(GridElement.builder()
                    .id(0)
                    .gridPrice(price)
                    .gridPrice(price.setScale(prec, RoundingMode.HALF_UP))
                    .upId(longSize > 0 ? 1 : null)
                    .downId(shortSize > 0 ? -1 : null)
                    .longTraderParam(longParam)
@@ -2302,156 +2460,290 @@
    /** 多仓仓位归零后,在当前价上方最近网格重新挂多单(遍历 totalLongPriceQueue 升序)。 */
    private void processLongGrid(BigDecimal currentPrice) {
        BigDecimal matched = BigDecimal.ZERO;
        GridElement newEntryGrid = null;
        boolean hasLongOrderBelow = false;
        // 阶段1(队列锁内):匹配价格 + 网格定位 + 本地挂单检查 + 提交撤单,全程无阻塞 IO
        synchronized (totalLongPriceQueue) {
            BigDecimal matched = BigDecimal.ZERO;
            for (BigDecimal p : totalLongPriceQueue) {
                if (p.compareTo(currentPrice) >= 0) {
                    matched =  p;
                    matched = p;
                    break;
                }
            }
//            log.info("[Gate-1] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
            if (BigDecimal.ZERO.compareTo( matched) == 0) {
            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null){
                if (!matchedUpGridElement.isHasLongOrder()){
                    Integer upId = matchedUpGridElement.getUpId();
                    GridElement newEntryGrid = GridElement.findById(upId);
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasLongOrder()) {
                Integer upId = matchedUpGridElement.getUpId();
                newEntryGrid = GridElement.findById(upId);
                    if (newEntryGrid != null) {
//                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
//                        String quantity = String.valueOf(config.getBaseQuantity());
                        String quantity = calculateEntryQuantity(true, false, 0);
                        // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
                        boolean hasLongOrderBelow = false;
                        GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
                        while (checkDownCursor != null) {
                            if (checkDownCursor.isHasLongOrder()) {
                                hasLongOrderBelow = true;
                                log.info("[Gate] 多仓仓位归零 gridId:{}, 下方gridId:{}已有多单, 跳过本次挂单",
                                        newEntryGrid.getId(), checkDownCursor.getId());
                                break;
                if (newEntryGrid != null) {
                    // 止损追单接管(先撤后挂):价格继续下跌,目标格已低于追单格
                    // (如追单在 grid-1、价格到 grid-3 → 目标格 grid-2)→ 撤掉落后追单,
                    // 撤单成功后再挂新单,杜绝撤挂并发导致双单并存
                    if (longSlReentryGridId != Integer.MIN_VALUE
                            && newEntryGrid.getId() < longSlReentryGridId) {
                        GridElement reentryElem = GridElement.findById(longSlReentryGridId);
                        if (reentryElem != null && reentryElem.isHasLongOrder()) {
                            final GridElement takeoverTarget = newEntryGrid;
                            for (String oid : new ArrayList<>(reentryElem.getLongOrderIds())) {
                                executor.cancelConditionalOrder(oid, o -> {
                                    longEntryTraderIdParam(reentryElem, oid, false);
                                    // 全部撤完后再挂新单(先撤后挂)
                                    if (!reentryElem.hasLongOrderIds()) {
                                        hangLongEntryWithVerify(takeoverTarget);
                                    }
                                });
                            }
                            Integer nextDownId = checkDownCursor.getDownId();
                            checkDownCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                            return;   // 接管流程已启动,本轮不走常规挂单
                        }
                        longSlReentryGridId = Integer.MIN_VALUE;
                    }
                    // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
                    GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
                    while (checkDownCursor != null) {
                        if (checkDownCursor.isHasLongOrder()) {
                            hasLongOrderBelow = true;
                            log.debug("[Gate] 多仓仓位归零 gridId:{}, 下方gridId:{}已有多单, 跳过本次挂单",
                                    newEntryGrid.getId(), checkDownCursor.getId());
                            break;
                        }
                        Integer nextDownId = checkDownCursor.getDownId();
                        checkDownCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                    }
                        // 向上遍历取消所有遗留多单(跳过基础入场网格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);
                                    });
                                }
                    // 向上遍历取消所有遗留多单(跳过基础入场网格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);
                                });
                            }
                            Integer nextUpId = cancelCursor.getUpId();
                            cancelCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                        }
//                        log.info("[Gate-2] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                        if (!newEntryGrid.isHasLongOrder() && !hasLongOrderBelow) {
                            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
                            String size = quantity;
                            log.info("[Gate] 多仓仓位归零 gridId:{}, 挂{}张多单",
                                    newEntryGrid.getId(), size);
                            newEntryGrid.getLongTraderParam().setQuantity(size);
                            // 含加仓量的单打标记:真正成交后才计入加仓执行次数
                            boolean hasAdd = computeAddQty(true) > 0;
                            placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
                                    FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
                                    hasAdd ? pendingAddEntryOrderIds::add : null);
                        }
                        Integer nextUpId = cancelCursor.getUpId();
                        cancelCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                    }
                }
            }
        }
        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
        if (newEntryGrid == null || newEntryGrid.isHasLongOrder() || hasLongOrderBelow) {
            return;
        }
        // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
        // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍(历史出现过 68→136 张);
        // 顺带同步 entryPrice(此前核实只修 size/active,均价仍是旧值)
        Position longPos = queryPosition(Position.ModeEnum.DUAL_LONG);
        int realPos = longPos != null ? Math.abs(new BigDecimal(longPos.getSize()).intValue()) : 0;
        if (realPos > 0) {
            longActive = true;
            longPositionSize = BigDecimal.valueOf(realPos);
            if (longPos.getEntryPrice() != null) {
                try {
                    longEntryPrice = new BigDecimal(longPos.getEntryPrice());
                } catch (NumberFormatException ignored) {
                }
            }
            log.warn("[Gate] 多仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
            return;
        }
        // 阶段3:挂单
        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
        String size = calculateEntryQuantity(true, false, 0);
        log.info("[Gate] 多仓仓位归零 gridId:{}, 挂{}张多单",
                newEntryGrid.getId(), size);
        newEntryGrid.getLongTraderParam().setQuantity(size);
        // 含加仓量的单打标记:真正成交后才计入加仓执行次数
        boolean hasAdd = computeAddQty(true) > 0;
        placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
                hasAdd ? pendingAddEntryOrderIds::add : null);
    }
    /**
     * 接管挂单(多仓):撤掉落后止损追单成功后,REST 核实持仓为 0 再占坑挂多开仓单。
     * 核实失败(追单实际已成交)则跳过,避免重复建仓。
     */
    private void hangLongEntryWithVerify(GridElement entryGrid) {
        Position longPos = queryPosition(Position.ModeEnum.DUAL_LONG);
        int realPos = longPos != null ? Math.abs(new BigDecimal(longPos.getSize()).intValue()) : 0;
        if (realPos > 0) {
            longActive = true;
            longPositionSize = BigDecimal.valueOf(realPos);
            if (longPos.getEntryPrice() != null) {
                try {
                    longEntryPrice = new BigDecimal(longPos.getEntryPrice());
                } catch (NumberFormatException ignored) {
                }
            }
            log.warn("[Gate] 接管挂单核实: 多仓实际持仓{}张>0, 跳过挂单(追单已成交)", realPos);
            return;
        }
        BigDecimal triggerPrice = entryGrid.getGridPrice();
        String size = calculateEntryQuantity(true, false, 0);
        if (Integer.parseInt(size) <= 0) {
            log.warn("[Gate] 接管挂单: 已达单边上限({}), 跳过", config.getMaxPositionPerSide());
            return;
        }
        entryGrid.getLongTraderParam().setQuantity(size);
        boolean hasAdd = computeAddQty(true) > 0;
        log.info("[Gate] 价格驱动接管: 多仓挂单 gridId:{}, {}张", entryGrid.getId(), size);
        placeEntryOrderWithPreFlag(entryGrid, true, triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
                hasAdd ? pendingAddEntryOrderIds::add : null);
    }
    /**
     * 接管挂单(空仓):撤掉落后止损追单成功后,REST 核实持仓为 0 再占坑挂空开仓单。
     * 核实失败(追单实际已成交)则跳过,避免重复建仓。
     */
    private void hangShortEntryWithVerify(GridElement entryGrid) {
        Position shortPos = queryPosition(Position.ModeEnum.DUAL_SHORT);
        int realPos = shortPos != null ? Math.abs(new BigDecimal(shortPos.getSize()).intValue()) : 0;
        if (realPos > 0) {
            shortActive = true;
            shortPositionSize = BigDecimal.valueOf(realPos);
            if (shortPos.getEntryPrice() != null) {
                try {
                    shortEntryPrice = new BigDecimal(shortPos.getEntryPrice());
                } catch (NumberFormatException ignored) {
                }
            }
            log.warn("[Gate] 接管挂单核实: 空仓实际持仓{}张>0, 跳过挂单(追单已成交)", realPos);
            return;
        }
        BigDecimal triggerPrice = entryGrid.getGridPrice();
        String size = calculateEntryQuantity(false, false, 0);
        if (Integer.parseInt(size) <= 0) {
            log.warn("[Gate] 接管挂单: 已达单边上限({}), 跳过", config.getMaxPositionPerSide());
            return;
        }
        entryGrid.getShortTraderParam().setQuantity(size);
        boolean hasAdd = computeAddQty(false) > 0;
        log.info("[Gate] 价格驱动接管: 空仓挂单 gridId:{}, {}张", entryGrid.getId(), size);
        placeEntryOrderWithPreFlag(entryGrid, false, triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
                hasAdd ? pendingAddEntryOrderIds::add : null);
    }
    /** 空仓仓位归零后,在当前价下方最近网格重新挂空单(遍历 totalShortPriceQueue 降序)。 */
    private void processShortGrid(BigDecimal currentPrice) {
        BigDecimal matched = BigDecimal.ZERO;
        GridElement newEntryGrid = null;
        boolean hasShortOrderAbove = false;
        // 阶段1(队列锁内):匹配价格 + 网格定位 + 本地挂单检查 + 提交撤单,全程无阻塞 IO
        synchronized (totalShortPriceQueue) {
            BigDecimal matched = BigDecimal.ZERO;
            for (BigDecimal p : totalShortPriceQueue) {
                if (p.compareTo(currentPrice) <= 0) {
                    matched = p;
                    break;
                }
            }
//            log.info("[Gate-3] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
            if (BigDecimal.ZERO.compareTo( matched) == 0) {
            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null){
                if(!matchedUpGridElement.isHasShortOrder()){
                    Integer downId = matchedUpGridElement.getDownId();
                    GridElement newEntryGrid = GridElement.findById(downId);
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasShortOrder()) {
                Integer downId = matchedUpGridElement.getDownId();
                newEntryGrid = GridElement.findById(downId);
                    if (newEntryGrid != null) {
//                        String quantity = String.valueOf((accumulatedShortLossCount + 1) * Integer.parseInt(config.getQuantity()));
//                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
//                        String quantity = String.valueOf(config.getBaseQuantity());
                        String quantity = calculateEntryQuantity(false, false, 0);
                        // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
                        boolean hasShortOrderAbove = false;
                        GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
                        while (checkUpCursor != null) {
                            if (checkUpCursor.isHasShortOrder()) {
                                hasShortOrderAbove = true;
                                log.info("[Gate] 空仓仓位归零 gridId:{}, 上方gridId:{}已有空单, 跳过本次挂单",
                                        newEntryGrid.getId(), checkUpCursor.getId());
                                break;
                if (newEntryGrid != null) {
                    // 止损追单接管(先撤后挂):价格继续上涨,目标格已高于追单格
                    // (如追单在 grid1、价格到 grid3 → 目标格 grid2)→ 撤掉落后追单,
                    // 撤单成功后再挂新单,杜绝撤挂并发导致双单并存
                    if (shortSlReentryGridId != Integer.MIN_VALUE
                            && newEntryGrid.getId() > shortSlReentryGridId) {
                        GridElement reentryElem = GridElement.findById(shortSlReentryGridId);
                        if (reentryElem != null && reentryElem.isHasShortOrder()) {
                            final GridElement takeoverTarget = newEntryGrid;
                            for (String oid : new ArrayList<>(reentryElem.getShortOrderIds())) {
                                executor.cancelConditionalOrder(oid, o -> {
                                    shortEntryTraderIdParam(reentryElem, oid, false);
                                    // 全部撤完后再挂新单(先撤后挂)
                                    if (!reentryElem.hasShortOrderIds()) {
                                        hangShortEntryWithVerify(takeoverTarget);
                                    }
                                });
                            }
                            Integer nextUpId = checkUpCursor.getUpId();
                            checkUpCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                            return;   // 接管流程已启动,本轮不走常规挂单
                        }
                        shortSlReentryGridId = Integer.MIN_VALUE;
                    }
                    // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
                    GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
                    while (checkUpCursor != null) {
                        if (checkUpCursor.isHasShortOrder()) {
                            hasShortOrderAbove = true;
                            log.debug("[Gate] 空仓仓位归零 gridId:{}, 上方gridId:{}已有空单, 跳过本次挂单",
                                    newEntryGrid.getId(), checkUpCursor.getId());
                            break;
                        }
                        Integer nextUpId = checkUpCursor.getUpId();
                        checkUpCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                    }
                        // 向下遍历取消所有遗留空单(跳过基础入场网格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);
                                    });
                                }
                    // 向下遍历取消所有遗留空单(跳过基础入场网格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);
                                });
                            }
                            Integer nextDownId = cancelCursor.getDownId();
                            cancelCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                        }
//                        log.info("[Gate-4] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                        if (!newEntryGrid.isHasShortOrder() && !hasShortOrderAbove){
                            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
                            String size = quantity;
                            log.info("[Gate] 空仓仓位归零 gridId:{}, 挂{}张空单",
                                    newEntryGrid.getId(), size);
                            newEntryGrid.getShortTraderParam().setQuantity(size);
                            // 含加仓量的单打标记:真正成交后才计入加仓执行次数
                            boolean hasAdd = computeAddQty(false) > 0;
                            placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
                                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
                                    hasAdd ? pendingAddEntryOrderIds::add : null);
                        }
                        Integer nextDownId = cancelCursor.getDownId();
                        cancelCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                    }
                }
            }
        }
        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
        if (newEntryGrid == null || newEntryGrid.isHasShortOrder() || hasShortOrderAbove) {
            return;
        }
        // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
        // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍;
        // 顺带同步 entryPrice(此前核实只修 size/active,均价仍是旧值)
        Position shortPos = queryPosition(Position.ModeEnum.DUAL_SHORT);
        int realPos = shortPos != null ? Math.abs(new BigDecimal(shortPos.getSize()).intValue()) : 0;
        if (realPos > 0) {
            shortActive = true;
            shortPositionSize = BigDecimal.valueOf(realPos);
            if (shortPos.getEntryPrice() != null) {
                try {
                    shortEntryPrice = new BigDecimal(shortPos.getEntryPrice());
                } catch (NumberFormatException ignored) {
                }
            }
            log.warn("[Gate] 空仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
            return;
        }
        // 阶段3:挂单
        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
        String size = calculateEntryQuantity(false, false, 0);
        log.info("[Gate] 空仓仓位归零 gridId:{}, 挂{}张空单",
                newEntryGrid.getId(), size);
        newEntryGrid.getShortTraderParam().setQuantity(size);
        // 含加仓量的单打标记:真正成交后才计入加仓执行次数
        boolean hasAdd = computeAddQty(false) > 0;
        placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
                hasAdd ? pendingAddEntryOrderIds::add : null);
    }
    // ========== 加仓计算 ==========
@@ -2560,16 +2852,19 @@
        if (maxPerSide > 0) {
            int upperLimit = maxPerSide;
            if (respectCurrentPosition) {
                // 止损追单:单边总持仓不得超过 maxPerSide,追单量 = maxPerSide - 当前持仓。
                // 止损单刚成交、REST 查询可能仍返回止损前持仓(时序竞态),
                // 减去本网格全部止损张数得到止损后的真实持仓,避免追单量被错误扣减。
                // 止损追单:单边总持仓不得超过 maxPerSide。
                // REST 持仓可能返回止损前旧值,也可能返回止损后的真实剩余(阶梯止损部分成交时),
                // 两者无法区分,因此不再用"REST − 止损张数"估算止损后持仓(历史 bug:剩余20被减成0,
                // 按空仓追满100 → 20+100=120 张超限)。
                // 改为双重硬上限:追单量 ≤ maxPerSide − REST持仓,且 ≤ 本网格被平掉的止损张数。
                // 宁可少追(安全,缺口由价格驱动补齐),绝不在剩余仓位上多追。
                int currentPos = isLong
                        ? queryPositionSize(Position.ModeEnum.DUAL_LONG)
                        : queryPositionSize(Position.ModeEnum.DUAL_SHORT);
                upperLimit = Math.max(0, maxPerSide - Math.max(currentPos, 0));
                if (stopLossSize > 0) {
                    currentPos = Math.max(0, currentPos - stopLossSize);
                    upperLimit = Math.min(upperLimit, stopLossSize);
                }
                upperLimit = maxPerSide - currentPos;
            }
            if (upperLimit <= 0) {
                totalQty = 0;
@@ -2614,6 +2909,18 @@
            return;
        }
        // 止损触发:先取消该方向全部遗留多开仓单(对向加仓/补仓/旧追单),再挂新追单,
        // 避免旧单与新追单重复建仓(与价格驱动的扫荡口径一致)
        cancelAllLongEntryOrders();
        // 登记止损追单网格:价格驱动以此仲裁优先级(追单优先,价格越过追单格后价格驱动接管)
        longSlReentryGridId = newEntryGrid.getId();
        // 占坑前移:撤单后立即在追单目标网格预留"有单"标记(同步、无I/O),再执行 REST 数量计算
        // (耗时数百ms)。价格驱动的挂单判定(本格有单/游标检查)会看到该标记并跳过本轮,
        // 消除"撤旧挂新"窗口期被价格驱动抢先挂单导致的双单竞态。
        newEntryGrid.setHasLongOrder(true);
        // 止损追单:同一网格可有多笔挂单,不判断 isHasLongOrder,直接挂单
        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
        String size = calculateEntryQuantity(true, true, gridStopLossSize);
@@ -2622,6 +2929,10 @@
                config.getBaseQuantity(), size, config.getStopLossCountMode());
        if (Integer.parseInt(size) <= 0) {
            log.warn("[Gate] 多仓止损追单 当前持仓已达单边上限({}), 跳过挂单", config.getMaxPositionPerSide());
            // 清理占坑标记与追单登记(未挂单)
            newEntryGrid.setHasLongOrder(newEntryGrid.hasLongOrderIds());
            longSlReentryGridId = Integer.MIN_VALUE;
            GridElement.refreshIndices();
        } else {
            newEntryGrid.getLongTraderParam().setQuantity(size);
            // 含加仓量的单打标记:真正成交后才计入加仓执行次数(挂单后被取消的不算)
@@ -2629,18 +2940,6 @@
            placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
                    FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
                    hasAdd ? pendingAddEntryOrderIds::add : null);
        }
        // 取消 gridId+2 位置的所有多单
        int cancelGridId = gridId + 2;
        GridElement cancelGrid = GridElement.findById(cancelGridId);
        if (cancelGrid != null && cancelGrid.isHasLongOrder()) {
            for (String cancelOrderId : new ArrayList<>(cancelGrid.getLongOrderIds())) {
                executor.cancelConditionalOrder(cancelOrderId, oid -> {
                    longEntryTraderIdParam(cancelGrid, cancelOrderId, false);
                    log.info("[Gate] 多仓止损触发, 取消gridId:{}的多单,{}", cancelGridId, cancelOrderId);
                });
            }
        }
        // 自定义止损模式:第一次止损触发时,取消未触发侧(空仓)自定义止损单并重挂默认阶梯
@@ -2683,6 +2982,18 @@
            return;
        }
        // 止损触发:先取消该方向全部遗留空开仓单(对向加仓/补仓/旧追单),再挂新追单,
        // 避免旧单与新追单重复建仓(与价格驱动的扫荡口径一致)
        cancelAllShortEntryOrders();
        // 登记止损追单网格:价格驱动以此仲裁优先级(追单优先,价格越过追单格后价格驱动接管)
        shortSlReentryGridId = newEntryGrid.getId();
        // 占坑前移:撤单后立即在追单目标网格预留"有单"标记(同步、无I/O),再执行 REST 数量计算
        // (耗时数百ms)。价格驱动的挂单判定(本格有单/游标检查)会看到该标记并跳过本轮,
        // 消除"撤旧挂新"窗口期被价格驱动抢先挂单导致的双单竞态。
        newEntryGrid.setHasShortOrder(true);
        // 止损追单:同一网格可有多笔挂单,不判断 isHasShortOrder,直接挂单
        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
        String size = calculateEntryQuantity(false, true, gridStopLossSize);
@@ -2691,6 +3002,10 @@
                config.getBaseQuantity(), size, config.getStopLossCountMode());
        if (Integer.parseInt(size) <= 0) {
            log.warn("[Gate] 空仓止损追单 当前持仓已达单边上限({}), 跳过挂单", config.getMaxPositionPerSide());
            // 清理占坑标记与追单登记(未挂单)
            newEntryGrid.setHasShortOrder(newEntryGrid.hasShortOrderIds());
            shortSlReentryGridId = Integer.MIN_VALUE;
            GridElement.refreshIndices();
        } else {
            newEntryGrid.getShortTraderParam().setQuantity(size);
            // 含加仓量的单打标记:真正成交后才计入加仓执行次数(挂单后被取消的不算)
@@ -2698,18 +3013,6 @@
            placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
                    hasAdd ? pendingAddEntryOrderIds::add : null);
        }
        // 取消 gridId-2 位置的所有空单
        int cancelGridId = gridId - 2;
        GridElement cancelGrid = GridElement.findById(cancelGridId);
        if (cancelGrid != null && cancelGrid.isHasShortOrder()) {
            for (String cancelOrderId : new ArrayList<>(cancelGrid.getShortOrderIds())) {
                executor.cancelConditionalOrder(cancelOrderId, oid -> {
                    shortEntryTraderIdParam(cancelGrid, cancelOrderId, false);
                    log.info("[Gate] 空仓止损触发, 取消gridId:{}的空单,{}", cancelGridId, cancelOrderId);
                });
            }
        }
        // 自定义止损模式:第一次止损触发时,取消未触发侧(多仓)自定义止损单并重挂默认阶梯
@@ -2938,164 +3241,54 @@
        log.info("[Gate] 首次成交,取消所有初始化止盈单");
    }
    // ========== 止损追单(新逻辑:3 个固定位置,每个位置挂多个 1 张止损单) ==========
    // ========== 止损追单(单位置全量:全部持仓挂一张止损单) ==========
    /**
     * 多仓止损追单 — 把当前多头持仓<b>全量</b>拆分为多笔止损单,挂在靠近入场的连续网格上。
     * 网格数 gridCount = baseQuantity / quantity;最近网格挂大部分张数、其余网格各挂 1 笔 quantity 张,
     * 不足一格的余数单独在更远一网格挂一笔。所有异步挂单完成后通过计数器重置防重入标记;
     * 期间若有入场单成交则打 pendingStopLossReExtend 待重挂。
     * 多仓止损追单 — 把当前多头持仓<b>全量</b>合并为一张止损单,挂在入场格下方第 2 格
     * (价格 ≤ 触发价平多)。slSize = max(filledQty, baseQuantity),保证覆盖全部持仓;
     * 挂单完成回调重置防重入标记,期间若有入场单成交则打 pendingStopLossReExtend 待重挂。
     */
    private void extendLongStopLoss(int filledQty, int gridId) {
        int qty = Integer.parseInt(config.getQuantity());
        int baseQty = Integer.parseInt(config.getBaseQuantity());
        int gridCount = baseQty / qty;
        GridElement entryElem = GridElement.findById(gridId);
        if (gridCount <= 0 || filledQty <= 0) {
        if (filledQty <= 0) {
            // 早期返回需重置防重入标记
            if (entryElem != null) { entryElem.setExtendStopLossInProgress(false); }
            return;
        }
        // [Gate] 止损覆盖全持仓:加仓部分同样受止损保护,不再只保初始仓位。
        // 单位置全量止损:当前方向全部持仓挂一张止损单(入场格下方第2格,价格≤触发价平多)。
        // 取 max 是为了在 REST 时序竞态导致 filledQty 偏小时,至少保住 baseQuantity 的基础仓位
        int slSize = Math.max(filledQty, baseQty);
        int totalOrders = slSize / qty;
        int remainder = slSize % qty;
        int[] orders = new int[gridCount];
        if (gridCount == 1) {
            // 只有1个网格,全量挂在上面
            orders[0] = totalOrders;
        } else {
            // 最近网格(orders[0])挂剩余张数,其余每个网格各挂1张
            orders[0] = totalOrders - (gridCount - 1);
            if (orders[0] < 1) {
                // 订单数不够覆盖所有网格(理论上不会出现),全量挂在最近网格
                orders[0] = totalOrders;
            } else {
                for (int i = 1; i < gridCount; i++) {
                    orders[i] = 1;
                }
            }
        }
        // 计算总订单数,用于异步回调完成时重置防重入标记
        int totalOrdersToPlace = 0;
        for (int i = 0; i < gridCount; i++) {
            if (orders[i] > 0) { totalOrdersToPlace += orders[i]; }
        }
        if (remainder > 0) { totalOrdersToPlace += 1; }
        if (totalOrdersToPlace == 0) {
            if (entryElem != null) { entryElem.setExtendStopLossInProgress(false); }
            return;
        }
        AtomicInteger remainCount = new AtomicInteger(totalOrdersToPlace);
        StringBuilder detail = new StringBuilder();
        for (int i = 0; i < gridCount; i++) {
            if (orders[i] > 0) {
                int sgId = gridId - 2 - i;
                placeStopLossOrders(sgId, orders[i], String.valueOf(qty), FuturesPriceTrigger.RuleEnum.NUMBER_2,
                        ORDER_TYPE_CLOSE_LONG, true, remainCount, entryElem);
                if (detail.length() > 0) {
                    detail.append("  ");
                }
                detail.append(sgId).append("x").append(orders[i]);
            }
        }
        // 不足一个网格量的余数:单独挂一张止损
        if (remainder > 0) {
            int sgId = gridId - 2 - totalOrders;
            placeStopLossOrders(sgId, 1, String.valueOf(remainder), FuturesPriceTrigger.RuleEnum.NUMBER_2,
                    ORDER_TYPE_CLOSE_LONG, true, remainCount, entryElem);
            if (detail.length() > 0) {
                detail.append("  ");
            }
            detail.append(sgId).append("x").append(remainder);
        }
        log.info("[Gate] 多仓追挂止损, 成交{}张, gridId:{}, 网格数:{}, 分配:{}",
                filledQty, gridId, gridCount, detail);
        int slSize = Math.max(filledQty, Integer.parseInt(config.getBaseQuantity()));
        AtomicInteger remainCount = new AtomicInteger(1);
        int sgId = gridId - 2;
        placeStopLossOrders(sgId, 1, String.valueOf(slSize), FuturesPriceTrigger.RuleEnum.NUMBER_2,
                ORDER_TYPE_CLOSE_LONG, true, remainCount, entryElem);
        log.info("[Gate] 多仓追挂止损, 成交{}张, gridId:{}, 单位置全量止损:{}x{}张",
                filledQty, gridId, sgId, slSize);
    }
    /**
     * 空仓止损追单 — 把当前空头持仓<b>全量</b>拆分为多笔止损单,挂在靠近入场的连续网格上。
     * 网格数 gridCount = baseQuantity / quantity;最近网格挂大部分张数、其余网格各挂 1 笔 quantity 张,
     * 不足一格的余数单独在更远一网格挂一笔。所有异步挂单完成后通过计数器重置防重入标记;
     * 期间若有入场单成交则打 pendingStopLossReExtend 待重挂。
     * 空仓止损追单 — 把当前空头持仓<b>全量</b>合并为一张止损单,挂在入场格上方第 2 格
     * (价格 ≥ 触发价平空)。slSize = max(filledQty, baseQuantity),保证覆盖全部持仓;
     * 挂单完成回调重置防重入标记,期间若有入场单成交则打 pendingStopLossReExtend 待重挂。
     */
    private void extendShortStopLoss(int filledQty, int gridId) {
        int qty = Integer.parseInt(config.getQuantity());
        int baseQty = Integer.parseInt(config.getBaseQuantity());
        int gridCount = baseQty / qty;
        GridElement entryElem = GridElement.findById(gridId);
        if (gridCount <= 0 || filledQty <= 0) {
        if (filledQty <= 0) {
            // 早期返回需重置防重入标记
            if (entryElem != null) { entryElem.setExtendStopLossInProgress(false); }
            return;
        }
        // [Gate] 止损覆盖全持仓:加仓部分同样受止损保护,不再只保初始仓位。
        // 单位置全量止损:当前方向全部持仓挂一张止损单(入场格上方第2格,价格≥触发价平空)。
        // 取 max 是为了在 REST 时序竞态导致 filledQty 偏小时,至少保住 baseQuantity 的基础仓位
        int slSize = Math.max(filledQty, baseQty);
        int totalOrders = slSize / qty;
        int remainder = slSize % qty;
        int[] orders = new int[gridCount];
        if (gridCount == 1) {
            // 只有1个网格,全量挂在上面
            orders[0] = totalOrders;
        } else {
            // 最近网格(orders[0])挂剩余张数,其余每个网格各挂1张
            orders[0] = totalOrders - (gridCount - 1);
            if (orders[0] < 1) {
                // 订单数不够覆盖所有网格(理论上不会出现),全量挂在最近网格
                orders[0] = totalOrders;
            } else {
                for (int i = 1; i < gridCount; i++) {
                    orders[i] = 1;
                }
            }
        }
        // 计算总订单数,用于异步回调完成时重置防重入标记
        int totalOrdersToPlace = 0;
        for (int i = 0; i < gridCount; i++) {
            if (orders[i] > 0) { totalOrdersToPlace += orders[i]; }
        }
        if (remainder > 0) { totalOrdersToPlace += 1; }
        if (totalOrdersToPlace == 0) {
            if (entryElem != null) { entryElem.setExtendStopLossInProgress(false); }
            return;
        }
        AtomicInteger remainCount = new AtomicInteger(totalOrdersToPlace);
        StringBuilder detail = new StringBuilder();
        for (int i = 0; i < gridCount; i++) {
            if (orders[i] > 0) {
                int sgId = gridId + 2 + i;
                placeStopLossOrders(sgId, orders[i], String.valueOf(qty), FuturesPriceTrigger.RuleEnum.NUMBER_1,
                        ORDER_TYPE_CLOSE_SHORT, false, remainCount, entryElem);
                if (detail.length() > 0) {
                    detail.append("  ");
                }
                detail.append(sgId).append("x").append(orders[i]);
            }
        }
        // 不足一个网格量的余数:单独挂一张止损
        if (remainder > 0) {
            int sgId = gridId + 2 + totalOrders;
            placeStopLossOrders(sgId, 1, String.valueOf(remainder), FuturesPriceTrigger.RuleEnum.NUMBER_1,
                    ORDER_TYPE_CLOSE_SHORT, false, remainCount, entryElem);
            if (detail.length() > 0) {
                detail.append("  ");
            }
            detail.append(sgId).append("x").append(remainder);
        }
        log.info("[Gate] 空仓追挂止损, 成交{}张, gridId:{}, 网格数:{}, 分配:{}",
                filledQty, gridId, gridCount, detail);
        int slSize = Math.max(filledQty, Integer.parseInt(config.getBaseQuantity()));
        AtomicInteger remainCount = new AtomicInteger(1);
        int sgId = gridId + 2;
        placeStopLossOrders(sgId, 1, String.valueOf(slSize), FuturesPriceTrigger.RuleEnum.NUMBER_1,
                ORDER_TYPE_CLOSE_SHORT, false, remainCount, entryElem);
        log.info("[Gate] 空仓追挂止损, 成交{}张, gridId:{}, 单位置全量止损:{}x{}张",
                filledQty, gridId, sgId, slSize);
    }
    /**
@@ -3190,6 +3383,20 @@
                                } else {
                                    reExtendShortStopLoss(entryElement);
                                }
                            }
                        }
                    },
                    () -> {
                        // 挂单最终失败(已取消市价兜底):重置防重入标记,避免卡死后续重挂;
                        // 对账兜底/下一轮业务触发会重新挂单
                        log.warn("[Gate] {}止损挂单失败(放弃), gridId:{}, 等待后续重挂",
                                isLong ? "多仓" : "空仓", gridId);
                        if (remainCount != null) {
                            remainCount.decrementAndGet();
                            if (remainCount.get() <= 0 && entryElement != null) {
                                entryElement.setExtendStopLossInProgress(false);
                                log.warn("[Gate] {}止损追单失败, entryGridId:{}, 防重入标记已重置",
                                        isLong ? "多仓" : "空仓", entryElement.getId());
                            }
                        }
                    }
@@ -3359,48 +3566,18 @@
    /**
     * 手动重新生成多仓止盈 + 止损挂单,逻辑与挂单成交(onAutoOrder)一致:
     * 先撤多仓所有止盈止损,再按交易所最新持仓重挂止损阶梯,超额部分挂止盈到空仓第一止损位。
     * 先撤多仓所有止盈止损,再按交易所最新持仓重挂单位置全量止损,超额部分挂止盈到空仓第一止损位。
     */
    public void rebuildLongTakeProfitAndStopLoss() {
        submitManualTask(() -> {
            cancelAllLongTakeProfitsAndStopLosses();
            int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue());
            if (posSize <= 0) {
                log.warn("[Gate] 生成多仓止盈止损失败:无多仓持仓");
                return;
            }
            extendLongStopLoss(posSize, 0);
            if (GateConfig.EXCESS_TP_CONCENTRATED.equals(config.getPlaceExcessTakeProfit())) {
                placeExcessTakeProfit(posSize, true);
            } else if (GateConfig.EXCESS_TP_DISPERSED.equals(config.getPlaceExcessTakeProfit())) {
                placeDispersedTakeProfit(posSize, true, 0);
            }
            placeBaseTakeProfit(posSize, true, 0);
            log.info("[Gate] 生成多仓止盈止损完成, 仓位:{}张", posSize);
        });
        submitManualTask(this::rebuildLongProtection);
    }
    /**
     * 手动重新生成空仓止盈 + 止损挂单,逻辑与挂单成交(onAutoOrder)一致:
     * 先撤空仓所有止盈止损,再按交易所最新持仓重挂止损阶梯,超额部分挂止盈到多仓第一止损位。
     * 先撤空仓所有止盈止损,再按交易所最新持仓重挂单位置全量止损,超额部分挂止盈到多仓第一止损位。
     */
    public void rebuildShortTakeProfitAndStopLoss() {
        submitManualTask(() -> {
            cancelAllShortTakeProfitsAndStopLosses();
            int posSize = Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue());
            if (posSize <= 0) {
                log.warn("[Gate] 生成空仓止盈止损失败:无空仓持仓");
                return;
            }
            extendShortStopLoss(posSize, 0);
            if (GateConfig.EXCESS_TP_CONCENTRATED.equals(config.getPlaceExcessTakeProfit())) {
                placeExcessTakeProfit(posSize, false);
            } else if (GateConfig.EXCESS_TP_DISPERSED.equals(config.getPlaceExcessTakeProfit())) {
                placeDispersedTakeProfit(posSize, false, 0);
            }
            placeBaseTakeProfit(posSize, false, 0);
            log.info("[Gate] 生成空仓止盈止损完成, 仓位:{}张", posSize);
        });
        submitManualTask(this::rebuildShortProtection);
    }
    /**
@@ -3517,8 +3694,16 @@
     * 取消所有多仓入场单(条件开仓单),并清空 GridElement 的多仓挂单记录。
     */
    private void cancelAllLongEntryOrders() {
        longSlReentryGridId = Integer.MIN_VALUE;
        for (GridElement e : config.getGridElements()) {
            // 注意:不再跳过 grid 0——价格驱动/补仓/对向加仓会在 grid 0 挂条件开仓单,
            // 若跳过会导致止损全扫撤不掉 grid 0 的条件单,与追单并存形成双仓位。
            // 基底市价单不注册在 *OrderIds 里,遍历无副作用。
            for (String oid : new ArrayList<>(e.getLongOrderIds())) {
                // 同步清理对向加仓/补仓/加仓标记登记表,避免残留失效记录
                tpOppositeLongOrderGridMap.remove(oid);
                tpReplenishLongOrderMap.remove(oid);
                pendingAddEntryOrderIds.remove(oid);
                executor.cancelConditionalOrder(oid, o -> {});
            }
            e.getLongTraderParam().setEntryOrderId(null);
@@ -3534,8 +3719,16 @@
     * 取消所有空仓入场单(条件开仓单),并清空 GridElement 的空仓挂单记录。
     */
    private void cancelAllShortEntryOrders() {
        shortSlReentryGridId = Integer.MIN_VALUE;
        for (GridElement e : config.getGridElements()) {
            // 注意:不再跳过 grid 0——价格驱动/补仓/对向加仓会在 grid 0 挂条件开仓单,
            // 若跳过会导致止损全扫撤不掉 grid 0 的条件单,与追单并存形成双仓位。
            // 基底市价单不注册在 *OrderIds 里,遍历无副作用。
            for (String oid : new ArrayList<>(e.getShortOrderIds())) {
                // 同步清理对向加仓/补仓/加仓标记登记表,避免残留失效记录
                tpOppositeShortOrderGridMap.remove(oid);
                tpReplenishShortOrderMap.remove(oid);
                pendingAddEntryOrderIds.remove(oid);
                executor.cancelConditionalOrder(oid, o -> {});
            }
            e.getShortTraderParam().setEntryOrderId(null);
@@ -3728,31 +3921,35 @@
    }
    /**
     * 基础止盈:对基础仓位(baseQuantity)也挂止盈单,与超额止盈并行。
     * 基础止盈:对基础仓位挂止盈单,与超额止盈并行(原始仓位止盈挂单优化)。
     *
     * <p>规则:从入场网格下一格(entryGridId ± 1)开始,每格 baseTakeProfitPerGrid 张,
     * 最多挂 baseTakeProfitGridCount 格,挂到止损位前 2 格截止(即对手盘仓位线)。
     * <p>规则:
     * <ol>
     *   <li>总数量 = {@code baseTakeProfitTotalQty}(原始仓位止盈总数量);</li>
     *   <li>网格范围:从入场网格下一格(entryGridId ± 1,起始位置不变)
     *       一直挂到<b>对手盘止损位的前一个格子</b>;</li>
     *   <li>每格数量 = 总数量 ÷ 网格数平均分配,余数挂在最后一个格子;
     *       每格最少 1 张,总量不够网格数时从起始格开始各挂 1 张(挂到哪算哪)。</li>
     * </ol>
     *
     * <p>边界:累计张数到 min(baseQuantity, 当前持仓) 即停(张数不足则最后一格挂剩余 = "挂几个算几个");
     * 网格不足时挂到停止位置结束。
     * <p>张数硬上限 = min(设置总量, baseQuantity, 当前持仓),避免持仓不足时超挂。
     *
     * @param posSize     当前总持仓张数
     * @param isLong      true=多仓止盈,false=空仓止盈
     * @param entryGridId 入场网格 ID
     */
    private void placeBaseTakeProfit(int posSize, boolean isLong, int entryGridId) {
        BigDecimal perGrid = config.getBaseTakeProfitPerGrid();
        int gridCount = config.getBaseTakeProfitGridCount();
        if (perGrid == null || perGrid.compareTo(BigDecimal.ZERO) <= 0 || gridCount <= 0) {
        int totalQty = config.getBaseTakeProfitTotalQty();
        if (totalQty <= 0) {
            return;
        }
        int baseQty = Integer.parseInt(config.getBaseQuantity());
        if (baseQty <= 0) {
            return;
        }
        // 张数硬上限 = min(基础张数, 当前持仓),避免持仓不足 baseQuantity 时超挂
        int maxQty = Math.min(baseQty, posSize);
        if (maxQty <= 0) {
        // 张数硬上限 = min(设置总量, 基础张数, 当前持仓),避免持仓不足 baseQuantity 时超挂
        totalQty = Math.min(totalQty, Math.min(baseQty, posSize));
        if (totalQty <= 0) {
            return;
        }
@@ -3763,13 +3960,12 @@
        }
        int dir = isLong ? 1 : -1;
        int startId = entryGridId + dir;
        // 分配范围到止损位前 2 格截止(即对手盘仓位线)
        int endId = endElem.getId() - 2 * dir;
        // 一直挂到对手盘止损位的前一个格子
        int endId = endElem.getId() - dir;
        BigDecimal remaining = BigDecimal.valueOf(maxQty);
        int placed = 0;
        int id = startId;
        while (placed < gridCount && remaining.compareTo(BigDecimal.ZERO) > 0) {
        // 收集范围内所有网格(安全上限防异常数据长循环)
        List<GridElement> gridList = new ArrayList<>();
        for (int id = startId; ; id += dir) {
            if (isLong ? id > endId : id < endId) {
                break;
            }
@@ -3777,12 +3973,36 @@
            if (elem == null) {
                break;
            }
            BigDecimal qty = perGrid.min(remaining);
            final int fqty = qty.intValue();
            gridList.add(elem);
            if (gridList.size() > config.getGridQueueSize() * 2 + 4) {
                break;
            }
        }
        if (gridList.isEmpty()) {
            return;
        }
        int n = gridList.size();
        int perGrid = totalQty / n;
        int remainder = totalQty % n;
        for (int i = 0; i < n; i++) {
            int qty;
            if (totalQty < n) {
                // 总量不够铺满:每格至少 1 张,从起始格开始挂 totalQty 格,挂到哪算哪
                qty = (i < totalQty) ? 1 : 0;
            } else {
                // 平均分配,余数挂在最后一个格子(最靠近对手盘止损位的那格)
                qty = perGrid + (i == n - 1 ? remainder : 0);
            }
            if (qty <= 0) {
                continue;
            }
            GridElement elem = gridList.get(i);
            final int fqty = qty;
            final GridElement fe = elem;
            final int gid = id;
            final int gid = elem.getId();
            final BigDecimal triggerPrice = elem.getGridPrice();
            final String size = isLong ? negate(qty.toPlainString()) : qty.toPlainString();
            final String size = isLong ? negate(String.valueOf(qty)) : String.valueOf(qty);
            final String orderType = isLong ? ORDER_TYPE_CLOSE_LONG : ORDER_TYPE_CLOSE_SHORT;
            final FuturesPriceTrigger.RuleEnum rule = isLong ? FuturesPriceTrigger.RuleEnum.NUMBER_1
                    : FuturesPriceTrigger.RuleEnum.NUMBER_2;
@@ -3797,12 +4017,9 @@
                                isLong ? "多仓" : "空仓", gid, triggerPrice, size, profitId);
                    }
            );
            remaining = remaining.subtract(qty);
            placed++;
            id += dir;
        }
        log.info("[Gate] 基础止盈 {} 挂单完成, 入场gridId:{}, 挂{}格, 剩余{}张",
                isLong ? "多仓" : "空仓", entryGridId, placed, remaining);
        log.info("[Gate] 基础止盈 {} 挂单完成, 入场gridId:{}, 网格数:{}, 总量:{}张, 每格:{}张, 余数:{}张",
                isLong ? "多仓" : "空仓", entryGridId, n, totalQty, perGrid, remainder);
    }
    /**