| | |
| | | import io.gate.gateapi.auth.*; |
| | | import io.gate.gateapi.models.*; |
| | | import io.gate.gateapi.api.AccountApi; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | |
| | | import java.io.IOException; |
| | | import java.math.BigDecimal; |
| | | |
| | | |
| | | @Slf4j |
| | | public class Example { |
| | | public static void main(String[] args) { |
| | | ApiClient defaultClient = Configuration.getDefaultApiClient(); |
| | |
| | | |
| | | try { |
| | | |
| | | String contract = "ETH_USDT"; |
| | | String settle = "usdt"; |
| | | String CONTRACT = "ETH_USDT"; |
| | | String SETTLE = "usdt"; |
| | | //保证金模式 isolated/cross |
| | | String marginMode = "cross"; |
| | | AccountApi accountApi = new AccountApi(defaultClient); |
| | | AccountDetail accountDetail = accountApi.getAccountDetail(); |
| | | System.out.println(accountDetail.toString()); |
| | | |
| | | |
| | | /** |
| | | * 获取账户余额 |
| | | */ |
| | | String MARGINMODE = "CROSS"; |
| | | String LEVERAGE = "100"; |
| | | FuturesApi futuresApi = new FuturesApi(defaultClient); |
| | | FuturesAccount futuresAccount = futuresApi.listFuturesAccounts(settle); |
| | | String available = futuresAccount.getAvailable(); |
| | | String result = "可用余额:" + available; |
| | | System.out.println(result); |
| | | FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE); |
| | | log.info("[Gate] 初始本金: {} USDT", account.getTotal()); |
| | | |
| | | /** |
| | | * 设置仓位模式 |
| | | * 可选值:single, dual, dual_plus,分别表示单向、双向、分仓 |
| | | */ |
| | | |
| | | String position_mode = "dual"; |
| | | String positionMode = futuresAccount.getPositionMode(); |
| | | if (!position_mode.equals(positionMode)){ |
| | | futuresApi.setPositionMode(settle, position_mode); |
| | | //设置持仓模式为双向持仓 |
| | | Boolean inDualMode = account.getInDualMode(); |
| | | if (!inDualMode) { |
| | | try { |
| | | futuresApi.setDualModeCall(SETTLE,true,null).execute(); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 设置杠杆倍数(双向持仓模式专用) |
| | | * 设置合理的杠杆倍数,不能为0 |
| | | */ |
| | | String leverage = "25"; |
| | | futuresApi.updateDualModePositionLeverageCall( |
| | | settle, |
| | | contract, |
| | | leverage, |
| | | marginMode, |
| | | null); |
| | | try { |
| | | futuresApi.updateDualModePositionLeverageCall( |
| | | SETTLE, CONTRACT, LEVERAGE, |
| | | null, null).execute(); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | |
| | | if (!MARGINMODE.equals(account.getMarginMode())) { |
| | | |
| | | UpdateDualCompPositionCrossModeRequest updateDualCompPositionCrossModeRequest = new UpdateDualCompPositionCrossModeRequest(); |
| | | updateDualCompPositionCrossModeRequest.setMode(MARGINMODE); |
| | | updateDualCompPositionCrossModeRequest.setContract(CONTRACT); |
| | | try { |
| | | futuresApi.updateDualCompPositionCrossModeCall(SETTLE, updateDualCompPositionCrossModeRequest, null).execute(); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | } catch (GateApiException e) { |
| | | System.err.println(String.format("Gate api exception, label: %s, message: %s", e.getErrorLabel(), e.getMessage())); |
| | | e.printStackTrace(); |
| | | } catch (ApiException e) { |
| | | System.err.println("Exception when calling AccountApi#getAccountDetail"); |
| | | System.err.println("Status code: " + e.getCode()); |
| | | System.err.println("Response headers: " + e.getResponseHeaders()); |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | |
| | | import io.gate.gateapi.GateApiException; |
| | | import io.gate.gateapi.api.AccountApi; |
| | | import io.gate.gateapi.api.FuturesApi; |
| | | import io.gate.gateapi.models.AccountDetail; |
| | | import io.gate.gateapi.models.FuturesAccount; |
| | | import io.gate.gateapi.models.FuturesOrder; |
| | | import io.gate.gateapi.models.FuturesPriceTrigger; |
| | | import io.gate.gateapi.models.Position; |
| | | import io.gate.gateapi.models.*; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | |
| | | import java.io.IOException; |
| | | import java.math.BigDecimal; |
| | | import java.math.RoundingMode; |
| | | import java.util.ArrayList; |
| | |
| | | * |
| | | * ACTIVE: |
| | | * ├─ 每根K线 → 更新 unrealizedPnl + processShortGrid + processLongGrid |
| | | * │ ├─ 当前价 < 空仓队列元素 → 匹配 → 开空 + 队列元素转移到多仓队列 |
| | | * │ └─ 当前价 > 多仓队列元素 → 匹配 → 开多 + 队列元素转移到空仓队列 |
| | | * ├─ 仓位推送(非基底) → 设止盈条件单 entry × (1±gridRate) |
| | | * │ ├─ 当前价 < 空仓队列元素 → 匹配 → 开空 + 以多仓队列首元素为种子生成新元素加入多仓队列 |
| | | * │ └─ 当前价 > 多仓队列元素 → 匹配 → 开多 + 以空仓队列首元素为种子生成新元素加入空仓队列 |
| | | * ├─ 仓位推送(非基底) → 设止盈条件单 entry × (1±gridRate),使用 plan-close-*-position |
| | | * ├─ 保证金≥初始本金 marginRatioLimit → 跳过开仓,队列照常更新 |
| | | * ├─ 额外反向开仓:触发价夹在多/空持仓均价之间且多持仓均价>空持仓均价时,额外反向开仓一次 |
| | | * └─ cumulativePnl ≥ overallTp 或 ≤ -maxLoss → STOPPED |
| | | * </pre> |
| | | * |
| | | * <h3>队列转移规则</h3> |
| | | * 触发后不再简单复制 matched 元素到对方队列,而是以对方队列首元素为种子,生成新元素: |
| | | * <ul> |
| | | * <li>空仓队列触发 → 多仓队列新增:以多仓队列首元素(最小价)为基准,生成递减元素</li> |
| | | * <li>多仓队列触发 → 空仓队列新增:以空仓队列首元素(最高价)为基准,生成递增元素</li> |
| | | * </ul> |
| | | * |
| | | * <h3>贴近持仓均价过滤</h3> |
| | | * 转移生成新元素时,若新元素与对应方向持仓均价的差距小于 gridRate,则跳过该元素, |
| | | * 避免在持仓成本附近生成无效网格线。 |
| | | * |
| | | * <h3>额外反向开仓条件</h3> |
| | | * 当触发价在空仓均价和回撤后的多仓均价之间(即多>空且价格夹在中间),额外反向开仓一次: |
| | | * <ul> |
| | | * <li>空仓队列触发 → 额外开多:需满足 shortEntryPrice < currentPrice < longEntryPrice × (1 − gridRate)</li> |
| | | * <li>多仓队列触发 → 额外开空:需满足 shortEntryPrice × (1 + gridRate) < currentPrice < longEntryPrice</li> |
| | | * </ul> |
| | | * |
| | | * <h3>止盈条件单</h3> |
| | | * 使用 Gate API 的 plan-close-long-position / plan-close-short-position(仓位计划止盈止损), |
| | | * 支持指定张数部分平仓。每次网格触发开仓 quantity 张,只为该批张数创建独立条件单,互不覆盖。 |
| | | * |
| | | * @author Administrator |
| | | */ |
| | |
| | | WAITING_KLINE, OPENING, ACTIVE, STOPPED |
| | | } |
| | | |
| | | 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"; |
| | | /** |
| | | * 止盈条件单 order_type:仓位计划止盈止损 — 平多仓(支持部分平仓,size<0)。 |
| | | * 注意:不能用 close-long-position(仅支持全平且双仓需 auto_size), |
| | | * 必须用 plan-close-long-position 以支持指定张数部分平仓。 |
| | | */ |
| | | private static final String ORDER_TYPE_CLOSE_LONG = "plan-close-long-position"; |
| | | /** |
| | | * 止盈条件单 order_type:仓位计划止盈止损 — 平空仓(支持部分平仓,size>0)。 |
| | | * 注意:不能用 close-short-position(仅支持全平且双仓需 auto_size), |
| | | * 必须用 plan-close-short-position 以支持指定张数部分平仓。 |
| | | */ |
| | | private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position"; |
| | | |
| | | private final GateConfig config; |
| | | private final GateTradeExecutor executor; |
| | |
| | | this.initialPrincipal = new BigDecimal(account.getTotal()); |
| | | log.info("[Gate] 初始本金: {} USDT", initialPrincipal); |
| | | |
| | | if (!config.getPositionMode().equals(account.getPositionMode())) { |
| | | futuresApi.setPositionMode(SETTLE, config.getPositionMode()); |
| | | } |
| | | log.info("[Gate] 持仓模式: {} 余额: {}", config.getPositionMode(), account.getAvailable()); |
| | | |
| | | futuresApi.cancelPriceTriggeredOrderList(SETTLE, config.getContract()); |
| | | log.info("[Gate] 旧条件单已清除"); |
| | | |
| | | closeExistingPositions(); |
| | | |
| | | futuresApi.updateDualModePositionLeverageCall( |
| | | SETTLE, config.getContract(), config.getLeverage(), |
| | | config.getMarginMode(), null); |
| | | //设置持仓模式为双向持仓 |
| | | Boolean inDualMode = account.getInDualMode(); |
| | | if (!inDualMode) { |
| | | try { |
| | | futuresApi.setDualModeCall(SETTLE,true,null).execute(); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | |
| | | try { |
| | | futuresApi.updateDualModePositionLeverageCall( |
| | | SETTLE, config.getContract(), config.getLeverage(), |
| | | null, null).execute(); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | |
| | | if (!config.getMarginMode().equals(account.getMarginMode())) { |
| | | |
| | | UpdateDualCompPositionCrossModeRequest updateDualCompPositionCrossModeRequest = new UpdateDualCompPositionCrossModeRequest(); |
| | | updateDualCompPositionCrossModeRequest.setMode(config.getMarginMode()); |
| | | updateDualCompPositionCrossModeRequest.setContract(config.getContract()); |
| | | try { |
| | | futuresApi.updateDualCompPositionCrossModeCall(SETTLE, updateDualCompPositionCrossModeRequest, null).execute(); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | log.info("[Gate] 持仓模式: {} 余额: {}", config.getPositionMode(), account.getAvailable()); |
| | | log.info("[Gate] 杠杆: {}x {}", config.getLeverage(), config.getMarginMode()); |
| | | } catch (GateApiException e) { |
| | | log.error("[Gate] 初始化失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage()); |
| | |
| | | } 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, AUTO_SIZE_LONG); |
| | | log.info("[Gate] 多单止盈已设, entry:{}, tp:{}", entryPrice, tpPrice); |
| | | FuturesPriceTrigger.RuleEnum.NUMBER_1, ORDER_TYPE_CLOSE_LONG, negate(config.getQuantity())); |
| | | log.info("[Gate] 多单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, negate(config.getQuantity())); |
| | | } |
| | | } else { |
| | | longActive = false; |
| | |
| | | } 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, AUTO_SIZE_SHORT); |
| | | log.info("[Gate] 空单止盈已设, entry:{}, tp:{}", entryPrice, tpPrice); |
| | | FuturesPriceTrigger.RuleEnum.NUMBER_2, ORDER_TYPE_CLOSE_SHORT, config.getQuantity()); |
| | | log.info("[Gate] 空单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, config.getQuantity()); |
| | | } |
| | | } else { |
| | | shortActive = false; |
| | |
| | | log.info("[Gate] 多队列:{}", longPriceQueue); |
| | | } |
| | | |
| | | /** |
| | | * 空仓网格处理(价格跌破空仓队列中的高价)。 |
| | | * |
| | | * <h3>匹配规则</h3> |
| | | * 遍历空仓队列(降序),收集所有大于当前价的元素为 matched。 |
| | | * 队列为降序排列,一旦遇 price ≤ currentPrice 即停止遍历。 |
| | | * |
| | | * <h3>执行流程</h3> |
| | | * <ol> |
| | | * <li>匹配队列元素 → 为空则直接返回</li> |
| | | * <li>保证金检查 → 安全则开空一次</li> |
| | | * <li>额外反向开多:若多仓均价 > 空仓均价 且 当前价夹在中间且远离多仓均价</li> |
| | | * <li>空仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 − gridRate) 循环递减)</li> |
| | | * <li>多仓队列:以多仓队列首元素(最小价)为种子,生成 matched.size() 个递减元素加入</li> |
| | | * </ol> |
| | | * |
| | | * <h3>多仓队列转移过滤</h3> |
| | | * 新增元素若与多仓持仓均价差距小于 gridRate,则跳过该元素(避免在持仓成本附近生成无效网格线)。 |
| | | */ |
| | | private void processShortGrid(BigDecimal currentPrice) { |
| | | List<BigDecimal> matched = new ArrayList<>(); |
| | | synchronized (shortPriceQueue) { |
| | |
| | | } |
| | | } |
| | | } |
| | | log.info("[Gate] 原空队列:{}", shortPriceQueue); |
| | | if (matched.isEmpty()) { |
| | | log.info("[Gate] 空仓队列未触发, 当前价:{}", currentPrice); |
| | | return; |
| | | } |
| | | |
| | | log.info("[Gate] 空仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice); |
| | | if (!isMarginSafe()) { |
| | | log.warn("[Gate] 保证金超限,跳过空单开仓"); |
| | | } else { |
| | | executor.openShort(negate(config.getQuantity()), null, null); |
| | | if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | | && longEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | | && longEntryPrice.compareTo(shortEntryPrice) > 0 |
| | | && currentPrice.compareTo(shortEntryPrice) > 0 |
| | | && currentPrice.compareTo(longEntryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate()))) < 0) { |
| | | executor.openLong(config.getQuantity(), null, null); |
| | | log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", currentPrice); |
| | | } |
| | | } |
| | | |
| | | synchronized (shortPriceQueue) { |
| | |
| | | min = min.multiply(BigDecimal.ONE.subtract(step)).setScale(1, RoundingMode.HALF_UP); |
| | | shortPriceQueue.add(min); |
| | | } |
| | | shortPriceQueue.sort((a, b) -> b.compareTo(a)); |
| | | shortPriceQueue.sort(BigDecimal::compareTo); |
| | | |
| | | log.info("[Gate] 现空队列:{}", shortPriceQueue); |
| | | } |
| | | |
| | | synchronized (longPriceQueue) { |
| | | longPriceQueue.addAll(matched); |
| | | 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); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 多仓网格处理(价格涨破多仓队列中的低价)。 |
| | | * |
| | | * <h3>匹配规则</h3> |
| | | * 遍历多仓队列(升序),收集所有小于当前价的元素为 matched。 |
| | | * 队列为升序排列,一旦遇 price ≥ currentPrice 即停止遍历。 |
| | | * |
| | | * <h3>执行流程</h3> |
| | | * <ol> |
| | | * <li>匹配队列元素 → 为空则直接返回</li> |
| | | * <li>保证金检查 → 安全则开多一次</li> |
| | | * <li>额外反向开空:若多仓均价 > 空仓均价 且 当前价夹在中间且远离空仓均价</li> |
| | | * <li>多仓队列:移除 matched 元素,尾部补充新元素(尾价 × (1 + gridRate) 循环递增)</li> |
| | | * <li>空仓队列:以空仓队列首元素(最高价)为种子,生成 matched.size() 个递增元素加入</li> |
| | | * </ol> |
| | | * |
| | | * <h3>空仓队列转移过滤</h3> |
| | | * 新增元素若与空仓持仓均价差距小于 gridRate,则跳过该元素(避免在持仓成本附近生成无效网格线)。 |
| | | */ |
| | | private void processLongGrid(BigDecimal currentPrice) { |
| | | List<BigDecimal> matched = new ArrayList<>(); |
| | | synchronized (longPriceQueue) { |
| | |
| | | } |
| | | } |
| | | } |
| | | log.info("[Gate] 原多队列:{}", longPriceQueue); |
| | | if (matched.isEmpty()) { |
| | | log.info("[Gate] 多仓队列未触发, 当前价:{}", currentPrice); |
| | | return; |
| | | } |
| | | |
| | |
| | | log.warn("[Gate] 保证金超限,跳过多单开仓"); |
| | | } else { |
| | | executor.openLong(config.getQuantity(), null, null); |
| | | if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | | && longEntryPrice.compareTo(BigDecimal.ZERO) > 0 |
| | | && longEntryPrice.compareTo(shortEntryPrice) > 0 |
| | | && currentPrice.compareTo(shortEntryPrice.multiply(BigDecimal.ONE.add(config.getGridRate()))) > 0 |
| | | && currentPrice.compareTo(longEntryPrice) < 0) { |
| | | executor.openShort(negate(config.getQuantity()), null, null); |
| | | log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", currentPrice); |
| | | } |
| | | } |
| | | |
| | | synchronized (longPriceQueue) { |
| | |
| | | longPriceQueue.add(max); |
| | | } |
| | | longPriceQueue.sort(BigDecimal::compareTo); |
| | | |
| | | log.info("[Gate] 现多队列:{}", longPriceQueue); |
| | | } |
| | | |
| | | synchronized (shortPriceQueue) { |
| | | shortPriceQueue.addAll(matched); |
| | | 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); |
| | | } |
| | | } |
| | | |
| | |
| | | package com.xcong.excoin.modules.gateApi; |
| | | |
| | | import io.gate.gateapi.ApiClient; |
| | | import io.gate.gateapi.GateApiException; |
| | | import io.gate.gateapi.api.FuturesApi; |
| | | import io.gate.gateapi.models.FuturesInitialOrder; |
| | | import io.gate.gateapi.models.FuturesOrder; |
| | |
| | | } |
| | | |
| | | /** |
| | | * 异步创建止盈条件单。 |
| | | * <p>使用 Gate 的 PriceTriggeredOrder:服务器监控价格,达到触发价后自动平仓。 |
| | | * 如果账户已有同方向同规则的条件单(label=UNIQUE),自动清除后重试一次。 |
| | | * 异步创建止盈条件单(仓位计划止盈止损)。 |
| | | * |
| | | * <p>使用 Gate 的 {@code PriceTriggeredOrder} API:服务器监控价格,达到触发价后自动平指定张数。 |
| | | * order_type 使用 {@code plan-close-*-position}(仓位计划止盈止损), |
| | | * 支持指定 size 部分平仓,多次触发的止盈单互不影响。 |
| | | * |
| | | * <h3>为何不用 close-*-position</h3> |
| | | * {@code close-long-position} / {@code close-short-position} 仅支持全部平仓(size=0), |
| | | * 且双仓模式还需额外设置 {@code auto_size}。网格策略需要指定张数部分平仓, |
| | | * 因此必须使用 {@code plan-close-long-position} / {@code plan-close-short-position}。 |
| | | * |
| | | * @param triggerPrice 触发价格 |
| | | * @param rule 触发规则(NUMBER_1: ≥ 触发价,NUMBER_2: ≤ 触发价) |
| | | * @param orderType stop 类型(close-long-position / close-short-position) |
| | | * @param autoSize 双仓平仓方向(close_long / close_short) |
| | | * @param orderType stop 类型(plan-close-long-position / plan-close-short-position) |
| | | * @param size 平仓张数(正=平空,负=平多) |
| | | */ |
| | | public void placeTakeProfit(BigDecimal triggerPrice, |
| | | FuturesPriceTrigger.RuleEnum rule, |
| | | String orderType, |
| | | String autoSize) { |
| | | String size) { |
| | | executor.execute(() -> { |
| | | FuturesPriceTriggeredOrder order = buildTriggeredOrder(triggerPrice, rule, orderType, autoSize); |
| | | FuturesPriceTriggeredOrder order = buildTriggeredOrder(triggerPrice, rule, orderType, size); |
| | | try { |
| | | TriggerOrderResponse response = futuresApi.createPriceTriggeredOrder(SETTLE, order); |
| | | log.info("[TradeExec] 止盈单已创建, 触发价:{}, 类型:{}, id:{}", |
| | | triggerPrice, orderType, response.getId()); |
| | | } catch (GateApiException e) { |
| | | if ("AUTO_USER_EXIST_POSITION_ORDER".equals(e.getErrorLabel())) { |
| | | log.warn("[TradeExec] 止盈单已存在,清除旧单后重试"); |
| | | try { |
| | | futuresApi.cancelPriceTriggeredOrderList(SETTLE, contract); |
| | | TriggerOrderResponse response = futuresApi.createPriceTriggeredOrder(SETTLE, order); |
| | | log.info("[TradeExec] 止盈单重试成功, 触发价:{}, id:{}", triggerPrice, response.getId()); |
| | | } catch (Exception retryEx) { |
| | | log.error("[TradeExec] 止盈单重试失败", retryEx); |
| | | } |
| | | } else { |
| | | log.error("[TradeExec] 止盈单创建失败, 触发价:{}", triggerPrice, e); |
| | | } |
| | | log.info("[TradeExec] 止盈单已创建, 触发价:{}, 类型:{}, size:{}, id:{}", |
| | | triggerPrice, orderType, size, response.getId()); |
| | | } catch (Exception e) { |
| | | log.error("[TradeExec] 止盈单创建失败, 触发价:{}", triggerPrice, e); |
| | | log.error("[TradeExec] 止盈单创建失败, 触发价:{}, size:{}", triggerPrice, size, e); |
| | | } |
| | | }); |
| | | } |
| | |
| | | |
| | | /** |
| | | * 构建 FuturesPriceTriggeredOrder 对象。 |
| | | * |
| | | * <p>策略=0(价格触发),price_type=0(最新价),expiration=0(永不过期), |
| | | * tif=IOC(立即成交或取消),reduce_only=true(只减仓不开新仓)。 |
| | | * |
| | | * <h3>size 参数说明</h3> |
| | | * <ul> |
| | | * <li>plan-close-long-position:size 为负,表示平多仓多少张</li> |
| | | * <li>plan-close-short-position:size 为正,表示平空仓多少张</li> |
| | | * </ul> |
| | | * 每次只平指定张数,不会全平仓位,多个止盈单可并存且互不影响。 |
| | | */ |
| | | private FuturesPriceTriggeredOrder buildTriggeredOrder(BigDecimal triggerPrice, |
| | | FuturesPriceTrigger.RuleEnum rule, |
| | | String orderType, |
| | | String autoSize) { |
| | | String size) { |
| | | FuturesPriceTrigger trigger = new FuturesPriceTrigger(); |
| | | trigger.setStrategyType(FuturesPriceTrigger.StrategyTypeEnum.NUMBER_0); |
| | | trigger.setPriceType(FuturesPriceTrigger.PriceTypeEnum.NUMBER_0); |
| | |
| | | |
| | | FuturesInitialOrder initial = new FuturesInitialOrder(); |
| | | initial.setContract(contract); |
| | | initial.setSize(0L); |
| | | initial.setSize(Long.parseLong(size)); |
| | | initial.setPrice("0"); |
| | | initial.setTif(FuturesInitialOrder.TifEnum.IOC); |
| | | initial.setReduceOnly(true); |
| | | initial.setAutoSize(autoSize); |
| | | |
| | | FuturesPriceTriggeredOrder order = new FuturesPriceTriggeredOrder(); |
| | | order.setTrigger(trigger); |
| | |
| | | .apiSecret("1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274") |
| | | .contract("ETH_USDT") |
| | | .leverage("100") |
| | | .marginMode("cross") |
| | | .marginMode("CROSS") |
| | | .positionMode("dual") |
| | | .gridRate(new BigDecimal("0.004")) |
| | | .overallTp(new BigDecimal("0.5")) |
| | | .maxLoss(new BigDecimal("7.5")) |
| | | .gridRate(new BigDecimal("0.0015")) |
| | | .overallTp(new BigDecimal("5")) |
| | | .maxLoss(new BigDecimal("15")) |
| | | .quantity("1") |
| | | .contractMultiplier(new BigDecimal("0.01")) |
| | | .unrealizedPnlPriceMode(GateConfig.PnLPriceMode.LAST_PRICE) |
| | |
| | | | [GateWebSocketClientManager](#gatewebsocketclientmanager) | `@Component` | Spring 启动入口,组装组件 + 生命周期 | |
| | | | [GateConfig](#gateconfig) | 配置 | Builder 模式:API 密钥、合约、策略参数、环境切换 | |
| | | | [GateKlineWebSocketClient](#gateklinewebsocketclient) | WS 连接管理 | 连接/心跳/重连/消息路由 | |
| | | | [GateGridTradeService](#gategridtradeservice) | 交易服务 | 网格队列策略 + 保证金安全阀 + 盈亏管理 | |
| | | | [GateGridTradeService](#gategridtradeservice) | 交易服务 | 网格队列策略 + 保证金安全阀 + 盈亏管理 + 额外反向开仓 | |
| | | | [GateTradeExecutor](#gatetradeexecutor) | 异步执行器 | 独立线程池执行 REST 下单,成功/失败双回调 | |
| | | | [GateWebSocketClientMain](#gatewebsocketclientmain) | main 入口 | 独立测试启动 | |
| | | | [Example.java](#examplejava) | 示例 | Gate SDK 用法参考 | |
| | |
| | | | `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/PositionsChannelHandler.java` | 私有频道 | 仓位推送 → `onPositionUpdate()`(传 `Position.ModeEnum`),日志输出全部20个推送字段 | |
| | | | `wsHandler/handler/PositionClosesChannelHandler.java` | 私有频道 | 平仓推送 → `onPositionClose()` | |
| | | |
| | | --- |
| | |
| | | ├─ futures.positions (私有, HMAC-SHA512) |
| | | │ └─ PositionsChannelHandler |
| | | │ ├─ 解析 mode → Position.ModeEnum(DUAL_LONG / DUAL_SHORT) |
| | | │ ├─ 日志输出全部 20 个推送字段(contract/mode/size/entry_price/.../update_id) |
| | | │ └─ gridTradeService.onPositionUpdate(contract, mode, size, entryPrice) |
| | | │ ├─ 有仓位: 标记活跃,首次成交记录入场价并设止盈 |
| | | │ │ ├─ 基底开仓 → 首次成交 → 记录基底入场价 → 双基底都成交后生成网格队列 |
| | | │ │ └─ 网格开仓 → 成交后立即设止盈单 |
| | | │ │ └─ 网格开仓 → 成交后立即设止盈单(plan-close-*-position) |
| | | │ └─ 无仓位(size=0): 标记不活跃 |
| | | │ |
| | | ├─ futures.position_closes (私有, HMAC-SHA512) |
| | |
| | | └─ 所有下单操作 |
| | | └─ GateTradeExecutor (单线程 + 64队列 + CallerRunsPolicy) |
| | | ├─ openLong/Short(qty, onSuccess, onFailure) |
| | | └─ placeTakeProfit → 条件单 (REST) |
| | | └─ placeTakeProfit → 条件单(plan-close-*-position, REST) |
| | | ``` |
| | | |
| | | ### PositionsChannelHandler 完整推送字段(20个) |
| | | |
| | | | 字段 | 类型 | 描述 | |
| | | |------|------|------| |
| | | | contract | String | 合约名称 | |
| | | | mode | String | 持仓模式:dual_long / dual_short | |
| | | | size | String/Integer | 合约张数(正=多头,负=空头) | |
| | | | entry_price | Float | 开仓均价 | |
| | | | cross_leverage_limit | Float | 全仓模式下的杠杆倍数上限 | |
| | | | history_pnl | Float | 已平仓的仓位总盈亏 | |
| | | | history_point | Float | 已平仓的点卡总盈亏 | |
| | | | last_close_pnl | Float | 最近一次平仓的盈亏 | |
| | | | leverage | Integer | 杠杆倍数(0=全仓,正数=逐仓) | |
| | | | leverage_max | Integer | 当前风险限额下允许的最大杠杆倍数 | |
| | | | liq_price | Float | 爆仓价格 | |
| | | | maintenance_rate | Float | 当前风险限额下维持保证金比例 | |
| | | | margin | Float | 保证金 | |
| | | | realised_pnl | Float | 已实现盈亏 | |
| | | | realised_point | Float | 点卡已实现盈亏 | |
| | | | risk_limit | Integer | 风险限额 | |
| | | | time | Integer | 更新 unix 时间戳(秒) | |
| | | | time_ms | Integer | 更新 unix 时间戳(毫秒) | |
| | | | user | String | 用户 ID | |
| | | | update_id | Integer | 消息序列号,每次推送 order 后自增1 | |
| | | |
| | | > 以上 20 个字段在 PositionsChannelHandler.handleMessage() 中通过 SLF4J 日志全部输出。 |
| | | > 回调给 GateGridTradeService.onPositionUpdate() 的仅有 mode、size、entryPrice 三个核心字段。 |
| | | |
| | | --- |
| | | |
| | |
| | | GateChannelHandler (接口) |
| | | ├── CandlestickChannelHandler (公开频道) |
| | | └── AbstractPrivateChannelHandler (私有频道基类: HMAC-SHA512) |
| | | ├── PositionsChannelHandler (解析 mode → Position.ModeEnum) |
| | | ├── PositionsChannelHandler (解析 mode → Position.ModeEnum,日志输出20个字段) |
| | | └── PositionClosesChannelHandler |
| | | ``` |
| | | |
| | |
| | | │ │ ├─ cumPnl ≥ overallTp → STOPPED |
| | | │ │ ├─ cumPnl ≤ -maxLoss → STOPPED |
| | | │ │ ├─ 保证金超限 → 跳过开仓,队列照常更新 |
| | | │ │ └─ 网格触发 → 开仓+设止盈+队列转移 |
| | | │ │ ├─ 网格触发 → 开仓+设止盈+队列转移(以对方队列首元素为种子) |
| | | │ │ ├─ 多>空且价格夹在中间 → 额外反向开仓 |
| | | │ │ └─ 转移元素贴近持仓均价 → 跳过(过滤) |
| | | ▼ ▼ |
| | | STOPPED ←──────────────────┘ |
| | | ``` |
| | |
| | | |
| | | ### 概述 |
| | | |
| | | 策略采用"基底 + 价格网格队列"模式:先开一对基底多空仓位,然后以基底入场价为基准生成价格队列。每当K线穿破队列元素,就开新仓位并设止盈条件单,同时将穿破的元素转移到反方向队列。 |
| | | 策略采用"基底 + 价格网格队列"模式:先开一对基底多空仓位,然后以基底入场价为基准生成价格队列。每当K线穿破队列元素,就开新仓位并设止盈条件单,同时以对方队列首元素为种子生成新元素加入对方队列。 |
| | | |
| | | ### 基底开仓 |
| | | |
| | |
| | | K线到达(ACTIVE状态): |
| | | │ |
| | | ├─ processShortGrid: 当前价 < 空仓队列元素(价格跌破了队列中的高价) |
| | | │ ├─ 匹配: 收集所有 > 当前价的空仓队列元素 |
| | | │ ├─ 匹配: 收集所有 > 当前价的空仓队列元素(降序,一旦遇≤即停止) |
| | | │ ├─ 保证金检查: positionInitialMargin / initialPrincipal < marginRatioLimit(20%) |
| | | │ │ ├─ 安全 → openShort 开空单(成交后仓位推送会自动设止盈) |
| | | │ │ ├─ 安全 → openShort 开空单 |
| | | │ │ │ └─ 额外条件: 多>空 且 空仓均价 < 当前价 < 多仓均价×(1−gridRate) → openLong 额外开多一次 |
| | | │ │ └─ 超限 → 跳过开仓,队列照常更新 |
| | | │ ├─ 空仓队列: 移除匹配元素,尾部补充新价格(尾价 × (1 − gridRate)) |
| | | │ └─ 多仓队列: 接收匹配元素,升序排列,截断到 gridQueueSize |
| | | │ ├─ 空仓队列: 移除 matched,尾部补充新元素(尾价 × (1−gridRate) 循环递减) |
| | | │ └─ 多仓队列转移: |
| | | │ ├─ 以多仓队列首元素(最小价)为种子 |
| | | │ ├─ 生成 matched.size() 个递减元素: seed × (1 − gridRate × i) |
| | | │ ├─ 贴近过滤: |elem − longEntryPrice| < longEntryPrice × gridRate → 跳过 |
| | | │ └─ 升序排列,截断到 gridQueueSize |
| | | │ |
| | | └─ processLongGrid: 当前价 > 多仓队列元素(价格涨超了队列中的低价) |
| | | ├─ 匹配: 收集所有 < 当前价的多仓队列元素 |
| | | ├─ 匹配: 收集所有 < 当前价的多仓队列元素(升序,一旦遇≥即停止) |
| | | ├─ 保证金检查: 同上 |
| | | │ ├─ 安全 → openLong 开多单 |
| | | │ │ └─ 额外条件: 多>空 且 空仓均价×(1+gridRate) < 当前价 < 多仓均价 → openShort 额外开空一次 |
| | | │ └─ 超限 → 跳过开仓 |
| | | ├─ 多仓队列: 移除匹配元素,尾部补充新价格(尾价 × (1 + gridRate)) |
| | | └─ 空仓队列: 接收匹配元素,降序排列,截断到 gridQueueSize |
| | | ├─ 多仓队列: 移除 matched,尾部补充新元素(尾价 × (1+gridRate) 循环递增) |
| | | └─ 空仓队列转移: |
| | | ├─ 以空仓队列首元素(最高价)为种子 |
| | | ├─ 生成 matched.size() 个递增元素: seed × (1 + gridRate × i) |
| | | ├─ 贴近过滤: |elem − shortEntryPrice| < shortEntryPrice × gridRate → 跳过 |
| | | └─ 降序排列,截断到 gridQueueSize |
| | | ``` |
| | | |
| | | ### 队列转移规则(新) |
| | | |
| | | 触发后**不再简单复制** matched 元素到对方队列,而是以对方队列首元素为种子生成新元素: |
| | | |
| | | | 触发方向 | 目标队列 | 种子元素 | 生成公式 | 排序 | |
| | | |---------|---------|---------|---------|------| |
| | | | 空仓触发 → | 多仓队列 | 多仓队列首元素(最小价) | 种子 × (1 − gridRate × i) | 升序 | |
| | | | 多仓触发 → | 空仓队列 | 空仓队列首元素(最高价) | 种子 × (1 + gridRate × i) | 降序 | |
| | | |
| | | ### 贴近持仓均价过滤(新) |
| | | |
| | | 转移生成新元素时,若元素与对应方向持仓均价的差距小于 gridRate,则跳过: |
| | | |
| | | | 目标队列 | 过滤条件 | 含义 | |
| | | |---------|---------|------| |
| | | | 多仓队列 | \|elem − longEntryPrice\| < longEntryPrice × gridRate | 太贴近多仓成本,跳过 | |
| | | | 空仓队列 | \|elem − shortEntryPrice\| < shortEntryPrice × gridRate | 太贴近空仓成本,跳过 | |
| | | |
| | | > 过滤仅在对应方向有持仓时生效(entryPrice > 0),避免在持仓成本附近生成无效网格线。 |
| | | |
| | | ### 额外反向开仓条件(新) |
| | | |
| | | 当触发价夹在多/空持仓均价之间,且多仓均价大于空仓均价(多>空倒挂)时,额外反向开仓一次: |
| | | |
| | | | 触发方向 | 额外操作 | 条件 | |
| | | |---------|---------|------| |
| | | | 空仓队列触发 | 额外开多 | shortEntryPrice > 0 && longEntryPrice > shortEntryPrice && shortEntryPrice < currentPrice < longEntryPrice × (1 − gridRate) | |
| | | | 多仓队列触发 | 额外开空 | shortEntryPrice > 0 && longEntryPrice > shortEntryPrice && shortEntryPrice × (1 + gridRate) < currentPrice < longEntryPrice | |
| | | |
| | | **条件解释:** |
| | | - `longEntryPrice > shortEntryPrice`:多仓均价高于空仓均价("倒挂"状态) |
| | | - `shortEntryPrice × (1 + gridRate) < currentPrice`:空仓触发时金额够远离空仓均价 |
| | | - `currentPrice < longEntryPrice × (1 − gridRate)`:空仓触发时金额够远离多仓均价 |
| | | |
| | | > 背后的思路:当"多亏空赚"发生倒挂时,在价格区间中间补一单反方向仓位,利用均值回归获利。 |
| | | |
| | | ### 队列转移示意 |
| | | |
| | | ``` |
| | | ETH_USDT, gridRate=0.0035, 基底空入场价=2275, 基底多入场价=2275: |
| | | ETH_USDT, gridRate=0.0035, 空仓均价=2270, 多仓均价=2280, gridQueueSize=4: |
| | | |
| | | 初始状态: |
| | | 空仓队列: [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...) |
| | | 空仓队列: [2567.1, 2570.0, 2572.5, 2575.0] (降序) |
| | | 多仓队列: [2275.0, 2277.0, 2279.0, 2281.5] (升序) |
| | | |
| | | 价格跌到 2271 → processShortGrid 触发: |
| | | 匹配: [2275.0, 2272.5](都 > 2271) |
| | | 价格跌到 2571 → processShortGrid 触发: |
| | | 匹配: [2575.0, 2572.5](都 > 2571) |
| | | |
| | | 空仓队列: 移除[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] |
| | | 空仓队列: 移除[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 ? 否 |
| | | → 不触发额外开多 |
| | | ``` |
| | | |
| | | --- |
| | |
| | | 每根K线 → onKline → updateUnrealizedPnl → processShortGrid + processLongGrid |
| | | |
| | | 仓位推送(每次开仓成交后自动触发): |
| | | → DUAL_LONG, size>0, 非基底 → 设多头止盈单 entryPrice × (1+gridRate) |
| | | → DUAL_SHORT, size<0, 非基底 → 设空头止盈单 entryPrice × (1-gridRate) |
| | | → DUAL_LONG, size>0, 非基底 → 设多头止盈单:止盈价=entryPrice×(1+gridRate), |
| | | 使用 plan-close-long-position,平仓张数=-quantity(负=平多) |
| | | → DUAL_SHORT, size<0, 非基底 → 设空头止盈单:止盈价=entryPrice×(1−gridRate), |
| | | 使用 plan-close-short-position,平仓张数=+quantity(正=平空) |
| | | |
| | | 额外反向开仓(多>空倒挂时): |
| | | → 空仓队列触发 + 条件满足 → 额外开多一次 |
| | | → 多仓队列触发 + 条件满足 → 额外开空一次 |
| | | ``` |
| | | |
| | | > 止盈由 Gate 服务端条件单自动执行。服务端监控价格,达到触发价后自动平仓。 |
| | | > 平仓后仓位变为0,盈亏通过 position_closes 频道推送到 cumulativePnl。 |
| | | > 每次网格触发开仓 quantity 张,只在该批张数上设止盈,与之前已设的止盈单互不影响。 |
| | | > 平仓后仓位减少 quantity 张,盈亏通过 position_closes 频道推送到 cumulativePnl。 |
| | | |
| | | ### 阶段 4:停止 |
| | | |
| | |
| | | |------|------| |
| | | | `openLong(qty, onSuccess, onFailure)` | 异步 IOC 市价开多,双回调 | |
| | | | `openShort(qty, onSuccess, onFailure)` | 异步 IOC 市价开空,双回调 | |
| | | | `placeTakeProfit(trigger, rule, type, auto)` | 异步条件单。已存在则清除旧单重试 | |
| | | | `placeTakeProfit(trigger, rule, type, size)` | 异步止盈条件单(plan-close-*-position)。size 为显式平仓张数(正=平空,负=平多),多次调用互不影响 | |
| | | | `cancelAllPriceTriggeredOrders()` | 清除所有条件单 | |
| | | | `shutdown()` | 等待10秒,超时强制关闭 | |
| | | |
| | | ### 止盈条件单 order_type 说明 |
| | | |
| | | | order_type | 用途 | size 语义 | |
| | | |-----------|------|----------| |
| | | | `plan-close-long-position` | 部分/全部平多仓 | size<0 表示平多仓张数 | |
| | | | `plan-close-short-position` | 部分/全部平空仓 | size>0 表示平空仓张数 | |
| | | |
| | | > **为何不用 close-*-position**:`close-long-position` 和 `close-short-position` 仅支持全部平仓(size=0),且双仓模式还需设置 `auto_size`。网格策略需要指定张数部分平仓,因此必须使用 `plan-close-*-position`。 |
| | | |
| | | --- |
| | | |
| | |
| | | |
| | | **关键常量**: |
| | | ```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"; |
| | | // 止盈条件单 order_type:仓位计划止盈止损,支持指定张数部分平仓 |
| | | private static final String ORDER_TYPE_CLOSE_LONG = "plan-close-long-position"; |
| | | private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position"; |
| | | ``` |
| | | |
| | | **核心数据结构**: |
| | |
| | | |------|------|------| |
| | | | shortPriceQueue | List\<BigDecimal\> | 空仓价格队列,降序(大→小),容量 gridQueueSize | |
| | | | longPriceQueue | List\<BigDecimal\> | 多仓价格队列,升序(小→大),容量 gridQueueSize | |
| | | | shortBaseEntryPrice | BigDecimal | 基底空头入场价 | |
| | | | longBaseEntryPrice | BigDecimal | 基底多头入场价 | |
| | | | shortEntryPrice | BigDecimal | 当前空仓入场价(推送更新) | |
| | | | longEntryPrice | BigDecimal | 当前多仓入场价(推送更新) | |
| | | | shortBaseEntryPrice | BigDecimal | 基底空头入场价(仅首次记录,用于生成队列) | |
| | | | longBaseEntryPrice | BigDecimal | 基底多头入场价(仅首次记录,用于生成队列) | |
| | | | shortEntryPrice | BigDecimal | 当前空仓入场价(推送实时更新,加权均价) | |
| | | | longEntryPrice | BigDecimal | 当前多仓入场价(推送实时更新,加权均价) | |
| | | | shortPositionSize | BigDecimal | 当前空仓持仓量(绝对值) | |
| | | | longPositionSize | BigDecimal | 当前多仓持仓量 | |
| | | | baseLongOpened | boolean | 基底多头是否已开 | |
| | |
| | | |
| | | **回调方法**: |
| | | - `onKline(closePrice)`: 更新 lastKlinePrice → 计算 unrealizedPnl → WAITING_KLINE 时触发基底双开,ACTIVE 时驱动 processShortGrid+processLongGrid |
| | | - `onPositionUpdate(contract, mode, size, entryPrice)`: 记录当前入场价和持仓量 → 有仓位时标记活跃+设止盈,无仓位时清空持仓量并标记不活跃 |
| | | - `onPositionUpdate(contract, mode, size, entryPrice)`: 记录当前入场价和持仓量 → 基底:首次成交记录入场价、生成队列;非基底:按 quantity 张数创建独立止盈条件单(plan-close-*-position)。无仓位时清空持仓量并标记不活跃 |
| | | - `onPositionClose(contract, side, pnl)`: 累加已实现盈亏,检查停止条件 |
| | | |
| | | **processShortGrid / processLongGrid 核心逻辑**: |
| | | |
| | | | 步骤 | processShortGrid | processLongGrid | |
| | | |------|-----------------|-----------------| |
| | | | 匹配 | 收集 shortPriceQueue 中 > currentPrice 的元素 | 收集 longPriceQueue 中 < currentPrice 的元素 | |
| | | | 主开仓 | 保证金安全 → openShort | 保证金安全 → openLong | |
| | | | 额外反向 | 条件满足 → openLong | 条件满足 → openShort | |
| | | | 本队补充 | 尾价 × (1−gridRate) 循环递减 | 尾价 × (1+gridRate) 循环递增 | |
| | | | 对方转移 | 以多仓首元素为种子,递减生成 | 以空仓首元素为种子,递增生成 | |
| | | | 贴近过滤 | 新增与 longEntryPrice 太近 → 跳过 | 新增与 shortEntryPrice 太近 → 跳过 | |
| | | |
| | | **未实现盈亏计算** (`updateUnrealizedPnl()`): |
| | | |
| | |
| | | |
| | | **止盈计算**: |
| | | |
| | | | 方向 | 公式 | order_type | auto_size | rule | |
| | | | 方向 | 公式 | order_type | size(平仓张数) | rule | |
| | | |------|------|------------|-----------|------| |
| | | | 多头 TP | entry × (1+gridRate) | `close-long-position` | `close_long` | NUMBER_1(≥触发价) | |
| | | | 空头 TP | entry × (1-gridRate) | `close-short-position` | `close_short` | NUMBER_2(≤触发价) | |
| | | | 多头 TP | entry × (1+gridRate) | `plan-close-long-position` | `-quantity`(负=平多) | NUMBER_1(≥触发价) | |
| | | | 空头 TP | entry × (1−gridRate) | `plan-close-short-position` | `+quantity`(正=平空) | NUMBER_2(≤触发价) | |
| | | |
| | | > 止盈单使用显式张数而非 autoSize。每次网格触发开仓 quantity 张,只为该批张数创建独立的条件单,多个止盈单之间互不覆盖。 |
| | | |
| | | **REST API 调用**: |
| | | |
| | |
| | | | 查账户 | `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 | |
| | | | 条件单 | `POST /futures/usdt/price_orders` | `FuturesApi.createPriceTriggeredOrder()` | strategy=0, price_type=0, expiration=0, order_type=plan-close-*-position, size=显式张数,多次调用互不冲突 | |
| | | |
| | | **初始化顺序** (`init()`): |
| | | ``` |
| | |
| | | import java.math.BigDecimal; |
| | | |
| | | /** |
| | | * 仓位频道处理器。 |
| | | * 仓位频道处理器(futures.positions)。 |
| | | * |
| | | * <h3>数据用途</h3> |
| | | * 监控仓位数量(size)和入场价(entry_price)。 |
| | | * 有仓位时(size.abs > 0):标记方向活跃,记录入场价 → 基底首次成交记录基底入场价并等待生成网格队列, |
| | | * 非基底成交立即设止盈条件单。无仓位时(size=0):标记方向不活跃。 |
| | | * |
| | | * <h3>推送字段</h3> |
| | | * contract, mode(dual_long / dual_short), size(正=多头,负=空头),entry_price |
| | | * <h3>完整推送字段(共20个,日志全部输出)</h3> |
| | | * <table> |
| | | * <tr><th>字段</th><th>类型</th><th>描述</th></tr> |
| | | * <tr><td>contract</td><td>String</td><td>合约名称</td></tr> |
| | | * <tr><td>mode</td><td>String</td><td>持仓模式:dual_long / dual_short</td></tr> |
| | | * <tr><td>size</td><td>String/Integer</td><td>合约张数(正=多头,负=空头)</td></tr> |
| | | * <tr><td>entry_price</td><td>Float</td><td>开仓均价</td></tr> |
| | | * <tr><td>cross_leverage_limit</td><td>Float</td><td>全仓模式下的杠杆倍数上限</td></tr> |
| | | * <tr><td>history_pnl</td><td>Float</td><td>已平仓的仓位总盈亏</td></tr> |
| | | * <tr><td>history_point</td><td>Float</td><td>已平仓的点卡总盈亏</td></tr> |
| | | * <tr><td>last_close_pnl</td><td>Float</td><td>最近一次平仓的盈亏</td></tr> |
| | | * <tr><td>leverage</td><td>Integer</td><td>杠杆倍数(0=全仓,正数=逐仓)</td></tr> |
| | | * <tr><td>leverage_max</td><td>Integer</td><td>当前风险限额下允许的最大杠杆倍数</td></tr> |
| | | * <tr><td>liq_price</td><td>Float</td><td>爆仓价格</td></tr> |
| | | * <tr><td>maintenance_rate</td><td>Float</td><td>当前风险限额下维持保证金比例</td></tr> |
| | | * <tr><td>margin</td><td>Float</td><td>保证金</td></tr> |
| | | * <tr><td>realised_pnl</td><td>Float</td><td>已实现盈亏</td></tr> |
| | | * <tr><td>realised_point</td><td>Float</td><td>点卡已实现盈亏</td></tr> |
| | | * <tr><td>risk_limit</td><td>Integer</td><td>风险限额</td></tr> |
| | | * <tr><td>time</td><td>Integer</td><td>更新 unix 时间戳(秒)</td></tr> |
| | | * <tr><td>time_ms</td><td>Integer</td><td>更新 unix 时间戳(毫秒)</td></tr> |
| | | * <tr><td>user</td><td>String</td><td>用户 ID</td></tr> |
| | | * <tr><td>update_id</td><td>Integer</td><td>消息序列号,每次推送 order 后自增1</td></tr> |
| | | * </table> |
| | | * |
| | | * <h3>回调数据(传给 GateGridTradeService)</h3> |
| | | * mode (Position.ModeEnum), size (BigDecimal), entry_price (BigDecimal) |
| | | * |
| | | * <h3>注意</h3> |
| | | * 双向持仓模式下空头 size 为负数,使用 {@code size.abs()} 判断是否有仓位。 |
| | |
| | | Position.ModeEnum mode = Position.ModeEnum.fromValue(modeStr); |
| | | BigDecimal size = new BigDecimal(pos.getString("size")); |
| | | BigDecimal entryPrice = new BigDecimal(pos.getString("entry_price")); |
| | | log.info("[{}] 持仓更新, 模式:{}, 数量:{}, 入场价:{}", CHANNEL_NAME, modeStr, size, entryPrice); |
| | | log.info("[{}] 持仓更新, 合约:{}, 模式:{}, 数量:{}, 入场价:{}, 全仓杠杆上限:{}, 历史盈亏:{}, 历史点卡:{}, 最近平仓盈亏:{}, 杠杆:{}, 最大杠杆:{}, 爆仓价:{}, 维持保证金率:{}, 保证金:{}, 已实现盈亏:{}, 点卡已实现盈亏:{}, 风险限额:{}, 时间:{}, 时间ms:{}, 用户:{}, 更新ID:{}", |
| | | CHANNEL_NAME, pos.getString("contract"), modeStr, size, entryPrice, |
| | | pos.get("cross_leverage_limit"), pos.get("history_pnl"), pos.get("history_point"), |
| | | pos.get("last_close_pnl"), pos.get("leverage"), pos.get("leverage_max"), |
| | | pos.get("liq_price"), pos.get("maintenance_rate"), pos.get("margin"), |
| | | pos.get("realised_pnl"), pos.get("realised_point"), pos.get("risk_limit"), |
| | | pos.get("time"), pos.get("time_ms"), pos.get("user"), pos.get("update_id")); |
| | | if (getGridTradeService() != null) { |
| | | getGridTradeService().onPositionUpdate(getContract(), mode, size, entryPrice); |
| | | } |