feat(gate): 添加多账号支持和日志标签区分功能
- 在 GateConfig 中新增 label 字段用于日志区分多账号
- 修改 GateGridTradeService 使用 logLabel 替代固定 Gate 标签
- 更新所有日志输出格式为 [Gate-label] 形式便于多账号识别
- 修改 GateTradeExecutor 构造函数接收 label 参数并更新线程名
- 重构 GateWebSocketClientManager 支持多账号实例管理
- 创建 AccountInstance 内部类封装单个账号的完整组件
- 实现 buildAccountConfigs 方法用于配置多个账号
- 更新初始化流程支持批量创建和启动多个账号实例
- 修改销毁流程遍历销毁所有账号实例
- 添加 getInstanceCount 和 getGridTradeService 方法供外部查询
| | |
| | | MARK_PRICE |
| | | } |
| | | |
| | | /** 账号标签(用于日志区分多账号) */ |
| | | private final String label; |
| | | /** Gate API v4 密钥 */ |
| | | private final String apiKey; |
| | | /** Gate API v4 签名密钥 */ |
| | |
| | | private final PnLPriceMode unrealizedPnlPriceMode; |
| | | |
| | | private GateConfig(Builder builder) { |
| | | this.label = builder.label; |
| | | this.apiKey = builder.apiKey; |
| | | this.apiSecret = builder.apiSecret; |
| | | this.contract = builder.contract; |
| | |
| | | : "wss://ws-testnet.gate.com/v4/ws/futures/usdt"; |
| | | } |
| | | |
| | | public String getLabel() { return label; } |
| | | public String getApiKey() { return apiKey; } |
| | | public String getApiSecret() { return apiSecret; } |
| | | public String getContract() { return contract; } |
| | |
| | | * GateConfig 的流式构造器,提供合理的默认值。 |
| | | */ |
| | | public static class Builder { |
| | | private String label = "default"; |
| | | private String apiKey; |
| | | private String apiSecret; |
| | | private String contract = "BTC_USDT"; |
| | |
| | | private BigDecimal contractMultiplier = new BigDecimal("0.001"); |
| | | private PnLPriceMode unrealizedPnlPriceMode = PnLPriceMode.LAST_PRICE; |
| | | |
| | | public Builder label(String label) { this.label = label; return this; } |
| | | public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; } |
| | | public Builder apiSecret(String apiSecret) { this.apiSecret = apiSecret; return this; } |
| | | public Builder contract(String contract) { this.contract = contract; return this; } |
| | |
| | | private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position"; |
| | | |
| | | private final GateConfig config; |
| | | private final String logLabel; |
| | | private final GateTradeExecutor executor; |
| | | private final FuturesApi futuresApi; |
| | | private static final String SETTLE = "usdt"; |
| | |
| | | |
| | | public GateGridTradeService(GateConfig config) { |
| | | this.config = config; |
| | | this.logLabel = config.getLabel(); |
| | | ApiClient apiClient = new ApiClient(); |
| | | apiClient.setBasePath(config.getRestBasePath()); |
| | | apiClient.setApiKeySecret(config.getApiKey(), config.getApiSecret()); |
| | | this.futuresApi = new FuturesApi(apiClient); |
| | | this.executor = new GateTradeExecutor(apiClient, config.getContract()); |
| | | this.executor = new GateTradeExecutor(apiClient, config.getContract(), logLabel); |
| | | } |
| | | |
| | | // ---- 初始化 ---- |
| | |
| | | detailClient.setApiKeySecret(config.getApiKey(), config.getApiSecret()); |
| | | AccountDetail detail = new AccountApi(detailClient).getAccountDetail(); |
| | | this.userId = detail.getUserId(); |
| | | log.info("[Gate] 用户ID: {}", userId); |
| | | log.info("[Gate-{}] 用户ID: {}", logLabel, userId); |
| | | |
| | | FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE); |
| | | this.initialPrincipal = new BigDecimal(account.getTotal()); |
| | | log.info("[Gate] 初始本金: {} USDT", initialPrincipal); |
| | | log.info("[Gate-{}] 初始本金: {} USDT", logLabel, initialPrincipal); |
| | | |
| | | futuresApi.cancelPriceTriggeredOrderList(SETTLE, config.getContract()); |
| | | log.info("[Gate] 旧条件单已清除"); |
| | | log.info("[Gate-{}] 旧条件单已清除", logLabel); |
| | | closeExistingPositions(); |
| | | |
| | | //设置持仓模式为双向持仓 |
| | |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | log.info("[Gate] 持仓模式: {} 余额: {}", config.getPositionMode(), account.getAvailable()); |
| | | log.info("[Gate] 杠杆: {}x {}", config.getLeverage(), config.getMarginMode()); |
| | | log.info("[Gate-{}] 持仓模式: {} 余额: {}", logLabel, config.getPositionMode(), account.getAvailable()); |
| | | log.info("[Gate-{}] 杠杆: {}x {}", logLabel, config.getLeverage(), config.getMarginMode()); |
| | | } catch (GateApiException e) { |
| | | log.error("[Gate] 初始化失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage()); |
| | | log.error("[Gate-{}] 初始化失败, label:{}, msg:{}", logLabel, e.getErrorLabel(), e.getMessage()); |
| | | } catch (ApiException e) { |
| | | log.error("[Gate] 初始化失败, code:{}", e.getCode()); |
| | | log.error("[Gate-{}] 初始化失败, code:{}", logLabel, e.getCode()); |
| | | } |
| | | } |
| | | |
| | | private void closeExistingPositions() { |
| | | try { |
| | | List<Position> positions = futuresApi.listPositions(SETTLE).execute(); |
| | | if (positions == null || positions.isEmpty()) { log.info("[Gate] 无已有仓位"); return; } |
| | | if (positions == null || positions.isEmpty()) { log.info("[Gate-{}] 无已有仓位", logLabel); return; } |
| | | for (Position pos : positions) { |
| | | if (!config.getContract().equals(pos.getContract())) { |
| | | continue; |
| | |
| | | } |
| | | closeOrder.setText("t-grid-init-close"); |
| | | futuresApi.createFuturesOrder(SETTLE, closeOrder, null); |
| | | log.info("[Gate] 平已有仓位, 方向:{}, size:{}, mode:{}", size > 0 ? "多" : "空", sizeStr, mode); |
| | | log.info("[Gate-{}] 平已有仓位, 方向:{}, size:{}, mode:{}", logLabel, size > 0 ? "多" : "空", sizeStr, mode); |
| | | } |
| | | } catch (GateApiException e) { |
| | | log.warn("[Gate] 平仓位失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage()); |
| | | log.warn("[Gate-{}] 平仓位失败, label:{}, msg:{}", logLabel, e.getErrorLabel(), e.getMessage()); |
| | | } catch (Exception e) { |
| | | log.warn("[Gate] 平仓位异常", e); |
| | | log.warn("[Gate-{}] 平仓位异常", logLabel, e); |
| | | } |
| | | } |
| | | |
| | |
| | | |
| | | public void startGrid() { |
| | | if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) { |
| | | log.warn("[Gate] 策略已在运行中, state:{}", state); |
| | | log.warn("[Gate-{}] 策略已在运行中, state:{}", logLabel, state); |
| | | return; |
| | | } |
| | | state = StrategyState.WAITING_KLINE; |
| | |
| | | shortActive = false; |
| | | shortPriceQueue.clear(); |
| | | longPriceQueue.clear(); |
| | | log.info("[Gate] 网格策略已启动"); |
| | | log.info("[Gate-{}] 网格策略已启动", logLabel); |
| | | } |
| | | |
| | | public void stopGrid() { |
| | | state = StrategyState.STOPPED; |
| | | executor.cancelAllPriceTriggeredOrders(); |
| | | executor.shutdown(); |
| | | log.info("[Gate] 策略已停止, 累计盈亏: {}", cumulativePnl); |
| | | log.info("[Gate-{}] 策略已停止, 累计盈亏: {}", logLabel, cumulativePnl); |
| | | } |
| | | |
| | | // ---- K线回调 ---- |
| | |
| | | |
| | | if (state == StrategyState.WAITING_KLINE) { |
| | | state = StrategyState.OPENING; |
| | | log.info("[Gate] 首根K线到达,开基底仓位..."); |
| | | log.info("[Gate-{}] 首根K线到达,开基底仓位...", logLabel); |
| | | executor.openLong(config.getQuantity(), () -> { |
| | | log.info("[Gate] 基底多单已提交"); |
| | | log.info("[Gate-{}] 基底多单已提交", logLabel); |
| | | }, null); |
| | | executor.openShort(negate(config.getQuantity()), () -> { |
| | | log.info("[Gate] 基底空单已提交"); |
| | | log.info("[Gate-{}] 基底空单已提交", logLabel); |
| | | }, null); |
| | | return; |
| | | } |
| | |
| | | longPositionSize = size; |
| | | longBaseEntryPrice = entryPrice; |
| | | baseLongOpened = true; |
| | | log.info("[Gate] 基底多成交价: {}", longBaseEntryPrice); |
| | | log.info("[Gate-{}] 基底多成交价: {}", logLabel, longBaseEntryPrice); |
| | | tryGenerateQueues(); |
| | | } else if (size.compareTo(longPositionSize) > 0) { |
| | | longPositionSize = size; |
| | | BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.add(config.getGridRate())).setScale(1, RoundingMode.HALF_UP); |
| | | executor.placeTakeProfit(tpPrice, |
| | | FuturesPriceTrigger.RuleEnum.NUMBER_1, ORDER_TYPE_CLOSE_LONG, negate(config.getQuantity())); |
| | | log.info("[Gate] 多单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, negate(config.getQuantity())); |
| | | log.info("[Gate-{}] 多单止盈已设, entry:{}, tp:{}, size:{}", logLabel, entryPrice, tpPrice, negate(config.getQuantity())); |
| | | } else { |
| | | longPositionSize = size; |
| | | } |
| | |
| | | shortPositionSize = size.abs(); |
| | | shortBaseEntryPrice = entryPrice; |
| | | baseShortOpened = true; |
| | | log.info("[Gate] 基底空成交价: {}", shortBaseEntryPrice); |
| | | log.info("[Gate-{}] 基底空成交价: {}", logLabel, shortBaseEntryPrice); |
| | | tryGenerateQueues(); |
| | | } else if (size.abs().compareTo(shortPositionSize) > 0) { |
| | | shortPositionSize = size.abs(); |
| | | BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate())).setScale(1, RoundingMode.HALF_UP); |
| | | executor.placeTakeProfit(tpPrice, |
| | | FuturesPriceTrigger.RuleEnum.NUMBER_2, ORDER_TYPE_CLOSE_SHORT, config.getQuantity()); |
| | | log.info("[Gate] 空单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, config.getQuantity()); |
| | | log.info("[Gate-{}] 空单止盈已设, entry:{}, tp:{}, size:{}", logLabel, entryPrice, tpPrice, config.getQuantity()); |
| | | } else { |
| | | shortPositionSize = size.abs(); |
| | | } |
| | |
| | | return; |
| | | } |
| | | cumulativePnl = cumulativePnl.add(pnl); |
| | | log.info("[Gate] 盈亏累加:{}, 方向:{}, 累计:{}", pnl, side, cumulativePnl); |
| | | log.info("[Gate-{}] 盈亏累加:{}, 方向:{}, 累计:{}", logLabel, pnl, side, cumulativePnl); |
| | | |
| | | if (cumulativePnl.compareTo(config.getOverallTp()) >= 0) { |
| | | log.info("[Gate] 已达止盈目标 {}→已停止", cumulativePnl); |
| | | log.info("[Gate-{}] 已达止盈目标 {}→已停止", logLabel, cumulativePnl); |
| | | state = StrategyState.STOPPED; |
| | | } else if (cumulativePnl.compareTo(config.getMaxLoss().negate()) <= 0) { |
| | | log.info("[Gate] 已达亏损上限 {}→已停止", cumulativePnl); |
| | | log.info("[Gate-{}] 已达亏损上限 {}→已停止", logLabel, cumulativePnl); |
| | | state = StrategyState.STOPPED; |
| | | } |
| | | } |
| | |
| | | generateShortQueue(); |
| | | generateLongQueue(); |
| | | state = StrategyState.ACTIVE; |
| | | log.info("[Gate] 网格队列已生成, 空队首:{} → 尾:{}, 多队首:{} → 尾:{}, 已激活", |
| | | log.info("[Gate-{}] 网格队列已生成, 空队首:{} → 尾:{}, 多队首:{} → 尾:{}, 已激活", logLabel, |
| | | shortPriceQueue.get(0), shortPriceQueue.get(shortPriceQueue.size() - 1), |
| | | longPriceQueue.get(0), longPriceQueue.get(longPriceQueue.size() - 1)); |
| | | } |
| | |
| | | } |
| | | shortPriceQueue.sort((a, b) -> b.compareTo(a)); |
| | | //输出队列:shortPriceQueue; |
| | | log.info("[Gate] 空队列:{}", shortPriceQueue); |
| | | log.info("[Gate-{}] 空队列:{}", logLabel, shortPriceQueue); |
| | | } |
| | | |
| | | private void generateLongQueue() { |
| | |
| | | longPriceQueue.add(longBaseEntryPrice.multiply(BigDecimal.ONE.add(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP)); |
| | | } |
| | | longPriceQueue.sort(BigDecimal::compareTo); |
| | | log.info("[Gate] 多队列:{}", longPriceQueue); |
| | | log.info("[Gate-{}] 多队列:{}", logLabel, longPriceQueue); |
| | | } |
| | | |
| | | /** |
| | |
| | | } |
| | | } |
| | | } |
| | | log.info("[Gate] 原空队列:{}", shortPriceQueue); |
| | | log.info("[Gate-{}] 原空队列:{}", logLabel, shortPriceQueue); |
| | | if (matched.isEmpty()) { |
| | | log.info("[Gate] 空仓队列未触发, 当前价:{}", currentPrice); |
| | | log.info("[Gate-{}] 空仓队列未触发, 当前价:{}", logLabel, currentPrice); |
| | | return; |
| | | } |
| | | log.info("[Gate] 空仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice); |
| | | log.info("[Gate-{}] 空仓队列触发, 匹配{}个元素, 当前价:{}", logLabel, matched.size(), currentPrice); |
| | | if (!isMarginSafe()) { |
| | | log.warn("[Gate] 保证金超限,跳过空单开仓"); |
| | | log.warn("[Gate-{}] 保证金超限,跳过空单开仓", logLabel); |
| | | } else { |
| | | executor.openShort(negate(config.getQuantity()), null, null); |
| | | if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | |
| | | && currentPrice.compareTo(shortEntryPrice) > 0 |
| | | && currentPrice.compareTo(longEntryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate()))) < 0) { |
| | | executor.openLong(config.getQuantity(), null, null); |
| | | log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", currentPrice); |
| | | log.info("[Gate-{}] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", logLabel, currentPrice); |
| | | } |
| | | } |
| | | |
| | |
| | | for (int i = 0; i < matched.size(); i++) { |
| | | min = min.multiply(BigDecimal.ONE.subtract(step)).setScale(1, RoundingMode.HALF_UP); |
| | | shortPriceQueue.add(min); |
| | | log.info("[Gate] 空队列增加:{}", min); |
| | | log.info("[Gate-{}] 空队列增加:{}", logLabel, min); |
| | | } |
| | | |
| | | shortPriceQueue.sort((a, b) -> b.compareTo(a)); |
| | | |
| | | log.info("[Gate] 现空队列:{}", shortPriceQueue); |
| | | log.info("[Gate-{}] 现空队列:{}", logLabel, shortPriceQueue); |
| | | } |
| | | |
| | | synchronized (longPriceQueue) { |
| | |
| | | BigDecimal step = config.getGridRate(); |
| | | for (int i = 1; i <= matched.size(); i++) { |
| | | BigDecimal elem = first.multiply(BigDecimal.ONE.subtract(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP); |
| | | if (longEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | | && elem.subtract(longEntryPrice).abs().compareTo(longEntryPrice.multiply(step)) < 0) { |
| | | if (elem.subtract(currentPrice).abs().compareTo(currentPrice.multiply(step)) < 0) { |
| | | log.info("[Gate] 多队列跳过:{}", elem); |
| | | continue; |
| | | } |
| | |
| | | while (longPriceQueue.size() > config.getGridQueueSize()) { |
| | | longPriceQueue.remove(longPriceQueue.size() - 1); |
| | | } |
| | | log.info("[Gate] 现多队列:{}", longPriceQueue); |
| | | log.info("[Gate-{}] 现多队列:{}", logLabel, longPriceQueue); |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | } |
| | | log.info("[Gate] 原多队列:{}", longPriceQueue); |
| | | log.info("[Gate-{}] 原多队列:{}", logLabel, longPriceQueue); |
| | | if (matched.isEmpty()) { |
| | | log.info("[Gate] 多仓队列未触发, 当前价:{}", currentPrice); |
| | | log.info("[Gate-{}] 多仓队列未触发, 当前价:{}", logLabel, currentPrice); |
| | | return; |
| | | } |
| | | |
| | | log.info("[Gate] 多仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice); |
| | | log.info("[Gate-{}] 多仓队列触发, 匹配{}个元素, 当前价:{}", logLabel, matched.size(), currentPrice); |
| | | if (!isMarginSafe()) { |
| | | log.warn("[Gate] 保证金超限,跳过多单开仓"); |
| | | log.warn("[Gate-{}] 保证金超限,跳过多单开仓", logLabel); |
| | | } else { |
| | | executor.openLong(config.getQuantity(), null, null); |
| | | if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | |
| | | && currentPrice.compareTo(shortEntryPrice.multiply(BigDecimal.ONE.add(config.getGridRate()))) > 0 |
| | | && currentPrice.compareTo(longEntryPrice) < 0) { |
| | | executor.openShort(negate(config.getQuantity()), null, null); |
| | | log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", currentPrice); |
| | | log.info("[Gate-{}] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", logLabel, currentPrice); |
| | | } |
| | | } |
| | | |
| | |
| | | max = max.multiply(BigDecimal.ONE.add(step)).setScale(1, RoundingMode.HALF_UP); |
| | | longPriceQueue.add(max); |
| | | |
| | | log.info("[Gate] 多队列增加:{}", max); |
| | | log.info("[Gate-{}] 多队列增加:{}", logLabel, max); |
| | | } |
| | | longPriceQueue.sort(BigDecimal::compareTo); |
| | | |
| | | log.info("[Gate] 现多队列:{}", longPriceQueue); |
| | | log.info("[Gate-{}] 现多队列:{}", logLabel, longPriceQueue); |
| | | } |
| | | |
| | | synchronized (shortPriceQueue) { |
| | |
| | | BigDecimal step = config.getGridRate(); |
| | | for (int i = 1; i <= matched.size(); i++) { |
| | | BigDecimal elem = first.multiply(BigDecimal.ONE.add(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP); |
| | | if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | | && elem.subtract(shortEntryPrice).abs().compareTo(shortEntryPrice.multiply(step)) < 0) { |
| | | if (elem.subtract(currentPrice).abs().compareTo(currentPrice.multiply(step)) < 0) { |
| | | |
| | | log.info("[Gate] 空队列跳过:{}", elem); |
| | | continue; |
| | |
| | | while (shortPriceQueue.size() > config.getGridQueueSize()) { |
| | | shortPriceQueue.remove(shortPriceQueue.size() - 1); |
| | | } |
| | | log.info("[Gate] 现空队列:{}", shortPriceQueue); |
| | | log.info("[Gate-{}] 现空队列:{}", logLabel, shortPriceQueue); |
| | | } |
| | | } |
| | | |
| | |
| | | FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE); |
| | | BigDecimal margin = new BigDecimal(account.getPositionInitialMargin()); |
| | | BigDecimal ratio = margin.divide(initialPrincipal, 4, RoundingMode.HALF_UP); |
| | | log.debug("[Gate] 保证金比例: {}/{}={}", margin, initialPrincipal, ratio); |
| | | log.debug("[Gate-{}] 保证金比例: {}/{}={}", logLabel, margin, initialPrincipal, ratio); |
| | | return ratio.compareTo(config.getMarginRatioLimit()) < 0; |
| | | } catch (Exception e) { |
| | | log.warn("[Gate] 查保证金失败,默认放行", e); |
| | | log.warn("[Gate-{}] 查保证金失败,默认放行", logLabel, e); |
| | | return true; |
| | | } |
| | | } |
| | |
| | | } |
| | | unrealizedPnl = longPnl.add(shortPnl); |
| | | |
| | | log.info("[Gate] 未实现盈亏: {}", unrealizedPnl); |
| | | log.info("[Gate-{}] 未实现盈亏: {}", logLabel, unrealizedPnl); |
| | | } |
| | | |
| | | /** |
| | |
| | | |
| | | private static final String SETTLE = "usdt"; |
| | | |
| | | private final String logLabel; |
| | | private final FuturesApi futuresApi; |
| | | private final String contract; |
| | | |
| | | /** 交易线程池:单线程 + 有界队列 + 背压策略 */ |
| | | private final ExecutorService executor; |
| | | |
| | | public GateTradeExecutor(ApiClient apiClient, String contract) { |
| | | public GateTradeExecutor(ApiClient apiClient, String contract, String label) { |
| | | this.logLabel = label; |
| | | this.futuresApi = new FuturesApi(apiClient); |
| | | this.contract = contract; |
| | | this.executor = new ThreadPoolExecutor( |
| | |
| | | 60L, TimeUnit.SECONDS, |
| | | new LinkedBlockingQueue<>(64), |
| | | r -> { |
| | | Thread t = new Thread(r, "gate-trade-worker"); |
| | | Thread t = new Thread(r, "gate-trade-" + label); |
| | | t.setDaemon(true); |
| | | return t; |
| | | }, |
| | |
| | | order.setTif(FuturesOrder.TifEnum.IOC); |
| | | order.setText(text); |
| | | FuturesOrder result = futuresApi.createFuturesOrder(SETTLE, order, null); |
| | | log.info("[TradeExec] {}成功, 价格:{}, id:{}", label, result.getFillPrice(), result.getId()); |
| | | log.info("[TradeExec-{}] {}成功, 价格:{}, id:{}", logLabel, label, result.getFillPrice(), result.getId()); |
| | | if (onSuccess != null) { |
| | | onSuccess.run(); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("[TradeExec] {}失败", label, e); |
| | | log.error("[TradeExec-{}] {}失败", logLabel, label, e); |
| | | if (onFailure != null) { |
| | | onFailure.run(); |
| | | } |
| | |
| | | FuturesPriceTriggeredOrder order = buildTriggeredOrder(triggerPrice, rule, orderType, size); |
| | | try { |
| | | TriggerOrderResponse response = futuresApi.createPriceTriggeredOrder(SETTLE, order); |
| | | log.info("[TradeExec] 止盈单已创建, 触发价:{}, 类型:{}, size:{}, id:{}", |
| | | triggerPrice, orderType, size, response.getId()); |
| | | log.info("[TradeExec-{}] 止盈单已创建, 触发价:{}, 类型:{}, size:{}, id:{}", |
| | | logLabel, triggerPrice, orderType, size, response.getId()); |
| | | } catch (Exception e) { |
| | | log.error("[TradeExec] 止盈单创建失败, 触发价:{}, size:{}, 立即市价止盈", triggerPrice, size, e); |
| | | log.error("[TradeExec-{}] 止盈单创建失败, 触发价:{}, size:{}, 立即市价止盈", logLabel, triggerPrice, size, e); |
| | | marketClose(size); |
| | | } |
| | | }); |
| | |
| | | order.setReduceOnly(true); |
| | | order.setText("t-grid-mkt-close"); |
| | | FuturesOrder result = futuresApi.createFuturesOrder(SETTLE, order, null); |
| | | log.info("[TradeExec] 市价止盈成功, 价格:{}, size:{}, id:{}", result.getFillPrice(), size, result.getId()); |
| | | log.info("[TradeExec-{}] 市价止盈成功, 价格:{}, size:{}, id:{}", logLabel, result.getFillPrice(), size, result.getId()); |
| | | } catch (Exception e) { |
| | | log.error("[TradeExec] 市价止盈也失败, size:{}", size, e); |
| | | log.error("[TradeExec-{}] 市价止盈也失败, size:{}", logLabel, size, e); |
| | | } |
| | | } |
| | | |
| | |
| | | executor.execute(() -> { |
| | | try { |
| | | futuresApi.cancelPriceTriggeredOrderList(SETTLE, contract); |
| | | log.info("[TradeExec] 已清除所有止盈止损条件单"); |
| | | log.info("[TradeExec-{}] 已清除所有止盈止损条件单", logLabel); |
| | | } catch (Exception e) { |
| | | log.error("[TradeExec] 清除止盈止损条件单失败", e); |
| | | log.error("[TradeExec-{}] 清除止盈止损条件单失败", logLabel, e); |
| | | } |
| | | }); |
| | | } |
| | |
| | | import javax.annotation.PostConstruct; |
| | | import javax.annotation.PreDestroy; |
| | | import java.math.BigDecimal; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * Gate 模块 Spring 入口,组装所有组件并管理生命周期。 |
| | | * Gate 模块 Spring 入口,管理多个账号实例的生命周期。 |
| | | * |
| | | * <h3>启动流程 ({@code @PostConstruct})</h3> |
| | | * <ol> |
| | | * <li>构建 {@link GateConfig}(Builder 模式,含 API 密钥、合约、策略参数)</li> |
| | | * <li>创建 {@link GateGridTradeService} → init():切持仓模式、清旧条件单、设杠杆</li> |
| | | * <li>创建 {@link GateKlineWebSocketClient} → 注册 3 个 Handler → init():建立 WS 连接</li> |
| | | * <li>gridTradeService.startGrid():激活策略,等待 K 线触发首次双开</li> |
| | | * <li>遍历 {@link #buildAccountConfigs()} 构建每个账号的 {@link GateConfig}</li> |
| | | * <li>每个账号创建独立的 {@link AccountInstance}(含 service + wsClient)</li> |
| | | * <li>逐个 init → startGrid</li> |
| | | * </ol> |
| | | * |
| | | * <h3>销毁流程 ({@code @PreDestroy})</h3> |
| | | * <ol> |
| | | * <li>gridTradeService.stopGrid():取消条件单 → 关闭交易线程池</li> |
| | | * <li>wsClient.destroy():取消订阅 → 断开 WS → 关闭线程池</li> |
| | | * <li>遍历 instances:stopGrid + wsClient.destroy()</li> |
| | | * </ol> |
| | | * |
| | | * <h3>配置</h3> |
| | | * 当前在代码中硬编码测试网参数。切换到生产网只需改为 {@code .isProduction(true)}。 |
| | | * <h3>添加新账号</h3> |
| | | * 在 {@link #buildAccountConfigs()} 方法中添加新的 {@link GateConfig} 即可。 |
| | | * 通过 {@link GateConfig#getLabel()} 区分日志输出, |
| | | * 通过 {@link GateConfig#isProduction()} 控制模拟盘/实盘环境。 |
| | | * |
| | | * @author Administrator |
| | | */ |
| | |
| | | @Component |
| | | public class GateWebSocketClientManager { |
| | | |
| | | /** WebSocket 连接管理器 */ |
| | | private GateKlineWebSocketClient wsClient; |
| | | /** 网格交易策略服务 */ |
| | | private GateGridTradeService gridTradeService; |
| | | /** 统一配置 */ |
| | | private GateConfig config; |
| | | /** 所有账号实例列表 */ |
| | | private final List<AccountInstance> instances = new ArrayList<>(); |
| | | |
| | | @PostConstruct |
| | | public void init() { |
| | | log.info("[管理器] 开始初始化..."); |
| | | /** |
| | | * 封装一个账号的完整运行时组件。 |
| | | */ |
| | | private static class AccountInstance { |
| | | final String label; |
| | | final GateConfig config; |
| | | final GateGridTradeService service; |
| | | final GateKlineWebSocketClient wsClient; |
| | | |
| | | try { |
| | | config = GateConfig.builder() |
| | | AccountInstance(GateConfig config) { |
| | | this.label = config.getLabel(); |
| | | this.config = config; |
| | | this.service = new GateGridTradeService(config); |
| | | this.wsClient = new GateKlineWebSocketClient(config.getWsUrl()); |
| | | } |
| | | |
| | | void init() { |
| | | service.init(); |
| | | wsClient.addChannelHandler(new CandlestickChannelHandler(config.getContract(), service)); |
| | | wsClient.addChannelHandler(new PositionsChannelHandler( |
| | | config.getApiKey(), config.getApiSecret(), config.getContract(), service)); |
| | | wsClient.addChannelHandler(new PositionClosesChannelHandler( |
| | | config.getApiKey(), config.getApiSecret(), config.getContract(), service)); |
| | | wsClient.init(); |
| | | log.info("[{}] WS已连接, 已注册 3 个频道处理器", label); |
| | | service.startGrid(); |
| | | } |
| | | |
| | | void destroy() { |
| | | log.info("[{}] 开始销毁...", label); |
| | | service.stopGrid(); |
| | | wsClient.destroy(); |
| | | log.info("[{}] 销毁完成", label); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 在此方法中配置所有账号。 |
| | | * <p>每个 {@link GateConfig} 对应一个账号,label 用于日志区分, |
| | | * isProduction 控制连接测试网(true=实盘)还是测试网(false=模拟盘)。 |
| | | */ |
| | | private static GateConfig[] buildAccountConfigs() { |
| | | return new GateConfig[]{ |
| | | GateConfig.builder() |
| | | .label("模拟盘1") |
| | | .apiKey("d90ca272391992b8e74f8f92cedb21ec") |
| | | .apiSecret("1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274") |
| | | .contract("ETH_USDT") |
| | |
| | | .unrealizedPnlPriceMode(GateConfig.PnLPriceMode.LAST_PRICE) |
| | | .isProduction(false) |
| | | .reopenMaxRetries(3) |
| | | .build(); |
| | | |
| | | gridTradeService = new GateGridTradeService(config); |
| | | gridTradeService.init(); |
| | | |
| | | wsClient = new GateKlineWebSocketClient(config.getWsUrl()); |
| | | wsClient.addChannelHandler(new CandlestickChannelHandler(config.getContract(), gridTradeService)); |
| | | wsClient.addChannelHandler(new PositionsChannelHandler( |
| | | config.getApiKey(), config.getApiSecret(), config.getContract(), gridTradeService)); |
| | | wsClient.addChannelHandler(new PositionClosesChannelHandler( |
| | | config.getApiKey(), config.getApiSecret(), config.getContract(), gridTradeService)); |
| | | wsClient.init(); |
| | | log.info("[管理器] WS已连接, 已注册 3 个频道处理器"); |
| | | |
| | | gridTradeService.startGrid(); |
| | | } catch (Exception e) { |
| | | log.error("[管理器] 初始化失败", e); |
| | | .build(), |
| | | }; |
| | | } |
| | | |
| | | @PostConstruct |
| | | public void init() { |
| | | GateConfig[] configs = buildAccountConfigs(); |
| | | log.info("[管理器] 开始初始化 {} 个账号...", configs.length); |
| | | for (GateConfig config : configs) { |
| | | try { |
| | | AccountInstance instance = new AccountInstance(config); |
| | | instance.init(); |
| | | instances.add(instance); |
| | | } catch (Exception e) { |
| | | log.error("[管理器] 账号 {} 初始化失败", config.getLabel(), e); |
| | | } |
| | | } |
| | | |
| | | log.info("[管理器] 初始化完成, 成功启动 {}/{} 个账号", instances.size(), configs.length); |
| | | } |
| | | |
| | | @PreDestroy |
| | | public void destroy() { |
| | | log.info("[管理器] 开始销毁..."); |
| | | if (gridTradeService != null) { |
| | | gridTradeService.stopGrid(); |
| | | log.info("[管理器] 开始销毁 {} 个账号...", instances.size()); |
| | | for (AccountInstance instance : instances) { |
| | | try { |
| | | instance.destroy(); |
| | | } catch (Exception e) { |
| | | log.error("[管理器] 账号 {} 销毁失败", instance.label, e); |
| | | } |
| | | if (wsClient != null) { |
| | | wsClient.destroy(); |
| | | } |
| | | log.info("[管理器] 销毁完成"); |
| | | } |
| | | |
| | | public GateKlineWebSocketClient getKlineWebSocketClient() { return wsClient; } |
| | | public GateGridTradeService getGridTradeService() { return gridTradeService; } |
| | | /** 获取账号数量 */ |
| | | public int getInstanceCount() { |
| | | return instances.size(); |
| | | } |
| | | |
| | | /** 获取指定索引的 GridTradeService(用于外部监控/查询) */ |
| | | public GateGridTradeService getGridTradeService(int index) { |
| | | return instances.get(index).service; |
| | | } |
| | | } |