From e9a397babbbfa9cff8a5ed026447d585e739c37f Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Tue, 12 May 2026 21:47:21 +0800
Subject: [PATCH] refactor(gateApi): 将网格交易策略从限价单改为条件单
---
src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md | 698 ++++++++++++++++++++++++++++++++++++++++++++-------------
1 files changed, 536 insertions(+), 162 deletions(-)
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 57e30a5..75ac145 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
@@ -4,32 +4,44 @@
| 文件 | 类型 | 说明 |
|------|------|------|
-| [GateWebSocketClientManager](#gatewebsocketclientmanager) | `@Component` | 启动入口,生命周期管理 |
-| [GateKlineWebSocketClient](#gateklinewebsocketclient) | WebSocket 客户端 | K 线 + 仓位数据监听 |
-| [GateGridTradeService](#gategridtradeservice) | 交易服务 | 网格策略 + REST 下单 |
+| [GateWebSocketClientManager](#gatewebsocketclientmanager) | `@Component` | Spring 启动入口,组装组件 + 生命周期 |
+| [GateConfig](#gateconfig) | 配置 | Builder 模式:API 密钥、合约、策略参数、环境切换 |
+| [GateKlineWebSocketClient](#gateklinewebsocketclient) | WS 连接管理 | 连接/心跳/重连/消息路由 |
+| [GateGridTradeService](#gategridtradeservice) | 交易服务 | 网格队列策略 + 条件开仓单 + 止盈队列 + 反向条件单 |
+| [GateTradeExecutor](#gatetradeexecutor) | 异步执行器 | 独立线程池执行 REST 下单,成功/失败双回调 |
| [GateWebSocketClientMain](#gatewebsocketclientmain) | main 入口 | 独立测试启动 |
| [Example.java](#examplejava) | 示例 | Gate SDK 用法参考 |
+
+### wsHandler 子包
+
+| 文件 | 类型 | 说明 |
+|------|------|------|
+| `wsHandler/GateChannelHandler.java` | **接口** | subscribe / unsubscribe / handleMessage / getChannelName |
+| `wsHandler/AbstractPrivateChannelHandler.java` | **抽象类** | 私有频道基类:HMAC-SHA512 签名 + 认证请求 |
+| `wsHandler/handler/CandlestickChannelHandler.java` | 公开频道 | K 线解析 → `onKline()` |
+| `wsHandler/handler/PositionsChannelHandler.java` | 私有频道 | 仓位推送 → `onPositionUpdate()`(传 `Position.ModeEnum`),日志输出全部20个推送字段 |
+| `wsHandler/handler/PositionClosesChannelHandler.java` | 私有频道 | 平仓推送 → `onPositionClose()` |
---
## 架构总览
```
-┌────────────────────────────────────────────────────────────┐
-│ GateWebSocketClientManager │
-│ (Spring @Component) │
-│ │
-│ @PostConstruct init(): │
-│ ┌──────────────────────┐ ┌─────────────────────────┐ │
-│ │ GateGridTradeService │ │ GateKlineWebSocketClient │ │
-│ │ ▶ init() │ │ ▶ init() │ │
-│ │ ▶ startGrid() │←──│ ▶ connect() │ │
-│ └──────┬───────────────┘ └───────────┬─────────────┘ │
-│ │ REST API │ WebSocket │
-│ ▼ ▼ │
-│ Gate Testnet API Gate Testnet WS │
-│ (https://api-testnet...) (wss://ws-testnet.gate.com) │
-└────────────────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────────────────────┐
+│ GateWebSocketClientManager │
+│ (Spring @Component) │
+│ │
+│ GateConfig.builder() → GateGridTradeService + WS Client │
+│ │ │ │ │
+│ │ REST BasePath │ GateTradeExecutor │ WS URL │
+│ ▼ ▼ ▼ │
+│ Gate API (REST) 独立线程池 (async) Gate WebSocket │
+│ onSuccess/onFailure双回调 ┌──────────────┐ │
+│ │Candlestick H │ │
+│ │Positions H │ │
+│ │PosCloses H │ │
+│ └──────────────┘ │
+└──────────────────────────────────────────────────────────────────┘
```
---
@@ -37,30 +49,311 @@
## 数据流
```
-WebSocket 推送
+WebSocket → GateKlineWebSocketClient.handleMessage → 路由 dispatch
│
-├─ futures.candlesticks (update)
-│ └─ GateKlineWebSocketClient.processPushDataV2()
-│ ├─ 解析: o/h/l/c/v/a/t/w
-│ ├─ 打印 K 线日志
-│ └─ GateGridTradeService.onKline(closePx)
-│ ├─ 首次 → dualOpenPositions() → 开多 + 开空 + TP 单
-│ └─ 后续 → 仅缓存 lastKlinePrice
+├─ futures.pong → cancelPongTimeout
+├─ subscribe / unsubscribe / error → log
│
-├─ futures.positions (update) [需 HMAC-SHA512 签名]
-│ └─ GateKlineWebSocketClient.processPositionData()
-│ ├─ 解析: contract/mode/size/entry_price/history_pnl/realised_pnl
-│ └─ GateGridTradeService.onPositionUpdate(...)
-│ ├─ size=0 && longActive → reopenLongPosition()
-│ ├─ size=0 && shortActive → reopenShortPosition()
-│ ├─ size>0 → 确认仓位活跃
-│ └─ checkStopConditions(history_pnl)
+├─ futures.candlesticks (公开)
+│ └─ CandlestickChannelHandler
+│ └─ gridTradeService.onKline(closePrice, timestamp)
+│ ├─ 更新 unrealizedPnl(浮动盈亏)
+│ ├─ state=WAITING_KLINE → 异步双开基底仓位
+│ └─ state=ACTIVE → 方向区分: closePrice>longPriceQueue[0]→processLongGrid,
+│ closePrice<shortPriceQueue[0]→processShortGrid, 其余跳过(一个K线只触发一个方向)
│
-├─ futures.pong
-│ └─ cancelPongTimeout()
+├─ futures.positions (私有, HMAC-SHA512)
+│ └─ PositionsChannelHandler
+│ ├─ 解析 mode → Position.ModeEnum(DUAL_LONG / DUAL_SHORT)
+│ ├─ 日志输出全部 20 个推送字段(contract/mode/size/entry_price/.../update_id)
+│ └─ gridTradeService.onPositionUpdate(contract, mode, size, entryPrice)
+│ ├─ 有仓位: 标记活跃,首次成交记录入场价
+│ │ ├─ 基底开仓 → 首次成交 → 记录基底入场价 → 双基底都成交后
+│ │ │ 生成网格队列 + 止盈队列初始化 + 挂初始条件开仓单 → state=ACTIVE
+│ │ └─ 非基底(仓位净增) → 按 quantity 为单位计算增量,
+│ │ 逐个从止盈队列消费止盈价(队列不足时 entryPrice ± step 兜底)
+│ └─ 无仓位(size=0): 标记不活跃
│
-└─ subscribe/unsubscribe/error
- └─ 日志输出
+├─ futures.position_closes (私有, HMAC-SHA512)
+│ └─ PositionClosesChannelHandler
+│ └─ gridTradeService.onPositionClose(contract, side, pnl)
+│ └─ cumulativePnl += pnl → checkStopConditions()
+│
+└─ 所有下单操作
+ └─ GateTradeExecutor (单线程 + 64队列 + CallerRunsPolicy)
+ ├─ openLong/openShort → 市价 IOC 开仓(基底双开 + 额外反向开仓)
+ ├─ placeConditionalEntryOrder → 条件开仓单(网格触发,服务端监控价格触发后市价 IOC)
+ ├─ cancelConditionalOrder → 取消指定条件单
+ ├─ placeTakeProfit → 止盈条件单(plan-close-*-position)
+ ├─ cancelAllPriceTriggeredOrders → 清除所有条件单(停止时)
+ ├─ placeGridLimitOrder → 【遗留】限价 GTC 单(当前策略未使用)
+ └─ cancelOrder → 【遗留】取消限价单(当前策略未使用)
+```
+
+### PositionsChannelHandler 完整推送字段(20个)
+
+| 字段 | 类型 | 描述 |
+|------|------|------|
+| contract | String | 合约名称 |
+| mode | String | 持仓模式:dual_long / dual_short |
+| size | String/Integer | 合约张数(正=多头,负=空头) |
+| entry_price | Float | 开仓均价 |
+| cross_leverage_limit | Float | 全仓模式下的杠杆倍数上限 |
+| history_pnl | Float | 已平仓的仓位总盈亏 |
+| history_point | Float | 已平仓的点卡总盈亏 |
+| last_close_pnl | Float | 最近一次平仓的盈亏 |
+| leverage | Integer | 杠杆倍数(0=全仓,正数=逐仓) |
+| leverage_max | Integer | 当前风险限额下允许的最大杠杆倍数 |
+| liq_price | Float | 爆仓价格 |
+| maintenance_rate | Float | 当前风险限额下维持保证金比例 |
+| margin | Float | 保证金 |
+| realised_pnl | Float | 已实现盈亏 |
+| realised_point | Float | 点卡已实现盈亏 |
+| risk_limit | Integer | 风险限额 |
+| time | Integer | 更新 unix 时间戳(秒) |
+| time_ms | Integer | 更新 unix 时间戳(毫秒) |
+| user | String | 用户 ID |
+| update_id | Integer | 消息序列号,每次推送 order 后自增1 |
+
+> 以上 20 个字段在 PositionsChannelHandler.handleMessage() 中通过 SLF4J 日志全部输出。
+> 回调给 GateGridTradeService.onPositionUpdate() 的仅有 mode、size、entryPrice 三个核心字段。
+
+---
+
+## GateChannelHandler 接口体系
+
+```
+GateChannelHandler (接口)
+ ├── CandlestickChannelHandler (公开频道)
+ └── AbstractPrivateChannelHandler (私有频道基类: HMAC-SHA512)
+ ├── PositionsChannelHandler (解析 mode → Position.ModeEnum,日志输出20个字段)
+ └── PositionClosesChannelHandler
+```
+
+- **subscribe**: 发送订阅请求。私有Handler自动附加 auth 字段
+- **unsubscribe**: 发送取消订阅请求(私有频道也带签名认证)
+- **handleMessage**: 解析推送数据并回调GateGridTradeService,返回true表示已处理
+- 消息路由: update/all事件 → 遍历channelHandlers → handler内部二次匹配channel名 → 匹配成功回调并停止遍历
+- **PositionsChannelHandler 特殊处理**: 推送的 mode 字符串("dual_long")通过 `Position.ModeEnum.fromValue()` 转为枚举
+
+---
+
+## 策略状态机
+
+```
+WAITING_KLINE ──onKline──→ OPENING ──双基底都成交──→ ACTIVE
+ │ │ │
+ │ 下单异常 ├─ 每根K线: 更新 unrealizedPnl
+ │ │ ├─ cumPnl ≥ overallTp → STOPPED
+ │ │ ├─ cumPnl ≤ -maxLoss → STOPPED
+ │ │ ├─ 保证金超限 → 跳过挂单,队列照常更新(止盈队列仍更新)
+ │ │ ├─ 方向区分 → processShortGrid 或 processLongGrid(二者选一)
+ │ │ ├─ 网格触发 → 匹配队列→更新队列→止盈入队→
+ │ │ │ 取消对方旧条件单→挂新多空条件单→反向条件单
+ │ │ └─ 仓位推送(净增张数) → 从止盈队列消费止盈价 →
+ │ │ 挂止盈条件单(plan-close-*-position)
+ ▼ ▼
+ STOPPED ←──────────────────┘
+```
+
+| 状态 | 含义 |
+|------|------|
+| `WAITING_KLINE` | 等待首次K线价格 |
+| `OPENING` | 正在异步开基底多空仓位(已提交到GateTradeExecutor) |
+| `ACTIVE` | 网格队列激活,K线触发网格 → 挂条件单 → 条件单成交后止盈 |
+| `STOPPED` | 停止(盈利达标 / 亏损超限) |
+
+---
+
+## 策略核心:网格队列 + 条件单 + 止盈队列
+
+### 概述
+
+策略采用"基底 + 价格网格队列"模式:先开一对基底多空仓位,然后以基底入场价为基准生成价格队列和止盈队列。每当K线穿破队列元素,匹配后更新队列、补充止盈队列、取消旧条件单并挂新条件单。仓位推送时从止盈队列消费止盈价并挂止盈条件单。
+
+### 条件单设计(核心)
+
+**为什么用条件单而不是限价单?**
+
+限价单 `price=X, tif=GTC` 在价格位于挂单价有利侧时**会立即成交**。例如:
+- 多仓队列元素都在市场价之上,挂限价多单会立刻以市价成交
+- 空仓队列元素都在市场价之下,挂限价空单会立刻以市价成交
+
+改用 Gate API `FuturesPriceTriggeredOrder`(价格触发条件单),由服务端监控价格,**只有当前价格抵达触发价时才执行**,避免提前成交。
+
+**条件单结构**:
+```
+FuturesPriceTriggeredOrder
+ ├─ trigger: { price=触发价, rule=NUMBER_1(≥) 或 NUMBER_2(≤), expiration=0(永久有效) }
+ ├─ initial: { contract, size(正=开多/负=开空), price="0", tif=IOC, reduce_only=false }
+ └─ order_type: strategy_type=NUMBER_0(价格触发), price_type=NUMBER_0(最新价)
+```
+
+**执行逻辑**:服务端监控 → 最新价达到触发价 → 以市价 IOC 开仓(price="0" + tif=IOC)。
+
+### 基底开仓
+
+```
+K线到达 → 双开基底(市价开多 + 市价开空,IOC)
+ → 成交回调: baseLongOpened=true, longActive=true
+ → 成交回调: baseShortOpened=true, shortActive=true
+ → 两者都成交 → generateShortQueue() + generateLongQueue()
+ + 止盈队列初始化 + 挂初始条件开仓单 → state=ACTIVE
+```
+
+### 止盈队列初始化
+
+基底队列生成后,两个止盈队列各填入一个元素:
+
+| 止盈队列 | 初始元素 | 排序 |
+|---------|---------|------|
+| 多仓止盈队列 longTakeProfitQueue | longPriceQueue[0] + step | 升序(小→大) |
+| 空仓止盈队列 shortTakeProfitQueue | shortPriceQueue[0] - step | 降序(大→小) |
+
+### 初始条件开仓单
+
+队列生成后立即用队列首元素挂两个价格触发条件单:
+
+| 方向 | 触发价 | rule | size | 说明 |
+|------|--------|------|------|------|
+| 多仓条件单 | longPriceQueue[0] | NUMBER_1 (≥触发价) | +quantity | 价格涨到触发价时开多 |
+| 空仓条件单 | shortPriceQueue[0] | NUMBER_2 (≤触发价) | -quantity | 价格跌到触发价时开空 |
+
+### 网格队列生成
+
+以空头基底入场价 `shortBaseEntryPrice` 为唯一基准,计算绝对步长 `step = shortBaseEntryPrice × gridRate`(保留1位小数),存入 config。
+
+两个队列均从 `shortBaseEntryPrice` 出发,按 `step` 绝对偏移生成 N 个价格(N = gridQueueSize,默认50):
+
+| 队列 | 计算方式 | 排序 |
+|------|---------|------|
+| 空仓队列 shortPriceQueue | 首元素 = shortBaseEntryPrice − step,后续依次 −step (i=0..N-1) | 降序(大→小) |
+| 多仓队列 longPriceQueue | 首元素 = shortBaseEntryPrice + step,后续依次 +step (i=0..N-1) | 升序(小→大) |
+
+### K线触发网格
+
+```
+K线到达(ACTIVE状态):
+│
+├─ closePrice > longPriceQueue[0] → processLongGrid(价格涨超队列首=最小价)
+│ ├─ 匹配: 收集所有 < closePrice 的多仓队列元素(升序,一旦遇≥即停止)
+│ ├─ 多仓队列: 移除 matched,尾部补充(尾价 + step 循环递增)
+│ ├─ 空仓队列转移:
+│ │ ├─ 以空仓队列首元素(最高价)为种子
+│ │ ├─ 生成 matched.size() 个递增元素: seed + step × i
+│ │ └─ 降序排列,截断到 gridQueueSize
+│ ├─ 止盈队列: longTakeProfitQueue.add(新 longPriceQueue[0] + step) → 升序排列
+│ ├─ 下单(队列已更新,避免竞态):
+│ │ ├─ 保证金检查: positionInitialMargin / initialPrincipal < marginRatioLimit(20%)
+│ │ │ ├─ 安全 →
+│ │ │ │ ├─ 挂新多仓条件单(触发价=新 long[0], rule=NUMBER_1, size=+qty)
+│ │ │ │ └─ 空仓条件单守卫: 新 short[0] > shortEntryPrice 时才执行
+│ │ │ │ ├─ 取消所有旧空仓条件单(currentShortOrderIds 遍历取消,清空集合)
+│ │ │ │ └─ 挂新空仓条件单(触发价=新 short[0], rule=NUMBER_2, size=-qty)
+│ │ │ │ └─ 不满足 → 旧空仓条件单保持不动
+│ │ │ └─ 超限 → 跳过挂单(队列和止盈队列照常更新)
+│ └─ 反向条件单:
+│ ├─ 条件: 新 long[0] > shortEntryPrice && 新 long[0] < longEntryPrice && shortPositionSize < 3
+│ ├─ 满足 → 挂反向条件空单(触发价=新 long[0], rule=NUMBER_2, size=-qty)
+│ └─ 同时: shortTakeProfitQueue.add(触发价 - step)
+│
+└─ closePrice < shortPriceQueue[0] → processShortGrid(价格跌穿队列首=最高价)
+ ├─ 匹配: 收集所有 > closePrice 的空仓队列元素(降序,一旦遇≤即停止)
+ ├─ 空仓队列: 移除 matched,尾部补充(尾价 − step 循环递减)
+ ├─ 多仓队列转移:
+ │ ├─ 以多仓队列首元素(最小价)为种子
+ │ ├─ 生成 matched.size() 个递减元素: seed − step × i
+ │ └─ 升序排列,截断到 gridQueueSize
+ ├─ 止盈队列: shortTakeProfitQueue.add(新 shortPriceQueue[0] − step) → 降序排列
+ ├─ 下单(队列已更新,避免竞态):
+ │ ├─ 保证金检查: 同上
+ │ │ ├─ 安全 →
+ │ │ │ ├─ 挂新空仓条件单(触发价=新 short[0], rule=NUMBER_2, size=-qty)
+ │ │ │ └─ 多仓条件单守卫: 新 long[0] < longEntryPrice 时才执行
+ │ │ │ ├─ 取消所有旧多仓条件单(currentLongOrderIds 遍历取消,清空集合)
+ │ │ │ └─ 挂新多仓条件单(触发价=新 long[0], rule=NUMBER_1, size=+qty)
+ │ │ │ └─ 不满足 → 旧多仓条件单保持不动
+ │ │ └─ 超限 → 跳过挂单(队列和止盈队列照常更新)
+ └─ 反向条件单:
+ ├─ 条件: 新 short[0] > shortEntryPrice && 新 short[0] < longEntryPrice && longPositionSize < 3
+ ├─ 满足 → 挂反向条件多单(触发价=新 short[0], rule=NUMBER_1, size=+qty)
+ └─ 同时: longTakeProfitQueue.add(触发价 + step)
+
+closePrice 既不 > longPriceQueue[0] 也不 < shortPriceQueue[0] → 跳过本次K线
+```
+
+> **一个K线只触发一个方向。** 例如 closePrice=2295 时 longPriceQueue[0]=2277.9<2295 → 仅触发 processLongGrid。
+> **只取消对方旧条件单。** 触发方向对应的旧条件单大概率已成交,只取消对方未成交的旧条件单。
+> **条件单 ID 用 List<String> 管理。** 由于反向条件单也需要被追踪和取消,用同步列表统一管理(`Collections.synchronizedList`)。
+
+### 队列转移规则
+
+触发后**不再简单复制** matched 元素到对方队列,而是以对方队列首元素为种子,按绝对步长 step 生成新元素:
+
+| 触发方向 | 目标队列 | 种子元素 | 生成公式 | 排序 |
+|---------|---------|---------|---------|------|
+| 空仓触发 → | 多仓队列 | 多仓队列首元素(最小价) | 种子 − step × i | 升序 |
+| 多仓触发 → | 空仓队列 | 空仓队列首元素(最高价) | 种子 + step × i | 降序 |
+
+### 反向条件单条件
+
+当新网格首元素价格夹在多/空持仓均价之间,且反向持仓张数不超过3张时,额外挂一张反向条件单:
+
+```
+newFirstPrice > shortEntryPrice // 价格在空仓均价之上
+AND newFirstPrice < longEntryPrice // 价格在多仓均价之下
+AND 反向持仓张数 < 3 // 最多同时持有3张反向仓位
+```
+
+满足条件时以 newFirstPrice 为触发价挂反向条件单,同时将 newFirstPrice ± step 加入对方止盈队列。
+
+### 条件单 ID 管理
+
+| 字段 | 类型 | 说明 |
+|------|------|------|
+| currentLongOrderIds | `List<String>` | 多仓条件单 ID 集合,同步列表 |
+| currentShortOrderIds | `List<String>` | 空仓条件单 ID 集合,同步列表 |
+
+每次网格触发时:
+1. 遍历对方方向的 `currentXxxOrderIds`,逐个调用 `cancelConditionalOrder` 取消
+2. 清空集合
+3. 挂新条件单,将新 ID 加入对应集合
+4. 如有反向条件单,其 ID 也加入对应方向集合
+
+### 队列转移示意
+
+```
+ETH_USDT, gridRate=0.0035, shortBaseEntryPrice=2270, step=2270×0.0035≈7.9, gridQueueSize=4:
+
+初始状态:
+ 空仓队列: [2262.1, 2254.2, 2246.3, 2238.4] (降序, shortBaseEntryPrice−step 起递减)
+ 多仓队列: [2277.9, 2285.8, 2293.7, 2301.6] (升序, shortBaseEntryPrice+step 起递增)
+ 多止盈队列: [2285.8] (longPriceQueue[0]+step)
+ 空止盈队列: [2254.2] (shortPriceQueue[0]−step)
+ 初始条件单: 多仓触发价=2277.9, 空仓触发价=2262.1
+
+价格涨到 2290 → processLongGrid 触发:
+ 匹配: [2277.9, 2285.8](都 < 2290)
+
+ 多仓队列: 移除[2277.9,2285.8] → [2293.7,2301.6]
+ 补充: max=2301.6 → 2301.6+7.9=2309.5 → 2309.5+7.9=2317.4
+ → [2293.7, 2301.6, 2309.5, 2317.4]
+
+ 空仓队列转移:
+ 种子=空仓首元素 2262.1
+ 生成: 2262.1+7.9=2270.0, 2262.1+7.9×2=2277.9
+ 空仓队列: [2262.1, 2270.0, 2277.9, 2254.2, 2246.3, 2238.4] → 截断到4 → [2277.9, 2270.0, 2262.1, 2254.2]
+
+ 止盈队列: longTakeProfitQueue.add(2293.7+7.9) = 2301.6
+ → [2285.8, 2301.6] (升序)
+
+ 取消旧空仓条件单(currentShortOrderIds) → 挂新多仓条件单(触发价=2293.7) + 新空仓条件单(触发价=2277.9)
+
+仓位推送(多单 2277.9 成交 → 条件单触发开仓):
+ long size: 1→2,增量1
+ 消费止盈队列: longTakeProfitQueue.remove(0) = 2285.8
+ 挂止盈单: triggerPrice=2285.8, rule=NUMBER_1, order_type=plan-close-long-position, size=-1
+ 止盈单执行: price="0", tif=IOC (触发后市价平仓)
```
---
@@ -70,174 +363,255 @@
### 阶段 1:启动与初始化
```
-Spring 启动
- → GateWebSocketClientManager.init()
- → GateGridTradeService.init()
- → REST: 设杠杆 30x cross
- → REST: 查账户余额
- → REST: 切双向持仓 dual
- → GateKlineWebSocketClient.init()
- → WebSocket: connect()
- → onOpen: subscribe candlesticks + positions + ping
- → GateGridTradeService.startGrid()
- → strategyActive = true
+Spring @PostConstruct
+ → GateConfig.builder()...build()
+ → GateGridTradeService(config)
+ → init():
+ 1. 查用户ID(用于私有频道订阅)
+ 2. 查账户 → 记录初始本金 initialPrincipal → 如需要切持仓模式
+ 3. 清除旧止盈止损条件单
+ 4. 查当前合约所有仓位 → 逐个市价平仓(reduce_only, IOC)
+ - 单向持仓: size=相反数平仓
+ - 双向持仓: size=0, close=false, autoSize=LONG/SHORT
+ 5. 设杠杆
+ → GateKlineWebSocketClient(config.getWsUrl())
+ → addChannelHandler x3 → init() → connect()
+ → onOpen: handlers依次subscribe → sendPing
+ → gridTradeService.startGrid() → state=WAITING_KLINE
```
-### 阶段 2:首次开仓
+### 阶段 2:基底开仓 → 生成网格队列 → 挂条件单
```
-K 线推送 closePrice=80000
- → onKline(80000)
- → dualOpened = true
- → dualOpenPositions()
- → REST: 市价开多 10 张 → longEntryPrice=80000
- → REST: 创建多头止盈单 TP=80000×1.0035=80280
- → REST: 市价开空 10 张 → shortEntryPrice=80000
- → REST: 创建空头止盈单 TP=80000×0.9965=79720
+K线推送 → onKline(closePrice) → state=OPENING
+ → executor.openLong(qty, onSuccess, onFailure)
+ → 成交 → 仓位推送: DUAL_LONG, size>0, entryPrice=X
+ → baseLongOpened=true, longBaseEntryPrice=X
+ → tryGenerateQueues(): 双基底都成交? → 生成队列+止盈队列+挂初始条件单 → state=ACTIVE
+ → executor.openShort(-qty, onSuccess, onFailure)
+ → 成交 → 仓位推送: DUAL_SHORT, size<0, entryPrice=Y
+ → baseShortOpened=true, shortBaseEntryPrice=Y
+ → tryGenerateQueues(): 双基底都成交? → 生成队列+止盈队列+挂初始条件单 → state=ACTIVE
```
-### 阶段 3:止盈触发 → 补仓
+### 阶段 3:ACTIVE 状态 — K线驱动网格 + 止盈队列消费
```
-仓位推送: mode=dual_long, size=0 (多头被止盈平掉了)
- → longActive=true && size=0
- → longActive=false
- → reopenLongPosition()
- → REST: 市价开多 10 张 (用最新 K 线价)
- → REST: 创建新的多头止盈单
+每根K线 → onKline → updateUnrealizedPnl → 方向区分(一个K线只触发一个方向)
-仓位推送: history_pnl=0.12 (未达阈值,继续)
+processShortGrid / processLongGrid:
+ → 匹配 → 队列转移 → 止盈入队 → 保证金检查
+ → 取消对方方向旧条件单(遍历 currentXxxOrderIds)
+ → 挂新多空条件单(FuturesPriceTriggeredOrder, price="0"+IOC)
+ → 条件满足时挂反向条件单 + 对方止盈入队
+
+条件单被触发成交后 → 仓位推送:
+ → 检测净增张数(newUnits = (currentSize - lastSize) / quantity)
+ → 逐个消费止盈队列:
+ tpPrice = takeProfitQueue.remove(0)(空时兜底: entryPrice ± step)
+ executor.placeTakeProfit(tpPrice, rule, plan-close-*-position, ±quantity)
+ → 止盈条件单: triggerPrice=止盈价, price="0", tif=IOC, reduce_only=true
+
+额外反向开仓(市价 IOC):
+ → 统一条件: newFirst > shortEntryPrice && newFirst < longEntryPrice && 反向张数 < 3
+ → 空仓触发 → 挂反向多仓条件单(触发价=新 short[0])
+ → 多仓触发 → 挂反向空仓条件单(触发价=新 long[0])
```
### 阶段 4:停止
```
-仓位推送: history_pnl ≥ 0.5 (累计盈利达标)
- → strategyActive = false → 不再补仓
-
-仓位推送: history_pnl ≤ -7.5 (亏损超限)
- → strategyActive = false → 不再补仓
+平仓推送: pnl=+0.6 → cumulativePnl=0.6 ≥ overallTp(0.5) → state=STOPPED
+平仓推送: pnl=-8.0 → cumulativePnl=-8.0 ≤ -maxLoss(7.5) → state=STOPPED
```
---
-## GateWebSocketClientManager
+## GateConfig
-**角色**: Spring Bean 入口,组装并管理所有 Gate 模块组件。
+**角色**: 统一配置中心。Builder模式管理所有参数,提供 REST/WS URL 环境自动切换。
-**关键方法**:
-- `init()`: 创建 `GateGridTradeService` → 初始化 → 创建 `GateKlineWebSocketClient` → 启动策略
-- `destroy()`: 停止策略 → 关闭 WebSocket
+**核心方法**:
+- `getRestBasePath()`: isProduction ? 生产网 : 测试网
+- `getWsUrl()`: 同上
-**当前参数**(硬编码在 `init()` 中):
+**配置项**(含默认值):
-| 参数 | 值 | 说明 |
-|------|-----|------|
-| 合约 | XAU_USDT | 黄金 |
-| 杠杆 | 30x | 全仓模式 |
-| 持仓模式 | dual | 双向持仓 |
-| 网格间距 | 0.0035 | 0.35% |
-| 整体止盈 | 0.5 USDT | |
-| 最大亏损 | 7.5 USDT | 本金 50×15% |
-| 下单量 | 10 张 | |
+| 参数 | 默认值 | 说明 |
+|------|--------|------|
+| contract | BTC_USDT | 合约 |
+| leverage | 10 | 倍数 |
+| marginMode | cross | 全仓 |
+| positionMode | dual | 双向持仓 |
+| gridRate | 0.0035 | 网格间距比率 0.35% |
+| step | 运行时计算 | 网格绝对步长 = shortBaseEntryPrice × gridRate(保留1位小数) |
+| overallTp | 0.5 USDT | 整体止盈 |
+| maxLoss | 7.5 USDT | 最大亏损 |
+| quantity | 1 | 下单张数 |
+| reopenMaxRetries | 3 | 补仓最大重试次数(当前版本未使用) |
+| gridQueueSize | 50 | 网格价格队列容量 |
+| marginRatioLimit | 0.2 | 保证金占初始本金比例上限(20%),超限跳过开仓 |
+| contractMultiplier | 0.001 | 合约乘数(单张合约代表的基础资产数量) |
+| unrealizedPnlPriceMode | LAST_PRICE | 未实现盈亏计价模式:LAST_PRICE / MARK_PRICE |
---
-## GateKlineWebSocketClient
+## GateTradeExecutor
-**角色**: WebSocket 客户端,订阅 Gate 的行情和仓位频道。
+**角色**: 独立线程池执行 REST API 下单。采用成功/失败双回调模式。
-**订阅频道**:
+**线程模型**:
+- `ThreadPoolExecutor(1, 1, 60s, LinkedBlockingQueue(64), CallerRunsPolicy)`
+- 单线程保序 + 有界队列防堆积 + CallerRuns背压
+- allowCoreThreadTimeOut: 60s 空闲后线程回收
-| 频道 | 类型 | 认证 | 用途 |
-|------|------|------|------|
-| `futures.candlesticks` | 公开 | 否 | 1m K 线数据 |
-| `futures.positions` | 私有 | HMAC-SHA512 | 用户仓位更新 |
-| `futures.ping` | 公开 | 否 | 应用层心跳 |
+**回调设计**:
+- `openLong`/`openShort`/`placeTakeProfit`/`placeConditionalEntryOrder` 接受 `onSuccess` 和 `onFailure` 两个 `Consumer<String>`
+- REST 调用成功 → 执行 `onSuccess`(标记基底已开、记录 orderId 等)
+- REST 调用失败 → 执行 `onFailure`(当前版本多为 null,依赖 position 推送修正)
-**签名算法**(`futures.positions` 订阅时使用):
+### 核心方法
-```
-message = "channel=futures.positions&event=subscribe&time={秒级时间戳}"
-SIGN = Hex(HmacSHA512(apiSecret, message))
-```
+| 方法 | 说明 |
+|------|------|
+| `openLong(qty, onSuccess, onFailure)` | 异步 IOC 市价开多,双回调 |
+| `openShort(qty, onSuccess, onFailure)` | 异步 IOC 市价开空,双回调 |
+| `placeConditionalEntryOrder(triggerPrice, rule, size, onSuccess, onFailure)` | 异步**条件开仓单**。triggerPrice=监控价,rule 决定触发方向,size 正=开多/负=开空。触发后 price="0" + IOC 市价成交 |
+| `cancelConditionalOrder(orderId)` | 异步取消指定条件单(orderId 为 null 时跳过) |
+| `placeTakeProfit(trigger, rule, orderType, size)` | 异步**止盈条件单**(plan-close-*-position)。triggerPrice=止盈触发价,触发后 price="0" + IOC 市价平仓,reduce_only=true |
+| `cancelAllPriceTriggeredOrders()` | 清除所有条件单 |
+| `shutdown()` | 等待10秒,超时强制关闭 |
-**连接管理**:
-- 心跳: 10 秒超时,每 25 秒检查,超时发 ping
-- 重连: 指数退避,最多 3 次,初始 5 秒
-- 关闭: 先取消订阅 → 等 500ms → 关闭连接 → 关闭线程池
+### 遗留方法(当前策略未使用)
-**消息路由** (`handleWebSocketMessage`):
+| 方法 | 说明 |
+|------|------|
+| `placeGridLimitOrder(price, size, onSuccess, onFailure)` | 旧版限价 GTC 单,已被条件单替代 |
+| `cancelOrder(orderId)` | 旧版取消限价单,已被 cancelConditionalOrder 替代 |
-| channel | event | 处理 |
-|---------|-------|------|
-| `futures.pong` | — | `cancelPongTimeout()` |
-| — | `subscribe` | 打日志 |
-| — | `unsubscribe` | 打日志 |
-| — | `error` | 打错误日志 |
-| `futures.candlesticks` | `update`/`all` | `processPushDataV2()` |
-| `futures.positions` | `update`/`all` | `processPositionData()` |
+### 条件单 order_type 说明
+
+| order_type | 用途 | size 语义 |
+|-----------|------|----------|
+| `plan-close-long-position` | 部分/全部平多仓 | size<0 表示平多仓张数 |
+| `plan-close-short-position` | 部分/全部平空仓 | size>0 表示平空仓张数 |
+
+> **为何不用 close-*-position**:`close-long-position` 和 `close-short-position` 仅支持全部平仓(size=0),且双仓模式还需设置 `auto_size`。网格策略需要指定张数部分平仓,因此必须使用 `plan-close-*-position`。
+
+### 条件单构建 (buildTriggeredOrder)
+
+`FuturesPriceTriggeredOrder` 结构:
+
+| 组件 | 字段 | 开仓单值 | 止盈单值 |
+|------|------|---------|---------|
+| trigger | price | 触发价 | 止盈价 |
+| trigger | rule | NUMBER_1(≥) 或 NUMBER_2(≤) | 同左 |
+| trigger | strategy_type | 0 (价格触发) | 0 (价格触发) |
+| trigger | price_type | 0 (最新价) | 0 (最新价) |
+| trigger | expiration | 0 (永久有效) | 0 (永久有效) |
+| initial | contract | 合约名 | 合约名 |
+| initial | size | +qty(开多)/-qty(开空) | -qty(平多)/+qty(平空) |
+| initial | price | "0" (市价) | "0" (市价) |
+| initial | tif | IOC | IOC |
+| initial | reduce_only | false | true |
+| order_type | plan-close-long-position 或 plan-close-short-position | 止盈时才设置 | 止盈时才设置 |
---
## GateGridTradeService
-**角色**: 使用 Gate SDK (`io.gate:gate-api:7.2.71`) 通过 REST API 执行合约下单。
+**角色**: 策略核心,管理网格队列状态和执行下单。
-**状态机**:
+**状态**: `StrategyState` enum: `WAITING_KLINE` / `OPENING` / `ACTIVE` / `STOPPED`
+**关键常量**:
+```java
+// 止盈条件单 order_type:仓位计划止盈止损,支持指定张数部分平仓
+private static final String ORDER_TYPE_CLOSE_LONG = "plan-close-long-position";
+private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position";
```
-strategyActive=false ──startGrid()──→ strategyActive=true (等待K线)
- │
- onKline(price)
- │
- dualOpened=true
- dualOpenPositions()
- │
- ┌───────────┴───────────┐
- ▼ ▼
- longActive=true shortActive=true
- │ │
- 仓位推送 size=0 仓位推送 size=0
- │ │
- ▼ ▼
- reopenLong() reopenShort()
- │ │
- └───────────┬───────────┘
- │
- checkStopConditions()
- │
- ┌───────────┴───────────┐
- ▼ ▼
- history_pnl≥0.5 history_pnl≤-7.5
- strategyActive=false strategyActive=false
-```
+
+**核心数据结构**:
+
+| 字段 | 类型 | 说明 |
+|------|------|------|
+| shortPriceQueue | `List<BigDecimal>` | 空仓价格队列,降序(大→小),容量 gridQueueSize |
+| longPriceQueue | `List<BigDecimal>` | 多仓价格队列,升序(小→大),容量 gridQueueSize |
+| longTakeProfitQueue | `List<BigDecimal>` | 多仓止盈队列,升序(小→大),仓位推送时消费 |
+| shortTakeProfitQueue | `List<BigDecimal>` | 空仓止盈队列,降序(大→小),仓位推送时消费 |
+| currentLongOrderIds | `List<String>` | 当前多仓条件单 ID 集合(同步列表,含反向单) |
+| currentShortOrderIds | `List<String>` | 当前空仓条件单 ID 集合(同步列表,含反向单) |
+| shortBaseEntryPrice | `BigDecimal` | 基底空头入场价(仅首次记录,用于生成队列) |
+| longBaseEntryPrice | `BigDecimal` | 基底多头入场价(仅首次记录,用于生成队列) |
+| shortEntryPrice | `BigDecimal` | 当前空仓入场价(推送实时更新,加权均价) |
+| longEntryPrice | `BigDecimal` | 当前多仓入场价(推送实时更新,加权均价) |
+| shortPositionSize | `BigDecimal` | 当前空仓持仓量(绝对值) |
+| longPositionSize | `BigDecimal` | 当前多仓持仓量 |
+| baseLongOpened | `boolean` | 基底多头是否已开 |
+| baseShortOpened | `boolean` | 基底空头是否已开 |
+| longActive / shortActive | `boolean` | 多/空方向是否持有仓位 |
+| cumulativePnl | `BigDecimal` | 累计已实现盈亏(平仓推送驱动) |
+| unrealizedPnl | `BigDecimal` | 未实现盈亏(每根K线更新,浮动盈亏) |
+| markPrice | `BigDecimal` | 标记价格(外部注入,MARK_PRICE 模式使用) |
+| initialPrincipal | `BigDecimal` | 初始本金(启动时账户总资产) |
+
+**回调方法**:
+
+| 方法 | 触发源 | 逻辑 |
+|------|--------|------|
+| `onKline(closePrice, timestamp)` | CandlestickChannelHandler | 更新 lastKlinePrice → 计算 unrealizedPnl → WAITING_KLINE 时触发基底双开 → ACTIVE 时方向区分,一个K线只触发一个方向 |
+| `onPositionUpdate(contract, mode, size, entryPrice)` | PositionsChannelHandler | 记录入场价和持仓量 → 基底首次成交记录入场价 + tryGenerateQueues → 非基底仓位净增时从止盈队列消费止盈价挂止盈条件单 |
+| `onPositionClose(contract, side, pnl)` | PositionClosesChannelHandler | 累加已实现盈亏 → 检查停止条件 |
+
+**processShortGrid / processLongGrid 核心逻辑**:
+
+| 步骤 | processShortGrid(空仓触发) | processLongGrid(多仓触发) |
+|------|---------------------------|---------------------------|
+| 匹配 | 收集 shortPriceQueue 中 > currentPrice 的元素 | 收集 longPriceQueue 中 < currentPrice 的元素 |
+| 本队补充 | 尾价 − step 循环递减 × matched.size() 次 | 尾价 + step 循环递增 × matched.size() 次 |
+| 对方转移 | 以多仓首元素为种子,递减 step × i | 以空仓首元素为种子,递增 step × i |
+| 止盈队列 | shortTakeProfitQueue.add(新 short[0] − step),降序 | longTakeProfitQueue.add(新 long[0] + step),升序 |
+| 取消旧单 | 遍历 currentLongOrderIds,逐个 cancelConditionalOrder | 遍历 currentShortOrderIds,逐个 cancelConditionalOrder |
+| 挂新条件单 | 空仓条件单(触发价=新 short[0]) + 多仓条件单(触发价=新 long[0]) | 多仓条件单(触发价=新 long[0]) + 空仓条件单(触发价=新 short[0]) |
+| 反向条件单 | 新 short[0] 在[shortEntryPrice, longEntryPrice]间且 longPositionSize<3 → 反向多单 | 新 long[0] 在[shortEntryPrice, longEntryPrice]间且 shortPositionSize<3 → 反向空单 |
+
+**未实现盈亏计算** (`updateUnrealizedPnl()`):
+
+正向合约公式(含合约乘数):
+
+| 方向 | 公式 |
+|------|------|
+| 多仓 | 持仓量 × contractMultiplier × (计价价格 − 开仓均价) |
+| 空仓 | 持仓量(绝对值)× contractMultiplier × (开仓均价 − 计价价格) |
+
+计价价格由 `unrealizedPnlPriceMode` 决定:
+- `LAST_PRICE`:使用最新成交价(`lastKlinePrice`,每根 K 线更新)
+- `MARK_PRICE`:使用标记价格(通过 `setMarkPrice()` 外部注入,如未注入则回退到最新成交价)
+
+入场价和持仓量由 `onPositionUpdate` 实时推送更新。
+
+**保证金安全阀** (`isMarginSafe()`):
+- 实时查询 `positionInitialMargin / initialPrincipal`
+- 比例 ≥ marginRatioLimit(默认20%)→ 跳过开仓,队列照常更新
+- REST 查询失败 → 默认放行(避免因查询异常阻塞策略)
**止盈计算**:
-| 方向 | 公式 | 触发条件 | order_type | auto_size |
-|------|------|----------|------------|-----------|
-| 多头 TP | entryPrice × 1.0035 | 最新价 ≥ 触发价 | `close-long-position` | `close_long` |
-| 空头 TP | entryPrice × 0.9965 | 最新价 ≤ 触发价 | `close-short-position` | `close_short` |
+| 方向 | 止盈价来源 | 兜底价 | order_type | rule |
+|------|-----------|--------|------------|------|
+| 多头 TP | longTakeProfitQueue.remove(0) | longEntryPrice + step | `plan-close-long-position` | NUMBER_1(≥触发价) |
+| 空头 TP | shortTakeProfitQueue.remove(0) | shortEntryPrice − step | `plan-close-short-position` | NUMBER_2(≤触发价) |
+
+> 止盈价从止盈队列消费。止盈队列由 K线触发时新增元素(新 queue[0] ± step),仓位推送时按每批 quantity 张数逐个消费。
+> 止盈队列空时兜底用当前入场价 ± step。每批挂独立止盈条件单,互不覆盖。
**REST API 调用**:
-| 操作 | API |
-|------|-----|
-| 设杠杆 | `POST /futures/usdt/positions/{contract}/leverage` |
-| 查账户 | `GET /futures/usdt/accounts` |
-| 设持仓模式 | `POST /futures/usdt/set_position_mode` |
-| 市价下单 | `POST /futures/usdt/orders` (price=0, tif=IOC) |
-| 止盈条件单 | `POST /futures/usdt/price_orders` |
-
----
-
-## GateWebSocketClientMain
-
-**角色**: 独立的 `main()` 方法入口,通过 Spring XML 上下文启动。
-
----
-
-## Example.java
-
-Gate SDK 使用示例,展示 `FuturesApi` 的基本用法:获取账户、设置仓位模式、设置杠杆。仅作参考,不参与实际策略运行。
+| 操作 | API | 方法 | 说明 |
+|------|-----|------|------|
+| 获取用户ID | `GET /account/detail` | `AccountApi.getAccountDetail()` | |
+| 切持仓模式 | `POST /futures/usdt/set_position_mode` | `FuturesApi.setPositionMode()` | |
+| 查仓位 | `GET /futures/usdt/positions` | `FuturesApi.listPositions()` | 遍历所有仓位,按合约过滤 |
+| 市价平仓 | `POST /futures/usdt/orders` | `FuturesApi.createFuturesOrder()` | reduce_only, IOC。双向: size=0+close=false+autoSize |
+| 设杠杆 | `POST /futures/usdt/dual_comp/positions/{contract}/leverage` | `FuturesApi.updateDualModePositionLeverageCall()` | 双向模式专用 |
+| 查账户 | `GET /futures/usdt/accounts` | `FuturesApi.listFuturesAccounts()` | 获取初始
\ No newline at end of file
--
Gitblit v1.9.1