From 6b5efcaafe57c8c7f0e9c7761d960be063dfd8a2 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 29 Dec 2025 13:40:12 +0800
Subject: [PATCH] fix(okxNewPrice): 修复K线数据获取的时间间隔错误
---
src/main/java/com/xcong/excoin/modules/okxNewPrice/OkxQuantWebSocketClient.java | 272 +++++++++++++++++++++++++++++++++++++++--------------
1 files changed, 199 insertions(+), 73 deletions(-)
diff --git a/src/main/java/com/xcong/excoin/modules/okxNewPrice/OkxQuantWebSocketClient.java b/src/main/java/com/xcong/excoin/modules/okxNewPrice/OkxQuantWebSocketClient.java
index 5dd4c16..1fb20c7 100644
--- a/src/main/java/com/xcong/excoin/modules/okxNewPrice/OkxQuantWebSocketClient.java
+++ b/src/main/java/com/xcong/excoin/modules/okxNewPrice/OkxQuantWebSocketClient.java
@@ -1,21 +1,17 @@
package com.xcong.excoin.modules.okxNewPrice;
-import cn.hutool.core.util.StrUtil;
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.CoinEnums;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.OrderParamEnums;
+import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.ExchangeInfoEnum;
+import com.xcong.excoin.modules.okxNewPrice.okxWs.param.TradeRequestParam;
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;
@@ -23,6 +19,7 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
@@ -32,24 +29,46 @@
* @author Administrator
*/
@Slf4j
-@Component
-@ConditionalOnProperty(prefix = "app", name = "quant", havingValue = "true")
public class OkxQuantWebSocketClient {
- @Autowired
- private WangGeService wangGeService;
- @Autowired
- private CaoZuoService caoZuoService;
- @Autowired
- private RedisUtils redisUtils;
+ private final RedisUtils redisUtils;
+ private final ExchangeInfoEnum account;
+ private final CaoZuoService caoZuoService;
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);
+
+ /**
+ * 获取WebSocketClient实例
+ * @return WebSocketClient实例
+ */
+ public WebSocketClient getWebSocketClient() {
+ return webSocketClient;
+ }
+
+ /**
+ * 获取账号名称
+ * @return 账号名称
+ */
+ public String getAccountName() {
+ return account.name();
+ }
+
+ public OkxQuantWebSocketClient(ExchangeInfoEnum account,
+ CaoZuoService caoZuoService,
+ RedisUtils redisUtils) {
+ this.account = account;
+ 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 boolean INTERNET = false;
/**
* 订阅频道指令
@@ -67,12 +86,21 @@
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();
}
@@ -81,19 +109,50 @@
* 销毁方法,在 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() {
- if (webSocketClient != null && webSocketClient.isOpen()) {
- subscribeAccountChannel(UNSUBSCRIBE);
- subscribePositionChannel(UNSUBSCRIBE);
- subscribeOrderInfoChannel(UNSUBSCRIBE);
- webSocketClient.close();
+ 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) {
@@ -116,22 +175,51 @@
* 设置回调函数以监听连接打开、接收消息、关闭和错误事件。
*/
private void connect() {
+ // 避免重复连接
+ if (isConnecting.get()) {
+ log.info("连接已在进行中,跳过重复连接请求");
+ return;
+ }
+
+ if (!isConnecting.compareAndSet(false, true)) {
+ log.info("连接已在进行中,跳过重复连接请求");
+ return;
+ }
+
try {
- InstrumentsWs.handleEvent(redisUtils);
- wangGeService.initWangGe();
+ InstrumentsWs.handleEvent(account.name());
SSLConfig.configureSSL();
System.setProperty("https.protocols", "TLSv1.2,TLSv1.3");
String WS_URL = WS_URL_MONIPAN;
- if (INTERNET){
+ 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连接成功");
- resetHeartbeatTimer();
- websocketLogin();
+ isConnected.set(true);
+ isConnecting.set(false);
+
+ // 棜查应用是否正在关闭
+ if (!sharedExecutor.isShutdown()) {
+ resetHeartbeatTimer();
+ websocketLogin(account);
+ } else {
+ log.warn("应用正在关闭,忽略WebSocket连接成功回调");
+ }
}
@Override
@@ -144,6 +232,8 @@
@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()) {
@@ -165,17 +255,19 @@
@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() {
- LoginWs.websocketLogin(webSocketClient);
+ private void websocketLogin(ExchangeInfoEnum account) {
+ LoginWs.websocketLogin(webSocketClient, account);
}
private void subscribeBalanceAndPositionChannel(String option) {
@@ -203,7 +295,7 @@
private void handleWebSocketMessage(String message) {
try {
if ("pong".equals(message)) {
- log.info("收到心跳响应");
+ log.debug("{}: 收到心跳响应", account.name());
cancelPongTimeout();
return;
}
@@ -214,26 +306,49 @@
String code = response.getString("code");
if ("0".equals(code)) {
String connId = response.getString("connId");
- log.info("WebSocket登录成功, connId: {}", connId);
+ log.info("{}: WebSocket登录成功, connId: {}", account.name(), connId);
subscribeAccountChannel(SUBSCRIBE);
subscribeOrderInfoChannel(SUBSCRIBE);
subscribePositionChannel(SUBSCRIBE);
} else {
- log.error("WebSocket登录失败, code: {}, msg: {}", code, response.getString("msg"));
+ log.error("{}: WebSocket登录失败, code: {}, msg: {}", account.name(), code, response.getString("msg"));
}
} else if ("subscribe".equals(event)) {
- log.info("订阅成功: {}", response.getJSONObject("arg"));
+ subscribeEvent(response);
} else if ("error".equals(event)) {
- log.error("订阅错误: code={}, msg={}",
- response.getString("code"), response.getString("msg"));
+ log.error("{}: 订阅错误: code={}, msg={}",
+ account.name(), response.getString("code"), response.getString("msg"));
} else if ("channel-conn-count".equals(event)) {
- log.info("连接限制更新: channel={}, connCount={}",
- response.getString("channel"), response.getString("connCount"));
+ log.info("{}: 连接限制更新: channel={}, connCount={}",
+ account.name(), response.getString("channel"), response.getString("connCount"));
} else {
processPushData(response);
}
} catch (Exception e) {
- log.error("处理WebSocket消息失败: {}", message, 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());
}
}
@@ -244,50 +359,35 @@
* @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' 字段");
+ log.warn("{}: 无效的推送数据,缺少 'arg' 字段 :{}", account.name(), response);
return;
}
String channel = arg.getString("channel");
if (channel == null) {
- log.warn("无效的推送数据,缺少 'channel' 字段");
+ log.warn("{}: 无效的推送数据,缺少 'channel' 字段{}", account.name(), response);
return;
}
+ // 注意:当前实现中,OrderInfoWs等类使用静态Map存储数据
+ // 这会导致多账号之间的数据冲突。需要进一步修改这些类的设计,让数据存储与特定账号关联
if (OrderInfoWs.ORDERINFOWS_CHANNEL.equals(channel)) {
- OrderInfoWs.handleEvent(response, redisUtils);
+ OrderInfoWs.handleEvent(response, redisUtils, account.name());
}else if (AccountWs.ACCOUNTWS_CHANNEL.equals(channel)) {
- AccountWs.handleEvent(response, redisUtils);
+ AccountWs.handleEvent(response, account.name());
} else if (PositionsWs.POSITIONSWS_CHANNEL.equals(channel)) {
- PositionsWs.handleEvent(response, redisUtils);
-
- String posKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + CoinEnums.HE_YUE.getCode() + ":pos";
- String pos = (String) redisUtils.get(posKey);
- if (StrUtil.isBlank(pos)) {
- log.error("未获取到持仓数量");
- TradeOrderWs.orderEvent(webSocketClient, redisUtils, OrderParamEnums.INIT.getValue());
- return;
- }
-
- String uplKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + CoinEnums.HE_YUE.getCode() + ":upl";
- String totalOrderUsdtKey = AccountWs.ACCOUNTWS_CHANNEL + ":" + CoinEnums.USDT.getCode() + ":totalOrderUsdt";
-
- String upl = (String) redisUtils.get(uplKey);
- String totalOrderUsdt = (String) redisUtils.get(totalOrderUsdtKey);
- BigDecimal multiply = new BigDecimal(upl).multiply(new BigDecimal("-1"));
-
- if (new BigDecimal(totalOrderUsdt).compareTo(multiply) < 0) {
- log.error("持仓盈亏超过下单总保证金,止损冷静一天......");
- TradeOrderWs.orderEvent(webSocketClient, redisUtils, OrderParamEnums.OUT.getValue());
- return;
- }
-
- String side = caoZuoService.caoZuo();
- if (StrUtil.isNotBlank(pos)) {
- TradeOrderWs.orderEvent(webSocketClient, redisUtils, side);
- }
+ PositionsWs.handleEvent(response, account.name());
} else if (BalanceAndPositionWs.CHANNEL_NAME.equals(channel)) {
BalanceAndPositionWs.handleEvent(response);
}
@@ -308,8 +408,11 @@
return t;
});
- heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, 25, 25, TimeUnit.SECONDS);
+ heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout,
+ HEARTBEAT_TIMEOUT, HEARTBEAT_TIMEOUT, TimeUnit.SECONDS);
}
+
+ // 移除了 schedulePeriodicReconnect 方法
/**
* 重置心跳计时器。
@@ -318,17 +421,25 @@
private void resetHeartbeatTimer() {
cancelPongTimeout();
- if (heartbeatExecutor != null) {
+ // 检查线程池状态,避免在关闭过程中提交任务
+ 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();
@@ -367,15 +478,30 @@
* 在连接意外中断后尝试重新建立连接。
*/
private void reconnectWithBackoff() throws InterruptedException {
+ // 如果正在连接,则不重复发起重连
+ if (isConnecting.get()) {
+ log.info("连接已在进行中,跳过重连请求");
+ return;
+ }
+
int attempt = 0;
- int maxAttempts = 5;
+ int maxAttempts = 3;
long delayMs = 1000;
- while (attempt < maxAttempts) {
+ while (attempt < maxAttempts && !isConnected.get()) {
try {
Thread.sleep(delayMs);
connect();
- return;
+
+ // 等待连接建立
+ 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;
@@ -385,4 +511,4 @@
log.error("超过最大重试次数({})仍未连接成功", maxAttempts);
}
-}
+}
\ No newline at end of file
--
Gitblit v1.9.1