From 5d884f3ba7340d34891a5e50d2e8b7fa83c84c73 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 11 May 2026 14:11:18 +0800
Subject: [PATCH] docs(gateApi): 更新代码注释和文档说明

---
 src/main/java/com/xcong/excoin/modules/gateApi/Example.java                                        |   21 ++
 src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java                           |  134 ++++++++++++++++
 src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java                     |   24 +++
 src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md                                    |    4 
 src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java    |   36 ++++
 src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java                       |   54 ++++++
 src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/AbstractPrivateChannelHandler.java        |   45 +++++
 src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionClosesChannelHandler.java |   18 ++
 src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java                                     |   79 +++++++++
 src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java                              |   24 ++
 10 files changed, 423 insertions(+), 16 deletions(-)

diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/Example.java b/src/main/java/com/xcong/excoin/modules/gateApi/Example.java
index 87ecc4a..c8f8ff3 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/Example.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/Example.java
@@ -15,8 +15,29 @@
 import java.math.BigDecimal;
 
 
+/**
+ * Gate SDK API 使用示例。
+ *
+ * <h3>演示内容</h3>
+ * <ol>
+ *   <li>通过 API Key/Secret 初始化客户端</li>
+ *   <li>查询期货账户余额</li>
+ *   <li>设置双向持仓模式</li>
+ *   <li>设置杠杆倍数</li>
+ *   <li>切换保证金模式(全仓/逐仓)</li>
+ * </ol>
+ *
+ * <h3>注意</h3>
+ * 此文件仅作为 SDK 用法参考,不影响实际策略运行。
+ * 当前策略中相同功能的实现在 {@code GateGridTradeService.init()} 中。
+ *
+ * @author Administrator
+ */
 @Slf4j
 public class Example {
+    /**
+     * 示例入口:依次执行查询账户 → 设置双向持仓 → 设杠杆 → 切换保证金模式。
+     */
     public static void main(String[] args) {
         ApiClient defaultClient = Configuration.getDefaultApiClient();
         defaultClient.setBasePath("https://api-testnet.gateapi.io/api/v4");
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
index ca6446c..b65d0aa 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
@@ -96,6 +96,8 @@
         this.unrealizedPnlPriceMode = builder.unrealizedPnlPriceMode;
     }
 
+    // ==================== REST/WS 地址 ====================
+
     /**
      * 根据环境返回 REST API 基础路径。
      * <ul>
@@ -122,22 +124,58 @@
                 : "wss://ws-testnet.gate.com/v4/ws/futures/usdt";
     }
 
+    // ==================== 认证信息 ====================
+
+    /** @return Gate API v4 密钥 */
     public String getApiKey() { return apiKey; }
+    /** @return Gate API v4 签名密钥,用于 HMAC-SHA512 签名 */
     public String getApiSecret() { return apiSecret; }
+
+    // ==================== 交易标的 ====================
+
+    /** @return 合约名称(如 ETH_USDT、XAU_USDT) */
     public String getContract() { return contract; }
+    /** @return 杠杆倍数(如 "100" 表示 100x) */
     public String getLeverage() { return leverage; }
+
+    // ==================== 持仓配置 ====================
+
+    /** @return 保证金模式(cross=全仓 / isolated=逐仓) */
     public String getMarginMode() { return marginMode; }
+    /** @return 持仓模式(single=单向 / dual=双向 / dual_plus) */
     public String getPositionMode() { return positionMode; }
+
+    // ==================== 策略参数 ====================
+
+    /** @return 网格间距比例(如 0.0015 表示 0.15%),用于生成价格队列和计算止盈价 */
     public BigDecimal getGridRate() { return gridRate; }
+    /** @return 整体止盈阈值(USDT),累计已实现盈亏 ≥ 此值时策略停止 */
     public BigDecimal getOverallTp() { return overallTp; }
+    /** @return 最大亏损阈值(USDT),累计已实现盈亏 ≤ -此值时策略停止 */
     public BigDecimal getMaxLoss() { return maxLoss; }
+    /** @return 每次下单的张数(如 "1" 表示 1 张合约) */
     public String getQuantity() { return quantity; }
-    public boolean isProduction() { return isProduction; }
-    public int getReopenMaxRetries() { return reopenMaxRetries; }
+    /** @return 网格价格队列的容量上限(超出时截断尾部) */
     public int getGridQueueSize() { return gridQueueSize; }
+
+    // ==================== 风险控制 ====================
+
+    /** @return 保证金占初始本金比例上限(默认 0.2 即 20%),超限跳过开仓 */
     public BigDecimal getMarginRatioLimit() { return marginRatioLimit; }
+    /** @return 补仓最大重试次数(当前版本未使用) */
+    public int getReopenMaxRetries() { return reopenMaxRetries; }
+
+    // ==================== 盈亏计算 ====================
+
+    /** @return 合约乘数(单张合约代表的基础资产数量,如 ETH_USDT=0.01) */
     public BigDecimal getContractMultiplier() { return contractMultiplier; }
+    /** @return 未实现盈亏计价模式:LAST_PRICE(最新成交价)/ MARK_PRICE(标记价格) */
     public PnLPriceMode getUnrealizedPnlPriceMode() { return unrealizedPnlPriceMode; }
+
+    // ==================== 环境 ====================
+
+    /** @return 是否为生产环境(true=实盘生产网 / false=模拟盘测试网) */
+    public boolean isProduction() { return isProduction; }
 
     public static Builder builder() {
         return new Builder();
@@ -145,38 +183,75 @@
 
     /**
      * GateConfig 的流式构造器,提供合理的默认值。
+     *
+     * <h3>必填项</h3>
+     * {@code apiKey} 和 {@code apiSecret} 必须设置,其余参数均有默认值。
+     *
+     * <h3>默认值</h3>
+     * BTC_USDT / 10x / cross(全仓) / dual(双向) / gridRate=0.35% /
+     * overallTp=0.5 / maxLoss=7.5 / quantity=1 / isProduction=false
      */
     public static class Builder {
+        /** Gate API v4 密钥(必填) */
         private String apiKey;
+        /** Gate API v4 签名密钥(必填) */
         private String apiSecret;
+        /** 合约名称,默认 BTC_USDT */
         private String contract = "BTC_USDT";
+        /** 杠杆倍数,默认 "10" */
         private String leverage = "10";
+        /** 保证金模式,默认 "cross"(全仓) */
         private String marginMode = "cross";
+        /** 持仓模式,默认 "dual"(双向) */
         private String positionMode = "dual";
+        /** 网格间距比例,默认 0.0035(0.35%) */
         private BigDecimal gridRate = new BigDecimal("0.0035");
+        /** 整体止盈阈值(USDT),默认 0.5 */
         private BigDecimal overallTp = new BigDecimal("0.5");
+        /** 最大亏损阈值(USDT),默认 7.5 */
         private BigDecimal maxLoss = new BigDecimal("7.5");
+        /** 每次下单张数,默认 "1" */
         private String quantity = "1";
+        /** 是否为生产环境,默认 false(测试网) */
         private boolean isProduction = false;
+        /** 补仓最大重试次数,默认 3 */
         private int reopenMaxRetries = 3;
+        /** 网格队列容量,默认 50 */
         private int gridQueueSize = 50;
+        /** 保证金占初始本金比例上限,默认 0.2(20%) */
         private BigDecimal marginRatioLimit = new BigDecimal("0.2");
+        /** 合约乘数,默认 0.001 */
         private BigDecimal contractMultiplier = new BigDecimal("0.001");
+        /** 未实现盈亏计价模式,默认 LAST_PRICE(最新成交价) */
         private PnLPriceMode unrealizedPnlPriceMode = PnLPriceMode.LAST_PRICE;
 
+        /** 设置 API Key */
         public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; }
+        /** 设置 API Secret */
         public Builder apiSecret(String apiSecret) { this.apiSecret = apiSecret; return this; }
+        /** 设置合约名称 */
         public Builder contract(String contract) { this.contract = contract; return this; }
+        /** 设置杠杆倍数 */
         public Builder leverage(String leverage) { this.leverage = leverage; return this; }
+        /** 设置保证金模式(cross=全仓 / isolated=逐仓) */
         public Builder marginMode(String marginMode) { this.marginMode = marginMode; return this; }
+        /** 设置持仓模式(single=单向 / dual=双向) */
         public Builder positionMode(String positionMode) { this.positionMode = positionMode; return this; }
+        /** 设置网格间距比例 */
         public Builder gridRate(BigDecimal gridRate) { this.gridRate = gridRate; return this; }
+        /** 设置整体止盈阈值(USDT) */
         public Builder overallTp(BigDecimal overallTp) { this.overallTp = overallTp; return this; }
+        /** 设置最大亏损阈值(USDT) */
         public Builder maxLoss(BigDecimal maxLoss) { this.maxLoss = maxLoss; return this; }
+        /** 设置每次下单张数 */
         public Builder quantity(String quantity) { this.quantity = quantity; return this; }
+        /** 设置环境(true=实盘生产网 / false=模拟盘测试网) */
         public Builder isProduction(boolean isProduction) { this.isProduction = isProduction; return this; }
+        /** 设置补仓最大重试次数 */
         public Builder reopenMaxRetries(int reopenMaxRetries) { this.reopenMaxRetries = reopenMaxRetries; return this; }
+        /** 设置合约乘数(单张合约代表的基础资产数量) */
         public Builder contractMultiplier(BigDecimal contractMultiplier) { this.contractMultiplier = contractMultiplier; return this; }
+        /** 设置未实现盈亏计价模式 */
         public Builder unrealizedPnlPriceMode(PnLPriceMode mode) { this.unrealizedPnlPriceMode = mode; return this; }
 
         public GateConfig build() {
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 5710e88..ee9b68d 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -139,6 +139,20 @@
 
     // ---- 初始化 ----
 
+    /**
+     * 初始化策略环境。
+     *
+     * <h3>执行顺序</h3>
+     * <ol>
+     *   <li>获取用户 ID(用于私有频道订阅 payload)</li>
+     *   <li>获取账户信息 → 记录初始本金</li>
+     *   <li>如需要,切换为双向持仓模式</li>
+     *   <li>如需要,调整持仓模式(single/dual)</li>
+     *   <li>清除旧的止盈止损条件单</li>
+     *   <li>平掉所有已有仓位</li>
+     *   <li>设置杠杆倍数</li>
+     * </ol>
+     */
     public void init() {
         try {
             ApiClient detailClient = new ApiClient();
@@ -194,6 +208,19 @@
         }
     }
 
+    /**
+     * 平掉当前合约的所有已有仓位。
+     *
+     * <h3>平仓策略</h3>
+     * <ul>
+     *   <li>单向持仓:size=相反数,reduceOnly=true,市价 IOC 平仓</li>
+     *   <li>双向持仓:size=0,close=false,autoSize=LONG/SHORT,reduceOnly=true,市价 IOC 全平</li>
+     * </ul>
+     *
+     * <h3>注意事项</h3>
+     * 双向持仓模式下必须使用 autoSize 参数,不能直接传负数 size,
+     * 否则 Gate API 会拒绝(双向模式下空头 size 为负是正常的持仓方向)。
+     */
     private void closeExistingPositions() {
         try {
             List<Position> positions = futuresApi.listPositions(SETTLE).execute();
@@ -234,6 +261,10 @@
 
     // ---- 启动/停止 ----
 
+    /**
+     * 启动网格策略。重置所有状态变量和队列,进入 WAITING_KLINE 等待首根 K 线。
+     * 仅当当前状态为 WAITING_KLINE 或 STOPPED 时才允许启动。
+     */
     public void startGrid() {
         if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) {
             log.warn("[Gate] 策略已在运行中, state:{}", state);
@@ -256,6 +287,10 @@
         log.info("[Gate] 网格策略已启动");
     }
 
+    /**
+     * 停止网格策略。取消所有条件单 → 关闭交易线程池。
+     * 状态设为 STOPPED,K 线回调将直接返回不再处理。
+     */
     public void stopGrid() {
         state = StrategyState.STOPPED;
         executor.cancelAllPriceTriggeredOrders();
@@ -265,6 +300,24 @@
 
     // ---- K线回调 ----
 
+    /**
+     * K 线回调入口。由 {@link CandlestickChannelHandler} 在收到 WebSocket K 线推送时调用。
+     *
+     * <h3>处理流程</h3>
+     * <ol>
+     *   <li>更新 lastKlinePrice → 计算 unrealizedPnl(浮动盈亏)</li>
+     *   <li>STOPPED → 直接返回(仅保留盈亏更新)</li>
+     *   <li>WAITING_KLINE → 切换为 OPENING → 异步提交基底双开(开多+开空)</li>
+     *   <li>OPENING → 等待仓位推送回调生成队列,此处返回</li>
+     *   <li>ACTIVE → 执行 processShortGrid + processLongGrid</li>
+     * </ol>
+     *
+     * <h3>注意</h3>
+     * 基底双开下单提交到 GateTradeExecutor 的独立线程池中异步执行,
+     * 成交状态由 onPositionUpdate 回调驱动,不阻塞 WS 回调线程。
+     *
+     * @param closePrice K 线收盘价(即当前最新成交价)
+     */
     public void onKline(BigDecimal closePrice) {
         lastKlinePrice = closePrice;
         updateUnrealizedPnl();
@@ -293,6 +346,26 @@
 
     // ---- 仓位推送回调 ----
 
+    /**
+     * 仓位推送回调。由 {@link PositionsChannelHandler} 在收到 WebSocket 仓位更新时调用。
+     *
+     * <h3>处理逻辑</h3>
+     * <ul>
+     *   <li><b>有仓位 (size ≠ 0)</b>:
+     *     <ul>
+     *       <li>首次开仓(基底):标记 baseOpened=true,记录基底入场价,双基底都成交后生成网格队列</li>
+     *       <li>仓位净增加(size > 之前记录值):说明网格触发了新开仓 → 设止盈条件单</li>
+     *       <li>仓位减少或不变(止盈平仓后):仅更新 positionSize,不重复设止盈</li>
+     *     </ul>
+     *   </li>
+     *   <li><b>无仓位 (size = 0)</b>:清空活跃标记和持仓量</li>
+     * </ul>
+     *
+     * @param contract   合约名称
+     * @param mode       持仓模式(DUAL_LONG / DUAL_SHORT)
+     * @param size       持仓张数(多头为正、空头为负)
+     * @param entryPrice 当前持仓加权均价(交易所计算)
+     */
     public void onPositionUpdate(String contract, Position.ModeEnum mode, BigDecimal size,
                                   BigDecimal entryPrice) {
         if (state == StrategyState.STOPPED || state == StrategyState.WAITING_KLINE) {
@@ -352,6 +425,17 @@
 
     // ---- 平仓推送回调 ----
 
+    /**
+     * 平仓推送回调。由 {@link PositionClosesChannelHandler} 在收到平仓推送时调用。
+     *
+     * <h3>累加规则</h3>
+     * cumulativePnl += pnl。止盈平仓时 pnl > 0,止损平仓时 pnl < 0。
+     * 累加后检查停止条件:≥ overallTp 或 ≤ -maxLoss。
+     *
+     * @param contract 合约名称
+     * @param side     平仓方向("long" / "short")
+     * @param pnl      本次平仓的盈亏金额
+     */
     public void onPositionClose(String contract, String side, BigDecimal pnl) {
         if (state == StrategyState.STOPPED) {
             return;
@@ -370,6 +454,10 @@
 
     // ---- 网格队列处理 ----
 
+    /**
+     * 尝试生成网格队列。双基底(多+空)都成交后才触发:
+     * 生成空仓队列 + 多仓队列 → 状态切换为 ACTIVE。
+     */
     private void tryGenerateQueues() {
         if (baseLongOpened && baseShortOpened) {
             generateShortQueue();
@@ -381,6 +469,12 @@
         }
     }
 
+    /**
+     * 生成空仓价格队列。
+     * 以空头基底入场价 shortBaseEntryPrice 为基准,按 gridRate 递减生成 gridQueueSize 个价格元素:
+     * <pre>shortBaseEntryPrice × (1 − gridRate × i), i=1..gridQueueSize</pre>
+     * 队列降序排列(大→小),方便 processShortGrid 中从头遍历。
+     */
     private void generateShortQueue() {
         shortPriceQueue.clear();
         BigDecimal step = config.getGridRate();
@@ -392,6 +486,12 @@
         log.info("[Gate] 空队列:{}", shortPriceQueue);
     }
 
+    /**
+     * 生成多仓价格队列。
+     * 以多头基底入场价 longBaseEntryPrice 为基准,按 gridRate 递增生成 gridQueueSize 个价格元素:
+     * <pre>longBaseEntryPrice × (1 + gridRate × i), i=1..gridQueueSize</pre>
+     * 队列升序排列(小→大),方便 processLongGrid 中从头遍历。
+     */
     private void generateLongQueue() {
         longPriceQueue.clear();
         BigDecimal step = config.getGridRate();
@@ -472,6 +572,11 @@
             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
+                        && currentPrice.subtract(longEntryPrice).abs().compareTo(longEntryPrice.multiply(step)) < 0) {
+                    log.info("[Gate] 多队列跳过(price≈longEntry):{}", elem);
+                    continue;
+                }
                 longPriceQueue.add(elem);
                 log.info("[Gate] 多队列增加:{}", elem);
             }
@@ -554,6 +659,11 @@
             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
+                        && currentPrice.subtract(shortEntryPrice).abs().compareTo(shortEntryPrice.multiply(step)) < 0) {
+                    log.info("[Gate] 空队列跳过(price≈shortEntry):{}", elem);
+                    continue;
+                }
                 shortPriceQueue.add(elem);
                 log.info("[Gate] 空队列增加:{}", elem);
             }
@@ -567,6 +677,16 @@
 
     // ---- 保证金安全阀 ----
 
+    /**
+     * 保证金安全阀检查。
+     *
+     * <p>实时查询当前保证金占用额(positionInitialMargin),计算其占初始本金的比例。
+     * 比例 ≥ marginRatioLimit(默认 20%)时拒绝开仓,但仍照常更新队列。
+     *
+     * <p>查询失败时默认放行(返回 true),避免因 REST API 异常导致策略完全停滞。
+     *
+     * @return true=安全可开仓 / false=保证金超限跳过开仓
+     */
     private boolean isMarginSafe() {
         try {
             FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
@@ -582,6 +702,10 @@
 
     // ---- 工具 ----
 
+    /**
+     * 取反字符串数字。如 "1" → "-1","-2" → "2"。
+     * 用于开空单时将正数张数转为负数。
+     */
     private String negate(String qty) {
         return qty.startsWith("-") ? qty.substring(1) : "-" + qty;
     }
@@ -617,6 +741,9 @@
 
     /**
      * 根据配置的 PnLPriceMode 返回计价价格。
+     * MARK_PRICE 模式优先使用标记价格(外部注入),未注入时回退到最新成交价。
+     *
+     * @return 计价价格,可能为 null
      */
     private BigDecimal resolvePnlPrice() {
         if (config.getUnrealizedPnlPriceMode() == GateConfig.PnLPriceMode.MARK_PRICE
@@ -626,11 +753,18 @@
         return lastKlinePrice;
     }
 
+    /** @return 最新 K 线价格(每次 onKline 更新) */
     public BigDecimal getLastKlinePrice() { return lastKlinePrice; }
+    /** 设置标记价格(外部注入,MARK_PRICE 模式时用于盈亏计算) */
     public void setMarkPrice(BigDecimal markPrice) { this.markPrice = markPrice; }
+    /** @return 策略是否处于活跃状态(非 STOPPED 且非 WAITING_KLINE) */
     public boolean isStrategyActive() { return state != StrategyState.STOPPED && state != StrategyState.WAITING_KLINE; }
+    /** @return 累计已实现盈亏(平仓推送驱动累加) */
     public BigDecimal getCumulativePnl() { return cumulativePnl; }
+    /** @return 当前未实现盈亏(每根 K 线实时计算) */
     public BigDecimal getUnrealizedPnl() { return unrealizedPnl; }
+    /** @return Gate 用户 ID(用于私有频道订阅 payload) */
     public Long getUserId() { return userId; }
+    /** @return 当前策略状态 */
     public StrategyState getState() { return state; }
 }
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
index 5a5f7b0..d4cec97 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -91,13 +91,16 @@
 
     /**
      * 注册频道处理器。需在 init() 前调用。
+     *
+     * @param handler 实现了 {@link GateChannelHandler} 接口的频道处理器
      */
     public void addChannelHandler(GateChannelHandler handler) {
         channelHandlers.add(handler);
     }
 
     /**
-     * 初始化:建立 WebSocket 连接 → 启动心跳。
+     * 初始化:建立 WebSocket 连接 → 启动心跳检测。
+     * 使用 {@code AtomicBoolean} 防重入,同一实例只允许初始化一次。
      */
     public void init() {
         if (!isInitialized.compareAndSet(false, true)) {
@@ -109,9 +112,11 @@
     }
 
     /**
-     * 销毁:取消订阅 → 关闭连接 → 关闭线程池。
-     * <p>注意:先 closeBlocking 再 shutdown sharedExecutor,
-     * 避免 onClose 回调中的 reconnectWithBackoff 访问已关闭的线程池。
+     * 销毁:取消所有频道订阅 → 关闭 WebSocket 连接 → 关闭线程池。
+     *
+     * <h3>执行顺序</h3>
+     * 先取消订阅(等待 500ms 确保发送完成),再 closeBlocking 关闭连接,
+     * 最后 shutdown 线程池。先关连接再关线程池,避免 onClose 回调中的重连任务访问已关闭的线程池。
      */
     public void destroy() {
         log.info("[WS] 开始销毁...");
@@ -152,7 +157,20 @@
 
     /**
      * 建立 WebSocket 连接。使用 SSLContext 配置 TLS 协议。
-     * 连接成功后依次订阅所有已注册的频道处理器。
+     *
+     * <h3>连接成功回调</h3>
+     * <ol>
+     *   <li>设置 isConnected=true,isConnecting=false</li>
+     *   <li>重置心跳计时器</li>
+     *   <li>依次订阅所有已注册的频道处理器</li>
+     *   <li>发送首次 ping</li>
+     * </ol>
+     *
+     * <h3>连接关闭回调</h3>
+     * 设置断连状态 → 取消心跳超时 → 异步触发指数退避重连(最多3次)。
+     *
+     * <h3>线程安全</h3>
+     * 使用 {@code AtomicBoolean.isConnecting} 防止并发重连。
      */
     private void connect() {
         if (isConnecting.get() || !isConnecting.compareAndSet(false, true)) {
@@ -262,12 +280,19 @@
 
     // ---- heartbeat ----
 
+    /**
+     * 启动心跳检测器。
+     * 使用单线程 ScheduledExecutor,每 25 秒检查一次心跳超时。
+     */
     private void startHeartbeat() {
         if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) heartbeatExecutor.shutdownNow();
         heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "gate-ws-heartbeat"); t.setDaemon(true); return t; });
         heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, 25, 25, TimeUnit.SECONDS);
     }
 
+    /**
+     * 重置心跳计时器:取消旧超时任务,提交新的 10 秒超时检测。
+     */
     private synchronized void resetHeartbeatTimer() {
         cancelPongTimeout();
         if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
@@ -275,11 +300,17 @@
         }
     }
 
+    /**
+     * 检查心跳超时:如果距离上次收到消息超过 10 秒,主动发送 futures.ping。
+     */
     private void checkHeartbeatTimeout() {
         if (!isConnected.get()) return;
         if (System.currentTimeMillis() - lastMessageTime.get() >= HEARTBEAT_TIMEOUT * 1000L) sendPing();
     }
 
+    /**
+     * 发送应用层 futures.ping 消息。
+     */
     private void sendPing() {
         try {
             if (webSocketClient != null && webSocketClient.isOpen()) {
@@ -292,12 +323,20 @@
         } catch (Exception e) { log.warn("[WS] 发送 ping 失败", e); }
     }
 
+    /**
+     * 取消心跳超时检测任务。
+     */
     private synchronized void cancelPongTimeout() {
         if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) pongTimeoutFuture.cancel(true);
     }
 
     // ---- reconnect ----
 
+    /**
+     * 指数退避重连。初始延迟 5 秒,每次翻倍,最多重试 3 次。
+     *
+     * @throws InterruptedException 线程被中断
+     */
     private void reconnectWithBackoff() throws InterruptedException {
         int attempt = 0, maxAttempts = 3;
         long delayMs = 5000;
@@ -307,6 +346,11 @@
         log.error("[WS] 超过最大重试次数({}),放弃重连", maxAttempts);
     }
 
+    /**
+     * 优雅关闭线程池:先 shutdown,等待 5 秒,超时则 shutdownNow 强制中断。
+     *
+     * @param executor 需要关闭的线程池
+     */
     private void shutdownExecutorGracefully(ExecutorService executor) {
         if (executor == null || executor.isTerminated()) return;
         try { executor.shutdown(); if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); }
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java
index eac6c1e..6de0e63 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java
@@ -73,7 +73,8 @@
     }
 
     /**
-     * 优雅关闭:等待 10 秒,超时则强制中断。
+     * 优雅关闭:等待 10 秒让队列中的任务执行完毕,超时则强制中断。
+     * 关闭后的 REST 调用将通过 CallerRunsPolicy 直接在提交线程执行。
      */
     public void shutdown() {
         executor.shutdown();
@@ -86,19 +87,36 @@
     }
 
     /**
-     * 异步市价开多。quantity 为正数(如 "10")。
+     * 异步 IOC 市价开多。quantity 为正数(如 "1")。
+     *
+     * @param quantity  开仓张数(正数)
+     * @param onSuccess 成交成功回调(可为 null)
+     * @param onFailure 成交失败回调(可为 null)
      */
     public void openLong(String quantity, Runnable onSuccess, Runnable onFailure) {
         openPosition(quantity, "t-grid-long", "开多", onSuccess, onFailure);
     }
 
     /**
-     * 异步市价开空。quantity 为负数(如 "-10")。
+     * 异步 IOC 市价开空。quantity 为负数(如 "-1")。
+     *
+     * @param quantity  开仓张数(负数)
+     * @param onSuccess 成交成功回调(可为 null)
+     * @param onFailure 成交失败回调(可为 null)
      */
     public void openShort(String quantity, Runnable onSuccess, Runnable onFailure) {
         openPosition(quantity, "t-grid-short", "开空", onSuccess, onFailure);
     }
 
+    /**
+     * 通用异步 IOC 市价下单。
+     *
+     * @param size      下单张数(正=开多 / 负=开空)
+     * @param text      订单标记文本(如 "t-grid-long"),用于区分订单来源
+     * @param label     日志标签(如 "开多"/"开空")
+     * @param onSuccess 成功回调
+     * @param onFailure 失败回调
+     */
     private void openPosition(String size, String text, String label, Runnable onSuccess, Runnable onFailure) {
         executor.execute(() -> {
             try {
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 93ffff4..d86e81d 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
@@ -48,6 +48,7 @@
         log.info("[管理器] 开始初始化...");
 
         try {
+            //测试盘
             config = GateConfig.builder()
                     .apiKey("d90ca272391992b8e74f8f92cedb21ec")
                     .apiSecret("1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274")
@@ -64,10 +65,29 @@
                     .isProduction(false)
                     .reopenMaxRetries(3)
                     .build();
+            //实盘
+            config = GateConfig.builder()
+                    .apiKey("a04c223e801cb707b30939cebf25222d")
+                    .apiSecret("ee0ed22be6de47460631c9d3c00715d1db8ab5cf8b179af4d8d5bb0a5d735d00")
+                    .contract("ETH_USDT")
+                    .leverage("100")
+                    .marginMode("CROSS")
+                    .positionMode("dual")
+                    .gridRate(new BigDecimal("0.0035"))
+                    .overallTp(new BigDecimal("1"))
+                    .maxLoss(new BigDecimal("15"))
+                    .quantity("1")
+                    .contractMultiplier(new BigDecimal("0.01"))
+                    .unrealizedPnlPriceMode(GateConfig.PnLPriceMode.LAST_PRICE)
+                    .isProduction(true)
+                    .reopenMaxRetries(3)
+                    .build();
 
+            // 1. 初始化交易服务:查用户ID → 切持仓模式 → 清条件单 → 平已有仓位 → 设杠杆
             gridTradeService = new GateGridTradeService(config);
             gridTradeService.init();
 
+            // 2. 创建 WS 客户端并注册 3 个频道处理器
             wsClient = new GateKlineWebSocketClient(config.getWsUrl());
             wsClient.addChannelHandler(new CandlestickChannelHandler(config.getContract(), gridTradeService));
             wsClient.addChannelHandler(new PositionsChannelHandler(
@@ -77,12 +97,16 @@
             wsClient.init();
             log.info("[管理器] WS已连接, 已注册 3 个频道处理器");
 
+            // 3. 激活策略,等待首根 K 线触发基底双开
             gridTradeService.startGrid();
         } catch (Exception e) {
             log.error("[管理器] 初始化失败", e);
         }
     }
 
+    /**
+     * 销毁:停止策略 → 关闭交易线程池 → 取消 WS 订阅 → 断开连接 → 关闭 WS 线程池。
+     */
     @PreDestroy
     public void destroy() {
         log.info("[管理器] 开始销毁...");
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md b/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
index e3207b4..8a1dfb1 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
@@ -194,7 +194,7 @@
 │   └─ 多仓队列转移:
 │       ├─ 以多仓队列首元素(最小价)为种子
 │       ├─ 生成 matched.size() 个递减元素: seed × (1 − gridRate × i)
-│       ├─ 贴近过滤: |elem − longEntryPrice| < longEntryPrice × gridRate → 跳过
+│       ├─ 贴近过滤: |currentPrice − longEntryPrice| < longEntryPrice × gridRate → 跳过
 │       └─ 升序排列,截断到 gridQueueSize
 │
 └─ processLongGrid: 当前价 > 多仓队列元素(价格涨超了队列中的低价)
@@ -207,7 +207,7 @@
     └─ 空仓队列转移:
         ├─ 以空仓队列首元素(最高价)为种子
         ├─ 生成 matched.size() 个递增元素: seed × (1 + gridRate × i)
-        ├─ 贴近过滤: |elem − shortEntryPrice| < shortEntryPrice × gridRate → 跳过
+        ├─ 贴近过滤: |currentPrice − shortEntryPrice| < shortEntryPrice × gridRate → 跳过
         └─ 降序排列,截断到 gridQueueSize
 ```
 
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/AbstractPrivateChannelHandler.java b/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/AbstractPrivateChannelHandler.java
index f3173d2..8fb1d08 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/AbstractPrivateChannelHandler.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/AbstractPrivateChannelHandler.java
@@ -52,12 +52,24 @@
         this.gridTradeService = gridTradeService;
     }
 
+    /** @return 频道名称(如 "futures.positions") */
     @Override
     public String getChannelName() { return channelName; }
 
     /**
      * 发送带签名的订阅请求。
-     * payload: [userId, contract],auth: {method:"api_key", KEY, SIGN}
+     *
+     * <h3>请求格式</h3>
+     * <pre>
+     * {
+     *   "id":     &lt;唯一请求ID&gt;,
+     *   "time":   &lt;unix时间戳(秒)&gt;,
+     *   "channel":"futures.positions",
+     *   "event":  "subscribe",
+     *   "payload":[userId, contract],
+     *   "auth":   {"method":"api_key", "KEY":&lt;APIKEY&gt;, "SIGN":&lt;HMAC-SHA512签名&gt;}
+     * }
+     * </pre>
      */
     @Override
     public void subscribe(WebSocketClient ws) {
@@ -68,7 +80,8 @@
     }
 
     /**
-     * 发送带签名的取消订阅请求,与 subscribe 对称。
+     * 发送带签名的取消订阅请求,与 subscribe 结构一致。
+     * payload: [contract],无 userId(取消订阅不需要用户ID)。
      */
     @Override
     public void unsubscribe(WebSocketClient ws) {
@@ -90,11 +103,15 @@
         log.info("[{}] 取消订阅成功, 合约:{}", channelName, contract);
     }
 
+    /** @return 网格交易服务实例 */
     protected GateGridTradeService getGridTradeService() { return gridTradeService; }
+    /** @return 当前订阅的合约名称 */
     protected String getContract() { return contract; }
 
     /**
      * 从策略服务获取用户 ID,用于私有频道订阅的 payload[0]。
+     *
+     * @return 用户 ID 字符串,获取失败返回空字符串
      */
     private String buildUid() {
         return gridTradeService != null && gridTradeService.getUserId() != null
@@ -102,7 +119,13 @@
     }
 
     /**
-     * 构建认证请求 JSON。包含 id、time、channel、event、payload[auth_user_id, contract]、auth 字段。
+     * 构建认证请求 JSON。
+     * 包含 id、time、channel、event、payload[userId, contract]、auth 字段。
+     *
+     * @param event   事件类型("subscribe" / "unsubscribe")
+     * @param uid     认证用户 ID
+     * @param timeSec unix 时间戳(秒)
+     * @return 完整的认证请求 JSONObject
      */
     private JSONObject buildAuthRequest(String event, String uid, long timeSec) {
         JSONObject msg = new JSONObject();
@@ -123,7 +146,21 @@
     }
 
     /**
-     * HMAC-SHA512 签名,使用 UTF-8 编码。
+     * HMAC-SHA512 签名计算。
+     *
+     * <h3>签名算法</h3>
+     * <pre>
+     *   message = "channel={channelName}&event={event}&time={timeSec}"
+     *   SIGN = Hex(HmacSHA512(apiSecret(UTF-8), message(UTF-8)))
+     * </pre>
+     *
+     * <h3>错误处理</h3>
+     * 签名计算失败时返回空字符串(日志记录错误),不抛异常,
+     * 避免阻塞 WebSocket 回调线程。
+     *
+     * @param event   事件类型
+     * @param timeSec unix 时间戳(秒)
+     * @return 十六进制签名字符串,失败返回 ""
      */
     private String hs512Sign(String event, long timeSec) {
         try {
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java b/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java
index 9384359..bac9ef9 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java
@@ -43,9 +43,23 @@
         this.gridTradeService = gridTradeService;
     }
 
+    /** @return 频道名称 "futures.candlesticks" */
     @Override
     public String getChannelName() { return CHANNEL_NAME; }
 
+    /**
+     * 发送 K 线频道订阅请求(公开频道,无需签名)。
+     *
+     * <h3>订阅格式</h3>
+     * <pre>
+     * {
+     *   "time":    &lt;unix时间戳(秒)&gt;,
+     *   "channel": "futures.candlesticks",
+     *   "event":   "subscribe",
+     *   "payload": ["1m", "{contract}"]
+     * }
+     * </pre>
+     */
     @Override
     public void subscribe(WebSocketClient ws) {
         JSONObject msg = new JSONObject();
@@ -60,6 +74,9 @@
         log.info("[{}] 订阅成功, 合约:{}, 周期:{}", CHANNEL_NAME, contract, INTERVAL);
     }
 
+    /**
+     * 发送 K 线频道取消订阅请求。
+     */
     @Override
     public void unsubscribe(WebSocketClient ws) {
         JSONObject msg = new JSONObject();
@@ -74,6 +91,25 @@
         log.info("[{}] 取消订阅成功", CHANNEL_NAME);
     }
 
+    /**
+     * 处理 K 线推送消息。
+     *
+     * <h3>数据提取</h3>
+     * result[0] 中提取:
+     * <ul>
+     *   <li>c(close):收盘价 → 传给 gridTradeService.onKline()</li>
+     *   <li>n(name):烛线名称(如 "1m_ETH_USDT")</li>
+     *   <li>t(time):烛线起始时间戳</li>
+     *   <li>w(window_close):烛线是否完结(仅日志输出,不做门控)</li>
+     * </ul>
+     *
+     * <h3>注意</h3>
+     * 不判断 w(已完结)——策略需要 tick 级实时响应价格变动,
+     * 而非等 1 分钟烛线完结后才行动。
+     *
+     * @param response WebSocket 推送的完整 JSON
+     * @return true 表示已处理(匹配成功)
+     */
     @Override
     public boolean handleMessage(JSONObject response) {
         if (!CHANNEL_NAME.equals(response.getString("channel"))) {
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionClosesChannelHandler.java b/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionClosesChannelHandler.java
index 32615b2..3ca98ff 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionClosesChannelHandler.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionClosesChannelHandler.java
@@ -35,6 +35,24 @@
         super(CHANNEL_NAME, apiKey, apiSecret, contract, gridTradeService);
     }
 
+    /**
+     * 处理平仓推送消息。
+     *
+     * <h3>数据提取</h3>
+     * result 数组中每个元素包含:
+     * <ul>
+     *   <li>contract:合约名称</li>
+     *   <li>side:平仓方向("long" / "short")</li>
+     *   <li>pnl:本次平仓的盈亏金额(字符串格式,如 "+0.2" / "-0.1")</li>
+     * </ul>
+     *
+     * <h3>数据处理</h3>
+     * 按合约名称过滤 → 提取 pnl 和 side → 调用 gridTradeService.onPositionClose() 累加盈亏。
+     * pnl 来自服务端,不受本地计算误差影响。
+     *
+     * @param response WebSocket 推送的完整 JSON
+     * @return true 表示已处理(匹配成功)
+     */
     @Override
     public boolean handleMessage(JSONObject response) {
         if (!CHANNEL_NAME.equals(response.getString("channel"))) {

--
Gitblit v1.9.1