package com.xcong.excoin.modules.okxApi.wsHandler.handler; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.modules.okxApi.OkxGridTradeService; import com.xcong.excoin.modules.okxApi.enums.OkxEnums; import com.xcong.excoin.modules.okxApi.wsHandler.OkxChannelHandler; import lombok.extern.slf4j.Slf4j; import org.java_websocket.client.WebSocketClient; import java.math.BigDecimal; @Slf4j public class OkxPositionsChannelHandler implements OkxChannelHandler { private final String instId; private final OkxGridTradeService gridTradeService; public OkxPositionsChannelHandler(String instId, OkxGridTradeService gridTradeService) { this.instId = instId; this.gridTradeService = gridTradeService; } @Override public String getChannelName() { return OkxEnums.CHANNEL_POSITIONS; } @Override public void subscribe(WebSocketClient ws) { JSONObject msg = new JSONObject(); msg.put("op", "subscribe"); JSONArray args = new JSONArray(); JSONObject arg = new JSONObject(); arg.put("channel", OkxEnums.CHANNEL_POSITIONS); arg.put("instType", OkxEnums.INSTTYPE_SWAP); arg.put("instId", instId); args.add(arg); msg.put("args", args); ws.send(msg.toJSONString()); log.info("[{}] 订阅成功, 合约:{}", OkxEnums.CHANNEL_POSITIONS, instId); } @Override public void unsubscribe(WebSocketClient ws) { JSONObject msg = new JSONObject(); msg.put("op", "unsubscribe"); JSONArray args = new JSONArray(); JSONObject arg = new JSONObject(); arg.put("channel", OkxEnums.CHANNEL_POSITIONS); arg.put("instType", OkxEnums.INSTTYPE_SWAP); arg.put("instId", instId); args.add(arg); msg.put("args", args); ws.send(msg.toJSONString()); log.info("[{}] 取消订阅成功", OkxEnums.CHANNEL_POSITIONS); } @Override public boolean handleMessage(JSONObject response) { JSONObject argObj = response.getJSONObject("arg"); if (argObj == null) { return false; } String channel = argObj.getString("channel"); if (!OkxEnums.CHANNEL_POSITIONS.equals(channel)) { return false; } try { JSONArray dataArray = response.getJSONArray("data"); if (dataArray == null || dataArray.isEmpty()) { return true; } for (int i = 0; i < dataArray.size(); i++) { JSONObject pos = dataArray.getJSONObject(i); if (!instId.equals(pos.getString("instId"))) { continue; } String posSide = pos.getString("posSide"); BigDecimal size = new BigDecimal(pos.getString("pos")); BigDecimal avgPx = pos.containsKey("avgPx") && pos.getString("avgPx") != null ? new BigDecimal(pos.getString("avgPx")) : BigDecimal.ZERO; log.info("[{}] 持仓更新, 方向:{}, 数量:{}, 均价:{}, 未实现盈亏:{}, 保证金:{}", OkxEnums.CHANNEL_POSITIONS, posSide, size, avgPx, pos.get("upl"), pos.get("imr")); if (gridTradeService != null) { gridTradeService.onPositionUpdate(posSide, size, avgPx); } } } catch (Exception e) { log.error("[{}] 处理数据失败", OkxEnums.CHANNEL_POSITIONS, e); } return true; } }