From 5d0e6b7b45630f32100d23ca107a9c74df43db75 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 11 May 2026 11:58:04 +0800
Subject: [PATCH] refactor(gate): 移除账号标签配置和多账号支持功能
---
src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java | 107 +++++++++------------
src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java | 162 +++++++++++--------------------
src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java | 6 -
src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java | 25 ++--
4 files changed, 117 insertions(+), 183 deletions(-)
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
index 83e17d8..ca6446c 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateConfig.java
@@ -44,8 +44,6 @@
MARK_PRICE
}
- /** 账号标签(用于日志区分多账号) */
- private final String label;
/** Gate API v4 密钥 */
private final String apiKey;
/** Gate API v4 签名密钥 */
@@ -80,7 +78,6 @@
private final PnLPriceMode unrealizedPnlPriceMode;
private GateConfig(Builder builder) {
- this.label = builder.label;
this.apiKey = builder.apiKey;
this.apiSecret = builder.apiSecret;
this.contract = builder.contract;
@@ -125,7 +122,6 @@
: "wss://ws-testnet.gate.com/v4/ws/futures/usdt";
}
- public String getLabel() { return label; }
public String getApiKey() { return apiKey; }
public String getApiSecret() { return apiSecret; }
public String getContract() { return contract; }
@@ -151,7 +147,6 @@
* GateConfig 的流式构造器,提供合理的默认值。
*/
public static class Builder {
- private String label = "default";
private String apiKey;
private String apiSecret;
private String contract = "BTC_USDT";
@@ -169,7 +164,6 @@
private BigDecimal contractMultiplier = new BigDecimal("0.001");
private PnLPriceMode unrealizedPnlPriceMode = PnLPriceMode.LAST_PRICE;
- public Builder label(String label) { this.label = label; return this; }
public Builder apiKey(String apiKey) { this.apiKey = apiKey; return this; }
public Builder apiSecret(String apiSecret) { this.apiSecret = apiSecret; return this; }
public Builder contract(String contract) { this.contract = contract; return this; }
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
index 55aef49..5710e88 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateGridTradeService.java
@@ -92,7 +92,6 @@
private static final String ORDER_TYPE_CLOSE_SHORT = "plan-close-short-position";
private final GateConfig config;
- private final String logLabel;
private final GateTradeExecutor executor;
private final FuturesApi futuresApi;
private static final String SETTLE = "usdt";
@@ -131,12 +130,11 @@
public GateGridTradeService(GateConfig config) {
this.config = config;
- this.logLabel = config.getLabel();
ApiClient apiClient = new ApiClient();
apiClient.setBasePath(config.getRestBasePath());
apiClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
this.futuresApi = new FuturesApi(apiClient);
- this.executor = new GateTradeExecutor(apiClient, config.getContract(), logLabel);
+ this.executor = new GateTradeExecutor(apiClient, config.getContract());
}
// ---- 初始化 ----
@@ -148,14 +146,14 @@
detailClient.setApiKeySecret(config.getApiKey(), config.getApiSecret());
AccountDetail detail = new AccountApi(detailClient).getAccountDetail();
this.userId = detail.getUserId();
- log.info("[Gate-{}] 用户ID: {}", logLabel, userId);
+ log.info("[Gate] 用户ID: {}", userId);
FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
this.initialPrincipal = new BigDecimal(account.getTotal());
- log.info("[Gate-{}] 初始本金: {} USDT", logLabel, initialPrincipal);
+ log.info("[Gate] 初始本金: {} USDT", initialPrincipal);
futuresApi.cancelPriceTriggeredOrderList(SETTLE, config.getContract());
- log.info("[Gate-{}] 旧条件单已清除", logLabel);
+ log.info("[Gate] 旧条件单已清除");
closeExistingPositions();
//设置持仓模式为双向持仓
@@ -187,19 +185,19 @@
e.printStackTrace();
}
}
- log.info("[Gate-{}] 持仓模式: {} 余额: {}", logLabel, config.getPositionMode(), account.getAvailable());
- log.info("[Gate-{}] 杠杆: {}x {}", logLabel, config.getLeverage(), config.getMarginMode());
+ log.info("[Gate] 持仓模式: {} 余额: {}", config.getPositionMode(), account.getAvailable());
+ log.info("[Gate] 杠杆: {}x {}", config.getLeverage(), config.getMarginMode());
} catch (GateApiException e) {
- log.error("[Gate-{}] 初始化失败, label:{}, msg:{}", logLabel, e.getErrorLabel(), e.getMessage());
+ log.error("[Gate] 初始化失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage());
} catch (ApiException e) {
- log.error("[Gate-{}] 初始化失败, code:{}", logLabel, e.getCode());
+ log.error("[Gate] 初始化失败, code:{}", e.getCode());
}
}
private void closeExistingPositions() {
try {
List<Position> positions = futuresApi.listPositions(SETTLE).execute();
- if (positions == null || positions.isEmpty()) { log.info("[Gate-{}] 无已有仓位", logLabel); return; }
+ if (positions == null || positions.isEmpty()) { log.info("[Gate] 无已有仓位"); return; }
for (Position pos : positions) {
if (!config.getContract().equals(pos.getContract())) {
continue;
@@ -225,12 +223,12 @@
}
closeOrder.setText("t-grid-init-close");
futuresApi.createFuturesOrder(SETTLE, closeOrder, null);
- log.info("[Gate-{}] 平已有仓位, 方向:{}, size:{}, mode:{}", logLabel, size > 0 ? "多" : "空", sizeStr, mode);
+ log.info("[Gate] 平已有仓位, 方向:{}, size:{}, mode:{}", size > 0 ? "多" : "空", sizeStr, mode);
}
} catch (GateApiException e) {
- log.warn("[Gate-{}] 平仓位失败, label:{}, msg:{}", logLabel, e.getErrorLabel(), e.getMessage());
+ log.warn("[Gate] 平仓位失败, label:{}, msg:{}", e.getErrorLabel(), e.getMessage());
} catch (Exception e) {
- log.warn("[Gate-{}] 平仓位异常", logLabel, e);
+ log.warn("[Gate] 平仓位异常", e);
}
}
@@ -238,7 +236,7 @@
public void startGrid() {
if (state != StrategyState.WAITING_KLINE && state != StrategyState.STOPPED) {
- log.warn("[Gate-{}] 策略已在运行中, state:{}", logLabel, state);
+ log.warn("[Gate] 策略已在运行中, state:{}", state);
return;
}
state = StrategyState.WAITING_KLINE;
@@ -255,14 +253,14 @@
shortActive = false;
shortPriceQueue.clear();
longPriceQueue.clear();
- log.info("[Gate-{}] 网格策略已启动", logLabel);
+ log.info("[Gate] 网格策略已启动");
}
public void stopGrid() {
state = StrategyState.STOPPED;
executor.cancelAllPriceTriggeredOrders();
executor.shutdown();
- log.info("[Gate-{}] 策略已停止, 累计盈亏: {}", logLabel, cumulativePnl);
+ log.info("[Gate] 策略已停止, 累计盈亏: {}", cumulativePnl);
}
// ---- K线回调 ----
@@ -276,12 +274,12 @@
if (state == StrategyState.WAITING_KLINE) {
state = StrategyState.OPENING;
- log.info("[Gate-{}] 首根K线到达,开基底仓位...", logLabel);
+ log.info("[Gate] 首根K线到达,开基底仓位...");
executor.openLong(config.getQuantity(), () -> {
- log.info("[Gate-{}] 基底多单已提交", logLabel);
+ log.info("[Gate] 基底多单已提交");
}, null);
executor.openShort(negate(config.getQuantity()), () -> {
- log.info("[Gate-{}] 基底空单已提交", logLabel);
+ log.info("[Gate] 基底空单已提交");
}, null);
return;
}
@@ -311,14 +309,14 @@
longPositionSize = size;
longBaseEntryPrice = entryPrice;
baseLongOpened = true;
- log.info("[Gate-{}] 基底多成交价: {}", logLabel, longBaseEntryPrice);
+ log.info("[Gate] 基底多成交价: {}", longBaseEntryPrice);
tryGenerateQueues();
} else if (size.compareTo(longPositionSize) > 0) {
longPositionSize = size;
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:{}", logLabel, entryPrice, tpPrice, negate(config.getQuantity()));
+ log.info("[Gate] 多单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, negate(config.getQuantity()));
} else {
longPositionSize = size;
}
@@ -334,14 +332,14 @@
shortPositionSize = size.abs();
shortBaseEntryPrice = entryPrice;
baseShortOpened = true;
- log.info("[Gate-{}] 基底空成交价: {}", logLabel, shortBaseEntryPrice);
+ log.info("[Gate] 基底空成交价: {}", shortBaseEntryPrice);
tryGenerateQueues();
} else if (size.abs().compareTo(shortPositionSize) > 0) {
shortPositionSize = size.abs();
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:{}", logLabel, entryPrice, tpPrice, config.getQuantity());
+ log.info("[Gate] 空单止盈已设, entry:{}, tp:{}, size:{}", entryPrice, tpPrice, config.getQuantity());
} else {
shortPositionSize = size.abs();
}
@@ -359,13 +357,13 @@
return;
}
cumulativePnl = cumulativePnl.add(pnl);
- log.info("[Gate-{}] 盈亏累加:{}, 方向:{}, 累计:{}", logLabel, pnl, side, cumulativePnl);
+ log.info("[Gate] 盈亏累加:{}, 方向:{}, 累计:{}", pnl, side, cumulativePnl);
if (cumulativePnl.compareTo(config.getOverallTp()) >= 0) {
- log.info("[Gate-{}] 已达止盈目标 {}→已停止", logLabel, cumulativePnl);
+ log.info("[Gate] 已达止盈目标 {}→已停止", cumulativePnl);
state = StrategyState.STOPPED;
} else if (cumulativePnl.compareTo(config.getMaxLoss().negate()) <= 0) {
- log.info("[Gate-{}] 已达亏损上限 {}→已停止", logLabel, cumulativePnl);
+ log.info("[Gate] 已达亏损上限 {}→已停止", cumulativePnl);
state = StrategyState.STOPPED;
}
}
@@ -377,7 +375,7 @@
generateShortQueue();
generateLongQueue();
state = StrategyState.ACTIVE;
- log.info("[Gate-{}] 网格队列已生成, 空队首:{} → 尾:{}, 多队首:{} → 尾:{}, 已激活", logLabel,
+ log.info("[Gate] 网格队列已生成, 空队首:{} → 尾:{}, 多队首:{} → 尾:{}, 已激活",
shortPriceQueue.get(0), shortPriceQueue.get(shortPriceQueue.size() - 1),
longPriceQueue.get(0), longPriceQueue.get(longPriceQueue.size() - 1));
}
@@ -391,7 +389,7 @@
}
shortPriceQueue.sort((a, b) -> b.compareTo(a));
//输出队列:shortPriceQueue;
- log.info("[Gate-{}] 空队列:{}", logLabel, shortPriceQueue);
+ log.info("[Gate] 空队列:{}", shortPriceQueue);
}
private void generateLongQueue() {
@@ -401,7 +399,7 @@
longPriceQueue.add(longBaseEntryPrice.multiply(BigDecimal.ONE.add(step.multiply(BigDecimal.valueOf(i)))).setScale(1, RoundingMode.HALF_UP));
}
longPriceQueue.sort(BigDecimal::compareTo);
- log.info("[Gate-{}] 多队列:{}", logLabel, longPriceQueue);
+ log.info("[Gate] 多队列:{}", longPriceQueue);
}
/**
@@ -434,14 +432,14 @@
}
}
}
- log.info("[Gate-{}] 原空队列:{}", logLabel, shortPriceQueue);
+ log.info("[Gate] 原空队列:{}", shortPriceQueue);
if (matched.isEmpty()) {
- log.info("[Gate-{}] 空仓队列未触发, 当前价:{}", logLabel, currentPrice);
+ log.info("[Gate] 空仓队列未触发, 当前价:{}", currentPrice);
return;
}
- log.info("[Gate-{}] 空仓队列触发, 匹配{}个元素, 当前价:{}", logLabel, matched.size(), currentPrice);
+ log.info("[Gate] 空仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice);
if (!isMarginSafe()) {
- log.warn("[Gate-{}] 保证金超限,跳过空单开仓", logLabel);
+ log.warn("[Gate] 保证金超限,跳过空单开仓");
} else {
executor.openShort(negate(config.getQuantity()), null, null);
if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
@@ -450,7 +448,7 @@
&& currentPrice.compareTo(shortEntryPrice) > 0
&& currentPrice.compareTo(longEntryPrice.multiply(BigDecimal.ONE.subtract(config.getGridRate()))) < 0) {
executor.openLong(config.getQuantity(), null, null);
- log.info("[Gate-{}] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", logLabel, currentPrice);
+ log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离多仓均价, 额外开多一次, 当前价:{}", currentPrice);
}
}
@@ -461,12 +459,12 @@
for (int i = 0; i < matched.size(); i++) {
min = min.multiply(BigDecimal.ONE.subtract(step)).setScale(1, RoundingMode.HALF_UP);
shortPriceQueue.add(min);
- log.info("[Gate-{}] 空队列增加:{}", logLabel, min);
+ log.info("[Gate] 空队列增加:{}", min);
}
shortPriceQueue.sort((a, b) -> b.compareTo(a));
- log.info("[Gate-{}] 现空队列:{}", logLabel, shortPriceQueue);
+ log.info("[Gate] 现空队列:{}", shortPriceQueue);
}
synchronized (longPriceQueue) {
@@ -474,19 +472,14 @@
BigDecimal step = config.getGridRate();
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 (elem.subtract(currentPrice).abs().compareTo(currentPrice.multiply(step)) < 0) {
- log.info("[Gate] 多队列跳过:{}", 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-{}] 现多队列:{}", logLabel, longPriceQueue);
+ log.info("[Gate] 现多队列:{}", longPriceQueue);
}
}
@@ -520,15 +513,15 @@
}
}
}
- log.info("[Gate-{}] 原多队列:{}", logLabel, longPriceQueue);
+ log.info("[Gate] 原多队列:{}", longPriceQueue);
if (matched.isEmpty()) {
- log.info("[Gate-{}] 多仓队列未触发, 当前价:{}", logLabel, currentPrice);
+ log.info("[Gate] 多仓队列未触发, 当前价:{}", currentPrice);
return;
}
- log.info("[Gate-{}] 多仓队列触发, 匹配{}个元素, 当前价:{}", logLabel, matched.size(), currentPrice);
+ log.info("[Gate] 多仓队列触发, 匹配{}个元素, 当前价:{}", matched.size(), currentPrice);
if (!isMarginSafe()) {
- log.warn("[Gate-{}] 保证金超限,跳过多单开仓", logLabel);
+ log.warn("[Gate] 保证金超限,跳过多单开仓");
} else {
executor.openLong(config.getQuantity(), null, null);
if (shortEntryPrice.compareTo(BigDecimal.ZERO) > 0
@@ -537,7 +530,7 @@
&& currentPrice.compareTo(shortEntryPrice.multiply(BigDecimal.ONE.add(config.getGridRate()))) > 0
&& currentPrice.compareTo(longEntryPrice) < 0) {
executor.openShort(negate(config.getQuantity()), null, null);
- log.info("[Gate-{}] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", logLabel, currentPrice);
+ log.info("[Gate] 触发价在多/空持仓价之间且多>空且远离空仓均价, 额外开空一次, 当前价:{}", currentPrice);
}
}
@@ -549,11 +542,11 @@
max = max.multiply(BigDecimal.ONE.add(step)).setScale(1, RoundingMode.HALF_UP);
longPriceQueue.add(max);
- log.info("[Gate-{}] 多队列增加:{}", logLabel, max);
+ log.info("[Gate] 多队列增加:{}", max);
}
longPriceQueue.sort(BigDecimal::compareTo);
- log.info("[Gate-{}] 现多队列:{}", logLabel, longPriceQueue);
+ log.info("[Gate] 现多队列:{}", longPriceQueue);
}
synchronized (shortPriceQueue) {
@@ -561,20 +554,14 @@
BigDecimal step = config.getGridRate();
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 (elem.subtract(currentPrice).abs().compareTo(currentPrice.multiply(step)) < 0) {
-
- log.info("[Gate] 空队列跳过:{}", 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-{}] 现空队列:{}", logLabel, shortPriceQueue);
+ log.info("[Gate] 现空队列:{}", shortPriceQueue);
}
}
@@ -585,10 +572,10 @@
FuturesAccount account = futuresApi.listFuturesAccounts(SETTLE);
BigDecimal margin = new BigDecimal(account.getPositionInitialMargin());
BigDecimal ratio = margin.divide(initialPrincipal, 4, RoundingMode.HALF_UP);
- log.debug("[Gate-{}] 保证金比例: {}/{}={}", logLabel, margin, initialPrincipal, ratio);
+ log.debug("[Gate] 保证金比例: {}/{}={}", margin, initialPrincipal, ratio);
return ratio.compareTo(config.getMarginRatioLimit()) < 0;
} catch (Exception e) {
- log.warn("[Gate-{}] 查保证金失败,默认放行", logLabel, e);
+ log.warn("[Gate] 查保证金失败,默认放行", e);
return true;
}
}
@@ -625,7 +612,7 @@
}
unrealizedPnl = longPnl.add(shortPnl);
- log.info("[Gate-{}] 未实现盈亏: {}", logLabel, unrealizedPnl);
+ log.info("[Gate] 未实现盈亏: {}", unrealizedPnl);
}
/**
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java
index b003bd4..eac6c1e 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateTradeExecutor.java
@@ -49,14 +49,13 @@
private static final String SETTLE = "usdt";
- private final String logLabel;
private final FuturesApi futuresApi;
private final String contract;
+ /** 交易线程池:单线程 + 有界队列 + 背压策略 */
private final ExecutorService executor;
- public GateTradeExecutor(ApiClient apiClient, String contract, String label) {
- this.logLabel = label;
+ public GateTradeExecutor(ApiClient apiClient, String contract) {
this.futuresApi = new FuturesApi(apiClient);
this.contract = contract;
this.executor = new ThreadPoolExecutor(
@@ -64,7 +63,7 @@
60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(64),
r -> {
- Thread t = new Thread(r, "gate-trade-" + label);
+ Thread t = new Thread(r, "gate-trade-worker");
t.setDaemon(true);
return t;
},
@@ -110,12 +109,12 @@
order.setTif(FuturesOrder.TifEnum.IOC);
order.setText(text);
FuturesOrder result = futuresApi.createFuturesOrder(SETTLE, order, null);
- log.info("[TradeExec-{}] {}成功, 价格:{}, id:{}", logLabel, label, result.getFillPrice(), result.getId());
+ log.info("[TradeExec] {}成功, 价格:{}, id:{}", label, result.getFillPrice(), result.getId());
if (onSuccess != null) {
onSuccess.run();
}
} catch (Exception e) {
- log.error("[TradeExec-{}] {}失败", logLabel, label, e);
+ log.error("[TradeExec] {}失败", label, e);
if (onFailure != null) {
onFailure.run();
}
@@ -148,10 +147,10 @@
FuturesPriceTriggeredOrder order = buildTriggeredOrder(triggerPrice, rule, orderType, size);
try {
TriggerOrderResponse response = futuresApi.createPriceTriggeredOrder(SETTLE, order);
- log.info("[TradeExec-{}] 止盈单已创建, 触发价:{}, 类型:{}, size:{}, id:{}",
- logLabel, triggerPrice, orderType, size, response.getId());
+ log.info("[TradeExec] 止盈单已创建, 触发价:{}, 类型:{}, size:{}, id:{}",
+ triggerPrice, orderType, size, response.getId());
} catch (Exception e) {
- log.error("[TradeExec-{}] 止盈单创建失败, 触发价:{}, size:{}, 立即市价止盈", logLabel, triggerPrice, size, e);
+ log.error("[TradeExec] 止盈单创建失败, 触发价:{}, size:{}, 立即市价止盈", triggerPrice, size, e);
marketClose(size);
}
});
@@ -171,9 +170,9 @@
order.setReduceOnly(true);
order.setText("t-grid-mkt-close");
FuturesOrder result = futuresApi.createFuturesOrder(SETTLE, order, null);
- log.info("[TradeExec-{}] 市价止盈成功, 价格:{}, size:{}, id:{}", logLabel, result.getFillPrice(), size, result.getId());
+ log.info("[TradeExec] 市价止盈成功, 价格:{}, size:{}, id:{}", result.getFillPrice(), size, result.getId());
} catch (Exception e) {
- log.error("[TradeExec-{}] 市价止盈也失败, size:{}", logLabel, size, e);
+ log.error("[TradeExec] 市价止盈也失败, size:{}", size, e);
}
}
@@ -184,9 +183,9 @@
executor.execute(() -> {
try {
futuresApi.cancelPriceTriggeredOrderList(SETTLE, contract);
- log.info("[TradeExec-{}] 已清除所有止盈止损条件单", logLabel);
+ log.info("[TradeExec] 已清除所有止盈止损条件单");
} catch (Exception e) {
- log.error("[TradeExec-{}] 清除止盈止损条件单失败", logLabel, e);
+ log.error("[TradeExec] 清除止盈止损条件单失败", e);
}
});
}
diff --git a/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java b/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
index f0cd365..93ffff4 100644
--- a/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
+++ b/src/main/java/com/xcong/excoin/modules/gateApi/GateWebSocketClientManager.java
@@ -9,28 +9,26 @@
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.List;
/**
- * Gate 模块 Spring 入口,管理多个账号实例的生命周期。
+ * Gate 模块 Spring 入口,组装所有组件并管理生命周期。
*
* <h3>启动流程 ({@code @PostConstruct})</h3>
* <ol>
- * <li>遍历 {@link #buildAccountConfigs()} 构建每个账号的 {@link GateConfig}</li>
- * <li>每个账号创建独立的 {@link AccountInstance}(含 service + wsClient)</li>
- * <li>逐个 init → startGrid</li>
+ * <li>构建 {@link GateConfig}(Builder 模式,含 API 密钥、合约、策略参数)</li>
+ * <li>创建 {@link GateGridTradeService} → init():切持仓模式、清旧条件单、设杠杆</li>
+ * <li>创建 {@link GateKlineWebSocketClient} → 注册 3 个 Handler → init():建立 WS 连接</li>
+ * <li>gridTradeService.startGrid():激活策略,等待 K 线触发首次双开</li>
* </ol>
*
* <h3>销毁流程 ({@code @PreDestroy})</h3>
* <ol>
- * <li>遍历 instances:stopGrid + wsClient.destroy()</li>
+ * <li>gridTradeService.stopGrid():取消条件单 → 关闭交易线程池</li>
+ * <li>wsClient.destroy():取消订阅 → 断开 WS → 关闭线程池</li>
* </ol>
*
- * <h3>添加新账号</h3>
- * 在 {@link #buildAccountConfigs()} 方法中添加新的 {@link GateConfig} 即可。
- * 通过 {@link GateConfig#getLabel()} 区分日志输出,
- * 通过 {@link GateConfig#isProduction()} 控制模拟盘/实盘环境。
+ * <h3>配置</h3>
+ * 当前在代码中硬编码测试网参数。切换到生产网只需改为 {@code .isProduction(true)}。
*
* @author Administrator
*/
@@ -38,109 +36,65 @@
@Component
public class GateWebSocketClientManager {
- /** 所有账号实例列表 */
- private final List<AccountInstance> instances = new ArrayList<>();
-
- /**
- * 封装一个账号的完整运行时组件。
- */
- private static class AccountInstance {
- final String label;
- final GateConfig config;
- final GateGridTradeService service;
- final GateKlineWebSocketClient wsClient;
-
- AccountInstance(GateConfig config) {
- this.label = config.getLabel();
- this.config = config;
- this.service = new GateGridTradeService(config);
- this.wsClient = new GateKlineWebSocketClient(config.getWsUrl());
- }
-
- void init() {
- service.init();
- wsClient.addChannelHandler(new CandlestickChannelHandler(config.getContract(), service));
- wsClient.addChannelHandler(new PositionsChannelHandler(
- config.getApiKey(), config.getApiSecret(), config.getContract(), service));
- wsClient.addChannelHandler(new PositionClosesChannelHandler(
- config.getApiKey(), config.getApiSecret(), config.getContract(), service));
- wsClient.init();
- log.info("[{}] WS已连接, 已注册 3 个频道处理器", label);
- service.startGrid();
- }
-
- void destroy() {
- log.info("[{}] 开始销毁...", label);
- service.stopGrid();
- wsClient.destroy();
- log.info("[{}] 销毁完成", label);
- }
- }
-
- /**
- * 在此方法中配置所有账号。
- * <p>每个 {@link GateConfig} 对应一个账号,label 用于日志区分,
- * isProduction 控制连接测试网(true=实盘)还是测试网(false=模拟盘)。
- */
- private static GateConfig[] buildAccountConfigs() {
- return new GateConfig[]{
- GateConfig.builder()
- .label("模拟盘1")
- .apiKey("d90ca272391992b8e74f8f92cedb21ec")
- .apiSecret("1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274")
- .contract("ETH_USDT")
- .leverage("100")
- .marginMode("CROSS")
- .positionMode("dual")
- .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)
- .isProduction(false)
- .reopenMaxRetries(3)
- .build(),
- };
- }
+ /** WebSocket 连接管理器 */
+ private GateKlineWebSocketClient wsClient;
+ /** 网格交易策略服务 */
+ private GateGridTradeService gridTradeService;
+ /** 统一配置 */
+ private GateConfig config;
@PostConstruct
public void init() {
- GateConfig[] configs = buildAccountConfigs();
- log.info("[管理器] 开始初始化 {} 个账号...", configs.length);
- for (GateConfig config : configs) {
- try {
- AccountInstance instance = new AccountInstance(config);
- instance.init();
- instances.add(instance);
- } catch (Exception e) {
- log.error("[管理器] 账号 {} 初始化失败", config.getLabel(), e);
- }
- }
+ log.info("[管理器] 开始初始化...");
- log.info("[管理器] 初始化完成, 成功启动 {}/{} 个账号", instances.size(), configs.length);
+ try {
+ config = GateConfig.builder()
+ .apiKey("d90ca272391992b8e74f8f92cedb21ec")
+ .apiSecret("1861e4f52de4bb53369ea3208d9ede38ece4777368030f96c77d27934c46c274")
+ .contract("ETH_USDT")
+ .leverage("100")
+ .marginMode("CROSS")
+ .positionMode("dual")
+ .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)
+ .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("[管理器] WS已连接, 已注册 3 个频道处理器");
+
+ gridTradeService.startGrid();
+ } catch (Exception e) {
+ log.error("[管理器] 初始化失败", e);
+ }
}
@PreDestroy
public void destroy() {
- log.info("[管理器] 开始销毁 {} 个账号...", instances.size());
- for (AccountInstance instance : instances) {
- try {
- instance.destroy();
- } catch (Exception e) {
- log.error("[管理器] 账号 {} 销毁失败", instance.label, e);
- }
+ log.info("[管理器] 开始销毁...");
+ if (gridTradeService != null) {
+ gridTradeService.stopGrid();
+ }
+ if (wsClient != null) {
+ wsClient.destroy();
}
log.info("[管理器] 销毁完成");
}
- /** 获取账号数量 */
- public int getInstanceCount() {
- return instances.size();
- }
-
- /** 获取指定索引的 GridTradeService(用于外部监控/查询) */
- public GateGridTradeService getGridTradeService(int index) {
- return instances.get(index).service;
- }
+ public GateKlineWebSocketClient getKlineWebSocketClient() { return wsClient; }
+ public GateGridTradeService getGridTradeService() { return gridTradeService; }
}
--
Gitblit v1.9.1