package com.xcong.excoin.modules.gateApi; import com.xcong.excoin.modules.gateApi.wsHandler.handler.CandlestickChannelHandler; import com.xcong.excoin.modules.gateApi.wsHandler.handler.PositionClosesChannelHandler; import com.xcong.excoin.modules.gateApi.wsHandler.handler.PositionsChannelHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.math.BigDecimal; /** * Gate 模块 Spring 入口,组装所有组件并管理生命周期。 * *

启动流程 ({@code @PostConstruct})

*
    *
  1. 构建 {@link GateConfig}(Builder 模式,含 API 密钥、合约、策略参数)
  2. *
  3. 创建 {@link GateGridTradeService} → init():切持仓模式、清旧条件单、设杠杆
  4. *
  5. 创建 {@link GateKlineWebSocketClient} → 注册 3 个 Handler → init():建立 WS 连接
  6. *
  7. gridTradeService.startGrid():激活策略,等待 K 线触发首次双开
  8. *
* *

销毁流程 ({@code @PreDestroy})

*
    *
  1. gridTradeService.stopGrid():取消条件单 → 关闭交易线程池
  2. *
  3. wsClient.destroy():取消订阅 → 断开 WS → 关闭线程池
  4. *
* *

配置

* 当前在代码中硬编码测试网参数。切换到生产网只需改为 {@code .isProduction(true)}。 * * @author Administrator */ @Slf4j @Component public class GateWebSocketClientManager { /** WebSocket 连接管理器 */ private GateKlineWebSocketClient wsClient; /** 网格交易策略服务 */ private GateGridTradeService gridTradeService; /** 统一配置 */ private GateConfig config; @PostConstruct public void init() { log.info("[GateMgr] init..."); try { config = GateConfig.builder() .apiKey("d90ca272391992b8e74f8f92cedb21ec") .apiSecret("1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274") .contract("XAUT_USDT") .leverage("30") .marginMode("cross") .positionMode("dual") .gridRate(new BigDecimal("0.0035")) .overallTp(new BigDecimal("0.5")) .maxLoss(new BigDecimal("7.5")) .quantity("10") .isProduction(false) .reopenMaxRetries(3) .build(); gridTradeService = new GateGridTradeService(config); gridTradeService.init(); wsClient = new GateKlineWebSocketClient(config.getWsUrl()); wsClient.addChannelHandler(new CandlestickChannelHandler(config.getContract(), gridTradeService)); wsClient.addChannelHandler(new PositionsChannelHandler( config.getApiKey(), config.getApiSecret(), config.getContract(), gridTradeService)); wsClient.addChannelHandler(new PositionClosesChannelHandler( config.getApiKey(), config.getApiSecret(), config.getContract(), gridTradeService)); wsClient.init(); log.info("[GateMgr] ws connected, 3 handlers registered"); gridTradeService.startGrid(); } catch (Exception e) { log.error("[GateMgr] init fail", e); } } @PreDestroy public void destroy() { log.info("[GateMgr] destroy..."); if (gridTradeService != null) { gridTradeService.stopGrid(); } if (wsClient != null) { wsClient.destroy(); } log.info("[GateMgr] destroyed"); } public GateKlineWebSocketClient getKlineWebSocketClient() { return wsClient; } public GateGridTradeService getGridTradeService() { return gridTradeService; } }