Administrator
3 days ago c270dd43ad17bfc2f51f6ebb4f4143e912b9673a
src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
@@ -7,8 +7,8 @@
| [GateWebSocketClientManager](#gatewebsocketclientmanager) | `@Component` | Spring 启动入口,组装组件 + 生命周期 |
| [GateConfig](#gateconfig) | 配置 | Builder 模式:API 密钥、合约、策略参数、环境切换 |
| [GateKlineWebSocketClient](#gateklinewebsocketclient) | WS 连接管理 | 连接/心跳/重连/消息路由 |
| [GateGridTradeService](#gategridtradeservice) | 交易服务 | 网格策略状态机 + 盈亏管理 |
| [GateTradeExecutor](#gatetradeexecutor) | 异步执行器 | 独立线程池执行 REST 下单,不阻塞 WS 回调线程 |
| [GateGridTradeService](#gategridtradeservice) | 交易服务 | 网格队列策略 + 保证金安全阀 + 盈亏管理 |
| [GateTradeExecutor](#gatetradeexecutor) | 异步执行器 | 独立线程池执行 REST 下单,成功/失败双回调 |
| [GateWebSocketClientMain](#gatewebsocketclientmain) | main 入口 | 独立测试启动 |
| [Example.java](#examplejava) | 示例 | Gate SDK 用法参考 |
@@ -19,7 +19,7 @@
| `wsHandler/GateChannelHandler.java` | **接口** | subscribe / unsubscribe / handleMessage / getChannelName |
| `wsHandler/AbstractPrivateChannelHandler.java` | **抽象类** | 私有频道基类:HMAC-SHA512 签名 + 认证请求 |
| `wsHandler/handler/CandlestickChannelHandler.java` | 公开频道 | K 线解析 → `onKline()` |
| `wsHandler/handler/PositionsChannelHandler.java` | 私有频道 | 仓位推送 → `onPositionUpdate()` |
| `wsHandler/handler/PositionsChannelHandler.java` | 私有频道 | 仓位推送 → `onPositionUpdate()`(传 `Position.ModeEnum`) |
| `wsHandler/handler/PositionClosesChannelHandler.java` | 私有频道 | 平仓推送 → `onPositionClose()` |
---
@@ -36,7 +36,7 @@
│     │ REST BasePath           │ GateTradeExecutor    │ WS URL    │
│     ▼                         ▼                      ▼           │
│  Gate API (REST)        独立线程池 (async)     Gate WebSocket     │
│                                               ┌──────────────┐  │
│                      onSuccess/onFailure双回调  ┌──────────────┐  │
│                                               │Candlestick H  │  │
│                                               │Positions H    │  │
│                                               │PosCloses H    │  │
@@ -57,23 +57,27 @@
├─ futures.candlesticks (公开)
│   └─ CandlestickChannelHandler
│       └─ gridTradeService.onKline(closePx)
│           ├─ state=WAITING_KLINE → 异步双开 + 止盈单
│           └─ 后续 → 仅缓存 lastKlinePrice
│           ├─ 更新 unrealizedPnl(浮动盈亏)
│           ├─ state=WAITING_KLINE → 异步双开基底仓位
│           └─ state=ACTIVE → processShortGrid/processLongGrid 网格触发
├─ futures.positions (私有, HMAC-SHA512)
│   └─ PositionsChannelHandler
│       └─ gridTradeService.onPositionUpdate(mode, size, entryPrice)
│           ├─ size=0 && longActive → tryReopenLong()
│           └─ size=0 && shortActive → tryReopenShort()
│       ├─ 解析 mode → Position.ModeEnum(DUAL_LONG / DUAL_SHORT)
│       └─ gridTradeService.onPositionUpdate(contract, mode, size, entryPrice)
│           ├─ 有仓位: 标记活跃,首次成交记录入场价并设止盈
│           │   ├─ 基底开仓 → 首次成交 → 记录基底入场价 → 双基底都成交后生成网格队列
│           │   └─ 网格开仓 → 成交后立即设止盈单
│           └─ 无仓位(size=0): 标记不活跃
├─ futures.position_closes (私有, HMAC-SHA512)
│   └─ PositionClosesChannelHandler
│       └─ gridTradeService.onPositionClose(side, pnl)
│       └─ gridTradeService.onPositionClose(contract, side, pnl)
│           └─ cumulativePnl += pnl → checkStopConditions()
└─ 所有下单操作
    └─ GateTradeExecutor (单线程 + 64队列 + CallerRunsPolicy)
        ├─ openLong/openShort → 市价单 (REST)
        ├─ openLong/Short(qty, onSuccess, onFailure)
        └─ placeTakeProfit → 条件单 (REST)
```
@@ -85,7 +89,7 @@
GateChannelHandler (接口)
  ├── CandlestickChannelHandler          (公开频道)
  └── AbstractPrivateChannelHandler      (私有频道基类: HMAC-SHA512)
        ├── PositionsChannelHandler
        ├── PositionsChannelHandler       (解析 mode → Position.ModeEnum)
        └── PositionClosesChannelHandler
```
@@ -93,73 +97,152 @@
- **unsubscribe**: 发送取消订阅请求(私有频道也带签名认证)
- **handleMessage**: 解析推送数据并回调GateGridTradeService,返回true表示已处理
- 消息路由: update/all事件 → 遍历channelHandlers → handler内部二次匹配channel名 → 匹配成功回调并停止遍历
- **PositionsChannelHandler 特殊处理**: 推送的 mode 字符串("dual_long")通过 `Position.ModeEnum.fromValue()` 转为枚举
---
## 策略状态机
```
WAITING_KLINE ──onKline──→ OPENING ──双开成功──→ ACTIVE
     │                        │                     │
     │                    双开失败             ├─ size=0 → REOPENING_L/S → ACTIVE
     │                                         ├─ 补仓失败 retry → 仍失败 → STOPPED
     │                                         └─ cumulativePnl≥TP 或 ≤-maxLoss → STOPPED
     ▼
   STOPPED ←─────────────────────────────────────────┘
WAITING_KLINE ──onKline──→ OPENING ──双基底都成交──→ ACTIVE
     │                        │                         │
     │                    下单异常               ├─ 每根K线: 更新 unrealizedPnl
     │                        │                 ├─ cumPnl ≥ overallTp → STOPPED
     │                        │                 ├─ cumPnl ≤ -maxLoss → STOPPED
     │                        │                 ├─ 保证金超限 → 跳过开仓,队列照常更新
     │                        │                 └─ 网格触发 → 开仓+设止盈+队列转移
     ▼                        ▼
   STOPPED  ←──────────────────┘
```
| 状态 | 含义 |
|------|------|
| `WAITING_KLINE` | 等待首次K线价格 |
| `OPENING` | 正在异步双开(开多+开空已提交到GateTradeExecutor) |
| `ACTIVE` | 网格运行中,等待止盈触发 |
| `REOPENING_LONG` | 正在补开多头 |
| `REOPENING_SHORT` | 正在补开空头 |
| `STOPPED` | 停止(盈利达标 / 亏损超限 / 异常退出) |
| `OPENING` | 正在异步开基底多空仓位(已提交到GateTradeExecutor) |
| `ACTIVE` | 网格队列激活,K线触发网格元素 → 开仓+止盈 |
| `STOPPED` | 停止(盈利达标 / 亏损超限) |
---
## 策略核心:网格队列机制
### 概述
策略采用"基底 + 价格网格队列"模式:先开一对基底多空仓位,然后以基底入场价为基准生成价格队列。每当K线穿破队列元素,就开新仓位并设止盈条件单,同时将穿破的元素转移到反方向队列。
### 基底开仓
```
K线到达 → 双开基底(市价开多 + 市价开空)
  → 成交回调: baseLongOpened=true, longActive=true
  → 成交回调: baseShortOpened=true, shortActive=true
  → 两者都成交 → generateShortQueue() + generateLongQueue() → state=ACTIVE
```
### 网格队列生成
以基底入场价为基准,按 `gridRate`(百分比步长)生成 N 个价格(N = gridQueueSize,默认50):
| 队列 | 计算方式 | 排序 |
|------|---------|------|
| 空仓队列 shortPriceQueue | 基底空入场价 × (1 − gridRate × i) (i=1..N) | 降序(大→小) |
| 多仓队列 longPriceQueue | 基底多入场价 × (1 + gridRate × i) (i=1..N) | 升序(小→大) |
### K线触发网格
```
K线到达(ACTIVE状态):
├─ processShortGrid: 当前价 < 空仓队列元素(价格跌破了队列中的高价)
│   ├─ 匹配: 收集所有 > 当前价的空仓队列元素
│   ├─ 保证金检查: positionInitialMargin / initialPrincipal < marginRatioLimit(20%)
│   │   ├─ 安全 → openShort 开空单(成交后仓位推送会自动设止盈)
│   │   └─ 超限 → 跳过开仓,队列照常更新
│   ├─ 空仓队列: 移除匹配元素,尾部补充新价格(尾价 × (1 − gridRate))
│   └─ 多仓队列: 接收匹配元素,升序排列,截断到 gridQueueSize
└─ processLongGrid: 当前价 > 多仓队列元素(价格涨超了队列中的低价)
    ├─ 匹配: 收集所有 < 当前价的多仓队列元素
    ├─ 保证金检查: 同上
    │   ├─ 安全 → openLong 开多单
    │   └─ 超限 → 跳过开仓
    ├─ 多仓队列: 移除匹配元素,尾部补充新价格(尾价 × (1 + gridRate))
    └─ 空仓队列: 接收匹配元素,降序排列,截断到 gridQueueSize
```
### 队列转移示意
```
ETH_USDT, gridRate=0.0035, 基底空入场价=2275, 基底多入场价=2275:
初始状态:
  空仓队列: [2267.1, 2270.0, 2272.5, 2275.0]  (降序,base×0.9965, base×0.993...)
  多仓队列: [2275.0, 2277.5, 2280.0, 2282.5]  (升序,base×1.0035, base×1.007...)
价格跌到 2271 → processShortGrid 触发:
  匹配: [2275.0, 2272.5](都 > 2271)
  空仓队列: 移除[2275.0,2272.5] → [2270.0,2267.1] → 补充[2267.1×0.9965≈2259.1, 2259.1×0.9965≈2251.2] → [2270.0,2267.1,2259.1,2251.2]
  多仓队列: 接收[2275.0,2272.5] → 合并后截断到4 → [2272.5,2275.0,2277.5,2280.0]
```
---
## 策略时序
### 阶段 1:启动
### 阶段 1:启动与初始化
```
Spring @PostConstruct
  → GateConfig.builder()...build()
  → GateGridTradeService(config)
    → init(): 查ID → 查账户切持仓 → 清旧条件单 → 平已有仓位 → 设杠杆
    → 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线推送 → onKline(closePrice) → state=OPENING
  → GateTradeExecutor.openLong → 市价开多 → onSuccess: longActive=true, 下TP单
  → GateTradeExecutor.openShort → 市价开空 → onSuccess: shortActive=true, 下TP单
  → 双开均完成 → state=ACTIVE
  → 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线驱动网格
```
仓位推送: dual_long, size=0 → longActive且无仓位 → tryReopenLong
  → GateTradeExecutor.openLong → 市价补多 → onSuccess: 下新TP单
每根K线 → onKline → updateUnrealizedPnl → processShortGrid + processLongGrid
仓位推送: dual_short, size=0 → shortActive且无仓位 → tryReopenShort
  → GateTradeExecutor.openShort → 市价补空 → onSuccess: 下新TP单
仓位推送(每次开仓成交后自动触发):
  → DUAL_LONG, size>0, 非基底 → 设多头止盈单:止盈价=entryPrice×(1+gridRate),平仓张数=quantity(负=平多)
  → DUAL_SHORT, size<0, 非基底 → 设空头止盈单:止盈价=entryPrice×(1−gridRate),平仓张数=quantity(正=平空)
```
> 止盈由 Gate 服务端条件单自动执行。只补被平掉的单方向,另一方不受影响。
> 止盈由 Gate 服务端条件单自动执行。服务端监控价格,达到触发价后自动平仓。
> 每次网格触发开仓 quantity 张,只在该批张数上设止盈,与之前已设的止盈单互不影响。
> 平仓后仓位减少 quantity 张,盈亏通过 position_closes 频道推送到 cumulativePnl。
### 阶段 4:停止
```
平仓推送: pnl=+0.6 → cumulativePnl=0.6 ≥ overallTp → state=STOPPED
平仓推送: pnl=-8.0 → cumulativePnl=-8.0 ≤ -maxLoss → state=STOPPED
平仓推送: pnl=+0.6 → cumulativePnl=0.6 ≥ overallTp(0.5) → state=STOPPED
平仓推送: pnl=-8.0 → cumulativePnl=-8.0 ≤ -maxLoss(7.5) → state=STOPPED
```
---
@@ -184,23 +267,33 @@
| overallTp | 0.5 USDT | 整体止盈 |
| maxLoss | 7.5 USDT | 最大亏损 |
| quantity | 1 | 下单张数 |
| reopenMaxRetries | 3 | 补仓重试次数 |
| reopenMaxRetries | 3 | 补仓最大重试次数(当前版本未使用) |
| gridQueueSize | 50 | 网格价格队列容量 |
| marginRatioLimit | 0.2 | 保证金占初始本金比例上限(20%),超限跳过开仓 |
| contractMultiplier | 0.001 | 合约乘数(单张合约代表的基础资产数量) |
| unrealizedPnlPriceMode | LAST_PRICE | 未实现盈亏计价模式:LAST_PRICE / MARK_PRICE |
---
## GateTradeExecutor
**角色**: 独立线程池执行 REST API 下单,解决 WebSocket 回调线程阻塞问题。
**角色**: 独立线程池执行 REST API 下单。采用成功/失败双回调模式。
**线程模型**:
- `ThreadPoolExecutor(1, 1, 60s, LinkedBlockingQueue(64), CallerRunsPolicy)`
- 单线程保序 + 有界队列防堆积 + CallerRuns背压
- allowCoreThreadTimeOut: 60s 空闲后线程回收
**回调设计**:
- 每个下单方法接受 `onSuccess` 和 `onFailure` 两个 `Runnable`
- REST 调用成功 → 执行 `onSuccess`(标记基底已开等)
- REST 调用失败 → 执行 `onFailure`(当前版本多为 null,依赖 position 推送修正)
| 方法 | 说明 |
|------|------|
| `openLong(qty, onSuccess)` | 异步 IOC 市价开多,成功回调 |
| `openShort(qty, onSuccess)` | 异步 IOC 市价开空 |
| `placeTakeProfit(trigger, rule, type, auto)` | 异步条件单。已存在则清除旧单重试 |
| `openLong(qty, onSuccess, onFailure)` | 异步 IOC 市价开多,双回调 |
| `openShort(qty, onSuccess, onFailure)` | 异步 IOC 市价开空,双回调 |
| `placeTakeProfit(trigger, rule, type, size)` | 异步止盈条件单。size 为显式平仓张数(正=平空,负=平多),多次调用互不影响 |
| `cancelAllPriceTriggeredOrders()` | 清除所有条件单 |
| `shutdown()` | 等待10秒,超时强制关闭 |
@@ -208,48 +301,100 @@
## GateGridTradeService
**角色**: 策略核心,使用 Gate SDK 管理状态和执行下单。
**角色**: 策略核心,管理网格队列状态和执行下单。
**状态**: StrategyState enum + longActive/shortActive boolean
**状态**: `StrategyState` enum: `WAITING_KLINE` / `OPENING` / `ACTIVE` / `STOPPED`
**关键常量**:
```java
private static final String ORDER_TYPE_CLOSE_LONG = "close-long-position";
private static final String ORDER_TYPE_CLOSE_SHORT = "close-short-position";
```
**核心数据结构**:
| 字段 | 类型 | 说明 |
|------|------|------|
| shortPriceQueue | List\<BigDecimal\> | 空仓价格队列,降序(大→小),容量 gridQueueSize |
| longPriceQueue | List\<BigDecimal\> | 多仓价格队列,升序(小→大),容量 gridQueueSize |
| 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)`: 缓存价格,WAITING_KLINE状态下首次触发双开
- `onPositionUpdate(mode, size, entryPrice)`: size=0且方向活跃 → 补仓
- `onPositionClose(side, pnl)`: 累加盈亏,检查停止条件
- `onKline(closePrice)`: 更新 lastKlinePrice → 计算 unrealizedPnl → WAITING_KLINE 时触发基底双开,ACTIVE 时驱动 processShortGrid+processLongGrid
- `onPositionUpdate(contract, mode, size, entryPrice)`: 记录当前入场价和持仓量 → 基底:首次成交记录入场价、生成队列;非基底:按 quantity 张数创建独立止盈条件单。无仓位时清空持仓量并标记不活跃
- `onPositionClose(contract, side, pnl)`: 累加已实现盈亏,检查停止条件
**未实现盈亏计算** (`updateUnrealizedPnl()`):
正向合约公式(含合约乘数):
| 方向 | 公式 |
|------|------|
| 多仓 | 持仓量 × contractMultiplier × (计价价格 − 开仓均价) |
| 空仓 | 持仓量(绝对值)× contractMultiplier × (开仓均价 − 计价价格) |
计价价格由 `unrealizedPnlPriceMode` 决定:
- `LAST_PRICE`:使用最新成交价(`lastKlinePrice`,每根 K 线更新)
- `MARK_PRICE`:使用标记价格(通过 `setMarkPrice()` 外部注入,如未注入则回退到最新成交价)
入场价和持仓量由 `onPositionUpdate` 实时推送更新。
**保证金安全阀** (`isMarginSafe()`):
- 实时查询 `positionInitialMargin / initialPrincipal`
- 比例 ≥ marginRatioLimit(默认20%)→ 跳过开仓,队列照常更新
- REST 查询失败 → 默认放行(避免因查询异常阻塞策略)
**止盈计算**:
| 方向 | 公式 | order_type | auto_size |
|------|------|------------|-----------|
| 多头 TP | entry × (1+gridRate) | `close-long-position` | `close_long` |
| 空头 TP | entry × (1-gridRate) | `close-short-position` | `close_short` |
| 方向 | 公式 | order_type | size(平仓张数) | rule |
|------|------|------------|-----------|------|
| 多头 TP | entry × (1+gridRate) | `close-long-position` | `-quantity`(负=平多) | NUMBER_1(≥触发价) |
| 空头 TP | entry × (1−gridRate) | `close-short-position` | `+quantity`(正=平空) | NUMBER_2(≤触发价) |
> 止盈单使用显式张数而非 autoSize。每次网格触发开仓 quantity 张,只为该批张数创建独立的条件单,多个止盈单之间互不覆盖。
**REST API 调用**:
| 操作 | 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` (reduce_only, IOC) | `FuturesApi.createFuturesOrder()` |
| 设杠杆 | `POST /futures/usdt/positions/{contract}/leverage` | `FuturesApi.updateContractPositionLeverageCall()` |
| 查账户 | `GET /futures/usdt/accounts` | `FuturesApi.listFuturesAccounts()` |
| 清除条件单 | `DELETE /futures/usdt/price_orders` | `FuturesApi.cancelPriceTriggeredOrderList()` |
| 市价单 | `POST /futures/usdt/orders` (price=0, IOC) | `FuturesApi.createFuturesOrder()` |
| 条件单 | `POST /futures/usdt/price_orders` | `FuturesApi.createPriceTriggeredOrder()` |
| 操作 | 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()` | 获取初始本金和保证金 |
| 清除条件单 | `DELETE /futures/usdt/price_orders` | `FuturesApi.cancelPriceTriggeredOrderList()` | |
| 市价单 | `POST /futures/usdt/orders` | `FuturesApi.createFuturesOrder()` | price=0, tif=IOC |
| 条件单 | `POST /futures/usdt/price_orders` | `FuturesApi.createPriceTriggeredOrder()` | strategy=0, price_type=0, expiration=0, size=显式张数(非autoSize),多次调用互不冲突 |
**初始化顺序** (`init()`):
```
1. 获取用户 ID
2. 查账户 → 如需要切持仓模式
2. 查账户 → 记录初始本金 → 如需要切持仓模式
3. 清除旧的止盈止损条件单
4. 市价平掉当前合约所有已有仓位(确保从零持仓开始)
4. 查当前合约所有仓位 → 逐个市价平仓
   - 单向持仓(single): size=相反数, reduce_only=true
   - 双向持仓(dual): size=0, close=false, autoSize=LONG/SHORT, reduce_only=true
5. 设杠杆
6. 打印账户余额
```
---
## GateWebSocketClientMain
独立 `main()` 方法入口,通过 Spring XML 上下文启动,运行后手动关闭。
---