| 11 hours ago | Administrator | ![]() |
| 17 hours ago | Administrator | ![]() |
| 20 hours ago | Administrator | ![]() |
| 20 hours ago | Administrator | ![]() |
| 22 hours ago | Administrator | ![]() |
| 23 hours ago | Administrator | ![]() |
| 23 hours ago | Administrator | ![]() |
| yesterday | Administrator | ![]() |
src/main/java/com/xcong/excoin/modules/gateApi/Example.java
@@ -15,8 +15,29 @@ import java.math.BigDecimal; /** * Gate SDK API 使用示例。 * * <h3>演示内容</h3> * <ol> * <li>通过 API Key/Secret 初始化客户端</li> * <li>查询期货账户余额</li> * <li>设置双向持仓模式</li> * <li>设置杠杆倍数</li> * <li>切换保证金模式(全仓/逐仓)</li> * </ol> * * <h3>注意</h3> * 此文件仅作为 SDK 用法参考,不影响实际策略运行。 * 当前策略中相同功能的实现在 {@code GateGridTradeService.init()} 中。 * * @author Administrator */ @Slf4j public class Example { /** * 示例入口:依次执行查询账户 → 设置双向持仓 → 设杠杆 → 切换保证金模式。 */ public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); defaultClient.setBasePath("https://api-testnet.gateapi.io/api/v4"); src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
@@ -76,6 +76,8 @@ private final BigDecimal contractMultiplier; /** 未实现盈亏计价模式:最新价 / 标记价格 */ private final PnLPriceMode unrealizedPnlPriceMode; /** 网格绝对步长(shortBaseEntryPrice × gridRate),运行时由队列生成逻辑设置 */ private BigDecimal step; private GateConfig(Builder builder) { this.apiKey = builder.apiKey; @@ -95,6 +97,8 @@ this.contractMultiplier = builder.contractMultiplier; this.unrealizedPnlPriceMode = builder.unrealizedPnlPriceMode; } // ==================== REST/WS 地址 ==================== /** * 根据环境返回 REST API 基础路径。 @@ -122,22 +126,65 @@ : "wss://ws-testnet.gate.com/v4/ws/futures/usdt"; } // ==================== 认证信息 ==================== /** @return Gate API v4 密钥 */ public String getApiKey() { return apiKey; } /** @return Gate API v4 签名密钥,用于 HMAC-SHA512 签名 */ public String getApiSecret() { return apiSecret; } // ==================== 交易标的 ==================== /** @return 合约名称(如 ETH_USDT、XAU_USDT) */ public String getContract() { return contract; } /** @return 杠杆倍数(如 "100" 表示 100x) */ public String getLeverage() { return leverage; } // ==================== 持仓配置 ==================== /** @return 保证金模式(cross=全仓 / isolated=逐仓) */ public String getMarginMode() { return marginMode; } /** @return 持仓模式(single=单向 / dual=双向 / dual_plus) */ public String getPositionMode() { return positionMode; } // ==================== 策略参数 ==================== /** @return 网格间距比例(如 0.0015 表示 0.15%),用于生成价格队列和计算止盈价 */ public BigDecimal getGridRate() { return gridRate; } /** @return 整体止盈阈值(USDT),累计已实现盈亏 ≥ 此值时策略停止 */ public BigDecimal getOverallTp() { return overallTp; } /** @return 最大亏损阈值(USDT),累计已实现盈亏 ≤ -此值时策略停止 */ public BigDecimal getMaxLoss() { return maxLoss; } /** @return 每次下单的张数(如 "1" 表示 1 张合约) */ public String getQuantity() { return quantity; } public boolean isProduction() { return isProduction; } public int getReopenMaxRetries() { return reopenMaxRetries; } /** @return 网格价格队列的容量上限(超出时截断尾部) */ public int getGridQueueSize() { return gridQueueSize; } // ==================== 风险控制 ==================== /** @return 保证金占初始本金比例上限(默认 0.2 即 20%),超限跳过开仓 */ public BigDecimal getMarginRatioLimit() { return marginRatioLimit; } /** @return 补仓最大重试次数(当前版本未使用) */ public int getReopenMaxRetries() { return reopenMaxRetries; } // ==================== 盈亏计算 ==================== /** @return 合约乘数(单张合约代表的基础资产数量,如 ETH_USDT=0.01) */ public BigDecimal getContractMultiplier() { return contractMultiplier; } /** @return 未实现盈亏计价模式:LAST_PRICE(最新成交价)/ MARK_PRICE(标记价格) */ public PnLPriceMode getUnrealizedPnlPriceMode() { return unrealizedPnlPriceMode; } // ==================== 运行时参数 ==================== /** @return 网格绝对步长(shortBaseEntryPrice × gridRate),运行时设置 */ public BigDecimal getStep() { return step; } /** 设置网格绝对步长(由 generateShortQueue 在运行时计算并注入) */ public void setStep(BigDecimal step) { this.step = step; } // ==================== 环境 ==================== /** @return 是否为生产环境(true=实盘生产网 / false=模拟盘测试网) */ public boolean isProduction() { return isProduction; } public static Builder builder() { return new Builder(); @@ -145,38 +192,75 @@ /** * GateConfig 的流式构造器,提供合理的默认值。 * * <h3>必填项</h3> * {@code apiKey} 和 {@code apiSecret} 必须设置,其余参数均有默认值。 * * <h3>默认值</h3> * BTC_USDT / 10x / cross(全仓) / dual(双向) / gridRate=0.35% / * overallTp=0.5 / maxLoss=7.5 / quantity=1 / isProduction=false */ public static class Builder { /** Gate API v4 密钥(必填) */ private String apiKey; /** Gate API v4 签名密钥(必填) */ private String apiSecret; /** 合约名称,默认 BTC_USDT */ private String contract = "BTC_USDT"; /** 杠杆倍数,默认 "10" */ private String leverage = "10"; /** 保证金模式,默认 "cross"(全仓) */ private String marginMode = "cross"; /** 持仓模式,默认 "dual"(双向) */ private String positionMode = "dual"; /** 网格间距比例,默认 0.0035(0.35%) */ private BigDecimal gridRate = new BigDecimal("0.0035"); /** 整体止盈阈值(USDT),默认 0.5 */ private BigDecimal overallTp = new BigDecimal("0.5"); /** 最大亏损阈值(USDT),默认 7.5 */ private BigDecimal maxLoss = new BigDecimal("7.5"); /** 每次下单张数,默认 "1" */ private String quantity = "1"; /** 是否为生产环境,默认 false(测试网) */ private boolean isProduction = false; /** 补仓最大重试次数,默认 3 */ private int reopenMaxRetries = 3; /** 网格队列容量,默认 50 */ private int gridQueueSize = 50; /** 保证金占初始本金比例上限,默认 0.2(20%) */ private BigDecimal marginRatioLimit = new BigDecimal("0.2"); /** 合约乘数,默认 0.001 */ private BigDecimal contractMultiplier = new BigDecimal("0.001"); /** 未实现盈亏计价模式,默认 LAST_PRICE(最新成交价) */ private PnLPriceMode unrealizedPnlPriceMode = PnLPriceMode.LAST_PRICE; /** 设置 API Key */ public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; } /** 设置 API Secret */ public Builder apiSecret(String apiSecret) { this.apiSecret = apiSecret; return this; } /** 设置合约名称 */ public Builder contract(String contract) { this.contract = contract; return this; } /** 设置杠杆倍数 */ public Builder leverage(String leverage) { this.leverage = leverage; return this; } /** 设置保证金模式(cross=全仓 / isolated=逐仓) */ public Builder marginMode(String marginMode) { this.marginMode = marginMode; return this; } /** 设置持仓模式(single=单向 / dual=双向) */ public Builder positionMode(String positionMode) { this.positionMode = positionMode; return this; } /** 设置网格间距比例 */ public Builder gridRate(BigDecimal gridRate) { this.gridRate = gridRate; return this; } /** 设置整体止盈阈值(USDT) */ public Builder overallTp(BigDecimal overallTp) { this.overallTp = overallTp; return this; } /** 设置最大亏损阈值(USDT) */ public Builder maxLoss(BigDecimal maxLoss) { this.maxLoss = maxLoss; return this; } /** 设置每次下单张数 */ public Builder quantity(String quantity) { this.quantity = quantity; return this; } /** 设置环境(true=实盘生产网 / false=模拟盘测试网) */ public Builder isProduction(boolean isProduction) { this.isProduction = isProduction; return this; } /** 设置补仓最大重试次数 */ public Builder reopenMaxRetries(int reopenMaxRetries) { this.reopenMaxRetries = reopenMaxRetries; return this; } /** 设置合约乘数(单张合约代表的基础资产数量) */ public Builder contractMultiplier(BigDecimal contractMultiplier) { this.contractMultiplier = contractMultiplier; return this; } /** 设置未实现盈亏计价模式 */ public Builder unrealizedPnlPriceMode(PnLPriceMode mode) { this.unrealizedPnlPriceMode = mode; return this; } public GateConfig build() { src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -139,6 +139,20 @@ // ---- 初始化 ---- /** * 初始化策略环境。 * * <h3>执行顺序</h3> * <ol> * <li>获取用户 ID(用于私有频道订阅 payload)</li> * <li>获取账户信息 → 记录初始本金</li> * <li>如需要,切换为双向持仓模式</li> * <li>如需要,调整持仓模式(single/dual)</li> * <li>清除旧的止盈止损条件单</li> * <li>平掉所有已有仓位</li> * <li>设置杠杆倍数</li> * </ol> */ public void init() { try { ApiClient detailClient = new ApiClient(); @@ -194,6 +208,19 @@ } } /** * 平掉当前合约的所有已有仓位。 * * <h3>平仓策略</h3> * <ul> * <li>单向持仓:size=相反数,reduceOnly=true,市价 IOC 平仓</li> * <li>双向持仓:size=0,close=false,autoSize=LONG/SHORT,reduceOnly=true,市价 IOC 全平</li> * </ul> * * <h3>注意事项</h3> * 双向持仓模式下必须使用 autoSize 参数,不能直接传负数 size, * 否则 Gate API 会拒绝(双向模式下空头 size 为负是正常的持仓方向)。 */ private void closeExistingPositions() { try { List<Position> positions = futuresApi.listPositions(SETTLE).execute(); @@ -234,6 +261,10 @@ // ---- 启动/停止 ---- /** * 启动网格策略。重置所有状态变量和队列,进入 WAITING_KLINE 等待首根 K 线。 * 仅当当前状态为 WAITING_KLINE 或 STOPPED 时才允许启动。 */ public void startGrid() { if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) { log.warn("[Gate] 策略已在运行中, state:{}", state); @@ -256,6 +287,10 @@ log.info("[Gate] 网格策略已启动"); } /** * 停止网格策略。取消所有条件单 → 关闭交易线程池。 * 状态设为 STOPPED,K 线回调将直接返回不再处理。 */ public void stopGrid() { state = StrategyState.STOPPED; executor.cancelAllPriceTriggeredOrders(); @@ -265,6 +300,24 @@ // ---- K线回调 ---- /** * K 线回调入口。由 {@link CandlestickChannelHandler} 在收到 WebSocket K 线推送时调用。 * * <h3>处理流程</h3> * <ol> * <li>更新 lastKlinePrice → 计算 unrealizedPnl(浮动盈亏)</li> * <li>STOPPED → 直接返回(仅保留盈亏更新)</li> * <li>WAITING_KLINE → 切换为 OPENING → 异步提交基底双开(开多+开空)</li> * <li>OPENING → 等待仓位推送回调生成队列,此处返回</li> * <li>ACTIVE → 执行 processShortGrid + processLongGrid</li> * </ol> * * <h3>注意</h3> * 基底双开下单提交到 GateTradeExecutor 的独立线程池中异步执行, * 成交状态由 onPositionUpdate 回调驱动,不阻塞 WS 回调线程。 * * @param closePrice K 线收盘价(即当前最新成交价) */ public void onKline(BigDecimal closePrice) { lastKlinePrice = closePrice; updateUnrealizedPnl(); @@ -293,6 +346,26 @@ // ---- 仓位推送回调 ---- /** * 仓位推送回调。由 {@link PositionsChannelHandler} 在收到 WebSocket 仓位更新时调用。 * * <h3>处理逻辑</h3> * <ul> * <li><b>有仓位 (size ≠ 0)</b>: * <ul> * <li>首次开仓(基底):标记 baseOpened=true,记录基底入场价,双基底都成交后生成网格队列</li> * <li>仓位净增加(size > 之前记录值):说明网格触发了新开仓 → 取对应方向队列首元素为止盈价,设止盈条件单</li> * <li>仓位减少或不变(止盈平仓后):仅更新 positionSize,不重复设止盈</li> * </ul> * </li> * <li><b>无仓位 (size = 0)</b>:清空活跃标记和持仓量</li> * </ul> * * @param contract 合约名称 * @param mode 持仓模式(DUAL_LONG / DUAL_SHORT) * @param size 持仓张数(多头为正、空头为负) * @param entryPrice 当前持仓加权均价(交易所计算) */ public void onPositionUpdate(String contract, Position.ModeEnum mode, BigDecimal size, BigDecimal entryPrice) { if (state == StrategyState.STOPPED || state == StrategyState.WAITING_KLINE) { @@ -305,17 +378,24 @@ if (hasPosition) { longActive = true; longEntryPrice = entryPrice; longPositionSize = size; if (!baseLongOpened) { longPositionSize = size; longBaseEntryPrice = entryPrice; baseLongOpened = true; log.info("[Gate] 基底多成交价: {}", longBaseEntryPrice); tryGenerateQueues(); } else if (size.compareTo(longPositionSize) > 0) { longPositionSize = size; if (longPriceQueue.isEmpty()) { log.warn("[Gate] 多仓队列为空,无法设止盈"); } else { BigDecimal tpPrice = longPriceQueue.get(0); executor.placeTakeProfit(tpPrice, FuturesPriceTrigger.RuleEnum.NUMBER_1, ORDER_TYPE_CLOSE_LONG, negate(config.getQuantity())); log.info("[Gate] 多单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, negate(config.getQuantity())); } } else { BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.add(config.getGridRate())).setScale(1, RoundingMode.HALF_UP); executor.placeTakeProfit(tpPrice, FuturesPriceTrigger.RuleEnum.NUMBER_1, ORDER_TYPE_CLOSE_LONG, negate(config.getQuantity())); log.info("[Gate] 多单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, negate(config.getQuantity())); longPositionSize = size; } } else { longActive = false; @@ -325,17 +405,24 @@ if (hasPosition) { shortActive = true; shortEntryPrice = entryPrice; shortPositionSize = size.abs(); if (!baseShortOpened) { shortPositionSize = size.abs(); shortBaseEntryPrice = entryPrice; baseShortOpened = true; log.info("[Gate] 基底空成交价: {}", shortBaseEntryPrice); tryGenerateQueues(); } else if (size.abs().compareTo(shortPositionSize) > 0) { shortPositionSize = size.abs(); if (shortPriceQueue.isEmpty()) { log.warn("[Gate] 空仓队列为空,无法设止盈"); } else { BigDecimal tpPrice = shortPriceQueue.get(0); executor.placeTakeProfit(tpPrice, FuturesPriceTrigger.RuleEnum.NUMBER_2, ORDER_TYPE_CLOSE_SHORT, config.getQuantity()); log.info("[Gate] 空单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, config.getQuantity()); } } else { BigDecimal tpPrice = entryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate())).setScale(1, RoundingMode.HALF_UP); executor.placeTakeProfit(tpPrice, FuturesPriceTrigger.RuleEnum.NUMBER_2, ORDER_TYPE_CLOSE_SHORT, config.getQuantity()); log.info("[Gate] 空单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, config.getQuantity()); shortPositionSize = size.abs(); } } else { shortActive = false; @@ -346,6 +433,17 @@ // ---- 平仓推送回调 ---- /** * 平仓推送回调。由 {@link PositionClosesChannelHandler} 在收到平仓推送时调用。 * * <h3>累加规则</h3> * cumulativePnl += pnl。止盈平仓时 pnl > 0,止损平仓时 pnl < 0。 * 累加后检查停止条件:≥ overallTp 或 ≤ -maxLoss。 * * @param contract 合约名称 * @param side 平仓方向("long" / "short") * @param pnl 本次平仓的盈亏金额 */ public void onPositionClose(String contract, String side, BigDecimal pnl) { if (state == StrategyState.STOPPED) { return; @@ -364,6 +462,10 @@ // ---- 网格队列处理 ---- /** * 尝试生成网格队列。双基底(多+空)都成交后才触发: * 生成空仓队列 + 多仓队列 → 状态切换为 ACTIVE。 */ private void tryGenerateQueues() { if (baseLongOpened && baseShortOpened) { generateShortQueue(); @@ -375,22 +477,37 @@ } } /** * 生成空仓价格队列。 * 以 shortBaseEntryPrice × gridRate 作为绝对步长 step,存到 config。 * 第1个元素 = shortBaseEntryPrice − step,后续依次递减 step,共 gridQueueSize 个。 * 队列降序排列(大→小),方便 processShortGrid 中从头遍历。 */ private void generateShortQueue() { shortPriceQueue.clear(); BigDecimal step = config.getGridRate(); for (int i = 1; i <= config.getGridQueueSize(); i++) { shortPriceQueue.add(shortBaseEntryPrice.multiply(BigDecimal.ONE.subtract(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP)); BigDecimal step = shortBaseEntryPrice.multiply(config.getGridRate()).setScale(1, RoundingMode.HALF_UP); config.setStep(step); BigDecimal elem = shortBaseEntryPrice.subtract(step).setScale(1, RoundingMode.HALF_UP); for (int i = 0; i < config.getGridQueueSize(); i++) { shortPriceQueue.add(elem); elem = elem.subtract(step).setScale(1, RoundingMode.HALF_UP); } shortPriceQueue.sort((a, b) -> b.compareTo(a)); //输出队列:shortPriceQueue; log.info("[Gate] 空队列:{}", shortPriceQueue); } /** * 生成多仓价格队列。 * 以 shortBaseEntryPrice + step 为首元素,后续依次递增 step,共 gridQueueSize 个。 * 队列升序排列(小→大),方便 processLongGrid 中从头遍历。 */ private void generateLongQueue() { longPriceQueue.clear(); BigDecimal step = config.getGridRate(); for (int i = 1; i <= config.getGridQueueSize(); i++) { longPriceQueue.add(longBaseEntryPrice.multiply(BigDecimal.ONE.add(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP)); BigDecimal step = config.getStep(); BigDecimal elem = shortBaseEntryPrice.add(step).setScale(1, RoundingMode.HALF_UP); for (int i = 0; i < config.getGridQueueSize(); i++) { longPriceQueue.add(elem); elem = elem.add(step).setScale(1, RoundingMode.HALF_UP); } longPriceQueue.sort(BigDecimal::compareTo); log.info("[Gate] 多队列:{}", longPriceQueue); @@ -406,10 +523,10 @@ * <h3>执行流程</h3> * <ol> * <li>匹配队列元素 → 为空则直接返回</li> * <li>空仓队列:移除 matched 元素,尾部补充新元素(尾价 − step 循环递减)</li> * <li>多仓队列:以多仓队列首元素(最小价)为种子,递减 step 生成 matched.size() 个元素加入</li> * <li>保证金检查 → 安全则开空一次</li> * <li>额外反向开多:若多仓均价 > 空仓均价 且 当前价夹在中间且远离多仓均价</li> * <li>空仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 − gridRate) 循环递减)</li> * <li>多仓队列:以多仓队列首元素(最小价)为种子,生成 matched.size() 个递减元素加入</li> * </ol> * * <h3>多仓队列转移过滤</h3> @@ -432,6 +549,42 @@ return; } log.info("[Gate] 空仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice); synchronized (shortPriceQueue) { shortPriceQueue.removeAll(matched); BigDecimal min = shortPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : shortPriceQueue.get(shortPriceQueue.size() - 1); BigDecimal gridStep = config.getStep(); for (int i = 0; i < matched.size(); i++) { min = min.subtract(gridStep).setScale(1, RoundingMode.HALF_UP); shortPriceQueue.add(min); log.info("[Gate] 空队列增加:{}", min); } shortPriceQueue.sort((a, b) -> b.compareTo(a)); log.info("[Gate] 现空队列:{}", shortPriceQueue); } synchronized (longPriceQueue) { BigDecimal first = longPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : longPriceQueue.get(0); BigDecimal gridStep = config.getStep(); for (int i = 1; i <= matched.size(); i++) { BigDecimal elem = first.subtract(gridStep.multiply(BigDecimal.valueOf(i))).setScale(1, RoundingMode.HALF_UP); // if (longEntryPrice.compareTo(BigDecimal.ZERO) > 0 // && currentPrice.subtract(longEntryPrice).abs().compareTo(longEntryPrice.multiply(config.getGridRate())) < 0) { // log.info("[Gate] 多队列跳过(price≈longEntry):{}", elem); // continue; // } longPriceQueue.add(elem); log.info("[Gate] 多队列增加:{}", elem); } longPriceQueue.sort(BigDecimal::compareTo); while (longPriceQueue.size() > config.getGridQueueSize()) { longPriceQueue.remove(longPriceQueue.size() - 1); } log.info("[Gate] 现多队列:{}", longPriceQueue); } if (!isMarginSafe()) { log.warn("[Gate] 保证金超限,跳过空单开仓"); } else { @@ -445,39 +598,6 @@ log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", currentPrice); } } synchronized (shortPriceQueue) { shortPriceQueue.removeAll(matched); BigDecimal min = shortPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : shortPriceQueue.get(shortPriceQueue.size() - 1); BigDecimal step = config.getGridRate(); for (int i = 0; i < matched.size(); i++) { min = min.multiply(BigDecimal.ONE.subtract(step)).setScale(1, RoundingMode.HALF_UP); shortPriceQueue.add(min); } shortPriceQueue.sort(BigDecimal::compareTo); log.info("[Gate] 现空队列:{}", shortPriceQueue); } synchronized (longPriceQueue) { BigDecimal first = longPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : longPriceQueue.get(0); BigDecimal step = config.getGridRate(); int added = 0; for (int i = 1; i <= matched.size(); i++) { BigDecimal elem = first.multiply(BigDecimal.ONE.subtract(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP); if (longEntryPrice.compareTo(BigDecimal.ZERO) > 0 && elem.subtract(longEntryPrice).abs().compareTo(longEntryPrice.multiply(step)) < 0) { continue; } longPriceQueue.add(elem); added++; } longPriceQueue.sort(BigDecimal::compareTo); while (longPriceQueue.size() > config.getGridQueueSize()) { longPriceQueue.remove(longPriceQueue.size() - 1); } log.info("[Gate] 现多队列:{}, 跳过{}个(贴近多仓均价)", longPriceQueue, matched.size() - added); } } /** @@ -490,10 +610,10 @@ * <h3>执行流程</h3> * <ol> * <li>匹配队列元素 → 为空则直接返回</li> * <li>多仓队列:移除 matched 元素,尾部补充新元素(尾价 + step 循环递增)</li> * <li>空仓队列:以空仓队列首元素(最高价)为种子,递增 step 生成 matched.size() 个元素加入</li> * <li>保证金检查 → 安全则开多一次</li> * <li>额外反向开空:若多仓均价 > 空仓均价 且 当前价夹在中间且远离空仓均价</li> * <li>多仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 + gridRate) 循环递增)</li> * <li>空仓队列:以空仓队列首元素(最高价)为种子,生成 matched.size() 个递增元素加入</li> * </ol> * * <h3>空仓队列转移过滤</h3> @@ -517,6 +637,42 @@ } log.info("[Gate] 多仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice); synchronized (longPriceQueue) { longPriceQueue.removeAll(matched); BigDecimal max = longPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : longPriceQueue.get(longPriceQueue.size() - 1); BigDecimal gridStep = config.getStep(); for (int i = 0; i < matched.size(); i++) { max = max.add(gridStep).setScale(1, RoundingMode.HALF_UP); longPriceQueue.add(max); log.info("[Gate] 多队列增加:{}", max); } longPriceQueue.sort(BigDecimal::compareTo); log.info("[Gate] 现多队列:{}", longPriceQueue); } synchronized (shortPriceQueue) { BigDecimal first = shortPriceQueue.isEmpty() ? matched.get(0) : shortPriceQueue.get(0); BigDecimal gridStep = config.getStep(); for (int i = 1; i <= matched.size(); i++) { BigDecimal elem = first.add(gridStep.multiply(BigDecimal.valueOf(i))).setScale(1, RoundingMode.HALF_UP); // if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0 // && currentPrice.subtract(shortEntryPrice).abs().compareTo(shortEntryPrice.multiply(config.getGridRate())) < 0) { // log.info("[Gate] 空队列跳过(price≈shortEntry):{}", elem); // continue; // } shortPriceQueue.add(elem); log.info("[Gate] 空队列增加:{}", elem); } shortPriceQueue.sort((a, b) -> b.compareTo(a)); while (shortPriceQueue.size() > config.getGridQueueSize()) { shortPriceQueue.remove(shortPriceQueue.size() - 1); } log.info("[Gate] 现空队列:{}", shortPriceQueue); } if (!isMarginSafe()) { log.warn("[Gate] 保证金超限,跳过多单开仓"); } else { @@ -530,43 +686,20 @@ log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", currentPrice); } } synchronized (longPriceQueue) { longPriceQueue.removeAll(matched); BigDecimal max = longPriceQueue.isEmpty() ? matched.get(matched.size() - 1) : longPriceQueue.get(longPriceQueue.size() - 1); BigDecimal step = config.getGridRate(); for (int i = 0; i < matched.size(); i++) { max = max.multiply(BigDecimal.ONE.add(step)).setScale(1, RoundingMode.HALF_UP); longPriceQueue.add(max); } longPriceQueue.sort(BigDecimal::compareTo); log.info("[Gate] 现多队列:{}", longPriceQueue); } synchronized (shortPriceQueue) { BigDecimal first = shortPriceQueue.isEmpty() ? matched.get(0) : shortPriceQueue.get(0); BigDecimal step = config.getGridRate(); int added = 0; for (int i = 1; i <= matched.size(); i++) { BigDecimal elem = first.multiply(BigDecimal.ONE.add(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP); if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0 && elem.subtract(shortEntryPrice).abs().compareTo(shortEntryPrice.multiply(step)) < 0) { continue; } shortPriceQueue.add(elem); added++; } shortPriceQueue.sort((a, b) -> b.compareTo(a)); while (shortPriceQueue.size() > config.getGridQueueSize()) { shortPriceQueue.remove(shortPriceQueue.size() - 1); } log.info("[Gate] 现空队列:{}, 跳过{}个(贴近空仓均价)", shortPriceQueue, matched.size() - added); } } // ---- 保证金安全阀 ---- /** * 保证金安全阀检查。 * * <p>实时查询当前保证金占用额(positionInitialMargin),计算其占初始本金的比例。 * 比例 ≥ marginRatioLimit(默认 20%)时拒绝开仓,但仍照常更新队列。 * * <p>查询失败时默认放行(返回 true),避免因 REST API 异常导致策略完全停滞。 * * @return true=安全可开仓 / false=保证金超限跳过开仓 */ private boolean isMarginSafe() { try { FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE); @@ -582,6 +715,10 @@ // ---- 工具 ---- /** * 取反字符串数字。如 "1" → "-1","-2" → "2"。 * 用于开空单时将正数张数转为负数。 */ private String negate(String qty) { return qty.startsWith("-") ? qty.substring(1) : "-" + qty; } @@ -617,6 +754,9 @@ /** * 根据配置的 PnLPriceMode 返回计价价格。 * MARK_PRICE 模式优先使用标记价格(外部注入),未注入时回退到最新成交价。 * * @return 计价价格,可能为 null */ private BigDecimal resolvePnlPrice() { if (config.getUnrealizedPnlPriceMode() == GateConfig.PnLPriceMode.MARK_PRICE @@ -626,11 +766,18 @@ return lastKlinePrice; } /** @return 最新 K 线价格(每次 onKline 更新) */ public BigDecimal getLastKlinePrice() { return lastKlinePrice; } /** 设置标记价格(外部注入,MARK_PRICE 模式时用于盈亏计算) */ public void setMarkPrice(BigDecimal markPrice) { this.markPrice = markPrice; } /** @return 策略是否处于活跃状态(非 STOPPED 且非 WAITING_KLINE) */ public boolean isStrategyActive() { return state != StrategyState.STOPPED && state != StrategyState.WAITING_KLINE; } /** @return 累计已实现盈亏(平仓推送驱动累加) */ public BigDecimal getCumulativePnl() { return cumulativePnl; } /** @return 当前未实现盈亏(每根 K 线实时计算) */ public BigDecimal getUnrealizedPnl() { return unrealizedPnl; } /** @return Gate 用户 ID(用于私有频道订阅 payload) */ public Long getUserId() { return userId; } /** @return 当前策略状态 */ public StrategyState getState() { return state; } } src/main/java/com/xcong/excoin/modules/gateApi/GateKlineWebSocketClient.java
@@ -91,13 +91,16 @@ /** * 注册频道处理器。需在 init() 前调用。 * * @param handler 实现了 {@link GateChannelHandler} 接口的频道处理器 */ public void addChannelHandler(GateChannelHandler handler) { channelHandlers.add(handler); } /** * 初始化:建立 WebSocket 连接 → 启动心跳。 * 初始化:建立 WebSocket 连接 → 启动心跳检测。 * 使用 {@code AtomicBoolean} 防重入,同一实例只允许初始化一次。 */ public void init() { if (!isInitialized.compareAndSet(false, true)) { @@ -109,9 +112,11 @@ } /** * 销毁:取消订阅 → 关闭连接 → 关闭线程池。 * <p>注意:先 closeBlocking 再 shutdown sharedExecutor, * 避免 onClose 回调中的 reconnectWithBackoff 访问已关闭的线程池。 * 销毁:取消所有频道订阅 → 关闭 WebSocket 连接 → 关闭线程池。 * * <h3>执行顺序</h3> * 先取消订阅(等待 500ms 确保发送完成),再 closeBlocking 关闭连接, * 最后 shutdown 线程池。先关连接再关线程池,避免 onClose 回调中的重连任务访问已关闭的线程池。 */ public void destroy() { log.info("[WS] 开始销毁..."); @@ -152,7 +157,20 @@ /** * 建立 WebSocket 连接。使用 SSLContext 配置 TLS 协议。 * 连接成功后依次订阅所有已注册的频道处理器。 * * <h3>连接成功回调</h3> * <ol> * <li>设置 isConnected=true,isConnecting=false</li> * <li>重置心跳计时器</li> * <li>依次订阅所有已注册的频道处理器</li> * <li>发送首次 ping</li> * </ol> * * <h3>连接关闭回调</h3> * 设置断连状态 → 取消心跳超时 → 异步触发指数退避重连(最多3次)。 * * <h3>线程安全</h3> * 使用 {@code AtomicBoolean.isConnecting} 防止并发重连。 */ private void connect() { if (isConnecting.get() || !isConnecting.compareAndSet(false, true)) { @@ -262,12 +280,19 @@ // ---- heartbeat ---- /** * 启动心跳检测器。 * 使用单线程 ScheduledExecutor,每 25 秒检查一次心跳超时。 */ private void startHeartbeat() { if (heartbeatExecutor != null && !heartbeatExecutor.isTerminated()) heartbeatExecutor.shutdownNow(); heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "gate-ws-heartbeat"); t.setDaemon(true); return t; }); heartbeatExecutor.scheduleWithFixedDelay(this::checkHeartbeatTimeout, 25, 25, TimeUnit.SECONDS); } /** * 重置心跳计时器:取消旧超时任务,提交新的 10 秒超时检测。 */ private synchronized void resetHeartbeatTimer() { cancelPongTimeout(); if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) { @@ -275,11 +300,17 @@ } } /** * 检查心跳超时:如果距离上次收到消息超过 10 秒,主动发送 futures.ping。 */ private void checkHeartbeatTimeout() { if (!isConnected.get()) return; if (System.currentTimeMillis() - lastMessageTime.get() >= HEARTBEAT_TIMEOUT * 1000L) sendPing(); } /** * 发送应用层 futures.ping 消息。 */ private void sendPing() { try { if (webSocketClient != null && webSocketClient.isOpen()) { @@ -292,12 +323,20 @@ } catch (Exception e) { log.warn("[WS] 发送 ping 失败", e); } } /** * 取消心跳超时检测任务。 */ private synchronized void cancelPongTimeout() { if (pongTimeoutFuture != null && !pongTimeoutFuture.isDone()) pongTimeoutFuture.cancel(true); } // ---- reconnect ---- /** * 指数退避重连。初始延迟 5 秒,每次翻倍,最多重试 3 次。 * * @throws InterruptedException 线程被中断 */ private void reconnectWithBackoff() throws InterruptedException { int attempt = 0, maxAttempts = 3; long delayMs = 5000; @@ -307,6 +346,11 @@ log.error("[WS] 超过最大重试次数({}),放弃重连", maxAttempts); } /** * 优雅关闭线程池:先 shutdown,等待 5 秒,超时则 shutdownNow 强制中断。 * * @param executor 需要关闭的线程池 */ private void shutdownExecutorGracefully(ExecutorService executor) { if (executor == null || executor.isTerminated()) return; try { executor.shutdown(); if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); } src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java
@@ -73,7 +73,8 @@ } /** * 优雅关闭:等待 10 秒,超时则强制中断。 * 优雅关闭:等待 10 秒让队列中的任务执行完毕,超时则强制中断。 * 关闭后的 REST 调用将通过 CallerRunsPolicy 直接在提交线程执行。 */ public void shutdown() { executor.shutdown(); @@ -86,19 +87,36 @@ } /** * 异步市价开多。quantity 为正数(如 "10")。 * 异步 IOC 市价开多。quantity 为正数(如 "1")。 * * @param quantity 开仓张数(正数) * @param onSuccess 成交成功回调(可为 null) * @param onFailure 成交失败回调(可为 null) */ public void openLong(String quantity, Runnable onSuccess, Runnable onFailure) { openPosition(quantity, "t-grid-long", "开多", onSuccess, onFailure); } /** * 异步市价开空。quantity 为负数(如 "-10")。 * 异步 IOC 市价开空。quantity 为负数(如 "-1")。 * * @param quantity 开仓张数(负数) * @param onSuccess 成交成功回调(可为 null) * @param onFailure 成交失败回调(可为 null) */ public void openShort(String quantity, Runnable onSuccess, Runnable onFailure) { openPosition(quantity, "t-grid-short", "开空", onSuccess, onFailure); } /** * 通用异步 IOC 市价下单。 * * @param size 下单张数(正=开多 / 负=开空) * @param text 订单标记文本(如 "t-grid-long"),用于区分订单来源 * @param label 日志标签(如 "开多"/"开空") * @param onSuccess 成功回调 * @param onFailure 失败回调 */ private void openPosition(String size, String text, String label, Runnable onSuccess, Runnable onFailure) { executor.execute(() -> { try { @@ -150,12 +168,33 @@ log.info("[TradeExec] 止盈单已创建, 触发价:{}, 类型:{}, size:{}, id:{}", triggerPrice, orderType, size, response.getId()); } catch (Exception e) { log.error("[TradeExec] 止盈单创建失败, 触发价:{}, size:{}", triggerPrice, size, e); log.error("[TradeExec] 止盈单创建失败, 触发价:{}, size:{}, 立即市价止盈", triggerPrice, size, e); marketClose(size); } }); } /** * 市价止盈:在止盈条件单创建失败时立即市价平仓。 * size 与止盈单保持一致(负=平多,正=平空)。 */ private void marketClose(String size) { try { FuturesOrder order = new FuturesOrder(); order.setContract(contract); order.setSize(size); order.setPrice("0"); order.setTif(FuturesOrder.TifEnum.IOC); order.setReduceOnly(true); order.setText("t-grid-mkt-close"); FuturesOrder result = futuresApi.createFuturesOrder(SETTLE, order, null); log.info("[TradeExec] 市价止盈成功, 价格:{}, size:{}, id:{}", result.getFillPrice(), size, result.getId()); } catch (Exception e) { log.error("[TradeExec] 市价止盈也失败, size:{}", size, e); } } /** * 异步清除指定合约的所有止盈止损条件单。 */ public void cancelAllPriceTriggeredOrders() { src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
@@ -48,6 +48,7 @@ log.info("[管理器] 开始初始化..."); try { //测试盘 config = GateConfig.builder() .apiKey("d90ca272391992b8e74f8f92cedb21ec") .apiSecret("1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274") @@ -64,10 +65,29 @@ .isProduction(false) .reopenMaxRetries(3) .build(); //实盘 config = GateConfig.builder() .apiKey("865371cdaccd5d238aceb06a55f0143a") .apiSecret("49589c30dfdc3acba007eed445a94990c4b0aa5faac9843e32defdd7371f5a50") .contract("ETH_USDT") .leverage("100") .marginMode("CROSS") .positionMode("dual") .gridRate(new BigDecimal("0.0035")) .overallTp(new BigDecimal("1")) .maxLoss(new BigDecimal("15")) .quantity("1") .contractMultiplier(new BigDecimal("0.01")) .unrealizedPnlPriceMode(GateConfig.PnLPriceMode.LAST_PRICE) .isProduction(true) .reopenMaxRetries(3) .build(); // 1. 初始化交易服务:查用户ID → 切持仓模式 → 清条件单 → 平已有仓位 → 设杠杆 gridTradeService = new GateGridTradeService(config); gridTradeService.init(); // 2. 创建 WS 客户端并注册 3 个频道处理器 wsClient = new GateKlineWebSocketClient(config.getWsUrl()); wsClient.addChannelHandler(new CandlestickChannelHandler(config.getContract(), gridTradeService)); wsClient.addChannelHandler(new PositionsChannelHandler( @@ -77,12 +97,16 @@ wsClient.init(); log.info("[管理器] WS已连接, 已注册 3 个频道处理器"); // 3. 激活策略,等待首根 K 线触发基底双开 gridTradeService.startGrid(); } catch (Exception e) { log.error("[管理器] 初始化失败", e); } } /** * 销毁:停止策略 → 关闭交易线程池 → 取消 WS 订阅 → 断开连接 → 关闭 WS 线程池。 */ @PreDestroy public void destroy() { log.info("[管理器] 开始销毁..."); src/main/java/com/xcong/excoin/modules/gateApi/celue.outBinary files differ
src/main/java/com/xcong/excoin/modules/gateApi/gateApi-logic.md
@@ -172,12 +172,14 @@ ### 网格队列生成 以基底入场价为基准,按 `gridRate`(百分比步长)生成 N 个价格(N = gridQueueSize,默认50): 以空头基底入场价 `shortBaseEntryPrice` 为唯一基准,计算绝对步长 `step = shortBaseEntryPrice × gridRate`(保留1位小数),存入 config。 两个队列均从 `shortBaseEntryPrice` 出发,按 `step` 绝对偏移生成 N 个价格(N = gridQueueSize,默认50): | 队列 | 计算方式 | 排序 | |------|---------|------| | 空仓队列 shortPriceQueue | 基底空入场价 × (1 − gridRate × i) (i=1..N) | 降序(大→小) | | 多仓队列 longPriceQueue | 基底多入场价 × (1 + gridRate × i) (i=1..N) | 升序(小→大) | | 空仓队列 shortPriceQueue | 首元素 = shortBaseEntryPrice − step,后续依次 −step (i=0..N-1) | 降序(大→小) | | 多仓队列 longPriceQueue | 首元素 = shortBaseEntryPrice + step,后续依次 +step (i=0..N-1) | 升序(小→大) | ### K线触发网格 @@ -186,39 +188,41 @@ │ ├─ processShortGrid: 当前价 < 空仓队列元素(价格跌破了队列中的高价) │ ├─ 匹配: 收集所有 > 当前价的空仓队列元素(降序,一旦遇≤即停止) │ ├─ 保证金检查: positionInitialMargin / initialPrincipal < marginRatioLimit(20%) │ │ ├─ 安全 → openShort 开空单 │ │ │ └─ 额外条件: 多>空 且 空仓均价 < 当前价 < 多仓均价×(1−gridRate) → openLong 额外开多一次 │ │ └─ 超限 → 跳过开仓,队列照常更新 │ ├─ 空仓队列: 移除 matched,尾部补充新元素(尾价 × (1−gridRate) 循环递减) │ └─ 多仓队列转移: │ ├─ 以多仓队列首元素(最小价)为种子 │ ├─ 生成 matched.size() 个递减元素: seed × (1 − gridRate × i) │ ├─ 贴近过滤: |elem − longEntryPrice| < longEntryPrice × gridRate → 跳过 │ └─ 升序排列,截断到 gridQueueSize │ ├─ 空仓队列: 移除 matched,尾部补充新元素(尾价 − step 循环递减) │ ├─ 多仓队列转移: │ │ ├─ 以多仓队列首元素(最小价)为种子 │ │ ├─ 生成 matched.size() 个递减元素: seed − step × i │ │ ├─ 贴近过滤: |currentPrice − longEntryPrice| < longEntryPrice × gridRate → 跳过 │ │ └─ 升序排列,截断到 gridQueueSize │ └─ 下单(队列已更新,避免竞态): │ ├─ 保证金检查: positionInitialMargin / initialPrincipal < marginRatioLimit(20%) │ │ ├─ 安全 → openShort 开空单 │ │ │ └─ 额外条件: 多>空 且 空仓均价 < 当前价 < 多仓均价×(1−gridRate) → openLong 额外开多一次 │ │ └─ 超限 → 跳过开仓 │ └─ processLongGrid: 当前价 > 多仓队列元素(价格涨超了队列中的低价) ├─ 匹配: 收集所有 < 当前价的多仓队列元素(升序,一旦遇≥即停止) ├─ 保证金检查: 同上 │ ├─ 安全 → openLong 开多单 │ │ └─ 额外条件: 多>空 且 空仓均价×(1+gridRate) < 当前价 < 多仓均价 → openShort 额外开空一次 │ └─ 超限 → 跳过开仓 ├─ 多仓队列: 移除 matched,尾部补充新元素(尾价 × (1+gridRate) 循环递增) └─ 空仓队列转移: ├─ 以空仓队列首元素(最高价)为种子 ├─ 生成 matched.size() 个递增元素: seed × (1 + gridRate × i) ├─ 贴近过滤: |elem − shortEntryPrice| < shortEntryPrice × gridRate → 跳过 └─ 降序排列,截断到 gridQueueSize ├─ 多仓队列: 移除 matched,尾部补充新元素(尾价 + step 循环递增) ├─ 空仓队列转移: │ ├─ 以空仓队列首元素(最高价)为种子 │ ├─ 生成 matched.size() 个递增元素: seed + step × i │ ├─ 贴近过滤: |currentPrice − shortEntryPrice| < shortEntryPrice × gridRate → 跳过 │ └─ 降序排列,截断到 gridQueueSize └─ 下单(队列已更新,避免竞态): ├─ 保证金检查: 同上 │ ├─ 安全 → openLong 开多单 │ │ └─ 额外条件: 多>空 且 空仓均价×(1+gridRate) < 当前价 < 多仓均价 → openShort 额外开空一次 │ └─ 超限 → 跳过开仓 ``` ### 队列转移规则(新) 触发后**不再简单复制** matched 元素到对方队列,而是以对方队列首元素为种子生成新元素: 触发后**不再简单复制** matched 元素到对方队列,而是以对方队列首元素为种子,按绝对步长 step 生成新元素: | 触发方向 | 目标队列 | 种子元素 | 生成公式 | 排序 | |---------|---------|---------|---------|------| | 空仓触发 → | 多仓队列 | 多仓队列首元素(最小价) | 种子 × (1 − gridRate × i) | 升序 | | 多仓触发 → | 空仓队列 | 空仓队列首元素(最高价) | 种子 × (1 + gridRate × i) | 降序 | | 空仓触发 → | 多仓队列 | 多仓队列首元素(最小价) | 种子 − step × i | 升序 | | 多仓触发 → | 空仓队列 | 空仓队列首元素(最高价) | 种子 + step × i | 降序 | ### 贴近持仓均价过滤(新) @@ -250,26 +254,28 @@ ### 队列转移示意 ``` ETH_USDT, gridRate=0.0035, 空仓均价=2270, 多仓均价=2280, gridQueueSize=4: ETH_USDT, gridRate=0.0035, shortBaseEntryPrice=2270, step=2270×0.0035≈7.9, gridQueueSize=4: 初始状态: 空仓队列: [2567.1, 2570.0, 2572.5, 2575.0] (降序) 多仓队列: [2275.0, 2277.0, 2279.0, 2281.5] (升序) 空仓队列: [2262.1, 2254.2, 2246.3, 2238.4] (降序, shortBaseEntryPrice−step 起递减) 多仓队列: [2277.9, 2285.8, 2293.7, 2301.6] (升序, shortBaseEntryPrice+step 起递增) 价格跌到 2571 → processShortGrid 触发: 匹配: [2575.0, 2572.5](都 > 2571) 空仓队列: 移除[2575.0,2572.5] → [2570.0,2567.1] → 补充递减 → [2570.0,2567.1,2560.0,2552.0] 多仓队列转移: 种子=多仓首元素 2275.0 生成: 2275.0×(1−0.0035×1)≈2267.0, 2275.0×(1−0.0035×2)≈2259.0 贴近过滤: |2267−2280|=13 > 2280×0.0035=7.98 → 通过 |2259−2280|=21 > 7.98 → 通过 多仓队列: [2259.0, 2267.0, 2275.0, 2277.0] → 截断到4 → [2267.0, 2275.0, 2277.0] 当前价 2571 对比: 空仓均价=2270, 多仓均价=2280 多>空 成立,但 2270 < 2571 < 2280×(1−0.0035)=2272 ? 否 → 不触发额外开多 价格涨到 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 贴近过滤(shortEntryPrice=2270): |2270.0−2270|=0.0 < 2270×0.0035=7.9 → 跳过 |2277.9−2270|=7.9 ≥ 7.9 → 通过 空仓队列: [2277.9, 2262.1, 2254.2, 2246.3, 2238.4] → 截断到4 → [2262.1, 2254.2, 2246.3, 2238.4](2277.9被移除...) 注:当空仓队列已满时,新元素可能因排序+截断被丢弃。缩小 gridRate 可增加步长密度。 ``` --- @@ -316,10 +322,10 @@ 每根K线 → onKline → updateUnrealizedPnl → processShortGrid + processLongGrid 仓位推送(每次开仓成交后自动触发): → DUAL_LONG, size>0, 非基底 → 设多头止盈单:止盈价=entryPrice×(1+gridRate), 使用 plan-close-long-position,平仓张数=-quantity(负=平多) → DUAL_SHORT, size<0, 非基底 → 设空头止盈单:止盈价=entryPrice×(1−gridRate), 使用 plan-close-short-position,平仓张数=+quantity(正=平空) → DUAL_LONG, size>0, 非基底 → 设多头止盈单:止盈价=longPriceQueue[0](多仓队列首元素), 使用 plan-close-long-position,平仓张数=-quantity(负=平多),rule=NUMBER_1(≥) → DUAL_SHORT, size<0, 非基底 → 设空头止盈单:止盈价=shortPriceQueue[0](空仓队列首元素), 使用 plan-close-short-position,平仓张数=+quantity(正=平空),rule=NUMBER_2(≤) 额外反向开仓(多>空倒挂时): → 空仓队列触发 + 条件满足 → 额外开多一次 @@ -355,7 +361,8 @@ | leverage | 10 | 倍数 | | marginMode | cross | 全仓 | | positionMode | dual | 双向持仓 | | gridRate | 0.0035 | 网格间距 0.35% | | gridRate | 0.0035 | 网格间距比率 0.35%(用于过滤阈值计算) | | step | 运行时计算 | 网格绝对步长 = shortBaseEntryPrice × gridRate(队列元素生成用) | | overallTp | 0.5 USDT | 整体止盈 | | maxLoss | 7.5 USDT | 最大亏损 | | quantity | 1 | 下单张数 | @@ -443,10 +450,8 @@ | 步骤 | processShortGrid | processLongGrid | |------|-----------------|-----------------| | 匹配 | 收集 shortPriceQueue 中 > currentPrice 的元素 | 收集 longPriceQueue 中 < currentPrice 的元素 | | 主开仓 | 保证金安全 → openShort | 保证金安全 → openLong | | 额外反向 | 条件满足 → openLong | 条件满足 → openShort | | 本队补充 | 尾价 × (1−gridRate) 循环递减 | 尾价 × (1+gridRate) 循环递增 | | 对方转移 | 以多仓首元素为种子,递减生成 | 以空仓首元素为种子,递增生成 | | 本队补充 | 尾价 − step 循环递减 | 尾价 + step 循环递增 | | 对方转移 | 以多仓首元素为种子,递减 step | 以空仓首元素为种子,递增 step | | 贴近过滤 | 新增与 longEntryPrice 太近 → 跳过 | 新增与 shortEntryPrice 太近 → 跳过 | **未实现盈亏计算** (`updateUnrealizedPnl()`): @@ -473,10 +478,10 @@ | 方向 | 公式 | order_type | size(平仓张数) | rule | |------|------|------------|-----------|------| | 多头 TP | entry × (1+gridRate) | `plan-close-long-position` | `-quantity`(负=平多) | NUMBER_1(≥触发价) | | 空头 TP | entry × (1−gridRate) | `plan-close-short-position` | `+quantity`(正=平空) | NUMBER_2(≤触发价) | | 多头 TP | longPriceQueue[0](多仓队列首元素) | `plan-close-long-position` | `-quantity`(负=平多) | NUMBER_1(≥触发价) | | 空头 TP | shortPriceQueue[0](空仓队列首元素) | `plan-close-short-position` | `+quantity`(正=平空) | NUMBER_2(≤触发价) | > 止盈单使用显式张数而非 autoSize。每次网格触发开仓 quantity 张,只为该批张数创建独立的条件单,多个止盈单之间互不覆盖。 > 止盈价取自对应方向队列的首元素(多仓队列升序首=最小价,空仓队列降序首=最高价)。止盈单使用显式张数而非 autoSize。每次网格触发开仓 quantity 张,只为该批张数创建独立的条件单,多个止盈单之间互不覆盖。 **REST API 调用**: src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/AbstractPrivateChannelHandler.java
@@ -52,12 +52,24 @@ this.gridTradeService = gridTradeService; } /** @return 频道名称(如 "futures.positions") */ @Override public String getChannelName() { return channelName; } /** * 发送带签名的订阅请求。 * payload: [userId, contract],auth: {method:"api_key", KEY, SIGN} * * <h3>请求格式</h3> * <pre> * { * "id": <唯一请求ID>, * "time": <unix时间戳(秒)>, * "channel":"futures.positions", * "event": "subscribe", * "payload":[userId, contract], * "auth": {"method":"api_key", "KEY":<APIKEY>, "SIGN":<HMAC-SHA512签名>} * } * </pre> */ @Override public void subscribe(WebSocketClient ws) { @@ -68,7 +80,8 @@ } /** * 发送带签名的取消订阅请求,与 subscribe 对称。 * 发送带签名的取消订阅请求,与 subscribe 结构一致。 * payload: [contract],无 userId(取消订阅不需要用户ID)。 */ @Override public void unsubscribe(WebSocketClient ws) { @@ -90,11 +103,15 @@ log.info("[{}] 取消订阅成功, 合约:{}", channelName, contract); } /** @return 网格交易服务实例 */ protected GateGridTradeService getGridTradeService() { return gridTradeService; } /** @return 当前订阅的合约名称 */ protected String getContract() { return contract; } /** * 从策略服务获取用户 ID,用于私有频道订阅的 payload[0]。 * * @return 用户 ID 字符串,获取失败返回空字符串 */ private String buildUid() { return gridTradeService != null && gridTradeService.getUserId() != null @@ -102,7 +119,13 @@ } /** * 构建认证请求 JSON。包含 id、time、channel、event、payload[auth_user_id, contract]、auth 字段。 * 构建认证请求 JSON。 * 包含 id、time、channel、event、payload[userId, contract]、auth 字段。 * * @param event 事件类型("subscribe" / "unsubscribe") * @param uid 认证用户 ID * @param timeSec unix 时间戳(秒) * @return 完整的认证请求 JSONObject */ private JSONObject buildAuthRequest(String event, String uid, long timeSec) { JSONObject msg = new JSONObject(); @@ -123,7 +146,21 @@ } /** * HMAC-SHA512 签名,使用 UTF-8 编码。 * HMAC-SHA512 签名计算。 * * <h3>签名算法</h3> * <pre> * message = "channel={channelName}&event={event}&time={timeSec}" * SIGN = Hex(HmacSHA512(apiSecret(UTF-8), message(UTF-8))) * </pre> * * <h3>错误处理</h3> * 签名计算失败时返回空字符串(日志记录错误),不抛异常, * 避免阻塞 WebSocket 回调线程。 * * @param event 事件类型 * @param timeSec unix 时间戳(秒) * @return 十六进制签名字符串,失败返回 "" */ private String hs512Sign(String event, long timeSec) { try { src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/CandlestickChannelHandler.java
@@ -43,9 +43,23 @@ this.gridTradeService = gridTradeService; } /** @return 频道名称 "futures.candlesticks" */ @Override public String getChannelName() { return CHANNEL_NAME; } /** * 发送 K 线频道订阅请求(公开频道,无需签名)。 * * <h3>订阅格式</h3> * <pre> * { * "time": <unix时间戳(秒)>, * "channel": "futures.candlesticks", * "event": "subscribe", * "payload": ["1m", "{contract}"] * } * </pre> */ @Override public void subscribe(WebSocketClient ws) { JSONObject msg = new JSONObject(); @@ -60,6 +74,9 @@ log.info("[{}] 订阅成功, 合约:{}, 周期:{}", CHANNEL_NAME, contract, INTERVAL); } /** * 发送 K 线频道取消订阅请求。 */ @Override public void unsubscribe(WebSocketClient ws) { JSONObject msg = new JSONObject(); @@ -74,6 +91,25 @@ log.info("[{}] 取消订阅成功", CHANNEL_NAME); } /** * 处理 K 线推送消息。 * * <h3>数据提取</h3> * result[0] 中提取: * <ul> * <li>c(close):收盘价 → 传给 gridTradeService.onKline()</li> * <li>n(name):烛线名称(如 "1m_ETH_USDT")</li> * <li>t(time):烛线起始时间戳</li> * <li>w(window_close):烛线是否完结(仅日志输出,不做门控)</li> * </ul> * * <h3>注意</h3> * 不判断 w(已完结)——策略需要 tick 级实时响应价格变动, * 而非等 1 分钟烛线完结后才行动。 * * @param response WebSocket 推送的完整 JSON * @return true 表示已处理(匹配成功) */ @Override public boolean handleMessage(JSONObject response) { if (!CHANNEL_NAME.equals(response.getString("channel"))) { @@ -87,10 +123,7 @@ log.info("========== Gate K线数据 =========="); log.info("名称: {} 时间: {}", data.getString("n"), DateUtil.TimeStampToDateTime(data.getLong("t"))); log.info("开盘: {} 最高: {} 最低: {} 收盘: {} 成交量: {} 成交额: {} 已完结: {}", data.getString("o"), data.getString("h"), data.getString("l"), data.getString("c"), data.getString("v"), data.getString("a"), data.getBooleanValue("w")); log.info("收盘: {} 已完结: {}",data.getString("c"),data.getBooleanValue("w")); log.info("=================================="); if (gridTradeService != null) { src/main/java/com/xcong/excoin/modules/gateApi/wsHandler/handler/PositionClosesChannelHandler.java
@@ -35,6 +35,24 @@ super(CHANNEL_NAME, apiKey, apiSecret, contract, gridTradeService); } /** * 处理平仓推送消息。 * * <h3>数据提取</h3> * result 数组中每个元素包含: * <ul> * <li>contract:合约名称</li> * <li>side:平仓方向("long" / "short")</li> * <li>pnl:本次平仓的盈亏金额(字符串格式,如 "+0.2" / "-0.1")</li> * </ul> * * <h3>数据处理</h3> * 按合约名称过滤 → 提取 pnl 和 side → 调用 gridTradeService.onPositionClose() 累加盈亏。 * pnl 来自服务端,不受本地计算误差影响。 * * @param response WebSocket 推送的完整 JSON * @return true 表示已处理(匹配成功) */ @Override public boolean handleMessage(JSONObject response) { if (!CHANNEL_NAME.equals(response.getString("channel"))) {