Administrator
20 hours ago 025c66091b6b6903b5e830c5bde981fdbacbc744
src/main/java/com/xcong/excoin/modules/okxApi/OkxGridTradeService.java
@@ -17,9 +17,11 @@
        WAITING_KLINE, OPENING, ACTIVE, STOPPED
    }
    private static final String ORDER_TYPE_CLOSE_LONG = "plan-close-long-position";
    private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position";
    private final OkxConfig config;
    private final OkxTradeExecutor executor;
    private final String accountName;
    private volatile StrategyState state = StrategyState.WAITING_KLINE;
@@ -41,21 +43,18 @@
    private volatile BigDecimal longPositionSize = BigDecimal.ZERO;
    private volatile BigDecimal shortPositionSize = BigDecimal.ZERO;
    private volatile WebSocketClient wsClient;
    public OkxGridTradeService(OkxConfig config, String accountName) {
        this.config = config;
        this.accountName = accountName;
        this.executor = new OkxTradeExecutor(config, accountName);
        this.executor = new OkxTradeExecutor(config.getContract(), config.getMarginMode(), accountName);
    }
    public void setWebSocketClient(WebSocketClient wsClient) {
        this.wsClient = wsClient;
        this.executor.setWebSocketClient(wsClient);
    }
    public void startGrid() {
        if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) {
            log.warn("[{}] 策略已在运行中, state:{}", accountName, state);
            log.warn("[{}] 策略已在运行中, state:{}", config.getContract(), state);
            return;
        }
        state = StrategyState.WAITING_KLINE;
@@ -71,19 +70,17 @@
        shortActive = false;
        shortPriceQueue.clear();
        longPriceQueue.clear();
        log.info("[{}] 网格策略已启动", accountName);
        log.info("[{}] 网格策略已启动", config.getContract());
    }
    public void stopGrid() {
        state = StrategyState.STOPPED;
        executor.cancelAllPriceTriggeredOrders();
        executor.shutdown();
        log.info("[{}] 策略已停止, 累计盈亏: {}", accountName, cumulativePnl);
        log.info("[{}] 策略已停止, 累计盈亏: {}", config.getContract(), cumulativePnl);
    }
    public void onKline(BigDecimal closePrice) {
        if (wsClient == null || !wsClient.isOpen()) {
            return;
        }
        lastKlinePrice = closePrice;
        updateUnrealizedPnl();
        if (state == StrategyState.STOPPED) {
@@ -92,9 +89,13 @@
        if (state == StrategyState.WAITING_KLINE) {
            state = StrategyState.OPENING;
            log.info("[{}] 首根K线到达,开基底仓位...", accountName);
            executor.openLong(wsClient, () -> log.info("[{}] 基底多单已发送", accountName));
            executor.openShort(wsClient, () -> log.info("[{}] 基底空单已发送", accountName));
            log.info("[{}] 首根K线到达,开基底仓位...", config.getContract());
            executor.openLong(config.getQuantity(), () -> {
                log.info("[{}] 基底多单已提交", config.getContract());
            }, null);
            executor.openShort(config.getQuantity(), () -> {
                log.info("[{}] 基底空单已提交", config.getContract());
            }, null);
            return;
        }
@@ -120,13 +121,17 @@
                    longPositionSize = size;
                    longBaseEntryPrice = entryPrice;
                    baseLongOpened = true;
                    log.info("[{}] 基底多成交价: {}", accountName, longBaseEntryPrice);
                    log.info("[{}] 基底多成交价: {}", config.getContract(), longBaseEntryPrice);
                    tryGenerateQueues();
                } else if (size.compareTo(longPositionSize) > 0) {
                    longPositionSize = size;
                    BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.add(config.getGridRate())).setScale(1, RoundingMode.HALF_UP);
                    executor.placeTakeProfit(wsClient, OkxEnums.POSSIDE_LONG, tpPrice, config.getQuantity());
                    log.info("[{}] 多单止盈已设, entry:{}, tp:{}", accountName, entryPrice, tpPrice);
                    if (longPriceQueue.isEmpty()) {
                        log.warn("[{}] 多仓队列为空,无法设止盈", config.getContract());
                    } else {
                        BigDecimal tpPrice = longPriceQueue.get(0);
                        executor.placeTakeProfit(tpPrice, ORDER_TYPE_CLOSE_LONG, config.getQuantity());
                        log.info("[{}] 多单止盈已设, entry:{}, tp:{}, size:{}", config.getContract(), entryPrice, tpPrice, config.getQuantity());
                    }
                } else {
                    longPositionSize = size;
                }
