4 files modified
2 files added
971 ■■■■■ changed files
docs/策略运转逻辑.md 189 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateClosingApiClient.java 39 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java 588 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java 110 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/GridElement.java 13 ●●●●● patch | view | raw | blame | history
src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java 32 ●●●●● patch | view | raw | blame | history
docs/策略运转逻辑.md
New file
@@ -0,0 +1,189 @@
# Gate 网格策略运转逻辑总览
> 基于 gate-zhisun-v2-test 分支当前代码整理(2026-11-05)。
> 策略 = 双向网格(多仓网格 + 空仓网格),止损触发后追单重建仓位,止盈网格收割利润,仓位归零/盈利达标自动重启轮次。
---
## 1. 架构与线程模型
### 1.1 组成
- **Station(站内面板)**:Web 看板 + RabbitMQ 指令(START/STOP/改参数/平仓/重置);
- **Gate JAR(策略引擎)**:app.gate.enabled=true 时启用,核心类 GateGridTradeService;
- **通信**:站↔JAR 走 RabbitMQ(direct exchange biue-exchange-gate);JAR↔交易所走 REST + WebSocket v4。
### 1.2 WS 四频道(GateKlineWebSocketClient + 4 个 handler)
| 频道 | 类型 | 驱动什么 |
|---|---|---|
| futures.candlesticks(1m) | 公开 | 唯一时间/价格驱动源 → onKline |
| futures.positions | 私有 | 持仓推送 → onPositionUpdate |
| futures.position_closes | 私有 | 平仓推送 → onPositionClose(盈亏累计/风控) |
| futures.autoorders | 私有 | 条件单状态 → onAutoOrder(止损/止盈/开仓成交分发) |
### 1.3 线程模型
| 线程 | 职责 |
|---|---|
| WS ReadThread | 解析推送,直接调用服务方法(止损/止盈/成交/持仓处理) |
| te-trade-worker(单线程池) | 所有 REST 下单/撤单/查询任务 FIFO 串行(回调也在该线程) |
| gate-ws-worker | 重连循环 |
| te-ws-heartbeat | 25s 周期心跳检查(静默探测/主动换线) |
| 节流对账任务 | 提交到交易线程池,15s 一次 |
并发安全:持仓字段 volatile;GridElement 订单 ID 列表 CopyOnWriteArrayList;size 映射 ConcurrentHashMap;tryGenerateQueues synchronized;轮次重置整体提交到 executor 队列末尾保证顺序。
---
## 2. 生命周期状态机
```
STOPPED →(startGrid)→ WAITING_KLINE →(首根K线)→ OPENING →(双基底成交+挂完止损止盈)→ ACTIVE
ACTIVE →(仓位归零/盈利达标/轮数上限/手动)→ STOPPED →(自动/手动)→ WAITING_KLINE …
```
- **WAITING_KLINE**:等首根 K 线(顺带等四频道订阅完成)。
- **OPENING**:市价 IOC 开多空基底各 baseQuantity 张;双基底成交后生成网格队列、首挂止损止盈 → ACTIVE。
- **ACTIVE**:主循环(止损/止盈/价格驱动/风控/对账)。
- **STOPPED**:全撤单+平仓后短暂停留(3 秒),自动 startGrid() 进入下一轮。
---
## 3. 启动与基底(onKline 首根K线)
1. startGrid():清状态/计数器(**累计盈亏不清零,全局口径**)、加载配置;
2. 首根 K 线到达 → 开基底:多仓 openLong(base)、空仓 openShort(-base)(市价 IOC);
3. 双基底成交(WS 推送,丢失时由对账 REST 补齐)→ tryGenerateQueues();
4. 生成双向网格队列 + 首挂止损:空仓止损挂入场格上方第 2 格、多仓挂下方第 2 格,各覆盖 base 张(1 张/单)。
---
## 4. 网格构建
- 以基底成交价为基准(grid 0),按 gridStep 向上下各生成 N 个网格(totalLongPriceQueue 升序=多仓侧、totalShortPriceQueue 降序=空仓侧);
- 每个 GridElement:价格、上下指针、多/空挂单 ID 列表与张数映射、止盈/止损订单 ID 与张数映射、TraderParam(张数/orderId/placed 标记)。
---
## 5. 止损体系(核心循环)
### 5.1 首挂与延展
- 止损单 order_type=plan-close-long/short-position,覆盖张数 = max(filledQty, baseQty)(**全仓覆盖**);
- 开仓成交后 extendLong/ShortStopLoss(posSize, entryGrid) 在入场格 ±2 起逐格重挂,余数补在最外侧。
### 5.2 止损触发 → 追单(handleXxxStopLossTriggered)
1. 该网格止损单 finished(trade_id 有效)→ 记录止损次数 +1;
2. calculateEntryQuantity(方向, respectCurrentPosition=true, 本网格止损张数) 计算追单张数:
   - REST 查当前持仓并减去本网格止损张数(修正 REST 时序竞态);
   - 张数 = 基础 + 加仓量,上限 maxPositionPerSide;
