# Gate Api 模块 — 网格交易系统 ## 文件列表 | 文件 | 类型 | 说明 | |------|------|------| | [GateWebSocketClientManager](#gatewebsocketclientmanager) | `@Component` | 启动入口,生命周期管理 | | [GateKlineWebSocketClient](#gateklinewebsocketclient) | WebSocket 客户端 | K 线 + 仓位数据监听 | | [GateGridTradeService](#gategridtradeservice) | 交易服务 | 网格策略 + REST 下单 | | [GateWebSocketClientMain](#gatewebsocketclientmain) | main 入口 | 独立测试启动 | | [Example.java](#examplejava) | 示例 | Gate SDK 用法参考 | --- ## 架构总览 ``` ┌────────────────────────────────────────────────────────────┐ │ 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) │ └────────────────────────────────────────────────────────────┘ ``` --- ## 数据流 ``` WebSocket 推送 │ ├─ futures.candlesticks (update) │ └─ GateKlineWebSocketClient.processPushDataV2() │ ├─ 解析: o/h/l/c/v/a/t/w │ ├─ 打印 K 线日志 │ └─ GateGridTradeService.onKline(closePx) │ ├─ 首次 → dualOpenPositions() → 开多 + 开空 + TP 单 │ └─ 后续 → 仅缓存 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.pong │ └─ cancelPongTimeout() │ └─ subscribe/unsubscribe/error └─ 日志输出 ``` --- ## 策略时序 ### 阶段 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 ``` ### 阶段 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 ``` ### 阶段 3:止盈触发 → 补仓 ``` 仓位推送: mode=dual_long, size=0 (多头被止盈平掉了) → longActive=true && size=0 → longActive=false → reopenLongPosition() → REST: 市价开多 10 张 (用最新 K 线价) → REST: 创建新的多头止盈单 仓位推送: history_pnl=0.12 (未达阈值,继续) ``` ### 阶段 4:停止 ``` 仓位推送: history_pnl ≥ 0.5 (累计盈利达标) → strategyActive = false → 不再补仓 仓位推送: history_pnl ≤ -7.5 (亏损超限) → strategyActive = false → 不再补仓 ``` --- ## GateWebSocketClientManager **角色**: Spring Bean 入口,组装并管理所有 Gate 模块组件。 **关键方法**: - `init()`: 创建 `GateGridTradeService` → 初始化 → 创建 `GateKlineWebSocketClient` → 启动策略 - `destroy()`: 停止策略 → 关闭 WebSocket **当前参数**(硬编码在 `init()` 中): | 参数 | 值 | 说明 | |------|-----|------| | 合约 | XAU_USDT | 黄金 | | 杠杆 | 30x | 全仓模式 | | 持仓模式 | dual | 双向持仓 | | 网格间距 | 0.0035 | 0.35% | | 整体止盈 | 0.5 USDT | | | 最大亏损 | 7.5 USDT | 本金 50×15% | | 下单量 | 10 张 | | --- ## GateKlineWebSocketClient **角色**: WebSocket 客户端,订阅 Gate 的行情和仓位频道。 **订阅频道**: | 频道 | 类型 | 认证 | 用途 | |------|------|------|------| | `futures.candlesticks` | 公开 | 否 | 1m K 线数据 | | `futures.positions` | 私有 | HMAC-SHA512 | 用户仓位更新 | | `futures.ping` | 公开 | 否 | 应用层心跳 | **签名算法**(`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()` | --- ## GateGridTradeService **角色**: 使用 Gate SDK (`io.gate:gate-api:7.2.71`) 通过 REST API 执行合约下单。 **状态机**: ``` 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 ``` **止盈计算**: | 方向 | 公式 | 触发条件 | order_type | auto_size | |------|------|----------|------------|-----------| | 多头 TP | entryPrice × 1.0035 | 最新价 ≥ 触发价 | `close-long-position` | `close_long` | | 空头 TP | entryPrice × 0.9965 | 最新价 ≤ 触发价 | `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` | --- ## GateWebSocketClientMain **角色**: 独立的 `main()` 方法入口,通过 Spring XML 上下文启动。 --- ## Example.java Gate SDK 使用示例,展示 `FuturesApi` 的基本用法:获取账户、设置仓位模式、设置杠杆。仅作参考,不参与实际策略运行。