src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -21,14 +21,15 @@ * Gate 网格交易服务类。 * * <h3>策略概述</h3> * 多空双开 → 各放止盈条件单 → 仓位推送驱动补仓 → history_pnl 判断停止 * 多空双开 → 各放止盈条件单 → 仓位推送检测平仓补仓 → 平仓推送累加 pnl → 判断停止 * * <h3>触发逻辑</h3> * <pre> * K线首次价格就绪 → dualOpenPositions() // 多空双开 + 止盈条件单 * 仓位推送 size=0 → reopenXxxPosition() // 该方向被止盈平掉 → 补开 * 仓位推送 history_pnl ≥ overallTp → 停止 * 仓位推送 history_pnl ≤ -maxLoss → 停止 * 仓位推送 size=0 → reopenXxxPosition() // 该方向被平仓 → 只补该方向 * 平仓推送 pnl → cumulativePnl += pnl // 累计盈亏 * cumulativePnl ≥ overallTp → 停止 * cumulativePnl ≤ -maxLoss → 停止 * </pre> * * <h3>止盈计算</h3> @@ -37,7 +38,7 @@ * * <h3>依赖</h3> * 使用 {@code io.gate:gate-api (7.2.71)} SDK 通过 REST API 下单, * 市场数据由 {@link GateKlineWebSocketClient} 通过 WebSocket 提供。 * 市场数据由 WebSocket Handler 类提供。 * * @author Administrator */ @@ -72,8 +73,8 @@ private BigDecimal shortEntryPrice; /** WebSocket 推送的最新 K 线收盘价 */ private volatile BigDecimal lastKlinePrice; /** 服务器返回的累计已实现盈亏 */ private BigDecimal totalHistoryPnl = BigDecimal.ZERO; /** 平仓推送累计的盈亏 */ private volatile BigDecimal cumulativePnl = BigDecimal.ZERO; /** 用户 ID,用于 WebSocket 私有频道订阅 */ private Long userId; @@ -93,7 +94,7 @@ String contract, String leverage, String marginMode, String positionMode, BigDecimal gridRate, BigDecimal overallTp, int maxCycles, BigDecimal maxLoss, BigDecimal maxLoss, String quantity) { this.contract = contract; this.leverage = leverage; @@ -111,7 +112,7 @@ } /** * 初始化账户。设置杠杆、查询余额、切换持仓模式。 * 初始化账户。顺序:切持仓模式 → 清旧条件单 → 设杠杆 → 查余额。 */ public void init() { try { @@ -120,6 +121,13 @@ this.userId = accountDetail.getUserId(); log.info("[GateGrid] 用户ID: {}", userId); FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE); String positionModeSet = account.getPositionMode(); if (!positionMode.equals(positionModeSet)) { futuresApi.setPositionMode(SETTLE, positionMode); } log.info("[GateGrid] 已设置持仓模式: {}", positionMode); futuresApi.cancelPriceTriggeredOrderList(SETTLE, contract); log.info("[GateGrid] 已取消所有既有止盈止损条件单"); @@ -127,14 +135,8 @@ SETTLE, contract, leverage, marginMode, positionMode, null); log.info("[GateGrid] 已设置杠杆: {}x, 保证金模式: {}", leverage, marginMode); FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE); log.info("[GateGrid] 账户可用余额: {}, 总资产: {}", account.getAvailable(), account.getTotal()); String positionModeSet = account.getPositionMode(); if (!positionMode.equals(positionModeSet)) { futuresApi.setPositionMode(SETTLE, positionMode); } log.info("[GateGrid] 已设置双向持仓模式"); } catch (GateApiException e) { log.error("[GateGrid] 初始化失败, label: {}, msg: {}", e.getErrorLabel(), e.getMessage()); } catch (ApiException e) { @@ -151,7 +153,7 @@ return; } strategyActive = true; totalHistoryPnl = BigDecimal.ZERO; cumulativePnl = BigDecimal.ZERO; log.info("[GateGrid] 网格策略启动,等待K线价格..."); } @@ -160,7 +162,7 @@ */ public void stopGrid() { strategyActive = false; log.info("[GateGrid] 网格策略已停止, history_pnl: {}", totalHistoryPnl); log.info("[GateGrid] 网格策略已停止, cumulativePnl: {}", cumulativePnl); } /** @@ -187,18 +189,15 @@ * <li>size=0 且之前活跃 → 该方向被平仓 → 补开</li> * <li>size>0 → 确认仓位活跃,更新入场价</li> * </ul> * 每次推送更新 history_pnl 并检查停止条件。 * 注意:累计盈亏由 onPositionClose 独立计算。 * * @param contract 合约名 * @param mode 仓位模式(dual_long / dual_short) * @param size 仓位数量(0 表示无仓位) * @param entryPrice 入场价格 * @param historyPnl 已实现累计盈亏 * @param realisedPnl 已实现盈亏 */ public void onPositionUpdate(String contract, String mode, BigDecimal size, BigDecimal entryPrice, BigDecimal historyPnl, BigDecimal realisedPnl) { BigDecimal entryPrice) { if (!strategyActive) { return; } @@ -224,8 +223,22 @@ shortEntryPrice = entryPrice; } } } totalHistoryPnl = historyPnl; /** * 平仓推送回调入口。由 {@link GateKlineWebSocketClient} 调用。 * 累加平仓盈亏,每次平仓推送后检查停止条件。 * * @param contract 合约名 * @param side 平仓方向(long / short) * @param pnl 该次平仓的盈亏 */ public void onPositionClose(String contract, String side, BigDecimal pnl) { if (!strategyActive) { return; } cumulativePnl = cumulativePnl.add(pnl); log.info("[GateGrid] 平仓盈亏累计, side:{}, pnl:{}, cumulativePnl:{}", side, pnl, cumulativePnl); checkStopConditions(); } @@ -237,13 +250,13 @@ * </ul> */ private void checkStopConditions() { if (totalHistoryPnl.compareTo(overallTp) >= 0) { log.info("[GateGrid] 累计止盈 {} 达到 {} USDT,停止策略", totalHistoryPnl, overallTp); if (cumulativePnl.compareTo(overallTp) >= 0) { log.info("[GateGrid] 累计止盈 {} 达到 {} USDT,停止策略", cumulativePnl, overallTp); strategyActive = false; return; } if (totalHistoryPnl.compareTo(maxLoss.negate()) <= 0) { log.info("[GateGrid] 累计亏损 {} 达到上限 {} USDT,停止策略", totalHistoryPnl, maxLoss); if (cumulativePnl.compareTo(maxLoss.negate()) <= 0) { log.info("[GateGrid] 累计亏损 {} 达到上限 {} USDT,停止策略", cumulativePnl, maxLoss); strategyActive = false; } } @@ -381,36 +394,17 @@ FuturesPriceTrigger.RuleEnum rule, String orderType, String autoSize) { FuturesPriceTriggeredOrder order = buildTriggeredOrder(triggerPrice, rule, orderType, autoSize); try { FuturesPriceTrigger trigger = new FuturesPriceTrigger(); trigger.setStrategyType(FuturesPriceTrigger.StrategyTypeEnum.NUMBER_0); trigger.setPriceType(FuturesPriceTrigger.PriceTypeEnum.NUMBER_0); trigger.setPrice(triggerPrice.toString()); trigger.setRule(rule); trigger.setExpiration(0); FuturesInitialOrder initial = new FuturesInitialOrder(); initial.setContract(contract); initial.setSize(0L); initial.setPrice("0"); initial.setTif(FuturesInitialOrder.TifEnum.IOC); initial.setReduceOnly(true); initial.setAutoSize(autoSize); FuturesPriceTriggeredOrder order = new FuturesPriceTriggeredOrder(); order.setTrigger(trigger); order.setInitial(initial); order.setOrderType(orderType); TriggerOrderResponse response = futuresApi.createPriceTriggeredOrder(SETTLE, order); log.info("[GateGrid] 止盈条件单已创建, triggerPrice:{}, orderType:{}, autoSize:{}, id:{}", triggerPrice, orderType, autoSize, response.getId()); } catch (GateApiException e) { if ("AUTO_USER_EXIST_POSITION_ORDER".equals(e.getErrorLabel())) { log.warn("[GateGrid] 止盈条件单已存在,取消旧单后重试, label:{}", e.getErrorLabel()); log.warn("[GateGrid] 止盈条件单已存在,取消旧单后重试"); try { futuresApi.cancelPriceTriggeredOrderList(SETTLE, contract); TriggerOrderResponse response = futuresApi.createPriceTriggeredOrder(SETTLE, createPriceTriggeredOrderBean(triggerPrice, rule, orderType, autoSize)); TriggerOrderResponse response = futuresApi.createPriceTriggeredOrder(SETTLE, order); log.info("[GateGrid] 止盈条件单重试成功, triggerPrice:{}, orderType:{}, autoSize:{}, id:{}", triggerPrice, orderType, autoSize, response.getId()); } catch (Exception retryEx) { @@ -427,7 +421,7 @@ } } private FuturesPriceTriggeredOrder createPriceTriggeredOrderBean(BigDecimal triggerPrice, private FuturesPriceTriggeredOrder buildTriggeredOrder(BigDecimal triggerPrice, FuturesPriceTrigger.RuleEnum rule, String orderType, String autoSize) { @@ -498,8 +492,8 @@ return strategyActive; } public BigDecimal getTotalHistoryPnl() { return totalHistoryPnl; public BigDecimal getCumulativePnl() { return cumulativePnl; } public Long getUserId() { src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -1,119 +1,66 @@ package com.xcong.excoin.modules.gateApi; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.modules.blackchain.service.DateUtil; import com.xcong.excoin.modules.okxNewPrice.celue.CaoZuoService; import com.xcong.excoin.modules.okxNewPrice.okxWs.wanggeList.WangGeListService; import com.xcong.excoin.modules.gateApi.wsHandler.GateChannelHandler; import com.xcong.excoin.modules.okxNewPrice.utils.SSLConfig; import lombok.extern.slf4j.Slf4j; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Gate WebSocket 客户端,通过 Java-WebSocket 库连接 Gate.io 的 WebSocket 接口。 * Gate WebSocket 连接管理器。 * 负责建立连接、心跳检测、重连,将频道逻辑委托给 {@link GateChannelHandler} 实现类。 * * <h3>订阅频道</h3> * <ul> * <li>{@code futures.candlesticks} — 1m K 线数据(公开频道)</li> * <li>{@code futures.positions} — 用户仓位更新(私有频道,需 HMAC-SHA512 签名认证)</li> * <li>{@code futures.ping} — 应用层心跳</li> * </ul> * * <h3>数据流</h3> * <pre> * onMessage → handleWebSocketMessage → 按 channel 分流: * futures.pong → 取消心跳超时 * subscribe/unsubscribe/error → 日志 * futures.candlesticks → processPushDataV2 → GateGridTradeService.onKline() * futures.positions → processPositionData → GateGridTradeService.onPositionUpdate() * </pre> * * <h3>连接管理</h3> * 支持心跳检测、指数退避重连(最多 3 次)、优雅关闭。 * <h3>频道处理</h3> * 每个频道由独立的 Handler 类负责:订阅、取消订阅、消息解析。 * 运行时将消息按 channel 字段路由到对应 Handler。 * * @author Administrator */ @Slf4j public class GateKlineWebSocketClient { private final CaoZuoService caoZuoService; private final GateWebSocketClientManager clientManager; private final WangGeListService wangGeListService; private static final String FUTURES_PING = "futures.ping"; private static final String FUTURES_PONG = "futures.pong"; private static final int HEARTBEAT_TIMEOUT = 10; private static final String WS_URL_MONIPAN = "wss://ws-testnet.gate.com/v4/ws/futures/usdt"; private static final String WS_URL_SHIPAN = "wss://fx-ws.gateio.ws/v4/ws/usdt"; private static final boolean isAccountType = false; 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); /** 初始化标记,防止重复初始化 */ private final AtomicBoolean isInitialized = new AtomicBoolean(false); /** K 线频道 */ private static final String CHANNEL = "futures.candlesticks"; /** 仓位频道(私有,需认证) */ private static final String POSITIONS_CHANNEL = "futures.positions"; /** 应用层 ping 频道 */ private static final String FUTURES_PING = "futures.ping"; /** 应用层 pong 频道 */ private static final String FUTURES_PONG = "futures.pong"; /** K 线周期 */ private static final String GATE_INTERVAL = "1m"; /** 订阅合约 */ private static final String GATE_CONTRACT = "XAUT_USDT"; private final List<GateChannelHandler> channelHandlers = new ArrayList<>(); /** 网格交易策略实例 */ private GateGridTradeService gridTradeService; /** API 密钥,用于私有频道签名 */ private final String apiKey; /** API 密钥 */ private final String apiSecret; private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); // 心跳超时时间(秒),小于30秒 private static final int HEARTBEAT_TIMEOUT = 10; // 共享线程池用于重连等异步任务 private final ExecutorService sharedExecutor = Executors.newCachedThreadPool(r -> { Thread t = new Thread(r, "gate-kline-worker"); Thread t = new Thread(r, "gate-ws-worker"); t.setDaemon(true); return t; }); public GateKlineWebSocketClient(CaoZuoService caoZuoService, GateWebSocketClientManager clientManager, WangGeListService wangGeListService, GateGridTradeService gridTradeService, String apiKey, String apiSecret ) { this.caoZuoService = caoZuoService; this.clientManager = clientManager; this.wangGeListService = wangGeListService; this.gridTradeService = gridTradeService; this.apiKey = apiKey; this.apiSecret = apiSecret; public GateKlineWebSocketClient() { } /** * 初始化方法,创建并初始化WebSocket客户端实例 */ public void addChannelHandler(GateChannelHandler handler) { channelHandlers.add(handler); } public void init() { if (!isInitialized.compareAndSet(false, true)) { log.warn("GateKlineWebSocketClient 已经初始化过,跳过重复初始化"); @@ -123,25 +70,19 @@ startHeartbeat(); } /** * 销毁方法,关闭WebSocket连接和相关资源 */ public void destroy() { log.info("开始销毁GateKlineWebSocketClient"); if (webSocketClient != null && webSocketClient.isOpen()) { unsubscribeKlineChannels(); unsubscribePositionsChannels(); for (GateChannelHandler handler : channelHandlers) { handler.unsubscribe(webSocketClient); } try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("取消订阅等待被中断"); } } if (sharedExecutor != null && !sharedExecutor.isShutdown()) { sharedExecutor.shutdown(); } if (webSocketClient != null && webSocketClient.isOpen()) { @@ -153,6 +94,10 @@ } } if (sharedExecutor != null && !sharedExecutor.isShutdown()) { sharedExecutor.shutdown(); } shutdownExecutorGracefully(heartbeatExecutor); if (pongTimeoutFuture != null) { pongTimeoutFuture.cancel(true); @@ -162,36 +107,16 @@ log.info("GateKlineWebSocketClient销毁完成"); } private static final String WS_URL_MONIPAN = "wss://ws-testnet.gate.com/v4/ws/futures/usdt"; private static final String WS_URL_SHIPAN = "wss://fx-ws.gateio.ws/v4/ws/usdt"; private static final boolean isAccountType = false; /** * 建立与 Gate WebSocket 服务器的连接。 * 设置回调函数以监听连接打开、接收消息、关闭和错误事件。 */ private void connect() { // 避免重复连接 if (isConnecting.get()) { if (isConnecting.get() || !isConnecting.compareAndSet(false, true)) { 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; } String WS_URL = isAccountType ? WS_URL_SHIPAN : WS_URL_MONIPAN; URI uri = new URI(WS_URL); // 关闭之前的连接(如果存在) if (webSocketClient != null) { try { webSocketClient.closeBlocking(); @@ -200,20 +125,18 @@ log.warn("关闭之前连接时被中断"); } } webSocketClient = new WebSocketClient(uri) { @Override public void onOpen(ServerHandshake handshake) { log.info("Gate Kline WebSocket连接成功"); log.info("Gate WebSocket连接成功"); isConnected.set(true); isConnecting.set(false); // 检查应用是否正在关闭 if (sharedExecutor != null && !sharedExecutor.isShutdown()) { resetHeartbeatTimer(); subscribeKlineChannels(); subscribePositionsChannels(); subscribePingChannels(); for (GateChannelHandler handler : channelHandlers) { handler.subscribe(webSocketClient); } sendPing(); } else { log.warn("应用正在关闭,忽略WebSocket连接成功回调"); } @@ -222,17 +145,16 @@ @Override public void onMessage(String message) { lastMessageTime.set(System.currentTimeMillis()); handleWebSocketMessage(message); handleMessage(message); resetHeartbeatTimer(); } @Override public void onClose(int code, String reason, boolean remote) { log.warn("Gate Kline WebSocket连接关闭: code={}, reason={}", code, reason); log.warn("Gate WebSocket连接关闭: code={}, reason={}", code, reason); isConnected.set(false); isConnecting.set(false); cancelPongTimeout(); if (sharedExecutor != null && !sharedExecutor.isShutdown() && !sharedExecutor.isTerminated()) { sharedExecutor.execute(() -> { try { @@ -251,11 +173,10 @@ @Override public void onError(Exception ex) { log.error("Gate Kline WebSocket发生错误", ex); log.error("Gate WebSocket发生错误", ex); isConnected.set(false); } }; webSocketClient.connect(); } catch (URISyntaxException e) { log.error("WebSocket URI格式错误", e); @@ -263,134 +184,7 @@ } } /** * 订阅K线频道。 * 构造 Gate 格式的订阅请求并发送给服务端。 * payload: ["1m", "BTC_USDT"] (间隔, 合约名) */ private void subscribeKlineChannels() { JSONObject subscribeMsg = new JSONObject(); subscribeMsg.put("time", System.currentTimeMillis() / 1000); subscribeMsg.put("channel", CHANNEL); subscribeMsg.put("event", "subscribe"); JSONArray payload = new JSONArray(); payload.add(GATE_INTERVAL); payload.add(GATE_CONTRACT); subscribeMsg.put("payload", payload); webSocketClient.send(subscribeMsg.toJSONString()); log.info("已发送 K线频道订阅请求,合约: {}, 周期: {}", GATE_CONTRACT, GATE_INTERVAL); } /** * 发送应用层 ping 请求。 * 用于探测连接状态,服务器会返回 futures.pong。 */ private void subscribePingChannels() { JSONObject subscribeMsg = new JSONObject(); subscribeMsg.put("time", System.currentTimeMillis() / 1000); subscribeMsg.put("channel", FUTURES_PING); webSocketClient.send(subscribeMsg.toJSONString()); log.info("已发送 futures.ping"); } /** * 订阅仓位频道(私有频道,需 HMAC-SHA512 签名认证)。 * 签名算法: Hex(HmacSHA512(secret, "channel={channel}&event={event}&time={time}")) */ private void subscribePositionsChannels() { JSONObject subscribeMsg = new JSONObject(); long timeSec = System.currentTimeMillis() / 1000; subscribeMsg.put("id", timeSec * 1000000 + (System.currentTimeMillis() % 1000)); subscribeMsg.put("time", timeSec); subscribeMsg.put("channel", POSITIONS_CHANNEL); subscribeMsg.put("event", "subscribe"); String uid = gridTradeService != null && gridTradeService.getUserId() != null ? String.valueOf(gridTradeService.getUserId()) : ""; JSONArray payload = new JSONArray(); payload.add(uid); payload.add(GATE_CONTRACT); subscribeMsg.put("payload", payload); JSONObject auth = new JSONObject(); auth.put("method", "api_key"); auth.put("KEY", apiKey); auth.put("SIGN", hs512Sign(POSITIONS_CHANNEL, "subscribe", timeSec)); subscribeMsg.put("auth", auth); webSocketClient.send(subscribeMsg.toJSONString()); log.info("已发送仓位频道订阅请求(含认证),userId:{}, 合约: {}", uid, GATE_CONTRACT); } /** * 计算 Gate API v4 的 HMAC-SHA512 签名。 * * @param channel 频道名 * @param event 事件名(subscribe/unsubscribe) * @param timeSec 时间戳(秒) * @return 十六进制签名字符串 */ private String hs512Sign(String channel, String event, long timeSec) { try { String message = "channel=" + channel + "&event=" + event + "&time=" + timeSec; Mac mac = Mac.getInstance("HmacSHA512"); SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA512"); mac.init(spec); byte[] hash = mac.doFinal(message.getBytes(StandardCharsets.UTF_8)); StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { hex.append(HEX_ARRAY[(b >> 4) & 0xF]); hex.append(HEX_ARRAY[b & 0xF]); } String sign = hex.toString(); log.debug("签名计算, message: {}, sign: {}", message, sign); return sign; } catch (Exception e) { log.error("签名计算失败", e); return ""; } } /** * 取消订阅 K 线频道。 */ private void unsubscribeKlineChannels() { JSONObject unsubscribeMsg = new JSONObject(); unsubscribeMsg.put("time", System.currentTimeMillis() / 1000); unsubscribeMsg.put("channel", CHANNEL); unsubscribeMsg.put("event", "unsubscribe"); JSONArray payload = new JSONArray(); payload.add(GATE_INTERVAL); payload.add(GATE_CONTRACT); unsubscribeMsg.put("payload", payload); webSocketClient.send(unsubscribeMsg.toJSONString()); log.info("已发送 K线频道取消订阅请求,合约: {}, 周期: {}", GATE_CONTRACT, GATE_INTERVAL); } /** * 取消订阅仓位频道。 */ private void unsubscribePositionsChannels() { JSONObject unsubscribeMsg = new JSONObject(); unsubscribeMsg.put("time", System.currentTimeMillis() / 1000); unsubscribeMsg.put("channel", POSITIONS_CHANNEL); unsubscribeMsg.put("event", "unsubscribe"); JSONArray payload = new JSONArray(); payload.add(GATE_CONTRACT); unsubscribeMsg.put("payload", payload); webSocketClient.send(unsubscribeMsg.toJSONString()); log.info("已发送仓位频道取消订阅请求,合约: {}", GATE_CONTRACT); } /** * 处理从 WebSocket 收到的消息。 * 包括订阅确认、错误响应、心跳响应以及实际的数据推送。 * * @param message 来自 WebSocket 的原始字符串消息 */ private void handleWebSocketMessage(String message) { private void handleMessage(String message) { try { JSONObject response = JSON.parseObject(message); String channel = response.getString("channel"); @@ -399,21 +193,31 @@ if (FUTURES_PONG.equals(channel)) { log.debug("收到futures.pong响应"); cancelPongTimeout(); } else if ("subscribe".equals(event)) { return; } if ("subscribe".equals(event)) { log.info("{} 频道订阅成功: {}", channel, response.getJSONObject("result")); } else if ("unsubscribe".equals(event)) { return; } if ("unsubscribe".equals(event)) { log.info("{} 频道取消订阅成功", channel); } else if ("error".equals(event)) { return; } if ("error".equals(event)) { JSONObject error = response.getJSONObject("error"); log.error("{} 频道错误: code={}, msg={}", channel, error != null ? error.getInteger("code") : "N/A", error != null ? error.getString("message") : response.getString("msg")); } else if ("update".equals(event) || "all".equals(event)) { if (POSITIONS_CHANNEL.equals(channel)) { processPositionData(response); } else if (CHANNEL.equals(channel)) { processPushDataV2(response); return; } if ("update".equals(event) || "all".equals(event)) { for (GateChannelHandler handler : channelHandlers) { if (handler.handleMessage(response)) { return; } } } } catch (Exception e) { @@ -421,168 +225,35 @@ } } /** * 解析并处理K线推送数据。 * 控制台输出K线数据,并在K线完结时触发策略和量化操作。 * * @param response 包含K线数据的 JSON 对象 */ private void processPushDataV2(JSONObject response) { try { /** * Gate K线推送格式: * { * "time": 1542162490, * "time_ms": 1542162490123, * "channel": "futures.candlesticks", * "event": "update", * "result": [ * { * "t": 1545129300, * "v": "27525555", * "c": "95.4", * "h": "96.9", * "l": "89.5", * "o": "94.3", * "n": "1m_BTC_USD", * "a": "314732.87412", * "w": false * } * ] * } */ String channel = response.getString("channel"); if (!CHANNEL.equals(channel)) { return; } JSONArray resultArray = response.getJSONArray("result"); if (resultArray == null || resultArray.isEmpty()) { log.warn("K线频道数据为空"); return; } JSONObject data = resultArray.getJSONObject(0); BigDecimal openPx = new BigDecimal(data.getString("o")); BigDecimal highPx = new BigDecimal(data.getString("h")); BigDecimal lowPx = new BigDecimal(data.getString("l")); BigDecimal closePx = new BigDecimal(data.getString("c")); BigDecimal vol = new BigDecimal(data.getString("v")); BigDecimal baseVol = new BigDecimal(data.getString("a")); String name = data.getString("n"); long t = data.getLong("t"); boolean windowClosed = data.getBooleanValue("w"); String time = DateUtil.TimeStampToDateTime(t); log.info("========== Gate K线数据 =========="); log.info("名称(n): " + name); log.info("时间 : " + time); log.info("开盘(o): " + openPx); log.info("最高(h): " + highPx); log.info("最低(l): " + lowPx); log.info("收盘(c): " + closePx); log.info("成交量(v): " + vol); log.info("成交额(a): " + baseVol); log.info("K线完结(w): " + windowClosed); log.info("=================================="); if (gridTradeService != null) { gridTradeService.onKline(closePx); } } catch (Exception e) { log.error("处理 K线频道推送数据失败", e); } } /** * 解析仓位推送数据,提取目标合约的仓位信息并回调交易服务。 * 推送字段: contract, mode(dual_long/dual_short), size, entry_price, history_pnl, realised_pnl * * @param response 仓位推送的 JSON 对象 */ private void processPositionData(JSONObject response) { try { JSONArray resultArray = response.getJSONArray("result"); if (resultArray == null || resultArray.isEmpty()) { return; } for (int i = 0; i < resultArray.size(); i++) { JSONObject pos = resultArray.getJSONObject(i); String contract = pos.getString("contract"); if (!GATE_CONTRACT.equals(contract)) { continue; } String mode = pos.getString("mode"); BigDecimal size = new BigDecimal(pos.getString("size")); BigDecimal entryPrice = new BigDecimal(pos.getString("entry_price")); BigDecimal historyPnl = new BigDecimal(pos.getString("history_pnl")); BigDecimal realisedPnl = new BigDecimal(pos.getString("realised_pnl")); log.info("仓位推送: contract={}, mode={}, size={}, entry_price={}, history_pnl={}, realised_pnl={}", contract, mode, size, entryPrice, historyPnl, realisedPnl); if (gridTradeService != null) { gridTradeService.onPositionUpdate(contract, mode, size, entryPrice, historyPnl, realisedPnl); } } } catch (Exception e) { log.error("处理仓位推送数据失败", e); } } /** * 启动心跳检测任务。 * 使用 ScheduledExecutorService 定期检查是否需要发送 ping 请求来维持连接。 */ private void startHeartbeat() { if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) { heartbeatExecutor.shutdownNow(); } heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "gate-kline-heartbeat"); Thread t = new Thread(r, "gate-ws-heartbeat"); t.setDaemon(true); return t; }); heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, 25, 25, TimeUnit.SECONDS); } /** * 重置心跳计时器。 * 当收到新消息或发送 ping 后取消当前超时任务并重新安排下一次超时检查。 */ private synchronized void resetHeartbeatTimer() { cancelPongTimeout(); if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) { pongTimeoutFuture = heartbeatExecutor.schedule(this::checkHeartbeatTimeout, HEARTBEAT_TIMEOUT, TimeUnit.SECONDS); } } /** * 检查心跳超时情况。 * 若长时间未收到任何消息则主动发送 ping 请求保持连接活跃。 */ private void checkHeartbeatTimeout() { // 只有在连接状态下才检查心跳 if (!isConnected.get()) { return; } long currentTime = System.currentTimeMillis(); long lastTime = lastMessageTime.get(); if (currentTime - lastTime >= HEARTBEAT_TIMEOUT * 1000L) { if (System.currentTimeMillis() - lastMessageTime.get() >= HEARTBEAT_TIMEOUT * 1000L) { sendPing(); } } /** * 发送 ping 请求至 WebSocket 服务端。 * 用于维持长连接有效性。 */ private void sendPing() { try { if (webSocketClient != null && webSocketClient.isOpen()) { @@ -597,25 +268,16 @@ } } /** * 取消当前的心跳超时任务。 * 在收到 pong 或其他有效消息时调用此方法避免不必要的断开重连。 */ private synchronized void cancelPongTimeout() { if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) { pongTimeoutFuture.cancel(true); } } /** * 执行 WebSocket 重连操作。 * 在连接意外中断后尝试重新建立连接。 */ private void reconnectWithBackoff() throws InterruptedException { int attempt = 0; int maxAttempts = 3; long delayMs = 5000; while (attempt < maxAttempts) { try { Thread.sleep(delayMs); @@ -627,13 +289,9 @@ attempt++; } } log.error("超过最大重试次数({})仍未连接成功", maxAttempts); } /** * 优雅关闭线程池 */ private void shutdownExecutorGracefully(ExecutorService executor) { if (executor == null || executor.isTerminated()) { return; src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
@@ -1,9 +1,9 @@ package com.xcong.excoin.modules.gateApi; import com.xcong.excoin.modules.okxNewPrice.celue.CaoZuoService; import com.xcong.excoin.modules.okxNewPrice.okxWs.wanggeList.WangGeListService; import com.xcong.excoin.modules.gateApi.wsHandler.handler.CandlestickChannelHandler; import com.xcong.excoin.modules.gateApi.wsHandler.handler.PositionClosesChannelHandler; import com.xcong.excoin.modules.gateApi.wsHandler.handler.PositionsChannelHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -41,10 +41,6 @@ @Slf4j @Component public class GateWebSocketClientManager { @Autowired private CaoZuoService caoZuoService; @Autowired private WangGeListService wangGeListService; /** K 线 WebSocket 客户端 */ private GateKlineWebSocketClient klinePriceClient; @@ -55,6 +51,8 @@ private static final String API_KEY = "d90ca272391992b8e74f8f92cedb21ec"; /** Gate 测试网 API Secret */ private static final String API_SECRET = "1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274"; /** 合约 */ private static final String CONTRACT = "XAUT_USDT"; /** * Spring 容器启动后自动调用。初始化网格交易服务和 WebSocket 客户端。 @@ -66,21 +64,23 @@ try { gridTradeService = new GateGridTradeService( API_KEY, API_SECRET, "XAUT_USDT", CONTRACT, "30", "cross", "dual", new BigDecimal("0.0035"), new BigDecimal("0.5"), 3, new BigDecimal("7.5"), "10" ); gridTradeService.init(); klinePriceClient = new GateKlineWebSocketClient(caoZuoService, this, wangGeListService, gridTradeService, API_KEY, API_SECRET); klinePriceClient = new GateKlineWebSocketClient(); klinePriceClient.addChannelHandler(new CandlestickChannelHandler(CONTRACT, gridTradeService)); klinePriceClient.addChannelHandler(new PositionsChannelHandler(API_KEY, API_SECRET, CONTRACT, gridTradeService)); klinePriceClient.addChannelHandler(new PositionClosesChannelHandler(API_KEY, API_SECRET, CONTRACT, gridTradeService)); klinePriceClient.init(); log.info("已初始化GateKlineWebSocketClient"); log.info("已初始化GateKlineWebSocketClient及3个频道Handler"); gridTradeService.startGrid(); } catch (Exception e) { src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/AbstractPrivateChannelHandler.java
New file @@ -0,0 +1,116 @@ package com.xcong.excoin.modules.gateApi.wsHandler; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.modules.gateApi.GateGridTradeService; import com.xcong.excoin.modules.gateApi.wsHandler.GateChannelHandler; import lombok.extern.slf4j.Slf4j; import org.java_websocket.client.WebSocketClient; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; /** * 私有频道的抽象基类,封装 HMAC-SHA512 签名和认证请求构建。 * * @author Administrator */ @Slf4j public abstract class AbstractPrivateChannelHandler implements GateChannelHandler { private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); private final String channelName; private final String apiKey; private final String apiSecret; private final String contract; private final GateGridTradeService gridTradeService; public AbstractPrivateChannelHandler(String channelName, String apiKey, String apiSecret, String contract, GateGridTradeService gridTradeService) { this.channelName = channelName; this.apiKey = apiKey; this.apiSecret = apiSecret; this.contract = contract; this.gridTradeService = gridTradeService; } @Override public String getChannelName() { return channelName; } @Override public void subscribe(WebSocketClient ws) { long timeSec = System.currentTimeMillis() / 1000; JSONObject msg = buildAuthRequest("subscribe", buildUid(), timeSec); ws.send(msg.toJSONString()); log.info("[{}] 已发送订阅请求(含认证),合约: {}", channelName, contract); } @Override public void unsubscribe(WebSocketClient ws) { JSONObject unsubscribeMsg = new JSONObject(); unsubscribeMsg.put("time", System.currentTimeMillis() / 1000); unsubscribeMsg.put("channel", channelName); unsubscribeMsg.put("event", "unsubscribe"); JSONArray payload = new JSONArray(); payload.add(contract); unsubscribeMsg.put("payload", payload); ws.send(unsubscribeMsg.toJSONString()); log.info("[{}] 已发送取消订阅请求,合约: {}", channelName, contract); } protected GateGridTradeService getGridTradeService() { return gridTradeService; } protected String getContract() { return contract; } private String buildUid() { return gridTradeService != null && gridTradeService.getUserId() != null ? String.valueOf(gridTradeService.getUserId()) : ""; } private JSONObject buildAuthRequest(String event, String uid, long timeSec) { JSONObject msg = new JSONObject(); msg.put("id", timeSec * 1000000 + (System.currentTimeMillis() % 1000)); msg.put("time", timeSec); msg.put("channel", channelName); msg.put("event", event); JSONArray payload = new JSONArray(); payload.add(uid); payload.add(contract); msg.put("payload", payload); JSONObject auth = new JSONObject(); auth.put("method", "api_key"); auth.put("KEY", apiKey); auth.put("SIGN", hs512Sign(event, timeSec)); msg.put("auth", auth); return msg; } private String hs512Sign(String event, long timeSec) { try { String message = "channel=" + channelName + "&event=" + event + "&time=" + timeSec; Mac mac = Mac.getInstance("HmacSHA512"); SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA512"); mac.init(spec); byte[] hash = mac.doFinal(message.getBytes(StandardCharsets.UTF_8)); StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { hex.append(HEX_ARRAY[(b >> 4) & 0xF]); hex.append(HEX_ARRAY[b & 0xF]); } return hex.toString(); } catch (Exception e) { log.error("[{}] 签名计算失败", channelName, e); return ""; } } } src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/GateChannelHandler.java
New file @@ -0,0 +1,37 @@ package com.xcong.excoin.modules.gateApi.wsHandler; import com.alibaba.fastjson.JSONObject; import org.java_websocket.client.WebSocketClient; /** * WebSocket 频道处理器接口。 * 每个 Gate 频道(K线/仓位/平仓)对应一个实现类, * 负责该频道的订阅、取消订阅、消息处理。 * * @author Administrator */ public interface GateChannelHandler { /** * 频道名称,如 "futures.candlesticks" */ String getChannelName(); /** * 发送订阅请求 */ void subscribe(WebSocketClient ws); /** * 发送取消订阅请求 */ void unsubscribe(WebSocketClient ws); /** * 处理频道推送消息 * * @param response WebSocket 推送的 JSON 消息 * @return true 表示已处理,false 表示不匹配(频道名不对) */ boolean handleMessage(JSONObject response); } src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java
New file @@ -0,0 +1,103 @@ package com.xcong.excoin.modules.gateApi.wsHandler.handler; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.modules.blackchain.service.DateUtil; import com.xcong.excoin.modules.gateApi.GateGridTradeService; import com.xcong.excoin.modules.gateApi.wsHandler.GateChannelHandler; import lombok.extern.slf4j.Slf4j; import org.java_websocket.client.WebSocketClient; import java.math.BigDecimal; /** * K 线频道处理器。 * 公开频道,无需认证。订阅 1m K 线,解析后回调 {@link GateGridTradeService#onKline}。 * * @author Administrator */ @Slf4j public class CandlestickChannelHandler implements GateChannelHandler { private static final String CHANNEL_NAME = "futures.candlesticks"; private static final String INTERVAL = "1m"; private final String contract; private final GateGridTradeService gridTradeService; public CandlestickChannelHandler(String contract, GateGridTradeService gridTradeService) { this.contract = contract; this.gridTradeService = gridTradeService; } @Override public String getChannelName() { return CHANNEL_NAME; } @Override public void subscribe(WebSocketClient ws) { JSONObject subscribeMsg = new JSONObject(); subscribeMsg.put("time", System.currentTimeMillis() / 1000); subscribeMsg.put("channel", CHANNEL_NAME); subscribeMsg.put("event", "subscribe"); JSONArray payload = new JSONArray(); payload.add(INTERVAL); payload.add(contract); subscribeMsg.put("payload", payload); ws.send(subscribeMsg.toJSONString()); log.info("[{}] 已发送订阅请求,合约: {}, 周期: {}", CHANNEL_NAME, contract, INTERVAL); } @Override public void unsubscribe(WebSocketClient ws) { JSONObject unsubscribeMsg = new JSONObject(); unsubscribeMsg.put("time", System.currentTimeMillis() / 1000); unsubscribeMsg.put("channel", CHANNEL_NAME); unsubscribeMsg.put("event", "unsubscribe"); JSONArray payload = new JSONArray(); payload.add(INTERVAL); payload.add(contract); unsubscribeMsg.put("payload", payload); ws.send(unsubscribeMsg.toJSONString()); log.info("[{}] 已发送取消订阅请求,合约: {}, 周期: {}", CHANNEL_NAME, contract, INTERVAL); } @Override public boolean handleMessage(JSONObject response) { String channel = response.getString("channel"); if (!CHANNEL_NAME.equals(channel)) { return false; } try { JSONArray resultArray = response.getJSONArray("result"); if (resultArray == null || resultArray.isEmpty()) { log.warn("[{}] 数据为空", CHANNEL_NAME); return true; } JSONObject data = resultArray.getJSONObject(0); BigDecimal closePx = new BigDecimal(data.getString("c")); long t = data.getLong("t"); boolean windowClosed = data.getBooleanValue("w"); log.info("========== Gate K线数据 =========="); log.info("名称(n): {}", data.getString("n")); log.info("时间 : {}", DateUtil.TimeStampToDateTime(t)); log.info("开盘(o): {}", data.getString("o")); log.info("最高(h): {}", data.getString("h")); log.info("最低(l): {}", data.getString("l")); log.info("收盘(c): {}", data.getString("c")); log.info("成交量(v): {}", data.getString("v")); log.info("成交额(a): {}", data.getString("a")); log.info("K线完结(w): {}", windowClosed); log.info("=================================="); if (gridTradeService != null) { gridTradeService.onKline(closePx); } } catch (Exception e) { log.error("[{}] 处理数据失败", CHANNEL_NAME, e); } return true; } } src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionClosesChannelHandler.java
New file @@ -0,0 +1,57 @@ package com.xcong.excoin.modules.gateApi.wsHandler.handler; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.modules.gateApi.GateGridTradeService; import com.xcong.excoin.modules.gateApi.wsHandler.AbstractPrivateChannelHandler; import lombok.extern.slf4j.Slf4j; import java.math.BigDecimal; /** * 平仓频道处理器。 * 私有频道,需认证。解析平仓推送后回调 {@link GateGridTradeService#onPositionClose}。 * * @author Administrator */ @Slf4j public class PositionClosesChannelHandler extends AbstractPrivateChannelHandler { private static final String CHANNEL_NAME = "futures.position_closes"; public PositionClosesChannelHandler(String apiKey, String apiSecret, String contract, GateGridTradeService gridTradeService) { super(CHANNEL_NAME, apiKey, apiSecret, contract, gridTradeService); } @Override public boolean handleMessage(JSONObject response) { String channel = response.getString("channel"); if (!CHANNEL_NAME.equals(channel)) { return false; } try { JSONArray resultArray = response.getJSONArray("result"); if (resultArray == null || resultArray.isEmpty()) { return true; } for (int i = 0; i < resultArray.size(); i++) { JSONObject item = resultArray.getJSONObject(i); if (!getContract().equals(item.getString("contract"))) { continue; } BigDecimal pnl = new BigDecimal(item.getString("pnl")); String side = item.getString("side"); log.info("[{}] 推送: contract={}, side={}, pnl={}", CHANNEL_NAME, getContract(), side, pnl); if (getGridTradeService() != null) { getGridTradeService().onPositionClose(getContract(), side, pnl); } } } catch (Exception e) { log.error("[{}] 处理数据失败", CHANNEL_NAME, e); } return true; } } src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionsChannelHandler.java
New file @@ -0,0 +1,58 @@ package com.xcong.excoin.modules.gateApi.wsHandler.handler; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.modules.gateApi.GateGridTradeService; import com.xcong.excoin.modules.gateApi.wsHandler.AbstractPrivateChannelHandler; import lombok.extern.slf4j.Slf4j; import java.math.BigDecimal; /** * 仓位频道处理器。 * 私有频道,需认证。解析仓位推送后回调 {@link GateGridTradeService#onPositionUpdate}。 * * @author Administrator */ @Slf4j public class PositionsChannelHandler extends AbstractPrivateChannelHandler { private static final String CHANNEL_NAME = "futures.positions"; public PositionsChannelHandler(String apiKey, String apiSecret, String contract, GateGridTradeService gridTradeService) { super(CHANNEL_NAME, apiKey, apiSecret, contract, gridTradeService); } @Override public boolean handleMessage(JSONObject response) { String channel = response.getString("channel"); if (!CHANNEL_NAME.equals(channel)) { return false; } try { JSONArray resultArray = response.getJSONArray("result"); if (resultArray == null || resultArray.isEmpty()) { return true; } for (int i = 0; i < resultArray.size(); i++) { JSONObject pos = resultArray.getJSONObject(i); if (!getContract().equals(pos.getString("contract"))) { continue; } String mode = pos.getString("mode"); BigDecimal size = new BigDecimal(pos.getString("size")); BigDecimal entryPrice = new BigDecimal(pos.getString("entry_price")); log.info("[{}] 推送: contract={}, mode={}, size={}, entry_price={}", CHANNEL_NAME, getContract(), mode, size, entryPrice); if (getGridTradeService() != null) { getGridTradeService().onPositionUpdate(getContract(), mode, size, entryPrice); } } } catch (Exception e) { log.error("[{}] 处理数据失败", CHANNEL_NAME, e); } return true; } }