@@ -142,13 +147,17 @@
                    shortPositionSize = size;
                    shortBaseEntryPrice = entryPrice;
                    baseShortOpened = true;
                    log.info("[{}] 基底空成交价: {}", accountName, shortBaseEntryPrice);
                    log.info("[{}] 基底空成交价: {}", config.getContract(), shortBaseEntryPrice);
                    tryGenerateQueues();
                } else if (size.compareTo(shortPositionSize) > 0) {
                    shortPositionSize = size;
                    BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate())).setScale(1, RoundingMode.HALF_UP);
                    executor.placeTakeProfit(wsClient, OkxEnums.POSSIDE_SHORT, tpPrice, config.getQuantity());
                    log.info("[{}] 空单止盈已设, entry:{}, tp:{}", accountName, entryPrice, tpPrice);
                    if (shortPriceQueue.isEmpty()) {
                        log.warn("[{}] 空仓队列为空,无法设止盈", config.getContract());
                    } else {
                        BigDecimal tpPrice = shortPriceQueue.get(0);
                        executor.placeTakeProfit(tpPrice, ORDER_TYPE_CLOSE_SHORT, config.getQuantity());
                        log.info("[{}] 空单止盈已设, entry:{}, tp:{}, size:{}", config.getContract(), entryPrice, tpPrice, config.getQuantity());
                    }
                } else {
                    shortPositionSize = size;
                }
@@ -164,13 +173,13 @@
            return;
        }
        cumulativePnl = cumulativePnl.add(pnl);
        log.info("[{}] 订单成交盈亏: {}, 方向:{}, 累计:{}", accountName, pnl, posSide, cumulativePnl);
        log.info("[{}] 订单成交盈亏: {}, 方向:{}, 累计:{}", config.getContract(), pnl, posSide, cumulativePnl);
        if (cumulativePnl.compareTo(config.getOverallTp()) >= 0) {
            log.info("[{}] 已达止盈目标 {}→已停止", accountName, cumulativePnl);
            log.info("[{}] 已达止盈目标 {}→已停止", config.getContract(), cumulativePnl);
            state = StrategyState.STOPPED;
        } else if (cumulativePnl.compareTo(config.getMaxLoss().negate()) <= 0) {
            log.info("[{}] 已达亏损上限 {}→已停止", accountName, cumulativePnl);
            log.info("[{}] 已达亏损上限 {}→已停止", config.getContract(), cumulativePnl);
            state = StrategyState.STOPPED;
        }
    }
