From 097ee94cc027baf4970c4fc5daf2aece694d08d9 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Fri, 08 May 2026 14:34:58 +0800
Subject: [PATCH] refactor(gateApi): 重构 Gate API 模块代码结构

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java |   91 +++++++++++++++++++++++++++++++++++----------
 1 files changed, 71 insertions(+), 20 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 ed17373..f5b7f62 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -7,7 +7,9 @@
 import io.gate.gateapi.api.FuturesApi;
 import io.gate.gateapi.models.AccountDetail;
 import io.gate.gateapi.models.FuturesAccount;
+import io.gate.gateapi.models.FuturesOrder;
 import io.gate.gateapi.models.FuturesPriceTrigger;
+import io.gate.gateapi.models.Position;
 import lombok.extern.slf4j.Slf4j;
 
 import java.math.BigDecimal;
@@ -76,31 +78,79 @@
             detailClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
             AccountDetail detail = new AccountApi(detailClient).getAccountDetail();
             this.userId = detail.getUserId();
-            log.info("[Gate] uid:{}", userId);
+            log.info("[Gate] 用户ID: {}", userId);
 
             FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
             if (!config.getPositionMode().equals(account.getPositionMode())) {
                 futuresApi.setPositionMode(SETTLE, config.getPositionMode());
             }
-            log.info("[Gate] mode:{} balance:{}", config.getPositionMode(), account.getAvailable());
+            log.info("[Gate] 持仓模式: {} 余额: {}", config.getPositionMode(), account.getAvailable());
 
             futuresApi.cancelPriceTriggeredOrderList(SETTLE, config.getContract());
-            log.info("[Gate] old orders cleared");
+            log.info("[Gate] 旧条件单已清除");
+
+            closeExistingPositions();
 
             futuresApi.updateContractPositionLeverageCall(
                     SETTLE, config.getContract(), config.getLeverage(),
                     config.getMarginMode(), config.getPositionMode(), null);
-            log.info("[Gate] {}x {}", config.getLeverage(), config.getMarginMode());
+            log.info("[Gate] 杠杆: {}x {}", config.getLeverage(), config.getMarginMode());
         } catch (GateApiException e) {
-            log.error("[Gate] init fail, label:{}, msg:{}", e.getErrorLabel(), e.getMessage());
+            log.error("[Gate] 初始化失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage());
         } catch (ApiException e) {
-            log.error("[Gate] init fail, code:{}", e.getCode());
+            log.error("[Gate] 初始化失败, code:{}", e.getCode());
+        }
+    }
+
+    /**
+     * 平掉当前合约所有已有仓位。
+     * 策略启动前的准备工作,确保从零持仓状态开始运行。
+     */
+    private void closeExistingPositions() {
+        try {
+            java.util.List<Position> positions = futuresApi.listPositions(SETTLE).execute();
+            if (positions == null || positions.isEmpty()) {
+                log.info("[Gate] 无已有仓位,无需平仓");
+                return;
+            }
+
+            for (Position pos : positions) {
+                if (!config.getContract().equals(pos.getContract())) {
+                    continue;
+                }
+                String sizeStr = pos.getSize();
+                long size = Long.parseLong(sizeStr);
+                if (size == 0) {
+                    continue;
+                }
+
+                String closeSize = size > 0 ? String.valueOf(-size) : String.valueOf(Math.abs(size));
+                boolean isLong = size > 0;
+                Position.ModeEnum mode = pos.getMode();
+
+                FuturesOrder closeOrder = new FuturesOrder();
+                closeOrder.setContract(config.getContract());
+                closeOrder.setSize(closeSize);
+                closeOrder.setPrice("0");
+                closeOrder.setTif(FuturesOrder.TifEnum.IOC);
+                closeOrder.setReduceOnly(true);
+                if (mode != null && mode.getValue() != null && mode.getValue().contains("dual")) {
+                    closeOrder.setAutoSize(isLong ? FuturesOrder.AutoSizeEnum.LONG : FuturesOrder.AutoSizeEnum.SHORT);
+                }
+                closeOrder.setText("t-grid-init-close");
+                futuresApi.createFuturesOrder(SETTLE, closeOrder, null);
+                log.info("[Gate] 已平掉已有仓位, 方向:{}, sizes:{}, mode:{}", isLong ? "多头" : "空头", sizeStr, mode);
+            }
+        } catch (GateApiException e) {
+            log.warn("[Gate] 平已有仓位失败, label:{}, msg:{}, 可能无仓位", e.getErrorLabel(), e.getMessage());
+        } catch (Exception e) {
+            log.warn("[Gate] 平已有仓位异常, 可能无仓位", e);
         }
     }
 
     public void startGrid() {
         if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) {
-            log.warn("[Gate] already running, state:{}", state);
+            log.warn("[Gate] 策略已在运行中, state:{}", state);
             return;
         }
         state = StrategyState.WAITING_KLINE;
