From 60d0e9bd70f87de69b378ab63bac60394e3ff696 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 11 May 2026 11:31:52 +0800
Subject: [PATCH] feat(gate): 添加多账号支持和日志标签区分功能

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |  102 +++++++++++++++++++++++++-------------------------
 1 files changed, 51 insertions(+), 51 deletions(-)

diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
index a09714d..55aef49 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -92,6 +92,7 @@
     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";
@@ -130,11 +131,12 @@
 
     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);
     }
 
     // ---- 初始化 ----
@@ -146,14 +148,14 @@
             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();
 
             //设置持仓模式为双向持仓
@@ -185,19 +187,19 @@
                     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;
@@ -223,12 +225,12 @@
                 }
                 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);
         }
     }
 
@@ -236,7 +238,7 @@
 
     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;
@@ -253,14 +255,14 @@
         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线回调 ----
@@ -274,12 +276,12 @@
 
         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;
         }
@@ -309,14 +311,14 @@
                     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;
                 }
@@ -332,14 +334,14 @@
                     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();
                 }
@@ -357,13 +359,13 @@
             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;
         }
     }
@@ -375,7 +377,7 @@
             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));
         }
@@ -389,7 +391,7 @@
         }
         shortPriceQueue.sort((a, b) -> b.compareTo(a));
         //输出队列:shortPriceQueue;
-        log.info("[Gate] 空队列:{}", shortPriceQueue);
+        log.info("[Gate-{}] 空队列:{}", logLabel, shortPriceQueue);
     }
 
     private void generateLongQueue() {
@@ -399,7 +401,7 @@
             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);
     }
 
     /**
@@ -432,14 +434,14 @@
                 }
             }
         }
-        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
@@ -448,7 +450,7 @@
                     && 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);
             }
         }
 
@@ -459,12 +461,12 @@
             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) {
@@ -472,8 +474,7 @@
             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;
                 }
@@ -485,7 +486,7 @@
             while (longPriceQueue.size() > config.getGridQueueSize()) {
                 longPriceQueue.remove(longPriceQueue.size() - 1);
             }
-            log.info("[Gate] 现多队列:{}", longPriceQueue);
+            log.info("[Gate-{}] 现多队列:{}", logLabel, longPriceQueue);
         }
     }
 
@@ -519,15 +520,15 @@
                 }
             }
         }
-        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
@@ -536,7 +537,7 @@
                     && 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);
             }
         }
 
@@ -548,11 +549,11 @@
                 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) {
@@ -560,8 +561,7 @@
             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;
@@ -574,7 +574,7 @@
             while (shortPriceQueue.size() > config.getGridQueueSize()) {
                 shortPriceQueue.remove(shortPriceQueue.size() - 1);
             }
-            log.info("[Gate] 现空队列:{}", shortPriceQueue);
+            log.info("[Gate-{}] 现空队列:{}", logLabel, shortPriceQueue);
         }
     }
 
@@ -585,10 +585,10 @@
             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;
         }
     }
@@ -625,7 +625,7 @@
         }
         unrealizedPnl = longPnl.add(shortPnl);
 
-        log.info("[Gate] 未实现盈亏: {}", unrealizedPnl);
+        log.info("[Gate-{}] 未实现盈亏: {}", logLabel, unrealizedPnl);
     }
 
     /**

--
Gitblit v1.9.1