@@ -181,7 +190,7 @@
            generateLongQueue();
            state = StrategyState.ACTIVE;
            log.info("[{}] 网格队列已生成, 空队首:{} → 尾:{}, 多队首:{} → 尾:{}, 已激活",
                    accountName,
                    config.getContract(),
                    shortPriceQueue.isEmpty() ? "N/A" : shortPriceQueue.get(0),
                    shortPriceQueue.isEmpty() ? "N/A" : shortPriceQueue.get(shortPriceQueue.size() - 1),
                    longPriceQueue.isEmpty() ? "N/A" : longPriceQueue.get(0),
@@ -196,7 +205,7 @@
            shortPriceQueue.add(shortBaseEntryPrice.multiply(BigDecimal.ONE.subtract(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP));
        }
        shortPriceQueue.sort((a, b) -> b.compareTo(a));
        log.info("[{}] 空队列:{}", accountName, shortPriceQueue);
        log.info("[{}] 空队列:{}", config.getContract(), shortPriceQueue);
    }
    private void generateLongQueue() {
@@ -206,7 +215,7 @@
            longPriceQueue.add(longBaseEntryPrice.multiply(BigDecimal.ONE.add(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP));
        }
        longPriceQueue.sort(BigDecimal::compareTo);
        log.info("[{}] 多队列:{}", accountName, longPriceQueue);
        log.info("[{}] 多队列:{}", config.getContract(), longPriceQueue);
    }
    /**
@@ -219,10 +228,10 @@
     * <h3>执行流程</h3>
     * <ol>
     *   <li>匹配队列元素 → 为空则直接返回</li>
     *   <li>保证金检查 → 安全则开空一次</li>
     *   <li>额外反向开多:若多仓均价 > 空仓均价 且 当前价夹在中间且远离多仓均价</li>
     *   <li>空仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 − gridRate) 循环递减)</li>
     *   <li>多仓队列:以多仓队列首元素(最小价)为种子,生成 matched.size() 个递减元素加入</li>
     *   <li>保证金检查 → 安全则开空一次</li>
     *   <li>额外反向开多:若多仓均价 > 空仓均价 且 当前价夹在中间且远离多仓均价</li>
     * </ol>
     *
     * <h3>多仓队列转移过滤</h3>
@@ -239,23 +248,12 @@
                }
            }
        }
        log.info("[{}] 原空队列:{}", config.getContract(), shortPriceQueue);
        if (matched.isEmpty()) {
            log.info("[{}] 空仓队列未触发, 当前价:{}", config.getContract(), currentPrice);
            return;
        }
        log.info("[{}] 空仓队列触发, 匹配{}个元素, 当前价:{}", accountName, matched.size(), currentPrice);
        if (!isMarginSafe()) {
            log.warn("[{}] 保证金超限,跳过空单开仓", accountName);
        } else {
            executor.openShort(wsClient, null);
            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(shortEntryPrice) > 0
                    && currentPrice.compareTo(shortEntryPrice) > 0
                    && currentPrice.compareTo(longEntryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate()))) < 0) {
                executor.openLong(wsClient, null);
                log.info("[{}] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", accountName, currentPrice);
            }
        }
        log.info("[{}] 空仓队列触发, 匹配{}个元素, 当前价:{}", config.getContract(), matched.size(), currentPrice);
        synchronized (shortPriceQueue) {
            shortPriceQueue.removeAll(matched);
@@ -264,8 +262,10 @@
            for (int i = 0; i < matched.size(); i++) {
                min = min.multiply(BigDecimal.ONE.subtract(step)).setScale(1, RoundingMode.HALF_UP);
                shortPriceQueue.add(min);
                log.info("[{}] 空队列增加:{}", config.getContract(), min);
            }
            shortPriceQueue.sort((a, b) -> b.compareTo(a));
            log.info("[{}] 现空队列:{}", config.getContract(), shortPriceQueue);
        }
        synchronized (longPriceQueue) {
@@ -275,13 +275,30 @@
                BigDecimal elem = first.multiply(BigDecimal.ONE.subtract(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP);
                if (longEntryPrice.compareTo(BigDecimal.ZERO) > 0
                        && currentPrice.subtract(longEntryPrice).abs().compareTo(longEntryPrice.multiply(step)) < 0) {
                    log.info("[{}] 多队列跳过(price≈longEntry):{}", config.getContract(), elem);
                    continue;
                }
                longPriceQueue.add(elem);
                log.info("[{}] 多队列增加:{}", config.getContract(), elem);
            }
            longPriceQueue.sort(BigDecimal::compareTo);
            while (longPriceQueue.size() > config.getGridQueueSize()) {
                longPriceQueue.remove(longPriceQueue.size() - 1);
            }
            log.info("[{}] 现多队列:{}", config.getContract(), longPriceQueue);
        }
        if (!isMarginSafe()) {
            log.warn("[{}] 保证金超限,跳过空单开仓", config.getContract());
        } else {
            executor.openShort(config.getQuantity(), null, null);
            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(shortEntryPrice) > 0
                    && currentPrice.compareTo(shortEntryPrice) > 0
                    && currentPrice.compareTo(longEntryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate()))) < 0) {
                executor.openLong(config.getQuantity(), null, null);
                log.info("[{}] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", config.getContract(), currentPrice);
            }
        }
    }
@@ -296,10 +313,10 @@
     * <h3>执行流程</h3>
     * <ol>
     *   <li>匹配队列元素 → 为空则直接返回</li>
     *   <li>保证金检查 → 安全则开多一次</li>
     *   <li>额外反向开空:若多仓均价 > 空仓均价 且 当前价夹在中间且远离空仓均价</li>
     *   <li>多仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 + gridRate) 循环递增)</li>
     *   <li>空仓队列:以空仓队列首元素(最高价)为种子,生成 matched.size() 个递增元素加入</li>
     *   <li>保证金检查 → 安全则开多一次</li>
     *   <li>额外反向开空:若多仓均价 > 空仓均价 且 当前价夹在中间且远离空仓均价</li>
     * </ol>
     *
     * <h3>空仓队列转移过滤</h3>
@@ -316,23 +333,12 @@
                }
            }
        }
        log.info("[{}] 原多队列:{}", config.getContract(), longPriceQueue);
        if (matched.isEmpty()) {
            log.info("[{}] 多仓队列未触发, 当前价:{}", config.getContract(), currentPrice);
            return;
        }
        log.info("[{}] 多仓队列触发, 匹配{}个元素, 当前价:{}", accountName, matched.size(), currentPrice);
        if (!isMarginSafe()) {
            log.warn("[{}] 保证金超限,跳过多单开仓", accountName);
        } else {
            executor.openLong(wsClient, null);
            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(shortEntryPrice) > 0
                    && currentPrice.compareTo(shortEntryPrice.multiply(BigDecimal.ONE.add(config.getGridRate()))) > 0
                    && currentPrice.compareTo(longEntryPrice) < 0) {
                executor.openShort(wsClient, null);
                log.info("[{}] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", accountName, currentPrice);
            }
        }
        log.info("[{}] 多仓队列触发, 匹配{}个元素, 当前价:{}", config.getContract(), matched.size(), currentPrice);
        synchronized (longPriceQueue) {
            longPriceQueue.removeAll(matched);
@@ -341,8 +347,10 @@
            for (int i = 0; i < matched.size(); i++) {
                max = max.multiply(BigDecimal.ONE.add(step)).setScale(1, RoundingMode.HALF_UP);
                longPriceQueue.add(max);
                log.info("[{}] 多队列增加:{}", config.getContract(), max);
            }
            longPriceQueue.sort(BigDecimal::compareTo);
            log.info("[{}] 现多队列:{}", config.getContract(), longPriceQueue);
        }
        synchronized (shortPriceQueue) {
@@ -352,13 +360,30 @@
                BigDecimal elem = first.multiply(BigDecimal.ONE.add(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP);
                if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
                        && currentPrice.subtract(shortEntryPrice).abs().compareTo(shortEntryPrice.multiply(step)) < 0) {
                    log.info("[{}] 空队列跳过(price≈shortEntry):{}", config.getContract(), elem);
                    continue;
                }
                shortPriceQueue.add(elem);
                log.info("[{}] 空队列增加:{}", config.getContract(), elem);
            }
            shortPriceQueue.sort((a, b) -> b.compareTo(a));
            while (shortPriceQueue.size() > config.getGridQueueSize()) {
                shortPriceQueue.remove(shortPriceQueue.size() - 1);
            }
            log.info("[{}] 现空队列:{}", config.getContract(), shortPriceQueue);
        }
        if (!isMarginSafe()) {
            log.warn("[{}] 保证金超限,跳过多单开仓", config.getContract());
        } else {
            executor.openLong(config.getQuantity(), null, null);
            if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(BigDecimal.ZERO) > 0
                    && longEntryPrice.compareTo(shortEntryPrice) > 0
                    && currentPrice.compareTo(shortEntryPrice.multiply(BigDecimal.ONE.add(config.getGridRate()))) > 0
                    && currentPrice.compareTo(longEntryPrice) < 0) {
                executor.openShort(config.getQuantity(), null, null);
                log.info("[{}] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", config.getContract(), currentPrice);
            }
        }
    }
@@ -390,6 +415,7 @@
            shortPnl = shortPositionSize.multiply(multiplier).multiply(shortEntryPrice.subtract(price));
        }
        unrealizedPnl = longPnl.add(shortPnl);
        log.info("[{}] 未实现盈亏: {}", config.getContract(), unrealizedPnl);
    }
    public BigDecimal getLastKlinePrice() { return lastKlinePrice; }
@@ -397,5 +423,5 @@
    public BigDecimal getCumulativePnl() { return cumulativePnl; }
    public BigDecimal getUnrealizedPnl() { return unrealizedPnl; }
    public StrategyState getState() { return state; }
    public String getAccountName() { return accountName; }
    public String getAccountName() { return config.getContract(); }
}