@@ -109,14 +159,14 @@
         shortActive = false;
         longReopenFails = 0;
         shortReopenFails = 0;
-        log.info("[Gate] grid started");
+        log.info("[Gate] 网格策略已启动");
     }
 
     public void stopGrid() {
         state = StrategyState.STOPPED;
         executor.cancelAllPriceTriggeredOrders();
         executor.shutdown();
-        log.info("[Gate] stopped, pnl:{}", cumulativePnl);
+        log.info("[Gate] 策略已停止, 累计盈亏: {}", cumulativePnl);
     }
 
     /**
@@ -129,7 +179,7 @@
         }
 
         state = StrategyState.OPENING;
-        log.info("[Gate] first kline, opening...");
+        log.info("[Gate] 首根K线到达,开始双开...");
 
         executor.openLong(config.getQuantity(), () -> {
             synchronized (this) {
@@ -148,7 +198,7 @@
                     "close-short-position", "close_short");
             if (longActive && shortActive && state != StrategyState.STOPPED) {
                 state = StrategyState.ACTIVE;
-                log.info("[Gate] active, long:{}, short:{}, tpL:{}, tpS:{}",
+                log.info("[Gate] 已激活, 多头入场:{}, 空头入场:{}, 多头止盈:{}, 空头止盈:{}",
                         longEntryPrice, shortEntryPrice, longTpPrice(), shortTpPrice());
             }
         });
@@ -166,7 +216,7 @@
 
         if ("dual_long".equals(mode)) {
             if (longActive && !hasPosition) {
-                log.info("[Gate] long closed");
+                log.info("[Gate] 多头已平仓");
                 longActive = false;
                 tryReopenLong(0);
             } else if (hasPosition) {
@@ -175,7 +225,7 @@
             }
         } else if ("dual_short".equals(mode)) {
             if (shortActive && !hasPosition) {
-                log.info("[Gate] short closed");
+                log.info("[Gate] 空头已平仓");
                 shortActive = false;
                 tryReopenShort(0);
             } else if (hasPosition) {
@@ -193,18 +243,18 @@
             return;
         }
         cumulativePnl = cumulativePnl.add(pnl);
-        log.info("[Gate] pnl+{}, side:{}, total:{}", pnl, side, cumulativePnl);
+        log.info("[Gate] 盈亏累加:{}, 方向:{}, 累计:{}", pnl, side, cumulativePnl);
 
         if (cumulativePnl.compareTo(config.getOverallTp()) >= 0) {
-            log.info("[Gate] TP reached {}→STOPPED", cumulativePnl);
+            log.info("[Gate] 已达止盈目标 {}→已停止", cumulativePnl);
             state = StrategyState.STOPPED;
         } else if (cumulativePnl.compareTo(config.getMaxLoss().negate()) <= 0) {
-            log.info("[Gate] loss {}→STOPPED", cumulativePnl);
+            log.info("[Gate] 已达亏损上限 {}→已停止", cumulativePnl);
             state = StrategyState.STOPPED;
         }
     }
 
-    // ---- reopen with retry ----
+    // ---- 补仓(含重试) ----
 
     private void tryReopenLong(int retry) {
         if (state == StrategyState.STOPPED) {
@@ -226,7 +276,7 @@
             if (state != StrategyState.STOPPED) {
                 state = StrategyState.ACTIVE;
             }
-            log.info("[Gate] long reopened, price:{}", longEntryPrice);
+            log.info("[Gate] 多头已补开, 价格:{}", longEntryPrice);
         });
     }
 
@@ -250,11 +300,11 @@
             if (state != StrategyState.STOPPED) {
                 state = StrategyState.ACTIVE;
             }
-            log.info("[Gate] short reopened, price:{}", shortEntryPrice);
+            log.info("[Gate] 空头已补开, 价格:{}", shortEntryPrice);
         });
     }
 
-    // ---- util ----
+    // ---- 止盈价格计算 ----
 
     private BigDecimal longTpPrice() {
         return lastKlinePrice.multiply(BigDecimal.ONE.add(config.getGridRate()))
@@ -266,6 +316,7 @@
                 .setScale(1, RoundingMode.HALF_UP);
     }
 
+    /** 对数量取反(开多用正数,开空用负数) */
     private String negate(String qty) {
         return qty.startsWith("-") ? qty.substring(1) : "-" + qty;
     }

--
Gitblit v1.9.1