Administrator
4 days ago 01da1f754426a1285fc20b9cf1b80672b16d8814
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`) |
| `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,31 +49,78 @@
## 数据流
```
WebSocket 推送
WebSocket → GateKlineWebSocketClient.handleMessage → 路由 dispatch
├─ futures.candlesticks (update)
│   └─ GateKlineWebSocketClient.processPushDataV2()
│       ├─ 解析: o/h/l/c/v/a/t/w
│       ├─ 打印 K 线日志
│       └─ GateGridTradeService.onKline(closePx)
│           ├─ 首次 → dualOpenPositions() → 开多 + 开空 + TP 单
├─ futures.pong → cancelPongTimeout
├─ subscribe / unsubscribe / error → log
├─ futures.candlesticks (公开)
│   └─ CandlestickChannelHandler
│       └─ gridTradeService.onKline(closePx)
│           ├─ state=WAITING_KLINE → 异步双开 + 止盈单
│           └─ 后续 → 仅缓存 lastKlinePrice
├─ 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.positions (私有, HMAC-SHA512)
│   └─ PositionsChannelHandler
│       ├─ 解析 mode → Position.ModeEnum(DUAL_LONG / DUAL_SHORT)
│       └─ gridTradeService.onPositionUpdate(mode, size, entryPrice)
│           ├─ DUAL_LONG, size=0 && longActive → tryReopenLong()
│           └─ DUAL_SHORT, size=0 && shortActive → tryReopenShort()
├─ futures.pong
│   └─ cancelPongTimeout()
├─ futures.position_closes (私有, HMAC-SHA512)
│   └─ PositionClosesChannelHandler
│       └─ gridTradeService.onPositionClose(side, pnl)
│           └─ cumulativePnl += pnl → checkStopConditions()
└─ subscribe/unsubscribe/error
    └─ 日志输出
└─ 所有下单操作
    └─ GateTradeExecutor (单线程 + 64队列 + CallerRunsPolicy)
        ├─ openLong/Short(qty, onSuccess, onFailure)
        │   └─ 失败回调 → tryReopenXxx() 递归重试
        └─ placeTakeProfit → 条件单 (REST)
```
---
## GateChannelHandler 接口体系
```
GateChannelHandler (接口)
  ├── CandlestickChannelHandler          (公开频道)
  └── AbstractPrivateChannelHandler      (私有频道基类: HMAC-SHA512)
        ├── PositionsChannelHandler       (解析 mode → Position.ModeEnum)
        └── 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
     │                        │                     │
     │                    双开失败             ├─ size=0 → REOPENING_L/S
     │                                         │   ├─ 补仓成功 → ACTIVE
     │                                         │   └─ 补仓失败 → 递归重试
     │                                         │       └─ 超 reopenMaxRetries → STOPPED
     │                                         └─ cumPnl≥TP 或 ≤-maxLoss → STOPPED
     ▼
   STOPPED ←─────────────────────────────────────────┘
```
| 状态 | 含义 |
|------|------|
| `WAITING_KLINE` | 等待首次K线价格 |
| `OPENING` | 正在异步双开(开多+开空已提交到GateTradeExecutor) |
| `ACTIVE` | 网格运行中,等待止盈触发 |
| `REOPENING_LONG` | 正在补开多头 |
| `REOPENING_SHORT` | 正在补开空头 |
| `STOPPED` | 停止(盈利达标 / 亏损超限 / 补仓重试耗尽 / 异常退出) |
---
@@ -70,174 +129,178 @@
### 阶段 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. 查账户 → 如需要切持仓模式
      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:首次开仓
