From a0460af5da48133ae1fd7741c2ddf9e8c639323d Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 24 Aug 2026 14:05:44 +0800
Subject: [PATCH] feat(gate): 添加策略远程控制和监控功能

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java |  168 +++++++++++++++++++++++++++++++++++++++++--------------
 1 files changed, 125 insertions(+), 43 deletions(-)

diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
index 533fe8b..ebce648 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
@@ -5,6 +5,7 @@
 import com.xcong.excoin.modules.gateApi.wsHandler.handler.PositionClosesChannelHandler;
 import com.xcong.excoin.modules.gateApi.wsHandler.handler.PositionsChannelHandler;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.PostConstruct;
@@ -44,6 +45,30 @@
 @Component
 public class GateWebSocketClientManager {
 
+    // ==================== 修改配置只需改这里 ===================
+    static final String DEFAULT_API_KEY = "c29ae131fad0da74e7d4de5b55ad1f84";
+    static final String DEFAULT_API_SECRET = "39cdcf19ab613497b1a01afb7dc9dbd97f2d15d350e2af4ab5a4ff1bbe041fa1";
+    // 不可调参数
+    static final String DEFAULT_CONTRACT = "ETH_USDT";
+    static final String DEFAULT_LEVERAGE = "100";
+    static final String DEFAULT_MARGIN_MODE = "CROSS";
+    static final String DEFAULT_POSITION_MODE = "dual";
+    static final int DEFAULT_RESTART_GRID_SPAN = 2;
+    static final int DEFAULT_PRICE_SCALE = 2;
+    static final String DEFAULT_CONTRACT_MULTIPLIER = "0.01";
+    static final String DEFAULT_PNL_MODE = "LAST_PRICE";
+    static final int DEFAULT_REOPEN_MAX_RETRIES = 3;
+    // ==========================================================
+
+    @Autowired
+    private GateConfigPersistenceService persistenceService;
+
+    @Autowired
+    private GateLogBuffer logBuffer;
+
+    @Autowired
+    private StatsEventProducer statsEventProducer;
+
     /** WebSocket 连接管理器 */
     private GateKlineWebSocketClient wsClient;
     /** 网格交易策略服务 */
@@ -53,53 +78,24 @@
 
     @PostConstruct
     public void init() {
-        log.info("[管理器] 开始初始化...");
+        logBuffer.info("[管理器] 加载配置,策略待手动启动...");
 
         try {
-            //实盘
-            config = GateConfig.builder()
-                    .apiKey("dbf5cc322a0f3d6f308e143c494fb0b4")
-                    .apiSecret("83cb291e21e62148ec99bc9adef493ee9f7fc195f2b9dc929466d70350ec58c3")
-                    .contract("ETH_USDT")
-                    .leverage("100")
-                    .marginMode("CROSS")
-                    .positionMode("dual")
-                    .gridRate(new BigDecimal("0.0025"))
-                    .expectedProfit(new BigDecimal("5"))
-                    .maxLoss(new BigDecimal("15"))
-                    .baseQuantity("33")
-                    .quantity("33")
-                    .maxPositionSize(66)
-                    .stopLossCount(2)
-                    .restartGridSpan(4)
-                    .priceScale(2)
-                    .contractMultiplier(new BigDecimal("0.01"))
-                    .unrealizedPnlPriceMode(GateConfig.PnLPriceMode.LAST_PRICE)
-                    .isProduction(true)
-                    .reopenMaxRetries(3)
-                    .build();
+            // 优先读取持久化配置,不存在则用默认值创建文件
+            GateConfigDTO saved = persistenceService.load(DEFAULT_API_KEY);
+            if (saved != null) {
+                config = persistenceService.buildFromDTO(saved, DEFAULT_API_KEY);
+                logBuffer.info("[管理器] 已加载持久化配置, apiKey=" + mask(DEFAULT_API_KEY));
+            } else {
+                GateConfigDTO defaults = GateConfigDTO.defaultsFor(DEFAULT_API_KEY);
+                persistenceService.ensureExists(DEFAULT_API_KEY, defaults);
+                config = persistenceService.buildFromDTO(defaults, DEFAULT_API_KEY);
+                logBuffer.info("[管理器] 已创建默认配置文件");
+            }
 
-            // 1. 初始化交易服务:查用户ID → 切持仓模式 → 清条件单 → 平已有仓位 → 设杠杆
-            gridTradeService = new GateGridTradeService(config);
-            gridTradeService.init();
-
-            // 2. 创建 WS 客户端并注册频道处理器
-            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.addChannelHandler(new AutoOrdersChannelHandler(
-                    config.getApiKey(), config.getApiSecret(), config.getContract(), gridTradeService));
-            gridTradeService.setWsClient(wsClient);
-            wsClient.init();
-            log.info("[管理器] WS已连接, 已注册 4 个频道处理器");
-
-            // 3. 激活策略,等待首根 K 线触发基底双开
-            gridTradeService.startGrid();
+            logBuffer.info("[管理器] 配置就绪,请通过控制面板点击「重启策略」启动");
         } catch (Exception e) {
-            log.error("[管理器] 初始化失败", e);
+            logBuffer.error("[管理器] 配置加载失败: " + e.getMessage());
         }
     }
 
@@ -126,4 +122,90 @@
      * @return 网格交易策略服务实例
      */
     public GateGridTradeService getGridTradeService() { return gridTradeService; }
+    /**
+     * @return 当前生效的配置
+     */
+    public GateConfig getConfig() { return config; }
+
+    /**
+     * 远程更新策略参数 — 仅持久化到 JSON 文件,不自动重启。
+     * 下次「启动」指令会从文件读取最新配置后重建策略。
+     *
+     * @param dto 从 Station 下发的可调参数(不含 apiSecret)
+     */
+    public void updateConfig(GateConfigDTO dto) {
+        logBuffer.info("[管理器] 收到远程参数更新指令(仅持久化)");
+        persistenceService.save(config.getApiKey(), dto);
+        logBuffer.info("[管理器] 参数已保存,待下次启动生效");
+    }
+
+    /**
+     * 从持久化文件重载配置并重启策略。
+     * 用于远程「启动」指令:先读最新配置 → 重建服务 → 启动。
+     */
+    public void reloadAndStart() {
+        logBuffer.info("[管理器] 从文件重载配置并启动...");
+        GateConfigDTO saved = persistenceService.load(config.getApiKey());
+        if (saved == null) {
+            logBuffer.info("[管理器] 无持久化配置,使用当前内存配置启动");
+            if (gridTradeService != null) {
+                gridTradeService.startGrid();
+            }
+            return;
+        }
+        GateConfig newConfig = persistenceService.buildFromDTO(saved, config.getApiKey());
+        restartWithConfig(newConfig);
+    }
+
+    /**
+     * 使用新配置重启策略:停止旧策略 → 重建 WS → 重新 init + startGrid。
+     */
+    public void restartWithConfig(GateConfig newConfig) {
+        logBuffer.info("[管理器] 开始策略重启...");
+        // 1. 停止旧策略 + 断开旧 WS
+        if (gridTradeService != null) {
+            gridTradeService.stopGrid();
+        }
+        if (wsClient != null) {
+            wsClient.destroy();
+        }
+        // 2. 使用新配置重建
+        this.config = newConfig;
+        this.gridTradeService = new GateGridTradeService(config, statsEventProducer);
+        gridTradeService.init();
+        // 3. 重建 WS 客户端并重新注册 Handler
+        this.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.addChannelHandler(new AutoOrdersChannelHandler(
+                config.getApiKey(), config.getApiSecret(), config.getContract(), gridTradeService));
+        gridTradeService.setWsClient(wsClient);
+        wsClient.init();
+        logBuffer.info("[管理器] WS已重连, Handler 已重新绑定");
+        // 4. 启动策略
+        gridTradeService.startGrid();
+        logBuffer.info("[管理器] 策略已使用新配置重启完成");
+    }
+
+    /**
+     * 停止策略:取消所有条件单 → 停止网格 → 断开 WS。
+     */
+    public void stopStrategy() {
+        logBuffer.info("[管理器] 停止策略...");
+        if (gridTradeService != null) {
+            gridTradeService.stopGrid();
+        }
+        if (wsClient != null) {
+            wsClient.destroy();
+        }
+        logBuffer.info("[管理器] 策略已停止");
+    }
+
+    private static String mask(String key) {
+        if (key == null || key.length() <= 8) return "***";
+        return key.substring(0, 4) + "****" + key.substring(key.length() - 4);
+    }
 }

--
Gitblit v1.9.1