| | |
| | | package com.xcong.excoin.modules.okxNewPrice; |
| | | |
| | | import cn.hutool.core.collection.CollUtil; |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import cn.hutool.json.JSONException; |
| | | import cn.hutool.json.JSONUtil; |
| | | 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.TradingStrategy; |
| | | 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.*; |
| | | import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.CoinEnums; |
| | | import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.OrderParamEnums; |
| | |
| | | import java.math.BigDecimal; |
| | | import java.net.URI; |
| | | import java.net.URISyntaxException; |
| | | import java.util.ArrayList; |
| | | import java.util.Collection; |
| | | import java.util.LinkedHashMap; |
| | | import java.util.List; |
| | | import java.util.*; |
| | | import java.util.concurrent.*; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicReference; |
| | |
| | | private final AtomicBoolean isConnecting = new AtomicBoolean(false); |
| | | private final AtomicBoolean isInitialized = new AtomicBoolean(false); |
| | | |
| | | private static final String CHANNEL = "candle5m"; |
| | | // private static final String CHANNEL = "mark-price"; |
| | | private static final String CHANNEL = "candle1m"; |
| | | // private static final String CHANNEL = "candle15m"; |
| | | |
| | | // 心跳超时时间(秒),小于30秒 |
| | |
| | | |
| | | private static final String WS_URL_MONIPAN = "wss://wspap.okx.com:8443/ws/v5/business"; |
| | | private static final String WS_URL_SHIPAN = "wss://ws.okx.com:8443/ws/v5/business"; |
| | | private static final boolean isAccountType = true; |
| | | private static final boolean isAccountType = false; |
| | | |
| | | /** |
| | | * 建立与 OKX WebSocket 服务器的连接。 |
| | |
| | | */ |
| | | private void handleWebSocketMessage(String message) { |
| | | try { |
| | | if ("pong".equals(message)) { |
| | | log.debug("{}: 收到心跳响应"); |
| | | cancelPongTimeout(); |
| | | return; |
| | | } |
| | | JSONObject response = JSON.parseObject(message); |
| | | String event = response.getString("event"); |
| | | |
| | |
| | | log.debug("收到pong响应"); |
| | | cancelPongTimeout(); |
| | | } else { |
| | | processPushData(response); |
| | | // processPushData(response); |
| | | processPushDataV2(response); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("处理WebSocket消息失败: {}", message, e); |
| | |
| | | * |
| | | * @param response 包含价格数据的 JSON 对象 |
| | | */ |
| | | private void processPushData(JSONObject response) { |
| | | private void processPushDataV2(JSONObject response) { |
| | | try { |
| | | /** |
| | | * { |
| | |
| | | BigDecimal lowPx = new BigDecimal(data.getString(3)); |
| | | BigDecimal closePx = new BigDecimal(data.getString(4)); |
| | | BigDecimal vol = new BigDecimal(data.getString(5)); |
| | | //ts String 开始时间,Unix时间戳的毫秒数格式,如 1597026383085 转日期:2020-08-07 15:13:03.085 |
| | | String time = DateUtil.TimeStampToDateTime(Long.parseLong(data.getString(0))); |
| | | /** |
| | | * K线状态 |
| | | * 0:K线未完结 |
| | |
| | | */ |
| | | String confirm = data.getString(8); |
| | | if ("1".equals(confirm)){ |
| | | log.info("{}开仓{}:{}",time,closePx,instId); |
| | | //调用策略 |
| | | // 创建交易策略 |
| | | TradingStrategy tradingStrategy = new TradingStrategy(); |
| | | // 创建策略实例 |
| | | // MacdMaStrategy strategy = new MacdMaStrategy(); |
| | | MacdEmaStrategy strategy = new MacdEmaStrategy(); |
| | | |
| | | // 生成100个15分钟价格数据点 |
| | | List<Kline> kline15MinuteData = getKlineDataByInstIdAndBar(instId, "15m"); |
| | | //stream流获取kline15MinuteData中的o数据的集合 |
| | | List<BigDecimal> prices = kline15MinuteData.stream() |
| | | // 生成200个1m价格数据点 |
| | | List<Kline> kline1MinuteData = getKlineDataByInstIdAndBar(instId, "1m"); |
| | | List<BigDecimal> historicalPrices1M = kline1MinuteData.stream() |
| | | .map(Kline::getC) |
| | | .collect(Collectors.toList()); |
| | | |
| | | // 生成对应的高、低、收盘价数据 |
| | | List<BigDecimal> high = kline15MinuteData.stream() |
| | | .map(Kline::getH) |
| | | .collect(Collectors.toList()); |
| | | List<BigDecimal> low = kline15MinuteData.stream() |
| | | .map(Kline::getL) |
| | | .collect(Collectors.toList()); |
| | | List<BigDecimal> close = prices; |
| | | // 生成200个1D价格数据点 |
| | | // List<Kline> kline1DayData = getKlineDataByInstIdAndBar(instId, "1D"); |
| | | // List<BigDecimal> historicalPrices1D = kline1DayData.stream() |
| | | // .map(Kline::getC) |
| | | // .collect(Collectors.toList()); |
| | | // log.info("1D:{}", JSONUtil.parse( historicalPrices1D)); |
| | | // 使用策略分析最新价格数据 |
| | | // MacdMaStrategy.TradingOrder tradingOrderOpenOpen = strategy.generateTradingOrder(historicalPrices1M,historicalPrices1D,MacdMaStrategy.OperationType.open.name()); |
| | | MacdEmaStrategy.TradingOrder tradingOrderOpenOpen = strategy.generateTradingOrder(historicalPrices1M, MacdMaStrategy.OperationType.open.name()); |
| | | if (tradingOrderOpenOpen == null){ |
| | | return; |
| | | } |
| | | |
| | | // 生成成交量数据 |
| | | List<BigDecimal> volume = kline15MinuteData.stream() |
| | | .map(Kline::getVol) |
| | | .collect(Collectors.toList()); |
| | | |
| | | // 获取最新价格 |
| | | BigDecimal currentPrice = closePx; |
| | | |
| | | // 生成多周期价格数据(5分钟、1小时、4小时) |
| | | List<Kline> kline5MinuteData = getKlineDataByInstIdAndBar(instId, "5m"); |
| | | List<BigDecimal> fiveMinPrices = kline5MinuteData.stream() |
| | | .map(Kline::getC) |
| | | .collect(Collectors.toList()); |
| | | List<Kline> kline60MinuteData = getKlineDataByInstIdAndBar(instId, "1H"); |
| | | List<BigDecimal> oneHourPrices = kline60MinuteData.stream() |
| | | .map(Kline::getC) |
| | | .collect(Collectors.toList()); |
| | | List<Kline> kline240MinuteData = getKlineDataByInstIdAndBar(instId, "4H"); |
| | | List<BigDecimal> fourHourPrices = kline240MinuteData.stream() |
| | | .map(Kline::getC) |
| | | .collect(Collectors.toList()); |
| | | |
| | | // 其他参数 |
| | | BigDecimal fundingRate = new BigDecimal("0.001"); // 正常资金费率 |
| | | boolean hasLargeTransfer = false; // 无大额转账 |
| | | boolean hasUpcomingEvent = false; // 无即将到来的重大事件 |
| | | // 确定市场方向 |
| | | TradingStrategy.Direction direction = tradingStrategy.getDirection(prices, high, low, close, currentPrice); |
| | | System.out.println("市场方向(15分钟): " + direction); |
| | | // if (direction == TradingStrategy.Direction.RANGING){ |
| | | // return; |
| | | // } |
| | | |
| | | /** |
| | | * 获取当前网格信息 |
| | | * 根据当前网格的持仓方向获取反方向是否存在持仓 |
| | | * 如果持有,直接止损 |
| | | */ |
| | | Collection<OkxQuantWebSocketClient> allClients = clientManager.getAllClients(); |
| | | //如果为空,则直接返回 |
| | | if (allClients.isEmpty()) { |
| | |
| | | for (OkxQuantWebSocketClient client : clientManager.getAllClients()) { |
| | | String accountName = client.getAccountName(); |
| | | if (accountName != null) { |
| | | TradingStrategy.SignalType signal = TradingStrategy.SignalType.NONE; |
| | | TradeRequestParam tradeRequestParam = new TradeRequestParam(); |
| | | // 检查当前持仓状态 |
| | | boolean hasLongPosition = false; // 示例:无当前做多持仓 |
| | | boolean hasShortPosition = false; // 示例:无当前做空持仓 |
| | | //先判断账户是否有持多仓 |
| | | String positionLongAccountName = PositionsWs.initAccountName(accountName, CoinEnums.POSSIDE_LONG.getCode()); |
| | | BigDecimal imrLong = PositionsWs.getAccountMap(positionLongAccountName).get("imr"); |
| | | if (imrLong != null && imrLong.compareTo(BigDecimal.ZERO) > 0){ |
| | | log.info("账户{}有持多仓", accountName); |
| | | hasLongPosition = true; |
| | | if (ObjectUtil.isNotEmpty(tradingOrderOpenOpen)){ |
| | | // 根据信号执行交易操作 |
| | | TradeRequestParam tradeRequestParam = new TradeRequestParam(); |
| | | |
| | | } |
| | | //先判断账户是否有持空仓 |
| | | String positionShortAccountName = PositionsWs.initAccountName(accountName, CoinEnums.POSSIDE_LONG.getCode()); |
| | | BigDecimal imrShort = PositionsWs.getAccountMap(positionShortAccountName).get("imr"); |
| | | if (imrShort != null && imrShort.compareTo(BigDecimal.ZERO) > 0){ |
| | | log.info("账户{}有持空仓", accountName); |
| | | hasShortPosition = true; |
| | | } |
| | | signal = tradingStrategy.generateSignal(prices, high, low, close, volume, currentPrice, |
| | | hasLongPosition, hasShortPosition, |
| | | fiveMinPrices, oneHourPrices, fourHourPrices, |
| | | fundingRate, hasLargeTransfer, hasUpcomingEvent); |
| | | log.info("账户{}交易信号: " + signal, accountName); |
| | | if (TradingStrategy.SignalType.NONE == signal) { |
| | | continue; |
| | | }else if (TradingStrategy.SignalType.BUY == signal){ |
| | | tradeRequestParam = caoZuoService.caoZuoStrategy(accountName, String.valueOf(currentPrice), CoinEnums.POSSIDE_LONG.getCode()); |
| | | tradeRequestParam.setSide(CoinEnums.SIDE_BUY.getCode()); |
| | | String clOrdId = WsParamBuild.getOrderNum(CoinEnums.SIDE_BUY.getCode()); |
| | | String posSide = tradingOrderOpenOpen.getPosSide(); |
| | | tradeRequestParam.setPosSide(posSide); |
| | | String currentPrice = String.valueOf(closePx); |
| | | tradeRequestParam = caoZuoService.caoZuoStrategy(accountName, currentPrice, posSide); |
| | | |
| | | String side = tradingOrderOpenOpen.getSide(); |
| | | tradeRequestParam.setSide(side); |
| | | |
| | | String clOrdId = WsParamBuild.getOrderNum(side); |
| | | tradeRequestParam.setClOrdId(clOrdId); |
| | | |
| | | String sz = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.BUY_CNT_INIT.name()); |
| | | tradeRequestParam.setSz(sz); |
| | | TradeOrderWs.orderEvent(client.getWebSocketClient(), tradeRequestParam); |
| | | }else if (TradingStrategy.SignalType.SELL == signal){ |
| | | tradeRequestParam = caoZuoService.caoZuoStrategy(accountName, String.valueOf(currentPrice), CoinEnums.POSSIDE_SHORT.getCode()); |
| | | tradeRequestParam.setSide(CoinEnums.SIDE_SELL.getCode()); |
| | | String clOrdId = WsParamBuild.getOrderNum(CoinEnums.SIDE_SELL.getCode()); |
| | | } |
| | | } |
| | | } |
| | | }else{ |
| | | log.info("{}平仓{}:{}",time,closePx,instId); |
| | | //调用策略 |
| | | // 创建策略实例 |
| | | MacdMaStrategy strategy = new MacdMaStrategy(); |
| | | |
| | | // 生成200个1m价格数据点 |
| | | List<Kline> kline1MinuteData = getKlineDataByInstIdAndBar(instId, "1m"); |
| | | List<BigDecimal> historicalPrices1M = kline1MinuteData.stream() |
| | | .map(Kline::getC) |
| | | .collect(Collectors.toList()); |
| | | |
| | | |
| | | // 生成200个1D价格数据点 |
| | | List<Kline> kline1DayData = getKlineDataByInstIdAndBar(instId, "1D"); |
| | | List<BigDecimal> historicalPrices1D = kline1DayData.stream() |
| | | .map(Kline::getC) |
| | | .collect(Collectors.toList()); |
| | | // 使用策略分析最新价格数据 |
| | | MacdMaStrategy.TradingOrder tradingOrderOpenClose = strategy.generateTradingOrder(historicalPrices1M,historicalPrices1D,MacdMaStrategy.OperationType.close.name()); |
| | | if (tradingOrderOpenClose == null){ |
| | | return; |
| | | } |
| | | |
| | | Collection<OkxQuantWebSocketClient> allClients = clientManager.getAllClients(); |
| | | //如果为空,则直接返回 |
| | | if (allClients.isEmpty()) { |
| | | return; |
| | | } |
| | | // 获取所有OkxQuantWebSocketClient实例 |
| | | for (OkxQuantWebSocketClient client : clientManager.getAllClients()) { |
| | | String accountName = client.getAccountName(); |
| | | if (accountName != null) { |
| | | if (ObjectUtil.isNotEmpty(tradingOrderOpenClose)){ |
| | | // 根据信号执行交易操作 |
| | | TradeRequestParam tradeRequestParam = new TradeRequestParam(); |
| | | tradeRequestParam.setAccountName(accountName); |
| | | tradeRequestParam.setMarkPx(String.valueOf(closePx)); |
| | | tradeRequestParam.setInstId(CoinEnums.HE_YUE.getCode()); |
| | | tradeRequestParam.setTdMode(CoinEnums.CROSS.getCode()); |
| | | tradeRequestParam.setOrdType(CoinEnums.ORDTYPE_MARKET.getCode()); |
| | | String posSide = tradingOrderOpenClose.getPosSide(); |
| | | tradeRequestParam.setPosSide(posSide); |
| | | |
| | | String side = tradingOrderOpenClose.getSide(); |
| | | tradeRequestParam.setSide(side); |
| | | |
| | | String clOrdId = WsParamBuild.getOrderNum(side); |
| | | tradeRequestParam.setClOrdId(clOrdId); |
| | | String sz = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.BUY_CNT_INIT.name()); |
| | | tradeRequestParam.setSz(sz); |
| | | TradeOrderWs.orderEvent(client.getWebSocketClient(), tradeRequestParam); |
| | | }else if (TradingStrategy.SignalType.CLOSE_BUY == signal){ |
| | | tradeRequestParam = caoZuoService.caoZuoStrategy(accountName, String.valueOf(currentPrice), CoinEnums.POSSIDE_LONG.getCode()); |
| | | tradeRequestParam.setSide(CoinEnums.SIDE_SELL.getCode()); |
| | | String clOrdId = WsParamBuild.getOrderNum(CoinEnums.SIDE_SELL.getCode()); |
| | | tradeRequestParam.setClOrdId(clOrdId); |
| | | BigDecimal pos = PositionsWs.getAccountMap(PositionsWs.initAccountName(accountName, CoinEnums.POSSIDE_LONG.getCode())).get("pos"); |
| | | if (BigDecimal.ZERO.compareTo( pos) >= 0) { |
| | | tradeRequestParam.setTradeType(OrderParamEnums.TRADE_NO.getValue()); |
| | | } |
| | | tradeRequestParam.setSz(String.valueOf( pos)); |
| | | TradeOrderWs.orderEvent(client.getWebSocketClient(), tradeRequestParam); |
| | | }else if (TradingStrategy.SignalType.CLOSE_SELL == signal){ |
| | | tradeRequestParam = caoZuoService.caoZuoStrategy(accountName, String.valueOf(currentPrice), CoinEnums.POSSIDE_SHORT.getCode()); |
| | | tradeRequestParam.setSide(CoinEnums.SIDE_BUY.getCode()); |
| | | String clOrdId = WsParamBuild.getOrderNum(CoinEnums.SIDE_BUY.getCode()); |
| | | tradeRequestParam.setClOrdId(clOrdId); |
| | | BigDecimal pos = PositionsWs.getAccountMap(PositionsWs.initAccountName(accountName, CoinEnums.POSSIDE_SHORT.getCode())).get("pos"); |
| | | if (BigDecimal.ZERO.compareTo( pos) >= 0) { |
| | | tradeRequestParam.setTradeType(OrderParamEnums.TRADE_NO.getValue()); |
| | | } |
| | | tradeRequestParam.setSz(String.valueOf( pos)); |
| | | TradeOrderWs.orderEvent(client.getWebSocketClient(), tradeRequestParam); |
| | | |
| | | String positionAccountName = PositionsWs.initAccountName(accountName, posSide); |
| | | BigDecimal pos = PositionsWs.getAccountMap(positionAccountName).get("pos"); |
| | | tradeRequestParam.setSz(String.valueOf(pos)); |
| | | TradeOrderWs.orderZhiYingZhiSunEventNoState(client.getWebSocketClient(), tradeRequestParam); |
| | | } |
| | | } |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | |
| | | |
| | | /** |
| | | * 触发所有账号的量化操作 |
| | | * @param markPx 当前标记价格 |
| | | */ |
| | | private void triggerQuantOperations(String markPx) { |
| | | try { |
| | | // 1. 判断当前价格属于哪个网格 |
| | | WangGeListEnum gridByPriceNew = WangGeListEnum.getGridByPrice(new BigDecimal(markPx)); |
| | | if (gridByPriceNew == null) { |
| | | log.error("当前 K线频道{}不在任何网格范围内,无法触发量化操作", markPx); |
| | | return; |
| | | } |
| | | |
| | | } catch (Exception e) { |
| | | log.error("触发量化操作失败", e); |
| | | } |
| | | } |
| | | |
| | | private List<Kline> getKlineDataByInstIdAndBar(String instId, String bar) { |
| | | |
| | | |
| | | LinkedHashMap<String, Object> requestParam = new LinkedHashMap<>(); |
| | | requestParam.put("instId",instId); |
| | | requestParam.put("bar",bar); |
| | | requestParam.put("limit","100"); |
| | | String result = ExchangeLoginService.getInstance(ExchangeInfoEnum.OKX_UAT.name()).lineHistory(requestParam); |
| | | log.info("加载OKX-KLINE,{}", result); |
| | | JSONObject json = JSON.parseObject(result); |
| | | String data = json.getString("data"); |
| | | List<String[]> klinesList = JSON.parseArray(data, String[].class); |
| | | if(CollUtil.isEmpty(klinesList)){ |
| | | return null; |
| | | List<Kline> klineList = new ArrayList<>(); |
| | | try { |
| | | LinkedHashMap<String, Object> requestParam = new LinkedHashMap<>(); |
| | | requestParam.put("instId", instId); |
| | | requestParam.put("bar", bar); |
| | | requestParam.put("limit", "200"); |
| | | String result = ExchangeLoginService.getInstance(ExchangeInfoEnum.OKX_UAT.name()).lineHistory(requestParam); |
| | | JSONObject json = JSON.parseObject(result); |
| | | String data = json.getString("data"); |
| | | |
| | | if (data != null) { |
| | | List<String[]> klinesList = JSON.parseArray(data, String[].class); |
| | | if (!CollUtil.isEmpty(klinesList)) { |
| | | for (String[] s : klinesList) { |
| | | // 确保数组有足够的元素 |
| | | if (s != null && s.length >= 9) { |
| | | String s1 = s[8]; |
| | | try { |
| | | if ("1".equals(s1)){ |
| | | Kline kline = new Kline(); |
| | | kline.setTs(s[0]); |
| | | kline.setO(new BigDecimal(s[1])); |
| | | kline.setH(new BigDecimal(s[2])); |
| | | kline.setL(new BigDecimal(s[3])); |
| | | kline.setC(new BigDecimal(s[4])); |
| | | kline.setVol(new BigDecimal(s[5])); |
| | | kline.setConfirm(s[8]); |
| | | klineList.add(kline); |
| | | } |
| | | } catch (NumberFormatException e) { |
| | | log.error("K线数据转换为BigDecimal失败: {}", Arrays.toString(s), e); |
| | | } |
| | | } else { |
| | | log.warn("K线数据数组长度不足: {}", Arrays.toString(s)); |
| | | } |
| | | } |
| | | } |
| | | } else { |
| | | log.warn("K线数据为空"); |
| | | } |
| | | } catch (JSONException e) { |
| | | log.error("K线数据解析失败", e); |
| | | } catch (Exception e) { |
| | | log.error("获取K线数据异常", e); |
| | | } |
| | | ArrayList<Kline> objects = new ArrayList<>(); |
| | | for(String[] s : klinesList) { |
| | | Kline kline = new Kline(); |
| | | kline.setTs(s[0]); |
| | | kline.setO(new BigDecimal(s[1])); |
| | | kline.setH(new BigDecimal(s[2])); |
| | | kline.setL(new BigDecimal(s[3])); |
| | | kline.setC(new BigDecimal(s[4])); |
| | | kline.setVol(new BigDecimal(s[5])); |
| | | kline.setConfirm(s[8]); |
| | | objects.add(kline); |
| | | } |
| | | return objects; |
| | | return klineList; |
| | | } |
| | | |
| | | /** |
| | |
| | | private void sendPing() { |
| | | try { |
| | | if (webSocketClient != null && webSocketClient.isOpen()) { |
| | | JSONObject ping = new JSONObject(); |
| | | ping.put("op", "ping"); |
| | | webSocketClient.send(ping.toJSONString()); |
| | | webSocketClient.send("ping"); |
| | | log.debug("发送ping请求"); |
| | | } |
| | | } catch (Exception e) { |