Administrator
2026-11-05 b5f0ae706cbbd0b87d4e878abf1317f9839da5bd
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -201,7 +201,7 @@
    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)
@@ -268,7 +268,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();
@@ -2302,30 +2302,28 @@
    /** 多仓仓位归零后,在当前价上方最近网格重新挂多单(遍历 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;
                    break;
                }
            }
//            log.info("[Gate-1] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
            if (BigDecimal.ZERO.compareTo( matched) == 0) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null){
                if (!matchedUpGridElement.isHasLongOrder()){
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasLongOrder()) {
                    Integer upId = matchedUpGridElement.getUpId();
                    GridElement newEntryGrid = GridElement.findById(upId);
                newEntryGrid = GridElement.findById(upId);
                    if (newEntryGrid != null) {
                        String quantity = calculateEntryQuantity(true, false, 0);
                        // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
                        boolean hasLongOrderBelow = false;
                        GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
                        while (checkDownCursor != null) {
                            if (checkDownCursor.isHasLongOrder()) {
@@ -2353,19 +2351,35 @@
                            Integer nextUpId = cancelCursor.getUpId();
                            cancelCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                        }
//                        log.info("[Gate-2] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                        if (!newEntryGrid.isHasLongOrder() && !hasLongOrderBelow) {
                }
            }
        }
        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
        if (newEntryGrid == null || newEntryGrid.isHasLongOrder() || hasLongOrderBelow) {
            return;
        }
                            // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
                            // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍(历史出现过 68→136 张)
                            int realPos = queryPositionSize(Position.ModeEnum.DUAL_LONG);
        // 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 = quantity;
        String size = calculateEntryQuantity(true, false, 0);
                            log.info("[Gate] 多仓仓位归零 gridId:{}, 挂{}张多单",
                                    newEntryGrid.getId(), size);
                            newEntryGrid.getLongTraderParam().setQuantity(size);
@@ -2375,39 +2389,31 @@
                                    FuturesPriceTrigger.RuleEnum.NUMBER_1, 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) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null){
                if(!matchedUpGridElement.isHasShortOrder()){
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasShortOrder()) {
                    Integer downId = matchedUpGridElement.getDownId();
                    GridElement newEntryGrid = GridElement.findById(downId);
                newEntryGrid = GridElement.findById(downId);
                    if (newEntryGrid != null) {
                        String quantity = calculateEntryQuantity(false, false, 0);
                        // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
                        boolean hasShortOrderAbove = false;
                        GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
                        while (checkUpCursor != null) {
                            if (checkUpCursor.isHasShortOrder()) {
@@ -2435,19 +2441,35 @@
                            Integer nextDownId = cancelCursor.getDownId();
                            cancelCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                        }
//                        log.info("[Gate-4] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                        if (!newEntryGrid.isHasShortOrder() && !hasShortOrderAbove){
                }
            }
        }
        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
        if (newEntryGrid == null || newEntryGrid.isHasShortOrder() || hasShortOrderAbove) {
            return;
        }
                            // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
                            // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍
                            int realPos = queryPositionSize(Position.ModeEnum.DUAL_SHORT);
        // 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 = quantity;
        String size = calculateEntryQuantity(false, false, 0);
                            log.info("[Gate] 空仓仓位归零 gridId:{}, 挂{}张空单",
                                    newEntryGrid.getId(), size);
                            newEntryGrid.getShortTraderParam().setQuantity(size);
@@ -2456,12 +2478,6 @@
                            placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
                                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
                                    hasAdd ? pendingAddEntryOrderIds::add : null);
                        }
                    }
                }
            }
        }
    }
    // ========== 加仓计算 ==========