Compare commits

...

16 Commits

Author SHA1 Message Date
WrBug e5acad5091 fix(frontend): 限制下单价格最高为 0.99
- 修改所有价格限制从 1 改为 0.99
- 影响位置:
  - handleOpenManualOrderModal: 默认价格计算
  - handlePriceChange: 手动修改价格
  - handleFetchLatestPrice: 获取最新价
  - handleSizeChange: 修改数量时重新计算价格
  - handleManualOrder: 提交订单时
- 确保价格不会超过 Polymarket 的最高限制 0.99

Made-with: Cursor
2026-02-26 21:36:59 +08:00
WrBug 1688fa9633 feat(frontend): 优化"最大"按钮计算,支持保留2位小数
- 修改前:只能整数数量,导致余额浪费
  - 示例:余额2.95U,价格0.86 → 数量3张(浪费0.37U)
- 修改后:保留2位小数,充分利用余额
  - 示例:余额2.95U,价格0.86 → 数量3.43张(利用全部余额)

Made-with: Cursor
2026-02-26 21:30:18 +08:00
WrBug 1967d97c31 fix(frontend): 修复 RATIO 模式下金额被错误截断的问题
- 移除 RATIO 模式下对 defaultAmountUsdc 的 Math.floor 取整
- 保持精确的金额用于计算数量,确保符合用户预期
- 修复示例:60%比例,余额2.95U,价格0.682
  - 修复前:数量 = 1.47(金额被截断为1U)
  - 修复后:数量 = 2.60(金额正确为1.77U)

Made-with: Cursor
2026-02-26 21:26:12 +08:00
WrBug 79b154515d feat(frontend): 手动下单功能增强与金额模式支持
- 后端返回 amountMode 和 amountValue 字段,支持前端获取策略配置
- 手动下单确认弹窗显示用户可用余额(绿色高亮)
- 价格输入框右侧添加"获取最新价"按钮,支持实时更新价格
- 数量输入框右侧添加"最大"按钮,根据余额自动计算最大购买数量
- 修正数量计算逻辑:FIXED 和 RATIO 模式均按实际金额计算数量,保留2位小数
  - FIXED 模式:使用配置的固定金额
  - RATIO 模式:按比例计算可用余额
- 数量计算使用保留小数方式(而非向上取整),确保精确匹配投入金额
  - 示例:固定1U,价格0.4,自动填充2.5张
  - 示例:比例30%,余额20U,价格0.4,自动填充15张

Made-with: Cursor
2026-02-26 21:19:06 +08:00
WrBug 9b4d8fc001 feat(frontend): 优化加密价差策略监控页面移动端体验
- 移动端策略选择器:标题与下拉框垂直布局,支持换行显示
- 下拉框选项支持文本换行,避免长策略名称被截断
- 移动端手动下单按钮改为底部悬浮固定显示
- 两个按钮均分屏幕宽度,符合移动端触摸操作规范

Made-with: Cursor
2026-02-26 20:50:46 +08:00
WrBug cb1f43871a fix(crypto-tail): 周期切换时按周期拉取 tokenIds,修复手动下单 orderbook 不存在
- 后端 initMonitor 支持可选 periodStartUnix,按指定周期取市场与 tokenIds
- 前端周期切换时调用 monitorInit 传入 pushPeriod,确保 tokenIds 与当前周期一致
- 修复切换周期无变化及手动下单报 orderbook does not exist

Made-with: Cursor
2026-02-26 20:43:27 +08:00
WrBug a2be5b7f52 feat(crypto-tail): 价差策略监控页手动下单与 UI 优化
- 后端:手动下单 API,trigger_type 区分 AUTO/MANUAL,价格 4 位小数向上取整
- 前端:监控页手动买入 Up/Down 按钮、二次确认弹窗、策略信息移动端适配
- 下单价格最多 4 位小数;确认页方向仅显示 Up/Down;按钮文案改为「买入 Up/Down」

Made-with: Cursor
2026-02-26 19:23:00 +08:00
WrBug 708d6ddb41 fix(binance): 修复 K 线 WebSocket 断开后无法重连导致 openPrice/closePrice 丢失的问题
当 WebSocket 因网络问题断开时,updateSubscriptions() 只检查订阅集合是否相同,
未检查连接是否真的存在,导致断开后无法重连。
现在会额外检查需要的连接是否都存在,如果缺失则重新建立连接。

