Administrator
2025-12-15 f995b6477c4d3da56e37e8f718ae7f7e8c0fd00d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
package com.xcong.excoin.modules.okxNewPrice;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcong.excoin.modules.okxNewPrice.celue.CaoZuoService;
import com.xcong.excoin.modules.okxNewPrice.okxWs.*;
import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.ExchangeInfoEnum;
import com.xcong.excoin.modules.okxNewPrice.utils.SSLConfig;
import com.xcong.excoin.modules.okxNewPrice.wangge.WangGeService;
import com.xcong.excoin.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
 
/**
 * OKX 新价格 WebSocket 客户端类,用于连接 OKX 的 WebSocket 接口,
 * 实时获取并处理标记价格(mark price)数据,并将价格信息存储到 Redis 中。
 * 同时支持心跳检测、自动重连以及异常恢复机制。
 * @author Administrator
 */
@Slf4j
public class OkxQuantWebSocketClient {
    private final WangGeService wangGeService;
    private final CaoZuoService caoZuoService;
    private final RedisUtils redisUtils;
    private final ExchangeInfoEnum account;
 
    private WebSocketClient webSocketClient;
    private ScheduledExecutorService heartbeatExecutor;
    private volatile ScheduledFuture<?> pongTimeoutFuture;
    private final AtomicReference<Long> lastMessageTime = new AtomicReference<>(System.currentTimeMillis());
    
    // 连接状态标志
    private final AtomicBoolean isConnected = new AtomicBoolean(false);
    private final AtomicBoolean isConnecting = new AtomicBoolean(false);
    
    public OkxQuantWebSocketClient(ExchangeInfoEnum account, WangGeService wangGeService, 
                                   CaoZuoService caoZuoService, RedisUtils redisUtils) {
        this.account = account;
        this.wangGeService = wangGeService;
        this.caoZuoService = caoZuoService;
        this.redisUtils = redisUtils;
    }
 
    private static final String WS_URL_MONIPAN = "wss://wspap.okx.com:8443/ws/v5/private";
    private static final String WS_URL_SHIPAN = "wss://ws.okx.com:8443/ws/v5/private";
 
    /**
     * 订阅频道指令
     */
    private static final String SUBSCRIBE = "subscribe";
    private static final String UNSUBSCRIBE = "unsubscribe";
 
    // 心跳超时时间(秒),小于30秒
    private static final int HEARTBEAT_TIMEOUT = 10;
 
    // 共享线程池用于重连等异步任务
    private final ExecutorService sharedExecutor = Executors.newCachedThreadPool(r -> {
        Thread t = new Thread(r, "okx-ws-account-order-worker");
        t.setDaemon(true);
        return t;
    });
 
    // 在 OkxQuantWebSocketClient 中添加初始化标记
    private final AtomicBoolean isInitialized = new AtomicBoolean(false);
 
    /**
     * 初始化方法,在 Spring Bean 构造完成后执行。
     * 负责建立 WebSocket 连接并启动心跳检测任务。
     */
    @PostConstruct
    public void init() {
        // 防止重复初始化
        if (!isInitialized.compareAndSet(false, true)) {
            log.warn("OkxQuantWebSocketClient 已经初始化过,跳过重复初始化");
            return;
        }
 
        connect();
        startHeartbeat();
    }
 