3. 在入场格 ±1 挂条件开仓单,成交后走 ENTRY_FILLED → 延展止损。
### 5.3 加仓公式(computeAddQty)
```
effectiveCount = max(0, 累计止损次数 - addPositionStartThreshold)
divisor        = addPositionInterval + 1
addMultiplier  = floor(effectiveCount / divisor)
addQty         = addMultiplier × addPositionQuantity
停止阈值:加仓执行次数 ≥ addPositionStopThreshold → addQty=0(回到基础张数)
```
- **加仓执行次数 = 含加仓量的开仓单「真正成交」后 +1**(挂单后被取消的不算);
- 计数口径按 stopLossCountMode:single=单方向、dual=双向合计;
- 价格驱动的仓位归零重入同样套用公式(挂单时打标记、成交才计数),对向加仓/补仓不计数。
### 5.4 同网格防抖
同一网格连续触发只处理第一次(lastLong/ShortStopLossGridId),其余忽略。
---
## 6. 止盈体系(handleXxxTakeProfitTriggered)
| 类型 | 触发条件 | 行为 |
|---|---|---|
| 基础止盈 | 仓位 > 基础张数时,在入场格上方逐格挂 baseTakeProfitPerGrid 张(≤gridCount 格) | 成交即落袋 |
| 超额止盈 | placeExcessTakeProfit=concentrated:全部超额挂在一个网格;dispersed:逐格分散 | 同上 |
| 对向加仓止盈 | tpTriggerOppositeAdd 开:止盈成交后在相邻格反向挂一张 | 增加网格密度 |
| 仓位止盈补仓 | tpPositionReplenishEnabled 开:止盈成交后补回原方向仓位 | 见下 |
**仓位止盈补仓(专用分支)**:止盈平掉 N 张后,在相邻网格挂同方向 N 张开仓单;成交后(handleReplenishXxxAddFilled)**只取消该方向的全部止损并按原止损位置、以最新总持仓重挂**(不动止盈、不扩展新位置)。
---
## 7. 价格驱动(仓位归零重入,processLongGrid/processShortGrid)
条件:state==ACTIVE && isPriceDriveEnabled && 本地该方向 active==false && 持仓==0,每根 K 线评估。
1. 在价格队列中找当前价上(多)/下(空)方最近的网格;
2. 该网格及以上(多)各网格已有挂单 → 跳过;否则向上遍历**取消所有遗留挂单**;
3. **挂单前 REST 核实该方向真实持仓为 0**(防成交推送滞后导致重复建仓,历史出现过 68→136 张翻倍)——非 0 则刷新本地字段并跳过;
4. 挂条件开仓单(张数同样走加仓公式,打标记,成交才计加仓执行次数)。
---
## 8. 轮次重置(三个入口)
| 入口 | 触发条件 | 流程 |
|---|---|---|
| 仓位归零 | ACTIVE 下双方向持仓都变 0(持仓推送驱动) | 取消全部条件单 → 平仓 → STOPPED → 3s 后 startGrid |
| 盈利达标 | 账户净值-预估平仓费 ≥ 初始本金+预期盈利(每根 K 线检查) | 同上 + currentRound+1;达 rounds 上限则永久停止 |
| 手动指令 | 站内 STOP/重置 | stopGrid / restartWithConfig |
重置任务整体提交到 executor 队列**末尾**(FIFO),保证上一轮排队的挂单先挂出、随后的 cancel 才能取消到。
---
## 9. 风控
- **最大亏损**:onPositionClose 累加已实现盈亏 + 账户浮动盈亏,合计 ≤ -maxLoss 时钉钉告警(maxLossAlerted 闩锁:只在首次下穿阈值时提醒,回上后复位,防轰炸);
- **累计盈亏(全局口径,不按轮次)**:推送逐笔累加;对账任务用 REST 校准(当前数据源为持仓 realised_pnl,**已发现口径不对,待改为 history_pnl 或 position_close 历史**);
- **主动换线**:连接存活 55 分钟主动重连,绕开链路约 1 小时强制断连。
---
## 10. WS 连接管理(GateKlineWebSocketClient)
- 心跳三层:10s 静默发应用层 futures.ping;20s 无任何回应(含 pong)判死重连;协议层 ping 由库自动回,30s lost-timeout 兜底;
- 重连:指数退避 5s→10s→20s→40s→60s(封顶)无限重试,成功后重订阅四频道;
- 重订阅完成后回调 → 立即触发一次持仓对账;
- 订阅确认 event=subscribe + result.status=success 才置 subscribed=true(areAllSubscribed 全真才放行策略)。
---
## 11. 对账体系(15s 节流 + 事件触发)
| 对账项 | 触发 | 行为 |
|---|---|---|
| 持仓 active/size/均价 | 15s 节流 + 重连订阅完成 | REST 权威值同步本地六字段,不一致打 WARN |
| OPENING 基底 | 同上(OPENING 态) | 双基底 REST 已成交 → 补 baseOpened/entryPrice + 触发队列生成 |
| 条件单幽灵清理 | 同上(ACTIVE 态) | 本地索引中不在交易所 open 列表的单 → 移除 + 修正标志 |
| 累计盈亏 | 同上 | REST 校准(数据源待修,见 §9) |
| 止损覆盖兜底 | 同上 | 有持仓但止损覆盖 < 持仓 → 按原位置重挂全持仓止损 |
| 挂单前核实 | 价格驱动挂单瞬间 | REST 确认该方向持仓为 0 才挂(防翻倍) |
---
## 12. K 线处理(CandlestickChannelHandler)
- 订阅快照/更新可能带多根烛线:取 t 最大的一根,同 t 优先 w=false(实时烛线);
- 跨消息 t 单调过滤:t < 已处理最新 t 的历史烛线直接丢弃(防重连后快照逐条重放引发风暴);
- 每根有效烛线 → onKline(close):WAITING_KLINE 开基底;ACTIVE 跑价格驱动 + 盈亏检查 + 节流对账。
---
## 13. 数据上报(station 看板)
- 心跳 HEARTBEAT(状态/轮次/盈亏/持仓等);
- STRATEGY_START/STOP、ROUND_COMPLETE、PNL_SNAPSHOT(60s:累计/浮动/总权益)、ENTRY_FILLED、STOP_LOSS_TRIGGERED、CMD_ACK;
- 配置下发:/config、/alias、/strategy-status;指令:启动/停止/取消挂单/平仓/重建。
---
## 14. 关键配置项速查
baseQuantity/quantity(基础/单笔张数)、gridStep(网格步长)、maxPositionPerSide(单边上限)、addPositionStartThreshold/Interval/Quantity/StopThreshold(加仓四件套)、stopLossCountMode(single/dual)、placeExcessTakeProfit(concentrated/dispersed)、baseTakeProfitPerGrid/GridCount、tpTriggerOppositeAdd、tpPositionReplenishEnabled、priceDriveEnabled、maxLoss、expectedProfit、rounds。
---
## 15. 已知遗留问题(待修清单)
1. 累计盈亏对账数据源口径错误(realised_pnl → 应为 history_pnl/position_close 历史);
2. WS error 事件解析读嵌套字段(官方是顶层 code/message)+ 订阅失败无重试;
3. ~~挂单前核实跑在网格队列锁内 + 未同步 entryPrice~~(已修复:核实移出锁、一次 REST 同步 size/active/entryPrice);
4. 基底开仓 REST 失败无回调重试(仅推送丢失可被对账救回);
5. ~~OkHttp response body 未关闭(连接泄漏 WARN)~~(已修复:GateClosingApiClient 子类 try-with-resources 强制关闭响应,替换两处 new ApiClient())。
src/main/java/com/xcong/excoin/modules/gateApi/GateClosingApiClient.java
New file
@@ -0,0 +1,39 @@
package com.xcong.excoin.modules.gateApi;
import io.gate.gateapi.ApiClient;
import io.gate.gateapi.ApiException;
import io.gate.gateapi.ApiResponse;
import okhttp3.Call;
import okhttp3.Response;
import java.io.IOException;
import java.lang.reflect.Type;
/**
 * 修复 gate-api SDK 同步请求 Response 未关闭导致 OkHttp 连接泄漏的 ApiClient 子类。
 *
 * <p>SDK 的 {@code ApiClient.execute(Call, Type)} 读取响应体后不调用 {@code response.close()},
 * 触发 OkHttp 连接池 "A connection to ... was leaked. Did you forget to close a response body?" 告警
 * (日志中已多次出现)。本类用 try-with-resources 保证响应在任意路径
 * (成功 / 4xx / 反序列化失败 / IO 异常)都被关闭,行为与 SDK 内置执行完全一致
 * ({@code handleResponse} 为 SDK 公开方法)。</p>
 */
public class GateClosingApiClient extends ApiClient {
    /**
     * 重写 SDK 执行逻辑:响应读取完成后强制 close。
     * <ul>
     *   <li>成功路径:反序列化后关闭;</li>
     *   <li>异常路径(handleResponse 抛 ApiException / IOException):try-with-resources 兜底关闭。</li>
     * </ul>
     */
    @Override
    public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
        try (Response response = call.execute()) {
            T data = handleResponse(response, returnType);
            return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
        } catch (IOException e) {
            throw new ApiException(e);
        }
    }
}
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -181,6 +181,8 @@
    private volatile BigDecimal lastKlinePrice;
    private volatile BigDecimal markPrice = BigDecimal.ZERO;
    private volatile BigDecimal cumulativePnl = BigDecimal.ZERO;
    /** 最大亏损钉钉提醒闩锁:全局累计口径下会持续低于阈值,只在上穿/下穿阈值时各提醒一次,避免每次平仓轰炸 */
    private volatile boolean maxLossAlerted = false;
    private volatile BigDecimal unrealizedPnl = BigDecimal.ZERO;
    private volatile BigDecimal longEntryPrice = BigDecimal.ZERO;
    private volatile BigDecimal shortEntryPrice = BigDecimal.ZERO;
