Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a31ed31c98 | |||
| 0625c62e36 |
@@ -122,7 +122,7 @@ docker pull wrbug/polyhermes:v1.0.1
|
|||||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||||
|
|
||||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||||
* **Twitter**:@quant_tr
|
* **Twitter**:@polyhermes
|
||||||
* **Telegram 群组**:加入群组
|
* **Telegram 群组**:加入群组
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# PolyHermes
|
# PolyHermes
|
||||||
|
|
||||||
[](https://github.com/WrBug/PolyHermes)
|
[](https://github.com/WrBug/PolyHermes)
|
||||||
[](https://x.com/quant_tr)
|
[](https://x.com/polyhermes)
|
||||||
|
|
||||||
> 🌐 **Language**: [English](README_EN.md) | 中文
|
> 🌐 **Language**: [English](README_EN.md) | 中文
|
||||||
|
|
||||||
@@ -414,7 +414,7 @@ cd frontend
|
|||||||
## 🔗 相关链接
|
## 🔗 相关链接
|
||||||
|
|
||||||
- [GitHub 仓库](https://github.com/WrBug/PolyHermes)
|
- [GitHub 仓库](https://github.com/WrBug/PolyHermes)
|
||||||
- [Twitter](https://x.com/quant_tr)
|
- [Twitter](https://x.com/polyhermes)
|
||||||
- [Polymarket 官网](https://polymarket.com)
|
- [Polymarket 官网](https://polymarket.com)
|
||||||
- [Polymarket API 文档](https://docs.polymarket.com)
|
- [Polymarket API 文档](https://docs.polymarket.com)
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
# PolyHermes
|
# PolyHermes
|
||||||
|
|
||||||
[](https://github.com/WrBug/PolyHermes)
|
[](https://github.com/WrBug/PolyHermes)
|
||||||
[](https://x.com/quant_tr)
|
[](https://x.com/polyhermes)
|
||||||
|
|
||||||
> 🌐 **Language**: English | [中文](README.md)
|
> 🌐 **Language**: English | [中文](README.md)
|
||||||
|
|
||||||
@@ -414,7 +414,7 @@ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file
|
|||||||
## 🔗 Related Links
|
## 🔗 Related Links
|
||||||
|
|
||||||
- [GitHub Repository](https://github.com/WrBug/PolyHermes)
|
- [GitHub Repository](https://github.com/WrBug/PolyHermes)
|
||||||
- [Twitter](https://x.com/quant_tr)
|
- [Twitter](https://x.com/polyhermes)
|
||||||
- [Polymarket Official Website](https://polymarket.com)
|
- [Polymarket Official Website](https://polymarket.com)
|
||||||
- [Polymarket API Documentation](https://docs.polymarket.com)
|
- [Polymarket API Documentation](https://docs.polymarket.com)
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ data class SystemConfigDto(
|
|||||||
val builderApiKeyConfigured: Boolean, // Builder API Key 是否已配置
|
val builderApiKeyConfigured: Boolean, // Builder API Key 是否已配置
|
||||||
val builderSecretConfigured: Boolean, // Builder Secret 是否已配置
|
val builderSecretConfigured: Boolean, // Builder Secret 是否已配置
|
||||||
val builderPassphraseConfigured: Boolean, // Builder Passphrase 是否已配置
|
val builderPassphraseConfigured: Boolean, // Builder Passphrase 是否已配置
|
||||||
|
val builderApiKeyDisplay: String? = null, // Builder API Key 显示值(部分显示,用于前端展示)
|
||||||
|
val builderSecretDisplay: String? = null, // Builder Secret 显示值(部分显示,用于前端展示)
|
||||||
|
val builderPassphraseDisplay: String? = null, // Builder Passphrase 显示值(部分显示,用于前端展示)
|
||||||
val autoRedeemEnabled: Boolean = true // 自动赎回(系统级别配置,默认开启)
|
val autoRedeemEnabled: Boolean = true // 自动赎回(系统级别配置,默认开启)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+234
-107
@@ -10,6 +10,8 @@ import com.wrbug.polymarketbot.util.*
|
|||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
import org.slf4j.LoggerFactory
|
import org.slf4j.LoggerFactory
|
||||||
import org.springframework.dao.DataIntegrityViolationException
|
import org.springframework.dao.DataIntegrityViolationException
|
||||||
|
import org.springframework.dao.DuplicateKeyException
|
||||||
|
import java.sql.SQLException
|
||||||
import com.wrbug.polymarketbot.service.copytrading.configs.CopyTradingFilterService
|
import com.wrbug.polymarketbot.service.copytrading.configs.CopyTradingFilterService
|
||||||
import com.wrbug.polymarketbot.service.copytrading.configs.FilterStatus
|
import com.wrbug.polymarketbot.service.copytrading.configs.FilterStatus
|
||||||
import com.wrbug.polymarketbot.service.copytrading.orders.OrderSigningService
|
import com.wrbug.polymarketbot.service.copytrading.orders.OrderSigningService
|
||||||
@@ -27,7 +29,7 @@ import java.math.BigDecimal
|
|||||||
* 实际创建订单并记录跟踪信息
|
* 实际创建订单并记录跟踪信息
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
class CopyOrderTrackingService(
|
open class CopyOrderTrackingService(
|
||||||
private val copyOrderTrackingRepository: CopyOrderTrackingRepository,
|
private val copyOrderTrackingRepository: CopyOrderTrackingRepository,
|
||||||
private val sellMatchRecordRepository: SellMatchRecordRepository,
|
private val sellMatchRecordRepository: SellMatchRecordRepository,
|
||||||
private val sellMatchDetailRepository: SellMatchDetailRepository,
|
private val sellMatchDetailRepository: SellMatchDetailRepository,
|
||||||
@@ -51,6 +53,12 @@ class CopyOrderTrackingService(
|
|||||||
// 协程作用域(用于异步发送通知)
|
// 协程作用域(用于异步发送通知)
|
||||||
private val notificationScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
private val notificationScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
|
|
||||||
|
// 订单创建重试配置
|
||||||
|
companion object {
|
||||||
|
private const val MAX_RETRY_ATTEMPTS = 2 // 最多重试次数(首次 + 1次重试)
|
||||||
|
private const val RETRY_DELAY_MS = 3000L // 重试前等待时间(毫秒,3秒)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解密账户私钥
|
* 解密账户私钥
|
||||||
*/
|
*/
|
||||||
@@ -144,21 +152,38 @@ class CopyOrderTrackingService(
|
|||||||
processedAt = System.currentTimeMillis()
|
processedAt = System.currentTimeMillis()
|
||||||
)
|
)
|
||||||
processedTradeRepository.save(processed)
|
processedTradeRepository.save(processed)
|
||||||
} catch (e: DataIntegrityViolationException) {
|
} catch (e: Exception) {
|
||||||
// 唯一约束冲突,说明已经处理过了(可能是并发请求)
|
// 检查是否是唯一键冲突异常(可能是 DataIntegrityViolationException、DuplicateKeyException 或 SQLException)
|
||||||
// 再次检查确认状态
|
if (isUniqueConstraintViolation(e)) {
|
||||||
val existing = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
// 唯一约束冲突,说明已经处理过了(可能是并发请求)
|
||||||
if (existing != null) {
|
// 再次检查确认状态
|
||||||
if (existing.status == "FAILED") {
|
val existing = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||||
|
if (existing != null) {
|
||||||
|
if (existing.status == "FAILED") {
|
||||||
|
logger.debug("交易已标记为失败,跳过处理: leaderId=$leaderId, tradeId=${trade.id}")
|
||||||
|
return Result.success(Unit)
|
||||||
|
}
|
||||||
|
logger.debug("交易已处理(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existing.status}")
|
||||||
|
return Result.success(Unit)
|
||||||
|
} else {
|
||||||
|
// 如果检查不到,可能是事务隔离级别问题,等待一下再查询
|
||||||
|
delay(100)
|
||||||
|
val existingAfterDelay =
|
||||||
|
processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||||
|
if (existingAfterDelay != null) {
|
||||||
|
logger.debug("延迟查询到记录(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existingAfterDelay.status}")
|
||||||
|
return Result.success(Unit)
|
||||||
|
}
|
||||||
|
// 如果还是查询不到,记录警告但不抛出异常(可能是其他约束冲突)
|
||||||
|
logger.warn(
|
||||||
|
"保存ProcessedTrade时发生唯一约束冲突,但查询不到记录: leaderId=$leaderId, tradeId=${trade.id}",
|
||||||
|
e
|
||||||
|
)
|
||||||
|
// 不抛出异常,避免影响其他交易的处理
|
||||||
return Result.success(Unit)
|
return Result.success(Unit)
|
||||||
}
|
}
|
||||||
return Result.success(Unit)
|
|
||||||
} else {
|
} else {
|
||||||
// 如果检查不到,说明可能是其他约束冲突,重新抛出异常
|
// 其他类型的异常,重新抛出
|
||||||
logger.warn(
|
|
||||||
"保存ProcessedTrade时发生唯一约束冲突,但查询不到记录: leaderId=$leaderId, tradeId=${trade.id}",
|
|
||||||
e
|
|
||||||
)
|
|
||||||
throw e
|
throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -358,6 +383,35 @@ class CopyOrderTrackingService(
|
|||||||
// 计算价格(应用价格容忍度)
|
// 计算价格(应用价格容忍度)
|
||||||
val buyPrice = calculateAdjustedPrice(trade.price.toSafeBigDecimal(), copyTrading, isBuy = true)
|
val buyPrice = calculateAdjustedPrice(trade.price.toSafeBigDecimal(), copyTrading, isBuy = true)
|
||||||
|
|
||||||
|
// 在创建订单前,检查订单簿中是否有可匹配的订单(避免 FAK 订单失败)
|
||||||
|
// 如果过滤检查时已经获取了订单簿,直接使用;否则重新获取
|
||||||
|
val orderbookForCheck = orderbook ?: run {
|
||||||
|
val orderbookResult = clobService.getOrderbookByTokenId(tokenId)
|
||||||
|
if (orderbookResult.isSuccess) {
|
||||||
|
orderbookResult.getOrNull()
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否有可匹配的卖单(asks)
|
||||||
|
if (orderbookForCheck != null) {
|
||||||
|
val bestAsk = orderbookForCheck.asks
|
||||||
|
.mapNotNull { it.price.toSafeBigDecimal() }
|
||||||
|
.minOrNull()
|
||||||
|
|
||||||
|
if (bestAsk == null) {
|
||||||
|
logger.warn("订单簿中没有卖单,跳过创建订单: copyTradingId=${copyTrading.id}, tradeId=${trade.id}")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果调整后的买入价格低于最佳卖单价格,无法匹配
|
||||||
|
if (buyPrice.lt(bestAsk)) {
|
||||||
|
logger.warn("调整后的买入价格 ($buyPrice) 低于最佳卖单价格 ($bestAsk),无法匹配,跳过创建订单: copyTradingId=${copyTrading.id}, tradeId=${trade.id}, leaderPrice=${trade.price}, tolerance=${copyTrading.priceTolerance}")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 解密 API 凭证
|
// 解密 API 凭证
|
||||||
val apiSecret = try {
|
val apiSecret = try {
|
||||||
decryptApiSecret(account)
|
decryptApiSecret(account)
|
||||||
@@ -383,7 +437,9 @@ class CopyOrderTrackingService(
|
|||||||
// 解密私钥
|
// 解密私钥
|
||||||
val decryptedPrivateKey = decryptPrivateKey(account)
|
val decryptedPrivateKey = decryptPrivateKey(account)
|
||||||
|
|
||||||
// 调用API创建订单(带重试机制,重试时会重新生成salt并重新签名)
|
// 调用API创建订单(带重试机制)
|
||||||
|
// 重试策略:最多重试 MAX_RETRY_ATTEMPTS 次,每次重试前等待 RETRY_DELAY_MS 毫秒
|
||||||
|
// 每次重试都会重新生成salt并重新签名,确保签名唯一性
|
||||||
val createOrderResult = createOrderWithRetry(
|
val createOrderResult = createOrderWithRetry(
|
||||||
clobApi = clobApi,
|
clobApi = clobApi,
|
||||||
privateKey = decryptedPrivateKey,
|
privateKey = decryptedPrivateKey,
|
||||||
@@ -397,8 +453,9 @@ class CopyOrderTrackingService(
|
|||||||
tradeId = trade.id
|
tradeId = trade.id
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 处理订单创建失败
|
||||||
if (createOrderResult.isFailure) {
|
if (createOrderResult.isFailure) {
|
||||||
// 创建订单失败,记录到失败表
|
// 提取错误信息(只保留 code 和 errorBody)
|
||||||
val exception = createOrderResult.exceptionOrNull()
|
val exception = createOrderResult.exceptionOrNull()
|
||||||
val errorMsg = buildFullErrorMessage(
|
val errorMsg = buildFullErrorMessage(
|
||||||
exception,
|
exception,
|
||||||
@@ -407,16 +464,19 @@ class CopyOrderTrackingService(
|
|||||||
finalBuyQuantity.toString(),
|
finalBuyQuantity.toString(),
|
||||||
trade.id
|
trade.id
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 记录失败交易到数据库
|
||||||
|
// retryCount = MAX_RETRY_ATTEMPTS - 1,表示已重试的次数
|
||||||
recordFailedTrade(
|
recordFailedTrade(
|
||||||
leaderId = leaderId,
|
leaderId = leaderId,
|
||||||
trade = trade,
|
trade = trade,
|
||||||
copyTradingId = copyTrading.id!!,
|
copyTradingId = copyTrading.id!!,
|
||||||
accountId = copyTrading.accountId,
|
accountId = copyTrading.accountId,
|
||||||
side = "BUY", // 订单方向是BUY
|
side = "BUY",
|
||||||
price = buyPrice.toString(),
|
price = buyPrice.toString(),
|
||||||
size = finalBuyQuantity.toString(),
|
size = finalBuyQuantity.toString(),
|
||||||
errorMessage = errorMsg,
|
errorMessage = errorMsg,
|
||||||
retryCount = 1 // 已重试一次
|
retryCount = MAX_RETRY_ATTEMPTS - 1 // 已重试次数
|
||||||
)
|
)
|
||||||
|
|
||||||
// 发送订单失败通知(异步,不阻塞,仅在 pushFailedOrders 为 true 时发送)
|
// 发送订单失败通知(异步,不阻塞,仅在 pushFailedOrders 为 true 时发送)
|
||||||
@@ -427,7 +487,8 @@ class CopyOrderTrackingService(
|
|||||||
val marketInfo = withContext(Dispatchers.IO) {
|
val marketInfo = withContext(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
val gammaApi = retrofitFactory.createGammaApi()
|
val gammaApi = retrofitFactory.createGammaApi()
|
||||||
val marketResponse = gammaApi.listMarkets(conditionIds = listOf(trade.market))
|
val marketResponse =
|
||||||
|
gammaApi.listMarkets(conditionIds = listOf(trade.market))
|
||||||
if (marketResponse.isSuccessful && marketResponse.body() != null) {
|
if (marketResponse.isSuccessful && marketResponse.body() != null) {
|
||||||
marketResponse.body()!!.firstOrNull()
|
marketResponse.body()!!.firstOrNull()
|
||||||
} else {
|
} else {
|
||||||
@@ -648,8 +709,8 @@ class CopyOrderTrackingService(
|
|||||||
* 卖出订单匹配
|
* 卖出订单匹配
|
||||||
* 统一按比例计算,不区分RATIO或FIXED模式
|
* 统一按比例计算,不区分RATIO或FIXED模式
|
||||||
* 实际创建卖出订单并记录匹配关系
|
* 实际创建卖出订单并记录匹配关系
|
||||||
|
* 注意:此方法在 @Transactional 方法中被调用,会自动继承事务
|
||||||
*/
|
*/
|
||||||
@Transactional
|
|
||||||
private suspend fun matchSellOrder(
|
private suspend fun matchSellOrder(
|
||||||
copyTrading: CopyTrading,
|
copyTrading: CopyTrading,
|
||||||
leaderSellTrade: TradeResponse
|
leaderSellTrade: TradeResponse
|
||||||
@@ -693,7 +754,28 @@ class CopyOrderTrackingService(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 按FIFO顺序匹配,计算实际可以卖出的数量
|
// 4. 获取tokenId(直接使用outcomeIndex,支持多元市场)
|
||||||
|
val tokenIdResult = blockchainService.getTokenId(leaderSellTrade.market, leaderSellTrade.outcomeIndex)
|
||||||
|
if (tokenIdResult.isFailure) {
|
||||||
|
logger.error("获取tokenId失败: market=${leaderSellTrade.market}, outcomeIndex=${leaderSellTrade.outcomeIndex}, error=${tokenIdResult.exceptionOrNull()?.message}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val tokenId = tokenIdResult.getOrNull() ?: return
|
||||||
|
|
||||||
|
// 5. 计算卖出价格(优先使用订单簿 bestBid,失败则使用 Leader 价格,固定按90%计算)
|
||||||
|
// 注意:需要先计算卖出价格,因为后续创建 matchDetails 需要使用实际卖出价格
|
||||||
|
val leaderPrice = leaderSellTrade.price.toSafeBigDecimal()
|
||||||
|
val sellPrice = runCatching {
|
||||||
|
clobService.getOrderbookByTokenId(tokenId)
|
||||||
|
.getOrNull()
|
||||||
|
?.let { calculateMarketSellPrice(it) }
|
||||||
|
}
|
||||||
|
.onFailure { e -> logger.warn("获取订单簿或计算 bestBid 失败,使用 Leader 价格: tokenId=$tokenId, error=${e.message}") }
|
||||||
|
.getOrNull()
|
||||||
|
?: calculateFallbackSellPrice(leaderPrice)
|
||||||
|
|
||||||
|
// 6. 按FIFO顺序匹配,计算实际可以卖出的数量
|
||||||
|
// 使用计算出的实际卖出价格(而不是 Leader 价格)来创建匹配明细
|
||||||
var totalMatched = BigDecimal.ZERO
|
var totalMatched = BigDecimal.ZERO
|
||||||
var remaining = needMatch
|
var remaining = needMatch
|
||||||
val matchDetails = mutableListOf<SellMatchDetail>()
|
val matchDetails = mutableListOf<SellMatchDetail>()
|
||||||
@@ -708,19 +790,18 @@ class CopyOrderTrackingService(
|
|||||||
|
|
||||||
if (matchQty.lte(BigDecimal.ZERO)) continue
|
if (matchQty.lte(BigDecimal.ZERO)) continue
|
||||||
|
|
||||||
// 计算盈亏
|
// 计算盈亏(使用实际卖出价格)
|
||||||
val buyPrice = order.price.toSafeBigDecimal()
|
val buyPrice = order.price.toSafeBigDecimal()
|
||||||
val sellPrice = leaderSellTrade.price.toSafeBigDecimal()
|
|
||||||
val realizedPnl = sellPrice.subtract(buyPrice).multi(matchQty)
|
val realizedPnl = sellPrice.subtract(buyPrice).multi(matchQty)
|
||||||
|
|
||||||
// 创建匹配明细(稍后保存)
|
// 创建匹配明细(使用实际卖出价格)
|
||||||
val detail = SellMatchDetail(
|
val detail = SellMatchDetail(
|
||||||
matchRecordId = 0, // 稍后设置
|
matchRecordId = 0, // 稍后设置
|
||||||
trackingId = order.id!!,
|
trackingId = order.id!!,
|
||||||
buyOrderId = order.buyOrderId,
|
buyOrderId = order.buyOrderId,
|
||||||
matchedQuantity = matchQty,
|
matchedQuantity = matchQty,
|
||||||
buyPrice = buyPrice,
|
buyPrice = buyPrice,
|
||||||
sellPrice = sellPrice,
|
sellPrice = sellPrice, // 使用实际卖出价格,与 SellMatchRecord 保持一致
|
||||||
realizedPnl = realizedPnl
|
realizedPnl = realizedPnl
|
||||||
)
|
)
|
||||||
matchDetails.add(detail)
|
matchDetails.add(detail)
|
||||||
@@ -733,25 +814,6 @@ class CopyOrderTrackingService(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 获取tokenId(直接使用outcomeIndex,支持多元市场)
|
|
||||||
val tokenIdResult = blockchainService.getTokenId(leaderSellTrade.market, leaderSellTrade.outcomeIndex)
|
|
||||||
if (tokenIdResult.isFailure) {
|
|
||||||
logger.error("获取tokenId失败: market=${leaderSellTrade.market}, outcomeIndex=${leaderSellTrade.outcomeIndex}, error=${tokenIdResult.exceptionOrNull()?.message}")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val tokenId = tokenIdResult.getOrNull() ?: return
|
|
||||||
|
|
||||||
// 6. 计算卖出价格(优先使用订单簿 bestBid,失败则使用 Leader 价格,固定按90%计算)
|
|
||||||
val leaderPrice = leaderSellTrade.price.toSafeBigDecimal()
|
|
||||||
val sellPrice = runCatching {
|
|
||||||
clobService.getOrderbookByTokenId(tokenId)
|
|
||||||
.getOrNull()
|
|
||||||
?.let { calculateMarketSellPrice(it) }
|
|
||||||
}
|
|
||||||
.onFailure { e -> logger.warn("获取订单簿或计算 bestBid 失败,使用 Leader 价格: tokenId=$tokenId, error=${e.message}") }
|
|
||||||
.getOrNull()
|
|
||||||
?: calculateFallbackSellPrice(leaderPrice)
|
|
||||||
|
|
||||||
// 7. 解密私钥(在方法开始时解密一次,后续复用)
|
// 7. 解密私钥(在方法开始时解密一次,后续复用)
|
||||||
val decryptedPrivateKey = decryptPrivateKey(account)
|
val decryptedPrivateKey = decryptPrivateKey(account)
|
||||||
// 8. 创建并签名卖出订单
|
// 8. 创建并签名卖出订单
|
||||||
@@ -872,8 +934,23 @@ class CopyOrderTrackingService(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建订单(带重试机制)
|
* 创建订单(带重试机制)
|
||||||
* 失败后重试一次,如果仍然失败则返回失败结果
|
*
|
||||||
* 注意:重试时会重新生成salt并重新签名,确保每次重试都是新的订单
|
* 重试策略:
|
||||||
|
* - 最多重试 MAX_RETRY_ATTEMPTS 次(首次尝试 + 重试)
|
||||||
|
* - 每次重试前等待 RETRY_DELAY_MS 毫秒
|
||||||
|
* - 每次重试都重新生成salt并重新签名,确保签名唯一性
|
||||||
|
*
|
||||||
|
* @param clobApi CLOB API 客户端
|
||||||
|
* @param privateKey 私钥(用于签名)
|
||||||
|
* @param makerAddress 代理钱包地址
|
||||||
|
* @param tokenId Token ID
|
||||||
|
* @param side 订单方向(BUY/SELL)
|
||||||
|
* @param price 价格
|
||||||
|
* @param size 数量
|
||||||
|
* @param owner API Key(用于owner字段)
|
||||||
|
* @param copyTradingId 跟单配置ID(用于日志)
|
||||||
|
* @param tradeId Leader 交易ID(用于日志)
|
||||||
|
* @return 成功返回订单ID,失败返回异常
|
||||||
*/
|
*/
|
||||||
private suspend fun createOrderWithRetry(
|
private suspend fun createOrderWithRetry(
|
||||||
clobApi: PolymarketClobApi,
|
clobApi: PolymarketClobApi,
|
||||||
@@ -883,16 +960,16 @@ class CopyOrderTrackingService(
|
|||||||
side: String,
|
side: String,
|
||||||
price: String,
|
price: String,
|
||||||
size: String,
|
size: String,
|
||||||
owner: String, // API Key,用于owner字段
|
owner: String,
|
||||||
copyTradingId: Long,
|
copyTradingId: Long,
|
||||||
tradeId: String
|
tradeId: String
|
||||||
): Result<String> {
|
): Result<String> {
|
||||||
var lastError: Exception? = null
|
var lastError: Exception? = null
|
||||||
|
|
||||||
// 最多重试2次(首次 + 1次重试)
|
// 重试循环:最多重试 MAX_RETRY_ATTEMPTS 次
|
||||||
for (attempt in 1..2) {
|
for (attempt in 1..MAX_RETRY_ATTEMPTS) {
|
||||||
try {
|
try {
|
||||||
// 每次重试都重新生成salt并重新签名
|
// 每次重试都重新生成salt并重新签名,确保签名唯一性
|
||||||
val signedOrder = orderSigningService.createAndSignOrder(
|
val signedOrder = orderSigningService.createAndSignOrder(
|
||||||
privateKey = privateKey,
|
privateKey = privateKey,
|
||||||
makerAddress = makerAddress,
|
makerAddress = makerAddress,
|
||||||
@@ -906,76 +983,118 @@ class CopyOrderTrackingService(
|
|||||||
expiration = "0"
|
expiration = "0"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 构建订单请求(每次重试都使用新签名的订单)
|
// 构建订单请求
|
||||||
// 跟单订单使用 FAK (Fill-And-Kill),允许部分成交,未成交部分立即取消
|
// 跟单订单使用 FAK (Fill-And-Kill),允许部分成交,未成交部分立即取消
|
||||||
// 这样可以快速响应 Leader 的交易,避免订单长期挂单导致价格不匹配
|
// 这样可以快速响应 Leader 的交易,避免订单长期挂单导致价格不匹配
|
||||||
val orderRequest = NewOrderRequest(
|
val orderRequest = NewOrderRequest(
|
||||||
order = signedOrder,
|
order = signedOrder,
|
||||||
owner = owner, // API Key
|
owner = owner,
|
||||||
orderType = "FAK", // Fill-And-Kill
|
orderType = "FAK", // Fill-And-Kill
|
||||||
deferExec = false
|
deferExec = false
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 调用 API 创建订单
|
||||||
val orderResponse = clobApi.createOrder(orderRequest)
|
val orderResponse = clobApi.createOrder(orderRequest)
|
||||||
|
|
||||||
|
// 检查 HTTP 响应状态
|
||||||
if (!orderResponse.isSuccessful || orderResponse.body() == null) {
|
if (!orderResponse.isSuccessful || orderResponse.body() == null) {
|
||||||
val errorBody = try {
|
val errorBody = try {
|
||||||
orderResponse.errorBody()?.string()
|
orderResponse.errorBody()?.string()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
val errorMsg =
|
val errorMsg = "code=${orderResponse.code()}, errorBody=${errorBody ?: "null"}"
|
||||||
"创建订单失败: copyTradingId=$copyTradingId, tradeId=$tradeId, attempt=$attempt, side=$side, price=$price, size=$size, tokenId=$tokenId, code=${orderResponse.code()}, message=${orderResponse.message()}${if (errorBody != null) ", errorBody=$errorBody" else ""}"
|
|
||||||
lastError = Exception(errorMsg)
|
lastError = Exception(errorMsg)
|
||||||
// 所有失败都记录详细日志
|
|
||||||
logger.error(errorMsg)
|
// 记录错误日志
|
||||||
if (attempt < 2) {
|
logger.error("创建订单失败 (尝试 $attempt/$MAX_RETRY_ATTEMPTS): copyTradingId=$copyTradingId, tradeId=$tradeId, $errorMsg")
|
||||||
delay(1000) // 重试前等待1秒
|
|
||||||
|
// 如果不是最后一次尝试,等待后重试
|
||||||
|
if (attempt < MAX_RETRY_ATTEMPTS) {
|
||||||
|
delay(RETRY_DELAY_MS)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
return Result.failure(lastError)
|
return Result.failure(lastError)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 检查业务响应状态
|
||||||
val response = orderResponse.body()!!
|
val response = orderResponse.body()!!
|
||||||
if (!response.success || response.orderId == null) {
|
if (!response.success || response.orderId == null) {
|
||||||
val errorMsg =
|
val errorMsg = "errorMsg=${response.errorMsg}"
|
||||||
"创建订单失败: copyTradingId=$copyTradingId, tradeId=$tradeId, attempt=$attempt, side=$side, price=$price, size=$size, tokenId=$tokenId, errorMsg=${response.errorMsg}"
|
|
||||||
lastError = Exception(errorMsg)
|
lastError = Exception(errorMsg)
|
||||||
// 所有失败都记录详细日志
|
|
||||||
logger.error(errorMsg)
|
// 记录错误日志
|
||||||
if (attempt < 2) {
|
logger.error("创建订单失败 (尝试 $attempt/$MAX_RETRY_ATTEMPTS): copyTradingId=$copyTradingId, tradeId=$tradeId, $errorMsg")
|
||||||
delay(1000) // 重试前等待1秒
|
|
||||||
|
// 如果不是最后一次尝试,等待后重试
|
||||||
|
if (attempt < MAX_RETRY_ATTEMPTS) {
|
||||||
|
delay(RETRY_DELAY_MS)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
return Result.failure(lastError)
|
return Result.failure(lastError)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 成功
|
// 创建订单成功
|
||||||
|
logger.info("创建订单成功: copyTradingId=$copyTradingId, tradeId=$tradeId, orderId=${response.orderId}, attempt=$attempt")
|
||||||
return Result.success(response.orderId)
|
return Result.success(response.orderId)
|
||||||
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
val errorMsg =
|
val errorMsg = "error=${e.message}"
|
||||||
"调用创建订单API异常: copyTradingId=$copyTradingId, tradeId=$tradeId, attempt=$attempt, side=$side, price=$price, size=$size, tokenId=$tokenId, error=${e.message}"
|
|
||||||
lastError = Exception(errorMsg, e)
|
lastError = Exception(errorMsg, e)
|
||||||
// 所有失败都记录详细日志(包括堆栈)
|
|
||||||
logger.error(errorMsg, e)
|
// 记录错误日志(包含堆栈)
|
||||||
if (attempt < 2) {
|
logger.error("创建订单异常 (尝试 $attempt/$MAX_RETRY_ATTEMPTS): copyTradingId=$copyTradingId, tradeId=$tradeId, $errorMsg", e)
|
||||||
delay(1000) // 重试前等待1秒
|
|
||||||
|
// 如果不是最后一次尝试,等待后重试
|
||||||
|
if (attempt < MAX_RETRY_ATTEMPTS) {
|
||||||
|
delay(RETRY_DELAY_MS)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
return Result.failure(lastError)
|
return Result.failure(lastError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val finalError = lastError ?: Exception("创建订单失败:未知错误")
|
// 所有重试都失败
|
||||||
logger.error(
|
val finalError = lastError ?: Exception("error=未知错误")
|
||||||
"创建订单失败(所有重试都失败): copyTradingId=$copyTradingId, tradeId=$tradeId, side=$side, price=$price, size=$size, tokenId=$tokenId",
|
logger.error("创建订单失败(所有重试都失败): copyTradingId=$copyTradingId, tradeId=$tradeId, side=$side, price=$price, size=$size", finalError)
|
||||||
finalError
|
|
||||||
)
|
|
||||||
return Result.failure(finalError)
|
return Result.failure(finalError)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建完整的错误信息(包括堆栈)
|
* 检查是否是唯一键冲突异常
|
||||||
|
*/
|
||||||
|
private fun isUniqueConstraintViolation(e: Exception): Boolean {
|
||||||
|
// 检查是否是 DataIntegrityViolationException 或 DuplicateKeyException
|
||||||
|
if (e is DataIntegrityViolationException || e is DuplicateKeyException) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否是 SQLException(MySQL 错误码 1062 表示重复键)
|
||||||
|
var cause: Throwable? = e.cause
|
||||||
|
while (cause != null) {
|
||||||
|
if (cause is SQLException) {
|
||||||
|
val sqlException = cause as SQLException
|
||||||
|
// MySQL 错误码 1062 表示重复键(Duplicate entry)
|
||||||
|
if (sqlException.errorCode == 1062 || sqlException.sqlState == "23000") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 检查异常消息中是否包含唯一键冲突的关键字
|
||||||
|
val message = cause.message ?: ""
|
||||||
|
if (message.contains("Duplicate entry") ||
|
||||||
|
message.contains("uk_leader_trade") ||
|
||||||
|
message.contains("UNIQUE constraint")
|
||||||
|
) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
cause = cause.cause
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建简化的错误信息(只保留 code 和 errorBody)
|
||||||
*/
|
*/
|
||||||
private fun buildFullErrorMessage(
|
private fun buildFullErrorMessage(
|
||||||
exception: Throwable?,
|
exception: Throwable?,
|
||||||
@@ -985,35 +1104,29 @@ class CopyOrderTrackingService(
|
|||||||
tradeId: String
|
tradeId: String
|
||||||
): String {
|
): String {
|
||||||
if (exception == null) {
|
if (exception == null) {
|
||||||
return "创建订单失败: side=$side, price=$price, size=$size, tradeId=$tradeId, 未知错误"
|
return "code=未知, errorBody=null"
|
||||||
}
|
}
|
||||||
|
|
||||||
val errorMsg = StringBuilder()
|
val exceptionMessage = exception.message ?: ""
|
||||||
errorMsg.append("创建订单失败: side=$side, price=$price, size=$size, tradeId=$tradeId")
|
|
||||||
errorMsg.append(", error=${exception.message}")
|
|
||||||
|
|
||||||
// 添加堆栈信息(限制长度,避免过长)
|
// 从错误信息中提取 code 和 errorBody
|
||||||
val stackTrace = exception.stackTraceToString()
|
val codePattern = Regex("code=([^,}]+)")
|
||||||
val maxLength = 2000 // 限制错误信息最大长度为2000字符
|
val errorBodyPattern = Regex("errorBody=([^,}]+)")
|
||||||
if (stackTrace.length > maxLength) {
|
|
||||||
errorMsg.append(", stackTrace=${stackTrace.substring(0, maxLength)}...")
|
|
||||||
} else {
|
|
||||||
errorMsg.append(", stackTrace=$stackTrace")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果有 cause,也添加
|
val codeMatch = codePattern.find(exceptionMessage)
|
||||||
exception.cause?.let { cause ->
|
val errorBodyMatch = errorBodyPattern.find(exceptionMessage)
|
||||||
errorMsg.append(", cause=${cause.message}")
|
|
||||||
}
|
|
||||||
|
|
||||||
return errorMsg.toString()
|
val code = codeMatch?.groupValues?.get(1)?.trim() ?: "未知"
|
||||||
|
val errorBody = errorBodyMatch?.groupValues?.get(1)?.trim() ?: "null"
|
||||||
|
|
||||||
|
return "code=$code, errorBody=$errorBody"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 记录失败交易到数据库
|
* 记录失败交易到数据库
|
||||||
|
* 注意:此方法在 @Transactional 方法中被调用,会自动继承事务
|
||||||
*/
|
*/
|
||||||
@Transactional
|
private suspend fun recordFailedTrade(
|
||||||
private fun recordFailedTrade(
|
|
||||||
leaderId: Long,
|
leaderId: Long,
|
||||||
trade: TradeResponse,
|
trade: TradeResponse,
|
||||||
copyTradingId: Long,
|
copyTradingId: Long,
|
||||||
@@ -1064,21 +1177,35 @@ class CopyOrderTrackingService(
|
|||||||
processedAt = System.currentTimeMillis()
|
processedAt = System.currentTimeMillis()
|
||||||
)
|
)
|
||||||
processedTradeRepository.save(processed)
|
processedTradeRepository.save(processed)
|
||||||
} catch (e: DataIntegrityViolationException) {
|
} catch (e: Exception) {
|
||||||
// 唯一约束冲突,说明已经处理过了(可能是并发请求)
|
// 检查是否是唯一键冲突异常
|
||||||
// 检查现有记录的状态
|
if (isUniqueConstraintViolation(e)) {
|
||||||
val existing = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
// 唯一约束冲突,说明已经处理过了(可能是并发请求)
|
||||||
if (existing != null) {
|
// 检查现有记录的状态
|
||||||
if (existing.status == "SUCCESS") {
|
val existing = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||||
logger.warn("交易已成功处理,但尝试记录为失败(并发冲突): leaderId=$leaderId, tradeId=${trade.id}")
|
if (existing != null) {
|
||||||
|
if (existing.status == "SUCCESS") {
|
||||||
|
logger.warn("交易已成功处理,但尝试记录为失败(并发冲突): leaderId=$leaderId, tradeId=${trade.id}")
|
||||||
|
} else {
|
||||||
|
logger.debug("交易已标记为失败(并发检测): leaderId=$leaderId, tradeId=${trade.id}")
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.debug("交易已标记为失败(并发检测): leaderId=$leaderId, tradeId=${trade.id}")
|
// 如果查询不到,等待一下再查询(可能是事务隔离级别问题)
|
||||||
|
delay(100)
|
||||||
|
val existingAfterDelay =
|
||||||
|
processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||||
|
if (existingAfterDelay != null) {
|
||||||
|
logger.debug("延迟查询到记录(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existingAfterDelay.status}")
|
||||||
|
} else {
|
||||||
|
logger.warn(
|
||||||
|
"保存ProcessedTrade失败记录时发生唯一约束冲突,但查询不到记录: leaderId=$leaderId, tradeId=${trade.id}",
|
||||||
|
e
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.warn(
|
// 其他类型的异常,记录但不抛出(避免影响其他交易的处理)
|
||||||
"保存ProcessedTrade失败记录时发生唯一约束冲突,但查询不到记录: leaderId=$leaderId, tradeId=${trade.id}",
|
logger.warn("保存ProcessedTrade失败记录时发生异常: leaderId=$leaderId, tradeId=${trade.id}", e)
|
||||||
e
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -298,8 +298,10 @@ class CopyTradingStatisticsService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 卖出统计
|
// 卖出统计
|
||||||
|
// 使用 SellMatchDetail 计算总卖出金额,确保准确性
|
||||||
|
// 因为每个明细都记录了准确的匹配数量和卖出价格
|
||||||
val totalSellQuantity = sellRecords.sumOf { it.totalMatchedQuantity.toSafeBigDecimal() }
|
val totalSellQuantity = sellRecords.sumOf { it.totalMatchedQuantity.toSafeBigDecimal() }
|
||||||
val totalSellAmount = sellRecords.sumOf { it.totalMatchedQuantity.toSafeBigDecimal().multi(it.sellPrice) }
|
val totalSellAmount = matchDetails.sumOf { it.matchedQuantity.toSafeBigDecimal().multi(it.sellPrice) }
|
||||||
val totalSellOrders = sellRecords.size.toLong()
|
val totalSellOrders = sellRecords.size.toLong()
|
||||||
|
|
||||||
// 持仓统计
|
// 持仓统计
|
||||||
|
|||||||
@@ -36,10 +36,38 @@ class SystemConfigService(
|
|||||||
val builderPassphrase = getConfigValue(CONFIG_KEY_BUILDER_PASSPHRASE)
|
val builderPassphrase = getConfigValue(CONFIG_KEY_BUILDER_PASSPHRASE)
|
||||||
val autoRedeem = isAutoRedeemEnabled()
|
val autoRedeem = isAutoRedeemEnabled()
|
||||||
|
|
||||||
|
// 获取完整的 API Key(用于前端展示)
|
||||||
|
val builderApiKeyDisplay = builderApiKey?.let {
|
||||||
|
try {
|
||||||
|
cryptoUtils.decrypt(it)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val builderSecretDisplay = builderSecret?.let {
|
||||||
|
try {
|
||||||
|
cryptoUtils.decrypt(it)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val builderPassphraseDisplay = builderPassphrase?.let {
|
||||||
|
try {
|
||||||
|
cryptoUtils.decrypt(it)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return SystemConfigDto(
|
return SystemConfigDto(
|
||||||
builderApiKeyConfigured = builderApiKey != null,
|
builderApiKeyConfigured = builderApiKey != null,
|
||||||
builderSecretConfigured = builderSecret != null,
|
builderSecretConfigured = builderSecret != null,
|
||||||
builderPassphraseConfigured = builderPassphrase != null,
|
builderPassphraseConfigured = builderPassphrase != null,
|
||||||
|
builderApiKeyDisplay = builderApiKeyDisplay,
|
||||||
|
builderSecretDisplay = builderSecretDisplay,
|
||||||
|
builderPassphraseDisplay = builderPassphraseDisplay,
|
||||||
autoRedeemEnabled = autoRedeem
|
autoRedeemEnabled = autoRedeem
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -648,5 +648,5 @@ Vite uses `.env.production` file to inject environment variables during build. T
|
|||||||
|
|
||||||
## Technical Support
|
## Technical Support
|
||||||
|
|
||||||
If you have any questions, please submit an Issue to [GitHub](https://github.com/WrBug/PolyHermes) or contact [Twitter](https://x.com/quant_tr).
|
If you have any questions, please submit an Issue to [GitHub](https://github.com/WrBug/PolyHermes) or contact [Twitter](https://x.com/polyhermes).
|
||||||
|
|
||||||
|
|||||||
@@ -648,5 +648,5 @@ Vite 使用 `.env.production` 文件在构建时注入环境变量。构建脚
|
|||||||
|
|
||||||
## 技术支持
|
## 技术支持
|
||||||
|
|
||||||
如有问题,请提交 Issue 到 [GitHub](https://github.com/WrBug/PolyHermes) 或联系 [Twitter](https://x.com/quant_tr)。
|
如有问题,请提交 Issue 到 [GitHub](https://github.com/WrBug/PolyHermes) 或联系 [Twitter](https://x.com/polyhermes)。
|
||||||
|
|
||||||
|
|||||||
@@ -238,7 +238,7 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
|
|||||||
<GithubOutlined />
|
<GithubOutlined />
|
||||||
</a>
|
</a>
|
||||||
<a
|
<a
|
||||||
href="https://x.com/quant_tr"
|
href="https://x.com/polyhermes"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
style={{ color: '#fff', fontSize: '16px', display: 'flex', alignItems: 'center' }}
|
style={{ color: '#fff', fontSize: '16px', display: 'flex', alignItems: 'center' }}
|
||||||
@@ -362,7 +362,7 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
|
|||||||
<GithubOutlined />
|
<GithubOutlined />
|
||||||
</a>
|
</a>
|
||||||
<a
|
<a
|
||||||
href="https://x.com/quant_tr"
|
href="https://x.com/polyhermes"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
style={{ color: '#fff', fontSize: '18px', display: 'flex', alignItems: 'center' }}
|
style={{ color: '#fff', fontSize: '18px', display: 'flex', alignItems: 'center' }}
|
||||||
|
|||||||
@@ -856,6 +856,8 @@
|
|||||||
"copyTradingList": {
|
"copyTradingList": {
|
||||||
"title": "Copy Trading Config Management",
|
"title": "Copy Trading Config Management",
|
||||||
"addCopyTrading": "Add Copy Trading",
|
"addCopyTrading": "Add Copy Trading",
|
||||||
|
"configName": "Config Name",
|
||||||
|
"configNameNotProvided": "Not Provided",
|
||||||
"wallet": "Wallet",
|
"wallet": "Wallet",
|
||||||
"account": "Account",
|
"account": "Account",
|
||||||
"template": "Template",
|
"template": "Template",
|
||||||
|
|||||||
@@ -117,19 +117,40 @@
|
|||||||
},
|
},
|
||||||
"accountImport": {
|
"accountImport": {
|
||||||
"title": "导入账户",
|
"title": "导入账户",
|
||||||
|
"back": "返回",
|
||||||
|
"securityTip": "安全提示",
|
||||||
|
"securityTipDesc": "私钥将存储在后端数据库中,请确保数据库访问安全。建议使用 HTTPS 连接。",
|
||||||
|
"importMethod": "导入方式",
|
||||||
"privateKey": "私钥",
|
"privateKey": "私钥",
|
||||||
|
"mnemonic": "助记词",
|
||||||
|
"privateKeyLabel": "私钥",
|
||||||
|
"privateKeyPlaceholder": "请输入私钥(64位十六进制字符串,可选0x前缀)",
|
||||||
"privateKeyRequired": "请输入私钥",
|
"privateKeyRequired": "请输入私钥",
|
||||||
"privateKeyPlaceholder": "请输入或粘贴私钥",
|
"privateKeyInvalid": "私钥格式不正确(应为64位十六进制字符串)",
|
||||||
"privateKeyHelp": "私钥将加密存储,仅用于签名交易",
|
"walletAddress": "钱包地址",
|
||||||
|
"walletAddressPlaceholder": "钱包地址(将从私钥自动推导)",
|
||||||
|
"walletAddressRequired": "请输入钱包地址",
|
||||||
|
"walletAddressInvalid": "钱包地址格式不正确",
|
||||||
|
"walletAddressMismatch": "钱包地址与私钥不匹配",
|
||||||
|
"mnemonicLabel": "助记词",
|
||||||
|
"mnemonicPlaceholder": "请输入12或24个单词的助记词(用空格分隔)",
|
||||||
|
"mnemonicRequired": "请输入助记词",
|
||||||
|
"mnemonicInvalid": "助记词格式不正确(应为12或24个单词,用空格分隔)",
|
||||||
|
"walletAddressMismatchMnemonic": "钱包地址与助记词不匹配",
|
||||||
"accountName": "账户名称",
|
"accountName": "账户名称",
|
||||||
"accountNameRequired": "请输入账户名称",
|
"accountNameRequired": "请输入账户名称",
|
||||||
"accountNamePlaceholder": "请输入账户名称",
|
"accountNamePlaceholder": "可选,用于标识账户",
|
||||||
"accountNameHelp": "用于标识账户,便于管理",
|
"accountNameHelp": "用于标识账户,便于管理",
|
||||||
|
"privateKeyHelp": "私钥将加密存储,仅用于签名交易",
|
||||||
"submit": "导入",
|
"submit": "导入",
|
||||||
|
"invalidPrivateKey": "无效的私钥",
|
||||||
|
"duplicateAccount": "账户已存在",
|
||||||
|
"importAccount": "导入账户",
|
||||||
"importSuccess": "导入账户成功",
|
"importSuccess": "导入账户成功",
|
||||||
"importFailed": "导入账户失败",
|
"importFailed": "导入账户失败",
|
||||||
"invalidPrivateKey": "无效的私钥",
|
"derivedAddress": "推导地址",
|
||||||
"duplicateAccount": "账户已存在"
|
"addressError": "无法从私钥推导地址",
|
||||||
|
"addressErrorMnemonic": "无法从助记词推导地址"
|
||||||
},
|
},
|
||||||
"leader": {
|
"leader": {
|
||||||
"title": "Leader 管理",
|
"title": "Leader 管理",
|
||||||
|
|||||||
@@ -856,6 +856,8 @@
|
|||||||
"copyTradingList": {
|
"copyTradingList": {
|
||||||
"title": "跟單配置管理",
|
"title": "跟單配置管理",
|
||||||
"addCopyTrading": "新增跟單",
|
"addCopyTrading": "新增跟單",
|
||||||
|
"configName": "配置名",
|
||||||
|
"configNameNotProvided": "未提供",
|
||||||
"wallet": "錢包",
|
"wallet": "錢包",
|
||||||
"account": "賬戶",
|
"account": "賬戶",
|
||||||
"template": "模板",
|
"template": "模板",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { Card, Form, Input, Button, Select, message, Typography, Space } from 'antd'
|
import { Card, Form, Input, Button, message, Typography, Space } from 'antd'
|
||||||
import { ArrowLeftOutlined } from '@ant-design/icons'
|
import { ArrowLeftOutlined } from '@ant-design/icons'
|
||||||
import { apiService } from '../services/api'
|
import { apiService } from '../services/api'
|
||||||
import { useMediaQuery } from 'react-responsive'
|
import { useMediaQuery } from 'react-responsive'
|
||||||
@@ -8,7 +8,6 @@ import { useTranslation } from 'react-i18next'
|
|||||||
import { isValidWalletAddress } from '../utils'
|
import { isValidWalletAddress } from '../utils'
|
||||||
|
|
||||||
const { Title } = Typography
|
const { Title } = Typography
|
||||||
const { Option } = Select
|
|
||||||
|
|
||||||
const LeaderAdd: React.FC = () => {
|
const LeaderAdd: React.FC = () => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
@@ -24,8 +23,7 @@ const LeaderAdd: React.FC = () => {
|
|||||||
leaderAddress: values.leaderAddress.trim(),
|
leaderAddress: values.leaderAddress.trim(),
|
||||||
leaderName: values.leaderName?.trim() || undefined,
|
leaderName: values.leaderName?.trim() || undefined,
|
||||||
remark: values.remark?.trim() || undefined,
|
remark: values.remark?.trim() || undefined,
|
||||||
website: values.website?.trim() || undefined,
|
website: values.website?.trim() || undefined
|
||||||
category: values.category || undefined
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if (response.data.code === 0) {
|
if (response.data.code === 0) {
|
||||||
@@ -121,17 +119,6 @@ const LeaderAdd: React.FC = () => {
|
|||||||
<Input placeholder={t('leaderAdd.websitePlaceholder') || '可选,例如:https://example.com'} />
|
<Input placeholder={t('leaderAdd.websitePlaceholder') || '可选,例如:https://example.com'} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|
||||||
<Form.Item
|
|
||||||
label={t('leaderAdd.category') || '分类筛选'}
|
|
||||||
name="category"
|
|
||||||
tooltip={t('leaderAdd.categoryTooltip') || '仅跟单该分类的交易,不选择则跟单所有分类(sports 或 crypto)'}
|
|
||||||
>
|
|
||||||
<Select placeholder={t('leaderAdd.categoryPlaceholder') || '选择分类(可选)'} allowClear>
|
|
||||||
<Option value="sports">Sports</Option>
|
|
||||||
<Option value="crypto">Crypto</Option>
|
|
||||||
</Select>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<Form.Item>
|
<Form.Item>
|
||||||
<Space>
|
<Space>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState, useEffect } from 'react'
|
import { useState, useEffect } from 'react'
|
||||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||||
import { Card, Form, Input, Button, Select, message, Typography, Space, Spin } from 'antd'
|
import { Card, Form, Input, Button, message, Typography, Space, Spin } from 'antd'
|
||||||
import { ArrowLeftOutlined } from '@ant-design/icons'
|
import { ArrowLeftOutlined } from '@ant-design/icons'
|
||||||
import { apiService } from '../services/api'
|
import { apiService } from '../services/api'
|
||||||
import { useMediaQuery } from 'react-responsive'
|
import { useMediaQuery } from 'react-responsive'
|
||||||
@@ -8,7 +8,6 @@ import { useTranslation } from 'react-i18next'
|
|||||||
import type { Leader } from '../types'
|
import type { Leader } from '../types'
|
||||||
|
|
||||||
const { Title } = Typography
|
const { Title } = Typography
|
||||||
const { Option } = Select
|
|
||||||
|
|
||||||
const LeaderEdit: React.FC = () => {
|
const LeaderEdit: React.FC = () => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
@@ -38,8 +37,7 @@ const LeaderEdit: React.FC = () => {
|
|||||||
form.setFieldsValue({
|
form.setFieldsValue({
|
||||||
leaderName: leader.leaderName || '',
|
leaderName: leader.leaderName || '',
|
||||||
remark: leader.remark || '',
|
remark: leader.remark || '',
|
||||||
website: leader.website || '',
|
website: leader.website || ''
|
||||||
category: leader.category || undefined
|
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
message.error(response.data.msg || t('leaderEdit.fetchFailed') || '获取 Leader 详情失败')
|
message.error(response.data.msg || t('leaderEdit.fetchFailed') || '获取 Leader 详情失败')
|
||||||
@@ -65,8 +63,7 @@ const LeaderEdit: React.FC = () => {
|
|||||||
leaderId: parseInt(leaderId),
|
leaderId: parseInt(leaderId),
|
||||||
leaderName: values.leaderName?.trim() || undefined,
|
leaderName: values.leaderName?.trim() || undefined,
|
||||||
remark: values.remark?.trim() || undefined,
|
remark: values.remark?.trim() || undefined,
|
||||||
website: values.website?.trim() || undefined,
|
website: values.website?.trim() || undefined
|
||||||
category: values.category || undefined
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if (response.data.code === 0) {
|
if (response.data.code === 0) {
|
||||||
@@ -145,17 +142,6 @@ const LeaderEdit: React.FC = () => {
|
|||||||
<Input placeholder={t('leaderEdit.websitePlaceholder') || '可选,例如:https://example.com'} />
|
<Input placeholder={t('leaderEdit.websitePlaceholder') || '可选,例如:https://example.com'} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|
||||||
<Form.Item
|
|
||||||
label={t('leaderEdit.category') || '分类筛选'}
|
|
||||||
name="category"
|
|
||||||
tooltip={t('leaderEdit.categoryTooltip') || '仅跟单该分类的交易,不选择则跟单所有分类(sports 或 crypto)'}
|
|
||||||
>
|
|
||||||
<Select placeholder={t('leaderEdit.categoryPlaceholder') || '选择分类(可选)'} allowClear>
|
|
||||||
<Option value="sports">Sports</Option>
|
|
||||||
<Option value="crypto">Crypto</Option>
|
|
||||||
</Select>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<Form.Item>
|
<Form.Item>
|
||||||
<Space>
|
<Space>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import { Card, Table, Button, Space, Tag, Popconfirm, message, List, Empty, Spin, Divider, Typography } from 'antd'
|
import { Card, Table, Button, Space, Tag, Popconfirm, message, List, Empty, Spin, Divider, Typography } from 'antd'
|
||||||
import { PlusOutlined, EditOutlined, DeleteOutlined, LinkOutlined, GlobalOutlined } from '@ant-design/icons'
|
import { PlusOutlined, EditOutlined, DeleteOutlined, GlobalOutlined } from '@ant-design/icons'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { apiService } from '../services/api'
|
import { apiService } from '../services/api'
|
||||||
import type { Leader } from '../types'
|
import type { Leader } from '../types'
|
||||||
@@ -67,14 +67,6 @@ const LeaderList: React.FC = () => {
|
|||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
{
|
|
||||||
title: t('leaderList.category') || '分类',
|
|
||||||
dataIndex: 'category',
|
|
||||||
key: 'category',
|
|
||||||
render: (category: string | undefined) => category ? (
|
|
||||||
<Tag color={category === 'sports' ? 'blue' : 'green'}>{category}</Tag>
|
|
||||||
) : <Tag>{t('leaderList.all') || '全部'}</Tag>
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
title: t('leaderList.remark') || '备注',
|
title: t('leaderList.remark') || '备注',
|
||||||
dataIndex: 'remark',
|
dataIndex: 'remark',
|
||||||
@@ -233,37 +225,11 @@ const LeaderList: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 网站 */}
|
|
||||||
{leader.website && (
|
|
||||||
<div style={{ marginBottom: '12px' }}>
|
|
||||||
<Text type="secondary" style={{ fontSize: '12px' }}>
|
|
||||||
{t('leaderList.website') || '网站'}:
|
|
||||||
</Text>
|
|
||||||
<a
|
|
||||||
href={leader.website}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
style={{ fontSize: '12px', marginLeft: '4px' }}
|
|
||||||
>
|
|
||||||
<LinkOutlined /> {leader.website}
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Divider style={{ margin: '12px 0' }} />
|
<Divider style={{ margin: '12px 0' }} />
|
||||||
|
|
||||||
{/* 分类和跟单关系数 */}
|
{/* 跟单关系数 */}
|
||||||
<div style={{ marginBottom: '12px' }}>
|
<div style={{ marginBottom: '12px' }}>
|
||||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', alignItems: 'center' }}>
|
<Tag>{t('leaderList.copyTradingRelations', { count: leader.copyTradingCount }) || `${leader.copyTradingCount} 个跟单关系`}</Tag>
|
||||||
{leader.category ? (
|
|
||||||
<Tag color={leader.category === 'sports' ? 'blue' : 'green'}>
|
|
||||||
{leader.category}
|
|
||||||
</Tag>
|
|
||||||
) : (
|
|
||||||
<Tag>{t('leaderList.all') || '全部'}</Tag>
|
|
||||||
)}
|
|
||||||
<Tag>{t('leaderList.copyTradingRelations', { count: leader.copyTradingCount }) || `${leader.copyTradingCount} 个跟单关系`}</Tag>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 创建时间 */}
|
{/* 创建时间 */}
|
||||||
|
|||||||
@@ -348,10 +348,11 @@ const SystemSettings: React.FC = () => {
|
|||||||
if (response.data.code === 0 && response.data.data) {
|
if (response.data.code === 0 && response.data.data) {
|
||||||
const config = response.data.data
|
const config = response.data.data
|
||||||
setSystemConfig(config)
|
setSystemConfig(config)
|
||||||
|
// 将已配置的值填充到输入框中
|
||||||
relayerForm.setFieldsValue({
|
relayerForm.setFieldsValue({
|
||||||
builderApiKey: '',
|
builderApiKey: config.builderApiKeyDisplay || '',
|
||||||
builderSecret: '',
|
builderSecret: config.builderSecretDisplay || '',
|
||||||
builderPassphrase: '',
|
builderPassphrase: config.builderPassphraseDisplay || '',
|
||||||
})
|
})
|
||||||
autoRedeemForm.setFieldsValue({
|
autoRedeemForm.setFieldsValue({
|
||||||
autoRedeemEnabled: config.autoRedeemEnabled
|
autoRedeemEnabled: config.autoRedeemEnabled
|
||||||
@@ -685,30 +686,32 @@ const SystemSettings: React.FC = () => {
|
|||||||
<Form.Item
|
<Form.Item
|
||||||
label={t('builderApiKey.apiKey')}
|
label={t('builderApiKey.apiKey')}
|
||||||
name="builderApiKey"
|
name="builderApiKey"
|
||||||
help={systemConfig?.builderApiKeyConfigured ? t('builderApiKey.apiKeyHelp') : t('builderApiKey.apiKeyPlaceholder')}
|
|
||||||
>
|
>
|
||||||
<Input
|
<Input
|
||||||
placeholder={systemConfig?.builderApiKeyConfigured ? t('builderApiKey.apiKeyHelp') : t('builderApiKey.apiKeyPlaceholder')}
|
placeholder={t('builderApiKey.apiKeyPlaceholder')}
|
||||||
|
style={{ fontFamily: 'monospace' }}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|
||||||
<Form.Item
|
<Form.Item
|
||||||
label={t('builderApiKey.secret')}
|
label={t('builderApiKey.secret')}
|
||||||
name="builderSecret"
|
name="builderSecret"
|
||||||
help={systemConfig?.builderSecretConfigured ? t('builderApiKey.secretHelp') : t('builderApiKey.secretPlaceholder')}
|
|
||||||
>
|
>
|
||||||
<Input
|
<Input.Password
|
||||||
placeholder={systemConfig?.builderSecretConfigured ? t('builderApiKey.secretHelp') : t('builderApiKey.secretPlaceholder')}
|
placeholder={t('builderApiKey.secretPlaceholder')}
|
||||||
|
style={{ fontFamily: 'monospace' }}
|
||||||
|
iconRender={(visible) => (visible ? <span>👁️</span> : <span>👁️🗨️</span>)}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|
||||||
<Form.Item
|
<Form.Item
|
||||||
label={t('builderApiKey.passphrase')}
|
label={t('builderApiKey.passphrase')}
|
||||||
name="builderPassphrase"
|
name="builderPassphrase"
|
||||||
help={systemConfig?.builderPassphraseConfigured ? t('builderApiKey.passphraseHelp') : t('builderApiKey.passphrasePlaceholder')}
|
|
||||||
>
|
>
|
||||||
<Input
|
<Input.Password
|
||||||
placeholder={systemConfig?.builderPassphraseConfigured ? t('builderApiKey.passphraseHelp') : t('builderApiKey.passphrasePlaceholder')}
|
placeholder={t('builderApiKey.passphrasePlaceholder')}
|
||||||
|
style={{ fontFamily: 'monospace' }}
|
||||||
|
iconRender={(visible) => (visible ? <span>👁️</span> : <span>👁️🗨️</span>)}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|
||||||
|
|||||||
@@ -770,6 +770,9 @@ export interface SystemConfig {
|
|||||||
builderApiKeyConfigured: boolean
|
builderApiKeyConfigured: boolean
|
||||||
builderSecretConfigured: boolean
|
builderSecretConfigured: boolean
|
||||||
builderPassphraseConfigured: boolean
|
builderPassphraseConfigured: boolean
|
||||||
|
builderApiKeyDisplay?: string // Builder API Key 显示值(部分显示)
|
||||||
|
builderSecretDisplay?: string // Builder Secret 显示值(部分显示)
|
||||||
|
builderPassphraseDisplay?: string // Builder Passphrase 显示值(部分显示)
|
||||||
autoRedeemEnabled: boolean // 自动赎回(系统级别配置,默认开启)
|
autoRedeemEnabled: boolean // 自动赎回(系统级别配置,默认开启)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user