    /**
     * 销毁方法,在 Spring Bean 销毁前执行。
     * 关闭 WebSocket 连接、停止心跳定时器及相关的线程资源。
     */
//    @PreDestroy
//    public void destroy() {
//        if (webSocketClient != null && webSocketClient.isOpen()) {
//            subscribeAccountChannel(UNSUBSCRIBE);
//            subscribePositionChannel(UNSUBSCRIBE);
//            subscribeOrderInfoChannel(UNSUBSCRIBE);
//            webSocketClient.close();
//        }
//        shutdownExecutorGracefully(heartbeatExecutor);
//        if (pongTimeoutFuture != null) {
//            pongTimeoutFuture.cancel(true);
//        }
//        shutdownExecutorGracefully(sharedExecutor);
//
//        // 移除了 reconnectScheduler 的关闭操作
//    }
    @PreDestroy
    public void destroy() {
        log.info("开始销毁OkxQuantWebSocketClient");
 
        // 设置关闭标志,避免重连
        if (sharedExecutor != null && !sharedExecutor.isShutdown()) {
            sharedExecutor.shutdown();
        }
 
        if (webSocketClient != null && webSocketClient.isOpen()) {
            try {
                subscribeAccountChannel(UNSUBSCRIBE);
                subscribePositionChannel(UNSUBSCRIBE);
                subscribeOrderInfoChannel(UNSUBSCRIBE);
                webSocketClient.closeBlocking();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.warn("关闭WebSocket连接时被中断");
            }
        }
 
        shutdownExecutorGracefully(heartbeatExecutor);
        if (pongTimeoutFuture != null) {
            pongTimeoutFuture.cancel(true);
        }
        shutdownExecutorGracefully(sharedExecutor);
 
        log.info("OkxQuantWebSocketClient销毁完成");
    }
 
    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();
        }
    }
 
    /**
     * 建立与 OKX WebSocket 服务器的连接。
     * 设置回调函数以监听连接打开、接收消息、关闭和错误事件。
     */
    private void connect() {
        // 避免重复连接
        if (isConnecting.get()) {
            log.info("连接已在进行中,跳过重复连接请求");
            return;
        }
        
        if (!isConnecting.compareAndSet(false, true)) {
            log.info("连接已在进行中,跳过重复连接请求");
            return;
        }
        
        try {
            InstrumentsWs.handleEvent(account.name());
            wangGeService.initWangGe();
            SSLConfig.configureSSL();
            System.setProperty("https.protocols", "TLSv1.2,TLSv1.3");
            String WS_URL = WS_URL_MONIPAN;
            if (account.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 account-order WebSocket连接成功");
                    isConnected.set(true);
                    isConnecting.set(false);
                    
                    // 棜查应用是否正在关闭
                    if (!sharedExecutor.isShutdown()) {
                        resetHeartbeatTimer();
                        websocketLogin(account);
                    } else {
                        log.warn("应用正在关闭,忽略WebSocket连接成功回调");
                    }
                }
 
                @Override
                public void onMessage(String message) {
                    lastMessageTime.set(System.currentTimeMillis());
                    handleWebSocketMessage(message);
                    resetHeartbeatTimer();
                }
 
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.warn("OKX account-order WebSocket连接关闭: code={}, reason={}", code, reason);
                    isConnected.set(false);
                    isConnecting.set(false);
                    cancelPongTimeout();
 
                    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 account-order WebSocket发生错误", ex);
                    isConnected.set(false);
                }
            };
 
            webSocketClient.connect();
        } catch (URISyntaxException e) {
            log.error("WebSocket URI格式错误", e);
            isConnecting.set(false);
        }
    }
 
    private void websocketLogin(ExchangeInfoEnum account) {
        LoginWs.websocketLogin(webSocketClient, account);
    }
 
    private void subscribeBalanceAndPositionChannel(String option) {
        BalanceAndPositionWs.subscribeBalanceAndPositionChannel(webSocketClient, option);
    }
 
    private void subscribeOrderInfoChannel(String option) {
        OrderInfoWs.subscribeOrderInfoChannel(webSocketClient, option);
    }
 
    private void subscribeAccountChannel(String option) {
        AccountWs.subscribeAccountChannel(webSocketClient, option);
    }
 
    private void subscribePositionChannel(String option) {
        PositionsWs.subscribePositionChannel(webSocketClient, option);
    }
 
    /**
     * 处理从 WebSocket 收到的消息。
     * 包括订阅确认、错误响应、心跳响应以及实际的数据推送。
     *
     * @param message 来自 WebSocket 的原始字符串消息
     */
    private void handleWebSocketMessage(String message) {
        try {
            if ("pong".equals(message)) {
                log.debug("{}: 收到心跳响应", account.name());
                cancelPongTimeout();
                return;
            }
            JSONObject response = JSON.parseObject(message);
            String event = response.getString("event");
 
            if ("login".equals(event)) {
                String code = response.getString("code");
                if ("0".equals(code)) {
                    String connId = response.getString("connId");
                    log.info("{}: WebSocket登录成功, connId: {}", account.name(), connId);
                    subscribeAccountChannel(SUBSCRIBE);
                    subscribeOrderInfoChannel(SUBSCRIBE);
                    subscribePositionChannel(SUBSCRIBE);
                } else {
                    log.error("{}: WebSocket登录失败, code: {}, msg: {}", account.name(), code, response.getString("msg"));
                }
            } else if ("subscribe".equals(event)) {
                subscribeEvent(response);
            } else if ("error".equals(event)) {
                log.error("{}: 订阅错误: code={}, msg={}",
                         account.name(), response.getString("code"), response.getString("msg"));
            } else if ("channel-conn-count".equals(event)) {
                log.info("{}: 连接限制更新: channel={}, connCount={}",
                         account.name(), response.getString("channel"), response.getString("connCount"));
            } else {
                processPushData(response);
            }
        } catch (Exception e) {
            log.error("{}: 处理WebSocket消息失败: {}", account.name(), message, e);
        }
    }
 
    private void subscribeEvent(JSONObject response) {
        JSONObject arg = response.getJSONObject("arg");
        if (arg == null) {
            log.warn("无效的推送数据,缺少 'arg' 字段 :{}",response);
            return;
        }
 
        String channel = arg.getString("channel");
        if (channel == null) {
            log.warn("无效的推送数据,缺少 'channel' 字段{}",response);
            return;
        }
        if (OrderInfoWs.ORDERINFOWS_CHANNEL.equals(channel)) {
            OrderInfoWs.initEvent(response, account.name());
        }
        if (AccountWs.ACCOUNTWS_CHANNEL.equals(channel)) {
            AccountWs.initEvent(response, account.name());
        }
        if (PositionsWs.POSITIONSWS_CHANNEL.equals(channel)) {
            PositionsWs.initEvent(response, account.name());
        }
    }
 
    /**
     * 解析并处理价格推送数据。
     * 将最新的标记价格存入 Redis 并触发后续业务逻辑比较处理。
     *
     * @param response 包含价格数据的 JSON 对象
     */
    private void processPushData(JSONObject response) {
        String op = response.getString("op");
        if (op != null){
            if (TradeOrderWs.ORDERWS_CHANNEL.equals(op)) {
                // 直接使用Object类型接收,避免强制类型转换
                Object data = response.get("data");
                log.info("{}: 收到下单推送结果: {}", account.name(), JSON.toJSONString(data));
                return;
            }
        }
        JSONObject arg = response.getJSONObject("arg");
        if (arg == null) {
            log.warn("{}: 无效的推送数据,缺少 'arg' 字段 :{}", account.name(), response);
            return;
        }
 
        String channel = arg.getString("channel");
        if (channel == null) {
            log.warn("{}: 无效的推送数据,缺少 'channel' 字段{}", account.name(), response);
            return;
        }
 
        // 注意:当前实现中,OrderInfoWs等类使用静态Map存储数据
        // 这会导致多账号之间的数据冲突。需要进一步修改这些类的设计,让数据存储与特定账号关联
        if (OrderInfoWs.ORDERINFOWS_CHANNEL.equals(channel)) {
            OrderInfoWs.handleEvent(response, redisUtils, account.name());
        }else if (AccountWs.ACCOUNTWS_CHANNEL.equals(channel)) {
            AccountWs.handleEvent(response, account.name());
            String side = caoZuoService.caoZuo(account.name());
            TradeOrderWs.orderEvent(webSocketClient, side, account.name());
        } else if (PositionsWs.POSITIONSWS_CHANNEL.equals(channel)) {
            PositionsWs.handleEvent(response, account.name());
        } else if (BalanceAndPositionWs.CHANNEL_NAME.equals(channel)) {
            BalanceAndPositionWs.handleEvent(response);
        }
    }
 
    /**
     * 启动心跳检测任务。
     * 使用 ScheduledExecutorService 定期检查是否需要发送 ping 请求来维持连接。
     */
    private void startHeartbeat() {
        if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) {
            heartbeatExecutor.shutdownNow();
        }
 
        heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread t = new Thread(r, "okx-account-order-heartbeat");
            t.setDaemon(true);
            return t;
        });
 
        heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout,
                HEARTBEAT_TIMEOUT, HEARTBEAT_TIMEOUT, TimeUnit.SECONDS);
    }
 
    // 移除了 schedulePeriodicReconnect 方法
 
    /**
     * 重置心跳计时器。
     * 当收到新消息或发送 ping 后取消当前超时任务并重新安排下一次超时检查。
     */
    private void resetHeartbeatTimer() {
        cancelPongTimeout();
 
        // 检查线程池状态,避免在关闭过程中提交任务
        if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
            pongTimeoutFuture = heartbeatExecutor.schedule(this::checkHeartbeatTimeout,
                    HEARTBEAT_TIMEOUT, TimeUnit.SECONDS);
        }
    }
 
    // 移除了 performScheduledReconnect 方法
 
    /**
     * 检查心跳超时情况。
     * 若长时间未收到任何消息则主动发送 ping 请求保持连接活跃。
     */
    private void checkHeartbeatTimeout() {
        // 只有在连接状态下才检查心跳
        if (!isConnected.get()) {
            return;
        }
        
        long currentTime = System.currentTimeMillis();
        long lastTime = lastMessageTime.get();
 
        if (currentTime - lastTime >= HEARTBEAT_TIMEOUT * 1000L) {
            sendPing();
        }
    }
 
    /**
     * 发送 ping 请求至 WebSocket 服务端。
     * 用于维持长连接有效性。
     */
    private void sendPing() {
        try {
            if (webSocketClient != null && webSocketClient.isOpen()) {
                webSocketClient.send("ping");
                log.debug("发送ping请求");
            }
        } catch (Exception e) {
            log.warn("发送ping失败", e);
        }
    }
 
    /**
     * 取消当前的心跳超时任务。
     * 在收到 pong 或其他有效消息时调用此方法避免不必要的断开重连。
     */
    private void cancelPongTimeout() {
        if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) {
            pongTimeoutFuture.cancel(true);
        }
    }
 
    /**
     * 执行 WebSocket 重连操作。
     * 在连接意外中断后尝试重新建立连接。
     */
    private void reconnectWithBackoff() throws InterruptedException {
        // 如果正在连接,则不重复发起重连
        if (isConnecting.get()) {
            log.info("连接已在进行中,跳过重连请求");
            return;
        }
        
        int attempt = 0;
        int maxAttempts = 5;
        long delayMs = 1000;
 
        while (attempt < maxAttempts && !isConnected.get()) {
            try {
                Thread.sleep(delayMs);
                connect();
                
                // 等待连接建立
                for (int i = 0; i < 10 && isConnecting.get(); i++) {
                    Thread.sleep(500);
                }
                
                if (isConnected.get()) {
                    log.info("重连成功");
                    return;
                }
            } catch (Exception e) {
                log.warn("第{}次重连失败", attempt + 1, e);
                delayMs *= 2;
                attempt++;
            }
        }
 
        log.error("超过最大重试次数({})仍未连接成功", maxAttempts);
    }
}