Administrator
7 days ago b04ced3a372ad561b75066f668abfdae58ca20b3
src/main/java/com/xcong/excoin/modules/okxNewPrice/OkxNewPriceWebSocketClient.java
@@ -3,20 +3,24 @@
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcong.excoin.rabbit.pricequeue.WebsocketPriceService;
import com.xcong.excoin.utils.CoinTypeConvert;
import com.xcong.excoin.modules.okxNewPrice.celue.CaoZuoService;
import com.xcong.excoin.modules.okxNewPrice.okxWs.TradeOrderWs;
import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.CoinEnums;
import com.xcong.excoin.modules.okxNewPrice.okxWs.param.TradeRequestParam;
import com.xcong.excoin.modules.okxNewPrice.okxWs.wanggeList.WangGeListEnum;
import com.xcong.excoin.modules.okxNewPrice.okxWs.wanggeList.WangGeListService;
import com.xcong.excoin.modules.okxNewPrice.utils.SSLConfig;
import com.xcong.excoin.utils.RedisUtils;
import java.math.BigDecimal;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
@@ -26,24 +30,23 @@
 * @author Administrator
 */
@Slf4j
@Component
public class OkxNewPriceWebSocketClient {
    @Resource
    private WebsocketPriceService websocketPriceService;
    @Resource
    private RedisUtils redisUtils;
    private final RedisUtils redisUtils;
    private final CaoZuoService caoZuoService;
    private final OkxWebSocketClientManager clientManager;
    private final WangGeListService wangGeListService;
    private WebSocketClient webSocketClient;
    private ScheduledExecutorService heartbeatExecutor;
    private volatile ScheduledFuture<?> pongTimeoutFuture;
    private final AtomicReference<Long> lastMessageTime = new AtomicReference<>(System.currentTimeMillis());
    private static final String WS_URL = "wss://ws.okx.com:8443/ws/v5/public";
    private static final String CHANNEL = "mark-price";
    // 连接状态标志
    private final AtomicBoolean isConnected = new AtomicBoolean(false);
    private final AtomicBoolean isConnecting = new AtomicBoolean(false);
    private final AtomicBoolean isInitialized = new AtomicBoolean(false);
    private static final String[] INST_IDS = {
            "BTC-USDT", "ETH-USDT", "XRP-USDT", "LTC-USDT", "BCH-USDT", "ETC-USDT"
    };
    private static final String CHANNEL = "mark-price";
    // 心跳超时时间(秒),小于30秒
    private static final int HEARTBEAT_TIMEOUT = 10;
@@ -55,47 +58,109 @@
        return t;
    });
    public OkxNewPriceWebSocketClient(RedisUtils redisUtils,
                                      CaoZuoService caoZuoService, OkxWebSocketClientManager clientManager,
                                      WangGeListService wangGeListService) {
        this.redisUtils = redisUtils;
        this.caoZuoService = caoZuoService;
        this.clientManager = clientManager;
        this.wangGeListService = wangGeListService;
    }
    /**
     * 初始化方法,在 Spring Bean 构造完成后执行。
     * 负责建立 WebSocket 连接并启动心跳检测任务。
     * 初始化方法,创建并初始化WebSocket客户端实例
     */
    @PostConstruct
    public void init() {
        if (!isInitialized.compareAndSet(false, true)) {
            log.warn("OkxNewPriceWebSocketClient 已经初始化过,跳过重复初始化");
            return;
        }
        connect();
        startHeartbeat();
    }
    /**
     * 销毁方法,在 Spring Bean 销毁前执行。
     * 关闭 WebSocket 连接、停止心跳定时器及相关的线程资源。
     * 销毁方法,关闭WebSocket连接和相关资源
     */
    @PreDestroy
    public void destroy() {
        log.info("开始销毁OkxNewPriceWebSocketClient");
        // 设置关闭标志,避免重连
        if (sharedExecutor != null && !sharedExecutor.isShutdown()) {
            sharedExecutor.shutdown();
        }
        if (webSocketClient != null && webSocketClient.isOpen()) {
            webSocketClient.close();
            try {
                webSocketClient.closeBlocking();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warn("关闭WebSocket连接时被中断");
            }
        }
        if (heartbeatExecutor != null) {
            heartbeatExecutor.shutdownNow();
        }
        shutdownExecutorGracefully(heartbeatExecutor);
        if (pongTimeoutFuture != null) {
            pongTimeoutFuture.cancel(true);
        }
        sharedExecutor.shutdownNow();
        shutdownExecutorGracefully(sharedExecutor);
        log.info("OkxNewPriceWebSocketClient销毁完成");
    }
    private static final String WS_URL_MONIPAN = "wss://wspap.okx.com:8443/ws/v5/public";
    private static final String WS_URL_SHIPAN = "wss://ws.okx.com:8443/ws/v5/public";
    private static final boolean isAccountType = true;
    /**
     * 建立与 OKX WebSocket 服务器的连接。
     * 设置回调函数以监听连接打开、接收消息、关闭和错误事件。
     */
    private void connect() {
        // 避免重复连接
        if (isConnecting.get()) {
            log.info("连接已在进行中,跳过重复连接请求");
            return;
        }
        if (!isConnecting.compareAndSet(false, true)) {
            log.info("连接已在进行中,跳过重复连接请求");
            return;
        }
        try {
            SSLConfig.configureSSL();
            System.setProperty("https.protocols", "TLSv1.2,TLSv1.3");
            String WS_URL = WS_URL_MONIPAN;
            if (isAccountType){
                WS_URL = WS_URL_SHIPAN;
            }
            URI uri = new URI(WS_URL);
            // 关闭之前的连接(如果存在)
            if (webSocketClient != null) {
                try {
                    webSocketClient.closeBlocking();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.warn("关闭之前连接时被中断");
                }
            }
            webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshake) {
                    log.info("OKX New Price WebSocket连接成功");
                    resetHeartbeatTimer();
                    subscribeChannels();
                    isConnected.set(true);
                    isConnecting.set(false);
                    // 检查应用是否正在关闭
                    if (sharedExecutor != null && !sharedExecutor.isShutdown()) {
                        resetHeartbeatTimer();
                        subscribeChannels();
                    } else {
                        log.warn("应用正在关闭,忽略WebSocket连接成功回调");
                    }
                }
                @Override
@@ -108,28 +173,37 @@
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.warn("OKX New Price WebSocket连接关闭: code={}, reason={}", code, reason);
                    isConnected.set(false);
                    isConnecting.set(false);
                    cancelPongTimeout();
                    sharedExecutor.execute(() -> {
                        try {
                            reconnectWithBackoff();
                        } catch (InterruptedException ignored) {
                            Thread.currentThread().interrupt();
                        } catch (Exception e) {
                            log.error("重连失败", e);
                        }
                    });
                    if (sharedExecutor != null && !sharedExecutor.isShutdown() && !sharedExecutor.isTerminated()) {
                        sharedExecutor.execute(() -> {
                            try {
                                reconnectWithBackoff();
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                                log.error("重连线程被中断", e);
                            } catch (Exception e) {
                                log.error("重连失败", e);
                            }
                        });
                    } else {
                        log.warn("共享线程池已关闭,无法执行重连任务");
                    }
                }
                @Override
                public void onError(Exception ex) {
                    log.error("OKX New Price WebSocket发生错误", ex);
                    isConnected.set(false);
                }
            };
            webSocketClient.connect();
        } catch (URISyntaxException e) {
            log.error("WebSocket URI格式错误", e);
            isConnecting.set(false);
        }
    }
