package com.xcong.excoin.modules.okxApi; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.utils.dingtalk.DingTalkUtils; import lombok.extern.slf4j.Slf4j; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; /** * OKX 网格交易策略引擎 — 多空对冲网格。 * *

策略原理

* 以空仓基底入场价(shortBaseEntryPrice)为价格基准,向上/向下各生成一个价格网格队列。 * 价格触发网格层级时挂条件单,成交后自动挂止盈单。每笔止盈盈利 = step - minTick。 * *

与 GateGridTradeService 的关系

* 策略逻辑完全一致,仅 API 层(REST/WS/签名)替换为 OKX 实现。 * GridElement 和 TraderParam 从 gateApi 包复用(交易所无关的数据模型)。 * *

完整生命周期

*
 *   init() → startGrid() → WAITING_KLINE
 *     ↓
 *   onKline(首根K线) → OPENING → 异步市价双开基底(开多+开空)
 *     ↓
 *   onPositionUpdate() → 基底成交 → baseLongOpened && baseShortOpened
 *     ↓
 *   tryGenerateQueues()
 *     ├── generateShortQueue()   ← 空仓价格队列(降序,从 shortBaseEntryPrice-step 向下)
 *     ├── generateLongQueue()    ← 多仓价格队列(升序,从 shortBaseEntryPrice+step 向上)
 *     ├── updateGridElements()   ← 构建 GridElement 列表 + TraderParam + 全局索引
 *     ├── 挂基座止盈单(ID=0 的 long/short takeProfit)
 *     └── 挂初始条件单(up=-1 多单, down=1 空单)
 *     ↓
 *   state = ACTIVE
 *     ↓
 *   onKline() → processLongGrid() + processShortGrid()
 *     ├── 匹配队列元素 → 队列补偿 → 保证金检查
 *     ├── 首元素方向:挂条件开仓单 → 订单ID + GridElement状态同步
 *     └── 反向守卫:在 downGrid 位置挂对向单
 *     ↓
 *   onAutoOrder() ← orders-algo WS 推送
 *     ├── 匹配止盈单ID → 清空止盈状态(已成交)
 *     └── 匹配挂单ID → 挂止盈条件单 → 止盈ID + GridElement状态同步
 * 
* * @author Administrator */ @Slf4j public class OkxGridTradeService { public enum StrategyState { WAITING_KLINE, OPENING, ACTIVE, STOPPED } /** 止盈条件单 order_type:平多仓 */ private static final String ORDER_TYPE_CLOSE_LONG = "plan-close-long-position"; /** 止盈条件单 order_type:平空仓 */ private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position"; private final OkxConfig config; private final OkxTradeExecutor executor; private volatile StrategyState state = StrategyState.WAITING_KLINE; /** 空仓价格队列,降序排列(大→小),容量 gridQueueSize */ private final List shortPriceQueue = Collections.synchronizedList(new ArrayList<>()); /** 多仓价格队列,升序排列(小→大),容量 gridQueueSize */ private final List longPriceQueue = Collections.synchronizedList(new ArrayList<>()); private final List totalLongPriceQueue = Collections.synchronizedList(new ArrayList<>()); private final List totalShortPriceQueue = Collections.synchronizedList(new ArrayList<>()); /** 当前多仓条件单映射 */ private final Map currentLongOrderIds = Collections.synchronizedMap(new LinkedHashMap<>()); /** 当前空仓条件单映射 */ private final Map currentShortOrderIds = Collections.synchronizedMap(new LinkedHashMap<>()); /** 基底空头入场价 */ private BigDecimal shortBaseEntryPrice; /** 基底多头入场价 */ private BigDecimal longBaseEntryPrice; /** 基底多头是否已开 */ private volatile boolean baseLongOpened = false; /** 基底空头是否已开 */ private volatile boolean baseShortOpened = false; /** 空头是否活跃 */ private volatile boolean shortActive = false; /** 多头是否活跃 */ private volatile boolean longActive = false; /** 多头累计止损张数 */ private volatile int accumulatedLongLossCount = 0; /** 空头累计止损张数 */ private volatile int accumulatedShortLossCount = 0; private volatile BigDecimal lastKlinePrice; private volatile BigDecimal markPrice = BigDecimal.ZERO; private volatile BigDecimal cumulativePnl = BigDecimal.ZERO; private volatile BigDecimal unrealizedPnl = BigDecimal.ZERO; private volatile BigDecimal longEntryPrice = BigDecimal.ZERO; private volatile BigDecimal shortEntryPrice = BigDecimal.ZERO; private volatile BigDecimal longPositionSize = BigDecimal.ZERO; private volatile BigDecimal shortPositionSize = BigDecimal.ZERO; private volatile BigDecimal initialPrincipal = BigDecimal.ZERO; private volatile OkxKlineWebSocketClient wsClient; public OkxGridTradeService(OkxConfig config) { this.config = config; this.executor = new OkxTradeExecutor(config); } // ---- 仓位模式(替代 Gate 的 Position.ModeEnum)---- /** OKX 持仓方向枚举 */ public enum OkxPosMode { LONG, SHORT } /** 持仓查询结果 */ static class OkxPositionInfo { String size; String entryPrice; } // ---- 初始化 ---- /** * 初始化策略环境:获取账户信息 → 切双向持仓 → 清旧条件单 → 平仓 → 设杠杆。 */ public void init() { try { JSONObject account = executorGet("/api/v5/account/balance"); JSONArray dataArr = account.getJSONArray("data"); if (dataArr != null && !dataArr.isEmpty()) { JSONArray details = dataArr.getJSONObject(0).getJSONArray("details"); if (details != null) { for (int i = 0; i < details.size(); i++) { JSONObject currency = details.getJSONObject(i); if ("USDT".equals(currency.getString("ccy"))) { this.initialPrincipal = currency.getBigDecimal("eq"); log.info("[OKX] 初始本金(USDT余额): {}", initialPrincipal); break; } } } } // 设置双向持仓模式 JSONObject posModeBody = new JSONObject(); posModeBody.put("posMode", config.getPositionMode()); executorPost("/api/v5/account/set-position-mode", posModeBody.toJSONString()); log.info("[OKX] 持仓模式已设为: {}", config.getPositionMode()); // 设置杠杆 JSONObject levBody = new JSONObject(); levBody.put("instId", config.getContract()); levBody.put("lever", config.getLeverage()); levBody.put("mgnMode", config.getMarginMode()); executorPost("/api/v5/account/set-leverage", levBody.toJSONString()); log.info("[OKX] 杠杆已设为: {}x {}", config.getLeverage(), config.getMarginMode()); executor.cancelAllPriceTriggeredOrders(); log.info("[OKX] 旧条件单已清除"); closeExistingPositions(); log.info("[OKX] 初始化完成"); } catch (Exception e) { log.error("[OKX] 初始化失败", e); } } /** * 平掉当前合约的所有已有仓位。 */ private void closeExistingPositions() { try { JSONObject resp = executorGet("/api/v5/account/positions?instType=SWAP"); JSONArray data = resp.getJSONArray("data"); if (data == null || data.isEmpty()) { log.info("[OKX] 无已有仓位"); return; } for (int i = 0; i < data.size(); i++) { JSONObject pos = data.getJSONObject(i); String instId = pos.getString("instId"); if (instId == null || !instId.equals(config.getContract())) { continue; } String posVal = pos.getString("pos"); if (posVal == null || "0".equals(posVal)) { continue; } String posSide = pos.getString("posSide"); String side = "long".equals(posSide) ? "sell" : "buy"; JSONObject body = new JSONObject(); body.put("instId", config.getContract()); body.put("tdMode", "cross"); body.put("side", side); body.put("posSide", posSide); body.put("ordType", "market"); body.put("sz", posVal); executorPost("/api/v5/trade/order", body.toJSONString()); log.info("[OKX] 平已有仓位, posSide:{}, sz:{}", posSide, posVal); } } catch (Exception e) { log.warn("[OKX] 平仓位异常", e); } } // ---- 启动/停止 ---- public void startGrid() { if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) { log.warn("[OKX] 策略已在运行中, state:{}", state); return; } state = StrategyState.WAITING_KLINE; cumulativePnl = BigDecimal.ZERO; unrealizedPnl = BigDecimal.ZERO; markPrice = BigDecimal.ZERO; longEntryPrice = BigDecimal.ZERO; shortEntryPrice = BigDecimal.ZERO; longPositionSize = BigDecimal.ZERO; shortPositionSize = BigDecimal.ZERO; baseLongOpened = false; baseShortOpened = false; longActive = false; shortActive = false; accumulatedLongLossCount = 0; accumulatedShortLossCount = 0; shortPriceQueue.clear(); longPriceQueue.clear(); totalShortPriceQueue.clear(); totalLongPriceQueue.clear(); currentLongOrderIds.clear(); currentShortOrderIds.clear(); refreshInitialPrincipal(); log.info("[OKX] 网格策略已启动, 当前本金: {} USDT", initialPrincipal); } private void refreshInitialPrincipal() { try { JSONObject account = executorGet("/api/v5/account/balance"); JSONArray dataArr = account.getJSONArray("data"); if (dataArr != null && !dataArr.isEmpty()) { JSONArray details = dataArr.getJSONObject(0).getJSONArray("details"); if (details != null) { for (int i = 0; i < details.size(); i++) { JSONObject currency = details.getJSONObject(i); if ("USDT".equals(currency.getString("ccy"))) { this.initialPrincipal = currency.getBigDecimal("eq"); break; } } } } } catch (Exception e) { log.warn("[OKX] 获取初始化本金失败,使用旧值: {}", initialPrincipal); } } public void stopGrid() { state = StrategyState.STOPPED; executor.cancelAllPriceTriggeredOrders(); closeExistingPositions(); executor.shutdown(); log.info("[OKX] 策略已停止, 累计盈亏: {}", cumulativePnl); } // ---- K线回调 ---- public void onKline(BigDecimal closePrice) { lastKlinePrice = closePrice; if (state == StrategyState.WAITING_KLINE) { if (wsClient == null || !wsClient.areAllSubscribed()) { return; } state = StrategyState.OPENING; String size = config.getBaseQuantity(); log.info("[OKX] 首根K线到达,开基底仓位 多空各{}张...", size); executor.openLong(size, (orderId) -> { TraderParam baseLongTp = TraderParam.builder() .entryOrderId(orderId) .build(); config.setBaseLongTraderParam(baseLongTp); }, null); executor.openShort(size, (orderId) -> { TraderParam baseShortTp = TraderParam.builder() .entryOrderId(orderId) .build(); config.setBaseShortTraderParam(baseShortTp); }, null); return; } // OPENING 状态下若 WS 仓位已确认但 REST 回调尚未完成,等标记价格推送时重试队列生成 if (state == StrategyState.OPENING && baseLongOpened && baseShortOpened) { tryGenerateQueues(); } if (state == StrategyState.ACTIVE && !longActive && longPositionSize.compareTo(BigDecimal.ZERO) == 0) { processShortGrid(closePrice); } if (state == StrategyState.ACTIVE && !shortActive && shortPositionSize.compareTo(BigDecimal.ZERO) == 0) { processLongGrid(closePrice); } } // ---- 仓位推送回调 ---- /** * 仓位推送回调。由 PositionsOkxChannelHandler 调用。 * direction 使用 TraderParam.Direction:LONG 表示多头,SHORT 表示空头。 */ public void onPositionUpdate(String contract, TraderParam.Direction direction, BigDecimal size, BigDecimal entryPrice) { if (state == StrategyState.STOPPED || state == StrategyState.WAITING_KLINE) { return; } boolean hasPosition = size.abs().compareTo(BigDecimal.ZERO) > 0; boolean isLong = (direction == TraderParam.Direction.LONG); if (state == StrategyState.OPENING) { if (isLong && hasPosition && !baseLongOpened) { longActive = true; longPositionSize = size; longEntryPrice = entryPrice; longBaseEntryPrice = entryPrice; baseLongOpened = true; log.info("[OKX] 基底多成交价: {}", longBaseEntryPrice); tryGenerateQueues(); } else if (!isLong && hasPosition && !baseShortOpened) { shortActive = true; shortPositionSize = size.abs(); shortEntryPrice = entryPrice; shortBaseEntryPrice = entryPrice; baseShortOpened = true; log.info("[OKX] 基底空成交价: {}", shortBaseEntryPrice); tryGenerateQueues(); } } if (state == StrategyState.ACTIVE) { if (isLong) { if (hasPosition) { longActive = true; longPositionSize = size; longEntryPrice = entryPrice; } else { log.info("[OKX-0]多仓归零: {}", shortBaseEntryPrice); longActive = false; longPositionSize = BigDecimal.ZERO; longEntryPrice = BigDecimal.ZERO; } } else { if (hasPosition) { shortActive = true; shortPositionSize = size.abs(); shortEntryPrice = entryPrice; } else { log.info("[OKX-0]空仓归零: {}", shortBaseEntryPrice); shortActive = false; shortPositionSize = BigDecimal.ZERO; shortEntryPrice = BigDecimal.ZERO; } } } if (state == StrategyState.ACTIVE && !shortActive && !longActive) { executor.cancelAllPriceTriggeredOrders(); closeExistingPositions(); state = StrategyState.STOPPED; executor.submitTask(() -> { try { Thread.sleep(3000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } startGrid(); }); log.info("[OKX] 重置策略"); } } // ---- 平仓推送回调 ---- /** * 平仓盈亏累加(OKX 目前没有独立的 position_closes 频道, * 盈亏信息可从 orders 频道或 REST API 获取,这里保留接口以备将来使用)。 */ public void onPositionClose(String contract, String side, BigDecimal pnl) { if (state == StrategyState.STOPPED) { return; } cumulativePnl = cumulativePnl.add(pnl); updateUnrealizedPnl(); BigDecimal totalPnl = cumulativePnl.add(unrealizedPnl); log.info("[OKX] 已实现:{}, 未实现:{}, 合计:{}", cumulativePnl, unrealizedPnl, totalPnl); if (totalPnl.compareTo(config.getMaxLoss().negate()) <= 0) { String logMessage = StrUtil.format("[OKX] 已达亏损风险值(合计{}), 已实现:{}, 未实现:{}", totalPnl, cumulativePnl, unrealizedPnl); log.info(logMessage); DingTalkUtils.getDefault().sendActionCard("风险提醒", logMessage, config.getApiKey(), ""); } } // ---- 自动订单(条件单)状态变更回调 ---- /** * 自动订单状态变更回调。由 OrderAlgoOkxChannelHandler 调用。 */ public void onAutoOrder(String orderId, String status, String reason, String orderType, String tradeId) { if (state == StrategyState.STOPPED) { return; } log.info("[OKX] 条件单状态变更, id:{}, status:{}, reason:{}, order_type:{}", orderId, status, reason, orderType); if (!"finished".equals(status)) { return; } // 多仓止盈触发 GridElement longTpElem = GridElement.findByLongTakeProfitOrderId(orderId); if (longTpElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) { longTakeProfitTraderIdParam(longTpElem, null, false); log.info("[OKX] 多仓止盈触发 gridId:{}, orderId:{}", longTpElem.getId(), orderId); cancelFarthestLongStopLoss(); checkLastTakeProfitAndRestart(); return; } // 空仓止盈触发 GridElement shortTpElem = GridElement.findByShortTakeProfitOrderId(orderId); if (shortTpElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) { shortTakeProfitTraderIdParam(shortTpElem, null, false); log.info("[OKX] 空仓止盈触发 gridId:{}, orderId:{}", shortTpElem.getId(), orderId); cancelFarthestShortStopLoss(); checkLastTakeProfitAndRestart(); return; } // 多仓止损触发 GridElement longStopLossElem = GridElement.findByLongStopLossOrderId(orderId); if (longStopLossElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) { handleLongStopLossTriggered(longStopLossElem); return; } // 空仓止损触发 GridElement shortStopLossElem = GridElement.findByShortStopLossOrderId(orderId); if (shortStopLossElem != null && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) { handleShortStopLossTriggered(shortStopLossElem); return; } // 空仓挂单成交 GridElement shortGridElement = GridElement.findByShortOrderId(orderId); if (shortGridElement != null) { if (shortGridElement.isHasShortOrder() && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) { int filledQty = Integer.parseInt(shortGridElement.getShortTraderParam().getQuantity()); shortEntryTraderIdParam(shortGridElement, null, false); cancelAllShortTakeProfitsAndStopLosses(); int posSize = queryPositionSize(OkxPosMode.SHORT); extendShortStopLoss(posSize, shortGridElement.getId()); accumulatedShortLossCount = 0; log.info("[OKX] 空单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize); BigDecimal shortBaseQty = new BigDecimal(config.getBaseQuantity()); BigDecimal shortGridQty = new BigDecimal(config.getQuantity()); if (BigDecimal.valueOf(posSize).compareTo(shortBaseQty) > 0) { BigDecimal shortExcess = BigDecimal.valueOf(posSize).subtract(shortBaseQty); int shortExcessCount = shortExcess.divide(shortGridQty, 0, RoundingMode.DOWN).intValue(); for (int i = 0; i < shortExcessCount; i++) { int tpGridId = shortGridElement.getId() - 2 - i; if (i > 0) { tpGridId = tpGridId - 1; } GridElement tpElem = GridElement.findById(tpGridId); if (tpElem == null || tpElem.getShortTakeProfitOrderId() != null) { continue; } BigDecimal tpPrice = tpElem.getGridPrice(); int finalTpGridId = tpGridId; executor.placeTakeProfit( tpPrice, "close_short", config.getQuantity(), profitId -> { shortTakeProfitTraderIdParam(tpElem, profitId, true); log.info("[OKX] 空仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}", finalTpGridId, tpPrice, profitId); } ); } } } } // 多仓挂单成交 GridElement longGridElement = GridElement.findByLongOrderId(orderId); if (longGridElement != null) { if (longGridElement.isHasLongOrder() && StrUtil.isNotEmpty(tradeId) && !tradeId.equals("0")) { int filledQty = Integer.parseInt(longGridElement.getLongTraderParam().getQuantity()); longEntryTraderIdParam(longGridElement, null, false); cancelAllLongTakeProfitsAndStopLosses(); int posSize = queryPositionSize(OkxPosMode.LONG); extendLongStopLoss(posSize, longGridElement.getId()); accumulatedLongLossCount = 0; log.info("[OKX] 多单成交 gridId:{}, 当前持仓:{}张", filledQty, posSize); BigDecimal longBaseQty = new BigDecimal(config.getBaseQuantity()); BigDecimal longGridQty = new BigDecimal(config.getQuantity()); if (BigDecimal.valueOf(posSize).compareTo(longBaseQty) > 0) { BigDecimal longExcess = BigDecimal.valueOf(posSize).subtract(longBaseQty); int longExcessCount = longExcess.divide(longGridQty, 0, RoundingMode.DOWN).intValue(); for (int i = 0; i < longExcessCount; i++) { int tpGridId = longGridElement.getId() + 2 + i; if (i > 0) { tpGridId = tpGridId + 1; } GridElement tpElem = GridElement.findById(tpGridId); if (tpElem == null || tpElem.getLongTakeProfitOrderId() != null) { continue; } BigDecimal tpPrice = tpElem.getGridPrice(); int finalTpGridId = tpGridId; executor.placeTakeProfit( tpPrice, "close_long", config.getQuantity(), profitId -> { longTakeProfitTraderIdParam(tpElem, profitId, true); log.info("[OKX] 多仓止盈挂单, gridId:{}, 触发价:{}, takeProfitId:{}", finalTpGridId, tpPrice, profitId); } ); } } } } } // ========== REST 查询辅助 ========== private int queryPositionSize(OkxPosMode mode) { OkxPositionInfo p = queryPosition(mode); if (p != null) { return new BigDecimal(p.size).abs().intValue(); } return 0; } private BigDecimal queryEntryPrice(OkxPosMode mode) { OkxPositionInfo p = queryPosition(mode); if (p != null && p.entryPrice != null) { return new BigDecimal(p.entryPrice); } return BigDecimal.ZERO; } private OkxPositionInfo queryPosition(OkxPosMode mode) { try { JSONObject resp = executorGet("/api/v5/account/positions?instType=SWAP"); JSONArray data = resp.getJSONArray("data"); if (data != null) { for (int i = 0; i < data.size(); i++) { JSONObject p = data.getJSONObject(i); if (config.getContract().equals(p.getString("instId")) && mode.name().toLowerCase().equals(p.getString("posSide"))) { OkxPositionInfo info = new OkxPositionInfo(); info.size = p.getString("pos"); info.entryPrice = p.getString("avgPx"); return info; } } } } catch (Exception e) { log.warn("[OKX] 查询{}持仓失败", mode, e); } return null; } // ---- REST 快捷方法 ---- private JSONObject executorGet(String path) throws Exception { return executor.okGet(path); } private JSONObject executorPost(String path, String body) throws Exception { return executor.okPost(path, body); } // ---- 网格队列处理 ---- private void tryGenerateQueues() { if (baseLongOpened && baseShortOpened) { // 确保 openLong/openShort 的 REST 回调已完成(WS 推送可能比回调更快到达) if (config.getBaseLongTraderParam() == null || config.getBaseShortTraderParam() == null) { log.warn("[OKX] 基底REST回调尚未完成, 延后队列生成"); return; } generateShortQueue(); generateLongQueue(); updateGridElements(); GridElement baseGridElement = GridElement.findById(0); TraderParam baseLongTraderParam = config.getBaseLongTraderParam(); baseGridElement.setLongOrderId(baseLongTraderParam.getEntryOrderId()); baseGridElement.setHasLongOrder(true); TraderParam baseShortTraderParam = config.getBaseShortTraderParam(); baseGridElement.setShortOrderId(baseShortTraderParam.getEntryOrderId()); baseGridElement.setHasShortOrder(true); // 挂初始止损 int stopCount = Integer.parseInt(config.getBaseQuantity()) / Integer.parseInt(config.getQuantity()) + 1; for (int id = 2; id <= stopCount; id++) { GridElement elem = GridElement.findById(id); if (elem == null) { continue; } BigDecimal triggerPrice = elem.getGridPrice(); int finalId = id; executor.placeStopLoss(triggerPrice, "close_short", config.getQuantity(), profitId -> { elem.setShortStopLossOrderId(profitId); GridElement.refreshIndices(); log.info("[OKX] 空仓止损已挂, gridId:{}, 触发价:{}, slId:{}", finalId, triggerPrice, profitId); }); } for (int id = -2; id >= -stopCount; id--) { GridElement elem = GridElement.findById(id); if (elem == null) { continue; } BigDecimal triggerPrice = elem.getGridPrice(); int finalId = id; executor.placeStopLoss(triggerPrice, "close_long", config.getQuantity(), profitId -> { elem.setLongStopLossOrderId(profitId); GridElement.refreshIndices(); log.info("[OKX] 多仓止损已挂, gridId:{}, 触发价:{}, slId:{}", finalId, triggerPrice, profitId); }); } log.info("[OKX] 止损单已全部挂完, 空仓止损: 2~{}, 多仓止损: -2~-{}", stopCount, stopCount); state = StrategyState.ACTIVE; } } // ---- TraderParam 更新辅助方法 ---- private void longTakeProfitTraderIdParam(GridElement e, String profitId, boolean flag) { TraderParam tp = e.getLongTraderParam(); tp.setTakeProfitOrderId(profitId); tp.setTakeProfitPlaced(flag); e.setLongTakeProfitOrderId(profitId); GridElement.refreshIndices(); } private void shortTakeProfitTraderIdParam(GridElement e, String profitId, boolean flag) { TraderParam tp = e.getShortTraderParam(); tp.setTakeProfitOrderId(profitId); tp.setTakeProfitPlaced(flag); e.setShortTakeProfitOrderId(profitId); GridElement.refreshIndices(); } private void longEntryTraderIdParam(GridElement e, String entryId, boolean flag) { TraderParam tp = e.getLongTraderParam(); tp.setEntryOrderId(entryId); tp.setEntryOrderPlaced(flag); e.setHasLongOrder(flag); e.setLongOrderId(entryId); GridElement.refreshIndices(); } private void shortEntryTraderIdParam(GridElement e, String entryId, boolean flag) { TraderParam tp = e.getShortTraderParam(); tp.setEntryOrderId(entryId); tp.setEntryOrderPlaced(flag); e.setHasShortOrder(flag); e.setShortOrderId(entryId); GridElement.refreshIndices(); } // ---- 队列生成 ---- private void generateShortQueue() { shortPriceQueue.clear(); totalShortPriceQueue.clear(); totalLongPriceQueue.clear(); int prec = config.getPriceScale(); BigDecimal step = shortBaseEntryPrice.multiply(config.getGridRate()).setScale(prec, RoundingMode.HALF_UP); config.setStep(step); BigDecimal elem = shortBaseEntryPrice.subtract(step).setScale(prec, RoundingMode.HALF_UP); for (int i = 0; i < config.getGridQueueSize(); i++) { shortPriceQueue.add(elem); totalLongPriceQueue.add(elem); totalShortPriceQueue.add(elem); elem = elem.subtract(step).setScale(prec, RoundingMode.HALF_UP); if (elem.compareTo(BigDecimal.ZERO) <= 0) { break; } } shortPriceQueue.sort((a, b) -> b.compareTo(a)); log.info("[OKX] 空队列:{}", shortPriceQueue); } private void generateLongQueue() { longPriceQueue.clear(); int prec = config.getPriceScale(); BigDecimal step = config.getStep(); BigDecimal elem = shortBaseEntryPrice.add(step).setScale(prec, RoundingMode.HALF_UP); for (int i = 0; i < config.getGridQueueSize(); i++) { longPriceQueue.add(elem); totalLongPriceQueue.add(elem); totalShortPriceQueue.add(elem); elem = elem.add(step).setScale(prec, RoundingMode.HALF_UP); } longPriceQueue.sort(BigDecimal::compareTo); log.info("[OKX] 多队列:{}", longPriceQueue); totalShortPriceQueue.sort((a, b) -> b.compareTo(a)); totalLongPriceQueue.sort(BigDecimal::compareTo); } private void updateGridElements() { List elements = new ArrayList<>(); int shortSize = shortPriceQueue.size(); int longSize = longPriceQueue.size(); int prec = config.getPriceScale(); BigDecimal step = config.getStep(); String qty = config.getQuantity(); // 空仓队列:id 从 -1 自减 for (int i = 0; i < shortSize; i++) { int id = -(i + 1); Integer upId = (i == 0) ? 0 : id + 1; Integer downId = (i == shortSize - 1) ? null : id - 1; BigDecimal price = shortPriceQueue.get(i); elements.add(GridElement.builder() .id(id).gridPrice(price).upId(upId).downId(downId) .longTraderParam(TraderParam.builder().direction(TraderParam.Direction.LONG) .entryPrice(price).takeProfitPrice(price.add(step).setScale(prec, RoundingMode.HALF_UP)) .quantity(qty).build()) .shortTraderParam(TraderParam.builder().direction(TraderParam.Direction.SHORT) .entryPrice(price).takeProfitPrice(price.subtract(step).setScale(prec, RoundingMode.HALF_UP)) .quantity(qty).build()) .build()); } // 位置 0 { BigDecimal price = shortBaseEntryPrice; elements.add(GridElement.builder() .id(0).gridPrice(price) .upId(longSize > 0 ? 1 : null).downId(shortSize > 0 ? -1 : null) .longTraderParam(TraderParam.builder().direction(TraderParam.Direction.LONG) .entryPrice(price).takeProfitPrice(price.add(step).setScale(prec, RoundingMode.HALF_UP)) .quantity(qty).build()) .shortTraderParam(TraderParam.builder().direction(TraderParam.Direction.SHORT) .entryPrice(price).takeProfitPrice(price.subtract(step).setScale(prec, RoundingMode.HALF_UP)) .quantity(qty).build()) .build()); } // 多仓队列:id 从 1 自增 for (int i = 0; i < longSize; i++) { int id = i + 1; Integer downId = (i == 0) ? 0 : id - 1; Integer upId = (i == longSize - 1) ? null : id + 1; BigDecimal price = longPriceQueue.get(i); elements.add(GridElement.builder() .id(id).gridPrice(price).upId(upId).downId(downId) .longTraderParam(TraderParam.builder().direction(TraderParam.Direction.LONG) .entryPrice(price).takeProfitPrice(price.add(step).setScale(prec, RoundingMode.HALF_UP)) .quantity(qty).build()) .shortTraderParam(TraderParam.builder().direction(TraderParam.Direction.SHORT) .entryPrice(price).takeProfitPrice(price.subtract(step).setScale(prec, RoundingMode.HALF_UP)) .quantity(qty).build()) .build()); } config.setGridElements(elements); log.info("[OKX] 网格元素列表已构建, 共{}个元素 (空仓:{} 位置:0 多仓:{})", elements.size(), shortSize, longSize); } // ---- processShortGrid / processLongGrid ---- private void processShortGrid(BigDecimal currentPrice) { BigDecimal matched = BigDecimal.ZERO; synchronized (totalLongPriceQueue) { for (BigDecimal p : totalLongPriceQueue) { if (p.compareTo(currentPrice) >= 0) { matched = p; break; } } if (BigDecimal.ZERO.compareTo(matched) == 0) { return; } GridElement matchedUpGridElement = GridElement.findByPrice(matched); if (matchedUpGridElement != null && !matchedUpGridElement.isHasLongOrder()) { Integer upId = matchedUpGridElement.getUpId(); GridElement newEntryGrid = GridElement.findById(upId); if (newEntryGrid != null) { GridElement cancelGridElement = GridElement.findById(newEntryGrid.getUpId()); String quantity = cancelGridElement != null ? cancelGridElement.getLongTraderParam().getQuantity() : config.getBaseQuantity(); if (cancelGridElement != null && cancelGridElement.isHasLongOrder()) { String longOrderId = cancelGridElement.getLongOrderId(); executor.cancelConditionalOrder(longOrderId, oid -> { longEntryTraderIdParam(cancelGridElement, null, false); log.info("[OKX] 多仓仓位归零, 取消gridId:{}的多单,{}", cancelGridElement.getId(), longOrderId); }); } if (!newEntryGrid.isHasLongOrder()) { BigDecimal triggerPrice = newEntryGrid.getGridPrice(); String size = quantity; log.info("[OKX] 多仓仓位归零 gridId:{}, 挂{}基础张多单", newEntryGrid.getId(), size); newEntryGrid.getLongTraderParam().setQuantity(size); placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice, size); } } } } } private void processLongGrid(BigDecimal currentPrice) { BigDecimal matched = BigDecimal.ZERO; synchronized (totalShortPriceQueue) { for (BigDecimal p : totalShortPriceQueue) { if (p.compareTo(currentPrice) <= 0) { matched = p; break; } } if (BigDecimal.ZERO.compareTo(matched) == 0) { return; } GridElement matchedUpGridElement = GridElement.findByPrice(matched); if (matchedUpGridElement != null && !matchedUpGridElement.isHasShortOrder()) { Integer downId = matchedUpGridElement.getDownId(); GridElement newEntryGrid = GridElement.findById(downId); if (newEntryGrid != null) { GridElement cancelGridElement = GridElement.findById(newEntryGrid.getDownId()); String quantity = cancelGridElement != null ? cancelGridElement.getShortTraderParam().getQuantity() : config.getBaseQuantity(); if (cancelGridElement != null && cancelGridElement.isHasShortOrder()) { String shortOrderId = cancelGridElement.getShortOrderId(); executor.cancelConditionalOrder(shortOrderId, oid -> { shortEntryTraderIdParam(cancelGridElement, null, false); log.info("[OKX] 空仓仓位归零, 取消gridId:{}的空单{}", cancelGridElement.getId(), shortOrderId); }); } if (!newEntryGrid.isHasShortOrder()) { BigDecimal triggerPrice = newEntryGrid.getGridPrice(); String size = quantity; log.info("[OKX] 空仓仓位归零 gridId:{}, 挂{}基础张空单", newEntryGrid.getId(), size); newEntryGrid.getShortTraderParam().setQuantity(size); placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice, negate(size)); } } } } } // ---- 止损处理 ---- private void handleLongStopLossTriggered(GridElement gridElement) { gridElement.setLongStopLossOrderId(null); int gridId = gridElement.getId(); log.info("[OKX] 多仓止损触发 gridId:{}, 开始追单", gridId); int newEntryGridId = gridId + 1; GridElement newEntryGrid = GridElement.findById(newEntryGridId); if (newEntryGrid == null) { log.warn("[OKX] 多仓止损触发 but gridId:{} 不存在", newEntryGridId); GridElement.refreshIndices(); return; } if (!newEntryGrid.isHasLongOrder()) { BigDecimal triggerPrice = newEntryGrid.getGridPrice(); accumulatedLongLossCount += Integer.parseInt(config.getQuantity()); String size = String.valueOf(accumulatedLongLossCount + Integer.parseInt(config.getQuantity())); log.info("[OKX] 多仓止损触发 gridId:{}, 在gridId:{}挂{}基础张多单", gridId, newEntryGridId, size); newEntryGrid.getLongTraderParam().setQuantity(size); placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice, size); } else { log.warn("[OKX] 多仓止损触发 gridId:{}, 目标gridId:{}已有挂单,跳过", gridId, newEntryGridId); } int cancelGridId = gridId + 2; GridElement cancelGrid = GridElement.findById(cancelGridId); if (cancelGrid != null && cancelGrid.isHasLongOrder()) { executor.cancelConditionalOrder(cancelGrid.getLongOrderId(), oid -> { longEntryTraderIdParam(cancelGrid, null, false); log.info("[OKX] 多仓止损触发, 取消gridId:{}的多单", cancelGridId); }); } GridElement farthestLongTp = null; for (GridElement e : config.getGridElements()) { if (e.getLongTakeProfitOrderId() != null) { if (farthestLongTp == null || e.getGridPrice().compareTo(farthestLongTp.getGridPrice()) > 0) { farthestLongTp = e; } } } if (farthestLongTp != null) { String tpOrderId = farthestLongTp.getLongTakeProfitOrderId(); GridElement finalFarthest = farthestLongTp; executor.cancelConditionalOrder(tpOrderId, oid -> { longTakeProfitTraderIdParam(finalFarthest, null, false); log.info("[OKX] 多仓止损触发, 取消最远止盈 gridId:{}, orderId:{}", finalFarthest.getId(), tpOrderId); }); } } private void handleShortStopLossTriggered(GridElement gridElement) { gridElement.setShortStopLossOrderId(null); int gridId = gridElement.getId(); log.info("[OKX] 空仓止损触发 gridId:{}, 开始追单", gridId); int newEntryGridId = gridId - 1; GridElement newEntryGrid = GridElement.findById(newEntryGridId); if (newEntryGrid == null) { log.warn("[OKX] 空仓止损触发 but gridId:{} 不存在", newEntryGridId); GridElement.refreshIndices(); return; } if (!newEntryGrid.isHasShortOrder()) { BigDecimal triggerPrice = newEntryGrid.getGridPrice(); accumulatedShortLossCount += Integer.parseInt(config.getQuantity()); String size = String.valueOf(accumulatedShortLossCount + Integer.parseInt(config.getQuantity())); log.info("[OKX] 空仓止损触发 gridId:{}, 在gridId:{}挂{}基础张空单", gridId, newEntryGridId, size); newEntryGrid.getShortTraderParam().setQuantity(size); placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice, negate(size)); } else { log.warn("[OKX] 空仓止损触发 gridId:{}, 目标gridId:{}已有挂单,跳过", gridId, newEntryGridId); } int cancelGridId = gridId - 2; GridElement cancelGrid = GridElement.findById(cancelGridId); if (cancelGrid != null && cancelGrid.isHasShortOrder()) { executor.cancelConditionalOrder(cancelGrid.getShortOrderId(), oid -> { shortEntryTraderIdParam(cancelGrid, null, false); log.info("[OKX] 空仓止损触发, 取消gridId:{}的空单", cancelGridId); }); } GridElement farthestShortTp = null; for (GridElement e : config.getGridElements()) { if (e.getShortTakeProfitOrderId() != null) { if (farthestShortTp == null || e.getGridPrice().compareTo(farthestShortTp.getGridPrice()) < 0) { farthestShortTp = e; } } } if (farthestShortTp != null) { String tpOrderId = farthestShortTp.getShortTakeProfitOrderId(); GridElement finalFarthest = farthestShortTp; executor.cancelConditionalOrder(tpOrderId, oid -> { shortTakeProfitTraderIdParam(finalFarthest, null, false); log.info("[OKX] 空仓止损触发, 取消最远止盈 gridId:{}, orderId:{}", finalFarthest.getId(), tpOrderId); }); } } // ---- 止盈/止损取消辅助 ---- private void checkLastTakeProfitAndRestart() { int span = config.getRestartGridSpan(); if (span <= 0) { return; } if (GridElement.getLongTakeProfitCount() > 0 || GridElement.getShortTakeProfitCount() > 0) { log.info("[OKX] 尚有未触发止盈单, 暂不检查跨度重启 longTpCount:{}, shortTpCount:{}", GridElement.getLongTakeProfitCount(), GridElement.getShortTakeProfitCount()); return; } BigDecimal step = config.getStep(); if (step == null || step.compareTo(BigDecimal.ZERO) == 0) { return; } BigDecimal threshold = step.multiply(new BigDecimal(span)); BigDecimal currentPrice = lastKlinePrice; if (currentPrice == null || currentPrice.compareTo(BigDecimal.ZERO) == 0) { return; } // 查交易所获取最新持仓均价 OkxPositionInfo longPos = queryPosition(OkxPosMode.LONG); OkxPositionInfo shortPos = queryPosition(OkxPosMode.SHORT); boolean hasLong = longPos != null && Math.abs(Integer.parseInt(longPos.size)) > 0; boolean hasShort = shortPos != null && Math.abs(Integer.parseInt(shortPos.size)) > 0; BigDecimal longAvgPrice = (longPos != null && longPos.entryPrice != null) ? new BigDecimal(longPos.entryPrice) : BigDecimal.ZERO; BigDecimal shortAvgPrice = (shortPos != null && shortPos.entryPrice != null) ? new BigDecimal(shortPos.entryPrice) : BigDecimal.ZERO; boolean shouldRestart = false; String reason = ""; if (hasLong && hasShort) { BigDecimal gap = shortAvgPrice.subtract(longAvgPrice); if (gap.compareTo(threshold) >= 0) { shouldRestart = true; reason = StrUtil.format("双边跨度 |多均价:{} − 空均价:{}| = {} >= {} (span:{}×step:{})", longAvgPrice, shortAvgPrice, gap, threshold, span, step); } } else if (hasLong) { BigDecimal gap = currentPrice.subtract(longAvgPrice); if (gap.compareTo(threshold) >= 0) { shouldRestart = true; reason = StrUtil.format("多仓跨度 当前价:{} − 多均价:{} = {} > {} (span:{}×step:{})", currentPrice, longAvgPrice, gap, threshold, span, step); } } else if (hasShort) { BigDecimal gap = shortAvgPrice.subtract(currentPrice); if (gap.compareTo(threshold) >= 0) { shouldRestart = true; reason = StrUtil.format("空仓跨度 空均价:{} − 当前价:{} = {} > {} (span:{}×step:{})", shortAvgPrice, currentPrice, gap, threshold, span, step); } } if (shouldRestart) { log.info("[OKX] 跨度已达要求 → {},最后一个止盈触发策略重启", reason); executor.cancelAllPriceTriggeredOrders(); closeExistingPositions(); state = StrategyState.STOPPED; executor.submitTask(() -> { try { Thread.sleep(3000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } startGrid(); }); } } private void cancelFarthestLongStopLoss() { GridElement farthest = null; for (GridElement e : config.getGridElements()) { if (e.getLongStopLossOrderId() != null) { if (farthest == null || e.getId() < farthest.getId()) { farthest = e; } } } if (farthest != null) { String slId = farthest.getLongStopLossOrderId(); farthest.setLongStopLossOrderId(null); GridElement.refreshIndices(); GridElement finalFarthest = farthest; executor.cancelConditionalOrder(slId, oid -> log.info("[OKX] 止盈触发, 取消最远多仓止损 gridId:{}, orderId:{}", finalFarthest.getId(), slId)); } } private void cancelFarthestShortStopLoss() { GridElement farthest = null; for (GridElement e : config.getGridElements()) { if (e.getShortStopLossOrderId() != null) { if (farthest == null || e.getId() > farthest.getId()) { farthest = e; } } } if (farthest != null) { String slId = farthest.getShortStopLossOrderId(); farthest.setShortStopLossOrderId(null); GridElement.refreshIndices(); GridElement finalFarthest = farthest; executor.cancelConditionalOrder(slId, oid -> log.info("[OKX] 止盈触发, 取消最远空仓止损 gridId:{}, orderId:{}", finalFarthest.getId(), slId)); } } private void cancelAllLongTakeProfitsAndStopLosses() { for (GridElement e : config.getGridElements()) { String tpId = e.getLongTakeProfitOrderId(); if (tpId != null) { e.setLongTakeProfitOrderId(null); executor.cancelConditionalOrder(tpId, oid -> {}); } String slId = e.getLongStopLossOrderId(); if (slId != null) { e.setLongStopLossOrderId(null); executor.cancelConditionalOrder(slId, oid -> {}); } } GridElement.refreshIndices(); log.info("[OKX] 已提交取消所有多仓止盈+止损"); } private void cancelAllShortTakeProfitsAndStopLosses() { for (GridElement e : config.getGridElements()) { String tpId = e.getShortTakeProfitOrderId(); if (tpId != null) { e.setShortTakeProfitOrderId(null); executor.cancelConditionalOrder(tpId, oid -> {}); } String slId = e.getShortStopLossOrderId(); if (slId != null) { e.setShortStopLossOrderId(null); executor.cancelConditionalOrder(slId, oid -> {}); } } GridElement.refreshIndices(); log.info("[OKX] 已提交取消所有空仓止盈+止损"); } // ---- 止损追单 ---- private void extendLongStopLoss(int filledQty, int gridId) { int furthestSlId = 0; for (GridElement e : config.getGridElements()) { if (e.getLongStopLossOrderId() != null && e.getId() < furthestSlId) { furthestSlId = e.getId(); } } int interval = 1; if (furthestSlId == 0) { furthestSlId = gridId; interval = 2; } int stopLossCount = filledQty / Integer.parseInt(config.getQuantity()); log.info("[OKX] 多仓追挂止损, 当前最远止损gridId:{}, 成交{}张, 追加{}个止损单", furthestSlId, filledQty, stopLossCount); for (int i = 0; i < stopLossCount; i++) { int newSlId = furthestSlId - i - interval; GridElement elem = GridElement.findById(newSlId); if (elem == null) { continue; } BigDecimal triggerPrice = elem.getGridPrice(); int finalSlId = newSlId; executor.placeStopLoss(triggerPrice, "close_long", config.getQuantity(), profitId -> { elem.setLongStopLossOrderId(profitId); GridElement.refreshIndices(); log.info("[OKX] 多仓止损追加, gridId:{}, 触发价:{}, slId:{}", finalSlId, triggerPrice, profitId); }); } } private void extendShortStopLoss(int filledQty, int gridId) { int furthestSlId = 0; for (GridElement e : config.getGridElements()) { if (e.getShortStopLossOrderId() != null && e.getId() > furthestSlId) { furthestSlId = e.getId(); } } int interval = 1; if (furthestSlId == 0) { furthestSlId = gridId; interval = 2; } int stopLossCount = filledQty / Integer.parseInt(config.getQuantity()); log.info("[OKX] 空仓追挂止损, 当前最远止损gridId:{}, 成交{}张, 追加{}个止损单", furthestSlId, filledQty, stopLossCount); for (int i = 0; i < stopLossCount; i++) { int newSlId = furthestSlId + i + interval; GridElement elem = GridElement.findById(newSlId); if (elem == null) { continue; } BigDecimal triggerPrice = elem.getGridPrice(); int finalSlId = newSlId; executor.placeStopLoss(triggerPrice, "close_short", config.getQuantity(), profitId -> { elem.setShortStopLossOrderId(profitId); GridElement.refreshIndices(); log.info("[OKX] 空仓止损追加, gridId:{}, 触发价:{}, slId:{}", finalSlId, triggerPrice, profitId); }); } } // ---- 工具 ---- private String negate(String qty) { return qty.startsWith("-") ? qty.substring(1) : "-" + qty; } private void placeEntryOrderWithPreFlag(GridElement gridElement, boolean isLong, BigDecimal triggerPrice, String size) { if (isLong) { gridElement.setHasLongOrder(true); } else { gridElement.setHasShortOrder(true); } executor.placeConditionalEntryOrder(triggerPrice, isLong, size, orderId -> { if (isLong) { longEntryTraderIdParam(gridElement, orderId, true); } else { shortEntryTraderIdParam(gridElement, orderId, true); } }, () -> { if (isLong) { gridElement.setHasLongOrder(false); gridElement.setLongOrderId(null); } else { gridElement.setHasShortOrder(false); gridElement.setShortOrderId(null); } GridElement.refreshIndices(); log.warn("[OKX] 条件单创建失败,回滚标志位 gridId:{}, isLong:{}", gridElement.getId(), isLong); }); } private void updateUnrealizedPnl() { BigDecimal price = resolvePnlPrice(); if (price == null || price.compareTo(BigDecimal.ZERO) == 0) { return; } BigDecimal multiplier = config.getContractMultiplier(); BigDecimal longPnl = BigDecimal.ZERO; BigDecimal shortPnl = BigDecimal.ZERO; if (longPositionSize.compareTo(BigDecimal.ZERO) > 0 && longEntryPrice.compareTo(BigDecimal.ZERO) > 0) { longPnl = longPositionSize.multiply(multiplier).multiply(price.subtract(longEntryPrice)); } if (shortPositionSize.compareTo(BigDecimal.ZERO) > 0 && shortEntryPrice.compareTo(BigDecimal.ZERO) > 0) { shortPnl = shortPositionSize.multiply(multiplier).multiply(shortEntryPrice.subtract(price)); } unrealizedPnl = longPnl.add(shortPnl); log.info("[OKX] 未实现盈亏: {}", unrealizedPnl); } private BigDecimal resolvePnlPrice() { if (config.getUnrealizedPnlPriceMode() == OkxConfig.PnLPriceMode.MARK_PRICE && markPrice.compareTo(BigDecimal.ZERO) > 0) { return markPrice; } return lastKlinePrice; } // ---- getters ---- public BigDecimal getLastKlinePrice() { return lastKlinePrice; } public void setMarkPrice(BigDecimal markPrice) { this.markPrice = markPrice; } public boolean isStrategyActive() { return state != StrategyState.STOPPED && state != StrategyState.WAITING_KLINE; } public BigDecimal getCumulativePnl() { return cumulativePnl; } public BigDecimal getUnrealizedPnl() { return unrealizedPnl; } public StrategyState getState() { return state; } public void setWsClient(OkxKlineWebSocketClient wsClient) { this.wsClient = wsClient; } }