```
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
  → GateTradeExecutor.openLong(qty, onSuccess, null)
    → 市价开多 → onSuccess: longActive=true, placeTakeProfit(多头TP)
  → GateTradeExecutor.openShort(-qty, onSuccess, null)
    → 市价开空 → onSuccess: shortActive=true, placeTakeProfit(空头TP)
  → 双开均完成 → state=ACTIVE
```
### 阶段 3:止盈触发 → 补仓
### 阶段 3:止盈触发 → 补仓(含重试)
```
仓位推送: mode=dual_long, size=0  (多头被止盈平掉了)
  → longActive=true && size=0
    → longActive=false
    → reopenLongPosition()
      → REST: 市价开多 10 张 (用最新 K 线价)
      → REST: 创建新的多头止盈单
仓位推送: mode=DUAL_LONG, size=0 → longActive且无仓位 → tryReopenLong()
  ┌─ longReopenFails++  → 超 reopenMaxRetries → STOPPED
  └─ GateTradeExecutor.openLong(qty,
        onSuccess: failCount=0, ACTIVE, 下新TP单,
        onFailure: → 递归调用 tryReopenLong() 再试
     )
仓位推送: history_pnl=0.12  (未达阈值,继续)
仓位推送: mode=DUAL_SHORT, size=0 → 同理 tryReopenShort()
```
> 止盈由 Gate 服务端条件单自动执行。只补被平掉的单方向,另一方不受影响。
> 补仓失败通过 onFailure 回调递归重试,连续失败超过 `reopenMaxRetries`(默认3次)则停止策略。
### 阶段 4:停止
```
仓位推送: history_pnl ≥ 0.5 (累计盈利达标)
  → strategyActive = false  → 不再补仓
仓位推送: history_pnl ≤ -7.5 (亏损超限)
  → strategyActive = false  → 不再补仓
平仓推送: pnl=+0.6 → cumulativePnl=0.6 ≥ overallTp → state=STOPPED
平仓推送: pnl=-8.0 → cumulativePnl=-8.0 ≤ -maxLoss → state=STOPPED
补仓连续失败 4 次 → 超过 reopenMaxRetries=3 → 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% |
| overallTp | 0.5 USDT | 整体止盈 |
| maxLoss | 7.5 USDT | 最大亏损 |
| quantity | 1 | 下单张数 |
| reopenMaxRetries | 3 | 补仓最大重试次数 |
---
## GateKlineWebSocketClient
## GateTradeExecutor
**角色**: WebSocket 客户端,订阅 Gate 的行情和仓位频道。
**角色**: 独立线程池执行 REST API 下单。采用成功/失败双回调模式支持补仓重试。
**订阅频道**:
**线程模型**:
- `ThreadPoolExecutor(1, 1, 60s, LinkedBlockingQueue(64), CallerRunsPolicy)`
- 单线程保序 + 有界队列防堆积 + CallerRuns背压
| 频道 | 类型 | 认证 | 用途 |
|------|------|------|------|
| `futures.candlesticks` | 公开 | 否 | 1m K 线数据 |
| `futures.positions` | 私有 | HMAC-SHA512 | 用户仓位更新 |
| `futures.ping` | 公开 | 否 | 应用层心跳 |
**回调设计**:
- 每个下单方法接受 `onSuccess` 和 `onFailure` 两个 `Runnable`
- REST 调用成功 → 执行 `onSuccess`(更新状态、下止盈单、重置失败计数)
- REST 调用失败 → 执行 `onFailure`(递归重试入口)
**签名算法**(`futures.positions` 订阅时使用):
```
message = "channel=futures.positions&event=subscribe&time={秒级时间戳}"
SIGN = Hex(HmacSHA512(apiSecret, message))
```
**连接管理**:
- 心跳: 10 秒超时,每 25 秒检查,超时发 ping
- 重连: 指数退避,最多 3 次,初始 5 秒
- 关闭: 先取消订阅 → 等 500ms → 关闭连接 → 关闭线程池
**消息路由** (`handleWebSocketMessage`):
| channel | event | 处理 |
|---------|-------|------|
| `futures.pong` | — | `cancelPongTimeout()` |
| — | `subscribe` | 打日志 |
| — | `unsubscribe` | 打日志 |
| — | `error` | 打错误日志 |
| `futures.candlesticks` | `update`/`all` | `processPushDataV2()` |
| `futures.positions` | `update`/`all` | `processPositionData()` |
| 方法 | 说明 |
|------|------|
| `openLong(qty, onSuccess, onFailure)` | 异步 IOC 市价开多,双回调 |
| `openShort(qty, onSuccess, onFailure)` | 异步 IOC 市价开空,双回调 |
| `placeTakeProfit(trigger, rule, type, auto)` | 异步条件单。已存在则清除旧单重试 |
| `cancelAllPriceTriggeredOrders()` | 清除所有条件单 |
| `shutdown()` | 等待10秒,超时强制关闭 |
---
## GateGridTradeService
**角色**: 使用 Gate SDK (`io.gate:gate-api:7.2.71`) 通过 REST API 执行合约下单。
**角色**: 策略核心,使用 Gate SDK 管理状态和执行下单。
**状态机**:
**状态**: `StrategyState` enum + `longActive`/`shortActive` boolean
**关键常量**(替代字面字符串):
```java
private static final String AUTO_SIZE_LONG = "close_long";
private static final String AUTO_SIZE_SHORT = "close_short";
private static final String ORDER_TYPE_CLOSE_LONG = "close-long-position";
private static final String ORDER_TYPE_CLOSE_SHORT = "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
**回调方法**:
- `onKline(closePrice)`: 缓存价格,WAITING_KLINE状态下首次触发双开
- `onPositionUpdate(Position.ModeEnum mode, size, entryPrice)`: `== DUAL_LONG/DUAL_SHORT` 枚举比较,size=0且方向活跃 → 补仓重试
- `onPositionClose(side, pnl)`: 累加盈亏,检查停止条件
**补仓重试逻辑**:
```
tryReopenLong():
  1. longReopenFails++(失败计数递增)
  2. 超过 reopenMaxRetries → STOPPED
  3. openLong(qty,
       onSuccess → failCount=0, ACTIVE, 下新TP单,
       onFailure → 递归 tryReopenLong() 重试
     )
```
**止盈计算**:
| 方向 | 公式 | 触发条件 | order_type | auto_size |
|------|------|----------|------------|-----------|
| 多头 TP | entryPrice × 1.0035 | 最新价 ≥ 触发价 | `close-long-position` | `close_long` |
| 空头 TP | entryPrice × 0.9965 | 最新价 ≤ 触发价 | `close-short-position` | `close_short` |
| 方向 | 公式 | order_type | auto_size |
|------|------|------------|-----------|
| 多头 TP | entry × (1+gridRate) | `close-long-position` | `close_long` |
| 空头 TP | entry × (1-gridRate) | `close-short-position` | `close_short` |
**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` |
| 操作 | 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/positions/{contract}/leverage` | `FuturesApi.updateContractPositionLeverageCall()` | |
| 查账户 | `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 |
**初始化顺序** (`init()`):
```
1. 获取用户 ID
2. 查账户 → 如需要切持仓模式
3. 清除旧的止盈止损条件单
4. 查当前合约所有仓位 → 逐个市价平仓
   - 单向持仓(single): size=相反数, reduce_only=true
   - 双向持仓(dual): size=0, close=false, autoSize=LONG/SHORT, reduce_only=true
5. 设杠杆
6. 打印账户余额
```
---
## GateWebSocketClientMain
**角色**: 独立的 `main()` 方法入口,通过 Spring XML 上下文启动。
独立 `main()` 方法入口,通过 Spring XML 上下文启动,运行后手动关闭。
---
## Example.java
Gate SDK 使用示例,展示 `FuturesApi` 的基本用法:获取账户、设置仓位模式、设置杠杆。仅作参考,不参与实际策略运行。
Gate SDK 使用示例,展示 `FuturesApi` 的基本用法。仅作参考。