| | |
| | | package com.xcong.excoin.modules.gateApi; |
| | | |
| | | import cn.hutool.core.collection.CollUtil; |
| | | import cn.hutool.json.JSONException; |
| | | 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.indicator.macdAndMatrategy.MacdEmaStrategy; |
| | | import com.xcong.excoin.modules.okxNewPrice.indicator.macdAndMatrategy.MacdMaStrategy; |
| | | import com.xcong.excoin.modules.okxNewPrice.okxWs.InstrumentsWs; |
| | | 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.Kline; |
| | | import com.xcong.excoin.modules.okxNewPrice.okxWs.param.TradeRequestParam; |
| | | import com.xcong.excoin.modules.okxNewPrice.okxWs.wanggeList.WangGeListService; |
| | | import com.xcong.excoin.modules.okxNewPrice.okxpi.config.ExchangeInfoEnum; |
| | | import com.xcong.excoin.modules.okxNewPrice.okxpi.config.ExchangeLoginService; |
| | | import com.xcong.excoin.modules.okxNewPrice.utils.SSLConfig; |
| | | import com.xcong.excoin.modules.okxNewPrice.utils.WsParamBuild; |
| | | 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.util.*; |
| | | import java.util.concurrent.*; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * Gate K线 WebSocket 客户端类,用于连接 Gate 的 WebSocket 接口, |
| | |
| | | private final AtomicBoolean isInitialized = new AtomicBoolean(false); |
| | | |
| | | private static final String CHANNEL = "futures.candlesticks"; |
| | | private static final String POSITIONS_CHANNEL = "futures.positions"; |
| | | private static final String FUTURES_PING = "futures.ping"; |
| | | private static final String FUTURES_PONG = "futures.pong"; |
| | | private static final String GATE_INTERVAL = "1m"; |
| | | private static final String GATE_CONTRACT = "XAUT_USDT"; |
| | | |
| | | private GateGridTradeService gridTradeService; |
| | | |
| | | private final String apiKey; |
| | | private final String apiSecret; |
| | | |
| | | private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); |
| | | |
| | | // 心跳超时时间(秒),小于30秒 |
| | | private static final int HEARTBEAT_TIMEOUT = 10; |
| | |
| | | public GateKlineWebSocketClient(CaoZuoService caoZuoService, |
| | | GateWebSocketClientManager clientManager, |
| | | WangGeListService wangGeListService, |
| | | GateGridTradeService gridTradeService |
| | | GateGridTradeService gridTradeService, |
| | | String apiKey, String apiSecret |
| | | ) { |
| | | this.caoZuoService = caoZuoService; |
| | | this.clientManager = clientManager; |
| | | this.wangGeListService = wangGeListService; |
| | | this.gridTradeService = gridTradeService; |
| | | this.apiKey = apiKey; |
| | | this.apiSecret = apiSecret; |
| | | } |
| | | |
| | | /** |
| | |
| | | |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | unsubscribeKlineChannels(); |
| | | unsubscribePositionsChannels(); |
| | | try { |
| | | Thread.sleep(500); |
| | | } catch (InterruptedException e) { |
| | |
| | | if (sharedExecutor != null && !sharedExecutor.isShutdown()) { |
| | | resetHeartbeatTimer(); |
| | | subscribeKlineChannels(); |
| | | subscribePositionsChannels(); |
| | | subscribePingChannels(); |
| | | } else { |
| | | log.warn("应用正在关闭,忽略WebSocket连接成功回调"); |
| | |
| | | log.info("已发送 futures.ping"); |
| | | } |
| | | |
| | | private void subscribePositionsChannels() { |
| | | JSONObject subscribeMsg = new JSONObject(); |
| | | long timeSec = System.currentTimeMillis() / 1000; |
| | | subscribeMsg.put("time", timeSec); |
| | | subscribeMsg.put("channel", POSITIONS_CHANNEL); |
| | | subscribeMsg.put("event", "subscribe"); |
| | | JSONArray payload = new JSONArray(); |
| | | payload.add("user_id"); |
| | | 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("已发送仓位频道订阅请求(含认证),合约: {}", GATE_CONTRACT); |
| | | } |
| | | |
| | | 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(), "HmacSHA512"); |
| | | mac.init(spec); |
| | | byte[] hash = mac.doFinal(message.getBytes()); |
| | | 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("签名计算失败", e); |
| | | return ""; |
| | | } |
| | | } |
| | | |
| | | private void unsubscribeKlineChannels() { |
| | | JSONObject unsubscribeMsg = new JSONObject(); |
| | | unsubscribeMsg.put("time", System.currentTimeMillis() / 1000); |
| | |
| | | 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); |
| | | } |
| | | |
| | | /** |
| | |
| | | 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); |
| | | } |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("处理WebSocket消息失败: {}", message, e); |
| | |
| | | } |
| | | } |
| | | |
| | | 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 请求来维持连接。 |