@@ -142,12 +216,10 @@
        subscribeMsg.put("op", "subscribe");
        JSONArray argsArray = new JSONArray();
        for (String instId : INST_IDS) {
            JSONObject arg = new JSONObject();
            arg.put("channel", CHANNEL);
            arg.put("instId", instId);
            argsArray.add(arg);
        }
        JSONObject arg = new JSONObject();
        arg.put("channel", CHANNEL);
        arg.put("instId", CoinEnums.HE_YUE.getCode());
        argsArray.add(arg);
        subscribeMsg.put("args", argsArray);
        webSocketClient.send(subscribeMsg.toJSONString());
@@ -184,6 +256,7 @@
    /**
     * 解析并处理价格推送数据。
     * 将最新的标记价格存入 Redis 并触发后续业务逻辑比较处理。
     * 当价格变化时,调用CaoZuoService的caoZuo方法,触发所有账号的量化操作
     *
     * @param response 包含价格数据的 JSON 对象
     */
@@ -196,19 +269,13 @@
                        JSONObject priceData = dataArray.getJSONObject(i);
                        String instId = priceData.getString("instId");
                        String markPx = priceData.getString("markPx");
                        String ts = priceData.getString("ts");
                        // 保存价格到Redis
                        redisUtils.set(CoinEnums.HE_YUE.getCode(), markPx);
                        String redisKey = buildRedisKey(instId);
                        redisUtils.set(redisKey, markPx);
                        String symbol = CoinTypeConvert.okxConvert(instId);
                        if (symbol != null) {
                            redisUtils.set(CoinTypeConvert.convertToKey(symbol), markPx);
                            websocketPriceService.comparePriceAsc(symbol, markPx);
                            websocketPriceService.comparePriceDesc(symbol, markPx);
                        }
                        log.debug("更新最新价格: {} = {}, 时间: {}", redisKey, markPx, ts);
                        log.debug("更新最新价格: {} = {}, 币种: {}", CoinEnums.HE_YUE.getCode(), markPx, instId);
                        // 价格变化时,触发所有账号的量化操作
                        triggerQuantOperations(markPx);
                    } catch (Exception innerEx) {
                        log.warn("处理单条价格数据失败", innerEx);
                    }