@@ -190,12 +192,16 @@
    private volatile BigDecimal initialPrincipal = BigDecimal.ZERO;
    /** 上次 PNL 快照时间(毫秒),用于控制 PNL_SNAPSHOT 埋点频率 */
    private volatile long lastPnlSnapshotTime = 0;
    /** 上次持仓主动对账时间(毫秒),用于节流 */
    private volatile long lastPositionSyncTime = 0;
    /** 持仓主动对账间隔(毫秒):本地 WS 持仓可能因断线盲区/推送延迟失真,定期用 REST 权威持仓修正 */
    private static final long POSITION_SYNC_INTERVAL_MS = 15_000;
    private volatile GateKlineWebSocketClient wsClient;
    public GateGridTradeService(GateConfig config, StatsEventProducer statsProducer) {
        this.config = config;
        this.statsProducer = statsProducer;
        ApiClient apiClient = new ApiClient();
        ApiClient apiClient = new GateClosingApiClient();
        apiClient.setBasePath(config.getRestBasePath());
        apiClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
        // 修复 gate-api SDK finishAs 枚举不完整导致的反序列化失败(见 buildLenientJson)
@@ -262,7 +268,7 @@
     */
    public void init() {
        try {
            ApiClient detailClient = new ApiClient();
            ApiClient detailClient = new GateClosingApiClient();
            detailClient.setBasePath(config.getRestBasePath());
            detailClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
            AccountDetail detail = new AccountApi(detailClient).getAccountDetail();
@@ -416,7 +422,7 @@
            return;
        }
        state = StrategyState.WAITING_KLINE;
        cumulativePnl = BigDecimal.ZERO;
        // 累计盈亏为全局口径(不按轮次),轮次重启不清零,由持仓对账以账户已实现盈亏校准
        unrealizedPnl = BigDecimal.ZERO;
        markPrice = BigDecimal.ZERO;
        longEntryPrice = BigDecimal.ZERO;
@@ -547,6 +553,15 @@
        // 异步检查盈亏,避免 REST 调用阻塞 WS 心跳导致 Socket closed
        executor.submitTask(this::checkProfitAndReset);
        // 持仓主动对账(节流):WS 持仓推送可能因断线盲区/推送延迟而失真,
        // 导致本地持仓状态与交易所不一致、价格驱动重入迟迟不触发。
        // 定期用 REST 权威持仓修正,异步执行不阻塞 WS 回调线程。
        if ((state == StrategyState.ACTIVE || state == StrategyState.OPENING)
                && System.currentTimeMillis() - lastPositionSyncTime >= POSITION_SYNC_INTERVAL_MS) {
            lastPositionSyncTime = System.currentTimeMillis();
            executor.submitTask(this::syncPositionsFromExchange);
        }
        if (state == StrategyState.ACTIVE &&
                config.isPriceDriveEnabled() &&
                longActive == false &&
@@ -574,6 +589,8 @@
            BigDecimal target = initialPrincipal.add(config.getExpectedProfit());
            FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
            // 浮动盈亏同步:本地 unrealizedPnl 只在平仓推送时刷新,断线期间会陈旧,用账户权威值覆盖
            try { unrealizedPnl = new BigDecimal(account.getUnrealisedPnl()); } catch (NumberFormatException ignored) {}
            // 预估平仓手续费 = 持仓量 × 合约乘数 × 入场价 × taker费率
            BigDecimal multiplier = config.getContractMultiplier();
            BigDecimal longCloseFee = BigDecimal.ZERO;
@@ -706,7 +723,7 @@
                    longEntryPrice = entryPrice;
                } else {
                    log.info("[Gate-0]多仓: {}", shortBaseEntryPrice);
                    log.info("[Gate-0]多仓: {}", longBaseEntryPrice);
                    longActive = false;
                    longPositionSize = BigDecimal.ZERO;
                    longEntryPrice = BigDecimal.ZERO;
@@ -770,11 +787,17 @@
        log.info("[Gate] 已实现:{}, 未实现:{}, 合计:{}",
                cumulativePnl, unrealizedPnl, totalPnl);
        if(totalPnl.compareTo(config.getMaxLoss().negate()) <= 0) {
            String logMessage = StrUtil.format("[Gate] 已达亏损风险值(合计{}), 已实现:{}, 未实现:{}",
                    totalPnl, cumulativePnl, unrealizedPnl);
            log.info(logMessage);
            // 全局累计口径下会持续低于阈值:只在首次下穿阈值时提醒,回到阈值上方后复位
            if (!maxLossAlerted) {
                maxLossAlerted = true;
                String logMessage = StrUtil.format("[Gate] 已达亏损风险值(合计{}), 已实现:{}, 未实现:{}",
                        totalPnl, cumulativePnl, unrealizedPnl);
                log.info(logMessage);
            DingTalkUtils.getDefault().sendActionCard("风险提醒", logMessage, config.getApiKey(), "");
                DingTalkUtils.getDefault().sendActionCard("风险提醒", logMessage, config.getApiKey(), "");
            }
        } else {
            maxLossAlerted = false;
        }
    }
@@ -1419,6 +1442,299 @@
        return null;
    }
    /**
     * 持仓主动对账:用 REST 权威持仓同步本地持仓状态(多空各自的 active 标记、持仓量与均价)。
     * <p>WS 持仓推送可能因断线盲区(约 50 秒无消息窗口)或推送延迟而丢失/迟到,
     * 导致本地 longActive/shortActive/longPositionSize/shortPositionSize 与交易所实际不一致;
     * 价格驱动的仓位归零重入依赖这些字段,失真会导致该侧迟迟不重开。</p>
     * <p>触发点:{@code onKline} 节流({@link #POSITION_SYNC_INTERVAL_MS})+ WS 重连订阅完成回调。
     * 提交到交易线程池异步执行,不阻塞 WS 回调线程。</p>
     */
    public void syncPositionsFromExchange() {
        if (state != StrategyState.ACTIVE && state != StrategyState.OPENING) {
            return;
        }
        try {
            List<Position> positions = futuresApi.listPositions(SETTLE).execute();
            if (state == StrategyState.ACTIVE) {
                applySyncedPosition(findPosition(positions, Position.ModeEnum.DUAL_LONG), true);
                applySyncedPosition(findPosition(positions, Position.ModeEnum.DUAL_SHORT), false);
                // 累计盈亏对账(全局口径,不按轮次)+ 条件单幽灵清理 + 止损覆盖兜底
                syncCumulativePnl(positions);
                reconcileOpenPriceTriggeredOrders();
                ensureStopLossCoverage();
            } else {
                // OPENING:基底成交推送若落在断线盲区会永久卡住,用 REST 持仓补触发队列生成
                reconcileBaseOpen(positions);
            }
        } catch (Exception e) {
            log.warn("[Gate] 持仓主动对账失败", e);
        }
    }
    /**
     * 从持仓列表中按模式/合约查找持仓对象(与 queryPosition 过滤口径一致)。
     */
    private Position findPosition(List<Position> positions, Position.ModeEnum mode) {
        if (positions == null) {
            return null;
        }
        for (Position p : positions) {
            if (mode == p.getMode() && config.getContract().equals(p.getContract())) {
                return p;
            }
        }
        return null;
    }
    /**
     * OPENING 阶段对账(A):基底是市价 IOC 成交,成交推送若在断线盲区丢失会永久卡在 OPENING。
     * REST 显示双基底均已成交时,补齐本地基底状态并触发队列生成。
     */
    private void reconcileBaseOpen(List<Position> positions) {
        if (state != StrategyState.OPENING) {
            return;
        }
        Position longPos = findPosition(positions, Position.ModeEnum.DUAL_LONG);
        Position shortPos = findPosition(positions, Position.ModeEnum.DUAL_SHORT);
        if (longPos == null || shortPos == null) {
            return;
        }
        BigDecimal longSize = new BigDecimal(longPos.getSize());
        BigDecimal shortSize = new BigDecimal(shortPos.getSize());
        boolean longFilled = longSize.abs().compareTo(BigDecimal.ZERO) > 0;
        boolean shortFilled = shortSize.abs().compareTo(BigDecimal.ZERO) > 0;
        if (!longFilled || !shortFilled) {
            return;
        }
        if (!baseLongOpened) {
            BigDecimal ep = toEntryPrice(longPos.getEntryPrice());
            longActive = true;
            longPositionSize = longSize;
            longEntryPrice = ep;
            longBaseEntryPrice = ep;
            baseLongOpened = true;
            log.warn("[Gate] 基底多成交推送缺失,由 REST 对账补齐: 数量:{}, 均价:{}", longSize, ep);
        }
        if (!baseShortOpened) {
            BigDecimal ep = toEntryPrice(shortPos.getEntryPrice());
            shortActive = true;
            shortPositionSize = shortSize.abs();
            shortEntryPrice = ep;
            shortBaseEntryPrice = ep;
            baseShortOpened = true;
            log.warn("[Gate] 基底空成交推送缺失,由 REST 对账补齐: 数量:{}, 均价:{}", shortSize, ep);
        }
        if (baseLongOpened && baseShortOpened) {
            // 基底下单参数若也丢失(REST 下单响应未回),补占位参数保证 tryGenerateQueues 判空通过
            if (config.getBaseLongTraderParam() == null) {
                config.setBaseLongTraderParam(TraderParam.builder().build());
            }
            if (config.getBaseShortTraderParam() == null) {
                config.setBaseShortTraderParam(TraderParam.builder().build());
            }
            tryGenerateQueues();
        }
    }
    /** 解析均价字符串,空/异常返回 0 */
    private BigDecimal toEntryPrice(String s) {
        if (s == null) {
            return BigDecimal.ZERO;
        }
        try {
            return new BigDecimal(s);
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }
    /**
     * 条件单对账(B):断线期间触发的止损/止盈/开仓单 finished 事件会丢失,
     * 本地 GridElement 索引残留"已失效"订单(幽灵单,含 REDUCE_EXCEEDED 那种)。
     * 以交易所 open 条件单列表为准:本地记录中不在 open 列表的 → 移除并修正网格挂单状态。
     */
    private void reconcileOpenPriceTriggeredOrders() {
        Set<String> openIds = new HashSet<>();
        try {
            List<FuturesPriceTriggeredOrder> openOrders = futuresApi.listPriceTriggeredOrders(SETTLE, "open")
                    .contract(config.getContract())
                    .limit(1000)
                    .execute();
            if (openOrders != null) {
                for (FuturesPriceTriggeredOrder o : openOrders) {
                    if (o.getId() != null) {
                        openIds.add(String.valueOf(o.getId()));
                    }
                }
            }
        } catch (Exception e) {
            log.warn("[Gate] 条件单对账: 查询交易所 open 条件单失败", e);
            return;
        }
        int removed = 0;
        for (GridElement e : config.getGridElements()) {
            for (String id : new ArrayList<>(e.getLongStopLossOrderIds())) {
                if (!openIds.contains(id)) { e.removeLongStopLossOrderId(id); removed++; }
            }
            for (String id : new ArrayList<>(e.getShortStopLossOrderIds())) {
                if (!openIds.contains(id)) { e.removeShortStopLossOrderId(id); removed++; }
            }
            for (String id : new ArrayList<>(e.getLongTakeProfitOrderIds())) {
                if (!openIds.contains(id)) { e.removeLongTakeProfitOrderId(id); removed++; }
            }
            for (String id : new ArrayList<>(e.getShortTakeProfitOrderIds())) {
                if (!openIds.contains(id)) { e.removeShortTakeProfitOrderId(id); removed++; }
            }
            for (String id : new ArrayList<>(e.getLongOrderIds())) {
                if (!openIds.contains(id)) { e.removeLongOrderId(id); removed++; }
            }
            for (String id : new ArrayList<>(e.getShortOrderIds())) {
                if (!openIds.contains(id)) { e.removeShortOrderId(id); removed++; }
            }
            // 清理后修正预置标记与止盈状态
            e.setHasLongOrder(e.hasLongOrderIds());
            e.setHasShortOrder(e.hasShortOrderIds());
            if (!e.hasLongTakeProfitOrders() && e.getLongTraderParam() != null) {
                e.getLongTraderParam().setTakeProfitPlaced(false);
                e.getLongTraderParam().setTakeProfitOrderId(null);
            }
            if (!e.hasShortTakeProfitOrders() && e.getShortTraderParam() != null) {
                e.getShortTraderParam().setTakeProfitPlaced(false);
                e.getShortTraderParam().setTakeProfitOrderId(null);
            }
        }
        if (removed > 0) {
            GridElement.refreshIndices();
            log.warn("[Gate] 条件单对账: 移除 {} 个本地失效订单(交易所已不存在)", removed);
        }
    }
    /**
     * 累计盈亏对账(C,全局口径不按轮次):以交易所账户已实现盈亏为准,
     * 修正断线期间丢失平仓推送导致的本地少算/多算。
     */
    private void syncCumulativePnl(List<Position> positions) {
        if (positions == null) {
            return;
        }
        BigDecimal realised = BigDecimal.ZERO;
        for (Position p : positions) {
            if (config.getContract().equals(p.getContract()) && p.getRealisedPnl() != null) {
                try {
                    realised = realised.add(new BigDecimal(p.getRealisedPnl()));
                } catch (NumberFormatException ignored) {
                }
            }
        }
        if (cumulativePnl.subtract(realised).abs().compareTo(new BigDecimal("0.000001")) > 0) {
            log.warn("[Gate] 累计盈亏对账修正: 本地:{}, 账户已实现:{}", cumulativePnl, realised);
            cumulativePnl = realised;
        }
    }
    /**
     * 止损覆盖兜底:对账后若某方向有持仓但止损覆盖张数不足(如断线期间成交的挂单漏了重挂流程),
     * 按原止损位重挂全持仓止损,避免裸奔。挂单防重入标记进行中时跳过。
     */
    private void ensureStopLossCoverage() {
        int longPos = longPositionSize.intValue();
        if (longPos > 0) {
            GridElement anchor = findNearestLongStopLossGrid();
            if (anchor != null) {
                int covered = 0;
                for (GridElement e : config.getGridElements()) {
                    covered += e.getLongStopLossTotalSize();
                }
                GridElement entryElem = GridElement.findById(anchor.getId() + 2);
                boolean inProgress = entryElem != null && entryElem.isExtendStopLossInProgress();
                if (!inProgress && covered < longPos) {
                    log.warn("[Gate] 多仓止损覆盖不足: 持仓:{}张, 覆盖:{}张, 按原位置重挂", longPos, covered);
                    cancelAllLongStopLossesOnly();
                    extendLongStopLoss(longPos, anchor.getId() + 2);
                }
            }
        }
        int shortPos = shortPositionSize.intValue();
        if (shortPos > 0) {
            GridElement anchor = findNearestShortStopLossGrid();
            if (anchor != null) {
                int covered = 0;
                for (GridElement e : config.getGridElements()) {
                    covered += e.getShortStopLossTotalSize();
                }
                GridElement entryElem = GridElement.findById(anchor.getId() - 2);
                boolean inProgress = entryElem != null && entryElem.isExtendStopLossInProgress();
                if (!inProgress && covered < shortPos) {
                    log.warn("[Gate] 空仓止损覆盖不足: 持仓:{}张, 覆盖:{}张, 按原位置重挂", shortPos, covered);
                    cancelAllShortStopLossesOnly();
                    extendShortStopLoss(shortPos, anchor.getId() - 2);
                }
            }
        }
    }
    /**
     * 把对账查询到的持仓写入本地状态(口径与 onPositionUpdate 的 ACTIVE 分支一致),
     * 与本地记录不一致时打 WARN 便于观察对账是否真正修正过状态。
     */
    private void applySyncedPosition(Position pos, boolean isLong) {
        if (pos == null) {
            return;
        }
        BigDecimal size = new BigDecimal(pos.getSize());
        boolean has = size.abs().compareTo(BigDecimal.ZERO) > 0;
        BigDecimal entryPrice = BigDecimal.ZERO;
        if (pos.getEntryPrice() != null) {
            try {
                entryPrice = new BigDecimal(pos.getEntryPrice());
            } catch (NumberFormatException e) {
                entryPrice = BigDecimal.ZERO;
            }
        }
        if (isLong) {
            if (has) {
                if (!longActive || longPositionSize.compareTo(size) != 0) {
                    log.warn("[Gate] 持仓对账修正多仓: 本地 active:{}, size:{}, 实际 size:{}",
                            longActive, longPositionSize, size);
                }
                longActive = true;
                longPositionSize = size;
                if (entryPrice.compareTo(BigDecimal.ZERO) > 0) {
                    longEntryPrice = entryPrice;
                }
            } else {
                if (longActive || longPositionSize.compareTo(BigDecimal.ZERO) != 0) {
                    log.warn("[Gate] 持仓对账修正多仓: 本地 active:{}, size:{}, 实际已无仓位",
                            longActive, longPositionSize);
                }
                longActive = false;
                longPositionSize = BigDecimal.ZERO;
                longEntryPrice = BigDecimal.ZERO;
            }
        } else {
            if (has) {
                if (!shortActive || shortPositionSize.compareTo(size.abs()) != 0) {
                    log.warn("[Gate] 持仓对账修正空仓: 本地 active:{}, size:{}, 实际 size:{}",
                            shortActive, shortPositionSize, size.abs());
                }
                shortActive = true;
                shortPositionSize = size.abs();
                if (entryPrice.compareTo(BigDecimal.ZERO) > 0) {
                    shortEntryPrice = entryPrice;
                }
            } else {
                if (shortActive || shortPositionSize.compareTo(BigDecimal.ZERO) != 0) {
                    log.warn("[Gate] 持仓对账修正空仓: 本地 active:{}, size:{}, 实际已无仓位",
                            shortActive, shortPositionSize);
                }
                shortActive = false;
                shortPositionSize = BigDecimal.ZERO;
                shortEntryPrice = BigDecimal.ZERO;
            }
        }
    }
    // ---- 网格队列处理 ----
    /**
@@ -1986,156 +2302,182 @@
    /** 多仓仓位归零后,在当前价上方最近网格重新挂多单(遍历 totalLongPriceQueue 升序)。 */
    private void processLongGrid(BigDecimal currentPrice) {
        BigDecimal matched = BigDecimal.ZERO;
        GridElement newEntryGrid = null;
        boolean hasLongOrderBelow = false;
        // 阶段1(队列锁内):匹配价格 + 网格定位 + 本地挂单检查 + 提交撤单,全程无阻塞 IO
        synchronized (totalLongPriceQueue) {
            BigDecimal matched = BigDecimal.ZERO;
            for (BigDecimal p : totalLongPriceQueue) {
                if (p.compareTo(currentPrice) >= 0) {
                    matched =  p;
                    matched = p;
                    break;
                }
            }
//            log.info("[Gate-1] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
            if (BigDecimal.ZERO.compareTo( matched) == 0) {
            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null){
                if (!matchedUpGridElement.isHasLongOrder()){
                    Integer upId = matchedUpGridElement.getUpId();
                    GridElement newEntryGrid = GridElement.findById(upId);
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasLongOrder()) {
                Integer upId = matchedUpGridElement.getUpId();
                newEntryGrid = GridElement.findById(upId);
                    if (newEntryGrid != null) {
                if (newEntryGrid != null) {
                    // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
                    GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
                    while (checkDownCursor != null) {
                        if (checkDownCursor.isHasLongOrder()) {
                            hasLongOrderBelow = true;
                            log.debug("[Gate] 多仓仓位归零 gridId:{}, 下方gridId:{}已有多单, 跳过本次挂单",
                                    newEntryGrid.getId(), checkDownCursor.getId());
                            break;
                        }
                        Integer nextDownId = checkDownCursor.getDownId();
                        checkDownCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                    }
//                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_SHORT), shortPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
//                        String quantity = String.valueOf(config.getBaseQuantity());
                        String quantity = calculateEntryQuantity(true, false, 0);
                        // 向下检查是否已有多单挂在更低价格网格,有则跳过(防止价格回升后重复挂单)
                        boolean hasLongOrderBelow = false;
                        GridElement checkDownCursor = GridElement.findById(newEntryGrid.getDownId());
                        while (checkDownCursor != null) {
                            if (checkDownCursor.isHasLongOrder()) {
                                hasLongOrderBelow = true;
                                log.info("[Gate] 多仓仓位归零 gridId:{}, 下方gridId:{}已有多单, 跳过本次挂单",
                                        newEntryGrid.getId(), checkDownCursor.getId());
                                break;
                    // 向上遍历取消所有遗留多单(跳过基础入场网格0)
                    GridElement cancelCursor = GridElement.findById(newEntryGrid.getUpId());
                    while (cancelCursor != null) {
                        if (cancelCursor.isHasLongOrder()) {
                            for (String longOrderId : new ArrayList<>(cancelCursor.getLongOrderIds())) {
                                GridElement finalCancelCursor = cancelCursor;
                                executor.cancelConditionalOrder(longOrderId, oid -> {
                                    longEntryTraderIdParam(finalCancelCursor, longOrderId, false);
                                    log.info("[Gate] 多仓仓位归零, 取消gridId:{}的多单,{}", finalCancelCursor.getId(), longOrderId);
                                });
                            }
                            Integer nextDownId = checkDownCursor.getDownId();
                            checkDownCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                        }
                        // 向上遍历取消所有遗留多单(跳过基础入场网格0)
                        GridElement cancelCursor = GridElement.findById(newEntryGrid.getUpId());
                        while (cancelCursor != null) {
                            if (cancelCursor.isHasLongOrder()) {
                                for (String longOrderId : new ArrayList<>(cancelCursor.getLongOrderIds())) {
                                    GridElement finalCancelCursor = cancelCursor;
                                    executor.cancelConditionalOrder(longOrderId, oid -> {
                                        longEntryTraderIdParam(finalCancelCursor, longOrderId, false);
                                        log.info("[Gate] 多仓仓位归零, 取消gridId:{}的多单,{}", finalCancelCursor.getId(), longOrderId);
                                    });
                                }
                            }
                            Integer nextUpId = cancelCursor.getUpId();
                            cancelCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                        }
//                        log.info("[Gate-2] 多仓仓位归零 空仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                        if (!newEntryGrid.isHasLongOrder() && !hasLongOrderBelow) {
                            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
                            String size = quantity;
                            log.info("[Gate] 多仓仓位归零 gridId:{}, 挂{}张多单",
                                    newEntryGrid.getId(), size);
                            newEntryGrid.getLongTraderParam().setQuantity(size);
                            // 含加仓量的单打标记:真正成交后才计入加仓执行次数
                            boolean hasAdd = computeAddQty(true) > 0;
                            placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
                                    FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
                                    hasAdd ? pendingAddEntryOrderIds::add : null);
                        }
                        Integer nextUpId = cancelCursor.getUpId();
                        cancelCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                    }
                }
            }
        }
        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
        if (newEntryGrid == null || newEntryGrid.isHasLongOrder() || hasLongOrderBelow) {
            return;
        }
        // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
        // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍(历史出现过 68→136 张);
        // 顺带同步 entryPrice(此前核实只修 size/active,均价仍是旧值)
        Position longPos = queryPosition(Position.ModeEnum.DUAL_LONG);
        int realPos = longPos != null ? Math.abs(new BigDecimal(longPos.getSize()).intValue()) : 0;
        if (realPos > 0) {
            longActive = true;
            longPositionSize = BigDecimal.valueOf(realPos);
            if (longPos.getEntryPrice() != null) {
                try {
                    longEntryPrice = new BigDecimal(longPos.getEntryPrice());
                } catch (NumberFormatException ignored) {
                }
            }
            log.warn("[Gate] 多仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
            return;
        }
        // 阶段3:挂单
        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
        String size = calculateEntryQuantity(true, false, 0);
        log.info("[Gate] 多仓仓位归零 gridId:{}, 挂{}张多单",
                newEntryGrid.getId(), size);
        newEntryGrid.getLongTraderParam().setQuantity(size);
        // 含加仓量的单打标记:真正成交后才计入加仓执行次数
        boolean hasAdd = computeAddQty(true) > 0;
        placeEntryOrderWithPreFlag(newEntryGrid, true, triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_1, size,
                hasAdd ? pendingAddEntryOrderIds::add : null);
    }
    /** 空仓仓位归零后,在当前价下方最近网格重新挂空单(遍历 totalShortPriceQueue 降序)。 */
    private void processShortGrid(BigDecimal currentPrice) {
        BigDecimal matched = BigDecimal.ZERO;
        GridElement newEntryGrid = null;
        boolean hasShortOrderAbove = false;
        // 阶段1(队列锁内):匹配价格 + 网格定位 + 本地挂单检查 + 提交撤单,全程无阻塞 IO
        synchronized (totalShortPriceQueue) {
            BigDecimal matched = BigDecimal.ZERO;
            for (BigDecimal p : totalShortPriceQueue) {
                if (p.compareTo(currentPrice) <= 0) {
                    matched = p;
                    break;
                }
            }
//            log.info("[Gate-3] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
            if (BigDecimal.ZERO.compareTo( matched) == 0) {
            if (BigDecimal.ZERO.compareTo(matched) == 0) {
                return;
            }
            GridElement matchedUpGridElement = GridElement.findByPrice(matched);
            if (matchedUpGridElement != null){
                if(!matchedUpGridElement.isHasShortOrder()){
                    Integer downId = matchedUpGridElement.getDownId();
                    GridElement newEntryGrid = GridElement.findById(downId);
            if (matchedUpGridElement != null && !matchedUpGridElement.isHasShortOrder()) {
                Integer downId = matchedUpGridElement.getDownId();
                newEntryGrid = GridElement.findById(downId);
                    if (newEntryGrid != null) {
                if (newEntryGrid != null) {
                    // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
                    GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
                    while (checkUpCursor != null) {
                        if (checkUpCursor.isHasShortOrder()) {
                            hasShortOrderAbove = true;
                            log.debug("[Gate] 空仓仓位归零 gridId:{}, 上方gridId:{}已有空单, 跳过本次挂单",
                                    newEntryGrid.getId(), checkUpCursor.getId());
                            break;
                        }
                        Integer nextUpId = checkUpCursor.getUpId();
                        checkUpCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                    }
//                        String quantity = String.valueOf((accumulatedShortLossCount + 1) * Integer.parseInt(config.getQuantity()));
//                        String quantity = String.valueOf(Math.max(queryPositionSize(Position.ModeEnum.DUAL_LONG), longPositionSize.intValue()) + Integer.parseInt(config.getQuantity()));
//                        String quantity = String.valueOf(config.getBaseQuantity());
                        String quantity = calculateEntryQuantity(false, false, 0);
                        // 向上检查是否已有空单挂在更高价格网格,有则跳过(防止价格回落后重复挂单)
                        boolean hasShortOrderAbove = false;
                        GridElement checkUpCursor = GridElement.findById(newEntryGrid.getUpId());
                        while (checkUpCursor != null) {
                            if (checkUpCursor.isHasShortOrder()) {
                                hasShortOrderAbove = true;
                                log.info("[Gate] 空仓仓位归零 gridId:{}, 上方gridId:{}已有空单, 跳过本次挂单",
                                        newEntryGrid.getId(), checkUpCursor.getId());
                                break;
                    // 向下遍历取消所有遗留空单(跳过基础入场网格0)
                    GridElement cancelCursor = GridElement.findById(newEntryGrid.getDownId());
                    while (cancelCursor != null) {
                        if (cancelCursor.isHasShortOrder()) {
                            for (String shortOrderId : new ArrayList<>(cancelCursor.getShortOrderIds())) {
                                GridElement finalCancelCursor = cancelCursor;
                                executor.cancelConditionalOrder(shortOrderId, oid -> {
                                    shortEntryTraderIdParam(finalCancelCursor, shortOrderId, false);
                                    log.info("[Gate] 空仓仓位归零, 取消gridId:{}的空单{}", finalCancelCursor.getId(), shortOrderId);
                                });
                            }
                            Integer nextUpId = checkUpCursor.getUpId();
                            checkUpCursor = nextUpId != null ? GridElement.findById(nextUpId) : null;
                        }
                        // 向下遍历取消所有遗留空单(跳过基础入场网格0)
                        GridElement cancelCursor = GridElement.findById(newEntryGrid.getDownId());
                        while (cancelCursor != null) {
                            if (cancelCursor.isHasShortOrder()) {
                                for (String shortOrderId : new ArrayList<>(cancelCursor.getShortOrderIds())) {
                                    GridElement finalCancelCursor = cancelCursor;
                                    executor.cancelConditionalOrder(shortOrderId, oid -> {
                                        shortEntryTraderIdParam(finalCancelCursor, shortOrderId, false);
                                        log.info("[Gate] 空仓仓位归零, 取消gridId:{}的空单{}", finalCancelCursor.getId(), shortOrderId);
                                    });
                                }
                            }
                            Integer nextDownId = cancelCursor.getDownId();
                            cancelCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                        }
//                        log.info("[Gate-4] 空仓仓位归零 多仓队列触发, 匹配:{},当前价:{}", matched, currentPrice);
                        if (!newEntryGrid.isHasShortOrder() && !hasShortOrderAbove){
                            BigDecimal triggerPrice = newEntryGrid.getGridPrice();
                            String size = quantity;
                            log.info("[Gate] 空仓仓位归零 gridId:{}, 挂{}张空单",
                                    newEntryGrid.getId(), size);
                            newEntryGrid.getShortTraderParam().setQuantity(size);
                            // 含加仓量的单打标记:真正成交后才计入加仓执行次数
                            boolean hasAdd = computeAddQty(false) > 0;
                            placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
                                    FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
                                    hasAdd ? pendingAddEntryOrderIds::add : null);
                        }
                        Integer nextDownId = cancelCursor.getDownId();
                        cancelCursor = nextDownId != null ? GridElement.findById(nextDownId) : null;
                    }
                }
            }
        }
        // 阶段2(队列锁外):REST 持仓核实,阻塞 IO 不持锁
        if (newEntryGrid == null || newEntryGrid.isHasShortOrder() || hasShortOrderAbove) {
            return;
        }
        // 挂单前核实:本地持仓可能滞后(成交推送延迟/被快照风暴阻塞),
        // REST 确认该方向真实持仓为 0 才挂单,避免重复建仓导致持仓翻倍;
        // 顺带同步 entryPrice(此前核实只修 size/active,均价仍是旧值)
        Position shortPos = queryPosition(Position.ModeEnum.DUAL_SHORT);
        int realPos = shortPos != null ? Math.abs(new BigDecimal(shortPos.getSize()).intValue()) : 0;
        if (realPos > 0) {
            shortActive = true;
            shortPositionSize = BigDecimal.valueOf(realPos);
            if (shortPos.getEntryPrice() != null) {
                try {
                    shortEntryPrice = new BigDecimal(shortPos.getEntryPrice());
                } catch (NumberFormatException ignored) {
                }
            }
            log.warn("[Gate] 空仓仓位归零挂单前核实: 实际持仓{}张>0, 跳过挂单(本地状态已滞后)", realPos);
            return;
        }
        // 阶段3:挂单
        BigDecimal triggerPrice = newEntryGrid.getGridPrice();
        String size = calculateEntryQuantity(false, false, 0);
        log.info("[Gate] 空仓仓位归零 gridId:{}, 挂{}张空单",
                newEntryGrid.getId(), size);
        newEntryGrid.getShortTraderParam().setQuantity(size);
        // 含加仓量的单打标记:真正成交后才计入加仓执行次数
        boolean hasAdd = computeAddQty(false) > 0;
        placeEntryOrderWithPreFlag(newEntryGrid, false, triggerPrice,
                FuturesPriceTrigger.RuleEnum.NUMBER_2, negate(size),
                hasAdd ? pendingAddEntryOrderIds::add : null);
    }
    // ========== 加仓计算 ==========
@@ -3011,7 +3353,19 @@
    /** @return 当前策略状态 */
    public StrategyState getState() { return state; }
    /** 注入WS客户端,用于订阅状态检查 */
    public void setWsClient(GateKlineWebSocketClient wsClient) { this.wsClient = wsClient; }
    public void setWsClient(GateKlineWebSocketClient wsClient) {
        this.wsClient = wsClient;
        // WS 重连、四个频道重新订阅完成后立即做一次持仓对账:
        // 断线盲区内错过的仓位变化在重连后尽快恢复,不必等 15 秒节流窗口。
        // 回调在 WS 读线程执行,这里只入队、不阻塞(ACTIVE 才提交,关闭期间跳过)。
        if (wsClient != null) {
            wsClient.setOnAllSubscribedCallback(() -> {
                if (state == StrategyState.ACTIVE || state == StrategyState.OPENING) {
                    executor.submitTask(this::syncPositionsFromExchange);
                }
            });
        }
    }
    // ========== 手动控制(Station 指令) ==========
src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -12,6 +12,7 @@
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -116,6 +117,21 @@
    /** 频道处理器列表,通过 addChannelHandler 注册 */
    private final List<GateChannelHandler> channelHandlers = new ArrayList<>();
    /** 全部频道订阅完成后的回调(首次连接与重连后都会触发,供持仓对账等逻辑使用) */
    private volatile Runnable onAllSubscribedCallback;
    /** 设置全部频道订阅完成回调(由 GateGridTradeService 挂接,重连后触发持仓对账) */
    public void setOnAllSubscribedCallback(Runnable callback) { this.onAllSubscribedCallback = callback; }
    /** 订阅确认超时(秒):连接建立后超过该时长仍未全部订阅成功 → 判定订阅失败,断开重连 */
    private static final int SUBSCRIBE_TIMEOUT_SECONDS = 20;
    /** 单频道订阅失败后的重新订阅延迟(秒) */
    private static final int RESUBSCRIBE_DELAY_SECONDS = 2;
    /** 单频道订阅失败重试次数上限(超过则整体断开重连,重订阅全部频道) */
    private static final int MAX_RESUBSCRIBE_RETRIES = 3;
    /** 订阅确认超时 Future(连接建立后启动,全部订阅成功或断开时取消) */
    private volatile ScheduledFuture<?> subscribeTimeoutFuture;
    /** 各频道重新订阅重试计数(channelName → 次数),连接成功后清空 */
    private final Map<String, AtomicInteger> resubscribeRetryCount = new ConcurrentHashMap<>();
    /** 重连等异步任务的缓存线程池(daemon 线程) */
    private final ExecutorService sharedExecutor = Executors.newCachedThreadPool(r -> {
@@ -188,6 +204,7 @@
        if (pongTimeoutFuture != null) {
            pongTimeoutFuture.cancel(true);
        }
        cancelSubscribeTimeout();
        shutdownExecutorGracefully(heartbeatExecutor);
        shutdownExecutorGracefully(sharedExecutor);
@@ -247,6 +264,14 @@
                            handler.subscribe(webSocketClient);
                        }
                        sendPing();
                        // 订阅确认超时保护:若服务器既不回 subscribe 确认、也不回 error,
                        // 超时后判定订阅失败断开重连,避免策略永久卡在 WAITING_KLINE
                        cancelSubscribeTimeout();
                        resubscribeRetryCount.clear();
                        if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
                            subscribeTimeoutFuture = heartbeatExecutor.schedule(
                                    () -> checkSubscriptionTimeout(), SUBSCRIBE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
                        }
                    } else {
                        log.warn("[WS] 应用正在关闭,忽略连接成功回调");
                    }
@@ -265,6 +290,7 @@
                    isConnected.set(false);
                    isConnecting.set(false);
                    cancelPongTimeout();
                    cancelSubscribeTimeout();
                    scheduleReconnect();
                }
@@ -316,6 +342,15 @@
                        break;
                    }
                }
                // 全部频道订阅完成(含重连后的重新订阅)→ 通知持仓对账等逻辑
                if (areAllSubscribed()) {
                    cancelSubscribeTimeout();
                    resubscribeRetryCount.clear();
                    Runnable cb = onAllSubscribedCallback;
                    if (cb != null) {
                        cb.run();
                    }
                }
                return;
            }
            if ("unsubscribe".equals(event)) {
@@ -323,11 +358,12 @@
                return;
            }
            if ("error".equals(event)) {
                JSONObject error = response.getJSONObject("error");
                // 官方格式:code/message 在顶层(非嵌套 error 对象)
                log.error("[WS] {} 错误, code:{}, msg:{}",
                        channel,
                        error != null ? error.getInteger("code") : "N/A",
                        error != null ? error.getString("message") : response.getString("msg"));
                        response.getInteger("code"),
                        response.getString("message"));
                handleChannelSubscribeError(channel);
                return;
            }
            if ("update".equals(event) || "all".equals(event)) {
@@ -442,6 +478,74 @@
        if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) pongTimeoutFuture.cancel(true);
    }
    /**
     * 订阅确认超时检查:连接建立后超过 {@link #SUBSCRIBE_TIMEOUT_SECONDS} 秒仍未全部订阅成功
     * (服务器既不回 subscribe 确认、也不回 error),判定订阅失败,主动断开触发整体重连。
     */
    private void checkSubscriptionTimeout() {
        if (destroyed.get() || !isConnected.get()) {
            return;
        }
        if (!areAllSubscribed()) {
            StringBuilder sb = new StringBuilder();
            for (GateChannelHandler h : channelHandlers) {
                if (!h.isSubscribed()) {
                    if (sb.length() > 0) sb.append(',');
                    sb.append(h.getChannelName());
                }
            }
            log.warn("[WS] 连接建立 {} 秒后仍有频道未订阅成功({}), 判定订阅失败,断开重连",
                    SUBSCRIBE_TIMEOUT_SECONDS, sb);
            closeSocket();
        }
    }
    /** 取消订阅确认超时任务。 */
    private void cancelSubscribeTimeout() {
        if (subscribeTimeoutFuture != null && !subscribeTimeoutFuture.isDone()) {
            subscribeTimeoutFuture.cancel(true);
        }
        subscribeTimeoutFuture = null;
    }
    /**
     * 频道订阅失败处理:先按频道延迟重新订阅(有限次数),超过上限则整体断开重连。
     * 覆盖"鉴权失败/订阅参数错误"等 error 场景,避免订阅失败后策略永久卡在 WAITING_KLINE。
     */
    private void handleChannelSubscribeError(String channel) {
        if (destroyed.get()) {
            return;
        }
        GateChannelHandler target = null;
        for (GateChannelHandler h : channelHandlers) {
            if (channel.equals(h.getChannelName())) {
                target = h;
                break;
            }
        }
        if (target == null) {
            return;
        }
        target.setSubscribed(false);
        int retries = resubscribeRetryCount.computeIfAbsent(channel, k -> new AtomicInteger()).incrementAndGet();
        if (retries > MAX_RESUBSCRIBE_RETRIES) {
            log.warn("[WS] {} 重新订阅失败已达 {} 次,断开整体重连", channel, retries - 1);
            closeSocket();
            return;
        }
        log.warn("[WS] {} 订阅失败(第{}次),{} 秒后重新订阅", channel, retries, RESUBSCRIBE_DELAY_SECONDS);
        if (heartbeatExecutor == null || heartbeatExecutor.isShutdown()) {
            return;
        }
        // target 在查找循环中被赋值,非 effectively final,须用 final 变量捕获进 lambda
        final GateChannelHandler handlerToResubscribe = target;
        heartbeatExecutor.schedule(() -> {
            if (!destroyed.get() && isConnected.get() && webSocketClient != null && webSocketClient.isOpen()) {
                handlerToResubscribe.subscribe(webSocketClient);
            }
        }, RESUBSCRIBE_DELAY_SECONDS, TimeUnit.SECONDS);
    }
    // ---- reconnect ----
    /**
src/main/java/com/xcong/excoin/modules/gateApi/GridElement.java
@@ -5,6 +5,7 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
 * 网格价格层级,策略的最小操作单元。
@@ -80,21 +81,21 @@
    /** 下一个网格编号,null 表示无下一级 */
    private Integer downId;
    /** 多仓挂单订单 ID 列表(支持同一网格多个挂单,由止损追单产生) */
    private List<String> longOrderIds = new ArrayList<>();
    private List<String> longOrderIds = new CopyOnWriteArrayList<>();
    /** 空仓挂单订单 ID 列表(支持同一网格多个挂单,由止损追单产生) */
    private List<String> shortOrderIds = new ArrayList<>();
    private List<String> shortOrderIds = new CopyOnWriteArrayList<>();
    /** 多仓止盈订单 ID 列表(支持一网格多笔止盈单:基础止盈 + 超额止盈并行挂单) */
    private List<String> longTakeProfitOrderIds = new ArrayList<>();
    private List<String> longTakeProfitOrderIds = new CopyOnWriteArrayList<>();
    /** 空仓止盈订单 ID 列表(支持一网格多笔止盈单:基础止盈 + 超额止盈并行挂单) */
    private List<String> shortTakeProfitOrderIds = new ArrayList<>();
    private List<String> shortTakeProfitOrderIds = new CopyOnWriteArrayList<>();
    /** 多仓止盈订单 ID → 张数(仓位止盈补仓时取本次止盈单张数) */
    private final Map<String, Integer> longTakeProfitOrderSizes = new ConcurrentHashMap<>();
    /** 空仓止盈订单 ID → 张数 */
    private final Map<String, Integer> shortTakeProfitOrderSizes = new ConcurrentHashMap<>();
    /** 多仓止损订单 ID 列表(支持一个网格多个止损单) */
    private List<String> longStopLossOrderIds = new ArrayList<>();
    private List<String> longStopLossOrderIds = new CopyOnWriteArrayList<>();
    /** 空仓止损订单 ID 列表(支持一个网格多个止损单) */
    private List<String> shortStopLossOrderIds = new ArrayList<>();
    private List<String> shortStopLossOrderIds = new CopyOnWriteArrayList<>();
    /** 多仓止损订单 ID → 张数(止损触发时统计该网格全部止损覆盖张数,修正追单的 REST 持仓时序竞态) */
    private final Map<String, Integer> longStopLossOrderSizes = new ConcurrentHashMap<>();
    /** 空仓止损订单 ID → 张数 */
src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java
@@ -35,6 +35,8 @@
    private final GateGridTradeService gridTradeService;
    private volatile boolean subscribed = false;
    /** 已处理的最新烛线起始时间戳(秒),用于跳过重连后历史快照的逐条重放 */
    private volatile long lastCandleT = 0;
    /**
      * @param contract         合约名称(如 ETH_USDT)
@@ -97,7 +99,7 @@
     * 处理 K 线推送消息。
     *
     * <h3>数据提取</h3>
     * result[0] 中提取:
     * result 数组中提取<b>t(时间戳)最大</b>的一根;同一 t 出现 w=true/w=false 两根时优先取 w=false(实时烛线):
     * <ul>
     *   <li>c(close):收盘价 → 传给 gridTradeService.onKline()</li>
     *   <li>n(name):烛线名称(如 "1m_ETH_USDT")</li>
@@ -120,7 +122,33 @@
        try {
            JSONArray resultArray = response.getJSONArray("result");
            if (resultArray == null || resultArray.isEmpty()) { log.warn("[{}] 数据为空", CHANNEL_NAME); return true; }
            JSONObject data = resultArray.getJSONObject(0);
            // 快照/更新可能一次带多根烛线:同一 t 会同时出现 w=true(已完结)+ w=false(进行中)两根。
            // 不依赖数组顺序:取 t(烛线起始时间戳)最大的一根;同一 t 时优先取 w=false(实时更新中的烛线),
            // 保证策略拿到的始终是最新实时价,而不是刚完结烛线的收盘价。
            JSONObject data = null;
            long maxT = Long.MIN_VALUE;
            boolean foundLive = false;
            for (int i = 0; i < resultArray.size(); i++) {
                JSONObject candle = resultArray.getJSONObject(i);
                long t = candle.getLongValue("t");
                boolean live = !candle.getBooleanValue("w");
                if (t > maxT) {
                    maxT = t;
                    data = candle;
                    foundLive = live;
                } else if (t == maxT && live && !foundLive) {
                    data = candle;
                    foundLive = true;
                }
            }
            if (data == null) { log.warn("[{}] 烛线无有效条目", CHANNEL_NAME); return true; }
            // 跨消息单调过滤:重连后快照按历史顺序逐条推送(每条消息一根),
            // t 早于已处理最新烛线的历史数据直接跳过,避免重放旧价格驱动策略(历史出现过 950 条风暴 + 持仓翻倍)
            if (maxT < lastCandleT) {
                log.debug("[{}] 跳过历史烛线 t:{} (已处理最新 t:{})", CHANNEL_NAME, maxT, lastCandleT);
                return true;
            }
            lastCandleT = maxT;
            BigDecimal closePx = new BigDecimal(data.getString("c"));
            if (gridTradeService != null) {