From 682a5c4a1e06d78ca2d42ecd5a1ceac066630bfb Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Sat, 11 Jul 2026 14:48:01 +0800
Subject: [PATCH] 初始化开仓撤销挂止盈单

---
 src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java |  204 ++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 155 insertions(+), 49 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 f020544..2e311e1 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
@@ -1,83 +1,189 @@
 package com.xcong.excoin.modules.gateApi;
 
-import com.xcong.excoin.modules.okxNewPrice.OkxKlineWebSocketClient;
-import com.xcong.excoin.modules.okxNewPrice.OkxQuantWebSocketClient;
-import com.xcong.excoin.modules.okxNewPrice.celue.CaoZuoService;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.ExchangeInfoEnum;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.wanggeList.WangGeListService;
-import com.xcong.excoin.utils.RedisUtils;
+import com.xcong.excoin.modules.gateApi.wsHandler.handler.AutoOrdersChannelHandler;
+import com.xcong.excoin.modules.gateApi.wsHandler.handler.CandlestickChannelHandler;
+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.boot.autoconfigure.condition.ConditionalOnProperty;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
-import java.util.Collection;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
+import java.math.BigDecimal;
 
 /**
- * 管理多个OKX WebSocket客户端实例,每个实例对应一个账号
+ * Gate 模块 Spring 容器入口 — 组件组装 + 生命周期管理。
+ *
+ * <h3>组装顺序({@code @PostConstruct})</h3>
+ * <ol>
+ *   <li>{@link GateConfig} — 构建配置(API 密钥、合约、策略参数)</li>
+ *   <li>{@link GateGridTradeService} — init():获取用户 ID → 切双向持仓 → 清旧条件单 → 平仓 → 设杠杆</li>
+ *   <li>{@link GateKlineWebSocketClient} — 注册 6 个频道处理器 → init():建立 WS 连接并订阅</li>
+ *   <li>{@code gridTradeService.startGrid()} — 状态重置,等待首根 K 线</li>
+ * </ol>
+ *
+ * <h3>6 个频道处理器</h3>
+ * <ol>
+ *   <li>CandlestickChannelHandler — 公开频道,K线 → onKline()</li>
+ *   <li>PositionsChannelHandler — 私有频道,仓位 → onPositionUpdate()</li>
+ *   <li>PositionClosesChannelHandler — 私有频道,平仓 → onPositionClose()</li>
+ *   <li>OrdersChannelHandler — 私有频道,订单成交 → onOrderUpdate()</li>
+ *   <li>UserTradesChannelHandler — 私有频道,用户成交 → onUserTrade()</li>
+ *   <li>AutoOrdersChannelHandler — 私有频道,条件单状态 → onAutoOrder()</li>
+ * </ol>
+ *
+ * <h3>销毁顺序({@code @PreDestroy})</h3>
+ * <ol>
+ *   <li>gridTradeService.stopGrid():取消所有条件单 → 关闭交易线程池</li>
+ *   <li>wsClient.destroy():取消订阅 → 断开 WS → 关闭线程池</li>
+ * </ol>
+ *
+ * @author Administrator
  */
 @Slf4j
 @Component
 public class GateWebSocketClientManager {
-    @Autowired
-    private CaoZuoService caoZuoService;
-    @Autowired
-    private RedisUtils redisUtils;
-    @Autowired
-    private WangGeListService wangGeListService;
 
-    private GateKlineWebSocketClient klinePriceClient;
+    // ==================== 修改配置只需改这里 ===================
+    static final String DEFAULT_API_KEY = "b698ffb0cabdb575d04f42539b4b5acf";
+    static final String DEFAULT_API_SECRET = "6bd6d436abd5c05ebf382bf4494cf6f9444ec1b074eadbba4ee239aaffb0fa09";
+    // 不可调参数
+    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;
 
-    /**
-     * 初始化方法,在Spring Bean构造完成后执行
-     * 创建并初始化所有账号的WebSocket客户端实例
-     */
+    @Autowired
+    private GateLogBuffer logBuffer;
+
+    /** WebSocket 连接管理器 */
+    private GateKlineWebSocketClient wsClient;
+    /** 网格交易策略服务 */
+    private GateGridTradeService gridTradeService;
+    /** 统一配置 */
+    private GateConfig config;
+
     @PostConstruct
     public void init() {
-        log.info("开始初始化OkxWebSocketClientManager");
-        
-        // 初始化价格WebSocket客户端
+        logBuffer.info("[管理器] 加载配置,策略待手动启动...");
+
         try {
-            klinePriceClient = new GateKlineWebSocketClient(caoZuoService, this, wangGeListService);
-            klinePriceClient.init();
-            log.info("已初始化OkxNewPriceWebSocketClient");
+            // 优先读取持久化配置,不存在则用默认值创建文件
+            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 {
+                // 构建默认配置 DTO(只有 7 项可调参数)
+                GateConfigDTO defaults = GateConfigDTO.builder()
+                        .apiKey(DEFAULT_API_KEY)
+                        .gridRate(new BigDecimal("0.005"))
+                        .expectedProfit(new BigDecimal("0.15"))
+                        .maxLoss(new BigDecimal("1.5"))
+                        .baseQuantity("2")
+                        .quantity("2")
+                        .maxPositionSize(4)
+                        .stopLossCount(0)
+                        .build();
+                // 确保配置文件存在
+                persistenceService.ensureExists(DEFAULT_API_KEY, defaults);
+                config = persistenceService.buildFromDTO(defaults, DEFAULT_API_KEY);
+                logBuffer.info("[管理器] 已创建默认配置文件");
+            }
+
+            logBuffer.info("[管理器] 配置就绪,请通过控制面板点击「重启策略」启动");
         } catch (Exception e) {
-            log.error("初始化OkxNewPriceWebSocketClient失败", e);
+            logBuffer.error("[管理器] 配置加载失败: " + e.getMessage());
         }
-        
     }
 
     /**
-     * 销毁方法,在Spring Bean销毁前执行
-     * 关闭所有WebSocket客户端连接和相关资源
+     * 销毁:停止策略 → 关闭交易线程池 → 取消 WS 订阅 → 断开连接 → 关闭 WS 线程池。
      */
     @PreDestroy
     public void destroy() {
-        log.info("开始销毁OkxWebSocketClientManager");
-        
-        // 关闭价格WebSocket客户端
-        if (klinePriceClient != null) {
-            try {
-                klinePriceClient.destroy();
-                log.info("已销毁OkxNewPriceWebSocketClient");
-            } catch (Exception e) {
-                log.error("销毁OkxNewPriceWebSocketClient失败", e);
-            }
+        log.info("[管理器] 开始销毁...");
+        if (gridTradeService != null) {
+            gridTradeService.stopGrid();
         }
-        
-        log.info("OkxWebSocketClientManager销毁完成");
+        if (wsClient != null) {
+            wsClient.destroy();
+        }
+        log.info("[管理器] 销毁完成");
     }
 
     /**
-     * 获取OkxNewPriceWebSocketClient实例
-     * @return 价格WebSocket客户端实例
+     * @return WebSocket 连接管理器实例
      */
-    public GateKlineWebSocketClient getKlineWebSocketClient() {
-        return klinePriceClient;
+    public GateKlineWebSocketClient getKlineWebSocketClient() { return wsClient; }
+    /**
+     * @return 网格交易策略服务实例
+     */
+    public GateGridTradeService getGridTradeService() { return gridTradeService; }
+    /**
+     * @return 当前生效的配置
+     */
+    public GateConfig getConfig() { return config; }
+
+    /**
+     * 使用新配置重启策略:停止旧策略 → 重建 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);
+        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("[管理器] 策略已使用新配置重启完成");
     }
-}
\ No newline at end of file
+
+    /**
+     * 停止策略:取消所有条件单 → 停止网格 → 断开 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