Made-with: Cursor
2026-02-26 10:28:28 +08:00
WrBug c5d59dfdf9 refactor: 尾盘策略统一更名为加密价差策略
- 前端:菜单父级「加密价差策略」,子项「策略配置」「实时监控」;i18n 与类型注释全部替换
- 后端:i18n、ErrorCode、DTO/实体/服务注释与日志「尾盘」→「加密价差策略」;TG 通知文案
- 文档:README、中英文用户指南、UI 规格、任务、流程、价差流程、市场数据、动态系数等全部更新
- 不修改 API 路径、路由、表名与类名,保持兼容

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 21:30:50 +08:00
WrBug 4b277eaeab feat(frontend): 尾盘父级菜单与图标优化
- 尾盘策略、尾盘监控归入「尾盘」父级菜单,与跟单交易结构一致
- 菜单图标:父级 LineChart,尾盘策略 RocketOutlined,尾盘监控 DashboardOutlined
- 多语言:新增 menu.cryptoTail(尾盘/尾盤/Crypto Tail)
- 含 CryptoTailMonitor 及后端 DTO/Service 等修改

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 21:17:44 +08:00
WrBug f35bad78d4 feat(i18n): 系统更新功能多语言支持与缺失 key 补全
- 新增 systemUpdate 区块(zh-CN/zh-TW/en)覆盖系统更新页与版本提示
- zh-CN 补充 account.walletType
- SystemUpdate 页与 Layout 版本 tag 全部改为 useTranslation,移除硬编码中文

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 21:14:59 +08:00
WrBug 0740abcf16 fix(crypto-tail): 监控分时图推送节流与前端采样,避免1s内多条数据导致点过密
- 后端: price_change 推送节流,每策略 1s 内最多推送 1 次,其余靠定时 1.5s 推送补足
- 前端: 同周期内分时图追加点时至少间隔 1s 才追加,保证曲线连续且不过密
- 最新价等展示仍实时更新,仅图表序列做采样

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 20:01:29 +08:00
WrBug 377da4fff6 fix(cryptotail): 优化 WebSocket 订阅管理与日志清理
- 使用 createClient() 懒加载 OkHttpClient
- 修复订阅计数归零时未移除策略的问题
- 简化 handleMessage,移除 isFromCurrentPeriod 参数和 book 事件处理
- 清理调试日志,保留关键业务日志

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 19:27:49 +08:00
WrBug 84c79d8812 feat(cryptotail): 尾盘监控双连接与分时图优化
- 监控 WebSocket 拆分为当前周期连接与下一周期连接,周期切换时关闭过期连接并新建下一周期
- 下一周期市场未创建时也建立第二条空连接,保证始终两条连接
- refreshSubscription 增加 Mutex 防重入,避免周期结束时定时器与消息同时触发导致重复执行
- 修复 initMonitor/buildPushData 中 getCurrentOpenClose、spreadMode/spreadValue 等 API 与实体字段引用
- 移除重复的 buildSubscriptionMap、buildPushData 等方法,修复 StrategyPriceData.periodStartUnix
- 前端分时图:市场价折线增加 connectNulls,新周期默认 0.5 价格展示
- 多语言与监控页入口、API 类型与 WebSocket 订阅集成

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 17:00:41 +08:00
WrBug d3196a783f feat(cryptotail): 尾盘策略多市场与币安按需订阅
- 新增 ETH/SOL/XRP 市场选项(5m/15m),Binance 多币种 K 线支持
- 币安 K 线按策略按周期订阅:仅在有启用策略时建连,只订阅用到的市场+周期(如仅 btc 5m 只建 btc 5m)
- BinanceKlineAutoSpreadService 支持完整 slug(如 eth-updown-5m)解析
- 尾盘服务 PreDestroy 与内存/缓存清理(OrderbookWs、Notification、Settlement、Execution)
- 健康检查:无策略时币安 WS 显示「未订阅」;前端币安提醒仅在有启用策略时展示
- 前端:up/down 标签去掉箭头图标

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-20 23:45:24 +08:00
WrBug 4c989a48c4 fix(cryptotail): 防止 refreshAndSubscribe 并发重复调用导致日志刷屏
- 增加 refreshLock 与 isRefreshing 状态,串行化刷新逻辑
- 刷新进行中时直接跳过后续调用,避免 1s 内大量重复「倒计时」「已过时间窗口」日志

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-20 23:18:52 +08:00
50 changed files with 4463 additions and 591 deletions
@@ -0,0 +1,23 @@
package com.wrbug.polymarketbot.config
import com.wrbug.polymarketbot.service.common.WebSocketSubscriptionService
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailMonitorService
import jakarta.annotation.PostConstruct
import org.springframework.context.annotation.Configuration
/**
* 加密价差策略监控服务配置
* 处理 WebSocketSubscriptionService 和 CryptoTailMonitorService 之间的循环依赖
*/
@Configuration
class MonitorServiceConfig(
private val webSocketSubscriptionService: WebSocketSubscriptionService,
private val cryptoTailMonitorService: CryptoTailMonitorService
) {
@PostConstruct
fun init() {
// 在所有 Bean 初始化后设置引用
webSocketSubscriptionService.setCryptoTailMonitorService(cryptoTailMonitorService)
}
}
@@ -11,9 +11,15 @@ import com.wrbug.polymarketbot.dto.CryptoTailStrategyTriggerListResponse
import com.wrbug.polymarketbot.dto.CryptoTailStrategyUpdateRequest
import com.wrbug.polymarketbot.dto.CryptoTailMarketOptionDto
import com.wrbug.polymarketbot.dto.CryptoTailAutoMinSpreadResponse
import com.wrbug.polymarketbot.dto.CryptoTailMonitorInitRequest
import com.wrbug.polymarketbot.dto.CryptoTailMonitorInitResponse
import com.wrbug.polymarketbot.dto.CryptoTailManualOrderRequest
import com.wrbug.polymarketbot.dto.CryptoTailManualOrderResponse
import com.wrbug.polymarketbot.enums.ErrorCode
import com.wrbug.polymarketbot.service.binance.BinanceKlineAutoSpreadService
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailStrategyService
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailMonitorService
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailStrategyExecutionService
import org.slf4j.LoggerFactory
import org.springframework.context.MessageSource
import org.springframework.http.ResponseEntity
@@ -21,11 +27,14 @@ import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import kotlinx.coroutines.runBlocking
@RestController
@RequestMapping("/api/crypto-tail-strategy")
class CryptoTailStrategyController(
private val cryptoTailStrategyService: CryptoTailStrategyService,
private val cryptoTailMonitorService: CryptoTailMonitorService,
private val cryptoTailStrategyExecutionService: CryptoTailStrategyExecutionService,
private val binanceKlineAutoSpreadService: BinanceKlineAutoSpreadService,
private val messageSource: MessageSource
) {
@@ -39,12 +48,12 @@ class CryptoTailStrategyController(
result.fold(
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
onFailure = { e ->
logger.error("查询尾盘策略列表失败: ${e.message}", e)
logger.error("查询加密价差策略列表失败: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_LIST_FETCH_FAILED, e.message, messageSource))
}
)
} catch (e: Exception) {
logger.error("查询尾盘策略列表异常: ${e.message}", e)
logger.error("查询加密价差策略列表异常: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_LIST_FETCH_FAILED, e.message, messageSource))
}
}
@@ -56,7 +65,7 @@ class CryptoTailStrategyController(
result.fold(
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
onFailure = { e ->
logger.error("创建尾盘策略失败: ${e.message}", e)
logger.error("创建加密价差策略失败: ${e.message}", e)
val code = when (e.message) {
ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID
ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED
@@ -68,7 +77,7 @@ class CryptoTailStrategyController(
}
)
} catch (e: Exception) {
logger.error("创建尾盘策略异常: ${e.message}", e)
logger.error("创建加密价差策略异常: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_CREATE_FAILED, e.message, messageSource))
}
}
@@ -83,7 +92,7 @@ class CryptoTailStrategyController(
result.fold(
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
onFailure = { e ->
logger.error("更新尾盘策略失败: ${e.message}", e)
logger.error("更新加密价差策略失败: ${e.message}", e)
val code = when (e.message) {
ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND
ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID.messageKey -> ErrorCode.CRYPTO_TAIL_STRATEGY_WINDOW_INVALID
@@ -95,7 +104,7 @@ class CryptoTailStrategyController(
}
)
} catch (e: Exception) {
logger.error("更新尾盘策略异常: ${e.message}", e)
logger.error("更新加密价差策略异常: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_UPDATE_FAILED, e.message, messageSource))
}
}
@@ -111,12 +120,12 @@ class CryptoTailStrategyController(
result.fold(
onSuccess = { ResponseEntity.ok(ApiResponse.success(Unit)) },
onFailure = { e ->
logger.error("删除尾盘策略失败: ${e.message}", e)
logger.error("删除加密价差策略失败: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_DELETE_FAILED, e.message, messageSource))
}
)
} catch (e: Exception) {
logger.error("删除尾盘策略异常: ${e.message}", e)
logger.error("删除加密价差策略异常: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_CRYPTO_TAIL_STRATEGY_DELETE_FAILED, e.message, messageSource))
}
}
@@ -146,7 +155,13 @@ class CryptoTailStrategyController(
return try {
val options = listOf(
CryptoTailMarketOptionDto(slug = "btc-updown-5m", title = "Bitcoin Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
CryptoTailMarketOptionDto(slug = "btc-updown-15m", title = "Bitcoin Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null)
CryptoTailMarketOptionDto(slug = "btc-updown-15m", title = "Bitcoin Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null),
CryptoTailMarketOptionDto(slug = "eth-updown-5m", title = "Ethereum Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
CryptoTailMarketOptionDto(slug = "eth-updown-15m", title = "Ethereum Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null),
CryptoTailMarketOptionDto(slug = "sol-updown-5m", title = "Solana Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
CryptoTailMarketOptionDto(slug = "sol-updown-15m", title = "Solana Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null),
CryptoTailMarketOptionDto(slug = "xrp-updown-5m", title = "XRP Up or Down - 5 minute", intervalSeconds = 300, periodStartUnix = 0L, endDate = null),
CryptoTailMarketOptionDto(slug = "xrp-updown-15m", title = "XRP Up or Down - 15 minute", intervalSeconds = 900, periodStartUnix = 0L, endDate = null)
)
ResponseEntity.ok(ApiResponse.success(options))
} catch (e: Exception) {
@@ -167,8 +182,10 @@ class CryptoTailStrategyController(
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, messageSource = messageSource))
}
val periodStartUnix = (request["periodStartUnix"] as? Number)?.toLong()
?: (System.currentTimeMillis() / 1000 / intervalSeconds) * intervalSeconds
val pair = binanceKlineAutoSpreadService.computeAndCache(intervalSeconds, periodStartUnix)
?: ((System.currentTimeMillis() / 1000 / intervalSeconds) * intervalSeconds)
// 默认使用 BTC 市场(向后兼容)
val marketSlugPrefix = (request["marketSlugPrefix"] as? String) ?: "btc-updown"
val pair = binanceKlineAutoSpreadService.computeAndCache(marketSlugPrefix, intervalSeconds, periodStartUnix)
?: return ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, "fetch_failed", messageSource))
val body = CryptoTailAutoMinSpreadResponse(
minSpreadUp = pair.first.toPlainString(),
@@ -180,4 +197,65 @@ class CryptoTailStrategyController(
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
}
}
/**
* 初始化加密价差策略监控
* 返回策略信息、开盘价、tokenIds等初始化数据
*/
@PostMapping("/monitor/init")
fun initMonitor(@RequestBody request: CryptoTailMonitorInitRequest): ResponseEntity<ApiResponse<CryptoTailMonitorInitResponse>> {
return try {
if (request.strategyId <= 0) {
return ResponseEntity.ok(ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource))
}
val result = cryptoTailMonitorService.initMonitor(request)
result.fold(
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
onFailure = { e ->
logger.error("初始化加密价差策略监控失败: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
}
)
} catch (e: Exception) {
logger.error("初始化加密价差策略监控异常: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
}
}
/**
* 手动下单
* 用户主动触发下单,不检查任何条件,仅检查当前周期是否已下单
*/
@PostMapping("/manual-order")
fun manualOrder(@RequestBody request: CryptoTailManualOrderRequest): ResponseEntity<ApiResponse<CryptoTailManualOrderResponse>> {
return runBlocking {
try {
if (request.strategyId <= 0) {
return@runBlocking ResponseEntity.ok(
ApiResponse.error(ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND, messageSource = messageSource)
)
}
val result = cryptoTailStrategyExecutionService.manualOrder(request)
result.fold(
onSuccess = { ResponseEntity.ok(ApiResponse.success(it)) },
onFailure = { e ->
logger.error("手动下单失败: ${e.message}", e)
val code = when (e.message) {
"策略不存在" -> ErrorCode.CRYPTO_TAIL_STRATEGY_NOT_FOUND
"当前周期已下单" -> ErrorCode.PARAM_ERROR
"价格必须在 0~1 之间" -> ErrorCode.PARAM_ERROR
"数量不能少于 1" -> ErrorCode.PARAM_ERROR
"总金额不能少于 1 USDC" -> ErrorCode.PARAM_ERROR
"总金额超过策略配置的投入金额" -> ErrorCode.PARAM_ERROR
else -> ErrorCode.SERVER_ERROR
}
ResponseEntity.ok(ApiResponse.error(code, e.message, messageSource))
}
)
} catch (e: Exception) {
logger.error("手动下单异常: ${e.message}", e)
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, e.message, messageSource))
}
}
}
}
@@ -0,0 +1,21 @@
package com.wrbug.polymarketbot.dto
/**
* 加密价差策略手动下单请求
*/
data class CryptoTailManualOrderRequest(
/** 策略ID */
val strategyId: Long = 0L,
/** 当前周期开始时间 (Unix 秒) */
val periodStartUnix: Long = 0L,
/** 下单方向: UP or DOWN */
val direction: String = "UP",
/** 下单价格 */
val price: String = "0",
/** 下单数量 */
val size: String = "1",
/** 市场标题(用于记录) */
val marketTitle: String = "",
/** Token IDs */
val tokenIds: List<String> = emptyList()
)
@@ -0,0 +1,31 @@
package com.wrbug.polymarketbot.dto
/**
* 加密价差策略手动下单响应
*/
data class CryptoTailManualOrderResponse(
/** 是否成功 */
val success: Boolean = false,
/** 订单ID */
val orderId: String? = null,
/** 提示消息 */
val message: String = "",
/** 下单详情 */
val orderDetails: ManualOrderDetails? = null
)
/**
* 手动下单详情
*/
data class ManualOrderDetails(
/** 策略ID */
val strategyId: Long = 0L,
/** 方向 */
val direction: String = "",
/** 下单价格 */
val price: String = "",
/** 下单数量 */
val size: String = "",
/** 总金额 */
val totalAmount: String = ""
)
@@ -0,0 +1,111 @@
package com.wrbug.polymarketbot.dto
/**
* 加密价差策略监控初始化请求
*/
data class CryptoTailMonitorInitRequest(
/** 策略ID */
val strategyId: Long = 0L,
/** 指定周期开始时间 (Unix 秒),不传则用服务器当前周期 */
val periodStartUnix: Long? = null
)
/**
* 加密价差策略监控初始化响应
*/
data class CryptoTailMonitorInitResponse(
/** 策略ID */
val strategyId: Long = 0L,
/** 策略名称 */
val name: String = "",
/** 账户ID */
val accountId: Long = 0L,
/** 账户名称 */
val accountName: String = "",
/** 市场 slug 前缀 */
val marketSlugPrefix: String = "",
/** 市场标题 */
val marketTitle: String = "",
/** 周期秒数 (300=5m, 900=15m) */
val intervalSeconds: Int = 300,
/** 当前周期开始时间 (Unix 秒) */
val periodStartUnix: Long = 0L,
/** 时间窗口开始秒数 */
val windowStartSeconds: Int = 0,
/** 时间窗口结束秒数 */
val windowEndSeconds: Int = 0,
/** 最低价格 */
val minPrice: String = "0",
/** 最高价格 */
val maxPrice: String = "1",
/** 最小价差模式: NONE, FIXED, AUTO */
val minSpreadMode: String = "NONE",
/** 价差方向: MIN(显示周期内最小价差), MAX(显示周期内最大价差) */
val spreadDirection: String = "MIN",
/** 最小价差数值 (FIXED 时有值) */
val minSpreadValue: String? = null,
/** 自动计算的最小价差 (Up方向) */
val autoMinSpreadUp: String? = null,
/** 自动计算的最小价差 (Down方向) */
val autoMinSpreadDown: String? = null,
/** BTC 开盘价 USDC(来自币安 K 线 open */
val openPriceBtc: String? = null,
/** Up tokenId */
val tokenIdUp: String? = null,
/** Down tokenId */
val tokenIdDown: String? = null,
/** 当前时间 (毫秒时间戳) */
val currentTimestamp: Long = System.currentTimeMillis(),
/** 是否启用 */
val enabled: Boolean = true,
/** 投入金额模式: FIXED or RATIO */
val amountMode: String? = null,
/** 投入金额数值 */
val amountValue: String? = null
)
/**
* 加密价差策略监控实时推送数据
*/
data class CryptoTailMonitorPushData(
/** 策略ID */
val strategyId: Long = 0L,
/** 推送时间 (毫秒时间戳) */
val timestamp: Long = System.currentTimeMillis(),
/** 当前周期开始时间 (Unix 秒) */
val periodStartUnix: Long = 0L,
/** 当前周期市场标题(周期切换时更新) */
val marketTitle: String = "",
/** 当前价格 (Up方向,来自订单簿) */
val currentPriceUp: String? = null,
/** 当前价格 (Down方向,来自订单簿) */
val currentPriceDown: String? = null,
/** 当前价差 (Up方向: 1 - currentPriceUp) */
val spreadUp: String? = null,
/** 当前价差 (Down方向: currentPriceUp) */
val spreadDown: String? = null,
/** 最小价差线 (Up方向) */
val minSpreadLineUp: String? = null,
/** 最小价差线 (Down方向,USDC 价差) */
val minSpreadLineDown: String? = null,
/** BTC 开盘价 USDC(币安 K 线 open */
val openPriceBtc: String? = null,
/** BTC 最新价 USDC(币安 K 线 close,当前周期实时) */
val currentPriceBtc: String? = null,
/** BTC 价差 USDCcurrentPriceBtc - openPriceBtc */
val spreadBtc: String? = null,
/** 周期剩余秒数 */
val remainingSeconds: Int = 0,
/** 是否在时间窗口内 */
val inTimeWindow: Boolean = false,
/** 是否在价格区间内 (Up方向) */
val inPriceRangeUp: Boolean = false,
/** 是否在价格区间内 (Down方向) */
val inPriceRangeDown: Boolean = false,
/** 是否已触发 */
val triggered: Boolean = false,
/** 触发方向: UP, DOWN, null */
val triggerDirection: String? = null,
/** 周期是否已结束 */
val periodEnded: Boolean = false
)
@@ -1,7 +1,7 @@
package com.wrbug.polymarketbot.dto
/**
* 尾盘策略创建请求
* 加密价差策略创建请求
* 金额与价格使用 String,后端转为 BigDecimal
*/
data class CryptoTailStrategyCreateRequest(
@@ -25,7 +25,7 @@ data class CryptoTailStrategyCreateRequest(
)
/**
* 尾盘策略更新请求
* 加密价差策略更新请求
*/
data class CryptoTailStrategyUpdateRequest(
val strategyId: Long = 0L,
@@ -46,7 +46,7 @@ data class CryptoTailStrategyUpdateRequest(
)
/**
* 尾盘策略列表请求
* 加密价差策略列表请求
*/
data class CryptoTailStrategyListRequest(
val accountId: Long? = null,
@@ -54,7 +54,7 @@ data class CryptoTailStrategyListRequest(
)
/**
* 尾盘策略 DTO(列表与详情)
* 加密价差策略 DTO(列表与详情)
*/
data class CryptoTailStrategyDto(
val id: Long = 0L,
@@ -90,14 +90,14 @@ data class CryptoTailStrategyDto(
)
/**
* 尾盘策略列表响应
* 加密价差策略列表响应
*/
data class CryptoTailStrategyListResponse(
val list: List<CryptoTailStrategyDto> = emptyList()
)
/**
* 尾盘策略删除请求
* 加密价差策略删除请求
*/
data class CryptoTailStrategyDeleteRequest(
val strategyId: Long = 0L
@@ -8,7 +8,7 @@ import jakarta.persistence.*
import java.math.BigDecimal
/**
* 加密市场尾盘策略实体
* 加密价差策略实体
* 5/15 分钟 Up or Down 市场,在周期内时间窗口、价格进入区间时市价买入
*/
@Entity
@@ -5,7 +5,7 @@ import java.math.BigDecimal
import com.wrbug.polymarketbot.util.toSafeBigDecimal
/**
* 尾盘策略触发记录
* 加密价差策略触发记录
*/
@Entity
@Table(name = "crypto_tail_strategy_trigger")
@@ -56,6 +56,9 @@ data class CryptoTailStrategyTrigger(
@Column(name = "fail_reason", length = 500)
val failReason: String? = null,
@Column(name = "trigger_type", nullable = false, length = 20)
val triggerType: String = "AUTO",
@Column(name = "created_at", nullable = false)
val createdAt: Long = System.currentTimeMillis(),
@@ -158,8 +158,8 @@ enum class ErrorCode(
ACCOUNT_BALANCE_FETCH_FAILED(4707, "查询账户余额失败", "error.account_balance_fetch_failed"),
ACCOUNT_POSITIONS_FETCH_FAILED(4708, "查询仓位列表失败", "error.account_positions_fetch_failed"),
// 尾盘策略 (4710-4729)
CRYPTO_TAIL_STRATEGY_NOT_FOUND(4710, "尾盘策略不存在", "error.crypto_tail_strategy_not_found"),
// 加密价差策略 (4710-4729)
CRYPTO_TAIL_STRATEGY_NOT_FOUND(4710, "加密价差策略不存在", "error.crypto_tail_strategy_not_found"),
CRYPTO_TAIL_STRATEGY_WINDOW_INVALID(4711, "时间区间开始不能大于结束", "error.crypto_tail_strategy_window_invalid"),
CRYPTO_TAIL_STRATEGY_WINDOW_EXCEED(4712, "时间区间不能超过周期长度", "error.crypto_tail_strategy_window_exceed"),
CRYPTO_TAIL_STRATEGY_INTERVAL_INVALID(4713, "周期仅支持 300 或 900 秒", "error.crypto_tail_strategy_interval_invalid"),
@@ -259,11 +259,11 @@ enum class ErrorCode(
SERVER_BACKTEST_RETRY_FAILED(5612, "重试回测任务失败", "error.server.backtest_retry_failed"),
SERVER_BACKTEST_RERUN_FAILED(5613, "按配置重新测试失败", "error.server.backtest_rerun_failed"),
// 尾盘策略服务 (5620-5629)
SERVER_CRYPTO_TAIL_STRATEGY_CREATE_FAILED(5620, "创建尾盘策略失败", "error.server.crypto_tail_strategy_create_failed"),
SERVER_CRYPTO_TAIL_STRATEGY_UPDATE_FAILED(5621, "更新尾盘策略失败", "error.server.crypto_tail_strategy_update_failed"),
SERVER_CRYPTO_TAIL_STRATEGY_DELETE_FAILED(5622, "删除尾盘策略失败", "error.server.crypto_tail_strategy_delete_failed"),
SERVER_CRYPTO_TAIL_STRATEGY_LIST_FETCH_FAILED(5623, "查询尾盘策略列表失败", "error.server.crypto_tail_strategy_list_fetch_failed"),
// 加密价差策略服务 (5620-5629)
SERVER_CRYPTO_TAIL_STRATEGY_CREATE_FAILED(5620, "创建加密价差策略失败", "error.server.crypto_tail_strategy_create_failed"),
SERVER_CRYPTO_TAIL_STRATEGY_UPDATE_FAILED(5621, "更新加密价差策略失败", "error.server.crypto_tail_strategy_update_failed"),
SERVER_CRYPTO_TAIL_STRATEGY_DELETE_FAILED(5622, "删除加密价差策略失败", "error.server.crypto_tail_strategy_delete_failed"),
SERVER_CRYPTO_TAIL_STRATEGY_LIST_FETCH_FAILED(5623, "查询加密价差策略列表失败", "error.server.crypto_tail_strategy_list_fetch_failed"),
SERVER_CRYPTO_TAIL_STRATEGY_TRIGGERS_FETCH_FAILED(5624, "查询触发记录失败", "error.server.crypto_tail_strategy_triggers_fetch_failed");
companion object {
@@ -3,6 +3,6 @@ package com.wrbug.polymarketbot.event
import org.springframework.context.ApplicationEvent
/**
* 尾盘策略创建/更新/启用状态变更后发布,用于立即触发一轮执行检查。
* 加密价差策略创建/更新/启用状态变更后发布,用于立即触发一轮执行检查。
*/
class CryptoTailStrategyChangedEvent(source: Any) : ApplicationEvent(source)
@@ -23,7 +23,7 @@ interface CryptoTailStrategyTriggerRepository : JpaRepository<CryptoTailStrategy
/** 轮询结算:仅处理下单成功的订单(status=success 且 orderId 非空)、且未结算的触发记录 */
fun findByStatusAndResolvedAndOrderIdIsNotNullOrderByCreatedAtAsc(status: String, resolved: Boolean): List<CryptoTailStrategyTrigger>
/** 根据订单 ID 查询尾盘触发记录 */
/** 根据订单 ID 查询加密价差策略触发记录 */
fun findByOrderId(orderId: String): CryptoTailStrategyTrigger?
/** 轮询发 TGstatus=success、orderId 非空、未发过通知,按创建时间正序 */
@@ -125,8 +125,8 @@ class AccountService(
// 7. 加密敏感信息
val encryptedPrivateKey = cryptoUtils.encrypt(request.privateKey)
val encryptedApiSecret = apiKeyCreds.secret?.let { cryptoUtils.encrypt(it) }
val encryptedApiPassphrase = apiKeyCreds.passphrase?.let { cryptoUtils.encrypt(it) }
val encryptedApiSecret = apiKeyCreds.secret.let { cryptoUtils.encrypt(it) }
val encryptedApiPassphrase = apiKeyCreds.passphrase.let { cryptoUtils.encrypt(it) }
// 8. 生成账户名称(如果未提供,使用 SAFE/MAGIC-代理地址后4位)
val accountName = if (request.accountName.isNullOrBlank()) {
@@ -518,8 +518,8 @@ class AccountService(
}
val creds = result.getOrNull()
?: return Result.failure(IllegalStateException("API Key 返回为空"))
val encryptedSecret = creds.secret?.let { cryptoUtils.encrypt(it) }
val encryptedPassphrase = creds.passphrase?.let { cryptoUtils.encrypt(it) }
val encryptedSecret = creds.secret.let { cryptoUtils.encrypt(it) }
val encryptedPassphrase = creds.passphrase.let { cryptoUtils.encrypt(it) }
val updated = account.copy(
apiKey = creds.apiKey,
apiSecret = encryptedSecret,
@@ -1128,7 +1128,7 @@ class AccountService(
// 3. 验证仓位是否存在并获取原始数量
val positionsResult = getAllPositions()
val (position, originalQuantity) = positionsResult.fold(
val (_, originalQuantity) = positionsResult.fold(
onSuccess = { positionListResponse ->
val position = positionListResponse.currentPositions.find {
it.accountId == request.accountId &&
@@ -1161,7 +1161,7 @@ class AccountService(
onFailure = { e ->
return Result.failure(Exception("查询仓位失败: ${e.message}"))
}
) ?: return Result.failure(IllegalArgumentException("仓位不存在"))
)
// 4. 计算实际卖出数量
val sellQuantity = if (percentDecimal != null) {
@@ -1280,7 +1280,7 @@ class AccountService(
val newOrderRequest = com.wrbug.polymarketbot.api.NewOrderRequest(
order = signedOrder,
owner = account.apiKey!!, // API Key
owner = account.apiKey, // API Key
orderType = orderType,
deferExec = false
)
@@ -1300,7 +1300,7 @@ class AccountService(
}
val clobApi = retrofitFactory.createClobApi(
account.apiKey!!,
account.apiKey,
apiSecret,
apiPassphrase,
account.walletAddress
@@ -396,7 +396,7 @@ class PositionCheckService(
val positionsByAccount = redeemablePositions.groupBy { it.accountId }
for ((accountId, positions) in positionsByAccount) {
// 查找该账户下所有启用的跟单配置(仅用于赎回成功后更新跟单订单状态;无跟单配置的账户如尾盘策略账户也会执行赎回)
// 查找该账户下所有启用的跟单配置(仅用于赎回成功后更新跟单订单状态;无跟单配置的账户如加密价差策略账户也会执行赎回)
val copyTradings = copyTradingRepository.findByAccountId(accountId)
.filter { it.enabled }
@@ -9,7 +9,7 @@ import java.math.RoundingMode
import java.util.concurrent.ConcurrentHashMap
/**
* 自动最小价差按周期计算每个周期首次需要时拉取该周期前的 20 根已收盘 K 线按方向筛选IQR 剔除后求平均缓存 100% 基准值 (interval, period)
* 自动最小价差按周期计算每个周期首次需要时拉取该周期前的 20 根已收盘 K 线按方向筛选IQR 剔除后求平均缓存 100% 基准值 (marketSlugPrefix, interval, period)
* 触发时由调用方按窗口进度计算动态系数100%50%后得到有效最小价差不在保存策略时计算
*/
@Service
@@ -19,29 +19,68 @@ class BinanceKlineAutoSpreadService(
private val logger = LoggerFactory.getLogger(BinanceKlineAutoSpreadService::class.java)
private val symbol = "BTCUSDC"
/** 市场 slug 前缀 -> Binance 交易对映射 */
private val marketToSymbol = mapOf(
"btc-updown" to "BTCUSDC",
"eth-updown" to "ETHUSDC",
"sol-updown" to "SOLUSDC",
"xrp-updown" to "XRPUSDC"
)
private val historyLimit = 20
private val minSamplesAfterIqr = 3
/** (intervalSeconds, periodStartUnix) -> (baseSpreadUp, baseSpreadDown)100% 基准价差 */
/** (marketSlugPrefix, intervalSeconds, periodStartUnix) -> (baseSpreadUp, baseSpreadDown)100% 基准价差 */
private val cache = ConcurrentHashMap<String, Pair<BigDecimal, BigDecimal>>()
private fun cacheKey(intervalSeconds: Int, periodStartUnix: Long): String = "$intervalSeconds-$periodStartUnix"
/** 缓存保留时间(秒),超过则清理,防止无界增长 */
private val cacheExpireSeconds = 3600L
/** 从市场 slug 前缀获取 Binance 交易对;支持完整 slug(如 eth-updown-5m)或前缀(如 eth-updown */
private fun getSymbol(marketSlugPrefix: String): String? {
val base = marketSlugPrefix.lowercase().removeSuffix("-15m").removeSuffix("-5m")
return marketToSymbol[base]
}
private fun cacheKey(marketSlugPrefix: String, intervalSeconds: Int, periodStartUnix: Long): String {
return "$marketSlugPrefix-$intervalSeconds-$periodStartUnix"
}
/** 清理已过期的价差缓存,避免内存泄漏 */
private fun cleanExpiredCache() {
val nowSeconds = System.currentTimeMillis() / 1000
val expireThreshold = nowSeconds - cacheExpireSeconds
val keysToRemove = cache.keys.filter { key ->
// key 格式: marketSlugPrefix-intervalSeconds-periodStartUnix
val parts = key.split('-')
if (parts.size >= 3) {
parts.last().toLongOrNull()?.let { it < expireThreshold } ?: false
} else {
false
}
}
keysToRemove.forEach { cache.remove(it) }
}
/** 返回该周期、该方向的 100% 基准价差,供调用方按窗口进度应用动态系数。 */
fun getAutoMinSpreadBase(intervalSeconds: Int, periodStartUnix: Long, outcomeIndex: Int): BigDecimal? {
val key = cacheKey(intervalSeconds, periodStartUnix)
fun getAutoMinSpreadBase(marketSlugPrefix: String, intervalSeconds: Int, periodStartUnix: Long, outcomeIndex: Int): BigDecimal? {
val key = cacheKey(marketSlugPrefix, intervalSeconds, periodStartUnix)
val (up, down) = cache[key] ?: run {
computeAndCache(intervalSeconds, periodStartUnix) ?: return null
computeAndCache(marketSlugPrefix, intervalSeconds, periodStartUnix) ?: return null
}
return if (outcomeIndex == 0) up else down
}
/** 计算并缓存 100% 基准价差(IQR 平均,不乘系数)。预加载与触发时共用此缓存。 */
fun computeAndCache(intervalSeconds: Int, periodStartUnix: Long): Pair<BigDecimal, BigDecimal>? {
fun computeAndCache(marketSlugPrefix: String, intervalSeconds: Int, periodStartUnix: Long): Pair<BigDecimal, BigDecimal>? {
cleanExpiredCache()
val symbol = getSymbol(marketSlugPrefix) ?: run {
logger.warn("不支持的市场 slug 前缀: $marketSlugPrefix")
return null
}
val intervalStr = if (intervalSeconds == 300) "5m" else "15m"
val endTimeMs = periodStartUnix * 1000L
val klines = fetchKlines(intervalStr, historyLimit, endTime = endTimeMs) ?: return null
val klines = fetchKlines(symbol, intervalStr, historyLimit, endTime = endTimeMs) ?: return null
val spreadsUp = mutableListOf<BigDecimal>()
val spreadsDown = mutableListOf<BigDecimal>()
for (k in klines) {
@@ -53,16 +92,16 @@ class BinanceKlineAutoSpreadService(
}
val baseUp = averageAfterIqr(spreadsUp).setScale(8, RoundingMode.HALF_UP)
val baseDown = averageAfterIqr(spreadsDown).setScale(8, RoundingMode.HALF_UP)
cache[cacheKey(intervalSeconds, periodStartUnix)] = baseUp to baseDown
cache[cacheKey(marketSlugPrefix, intervalSeconds, periodStartUnix)] = baseUp to baseDown
logger.info(
"尾盘自动价差已计算并缓存(100%基准): interval=${intervalSeconds}s periodStartUnix=$periodStartUnix | " +
"加密价差策略自动价差已计算并缓存(100%基准): market=$marketSlugPrefix symbol=$symbol interval=${intervalSeconds}s periodStartUnix=$periodStartUnix | " +
"Up方向: 样本数=${spreadsUp.size}, baseSpreadUp=${baseUp.toPlainString()} | " +
"Down方向: 样本数=${spreadsDown.size}, baseSpreadDown=${baseDown.toPlainString()}"
)
return baseUp to baseDown
}
private fun fetchKlines(interval: String, limit: Int, endTime: Long? = null): List<List<Any>>? {
private fun fetchKlines(symbol: String, interval: String, limit: Int, endTime: Long? = null): List<List<Any>>? {
return try {
val api = retrofitFactory.createBinanceApi()
val call = api.getKlines(symbol = symbol, interval = interval, limit = limit, endTime = endTime)
@@ -16,10 +16,11 @@ import org.springframework.stereotype.Service
import java.math.BigDecimal
import jakarta.annotation.PreDestroy
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/**
* 币安 K 线 WebSocket订阅 BTCUSDC 5m/15m维护当前周期 (open, close)尾盘策略价差校验使用
* 币安 K 线 WebSocket按需订阅加密价差策略使用的币种 5m/15m维护当前周期 (open, close)供价差校验使用
* 仅当存在启用策略且策略使用到某市场时才订阅对应币种无策略时不建立连接
*/
@Service
class BinanceKlineService {
@@ -28,91 +29,138 @@ class BinanceKlineService {
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val wsBase = "wss://stream.binance.com:9443"
private val client = createClient().build()
private val client by lazy {
createClient().build()
}
/** (intervalSeconds, periodStartUnix) -> (open, close) */
/** (marketSlugPrefix, intervalSeconds, periodStartUnix) -> (open, close) */
private val openCloseByPeriod = ConcurrentHashMap<String, Pair<BigDecimal, BigDecimal>>()
private var ws5m: WebSocket? = null
private var ws15m: WebSocket? = null
private var reconnectJob: Job? = null
private val connected5m = AtomicBoolean(false)
private val connected15m = AtomicBoolean(false)
init {
connectAll()
}
private fun key(intervalSeconds: Int, periodStartUnix: Long): String = "$intervalSeconds-$periodStartUnix"
fun getCurrentOpenClose(intervalSeconds: Int, periodStartUnix: Long): Pair<BigDecimal, BigDecimal>? {
return openCloseByPeriod[key(intervalSeconds, periodStartUnix)]
}
/** 供 API 健康检查使用:5m / 15m 连接是否正常 */
fun getConnectionStatuses(): Map<String, Boolean> = mapOf(
"5m" to connected5m.get(),
"15m" to connected15m.get()
/** 市场 slug 前缀(如 btc-updown-> Binance 交易对映射 */
private val marketToSymbol = mapOf(
"btc-updown" to "BTCUSDC",
"eth-updown" to "ETHUSDC",
"sol-updown" to "SOLUSDC",
"xrp-updown" to "XRPUSDC"
)
/** 已连接的 WebSocket: wsKey (symbol-interval) -> WebSocket */
private val connectedWebSockets = ConcurrentHashMap<String, WebSocket>()
/** 当前需要订阅的完整市场集合(如 btc-updown-5m、btc-updown-15m),由加密价差策略刷新时更新 */
private val requiredMarketPrefixes = AtomicReference<Set<String>>(emptySet())
private val subscriptionLock = Any()
private var reconnectJob: Job? = null
private fun connectAll() {
if (ws5m != null && ws15m != null) return
connectStream("btcusdc@kline_5m") { intervalSec, tMs, openP, closeP ->
val periodSec = tMs / 1000
openCloseByPeriod[key(intervalSec, periodSec)] = openP to closeP
}.also { ws5m = it }
connectStream("btcusdc@kline_15m") { intervalSec, tMs, openP, closeP ->
val periodSec = tMs / 1000
openCloseByPeriod[key(intervalSec, periodSec)] = openP to closeP
}.also { ws15m = it }
/** 解析完整市场 slug(如 btc-updown-5m)为 (basePrefix, interval),不支持则返回 null */
private fun parseMarketSlug(full: String): Pair<String, String>? {
val lower = full.lowercase()
return when {
lower.endsWith("-5m") -> Pair(lower.removeSuffix("-5m"), "5m")
lower.endsWith("-15m") -> Pair(lower.removeSuffix("-15m"), "15m")
else -> null
}
}
/** 从市场 base 前缀(如 btc-updown)获取 Binance 交易对 */
private fun getSymbol(basePrefix: String): String? = marketToSymbol[basePrefix]
private fun key(marketSlugPrefix: String, intervalSeconds: Int, periodStartUnix: Long): String {
return "$marketSlugPrefix-$intervalSeconds-$periodStartUnix"
}
fun getCurrentOpenClose(marketSlugPrefix: String, intervalSeconds: Int, periodStartUnix: Long): Pair<BigDecimal, BigDecimal>? {
return openCloseByPeriod[key(marketSlugPrefix, intervalSeconds, periodStartUnix)]
}
/** 供 API 健康检查使用:各币种各周期的连接状态 */
fun getConnectionStatuses(): Map<String, Boolean> {
return connectedWebSockets.keys.associateWith { connectedWebSockets[it] != null }
}
/**
* 按需更新订阅仅订阅策略用到的 (币种, 周期)例如只开 btc 5min 则只建 btc 5min K 线连接
* CryptoTailOrderbookWsService 在刷新订阅时根据启用策略的 marketSlugPrefix 调用
* @param marketPrefixes 当前启用策略用到的完整市场集合 ["btc-updown-5m"] ["btc-updown-5m", "eth-updown-15m"]空集合时关闭所有连接
*/
fun updateSubscriptions(marketPrefixes: Set<String>) {
val normalized = marketPrefixes.map { it.lowercase() }.toSet()
val parsed = normalized.mapNotNull { full ->
parseMarketSlug(full)?.let { (base, interval) ->
getSymbol(base)?.let { symbol -> Triple(full, symbol, interval) }
}
}.toSet()
val wsKeysNeeded = parsed.map { (_, symbol, interval) -> "$symbol-$interval" }.toSet()
// 检查是否有需要的 WebSocket 连接缺失(可能因网络问题断开)
val hasMissingConnection = wsKeysNeeded.any { it !in connectedWebSockets.keys }
// 只有当集合相同且所有需要的连接都存在时才跳过
if (normalized == requiredMarketPrefixes.get() && !hasMissingConnection) return
requiredMarketPrefixes.set(normalized)
synchronized(subscriptionLock) {
connectedWebSockets.keys.toList().forEach { wsKey ->
if (wsKey !in wsKeysNeeded) {
connectedWebSockets.remove(wsKey)?.close(1000, "subscription_update")
logger.info("币安 K 线 WS 已关闭(无策略使用): $wsKey")
}
}
parsed.forEach { (fullPrefix, symbol, interval) ->
connectStream(symbol, interval, fullPrefix) { marketPrefixParam, intervalSec, tMs, openP, closeP ->
val periodSec = tMs / 1000
openCloseByPeriod[key(marketPrefixParam, intervalSec, periodSec)] = openP to closeP
}
}
}
}
private fun connectStream(
streamName: String,
onKline: (intervalSeconds: Int, openTimeMs: Long, open: BigDecimal, close: BigDecimal) -> Unit
): WebSocket {
symbol: String,
interval: String,
marketPrefix: String,
onKline: (marketPrefix: String, intervalSeconds: Int, openTimeMs: Long, open: BigDecimal, close: BigDecimal) -> Unit
) {
val streamName = "${symbol.lowercase()}@kline_$interval"
val wsKey = "$symbol-$interval"
if (connectedWebSockets[wsKey] != null) return
val url = "$wsBase/ws/$streamName"
val intervalSeconds = when {
streamName.contains("kline_5m") -> 300
streamName.contains("kline_15m") -> 900
val intervalSeconds = when (interval) {
"5m" -> 300
"15m" -> 900
else -> 300
}
val request = Request.Builder().url(url).build()
val connectedFlag = when {
streamName.contains("kline_5m") -> connected5m
streamName.contains("kline_15m") -> connected15m
else -> null
}
val ws = client.newWebSocket(request, object : WebSocketListener() {
client.newWebSocket(request, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
connectedFlag?.set(true)
connectedWebSockets[wsKey] = webSocket
logger.info("币安 K 线 WS 已连接: $streamName")
}
override fun onMessage(webSocket: WebSocket, text: String) {
parseKlineMessage(text, intervalSeconds)?.let { (tMs, o, c) ->
onKline(intervalSeconds, tMs, o, c)
parseKlineMessage(text)?.let { (tMs, o, c) ->
onKline(marketPrefix, intervalSeconds, tMs, o, c)
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
connectedFlag?.set(false)
connectedWebSockets.remove(wsKey)
logger.warn("币安 K 线 WS 异常 $streamName: ${t.message}")
scheduleReconnect()
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
connectedFlag?.set(false)
connectedWebSockets.remove(wsKey)
if (code != 1000) scheduleReconnect()
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
connectedFlag?.set(false)
connectedWebSockets.remove(wsKey)
}
})
logger.info("币安 K 线 WS 已连接: $streamName")
return ws
}
private fun parseKlineMessage(text: String, intervalSeconds: Int): Triple<Long, BigDecimal, BigDecimal>? {
private fun parseKlineMessage(text: String): Triple<Long, BigDecimal, BigDecimal>? {
return try {
val json = com.google.gson.JsonParser.parseString(text).asJsonObject
if (json.get("e")?.asString != "kline") return null
@@ -132,23 +180,20 @@ class BinanceKlineService {
reconnectJob = scope.launch {
delay(3_000)
reconnectJob = null
ws5m?.close(1000, "reconnect")
ws15m?.close(1000, "reconnect")
ws5m = null
ws15m = null
connected5m.set(false)
connected15m.set(false)
val current = requiredMarketPrefixes.get()
connectedWebSockets.values.forEach { it.close(1000, "reconnect") }
connectedWebSockets.clear()
logger.info("币安 K 线 WS 尝试重连")
connectAll()
// 清空 requiredMarketPrefixes,否则 updateSubscriptions(current) 内会因 normalized == requiredMarketPrefixes.get() 直接 return,不会重新 connectStream
requiredMarketPrefixes.set(emptySet())
updateSubscriptions(current)
}
}
@PreDestroy
fun destroy() {
reconnectJob?.cancel()
ws5m?.close(1000, "shutdown")
ws15m?.close(1000, "shutdown")
ws5m = null
ws15m = null
connectedWebSockets.values.forEach { it.close(1000, "shutdown") }
connectedWebSockets.clear()
}
}
@@ -1,11 +1,13 @@
package com.wrbug.polymarketbot.service.common
import com.wrbug.polymarketbot.dto.CryptoTailMonitorPushData
import com.wrbug.polymarketbot.dto.OrderPushMessage
import com.wrbug.polymarketbot.dto.PositionPushMessage
import com.wrbug.polymarketbot.dto.WebSocketMessage as WsMessage
import com.wrbug.polymarketbot.dto.WebSocketMessageType
import com.wrbug.polymarketbot.service.accounts.PositionPushService
import com.wrbug.polymarketbot.service.copytrading.orders.OrderPushService
import com.wrbug.polymarketbot.service.cryptotail.CryptoTailMonitorService
import kotlinx.coroutines.*
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@@ -38,28 +40,47 @@ class WebSocketSubscriptionService(
// 存储 order 频道的订阅回调:sessionId -> callback(用于取消订阅)
private val orderChannelCallbacks = ConcurrentHashMap<String, (OrderPushMessage) -> Unit>()
// 存储加密价差策略监控频道的订阅回调:sessionId -> (strategyId -> callback)
private val monitorChannelCallbacks = ConcurrentHashMap<String, MutableMap<Long, (CryptoTailMonitorPushData) -> Unit>>()
// 加密价差策略监控服务(延迟注入,避免循环依赖)
private var cryptoTailMonitorService: CryptoTailMonitorService? = null
/**
* 设置加密价差策略监控服务 Spring 在初始化后调用
*/
fun setCryptoTailMonitorService(service: CryptoTailMonitorService) {
cryptoTailMonitorService = service
}
/**
* 注册会话
*/
fun registerSession(sessionId: String, callback: (WsMessage) -> Unit) {
sessionCallbacks[sessionId] = callback
sessionSubscriptions[sessionId] = mutableSetOf()
monitorChannelCallbacks[sessionId] = mutableMapOf()
}
/**
* 注销会话
*/
fun unregisterSession(sessionId: String) {
// 取消所有订阅
val channels = sessionSubscriptions.remove(sessionId) ?: emptySet()
channels.forEach { channel ->
unsubscribe(sessionId, channel)
}
// 清理 order 频道的回调
orderChannelCallbacks.remove(sessionId)
// 清理加密价差策略监控频道的回调
val monitorCallbacks = monitorChannelCallbacks.remove(sessionId)
monitorCallbacks?.keys?.forEach { strategyId ->
cryptoTailMonitorService?.unsubscribe(sessionId, strategyId)
}
sessionCallbacks.remove(sessionId)
}
@@ -83,8 +104,8 @@ class WebSocketSubscriptionService(
sendSubscribeAck(sessionId, channel, true)
// 根据频道类型启动推送服务
when (channel) {
"position" -> {
when {
channel == "position" -> {
positionPushService.subscribe(sessionId) { message ->
pushData(sessionId, channel, message)
}
@@ -97,7 +118,7 @@ class WebSocketSubscriptionService(
}
}
}
"order" -> {
channel == "order" -> {
// 订单推送:自动订阅所有启用的账户
val callback: (OrderPushMessage) -> Unit = { message ->
pushData(sessionId, channel, message)
@@ -105,6 +126,20 @@ class WebSocketSubscriptionService(
orderChannelCallbacks[sessionId] = callback
orderPushService.subscribeAllEnabled(callback)
}
channel.startsWith("crypto_tail_monitor_") -> {
// 加密价差策略监控频道
val strategyId = channel.removePrefix("crypto_tail_monitor_").toLongOrNull()
if (strategyId != null && cryptoTailMonitorService != null) {
val callback: (CryptoTailMonitorPushData) -> Unit = { message ->
pushData(sessionId, channel, message)
}
monitorChannelCallbacks.getOrPut(sessionId) { mutableMapOf() }[strategyId] = callback
cryptoTailMonitorService!!.subscribe(sessionId, strategyId, callback)
} else {
logger.warn("无效的加密价差策略监控频道或服务未初始化: $channel")
sendSubscribeAck(sessionId, channel, false, "无效的策略ID")
}
}
else -> {
logger.warn("未知的频道: $channel")
sendSubscribeAck(sessionId, channel, false, "未知的频道")
@@ -122,15 +157,58 @@ class WebSocketSubscriptionService(
channelSubscriptions[channel]?.remove(sessionId)
// 取消推送服务的订阅(推送服务内部会处理是否停止轮询)
when (channel) {
"position" -> positionPushService.unsubscribe(sessionId)
"order" -> {
when {
channel == "position" -> positionPushService.unsubscribe(sessionId)
channel == "order" -> {
// 取消订阅所有账户的订单推送
val callback = orderChannelCallbacks.remove(sessionId)
if (callback != null) {
orderPushService.unsubscribeAll(callback)
}
}
channel.startsWith("crypto_tail_monitor_") -> {
// 取消加密价差策略监控订阅
val strategyId = channel.removePrefix("crypto_tail_monitor_").toLongOrNull()
if (strategyId != null) {
monitorChannelCallbacks[sessionId]?.remove(strategyId)
cryptoTailMonitorService?.unsubscribe(sessionId, strategyId)
}
}
}
}
/**
* 注册加密价差策略监控回调 CryptoTailMonitorService 调用
*/
fun registerMonitorCallback(sessionId: String, strategyId: Long, callback: (CryptoTailMonitorPushData) -> Unit) {
monitorChannelCallbacks.getOrPut(sessionId) { mutableMapOf() }[strategyId] = callback
}
/**
* 注销加密价差策略监控回调 CryptoTailMonitorService 调用
*/
fun unregisterMonitorCallback(sessionId: String, strategyId: Long) {
monitorChannelCallbacks[sessionId]?.remove(strategyId)
}
/**
* 推送加密价差策略监控数据 CryptoTailMonitorService 调用
*/
fun pushMonitorData(strategyId: Long, data: CryptoTailMonitorPushData) {
val channel = "crypto_tail_monitor_$strategyId"
val sessionIds = channelSubscriptions[channel] ?: return
for (sessionId in sessionIds) {
val callback = sessionCallbacks[sessionId]
if (callback != null) {
val message = WsMessage(
type = WebSocketMessageType.DATA.value,
channel = channel,
payload = data,
timestamp = System.currentTimeMillis()
)
callback(message)
}
}
}
@@ -168,4 +246,3 @@ class WebSocketSubscriptionService(
}
}
}
@@ -0,0 +1,843 @@
package com.wrbug.polymarketbot.service.cryptotail
import com.wrbug.polymarketbot.api.GammaEventBySlugResponse
import com.wrbug.polymarketbot.constants.PolymarketConstants
import com.wrbug.polymarketbot.dto.CryptoTailMonitorInitRequest
import com.wrbug.polymarketbot.dto.CryptoTailMonitorInitResponse
import com.wrbug.polymarketbot.dto.CryptoTailMonitorPushData
import com.wrbug.polymarketbot.entity.CryptoTailStrategy
import com.wrbug.polymarketbot.repository.AccountRepository
import com.wrbug.polymarketbot.repository.CryptoTailStrategyRepository
import com.wrbug.polymarketbot.service.binance.BinanceKlineAutoSpreadService
import com.wrbug.polymarketbot.service.binance.BinanceKlineService
import com.wrbug.polymarketbot.service.common.WebSocketSubscriptionService
import com.wrbug.polymarketbot.util.RetrofitFactory
import com.wrbug.polymarketbot.util.createClient
import com.wrbug.polymarketbot.util.fromJson
import com.wrbug.polymarketbot.util.toJson
import com.wrbug.polymarketbot.util.toSafeBigDecimal
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.slf4j.LoggerFactory
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Service
import jakarta.annotation.PostConstruct
import jakarta.annotation.PreDestroy
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.Collections
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/**
* 加密价差策略监控服务
* 负责实时推送监控数据到前端
*/
@Service
class CryptoTailMonitorService(
private val strategyRepository: CryptoTailStrategyRepository,
private val accountRepository: AccountRepository,
private val retrofitFactory: RetrofitFactory,
private val binanceKlineService: BinanceKlineService,
private val binanceKlineAutoSpreadService: BinanceKlineAutoSpreadService,
private val webSocketSubscriptionService: WebSocketSubscriptionService
) {
private val logger = LoggerFactory.getLogger(CryptoTailMonitorService::class.java)
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
/** 当前周期 token 映射 */
private val currentPeriodTokenToStrategy = AtomicReference<Map<String, List<MonitorEntry>>>(emptyMap())
/** 下一周期 token 映射 */
private val nextPeriodTokenToStrategy = AtomicReference<Map<String, List<MonitorEntry>>>(emptyMap())
/** strategyId -> 当前价格数据 */
private val strategyPriceData = ConcurrentHashMap<Long, StrategyPriceData>()
/** strategyId -> 订阅者数量 */
private val strategySubscribers = ConcurrentHashMap<Long, Int>()
private var currentPeriodWebSocket: WebSocket? = null
private var nextPeriodWebSocket: WebSocket? = null
private val wsUrl = PolymarketConstants.RTDS_WS_URL + "/ws/market"
private val client by lazy {
createClient().build()
}
private val reconnectDelayMs = 3_000L
private var reconnectJob: Job? = null
private val closedForNoSubscribers = AtomicBoolean(false)
private val connectLock = Any()
/** 防止 refreshSubscription 并发执行(周期结束时定时器与消息可能同时触发) */
private val refreshSubscriptionMutex = Mutex()
/** 周期结束倒计时 Job */
private var periodEndCountdownJob: Job? = null
/** 定时推送 Job(每 1.5 秒推送一次,保证 BTC 价格和分时图持续更新) */
private var periodicPushJob: Job? = null
private val pushIntervalMs = 1_500L
/** 策略推送历史(用于中途进入时补全分时图,最多保留 300 条) */
private val strategyPushHistory = ConcurrentHashMap<Long, MutableList<CryptoTailMonitorPushData>>()
private val strategyHistoryPeriod = ConcurrentHashMap<Long, Long>()
private val maxHistorySize = 300
/** price_change 推送节流:每策略最近一次推送时间,1s 内不重复推送 */
private val lastPriceChangePushTime = ConcurrentHashMap<Long, Long>()
private val priceChangePushThrottleMs = 1_000L
/** 当前周期/下一周期构建时缓存的市场标题,key = "strategyId-periodStartUnix",供推送携带 */
private val marketTitleByStrategyPeriod = ConcurrentHashMap<String, String>()
data class MonitorEntry(
val strategyId: Long,
val strategy: CryptoTailStrategy,
val periodStartUnix: Long,
val outcomeIndex: Int,
val tokenId: String,
/** 是否为下一个周期(用于预先订阅) */
val isNextPeriod: Boolean = false
)
data class StrategyPriceData(
val currentPriceUp: BigDecimal? = null,
val currentPriceDown: BigDecimal? = null,
/** BTC 开盘价 USDC(币安 K 线 open */
val openPriceBtc: BigDecimal? = null,
val spreadUp: BigDecimal? = null,
val spreadDown: BigDecimal? = null,
val minSpreadLineUp: BigDecimal? = null,
val minSpreadLineDown: BigDecimal? = null,
val triggered: Boolean = false,
val triggerDirection: String? = null,
val lastUpdateTime: Long = System.currentTimeMillis(),
/** 当前周期开始时间(用于双连接周期切换) */
val periodStartUnix: Long? = null
)
@PostConstruct
fun init() {
// 服务启动时不主动连接,等待前端订阅
}
/**
* 初始化监控数据
*/
fun initMonitor(request: CryptoTailMonitorInitRequest): Result<CryptoTailMonitorInitResponse> {
return try {
val strategy = strategyRepository.findById(request.strategyId).orElse(null)
if (strategy == null) {
return Result.failure(IllegalArgumentException("策略不存在"))
}
val account = accountRepository.findById(strategy.accountId).orElse(null)
val nowSeconds = System.currentTimeMillis() / 1000
val periodStartUnix = request.periodStartUnix
?: ((nowSeconds / strategy.intervalSeconds) * strategy.intervalSeconds)
// 获取市场信息
val slug = "${strategy.marketSlugPrefix}-$periodStartUnix"
val event = fetchEventBySlug(slug).getOrNull()
val market = event?.markets?.firstOrNull()
val tokenIds = parseClobTokenIds(market?.clobTokenIds)
// 获取开盘价(币安 K 线 open = BTC 价格 USDC
val openClose = binanceKlineService.getCurrentOpenClose(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)
val openPriceBtc = openClose?.first
// 获取自动计算的最小价差
var autoMinSpreadUp: BigDecimal? = null
var autoMinSpreadDown: BigDecimal? = null
if (strategy.spreadMode.name.uppercase() == "AUTO") {
val autoSpreads = binanceKlineAutoSpreadService.computeAndCache(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)
autoMinSpreadUp = autoSpreads?.first
autoMinSpreadDown = autoSpreads?.second
}
// 保存价格数据到缓存
val priceData = StrategyPriceData(
openPriceBtc = openPriceBtc,
minSpreadLineUp = autoMinSpreadUp ?: strategy.spreadValue?.toSafeBigDecimal(),
minSpreadLineDown = autoMinSpreadDown ?: strategy.spreadValue?.toSafeBigDecimal(),
periodStartUnix = periodStartUnix
)
strategyPriceData[strategy.id!!] = priceData
val response = CryptoTailMonitorInitResponse(
strategyId = strategy.id!!,
name = strategy.name ?: "",
accountId = strategy.accountId,
accountName = account?.accountName ?: "",
marketSlugPrefix = strategy.marketSlugPrefix,
marketTitle = event?.title ?: strategy.marketSlugPrefix,
intervalSeconds = strategy.intervalSeconds,
periodStartUnix = periodStartUnix,
windowStartSeconds = strategy.windowStartSeconds,
windowEndSeconds = strategy.windowEndSeconds,
minPrice = strategy.minPrice.toPlainString(),
maxPrice = strategy.maxPrice.toPlainString(),
minSpreadMode = strategy.spreadMode.name,
spreadDirection = strategy.spreadDirection.name,
minSpreadValue = strategy.spreadValue?.toPlainString(),
autoMinSpreadUp = autoMinSpreadUp?.toPlainString(),
autoMinSpreadDown = autoMinSpreadDown?.toPlainString(),
openPriceBtc = openPriceBtc?.setScale(2, RoundingMode.HALF_UP)?.toPlainString(),
tokenIdUp = tokenIds.getOrNull(0),
tokenIdDown = tokenIds.getOrNull(1),
currentTimestamp = System.currentTimeMillis(),
enabled = strategy.enabled,
amountMode = strategy.amountMode,
amountValue = strategy.amountValue.toPlainString()
)
Result.success(response)
} catch (e: Exception) {
logger.error("初始化监控失败: ${e.message}", e)
Result.failure(e)
}
}
/**
* 订阅策略监控
*/
fun subscribe(sessionId: String, strategyId: Long, callback: (CryptoTailMonitorPushData) -> Unit) {
// 增加订阅计数
val count = strategySubscribers.merge(strategyId, 1) { old, inc -> old + inc } ?: 1
// 注册推送回调
webSocketSubscriptionService.registerMonitorCallback(sessionId, strategyId, callback)
// 如果是第一个订阅者,启动 WebSocket 和定时推送
if (count == 1) {
scope.launch {
refreshSubscription()
}
startPeriodicPush()
}
// 立即发送当前数据
scope.launch {
try {
sendCurrentData(sessionId, strategyId, callback)
} catch (e: Exception) {
logger.error("发送当前监控数据失败: $sessionId, ${e.message}")
}
}
}
/**
* 取消订阅策略监控
*/
fun unsubscribe(sessionId: String, strategyId: Long) {
// 减少订阅计数
val currentCount = strategySubscribers[strategyId] ?: 0
val newCount = (currentCount - 1).coerceAtLeast(0)
if (newCount == 0) {
strategySubscribers.remove(strategyId)
} else {
strategySubscribers[strategyId] = newCount
}
// 移除回调
webSocketSubscriptionService.unregisterMonitorCallback(sessionId, strategyId)
// 如果没有订阅者,关闭 WebSocket 和定时推送
if (newCount == 0) {
scope.launch {
refreshSubscription()
}
stopPeriodicPush()
}
}
private fun startPeriodicPush() {
if (periodicPushJob?.isActive == true) return
periodicPushJob = scope.launch {
while (strategySubscribers.isNotEmpty() && strategySubscribers.values.any { (it ?: 0) > 0 }) {
delay(pushIntervalMs)
if (closedForNoSubscribers.get()) continue
val ids = strategySubscribers.filter { (it.value ?: 0) > 0 }.keys.toList()
for (strategyId in ids) {
try {
val strategy = strategyRepository.findById(strategyId).orElse(null) ?: continue
val priceData = strategyPriceData[strategyId] ?: continue
val pushData = buildPushData(strategy, priceData)
addToHistoryAndPush(strategyId, pushData)
} catch (e: Exception) {
logger.debug("定时推送失败 strategyId=$strategyId: ${e.message}")
}
}
}
}
}
private fun stopPeriodicPush() {
if (strategySubscribers.isEmpty() || strategySubscribers.values.all { (it ?: 0) <= 0 }) {
periodicPushJob?.cancel()
periodicPushJob = null
}
}
/**
* 发送当前数据含历史补全用于中途进入时填充分时图
*/
private suspend fun sendCurrentData(
sessionId: String,
strategyId: Long,
callback: (CryptoTailMonitorPushData) -> Unit
) {
val strategy = strategyRepository.findById(strategyId).orElse(null) ?: return
val priceData = strategyPriceData[strategyId] ?: StrategyPriceData()
val history = strategyPushHistory[strategyId]?.let { list ->
synchronized(list) { list.toList() }
} ?: emptyList()
for (item in history) {
callback(item)
}
val pushData = buildPushData(strategy, priceData)
callback(pushData)
}
/**
* 刷新订阅双连接模式当前周期连接 + 下一周期连接周期切换时关闭过期连接下一连接晋升为当前并新建下一周期连接
* 使用 Mutex 防止周期结束时 scheduleRefreshAtPeriodEnd maybeRefreshSubscriptionIfPeriodChanged 同时触发导致重复执行
*/
private suspend fun refreshSubscription() {
if (!refreshSubscriptionMutex.tryLock()) {
return
}
try {
refreshSubscriptionInternal()
} finally {
refreshSubscriptionMutex.unlock()
}
}
private suspend fun refreshSubscriptionInternal() {
periodEndCountdownJob?.cancel()
periodEndCountdownJob = null
val subscribedStrategyIds = strategySubscribers.keys.filter { (strategySubscribers[it] ?: 0) > 0 }
if (subscribedStrategyIds.isEmpty()) {
closeAllWebSockets()
return
}
val strategies = strategyRepository.findAllById(subscribedStrategyIds).filter { it.enabled && it.id != null }
if (strategies.isEmpty()) {
closeAllWebSockets()
return
}
val nowSeconds = System.currentTimeMillis() / 1000
val isSwitch = currentPeriodWebSocket != null
if (isSwitch) {
// 周期切换:关闭当前周期连接,下一晋升为当前,新建下一周期连接
closeCurrentPeriodWebSocket()
currentPeriodWebSocket = nextPeriodWebSocket
nextPeriodWebSocket = null
val nextMap = nextPeriodTokenToStrategy.get()
currentPeriodTokenToStrategy.set(nextMap)
val nextPeriodByStrategy =
nextMap.values.flatten().distinctBy { it.strategyId }.associate { it.strategyId to it.periodStartUnix }
logger.info("周期切换:下一周期连接晋升为当前")
for ((strategyId, periodStartUnix) in nextPeriodByStrategy) {
updateStrategyPriceDataForPeriod(listOf(strategyId), periodStartUnix, pushDefault = true)
}
val (newNextTokenIds, newNextMap) = buildSubscriptionMapForNextPeriod(subscribedStrategyIds)
nextPeriodTokenToStrategy.set(newNextMap)
if (newNextTokenIds.isNotEmpty()) {
connectNextPeriod(newNextTokenIds, newNextMap)
} else {
logger.info("下一周期市场尚未创建,仅建立空连接以便周期切换时复用")
connectNextPeriod(emptyList(), emptyMap())
}
scheduleRefreshAtPeriodEnd(if (newNextMap.isNotEmpty()) newNextMap else nextMap)
} else {
// 首次:建立当前周期连接 + 下一周期连接
val (currentTokenIds, currentMap) = buildSubscriptionMapForCurrentPeriod(subscribedStrategyIds)
currentPeriodTokenToStrategy.set(currentMap)
for (entry in currentMap.values.flatten().distinctBy { it.strategyId }) {
updateStrategyPriceDataForPeriod(listOf(entry.strategyId), entry.periodStartUnix, pushDefault = false)
}
if (currentTokenIds.isEmpty()) {
closeAllWebSockets()
return
}
connectCurrentPeriod(currentTokenIds, currentMap)
val (nextTokenIds, nextMap) = buildSubscriptionMapForNextPeriod(subscribedStrategyIds)
nextPeriodTokenToStrategy.set(nextMap)
if (nextTokenIds.isNotEmpty()) {
connectNextPeriod(nextTokenIds, nextMap)
} else {
logger.info("下一周期市场尚未创建,先建立空连接,周期切换时会重新订阅")
connectNextPeriod(emptyList(), emptyMap())
}
scheduleRefreshAtPeriodEnd(currentMap)
}
}
/** 构建当前周期订阅(每个策略按自己的 interval 算当前周期) */
private suspend fun buildSubscriptionMapForCurrentPeriod(strategyIds: List<Long>): Pair<List<String>, Map<String, List<MonitorEntry>>> {
val strategies = strategyRepository.findAllById(strategyIds)
val nowSeconds = System.currentTimeMillis() / 1000
val tokenIdSet = mutableSetOf<String>()
val map = mutableMapOf<String, MutableList<MonitorEntry>>()
for (strategy in strategies) {
if (!strategy.enabled || strategy.id == null) continue
val strategyPeriod = (nowSeconds / strategy.intervalSeconds) * strategy.intervalSeconds
val slug = "${strategy.marketSlugPrefix}-$strategyPeriod"
val event = fetchEventBySlug(slug).getOrNull() ?: continue
marketTitleByStrategyPeriod["${strategy.id!!}-$strategyPeriod"] = event.title ?: strategy.marketSlugPrefix
val market = event.markets?.firstOrNull() ?: continue
val tokenIds = parseClobTokenIds(market.clobTokenIds)
if (tokenIds.size < 2) continue
for (i in tokenIds.indices) {
tokenIdSet.add(tokenIds[i])
map.getOrPut(tokenIds[i]) { mutableListOf() }.add(
MonitorEntry(strategy.id!!, strategy, strategyPeriod, i, tokenIds[i], false)
)
}
}
return Pair(tokenIdSet.toList(), map)
}
/** 构建下一周期订阅(每个策略按自己的 interval 算下一周期) */
private suspend fun buildSubscriptionMapForNextPeriod(strategyIds: List<Long>): Pair<List<String>, Map<String, List<MonitorEntry>>> {
val strategies = strategyRepository.findAllById(strategyIds)
val nowSeconds = System.currentTimeMillis() / 1000
val tokenIdSet = mutableSetOf<String>()
val map = mutableMapOf<String, MutableList<MonitorEntry>>()
for (strategy in strategies) {
if (!strategy.enabled || strategy.id == null) {
continue
}
val currentPeriod = (nowSeconds / strategy.intervalSeconds) * strategy.intervalSeconds
val nextPeriod = currentPeriod + strategy.intervalSeconds
val slug = "${strategy.marketSlugPrefix}-$nextPeriod"
val event = fetchEventBySlug(slug).getOrNull()
if (event == null) {
continue
}
marketTitleByStrategyPeriod["${strategy.id!!}-$nextPeriod"] = event.title ?: strategy.marketSlugPrefix
val market = event.markets?.firstOrNull()
if (market == null) {
continue
}
val tokenIds = parseClobTokenIds(market.clobTokenIds)
if (tokenIds.size < 2) {
continue
}
for (i in tokenIds.indices) {
tokenIdSet.add(tokenIds[i])
map.getOrPut(tokenIds[i]) { mutableListOf() }.add(
MonitorEntry(strategy.id!!, strategy, nextPeriod, i, tokenIds[i], true)
)
}
}
return Pair(tokenIdSet.toList(), map)
}
/** 更新策略价格数据为指定周期(开盘价、价差线等),可选是否推送默认 0.5 */
private suspend fun updateStrategyPriceDataForPeriod(
strategyIds: List<Long>,
periodStartUnix: Long,
pushDefault: Boolean
) {
val strategies = strategyRepository.findAllById(strategyIds)
for (strategy in strategies) {
if (strategy.id == null) continue
val openClose = binanceKlineService.getCurrentOpenClose(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)
val openPriceBtc = openClose?.first
var minSpreadLineUp: BigDecimal? = null
var minSpreadLineDown: BigDecimal? = null
when (strategy.spreadMode.name.uppercase()) {
"FIXED" -> {
minSpreadLineUp = strategy.spreadValue?.toSafeBigDecimal()
minSpreadLineDown = strategy.spreadValue?.toSafeBigDecimal()
}
"AUTO" -> {
val autoSpreads = binanceKlineAutoSpreadService.computeAndCache(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)
minSpreadLineUp = autoSpreads?.first
minSpreadLineDown = autoSpreads?.second
}
}
val existingData = strategyPriceData[strategy.id] ?: StrategyPriceData()
val periodChanged = existingData.periodStartUnix != null && existingData.periodStartUnix != periodStartUnix
val newData = StrategyPriceData(
currentPriceUp = if (periodChanged && pushDefault) BigDecimal("0.5") else existingData.currentPriceUp,
currentPriceDown = if (periodChanged && pushDefault) BigDecimal("0.5") else existingData.currentPriceDown,
spreadUp = if (periodChanged && pushDefault) BigDecimal("0.5") else existingData.spreadUp,
spreadDown = if (periodChanged && pushDefault) BigDecimal("0.5") else existingData.spreadDown,
openPriceBtc = openPriceBtc,
minSpreadLineUp = minSpreadLineUp,
minSpreadLineDown = minSpreadLineDown,
periodStartUnix = periodStartUnix
)
strategyPriceData[strategy.id!!] = newData
if (periodChanged && pushDefault) {
val pushData = buildPushData(strategy, newData)
addToHistoryAndPush(strategy.id!!, pushData)
}
}
}
private fun connectCurrentPeriod(tokenIds: List<String>, map: Map<String, List<MonitorEntry>>) {
if (currentPeriodWebSocket != null) return
val request = Request.Builder().url(wsUrl).build()
currentPeriodWebSocket = client.newWebSocket(request, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
closedForNoSubscribers.set(false)
val msg = """{"type":"MARKET","assets_ids":${tokenIds.toJson()}}"""
try {
webSocket.send(msg)
logger.info("加密价差策略监控 WebSocket(当前周期)已连接并订阅: ${tokenIds.size} 个 token")
} catch (e: Exception) {
logger.warn("发送当前周期订阅失败: ${e.message}")
}
}
override fun onMessage(webSocket: WebSocket, text: String) {
handleMessage(webSocket, text)
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
if (this@CryptoTailMonitorService.currentPeriodWebSocket == webSocket) {
this@CryptoTailMonitorService.currentPeriodWebSocket = null
if (!closedForNoSubscribers.get()) scheduleReconnect()
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
if (this@CryptoTailMonitorService.currentPeriodWebSocket == webSocket) {
this@CryptoTailMonitorService.currentPeriodWebSocket = null
scheduleReconnect()
}
}
})
}
private fun connectNextPeriod(tokenIds: List<String>, map: Map<String, List<MonitorEntry>>) {
if (nextPeriodWebSocket != null) {
return
}
val request = Request.Builder().url(wsUrl).build()
nextPeriodWebSocket = client.newWebSocket(request, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
val msg = """{"type":"MARKET","assets_ids":${tokenIds.toJson()}}"""
try {
webSocket.send(msg)
if (tokenIds.isEmpty()) {
logger.info("加密价差策略监控 WebSocket(下一周期)已连接,暂无 token 订阅,等待周期切换后更新")
} else {
logger.info("加密价差策略监控 WebSocket(下一周期)已连接并订阅: ${tokenIds.size} 个 token")
}
} catch (e: Exception) {
logger.warn("发送下一周期订阅失败: ${e.message}")
}
}
override fun onMessage(webSocket: WebSocket, text: String) {
handleMessage(webSocket, text)
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
if (this@CryptoTailMonitorService.nextPeriodWebSocket == webSocket) {
this@CryptoTailMonitorService.nextPeriodWebSocket = null
}
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
if (this@CryptoTailMonitorService.nextPeriodWebSocket == webSocket) {
this@CryptoTailMonitorService.nextPeriodWebSocket = null
}
}
})
}
private fun closeCurrentPeriodWebSocket() {
currentPeriodWebSocket?.close(1000, "period_ended")
currentPeriodWebSocket = null
logger.info("加密价差策略监控 WebSocket(当前周期)已关闭")
}
private fun closeAllWebSockets() {
reconnectJob?.cancel()
reconnectJob = null
closedForNoSubscribers.set(true)
currentPeriodWebSocket?.close(1000, "no_subscribers")
currentPeriodWebSocket = null
nextPeriodWebSocket?.close(1000, "no_subscribers")
nextPeriodWebSocket = null
logger.info("加密价差策略监控 WebSocket 已全部关闭(无订阅者)")
}
private fun handleMessage(webSocket: WebSocket, text: String) {
if (text == "pong" || text.isEmpty()) return
if (closedForNoSubscribers.get()) return
maybeRefreshSubscriptionIfPeriodChanged()
val json = text.fromJson<com.google.gson.JsonObject>() ?: return
val eventType = (json.get("event_type") as? com.google.gson.JsonPrimitive)?.asString ?: return
val map = currentPeriodTokenToStrategy.get()
when (eventType) {
"price_change" -> {
val priceChanges = json.get("price_changes") as? com.google.gson.JsonArray ?: return
for (i in 0 until priceChanges.size()) {
val pc = priceChanges.get(i) as? com.google.gson.JsonObject ?: continue
val assetId = (pc.get("asset_id") as? com.google.gson.JsonPrimitive)?.asString ?: continue
val bestBidStr = (pc.get("best_bid") as? com.google.gson.JsonPrimitive)?.asString
val bestBid = bestBidStr?.toSafeBigDecimal()
if (bestBid != null) onPriceUpdate(assetId, bestBid, map)
}
}
}
}
private fun onPriceUpdate(tokenId: String, bestBid: BigDecimal, map: Map<String, List<MonitorEntry>>) {
if (closedForNoSubscribers.get()) return
val entries = map[tokenId] ?: return
for (entry in entries) {
val strategy = entry.strategy
val priceData = strategyPriceData[strategy.id!!] ?: StrategyPriceData()
// 根据方向更新价格
val newPriceData = if (entry.outcomeIndex == 0) {
// Up 方向
priceData.copy(
currentPriceUp = bestBid,
currentPriceDown = BigDecimal.ONE.subtract(bestBid),
spreadUp = BigDecimal.ONE.subtract(bestBid),
spreadDown = bestBid,
lastUpdateTime = System.currentTimeMillis()
)
} else {
// Down 方向
priceData.copy(
currentPriceDown = bestBid,
currentPriceUp = BigDecimal.ONE.subtract(bestBid),
spreadUp = bestBid,
spreadDown = BigDecimal.ONE.subtract(bestBid),
lastUpdateTime = System.currentTimeMillis()
)
}
strategyPriceData[strategy.id!!] = newPriceData
val now = System.currentTimeMillis()
val last = lastPriceChangePushTime[strategy.id!!] ?: 0L
if (now - last >= priceChangePushThrottleMs) {
lastPriceChangePushTime[strategy.id!!] = now
val pushData = buildPushData(strategy, newPriceData)
addToHistoryAndPush(strategy.id!!, pushData)
}
}
}
private fun addToHistoryAndPush(strategyId: Long, pushData: CryptoTailMonitorPushData) {
addToHistory(strategyId, pushData)
webSocketSubscriptionService.pushMonitorData(strategyId, pushData)
}
private fun addToHistory(strategyId: Long, pushData: CryptoTailMonitorPushData) {
val list = strategyPushHistory.getOrPut(strategyId) {
Collections.synchronizedList(mutableListOf<CryptoTailMonitorPushData>())
}
synchronized(list) {
val lastPeriod = strategyHistoryPeriod[strategyId]
if (lastPeriod != null && lastPeriod != pushData.periodStartUnix) {
list.clear()
}
strategyHistoryPeriod[strategyId] = pushData.periodStartUnix
list.add(pushData)
while (list.size > maxHistorySize) {
list.removeAt(0)
}
}
}
/**
* 构建推送数据
* 最新价价差使用币安 K 线的 BTC 价格open/close
*/
private fun buildPushData(strategy: CryptoTailStrategy, priceData: StrategyPriceData): CryptoTailMonitorPushData {
val nowSeconds = System.currentTimeMillis() / 1000
val periodStartUnix = (nowSeconds / strategy.intervalSeconds) * strategy.intervalSeconds
val periodEndUnix = periodStartUnix + strategy.intervalSeconds
val remainingSeconds = (periodEndUnix - nowSeconds).toInt().coerceAtLeast(0)
val windowStart = periodStartUnix + strategy.windowStartSeconds
val windowEnd = periodStartUnix + strategy.windowEndSeconds
val inTimeWindow = nowSeconds >= windowStart && nowSeconds < windowEnd
// 币安 K 线:open = 周期开盘价,close = 当前最新价(实时更新)
val openClose = binanceKlineService.getCurrentOpenClose(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)
val openPriceBtc = priceData.openPriceBtc ?: openClose?.first
val currentPriceBtc = openClose?.second
// K 线数据回来后更新缓存,供后续使用
if (openPriceBtc != null && priceData.openPriceBtc == null && strategy.id != null) {
strategyPriceData[strategy.id] = priceData.copy(openPriceBtc = openPriceBtc)
}
val spreadBtc = if (openPriceBtc != null && currentPriceBtc != null) {
currentPriceBtc.subtract(openPriceBtc)
} else null
// 判断价格区间(Polymarket 0-1
val currentUp = priceData.currentPriceUp
val currentDown = priceData.currentPriceDown
val inPriceRangeUp = currentUp != null &&
currentUp >= strategy.minPrice && currentUp <= strategy.maxPrice
val inPriceRangeDown = currentDown != null &&
currentDown >= strategy.minPrice && currentDown <= strategy.maxPrice
val marketTitle = marketTitleByStrategyPeriod["${strategy.id!!}-$periodStartUnix"] ?: strategy.marketSlugPrefix
return CryptoTailMonitorPushData(
strategyId = strategy.id!!,
timestamp = System.currentTimeMillis(),
periodStartUnix = periodStartUnix,
marketTitle = marketTitle,
currentPriceUp = priceData.currentPriceUp?.setScale(4, RoundingMode.HALF_UP)?.toPlainString(),
currentPriceDown = priceData.currentPriceDown?.setScale(4, RoundingMode.HALF_UP)?.toPlainString(),
spreadUp = priceData.spreadUp?.setScale(4, RoundingMode.HALF_UP)?.toPlainString(),
spreadDown = priceData.spreadDown?.setScale(4, RoundingMode.HALF_UP)?.toPlainString(),
minSpreadLineUp = priceData.minSpreadLineUp?.setScale(2, RoundingMode.HALF_UP)?.toPlainString(),
minSpreadLineDown = priceData.minSpreadLineDown?.setScale(2, RoundingMode.HALF_UP)?.toPlainString(),
openPriceBtc = openPriceBtc?.setScale(2, RoundingMode.HALF_UP)?.toPlainString(),
currentPriceBtc = currentPriceBtc?.setScale(2, RoundingMode.HALF_UP)?.toPlainString(),
spreadBtc = spreadBtc?.setScale(2, RoundingMode.HALF_UP)?.toPlainString(),
remainingSeconds = remainingSeconds,
inTimeWindow = inTimeWindow,
inPriceRangeUp = inPriceRangeUp,
inPriceRangeDown = inPriceRangeDown,
triggered = priceData.triggered,
triggerDirection = priceData.triggerDirection,
periodEnded = remainingSeconds <= 0
)
}
private fun maybeRefreshSubscriptionIfPeriodChanged() {
val subscribed = currentPeriodTokenToStrategy.get().values.flatten().distinctBy { it.strategyId }
.associate { it.strategyId to it.periodStartUnix }
if (subscribed.isEmpty()) return
val strategies = strategyRepository.findAllById(subscribed.keys)
val nowSeconds = System.currentTimeMillis() / 1000
for (s in strategies) {
if (s.id == null) continue
val currentPeriod = (nowSeconds / s.intervalSeconds) * s.intervalSeconds
val subPeriod = subscribed[s.id] ?: continue
if (currentPeriod != subPeriod) {
scope.launch { refreshSubscription() }
return
}
}
}
private fun scheduleRefreshAtPeriodEnd(newMap: Map<String, List<MonitorEntry>>) {
val entries = newMap.values.flatten()
if (entries.isEmpty()) return
val nextPeriodEndSeconds = entries.minOf { it.periodStartUnix + it.strategy.intervalSeconds }
val delayMs = (nextPeriodEndSeconds * 1000) - System.currentTimeMillis() + 2000
if (delayMs <= 0) return
periodEndCountdownJob = scope.launch {
delay(delayMs)
periodEndCountdownJob = null
refreshSubscription()
}
}
private fun closeWebSocketForNoSubscribers() {
closeAllWebSockets()
}
private fun scheduleReconnect() {
if (reconnectJob?.isActive == true) return
reconnectJob = scope.launch {
delay(reconnectDelayMs)
reconnectJob = null
if (strategySubscribers.isNotEmpty()) {
logger.info("加密价差策略监控 WebSocket 尝试重连")
refreshSubscription()
}
}
}
private fun fetchEventBySlug(slug: String): Result<GammaEventBySlugResponse> {
return try {
val api = retrofitFactory.createGammaApi()
val response = runBlocking { api.getEventBySlug(slug) }
if (response.isSuccessful && response.body() != null) {
Result.success(response.body()!!)
} else {
Result.failure(Exception("${response.code()}"))
}
} catch (e: Exception) {
Result.failure(e)
}
}
private fun parseClobTokenIds(clobTokenIds: String?): List<String> {
if (clobTokenIds.isNullOrBlank()) return emptyList()
return clobTokenIds.fromJson<List<String>>() ?: emptyList()
}
@PreDestroy
fun destroy() {
reconnectJob?.cancel()
periodEndCountdownJob?.cancel()
periodicPushJob?.cancel()
currentPeriodWebSocket?.close(1000, "shutdown")
currentPeriodWebSocket = null
nextPeriodWebSocket?.close(1000, "shutdown")
nextPeriodWebSocket = null
}
}
@@ -19,9 +19,10 @@ import org.springframework.context.ApplicationContextAware
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import jakarta.annotation.PreDestroy
/**
* 尾盘策略订单 TG 通知轮询服务与跟单一致
* 加密价差策略订单 TG 通知轮询服务与跟单一致
* 定时查询下单成功且未发 TG的触发记录通过 CLOB getOrder 获取订单详情后发送 TG 并标记已发
*/
@Service
@@ -36,7 +37,8 @@ class CryptoTailOrderNotificationPollingService(
) : ApplicationContextAware {
private val logger = LoggerFactory.getLogger(CryptoTailOrderNotificationPollingService::class.java)
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val scopeJob = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.IO + scopeJob)
private var applicationContext: ApplicationContext? = null
@@ -55,14 +57,14 @@ class CryptoTailOrderNotificationPollingService(
@Scheduled(fixedDelay = 5000)
fun scheduledSendPendingNotifications() {
if (notificationJob != null && notificationJob!!.isActive) {
logger.debug("上一轮尾盘 TG 通知任务仍在执行,跳过本次")
logger.debug("上一轮加密价差策略 TG 通知任务仍在执行,跳过本次")
return
}
notificationJob = scope.launch {
try {
getSelf().sendPendingNotifications()
} catch (e: Exception) {
logger.error("尾盘 TG 通知轮询异常: ${e.message}", e)
logger.error("加密价差策略 TG 通知轮询异常: ${e.message}", e)
} finally {
notificationJob = null
}
@@ -86,7 +88,7 @@ class CryptoTailOrderNotificationPollingService(
triggerRepository.save(trigger)
}
} catch (e: Exception) {
logger.warn("尾盘 TG 通知单条失败: triggerId=${trigger.id}, orderId=${trigger.orderId}, ${e.message}", e)
logger.warn("加密价差策略 TG 通知单条失败: triggerId=${trigger.id}, orderId=${trigger.orderId}, ${e.message}", e)
}
}
}
@@ -100,16 +102,16 @@ class CryptoTailOrderNotificationPollingService(
return false
}
val apiSecret = try {
cryptoUtils.decrypt(account.apiSecret) ?: return false
cryptoUtils.decrypt(account.apiSecret)
} catch (e: Exception) {
logger.warn("解密 API Secret 失败: accountId=${account.id}", e)
return false
}
val apiPassphrase = try {
cryptoUtils.decrypt(account.apiPassphrase) ?: ""
cryptoUtils.decrypt(account.apiPassphrase)
} catch (e: Exception) { "" }
val clobApi = retrofitFactory.createClobApi(
account.apiKey!!,
account.apiKey,
apiSecret,
apiPassphrase,
account.walletAddress
@@ -140,7 +142,14 @@ class CryptoTailOrderNotificationPollingService(
walletAddress = account.walletAddress,
orderTime = orderTimeMs
)
logger.info("尾盘订单 TG 通知已发送: orderId=$orderId, strategyId=${strategy.id}, triggerId=${trigger.id}")
logger.info("加密价差策略订单 TG 通知已发送: orderId=$orderId, strategyId=${strategy.id}, triggerId=${trigger.id}")
return true
}
@PreDestroy
fun destroy() {
notificationJob?.cancel()
notificationJob = null
scopeJob.cancel()
}
}
@@ -7,6 +7,7 @@ import com.wrbug.polymarketbot.enums.SpreadMode
import com.wrbug.polymarketbot.event.CryptoTailStrategyChangedEvent
import com.wrbug.polymarketbot.repository.CryptoTailStrategyRepository
import com.wrbug.polymarketbot.service.binance.BinanceKlineAutoSpreadService
import com.wrbug.polymarketbot.service.binance.BinanceKlineService
import com.wrbug.polymarketbot.util.RetrofitFactory
import com.wrbug.polymarketbot.util.createClient
import com.wrbug.polymarketbot.util.fromJson
@@ -28,24 +29,27 @@ import org.slf4j.LoggerFactory
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Service
import jakarta.annotation.PostConstruct
import jakarta.annotation.PreDestroy
import java.math.BigDecimal
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/**
* 尾盘策略订单簿 WebSocket 监听订阅 CLOB Market 频道收到订单簿/价格变更时若满足条件立即触发下单
* 加密价差策略订单簿 WebSocket 监听订阅 CLOB Market 频道收到订单簿/价格变更时若满足条件立即触发下单
*/
@Service
class CryptoTailOrderbookWsService(
private val strategyRepository: CryptoTailStrategyRepository,
private val executionService: CryptoTailStrategyExecutionService,
private val retrofitFactory: RetrofitFactory,
private val binanceKlineAutoSpreadService: BinanceKlineAutoSpreadService
private val binanceKlineAutoSpreadService: BinanceKlineAutoSpreadService,
private val binanceKlineService: BinanceKlineService
) {
private val logger = LoggerFactory.getLogger(CryptoTailOrderbookWsService::class.java)
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val scopeJob = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.Default + scopeJob)
/** tokenId -> list of (strategy, periodStartUnix, marketTitle, tokenIds, outcomeIndex) */
private val tokenToEntries = AtomicReference<Map<String, List<WsBookEntry>>>(emptyMap())
@@ -66,6 +70,12 @@ class CryptoTailOrderbookWsService(
/** 保护 connect() 的互斥锁,避免多线程并发创建连接 */
private val connectLock = Any()
/** 保护 refreshAndSubscribe() 的互斥锁,避免多线程并发刷新订阅 */
private val refreshLock = Any()
/** 标记是否正在刷新订阅,避免重复调用 */
private val isRefreshing = AtomicBoolean(false)
data class WsBookEntry(
val strategy: CryptoTailStrategy,
val periodStartUnix: Long,
@@ -79,6 +89,26 @@ class CryptoTailOrderbookWsService(
if (strategyRepository.findAllByEnabledTrue().isNotEmpty()) connect()
}
@PreDestroy
fun destroy() {
periodEndCountdownJob?.cancel()
periodEndCountdownJob = null
reconnectJob?.cancel()
reconnectJob = null
synchronized(precomputeJobs) {
precomputeJobs.forEach { it.cancel() }
precomputeJobs.clear()
}
closedForNoStrategies.set(true)
try {
webSocket?.close(1000, "shutdown")
} catch (e: Exception) {
logger.debug("关闭加密价差策略 WebSocket 时异常: ${e.message}")
}
webSocket = null
scopeJob.cancel()
}
private fun connect() {
synchronized(connectLock) {
if (webSocket != null) return
@@ -86,7 +116,7 @@ class CryptoTailOrderbookWsService(
val request = Request.Builder().url(wsUrl).build()
webSocket = client.newWebSocket(request, object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
logger.info("尾盘策略订单簿 WebSocket 已连接")
logger.info("加密价差策略订单簿 WebSocket 已连接")
refreshAndSubscribe(fromConnect = true)
}
@@ -100,13 +130,13 @@ class CryptoTailOrderbookWsService(
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
logger.warn("尾盘策略订单簿 WebSocket 异常: ${t.message}")
logger.warn("加密价差策略订单簿 WebSocket 异常: ${t.message}")
this@CryptoTailOrderbookWsService.webSocket = null
scheduleReconnect()
}
})
} catch (e: Exception) {
logger.error("尾盘策略订单簿 WebSocket 连接失败: ${e.message}", e)
logger.error("加密价差策略订单簿 WebSocket 连接失败: ${e.message}", e)
scheduleReconnect()
}
}
@@ -120,7 +150,7 @@ class CryptoTailOrderbookWsService(
delay(reconnectDelayMs)
reconnectJob = null
if (strategyRepository.findAllByEnabledTrue().isEmpty()) return@launch
logger.info("尾盘策略订单簿 WebSocket 尝试重连")
logger.info("加密价差策略订单簿 WebSocket 尝试重连")
connect()
}
}
@@ -171,16 +201,14 @@ class CryptoTailOrderbookWsService(
if (nowSeconds < windowStart || nowSeconds >= windowEnd) continue
scope.launch {
try {
runBlocking {
executionService.tryTriggerWithPriceFromWs(
strategy = e.strategy,
periodStartUnix = e.periodStartUnix,
marketTitle = e.marketTitle,
tokenIds = e.tokenIds,
outcomeIndex = e.outcomeIndex,
bestBid = bestBid
)
}
executionService.tryTriggerWithPriceFromWs(
strategy = e.strategy,
periodStartUnix = e.periodStartUnix,
marketTitle = e.marketTitle,
tokenIds = e.tokenIds,
outcomeIndex = e.outcomeIndex,
bestBid = bestBid
)
} catch (ex: Exception) {
logger.error("WS 触发下单异常: strategyId=${e.strategy.id}, ${ex.message}", ex)
}
@@ -213,42 +241,56 @@ class CryptoTailOrderbookWsService(
}
private fun refreshAndSubscribe(fromConnect: Boolean = false) {
periodEndCountdownJob?.cancel()
periodEndCountdownJob = null
val oldTokenIds = tokenToEntries.get().keys.toSet()
val (tokenIds, newMap) = buildSubscriptionMap()
tokenToEntries.set(newMap)
if (tokenIds.isEmpty()) {
closeWebSocketForNoStrategies()
return
}
if (!fromConnect) {
if (webSocket == null) {
connect()
synchronized(refreshLock) {
// 如果正在刷新,直接返回,避免重复调用
if (isRefreshing.get()) {
logger.debug("加密价差策略订阅刷新已在进行中,跳过本次调用")
return
}
if (oldTokenIds == tokenIds.toSet()) {
scheduleRefreshAtPeriodEnd(newMap)
precomputeAutoSpreadForCurrentPeriods(newMap)
return
}
closeWebSocketAndReconnect()
return
isRefreshing.set(true)
}
val marketSlugs = newMap.values.asSequence().flatten()
.distinctBy { "${it.strategy.marketSlugPrefix}-${it.periodStartUnix}" }
.map { "${it.strategy.marketSlugPrefix}-${it.periodStartUnix}" }
.toList()
val msg = """{"type":"MARKET","assets_ids":${tokenIds.toJson()}}"""
try {
webSocket?.send(msg)
logger.info("尾盘策略订单簿订阅: ${tokenIds.size} 个 token, 市场: $marketSlugs")
} catch (e: Exception) {
logger.warn("发送订阅失败: ${e.message}")
return
val strategies = strategyRepository.findAllByEnabledTrue()
binanceKlineService.updateSubscriptions(strategies.map { it.marketSlugPrefix }.toSet())
periodEndCountdownJob?.cancel()
periodEndCountdownJob = null
val oldTokenIds = tokenToEntries.get().keys.toSet()
val (tokenIds, newMap) = buildSubscriptionMap()
tokenToEntries.set(newMap)
if (tokenIds.isEmpty()) {
closeWebSocketForNoStrategies()
return
}
if (!fromConnect) {
if (webSocket == null) {
connect()
return
}
if (oldTokenIds == tokenIds.toSet()) {
scheduleRefreshAtPeriodEnd(newMap)
precomputeAutoSpreadForCurrentPeriods(newMap)
return
}
closeWebSocketAndReconnect()
return
}
val marketSlugs = newMap.values.asSequence().flatten()
.distinctBy { "${it.strategy.marketSlugPrefix}-${it.periodStartUnix}" }
.map { "${it.strategy.marketSlugPrefix}-${it.periodStartUnix}" }
.toList()
val msg = """{"type":"MARKET","assets_ids":${tokenIds.toJson()}}"""
try {
webSocket?.send(msg)
logger.info("加密价差策略订单簿订阅: ${tokenIds.size} 个 token, 市场: $marketSlugs")
} catch (e: Exception) {
logger.warn("发送订阅失败: ${e.message}")
return
}
scheduleRefreshAtPeriodEnd(newMap)
precomputeAutoSpreadForCurrentPeriods(newMap)
} finally {
isRefreshing.set(false)
}
scheduleRefreshAtPeriodEnd(newMap)
precomputeAutoSpreadForCurrentPeriods(newMap)
}
/**
@@ -261,37 +303,45 @@ class CryptoTailOrderbookWsService(
try {
ws.close(1000, "subscription_change")
} catch (e: Exception) {
logger.debug("关闭尾盘策略 WebSocket 时异常: ${e.message}")
logger.debug("关闭加密价差策略 WebSocket 时异常: ${e.message}")
}
logger.info("尾盘策略订单簿 WebSocket 已关闭(订阅更新,将重连)")
logger.info("加密价差策略订单簿 WebSocket 已关闭(订阅更新,将重连)")
}
}
/** 跟踪预计算价差的协程 Job,用于在关闭时取消 */
private val precomputeJobs = mutableSetOf<Job>()
/**
* AUTO 模式在周期开始刷新订阅时预拉历史 30 K 线并计算该周期价差触发时直接用缓存
*/
private fun precomputeAutoSpreadForCurrentPeriods(newMap: Map<String, List<WsBookEntry>>) {
val autoPeriods = newMap.values.asSequence().flatten()
.filter { it.strategy.spreadMode == SpreadMode.AUTO }
.distinctBy { "${it.strategy.intervalSeconds}-${it.periodStartUnix}" }
.map { it.strategy.intervalSeconds to it.periodStartUnix }
.distinctBy { "${it.strategy.marketSlugPrefix}-${it.strategy.intervalSeconds}-${it.periodStartUnix}" }
.map { Triple(it.strategy.marketSlugPrefix, it.strategy.intervalSeconds, it.periodStartUnix) }
.toList()
if (autoPeriods.isEmpty()) return
scope.launch {
for ((intervalSeconds, periodStartUnix) in autoPeriods) {
val job = scope.launch {
for ((marketPrefix, intervalSeconds, periodStartUnix) in autoPeriods) {
try {
val pair = binanceKlineAutoSpreadService.computeAndCache(intervalSeconds, periodStartUnix)
val pair = binanceKlineAutoSpreadService.computeAndCache(marketPrefix, intervalSeconds, periodStartUnix)
if (pair != null) {
logger.info(
"周期开始初始价差: interval=${intervalSeconds}s periodStartUnix=$periodStartUnix " +
"周期开始初始价差: market=$marketPrefix interval=${intervalSeconds}s periodStartUnix=$periodStartUnix " +
"baseSpreadUp=${pair.first.toPlainString()} baseSpreadDown=${pair.second.toPlainString()}"
)
}
} catch (e: Exception) {
logger.warn("周期开始预计算 AUTO 价差失败: interval=$intervalSeconds periodStartUnix=$periodStartUnix ${e.message}")
logger.warn("周期开始预计算 AUTO 价差失败: market=$marketPrefix interval=$intervalSeconds periodStartUnix=$periodStartUnix ${e.message}")
}
}
}
synchronized(precomputeJobs) {
precomputeJobs.add(job)
// 清理已完成的 Job,避免集合无限增长
precomputeJobs.removeIf { !it.isActive }
}
}
/**
@@ -307,9 +357,9 @@ class CryptoTailOrderbookWsService(
try {
ws.close(1000, "no_enabled_strategies")
} catch (e: Exception) {
logger.debug("关闭尾盘策略 WebSocket 时异常: ${e.message}")
logger.debug("关闭加密价差策略 WebSocket 时异常: ${e.message}")
}
logger.info("尾盘策略订单簿 WebSocket 已关闭(无启用策略)")
logger.info("加密价差策略订单簿 WebSocket 已关闭(无启用策略)")
}
}
@@ -327,7 +377,7 @@ class CryptoTailOrderbookWsService(
periodEndCountdownJob = null
refreshAndSubscribe()
}
logger.debug("尾盘策略订单簿订阅倒计时: ${delayMs / 1000}s 后刷新")
logger.debug("加密价差策略订单簿订阅倒计时: ${delayMs / 1000}s 后刷新")
}
private fun buildSubscriptionMap(): Pair<List<String>, Map<String, List<WsBookEntry>>> {
@@ -341,23 +391,23 @@ class CryptoTailOrderbookWsService(
val periodStartUnix = (nowSeconds / interval) * interval
val windowEnd = periodStartUnix + strategy.windowEndSeconds
if (nowSeconds >= windowEnd) {
logger.debug("尾盘策略跳过(已过时间窗口): strategyId=${strategy.id}, slug=${strategy.marketSlugPrefix}, windowEnd=$windowEnd")
logger.debug("加密价差策略跳过(已过时间窗口): strategyId=${strategy.id}, slug=${strategy.marketSlugPrefix}, windowEnd=$windowEnd")
continue
}
val slug = "${strategy.marketSlugPrefix}-$periodStartUnix"
val event = fetchEventBySlugWithRetry(slug).getOrNull()
val event = runBlocking { fetchEventBySlugWithRetry(slug).getOrNull() }
if (event == null) {
logger.warn("尾盘策略跳过(拉取事件失败): strategyId=${strategy.id}, slug=$slug,请确认 Gamma 是否存在该 slug 或稍后重试")
logger.warn("加密价差策略跳过(拉取事件失败): strategyId=${strategy.id}, slug=$slug,请确认 Gamma 是否存在该 slug 或稍后重试")
continue
}
val market = event.markets?.firstOrNull()
if (market == null) {
logger.warn("尾盘策略跳过(事件无市场): strategyId=${strategy.id}, slug=$slug")
logger.warn("加密价差策略跳过(事件无市场): strategyId=${strategy.id}, slug=$slug")
continue
}
val tokenIds = parseClobTokenIds(market.clobTokenIds)
if (tokenIds.size < 2) {
logger.warn("尾盘策略跳过(token 数量不足): strategyId=${strategy.id}, slug=$slug, tokenCount=${tokenIds.size}")
logger.warn("加密价差策略跳过(token 数量不足): strategyId=${strategy.id}, slug=$slug, tokenCount=${tokenIds.size}")
continue
}
tokenIdSet.addAll(tokenIds)
@@ -372,21 +422,21 @@ class CryptoTailOrderbookWsService(
}
/** 拉取事件,失败时重试最多 2 次(间隔 1s),避免瞬时失败导致多策略只订阅到其中一个 */
private fun fetchEventBySlugWithRetry(slug: String, maxAttempts: Int = 3): Result<GammaEventBySlugResponse> {
private suspend fun fetchEventBySlugWithRetry(slug: String, maxAttempts: Int = 3): Result<GammaEventBySlugResponse> {
var lastFailure: Exception? = null
repeat(maxAttempts) { attempt ->
val result = fetchEventBySlug(slug)
if (result.isSuccess) return result
lastFailure = result.exceptionOrNull() as? Exception
if (attempt < maxAttempts - 1) runBlocking { delay(1000L) }
if (attempt < maxAttempts - 1) delay(1000L)
}
return Result.failure(lastFailure ?: Exception("fetchEventBySlug failed"))
}
private fun fetchEventBySlug(slug: String): Result<GammaEventBySlugResponse> {
private suspend fun fetchEventBySlug(slug: String): Result<GammaEventBySlugResponse> {
return try {
val api = retrofitFactory.createGammaApi()
val response = runBlocking { api.getEventBySlug(slug) }
val response = api.getEventBySlug(slug)
if (response.isSuccessful && response.body() != null) {
Result.success(response.body()!!)
} else {
@@ -22,11 +22,12 @@ import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import jakarta.annotation.PreDestroy
import java.math.BigDecimal
import java.math.RoundingMode
/**
* 尾盘策略结算轮询服务
* 加密价差策略结算轮询服务
* 定时扫描状态成功但未结算的触发记录通过 Gamma 获取 conditionId链上查询结算结果计算收益并回写
* 实际成交价与成交量使用 Data API activity 接口获取getUserActivity CLOB getOrder 更准确失败时回退为触发时的 amountUsdc + 固定价 0.99
*/
@@ -44,7 +45,8 @@ class CryptoTailSettlementService(
private val triggerFixedPrice = BigDecimal("0.99")
private val pnlScale = 8
private val settlementScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val settlementScopeJob = SupervisorJob()
private val settlementScope = CoroutineScope(Dispatchers.IO + settlementScopeJob)
/** 跟踪上一轮结算任务的 Job,防止并发执行(与 OrderStatusUpdateService 一致) */
@Volatile
@@ -58,14 +60,14 @@ class CryptoTailSettlementService(
fun scheduledPollAndSettle() {
val previousJob = settlementJob
if (previousJob != null && previousJob.isActive) {
logger.debug("上一轮尾盘结算任务仍在执行,跳过本次调度")
logger.debug("上一轮加密价差策略结算任务仍在执行,跳过本次调度")
return
}
settlementJob = settlementScope.launch {
try {
doPollAndSettle()
} catch (e: Exception) {
logger.error("尾盘策略结算定时任务异常: ${e.message}", e)
logger.error("加密价差策略结算定时任务异常: ${e.message}", e)
} finally {
settlementJob = null
}
@@ -89,11 +91,11 @@ class CryptoTailSettlementService(
try {
if (settleOne(trigger)) settledCount++
} catch (e: Exception) {
logger.warn("尾盘结算单条失败: triggerId=${trigger.id}, ${e.message}", e)
logger.warn("加密价差策略结算单条失败: triggerId=${trigger.id}, ${e.message}", e)
}
}
if (settledCount > 0) {
logger.info("尾盘策略结算轮询完成: 处理=${pending.size}, 新结算=$settledCount")
logger.info("加密价差策略结算轮询完成: 处理=${pending.size}, 新结算=$settledCount")
}
return settledCount
}
@@ -152,7 +154,7 @@ class CryptoTailSettlementService(
settledAt = now
)
triggerRepository.save(updated)
logger.debug("尾盘结算已更新: triggerId=${trigger.id}, winnerOutcomeIndex=$winnerIndex, won=$won, pnl=$pnl")
logger.debug("加密价差策略结算已更新: triggerId=${trigger.id}, winnerOutcomeIndex=$winnerIndex, won=$won, pnl=$pnl")
return true
}
@@ -199,7 +201,7 @@ class CryptoTailSettlementService(
conditionId: String
): ActivityFill? {
val account = accountRepository.findById(strategy.accountId).orElse(null) ?: run {
logger.warn("尾盘结算未拉取 activity: 账户不存在, triggerId=${trigger.id}, accountId=${strategy.accountId}")
logger.warn("加密价差策略结算未拉取 activity: 账户不存在, triggerId=${trigger.id}, accountId=${strategy.accountId}")
return null
}
val user = account.proxyAddress
@@ -218,7 +220,7 @@ class CryptoTailSettlementService(
sortDirection = "DESC"
)
if (!response.isSuccessful || response.body() == null) {
logger.warn("尾盘结算拉取 activity 失败: triggerId=${trigger.id}, code=${response.code()}")
logger.warn("加密价差策略结算拉取 activity 失败: triggerId=${trigger.id}, code=${response.code()}")
return null
}
val activities = response.body()!!
@@ -226,13 +228,13 @@ class CryptoTailSettlementService(
val match = activities.firstOrNull { a ->
a.type == "TRADE" &&
a.conditionId == conditionId &&
a.outcomeIndex != null && a.outcomeIndex!! in 0..1 &&
a.outcomeIndex != null && a.outcomeIndex in 0..1 &&
a.outcomeIndex == trigger.outcomeIndex &&
a.side?.uppercase() == "BUY" &&
a.price != null && a.price!! > 0 &&
a.size != null && a.size!! > 0
a.price != null && a.price > 0 &&
a.size != null && a.size > 0
} ?: run {
logger.debug("尾盘结算 activity 无匹配成交: triggerId=${trigger.id}, conditionId=$conditionId, outcomeIndex=${trigger.outcomeIndex}, 条数=${activities.size}")
logger.debug("加密价差策略结算 activity 无匹配成交: triggerId=${trigger.id}, conditionId=$conditionId, outcomeIndex=${trigger.outcomeIndex}, 条数=${activities.size}")
return null
}
val price = match.price!!.toSafeBigDecimal()
@@ -241,11 +243,11 @@ class CryptoTailSettlementService(
if (price.gt(BigDecimal.ZERO) && size.gt(BigDecimal.ZERO)) {
ActivityFill(price = price, size = size, usdcSize = usdcSize)
} else {
logger.debug("尾盘结算 activity 成交数据无效: triggerId=${trigger.id}, price=$price, size=$size")
logger.debug("加密价差策略结算 activity 成交数据无效: triggerId=${trigger.id}, price=$price, size=$size")
null
}
} catch (e: Exception) {
logger.warn("尾盘结算拉取 activity 异常,触发价/投入金额不会更新: triggerId=${trigger.id}, error=${e.message}")
logger.warn("加密价差策略结算拉取 activity 异常,触发价/投入金额不会更新: triggerId=${trigger.id}, error=${e.message}")
null
}
}
@@ -273,4 +275,11 @@ class CryptoTailSettlementService(
amountUsdc.negate()
}
}
@PreDestroy
fun destroy() {
settlementJob?.cancel()
settlementJob = null
settlementScopeJob.cancel()
}
}
@@ -3,6 +3,9 @@ package com.wrbug.polymarketbot.service.cryptotail
import com.wrbug.polymarketbot.api.GammaEventBySlugResponse
import com.wrbug.polymarketbot.api.NewOrderRequest
import com.wrbug.polymarketbot.api.PolymarketClobApi
import com.wrbug.polymarketbot.dto.CryptoTailManualOrderRequest
import com.wrbug.polymarketbot.dto.CryptoTailManualOrderResponse
import com.wrbug.polymarketbot.dto.ManualOrderDetails
import com.wrbug.polymarketbot.entity.Account
import com.wrbug.polymarketbot.entity.CryptoTailStrategy
import com.wrbug.polymarketbot.entity.CryptoTailStrategyTrigger
@@ -28,12 +31,13 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import jakarta.annotation.PreDestroy
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.concurrent.ConcurrentHashMap
import java.util.regex.Pattern
/** 尾盘策略固定下单价格(最高价 0.99),不再在触发时拉取最优价 */
/** 加密价差策略固定下单价格(最高价 0.99),不再在触发时拉取最优价 */
private const val TRIGGER_FIXED_PRICE = "0.99"
/** 最大价差模式(MAX)时,买入价格调整系数(加在触发价格上) */
@@ -61,7 +65,7 @@ private data class PeriodContext(
)
/**
* 尾盘策略执行服务按周期与时间窗口检查价格并下单每周期最多触发一次
* 加密价差策略执行服务按周期与时间窗口检查价格并下单每周期最多触发一次
* 周期开始预置账户解密费率签名类型CLOB 客户端触发时按 outcomeIndex 计算 size 并签名提交
*/
@Service
@@ -83,10 +87,25 @@ class CryptoTailStrategyExecutionService(
/** 按 (strategyId, periodStartUnix) 加锁,避免同一周期被调度器与 WebSocket 等多路并发重复下单 */
private val triggerMutexMap = ConcurrentHashMap<String, Mutex>()
/** 过期锁 key 保留时间(秒),超过则清理,防止 map 无界增长 */
private val triggerMutexExpireSeconds = 3600L
private fun triggerLockKey(strategyId: Long, periodStartUnix: Long): String = "$strategyId-$periodStartUnix"
private fun getTriggerMutex(strategyId: Long, periodStartUnix: Long): Mutex =
triggerMutexMap.getOrPut(triggerLockKey(strategyId, periodStartUnix)) { Mutex() }
private fun getTriggerMutex(strategyId: Long, periodStartUnix: Long): Mutex {
cleanExpiredTriggerMutexKeys()
return triggerMutexMap.getOrPut(triggerLockKey(strategyId, periodStartUnix)) { Mutex() }
}
/** 清理已过期的 (strategyId, periodStartUnix) 锁,避免内存泄漏 */
private fun cleanExpiredTriggerMutexKeys() {
val nowSeconds = System.currentTimeMillis() / 1000
val expireThreshold = nowSeconds - triggerMutexExpireSeconds
val keysToRemove = triggerMutexMap.keys.filter { key ->
key.substringAfterLast('-').toLongOrNull()?.let { it < expireThreshold } ?: false
}
keysToRemove.forEach { triggerMutexMap.remove(it) }
}
/** 周期预置上下文缓存:(strategyId-periodStartUnix) -> PeriodContext,过期周期在读取时剔除 */
private val periodContextCache = ConcurrentHashMap<String, PeriodContext>()
@@ -115,17 +134,21 @@ class CryptoTailStrategyExecutionService(
val decryptedKey = try {
cryptoUtils.decrypt(account.privateKey) ?: return null
} catch (e: Exception) {
logger.warn("尾盘策略周期上下文解密私钥失败: accountId=${account.id}", e)
logger.warn("加密价差策略周期上下文解密私钥失败: accountId=${account.id}", e)
return null
}
val apiSecret = try {
account.apiSecret?.let { cryptoUtils.decrypt(it) } ?: ""
} catch (e: Exception) { "" }
account.apiSecret.let { cryptoUtils.decrypt(it) }
} catch (e: Exception) {
""
}
val apiPassphrase = try {
account.apiPassphrase?.let { cryptoUtils.decrypt(it) } ?: ""
} catch (e: Exception) { "" }
account.apiPassphrase.let { cryptoUtils.decrypt(it) }
} catch (e: Exception) {
""
}
val clobApi = retrofitFactory.createClobApi(account.apiKey!!, apiSecret, apiPassphrase, account.walletAddress)
val clobApi = retrofitFactory.createClobApi(account.apiKey, apiSecret, apiPassphrase, account.walletAddress)
val feeRateByTokenId = tokenIds.associate { tokenId ->
tokenId to (clobService.getFeeRate(tokenId).getOrNull()?.toString() ?: "0")
}
@@ -165,11 +188,20 @@ class CryptoTailStrategyExecutionService(
val ctx = periodContextCache[key] ?: return null
if (periodStartUnix + strategy.intervalSeconds <= nowSeconds) {
periodContextCache.remove(key)
cleanExpiredPeriodContextCache(nowSeconds)
return null
}
return ctx
}
/** 清理已过期的周期上下文缓存,避免内存泄漏 */
private fun cleanExpiredPeriodContextCache(nowSeconds: Long) {
val keysToRemove = periodContextCache.entries
.filter { (_, ctx) -> ctx.periodStartUnix + ctx.strategy.intervalSeconds <= nowSeconds }
.map { it.key }
keysToRemove.forEach { periodContextCache.remove(it) }
}
/**
* 由订单簿 WebSocket 触发当收到某 token bestBid 且满足区间时调用若本周期未触发则下单
*/
@@ -186,20 +218,28 @@ class CryptoTailStrategyExecutionService(
val mutex = getTriggerMutex(strategy.id!!, periodStartUnix)
mutex.withLock {
if (triggerRepository.findByStrategyIdAndPeriodStartUnix(strategy.id!!, periodStartUnix) != null) return@withLock
if (triggerRepository.findByStrategyIdAndPeriodStartUnix(
strategy.id!!,
periodStartUnix
) != null
) return@withLock
val logKey = triggerLockKey(strategy.id!!, periodStartUnix)
if (conditionLoggedCache.getIfPresent(logKey) == null) {
conditionLoggedCache.put(logKey, periodStartUnix + strategy.intervalSeconds)
val oc = binanceKlineService.getCurrentOpenClose(strategy.intervalSeconds, periodStartUnix)
val oc = binanceKlineService.getCurrentOpenClose(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)
val openPrice = oc?.first?.toPlainString() ?: "-"
val closePrice = oc?.second?.toPlainString() ?: "-"
val strategyName = strategy.name?.takeIf { it.isNotBlank() } ?: "尾盘策略-${strategy.marketSlugPrefix}"
val strategyName = strategy.name?.takeIf { it.isNotBlank() } ?: "加密价差策略-${strategy.marketSlugPrefix}"
val direction = if (outcomeIndex == 0) "Up" else "Down"
val modeStr = if (strategy.spreadDirection == SpreadDirection.MAX) "最大价差" else "最小价差"
logger.info(
"尾盘策略首次满足条件: strategyName=$strategyName, strategyId=${strategy.id}, " +
"openPrice=$openPrice, closePrice=$closePrice, marketPrice=${bestBid.toPlainString()}, " +
"direction=$direction, outcomeIndex=$outcomeIndex, spreadMode=$modeStr"
"加密价差策略首次满足条件: strategyName=$strategyName, strategyId=${strategy.id}, " +
"openPrice=$openPrice, closePrice=$closePrice, marketPrice=${bestBid.toPlainString()}, " +
"direction=$direction, outcomeIndex=$outcomeIndex, spreadMode=$modeStr"
)
}
if (!passSpreadCheck(strategy, periodStartUnix, outcomeIndex)) return@withLock
@@ -210,23 +250,29 @@ class CryptoTailStrategyExecutionService(
private fun passSpreadCheck(strategy: CryptoTailStrategy, periodStartUnix: Long, outcomeIndex: Int): Boolean {
if (strategy.spreadMode == SpreadMode.NONE) return true
val oc = binanceKlineService.getCurrentOpenClose(strategy.intervalSeconds, periodStartUnix)
val oc = binanceKlineService.getCurrentOpenClose(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)
?: return false
val (openP, closeP) = oc
val spreadAbs = closeP.subtract(openP).abs()
// 获取有效价差
val effectiveSpread = when (strategy.spreadMode) {
SpreadMode.FIXED -> {
strategy.spreadValue?.takeIf { it > BigDecimal.ZERO } ?: return true
}
SpreadMode.AUTO -> {
val result = computeAutoEffectiveSpread(strategy, periodStartUnix, outcomeIndex) ?: return true
result.effectiveSpread.takeIf { it > BigDecimal.ZERO } ?: return true
}
SpreadMode.NONE -> return true
}
// 根据价差方向判断
return if (strategy.spreadDirection == SpreadDirection.MAX) {
// 最大价差模式:价差 <= 配置值时触发
@@ -246,9 +292,22 @@ class CryptoTailStrategyExecutionService(
val effectiveSpread: BigDecimal
)
private fun computeAutoEffectiveSpread(strategy: CryptoTailStrategy, periodStartUnix: Long, outcomeIndex: Int): AutoSpreadResult? {
val baseSpread = binanceKlineAutoSpreadService.getAutoMinSpreadBase(strategy.intervalSeconds, periodStartUnix, outcomeIndex)
?: binanceKlineAutoSpreadService.computeAndCache(strategy.intervalSeconds, periodStartUnix)?.let { if (outcomeIndex == 0) it.first else it.second }
private fun computeAutoEffectiveSpread(
strategy: CryptoTailStrategy,
periodStartUnix: Long,
outcomeIndex: Int
): AutoSpreadResult? {
val baseSpread = binanceKlineAutoSpreadService.getAutoMinSpreadBase(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix,
outcomeIndex
)
?: binanceKlineAutoSpreadService.computeAndCache(
strategy.marketSlugPrefix,
strategy.intervalSeconds,
periodStartUnix
)?.let { if (outcomeIndex == 0) it.first else it.second }
?: return null
if (baseSpread <= BigDecimal.ZERO) return null
val windowStartMs = (periodStartUnix + strategy.windowStartSeconds) * 1000L
@@ -281,18 +340,40 @@ class CryptoTailStrategyExecutionService(
val amountUsdc = when (strategy.amountMode.uppercase()) {
"RATIO" -> {
val balanceResult = accountService.getAccountBalance(ctx.account.id)
val availableBalance = balanceResult.getOrNull()?.availableBalance?.toSafeBigDecimal() ?: BigDecimal.ZERO
val availableBalance =
balanceResult.getOrNull()?.availableBalance?.toSafeBigDecimal() ?: BigDecimal.ZERO
availableBalance.multiply(strategy.amountValue).divide(BigDecimal("100"), 18, RoundingMode.DOWN)
}
else -> strategy.amountValue
}
if (amountUsdc < BigDecimal("1")) {
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, null, "fail", "投入金额不足")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
null,
"fail",
"投入金额不足"
)
return
}
val tokenId = tokenIds.getOrNull(outcomeIndex) ?: run {
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, null, "fail", "tokenIds 越界")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
null,
"fail",
"tokenIds 越界"
)
return
}
@@ -325,7 +406,17 @@ class CryptoTailStrategyExecutionService(
orderType = "FAK",
deferExec = false
)
submitOrderAndSaveRecord(ctx.clobApi, strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, orderRequest)
submitOrderAndSaveRecord(
ctx.clobApi,
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
orderRequest,
triggerType = "AUTO"
)
return
}
@@ -340,7 +431,8 @@ class CryptoTailStrategyExecutionService(
outcomeIndex: Int,
triggerPrice: BigDecimal,
amountUsdc: BigDecimal,
orderRequest: NewOrderRequest
orderRequest: NewOrderRequest,
triggerType: String = "AUTO"
) {
var failReason: String? = null
try {
@@ -348,8 +440,19 @@ class CryptoTailStrategyExecutionService(
if (response.isSuccessful && response.body() != null) {
val body = response.body()!!
if (body.success && body.orderId != null) {
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, body.orderId, "success", null)
logger.info("尾盘策略下单成功: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix, outcomeIndex=$outcomeIndex, orderId=${body.orderId}")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
body.orderId,
"success",
null,
triggerType = triggerType
)
logger.info("加密价差策略下单成功: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix, outcomeIndex=$outcomeIndex, orderId=${body.orderId}, triggerType=$triggerType")
return
}
failReason = body.errorMsg ?: "unknown"
@@ -359,10 +462,21 @@ class CryptoTailStrategyExecutionService(
}
} catch (e: Exception) {
failReason = e.message ?: e.toString()
logger.error("尾盘策略下单异常: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix", e)
logger.error("加密价差策略下单异常: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix", e)
}
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, null, "fail", failReason)
logger.error("尾盘策略下单失败: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix, reason=$failReason")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
null,
"fail",
failReason,
triggerType = triggerType
)
logger.error("加密价差策略下单失败: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix, reason=$failReason")
}
/** 无预置上下文时的完整流程:固定价格 0.99,账户/解密/费率/签名在触发时执行 */
@@ -376,12 +490,32 @@ class CryptoTailStrategyExecutionService(
) {
val account = accountRepository.findById(strategy.accountId).orElse(null) ?: run {
logger.warn("账户不存在: accountId=${strategy.accountId}")
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, BigDecimal.ZERO, null, "fail", "账户不存在")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
BigDecimal.ZERO,
null,
"fail",
"账户不存在"
)
return
}
if (account.apiKey == null || account.apiSecret == null || account.apiPassphrase == null) {
logger.warn("账户未配置 API 凭证: accountId=${account.id}")
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, BigDecimal.ZERO, null, "fail", "账户未配置API凭证")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
BigDecimal.ZERO,
null,
"fail",
"账户未配置API凭证"
)
return
}
@@ -392,12 +526,32 @@ class CryptoTailStrategyExecutionService(
else -> strategy.amountValue
}
if (amountUsdc < BigDecimal("1")) {
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, null, "fail", "投入金额不足")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
null,
"fail",
"投入金额不足"
)
return
}
val tokenId = tokenIds.getOrNull(outcomeIndex) ?: run {
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, null, "fail", "tokenIds 越界")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
null,
"fail",
"tokenIds 越界"
)
return
}
@@ -416,16 +570,30 @@ class CryptoTailStrategyExecutionService(
cryptoUtils.decrypt(account.privateKey) ?: ""
} catch (e: Exception) {
logger.error("解密私钥失败: accountId=${account.id}", e)
saveTriggerRecord(strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, null, "fail", "解密私钥失败")
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
null,
"fail",
"解密私钥失败"
)
return
}
val apiSecret = try {
account.apiSecret?.let { cryptoUtils.decrypt(it) } ?: ""
} catch (e: Exception) { "" }
account.apiSecret.let { cryptoUtils.decrypt(it) }
} catch (e: Exception) {
""
}
val apiPassphrase = try {
account.apiPassphrase?.let { cryptoUtils.decrypt(it) } ?: ""
} catch (e: Exception) { "" }
val clobApi = retrofitFactory.createClobApi(account.apiKey!!, apiSecret, apiPassphrase, account.walletAddress)
account.apiPassphrase.let { cryptoUtils.decrypt(it) }
} catch (e: Exception) {
""
}
val clobApi = retrofitFactory.createClobApi(account.apiKey, apiSecret, apiPassphrase, account.walletAddress)
val feeRateBps = clobService.getFeeRate(tokenId).getOrNull()?.toString() ?: "0"
val signatureType = orderSigningService.getSignatureTypeForWalletType(account.walletType)
@@ -447,7 +615,16 @@ class CryptoTailStrategyExecutionService(
orderType = "FAK",
deferExec = false
)
submitOrderAndSaveRecord(clobApi, strategy, periodStartUnix, marketTitle, outcomeIndex, triggerPrice, amountUsdc, orderRequest)
submitOrderAndSaveRecord(
clobApi,
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
triggerPrice,
amountUsdc,
orderRequest
)
}
private suspend fun fetchEventBySlug(slug: String): Result<GammaEventBySlugResponse> {
@@ -480,7 +657,8 @@ class CryptoTailStrategyExecutionService(
amountUsdc: BigDecimal,
orderId: String?,
status: String,
failReason: String?
failReason: String?,
triggerType: String = "AUTO"
) {
val record = CryptoTailStrategyTrigger(
strategyId = strategy.id!!,
@@ -491,8 +669,179 @@ class CryptoTailStrategyExecutionService(
amountUsdc = amountUsdc,
orderId = orderId,
status = status,
failReason = failReason
failReason = failReason,
triggerType = triggerType
)
triggerRepository.save(record)
}
/**
* 手动下单用户主动触发下单不检查任何条件仅检查当前周期是否已下单
*/
suspend fun manualOrder(request: CryptoTailManualOrderRequest): Result<CryptoTailManualOrderResponse> {
return try {
val strategy = strategyRepository.findById(request.strategyId).orElse(null)
?: return Result.failure(IllegalArgumentException("策略不存在"))
val outcomeIndex = if (request.direction.uppercase() == "UP") 0 else 1
if (outcomeIndex < 0 || outcomeIndex >= request.tokenIds.size) {
return Result.failure(IllegalArgumentException("outcomeIndex 越界"))
}
val price = request.price.toSafeBigDecimal()
if (price <= BigDecimal.ZERO || price > BigDecimal.ONE) {
return Result.failure(IllegalArgumentException("价格必须在 0~1 之间"))
}
val priceRounded = price.setScale(4, RoundingMode.UP)
val size = request.size.toSafeBigDecimal()
if (size < BigDecimal.ONE) {
return Result.failure(IllegalArgumentException("数量不能少于 1"))
}
val amountUsdc = priceRounded.multi(size).setScale(2, RoundingMode.HALF_UP)
if (amountUsdc < BigDecimal.ONE) {
return Result.failure(IllegalArgumentException("总金额不能少于 1 USDC"))
}
val mutex = getTriggerMutex(strategy.id!!, request.periodStartUnix)
mutex.withLock {
if (triggerRepository.findByStrategyIdAndPeriodStartUnix(
strategy.id!!,
request.periodStartUnix
) != null
) {
return@withLock Result.failure(IllegalArgumentException("当前周期已下单"))
}
var ctx = getOrInvalidatePeriodContext(strategy, request.periodStartUnix)
if (ctx == null) {
ctx = ensurePeriodContext(
strategy,
request.periodStartUnix,
request.tokenIds,
request.marketTitle.ifBlank { null }
)
}
if (ctx != null) {
val tokenId = request.tokenIds.getOrNull(outcomeIndex)
?: return@withLock Result.failure(IllegalArgumentException("tokenIds 越界"))
val priceStr = priceRounded.toPlainString()
val sizeStr = size.toPlainString()
val feeRateBps = ctx.feeRateByTokenId[tokenId] ?: "0"
val signedOrder = orderSigningService.createAndSignOrder(
privateKey = ctx.decryptedPrivateKey,
makerAddress = ctx.account.proxyAddress,
tokenId = tokenId,
side = "BUY",
price = priceStr,
size = sizeStr,
signatureType = ctx.signatureType,
nonce = "0",
feeRateBps = feeRateBps,
expiration = "0"
)
val orderRequest = NewOrderRequest(
order = signedOrder,
owner = ctx.account.apiKey!!,
orderType = "FAK",
deferExec = false
)
val orderResult = submitOrderForManualOrder(
ctx.clobApi,
strategy,
request.periodStartUnix,
request.marketTitle,
outcomeIndex,
priceRounded,
amountUsdc,
orderRequest
)
orderResult.fold(
onSuccess = { orderId ->
Result.success(
CryptoTailManualOrderResponse(
success = true,
orderId = orderId,
message = "下单成功",
orderDetails = ManualOrderDetails(
strategyId = strategy.id!!,
direction = request.direction,
price = priceStr,
size = sizeStr,
totalAmount = amountUsdc.toPlainString()
)
)
)
},
onFailure = { e ->
Result.failure(e)
}
)
} else {
Result.failure(IllegalArgumentException("账户未配置或凭证不足"))
}
}
} catch (e: Exception) {
logger.error("手动下单异常: strategyId=${request.strategyId}, ${e.message}", e)
Result.failure(e)
}
}
private suspend fun submitOrderForManualOrder(
clobApi: PolymarketClobApi,
strategy: CryptoTailStrategy,
periodStartUnix: Long,
marketTitle: String?,
outcomeIndex: Int,
price: BigDecimal,
amountUsdc: BigDecimal,
orderRequest: NewOrderRequest
): Result<String> {
return try {
val response = clobApi.createOrder(orderRequest)
if (response.isSuccessful && response.body() != null) {
val body = response.body()!!
if (body.success && body.orderId != null) {
saveTriggerRecord(
strategy,
periodStartUnix,
marketTitle,
outcomeIndex,
price,
amountUsdc,
body.orderId,
"success",
null,
triggerType = "MANUAL"
)
logger.info("手动下单成功: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix, outcomeIndex=$outcomeIndex, orderId=${body.orderId}")
Result.success(body.orderId)
} else {
Result.failure(Exception(body.errorMsg ?: "unknown"))
}
} else {
val errorBody = response.errorBody()?.string().orEmpty()
Result.failure(Exception(errorBody.ifEmpty { "请求失败" }))
}
} catch (e: Exception) {
logger.error("手动下单异常: strategyId=${strategy.id}, periodStartUnix=$periodStartUnix", e)
Result.failure(e)
}
}
@PreDestroy
fun destroy() {
// 清理所有周期上下文缓存,避免敏感信息(明文私钥、API Secret)在内存中保留
periodContextCache.clear()
// 清理所有锁,避免内存泄漏
triggerMutexMap.clear()
logger.debug("加密价差策略执行服务已清理缓存和锁")
}
}
@@ -104,7 +104,7 @@ class CryptoTailStrategyService(
} catch (e: IllegalArgumentException) {
Result.failure(e)
} catch (e: Exception) {
logger.error("创建尾盘策略失败: ${e.message}", e)
logger.error("创建加密价差策略失败: ${e.message}", e)
Result.failure(e)
}
}
@@ -179,7 +179,7 @@ class CryptoTailStrategyService(
} catch (e: IllegalArgumentException) {
Result.failure(e)
} catch (e: Exception) {
logger.error("更新尾盘策略失败: ${e.message}", e)
logger.error("更新加密价差策略失败: ${e.message}", e)
Result.failure(e)
}
}
@@ -194,7 +194,7 @@ class CryptoTailStrategyService(
eventPublisher.publishEvent(CryptoTailStrategyChangedEvent(this))
Result.success(Unit)
} catch (e: Exception) {
logger.error("删除尾盘策略失败: ${e.message}", e)
logger.error("删除加密价差策略失败: ${e.message}", e)
Result.failure(e)
}
}
@@ -215,7 +215,7 @@ class CryptoTailStrategyService(
val dtos = list.map { entityToDto(it, lastTriggerMap[it.id]) }
Result.success(CryptoTailStrategyListResponse(list = dtos))
} catch (e: Exception) {
logger.error("查询尾盘策略列表失败: ${e.message}", e)
logger.error("查询加密价差策略列表失败: ${e.message}", e)
Result.failure(e)
}
}
@@ -263,7 +263,7 @@ class CryptoTailStrategyService(
private fun generateStrategyName(marketSlugPrefix: String): String {
val suffix = Instant.now().atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
return "尾盘策略-${marketSlugPrefix}-$suffix"
return "加密价差策略-${marketSlugPrefix}-$suffix"
}
private fun entityToDto(e: CryptoTailStrategy, lastTriggerAt: Long?): CryptoTailStrategyDto {
@@ -243,7 +243,14 @@ class ApiHealthCheckService(
name = "币安 WebSocket",
url = binanceWsUrl,
status = "success",
message = "连接正常 (5m、15m)"
message = "连接正常 (按策略订阅)"
)
} else if (total == 0) {
ApiHealthCheckDto(
name = "币安 WebSocket",
url = binanceWsUrl,
status = "success",
message = "无加密价差策略,未订阅"
)
} else if (connected > 0) {
val which = statuses.filter { it.value }.keys.joinToString("")
@@ -304,7 +304,7 @@ class TelegramNotificationService(
}
/**
* 发送尾盘策略下单成功通知与跟单一致在收到 WS 订单推送时匹配尾盘订单后调用
* 发送加密价差策略下单成功通知与跟单一致在收到 WS 订单推送时匹配价差策略订单后调用
*/
suspend fun sendCryptoTailOrderSuccessNotification(
orderId: String?,
@@ -324,7 +324,7 @@ class TelegramNotificationService(
if (orderId != null) {
val lastSentTime = sentOrderIds[orderId]
if (lastSentTime != null && System.currentTimeMillis() - lastSentTime < 5 * 60 * 1000) {
logger.info("尾盘订单通知已发送过(5分钟内),跳过: orderId=$orderId")
logger.info("加密价差策略订单通知已发送过(5分钟内),跳过: orderId=$orderId")
return
}
sentOrderIds[orderId] = System.currentTimeMillis()
@@ -894,7 +894,7 @@ class TelegramNotificationService(
}
/**
* 构建尾盘策略下单成功消息与订单成功格式一致增加尾盘策略标题与策略名
* 构建加密价差策略下单成功消息与订单成功格式一致增加加密价差策略标题与策略名
*/
private fun buildCryptoTailOrderSuccessMessage(
orderId: String?,
@@ -912,7 +912,7 @@ class TelegramNotificationService(
locale: java.util.Locale,
orderTime: Long?
): String {
val tailOrderSuccess = messageSource.getMessage("notification.tail.order.success", null, "尾盘策略下单成功", locale)
val tailOrderSuccess = messageSource.getMessage("notification.tail.order.success", null, "加密价差策略下单成功", locale)
val strategyLabel = messageSource.getMessage("notification.tail.strategy", null, "策略", locale)
val orderInfo = messageSource.getMessage("notification.order.info", null, "订单信息", locale)
val orderIdLabel = messageSource.getMessage("notification.order.id", null, "订单ID", locale)
@@ -193,7 +193,7 @@ class UnifiedWebSocketHandler(
lastActivityTime.remove(sessionId)
sessionLocks.remove(sessionId) // 清理同步锁
subscriptionService.unregisterSession(sessionId)
if (session != null && session.isOpen) {
try {
session.close(CloseStatus.NORMAL)
@@ -201,7 +201,6 @@ class UnifiedWebSocketHandler(
// 忽略关闭时的异常
}
}
} catch (e: Exception) {
logger.error("清理 WebSocket 资源时发生错误: $sessionId, ${e.message}", e)
}
@@ -0,0 +1,5 @@
-- 添加触发类型字段到加密价差策略触发记录表
-- AUTO: 自动下单触发
-- MANUAL: 手动下单触发
ALTER TABLE crypto_tail_strategy_trigger
ADD COLUMN trigger_type VARCHAR(20) DEFAULT 'AUTO' COMMENT '触发类型:AUTO(自动)或 MANUAL(手动)';
@@ -16,7 +16,7 @@ notification.order.time=Time
notification.order.error_info=Error Information
notification.order.unknown_account=Unknown Account
notification.order.calculate_failed=Calculation Failed
notification.tail.order.success=Tail Session Order Success
notification.tail.order.success=Crypto spread strategy order success
notification.tail.strategy=Strategy
notification.redeem.success=Position Redeemed Successfully
notification.redeem.info=Redeem Information
@@ -277,16 +277,16 @@ error.server.backtest_stop_failed=Failed to stop backtest task
error.server.backtest_retry_failed=Failed to retry backtest task
error.server.backtest_rerun_failed=Failed to re-run backtest with same config
# Crypto tail strategy
error.crypto_tail_strategy_not_found=Crypto tail strategy not found
# Crypto spread strategy
error.crypto_tail_strategy_not_found=Crypto spread strategy not found
error.crypto_tail_strategy_window_invalid=Window start must not be greater than window end
error.crypto_tail_strategy_window_exceed=Time window must not exceed period length
error.crypto_tail_strategy_interval_invalid=Interval must be 300 or 900 seconds
error.crypto_tail_strategy_amount_mode_invalid=Amount mode must be RATIO or FIXED
error.server.crypto_tail_strategy_create_failed=Failed to create crypto tail strategy
error.server.crypto_tail_strategy_update_failed=Failed to update crypto tail strategy
error.server.crypto_tail_strategy_delete_failed=Failed to delete crypto tail strategy
error.server.crypto_tail_strategy_list_fetch_failed=Failed to fetch crypto tail strategy list
error.server.crypto_tail_strategy_create_failed=Failed to create crypto spread strategy
error.server.crypto_tail_strategy_update_failed=Failed to update crypto spread strategy
error.server.crypto_tail_strategy_delete_failed=Failed to delete crypto spread strategy
error.server.crypto_tail_strategy_list_fetch_failed=Failed to fetch crypto spread strategy list
error.server.crypto_tail_strategy_triggers_fetch_failed=Failed to fetch trigger records
# Backtest Management
backtest.title=Backtest Management
@@ -16,7 +16,7 @@ notification.order.time=时间
notification.order.error_info=错误信息
notification.order.unknown_account=未知账户
notification.order.calculate_failed=计算失败
notification.tail.order.success=尾盘策略下单成功
notification.tail.order.success=加密价差策略下单成功
notification.tail.strategy=策略
notification.redeem.success=仓位赎回成功
notification.redeem.info=赎回信息
@@ -277,16 +277,16 @@ error.server.backtest_stop_failed=停止回测任务失败
error.server.backtest_retry_failed=重试回测任务失败
error.server.backtest_rerun_failed=按配置重新测试失败
# 尾盘策略
error.crypto_tail_strategy_not_found=尾盘策略不存在
# 加密价差策略
error.crypto_tail_strategy_not_found=加密价差策略不存在
error.crypto_tail_strategy_window_invalid=时间区间开始不能大于结束
error.crypto_tail_strategy_window_exceed=时间区间不能超过周期长度
error.crypto_tail_strategy_interval_invalid=周期仅支持 300 或 900 秒
error.crypto_tail_strategy_amount_mode_invalid=投入方式仅支持 RATIO 或 FIXED
error.server.crypto_tail_strategy_create_failed=创建尾盘策略失败
error.server.crypto_tail_strategy_update_failed=更新尾盘策略失败
error.server.crypto_tail_strategy_delete_failed=删除尾盘策略失败
error.server.crypto_tail_strategy_list_fetch_failed=查询尾盘策略列表失败
error.server.crypto_tail_strategy_create_failed=创建加密价差策略失败
error.server.crypto_tail_strategy_update_failed=更新加密价差策略失败
error.server.crypto_tail_strategy_delete_failed=删除加密价差策略失败
error.server.crypto_tail_strategy_list_fetch_failed=查询加密价差策略列表失败
error.server.crypto_tail_strategy_triggers_fetch_failed=查询触发记录失败
# 回测管理
backtest.title=回测管理
@@ -16,7 +16,7 @@ notification.order.time=時間
notification.order.error_info=錯誤信息
notification.order.unknown_account=未知賬戶
notification.order.calculate_failed=計算失敗
notification.tail.order.success=尾盤策略下單成功
notification.tail.order.success=加密價差策略下單成功
notification.tail.strategy=策略
notification.redeem.success=倉位贖回成功
notification.redeem.info=贖回信息
@@ -277,16 +277,16 @@ error.server.backtest_stop_failed=停止回測任務失敗
error.server.backtest_retry_failed=重試回測任務失敗
error.server.backtest_rerun_failed=依配置重新測試失敗
# 尾盤策略
error.crypto_tail_strategy_not_found=尾盤策略不存在
# 加密價差策略
error.crypto_tail_strategy_not_found=加密價差策略不存在
error.crypto_tail_strategy_window_invalid=時間區間開始不能大於結束
error.crypto_tail_strategy_window_exceed=時間區間不能超過週期長度
error.crypto_tail_strategy_interval_invalid=週期僅支援 300 或 900 秒
error.crypto_tail_strategy_amount_mode_invalid=投入方式僅支援 RATIO 或 FIXED
error.server.crypto_tail_strategy_create_failed=創建尾盤策略失敗
error.server.crypto_tail_strategy_update_failed=更新尾盤策略失敗
error.server.crypto_tail_strategy_delete_failed=刪除尾盤策略失敗
error.server.crypto_tail_strategy_list_fetch_failed=查詢尾盤策略列表失敗
error.server.crypto_tail_strategy_create_failed=創建加密價差策略失敗
error.server.crypto_tail_strategy_update_failed=更新加密價差策略失敗
error.server.crypto_tail_strategy_delete_failed=刪除加密價差策略失敗
error.server.crypto_tail_strategy_list_fetch_failed=查詢加密價差策略列表失敗
error.server.crypto_tail_strategy_triggers_fetch_failed=查詢觸發記錄失敗
# 回測管理
backtest.title=回測管理
+206 -1
View File
@@ -1,4 +1,209 @@
# PolyHermes 一键部署脚本使用说明
# PolyHermes One-Click Deployment Script / PolyHermes 一键部署脚本使用说明
[English](#english) | [中文](#中文)
---
<a name="english"></a>
## English
## ✨ Core Features
- **Run from any directory** - No need to download source code
- **Online images only** - Pull official images from Docker Hub
- **Auto-download config** - Download the latest `docker-compose.prod.yml` from GitHub
- **Interactive configuration** - User-friendly Q&A style configuration wizard
- **Auto-generate secrets** - All sensitive configurations will auto-generate secure random values on Enter
## 🚀 Quick Start
### One-Click Installation (Recommended)
**Using curl (Recommended):**
```bash
mkdir -p ~/polyhermes && cd ~/polyhermes && curl -fsSL https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh -o deploy.sh && chmod +x deploy.sh && ./deploy.sh
```
**Using wget:**
```bash
mkdir -p ~/polyhermes && cd ~/polyhermes && wget -O deploy.sh https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh && chmod +x deploy.sh && ./deploy.sh
```
This command will automatically:
- 📁 Create a dedicated working directory `~/polyhermes`
- 📥 Download the deployment script
- ✅ Check Docker environment
- ⚙️ Configure all parameters interactively (press Enter for defaults)
- 🔐 Auto-generate secure random secrets
- 🚀 Download latest images and deploy
**Or run directly via pipe (without saving file):**
```bash
# curl method
mkdir -p ~/polyhermes && cd ~/polyhermes && curl -fsSL https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh | bash
# wget method
mkdir -p ~/polyhermes && cd ~/polyhermes && wget -qO- https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh | bash
```
### Method 1: Download and Run Script Directly
```bash
# Download script
curl -O https://raw.githubusercontent.com/WrBug/PolyHermes/main/deploy-interactive.sh
# Add execute permission
chmod +x deploy-interactive.sh
# Run
./deploy-interactive.sh
```
### Method 2: Run in Project Directory
```bash
git clone https://github.com/WrBug/PolyHermes.git
cd PolyHermes
./deploy-interactive.sh
```
## 📝 Usage Flow
After running the script, you will be guided through the following steps:
```
Step 1: Environment Check → Check Docker/Docker Compose
Step 2: Configuration → Interactive input (press Enter for defaults)
Step 3: Get Deploy Config → Download docker-compose.prod.yml from GitHub
Step 4: Generate Env File → Auto-generate .env
Step 5: Pull Docker Images → Pull latest images from Docker Hub
Step 6: Deploy Services → Start containers
Step 7: Health Check → Verify services are running properly
```
## ⚡ Simplest Usage
**Press Enter for all configuration items to use default values**, the script will automatically:
- Use port 80 (application) and 3307 (MySQL)
- Generate 32-character database password
- Generate 128-character JWT secret
- Generate 64-character admin reset key
- Generate 64-character encryption key
- Configure reasonable log levels
### Interactive Example
The script will prompt you for configuration one by one, **press Enter to skip and use default values**:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 2: Configuration
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 All configurations are optional, press Enter to use default or auto-generated values
⚠ Secret config: Press Enter to auto-generate secure random secrets
⚠ Other config: Press Enter to use default values in parentheses
【Basic Configuration】
Will configure: Server port, MySQL port, Timezone
➤ Server port [Default: 80]: ⏎
➤ MySQL port (external access) [Default: 3307]: ⏎
➤ Timezone [Default: Asia/Shanghai]: ⏎
【Database Configuration】
Will configure: Database username, Database password
➤ Database username [Default: root]: ⏎
➤ Database password [Enter to auto-generate]: ⏎
[✓] Database password auto-generated (32 characters)
【Security Configuration】
Will configure: JWT secret, Admin password reset key, Data encryption key
➤ JWT secret [Enter to auto-generate]: ⏎
[✓] JWT secret auto-generated (128 characters)
➤ Admin password reset key [Enter to auto-generate]: ⏎
[✓] Admin reset key auto-generated (64 characters)
➤ Encryption key (for API Key encryption) [Enter to auto-generate]: ⏎
[✓] Encryption key auto-generated (64 characters)
【Log Configuration】
Will configure: Root log level, Application log level
Available levels: TRACE, DEBUG, INFO, WARN, ERROR, OFF
➤ Root log level (third-party libs) [Default: WARN]: ⏎
➤ Application log level [Default: INFO]: ⏎
【Other Configuration】
Will configure: Runtime environment, Auto-update policy, GitHub repo
➤ Spring Profile [Default: prod]: ⏎
➤ Allow prerelease updates (true/false) [Default: false]: ⏎
➤ GitHub repository [Default: WrBug/PolyHermes]: ⏎
```
## 🔧 Files Generated by Script
After running, the script will generate in the current directory:
1. **docker-compose.prod.yml** - Docker Compose config downloaded from GitHub (always latest)
2. **.env** - Environment variables file auto-generated based on your configuration
These two files contain all the configuration needed to run PolyHermes.
## 🌐 Post-Deployment Management
### Quick Update (Recommended)
If you already have configuration files, running the script again will detect and ask:
```bash
./deploy-interactive.sh
```
```
【Existing Configuration Detected】
Found existing .env configuration file
Use existing configuration to update images directly? [Y/n]: ⏎
```
- **Press Enter or input Y**: Use existing config, pull latest images and update
- **Input N**: Reconfigure (existing config will be backed up)
### Manual Management Commands
```bash
# View service status
docker compose -f docker-compose.prod.yml ps
# View logs
docker compose -f docker-compose.prod.yml logs -f
# Restart services
docker compose -f docker-compose.prod.yml restart
# Stop services
docker compose -f docker-compose.prod.yml down
# Update to latest version
docker pull wrbug/polyhermes:latest
docker compose -f docker-compose.prod.yml up -d
```
## 🔐 Security Recommendations
- **Protect .env file**: Contains sensitive information, never commit to version control
- **Backup database regularly**: Data is stored in Docker volume `mysql-data`
- **Configure HTTPS for production**: Recommend using Nginx or Caddy as reverse proxy
## 📞 Support
- [GitHub Repository](https://github.com/WrBug/PolyHermes)
- [Issue Feedback](https://github.com/WrBug/PolyHermes/issues)
- [Full Deployment Documentation](docs/zh/DEPLOYMENT_GUIDE.md)
---
<a name="中文"></a>
## 中文
## ✨ 核心特性
+175 -179
View File
@@ -1,18 +1,19 @@
#!/bin/bash
# ========================================
# PolyHermes Interactive Deploy Script
# PolyHermes 交互式一键部署脚本
# ========================================
# 功能:
# - 交互式配置环境变量
# - 自动生成安全密钥
# - 使用 Docker Hub 线上镜像部署
# - 支持配置预检和回滚
# Features / 功能:
# - Interactive env config / 交互式配置环境变量
# - Auto-generate secrets / 自动生成安全密钥
# - Deploy via Docker Hub images / 使用 Docker Hub 线上镜像部署
# - Config check and rollback / 支持配置预检和回滚
# ========================================
set -e
# 颜色输出
# Colors / 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
@@ -20,7 +21,14 @@ BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# 打印函数
# Language: LANG=zh* → prompts in Chinese only; else show "中文 / English"
# 语言:LANG 为 zh* 时仅中文,否则显示「中文 / English」
USE_ZH_ONLY=false
case "${LANG:-}" in
zh*) USE_ZH_ONLY=true ;;
esac
# Print functions / 打印函数
info() {
echo -e "${GREEN}[✓]${NC} $1"
}
@@ -37,6 +45,17 @@ title() {
echo -e "${CYAN}${1}${NC}"
}
# Bilingual: 中文 / English (or Chinese only when LANG=zh*)
bilingual() {
local zh="$1"
local en="$2"
if [ "$USE_ZH_ONLY" = true ]; then
echo "$zh"
else
echo "$zh / $en"
fi
}
# 生成随机密钥
generate_secret() {
local length=${1:-32}
@@ -47,54 +66,57 @@ generate_secret() {
fi
}
# 生成随机端口号(10000-60000之间)
# 生成随机端口号(10000-60000之间)/ Generate random port (10000-60000)
generate_random_port() {
echo $((10000 + RANDOM % 50001))
}
# 读取用户输入(支持默认值)
# 读取用户输入(支持默认值)/ Read user input (with default)
read_input() {
local prompt="$1"
local default="$2"
local is_secret="$3"
local value=""
# 构建提示信息(不使用颜色,因为 read -p 可能不支持)
local prompt_text=""
if [ -n "$default" ]; then
if [ "$is_secret" = "secret" ]; then
prompt_text="${prompt} [回车自动生成]: "
if [ "$USE_ZH_ONLY" = true ]; then
prompt_text="${prompt} [回车自动生成]: "
else
prompt_text="${prompt} [Enter to auto-generate]: "
fi
else
prompt_text="${prompt} [默认: ${default}]: "
if [ "$USE_ZH_ONLY" = true ]; then
prompt_text="${prompt} [默认: ${default}]: "
else
prompt_text="${prompt} [Default: ${default}]: "
fi
fi
else
prompt_text="${prompt}: "
fi
# 使用 read -p 确保提示正确显示
read -r -p "$prompt_text" value
# 如果用户没有输入,使用默认值
if [ -z "$value" ]; then
if [ "$is_secret" = "secret" ] && [ -z "$default" ]; then
# 自动生成密钥
case "$prompt" in
*JWT*)
*JWT*|*jwt*)
value=$(generate_secret 64)
# 输出到 stderr,避免被捕获到返回值中
info "已自动生成 JWT 密钥(128字符)" >&2
info "$(bilingual "已自动生成 JWT 密钥(128字符)" "JWT secret auto-generated (128 chars)")" >&2
;;
*管理员*|*ADMIN*)
*管理员*|*ADMIN*|*admin*|*reset*|*Reset*)
value=$(generate_secret 32)
info "已自动生成管理员重置密钥(64字符)" >&2
info "$(bilingual "已自动生成管理员重置密钥(64字符)" "Admin reset key auto-generated (64 chars)")" >&2
;;
*加密*|*CRYPTO*)
*加密*|*CRYPTO*|*crypto*|*Encryption*)
value=$(generate_secret 32)
info "已自动生成加密密钥(64字符)" >&2
info "$(bilingual "已自动生成加密密钥(64字符)" "Encryption key auto-generated (64 chars)")" >&2
;;
*数据库密码*|*DB_PASSWORD*)
*数据库密码*|*DB_PASSWORD*|*database*|*Database*)
value=$(generate_secret 16)
info "已自动生成数据库密码(32字符)" >&2
info "$(bilingual "已自动生成数据库密码(32字符)" "Database password auto-generated (32 chars)")" >&2
;;
*)
value="$default"
@@ -108,126 +130,115 @@ read_input() {
echo "$value"
}
# 检查 Docker 环境
# 检查 Docker 环境 / Check Docker environment
check_docker() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 步骤 1: 环境检查"
title " $(bilingual "步骤 1: 环境检查" "Step 1: Environment Check")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 检查 Docker
if ! command -v docker &> /dev/null; then
error "Docker 未安装"
error "$(bilingual "Docker 未安装" "Docker is not installed")"
echo ""
info "请先安装 Docker"
info "$(bilingual "请先安装 Docker" "Please install Docker first:")"
info " macOS: brew install docker"
info " Ubuntu/Debian: apt-get install docker.io"
info " CentOS/RHEL: yum install docker"
exit 1
fi
info "Docker 已安装: $(docker --version | head -1)"
info "$(bilingual "Docker 已安装" "Docker installed"): $(docker --version | head -1)"
# 检查 Docker Compose
if docker compose version &> /dev/null 2>&1; then
info "Docker Compose 已安装: $(docker compose version)"
info "$(bilingual "Docker Compose 已安装" "Docker Compose installed"): $(docker compose version)"
elif command -v docker-compose &> /dev/null; then
info "Docker Compose 已安装: $(docker-compose --version)"
info "$(bilingual "Docker Compose 已安装" "Docker Compose installed"): $(docker-compose --version)"
else
error "Docker Compose 未安装"
error "$(bilingual "Docker Compose 未安装" "Docker Compose is not installed")"
echo ""
info "请先安装 Docker Compose"
info "$(bilingual "请先安装 Docker Compose" "Please install Docker Compose:")"
info " https://docs.docker.com/compose/install/"
exit 1
fi
# 检查 Docker 守护进程
if ! docker info &> /dev/null; then
error "Docker 守护进程未运行"
info "请启动 Docker 服务:"
info " macOS: 打开 Docker Desktop"
error "$(bilingual "Docker 守护进程未运行" "Docker daemon is not running")"
info "$(bilingual "请启动 Docker 服务:" "Please start Docker:")"
info " $(bilingual "macOS: 打开 Docker Desktop" "macOS: Open Docker Desktop")"
info " Linux: systemctl start docker"
exit 1
fi
info "Docker 守护进程运行正常"
info "$(bilingual "Docker 守护进程运行正常" "Docker daemon is running")"
echo ""
}
# 交互式配置收集
# 交互式配置收集 / Interactive configuration
collect_configuration() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 步骤 2: 配置收集"
title " $(bilingual "步骤 2: 配置收集" "Step 2: Configuration")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
info "💡 所有配置项均为可选,直接按回车即可使用默认值或自动生成"
info "$(bilingual "💡 所有配置项均为可选,直接按回车即可使用默认值或自动生成" "💡 All options are optional, press Enter for default or auto-generated values")"
echo ""
warn "密钥配置:回车将自动生成安全的随机密钥"
warn "其他配置:回车将使用括号中的默认值"
warn "$(bilingual "密钥配置:回车将自动生成安全的随机密钥" "Secrets: Enter to auto-generate secure random keys")"
warn "$(bilingual "其他配置:回车将使用括号中的默认值" "Other: Enter to use default value in brackets")"
echo ""
# 基础配置
title "【基础配置】"
echo -e "${CYAN}将配置:服务器端口、MySQL端口、时区${NC}"
# 生成随机端口作为默认值
title "$(bilingual "【基础配置】" "【Basic】")"
echo -e "${CYAN}$(bilingual "将配置:服务器端口、MySQL端口、时区" "Server port, MySQL port, Timezone")${NC}"
DEFAULT_PORT=$(generate_random_port)
SERVER_PORT=$(read_input "➤ 服务器端口" "$DEFAULT_PORT")
MYSQL_PORT=$(read_input "➤ MySQL 端口(外部访问)" "3307")
TZ=$(read_input "➤ 时区" "Asia/Shanghai")
SERVER_PORT=$(read_input "$(bilingual "➤ 服务器端口" "➤ Server port")" "$DEFAULT_PORT")
MYSQL_PORT=$(read_input "$(bilingual "➤ MySQL 端口(外部访问)" "➤ MySQL port (external)")" "3307")
TZ=$(read_input "$(bilingual "➤ 时区" "➤ Timezone")" "Asia/Shanghai")
echo ""
# 数据库配置
title "【数据库配置】"
echo -e "${CYAN}将配置:数据库用户名、数据库密码${NC}"
echo -e "${YELLOW}💡 提示:密码留空将自动生成 32 字符的安全随机密码${NC}"
DB_USERNAME=$(read_input "➤ 数据库用户名" "root")
DB_PASSWORD=$(read_input "➤ 数据库密码" "" "secret")
title "$(bilingual "【数据库配置】" "【Database】")"
echo -e "${CYAN}$(bilingual "将配置:数据库用户名、数据库密码" "Database username, password")${NC}"
echo -e "${YELLOW}$(bilingual "💡 提示:密码留空将自动生成 32 字符的安全随机密码" "💡 Leave password empty to auto-generate 32-char password")${NC}"
DB_USERNAME=$(read_input "$(bilingual "➤ 数据库用户名" "➤ Database username")" "root")
DB_PASSWORD=$(read_input "$(bilingual "➤ 数据库密码" "➤ Database password")" "" "secret")
echo ""
# 安全配置
title "【安全配置】"
echo -e "${CYAN}将配置:JWT密钥、管理员密码重置密钥、数据加密密钥${NC}"
echo -e "${YELLOW}💡 提示:留空将自动生成高强度随机密钥(推荐)${NC}"
JWT_SECRET=$(read_input "➤ JWT 密钥" "" "secret")
ADMIN_RESET_PASSWORD_KEY=$(read_input "➤ 管理员密码重置密钥" "" "secret")
CRYPTO_SECRET_KEY=$(read_input "➤ 加密密钥(用于加密 API Key" "" "secret")
title "$(bilingual "【安全配置】" "【Security】")"
echo -e "${CYAN}$(bilingual "将配置:JWT密钥、管理员密码重置密钥、数据加密密钥" "JWT secret, Admin reset key, Encryption key")${NC}"
echo -e "${YELLOW}$(bilingual "💡 提示:留空将自动生成高强度随机密钥(推荐)" "💡 Leave empty to auto-generate strong keys (recommended)")${NC}"
JWT_SECRET=$(read_input "$(bilingual "➤ JWT 密钥" "➤ JWT secret")" "" "secret")
ADMIN_RESET_PASSWORD_KEY=$(read_input "$(bilingual "➤ 管理员密码重置密钥" "➤ Admin password reset key")" "" "secret")
CRYPTO_SECRET_KEY=$(read_input "$(bilingual "➤ 加密密钥(用于加密 API Key" "➤ Encryption key (for API Key)")" "" "secret")
echo ""
# 日志配置
title "【日志配置】"
echo -e "${CYAN}将配置:Root日志级别、应用日志级别${NC}"
echo -e "${YELLOW}可选级别: TRACE, DEBUG, INFO, WARN, ERROR, OFF${NC}"
LOG_LEVEL_ROOT=$(read_input "➤ Root 日志级别(第三方库)" "WARN")
LOG_LEVEL_APP=$(read_input "➤ 应用日志级别" "INFO")
title "$(bilingual "【日志配置】" "【Logging】")"
echo -e "${CYAN}$(bilingual "将配置:Root日志级别、应用日志级别" "Root log level, App log level")${NC}"
echo -e "${YELLOW}$(bilingual "可选级别: TRACE, DEBUG, INFO, WARN, ERROR, OFF" "Levels: TRACE, DEBUG, INFO, WARN, ERROR, OFF")${NC}"
LOG_LEVEL_ROOT=$(read_input "$(bilingual "➤ Root 日志级别(第三方库)" "➤ Root log level (3rd party)")" "WARN")
LOG_LEVEL_APP=$(read_input "$(bilingual "➤ 应用日志级别" "➤ App log level")" "INFO")
echo ""
# 自动设置不需要用户输入的配置
SPRING_PROFILES_ACTIVE="prod"
ALLOW_PRERELEASE="false"
GITHUB_REPO="WrBug/PolyHermes"
}
# 下载 docker-compose.prod.yml(如果不存在)
# 下载 docker-compose.prod.yml(如果不存在)/ Download docker-compose.prod.yml if missing
download_docker_compose_file() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 步骤 3: 获取部署配置"
title " $(bilingual "步骤 3: 获取部署配置" "Step 3: Get Deploy Config")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ -f "docker-compose.prod.yml" ]; then
info "检测到现有 docker-compose.prod.yml,跳过下载"
info "$(bilingual "检测到现有 docker-compose.prod.yml,跳过下载" "Existing docker-compose.prod.yml found, skip download")"
echo ""
return 0
fi
info "正在从 GitHub 下载 docker-compose.prod.yml..."
info "$(bilingual "正在从 GitHub 下载 docker-compose.prod.yml..." "Downloading docker-compose.prod.yml from GitHub...")"
# GitHub raw 文件链接
local compose_url="https://raw.githubusercontent.com/WrBug/PolyHermes/main/docker-compose.prod.yml"
# 尝试下载
if curl -fsSL "$compose_url" -o docker-compose.prod.yml; then
info "docker-compose.prod.yml 下载成功"
info "$(bilingual "docker-compose.prod.yml 下载成功" "docker-compose.prod.yml downloaded")"
else
error "docker-compose.prod.yml 下载失败"
warn "请检查网络连接或手动下载:"
error "$(bilingual "docker-compose.prod.yml 下载失败" "Failed to download docker-compose.prod.yml")"
warn "$(bilingual "请检查网络连接或手动下载:" "Check network or download manually:")"
warn " $compose_url"
exit 1
fi
@@ -235,28 +246,26 @@ download_docker_compose_file() {
echo ""
}
# 生成 .env 文件
# 生成 .env 文件 / Generate .env file
generate_env_file() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 步骤 4: 生成环境变量文件"
title " $(bilingual "步骤 4: 生成环境变量文件" "Step 4: Generate .env")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 备份现有 .env 文件
if [ -f ".env" ]; then
BACKUP_FILE=".env.backup.$(date +%Y%m%d_%H%M%S)"
cp .env "$BACKUP_FILE"
warn "已备份现有配置文件到: $BACKUP_FILE"
warn "$(bilingual "已备份现有配置文件到" "Backed up existing config to"): $BACKUP_FILE"
fi
# 生成新的 .env 文件
cat > .env <<EOF
# ========================================
# PolyHermes 生产环境配置
# 生成时间: $(date '+%Y-%m-%d %H:%M:%S')
# PolyHermes Production Config / 生产环境配置
# Generated / 生成时间: $(date '+%Y-%m-%d %H:%M:%S')
# ========================================
# ============================================
# 基础配置
# Basic / 基础配置
# ============================================
TZ=${TZ}
SPRING_PROFILES_ACTIVE=${SPRING_PROFILES_ACTIVE}
@@ -264,112 +273,107 @@ SERVER_PORT=${SERVER_PORT}
MYSQL_PORT=${MYSQL_PORT}
# ============================================
# 数据库配置
# Database / 数据库配置
# ============================================
DB_URL=jdbc:mysql://mysql:3306/polyhermes?useSSL=false&serverTimezone=UTC&characterEncoding=utf8&allowPublicKeyRetrieval=true
DB_USERNAME=${DB_USERNAME}
DB_PASSWORD=${DB_PASSWORD}
# ============================================
# 安全配置(请妥善保管)
# Security (keep safe) / 安全配置(请妥善保管)
# ============================================
JWT_SECRET=${JWT_SECRET}
ADMIN_RESET_PASSWORD_KEY=${ADMIN_RESET_PASSWORD_KEY}
CRYPTO_SECRET_KEY=${CRYPTO_SECRET_KEY}
# ============================================
# 日志配置
# Logging / 日志配置
# ============================================
LOG_LEVEL_ROOT=${LOG_LEVEL_ROOT}
LOG_LEVEL_APP=${LOG_LEVEL_APP}
# ============================================
# 其他配置
# Other / 其他配置
# ============================================
ALLOW_PRERELEASE=${ALLOW_PRERELEASE}
GITHUB_REPO=${GITHUB_REPO}
EOF
info "配置文件已生成: .env"
info "$(bilingual "配置文件已生成" "Config file generated"): .env"
echo ""
# 显示配置摘要
title "【配置摘要】"
echo " 服务器端口: ${SERVER_PORT}"
echo " MySQL 端口: ${MYSQL_PORT}"
echo " 时区: ${TZ}"
echo " 数据库用户: ${DB_USERNAME}"
echo " 数据库密码: ${DB_PASSWORD:0:8}... (已隐藏)"
echo " JWT 密钥: ${JWT_SECRET:0:16}... (已隐藏)"
echo " 管理员重置密钥: ${ADMIN_RESET_PASSWORD_KEY:0:16}... (已隐藏)"
echo " 加密密钥: ${CRYPTO_SECRET_KEY:0:16}... (已隐藏)"
echo " 日志级别: Root=${LOG_LEVEL_ROOT}, App=${LOG_LEVEL_APP}"
title "$(bilingual "【配置摘要】" "【Config Summary】")"
echo " $(bilingual "服务器端口" "Server port"): ${SERVER_PORT}"
echo " $(bilingual "MySQL 端口" "MySQL port"): ${MYSQL_PORT}"
echo " $(bilingual "时区" "Timezone"): ${TZ}"
echo " $(bilingual "数据库用户" "DB user"): ${DB_USERNAME}"
echo " $(bilingual "数据库密码" "DB password"): ${DB_PASSWORD:0:8}... $(bilingual "(已隐藏)" "(hidden)")"
echo " $(bilingual "JWT 密钥" "JWT secret"): ${JWT_SECRET:0:16}... $(bilingual "(已隐藏)" "(hidden)")"
echo " $(bilingual "管理员重置密钥" "Admin reset key"): ${ADMIN_RESET_PASSWORD_KEY:0:16}... $(bilingual "(已隐藏)" "(hidden)")"
echo " $(bilingual "加密密钥" "Encryption key"): ${CRYPTO_SECRET_KEY:0:16}... $(bilingual "(已隐藏)" "(hidden)")"
echo " $(bilingual "日志级别" "Log level"): Root=${LOG_LEVEL_ROOT}, App=${LOG_LEVEL_APP}"
echo ""
}
# 拉取镜像
# 拉取镜像 / Pull images
pull_images() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 步骤 5: 拉取 Docker 镜像"
title " $(bilingual "步骤 5: 拉取 Docker 镜像" "Step 5: Pull Docker Images")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
info "正在从 Docker Hub 拉取最新镜像..."
info "$(bilingual "正在从 Docker Hub 拉取最新镜像..." "Pulling latest images from Docker Hub...")"
# 拉取应用镜像
if docker pull wrbug/polyhermes:latest; then
info "应用镜像拉取成功: wrbug/polyhermes:latest"
info "$(bilingual "应用镜像拉取成功" "App image pulled"): wrbug/polyhermes:latest"
else
error "应用镜像拉取失败"
warn "可能的原因:"
warn " 1. 网络连接问题"
warn " 2. Docker Hub 服务异常"
warn " 3. 镜像不存在"
error "$(bilingual "应用镜像拉取失败" "Failed to pull app image")"
warn "$(bilingual "可能的原因:" "Possible reasons:")"
warn " 1. $(bilingual "网络连接问题" "Network issue")"
warn " 2. $(bilingual "Docker Hub 服务异常" "Docker Hub unavailable")"
warn " 3. $(bilingual "镜像不存在" "Image not found")"
exit 1
fi
# 拉取 MySQL 镜像
if docker pull mysql:8.2; then
info "MySQL 镜像拉取成功: mysql:8.2"
info "$(bilingual "MySQL 镜像拉取成功" "MySQL image pulled"): mysql:8.2"
else
warn "MySQL 镜像拉取失败,将在启动时自动下载"
warn "$(bilingual "MySQL 镜像拉取失败,将在启动时自动下载" "MySQL pull failed, will download on start")"
fi
echo ""
}
# 部署服务
# 部署服务 / Deploy services
deploy_services() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 步骤 6: 部署服务"
title " $(bilingual "步骤 6: 部署服务" "Step 6: Deploy Services")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 停止现有服务
if docker compose -f docker-compose.prod.yml ps -q 2>/dev/null | grep -q .; then
warn "检测到正在运行的服务,正在停止..."
warn "$(bilingual "检测到正在运行的服务,正在停止..." "Stopping existing services...")"
docker compose -f docker-compose.prod.yml down
info "已停止现有服务"
info "$(bilingual "已停止现有服务" "Stopped existing services")"
fi
# 启动服务
info "正在启动服务..."
info "$(bilingual "正在启动服务..." "Starting services...")"
if docker compose -f docker-compose.prod.yml up -d; then
info "服务启动成功"
info "$(bilingual "服务启动成功" "Services started")"
else
error "服务启动失败"
error "请检查日志: docker compose -f docker-compose.prod.yml logs"
error "$(bilingual "服务启动失败" "Failed to start services")"
error "$(bilingual "请检查日志" "Check logs"): docker compose -f docker-compose.prod.yml logs"
exit 1
fi
echo ""
}
# 健康检查
# 健康检查 / Health check
health_check() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 步骤 7: 健康检查"
title " $(bilingual "步骤 7: 健康检查" "Step 7: Health Check")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
info "等待服务启动(最多等待 60 秒)..."
info "$(bilingual "等待服务启动(最多等待 60 秒)..." "Waiting for services (up to 60s)...")"
local max_attempts=12
local attempt=0
@@ -377,13 +381,11 @@ health_check() {
while [ $attempt -lt $max_attempts ]; do
attempt=$((attempt + 1))
# 检查容器状态
if docker compose -f docker-compose.prod.yml ps | grep -q "Up"; then
info "容器运行正常"
info "$(bilingual "容器运行正常" "Containers are up")"
# 检查应用是否响应
if curl -s -o /dev/null -w "%{http_code}" http://localhost:${SERVER_PORT} | grep -q "200\|302\|401"; then
info "应用响应正常"
info "$(bilingual "应用响应正常" "App is responding")"
echo ""
return 0
fi
@@ -394,79 +396,76 @@ health_check() {
done
echo ""
warn "健康检查超时,请手动检查服务状态"
warn "查看日志: docker compose -f docker-compose.prod.yml logs -f"
warn "$(bilingual "健康检查超时,请手动检查服务状态" "Health check timeout, please check services manually")"
warn "$(bilingual "查看日志" "View logs"): docker compose -f docker-compose.prod.yml logs -f"
echo ""
}
# 显示部署信息
# 显示部署信息 / Show deployment info
show_deployment_info() {
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
title " 部署完成!"
title " $(bilingual "部署完成!" "Deployment Complete!")"
title "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
info "访问地址: ${GREEN}http://localhost:${SERVER_PORT}${NC}"
info "$(bilingual "访问地址" "Access URL"): ${GREEN}http://localhost:${SERVER_PORT}${NC}"
echo ""
title "【常用命令】"
echo -e " 查看服务状态: ${CYAN}docker compose -f docker-compose.prod.yml ps${NC}"
echo -e " 查看日志: ${CYAN}docker compose -f docker-compose.prod.yml logs -f${NC}"
echo -e " 停止服务: ${CYAN}docker compose -f docker-compose.prod.yml down${NC}"
echo -e " 重启服务: ${CYAN}docker compose -f docker-compose.prod.yml restart${NC}"
echo -e " 更新镜像: ${CYAN}docker pull wrbug/polyhermes:latest && docker compose -f docker-compose.prod.yml up -d${NC}"
title "$(bilingual "【常用命令】" "【Common Commands】")"
echo -e " $(bilingual "查看服务状态" "Status"): ${CYAN}docker compose -f docker-compose.prod.yml ps${NC}"
echo -e " $(bilingual "查看日志" "Logs"): ${CYAN}docker compose -f docker-compose.prod.yml logs -f${NC}"
echo -e " $(bilingual "停止服务" "Stop"): ${CYAN}docker compose -f docker-compose.prod.yml down${NC}"
echo -e " $(bilingual "重启服务" "Restart"): ${CYAN}docker compose -f docker-compose.prod.yml restart${NC}"
echo -e " $(bilingual "更新镜像" "Update"): ${CYAN}docker pull wrbug/polyhermes:latest && docker compose -f docker-compose.prod.yml up -d${NC}"
echo ""
title "【数据库连接信息】"
echo -e " 主机: ${CYAN}localhost${NC}"
echo -e " 端口: ${CYAN}${MYSQL_PORT}${NC}"
echo -e " 数据库: ${CYAN}polyhermes${NC}"
echo -e " 用户名: ${CYAN}${DB_USERNAME}${NC}"
echo -e " 密码: ${CYAN}${DB_PASSWORD}${NC}"
title "$(bilingual "【数据库连接信息】" "【Database Connection】")"
echo -e " $(bilingual "主机" "Host"): ${CYAN}localhost${NC}"
echo -e " $(bilingual "端口" "Port"): ${CYAN}${MYSQL_PORT}${NC}"
echo -e " $(bilingual "数据库" "Database"): ${CYAN}polyhermes${NC}"
echo -e " $(bilingual "用户名" "Username"): ${CYAN}${DB_USERNAME}${NC}"
echo -e " $(bilingual "密码" "Password"): ${CYAN}${DB_PASSWORD}${NC}"
echo ""
title "【管理员重置密钥】"
echo -e " 重置密钥: ${CYAN}${ADMIN_RESET_PASSWORD_KEY}${NC}"
echo -e " ${YELLOW}💡 此密钥用于重置管理员密码,请妥善保管${NC}"
title "$(bilingual "【管理员重置密钥】" "【Admin Reset Key】")"
echo -e " $(bilingual "重置密钥" "Reset key"): ${CYAN}${ADMIN_RESET_PASSWORD_KEY}${NC}"
echo -e " ${YELLOW}$(bilingual "💡 此密钥用于重置管理员密码,请妥善保管" "💡 Keep this key safe; it is used to reset admin password")${NC}"
echo ""
warn "重要提示:"
warn " 1. 请妥善保管 .env 文件,勿提交到版本控制系统"
warn " 2. 定期备份数据库数据(位于 Docker volume: polyhermes_mysql-data"
warn " 3. 生产环境建议配置反向代理(如 Nginx)并启用 HTTPS"
warn "$(bilingual "重要提示:" "Important:")"
warn " 1. $(bilingual "请妥善保管 .env 文件,勿提交到版本控制系统" "Keep .env secure; do not commit to version control")"
warn " 2. $(bilingual "定期备份数据库数据(位于 Docker volume: polyhermes_mysql-data" "Back up DB regularly (Docker volume: polyhermes_mysql-data)")"
warn " 3. $(bilingual "生产环境建议配置反向代理(如 Nginx)并启用 HTTPS" "Use a reverse proxy (e.g. Nginx) and HTTPS in production")"
echo ""
}
# 主函数
# 主函数 / Main
main() {
clear
echo ""
title "========================================="
title " PolyHermes 交互式一键部署脚本 "
title " $(bilingual "PolyHermes 交互式一键部署脚本" "PolyHermes Interactive Deploy") "
title "========================================="
echo ""
# 执行部署流程
check_docker
# 检查是否已存在 .env 文件
if [ -f ".env" ]; then
echo ""
title "【检测到现有配置】"
info "发现已存在的 .env 配置文件"
title "$(bilingual "【检测到现有配置】" "【Existing Config Found】")"
info "$(bilingual "发现已存在的 .env 配置文件" "Found existing .env file")"
echo ""
echo -ne "${YELLOW}是否使用现有配置直接更新镜像?[Y/n]: ${NC}"
echo -ne "${YELLOW}$(bilingual "是否使用现有配置直接更新镜像?[Y/n]" "Use existing config to update images? [Y/n]"): ${NC}"
read -r use_existing
use_existing=${use_existing:-Y}
if [[ "$use_existing" =~ ^[Yy]$ ]]; then
info "将使用现有配置,跳过配置步骤"
info "$(bilingual "将使用现有配置,跳过配置步骤" "Using existing config, skipping configuration")"
echo ""
# 从现有 .env 文件读取必要的变量
source .env 2>/dev/null || true
else
warn "将重新配置,现有配置将被备份"
warn "$(bilingual "将重新配置,现有配置将被备份" "Will reconfigure; existing config will be backed up")"
echo ""
collect_configuration
fi
@@ -476,21 +475,18 @@ main() {
download_docker_compose_file
# 只有在重新配置时才生成新的 .env 文件
if [[ ! "$use_existing" =~ ^[Yy]$ ]] || [ ! -f ".env" ]; then
generate_env_file
fi
# 确认部署
echo ""
title "【确认部署】"
echo -ne "${YELLOW}是否开始部署?[Y/n](回车默认为是): ${NC}"
title "$(bilingual "【确认部署】" "【Confirm Deploy】")"
echo -ne "${YELLOW}$(bilingual "是否开始部署?[Y/n](回车默认为是)" "Start deployment? [Y/n] (Enter = Yes)"): ${NC}"
read -r confirm
# 默认为 Y,只有明确输入 n/N 才取消
confirm=${confirm:-Y}
if [[ "$confirm" =~ ^[Nn]$ ]]; then
warn "部署已取消"
warn "$(bilingual "部署已取消" "Deployment cancelled")"
exit 0
fi
@@ -500,11 +496,11 @@ main() {
health_check
show_deployment_info
info "部署流程已完成!"
info "$(bilingual "部署流程已完成!" "Deployment finished!")"
}
# 捕获 Ctrl+C
trap 'echo ""; warn "部署已中断"; exit 1' INT
# 捕获 Ctrl+C / Handle Ctrl+C
trap 'echo ""; warn "$(bilingual "部署已中断" "Deployment interrupted")"; exit 1' INT
# 运行主函数
# 运行主函数 / Run main
main "$@"
+2 -2
View File
@@ -1,6 +1,6 @@
# 尾盘策略文档 (Crypto Tail Strategy)
# 加密价差策略文档 (Crypto Spread Strategy)
本目录集中存放与 Polymarket 加密市场尾盘策略相关的文档。
本目录集中存放与 Polymarket 加密市场加密价差策略相关的文档。
## 目录结构
@@ -55,7 +55,7 @@ effectiveMinSpread = baseSpread × coefficient
- 需要策略的 `windowStartSeconds``windowEndSeconds` 传入计算处;若窗口长度为 0,可退化为系数 = 1.0 或 0.5(需约定)。
**优点**:与「尾盘只在窗口内触发」一致,时间语义清晰;毫秒级 progress 更精确。
**优点**:与「加密价差策略只在窗口内触发」一致,时间语义清晰;毫秒级 progress 更精确。
**缺点**`getAutoMinSpread` 需要增加当前时间(毫秒)和窗口参数(或传整个 strategy)。
---
@@ -1,8 +1,8 @@
# Crypto Tail Strategy Configuration Guide
# Crypto Spread Strategy Configuration Guide
## Part 1: What is Crypto Tail Strategy?
## Part 1: What is Crypto Spread Strategy?
Crypto Tail Strategy is an automated trading strategy designed specifically for Polymarket crypto markets' **5-minute** or **15-minute** "Up or Down" markets.
Crypto Spread Strategy is an automated trading strategy designed specifically for Polymarket crypto markets' **5-minute** or **15-minute** "Up or Down" markets.
**Core Logic**: Within a specified time window, when the market price enters your set price range, the system will automatically buy at a fixed price (0.99) without manual operation.
@@ -39,7 +39,7 @@ Cycle Start → Within Time Window → Price Enters Range → Auto Order
- **Maximum one trigger per cycle**: Within the same cycle, even if conditions are met multiple times, only one order is placed
- **Fixed order price**: All orders are submitted at price 0.99
- **Requires separate wallet**: It's recommended to use a dedicated wallet for tail strategies to avoid conflicts with other operations (manual trading, copy trading, etc.)
- **Requires separate wallet**: It's recommended to use a dedicated wallet for crypto spread strategies to avoid conflicts with other operations (manual trading, copy trading, etc.)
---
@@ -50,7 +50,7 @@ Cycle Start → Within Time Window → Price Enters Range → Auto Order
| Parameter | Description | Required | Example |
|-----------|-------------|----------|---------|
| **Account** | Select the wallet account for trading | ✅ | Account A |
| **Strategy Name** | Name your strategy for easy identification | ❌ | "BTC 15min Tail Strategy" |
| **Strategy Name** | Name your strategy for easy identification | ❌ | "BTC 15min Crypto Spread Strategy" |
| **Market** | Select the market to trade (5-minute or 15-minute) | ✅ | btc-updown-15m |
### 3.2 Cycle Settings
@@ -341,7 +341,7 @@ Enabled: On
2. **Position conflicts**: Manual trading and strategy trading may conflict
3. **Management confusion**: Difficult to distinguish which orders are from strategy vs manual
**Recommendation**: Create a dedicated wallet, only for tail strategies.
**Recommendation**: Create a dedicated wallet, only for crypto spread strategies.
### Q7: Why is the order price fixed at 0.99?
@@ -352,7 +352,7 @@ Enabled: On
### Q8: Does the strategy depend on auto-redeem functionality?
**A**: Yes, tail strategy depends on auto-redeem functionality.
**A**: Yes, crypto spread strategy depends on auto-redeem functionality.
**Reasons**:
- Strategy orders create positions after execution
@@ -411,7 +411,7 @@ Enabled: On
### 7.1 View Strategy List
On the "Crypto Tail Strategy" page, you can view all strategies:
On the "Crypto Spread Strategy" page, you can view all strategies:
- Strategy name
- Market information
- Time window
@@ -453,7 +453,7 @@ After deleting a strategy:
## Part 8: Summary
Crypto Tail Strategy is a powerful automated trading tool that can help you:
Crypto Spread Strategy is a powerful automated trading tool that can help you:
1. **Automated Trading**: No need for manual monitoring, system executes automatically
2. **Precise Control**: Precisely control trigger conditions through time windows and price ranges
@@ -1,4 +1,4 @@
# 加密市场尾盘策略 - 流程图
# 加密价差策略 - 流程图
## 一、整体架构
@@ -1,4 +1,4 @@
# 加密市场尾盘策略 - 5/15 分钟市场数据获取说明
# 加密价差策略 - 5/15 分钟市场数据获取说明
> 前端 UI 与交互详见 `crypto-tail-strategy-ui-spec.md`
@@ -1,8 +1,8 @@
# 尾盘策略 - 最小价差参数流程分析
# 加密价差策略 - 最小价差参数流程分析
## 一、需求摘要
在现有尾盘策略上增加**最小价差**参数:当策略条件(时间窗、价格区间)满足时,再判断**当前周期 Binance K 线的开盘价与收盘价价差**是否满足最小价差;满足才下单,不满足则等待,直到价差满足再下单。
在现有加密价差策略上增加**最小价差**参数:当策略条件(时间窗、价格区间)满足时,再判断**当前周期 Binance K 线的开盘价与收盘价价差**是否满足最小价差;满足才下单,不满足则等待,直到价差满足再下单。
- **后端**:需订阅币安对应币对(如 BTC/USDC)的 K 线,维护当前周期的**开盘价**与**实时收盘价**,并在触发时做价差校验。
- **前端**:可配置三种场景——无、固定、自动(见下)。
@@ -244,4 +244,4 @@ sequenceDiagram
3. **下单与去重**
- 仍保持「每周期最多触发一次」;价差不满足时不写触发记录,直到某次同时满足价格与价差后才下单并写记录。
按上述流程即可在现有尾盘策略上接入「最小价差」参数,并由后端订阅币安 K 线、在触发前做价差校验;固定与自动的时序差异见**第六节时序图**。
按上述流程即可在现有加密价差策略上接入「最小价差」参数,并由后端订阅币安 K 线、在触发前做价差校验;固定与自动的时序差异见**第六节时序图**。
@@ -1,4 +1,4 @@
# 加密市场尾盘策略 - 任务梳理
# 加密价差策略 - 任务梳理
> 需求与 UI 见 `crypto-tail-strategy-ui-spec.md`,市场数据与执行规则见 `crypto-tail-strategy-market-data.md`
@@ -66,7 +66,7 @@
| 序号 | 任务 | 说明 |
|------|------|------|
| B16 | 自动赎回包含尾盘策略仓位 | 尾盘策略产生的仓位与跟单/手动一视同仁,纳入现有自动赎回逻辑,不排除(见 UI 规格附录 A)。 |
| B16 | 自动赎回包含加密价差策略仓位 | 加密价差策略产生的仓位与跟单/手动一视同仁,纳入现有自动赎回逻辑,不排除(见 UI 规格附录 A)。 |
| B17 | 调度/定时或常驻 | 对已启用策略按周期(如每 10–30 秒)检查:当前周期、是否在时间窗口内、是否已触发、价格是否进区间;满足则执行下单并写触发记录。 |
---
@@ -78,7 +78,7 @@
| 序号 | 任务 | 说明 |
|------|------|------|
| F1 | 路由 | App.tsx 增加 `/crypto-tail-strategy`、可选 `/crypto-tail-strategy/records/:id`。 |
| F2 | 菜单 | Layout 中增加「尾盘策略」菜单项,与跟单同级或在其下;key 与路由一致。 |
| F2 | 菜单 | Layout 中增加「加密价差策略」菜单项,与跟单同级或在其下;key 与路由一致。 |
### 4.2 列表页
@@ -146,5 +146,5 @@ F10 触发记录
- **时间区间**:仅当周期内当前时间落在 [windowStartSeconds, windowEndSeconds] 时才判断价格并下单;前端区间开始 ≤ 结束,且不超出 5min/15min。
- **每周期一次**:同一策略同一周期只触发一次(先满足价格的 outcome 买入,反方向不买)。
- **重试**:下单失败最多重试 2 次,共 3 次;仍失败记入触发记录为失败。
- **自动赎回**尾盘策略产生的仓位可被自动赎回,无排除逻辑。
- **自动赎回**加密价差策略产生的仓位可被自动赎回,无排除逻辑。
- **创建前检查**:未配置自动赎回时点击新增策略弹出「去配置」弹窗,不打开表单。
@@ -1,4 +1,4 @@
# 加密市场尾盘策略 - 前端 UI 规格
# 加密价差策略 - 前端 UI 规格
> 周期推导与市场数据获取详见 `crypto-tail-strategy-market-data.md`
@@ -10,7 +10,7 @@
| 项目 | 说明 |
|------|------|
| **菜单** | 在「跟单管理」同级或其下增加一项,如「尾盘策略」,key 建议 `/crypto-tail-strategy`。 |
| **菜单** | 在「跟单管理」同级或其下增加一项,如「加密价差策略」,key 建议 `/crypto-tail-strategy`。 |
| **路由** | 列表页 `/crypto-tail-strategy`;可选详情/触发记录 `/crypto-tail-strategy/records/:id`。 |
参考:`Layout.tsx``/copy-trading``/backtest` 的配置;`App.tsx` 中对应 `Route`
@@ -26,7 +26,7 @@
| 元素 | 类型 | 说明 |
|------|------|------|
| 页面标题 | 标题文案 | 如「加密尾盘策略」,用 `t('cryptoTailStrategy.list.title')`。 |
| 页面标题 | 标题文案 | 如「加密价差策略」,用 `t('cryptoTailStrategy.list.title')`。 |
| **钱包使用提示** | **AlertWarning** | **必须**在页面顶部或标题下方展示:提示用户**使用单独/专用钱包**运行本策略,避免该钱包用于手动交易、跟单等其他操作,否则可能导致余额或仓位变化,进而造成策略执行异常(如余额不足、下单失败等)。文案走多语言 `t('cryptoTailStrategy.list.walletTip')`,可带 `showIcon`。 |
| 新增策略 | ButtonPrimary) | 点击时**先检查自动赎回相关配置**(见 2.4);若未配置则弹出「去配置」简易弹窗,若已配置则打开「新增策略」表单弹窗。图标可用 `PlusOutlined`。 |
| 筛选(可选) | Select / 筛选项 | 按账户、启用状态筛选;移动端可收起到抽屉或折叠。 |
@@ -59,7 +59,7 @@
1. **检查**:请求系统配置(如 `apiService.systemConfig.getConfig()` 或已有接口),判断是否已配置 Builder API Key(及可选:自动赎回已开启)。若 `builderApiKeyConfigured === false`(或后端约定之「未配置」状态),视为未配置。
2. **未配置时**:不打开新增策略表单,改为弹出**简易弹窗**(Modal),内容建议:
- **标题**:如「请先配置自动赎回」,`t('cryptoTailStrategy.redeemRequiredModal.title')`
- **正文**:简短说明尾盘策略依赖自动赎回,需要先在「系统设置」中配置 Builder API Key 及自动赎回。文案 `t('cryptoTailStrategy.redeemRequiredModal.description')`
- **正文**:简短说明加密价差策略依赖自动赎回,需要先在「系统设置」中配置 Builder API Key 及自动赎回。文案 `t('cryptoTailStrategy.redeemRequiredModal.description')`
- **操作**
- **去配置**:主按钮,点击后关闭弹窗并跳转到系统设置页(如 `/system-settings`,该页含 Relayer 配置与自动赎回开关)。
- **取消**:次按钮或关闭图标,仅关闭弹窗。
@@ -133,7 +133,7 @@
|------|------|
| **钱包提示** | 列表页与新增/编辑表单**必须**包含「使用单独钱包」的 Alert 提示,避免用户用混用钱包导致异常;文案走多语言。 |
| **创建前检查** | 点击「新增策略」时先检查自动赎回/Builder API 是否已配置;未配置则弹出简易「去配置」弹窗,引导用户到系统设置配置 API Key 与自动赎回,不打开策略表单。 |
| 多语言 | 所有文案 `t('cryptoTailStrategy.xxx')`,在 `locales/zh-CN``zh-TW``en``common.json` 中增加键。需包含:`cryptoTailStrategy.list.walletTip``cryptoTailStrategy.form.walletTip`,以及 `cryptoTailStrategy.redeemRequiredModal.title``cryptoTailStrategy.redeemRequiredModal.description``cryptoTailStrategy.redeemRequiredModal.goToSettings``cryptoTailStrategy.redeemRequiredModal.cancel`。文案示例:列表页 `walletTip`:「请使用单独的钱包运行尾盘策略,避免该钱包用于手动交易、跟单等其他操作,否则可能导致余额或仓位变化,造成策略执行异常。」表单内 `walletTip`:「建议使用专用钱包,避免手动操作等导致余额或下单异常。」未配置赎回弹窗 `title`:「请先配置自动赎回」;`description`:「尾盘策略依赖自动赎回功能,请先在系统设置中配置 Builder API Key 并开启自动赎回。」;`goToSettings`:「去配置」;`cancel`:「取消」。 |
| 多语言 | 所有文案 `t('cryptoTailStrategy.xxx')`,在 `locales/zh-CN``zh-TW``en``common.json` 中增加键。需包含:`cryptoTailStrategy.list.walletTip``cryptoTailStrategy.form.walletTip`,以及 `cryptoTailStrategy.redeemRequiredModal.title``cryptoTailStrategy.redeemRequiredModal.description``cryptoTailStrategy.redeemRequiredModal.goToSettings``cryptoTailStrategy.redeemRequiredModal.cancel`。文案示例:列表页 `walletTip`:「请使用单独的钱包运行加密价差策略,避免该钱包用于手动交易、跟单等其他操作,否则可能导致余额或仓位变化,造成策略执行异常。」表单内 `walletTip`:「建议使用专用钱包,避免手动操作等导致余额或下单异常。」未配置赎回弹窗 `title`:「请先配置自动赎回」;`description`:「加密价差策略依赖自动赎回功能,请先在系统设置中配置 Builder API Key 并开启自动赎回。」;`goToSettings`:「去配置」;`cancel`:「取消」。 |
| 金额 | 统一 `formatUSDC`(见 frontend.mdc)。 |
| 响应式 | `useMediaQuery`;按钮触摸目标 ≥ 44px;移动端主操作突出。 |
| 类型 | 不用 `any`;为策略、触发记录定义 TypeScript 类型。 |
@@ -150,7 +150,7 @@
| 新增/编辑弹窗 | `frontend/src/pages/CryptoTailStrategyList/FormModal.tsx` 或内嵌 Modal |
| 触发记录 | `frontend/src/pages/CryptoTailStrategyList/TriggerRecordsModal.tsx``CryptoTailStrategyRecords.tsx` |
| 路由 | `App.tsx``/crypto-tail-strategy`、可选 `/crypto-tail-strategy/records/:id` |
| 菜单 | `Layout.tsx` 中增加「尾盘策略」菜单项 |
| 菜单 | `Layout.tsx` 中增加「加密价差策略」菜单项 |
| 类型 | `frontend/src/types/index.ts``types/cryptoTailStrategy.ts` 中增加策略与触发记录类型 |
| 多语言 | `frontend/src/locales/{zh-CN,zh-TW,en}/common.json` 中增加 `cryptoTailStrategy.*` |
@@ -158,7 +158,7 @@
## 7. 小结:UI 包含的主要元素
- **导航**:主导航中「尾盘策略」入口。
- **导航**:主导航中「加密价差策略」入口。
- **列表页**:标题、钱包提示 Alert、新增按钮(点击前先检查赎回配置,未配置则弹「去配置」简易弹窗)、筛选、表格/卡片(策略名、市场、价格区间、投入方式、状态、最近触发、操作)、加载与空状态。
- **未配置赎回弹窗**:简易 Modal,提示依赖自动赎回、需先配置 Builder API Key 与自动赎回;按钮「去配置」(跳转 `/system-settings`)、「取消」。
- **表单弹窗**:策略名、账户、市场选择、minPrice/maxPrice、投入方式(比例/固定)、启用开关、提交/取消。
@@ -169,9 +169,9 @@
## 附录 A 后端/产品要求:自动赎回须支持本策略仓位
自动赎回逻辑**必须支持赎回由尾盘策略产生的订单所对应的仓位**。即:本策略触发的市价买入会形成仓位,这些仓位在满足「可赎回」条件时,应被纳入现有自动赎回流程并正常发起赎回,不得因来源为「尾盘策略」而被排除。后端实现时需保证:
自动赎回逻辑**必须支持赎回由加密价差策略产生的订单所对应的仓位**。即:本策略触发的市价买入会形成仓位,这些仓位在满足「可赎回」条件时,应被纳入现有自动赎回流程并正常发起赎回,不得因来源为「加密价差策略」而被排除。后端实现时需保证:
- 尾盘策略下单产生的仓位,与跟单/手动下单等来源的仓位一视同仁,参与可赎回查询与批量赎回;
- 若当前自动赎回按账户或仓位类型过滤,需将「尾盘策略订单产生的仓位」包含在内。
- 加密价差策略下单产生的仓位,与跟单/手动下单等来源的仓位一视同仁,参与可赎回查询与批量赎回;
- 若当前自动赎回按账户或仓位类型过滤,需将「加密价差策略订单产生的仓位」包含在内。
这样前端所依赖的「自动赎回」对该策略才完整有效。
@@ -1,8 +1,8 @@
# 尾盘策略配置指南
# 加密价差策略配置指南
## 一、什么是尾盘策略?
## 一、什么是加密价差策略?
尾盘策略是一种自动化交易策略,专门用于 Polymarket 加密市场的 **5分钟****15分钟** "Up or Down" 市场。
加密价差策略是一种自动化交易策略,专门用于 Polymarket 加密市场的 **5分钟****15分钟** "Up or Down" 市场。
**核心逻辑**:在指定时间窗口内,当市场价格进入您设定的价格区间时,系统会自动以固定价格(0.99)买入,无需手动操作。
@@ -39,7 +39,7 @@
- **每周期最多触发一次**:同一个周期内,即使多次满足条件,也只下单一次
- **固定下单价格**:所有订单都以 0.99 的价格提交
- **需要单独钱包**:建议使用专门的钱包运行尾盘策略,避免与其他操作(手动交易、跟单等)冲突
- **需要单独钱包**:建议使用专门的钱包运行加密价差策略,避免与其他操作(手动交易、跟单等)冲突
---
@@ -50,7 +50,7 @@
| 参数 | 说明 | 必填 | 示例 |
|------|------|------|------|
| **账户** | 选择用于交易的钱包账户 | ✅ | 账户A |
| **策略名称** | 给策略起个名字,方便识别 | ❌ | "BTC 15分钟尾盘策略" |
| **策略名称** | 给策略起个名字,方便识别 | ❌ | "BTC 15分钟加密价差策略" |
| **市场** | 选择要交易的市场(5分钟或15分钟) | ✅ | btc-updown-15m |
### 3.2 周期设置
@@ -341,7 +341,7 @@
2. **仓位冲突**:手动交易和策略交易可能产生冲突
3. **管理混乱**:难以区分哪些订单是策略产生的,哪些是手动产生的
**建议**:创建一个专门的钱包,只用于尾盘策略。
**建议**:创建一个专门的钱包,只用于加密价差策略。
### Q7:下单价格为什么是固定的 0.99?
@@ -352,7 +352,7 @@
### Q8:策略需要依赖自动赎回功能吗?
**A**:是的,尾盘策略依赖自动赎回功能。
**A**:是的,加密价差策略依赖自动赎回功能。
**原因**
- 策略下单后会形成仓位
@@ -411,7 +411,7 @@
### 7.1 查看策略列表
在「尾盘策略」页面可以查看所有策略:
在「加密价差策略」页面可以查看所有策略:
- 策略名称
- 市场信息
- 时间窗口
@@ -453,7 +453,7 @@
## 八、总结
尾盘策略是一个强大的自动化交易工具,可以帮助您:
加密价差策略是一个强大的自动化交易工具,可以帮助您:
1. **自动化交易**:无需手动盯盘,系统自动执行
2. **精准控制**:通过时间窗口和价格区间精确控制触发条件
+2
View File
@@ -35,6 +35,7 @@ import Announcements from './pages/Announcements'
import BacktestList from './pages/BacktestList'
import BacktestDetail from './pages/BacktestDetail'
import CryptoTailStrategyList from './pages/CryptoTailStrategyList'
import CryptoTailMonitor from './pages/CryptoTailMonitor'
import { wsManager } from './services/websocket'
import type { OrderPushMessage } from './types'
import { apiService } from './services/api'
@@ -252,6 +253,7 @@ function App() {
<Route path="/templates/edit/:id" element={<ProtectedRoute><TemplateEdit /></ProtectedRoute>} />
<Route path="/copy-trading" element={<ProtectedRoute><CopyTradingList /></ProtectedRoute>} />
<Route path="/crypto-tail-strategy" element={<ProtectedRoute><CryptoTailStrategyList /></ProtectedRoute>} />
<Route path="/crypto-tail-monitor" element={<ProtectedRoute><CryptoTailMonitor /></ProtectedRoute>} />
<Route path="/copy-trading/statistics/:copyTradingId" element={<ProtectedRoute><CopyTradingStatistics /></ProtectedRoute>} />
{/* 保留旧路由以保持向后兼容 */}
<Route path="/copy-trading/orders/buy/:copyTradingId" element={<ProtectedRoute><CopyTradingBuyOrders /></ProtectedRoute>} />
+26 -6
View File
@@ -21,7 +21,9 @@ import {
SendOutlined,
ApiOutlined,
NotificationOutlined,
LineChartOutlined
LineChartOutlined,
RocketOutlined,
DashboardOutlined
} from '@ant-design/icons'
import type { MenuProps } from 'antd'
import type { ReactNode } from 'react'
@@ -75,6 +77,9 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
if (path.startsWith('/leaders') || path.startsWith('/templates') || path.startsWith('/copy-trading') || path.startsWith('/backtest')) {
keys.push('/copy-trading-management')
}
if (path.startsWith('/crypto-tail-strategy') || path.startsWith('/crypto-tail-monitor')) {
keys.push('/crypto-tail-management')
}
if (path.startsWith('/system-settings')) {
keys.push('/system-settings')
}
@@ -90,6 +95,9 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
if (path.startsWith('/leaders') || path.startsWith('/templates') || path.startsWith('/copy-trading') || path.startsWith('/backtest')) {
keys.push('/copy-trading-management')
}
if (path.startsWith('/crypto-tail-strategy') || path.startsWith('/crypto-tail-monitor')) {
keys.push('/crypto-tail-management')
}
if (path.startsWith('/system-settings')) {
keys.push('/system-settings')
}
@@ -158,9 +166,21 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
]
},
{
key: '/crypto-tail-strategy',
key: '/crypto-tail-management',
icon: <LineChartOutlined />,
label: t('menu.cryptoTailStrategy')
label: t('menu.cryptoSpreadStrategy'),
children: [
{
key: '/crypto-tail-strategy',
icon: <RocketOutlined />,
label: t('menu.cryptoTailStrategy')
},
{
key: '/crypto-tail-monitor',
icon: <DashboardOutlined />,
label: t('menu.cryptoTailMonitor')
}
]
},
{
key: '/positions',
@@ -230,7 +250,7 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
const handleMenuClick = ({ key }: { key: string }) => {
// 如果是父菜单,不导航(但 /system-settings 作为子菜单项时可以导航)
if (key === '/copy-trading-management') {
if (key === '/copy-trading-management' || key === '/crypto-tail-management') {
return
}
@@ -288,7 +308,7 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
alignItems: 'center',
verticalAlign: 'middle'
}}
title={hasUpdate ? '有新版本可用,点击前往系统更新' : '当前已是最新版本'}
title={hasUpdate ? t('systemUpdate.versionTooltipNew') : t('systemUpdate.versionTooltipLatest')}
>
{getVersionInfo().gitTag || `v${getVersionText()}`}
</Tag>
@@ -410,7 +430,7 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
alignItems: 'center',
verticalAlign: 'middle'
}}
title={hasUpdate ? '有新版本可用,点击前往系统更新' : '当前已是最新版本'}
title={hasUpdate ? t('systemUpdate.versionTooltipNew') : t('systemUpdate.versionTooltipLatest')}
>
{getVersionInfo().gitTag || `v${getVersionText()}`}
</Tag>
+151 -5
View File
@@ -312,7 +312,9 @@
"leaders": "Leader Management",
"templates": "Templates",
"copyTradingConfig": "Copy Trading Config",
"cryptoTailStrategy": "Tail Strategy",
"cryptoSpreadStrategy": "Crypto Spread Strategy",
"cryptoTailStrategy": "Strategy Config",
"cryptoTailMonitor": "Real-time Monitor",
"positions": "Position Management",
"backtest": "Backtest",
"statistics": "Statistics",
@@ -418,6 +420,40 @@
"saveFailed": "Failed to save auto redeem configuration"
}
},
"systemUpdate": {
"title": "System Update",
"currentVersion": "Current Version",
"ready": "Ready",
"hasNewVersion": "New version available: {{version}}",
"alreadyLatest": "You are on the latest version",
"checkFailed": "Failed to check for updates",
"confirmTitle": "Confirm Update",
"confirmContent1": "Update to version {{version}}?",
"confirmContent2": "The system will be temporarily unavailable during the update (about 30-60 seconds).",
"confirmContent3": "The page will refresh automatically when the update completes.",
"okText": "Update Now",
"cancelText": "Cancel",
"updateStarted": "Update started, please wait...",
"updateFailedWithMessage": "Update failed: {{message}}",
"updateSuccessRefresh": "Update successful! Page will refresh in 3 seconds...",
"needAdmin": "Admin permission required to perform update",
"startFailed": "Failed to start update",
"updating": "System is updating",
"updateFailedTitle": "Update Failed",
"checkUpdate": "Check for Updates",
"newVersionFound": "New Version Available",
"publishedAt": "Published At",
"releaseNotes": "Release Notes",
"upgradeNow": "Upgrade to v{{version}} Now",
"usageTitle": "Instructions",
"usage1": "Click \"Check for Updates\" to see if a new version is available",
"usage2": "Update takes about 30-60 seconds; the system will be temporarily unavailable",
"usage3": "The page will refresh automatically after a successful update",
"usage4": "If the update fails, the system will roll back to the current version",
"versionTooltipNew": "New version available, click to go to System Update",
"versionTooltipLatest": "You are on the latest version",
"prerelease": "Pre-release"
},
"builderApiKey": {
"title": "Builder API Key Configuration",
"alertTitle": "What is Builder API Key?",
@@ -1450,12 +1486,12 @@
"cryptoTailStrategy": {
"binanceApiAlert": {
"title": "Cannot connect to Binance API — strategy cannot run for now",
"description": "Tail strategy needs Binance market data to work. The connection failed; this may be a network issue or Binance outage. Try again later by clicking the button below.",
"description": "Crypto spread strategy needs Binance market data to work. The connection failed; this may be a network issue or Binance outage. Try again later by clicking the button below.",
"recheck": "Re-check"
},
"list": {
"title": "Crypto Tail Strategy",
"walletTip": "Use a dedicated wallet for tail strategy. Do not use it for manual trading or copy trading to avoid balance/position issues.",
"title": "Crypto Spread Strategy",
"walletTip": "Use a dedicated wallet for crypto spread strategy. Do not use it for manual trading or copy trading to avoid balance/position issues.",
"addStrategy": "Add Strategy",
"strategyName": "Strategy Name",
"account": "Account",
@@ -1512,7 +1548,7 @@
},
"redeemRequiredModal": {
"title": "Configure Auto Redeem First",
"description": "Tail strategy requires auto redeem. Please configure Builder API Key and enable auto redeem in System Settings.",
"description": "Crypto spread strategy requires auto redeem. Please configure Builder API Key and enable auto redeem in System Settings.",
"goToSettings": "Go to Settings",
"cancel": "Cancel"
},
@@ -1541,5 +1577,115 @@
"emptyFail": "No failed records",
"totalCount": "{count} record(s)"
}
},
"cryptoTailMonitor": {
"title": "Crypto Spread Strategy Monitor",
"selectStrategy": "Strategy",
"selectStrategyPlaceholder": "Select a strategy to monitor",
"direction": "Direction",
"directionUp": "Up",
"directionDown": "Down",
"noData": "Select a strategy to start monitoring",
"priceRange": "Price Range",
"timeWindow": "Time Window",
"stat": {
"openPrice": "Open Price",
"currentPrice": "Current Price",
"spread": "Spread",
"remainingTime": "Remaining",
"configuredSpread": "Configured Spread",
"configuredSpreadMin": "Min Spread",
"configuredSpreadMax": "Max Spread",
"status": "Status",
"minSpreadLine": "Min Spread",
"periodSpreadMinMax": "Period Spread",
"periodSpreadMin": "Period Min Spread",
"periodSpreadMax": "Period Max Spread",
"minSpread": "Min",
"maxSpread": "Max"
},
"status": {
"triggered": "Triggered",
"periodEnded": "Period Ended",
"inCondition": "In Condition",
"waiting": "Waiting"
},
"chart": {
"title": "Price Chart",
"btcTitle": "BTC Price Chart",
"marketTitle": "Market Price Chart",
"priceChart": "Price Chart",
"price": "Price",
"openPrice": "Open",
"spread": "Spread",
"minSpreadLine": "Min Spread Line",
"maxSpreadLine": "Max Spread Line",
"marketUp": "Up",
"marketDown": "Down",
"time": "Time",
"latestPrice": "Latest",
"timeWindowStart": "Window Start",
"timeWindowEnd": "Window End"
},
"strategyInfo": {
"title": "Strategy Info",
"market": "Market",
"interval": "Interval",
"account": "Account",
"spreadMode": "Spread Mode",
"spreadDirection": "Spread Direction"
},
"periodSwitch": {
"mode": "Period Switch Mode",
"auto": "Auto",
"manual": "Manual",
"autoDesc": "Automatically switch to the latest period when it ends",
"manualDesc": "Keep complete data when period ends",
"switchToLatest": "Switch to Latest Period",
"periodEnded": "Current period has ended",
"newPeriodAvailable": "New period has started"
},
"manualOrder": {
"title": "Manual Order",
"buttonUp": "Buy Up",
"buttonDown": "Buy Down",
"confirmTitle": "Manual Order Confirmation",
"marketTitle": "Market Title",
"direction": "Direction",
"directionUp": "Up",
"directionDown": "Down",
"orderPrice": "Order Price",
"orderSize": "Order Size",
"totalAmount": "Total Amount",
"account": "Account",
"cancel": "Cancel",
"confirm": "Confirm Order",
"orderUnit": "USDC",
"sizeUnit": "shares",
"statusNotOrdered": "Not Ordered",
"statusOrdered": "This period has been ordered",
"statusOrderedAuto": "This period has been auto-ordered",
"statusOrderedManual": "This period has been manually ordered",
"errorInsufficientBalance": "Insufficient account balance, available: {balance} USDC",
"errorPriceOutOfRange": "Price must be between 0 and 1",
"errorMinSize": "Size cannot be less than 1 share",
"errorExceedsBalance": "Total amount exceeds available balance",
"errorPriceRequired": "Please enter order price",
"errorSizeRequired": "Please enter order size",
"success": "Manual order successful",
"failed": "Manual order failed: {{reason}}",
"errorSigning": "Signing failed: {reason}",
"errorNetwork": "Network error, please try again later",
"priceNotLoaded": "Price data not loaded",
"insufficientBalance": "Insufficient balance, available amount less than 1 USDC",
"fetchBalanceFailed": "Failed to fetch account balance",
"availableBalance": "Available Balance",
"fetchLatestPrice": "Latest Price",
"priceUpdated": "Price updated",
"maxSize": "Max",
"invalidPriceOrBalance": "Invalid price or balance",
"insufficientBalanceForMax": "Insufficient balance for max size",
"maxSizeUpdated": "Updated to max size"
}
}
}
+152 -5
View File
@@ -92,6 +92,7 @@
"accountNamePlaceholder": "账户名称(可选)",
"accountIdRequired": "账户ID不能为空",
"walletAddress": "钱包地址",
"walletType": "钱包类型",
"proxyAddress": "代理钱包地址",
"apiCredentials": "API 凭证",
"apiKey": "API Key",
@@ -311,7 +312,9 @@
"leaders": "Leader 管理",
"templates": "跟单模板",
"copyTradingConfig": "跟单配置",
"cryptoTailStrategy": "尾盘策略",
"cryptoSpreadStrategy": "加密价差策略",
"cryptoTailStrategy": "策略配置",
"cryptoTailMonitor": "实时监控",
"positions": "仓位管理",
"backtest": "回测",
"statistics": "统计信息",
@@ -417,6 +420,40 @@
"saveFailed": "保存自动赎回配置失败"
}
},
"systemUpdate": {
"title": "系统更新",
"currentVersion": "当前版本",
"ready": "就绪",
"hasNewVersion": "发现新版本: {{version}}",
"alreadyLatest": "当前已是最新版本",
"checkFailed": "检查更新失败",
"confirmTitle": "确认更新",
"confirmContent1": "确定要更新到版本 {{version}} 吗?",
"confirmContent2": "更新过程中系统将暂时不可用(约30-60秒)。",
"confirmContent3": "更新完成后页面将自动刷新。",
"okText": "立即更新",
"cancelText": "取消",
"updateStarted": "更新已启动,请稍候...",
"updateFailedWithMessage": "更新失败: {{message}}",
"updateSuccessRefresh": "更新成功!页面将在3秒后刷新...",
"needAdmin": "需要管理员权限才能执行更新",
"startFailed": "启动更新失败",
"updating": "系统正在更新",
"updateFailedTitle": "更新失败",
"checkUpdate": "检查更新",
"newVersionFound": "发现新版本",
"publishedAt": "发布时间",
"releaseNotes": "更新内容",
"upgradeNow": "立即升级到 v{{version}}",
"usageTitle": "使用说明",
"usage1": "点击「检查更新」按钮检查是否有新版本",
"usage2": "更新过程约需30-60秒,期间系统将暂时不可用",
"usage3": "更新成功后页面将自动刷新",
"usage4": "如果更新失败,系统会自动回滚到当前版本",
"versionTooltipNew": "有新版本可用,点击前往系统更新",
"versionTooltipLatest": "当前已是最新版本",
"prerelease": "预发布"
},
"builderApiKey": {
"title": "Builder API Key 配置",
"alertTitle": "什么是 Builder API Key",
@@ -1449,12 +1486,12 @@
"cryptoTailStrategy": {
"binanceApiAlert": {
"title": "无法连接币安 API,策略暂时不能运行",
"description": "尾盘策略需要从币安获取行情数据才能工作。当前连接失败,可能是网络问题或币安服务异常,请稍后点击下方按钮重新检测。",
"description": "加密价差策略需要从币安获取行情数据才能工作。当前连接失败,可能是网络问题或币安服务异常,请稍后点击下方按钮重新检测。",
"recheck": "重新检测"
},
"list": {
"title": "加密尾盘策略",
"walletTip": "请使用单独的钱包运行尾盘策略,避免该钱包用于手动交易、跟单等其他操作,否则可能导致余额或仓位变化,造成策略执行异常。",
"title": "加密价差策略",
"walletTip": "请使用单独的钱包运行加密价差策略,避免该钱包用于手动交易、跟单等其他操作,否则可能导致余额或仓位变化,造成策略执行异常。",
"addStrategy": "新增策略",
"strategyName": "策略名称",
"account": "账户",
@@ -1511,7 +1548,7 @@
},
"redeemRequiredModal": {
"title": "请先配置自动赎回",
"description": "尾盘策略依赖自动赎回功能,请先在系统设置中配置 Builder API Key 并开启自动赎回。",
"description": "加密价差策略依赖自动赎回功能,请先在系统设置中配置 Builder API Key 并开启自动赎回。",
"goToSettings": "去配置",
"cancel": "取消"
},
@@ -1540,5 +1577,115 @@
"emptyFail": "暂无失败记录",
"totalCount": "共 {count} 条"
}
},
"cryptoTailMonitor": {
"title": "加密价差策略监控",
"selectStrategy": "选择策略",
"selectStrategyPlaceholder": "请选择要监控的策略",
"direction": "监控方向",
"directionUp": "Up",
"directionDown": "Down",
"noData": "请选择一个策略开始监控",
"priceRange": "价格区间",
"timeWindow": "时间窗口",
"stat": {
"openPrice": "开盘价",
"currentPrice": "最新价",
"spread": "价差",
"remainingTime": "剩余时间",
"configuredSpread": "配置价差",
"configuredSpreadMin": "最小价差",
"configuredSpreadMax": "最大价差",
"status": "状态",
"minSpreadLine": "最小价差线",
"periodSpreadMinMax": "周期内价差",
"periodSpreadMin": "周期内最小价差",
"periodSpreadMax": "周期内最大价差",
"minSpread": "最小",
"maxSpread": "最大"
},
"status": {
"triggered": "已触发",
"periodEnded": "周期结束",
"inCondition": "满足条件",
"waiting": "等待中"
},
"chart": {
"title": "分时图",
"btcTitle": "BTC 分时图",
"marketTitle": "市场分时图",
"priceChart": "价格分时图",
"price": "价格",
"openPrice": "开盘价",
"spread": "价差",
"minSpreadLine": "最小价差线",
"maxSpreadLine": "最大价差线",
"marketUp": "Up",
"marketDown": "Down",
"time": "时间",
"latestPrice": "最新价",
"timeWindowStart": "区间开始",
"timeWindowEnd": "区间结束"
},
"strategyInfo": {
"title": "策略信息",
"market": "市场",
"interval": "周期",
"account": "账户",
"spreadMode": "价差模式",
"spreadDirection": "价差方向"
},
"periodSwitch": {
"mode": "周期切换模式",
"auto": "自动",
"manual": "手动",
"autoDesc": "周期结束时自动切换到最新周期",
"manualDesc": "周期结束时保留完整数据",
"switchToLatest": "切换到最新周期",
"periodEnded": "当前周期已结束",
"newPeriodAvailable": "新周期已开始"
},
"manualOrder": {
"title": "手动下单",
"buttonUp": "买入 Up",
"buttonDown": "买入 Down",
"confirmTitle": "手动下单确认",
"marketTitle": "市场标题",
"direction": "方向",
"directionUp": "Up",
"directionDown": "Down",
"orderPrice": "下单价格",
"orderSize": "下单数量",
"totalAmount": "总金额",
"account": "账户",
"cancel": "取消",
"confirm": "确认下单",
"orderUnit": "USDC",
"sizeUnit": "张",
"statusNotOrdered": "未下单",
"statusOrdered": "本周期已下单",
"statusOrderedAuto": "本周期已自动下单",
"statusOrderedManual": "本周期已手动下单",
"errorInsufficientBalance": "账户余额不足,可用余额:{{balance}} USDC",
"errorPriceOutOfRange": "价格必须在 0~1 之间",
"errorMinSize": "数量不能少于 1 张",
"errorExceedsBalance": "总金额超过可用余额",
"errorPriceRequired": "请输入下单价格",
"errorSizeRequired": "请输入下单数量",
"success": "手动下单成功",
"failed": "手动下单失败:{{reason}}",
"errorSigning": "签名失败:{{reason}}",
"errorNetwork": "网络错误,请稍后重试",
"priceNotLoaded": "价格数据未加载",
"insufficientBalance": "余额不足,可用金额少于 1 USDC",
"fetchBalanceFailed": "获取账户余额失败",
"availableBalance": "可用余额",
"fetchLatestPrice": "获取最新价",
"priceUpdated": "价格已更新",
"maxSize": "最大",
"invalidPriceOrBalance": "价格或余额无效",
"insufficientBalanceForMax": "余额不足以购买最大数量",
"maxSizeUpdated": "已更新为最大数量"
}
}
}
+151 -5
View File
@@ -312,7 +312,9 @@
"leaders": "Leader 管理",
"templates": "跟單模板",
"copyTradingConfig": "跟單配置",
"cryptoTailStrategy": "尾盤策略",
"cryptoSpreadStrategy": "加密價差策略",
"cryptoTailStrategy": "策略配置",
"cryptoTailMonitor": "即時監控",
"positions": "倉位管理",
"backtest": "回測",
"statistics": "統計信息",
@@ -418,6 +420,40 @@
"saveFailed": "保存自動贖回配置失敗"
}
},
"systemUpdate": {
"title": "系統更新",
"currentVersion": "當前版本",
"ready": "就緒",
"hasNewVersion": "發現新版本: {{version}}",
"alreadyLatest": "當前已是最新版本",
"checkFailed": "檢查更新失敗",
"confirmTitle": "確認更新",
"confirmContent1": "確定要更新到版本 {{version}} 嗎?",
"confirmContent2": "更新過程中系統將暫時不可用(約30-60秒)。",
"confirmContent3": "更新完成後頁面將自動刷新。",
"okText": "立即更新",
"cancelText": "取消",
"updateStarted": "更新已啟動,請稍候...",
"updateFailedWithMessage": "更新失敗: {{message}}",
"updateSuccessRefresh": "更新成功!頁面將在3秒後刷新...",
"needAdmin": "需要管理員權限才能執行更新",
"startFailed": "啟動更新失敗",
"updating": "系統正在更新",
"updateFailedTitle": "更新失敗",
"checkUpdate": "檢查更新",
"newVersionFound": "發現新版本",
"publishedAt": "發佈時間",
"releaseNotes": "更新內容",
"upgradeNow": "立即升級到 v{{version}}",
"usageTitle": "使用說明",
"usage1": "點擊「檢查更新」按鈕檢查是否有新版本",
"usage2": "更新過程約需30-60秒,期間系統將暫時不可用",
"usage3": "更新成功後頁面將自動刷新",
"usage4": "如果更新失敗,系統會自動回滾到當前版本",
"versionTooltipNew": "有新版本可用,點擊前往系統更新",
"versionTooltipLatest": "當前已是最新版本",
"prerelease": "預發佈"
},
"builderApiKey": {
"title": "Builder API Key 配置",
"alertTitle": "什麼是 Builder API Key",
@@ -1450,12 +1486,12 @@
"cryptoTailStrategy": {
"binanceApiAlert": {
"title": "無法連接幣安 API,策略暫時不能運行",
"description": "尾盤策略需要從幣安取得行情資料才能運作。目前連線失敗,可能是網路問題或幣安服務異常,請稍後點擊下方按鈕重新檢測。",
"description": "加密價差策略需要從幣安取得行情資料才能運作。目前連線失敗,可能是網路問題或幣安服務異常,請稍後點擊下方按鈕重新檢測。",
"recheck": "重新檢測"
},
"list": {
"title": "加密尾盤策略",
"walletTip": "請使用單獨的錢包運行尾盤策略,避免該錢包用於手動交易、跟單等其他操作,否則可能導致餘額或倉位變化,造成策略執行異常。",
"title": "加密價差策略",
"walletTip": "請使用單獨的錢包運行加密價差策略,避免該錢包用於手動交易、跟單等其他操作,否則可能導致餘額或倉位變化,造成策略執行異常。",
"addStrategy": "新增策略",
"strategyName": "策略名稱",
"account": "賬戶",
@@ -1512,7 +1548,7 @@
},
"redeemRequiredModal": {
"title": "請先配置自動贖回",
"description": "尾盤策略依賴自動贖回功能,請先在系統設置中配置 Builder API Key 並開啟自動贖回。",
"description": "加密價差策略依賴自動贖回功能,請先在系統設置中配置 Builder API Key 並開啟自動贖回。",
"goToSettings": "去配置",
"cancel": "取消"
},
@@ -1541,5 +1577,115 @@
"emptyFail": "暫無失敗記錄",
"totalCount": "共 {count} 條"
}
},
"cryptoTailMonitor": {
"title": "加密價差策略監控",
"selectStrategy": "選擇策略",
"selectStrategyPlaceholder": "請選擇要監控的策略",
"direction": "監控方向",
"directionUp": "Up",
"directionDown": "Down",
"noData": "請選擇一個策略開始監控",
"priceRange": "價格區間",
"timeWindow": "時間窗口",
"stat": {
"openPrice": "開盤價",
"currentPrice": "最新價",
"spread": "價差",
"remainingTime": "剩餘時間",
"configuredSpread": "配置價差",
"configuredSpreadMin": "最小價差",
"configuredSpreadMax": "最大價差",
"status": "狀態",
"minSpreadLine": "最小價差線",
"periodSpreadMinMax": "週期內價差",
"periodSpreadMin": "週期內最小價差",
"periodSpreadMax": "週期內最大價差",
"minSpread": "最小",
"maxSpread": "最大"
},
"status": {
"triggered": "已觸發",
"periodEnded": "週期結束",
"inCondition": "滿足條件",
"waiting": "等待中"
},
"chart": {
"title": "分時圖",
"btcTitle": "BTC 分時圖",
"marketTitle": "市場分時圖",
"priceChart": "價格分時圖",
"price": "價格",
"openPrice": "開盤價",
"spread": "價差",
"minSpreadLine": "最小價差線",
"maxSpreadLine": "最大價差線",
"marketUp": "Up",
"marketDown": "Down",
"time": "時間",
"latestPrice": "最新價",
"timeWindowStart": "區間開始",
"timeWindowEnd": "區間結束"
},
"strategyInfo": {
"title": "策略信息",
"market": "市場",
"interval": "週期",
"account": "賬戶",
"spreadMode": "價差模式",
"spreadDirection": "價差方向"
},
"periodSwitch": {
"mode": "週期切換模式",
"auto": "自動",
"manual": "手動",
"autoDesc": "週期結束時自動切換到最新週期",
"manualDesc": "週期結束時保留完整數據",
"switchToLatest": "切換到最新週期",
"periodEnded": "當前週期已結束",
"newPeriodAvailable": "新週期已開始"
},
"manualOrder": {
"title": "手動下單",
"buttonUp": "買入 Up",
"buttonDown": "買入 Down",
"confirmTitle": "手動下單確認",
"marketTitle": "市場標題",
"direction": "方向",
"directionUp": "Up",
"directionDown": "Down",
"orderPrice": "下單價格",
"orderSize": "下單數量",
"totalAmount": "總金額",
"account": "賬戶",
"cancel": "取消",
"confirm": "確認下單",
"orderUnit": "USDC",
"sizeUnit": "張",
"statusNotOrdered": "未下單",
"statusOrdered": "本週期已下單",
"statusOrderedAuto": "本週期已自動下單",
"statusOrderedManual": "本週期已手動下單",
"errorInsufficientBalance": "賬戶餘額不足,可用餘額:{balance} USDC",
"errorPriceOutOfRange": "價格必須在 0~1 之間",
"errorMinSize": "數量不能少於 1 張",
"errorExceedsBalance": "總金額超過可用餘額",
"errorPriceRequired": "請輸入下單價格",
"errorSizeRequired": "請輸入下單數量",
"success": "手動下單成功",
"failed": "手動下單失敗:{{reason}}",
"errorSigning": "簽名失敗:{reason}",
"errorNetwork": "網絡錯誤,請稍後重試",
"priceNotLoaded": "價格數據未加載",
"insufficientBalance": "餘額不足,可用金額少於 1 USDC",
"fetchBalanceFailed": "獲取賬戶餘額失敗",
"availableBalance": "可用餘額",
"fetchLatestPrice": "獲取最新價",
"priceUpdated": "價格已更新",
"maxSize": "最大",
"invalidPriceOrBalance": "價格或餘額無效",
"insufficientBalanceForMax": "餘額不足以購買最大數量",
"maxSizeUpdated": "已更新為最大數量"
}
}
}
File diff suppressed because it is too large Load Diff
@@ -26,7 +26,7 @@ import {
} from 'antd'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import { PlusOutlined, EditOutlined, UnorderedListOutlined, InfoCircleOutlined, WarningOutlined, CalendarOutlined, ArrowUpOutlined, ArrowDownOutlined, FileTextOutlined } from '@ant-design/icons'
import { PlusOutlined, EditOutlined, UnorderedListOutlined, InfoCircleOutlined, WarningOutlined, CalendarOutlined, FileTextOutlined } from '@ant-design/icons'
import { useTranslation } from 'react-i18next'
import { useMediaQuery } from 'react-responsive'
import { apiService } from '../services/api'
@@ -555,7 +555,7 @@ const CryptoTailStrategyList: React.FC = () => {
{t('cryptoTailStrategy.list.configGuide')}
</Button>
</div>
{binanceUnhealthy.length > 0 && (
{binanceUnhealthy.length > 0 && list.some((s) => s.enabled) && (
<Alert
type="error"
showIcon
@@ -960,9 +960,9 @@ const CryptoTailStrategyList: React.FC = () => {
align: 'center',
render: (i: number) =>
i === 0 ? (
<Tag icon={<ArrowUpOutlined />} color="green">{t('cryptoTailStrategy.triggerRecords.up')}</Tag>
<Tag color="green">{t('cryptoTailStrategy.triggerRecords.up')}</Tag>
) : (
<Tag icon={<ArrowDownOutlined />} color="volcano">{t('cryptoTailStrategy.triggerRecords.down')}</Tag>
<Tag color="volcano">{t('cryptoTailStrategy.triggerRecords.down')}</Tag>
)
},
{
@@ -1035,9 +1035,9 @@ const CryptoTailStrategyList: React.FC = () => {
align: 'center',
render: (i: number) =>
i === 0 ? (
<Tag icon={<ArrowUpOutlined />} color="green">{t('cryptoTailStrategy.triggerRecords.up')}</Tag>
<Tag color="green">{t('cryptoTailStrategy.triggerRecords.up')}</Tag>
) : (
<Tag icon={<ArrowDownOutlined />} color="volcano">{t('cryptoTailStrategy.triggerRecords.down')}</Tag>
<Tag color="volcano">{t('cryptoTailStrategy.triggerRecords.down')}</Tag>
)
},
{
+44 -42
View File
@@ -6,6 +6,7 @@ import {
CheckCircleOutlined,
ExclamationCircleOutlined
} from '@ant-design/icons'
import { useTranslation } from 'react-i18next'
import { apiClient } from '../services/api'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
@@ -29,13 +30,14 @@ interface UpdateStatus {
}
const SystemUpdate: React.FC = () => {
const { t, i18n } = useTranslation()
const [currentVersion, setCurrentVersion] = useState('')
const [updateChecking, setUpdateChecking] = useState(false)
const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null)
const [updateStatus, setUpdateStatus] = useState<UpdateStatus>({
updating: false,
progress: 0,
message: '就绪',
message: '',
error: null
})
@@ -62,7 +64,7 @@ const SystemUpdate: React.FC = () => {
setUpdateStatus({
updating: response.data.data.updating,
progress: response.data.data.progress || 0,
message: response.data.data.message || '就绪',
message: response.data.data.message || '',
error: response.data.data.error || null
})
}
@@ -83,15 +85,15 @@ const SystemUpdate: React.FC = () => {
setUpdateInfo(data.data)
if (data.data.hasUpdate) {
message.success(`发现新版本: ${data.data.latestVersion}`)
message.success(t('systemUpdate.hasNewVersion', { version: data.data.latestVersion }))
} else {
message.info('当前已是最新版本')
message.info(t('systemUpdate.alreadyLatest'))
}
} else {
message.error(data.message || '检查更新失败')
message.error(data.message || t('systemUpdate.checkFailed'))
}
} catch (error: any) {
message.error(error.message || '检查更新失败')
message.error(error.message || t('systemUpdate.checkFailed'))
} finally {
setUpdateChecking(false)
}
@@ -99,25 +101,25 @@ const SystemUpdate: React.FC = () => {
const handleExecuteUpdate = () => {
Modal.confirm({
title: '确认更新',
title: t('systemUpdate.confirmTitle'),
icon: <ExclamationCircleOutlined />,
content: (
<div>
<p> <strong>{updateInfo?.latestVersion}</strong> </p>
<p>30-60</p>
<p></p>
<p>{t('systemUpdate.confirmContent1', { version: updateInfo?.latestVersion })}</p>
<p>{t('systemUpdate.confirmContent2')}</p>
<p>{t('systemUpdate.confirmContent3')}</p>
</div>
),
okText: '立即更新',
okText: t('systemUpdate.okText'),
okType: 'primary',
cancelText: '取消',
cancelText: t('systemUpdate.cancelText'),
onOk: async () => {
try {
const response = await apiClient.post('/update/update', {})
const data = response.data
if (data.code === 0) {
message.success('更新已启动,请稍候...')
message.success(t('systemUpdate.updateStarted'))
// 开始轮询更新状态
const pollInterval = setInterval(async () => {
@@ -138,9 +140,9 @@ const SystemUpdate: React.FC = () => {
clearInterval(pollInterval)
if (statusData.data.error) {
message.error(`更新失败: ${statusData.data.error}`)
message.error(t('systemUpdate.updateFailedWithMessage', { message: statusData.data.error }))
} else if (statusData.data.progress === 100) {
message.success('更新成功!页面将在3秒后刷新...')
message.success(t('systemUpdate.updateSuccessRefresh'))
setTimeout(() => window.location.reload(), 3000)
}
}
@@ -153,19 +155,19 @@ const SystemUpdate: React.FC = () => {
// 5分钟后停止轮询
setTimeout(() => clearInterval(pollInterval), 5 * 60 * 1000)
} else if (data.code === 403) {
message.error('需要管理员权限才能执行更新')
message.error(t('systemUpdate.needAdmin'))
} else {
message.error(data.message || '启动更新失败')
message.error(data.message || t('systemUpdate.startFailed'))
}
} catch (error: any) {
message.error(error.message || '启动更新失败')
message.error(error.message || t('systemUpdate.startFailed'))
}
}
})
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString('zh-CN')
return new Date(dateString).toLocaleString(i18n.language === 'zh-CN' ? 'zh-CN' : i18n.language === 'zh-TW' ? 'zh-TW' : 'en')
}
return (
@@ -173,7 +175,7 @@ const SystemUpdate: React.FC = () => {
title={
<Space>
<CloudUploadOutlined style={{ fontSize: '18px', color: '#1890ff' }} />
<span style={{ fontSize: '16px', fontWeight: 600 }}></span>
<span style={{ fontSize: '16px', fontWeight: 600 }}>{t('systemUpdate.title')}</span>
</Space>
}
style={{
@@ -195,7 +197,7 @@ const SystemUpdate: React.FC = () => {
}}>
<div>
<div style={{ fontSize: '13px', opacity: 0.9, marginBottom: '4px' }}>
{t('systemUpdate.currentVersion')}
</div>
<div style={{ fontSize: '20px', fontWeight: 600 }}>
v{currentVersion || 'unknown'}
@@ -208,16 +210,16 @@ const SystemUpdate: React.FC = () => {
{updateStatus.updating && (
<Alert
message={
<span style={{ fontSize: '15px', fontWeight: 500 }}></span>
<span style={{ fontSize: '15px', fontWeight: 500 }}>{t('systemUpdate.updating')}</span>
}
description={
<div style={{ marginTop: '12px' }}>
<div style={{
marginBottom: '12px',
fontSize: '14px',
color: '#595959'
color: '#595959'
}}>
{updateStatus.message}
{updateStatus.message || t('systemUpdate.ready')}
</div>
<Progress
percent={updateStatus.progress}
@@ -245,7 +247,7 @@ const SystemUpdate: React.FC = () => {
{updateStatus.error && (
<Alert
message={<span style={{ fontSize: '15px', fontWeight: 500 }}></span>}
message={<span style={{ fontSize: '15px', fontWeight: 500 }}>{t('systemUpdate.updateFailedTitle')}</span>}
description={
<div style={{
marginTop: '8px',
@@ -281,14 +283,14 @@ const SystemUpdate: React.FC = () => {
boxShadow: '0 2px 4px rgba(24, 144, 255, 0.2)'
}}
>
{t('systemUpdate.checkUpdate')}
</Button>
{updateInfo && !updateInfo.hasUpdate && (
<Alert
message={
<span style={{ fontSize: '15px', fontWeight: 500 }}>
{t('systemUpdate.alreadyLatest')}
</span>
}
type="success"
@@ -326,7 +328,7 @@ const SystemUpdate: React.FC = () => {
color: '#8c8c8c',
marginBottom: '6px'
}}>
{t('systemUpdate.newVersionFound')}
</div>
<Space size="small">
<Tag
@@ -341,15 +343,15 @@ const SystemUpdate: React.FC = () => {
v{updateInfo.latestVersion}
</Tag>
{updateInfo.prerelease && (
<Tag
color="orange"
style={{
<Tag
color="orange"
style={{
fontSize: '12px',
padding: '4px 12px',
borderRadius: '4px'
}}
>
Pre-release
{t('systemUpdate.prerelease')}
</Tag>
)}
</Space>
@@ -367,7 +369,7 @@ const SystemUpdate: React.FC = () => {
color: '#8c8c8c',
marginBottom: '4px'
}}>
{t('systemUpdate.publishedAt')}
</div>
<div style={{
fontSize: '14px',
@@ -385,7 +387,7 @@ const SystemUpdate: React.FC = () => {
marginBottom: '8px',
fontWeight: 500
}}>
{t('systemUpdate.releaseNotes')}
</div>
<div style={{
padding: '16px',
@@ -449,7 +451,7 @@ const SystemUpdate: React.FC = () => {
boxShadow: '0 4px 12px rgba(102, 126, 234, 0.4)'
}}
>
v{updateInfo.latestVersion}
{t('systemUpdate.upgradeNow', { version: updateInfo.latestVersion })}
</Button>
</div>
)}
@@ -458,20 +460,20 @@ const SystemUpdate: React.FC = () => {
{!updateStatus.updating && !(updateInfo && updateInfo.hasUpdate) && (
<Alert
message={
<span style={{ fontSize: '15px', fontWeight: 500 }}>使</span>
<span style={{ fontSize: '15px', fontWeight: 500 }}>{t('systemUpdate.usageTitle')}</span>
}
description={
<ul style={{
marginBottom: 0,
<ul style={{
marginBottom: 0,
paddingLeft: '20px',
fontSize: '14px',
color: '#595959',
lineHeight: '1.8'
}}>
<li>"检查更新"</li>
<li>30-60</li>
<li></li>
<li></li>
<li>{t('systemUpdate.usage1')}</li>
<li>{t('systemUpdate.usage2')}</li>
<li>{t('systemUpdate.usage3')}</li>
<li>{t('systemUpdate.usage4')}</li>
</ul>
}
type="info"
+15 -3
View File
@@ -446,7 +446,7 @@ export const apiService = {
},
/**
* API
* API
*/
cryptoTailStrategy: {
list: (data: { accountId?: number; enabled?: boolean } = {}) =>
@@ -497,9 +497,21 @@ export const apiService = {
marketOptions: () =>
apiClient.post<ApiResponse<import('../types').CryptoTailMarketOptionDto[]>>('/crypto-tail-strategy/market-options', {}),
autoMinSpread: (data: { intervalSeconds: number }) =>
apiClient.post<ApiResponse<import('../types').CryptoTailAutoMinSpreadResponse>>('/crypto-tail-strategy/auto-min-spread', data)
apiClient.post<ApiResponse<import('../types').CryptoTailAutoMinSpreadResponse>>('/crypto-tail-strategy/auto-min-spread', data),
monitorInit: (data: { strategyId: number; periodStartUnix?: number }) =>
apiClient.post<ApiResponse<import('../types').CryptoTailMonitorInitResponse>>('/crypto-tail-strategy/monitor/init', data),
manualOrder: (data: {
strategyId: number
periodStartUnix: number
direction: 'UP' | 'DOWN'
price: string
size: string
marketTitle: string
tokenIds: string[]
}) =>
apiClient.post<ApiResponse<import('../types').CryptoTailManualOrderResponse>>('/crypto-tail-strategy/manual-order', data)
},
/**
* API
*/
+127 -3
View File
@@ -1036,7 +1036,7 @@ export interface BacktestTaskDto {
}
/**
*
*
*/
export interface CryptoTailStrategyDto {
id: number
@@ -1076,7 +1076,7 @@ export interface CryptoTailAutoMinSpreadResponse {
}
/**
*
*
*/
export interface CryptoTailStrategyTriggerDto {
id: number
@@ -1098,7 +1098,7 @@ export interface CryptoTailStrategyTriggerDto {
}
/**
*
*
*/
export interface CryptoTailMarketOptionDto {
slug: string
@@ -1107,3 +1107,127 @@ export interface CryptoTailMarketOptionDto {
periodStartUnix: number
endDate?: string
}
/**
*
*/
export interface CryptoTailMonitorInitResponse {
/** 策略ID */
strategyId: number
/** 策略名称 */
name: string
/** 账户ID */
accountId: number
/** 账户名称 */
accountName: string
/** 市场 slug 前缀 */
marketSlugPrefix: string
/** 市场标题 */
marketTitle: string
/** 周期秒数 (300=5m, 900=15m) */
intervalSeconds: number
/** 当前周期开始时间 (Unix 秒) */
periodStartUnix: number
/** 时间窗口开始秒数 */
windowStartSeconds: number
/** 时间窗口结束秒数 */
windowEndSeconds: number
/** 最低价格 */
minPrice: string
/** 最高价格 */
maxPrice: string
/** 最小价差模式: NONE, FIXED, AUTO */
minSpreadMode: string
/** 价差方向: MIN(显示周期内最小价差), MAX(显示周期内最大价差) */
spreadDirection?: string
/** 最小价差数值 (FIXED 时有值) */
minSpreadValue?: string
/** 自动计算的最小价差 (Up方向) */
autoMinSpreadUp?: string
/** 自动计算的最小价差 (Down方向) */
autoMinSpreadDown?: string
/** BTC 开盘价 USDC(来自币安 K 线) */
openPriceBtc?: string
/** Up tokenId */
tokenIdUp?: string
/** Down tokenId */
tokenIdDown?: string
/** 当前时间 (毫秒时间戳) */
currentTimestamp: number
/** 是否启用 */
enabled: boolean
/** 投入金额模式: FIXED or RATIO */
amountMode?: string
/** 投入金额数值 */
amountValue?: string
}
/**
*
*/
export interface CryptoTailMonitorPushData {
/** 策略ID */
strategyId: number
/** 推送时间 (毫秒时间戳) */
timestamp: number
/** 当前周期开始时间 (Unix 秒) */
periodStartUnix: number
/** 当前周期市场标题(周期切换时更新) */
marketTitle?: string
/** 当前价格 (Up方向,来自订单簿) */
currentPriceUp?: string
/** 当前价格 (Down方向,来自订单簿) */
currentPriceDown?: string
/** 当前价差 (Up方向: 1 - currentPriceUp) */
spreadUp?: string
/** 当前价差 (Down方向: currentPriceUp) */
spreadDown?: string
/** 最小价差线 (Up方向,USDC) */
minSpreadLineUp?: string
/** 最小价差线 (Down方向,USDC) */
minSpreadLineDown?: string
/** BTC 开盘价 USDC */
openPriceBtc?: string
/** BTC 最新价 USDC */
currentPriceBtc?: string
/** BTC 价差 USDCcurrentPriceBtc - openPriceBtc */
spreadBtc?: string
/** 周期剩余秒数 */
remainingSeconds: number
/** 是否在时间窗口内 */
inTimeWindow: boolean
/** 是否在价格区间内 (Up方向) */
inPriceRangeUp: boolean
/** 是否在价格区间内 (Down方向) */
inPriceRangeDown: boolean
/** 是否已触发 */
triggered: boolean
/** 触发方向: UP, DOWN, null */
triggerDirection?: string
/** 周期是否已结束 */
periodEnded: boolean
}
export interface CryptoTailManualOrderResponse {
/** 是否成功 */
success: boolean
/** 订单ID */
orderId?: string
/** 提示消息 */
message: string
/** 下单详情 */
orderDetails?: ManualOrderDetails
}
export interface ManualOrderDetails {
/** 策略ID */
strategyId: number
/** 方向 */
direction: string
/** 下单价格 */
price: string
/** 下单数量 */
size: string
/** 总金额 */
totalAmount: string
}