@@ -216,6 +283,61 @@
            }
        } catch (Exception e) {
            log.error("处理价格推送数据失败", e);
        }
    }
    /**
     * 触发所有账号的量化操作
     * @param markPx 当前标记价格
     */
    private void triggerQuantOperations(String markPx) {
        try {
            // 1. 判断当前价格属于哪个网格
            WangGeListEnum gridByPriceNew = WangGeListEnum.getGridByPrice(new BigDecimal(markPx));
            if (gridByPriceNew == null) {
                log.error("当前价格{}不在任何网格范围内,无法触发量化操作", markPx);
                return;
            }
            /**
             * 获取当前网格信息
             *      根据当前网格的持仓方向获取反方向是否存在持仓
             *      如果持有,直接止损
             */
            Collection<OkxQuantWebSocketClient> allClients = clientManager.getAllClients();
            //如果为空,则直接返回
            if (allClients.isEmpty()) {
                return;
            }
            // 获取所有OkxQuantWebSocketClient实例
            for (OkxQuantWebSocketClient client : clientManager.getAllClients()) {
                String accountName = client.getAccountName();
                if (accountName != null) {
                    /**
                     * 处理历史网格的订单
                     * 根据历史网格的开单方向,是否需要止损处理
                     *      如果方向一致就不需要处理
                     *      如果不一致则需要处理
                     */
                    String fangXiang = gridByPriceNew.getFang_xiang();
                    String fangXiangOld = CoinEnums.POSSIDE_LONG.getCode().equals(fangXiang) ? CoinEnums.POSSIDE_SHORT.getCode() : CoinEnums.POSSIDE_LONG.getCode();
                    log.info("历史网格方向为:{}", fangXiangOld);
                    if (!fangXiang.equals(fangXiangOld)){
                        TradeRequestParam tradeRequestParamOld = caoZuoService.caoZuoZhiSunEvent(accountName, markPx, fangXiangOld);
                        TradeOrderWs.orderEvent(client.getWebSocketClient(), tradeRequestParamOld);
                    }
                    /**
                     * 处理当前网格的订单,触发量化操作
                     */
                    log.info("当前价格{}属于网格: {}-{}({}-{})", markPx, gridByPriceNew.getName(),gridByPriceNew.getFang_xiang(), gridByPriceNew.getJiage_xiaxian(), gridByPriceNew.getJiage_shangxian());
                    wangGeListService.initWangGe(markPx);
                    TradeRequestParam tradeRequestParam = caoZuoService.caoZuoHandler(accountName, markPx, gridByPriceNew.getFang_xiang());
                    TradeOrderWs.orderEvent(client.getWebSocketClient(), tradeRequestParam);
                    log.info("价格变化触发量化操作: 账号={}, 价格={}",  accountName, markPx);
                }
            }
        } catch (Exception e) {
            log.error("触发量化操作失败", e);
        }
    }
@@ -231,7 +353,7 @@
     * 使用 ScheduledExecutorService 定期检查是否需要发送 ping 请求来维持连接。
     */
    private void startHeartbeat() {
        if (heartbeatExecutor != null) {
        if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) {
            heartbeatExecutor.shutdownNow();
        }
@@ -251,7 +373,7 @@
    private synchronized void resetHeartbeatTimer() {
        cancelPongTimeout();
        if (heartbeatExecutor != null) {
        if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
            pongTimeoutFuture = heartbeatExecutor.schedule(this::checkHeartbeatTimeout,
                    HEARTBEAT_TIMEOUT, TimeUnit.SECONDS);
        }
@@ -262,6 +384,11 @@
     * 若长时间未收到任何消息则主动发送 ping 请求保持连接活跃。
     */
    private void checkHeartbeatTimeout() {
        // 只有在连接状态下才检查心跳
        if (!isConnected.get()) {
            return;
        }
        long currentTime = System.currentTimeMillis();
        long lastTime = lastMessageTime.get();
@@ -303,7 +430,7 @@
     */
    private void reconnectWithBackoff() throws InterruptedException {
        int attempt = 0;
        int maxAttempts = 5;
        int maxAttempts = 3;
        long delayMs = 5000;
        while (attempt < maxAttempts) {
@@ -320,4 +447,22 @@
        log.error("超过最大重试次数({})仍未连接成功", maxAttempts);
    }
}
    /**
     * 优雅关闭线程池
     */
    private void shutdownExecutorGracefully(ExecutorService executor) {
        if (executor == null || executor.isTerminated()) {
            return;
        }
        try {
            executor.shutdown();
            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            executor.shutdownNow();
        }
    }
}