Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e48149a19b | |||
| c0e0942404 | |||
| 6b8c11f171 | |||
| 3e667b70fd | |||
| 2bb8cbc564 | |||
| 8b73121c5d | |||
| 95930332df | |||
| 185cade11d | |||
| d9443e0d56 | |||
| a097376db7 | |||
| 6e5ccdfe5c | |||
| 21da06d8b0 | |||
| 5a83444b56 | |||
| 591e678f73 | |||
| 1cfdcb88d3 | |||
| 2cc9cf82ba | |||
| 00f0898d98 | |||
| 1de9b5e958 | |||
| c8e422a94b | |||
| 60e9f9235d | |||
| 46baa416f4 | |||
| ecdb8af14a | |||
| d6027e48eb | |||
| eb45013a93 | |||
| f97bd5b9d9 | |||
| df272156cf | |||
| 502b4fb0b7 | |||
| 64f6a2b897 | |||
| f7f2411b9d | |||
| d96eb3e00a | |||
| cc1a732984 | |||
| ec06003157 | |||
| 3d05b13298 | |||
| fe2db11b75 | |||
| 5c18cbd95d | |||
| ad2fa4eef2 | |||
| 8357546f3c | |||
| a62141ea5e | |||
| 9157203653 | |||
| 23fc20763a | |||
| e96a0b6279 | |||
| 85d8619fe7 | |||
| 89fb980da7 | |||
| 9f0b22fab5 | |||
| b5908a9bbf |
@@ -36,6 +36,49 @@ jobs:
|
||||
echo "Extracted version: $VERSION"
|
||||
echo "Full tag: $TAG_NAME"
|
||||
|
||||
- name: Send Telegram notification (build started)
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
run: |
|
||||
# 检查必要的环境变量
|
||||
if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then
|
||||
echo "⚠️ Telegram Bot Token 或 Chat ID 未配置,跳过通知"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 获取构建信息
|
||||
VERSION="${{ steps.extract_version.outputs.VERSION }}"
|
||||
TAG="${{ steps.extract_version.outputs.TAG }}"
|
||||
RELEASE_URL="${{ github.event.release.html_url }}"
|
||||
|
||||
# 构建消息内容(仅包含关键信息)
|
||||
MESSAGE="🔨 <b>Docker 镜像构建中</b>"$'\n'$'\n'"📦 <b>版本:</b> ${VERSION}"$'\n'"🏷️ <b>Tag:</b> <code>${TAG}</code>"$'\n'"🔗 <a href=\"${RELEASE_URL}\">查看 Release</a>"
|
||||
|
||||
# 发送 Telegram 消息(使用 jq 转义 JSON)
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n \
|
||||
--arg chat_id "$TELEGRAM_CHAT_ID" \
|
||||
--arg text "$MESSAGE" \
|
||||
'{chat_id: $chat_id, text: $text, parse_mode: "HTML", disable_web_page_preview: false}')" > /tmp/telegram_response.json
|
||||
|
||||
# 检查发送结果
|
||||
if [ $? -eq 0 ]; then
|
||||
RESPONSE=$(cat /tmp/telegram_response.json)
|
||||
if echo "$RESPONSE" | grep -q '"ok":true'; then
|
||||
echo "✅ Telegram 通知发送成功"
|
||||
else
|
||||
echo "❌ Telegram 通知发送失败: $RESPONSE"
|
||||
# 通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
echo "❌ 发送 Telegram 消息时发生错误"
|
||||
# 通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
@@ -65,3 +108,49 @@ jobs:
|
||||
GITHUB_REPO_URL=https://github.com/WrBug/PolyHermes
|
||||
cache-from: type=registry,ref=wrbug/polyhermes:latest
|
||||
cache-to: type=inline
|
||||
|
||||
- name: Send Telegram notification
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
run: |
|
||||
# 检查必要的环境变量
|
||||
if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then
|
||||
echo "⚠️ Telegram Bot Token 或 Chat ID 未配置,跳过通知"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 获取构建信息
|
||||
VERSION="${{ steps.extract_version.outputs.VERSION }}"
|
||||
TAG="${{ steps.extract_version.outputs.TAG }}"
|
||||
RELEASE_NAME="${{ github.event.release.name }}"
|
||||
RELEASE_URL="${{ github.event.release.html_url }}"
|
||||
REPO_NAME="${{ github.repository }}"
|
||||
|
||||
# 构建消息内容(仅包含关键信息)
|
||||
DEPLOY_DOC_URL="https://github.com/WrBug/PolyHermes/blob/main/docs/zh/DEPLOYMENT.md"
|
||||
MESSAGE="✅ <b>Docker 镜像构建成功</b>"$'\n'$'\n'"📦 <b>版本:</b> ${VERSION}"$'\n'"🏷️ <b>Tag:</b> <code>${TAG}</code>"$'\n'"🔗 <a href=\"${RELEASE_URL}\">查看 Release</a>"$'\n'"📚 <a href=\"${DEPLOY_DOC_URL}\">Docker 部署文档</a>"
|
||||
|
||||
# 发送 Telegram 消息(使用 jq 转义 JSON)
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n \
|
||||
--arg chat_id "$TELEGRAM_CHAT_ID" \
|
||||
--arg text "$MESSAGE" \
|
||||
'{chat_id: $chat_id, text: $text, parse_mode: "HTML", disable_web_page_preview: false}')" > /tmp/telegram_response.json
|
||||
|
||||
# 检查发送结果
|
||||
if [ $? -eq 0 ]; then
|
||||
RESPONSE=$(cat /tmp/telegram_response.json)
|
||||
if echo "$RESPONSE" | grep -q '"ok":true'; then
|
||||
echo "✅ Telegram 通知发送成功"
|
||||
else
|
||||
echo "❌ Telegram 通知发送失败: $RESPONSE"
|
||||
# 构建成功,通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
echo "❌ 发送 Telegram 消息时发生错误"
|
||||
# 构建成功,通知失败不应该导致整个 job 失败
|
||||
exit 0
|
||||
fi
|
||||
@@ -0,0 +1,103 @@
|
||||
name: Telegram Notification on PR Merge
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- closed # 当 PR 被关闭(合并或关闭)时触发
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# 只在 PR 被合并到 main 分支时执行
|
||||
if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'main'
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get PR details
|
||||
id: pr_details
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
PR_NUMBER="${{ github.event.pull_request.number }}"
|
||||
REPO="${{ github.repository }}"
|
||||
|
||||
# 获取 PR 详细信息
|
||||
PR_RESPONSE=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${REPO}/pulls/${PR_NUMBER}")
|
||||
|
||||
# 获取 PR 变更的文件列表
|
||||
FILES_RESPONSE=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${REPO}/pulls/${PR_NUMBER}/files")
|
||||
|
||||
# 提取 PR 描述(body),保留换行,限制长度
|
||||
PR_BODY=$(echo "$PR_RESPONSE" | jq -r '.body // ""')
|
||||
if [ ${#PR_BODY} -gt 500 ]; then
|
||||
PR_BODY="${PR_BODY:0:500}..."
|
||||
fi
|
||||
|
||||
# 保存到输出变量(使用 base64 编码避免特殊字符问题)
|
||||
echo "pr_body<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$PR_BODY" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Send Telegram notification
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
run: |
|
||||
# 检查 PR 是否被合并(而不是仅关闭)
|
||||
PR_MERGED="${{ github.event.pull_request.merged }}"
|
||||
if [ "$PR_MERGED" != "true" ]; then
|
||||
echo "ℹ️ PR 仅关闭,未合并,跳过通知"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 检查必要的环境变量
|
||||
# 注意:TELEGRAM_CHAT_ID 可以是个人聊天 ID(正数)或群组 ID(负数,如 -1001234567890)
|
||||
if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then
|
||||
echo "⚠️ Telegram Bot Token 或 Chat ID 未配置,跳过通知"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 获取 PR 基本信息
|
||||
PR_NUMBER="${{ github.event.pull_request.number }}"
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
PR_URL="${{ github.event.pull_request.html_url }}"
|
||||
PR_MERGE_COMMIT="${{ github.event.pull_request.merge_commit_sha }}"
|
||||
|
||||
# 获取 PR 详细信息
|
||||
PR_BODY="${{ steps.pr_details.outputs.pr_body }}"
|
||||
|
||||
# 转义 PR 标题中的 HTML 特殊字符
|
||||
PR_TITLE_ESCAPED=$(echo "$PR_TITLE" | sed 's/&/\&/g' | sed 's/</\</g' | sed 's/>/\>/g')
|
||||
|
||||
# 构建消息内容(仅包含关键信息)
|
||||
MESSAGE="🚀 <b>main 分支代码更新</b>"$'\n'$'\n'"📝 <b>PR #${PR_NUMBER}:</b> ${PR_TITLE_ESCAPED}"$'\n'"🔗 <a href=\"${PR_URL}\">查看 PR</a>"
|
||||
|
||||
# 发送 Telegram 消息(使用 jq 转义 JSON)
|
||||
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n \
|
||||
--arg chat_id "$TELEGRAM_CHAT_ID" \
|
||||
--arg text "$MESSAGE" \
|
||||
'{chat_id: $chat_id, text: $text, parse_mode: "HTML", disable_web_page_preview: false}')" > /tmp/telegram_response.json
|
||||
|
||||
# 检查发送结果
|
||||
if [ $? -eq 0 ]; then
|
||||
RESPONSE=$(cat /tmp/telegram_response.json)
|
||||
if echo "$RESPONSE" | grep -q '"ok":true'; then
|
||||
echo "✅ Telegram 通知发送成功"
|
||||
else
|
||||
echo "❌ Telegram 通知发送失败: $RESPONSE"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "❌ 发送 Telegram 消息时发生错误"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
# 🎉 v1.0.1 版本发布公告
|
||||
|
||||
## 📅 发布日期
|
||||
|
||||
2025年12月(具体日期待定)
|
||||
|
||||
## 🚀 主要更新
|
||||
|
||||
### 性能优化
|
||||
|
||||
#### 📊 订单簿请求优化
|
||||
- 优化订单簿获取逻辑,仅在需要时请求,避免不必要的 API 调用
|
||||
- 当未配置需要订单簿的过滤条件(价差、订单深度)时,跳过订单簿获取
|
||||
- 订单簿只请求一次,在过滤检查中复用,提高性能
|
||||
|
||||
#### 💰 卖出价格计算优化
|
||||
- 卖出改为市价卖出:优先使用订单簿的 bestBid(最高买入价)
|
||||
- 如果 bestBid 获取失败,自动降级使用 Leader 的交易价格
|
||||
- 卖出价格固定按 90% 计算,不再使用价格容忍度配置
|
||||
- 提高卖出订单的成交率
|
||||
|
||||
#### ⚙️ 价格容忍度默认值
|
||||
- 如果价格容忍度配置为 0,自动使用默认值 5%
|
||||
- 确保买入订单能够正常应用价格调整,提高成交率
|
||||
|
||||
### 代码优化
|
||||
|
||||
#### 🎯 使用枚举优化过滤逻辑
|
||||
- 新增 `FilterResult` 数据类和 `FilterStatus` 枚举
|
||||
- 使用类型安全的枚举替代字符串判断,提高代码可维护性
|
||||
- 移除无用字段 `isBuyOrder` 参数
|
||||
- 优化 `checkFilters` 方法返回值,使用数据类封装结果
|
||||
|
||||
#### 📝 代码结构优化
|
||||
- 减少 if-else 嵌套,使用 Kotlin 链式调用和空安全操作符
|
||||
- 优化卖出价格计算逻辑,使用 `runCatching` 和 `?.let` 简化代码
|
||||
- 提取公共方法 `calculateFallbackSellPrice`,提高代码复用性
|
||||
|
||||
### 功能改进
|
||||
|
||||
#### 🗑️ 移除最小订单簿深度功能
|
||||
- 移除 `minOrderbookDepth`(最小订单簿深度)配置项
|
||||
- 简化过滤逻辑,只保留 `minOrderDepth`(最小订单深度)
|
||||
- 更新前端界面,移除相关配置项和提示文案
|
||||
|
||||
#### 📈 优化最小订单深度逻辑
|
||||
- 修改 `minOrderDepth` 检查逻辑,检查所有方向(买盘+卖盘)的总深度
|
||||
- 不再区分买卖方向,提供更全面的市场流动性评估
|
||||
|
||||
#### 🎯 市场结算判断优化
|
||||
- 添加市场已关闭时的结算判断逻辑
|
||||
- 如果市场已关闭且该 outcome 赢了(价格 >= 0.99),返回价格为 1
|
||||
- 如果市场已关闭且该 outcome 输了(价格 <= 0.01),返回价格为 0
|
||||
- 当没有仓位但有未完成订单时,正确判断市场结算状态并设置价格
|
||||
|
||||
### Bug 修复
|
||||
|
||||
- ✅ 修复盈亏和持仓价值计算逻辑未实现的问题
|
||||
- ✅ 修复过滤检查中订单簿可能重复请求的问题
|
||||
- ✅ 修复健康检查路径不一致问题(从 `/api/health` 改为 `/api/system/health`)
|
||||
|
||||
## 📦 如何更新
|
||||
|
||||
### Docker 部署
|
||||
|
||||
```bash
|
||||
# 拉取最新镜像
|
||||
docker pull wrbug/polyhermes:v1.0.1
|
||||
|
||||
# 或使用 latest 标签
|
||||
docker pull wrbug/polyhermes:latest
|
||||
|
||||
# 重启容器
|
||||
docker-compose down
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
### 源码部署
|
||||
|
||||
```bash
|
||||
# 拉取最新代码
|
||||
git fetch origin
|
||||
git checkout v1.0.1
|
||||
|
||||
# 重新构建
|
||||
cd backend
|
||||
./gradlew bootJar
|
||||
|
||||
# 重启服务
|
||||
# 根据您的部署方式重启服务
|
||||
```
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 更新前端多语言文案,优化提示信息
|
||||
- 移除最小订单簿深度相关的文档说明
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.0.1
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.0.0...v1.0.1
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.0.1
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:加入群组
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
**💬 如有问题或建议,欢迎在 GitHub Issues 中反馈。**
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
# 🎉 v1.1.0 版本更新指南
|
||||
|
||||
## 📅 发布日期
|
||||
|
||||
2025年12月26日
|
||||
|
||||
## 🎯 这次更新对您意味着什么?
|
||||
|
||||
### ⚡ 更快的跟单响应速度
|
||||
- **实时链上监听**:通过 WebSocket 实时监听链上交易,跟单响应速度提升 50% 以上
|
||||
- **双重保障**:链上监听和轮询同时运行,确保不错过任何交易机会
|
||||
- **自动去重**:系统自动处理重复数据,确保每笔交易只执行一次
|
||||
|
||||
### 💰 更准确的盈亏统计
|
||||
- **实际成交价追踪**:系统会自动更新卖出订单的实际成交价,而不是下单时的价格
|
||||
- **自动价格更新**:每 5 秒自动查询并更新订单的实际成交价
|
||||
- **精确盈亏计算**:基于实际成交价计算盈亏,统计数据更准确
|
||||
|
||||
### 🔧 更灵活的系统配置
|
||||
- **RPC 节点管理**:可以添加、编辑、删除自定义 RPC 节点
|
||||
- **节点启用/禁用**:可以随时启用或禁用节点,无需删除配置
|
||||
- **智能节点选择**:系统自动选择可用的节点,禁用的节点会被忽略
|
||||
|
||||
### 🐛 问题修复
|
||||
- **修复卖出订单失败问题**:修复了部分情况下卖出订单因 API 凭证问题导致的失败
|
||||
- **修复订单精度错误**:修复了卖出订单因精度问题导致的 API 错误
|
||||
|
||||
## 📦 如何更新
|
||||
|
||||
### 方式一:使用 Docker(推荐)
|
||||
|
||||
#### 步骤 1:备份数据(强烈推荐)
|
||||
|
||||
**备份不是必须的,但强烈推荐!**
|
||||
|
||||
**为什么需要备份?**
|
||||
- Docker 更新不会删除数据(数据存储在独立的数据卷中)
|
||||
- 但数据库结构可能会变更(本次更新会添加 `price_updated` 字段)
|
||||
- 如果迁移失败或出现问题,备份可以帮助恢复数据
|
||||
- 生产环境建议必须备份,开发环境可以跳过
|
||||
|
||||
**如何备份?**
|
||||
|
||||
```bash
|
||||
# 方式 1:使用 mysqldump 备份数据库(推荐)
|
||||
docker exec polyhermes-mysql mysqldump -u root -p polyhermes > backup_$(date +%Y%m%d_%H%M%S).sql
|
||||
|
||||
# 方式 2:备份整个 MySQL 数据卷
|
||||
docker run --rm -v polyhermes_mysql-data:/data -v $(pwd):/backup alpine tar czf /backup/mysql_backup_$(date +%Y%m%d_%H%M%S).tar.gz /data
|
||||
|
||||
# 方式 3:如果已有定期备份,可以跳过此步骤
|
||||
```
|
||||
|
||||
**什么情况下可以跳过备份?**
|
||||
- ✅ 开发环境或测试环境
|
||||
- ✅ 数据不重要或可以重新生成
|
||||
- ✅ 已经有定期自动备份
|
||||
- ✅ 确定迁移不会失败(查看更新日志确认)
|
||||
|
||||
**什么情况下必须备份?**
|
||||
- ⚠️ 生产环境
|
||||
- ⚠️ 包含重要交易数据
|
||||
- ⚠️ 不确定迁移是否安全
|
||||
|
||||
#### 步骤 2:停止当前服务
|
||||
|
||||
```bash
|
||||
# 进入部署目录
|
||||
cd /path/to/polyhermes
|
||||
|
||||
# 停止服务
|
||||
docker-compose -f docker-compose.prod.yml down
|
||||
```
|
||||
|
||||
#### 步骤 3:拉取新版本
|
||||
|
||||
```bash
|
||||
# 拉取 v1.1.0 版本
|
||||
docker pull wrbug/polyhermes:v1.1.0
|
||||
|
||||
# 或者拉取最新版本(推荐)
|
||||
docker pull wrbug/polyhermes:latest
|
||||
```
|
||||
|
||||
#### 步骤 4:更新配置(如果需要)
|
||||
|
||||
如果您想固定使用 v1.1.0 版本,可以编辑 `docker-compose.prod.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
image: wrbug/polyhermes:v1.1.0 # 修改这里
|
||||
```
|
||||
|
||||
#### 步骤 5:启动服务
|
||||
|
||||
```bash
|
||||
# 启动服务
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
|
||||
# 查看日志,确认服务正常启动
|
||||
docker-compose -f docker-compose.prod.yml logs -f
|
||||
```
|
||||
|
||||
#### 步骤 6:验证更新
|
||||
|
||||
1. 访问系统首页,查看页面标题是否显示 `v1.1.0`
|
||||
2. 检查系统功能是否正常
|
||||
3. 查看日志是否有错误信息
|
||||
|
||||
### 方式二:一键更新脚本
|
||||
|
||||
如果您使用 `latest` 标签,可以使用以下命令一键更新:
|
||||
|
||||
```bash
|
||||
# 进入部署目录
|
||||
cd /path/to/polyhermes
|
||||
|
||||
# 拉取最新镜像并重启
|
||||
docker-compose -f docker-compose.prod.yml pull
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
|
||||
# 查看日志
|
||||
docker-compose -f docker-compose.prod.yml logs -f
|
||||
```
|
||||
|
||||
## ⚠️ 更新注意事项
|
||||
|
||||
### 1. 数据库迁移
|
||||
- 本次更新会自动执行数据库迁移(添加 `price_updated` 字段)
|
||||
- 迁移过程不会影响现有数据,只是添加新字段
|
||||
- 迁移是安全的,但如果迁移失败,请检查数据库权限和连接
|
||||
- **如果迁移失败,可以使用备份恢复数据**
|
||||
|
||||
### 2. 服务中断时间
|
||||
- 更新过程中服务会短暂中断(通常 1-2 分钟)
|
||||
- 建议在低峰期进行更新
|
||||
- 更新期间正在进行的跟单操作可能会受影响
|
||||
|
||||
### 3. 配置检查
|
||||
- 更新后请检查 RPC 节点配置是否正确
|
||||
- 如果使用自定义 RPC 节点,请确认节点状态正常
|
||||
|
||||
### 4. 功能验证
|
||||
更新后建议验证以下功能:
|
||||
- ✅ 跟单功能是否正常
|
||||
- ✅ 订单价格更新是否正常
|
||||
- ✅ RPC 节点管理是否正常
|
||||
- ✅ 盈亏统计是否准确
|
||||
|
||||
## 🆕 新功能使用指南
|
||||
|
||||
### 1. RPC 节点管理
|
||||
|
||||
#### 如何添加自定义 RPC 节点?
|
||||
|
||||
1. 登录系统,进入 **系统设置** → **RPC 节点设置**
|
||||
2. 点击 **添加节点** 按钮
|
||||
3. 填写节点信息:
|
||||
- **节点名称**:给节点起个名字(如:Alchemy Polygon)
|
||||
- **RPC URL**:节点的 HTTP/HTTPS 地址
|
||||
- **启用状态**:默认启用,可以稍后禁用
|
||||
4. 点击 **保存**
|
||||
|
||||
#### 如何启用/禁用节点?
|
||||
|
||||
1. 在 RPC 节点列表中,找到要操作的节点
|
||||
2. 点击 **启用/禁用** 开关
|
||||
3. 系统会自动更新节点状态
|
||||
|
||||
**提示**:
|
||||
- 禁用的节点不会被使用,但配置会保留
|
||||
- 可以随时重新启用禁用的节点
|
||||
- 建议至少保留一个启用的节点
|
||||
|
||||
### 2. 实际成交价追踪
|
||||
|
||||
#### 这个功能做什么?
|
||||
|
||||
系统会自动追踪卖出订单的实际成交价,而不是使用下单时的价格。这样可以:
|
||||
- 更准确地计算盈亏
|
||||
- 了解订单的实际执行情况
|
||||
- 优化卖出策略
|
||||
|
||||
#### 如何查看实际成交价?
|
||||
|
||||
1. 进入 **跟单统计** → **卖出订单**
|
||||
2. 查看订单列表,**卖出价格** 列显示的是实际成交价
|
||||
3. 如果价格旁边有更新标记,说明价格已从订单详情中获取
|
||||
|
||||
**注意**:
|
||||
- 价格更新是自动的,每 5 秒检查一次
|
||||
- 如果订单还未成交,价格可能还是下单时的价格
|
||||
- 部分成交的订单会使用加权平均价格
|
||||
|
||||
## 🔍 常见问题
|
||||
|
||||
### Q1: 更新后无法启动怎么办?
|
||||
|
||||
**A:** 请按以下步骤排查:
|
||||
|
||||
1. 检查日志:`docker-compose -f docker-compose.prod.yml logs`
|
||||
2. 检查数据库连接是否正常
|
||||
3. 检查端口是否被占用
|
||||
4. 如果问题持续,可以回退到之前的版本:
|
||||
```bash
|
||||
# 修改 docker-compose.prod.yml 中的镜像标签为之前的版本
|
||||
# 例如:image: wrbug/polyhermes:v1.0.3
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
### Q2: 更新后跟单不工作怎么办?
|
||||
|
||||
**A:** 请检查:
|
||||
|
||||
1. RPC 节点是否正常(进入 RPC 节点设置查看)
|
||||
2. 跟单配置是否启用
|
||||
3. 账户 API 凭证是否有效
|
||||
4. 查看系统日志是否有错误信息
|
||||
|
||||
### Q3: 如何回退到之前的版本?
|
||||
|
||||
**A:** 按以下步骤操作:
|
||||
|
||||
1. 停止当前服务:`docker-compose -f docker-compose.prod.yml down`
|
||||
2. 修改 `docker-compose.prod.yml` 中的镜像标签为之前的版本
|
||||
3. 启动服务:`docker-compose -f docker-compose.prod.yml up -d`
|
||||
|
||||
**注意**:回退版本时,数据库结构可能不兼容,建议先备份数据库。
|
||||
|
||||
### Q4: 更新后数据会丢失吗?
|
||||
|
||||
**A:** 不会。更新过程不会删除任何数据。但为了安全起见,建议更新前备份数据库。
|
||||
|
||||
### Q5: 如何查看当前版本?
|
||||
|
||||
**A:** 有两种方式:
|
||||
|
||||
1. **页面查看**:登录系统后,页面标题会显示版本号(如:PolyHermes v1.1.0)
|
||||
2. **命令行查看**:
|
||||
```bash
|
||||
docker inspect polyhermes | grep -i version
|
||||
```
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- [完整更新日志](https://github.com/WrBug/PolyHermes/compare/v1.0.3...v1.1.0)
|
||||
- [部署文档](docs/zh/DEPLOYMENT.md)
|
||||
- [版本管理文档](docs/zh/VERSION_MANAGEMENT.md)
|
||||
|
||||
## 🔗 获取帮助
|
||||
|
||||
如果更新过程中遇到问题:
|
||||
|
||||
1. 查看 [GitHub Issues](https://github.com/WrBug/PolyHermes/issues)
|
||||
2. 查看系统日志:`docker-compose -f docker-compose.prod.yml logs -f`
|
||||
3. 在 GitHub 上提交 Issue,描述您的问题
|
||||
|
||||
## ⚠️ 安全提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.0
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:加入群组
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
**💬 如有问题或建议,欢迎在 GitHub Issues 中反馈。**
|
||||
|
||||
@@ -270,7 +270,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -337,7 +336,6 @@ cd frontend
|
||||
| `DB_USERNAME` | 数据库用户名 | `root` |
|
||||
| `DB_PASSWORD` | 数据库密码 | - |
|
||||
| `SERVER_PORT` | 后端服务端口 | `8000` |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC 地址 | `https://polygon-rpc.com` |
|
||||
| `JWT_SECRET` | JWT 密钥 | - |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | 管理员密码重置密钥 | - |
|
||||
| `CRYPTO_SECRET_KEY` | 加密密钥(用于加密存储私钥和 API Key) | - |
|
||||
|
||||
@@ -270,7 +270,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -337,7 +336,6 @@ cd frontend
|
||||
| `DB_USERNAME` | Database username | `root` |
|
||||
| `DB_PASSWORD` | Database password | - |
|
||||
| `SERVER_PORT` | Backend service port | `8000` |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC address | `https://polygon-rpc.com` |
|
||||
| `JWT_SECRET` | JWT secret key | - |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | Admin password reset key | - |
|
||||
| `CRYPTO_SECRET_KEY` | Encryption key (for encrypting stored private keys and API Keys) | - |
|
||||
|
||||
+408
@@ -0,0 +1,408 @@
|
||||
# v1.1.5
|
||||
|
||||
## 🔧 功能优化与改进
|
||||
|
||||
### 前端优化
|
||||
|
||||
#### 优化 InputNumber 输入框格式化
|
||||
- 优化数值输入框的格式化逻辑,修正正则表达式以正确处理整数显示
|
||||
- 更新所有相关 InputNumber 组件的 formatter 函数,确保显示准确性
|
||||
- 影响的组件:CopyTradingAdd、CopyTradingEdit、EditModal、TemplateAdd、TemplateEdit、TemplateList
|
||||
- 影响范围:跟单配置、模板配置中的所有数值输入框
|
||||
|
||||
#### 优化数字显示格式
|
||||
- 添加 `formatNumber` 工具函数,自动去除小数尾随零(如 100.00 → 100)
|
||||
- 统一所有数值输入框的显示格式,提升用户体验
|
||||
|
||||
### 后端优化
|
||||
|
||||
#### 优化按比例跟单金额计算逻辑
|
||||
- 优化按比例计算的订单金额处理,使用向上取整确保满足最小限制要求
|
||||
- 对订单金额进行向上取整处理(保留 2 位小数精度)
|
||||
- 自动调整订单数量以满足最小限制要求
|
||||
- 使用 `RoundingMode.CEILING` 确保金额满足最小限制
|
||||
- 影响范围:按比例跟单的订单创建逻辑
|
||||
- 技术细节:
|
||||
- 扩展 `BigDecimal.div()` 扩展函数,支持指定精度和舍入模式
|
||||
- 在 `CopyOrderTrackingService` 中优化金额计算和验证逻辑
|
||||
|
||||
#### 增强 copyRatio 精度支持
|
||||
- 将 copyRatio 字段精度从 DECIMAL(10,2) 增加到 DECIMAL(20,8)
|
||||
- 支持更精确的跟单比例设置(最小 0.01%,最大 10000%)
|
||||
- 影响的实体:CopyTrading、CopyTradingTemplate
|
||||
- 数据库迁移:新增 V18 迁移脚本,自动升级数据库字段精度
|
||||
|
||||
## 🔧 功能优化
|
||||
|
||||
### 移除刷新代理钱包接口
|
||||
- **移除接口**:
|
||||
- `POST /api/accounts/refresh-proxy` - 刷新单个账户的代理地址
|
||||
- `POST /api/accounts/refresh-all-proxies` - 刷新所有账户的代理地址
|
||||
- **原因**:代理地址应在账户导入时自动计算,无需手动刷新
|
||||
- **影响范围**:AccountController、AccountService
|
||||
- **向后兼容性**:这些接口已不再使用,移除不影响现有功能
|
||||
|
||||
### 前端跟单比例配置优化
|
||||
- **最小比例**:从 10% 降低到 0.01%,支持更灵活的跟单比例设置
|
||||
- **最大比例**:增加到 10000%,满足大比例跟单需求
|
||||
- **显示格式**:比例模式显示为百分比(如 "100%" 而不是 "1x")
|
||||
- **输入验证**:增强输入验证,确保比例在合理范围内
|
||||
|
||||
## 📊 变更统计
|
||||
|
||||
- **提交数量**:3 个提交
|
||||
- **文件变更**:15 个文件
|
||||
- **代码变更**:+575 行 / -194 行(净增加 381 行)
|
||||
|
||||
### 详细文件变更
|
||||
|
||||
**后端变更**:
|
||||
- `AccountController.kt` - 移除刷新代理钱包接口(-59 行)
|
||||
- `AccountService.kt` - 移除刷新代理钱包方法(-79 行)
|
||||
- `CopyTrading.kt` - 增加 copyRatio 精度
|
||||
- `CopyTradingTemplate.kt` - 增加 copyRatio 精度
|
||||
- `CopyOrderTrackingService.kt` - 优化按比例跟单金额计算逻辑(+45 行)
|
||||
- `MathExt.kt` - 扩展 div 函数支持精度和舍入模式(+20 行)
|
||||
- `V18__increase_copy_ratio_precision.sql` - 数据库迁移脚本(+14 行)
|
||||
|
||||
**前端变更**:
|
||||
- `CopyTradingAdd.tsx` - 优化 formatter、优化比例配置(+106 行)
|
||||
- `CopyTradingEdit.tsx` - 优化 formatter、优化比例配置(+106 行)
|
||||
- `CopyTradingList.tsx` - 优化比例显示格式
|
||||
- `CopyTradingOrders/EditModal.tsx` - 优化 formatter、优化比例配置(+106 行)
|
||||
- `TemplateAdd.tsx` - 优化 formatter、优化比例配置(+65 行)
|
||||
- `TemplateEdit.tsx` - 优化 formatter、优化比例配置(+65 行)
|
||||
- `TemplateList.tsx` - 优化 formatter、优化比例配置(+65 行)
|
||||
- `utils/index.ts` - 添加 formatNumber 工具函数(+31 行)
|
||||
|
||||
## 🔧 技术细节
|
||||
|
||||
### 数据库变更
|
||||
- **迁移脚本**:`V18__increase_copy_ratio_precision.sql`
|
||||
- **变更内容**:
|
||||
- `copy_trading.copy_ratio`: DECIMAL(10,2) → DECIMAL(20,8)
|
||||
- `copy_trading_templates.copy_ratio`: DECIMAL(10,2) → DECIMAL(20,8)
|
||||
- **自动执行**:升级时会自动执行迁移脚本
|
||||
|
||||
### API 变更
|
||||
- **移除接口**:
|
||||
- `POST /api/accounts/refresh-proxy`
|
||||
- `POST /api/accounts/refresh-all-proxies`
|
||||
- **无新增接口**
|
||||
|
||||
### 前端变更
|
||||
- **工具函数**:新增 `formatNumber()` 函数,用于格式化数字显示
|
||||
- **组件更新**:所有数值输入框统一使用新的 formatter 函数
|
||||
- **显示优化**:跟单模式的比例显示为百分比格式
|
||||
|
||||
## 📝 升级说明
|
||||
|
||||
### 数据库升级
|
||||
本次版本包含数据库迁移脚本,升级时会自动执行:
|
||||
- 自动增加 `copy_ratio` 字段的精度
|
||||
- 现有数据不受影响,精度升级是向后兼容的
|
||||
|
||||
### 配置变更
|
||||
无需额外配置变更。
|
||||
|
||||
### 兼容性
|
||||
- **向后兼容**:所有变更都是向后兼容的
|
||||
- **API 兼容**:移除的接口不影响现有功能(这些接口已不再使用)
|
||||
- **数据兼容**:数据库字段精度升级不会影响现有数据
|
||||
|
||||
## 🎯 主要改进
|
||||
|
||||
1. **优化输入框格式化**:优化数值输入框的显示逻辑
|
||||
2. **优化跟单金额计算**:确保按比例跟单的金额满足最小限制要求
|
||||
3. **提升精度支持**:支持更精确的跟单比例设置(0.01% - 10000%)
|
||||
4. **代码清理**:移除不再使用的刷新代理钱包接口
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- [GitHub Tag](https://github.com/WrBug/PolyHermes/releases/tag/v1.1.5)
|
||||
- [变更日志](https://github.com/WrBug/PolyHermes/compare/v1.1.4...v1.1.5)
|
||||
|
||||
## 🙏 致谢
|
||||
|
||||
感谢所有贡献者和测试用户的反馈与支持!
|
||||
|
||||
---
|
||||
|
||||
# v1.1.2
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🐛 修复内存泄漏问题
|
||||
- 修复 Retrofit/OkHttpClient 实例重复创建导致的内存泄漏问题
|
||||
- 为不需要认证的 API 创建共享的 OkHttpClient 实例(Gamma API、Data API、GitHub API 等)
|
||||
- 带认证的 CLOB API 按钱包地址缓存(每个账户一个客户端)
|
||||
- RPC API 按 RPC URL 缓存,Builder Relayer API 按 relayerUrl 缓存
|
||||
- 添加 `@PreDestroy` 方法清理缓存,确保资源正确释放
|
||||
- **效果**:内存占用从运行几小时后从 400MB 涨到 1GB+ 变为保持稳定,大幅减少内存占用
|
||||
|
||||
### 📊 市场价格服务优化
|
||||
- 移除降级查询逻辑,仅保留链上 RPC 查询和 CLOB 订单簿查询
|
||||
- 移除 CLOB Trades、Gamma Market Status、Gamma Market Price 查询逻辑
|
||||
- 如果所有数据源都失败,抛出明确的异常信息
|
||||
- 价格截位到 4 位小数(向下截断,不四舍五入)
|
||||
- 简化代码逻辑,提高查询效率和准确性
|
||||
|
||||
### 🔧 代码架构优化
|
||||
- 统一 Gson 使用,改为依赖注入方式
|
||||
- 在 `GsonConfig` 中统一配置 Gson Bean(lenient 模式)
|
||||
- 所有 Service 类通过构造函数注入 Gson 实例
|
||||
- 移除所有 `GsonConverterFactory.create()` 无参调用,统一使用注入的 Gson
|
||||
- 提高代码一致性和可维护性
|
||||
|
||||
### 🗑️ 功能清理
|
||||
- 移除下单失败存储数据库的功能
|
||||
- 删除 `FailedTrade` 实体类和 `FailedTradeRepository`
|
||||
- 从 `CopyOrderTrackingService` 中移除失败交易存储逻辑
|
||||
- 创建 Flyway migration V16 删除 `failed_trade` 表
|
||||
- 下单失败时仅记录日志,不再存储到数据库,简化数据模型
|
||||
|
||||
### 🚀 部署优化
|
||||
- 自动使用当前分支名作为 Docker 版本号
|
||||
- 分支名中的 `/` 自动替换为 `-`(Docker tag 不支持 `/)
|
||||
- `docker-compose.yml` 启用 build args,从环境变量读取版本号
|
||||
- 前端页面将显示当前分支名作为版本号
|
||||
- 如果没有 Git 仓库或获取失败,使用默认值 `dev`
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复 Flyway Migration 问题
|
||||
- 恢复 V1 migration 文件,避免 checksum 不匹配
|
||||
- 保持 `V1__init_database.sql` 的原有内容不变
|
||||
- `failed_trade` 表的删除通过 V16 migration 处理
|
||||
- 确保已有数据库的 migration checksum 保持一致
|
||||
|
||||
### 修复前端编译错误
|
||||
- 修复 `PositionList.tsx` 中引用不存在的 `bestBid` 属性导致的编译错误
|
||||
- 使用 `currentPrice` 替代 `bestBid`,确保前端代码可以正常编译
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 新增智能资金分析文档(`docs/zh/smart-money-analysis.md`)
|
||||
- 详细说明智能资金分析功能的使用方法和策略
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 优化 `RetrofitFactory`,实现客户端实例缓存和复用
|
||||
- 优化 `CopyOrderTrackingService`,移除失败交易相关逻辑
|
||||
- 优化 `OrderStatusUpdateService`,增强订单状态更新功能
|
||||
- 优化 `TelegramNotificationService`,改进通知逻辑
|
||||
- 优化 `PositionCheckService`,简化代码结构
|
||||
- 优化 `PolymarketClobService`,改进 API 调用逻辑
|
||||
|
||||
## 📦 数据库变更
|
||||
|
||||
- 删除 `failed_trade` 表(Migration: V16)
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.1.2
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.1.1...v1.1.2
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## 📊 统计信息
|
||||
|
||||
- **文件变更**: 29 个文件
|
||||
- **代码变更**: +1597 行 / -678 行
|
||||
- **主要提交**: 8 个提交
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.2
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:加入群组
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
---
|
||||
|
||||
# v1.1.1
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🔗 链上 WebSocket 监听优化
|
||||
- 创建 `UnifiedOnChainWsService` 统一管理 WebSocket 连接,所有服务共享同一个连接
|
||||
- 创建 `OnChainWsUtils` 工具类,提取公共的链上 WebSocket 相关功能
|
||||
- 创建 `AccountOnChainMonitorService` 监听账户链上卖出和赎回事件
|
||||
- 优化 `OnChainWsService`,复用公共代码,减少代码重复
|
||||
- 支持通过链上 WebSocket 实时监听账户的卖出和赎回交易,自动更新订单状态
|
||||
|
||||
### 📊 市场状态查询优化
|
||||
- 优化市场结算状态查询,优先使用链上查询 `ConditionalTokens.getCondition`
|
||||
- 如果链上查询失败,自动降级到 Gamma API 查询
|
||||
- 提供更实时和准确的市场结算结果
|
||||
|
||||
### 🔕 自动订单通知优化
|
||||
- 自动生成的订单(AUTO_、AUTO_FIFO_、AUTO_WS_ 前缀)不再发送 Telegram 通知
|
||||
- 优化 `OrderStatusUpdateService`,跳过自动生成订单的通知处理
|
||||
- 减少不必要的通知,提升用户体验
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复移动端 API 健康页面缺少数据显示
|
||||
- 移动端添加 URL 地址显示
|
||||
- 移动端添加状态文本显示(正常/异常/未配置)
|
||||
- 移动端添加消息/状态信息显示
|
||||
- 移动端和桌面端显示信息保持一致
|
||||
|
||||
## 🔧 功能优化
|
||||
|
||||
### 优化 Telegram 推送消息格式
|
||||
- 添加价格和数量截位处理:
|
||||
* 价格保留最多4位小数(截断,不四舍五入)
|
||||
* 数量保留最多2位小数(截断,不四舍五入)
|
||||
- 优化账户信息显示格式:
|
||||
* 有账户名和钱包地址时显示:账户名(0x123...123)
|
||||
* 只有账户名时显示账户名
|
||||
* 只有钱包地址时显示脱敏后的地址
|
||||
* 都没有时显示未知账户
|
||||
|
||||
### 配置优化
|
||||
- 移除 `polygon.rpc.url` 配置,使用 RpcNodeService 统一管理 RPC 节点
|
||||
- 删除无用的 `position.push.polling-interval` 和 `position.push.heartbeat-timeout` 配置项
|
||||
- 修正日志配置中的包名(polyhermes -> polymarketbot)
|
||||
- 更新 `ApiHealthCheckService` 直接使用 `RpcNodeService.getHttpUrl()`
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 统一发布说明文件,使用 RELEASE.md 替代版本化文件(RELEASE_v1.0.1.md、RELEASE_v1.1.0.md)
|
||||
- 更新所有部署文档,移除 POLYGON_RPC_URL 相关说明
|
||||
- 更新所有 Docker Compose 配置文件,移除 POLYGON_RPC_URL 环境变量
|
||||
- 更新所有部署脚本,移除 POLYGON_RPC_URL 环境变量定义
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 重构链上 WebSocket 服务,提取公共代码到 `OnChainWsUtils`
|
||||
- 创建统一的 WebSocket 连接管理服务 `UnifiedOnChainWsService`
|
||||
- 添加链上查询市场结算结果的功能(`BlockchainService.getCondition`)
|
||||
- 添加 ABI 编码/解码工具方法(`EthereumUtils.decodeConditionResult`)
|
||||
- 优化代码结构,减少代码重复,提高可维护性
|
||||
|
||||
---
|
||||
|
||||
# v1.1.0
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🔗 链上 WebSocket 实时监听
|
||||
- 实现通过 Polygon RPC `eth_subscribe` 实时监听链上交易
|
||||
- 支持监听 USDC Transfer 和 ERC1155 Transfer 事件
|
||||
- 实现并行监控策略:链上 WebSocket 和轮询同时运行,哪个数据先返回用哪个
|
||||
- 支持通过 `eth_unsubscribe` 取消单个 Leader 的订阅,无需重新连接
|
||||
- 优化 WebSocket 连接管理:只创建一个连接,没有跟单配置时自动取消
|
||||
- 跟单配置生效/失效时及时更新 WebSocket 订阅
|
||||
- 使用 Gson 替换所有 JSON 解析,提高解析稳定性
|
||||
- 添加 Mutex 保证线程安全,防止并发处理导致的数据重复
|
||||
|
||||
### 📊 RPC 节点管理
|
||||
- 实现 RPC 节点管理功能,支持添加、编辑、删除自定义 RPC 节点
|
||||
- 支持 RPC 节点启用/禁用功能,禁用的节点会被自动忽略
|
||||
- 前端添加启用/禁用开关,支持实时切换节点状态
|
||||
- 健康检查只检查启用的节点,提高检查效率
|
||||
- 节点选择时自动过滤禁用的节点
|
||||
|
||||
### 💰 卖出订单价格轮询更新
|
||||
- 添加 `price_updated` 字段到 `sell_match_record` 表,用于标记价格是否已更新
|
||||
- 创建 `OrderStatusUpdateService` 定时任务服务,每 5 秒轮询一次:
|
||||
- 更新卖出订单的实际成交价(通过 orderId 查询订单详情)
|
||||
- 清理已删除账户的订单记录
|
||||
- 支持加权平均价格计算,处理部分成交的订单
|
||||
- 添加 orderId 格式验证:非 0x 开头的直接标记为已更新,0x 开头的等待定时任务更新
|
||||
- 下单完成后不再立即查询价格,直接保存,等待定时任务更新
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复跟单卖出订单的 API 凭证解密问题
|
||||
- 修复 `processSellTrade` 中 API 凭证未解密的问题,与 `processBuyTrade` 保持一致
|
||||
- 确保卖出订单能够正常使用 API 凭证进行认证
|
||||
|
||||
### 修复 SELL 订单精度问题
|
||||
- 修复 SELL 订单的 `makerAmount` 和 `takerAmount` 精度问题:
|
||||
- `makerAmount` (shares) 最多 2 位小数(符合 API 要求)
|
||||
- `takerAmount` (USDC) 最多 4 位小数(符合 API 要求)
|
||||
- 确保订单能够正常提交到 Polymarket API
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 添加 Docker 版本更新说明(中英文)
|
||||
- 添加链上 WebSocket 监听策略文档
|
||||
- 添加跟单逻辑总结文档
|
||||
- 更新部署文档,包含详细的版本更新步骤
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 使用 Gson 替换 ObjectMapper,提高 JSON 解析稳定性
|
||||
- `JsonRpcResponse.result` 使用 `JsonElement` 类型,支持灵活的 JSON 结构
|
||||
- 优化 WebSocket 连接管理,减少不必要的连接
|
||||
- 添加线程安全机制,使用 Kotlin Coroutines Mutex
|
||||
- 启用 Spring 定时任务功能(`@EnableScheduling`)
|
||||
|
||||
## 📦 数据库变更
|
||||
|
||||
- 新增 `price_updated` 字段到 `sell_match_record` 表(Migration: V13)
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.1.1
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.1.0...v1.1.1
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## 📊 统计信息
|
||||
|
||||
- **文件变更**: 32 个文件
|
||||
- **代码变更**: +1872 行 / -1503 行
|
||||
- **主要提交**: 7 个提交
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.1
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:加入群组
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# v1.0.1
|
||||
|
||||
## 🚀 性能优化
|
||||
|
||||
### 📊 订单簿请求优化
|
||||
* 优化订单簿获取逻辑,仅在需要时请求,避免不必要的 API 调用
|
||||
* 当未配置需要订单簿的过滤条件(价差、订单深度)时,跳过订单簿获取
|
||||
* 订单簿只请求一次,在过滤检查中复用,提高性能
|
||||
|
||||
### 💰 卖出价格计算优化
|
||||
* 卖出改为市价卖出:优先使用订单簿的 bestBid(最高买入价)
|
||||
* 如果 bestBid 获取失败,自动降级使用 Leader 的交易价格
|
||||
* 卖出价格固定按 90% 计算,不再使用价格容忍度配置
|
||||
* 提高卖出订单的成交率
|
||||
|
||||
### ⚙️ 价格容忍度默认值
|
||||
* 如果价格容忍度配置为 0,自动使用默认值 5%
|
||||
* 确保买入订单能够正常应用价格调整,提高成交率
|
||||
|
||||
## 🔧 代码优化
|
||||
|
||||
### 🎯 使用枚举优化过滤逻辑
|
||||
* 新增 `FilterResult` 数据类和 `FilterStatus` 枚举
|
||||
* 使用类型安全的枚举替代字符串判断,提高代码可维护性
|
||||
* 移除无用字段 `isBuyOrder` 参数
|
||||
* 优化 `checkFilters` 方法返回值,使用数据类封装结果
|
||||
|
||||
### 📝 代码结构优化
|
||||
* 减少 if-else 嵌套,使用 Kotlin 链式调用和空安全操作符
|
||||
* 优化卖出价格计算逻辑,使用 `runCatching` 和 `?.let` 简化代码
|
||||
* 提取公共方法 `calculateFallbackSellPrice`,提高代码复用性
|
||||
|
||||
## 🗑️ 功能移除
|
||||
|
||||
### 移除最小订单簿深度功能
|
||||
* 移除 `minOrderbookDepth`(最小订单簿深度)配置项
|
||||
* 简化过滤逻辑,只保留 `minOrderDepth`(最小订单深度)
|
||||
* 更新前端界面,移除相关配置项和提示文案
|
||||
|
||||
### 优化最小订单深度逻辑
|
||||
* 修改 `minOrderDepth` 检查逻辑,检查所有方向(买盘+卖盘)的总深度
|
||||
* 不再区分买卖方向,提供更全面的市场流动性评估
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
* 修复盈亏和持仓价值计算逻辑未实现的问题
|
||||
* 修复过滤检查中订单簿可能重复请求的问题
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
* 更新前端多语言文案,优化提示信息
|
||||
* 移除最小订单簿深度相关的文档说明
|
||||
|
||||
**Full Changelog**: https://github.com/WrBug/polymarket-bot/compare/v1.0.0...v1.0.1
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
# v1.1.0
|
||||
|
||||
## 🚀 主要功能
|
||||
|
||||
### 🔗 链上 WebSocket 实时监听
|
||||
- 实现通过 Polygon RPC `eth_subscribe` 实时监听链上交易
|
||||
- 支持监听 USDC Transfer 和 ERC1155 Transfer 事件
|
||||
- 实现并行监控策略:链上 WebSocket 和轮询同时运行,哪个数据先返回用哪个
|
||||
- 支持通过 `eth_unsubscribe` 取消单个 Leader 的订阅,无需重新连接
|
||||
- 优化 WebSocket 连接管理:只创建一个连接,没有跟单配置时自动取消
|
||||
- 跟单配置生效/失效时及时更新 WebSocket 订阅
|
||||
- 使用 Gson 替换所有 JSON 解析,提高解析稳定性
|
||||
- 添加 Mutex 保证线程安全,防止并发处理导致的数据重复
|
||||
|
||||
### 📊 RPC 节点管理
|
||||
- 实现 RPC 节点管理功能,支持添加、编辑、删除自定义 RPC 节点
|
||||
- 支持 RPC 节点启用/禁用功能,禁用的节点会被自动忽略
|
||||
- 前端添加启用/禁用开关,支持实时切换节点状态
|
||||
- 健康检查只检查启用的节点,提高检查效率
|
||||
- 节点选择时自动过滤禁用的节点
|
||||
|
||||
### 💰 卖出订单价格轮询更新
|
||||
- 添加 `price_updated` 字段到 `sell_match_record` 表,用于标记价格是否已更新
|
||||
- 创建 `OrderStatusUpdateService` 定时任务服务,每 5 秒轮询一次:
|
||||
- 更新卖出订单的实际成交价(通过 orderId 查询订单详情)
|
||||
- 清理已删除账户的订单记录
|
||||
- 支持加权平均价格计算,处理部分成交的订单
|
||||
- 添加 orderId 格式验证:非 0x 开头的直接标记为已更新,0x 开头的等待定时任务更新
|
||||
- 下单完成后不再立即查询价格,直接保存,等待定时任务更新
|
||||
|
||||
## 🐛 Bug 修复
|
||||
|
||||
### 修复跟单卖出订单的 API 凭证解密问题
|
||||
- 修复 `processSellTrade` 中 API 凭证未解密的问题,与 `processBuyTrade` 保持一致
|
||||
- 确保卖出订单能够正常使用 API 凭证进行认证
|
||||
|
||||
### 修复 SELL 订单精度问题
|
||||
- 修复 SELL 订单的 `makerAmount` 和 `takerAmount` 精度问题:
|
||||
- `makerAmount` (shares) 最多 2 位小数(符合 API 要求)
|
||||
- `takerAmount` (USDC) 最多 4 位小数(符合 API 要求)
|
||||
- 确保订单能够正常提交到 Polymarket API
|
||||
|
||||
## 📚 文档更新
|
||||
|
||||
- 添加 Docker 版本更新说明(中英文)
|
||||
- 添加链上 WebSocket 监听策略文档
|
||||
- 添加跟单逻辑总结文档
|
||||
- 更新部署文档,包含详细的版本更新步骤
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
- 使用 Gson 替换 ObjectMapper,提高 JSON 解析稳定性
|
||||
- `JsonRpcResponse.result` 使用 `JsonElement` 类型,支持灵活的 JSON 结构
|
||||
- 优化 WebSocket 连接管理,减少不必要的连接
|
||||
- 添加线程安全机制,使用 Kotlin Coroutines Mutex
|
||||
- 启用 Spring 定时任务功能(`@EnableScheduling`)
|
||||
|
||||
## 📦 数据库变更
|
||||
|
||||
- 新增 `price_updated` 字段到 `sell_match_record` 表(Migration: V13)
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- **GitHub Release**: https://github.com/WrBug/PolyHermes/releases/tag/v1.1.0
|
||||
- **完整更新日志**: https://github.com/WrBug/PolyHermes/compare/v1.0.3...v1.1.0
|
||||
- **Docker Hub**: https://hub.docker.com/r/wrbug/polyhermes
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
|
||||
**请务必使用官方 Docker 镜像源,避免财产损失!**
|
||||
|
||||
### ✅ 官方 Docker Hub 镜像
|
||||
|
||||
**官方镜像地址**:`wrbug/polyhermes`
|
||||
|
||||
```bash
|
||||
# ✅ 正确:使用官方镜像
|
||||
docker pull wrbug/polyhermes:v1.1.0
|
||||
|
||||
# ❌ 错误:不要使用其他来源的镜像
|
||||
# 任何非官方来源的镜像都可能包含恶意代码,导致您的私钥和资产被盗
|
||||
```
|
||||
|
||||
### 🔗 官方渠道
|
||||
|
||||
请通过以下**唯一官方渠道**获取 PolyHermes:
|
||||
|
||||
* **GitHub 仓库**:https://github.com/WrBug/PolyHermes
|
||||
* **Twitter**:@polyhermes
|
||||
* **Telegram 群组**:加入群组
|
||||
|
||||
---
|
||||
|
||||
**⭐ 如果这个项目对您有帮助,请给个 Star 支持一下!**
|
||||
|
||||
@@ -154,9 +154,6 @@ SPRING_PROFILES_ACTIVE=prod
|
||||
# 服务器端口
|
||||
SERVER_PORT=8000
|
||||
|
||||
# Polygon RPC
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
|
||||
# JWT 密钥(已自动生成随机值,生产环境建议修改)
|
||||
JWT_SECRET=${JWT_SECRET}
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ services:
|
||||
- DB_USERNAME=${DB_USERNAME:-root}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-}
|
||||
- SERVER_PORT=8000
|
||||
- POLYGON_RPC_URL=${POLYGON_RPC_URL:-https://polygon-rpc.com}
|
||||
- JWT_SECRET=${JWT_SECRET:-change-me-in-production}
|
||||
- ADMIN_RESET_PASSWORD_KEY=${ADMIN_RESET_PASSWORD_KEY:-change-me-in-production}
|
||||
depends_on:
|
||||
|
||||
@@ -16,12 +16,14 @@ interface PolymarketGammaApi {
|
||||
* 根据 condition ID 列表获取市场信息
|
||||
* 文档: https://docs.polymarket.com/api-reference/markets/list-markets
|
||||
* @param conditionIds condition ID 数组(16 进制字符串,如 "0x...")
|
||||
* @param clobTokenIds CLOB token ID 数组(用于通过 tokenId 查询市场)
|
||||
* @param includeTag 是否包含标签信息
|
||||
* @return 市场信息数组
|
||||
*/
|
||||
@GET("/markets")
|
||||
suspend fun listMarkets(
|
||||
@Query("condition_ids") conditionIds: List<String>? = null,
|
||||
@Query("clob_token_ids") clobTokenIds: List<String>? = null,
|
||||
@Query("include_tag") includeTag: Boolean? = null
|
||||
): Response<List<MarketResponse>>
|
||||
}
|
||||
@@ -51,6 +53,9 @@ data class MarketResponse(
|
||||
val liquidityNum: Double? = null,
|
||||
val lastTradePrice: Double? = null,
|
||||
val bestBid: Double? = null,
|
||||
val bestAsk: Double? = null
|
||||
val bestAsk: Double? = null,
|
||||
// 以下字段可能存在于响应中,但不在标准文档中
|
||||
val clobTokenIds: String? = null, // CLOB token IDs(可能是 JSON 字符串或数组)
|
||||
val clob_token_ids: String? = null // 下划线格式(兼容不同 API 版本)
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.wrbug.polymarketbot.config
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
/**
|
||||
* Gson 配置类
|
||||
* 统一配置 Gson 实例,使用 lenient 模式允许解析格式不严格的 JSON
|
||||
*/
|
||||
@Configuration
|
||||
class GsonConfig {
|
||||
|
||||
/**
|
||||
* 创建 Gson Bean
|
||||
* 使用 lenient 模式,允许解析格式不严格的 JSON
|
||||
*/
|
||||
@Bean
|
||||
fun gson(): Gson {
|
||||
return GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
}
|
||||
}
|
||||
|
||||
+7
-8
@@ -36,20 +36,19 @@ class JwtAuthenticationInterceptor(
|
||||
handler: Any
|
||||
): Boolean {
|
||||
val path = request.requestURI
|
||||
val method = request.method
|
||||
|
||||
// 只拦截POST请求
|
||||
if (method != "POST") {
|
||||
|
||||
// 只拦截 /api/** 路径
|
||||
if (!path.startsWith("/api/")) {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
// 排除不需要鉴权的路径
|
||||
if (excludePaths.contains(path)) {
|
||||
return true
|
||||
}
|
||||
|
||||
// 只拦截 /api/** 路径
|
||||
if (!path.startsWith("/api/")) {
|
||||
|
||||
// 允许 OPTIONS 请求(CORS 预检请求)
|
||||
if (request.method == "OPTIONS") {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.wrbug.polymarketbot.config
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.wrbug.polymarketbot.api.PolymarketClobApi
|
||||
import com.wrbug.polymarketbot.util.createClient
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
@@ -18,7 +19,9 @@ import retrofit2.converter.gson.GsonConverterFactory
|
||||
* - 账户 API Key 在调用时动态设置,不在此处配置
|
||||
*/
|
||||
@Configuration
|
||||
class RetrofitConfig {
|
||||
class RetrofitConfig(
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
@Value("\${polymarket.clob.base-url}")
|
||||
private lateinit var clobBaseUrl: String
|
||||
@@ -37,7 +40,7 @@ class RetrofitConfig {
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
}
|
||||
|
||||
@@ -21,10 +21,6 @@ class WebMvcConfig(
|
||||
// 再注册JWT认证拦截器
|
||||
registry.addInterceptor(jwtAuthenticationInterceptor)
|
||||
.addPathPatterns("/api/**")
|
||||
registry.addInterceptor(jwtAuthenticationInterceptor)
|
||||
.addPathPatterns("/api/**")
|
||||
registry.addInterceptor(jwtAuthenticationInterceptor)
|
||||
.addPathPatterns("/api/**")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+49
-18
@@ -1,6 +1,7 @@
|
||||
package com.wrbug.polymarketbot.config
|
||||
|
||||
import com.wrbug.polymarketbot.repository.UserRepository
|
||||
import com.wrbug.polymarketbot.service.auth.WebSocketTicketService
|
||||
import com.wrbug.polymarketbot.util.JwtUtils
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.http.server.ServerHttpRequest
|
||||
@@ -11,12 +12,13 @@ import org.springframework.web.socket.server.HandshakeInterceptor
|
||||
|
||||
/**
|
||||
* WebSocket 握手拦截器
|
||||
* 用于验证 JWT token
|
||||
* 优先使用短期票据验证,其次使用 JWT token
|
||||
*/
|
||||
@Component
|
||||
class WebSocketAuthInterceptor(
|
||||
private val jwtUtils: JwtUtils,
|
||||
private val userRepository: UserRepository
|
||||
private val userRepository: UserRepository,
|
||||
private val webSocketTicketService: WebSocketTicketService
|
||||
) : HandshakeInterceptor {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(WebSocketAuthInterceptor::class.java)
|
||||
@@ -27,22 +29,36 @@ class WebSocketAuthInterceptor(
|
||||
wsHandler: WebSocketHandler,
|
||||
attributes: MutableMap<String, Any>
|
||||
): Boolean {
|
||||
// 从查询参数或请求头获取 token
|
||||
val token = getTokenFromRequest(request)
|
||||
|
||||
if (token == null) {
|
||||
logger.warn("WebSocket 连接缺少认证令牌: ${request.uri}")
|
||||
// 优先使用票据验证(推荐方式,不暴露 JWT)
|
||||
val ticket = getTicketFromRequest(request)
|
||||
if (ticket != null) {
|
||||
val username = webSocketTicketService.validateAndConsumeTicket(ticket)
|
||||
if (username != null) {
|
||||
attributes["username"] = username
|
||||
logger.debug("WebSocket 连接票据认证成功: username=$username")
|
||||
return true
|
||||
}
|
||||
logger.warn("WebSocket 连接票据验证失败(可能已过期或已使用)")
|
||||
response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED)
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
// 兼容旧方式:使用 JWT token(不推荐,但保持向后兼容)
|
||||
val token = getTokenFromRequest(request)
|
||||
|
||||
if (token == null) {
|
||||
logger.warn("WebSocket 连接缺少认证令牌: ${request.uri.path}")
|
||||
response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED)
|
||||
return false
|
||||
}
|
||||
|
||||
// 验证 token
|
||||
if (!jwtUtils.validateToken(token)) {
|
||||
logger.warn("WebSocket 连接 token 验证失败: ${request.uri}")
|
||||
logger.warn("WebSocket 连接 token 验证失败")
|
||||
response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED)
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
// 验证tokenVersion(检查token是否因密码修改而失效)
|
||||
val username = jwtUtils.getUsernameFromToken(token)
|
||||
if (username != null) {
|
||||
@@ -50,21 +66,21 @@ class WebSocketAuthInterceptor(
|
||||
if (user != null) {
|
||||
val tokenVersion = jwtUtils.getTokenVersionFromToken(token)
|
||||
if (tokenVersion == null || tokenVersion != user.tokenVersion) {
|
||||
logger.warn("WebSocket 连接 token 版本不匹配,token已失效: username=$username, tokenVersion=$tokenVersion, userTokenVersion=${user.tokenVersion}, uri=${request.uri}")
|
||||
logger.warn("WebSocket 连接 token 版本不匹配,token已失效: username=$username")
|
||||
response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 获取用户名并存入 attributes,供后续使用
|
||||
attributes["username"] = username
|
||||
logger.debug("WebSocket 连接认证成功: username=$username, uri=${request.uri}")
|
||||
logger.debug("WebSocket 连接 JWT 认证成功: username=$username")
|
||||
} else {
|
||||
logger.warn("WebSocket 连接无法获取用户名: ${request.uri}")
|
||||
logger.warn("WebSocket 连接无法获取用户名")
|
||||
response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED)
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -78,7 +94,22 @@ class WebSocketAuthInterceptor(
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求中获取 token
|
||||
* 从请求中获取票据
|
||||
*/
|
||||
private fun getTicketFromRequest(request: ServerHttpRequest): String? {
|
||||
val queryParams = request.uri.query ?: return null
|
||||
val params = queryParams.split("&")
|
||||
for (param in params) {
|
||||
val parts = param.split("=", limit = 2)
|
||||
if (parts.size == 2 && parts[0] == "ticket") {
|
||||
return parts[1]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求中获取 token(兼容旧方式)
|
||||
* 支持从查询参数 token 或请求头 Authorization 获取
|
||||
*/
|
||||
private fun getTokenFromRequest(request: ServerHttpRequest): String? {
|
||||
@@ -93,13 +124,13 @@ class WebSocketAuthInterceptor(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 从请求头获取
|
||||
val authHeader = request.headers.getFirst("Authorization")
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
return authHeader.substring(7)
|
||||
}
|
||||
|
||||
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.wrbug.polymarketbot.config
|
||||
|
||||
import com.wrbug.polymarketbot.websocket.PolymarketWebSocketHandler
|
||||
import com.wrbug.polymarketbot.websocket.UnifiedWebSocketHandler
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocket
|
||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
|
||||
@@ -16,21 +17,46 @@ import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
|
||||
class WebSocketConfig(
|
||||
private val polymarketWebSocketHandler: PolymarketWebSocketHandler,
|
||||
private val unifiedWebSocketHandler: UnifiedWebSocketHandler,
|
||||
private val webSocketAuthInterceptor: WebSocketAuthInterceptor
|
||||
private val webSocketAuthInterceptor: WebSocketAuthInterceptor,
|
||||
@Value("\${websocket.allowed-origins:}") private val allowedOriginsConfig: String
|
||||
) : WebSocketConfigurer {
|
||||
|
||||
|
||||
/**
|
||||
* 获取允许的 WebSocket 来源
|
||||
* 如果配置了 WEBSOCKET_ALLOWED_ORIGINS 环境变量,使用配置的域名
|
||||
* 否则使用 setAllowedOriginPatterns 允许同源访问
|
||||
*/
|
||||
private fun getAllowedOrigins(): Array<String> {
|
||||
return if (allowedOriginsConfig.isNotBlank()) {
|
||||
allowedOriginsConfig.split(",").map { it.trim() }.toTypedArray()
|
||||
} else {
|
||||
emptyArray()
|
||||
}
|
||||
}
|
||||
|
||||
override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
|
||||
val origins = getAllowedOrigins()
|
||||
|
||||
// Polymarket RTDS 转发端点(转发外部 Polymarket 实时数据流)
|
||||
// 注意:此端点不需要鉴权,因为它只是转发外部数据
|
||||
registry.addHandler(polymarketWebSocketHandler, "/ws/polymarket")
|
||||
.setAllowedOrigins("*") // 生产环境应该配置具体的域名
|
||||
|
||||
val polymarketHandler = registry.addHandler(polymarketWebSocketHandler, "/ws/polymarket")
|
||||
if (origins.isNotEmpty()) {
|
||||
polymarketHandler.setAllowedOrigins(*origins)
|
||||
} else {
|
||||
// 使用 setAllowedOriginPatterns 替代 setAllowedOrigins("*"),更安全
|
||||
polymarketHandler.setAllowedOriginPatterns("*")
|
||||
}
|
||||
|
||||
// 统一 WebSocket 端点(所有推送服务统一使用此路径,通过 channel 区分)
|
||||
// 支持的频道:position(仓位推送)、order(订单推送,待实现)等
|
||||
// 支持的频道:position(仓位推送)、order(订单推送)等
|
||||
// 需要 JWT 鉴权
|
||||
registry.addHandler(unifiedWebSocketHandler, "/ws")
|
||||
.addInterceptors(webSocketAuthInterceptor) // 添加鉴权拦截器
|
||||
.setAllowedOrigins("*") // 生产环境应该配置具体的域名
|
||||
val unifiedHandler = registry.addHandler(unifiedWebSocketHandler, "/ws")
|
||||
.addInterceptors(webSocketAuthInterceptor)
|
||||
if (origins.isNotEmpty()) {
|
||||
unifiedHandler.setAllowedOrigins(*origins)
|
||||
} else {
|
||||
unifiedHandler.setAllowedOriginPatterns("*")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.wrbug.polymarketbot.controller.auth
|
||||
import com.wrbug.polymarketbot.dto.*
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.service.auth.AuthService
|
||||
import com.wrbug.polymarketbot.service.auth.WebSocketTicketService
|
||||
import jakarta.servlet.http.HttpServletRequest
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.MessageSource
|
||||
@@ -16,7 +17,8 @@ import org.springframework.web.bind.annotation.*
|
||||
@RequestMapping("/api/auth")
|
||||
class AuthController(
|
||||
private val authService: AuthService,
|
||||
private val messageSource: MessageSource
|
||||
private val messageSource: MessageSource,
|
||||
private val webSocketTicketService: WebSocketTicketService
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(AuthController::class.java)
|
||||
@@ -25,7 +27,10 @@ class AuthController(
|
||||
* 登录接口
|
||||
*/
|
||||
@PostMapping("/login")
|
||||
fun login(@RequestBody request: LoginRequest): ResponseEntity<ApiResponse<LoginResponse>> {
|
||||
fun login(
|
||||
@RequestBody request: LoginRequest,
|
||||
httpRequest: HttpServletRequest
|
||||
): ResponseEntity<ApiResponse<LoginResponse>> {
|
||||
return try {
|
||||
if (request.username.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_EMPTY, "用户名不能为空", messageSource))
|
||||
@@ -33,15 +38,19 @@ class AuthController(
|
||||
if (request.password.isBlank()) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_EMPTY, "密码不能为空", messageSource))
|
||||
}
|
||||
|
||||
val result = authService.login(request.username, request.password)
|
||||
|
||||
val ipAddress = getClientIpAddress(httpRequest)
|
||||
val result = authService.login(request.username, request.password, ipAddress)
|
||||
result.fold(
|
||||
onSuccess = { loginResponse ->
|
||||
ResponseEntity.ok(ApiResponse.success(loginResponse))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("登录失败: ${e.message}", e)
|
||||
when (e) {
|
||||
is IllegalStateException -> {
|
||||
// 限速或锁定错误
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.AUTH_ERROR, e.message ?: "登录失败", messageSource))
|
||||
}
|
||||
is IllegalArgumentException -> {
|
||||
if (e.message == ErrorCode.AUTH_USERNAME_OR_PASSWORD_ERROR.message) {
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.AUTH_USERNAME_OR_PASSWORD_ERROR, messageSource = messageSource))
|
||||
@@ -49,15 +58,36 @@ class AuthController(
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_ERROR, e.message, messageSource))
|
||||
}
|
||||
}
|
||||
else -> ResponseEntity.ok(ApiResponse.error(ErrorCode.AUTH_ERROR, "登录失败: ${e.message}", messageSource))
|
||||
else -> ResponseEntity.ok(ApiResponse.error(ErrorCode.AUTH_ERROR, "登录失败", messageSource))
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("登录异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.AUTH_ERROR, "登录失败: ${e.message}", messageSource))
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.AUTH_ERROR, "登录失败", messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端IP地址
|
||||
*/
|
||||
private fun getClientIpAddress(request: HttpServletRequest): String {
|
||||
var ip = request.getHeader("X-Forwarded-For")
|
||||
if (ip.isNullOrBlank() || "unknown".equals(ip, ignoreCase = true)) {
|
||||
ip = request.getHeader("X-Real-IP")
|
||||
}
|
||||
if (ip.isNullOrBlank() || "unknown".equals(ip, ignoreCase = true)) {
|
||||
ip = request.getHeader("Proxy-Client-IP")
|
||||
}
|
||||
if (ip.isNullOrBlank() || "unknown".equals(ip, ignoreCase = true)) {
|
||||
ip = request.remoteAddr
|
||||
}
|
||||
// 处理多个IP的情况
|
||||
if (ip.contains(",")) {
|
||||
ip = ip.split(",")[0].trim()
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置密码接口
|
||||
@@ -132,5 +162,27 @@ class AuthController(
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, "检查首次使用失败: ${e.message}", messageSource))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 WebSocket 连接票据
|
||||
* 返回一个短期有效(30秒)的一次性票据,用于 WebSocket 连接认证
|
||||
* 避免在 WebSocket URL 中暴露 JWT
|
||||
*/
|
||||
@PostMapping("/ws-ticket")
|
||||
fun getWebSocketTicket(httpRequest: HttpServletRequest): ResponseEntity<ApiResponse<WebSocketTicketResponse>> {
|
||||
return try {
|
||||
// 从请求属性中获取用户名(由 JWT 拦截器设置)
|
||||
val username = httpRequest.getAttribute("username") as? String
|
||||
if (username == null) {
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.AUTH_ERROR, "未认证", messageSource))
|
||||
}
|
||||
|
||||
val ticket = webSocketTicketService.generateTicket(username)
|
||||
ResponseEntity.ok(ApiResponse.success(WebSocketTicketResponse(ticket = ticket)))
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取 WebSocket 票据异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_ERROR, "获取票据失败", messageSource))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+15
-11
@@ -4,8 +4,10 @@ import com.wrbug.polymarketbot.api.LatestPriceResponse
|
||||
import com.wrbug.polymarketbot.dto.*
|
||||
import com.wrbug.polymarketbot.enums.ErrorCode
|
||||
import com.wrbug.polymarketbot.service.accounts.AccountService
|
||||
import com.wrbug.polymarketbot.service.common.MarketPriceService
|
||||
import com.wrbug.polymarketbot.service.common.PolymarketClobService
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.math.BigDecimal
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.MessageSource
|
||||
import org.springframework.http.ResponseEntity
|
||||
@@ -20,14 +22,16 @@ import org.springframework.web.bind.annotation.*
|
||||
class MarketController(
|
||||
private val accountService: AccountService,
|
||||
private val clobService: PolymarketClobService,
|
||||
private val marketPriceService: MarketPriceService,
|
||||
private val messageSource: MessageSource
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(MarketController::class.java)
|
||||
|
||||
/**
|
||||
* 获取市场价格(通过 Gamma API)
|
||||
* 使用 Gamma API 获取价格信息,因为 Gamma API 支持 condition_ids 参数
|
||||
* 获取市场价格
|
||||
* 使用 MarketPriceService 获取当前市场价格(支持多数据源降级)
|
||||
* 返回当前价格,前端接收后自行填充到 bestBid 字段
|
||||
*/
|
||||
@PostMapping("/price")
|
||||
fun getMarketPrice(@RequestBody request: MarketPriceRequest): ResponseEntity<ApiResponse<MarketPriceResponse>> {
|
||||
@@ -36,16 +40,16 @@ class MarketController(
|
||||
return ResponseEntity.ok(ApiResponse.error(ErrorCode.PARAM_MARKET_ID_EMPTY, messageSource = messageSource))
|
||||
}
|
||||
|
||||
val result = runBlocking { accountService.getMarketPrice(request.marketId, request.outcomeIndex) }
|
||||
result.fold(
|
||||
onSuccess = { response ->
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.error("获取市场价格失败: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_MARKET_PRICE_FETCH_FAILED, e.message, messageSource))
|
||||
}
|
||||
val outcomeIndex = request.outcomeIndex ?: 0
|
||||
val price = runBlocking {
|
||||
marketPriceService.getCurrentMarketPrice(request.marketId, outcomeIndex)
|
||||
}
|
||||
|
||||
val response = MarketPriceResponse(
|
||||
marketId = request.marketId,
|
||||
currentPrice = price.toString()
|
||||
)
|
||||
ResponseEntity.ok(ApiResponse.success(response))
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取市场价格异常: ${e.message}", e)
|
||||
ResponseEntity.ok(ApiResponse.error(ErrorCode.SERVER_MARKET_PRICE_FETCH_FAILED, e.message, messageSource))
|
||||
|
||||
@@ -7,7 +7,8 @@ data class AccountImportRequest(
|
||||
val privateKey: String, // 私钥(前端加密后传输)
|
||||
val walletAddress: String, // 钱包地址(前端从私钥推导,用于验证)
|
||||
val accountName: String? = null,
|
||||
val isEnabled: Boolean = true // 是否启用(用于订单推送等功能的开关)
|
||||
val isEnabled: Boolean = true, // 是否启用(用于订单推送等功能的开关)
|
||||
val walletType: String = "magic" // 钱包类型:magic(邮箱/OAuth登录)或 safe(MetaMask浏览器钱包)
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -72,6 +73,7 @@ data class AccountDto(
|
||||
val proxyAddress: String, // Polymarket 代理钱包地址
|
||||
val accountName: String?,
|
||||
val isEnabled: Boolean, // 是否启用(用于订单推送等功能的开关)
|
||||
val walletType: String = "magic", // 钱包类型:magic(邮箱/OAuth登录)或 safe(MetaMask浏览器钱包)
|
||||
val apiKeyConfigured: Boolean, // API Key 是否已配置(不返回实际 Key)
|
||||
val apiSecretConfigured: Boolean, // API Secret 是否已配置
|
||||
val apiPassphraseConfigured: Boolean, // API Passphrase 是否已配置
|
||||
@@ -195,14 +197,11 @@ data class LatestPriceRequest(
|
||||
)
|
||||
|
||||
/**
|
||||
* 市场价格响应
|
||||
* 市场当前价格响应
|
||||
*/
|
||||
data class MarketPriceResponse(
|
||||
val marketId: String,
|
||||
val lastPrice: String?, // 最新成交价
|
||||
val bestBid: String?, // 最优买价(用于卖出参考)
|
||||
val bestAsk: String?, // 最优卖价(用于买入参考)
|
||||
val midpoint: String? // 中间价
|
||||
val currentPrice: String // 当前价格(通过 MarketPriceService 获取,支持多数据源降级)
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,3 +14,10 @@ data class CheckFirstUseResponse(
|
||||
val isFirstUse: Boolean
|
||||
)
|
||||
|
||||
/**
|
||||
* WebSocket 票据响应
|
||||
*/
|
||||
data class WebSocketTicketResponse(
|
||||
val ticket: String
|
||||
)
|
||||
|
||||
|
||||
@@ -40,6 +40,9 @@ data class Account(
|
||||
@Column(name = "is_enabled", nullable = false)
|
||||
val isEnabled: Boolean = true, // 是否启用(用于订单推送等功能的开关)
|
||||
|
||||
@Column(name = "wallet_type", nullable = false, length = 20)
|
||||
val walletType: String = "magic", // 钱包类型:magic(邮箱/OAuth登录)或 safe(MetaMask浏览器钱包)
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ data class CopyTrading(
|
||||
@Column(name = "copy_mode", nullable = false, length = 10)
|
||||
val copyMode: String = "RATIO", // "RATIO" 或 "FIXED"
|
||||
|
||||
@Column(name = "copy_ratio", nullable = false, precision = 10, scale = 2)
|
||||
@Column(name = "copy_ratio", nullable = false, precision = 20, scale = 8)
|
||||
val copyRatio: BigDecimal = BigDecimal.ONE, // 仅在 copyMode="RATIO" 时生效
|
||||
|
||||
@Column(name = "fixed_amount", precision = 20, scale = 8)
|
||||
|
||||
@@ -20,7 +20,7 @@ data class CopyTradingTemplate(
|
||||
@Column(name = "copy_mode", nullable = false, length = 10)
|
||||
val copyMode: String = "RATIO", // "RATIO" 或 "FIXED"
|
||||
|
||||
@Column(name = "copy_ratio", nullable = false, precision = 10, scale = 2)
|
||||
@Column(name = "copy_ratio", nullable = false, precision = 20, scale = 8)
|
||||
val copyRatio: BigDecimal = BigDecimal.ONE, // 仅在 copyMode="RATIO" 时生效
|
||||
|
||||
@Column(name = "fixed_amount", precision = 20, scale = 8)
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.wrbug.polymarketbot.entity
|
||||
|
||||
import jakarta.persistence.*
|
||||
|
||||
/**
|
||||
* 失败交易实体
|
||||
* 记录处理失败的交易信息
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "failed_trade")
|
||||
data class FailedTrade(
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
val id: Long? = null,
|
||||
|
||||
@Column(name = "leader_id", nullable = false)
|
||||
val leaderId: Long,
|
||||
|
||||
@Column(name = "leader_trade_id", nullable = false, length = 100)
|
||||
val leaderTradeId: String, // Leader 的交易ID
|
||||
|
||||
@Column(name = "trade_type", nullable = false, length = 10)
|
||||
val tradeType: String, // BUY 或 SELL
|
||||
|
||||
@Column(name = "copy_trading_id", nullable = false)
|
||||
val copyTradingId: Long,
|
||||
|
||||
@Column(name = "account_id", nullable = false)
|
||||
val accountId: Long,
|
||||
|
||||
@Column(name = "market_id", nullable = false, length = 100)
|
||||
val marketId: String,
|
||||
|
||||
@Column(name = "side", nullable = false, length = 10)
|
||||
val side: String, // YES/NO
|
||||
|
||||
@Column(name = "price", nullable = false, length = 50)
|
||||
val price: String, // 价格(字符串格式)
|
||||
|
||||
@Column(name = "size", nullable = false, length = 50)
|
||||
val size: String, // 数量(字符串格式)
|
||||
|
||||
@Column(name = "error_message", columnDefinition = "TEXT")
|
||||
val errorMessage: String? = null, // 错误信息
|
||||
|
||||
@Column(name = "retry_count", nullable = false)
|
||||
val retryCount: Int = 0, // 重试次数
|
||||
|
||||
@Column(name = "failed_at", nullable = false)
|
||||
val failedAt: Long = System.currentTimeMillis(),
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
val createdAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
+29
@@ -55,5 +55,34 @@ interface CopyOrderTrackingRepository : JpaRepository<CopyOrderTracking, Long> {
|
||||
* 查询未发送通知的买入订单(用于轮询更新)
|
||||
*/
|
||||
fun findByNotificationSentFalse(): List<CopyOrderTracking>
|
||||
|
||||
/**
|
||||
* 查询指定时间之前创建的订单(用于检查30秒后未成交的订单)
|
||||
*/
|
||||
@Query("SELECT t FROM CopyOrderTracking t WHERE t.createdAt <= :beforeTime")
|
||||
fun findByCreatedAtBefore(beforeTime: Long): List<CopyOrderTracking>
|
||||
|
||||
/**
|
||||
* 查询指定时间之前创建且状态不为指定状态的订单
|
||||
*/
|
||||
fun findByCreatedAtBeforeAndStatusNot(beforeTime: Long, status: String): List<CopyOrderTracking>
|
||||
|
||||
/**
|
||||
* 查询指定跟单配置下的活跃仓位数量
|
||||
* 活跃仓位定义为 remainingQuantity > 0 的不同 (marketId, outcomeIndex) 组合
|
||||
*/
|
||||
@Query("SELECT COUNT(DISTINCT CONCAT(t.marketId, '_', COALESCE(t.outcomeIndex, -1))) FROM CopyOrderTracking t WHERE t.copyTradingId = :copyTradingId AND t.remainingQuantity > 0")
|
||||
fun countActivePositions(copyTradingId: Long): Int
|
||||
|
||||
/**
|
||||
* 检查指定市场是否存在活跃仓位
|
||||
*/
|
||||
fun existsByCopyTradingIdAndMarketIdAndRemainingQuantityGreaterThan(copyTradingId: Long, marketId: String, remainingQuantity: BigDecimal): Boolean
|
||||
|
||||
/**
|
||||
* 计算指定跟单配置和市场下的当前持仓总价值 (成本价计算)
|
||||
*/
|
||||
@Query("SELECT SUM(t.remainingQuantity * t.price) FROM CopyOrderTracking t WHERE t.copyTradingId = :copyTradingId AND t.marketId = :marketId AND t.remainingQuantity > 0")
|
||||
fun sumCurrentPositionValueByMarket(copyTradingId: Long, marketId: String): BigDecimal?
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.wrbug.polymarketbot.repository
|
||||
|
||||
import com.wrbug.polymarketbot.entity.FailedTrade
|
||||
import org.springframework.data.jpa.repository.JpaRepository
|
||||
import org.springframework.stereotype.Repository
|
||||
|
||||
/**
|
||||
* 失败交易Repository
|
||||
*/
|
||||
@Repository
|
||||
interface FailedTradeRepository : JpaRepository<FailedTrade, Long> {
|
||||
|
||||
/**
|
||||
* 根据Leader ID和交易ID查询
|
||||
*/
|
||||
fun findByLeaderIdAndLeaderTradeId(leaderId: Long, leaderTradeId: String): FailedTrade?
|
||||
|
||||
/**
|
||||
* 检查是否存在失败的交易
|
||||
*/
|
||||
fun existsByLeaderIdAndLeaderTradeId(leaderId: Long, leaderTradeId: String): Boolean
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@ class AccountService(
|
||||
private val orderSigningService: OrderSigningService,
|
||||
private val cryptoUtils: CryptoUtils,
|
||||
private val telegramNotificationService: TelegramNotificationService? = null, // 可选,避免循环依赖
|
||||
private val relayClientService: RelayClientService
|
||||
private val relayClientService: RelayClientService,
|
||||
private val jsonUtils: JsonUtils
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(AccountService::class.java)
|
||||
@@ -98,8 +99,9 @@ class AccountService(
|
||||
}
|
||||
|
||||
// 5. 获取代理地址(必须成功,否则导入失败)
|
||||
// 根据用户选择的钱包类型计算代理地址
|
||||
val proxyAddress = runBlocking {
|
||||
val proxyResult = blockchainService.getProxyAddress(request.walletAddress)
|
||||
val proxyResult = blockchainService.getProxyAddress(request.walletAddress, request.walletType)
|
||||
if (proxyResult.isSuccess) {
|
||||
val address = proxyResult.getOrNull()
|
||||
if (address != null) {
|
||||
@@ -149,6 +151,7 @@ class AccountService(
|
||||
accountName = accountName,
|
||||
isDefault = false, // 不再支持默认账户
|
||||
isEnabled = request.isEnabled,
|
||||
walletType = request.walletType, // 保存钱包类型
|
||||
createdAt = System.currentTimeMillis(),
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
@@ -225,11 +228,12 @@ class AccountService(
|
||||
|
||||
/**
|
||||
* 查询账户列表
|
||||
* 列表接口只返回基本信息,不查询统计信息(统计信息只在详情接口中查询)
|
||||
*/
|
||||
fun getAccountList(): Result<AccountListResponse> {
|
||||
return try {
|
||||
val accounts = accountRepository.findAllByOrderByCreatedAtAsc()
|
||||
val accountDtos = accounts.map { toDto(it) }
|
||||
val accountDtos = accounts.map { toBasicDto(it) }
|
||||
|
||||
Result.success(
|
||||
AccountListResponse(
|
||||
@@ -350,7 +354,30 @@ class AccountService(
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为 DTO
|
||||
* 转换为基础 DTO(列表使用,不包含统计信息)
|
||||
* 列表接口只返回基本信息,不查询统计信息,以提高性能
|
||||
*/
|
||||
private fun toBasicDto(account: Account): AccountDto {
|
||||
return AccountDto(
|
||||
id = account.id!!,
|
||||
walletAddress = account.walletAddress,
|
||||
proxyAddress = account.proxyAddress,
|
||||
accountName = account.accountName,
|
||||
isEnabled = account.isEnabled,
|
||||
walletType = account.walletType,
|
||||
apiKeyConfigured = account.apiKey != null,
|
||||
apiSecretConfigured = account.apiSecret != null,
|
||||
apiPassphraseConfigured = account.apiPassphrase != null,
|
||||
totalOrders = null,
|
||||
totalPnl = null,
|
||||
activeOrders = null,
|
||||
completedOrders = null,
|
||||
positionCount = null
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为完整 DTO(详情使用,包含交易统计数据)
|
||||
* 包含交易统计数据(总订单数、总盈亏、活跃订单数、已完成订单数、持仓数量)
|
||||
*/
|
||||
private fun toDto(account: Account): AccountDto {
|
||||
@@ -362,6 +389,7 @@ class AccountService(
|
||||
proxyAddress = account.proxyAddress,
|
||||
accountName = account.accountName,
|
||||
isEnabled = account.isEnabled,
|
||||
walletType = account.walletType,
|
||||
apiKeyConfigured = account.apiKey != null,
|
||||
apiSecretConfigured = account.apiSecret != null,
|
||||
apiPassphraseConfigured = account.apiPassphrase != null,
|
||||
@@ -1121,7 +1149,7 @@ class AccountService(
|
||||
// 如果目标 outcome 不是第一个(index != 0),需要转换价格
|
||||
// 对于二元市场:第二个 outcome 的价格 = 1 - 第一个 outcome 的价格
|
||||
if (outcomeIndex != null && outcomeIndex > 0) {
|
||||
val outcomes = JsonUtils.parseStringArray(market.outcomes)
|
||||
val outcomes = jsonUtils.parseStringArray(market.outcomes)
|
||||
// 只对二元市场进行价格转换
|
||||
if (outcomes.size == 2) {
|
||||
// 保存原始第一个 outcome 的价格
|
||||
@@ -1153,13 +1181,13 @@ class AccountService(
|
||||
null
|
||||
}
|
||||
|
||||
// 优先使用 lastPrice(最近成交价),如果没有则使用 bestBid,最后使用 midpoint
|
||||
val currentPrice = lastPrice ?: bestBid ?: midpoint ?: "0"
|
||||
|
||||
Result.success(
|
||||
MarketPriceResponse(
|
||||
marketId = marketId,
|
||||
lastPrice = lastPrice,
|
||||
bestBid = bestBid,
|
||||
bestAsk = bestAsk,
|
||||
midpoint = midpoint
|
||||
currentPrice = currentPrice
|
||||
)
|
||||
)
|
||||
} else {
|
||||
|
||||
+20
-115
@@ -21,8 +21,7 @@ import org.springframework.context.i18n.LocaleContextHolder
|
||||
import com.wrbug.polymarketbot.service.system.SystemConfigService
|
||||
import com.wrbug.polymarketbot.service.system.RelayClientService
|
||||
import com.wrbug.polymarketbot.service.system.TelegramNotificationService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.JsonUtils
|
||||
import com.wrbug.polymarketbot.service.common.MarketPriceService
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigDecimal
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
@@ -45,7 +44,7 @@ class PositionCheckService(
|
||||
private val telegramNotificationService: TelegramNotificationService?,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val messageSource: MessageSource,
|
||||
private val retrofitFactory: RetrofitFactory
|
||||
private val marketPriceService: MarketPriceService
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(PositionCheckService::class.java)
|
||||
@@ -383,9 +382,15 @@ class PositionCheckService(
|
||||
|
||||
if (ordersToMarkAsSold.isNotEmpty()) {
|
||||
// 有订单创建时间超过2分钟,认为仓位已被出售
|
||||
try {
|
||||
val currentPrice = getCurrentMarketPrice(marketId, outcomeIndex)
|
||||
updateOrdersAsSold(ordersToMarkAsSold, currentPrice, copyTrading.id, marketId, outcomeIndex)
|
||||
logger.debug("仓位不存在且订单创建时间超过2分钟,标记为已卖出: marketId=$marketId, outcomeIndex=$outcomeIndex, orderCount=${ordersToMarkAsSold.size}")
|
||||
} catch (e: Exception) {
|
||||
logger.warn("无法获取市场价格,跳过标记为已卖出: marketId=$marketId, outcomeIndex=$outcomeIndex, error=${e.message}")
|
||||
// 无法获取价格时,跳过该市场的处理,等待下次检查时再试
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
// 订单创建时间不足2分钟,可能是刚创建的订单,暂时不处理
|
||||
logger.debug("仓位不存在但订单创建时间不足2分钟,暂不标记为已卖出: marketId=$marketId, outcomeIndex=$outcomeIndex, orderCount=${orders.size}, oldestOrderAge=${orders.minOfOrNull { now - it.createdAt }?.let { "${it}ms" } ?: "N/A"}")
|
||||
@@ -414,9 +419,15 @@ class PositionCheckService(
|
||||
}
|
||||
|
||||
// 如果已成交数量 > 0,按FIFO顺序匹配订单
|
||||
try {
|
||||
val currentPrice = getCurrentMarketPrice(marketId, outcomeIndex)
|
||||
updateOrdersAsSoldByFIFO(orders, soldQuantity, currentPrice,
|
||||
copyTrading.id, marketId, outcomeIndex)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("无法获取市场价格,跳过FIFO匹配: marketId=$marketId, outcomeIndex=$outcomeIndex, error=${e.message}")
|
||||
// 无法获取价格时,跳过该市场的处理,等待下次检查时再试
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -427,118 +438,10 @@ class PositionCheckService(
|
||||
|
||||
/**
|
||||
* 获取当前市场最新价(用于更新订单卖出价)
|
||||
* 优先使用 bestBid(最优买价),如果没有则使用 midpoint(中间价)
|
||||
* 如果市场已关闭:
|
||||
* - 该 outcome 赢了,返回 1
|
||||
* - 该 outcome 输了,返回 0
|
||||
* 委托给 MarketPriceService 处理
|
||||
*/
|
||||
private suspend fun getCurrentMarketPrice(marketId: String, outcomeIndex: Int): BigDecimal {
|
||||
return try {
|
||||
// 先获取市场信息,检查市场是否已关闭
|
||||
val gammaApi = retrofitFactory.createGammaApi()
|
||||
val marketResponse = gammaApi.listMarkets(conditionIds = listOf(marketId))
|
||||
|
||||
if (marketResponse.isSuccessful && marketResponse.body() != null) {
|
||||
val markets = marketResponse.body()!!
|
||||
val market = markets.firstOrNull()
|
||||
|
||||
if (market != null && market.closed == true) {
|
||||
// 市场已关闭,检查该 outcome 是赢了还是输了
|
||||
val outcomeResult = checkOutcomeResult(market, outcomeIndex)
|
||||
when (outcomeResult) {
|
||||
OutcomeResult.WON -> {
|
||||
logger.info("市场已关闭且该 outcome 赢了,返回价格为 1: marketId=$marketId, outcomeIndex=$outcomeIndex")
|
||||
return BigDecimal.ONE
|
||||
}
|
||||
OutcomeResult.LOST -> {
|
||||
logger.info("市场已关闭且该 outcome 输了,返回价格为 0: marketId=$marketId, outcomeIndex=$outcomeIndex")
|
||||
return BigDecimal.ZERO
|
||||
}
|
||||
OutcomeResult.UNKNOWN -> {
|
||||
// 无法判断,继续使用正常价格逻辑
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 如果市场未关闭或无法判断输赢,获取正常价格
|
||||
val priceResult = accountService.getMarketPrice(marketId, outcomeIndex)
|
||||
val marketPrice = priceResult.getOrNull()
|
||||
if (marketPrice != null) {
|
||||
// 优先使用 bestBid(最优买价,用于卖出参考),如果没有则使用 midpoint
|
||||
val priceStr = marketPrice.bestBid ?: marketPrice.midpoint ?: marketPrice.lastPrice
|
||||
priceStr?.toSafeBigDecimal() ?: BigDecimal.ZERO
|
||||
} else {
|
||||
BigDecimal.ZERO
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取市场最新价失败: marketId=$marketId, outcomeIndex=$outcomeIndex, error=${e.message}", e)
|
||||
BigDecimal.ZERO
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Outcome 结果枚举
|
||||
*/
|
||||
private enum class OutcomeResult {
|
||||
WON, // 赢了
|
||||
LOST, // 输了
|
||||
UNKNOWN // 无法判断
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查该 outcome 的结果(赢了、输了或无法判断)
|
||||
* @param market 市场信息
|
||||
* @param outcomeIndex outcome 索引
|
||||
* @return OutcomeResult
|
||||
*/
|
||||
private fun checkOutcomeResult(market: com.wrbug.polymarketbot.api.MarketResponse, outcomeIndex: Int): OutcomeResult {
|
||||
return try {
|
||||
// 优先使用 outcomePrices(结算价格数组)
|
||||
val outcomePrices = market.outcomePrices
|
||||
if (outcomePrices != null && outcomePrices.isNotBlank()) {
|
||||
val prices = JsonUtils.parseStringArray(outcomePrices)
|
||||
if (outcomeIndex < prices.size) {
|
||||
val price = prices[outcomeIndex].toSafeBigDecimal()
|
||||
// 如果价格 >= 0.99,认为赢了
|
||||
if (price >= BigDecimal("0.99")) {
|
||||
return OutcomeResult.WON
|
||||
}
|
||||
// 如果价格 <= 0.01,认为输了
|
||||
if (price <= BigDecimal("0.01")) {
|
||||
return OutcomeResult.LOST
|
||||
}
|
||||
// 其他情况,无法判断
|
||||
return OutcomeResult.UNKNOWN
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有 outcomePrices,使用 bestBid 和 bestAsk 判断
|
||||
val bestBid = market.bestBid ?: 0.0
|
||||
val bestAsk = market.bestAsk ?: 0.0
|
||||
|
||||
// 如果目标 outcome 不是第一个(index != 0),需要转换价格
|
||||
val targetBid = if (outcomeIndex > 0) {
|
||||
// 第二个 outcome 的 bestBid = 1 - 第一个 outcome 的 bestAsk
|
||||
BigDecimal.ONE.subtract(BigDecimal.valueOf(bestAsk))
|
||||
} else {
|
||||
BigDecimal.valueOf(bestBid)
|
||||
}
|
||||
|
||||
// 如果 bestBid >= 0.99,认为赢了
|
||||
if (targetBid >= BigDecimal("0.99")) {
|
||||
return OutcomeResult.WON
|
||||
}
|
||||
// 如果 bestBid <= 0.01,认为输了
|
||||
if (targetBid <= BigDecimal("0.01")) {
|
||||
return OutcomeResult.LOST
|
||||
}
|
||||
// 其他情况,无法判断
|
||||
OutcomeResult.UNKNOWN
|
||||
} catch (e: Exception) {
|
||||
logger.warn("检查 outcome 结果失败: marketId=${market.conditionId}, outcomeIndex=$outcomeIndex, error=${e.message}", e)
|
||||
OutcomeResult.UNKNOWN
|
||||
}
|
||||
return marketPriceService.getCurrentMarketPrice(marketId, outcomeIndex)
|
||||
}
|
||||
|
||||
|
||||
@@ -628,7 +531,8 @@ class PositionCheckService(
|
||||
outcomeIndex = outcomeIndex,
|
||||
totalMatchedQuantity = totalMatchedQuantity,
|
||||
sellPrice = sellPrice,
|
||||
totalRealizedPnl = totalRealizedPnl
|
||||
totalRealizedPnl = totalRealizedPnl,
|
||||
priceUpdated = true // 自动生成的订单,直接标记为已处理,不发送通知
|
||||
)
|
||||
|
||||
val savedRecord = sellMatchRecordRepository.save(matchRecord)
|
||||
@@ -742,7 +646,8 @@ class PositionCheckService(
|
||||
outcomeIndex = outcomeIndex,
|
||||
totalMatchedQuantity = totalMatchedQuantity,
|
||||
sellPrice = sellPrice,
|
||||
totalRealizedPnl = totalRealizedPnl
|
||||
totalRealizedPnl = totalRealizedPnl,
|
||||
priceUpdated = true // 自动生成的订单,直接标记为已处理,不发送通知
|
||||
)
|
||||
|
||||
val savedRecord = sellMatchRecordRepository.save(matchRecord)
|
||||
|
||||
@@ -31,22 +31,44 @@ class AuthService(
|
||||
private lateinit var resetPasswordKey: String
|
||||
|
||||
/**
|
||||
* 登录
|
||||
* 登录(带IP限速保护)
|
||||
*/
|
||||
fun login(username: String, password: String): Result<LoginResponse> {
|
||||
fun login(username: String, password: String, ipAddress: String): Result<LoginResponse> {
|
||||
return try {
|
||||
// 检查登录频率限制
|
||||
rateLimitService.checkLoginRateLimit(ipAddress).fold(
|
||||
onSuccess = { },
|
||||
onFailure = { e ->
|
||||
return Result.failure(IllegalStateException(e.message ?: "登录频率限制"))
|
||||
}
|
||||
)
|
||||
|
||||
val user = userRepository.findByUsername(username)
|
||||
?: return Result.failure(IllegalArgumentException(ErrorCode.AUTH_USERNAME_OR_PASSWORD_ERROR.message))
|
||||
|
||||
// 验证密码
|
||||
if (!passwordEncoder.matches(password, user.password)) {
|
||||
logger.warn("登录失败:密码错误,username=$username")
|
||||
if (user == null) {
|
||||
// 记录失败尝试
|
||||
val lockoutMsg = rateLimitService.recordLoginFailure(ipAddress)
|
||||
if (lockoutMsg != null) {
|
||||
return Result.failure(IllegalStateException(lockoutMsg))
|
||||
}
|
||||
return Result.failure(IllegalArgumentException(ErrorCode.AUTH_USERNAME_OR_PASSWORD_ERROR.message))
|
||||
}
|
||||
|
||||
|
||||
// 验证密码
|
||||
if (!passwordEncoder.matches(password, user.password)) {
|
||||
// 记录失败尝试
|
||||
val lockoutMsg = rateLimitService.recordLoginFailure(ipAddress)
|
||||
if (lockoutMsg != null) {
|
||||
return Result.failure(IllegalStateException(lockoutMsg))
|
||||
}
|
||||
return Result.failure(IllegalArgumentException(ErrorCode.AUTH_USERNAME_OR_PASSWORD_ERROR.message))
|
||||
}
|
||||
|
||||
// 登录成功,清除失败记录
|
||||
rateLimitService.clearLoginFailures(ipAddress)
|
||||
|
||||
// 生成JWT token(包含tokenVersion,用于使修改密码后的旧token失效)
|
||||
val token = jwtUtils.generateToken(username, user.tokenVersion)
|
||||
|
||||
|
||||
logger.info("用户登录成功:username=$username")
|
||||
Result.success(LoginResponse(token = token))
|
||||
} catch (e: Exception) {
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.wrbug.polymarketbot.service.auth
|
||||
|
||||
import org.springframework.scheduling.annotation.Scheduled
|
||||
import org.springframework.stereotype.Service
|
||||
import java.security.SecureRandom
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* WebSocket 票据服务
|
||||
* 用于生成短期有效的一次性票据,避免在 WebSocket URL 中暴露 JWT
|
||||
*/
|
||||
@Service
|
||||
class WebSocketTicketService {
|
||||
|
||||
companion object {
|
||||
// 票据有效期(30秒)
|
||||
private const val TICKET_VALIDITY_MS = 30_000L
|
||||
|
||||
// 票据长度(32字节 = 64个十六进制字符)
|
||||
private const val TICKET_LENGTH = 32
|
||||
}
|
||||
|
||||
private val secureRandom = SecureRandom()
|
||||
|
||||
// 存储票据:ticket -> TicketInfo
|
||||
private val tickets = ConcurrentHashMap<String, TicketInfo>()
|
||||
|
||||
/**
|
||||
* 票据信息
|
||||
*/
|
||||
data class TicketInfo(
|
||||
val username: String,
|
||||
val createdAt: Long,
|
||||
val expiresAt: Long
|
||||
)
|
||||
|
||||
/**
|
||||
* 为用户生成 WebSocket 连接票据
|
||||
* @param username 用户名
|
||||
* @return 一次性票据
|
||||
*/
|
||||
fun generateTicket(username: String): String {
|
||||
// 清理过期票据
|
||||
cleanupExpiredTickets()
|
||||
|
||||
// 生成随机票据
|
||||
val bytes = ByteArray(TICKET_LENGTH)
|
||||
secureRandom.nextBytes(bytes)
|
||||
val ticket = bytes.joinToString("") { "%02x".format(it) }
|
||||
|
||||
val now = System.currentTimeMillis()
|
||||
tickets[ticket] = TicketInfo(
|
||||
username = username,
|
||||
createdAt = now,
|
||||
expiresAt = now + TICKET_VALIDITY_MS
|
||||
)
|
||||
|
||||
return ticket
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证并消费票据(一次性使用)
|
||||
* @param ticket 票据
|
||||
* @return 用户名,如果票据无效则返回 null
|
||||
*/
|
||||
fun validateAndConsumeTicket(ticket: String): String? {
|
||||
val ticketInfo = tickets.remove(ticket) ?: return null
|
||||
|
||||
// 检查是否过期
|
||||
if (System.currentTimeMillis() > ticketInfo.expiresAt) {
|
||||
return null
|
||||
}
|
||||
|
||||
return ticketInfo.username
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理过期票据
|
||||
*/
|
||||
private fun cleanupExpiredTickets() {
|
||||
val now = System.currentTimeMillis()
|
||||
tickets.entries.removeIf { it.value.expiresAt < now }
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时清理过期票据(每分钟执行一次)
|
||||
* 防止过期票据长时间占用内存
|
||||
*/
|
||||
@Scheduled(fixedRate = 60_000) // 60秒 = 60000毫秒
|
||||
fun scheduledCleanup() {
|
||||
cleanupExpiredTickets()
|
||||
}
|
||||
}
|
||||
+256
-21
@@ -1,5 +1,6 @@
|
||||
package com.wrbug.polymarketbot.service.common
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.wrbug.polymarketbot.api.EthereumRpcApi
|
||||
import com.wrbug.polymarketbot.api.JsonRpcRequest
|
||||
import com.wrbug.polymarketbot.api.JsonRpcResponse
|
||||
@@ -29,7 +30,8 @@ class BlockchainService(
|
||||
private val dataApiBaseUrl: String,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val relayClientService: RelayClientService,
|
||||
private val rpcNodeService: RpcNodeService
|
||||
private val rpcNodeService: RpcNodeService,
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(BlockchainService::class.java)
|
||||
@@ -37,9 +39,16 @@ class BlockchainService(
|
||||
// USDC 合约地址(Polygon 主网,Polymarket 使用 Polygon)
|
||||
private val usdcContractAddress = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
|
||||
|
||||
// Polymarket 代理工厂合约地址(Polygon 主网)
|
||||
// Polymarket Safe 代理工厂合约地址(Polygon 主网,用于 MetaMask 用户)
|
||||
// 合约地址: 0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b
|
||||
private val proxyFactoryContractAddress = "0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"
|
||||
private val safeProxyFactoryAddress = "0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"
|
||||
|
||||
// Polymarket Magic 代理工厂合约地址(Polygon 主网,用于邮箱/OAuth 登录用户)
|
||||
// 合约地址: 0xaB45c5A4B0c941a2F231C04C3f49182e1A254052
|
||||
private val magicProxyFactoryAddress = "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"
|
||||
|
||||
// Magic Proxy 的 init code hash(用于 CREATE2 计算)
|
||||
private val magicProxyInitCodeHash = "0xd21df8dc65880a8606f09fe0ce3df9b8869287ab0b058be05aa9e8af6330a00b"
|
||||
|
||||
// ConditionalTokens 合约地址(Polygon 主网)
|
||||
private val conditionalTokensAddress = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"
|
||||
@@ -64,7 +73,7 @@ class BlockchainService(
|
||||
Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketDataApi::class.java)
|
||||
}
|
||||
@@ -76,60 +85,162 @@ class BlockchainService(
|
||||
|
||||
/**
|
||||
* 获取 Polymarket 代理钱包地址
|
||||
* 通过 RPC 调用代理工厂合约获取用户的代理钱包地址
|
||||
* 根据指定的钱包类型返回对应的代理地址
|
||||
*
|
||||
* Polymarket 有两种代理钱包类型:
|
||||
* 1. Magic Proxy(邮箱/OAuth 登录用户)- 使用 CREATE2 计算地址
|
||||
* 2. Safe Proxy(MetaMask 钱包用户)- 通过合约调用获取地址
|
||||
*
|
||||
* @param walletAddress 用户的钱包地址(EOA)
|
||||
* @param walletType 钱包类型:"magic"(默认)或 "safe"
|
||||
* @return 代理钱包地址
|
||||
*/
|
||||
suspend fun getProxyAddress(walletAddress: String, walletType: String = "magic"): Result<String> {
|
||||
return try {
|
||||
when (walletType.lowercase()) {
|
||||
"safe" -> {
|
||||
// Safe Proxy(MetaMask 用户)
|
||||
val safeProxyResult = getSafeProxyAddress(walletAddress)
|
||||
if (safeProxyResult.isSuccess) {
|
||||
val safeProxyAddress = safeProxyResult.getOrNull()!!
|
||||
logger.debug("使用 Safe Proxy 地址: $safeProxyAddress")
|
||||
Result.success(safeProxyAddress)
|
||||
} else {
|
||||
Result.failure(safeProxyResult.exceptionOrNull() ?: Exception("获取 Safe Proxy 地址失败"))
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
// Magic Proxy(邮箱/OAuth 登录用户)- 默认
|
||||
val magicProxyAddress = calculateMagicProxyAddress(walletAddress)
|
||||
logger.debug("使用 Magic Proxy 地址: $magicProxyAddress")
|
||||
Result.success(magicProxyAddress)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取代理地址失败: ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 Magic Proxy 地址(使用 CREATE2)
|
||||
* 用于邮箱/OAuth 登录的用户
|
||||
*
|
||||
* CREATE2 地址计算公式:
|
||||
* address = keccak256(0xff ++ factory ++ salt ++ initCodeHash)[12:]
|
||||
* salt = keccak256(eoaAddress)
|
||||
*
|
||||
* @param walletAddress 用户的钱包地址(EOA)
|
||||
* @return Magic 代理钱包地址
|
||||
*/
|
||||
fun calculateMagicProxyAddress(walletAddress: String): String {
|
||||
// 计算 salt = keccak256(eoaAddress)
|
||||
val eoaBytes = EthereumUtils.hexToBytes(walletAddress.lowercase())
|
||||
val salt = EthereumUtils.keccak256(eoaBytes)
|
||||
|
||||
// 计算 CREATE2 地址
|
||||
// data = 0xff ++ factory ++ salt ++ initCodeHash
|
||||
val prefix = byteArrayOf(0xff.toByte())
|
||||
val factoryBytes = EthereumUtils.hexToBytes(magicProxyFactoryAddress)
|
||||
val initCodeHashBytes = EthereumUtils.hexToBytes(magicProxyInitCodeHash)
|
||||
|
||||
val data = prefix + factoryBytes + salt + initCodeHashBytes
|
||||
val hash = EthereumUtils.keccak256(data)
|
||||
|
||||
// 取后 20 字节作为地址
|
||||
return "0x" + hash.copyOfRange(12, 32).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Safe Proxy 地址
|
||||
* 通过 RPC 调用 Safe 代理工厂合约获取用户的代理钱包地址
|
||||
* 用于 MetaMask 钱包用户
|
||||
*
|
||||
* @param walletAddress 用户的钱包地址
|
||||
* @return 代理钱包地址
|
||||
*/
|
||||
suspend fun getProxyAddress(walletAddress: String): Result<String> {
|
||||
private suspend fun getSafeProxyAddress(walletAddress: String): Result<String> {
|
||||
return try {
|
||||
val rpcApi = polygonRpcApi
|
||||
|
||||
|
||||
// 计算函数选择器
|
||||
val functionSelector = EthereumUtils.getFunctionSelector(computeProxyAddressFunctionSignature)
|
||||
// 编码地址参数
|
||||
val encodedAddress = EthereumUtils.encodeAddress(walletAddress)
|
||||
// 构建调用数据
|
||||
val data = functionSelector + encodedAddress
|
||||
|
||||
|
||||
// 构建 JSON-RPC 请求
|
||||
val rpcRequest = JsonRpcRequest(
|
||||
method = "eth_call",
|
||||
params = listOf(
|
||||
mapOf(
|
||||
"to" to proxyFactoryContractAddress,
|
||||
"to" to safeProxyFactoryAddress,
|
||||
"data" to data
|
||||
),
|
||||
"latest"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
// 发送 RPC 请求
|
||||
val response = rpcApi.call(rpcRequest)
|
||||
|
||||
|
||||
if (!response.isSuccessful || response.body() == null) {
|
||||
throw Exception("RPC 请求失败: ${response.code()} ${response.message()}")
|
||||
return Result.failure(Exception("RPC 请求失败: ${response.code()} ${response.message()}"))
|
||||
}
|
||||
|
||||
|
||||
val rpcResponse = response.body()!!
|
||||
|
||||
|
||||
// 检查错误
|
||||
if (rpcResponse.error != null) {
|
||||
throw Exception("RPC 错误: ${rpcResponse.error.message}")
|
||||
return Result.failure(Exception("RPC 错误: ${rpcResponse.error.message}"))
|
||||
}
|
||||
|
||||
|
||||
// 使用 Gson 解析 result(JsonElement)
|
||||
val hexResult = rpcResponse.result?.asString
|
||||
?: throw Exception("RPC 响应格式错误: result 为空")
|
||||
|
||||
val hexResult = rpcResponse.result?.asString
|
||||
?: return Result.failure(Exception("RPC 响应格式错误: result 为空"))
|
||||
|
||||
// 解析代理地址
|
||||
val proxyAddress = EthereumUtils.decodeAddress(hexResult)
|
||||
|
||||
|
||||
Result.success(proxyAddress)
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取代理地址失败: ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查地址是否是合约
|
||||
* @param address 地址
|
||||
* @return 如果地址有代码(是合约)返回 true
|
||||
*/
|
||||
private suspend fun isContract(address: String): Boolean {
|
||||
return try {
|
||||
val rpcApi = polygonRpcApi
|
||||
|
||||
val rpcRequest = JsonRpcRequest(
|
||||
method = "eth_getCode",
|
||||
params = listOf(address, "latest")
|
||||
)
|
||||
|
||||
val response = rpcApi.call(rpcRequest)
|
||||
if (!response.isSuccessful || response.body() == null) {
|
||||
return false
|
||||
}
|
||||
|
||||
val rpcResponse = response.body()!!
|
||||
if (rpcResponse.error != null) {
|
||||
return false
|
||||
}
|
||||
|
||||
val code = rpcResponse.result?.asString ?: "0x"
|
||||
// 如果代码不是 "0x" 或 "0x0",则是合约
|
||||
code != "0x" && code != "0x0"
|
||||
} catch (e: Exception) {
|
||||
logger.warn("检查合约地址失败: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询账户 USDC 余额
|
||||
@@ -602,6 +713,130 @@ class BlockchainService(
|
||||
return Result.success(txHash)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从链上查询市场条件(Condition)的结算结果
|
||||
* 通过调用 ConditionalTokens 合约的 conditions mapping 和 payoutNumerators mapping
|
||||
*
|
||||
* @param conditionId 市场条件ID(bytes32,必须是 0x 开头的 66 位十六进制字符串)
|
||||
* @return Result<Pair<payoutDenominator, payouts>>
|
||||
* - payoutDenominator: 支付分母(通常为 1)
|
||||
* - payouts: 每个 outcome 的支付金额数组(0 或 1)
|
||||
* - 如果 payouts[outcomeIndex] == 1,表示该 outcome 赢了
|
||||
* - 如果 payouts[outcomeIndex] == 0,表示该 outcome 输了
|
||||
* - 如果 payouts 为空,表示市场尚未结算
|
||||
*/
|
||||
suspend fun getCondition(conditionId: String): Result<Pair<BigInteger, List<BigInteger>>> {
|
||||
return try {
|
||||
// 验证 conditionId 格式
|
||||
if (conditionId.isBlank() || !conditionId.startsWith("0x") || conditionId.length != 66) {
|
||||
return Result.failure(IllegalArgumentException("conditionId 格式错误,必须是 0x 开头的 66 位十六进制字符串"))
|
||||
}
|
||||
|
||||
val rpcApi = polygonRpcApi
|
||||
|
||||
// 1. 调用 conditions(bytes32) 获取 outcomeSlotCount 和 payoutDenominator
|
||||
// 注意:这是一个公开的 mapping,Solidity 自动生成的 getter
|
||||
// 函数签名: conditions(bytes32) returns (uint outcomeSlotCount, uint payoutDenominator)
|
||||
val conditionsFunctionSelector = EthereumUtils.getFunctionSelector("conditions(bytes32)")
|
||||
val encodedConditionId = EthereumUtils.encodeBytes32(conditionId)
|
||||
val conditionsData = conditionsFunctionSelector + encodedConditionId
|
||||
|
||||
// 构建 JSON-RPC 请求
|
||||
val conditionsRequest = JsonRpcRequest(
|
||||
method = "eth_call",
|
||||
params = listOf(
|
||||
mapOf(
|
||||
"to" to conditionalTokensAddress,
|
||||
"data" to conditionsData
|
||||
),
|
||||
"latest"
|
||||
)
|
||||
)
|
||||
|
||||
// 发送 RPC 请求
|
||||
val conditionsResponse = rpcApi.call(conditionsRequest)
|
||||
|
||||
if (!conditionsResponse.isSuccessful || conditionsResponse.body() == null) {
|
||||
return Result.failure(Exception("RPC 请求失败 (conditions): ${conditionsResponse.code()} ${conditionsResponse.message()}"))
|
||||
}
|
||||
|
||||
val conditionsRpcResponse = conditionsResponse.body()!!
|
||||
|
||||
// 检查错误
|
||||
if (conditionsRpcResponse.error != null) {
|
||||
// 记录完整的错误信息,包括 code 和 data
|
||||
val errorMsg = "RPC 错误 (code=${conditionsRpcResponse.error.code}): ${conditionsRpcResponse.error.message}, data=${conditionsRpcResponse.error.data}"
|
||||
logger.error("查询市场条件(conditions)出现RPC错误: conditionId=$conditionId, $errorMsg")
|
||||
logger.debug("RPC 请求详情: to=$conditionalTokensAddress, data=$conditionsData")
|
||||
return Result.failure(Exception(errorMsg))
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 result(JsonElement)
|
||||
val hexResult = conditionsRpcResponse.result?.asString
|
||||
?: return Result.failure(Exception("RPC 响应格式错误: result 为空"))
|
||||
|
||||
// 解析返回的 (outcomeSlotCount, payoutDenominator)
|
||||
val cleanHex = hexResult.removePrefix("0x")
|
||||
val outcomeSlotCountHex = cleanHex.substring(0, 64)
|
||||
val payoutDenominatorHex = cleanHex.substring(64, 128)
|
||||
|
||||
val outcomeSlotCount = BigInteger(outcomeSlotCountHex, 16).toInt()
|
||||
val payoutDenominator = BigInteger(payoutDenominatorHex, 16)
|
||||
|
||||
// 如果 outcomeSlotCount 为 0,说明市场尚未创建或不存在
|
||||
if (outcomeSlotCount <= 0) {
|
||||
logger.debug("市场尚未创建或不存在: conditionId=$conditionId, outcomeSlotCount=$outcomeSlotCount")
|
||||
return Result.success(Pair(BigInteger.ZERO, emptyList()))
|
||||
}
|
||||
|
||||
// 如果 payoutDenominator 为 0,说明市场尚未结算
|
||||
if (payoutDenominator == BigInteger.ZERO) {
|
||||
logger.debug("市场尚未结算: conditionId=$conditionId, payoutDenominator=$payoutDenominator")
|
||||
return Result.success(Pair(BigInteger.ZERO, emptyList()))
|
||||
}
|
||||
|
||||
// 2. 查询每个 outcome 的 payoutNumerators
|
||||
val payouts = mutableListOf<BigInteger>()
|
||||
for (i in 0 until outcomeSlotCount) {
|
||||
val payoutNumeratorsFunctionSelector = EthereumUtils.getFunctionSelector("payoutNumerators(bytes32,uint256)")
|
||||
val encodedIndex = EthereumUtils.encodeUint256(BigInteger.valueOf(i.toLong()))
|
||||
val payoutNumeratorsData = payoutNumeratorsFunctionSelector + encodedConditionId + encodedIndex
|
||||
|
||||
val payoutRequest = JsonRpcRequest(
|
||||
method = "eth_call",
|
||||
params = listOf(
|
||||
mapOf(
|
||||
"to" to conditionalTokensAddress,
|
||||
"data" to payoutNumeratorsData
|
||||
),
|
||||
"latest"
|
||||
)
|
||||
)
|
||||
|
||||
val payoutResponse = rpcApi.call(payoutRequest)
|
||||
if (!payoutResponse.isSuccessful || payoutResponse.body() == null) {
|
||||
logger.warn("查询 payoutNumerators 失败: index=$i")
|
||||
continue
|
||||
}
|
||||
|
||||
val payoutRpcResponse = payoutResponse.body()!!
|
||||
if (payoutRpcResponse.error != null) {
|
||||
logger.warn("查询 payoutNumerators 错误: index=$i, error=${payoutRpcResponse.error.message}")
|
||||
continue
|
||||
}
|
||||
|
||||
val payoutHex = payoutRpcResponse.result?.asString ?: "0x0"
|
||||
val payout = EthereumUtils.decodeUint256(payoutHex)
|
||||
payouts.add(payout)
|
||||
}
|
||||
|
||||
Result.success(Pair(payoutDenominator, payouts))
|
||||
} catch (e: Exception) {
|
||||
logger.error("查询市场条件失败: conditionId=$conditionId, ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询交易详情(用于调试和分析)
|
||||
* @param txHash 交易哈希
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
package com.wrbug.polymarketbot.service.common
|
||||
|
||||
import com.wrbug.polymarketbot.api.PolymarketClobApi
|
||||
import com.wrbug.polymarketbot.repository.AccountRepository
|
||||
import com.wrbug.polymarketbot.util.CryptoUtils
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigDecimal
|
||||
import java.math.BigInteger
|
||||
|
||||
/**
|
||||
* 市场价格服务
|
||||
* 统一封装从不同数据源获取市场价格的逻辑
|
||||
* 数据源包括:
|
||||
* 1. 链上 RPC 查询(市场结算结果)
|
||||
* 2. CLOB API(订单簿价格)
|
||||
*/
|
||||
@Service
|
||||
class MarketPriceService(
|
||||
private val blockchainService: BlockchainService,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val cryptoUtils: CryptoUtils
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(MarketPriceService::class.java)
|
||||
|
||||
/**
|
||||
* 获取当前市场最新价
|
||||
* 优先级:
|
||||
* 1. 链上查询市场结算结果(如果已结算,返回 1.0 或 0.0)
|
||||
* 2. CLOB API 查询订单簿价格(最准确,优先使用,使用 bestBid)
|
||||
* 3. Gamma Market API 查询市场价格(快速,作为备选)
|
||||
*
|
||||
* 价格会被截位到 4 位小数(向下截断,不四舍五入),用于显示和后续计算
|
||||
*
|
||||
* @param marketId 市场ID
|
||||
* @param outcomeIndex 结果索引
|
||||
* @return 市场价格(已截位到 4 位小数)
|
||||
* @throws IllegalStateException 如果所有数据源都失败
|
||||
*/
|
||||
suspend fun getCurrentMarketPrice(marketId: String, outcomeIndex: Int): BigDecimal {
|
||||
// 1. 优先从链上查询市场结算结果
|
||||
val chainPrice = getPriceFromChainCondition(marketId, outcomeIndex)
|
||||
if (chainPrice != null) {
|
||||
// 截位到 4 位小数(向下截断,不四舍五入)
|
||||
return chainPrice.setScale(4, java.math.RoundingMode.DOWN)
|
||||
}
|
||||
|
||||
// 2. 从 CLOB API 查询订单簿价格(最准确,优先使用)
|
||||
val orderbookPrice = getPriceFromClobOrderbook(marketId, outcomeIndex)
|
||||
if (orderbookPrice != null) {
|
||||
// 截位到 4 位小数(向下截断,不四舍五入)
|
||||
return orderbookPrice.setScale(4, java.math.RoundingMode.DOWN)
|
||||
}
|
||||
|
||||
// 3. 从 Gamma Market API 查询市场价格(作为备选)
|
||||
val marketPrice = getPriceFromGammaMarket(marketId, outcomeIndex)
|
||||
if (marketPrice != null) {
|
||||
// 截位到 4 位小数(向下截断,不四舍五入)
|
||||
return marketPrice.setScale(4, java.math.RoundingMode.DOWN)
|
||||
}
|
||||
|
||||
// 如果所有数据源都失败,抛出异常
|
||||
val errorMsg = "无法获取市场价格: marketId=$marketId, outcomeIndex=$outcomeIndex (链上查询、订单簿查询和 Market API 均失败)"
|
||||
logger.error(errorMsg)
|
||||
throw IllegalStateException(errorMsg)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从链上查询市场结算结果获取价格
|
||||
* 如果市场已结算:
|
||||
* - payout > 0(赢了)→ 返回 1.0
|
||||
* - payout == 0(输了)→ 返回 0.0
|
||||
* 如果市场未结算或查询失败,返回 null
|
||||
*/
|
||||
private suspend fun getPriceFromChainCondition(marketId: String, outcomeIndex: Int): BigDecimal? {
|
||||
return try {
|
||||
val chainResult = blockchainService.getCondition(marketId)
|
||||
chainResult.fold(
|
||||
onSuccess = { (_, payouts) ->
|
||||
// 如果 payouts 不为空,说明市场已结算
|
||||
if (payouts.isNotEmpty() && outcomeIndex < payouts.size) {
|
||||
val payout = payouts[outcomeIndex]
|
||||
when {
|
||||
payout > BigInteger.ZERO -> {
|
||||
logger.info("从链上查询到市场已结算,该 outcome 赢了: marketId=$marketId, outcomeIndex=$outcomeIndex, payout=$payout")
|
||||
return BigDecimal.ONE
|
||||
}
|
||||
payout == BigInteger.ZERO -> {
|
||||
logger.info("从链上查询到市场已结算,该 outcome 输了: marketId=$marketId, outcomeIndex=$outcomeIndex, payout=$payout")
|
||||
return BigDecimal.ZERO
|
||||
}
|
||||
else -> {
|
||||
logger.warn("从链上查询到异常的 payout 值: marketId=$marketId, outcomeIndex=$outcomeIndex, payout=$payout")
|
||||
null
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.debug("从链上查询到市场尚未结算: marketId=$marketId, payouts=${payouts.size}")
|
||||
null
|
||||
}
|
||||
},
|
||||
onFailure = { e ->
|
||||
logger.debug("链上查询市场条件失败,降级到 API 查询: marketId=$marketId, error=${e.message}")
|
||||
null
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.debug("链上查询市场条件异常: marketId=$marketId, outcomeIndex=$outcomeIndex, error=${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Gamma Market API 获取价格
|
||||
* 使用 outcomePrices 字段,格式通常为 JSON 字符串 "[\"0.5\", \"0.5\"]"
|
||||
* 如果查询失败或 outcomePrices 为空,返回 null
|
||||
*/
|
||||
private suspend fun getPriceFromGammaMarket(marketId: String, outcomeIndex: Int): BigDecimal? {
|
||||
return try {
|
||||
val gammaApi = retrofitFactory.createGammaApi()
|
||||
val marketResponse = gammaApi.listMarkets(conditionIds = listOf(marketId))
|
||||
|
||||
if (!marketResponse.isSuccessful || marketResponse.body() == null) {
|
||||
logger.debug("Gamma Market API 查询失败: marketId=$marketId, code=${marketResponse.code()}")
|
||||
return null
|
||||
}
|
||||
|
||||
val markets = marketResponse.body()!!
|
||||
if (markets.isEmpty()) {
|
||||
logger.debug("Gamma Market API 未找到市场: marketId=$marketId")
|
||||
return null
|
||||
}
|
||||
|
||||
val market = markets.first()
|
||||
|
||||
// 尝试从 outcomePrices 字段获取价格
|
||||
val outcomePricesStr = market.outcomePrices
|
||||
if (outcomePricesStr.isNullOrBlank()) {
|
||||
logger.debug("Market outcomePrices 为空: marketId=$marketId")
|
||||
return null
|
||||
}
|
||||
|
||||
// 解析 outcomePrices(通常是 JSON 数组字符串)
|
||||
val outcomePrices = try {
|
||||
// 移除首尾的方括号和引号,按逗号分割
|
||||
val cleanStr = outcomePricesStr.trim().removeSurrounding("[", "]")
|
||||
cleanStr.split(",").map {
|
||||
it.trim().removeSurrounding("\"").toSafeBigDecimal()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.warn("解析 outcomePrices 失败: marketId=$marketId, outcomePrices=$outcomePricesStr, error=${e.message}")
|
||||
null
|
||||
}
|
||||
|
||||
if (outcomePrices != null && outcomeIndex < outcomePrices.size) {
|
||||
val price = outcomePrices[outcomeIndex]
|
||||
logger.debug("从 Gamma Market API 获取价格: marketId=$marketId, outcomeIndex=$outcomeIndex, price=$price")
|
||||
return price
|
||||
}
|
||||
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
logger.debug("Gamma Market API 查询异常: marketId=$marketId, outcomeIndex=$outcomeIndex, error=${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从 CLOB API 查询订单簿价格
|
||||
* 获取订单簿的 bestBid 和 bestAsk,计算 midpoint = (bestBid + bestAsk) / 2
|
||||
* 订单簿数据最准确,反映当前市场真实价格
|
||||
* 如果查询失败,返回 null
|
||||
*/
|
||||
private suspend fun getPriceFromClobOrderbook(marketId: String, outcomeIndex: Int): BigDecimal? {
|
||||
return try {
|
||||
// 获取 tokenId(用于查询特定 outcome 的订单簿)
|
||||
val tokenIdResult = blockchainService.getTokenId(marketId, outcomeIndex)
|
||||
if (!tokenIdResult.isSuccess) {
|
||||
return null
|
||||
}
|
||||
|
||||
val tokenId = tokenIdResult.getOrNull() ?: return null
|
||||
|
||||
// 尝试使用带鉴权的 CLOB API,如果没有则使用不带鉴权的 API
|
||||
val clobApi = try {
|
||||
getAuthenticatedClobApi() ?: retrofitFactory.createClobApiWithoutAuth()
|
||||
} catch (e: Exception) {
|
||||
logger.debug("获取带鉴权的 CLOB API 失败,使用不带鉴权的 API: ${e.message}")
|
||||
retrofitFactory.createClobApiWithoutAuth()
|
||||
}
|
||||
|
||||
val orderbookResponse = clobApi.getOrderbook(tokenId = tokenId, market = null)
|
||||
|
||||
if (!orderbookResponse.isSuccessful || orderbookResponse.body() == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
val orderbook = orderbookResponse.body()!!
|
||||
|
||||
// 获取 bestBid(最高买入价):从 bids 中找到价格最大的
|
||||
// bids 表示买入订单列表,价格越高表示愿意出的价格越高
|
||||
val bestBid = orderbook.bids
|
||||
.mapNotNull { it.price.toSafeBigDecimal() }
|
||||
.maxOrNull()
|
||||
|
||||
// 获取 bestAsk(最低卖出价):从 asks 中找到价格最小的
|
||||
// asks 表示卖出订单列表,价格越低表示愿意卖的价格越低
|
||||
val bestAsk = orderbook.asks
|
||||
.mapNotNull { it.price.toSafeBigDecimal() }
|
||||
.minOrNull()
|
||||
|
||||
// 由于主要用于卖出场景,优先使用 bestBid(最高买入价,卖给愿意买入的人)
|
||||
// 如果没有 bestBid,则使用 midpoint 或 bestAsk
|
||||
if (bestBid != null) {
|
||||
logger.debug("从订单簿获取价格(bestBid): marketId=$marketId, outcomeIndex=$outcomeIndex, bestBid=$bestBid, bestAsk=$bestAsk")
|
||||
return bestBid
|
||||
} else if (bestAsk != null && bestAsk > BigDecimal.ZERO) {
|
||||
// 如果没有 bestBid,使用 bestAsk 作为备选
|
||||
logger.debug("从订单簿获取价格(bestAsk): marketId=$marketId, outcomeIndex=$outcomeIndex, bestAsk=$bestAsk")
|
||||
return bestAsk
|
||||
}
|
||||
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
logger.debug("CLOB API 查询订单簿失败: marketId=$marketId, outcomeIndex=$outcomeIndex, error=${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取带鉴权的 CLOB API 客户端
|
||||
* 使用第一个有 API 凭证的账户
|
||||
* 如果都没有,返回 null
|
||||
*/
|
||||
private fun getAuthenticatedClobApi(): PolymarketClobApi? {
|
||||
return try {
|
||||
// 使用第一个有 API 凭证的账户
|
||||
val account = accountRepository.findAllByOrderByCreatedAtAsc()
|
||||
.firstOrNull { it.apiKey != null && it.apiSecret != null && it.apiPassphrase != null }
|
||||
|
||||
if (account == null || account.apiKey == null || account.apiSecret == null || account.apiPassphrase == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
// 解密 API 凭证
|
||||
val apiKey = account.apiKey
|
||||
val apiSecret = try {
|
||||
cryptoUtils.decrypt(account.apiSecret)
|
||||
} catch (e: Exception) {
|
||||
logger.debug("解密 API Secret 失败: ${e.message}")
|
||||
return null
|
||||
}
|
||||
val apiPassphrase = try {
|
||||
cryptoUtils.decrypt(account.apiPassphrase)
|
||||
} catch (e: Exception) {
|
||||
logger.debug("解密 API Passphrase 失败: ${e.message}")
|
||||
return null
|
||||
}
|
||||
|
||||
// 创建带鉴权的 CLOB API 客户端
|
||||
retrofitFactory.createClobApi(apiKey, apiSecret, apiPassphrase, account.walletAddress)
|
||||
} catch (e: Exception) {
|
||||
logger.debug("获取带鉴权的 CLOB API 失败: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+14
-10
@@ -1,5 +1,6 @@
|
||||
package com.wrbug.polymarketbot.service.common
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.wrbug.polymarketbot.api.ApiKeyResponse
|
||||
import com.wrbug.polymarketbot.api.PolymarketClobApi
|
||||
import com.wrbug.polymarketbot.util.PolymarketL1AuthInterceptor
|
||||
@@ -19,7 +20,8 @@ import retrofit2.converter.gson.GsonConverterFactory
|
||||
@Service
|
||||
class PolymarketApiKeyService(
|
||||
@Value("\${polymarket.clob.base-url}")
|
||||
private val clobBaseUrl: String
|
||||
private val clobBaseUrl: String,
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(PolymarketApiKeyService::class.java)
|
||||
@@ -52,34 +54,36 @@ class PolymarketApiKeyService(
|
||||
try {
|
||||
// 先尝试获取现有的 API Key(derive)
|
||||
val deriveResult = deriveApiKey(privateKey, walletAddress, chainId)
|
||||
val maskedAddress = "${walletAddress.take(6)}...${walletAddress.takeLast(4)}"
|
||||
if (deriveResult.isSuccess) {
|
||||
val creds = deriveResult.getOrNull()
|
||||
if (creds != null && isApiCreds(creds)) {
|
||||
logger.info("成功获取现有 API Key: ${walletAddress}")
|
||||
logger.debug("成功获取现有 API Key: $maskedAddress")
|
||||
return@runBlocking Result.success(creds)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 如果获取失败或返回无效,尝试创建新的
|
||||
logger.info("获取现有 API Key 失败,尝试创建新的: ${walletAddress}")
|
||||
logger.debug("获取现有 API Key 失败,尝试创建新的: $maskedAddress")
|
||||
val createResult = createApiKey(privateKey, walletAddress, chainId)
|
||||
if (createResult.isSuccess) {
|
||||
val creds = createResult.getOrNull()
|
||||
if (creds != null && isApiCreds(creds)) {
|
||||
logger.info("成功创建新 API Key: ${walletAddress}")
|
||||
logger.debug("成功创建新 API Key: $maskedAddress")
|
||||
return@runBlocking Result.success(creds)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 两个都失败
|
||||
val error = createResult.exceptionOrNull() ?: deriveResult.exceptionOrNull()
|
||||
val errorMsg = error?.message ?: "未知错误"
|
||||
logger.error("获取和创建 API Key 都失败: ${walletAddress}", error)
|
||||
logger.error("获取和创建 API Key 都失败: $maskedAddress", error)
|
||||
Result.failure(
|
||||
IllegalStateException("无法获取或创建 API Key: $errorMsg")
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("创建或获取 API Key 异常: ${walletAddress}", e)
|
||||
val maskedAddress = "${walletAddress.take(6)}...${walletAddress.takeLast(4)}"
|
||||
logger.error("创建或获取 API Key 异常: $maskedAddress", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
@@ -222,7 +226,7 @@ class PolymarketApiKeyService(
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
}
|
||||
@@ -236,7 +240,7 @@ class PolymarketApiKeyService(
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
}
|
||||
|
||||
+14
-4
@@ -300,13 +300,23 @@ class PolymarketClobService(
|
||||
)
|
||||
|
||||
val response = authenticatedClobApi.getOrder(orderId)
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
Result.success(response.body()!!)
|
||||
if (response.isSuccessful) {
|
||||
val body = response.body()
|
||||
if (body != null) {
|
||||
Result.success(body)
|
||||
} else {
|
||||
// 响应体为空,可能是订单不存在或已过期
|
||||
logger.warn("获取订单详情失败: 响应体为空, orderId=$orderId, code=${response.code()}")
|
||||
Result.failure(Exception("订单不存在或已过期: orderId=$orderId"))
|
||||
}
|
||||
} else {
|
||||
Result.failure(Exception("获取订单详情失败: ${response.code()} ${response.message()}"))
|
||||
// HTTP 状态码不是 2xx
|
||||
val errorBody = response.errorBody()?.string()?.take(200) ?: "无错误详情"
|
||||
logger.warn("获取订单详情失败: HTTP ${response.code()}, orderId=$orderId, errorBody=$errorBody")
|
||||
Result.failure(Exception("获取订单详情失败: HTTP ${response.code()} ${response.message()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取订单详情异常: ${e.message}", e)
|
||||
logger.error("获取订单详情异常: orderId=$orderId, ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
+100
-17
@@ -3,50 +3,133 @@ package com.wrbug.polymarketbot.service.common
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.stereotype.Service
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* 频率限制服务(使用内存缓存,全局限制)
|
||||
* 频率限制服务(使用内存缓存)
|
||||
*/
|
||||
@Service
|
||||
class RateLimitService {
|
||||
|
||||
|
||||
private val logger = LoggerFactory.getLogger(RateLimitService::class.java)
|
||||
|
||||
|
||||
// 重置密码限速配置
|
||||
@Value("\${rate-limit.reset-password.max-attempts:3}")
|
||||
private var maxAttempts: Int = 3
|
||||
|
||||
private var resetPasswordMaxAttempts: Int = 3
|
||||
|
||||
@Value("\${rate-limit.reset-password.window-seconds:60}")
|
||||
private var windowSeconds: Long = 60
|
||||
|
||||
private var resetPasswordWindowSeconds: Long = 60
|
||||
|
||||
// 登录限速配置
|
||||
@Value("\${rate-limit.login.max-attempts:5}")
|
||||
private var loginMaxAttempts: Int = 5
|
||||
|
||||
@Value("\${rate-limit.login.window-seconds:300}")
|
||||
private var loginWindowSeconds: Long = 300 // 5分钟
|
||||
|
||||
@Value("\${rate-limit.login.lockout-seconds:900}")
|
||||
private var loginLockoutSeconds: Long = 900 // 15分钟
|
||||
|
||||
// 全局尝试记录列表(时间戳),所有请求共享
|
||||
private val resetPasswordAttempts = AtomicReference<MutableList<Long>>(mutableListOf())
|
||||
|
||||
|
||||
// 登录失败尝试记录(IP -> 时间戳列表)
|
||||
private val loginFailedAttempts = ConcurrentHashMap<String, MutableList<Long>>()
|
||||
|
||||
// 登录锁定记录(IP -> 锁定结束时间)
|
||||
private val loginLockouts = ConcurrentHashMap<String, Long>()
|
||||
|
||||
/**
|
||||
* 检查重置密码频率限制(全局限制,不按IP)
|
||||
* @return Result,如果超过限制则返回失败
|
||||
*/
|
||||
fun checkResetPasswordRateLimit(): Result<Unit> {
|
||||
val now = System.currentTimeMillis()
|
||||
val windowStart = now - (windowSeconds * 1000)
|
||||
|
||||
val windowStart = now - (resetPasswordWindowSeconds * 1000)
|
||||
|
||||
// 获取当前尝试记录列表
|
||||
val attempts = resetPasswordAttempts.get()
|
||||
|
||||
|
||||
// 清理过期记录(超过时间窗口的记录)
|
||||
val validAttempts = attempts.filter { it >= windowStart }.toMutableList()
|
||||
|
||||
|
||||
// 检查是否超过限制
|
||||
if (validAttempts.size >= maxAttempts) {
|
||||
logger.warn("重置密码频率限制触发: attempts=${validAttempts.size}/$maxAttempts")
|
||||
return Result.failure(IllegalStateException("频率限制:1分钟内最多尝试${maxAttempts}次,请稍后再试"))
|
||||
if (validAttempts.size >= resetPasswordMaxAttempts) {
|
||||
logger.warn("重置密码频率限制触发: attempts=${validAttempts.size}/$resetPasswordMaxAttempts")
|
||||
return Result.failure(IllegalStateException("频率限制:1分钟内最多尝试${resetPasswordMaxAttempts}次,请稍后再试"))
|
||||
}
|
||||
|
||||
|
||||
// 记录本次尝试
|
||||
validAttempts.add(now)
|
||||
resetPasswordAttempts.set(validAttempts)
|
||||
|
||||
|
||||
return Result.success(Unit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查登录频率限制(按IP限制)
|
||||
* @param ipAddress 客户端IP地址
|
||||
* @return Result,如果被锁定或超过限制则返回失败
|
||||
*/
|
||||
fun checkLoginRateLimit(ipAddress: String): Result<Unit> {
|
||||
val now = System.currentTimeMillis()
|
||||
|
||||
// 检查是否被锁定
|
||||
val lockoutEndTime = loginLockouts[ipAddress]
|
||||
if (lockoutEndTime != null) {
|
||||
if (now < lockoutEndTime) {
|
||||
val remainingSeconds = (lockoutEndTime - now) / 1000
|
||||
logger.warn("登录锁定中: ip=$ipAddress, remainingSeconds=$remainingSeconds")
|
||||
return Result.failure(IllegalStateException("账户已被锁定,请${remainingSeconds}秒后再试"))
|
||||
} else {
|
||||
// 锁定已过期,清除锁定记录
|
||||
loginLockouts.remove(ipAddress)
|
||||
loginFailedAttempts.remove(ipAddress)
|
||||
}
|
||||
}
|
||||
|
||||
return Result.success(Unit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录登录失败尝试
|
||||
* @param ipAddress 客户端IP地址
|
||||
* @return 如果触发锁定返回锁定信息,否则返回 null
|
||||
*/
|
||||
fun recordLoginFailure(ipAddress: String): String? {
|
||||
val now = System.currentTimeMillis()
|
||||
val windowStart = now - (loginWindowSeconds * 1000)
|
||||
|
||||
// 获取或创建该IP的尝试记录
|
||||
val attempts = loginFailedAttempts.computeIfAbsent(ipAddress) { mutableListOf() }
|
||||
|
||||
// 清理过期记录并添加新记录
|
||||
synchronized(attempts) {
|
||||
attempts.removeIf { it < windowStart }
|
||||
attempts.add(now)
|
||||
|
||||
// 检查是否需要锁定
|
||||
if (attempts.size >= loginMaxAttempts) {
|
||||
val lockoutEndTime = now + (loginLockoutSeconds * 1000)
|
||||
loginLockouts[ipAddress] = lockoutEndTime
|
||||
logger.warn("登录锁定触发: ip=$ipAddress, attempts=${attempts.size}, lockoutSeconds=$loginLockoutSeconds")
|
||||
return "登录失败次数过多,账户已被锁定${loginLockoutSeconds / 60}分钟"
|
||||
}
|
||||
}
|
||||
|
||||
val remainingAttempts = loginMaxAttempts - attempts.size
|
||||
logger.warn("登录失败: ip=$ipAddress, attempts=${attempts.size}/$loginMaxAttempts, remainingAttempts=$remainingAttempts")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录成功时清除失败记录
|
||||
* @param ipAddress 客户端IP地址
|
||||
*/
|
||||
fun clearLoginFailures(ipAddress: String) {
|
||||
loginFailedAttempts.remove(ipAddress)
|
||||
loginLockouts.remove(ipAddress)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+29
-13
@@ -9,6 +9,7 @@ import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
import org.slf4j.LoggerFactory
|
||||
import com.wrbug.polymarketbot.service.common.PolymarketClobService
|
||||
import com.wrbug.polymarketbot.service.accounts.AccountService
|
||||
import com.wrbug.polymarketbot.repository.CopyOrderTrackingRepository
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigDecimal
|
||||
|
||||
@@ -18,7 +19,8 @@ import java.math.BigDecimal
|
||||
@Service
|
||||
class CopyTradingFilterService(
|
||||
private val clobService: PolymarketClobService,
|
||||
private val accountService: AccountService
|
||||
private val accountService: AccountService,
|
||||
private val copyOrderTrackingRepository: CopyOrderTrackingRepository
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CopyTradingFilterService::class.java)
|
||||
@@ -234,32 +236,46 @@ class CopyTradingFilterService(
|
||||
|
||||
// 检查最大仓位金额(如果配置了)
|
||||
if (copyTrading.maxPositionValue != null) {
|
||||
// 计算该市场的当前仓位总价值(累加该市场所有仓位的 currentValue)
|
||||
val currentPositionValue = marketPositions.sumOf { position ->
|
||||
position.currentValue.toSafeBigDecimal()
|
||||
}
|
||||
// 比较数据库成本价(本地订单记录)和外部持仓市值(可能来自其他终端的操作),取最大值
|
||||
val dbValue = copyOrderTrackingRepository.sumCurrentPositionValueByMarket(copyTrading.id!!, marketId) ?: BigDecimal.ZERO
|
||||
val extValue = marketPositions.sumOf { it.currentValue.toSafeBigDecimal() }
|
||||
val currentPositionValue = dbValue.max(extValue)
|
||||
|
||||
// 检查:该市场的当前仓位 + 跟单金额 <= 最大仓位金额
|
||||
val totalValueAfterOrder = currentPositionValue.add(copyOrderAmount)
|
||||
|
||||
if (totalValueAfterOrder.gt(copyTrading.maxPositionValue)) {
|
||||
return FilterResult.maxPositionValueFailed(
|
||||
"超过最大仓位金额限制: 当前该市场仓位=${currentPositionValue} USDC, 跟单金额=${copyOrderAmount} USDC, 总计=${totalValueAfterOrder} USDC > 最大限制=${copyTrading.maxPositionValue} USDC"
|
||||
"超过最大仓位金额限制: 当前该市场仓位(取最大值)=${currentPositionValue} USDC (DB=${dbValue}, Ext=${extValue}), 跟单金额=${copyOrderAmount} USDC, 总计=${totalValueAfterOrder} USDC > 最大限制=${copyTrading.maxPositionValue} USDC"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 检查最大仓位数量(如果配置了)
|
||||
if (copyTrading.maxPositionCount != null) {
|
||||
// 计算该市场的当前仓位数量(该市场不同方向的仓位算不同仓位)
|
||||
val currentPositionCount = marketPositions.size
|
||||
// 使用数据库中的订单记录计算活跃仓位数量(解决延迟问题)
|
||||
val dbCount = copyOrderTrackingRepository.countActivePositions(copyTrading.id!!)
|
||||
|
||||
// 检查:该市场的当前仓位数量 <= 最大仓位数量
|
||||
// 注意:如果该市场已有仓位,跟单可能会增加新的仓位(不同方向)或增加现有仓位
|
||||
// 为了简化,我们检查当前该市场的仓位数量是否已经达到或超过限制
|
||||
if (currentPositionCount >= copyTrading.maxPositionCount) {
|
||||
// 计算外部持仓中的唯一市场数量(防止遗漏非本项目创建的仓位)
|
||||
val extCount = positions.currentPositions
|
||||
.filter { it.accountId == copyTrading.accountId }
|
||||
.map { it.marketId }
|
||||
.distinct()
|
||||
.size
|
||||
|
||||
val currentPositionCount = maxOf(dbCount, extCount)
|
||||
|
||||
// 检查:如果当前没有该市场的活跃仓位,且总仓位数量已达到限制,则不允许开新仓
|
||||
// 判断当前市场是否已有活跃仓位(数据库或外部持仓)
|
||||
val hasDbPosition = copyOrderTrackingRepository.existsByCopyTradingIdAndMarketIdAndRemainingQuantityGreaterThan(
|
||||
copyTrading.id, marketId, BigDecimal.ZERO
|
||||
)
|
||||
val hasExtPosition = marketPositions.isNotEmpty()
|
||||
val hasCurrentMarketPosition = hasDbPosition || hasExtPosition
|
||||
|
||||
if (!hasCurrentMarketPosition && currentPositionCount >= copyTrading.maxPositionCount) {
|
||||
return FilterResult.maxPositionCountFailed(
|
||||
"超过最大仓位数量限制: 当前该市场仓位数量=${currentPositionCount} >= 最大限制=${copyTrading.maxPositionCount}"
|
||||
"超过最大仓位数量限制: 当前活跃仓位总数(取最大值)=${currentPositionCount} (DB=${dbCount}, Ext=${extCount}) >= 最大限制=${copyTrading.maxPositionCount}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+10
-6
@@ -151,13 +151,14 @@ class CopyTradingService(
|
||||
|
||||
val saved = copyTradingRepository.save(copyTrading)
|
||||
|
||||
// 如果跟单已启用,更新 Leader 监听(增量更新,不重启所有监听)
|
||||
// 如果跟单已启用,更新 Leader 监听和账户监听(增量更新,不重启所有监听)
|
||||
if (saved.enabled) {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
try {
|
||||
monitorService.updateLeaderMonitoring(saved.leaderId)
|
||||
monitorService.updateAccountMonitoring(saved.accountId)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 监听失败", e)
|
||||
logger.error("更新监听失败", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,12 +220,13 @@ class CopyTradingService(
|
||||
|
||||
val saved = copyTradingRepository.save(updated)
|
||||
|
||||
// 更新 Leader 监听(增量更新,根据 enabled 状态决定添加或移除)
|
||||
// 更新 Leader 监听和账户监听(增量更新,根据 enabled 状态决定添加或移除)
|
||||
kotlinx.coroutines.runBlocking {
|
||||
try {
|
||||
monitorService.updateLeaderMonitoring(saved.leaderId)
|
||||
monitorService.updateAccountMonitoring(saved.accountId)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 监听失败", e)
|
||||
logger.error("更新监听失败", e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,14 +325,16 @@ class CopyTradingService(
|
||||
?: return Result.failure(IllegalArgumentException("跟单配置不存在"))
|
||||
|
||||
val leaderId = copyTrading.leaderId
|
||||
val accountId = copyTrading.accountId
|
||||
copyTradingRepository.delete(copyTrading)
|
||||
|
||||
// 更新 Leader 监听(检查该 Leader 是否还有其他启用的跟单配置)
|
||||
// 更新 Leader 监听和账户监听(检查是否还有其他启用的跟单配置)
|
||||
kotlinx.coroutines.runBlocking {
|
||||
try {
|
||||
monitorService.removeLeaderMonitoring(leaderId)
|
||||
monitorService.updateAccountMonitoring(accountId)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新 Leader 监听失败", e)
|
||||
logger.error("更新监听失败", e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.entity.Account
|
||||
import com.wrbug.polymarketbot.entity.CopyOrderTracking
|
||||
import com.wrbug.polymarketbot.entity.SellMatchDetail
|
||||
import com.wrbug.polymarketbot.entity.SellMatchRecord
|
||||
import com.wrbug.polymarketbot.repository.AccountRepository
|
||||
import com.wrbug.polymarketbot.repository.CopyOrderTrackingRepository
|
||||
import com.wrbug.polymarketbot.repository.CopyTradingRepository
|
||||
import com.wrbug.polymarketbot.repository.SellMatchDetailRepository
|
||||
import com.wrbug.polymarketbot.repository.SellMatchRecordRepository
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.multi
|
||||
import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
import jakarta.annotation.PreDestroy
|
||||
import kotlinx.coroutines.*
|
||||
import okhttp3.OkHttpClient
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigDecimal
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 跟单账户链上 WebSocket 监听服务
|
||||
* 通过统一服务订阅跟单账户的卖出和赎回事件
|
||||
* 用于更新订单状态,不再依赖轮询
|
||||
*/
|
||||
@Service
|
||||
class AccountOnChainMonitorService(
|
||||
private val unifiedOnChainWsService: UnifiedOnChainWsService,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val copyTradingRepository: CopyTradingRepository,
|
||||
private val copyOrderTrackingRepository: CopyOrderTrackingRepository,
|
||||
private val sellMatchRecordRepository: SellMatchRecordRepository,
|
||||
private val sellMatchDetailRepository: SellMatchDetailRepository
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(AccountOnChainMonitorService::class.java)
|
||||
|
||||
// 存储需要监听的账户:accountId -> Account
|
||||
private val monitoredAccounts = ConcurrentHashMap<Long, Account>()
|
||||
|
||||
/**
|
||||
* 启动链上 WebSocket 监听
|
||||
* 通过统一服务订阅所有跟单账户
|
||||
*/
|
||||
fun start(accounts: List<Account>) {
|
||||
// 如果没有账户,取消所有订阅
|
||||
if (accounts.isEmpty()) {
|
||||
logger.info("没有需要监听的跟单账户,取消所有订阅")
|
||||
stop()
|
||||
return
|
||||
}
|
||||
|
||||
// 更新账户列表
|
||||
monitoredAccounts.clear()
|
||||
accounts.forEach { account ->
|
||||
addAccount(account)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加账户监听
|
||||
* 通过统一服务订阅该账户的地址
|
||||
*/
|
||||
fun addAccount(account: Account) {
|
||||
if (account.id == null) {
|
||||
logger.warn("账户 ID 为空,跳过: ${account.proxyAddress}")
|
||||
return
|
||||
}
|
||||
|
||||
val accountId = account.id!!
|
||||
|
||||
// 如果已经在监听列表中,不重复添加
|
||||
if (monitoredAccounts.containsKey(accountId)) {
|
||||
return
|
||||
}
|
||||
|
||||
monitoredAccounts[accountId] = account
|
||||
|
||||
// 通过统一服务订阅
|
||||
val subscriptionId = "ACCOUNT_$accountId"
|
||||
unifiedOnChainWsService.subscribe(
|
||||
subscriptionId = subscriptionId,
|
||||
address = account.proxyAddress,
|
||||
entityType = "ACCOUNT",
|
||||
entityId = accountId,
|
||||
callback = { txHash, httpClient, rpcApi ->
|
||||
handleAccountTransaction(accountId, txHash, httpClient, rpcApi)
|
||||
}
|
||||
)
|
||||
|
||||
logger.info("已添加跟单账户进行链上监听: accountId=${accountId}, address=${account.proxyAddress}")
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理账户的交易
|
||||
*/
|
||||
private suspend fun handleAccountTransaction(accountId: Long, txHash: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
val account = monitoredAccounts[accountId] ?: return
|
||||
|
||||
try {
|
||||
// 获取交易 receipt
|
||||
val receiptRequest = JsonRpcRequest(
|
||||
method = "eth_getTransactionReceipt",
|
||||
params = listOf(txHash)
|
||||
)
|
||||
|
||||
val receiptResponse = rpcApi.call(receiptRequest)
|
||||
if (!receiptResponse.isSuccessful || receiptResponse.body() == null) {
|
||||
return
|
||||
}
|
||||
|
||||
val receiptRpcResponse = receiptResponse.body()!!
|
||||
if (receiptRpcResponse.error != null || receiptRpcResponse.result == null) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 receipt JSON
|
||||
val receiptJson = receiptRpcResponse.result.asJsonObject
|
||||
|
||||
// 获取区块号和时间戳
|
||||
val blockNumber = receiptJson.get("blockNumber")?.asString
|
||||
val blockTimestamp = if (blockNumber != null) {
|
||||
OnChainWsUtils.getBlockTimestamp(blockNumber, rpcApi)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
// 解析 receipt 中的 Transfer 日志
|
||||
val logs = receiptJson.getAsJsonArray("logs") ?: return
|
||||
val (erc20Transfers, erc1155Transfers) = OnChainWsUtils.parseReceiptTransfers(logs)
|
||||
|
||||
// 解析交易信息
|
||||
val trade = OnChainWsUtils.parseTradeFromTransfers(
|
||||
txHash = txHash,
|
||||
timestamp = blockTimestamp,
|
||||
walletAddress = account.proxyAddress,
|
||||
erc20Transfers = erc20Transfers,
|
||||
erc1155Transfers = erc1155Transfers,
|
||||
retrofitFactory = retrofitFactory
|
||||
)
|
||||
|
||||
if (trade != null && trade.side == "SELL") {
|
||||
// 检测到卖出或赎回事件,更新订单状态
|
||||
handleAccountSellOrRedeem(account, trade)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理账户交易失败: accountId=$accountId, txHash=$txHash, ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理账户的卖出或赎回事件
|
||||
* 更新对应的订单状态
|
||||
*/
|
||||
private suspend fun handleAccountSellOrRedeem(account: Account, trade: TradeResponse) {
|
||||
try {
|
||||
// 获取该账户的所有启用的跟单配置
|
||||
val copyTradings = copyTradingRepository.findByAccountId(account.id!!)
|
||||
.filter { it.enabled }
|
||||
|
||||
if (copyTradings.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 trade 中已有的市场信息
|
||||
val marketId = trade.market // conditionId
|
||||
val outcomeIndex = trade.outcomeIndex ?: 0
|
||||
|
||||
// 计算卖出价格
|
||||
val sellPrice = trade.price.toSafeBigDecimal()
|
||||
|
||||
// 为每个跟单配置更新订单状态
|
||||
for (copyTrading in copyTradings) {
|
||||
// 查找该跟单配置下所有未卖出的订单(remaining_quantity > 0)
|
||||
val unmatchedOrders = copyOrderTrackingRepository.findByCopyTradingId(copyTrading.id!!)
|
||||
.filter {
|
||||
it.remainingQuantity > BigDecimal.ZERO &&
|
||||
it.marketId == marketId &&
|
||||
it.outcomeIndex == outcomeIndex
|
||||
}
|
||||
.sortedBy { it.createdAt } // 按创建时间排序(FIFO)
|
||||
|
||||
if (unmatchedOrders.isEmpty()) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 卖出数量就是交易的 size
|
||||
val soldQuantity = trade.size.toSafeBigDecimal()
|
||||
|
||||
// 更新订单状态为已卖出
|
||||
updateOrdersAsSoldByFIFO(
|
||||
unmatchedOrders,
|
||||
soldQuantity,
|
||||
sellPrice,
|
||||
copyTrading.id!!,
|
||||
marketId,
|
||||
outcomeIndex
|
||||
)
|
||||
|
||||
logger.info("跟单账户卖出/赎回事件处理完成: accountId=${account.id}, copyTradingId=${copyTrading.id}, txHash=${trade.id}, soldQuantity=$soldQuantity, sellPrice=$sellPrice")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理账户卖出/赎回事件失败: accountId=${account.id}, txHash=${trade.id}, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 FIFO 顺序更新订单为已卖出
|
||||
*/
|
||||
private suspend fun updateOrdersAsSoldByFIFO(
|
||||
orders: List<CopyOrderTracking>,
|
||||
soldQuantity: BigDecimal,
|
||||
sellPrice: BigDecimal,
|
||||
copyTradingId: Long,
|
||||
marketId: String,
|
||||
outcomeIndex: Int
|
||||
) {
|
||||
var remainingSoldQuantity = soldQuantity
|
||||
val matchDetails = mutableListOf<SellMatchDetail>()
|
||||
var totalMatchedQuantity = BigDecimal.ZERO
|
||||
var totalRealizedPnl = BigDecimal.ZERO
|
||||
|
||||
for (order in orders) {
|
||||
if (remainingSoldQuantity <= BigDecimal.ZERO) {
|
||||
break
|
||||
}
|
||||
|
||||
val currentOrderRemaining = order.remainingQuantity.toSafeBigDecimal()
|
||||
val matchedQty = minOf(currentOrderRemaining, remainingSoldQuantity)
|
||||
|
||||
if (matchedQty <= BigDecimal.ZERO) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算盈亏
|
||||
val buyPrice = order.price.toSafeBigDecimal()
|
||||
val realizedPnl = sellPrice.subtract(buyPrice).multi(matchedQty)
|
||||
|
||||
// 创建匹配明细
|
||||
val detail = SellMatchDetail(
|
||||
matchRecordId = 0, // 稍后设置
|
||||
trackingId = order.id!!,
|
||||
buyOrderId = order.buyOrderId,
|
||||
matchedQuantity = matchedQty,
|
||||
buyPrice = buyPrice,
|
||||
sellPrice = sellPrice,
|
||||
realizedPnl = realizedPnl
|
||||
)
|
||||
matchDetails.add(detail)
|
||||
|
||||
totalMatchedQuantity = totalMatchedQuantity.add(matchedQty)
|
||||
totalRealizedPnl = totalRealizedPnl.add(realizedPnl)
|
||||
|
||||
// 更新订单状态
|
||||
order.matchedQuantity = order.matchedQuantity.add(matchedQty)
|
||||
order.remainingQuantity = currentOrderRemaining.subtract(matchedQty)
|
||||
order.status = if (order.remainingQuantity <= BigDecimal.ZERO) "fully_matched" else "partially_matched"
|
||||
order.updatedAt = System.currentTimeMillis()
|
||||
copyOrderTrackingRepository.save(order)
|
||||
|
||||
remainingSoldQuantity = remainingSoldQuantity.subtract(matchedQty)
|
||||
}
|
||||
|
||||
// 如果有匹配的订单,创建卖出记录
|
||||
if (totalMatchedQuantity > BigDecimal.ZERO && matchDetails.isNotEmpty()) {
|
||||
val timestamp = System.currentTimeMillis()
|
||||
val sellOrderId = "AUTO_WS_${timestamp}_${copyTradingId}" // 区分 WS 自动卖出
|
||||
val leaderSellTradeId = "AUTO_WS_${timestamp}"
|
||||
|
||||
val matchRecord = SellMatchRecord(
|
||||
copyTradingId = copyTradingId,
|
||||
sellOrderId = sellOrderId,
|
||||
leaderSellTradeId = leaderSellTradeId,
|
||||
marketId = marketId,
|
||||
side = outcomeIndex.toString(),
|
||||
outcomeIndex = outcomeIndex,
|
||||
totalMatchedQuantity = totalMatchedQuantity,
|
||||
sellPrice = sellPrice,
|
||||
totalRealizedPnl = totalRealizedPnl,
|
||||
priceUpdated = true // WS 实时获取,直接标记为已更新
|
||||
)
|
||||
|
||||
val savedRecord = sellMatchRecordRepository.save(matchRecord)
|
||||
|
||||
// 保存匹配明细
|
||||
for (detail in matchDetails) {
|
||||
val savedDetail = detail.copy(matchRecordId = savedRecord.id!!)
|
||||
sellMatchDetailRepository.save(savedDetail)
|
||||
}
|
||||
|
||||
logger.info("创建跟单账户链上自动卖出记录: copyTradingId=$copyTradingId, marketId=$marketId, totalMatched=$totalMatchedQuantity, totalPnl=$totalRealizedPnl")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除账户监听
|
||||
* 取消该账户的订阅
|
||||
*/
|
||||
fun removeAccount(accountId: Long) {
|
||||
monitoredAccounts.remove(accountId)
|
||||
|
||||
// 通过统一服务取消订阅
|
||||
val subscriptionId = "ACCOUNT_$accountId"
|
||||
unifiedOnChainWsService.unsubscribe(subscriptionId)
|
||||
|
||||
logger.info("已移除跟单账户的链上监听: accountId=$accountId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新账户监听状态
|
||||
*/
|
||||
fun updateAccountMonitoring(accountId: Long) {
|
||||
val account = accountRepository.findById(accountId).orElse(null)
|
||||
if (account != null && account.isEnabled) {
|
||||
addAccount(account)
|
||||
} else {
|
||||
removeAccount(accountId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止监听
|
||||
*/
|
||||
fun stop() {
|
||||
// 取消所有账户的订阅
|
||||
val accountIds = monitoredAccounts.keys.toList()
|
||||
for (accountId in accountIds) {
|
||||
removeAccount(accountId)
|
||||
}
|
||||
monitoredAccounts.clear()
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
+48
-16
@@ -2,6 +2,7 @@ package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.wrbug.polymarketbot.entity.CopyTrading
|
||||
import com.wrbug.polymarketbot.entity.Leader
|
||||
import com.wrbug.polymarketbot.repository.AccountRepository
|
||||
import com.wrbug.polymarketbot.repository.CopyTradingRepository
|
||||
import com.wrbug.polymarketbot.repository.LeaderRepository
|
||||
import jakarta.annotation.PostConstruct
|
||||
@@ -13,14 +14,16 @@ import org.springframework.stereotype.Service
|
||||
/**
|
||||
* 跟单监听服务(主服务)
|
||||
* 管理所有Leader的交易监听
|
||||
* 同时运行链上 WebSocket 监听和轮询监听(并行处理)
|
||||
* 使用链上 WebSocket 监听 Leader 的交易(实时,秒级延迟)
|
||||
* 同时监听跟单账户的卖出/赎回事件(通过链上 WebSocket)
|
||||
*/
|
||||
@Service
|
||||
class CopyTradingMonitorService(
|
||||
private val copyTradingRepository: CopyTradingRepository,
|
||||
private val leaderRepository: LeaderRepository,
|
||||
private val pollingService: CopyTradingPollingService,
|
||||
private val onChainWsService: OnChainWsService
|
||||
private val accountRepository: AccountRepository,
|
||||
private val onChainWsService: OnChainWsService,
|
||||
private val accountOnChainMonitorService: AccountOnChainMonitorService
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CopyTradingMonitorService::class.java)
|
||||
@@ -47,14 +50,15 @@ class CopyTradingMonitorService(
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
scope.cancel()
|
||||
// 停止轮询和链上 WS 监听
|
||||
pollingService.stop()
|
||||
// 停止链上 WS 监听
|
||||
onChainWsService.stop()
|
||||
accountOnChainMonitorService.stop()
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动监听
|
||||
* 同时启动链上 WebSocket 监听和轮询监听(并行运行)
|
||||
* 启动链上 WebSocket 监听 Leader 的交易(实时,秒级延迟)
|
||||
* 同时启动跟单账户的链上 WebSocket 监听(用于检测卖出/赎回事件)
|
||||
*/
|
||||
suspend fun startMonitoring() {
|
||||
// 1. 获取所有启用的跟单关系
|
||||
@@ -70,12 +74,17 @@ class CopyTradingMonitorService(
|
||||
leaderRepository.findById(leaderId).orElse(null)
|
||||
}
|
||||
|
||||
// 3. 同时启动链上 WebSocket 监听和轮询监听(并行运行)
|
||||
// 链上 WS 监听(实时,秒级延迟)
|
||||
// 3. 获取所有需要监听的跟单账户(去重)
|
||||
val accountIds = enabledCopyTradings.map { it.accountId }.distinct()
|
||||
val accounts = accountIds.mapNotNull { accountId ->
|
||||
accountRepository.findById(accountId).orElse(null)
|
||||
}
|
||||
|
||||
// 4. 启动链上 WebSocket 监听 Leader 的交易(实时,秒级延迟)
|
||||
onChainWsService.start(leaders)
|
||||
|
||||
// 轮询监听(延迟,2秒间隔,作为备份)
|
||||
pollingService.start(leaders)
|
||||
// 5. 启动跟单账户的链上 WebSocket 监听(用于检测卖出/赎回事件)
|
||||
accountOnChainMonitorService.start(accounts)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,9 +100,8 @@ class CopyTradingMonitorService(
|
||||
return
|
||||
}
|
||||
|
||||
// 同时添加到链上 WS 监听和轮询监听(如果不在列表中才添加)
|
||||
// 添加到链上 WS 监听(如果不在列表中才添加)
|
||||
onChainWsService.addLeader(leader)
|
||||
pollingService.addLeader(leader)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +117,6 @@ class CopyTradingMonitorService(
|
||||
|
||||
// 没有启用的跟单配置了,移除监听
|
||||
onChainWsService.removeLeader(leaderId)
|
||||
pollingService.removeLeader(leaderId)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -124,11 +131,37 @@ class CopyTradingMonitorService(
|
||||
if (copyTradings.isNotEmpty()) {
|
||||
// 有启用的跟单配置,确保在监听列表中
|
||||
onChainWsService.addLeader(leader)
|
||||
pollingService.addLeader(leader)
|
||||
|
||||
// 更新账户监听(添加该配置关联的账户)
|
||||
val accountIds = copyTradings.map { it.accountId }.distinct()
|
||||
accountIds.forEach { accountId ->
|
||||
val account = accountRepository.findById(accountId).orElse(null)
|
||||
if (account != null) {
|
||||
accountOnChainMonitorService.addAccount(account)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 没有启用的跟单配置,移除监听
|
||||
onChainWsService.removeLeader(leaderId)
|
||||
pollingService.removeLeader(leaderId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新账户监听(当跟单配置状态改变时调用)
|
||||
* 根据当前状态决定添加或移除账户监听
|
||||
*/
|
||||
suspend fun updateAccountMonitoring(accountId: Long) {
|
||||
val copyTradings = copyTradingRepository.findByAccountId(accountId)
|
||||
.filter { it.enabled }
|
||||
val account = accountRepository.findById(accountId).orElse(null)
|
||||
?: return
|
||||
|
||||
if (copyTradings.isNotEmpty()) {
|
||||
// 有启用的跟单配置,确保账户在监听列表中
|
||||
accountOnChainMonitorService.addAccount(account)
|
||||
} else {
|
||||
// 没有启用的跟单配置,移除账户监听
|
||||
accountOnChainMonitorService.removeAccount(accountId)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +172,6 @@ class CopyTradingMonitorService(
|
||||
suspend fun restartMonitoring() {
|
||||
// 停止所有监听
|
||||
onChainWsService.stop()
|
||||
pollingService.stop()
|
||||
delay(1000) // 等待1秒
|
||||
startMonitoring()
|
||||
}
|
||||
|
||||
-279
@@ -1,279 +0,0 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.wrbug.polymarketbot.api.TradeResponse
|
||||
import com.wrbug.polymarketbot.api.UserActivityResponse
|
||||
import com.wrbug.polymarketbot.entity.Leader
|
||||
import com.wrbug.polymarketbot.repository.CopyTradingTemplateRepository
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import jakarta.annotation.PreDestroy
|
||||
import kotlinx.coroutines.*
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import com.wrbug.polymarketbot.service.copytrading.statistics.CopyOrderTrackingService
|
||||
import org.springframework.stereotype.Service
|
||||
import retrofit2.Response
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 跟单轮询监听服务
|
||||
* 通过定期轮询 Polymarket Data API 的 /activity 接口获取Leader的交易记录
|
||||
* 使用 /activity 接口可以查询用户的链上活动,包括交易
|
||||
*/
|
||||
@Service
|
||||
class CopyTradingPollingService(
|
||||
private val copyOrderTrackingService: CopyOrderTrackingService,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val templateRepository: CopyTradingTemplateRepository
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CopyTradingPollingService::class.java)
|
||||
|
||||
@Value("\${copy.trading.polling.interval:2000}")
|
||||
private var pollingInterval: Long = 2000 // 轮询间隔(毫秒),默认2秒
|
||||
|
||||
@Value("\${copy.trading.polling.enabled:true}")
|
||||
private var pollingEnabled: Boolean = true // 是否启用轮询
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
// 存储需要监听的Leader:leaderId -> Leader
|
||||
private val monitoredLeaders = ConcurrentHashMap<Long, Leader>()
|
||||
|
||||
// 存储每个Leader已缓存的交易ID集合:leaderId -> Set<tradeId>
|
||||
private val cachedTradeIds = ConcurrentHashMap<Long, MutableSet<String>>()
|
||||
|
||||
// 存储每个Leader是否首次轮询:leaderId -> isFirstPoll
|
||||
private val isFirstPoll = ConcurrentHashMap<Long, Boolean>()
|
||||
|
||||
// 轮询任务
|
||||
private var pollingJob: Job? = null
|
||||
|
||||
/**
|
||||
* 启动轮询监听
|
||||
*/
|
||||
fun start(leaders: List<Leader>) {
|
||||
if (!pollingEnabled) {
|
||||
return
|
||||
}
|
||||
|
||||
leaders.forEach { leader ->
|
||||
addLeader(leader)
|
||||
}
|
||||
|
||||
// 启动轮询任务
|
||||
startPolling()
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加Leader监听
|
||||
*/
|
||||
fun addLeader(leader: Leader) {
|
||||
if (leader.id == null) {
|
||||
logger.warn("Leader ID为空,跳过: ${leader.leaderAddress}")
|
||||
return
|
||||
}
|
||||
|
||||
val leaderId = leader.id
|
||||
monitoredLeaders[leaderId] = leader
|
||||
// 初始化缓存的交易ID集合
|
||||
cachedTradeIds[leaderId] = mutableSetOf()
|
||||
// 首次轮询标志,用于缓存数据而不处理
|
||||
isFirstPoll[leaderId] = true
|
||||
|
||||
// 如果轮询任务没有运行,启动它
|
||||
startPolling()
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除Leader监听
|
||||
*/
|
||||
fun removeLeader(leaderId: Long) {
|
||||
monitoredLeaders.remove(leaderId)
|
||||
cachedTradeIds.remove(leaderId)
|
||||
isFirstPoll.remove(leaderId)
|
||||
|
||||
// 如果没有需要监听的Leader了,停止轮询任务
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
stopPolling()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止所有监听
|
||||
*/
|
||||
fun stop() {
|
||||
stopPolling()
|
||||
monitoredLeaders.clear()
|
||||
cachedTradeIds.clear()
|
||||
isFirstPoll.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动轮询任务
|
||||
*/
|
||||
private fun startPolling() {
|
||||
if (pollingJob != null && pollingJob!!.isActive) {
|
||||
return
|
||||
}
|
||||
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
pollingJob = scope.launch {
|
||||
|
||||
while (isActive) {
|
||||
try {
|
||||
// 轮询所有Leader的交易
|
||||
pollAllLeaders()
|
||||
|
||||
// 等待下一次轮询
|
||||
delay(pollingInterval)
|
||||
} catch (e: Exception) {
|
||||
logger.error("轮询任务异常", e)
|
||||
delay(pollingInterval) // 异常后继续等待
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止轮询任务
|
||||
*/
|
||||
private fun stopPolling() {
|
||||
pollingJob?.cancel()
|
||||
pollingJob = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询所有Leader的交易
|
||||
*/
|
||||
private suspend fun pollAllLeaders() {
|
||||
val leaders = monitoredLeaders.values.toList()
|
||||
|
||||
if (leaders.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
// 并发轮询所有Leader(限制并发数)
|
||||
leaders.chunked(10).forEach { chunk ->
|
||||
chunk.forEach { leader ->
|
||||
try {
|
||||
pollLeaderTrades(leader)
|
||||
} catch (e: Exception) {
|
||||
logger.error("轮询Leader交易失败: leaderId=${leader.id}, address=${leader.leaderAddress}", e)
|
||||
}
|
||||
}
|
||||
// 每个chunk之间稍作延迟,避免API限流
|
||||
delay(100)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询单个Leader的交易
|
||||
* 使用 Polymarket Data API 的 /activity 接口
|
||||
* 通过 diff 分析增量数据,不使用 start 字段
|
||||
*/
|
||||
private suspend fun pollLeaderTrades(leader: Leader) {
|
||||
if (leader.id == null) {
|
||||
return
|
||||
}
|
||||
|
||||
val leaderId = leader.id
|
||||
val leaderAddress = leader.leaderAddress
|
||||
|
||||
try {
|
||||
val firstPoll = isFirstPoll[leaderId] == true
|
||||
val cachedIds = cachedTradeIds[leaderId] ?: mutableSetOf()
|
||||
|
||||
// 创建 Data API 客户端(不需要认证)
|
||||
val dataApi = retrofitFactory.createDataApi()
|
||||
|
||||
// 查询用户活动(只查询交易类型,不使用 start 字段)
|
||||
// 查询最近的数据(limit=100),通过 diff 找出增量
|
||||
val response: Response<List<UserActivityResponse>> = dataApi.getUserActivity(
|
||||
user = leaderAddress,
|
||||
limit = 100, // 每次最多查询100条
|
||||
offset = 0,
|
||||
type = listOf("TRADE"), // 只查询交易类型
|
||||
start = null, // 不使用 start 字段
|
||||
sortBy = "TIMESTAMP",
|
||||
sortDirection = "DESC" // 按时间戳降序,最新的在前
|
||||
)
|
||||
|
||||
if (!response.isSuccessful || response.body() == null) {
|
||||
logger.warn("获取Leader活动失败: leaderId=$leaderId, address=$leaderAddress, code=${response.code()}, message=${response.message()}")
|
||||
return
|
||||
}
|
||||
|
||||
val activities = response.body()!!
|
||||
|
||||
// 将 UserActivityResponse 转换为 TradeResponse
|
||||
val allTrades = activities.mapNotNull { activity ->
|
||||
// 只处理交易类型
|
||||
if (activity.type != "TRADE" || activity.side == null || activity.price == null || activity.size == null) {
|
||||
return@mapNotNull null
|
||||
}
|
||||
|
||||
// 转换为 TradeResponse
|
||||
TradeResponse(
|
||||
id = activity.transactionHash ?: "${activity.timestamp}_${activity.conditionId}",
|
||||
market = activity.conditionId,
|
||||
side = activity.side, // BUY 或 SELL
|
||||
price = activity.price.toString(),
|
||||
size = activity.size.toString(),
|
||||
timestamp = activity.timestamp.toString(), // 时间戳(秒)
|
||||
user = activity.proxyWallet,
|
||||
outcomeIndex = activity.outcomeIndex, // 结果索引(0=YES, 1=NO)
|
||||
outcome = activity.outcome // 结果名称
|
||||
)
|
||||
}
|
||||
|
||||
if (firstPoll) {
|
||||
// 首次轮询:缓存所有查询到的交易ID,不处理
|
||||
val tradeIds = allTrades.map { it.id }.toSet()
|
||||
cachedIds.addAll(tradeIds)
|
||||
cachedTradeIds[leaderId] = cachedIds
|
||||
|
||||
// 标记首次轮询完成
|
||||
isFirstPoll[leaderId] = false
|
||||
} else {
|
||||
// 后续轮询:通过 diff 找出新增的交易
|
||||
val newTradeIds = allTrades.map { it.id }.toSet()
|
||||
val incrementalTradeIds = newTradeIds - cachedIds
|
||||
|
||||
if (incrementalTradeIds.isNotEmpty()) {
|
||||
// 找出新增的交易
|
||||
val incrementalTrades = allTrades.filter { it.id in incrementalTradeIds }
|
||||
|
||||
|
||||
// 处理新增的交易
|
||||
incrementalTrades.forEach { trade ->
|
||||
try {
|
||||
// 检查是否已处理(去重由processTrade内部处理)
|
||||
copyOrderTrackingService.processTrade(leaderId, trade, "polling")
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理交易失败: leaderId=$leaderId, tradeId=${trade.id}", e)
|
||||
}
|
||||
}
|
||||
|
||||
// 更新缓存:添加新增的交易ID
|
||||
cachedIds.addAll(incrementalTradeIds)
|
||||
cachedTradeIds[leaderId] = cachedIds
|
||||
|
||||
} else {
|
||||
}
|
||||
|
||||
// 限制缓存大小,避免内存溢出(只保留最近1000条)
|
||||
if (cachedIds.size > 1000) {
|
||||
// 保留最新的1000条(由于查询是按时间戳降序,保留前1000条即可)
|
||||
val sortedTradeIds = allTrades.map { it.id }.take(1000).toSet()
|
||||
cachedTradeIds[leaderId] = sortedTradeIds.toMutableSet()
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("轮询Leader交易异常: leaderId=$leaderId, address=$leaderAddress", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-3
@@ -22,15 +22,14 @@ import java.util.concurrent.ConcurrentHashMap
|
||||
@Service
|
||||
class CopyTradingWebSocketService(
|
||||
private val copyOrderTrackingService: CopyOrderTrackingService,
|
||||
private val templateRepository: CopyTradingTemplateRepository
|
||||
private val templateRepository: CopyTradingTemplateRepository,
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CopyTradingWebSocketService::class.java)
|
||||
|
||||
@Value("\${polymarket.websocket.url:wss://ws-live-data.polymarket.com}")
|
||||
private var websocketUrl: String = "wss://ws-live-data.polymarket.com"
|
||||
|
||||
private val gson = Gson()
|
||||
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
// 存储每个Leader的WebSocket客户端:leaderId -> WebSocketClient
|
||||
|
||||
+70
-807
@@ -1,37 +1,24 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.entity.Leader
|
||||
import com.wrbug.polymarketbot.repository.LeaderRepository
|
||||
import com.wrbug.polymarketbot.service.copytrading.statistics.CopyOrderTrackingService
|
||||
import com.wrbug.polymarketbot.service.system.RpcNodeService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.createClient
|
||||
import com.wrbug.polymarketbot.util.getProxyConfig
|
||||
import jakarta.annotation.PreDestroy
|
||||
import kotlinx.coroutines.*
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okio.ByteString
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.stereotype.Service
|
||||
import java.math.BigInteger
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 链上 WebSocket 监听服务
|
||||
* 通过 Polygon RPC 的 eth_subscribe 实时监听链上交易
|
||||
* 通过统一服务订阅 Leader 的链上交易
|
||||
*/
|
||||
@Service
|
||||
class OnChainWsService(
|
||||
private val rpcNodeService: RpcNodeService,
|
||||
private val unifiedOnChainWsService: UnifiedOnChainWsService,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val copyOrderTrackingService: CopyOrderTrackingService,
|
||||
private val leaderRepository: LeaderRepository
|
||||
@@ -39,84 +26,31 @@ class OnChainWsService(
|
||||
|
||||
private val logger = LoggerFactory.getLogger(OnChainWsService::class.java)
|
||||
|
||||
// Gson 实例,用于解析 JSON
|
||||
private val gson = Gson()
|
||||
|
||||
@Value("\${copy.trading.onchain.ws.reconnect.delay:3000}")
|
||||
private var reconnectDelay: Long = 3000 // 重连延迟(毫秒),默认3秒
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
// 存储需要监听的Leader:leaderId -> Leader
|
||||
private val monitoredLeaders = ConcurrentHashMap<Long, Leader>()
|
||||
|
||||
// 存储每个 Leader 的订阅 ID:leaderId -> List<subscriptionId>
|
||||
// 每个 Leader 有 6 个订阅:USDC from/to, ERC1155 TransferSingle from/to, ERC1155 TransferBatch from/to
|
||||
private val leaderSubscriptions = ConcurrentHashMap<Long, MutableList<String>>()
|
||||
|
||||
// 存储请求 ID 到 Leader ID 的映射:requestId -> leaderId
|
||||
// 用于在收到订阅响应时,将 subscription ID 关联到对应的 Leader
|
||||
private val requestIdToLeaderId = ConcurrentHashMap<Int, Long>()
|
||||
|
||||
// WebSocket 连接
|
||||
private var webSocket: WebSocket? = null
|
||||
@Volatile
|
||||
private var isConnected = false
|
||||
|
||||
// 订阅ID计数器(用于请求 ID)
|
||||
private var requestIdCounter = 0
|
||||
|
||||
// 合约地址
|
||||
companion object {
|
||||
private const val USDC_CONTRACT = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
|
||||
private const val ERC1155_CONTRACT = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
|
||||
private const val ERC20_TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
|
||||
private const val ERC1155_TRANSFER_SINGLE_TOPIC = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"
|
||||
private const val ERC1155_TRANSFER_BATCH_TOPIC = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb"
|
||||
}
|
||||
|
||||
// 连接任务(确保只有一个连接任务在运行)
|
||||
private var connectionJob: Job? = null
|
||||
|
||||
/**
|
||||
* 启动链上 WebSocket 监听
|
||||
* 只创建一个 WebSocket 连接,为所有 Leader 订阅
|
||||
* 通过统一服务订阅所有 Leader
|
||||
*/
|
||||
fun start(leaders: List<Leader>) {
|
||||
// 如果没有 Leader,不启动连接
|
||||
// 如果没有 Leader,取消所有订阅
|
||||
if (leaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,不启动链上 WebSocket 连接")
|
||||
logger.info("没有需要监听的 Leader,取消所有订阅")
|
||||
stop()
|
||||
return
|
||||
}
|
||||
|
||||
// 如果连接任务已经在运行,先停止旧任务
|
||||
if (connectionJob != null && connectionJob!!.isActive) {
|
||||
logger.info("停止旧的连接任务,准备重新启动")
|
||||
connectionJob?.cancel()
|
||||
connectionJob = null
|
||||
// 关闭旧连接
|
||||
webSocket?.close(1000, "重新启动")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
}
|
||||
|
||||
// 更新 Leader 列表
|
||||
monitoredLeaders.clear()
|
||||
leaders.forEach { leader ->
|
||||
addLeader(leader)
|
||||
}
|
||||
|
||||
// 启动连接任务(只创建一个)
|
||||
connectionJob = scope.launch {
|
||||
startConnection()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加Leader监听
|
||||
* 如果 Leader 已经在监听列表中,不重复添加
|
||||
* 如果已连接,立即订阅
|
||||
* 通过统一服务订阅该 Leader 的地址
|
||||
*/
|
||||
fun addLeader(leader: Leader) {
|
||||
if (leader.id == null) {
|
||||
@@ -133,406 +67,30 @@ class OnChainWsService(
|
||||
}
|
||||
|
||||
monitoredLeaders[leaderId] = leader
|
||||
|
||||
// 通过统一服务订阅
|
||||
val subscriptionId = "LEADER_$leaderId"
|
||||
unifiedOnChainWsService.subscribe(
|
||||
subscriptionId = subscriptionId,
|
||||
address = leader.leaderAddress,
|
||||
entityType = "LEADER",
|
||||
entityId = leaderId,
|
||||
callback = { txHash, httpClient, rpcApi ->
|
||||
handleLeaderTransaction(leaderId, txHash, httpClient, rpcApi)
|
||||
}
|
||||
)
|
||||
|
||||
logger.info("添加 Leader 监听: ${leader.leaderName} (${leader.leaderAddress})")
|
||||
|
||||
// 如果已连接,立即订阅
|
||||
if (isConnected && webSocket != null) {
|
||||
scope.launch {
|
||||
subscribeLeader(leader)
|
||||
}
|
||||
} else {
|
||||
// 如果未连接,启动连接(如果连接任务未运行)
|
||||
if (connectionJob == null || !connectionJob!!.isActive) {
|
||||
connectionJob = scope.launch {
|
||||
startConnection()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除Leader监听
|
||||
* 通过 eth_unsubscribe 取消该 Leader 的所有订阅
|
||||
* 如果没有 Leader 了,关闭 WebSocket 连接
|
||||
* 处理 Leader 的交易
|
||||
*/
|
||||
fun removeLeader(leaderId: Long) {
|
||||
val leader = monitoredLeaders.remove(leaderId)
|
||||
if (leader != null) {
|
||||
logger.info("移除 Leader 监听: ${leader.leaderName} (${leader.leaderAddress})")
|
||||
}
|
||||
private suspend fun handleLeaderTransaction(leaderId: Long, txHash: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
val leader = monitoredLeaders[leaderId] ?: return
|
||||
|
||||
// 取消该 Leader 的所有订阅
|
||||
val subscriptions = leaderSubscriptions.remove(leaderId)
|
||||
if (subscriptions != null && subscriptions.isNotEmpty() && isConnected && webSocket != null) {
|
||||
logger.info("取消 Leader ${leader?.leaderName} 的 ${subscriptions.size} 个订阅")
|
||||
subscriptions.forEach { subscriptionId ->
|
||||
unsubscribe(subscriptionId)
|
||||
}
|
||||
}
|
||||
logger.debug("开始处理 Leader 交易: leaderId=$leaderId, txHash=$txHash, leaderAddress=${leader.leaderAddress}")
|
||||
|
||||
// 如果没有 Leader 了,关闭连接
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,关闭链上 WebSocket 连接")
|
||||
stop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止所有监听
|
||||
*/
|
||||
fun stop() {
|
||||
connectionJob?.cancel()
|
||||
connectionJob = null
|
||||
|
||||
// 取消所有订阅
|
||||
if (isConnected && webSocket != null) {
|
||||
leaderSubscriptions.values.flatten().forEach { subscriptionId ->
|
||||
unsubscribe(subscriptionId)
|
||||
}
|
||||
}
|
||||
|
||||
webSocket?.close(1000, "正常关闭")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
monitoredLeaders.clear()
|
||||
leaderSubscriptions.clear()
|
||||
requestIdToLeaderId.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动连接(带重连机制)
|
||||
* 只创建一个 WebSocket 连接
|
||||
*/
|
||||
private suspend fun startConnection() {
|
||||
while (scope.isActive) {
|
||||
try {
|
||||
// 检查是否有需要监听的 Leader
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,停止连接")
|
||||
// 确保关闭连接
|
||||
webSocket?.close(1000, "没有 Leader")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
break
|
||||
}
|
||||
|
||||
// 如果已经连接,不需要重新连接
|
||||
if (isConnected && webSocket != null) {
|
||||
// 等待连接断开
|
||||
waitForDisconnect()
|
||||
// 连接断开后继续重连循环
|
||||
continue
|
||||
}
|
||||
|
||||
// 从后台配置获取 WS RPC URL
|
||||
val wsUrl = rpcNodeService.getWsUrl()
|
||||
val httpUrl = rpcNodeService.getHttpUrl()
|
||||
|
||||
logger.info("连接链上 WebSocket: $wsUrl (监听 ${monitoredLeaders.size} 个 Leader)")
|
||||
|
||||
// 创建 HTTP 客户端(用于 RPC 调用)
|
||||
val httpClient = createHttpClient()
|
||||
|
||||
// 创建 RPC API 客户端
|
||||
val rpcApi = retrofitFactory.createEthereumRpcApi(httpUrl)
|
||||
|
||||
// 连接 WebSocket(只创建一个连接,会先关闭旧连接)
|
||||
connectWebSocket(wsUrl, httpClient, rpcApi)
|
||||
|
||||
// 等待连接建立(最多等待 15 秒)
|
||||
// 注意:onOpen 回调是异步的,需要等待一段时间
|
||||
var waitCount = 0
|
||||
val maxWait = 15 // 最多等待 15 秒
|
||||
while (!isConnected && waitCount < maxWait && scope.isActive) {
|
||||
delay(1000)
|
||||
waitCount++
|
||||
// 每 3 秒打印一次日志,方便调试
|
||||
if (waitCount % 3 == 0) {
|
||||
logger.debug("等待 WebSocket 连接建立... (${waitCount}/${maxWait}秒)")
|
||||
}
|
||||
}
|
||||
|
||||
// 检查连接状态(同时检查 isConnected 和 webSocket 状态)
|
||||
val actuallyConnected = isConnected && webSocket != null
|
||||
|
||||
// 如果连接失败,等待重连延迟后继续
|
||||
if (!actuallyConnected) {
|
||||
logger.warn("WebSocket 连接超时或失败: isConnected=$isConnected, webSocket=${webSocket != null}, 等待重连")
|
||||
delay(reconnectDelay)
|
||||
continue
|
||||
}
|
||||
|
||||
logger.info("WebSocket 连接已建立,开始监听")
|
||||
|
||||
// 连接成功后持续监听
|
||||
waitForDisconnect()
|
||||
|
||||
// 连接断开后,如果没有 Leader 了,不再重连
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,停止重连")
|
||||
break
|
||||
}
|
||||
|
||||
// 连接断开后,等待一下再重连(避免立即重连)
|
||||
logger.info("WebSocket 连接断开,等待 ${reconnectDelay}ms 后重连")
|
||||
delay(reconnectDelay)
|
||||
} catch (e: Exception) {
|
||||
// 如果没有 Leader 了,不再重连
|
||||
if (monitoredLeaders.isEmpty()) {
|
||||
logger.info("没有需要监听的 Leader,停止重连")
|
||||
// 确保关闭连接
|
||||
webSocket?.close(1000, "没有 Leader")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
break
|
||||
}
|
||||
logger.warn("链上 WebSocket 连接失败,等待重连: ${e.message}")
|
||||
// 确保关闭旧连接
|
||||
webSocket?.close(1000, "重连前关闭")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
delay(reconnectDelay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 HTTP 客户端
|
||||
*/
|
||||
private fun createHttpClient(): OkHttpClient {
|
||||
val proxy = getProxyConfig()
|
||||
val builder = createClient()
|
||||
|
||||
if (proxy != null) {
|
||||
builder.proxy(proxy)
|
||||
}
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接 WebSocket
|
||||
* 确保只创建一个连接,创建新连接前先关闭旧连接
|
||||
*/
|
||||
private fun connectWebSocket(wsUrl: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
// 先关闭旧连接(如果存在)
|
||||
val oldWebSocket = webSocket
|
||||
if (oldWebSocket != null) {
|
||||
try {
|
||||
oldWebSocket.close(1000, "重新连接")
|
||||
} catch (e: Exception) {
|
||||
logger.debug("关闭旧 WebSocket 连接时出错: ${e.message}")
|
||||
}
|
||||
}
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(wsUrl)
|
||||
.build()
|
||||
|
||||
// 创建新连接(只创建一个)
|
||||
webSocket = httpClient.newWebSocket(request, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
|
||||
isConnected = true
|
||||
logger.info("链上 WebSocket 连接成功")
|
||||
|
||||
// 订阅所有 Leader
|
||||
scope.launch {
|
||||
monitoredLeaders.values.forEach { leader ->
|
||||
subscribeLeader(leader)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
scope.launch {
|
||||
handleMessage(text, httpClient, rpcApi)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
scope.launch {
|
||||
handleMessage(bytes.utf8(), httpClient, rpcApi)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("链上 WebSocket 连接关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("链上 WebSocket 连接已关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
|
||||
logger.error("链上 WebSocket 连接失败: ${t.message}", t)
|
||||
isConnected = false
|
||||
// 注意:这里不直接重连,由 startConnection 循环处理重连逻辑
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待连接断开
|
||||
*/
|
||||
private suspend fun waitForDisconnect() {
|
||||
while (isConnected && scope.isActive) {
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅 Leader 钱包地址
|
||||
* 每个 Leader 有 6 个订阅,保存订阅 ID 以便后续取消
|
||||
*/
|
||||
private suspend fun subscribeLeader(leader: Leader) {
|
||||
if (webSocket == null || !isConnected || leader.id == null) {
|
||||
return
|
||||
}
|
||||
|
||||
val walletAddress = leader.leaderAddress.lowercase()
|
||||
val walletTopic = addressToTopic32(walletAddress)
|
||||
val leaderId = leader.id!!
|
||||
|
||||
// 初始化该 Leader 的订阅列表
|
||||
if (!leaderSubscriptions.containsKey(leaderId)) {
|
||||
leaderSubscriptions[leaderId] = mutableListOf()
|
||||
}
|
||||
|
||||
try {
|
||||
// 订阅 USDC Transfer (from wallet)
|
||||
subscribeLogs(USDC_CONTRACT, listOf(ERC20_TRANSFER_TOPIC, walletTopic), leaderId)
|
||||
|
||||
// 订阅 USDC Transfer (to wallet)
|
||||
subscribeLogs(USDC_CONTRACT, listOf(ERC20_TRANSFER_TOPIC, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferSingle (from wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_SINGLE_TOPIC, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferSingle (to wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_SINGLE_TOPIC, null, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferBatch (from wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_BATCH_TOPIC, null, walletTopic), leaderId)
|
||||
|
||||
// 订阅 ERC1155 TransferBatch (to wallet)
|
||||
subscribeLogs(ERC1155_CONTRACT, listOf(ERC1155_TRANSFER_BATCH_TOPIC, null, null, walletTopic), leaderId)
|
||||
|
||||
logger.debug("已订阅 Leader 钱包地址: ${leader.leaderName} (${walletAddress})")
|
||||
} catch (e: Exception) {
|
||||
logger.error("订阅 Leader 失败: leaderId=$leaderId, address=$walletAddress", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅日志
|
||||
* @param address 合约地址
|
||||
* @param topics 主题列表
|
||||
* @param leaderId Leader ID,用于关联订阅响应
|
||||
*/
|
||||
private fun subscribeLogs(address: String, topics: List<String?>, leaderId: Long) {
|
||||
val ws = webSocket ?: return
|
||||
|
||||
val params = mapOf(
|
||||
"address" to address.lowercase(),
|
||||
"topics" to topics
|
||||
)
|
||||
|
||||
val subscribeParams = listOf("logs", params)
|
||||
|
||||
val requestId = ++requestIdCounter
|
||||
|
||||
// 保存请求 ID 到 Leader ID 的映射
|
||||
requestIdToLeaderId[requestId] = leaderId
|
||||
|
||||
val request = mapOf(
|
||||
"jsonrpc" to "2.0",
|
||||
"id" to requestId,
|
||||
"method" to "eth_subscribe",
|
||||
"params" to subscribeParams
|
||||
)
|
||||
|
||||
val json = gson.toJson(request)
|
||||
ws.send(json)
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消订阅
|
||||
* @param subscriptionId 订阅 ID
|
||||
*/
|
||||
private fun unsubscribe(subscriptionId: String) {
|
||||
val ws = webSocket ?: return
|
||||
|
||||
val request = mapOf(
|
||||
"jsonrpc" to "2.0",
|
||||
"id" to (++requestIdCounter),
|
||||
"method" to "eth_unsubscribe",
|
||||
"params" to listOf(subscriptionId)
|
||||
)
|
||||
|
||||
val json = gson.toJson(request)
|
||||
ws.send(json)
|
||||
logger.debug("已发送取消订阅请求: subscriptionId=$subscriptionId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 WebSocket 消息
|
||||
*/
|
||||
private suspend fun handleMessage(message: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
try {
|
||||
// 使用 Gson 解析消息
|
||||
val messageJson = gson.fromJson(message, JsonObject::class.java)
|
||||
|
||||
// 处理订阅响应(包含 subscription ID)
|
||||
val id = messageJson.get("id")
|
||||
if (id != null && !id.isJsonNull) {
|
||||
val result = messageJson.get("result")
|
||||
if (result != null && result.isJsonPrimitive && result.asJsonPrimitive.isString) {
|
||||
// 这是订阅响应,result 是 subscription ID(字符串)
|
||||
val requestId = id.asInt
|
||||
val subscriptionId = result.asString
|
||||
val leaderId = requestIdToLeaderId.remove(requestId)
|
||||
if (leaderId != null) {
|
||||
// 保存订阅 ID 到 Leader
|
||||
leaderSubscriptions.getOrPut(leaderId) { mutableListOf() }.add(subscriptionId)
|
||||
logger.debug("收到订阅响应: leaderId=$leaderId, subscriptionId=$subscriptionId")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 处理订阅通知(交易日志)
|
||||
val method = messageJson.get("method")?.asString
|
||||
if (method != "eth_subscription") {
|
||||
return
|
||||
}
|
||||
|
||||
val params = messageJson.getAsJsonObject("params") ?: return
|
||||
// result 是一个对象,包含日志信息
|
||||
val result = params.getAsJsonObject("result") ?: return
|
||||
|
||||
// 从 result 对象中获取 transactionHash(关键数据)
|
||||
val txHash = result.get("transactionHash")?.asString
|
||||
if (txHash.isNullOrEmpty()) {
|
||||
logger.debug("订阅通知中缺少 transactionHash,跳过处理")
|
||||
return
|
||||
}
|
||||
|
||||
// 处理交易
|
||||
processTransaction(txHash, httpClient, rpcApi)
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理 WebSocket 消息失败: ${e.message}", e)
|
||||
logger.debug("消息内容: $message", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理交易
|
||||
*/
|
||||
private suspend fun processTransaction(txHash: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
try {
|
||||
// 获取交易 receipt
|
||||
val receiptRequest = JsonRpcRequest(
|
||||
@@ -542,384 +100,89 @@ class OnChainWsService(
|
||||
|
||||
val receiptResponse = rpcApi.call(receiptRequest)
|
||||
if (!receiptResponse.isSuccessful || receiptResponse.body() == null) {
|
||||
logger.warn("获取交易 receipt 失败: leaderId=$leaderId, txHash=$txHash, code=${receiptResponse.code()}")
|
||||
return
|
||||
}
|
||||
|
||||
val receiptRpcResponse = receiptResponse.body()!!
|
||||
if (receiptRpcResponse.error != null || receiptRpcResponse.result == null) {
|
||||
logger.warn("交易 receipt 错误: leaderId=$leaderId, txHash=$txHash, error=${receiptRpcResponse.error}")
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 receipt JSON(result 是 JsonElement)
|
||||
// 使用 Gson 解析 receipt JSON
|
||||
val receiptJson = receiptRpcResponse.result.asJsonObject
|
||||
|
||||
// 获取区块号和时间戳
|
||||
val blockNumber = receiptJson.get("blockNumber")?.asString
|
||||
val blockTimestamp = if (blockNumber != null) {
|
||||
getBlockTimestamp(blockNumber, rpcApi)
|
||||
OnChainWsUtils.getBlockTimestamp(blockNumber, rpcApi)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
// 解析 receipt 中的 Transfer 日志
|
||||
val logs = receiptJson.getAsJsonArray("logs") ?: return
|
||||
val (erc20Transfers, erc1155Transfers) = parseReceiptTransfers(logs)
|
||||
val logs = receiptJson.getAsJsonArray("logs") ?: run {
|
||||
logger.warn("交易 receipt 中没有日志: leaderId=$leaderId, txHash=$txHash")
|
||||
return
|
||||
}
|
||||
val (erc20Transfers, erc1155Transfers) = OnChainWsUtils.parseReceiptTransfers(logs)
|
||||
logger.debug("解析交易日志: leaderId=$leaderId, txHash=$txHash, erc20Transfers=${erc20Transfers.size}, erc1155Transfers=${erc1155Transfers.size}")
|
||||
|
||||
// 为每个 Leader 处理交易
|
||||
for (leader in monitoredLeaders.values) {
|
||||
val trade = parseTradeFromTransfers(
|
||||
txHash = txHash,
|
||||
timestamp = blockTimestamp,
|
||||
walletAddress = leader.leaderAddress,
|
||||
erc20Transfers = erc20Transfers,
|
||||
erc1155Transfers = erc1155Transfers
|
||||
// 解析交易信息
|
||||
val trade = OnChainWsUtils.parseTradeFromTransfers(
|
||||
txHash = txHash,
|
||||
timestamp = blockTimestamp,
|
||||
walletAddress = leader.leaderAddress,
|
||||
erc20Transfers = erc20Transfers,
|
||||
erc1155Transfers = erc1155Transfers,
|
||||
retrofitFactory = retrofitFactory
|
||||
)
|
||||
|
||||
if (trade != null) {
|
||||
logger.info("成功解析交易: leaderId=$leaderId, txHash=$txHash, side=${trade.side}, market=${trade.market}, size=${trade.size}")
|
||||
// 调用 processTrade 处理交易
|
||||
copyOrderTrackingService.processTrade(
|
||||
leaderId = leaderId,
|
||||
trade = trade,
|
||||
source = "onchain-ws"
|
||||
)
|
||||
|
||||
if (trade != null) {
|
||||
// 调用 processTrade 处理交易(元数据已在 parseTradeFromTransfers 中补齐)
|
||||
copyOrderTrackingService.processTrade(
|
||||
leaderId = leader.id!!,
|
||||
trade = trade,
|
||||
source = "onchain-ws"
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理交易失败: txHash=$txHash, ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 receipt 中的 Transfer 日志
|
||||
*/
|
||||
private fun parseReceiptTransfers(logs: com.google.gson.JsonArray): Pair<List<Erc20Transfer>, List<Erc1155Transfer>> {
|
||||
val erc20 = mutableListOf<Erc20Transfer>()
|
||||
val erc1155 = mutableListOf<Erc1155Transfer>()
|
||||
|
||||
for (logElement in logs) {
|
||||
val log = logElement.asJsonObject
|
||||
val address = log.get("address")?.asString?.lowercase() ?: continue
|
||||
val topicsArray = log.getAsJsonArray("topics") ?: continue
|
||||
val topics = topicsArray.mapNotNull { it.asString }
|
||||
if (topics.isEmpty()) continue
|
||||
|
||||
val t0 = topics[0].lowercase()
|
||||
val data = log.get("data")?.asString ?: "0x"
|
||||
|
||||
// USDC ERC20 Transfer
|
||||
if (address == USDC_CONTRACT.lowercase() && t0 == ERC20_TRANSFER_TOPIC && topics.size >= 3) {
|
||||
val from = topicToAddress(topics[1])
|
||||
val to = topicToAddress(topics[2])
|
||||
val value = hexToBigInt(data)
|
||||
erc20.add(Erc20Transfer(from, to, value))
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferSingle
|
||||
if (t0 == ERC1155_TRANSFER_SINGLE_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size >= 64) {
|
||||
val tokenId = sliceBigInt32(bytes, 0)
|
||||
val value = sliceBigInt32(bytes, 32)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferBatch
|
||||
if (t0 == ERC1155_TRANSFER_BATCH_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size < 64) continue
|
||||
|
||||
val offIds = sliceBigInt32(bytes, 0).toInt()
|
||||
val offVals = sliceBigInt32(bytes, 32).toInt()
|
||||
if (offIds + 32 > bytes.size || offVals + 32 > bytes.size) continue
|
||||
|
||||
val nIds = sliceBigInt32(bytes, offIds).toInt()
|
||||
val nVals = sliceBigInt32(bytes, offVals).toInt()
|
||||
if (nIds != nVals) continue
|
||||
|
||||
val idsStart = offIds + 32
|
||||
val valsStart = offVals + 32
|
||||
for (i in 0 until nIds) {
|
||||
val ib = idsStart + i * 32
|
||||
val vb = valsStart + i * 32
|
||||
if (ib + 32 > bytes.size || vb + 32 > bytes.size) break
|
||||
val tokenId = sliceBigInt32(bytes, ib)
|
||||
val value = sliceBigInt32(bytes, vb)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Pair(erc20, erc1155)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Transfer 日志解析交易信息
|
||||
*/
|
||||
private suspend fun parseTradeFromTransfers(
|
||||
txHash: String,
|
||||
timestamp: Long?,
|
||||
walletAddress: String,
|
||||
erc20Transfers: List<Erc20Transfer>,
|
||||
erc1155Transfers: List<Erc1155Transfer>
|
||||
): TradeResponse? {
|
||||
val wallet = walletAddress.lowercase()
|
||||
|
||||
// 计算 USDC 流入和流出
|
||||
val usdcOut = erc20Transfers.filter { it.from.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
val usdcIn = erc20Transfers.filter { it.to.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
|
||||
// 计算 ERC1155 流入和流出(按 tokenId 聚合)
|
||||
val inById = mutableMapOf<BigInteger, BigInteger>()
|
||||
val outById = mutableMapOf<BigInteger, BigInteger>()
|
||||
for (t in erc1155Transfers) {
|
||||
if (t.to.lowercase() == wallet) {
|
||||
inById[t.tokenId] = (inById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
if (t.from.lowercase() == wallet) {
|
||||
outById[t.tokenId] = (outById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
}
|
||||
|
||||
// 找到最大的流入和流出 tokenId
|
||||
fun best(map: Map<BigInteger, BigInteger>): Pair<BigInteger?, BigInteger> =
|
||||
map.entries.maxByOrNull { it.value }?.let { it.key to it.value } ?: (null to BigInteger.ZERO)
|
||||
|
||||
val (bestInId, bestInVal) = best(inById)
|
||||
val (bestOutId, bestOutVal) = best(outById)
|
||||
|
||||
// 判断交易方向
|
||||
var side: String? = null
|
||||
var asset: BigInteger? = null
|
||||
var sizeRaw = BigInteger.ZERO
|
||||
var usdcRaw = BigInteger.ZERO
|
||||
|
||||
if (bestInId != null && bestInVal > BigInteger.ZERO && usdcOut > BigInteger.ZERO) {
|
||||
// BUY: 收到 token,支付 USDC
|
||||
side = "BUY"
|
||||
asset = bestInId
|
||||
sizeRaw = bestInVal
|
||||
usdcRaw = usdcOut
|
||||
} else if (bestOutId != null && bestOutVal > BigInteger.ZERO && usdcIn > BigInteger.ZERO) {
|
||||
// SELL: 卖出 token,收到 USDC
|
||||
side = "SELL"
|
||||
asset = bestOutId
|
||||
sizeRaw = bestOutVal
|
||||
usdcRaw = usdcIn
|
||||
} else {
|
||||
// 无法判断交易方向
|
||||
return null
|
||||
}
|
||||
|
||||
// 计算价格和数量(USDC 有 6 位小数,shares 也有 6 位小数)
|
||||
val usdcSize = usdcRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val size = sizeRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val price = if (size.signum() > 0) {
|
||||
usdcSize.divide(size, 8, java.math.RoundingMode.DOWN)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
// 尝试通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
val marketInfo = fetchMarketByTokenId(asset.toString())
|
||||
|
||||
// 创建 TradeResponse
|
||||
return TradeResponse(
|
||||
id = txHash,
|
||||
market = marketInfo?.conditionId ?: "",
|
||||
side = side,
|
||||
price = price.toPlainString(),
|
||||
size = size.toPlainString(),
|
||||
timestamp = (timestamp ?: System.currentTimeMillis() / 1000).toString(),
|
||||
user = walletAddress,
|
||||
outcomeIndex = marketInfo?.outcomeIndex,
|
||||
outcome = marketInfo?.outcome
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
*/
|
||||
private suspend fun fetchMarketByTokenId(tokenId: String): MarketInfo? {
|
||||
return try {
|
||||
// 使用 HTTP 请求直接调用 Gamma API(因为 Retrofit 接口可能不支持 clob_token_ids 参数)
|
||||
val httpClient = createHttpClient()
|
||||
val url = "https://gamma-api.polymarket.com/markets?clob_token_ids=$tokenId"
|
||||
|
||||
val request = okhttp3.Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.build()
|
||||
|
||||
val response = httpClient.newCall(request).execute()
|
||||
if (!response.isSuccessful || response.body == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
val responseBody = response.body!!.string()
|
||||
// 使用 Gson 解析市场列表
|
||||
val marketsType = object : TypeToken<List<JsonObject>>() {}.type
|
||||
val markets = gson.fromJson<List<JsonObject>>(responseBody, marketsType)
|
||||
|
||||
if (markets.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
|
||||
val market = markets.first()
|
||||
|
||||
// 解析 clob_token_ids(可能是 JSON 字符串或数组)
|
||||
val clobTokenIdsRaw = market.get("clobTokenIds") ?: market.get("clob_token_ids")
|
||||
val clobTokenIds = when {
|
||||
clobTokenIdsRaw == null || clobTokenIdsRaw.isJsonNull -> null
|
||||
clobTokenIdsRaw.isJsonPrimitive && clobTokenIdsRaw.asJsonPrimitive.isString -> {
|
||||
// 尝试解析 JSON 字符串
|
||||
try {
|
||||
val listType = object : TypeToken<List<String>>() {}.type
|
||||
gson.fromJson<List<String>>(clobTokenIdsRaw.asString, listType)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
clobTokenIdsRaw.isJsonArray -> {
|
||||
clobTokenIdsRaw.asJsonArray.mapNotNull { it.asString }
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
// 解析 outcomes(可能是 JSON 字符串或数组)
|
||||
val outcomesRaw = market.get("outcomes")
|
||||
val outcomes = when {
|
||||
outcomesRaw == null || outcomesRaw.isJsonNull -> null
|
||||
outcomesRaw.isJsonPrimitive && outcomesRaw.asJsonPrimitive.isString -> {
|
||||
try {
|
||||
val listType = object : TypeToken<List<String>>() {}.type
|
||||
gson.fromJson<List<String>>(outcomesRaw.asString, listType)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
outcomesRaw.isJsonArray -> {
|
||||
outcomesRaw.asJsonArray.mapNotNull { it.asString }
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
// 查找 tokenId 在 clobTokenIds 中的索引
|
||||
val outcomeIndex = clobTokenIds?.indexOfFirst {
|
||||
it.equals(tokenId, ignoreCase = true)
|
||||
}?.takeIf { it >= 0 }
|
||||
|
||||
// 获取 outcome 名称
|
||||
val outcome = if (outcomeIndex != null && outcomes != null && outcomeIndex < outcomes.size) {
|
||||
outcomes[outcomeIndex]
|
||||
} else {
|
||||
null
|
||||
logger.warn("无法解析交易(返回 null): leaderId=$leaderId, txHash=$txHash, erc20Transfers=${erc20Transfers.size}, erc1155Transfers=${erc1155Transfers.size}")
|
||||
}
|
||||
|
||||
val conditionId = market.get("conditionId")?.asString ?: return null
|
||||
|
||||
MarketInfo(
|
||||
conditionId = conditionId,
|
||||
outcomeIndex = outcomeIndex,
|
||||
outcome = outcome
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("通过 Gamma API 查询市场信息失败: tokenId=$tokenId, ${e.message}")
|
||||
null
|
||||
logger.error("处理 Leader 交易失败: leaderId=$leaderId, txHash=$txHash, ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 市场信息(从 Gamma API 获取)
|
||||
* 移除Leader监听
|
||||
* 取消该 Leader 的订阅
|
||||
*/
|
||||
private data class MarketInfo(
|
||||
val conditionId: String,
|
||||
val outcomeIndex: Int?,
|
||||
val outcome: String?
|
||||
)
|
||||
|
||||
/**
|
||||
* 获取区块时间戳
|
||||
*/
|
||||
private suspend fun getBlockTimestamp(blockNumber: String, rpcApi: EthereumRpcApi): Long? {
|
||||
return try {
|
||||
val blockRequest = JsonRpcRequest(
|
||||
method = "eth_getBlockByNumber",
|
||||
params = listOf(blockNumber, false)
|
||||
)
|
||||
|
||||
val blockResponse = rpcApi.call(blockRequest)
|
||||
if (!blockResponse.isSuccessful || blockResponse.body() == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
val blockRpcResponse = blockResponse.body()!!
|
||||
if (blockRpcResponse.error != null || blockRpcResponse.result == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
// 使用 Gson 解析 block JSON(result 是 JsonElement)
|
||||
val blockJson = blockRpcResponse.result.asJsonObject
|
||||
val timestampHex = blockJson.get("timestamp")?.asString ?: return null
|
||||
hexToBigInt(timestampHex).toLong()
|
||||
} catch (e: Exception) {
|
||||
logger.warn("获取区块时间戳失败: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
// 辅助函数
|
||||
private data class Erc20Transfer(val from: String, val to: String, val value: BigInteger)
|
||||
private data class Erc1155Transfer(val from: String, val to: String, val tokenId: BigInteger, val value: BigInteger)
|
||||
|
||||
private fun topicToAddress(topic: String): String {
|
||||
val t = topic.removePrefix("0x").lowercase()
|
||||
return "0x" + t.takeLast(40)
|
||||
}
|
||||
|
||||
private fun hexToBigInt(hex: String): BigInteger {
|
||||
val h = hex.removePrefix("0x")
|
||||
if (h.isEmpty()) return BigInteger.ZERO
|
||||
return BigInteger(h, 16)
|
||||
}
|
||||
|
||||
private fun bytesFromHex(hex: String): ByteArray {
|
||||
val s = hex.removePrefix("0x")
|
||||
if (s.isEmpty()) return ByteArray(0)
|
||||
val out = ByteArray(s.length / 2)
|
||||
var i = 0
|
||||
while (i < s.length) {
|
||||
out[i / 2] = s.substring(i, i + 2).toInt(16).toByte()
|
||||
i += 2
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun sliceBigInt32(b: ByteArray, offset: Int): BigInteger {
|
||||
val sub = b.copyOfRange(offset, offset + 32)
|
||||
return BigInteger(1, sub)
|
||||
fun removeLeader(leaderId: Long) {
|
||||
monitoredLeaders.remove(leaderId)
|
||||
|
||||
// 通过统一服务取消订阅
|
||||
val subscriptionId = "LEADER_$leaderId"
|
||||
unifiedOnChainWsService.unsubscribe(subscriptionId)
|
||||
|
||||
logger.info("移除 Leader 监听: leaderId=$leaderId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 地址转换为 32 字节 topic(前 24 字节为 0,后 8 字节为地址)
|
||||
* 停止监听
|
||||
*/
|
||||
private fun addressToTopic32(address: String): String {
|
||||
val addr = address.removePrefix("0x").lowercase()
|
||||
return "0x" + "0".repeat(24) + addr
|
||||
fun stop() {
|
||||
// 取消所有 Leader 的订阅
|
||||
val leaderIds = monitoredLeaders.keys.toList()
|
||||
for (leaderId in leaderIds) {
|
||||
removeLeader(leaderId)
|
||||
}
|
||||
monitoredLeaders.clear()
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
stop()
|
||||
scope.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.service.system.RpcNodeService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.math.BigInteger
|
||||
|
||||
/**
|
||||
* 链上 WebSocket 工具类
|
||||
* 提取公共的交易解析、工具函数等逻辑
|
||||
*/
|
||||
object OnChainWsUtils {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(OnChainWsUtils::class.java)
|
||||
|
||||
// 创建 Gson 实例(与 GsonConfig 中的配置一致,使用 lenient 模式)
|
||||
private val gson: Gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
/**
|
||||
* 解析 JSON 字符串数组
|
||||
* @param jsonString JSON 字符串,如 "[\"Yes\", \"No\"]"
|
||||
* @return 字符串列表,如果解析失败返回空列表
|
||||
*/
|
||||
private fun parseStringArray(jsonString: String?): List<String> {
|
||||
if (jsonString.isNullOrBlank()) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
return try {
|
||||
val listType = object : TypeToken<List<String>>() {}.type
|
||||
gson.fromJson<List<String>>(jsonString, listType) ?: emptyList()
|
||||
} catch (e: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
// 合约地址
|
||||
const val USDC_CONTRACT = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"
|
||||
const val ERC1155_CONTRACT = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045"
|
||||
const val ERC20_TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
|
||||
const val ERC1155_TRANSFER_SINGLE_TOPIC = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"
|
||||
const val ERC1155_TRANSFER_BATCH_TOPIC = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb"
|
||||
|
||||
/**
|
||||
* ERC20 Transfer 数据类
|
||||
*/
|
||||
data class Erc20Transfer(
|
||||
val from: String,
|
||||
val to: String,
|
||||
val value: BigInteger
|
||||
)
|
||||
|
||||
/**
|
||||
* ERC1155 Transfer 数据类
|
||||
*/
|
||||
data class Erc1155Transfer(
|
||||
val from: String,
|
||||
val to: String,
|
||||
val tokenId: BigInteger,
|
||||
val value: BigInteger
|
||||
)
|
||||
|
||||
/**
|
||||
* 市场信息数据类
|
||||
*/
|
||||
data class MarketInfo(
|
||||
val conditionId: String,
|
||||
val outcomeIndex: Int?, // 可空,因为可能找不到对应的 tokenId
|
||||
val outcome: String?
|
||||
)
|
||||
|
||||
/**
|
||||
* 解析 receipt 中的 Transfer 日志
|
||||
*/
|
||||
fun parseReceiptTransfers(logs: JsonArray): Pair<List<Erc20Transfer>, List<Erc1155Transfer>> {
|
||||
val erc20 = mutableListOf<Erc20Transfer>()
|
||||
val erc1155 = mutableListOf<Erc1155Transfer>()
|
||||
|
||||
for (logElement in logs) {
|
||||
val log = logElement.asJsonObject
|
||||
val address = log.get("address")?.asString?.lowercase() ?: continue
|
||||
val topicsArray = log.getAsJsonArray("topics") ?: continue
|
||||
val topics = topicsArray.mapNotNull { it.asString }
|
||||
if (topics.isEmpty()) continue
|
||||
|
||||
val t0 = topics[0].lowercase()
|
||||
val data = log.get("data")?.asString ?: "0x"
|
||||
|
||||
// USDC ERC20 Transfer
|
||||
if (address == USDC_CONTRACT.lowercase() && t0 == ERC20_TRANSFER_TOPIC && topics.size >= 3) {
|
||||
val from = topicToAddress(topics[1])
|
||||
val to = topicToAddress(topics[2])
|
||||
val value = hexToBigInt(data)
|
||||
erc20.add(Erc20Transfer(from, to, value))
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferSingle
|
||||
if (t0 == ERC1155_TRANSFER_SINGLE_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size >= 64) {
|
||||
val tokenId = sliceBigInt32(bytes, 0)
|
||||
val value = sliceBigInt32(bytes, 32)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// ERC1155 TransferBatch
|
||||
if (t0 == ERC1155_TRANSFER_BATCH_TOPIC && topics.size >= 4) {
|
||||
val from = topicToAddress(topics[2])
|
||||
val to = topicToAddress(topics[3])
|
||||
val bytes = bytesFromHex(data)
|
||||
if (bytes.size < 64) continue
|
||||
|
||||
val offIds = sliceBigInt32(bytes, 0).toInt()
|
||||
val offVals = sliceBigInt32(bytes, 32).toInt()
|
||||
if (offIds + 32 > bytes.size || offVals + 32 > bytes.size) continue
|
||||
|
||||
val nIds = sliceBigInt32(bytes, offIds).toInt()
|
||||
val nVals = sliceBigInt32(bytes, offVals).toInt()
|
||||
if (nIds != nVals) continue
|
||||
|
||||
val idsStart = offIds + 32
|
||||
val valsStart = offVals + 32
|
||||
for (i in 0 until nIds) {
|
||||
val ib = idsStart + i * 32
|
||||
val vb = valsStart + i * 32
|
||||
if (ib + 32 > bytes.size || vb + 32 > bytes.size) break
|
||||
val tokenId = sliceBigInt32(bytes, ib)
|
||||
val value = sliceBigInt32(bytes, vb)
|
||||
erc1155.add(Erc1155Transfer(from, to, tokenId, value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Pair(erc20, erc1155)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Transfer 日志解析交易信息
|
||||
*/
|
||||
suspend fun parseTradeFromTransfers(
|
||||
txHash: String,
|
||||
timestamp: Long?,
|
||||
walletAddress: String,
|
||||
erc20Transfers: List<Erc20Transfer>,
|
||||
erc1155Transfers: List<Erc1155Transfer>,
|
||||
retrofitFactory: RetrofitFactory
|
||||
): TradeResponse? {
|
||||
val wallet = walletAddress.lowercase()
|
||||
|
||||
// 计算 USDC 流入和流出
|
||||
val usdcOut = erc20Transfers.filter { it.from.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
val usdcIn = erc20Transfers.filter { it.to.lowercase() == wallet }
|
||||
.fold(BigInteger.ZERO) { acc, t -> acc + t.value }
|
||||
|
||||
// 计算 ERC1155 流入和流出(按 tokenId 聚合)
|
||||
val inById = mutableMapOf<BigInteger, BigInteger>()
|
||||
val outById = mutableMapOf<BigInteger, BigInteger>()
|
||||
for (t in erc1155Transfers) {
|
||||
if (t.to.lowercase() == wallet) {
|
||||
inById[t.tokenId] = (inById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
if (t.from.lowercase() == wallet) {
|
||||
outById[t.tokenId] = (outById[t.tokenId] ?: BigInteger.ZERO) + t.value
|
||||
}
|
||||
}
|
||||
|
||||
// 找到最大的流入和流出 tokenId
|
||||
fun best(map: Map<BigInteger, BigInteger>): Pair<BigInteger?, BigInteger> =
|
||||
map.entries.maxByOrNull { it.value }?.let { it.key to it.value } ?: (null to BigInteger.ZERO)
|
||||
|
||||
val (bestInId, bestInVal) = best(inById)
|
||||
val (bestOutId, bestOutVal) = best(outById)
|
||||
|
||||
// 判断交易方向
|
||||
var side: String? = null
|
||||
var asset: BigInteger? = null
|
||||
var sizeRaw = BigInteger.ZERO
|
||||
var usdcRaw = BigInteger.ZERO
|
||||
|
||||
if (bestInId != null && bestInVal > BigInteger.ZERO && usdcOut > BigInteger.ZERO) {
|
||||
// BUY: 收到 token,支付 USDC
|
||||
side = "BUY"
|
||||
asset = bestInId
|
||||
sizeRaw = bestInVal
|
||||
usdcRaw = usdcOut
|
||||
} else if (bestOutId != null && bestOutVal > BigInteger.ZERO && usdcIn > BigInteger.ZERO) {
|
||||
// SELL: 卖出 token,收到 USDC
|
||||
side = "SELL"
|
||||
asset = bestOutId
|
||||
sizeRaw = bestOutVal
|
||||
usdcRaw = usdcIn
|
||||
} else {
|
||||
// 无法判断交易方向
|
||||
logger.debug("无法判断交易方向: txHash=$txHash, bestInId=$bestInId, bestInVal=$bestInVal, bestOutId=$bestOutId, bestOutVal=$bestOutVal, usdcOut=$usdcOut, usdcIn=$usdcIn")
|
||||
return null
|
||||
}
|
||||
|
||||
// 计算价格和数量(USDC 有 6 位小数,shares 也有 6 位小数)
|
||||
val usdcSize = usdcRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val size = sizeRaw.toBigDecimal().divide(BigInteger("1000000").toBigDecimal(), 8, java.math.RoundingMode.DOWN)
|
||||
val price = if (size.signum() > 0) {
|
||||
usdcSize.divide(size, 8, java.math.RoundingMode.DOWN)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
// 尝试通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
val marketInfo = fetchMarketByTokenId(asset.toString(), retrofitFactory)
|
||||
|
||||
// 创建 TradeResponse
|
||||
return TradeResponse(
|
||||
id = txHash,
|
||||
market = marketInfo?.conditionId ?: "",
|
||||
side = side,
|
||||
price = price.toPlainString(),
|
||||
size = size.toPlainString(),
|
||||
timestamp = (timestamp ?: System.currentTimeMillis() / 1000).toString(),
|
||||
user = walletAddress,
|
||||
outcomeIndex = marketInfo?.outcomeIndex,
|
||||
outcome = marketInfo?.outcome
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 Gamma API 查询市场信息(通过 tokenId)
|
||||
* 使用 Retrofit 接口,支持 clob_token_ids 参数
|
||||
*/
|
||||
suspend fun fetchMarketByTokenId(tokenId: String, retrofitFactory: RetrofitFactory): MarketInfo? {
|
||||
return try {
|
||||
val gammaApi = retrofitFactory.createGammaApi()
|
||||
val marketsResponse = gammaApi.listMarkets(
|
||||
conditionIds = null,
|
||||
clobTokenIds = listOf(tokenId),
|
||||
includeTag = null
|
||||
)
|
||||
|
||||
if (!marketsResponse.isSuccessful || marketsResponse.body() == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
val markets = marketsResponse.body()!!
|
||||
val market = markets.firstOrNull()
|
||||
|
||||
if (market == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
// 解析 clobTokenIds(可能是 JSON 字符串或数组)
|
||||
val clobTokenIdsRaw = market.clobTokenIds ?: market.clob_token_ids
|
||||
val clobTokenIds = when {
|
||||
clobTokenIdsRaw == null -> null
|
||||
else -> {
|
||||
// 解析 JSON 字符串
|
||||
parseStringArray(clobTokenIdsRaw)
|
||||
}
|
||||
}
|
||||
|
||||
// 解析 outcomes(可能是 JSON 字符串或数组)
|
||||
val outcomes = parseStringArray(market.outcomes)
|
||||
|
||||
// 查找 tokenId 在 clobTokenIds 中的索引
|
||||
val outcomeIndex = clobTokenIds?.indexOfFirst { token ->
|
||||
token.equals(tokenId, ignoreCase = true)
|
||||
}?.takeIf { it >= 0 }
|
||||
|
||||
// 获取 outcome 名称
|
||||
val outcome = if (outcomeIndex != null && outcomes.isNotEmpty() && outcomeIndex < outcomes.size) {
|
||||
outcomes[outcomeIndex]
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
val conditionId = market.conditionId ?: return null
|
||||
|
||||
MarketInfo(
|
||||
conditionId = conditionId,
|
||||
outcomeIndex = outcomeIndex,
|
||||
outcome = outcome
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("查询市场信息失败: tokenId=$tokenId, error=${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取区块时间戳
|
||||
*/
|
||||
suspend fun getBlockTimestamp(blockNumber: String, rpcApi: EthereumRpcApi): Long? {
|
||||
return try {
|
||||
val blockRequest = JsonRpcRequest(
|
||||
method = "eth_getBlockByNumber",
|
||||
params = listOf(blockNumber, false)
|
||||
)
|
||||
|
||||
val blockResponse = rpcApi.call(blockRequest)
|
||||
if (blockResponse.isSuccessful && blockResponse.body() != null) {
|
||||
val blockRpcResponse = blockResponse.body()!!
|
||||
if (blockRpcResponse.error == null && blockRpcResponse.result != null) {
|
||||
val blockJson = blockRpcResponse.result.asJsonObject
|
||||
val timestampHex = blockJson.get("timestamp")?.asString
|
||||
if (timestampHex != null) {
|
||||
BigInteger(timestampHex.removePrefix("0x"), 16).toLong() * 1000 // 转换为毫秒
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.warn("获取区块时间戳失败: blockNumber=$blockNumber, error=${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:地址转 topic(32字节,左对齐)
|
||||
*/
|
||||
fun addressToTopic32(address: String): String {
|
||||
val clean = address.removePrefix("0x").lowercase()
|
||||
return "0x" + clean.padStart(64, '0')
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:topic 转地址
|
||||
*/
|
||||
fun topicToAddress(topic: String): String {
|
||||
val clean = topic.removePrefix("0x").lowercase()
|
||||
return "0x" + clean.takeLast(40)
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:十六进制转 BigInteger
|
||||
*/
|
||||
fun hexToBigInt(hex: String): BigInteger {
|
||||
val clean = hex.removePrefix("0x")
|
||||
return if (clean.isBlank()) BigInteger.ZERO else BigInteger(clean, 16)
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:十六进制转字节数组
|
||||
*/
|
||||
fun bytesFromHex(hex: String): ByteArray {
|
||||
val clean = hex.removePrefix("0x")
|
||||
return ByteArray(clean.length / 2) { i ->
|
||||
clean.substring(i * 2, i * 2 + 2).toInt(16).toByte()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工具函数:从字节数组切片 BigInteger(32字节)
|
||||
*/
|
||||
fun sliceBigInt32(bytes: ByteArray, offset: Int): BigInteger {
|
||||
if (offset + 32 > bytes.size) return BigInteger.ZERO
|
||||
val slice = bytes.sliceArray(offset until offset + 32)
|
||||
return BigInteger(1, slice)
|
||||
}
|
||||
}
|
||||
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
package com.wrbug.polymarketbot.service.copytrading.monitor
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonArray
|
||||
import com.google.gson.JsonObject
|
||||
import com.wrbug.polymarketbot.api.*
|
||||
import com.wrbug.polymarketbot.service.system.RpcNodeService
|
||||
import com.wrbug.polymarketbot.util.RetrofitFactory
|
||||
import com.wrbug.polymarketbot.util.createClient
|
||||
import com.wrbug.polymarketbot.util.getProxyConfig
|
||||
import jakarta.annotation.PostConstruct
|
||||
import jakarta.annotation.PreDestroy
|
||||
import kotlinx.coroutines.*
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import okio.ByteString
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.stereotype.Service
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* 统一的链上 WebSocket 服务
|
||||
* 管理唯一的 WebSocket 连接,其他服务通过订阅的方式接收链上事件
|
||||
*/
|
||||
@Service
|
||||
class UnifiedOnChainWsService(
|
||||
private val rpcNodeService: RpcNodeService,
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(UnifiedOnChainWsService::class.java)
|
||||
|
||||
@Value("\${copy.trading.onchain.ws.reconnect.delay:3000}")
|
||||
private var reconnectDelay: Long = 3000 // 重连延迟(毫秒),默认3秒
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
||||
|
||||
// 存储所有地址的连接:address -> AddressWsConnection
|
||||
private val addressConnections = ConcurrentHashMap<String, AddressWsConnection>()
|
||||
|
||||
/**
|
||||
* 订阅信息
|
||||
*/
|
||||
data class SubscriptionInfo(
|
||||
val subscriptionId: String, // 订阅的唯一标识
|
||||
val address: String, // 要监听的地址(Leader 地址或账户代理地址)
|
||||
val entityType: String, // 实体类型:LEADER 或 ACCOUNT
|
||||
val entityId: Long, // 实体 ID(Leader ID 或 Account ID)
|
||||
val callback: suspend (String, OkHttpClient, EthereumRpcApi) -> Unit // 回调函数
|
||||
)
|
||||
|
||||
/**
|
||||
* 订阅地址监听
|
||||
* @param subscriptionId 订阅的唯一标识(建议格式:"{entityType}_{entityId}")
|
||||
* @param address 要监听的地址(Leader 地址或账户代理地址)
|
||||
* @param entityType 实体类型:LEADER 或 ACCOUNT
|
||||
* @param entityId 实体 ID(Leader ID 或 Account ID)
|
||||
* @param callback 回调函数,当检测到该地址的交易时调用
|
||||
* @return 是否订阅成功
|
||||
*/
|
||||
fun subscribe(
|
||||
subscriptionId: String,
|
||||
address: String,
|
||||
entityType: String,
|
||||
entityId: Long,
|
||||
callback: suspend (String, OkHttpClient, EthereumRpcApi) -> Unit
|
||||
): Boolean {
|
||||
try {
|
||||
val lowerAddress = address.lowercase()
|
||||
|
||||
// 找到或创建该地址的连接
|
||||
val connection = addressConnections.computeIfAbsent(lowerAddress) {
|
||||
AddressWsConnection(it).apply { start() }
|
||||
}
|
||||
|
||||
// 创建订阅信息
|
||||
val subscription = SubscriptionInfo(
|
||||
subscriptionId = subscriptionId,
|
||||
address = lowerAddress,
|
||||
entityType = entityType,
|
||||
entityId = entityId,
|
||||
callback = callback
|
||||
)
|
||||
|
||||
// 添加订阅
|
||||
connection.addSubscription(subscription)
|
||||
|
||||
logger.info("订阅地址监听: subscriptionId=$subscriptionId, address=$address, entityType=$entityType, entityId=$entityId")
|
||||
return true
|
||||
} catch (e: Exception) {
|
||||
logger.error("订阅地址监听失败: subscriptionId=$subscriptionId, address=$address, error=${e.message}", e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消订阅
|
||||
*/
|
||||
fun unsubscribe(subscriptionId: String) {
|
||||
// 遍历所有连接找到含有该订阅的连接
|
||||
for (connection in addressConnections.values) {
|
||||
if (connection.hasSubscription(subscriptionId)) {
|
||||
connection.removeSubscription(subscriptionId)
|
||||
|
||||
// 如果该连接没有订阅了,停止并移除
|
||||
if (connection.isSubscriptionsEmpty()) {
|
||||
connection.stop()
|
||||
addressConnections.remove(connection.address)
|
||||
logger.info("连接已无订阅,关闭连接: address=${connection.address}")
|
||||
}
|
||||
|
||||
logger.info("取消订阅: subscriptionId=$subscriptionId")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止所有服务
|
||||
*/
|
||||
fun stop() {
|
||||
for (connection in addressConnections.values) {
|
||||
connection.stop()
|
||||
}
|
||||
addressConnections.clear()
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
fun init() {
|
||||
logger.info("统一链上 WebSocket 服务已初始化 (独立连接模式)")
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
stop()
|
||||
scope.cancel()
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个地址的 WebSocket 连接管理
|
||||
*/
|
||||
inner class AddressWsConnection(val address: String) {
|
||||
private var webSocket: WebSocket? = null
|
||||
@Volatile
|
||||
private var isConnected = false
|
||||
|
||||
// 订阅ID计数器(用于请求 ID)
|
||||
private var requestIdCounter = AtomicInteger(0)
|
||||
|
||||
// 连接任务
|
||||
private var connectionJob: Job? = null
|
||||
|
||||
// 该连接下的所有订阅:subscriptionId -> SubscriptionInfo
|
||||
// 理论上一个地址可能被多个业务订阅(如:既是被跟单者又是普通监控),虽然业务上通常只有一个
|
||||
private val subscriptions = ConcurrentHashMap<String, SubscriptionInfo>()
|
||||
|
||||
// 存储请求 ID 到订阅 ID 的映射:requestId -> subscriptionId
|
||||
private val requestIdToSubscriptionId = ConcurrentHashMap<Int, String>()
|
||||
|
||||
// 存储 RPC subscriptionId 到订阅 ID 的映射:rpcSubscriptionId -> subscriptionId
|
||||
private val rpcSubscriptionIdToSubscriptionId = ConcurrentHashMap<String, String>()
|
||||
|
||||
fun start() {
|
||||
if (connectionJob != null && connectionJob!!.isActive) return
|
||||
connectionJob = scope.launch {
|
||||
startConnectionLoop()
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
connectionJob?.cancel()
|
||||
connectionJob = null
|
||||
webSocket?.close(1000, "停止监听")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
subscriptions.clear()
|
||||
requestIdToSubscriptionId.clear()
|
||||
rpcSubscriptionIdToSubscriptionId.clear()
|
||||
}
|
||||
|
||||
fun addSubscription(subscription: SubscriptionInfo) {
|
||||
// 如果已经存在,先移除旧的
|
||||
removeSubscription(subscription.subscriptionId)
|
||||
subscriptions[subscription.subscriptionId] = subscription
|
||||
|
||||
// 如果已经连接,立即发送链上订阅请求
|
||||
if (isConnected) {
|
||||
scope.launch {
|
||||
subscribeAddressOnChain(subscription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun removeSubscription(subscriptionId: String) {
|
||||
subscriptions.remove(subscriptionId)
|
||||
// 不需要显式发送 eth_unsubscribe,因为连接是 per-address 的,
|
||||
// 只要只要连接还在,就保持该地址相关的所有 logs 订阅。
|
||||
// 只有当所有 subscription 都移除了,连接才会关闭。
|
||||
}
|
||||
|
||||
fun hasSubscription(subscriptionId: String): Boolean {
|
||||
return subscriptions.containsKey(subscriptionId)
|
||||
}
|
||||
|
||||
fun isSubscriptionsEmpty(): Boolean {
|
||||
return subscriptions.isEmpty()
|
||||
}
|
||||
|
||||
private suspend fun startConnectionLoop() {
|
||||
while (scope.isActive) {
|
||||
try {
|
||||
if (subscriptions.isEmpty()) {
|
||||
// 如果启动循环时还没订阅(不太可能,通常是先 addSubscription 再 start,或者是 start 后 addSubscription)
|
||||
// 或者订阅被清空了,外部应当掉 stop,但这里作为防守
|
||||
delay(1000)
|
||||
continue
|
||||
}
|
||||
|
||||
if (isConnected && webSocket != null) {
|
||||
waitForDisconnect()
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取可用的 RPC 节点
|
||||
val wsUrl = rpcNodeService.getWsUrl()
|
||||
val httpUrl = rpcNodeService.getHttpUrl()
|
||||
|
||||
logger.info("[$address] 连接链上 WebSocket: $wsUrl")
|
||||
|
||||
val httpClient = createHttpClient()
|
||||
val rpcApi = retrofitFactory.createEthereumRpcApi(httpUrl)
|
||||
|
||||
connectWebSocket(wsUrl, httpClient, rpcApi)
|
||||
waitForConnect()
|
||||
|
||||
if (isConnected) {
|
||||
logger.info("[$address] WebSocket 连接已建立,开始注册订阅")
|
||||
// 重新为所有订阅注册链上监听
|
||||
for (subscription in subscriptions.values) {
|
||||
subscribeAddressOnChain(subscription)
|
||||
}
|
||||
waitForDisconnect()
|
||||
}
|
||||
|
||||
logger.info("[$address] WebSocket 连接断开,等待 ${reconnectDelay}ms 后重连")
|
||||
delay(reconnectDelay)
|
||||
|
||||
} catch (e: Exception) {
|
||||
logger.error("[$address] 连接异常: ${e.message}", e)
|
||||
delay(reconnectDelay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun connectWebSocket(wsUrl: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
webSocket?.close(1000, "重新连接")
|
||||
webSocket = null
|
||||
isConnected = false
|
||||
|
||||
val request = Request.Builder().url(wsUrl).build()
|
||||
|
||||
webSocket = httpClient.newWebSocket(request, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {
|
||||
isConnected = true
|
||||
logger.info("[$address] 链上 WebSocket 连接成功")
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
scope.launch { handleMessage(text, httpClient, rpcApi) }
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
|
||||
scope.launch { handleMessage(bytes.utf8(), httpClient, rpcApi) }
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("[$address] 链上 WebSocket 连接关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
isConnected = false
|
||||
logger.warn("[$address] 链上 WebSocket 连接已关闭: code=$code, reason=$reason")
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {
|
||||
logger.error("[$address] 链上 WebSocket 连接失败: ${t.message}", t)
|
||||
isConnected = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private suspend fun subscribeAddressOnChain(subscription: SubscriptionInfo) {
|
||||
if (webSocket == null || !isConnected) return
|
||||
|
||||
val walletTopic = OnChainWsUtils.addressToTopic32(address)
|
||||
val subId = subscription.subscriptionId
|
||||
|
||||
try {
|
||||
// 订阅该地址相关的所有事件
|
||||
// USDC Transfer (from/to)
|
||||
subscribeLogs(OnChainWsUtils.USDC_CONTRACT, listOf(OnChainWsUtils.ERC20_TRANSFER_TOPIC, walletTopic), subId)
|
||||
subscribeLogs(OnChainWsUtils.USDC_CONTRACT, listOf(OnChainWsUtils.ERC20_TRANSFER_TOPIC, null, walletTopic), subId)
|
||||
|
||||
// ERC1155 TransferSingle (from/to)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_SINGLE_TOPIC, null, walletTopic), subId)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_SINGLE_TOPIC, null, null, walletTopic), subId)
|
||||
|
||||
// ERC1155 TransferBatch (from/to)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_BATCH_TOPIC, null, walletTopic), subId)
|
||||
subscribeLogs(OnChainWsUtils.ERC1155_CONTRACT, listOf(OnChainWsUtils.ERC1155_TRANSFER_BATCH_TOPIC, null, null, walletTopic), subId)
|
||||
|
||||
logger.debug("[$address] 已发送链上订阅请求: subscriptionId=$subId")
|
||||
} catch (e: Exception) {
|
||||
logger.error("[$address] 发送链上订阅请求失败: error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun subscribeLogs(contractAddress: String, topics: List<String?>, subscriptionId: String) {
|
||||
val ws = webSocket ?: return
|
||||
|
||||
val topicsArray = gson.toJsonTree(topics).asJsonArray
|
||||
val logParams = JsonObject()
|
||||
logParams.addProperty("address", contractAddress.lowercase())
|
||||
logParams.add("topics", topicsArray)
|
||||
|
||||
val requestId = requestIdCounter.incrementAndGet()
|
||||
requestIdToSubscriptionId[requestId] = subscriptionId
|
||||
|
||||
val request = JsonObject()
|
||||
request.addProperty("jsonrpc", "2.0")
|
||||
request.addProperty("id", requestId)
|
||||
request.addProperty("method", "eth_subscribe")
|
||||
val paramsArray = JsonArray()
|
||||
paramsArray.add("logs")
|
||||
paramsArray.add(logParams)
|
||||
request.add("params", paramsArray)
|
||||
|
||||
ws.send(gson.toJson(request))
|
||||
}
|
||||
|
||||
private suspend fun handleMessage(text: String, httpClient: OkHttpClient, rpcApi: EthereumRpcApi) {
|
||||
try {
|
||||
val message = gson.fromJson(text, JsonObject::class.java)
|
||||
|
||||
// 1. 处理订阅响应 (eth_subscribe response)
|
||||
if (message.has("result") && message.has("id")) {
|
||||
val requestId = message.get("id")?.asInt
|
||||
val rpcSubscriptionId = message.get("result")?.asString
|
||||
|
||||
if (requestId != null && rpcSubscriptionId != null) {
|
||||
val subId = requestIdToSubscriptionId.remove(requestId)
|
||||
if (subId != null) {
|
||||
rpcSubscriptionIdToSubscriptionId[rpcSubscriptionId] = subId
|
||||
logger.debug("[$address] 链上订阅成功: mapped connection rpcSubId=$rpcSubscriptionId to localSubId=$subId")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 处理日志通知 (eth_subscription)
|
||||
val method = message.get("method")?.asString
|
||||
if (method == "eth_subscription") {
|
||||
val params = message.getAsJsonObject("params") ?: return
|
||||
val rpcSubParam = params.get("subscription")?.asString
|
||||
val result = params.getAsJsonObject("result") ?: return
|
||||
val txHash = result.get("transactionHash")?.asString
|
||||
|
||||
if (txHash != null && rpcSubParam != null) {
|
||||
// 找到触发此通知的本地订阅 ID
|
||||
// 因为我们在这个连接里只订阅了 this.address,所以理论上所有通知都跟这个 address 有关
|
||||
// 但我们需要找到对应的 callback
|
||||
val localSubId = rpcSubscriptionIdToSubscriptionId[rpcSubParam]
|
||||
|
||||
if (localSubId != null) {
|
||||
val subscription = subscriptions[localSubId]
|
||||
if (subscription != null) {
|
||||
logger.info("[$address] 收到交易通知: txHash=$txHash, subId=$localSubId")
|
||||
runCatching {
|
||||
subscription.callback(txHash, httpClient, rpcApi)
|
||||
}.onFailure { e ->
|
||||
logger.error("[$address] 回调执行失败: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 找不到具体是哪个订阅请求触发的(可能是重启后之前的订阅残留?或者映射丢失?)
|
||||
// 在单地址单连接模式下,只要是这个 connection 收到的,肯定是关于这个 address 的
|
||||
// 我们可以尝试通知所有订阅者(通常一个地址只有一个订阅者,除非此地址既是Leader又是User)
|
||||
logger.warn("[$address] 未找到映射的订阅ID: rpcSubId=$rpcSubParam. 广播给所有订阅者.")
|
||||
subscriptions.values.forEach { sub ->
|
||||
runCatching {
|
||||
sub.callback(txHash, httpClient, rpcApi)
|
||||
}.onFailure { e ->
|
||||
logger.error("[$address] 广播回调执行失败: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("[$address] 处理消息失败: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun waitForConnect() {
|
||||
var waited = 0L
|
||||
val timeout = 15000L
|
||||
while (!isConnected && waited < timeout) {
|
||||
delay(100)
|
||||
waited += 100
|
||||
}
|
||||
if (!isConnected) logger.warn("[$address] WebSocket 连接超时")
|
||||
}
|
||||
|
||||
private suspend fun waitForDisconnect() {
|
||||
while (isConnected && scope.isActive) {
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
|
||||
private fun createHttpClient(): OkHttpClient {
|
||||
val proxy = getProxyConfig()
|
||||
val builder = createClient()
|
||||
if (proxy != null) builder.proxy(proxy)
|
||||
return builder.build()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-19
@@ -172,25 +172,15 @@ class OrderSigningService {
|
||||
// 5. 确保 maker 地址也是小写格式
|
||||
val makerAddressLower = makerAddress.lowercase()
|
||||
|
||||
// 打印签名前的订单参数
|
||||
logger.info("========== 订单签名前参数 ==========")
|
||||
logger.info("订单方向: $side")
|
||||
logger.info("价格: $price")
|
||||
logger.info("数量: $size")
|
||||
logger.info("Token ID: $tokenId")
|
||||
logger.info("Maker 地址: $makerAddressLower")
|
||||
logger.info("Signer 地址: $signerAddress")
|
||||
logger.info("Taker 地址: $taker")
|
||||
logger.info("Maker Amount (wei): ${amounts.makerAmount}")
|
||||
logger.info("Taker Amount (wei): ${amounts.takerAmount}")
|
||||
logger.info("Salt: $salt")
|
||||
logger.info("Expiration: $expiration")
|
||||
logger.info("Nonce: $nonce")
|
||||
logger.info("Fee Rate BPS: $feeRateBps")
|
||||
logger.info("Signature Type: $signatureType")
|
||||
logger.info("Exchange Contract: $EXCHANGE_CONTRACT")
|
||||
logger.info("Chain ID: $CHAIN_ID")
|
||||
logger.info("====================================")
|
||||
// 打印签名前的订单参数(DEBUG 级别,避免敏感信息泄露)
|
||||
logger.debug("========== 订单签名前参数 ==========")
|
||||
logger.debug("订单方向: $side, 价格: $price, 数量: $size")
|
||||
logger.debug("Token ID: $tokenId")
|
||||
logger.debug("Maker: ${makerAddressLower.take(10)}...${makerAddressLower.takeLast(6)}")
|
||||
logger.debug("Signer: ${signerAddress.take(10)}...${signerAddress.takeLast(6)}")
|
||||
logger.debug("Amounts - Maker: ${amounts.makerAmount}, Taker: ${amounts.takerAmount}")
|
||||
logger.debug("Salt: $salt, Expiration: $expiration, Nonce: $nonce, FeeRateBPS: $feeRateBps")
|
||||
logger.debug("Signature Type: $signatureType, Chain ID: $CHAIN_ID")
|
||||
|
||||
// 6. 构建订单数据并签名
|
||||
val signature = signOrder(
|
||||
|
||||
+145
-201
@@ -25,6 +25,7 @@ import com.wrbug.polymarketbot.util.CryptoUtils
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
import java.math.BigDecimal
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* 订单跟踪服务
|
||||
@@ -37,7 +38,6 @@ open class CopyOrderTrackingService(
|
||||
private val sellMatchRecordRepository: SellMatchRecordRepository,
|
||||
private val sellMatchDetailRepository: SellMatchDetailRepository,
|
||||
private val processedTradeRepository: ProcessedTradeRepository,
|
||||
private val failedTradeRepository: FailedTradeRepository,
|
||||
private val filteredOrderRepository: FilteredOrderRepository,
|
||||
private val copyTradingRepository: CopyTradingRepository,
|
||||
private val accountRepository: AccountRepository,
|
||||
@@ -55,16 +55,16 @@ open class CopyOrderTrackingService(
|
||||
|
||||
// 协程作用域(用于异步发送通知)
|
||||
private val notificationScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
|
||||
// 使用 Mutex 保证线程安全(按交易ID锁定)
|
||||
private val tradeMutexMap = ConcurrentHashMap<String, Mutex>()
|
||||
|
||||
|
||||
// 订单创建重试配置
|
||||
companion object {
|
||||
private const val MAX_RETRY_ATTEMPTS = 2 // 最多重试次数(首次 + 1次重试)
|
||||
private const val RETRY_DELAY_MS = 3000L // 重试前等待时间(毫秒,3秒)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取或创建 Mutex(按交易ID)
|
||||
*/
|
||||
@@ -122,7 +122,7 @@ open class CopyOrderTrackingService(
|
||||
suspend fun processTrade(leaderId: Long, trade: TradeResponse, source: String): Result<Unit> {
|
||||
// 获取该交易的 Mutex(按交易ID锁定,不同交易可以并行处理)
|
||||
val mutex = getMutex(leaderId, trade.id)
|
||||
|
||||
|
||||
return mutex.withLock {
|
||||
try {
|
||||
// 1. 检查是否已处理(去重,包括失败状态)
|
||||
@@ -135,12 +135,6 @@ open class CopyOrderTrackingService(
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
|
||||
// 检查是否已记录为失败交易
|
||||
val failedTrade = failedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (failedTrade != null) {
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
|
||||
// 2. 处理交易逻辑
|
||||
val result = when (trade.side.uppercase()) {
|
||||
"BUY" -> processBuyTrade(leaderId, trade)
|
||||
@@ -260,13 +254,13 @@ open class CopyOrderTrackingService(
|
||||
// 先计算跟单金额(用于仓位检查)
|
||||
// 注意:这里先计算金额,即使后续被过滤也会记录
|
||||
val tradePrice = trade.price.toSafeBigDecimal()
|
||||
val buyQuantity = try {
|
||||
var buyQuantity = try {
|
||||
calculateBuyQuantity(trade, copyTrading)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("计算买入数量失败: ${e.message}", e)
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
// 计算跟单金额(USDC)= 买入数量 × 价格
|
||||
val copyOrderAmount = buyQuantity.multi(tradePrice)
|
||||
|
||||
@@ -275,8 +269,8 @@ open class CopyOrderTrackingService(
|
||||
// 传入跟单金额和市场ID,用于仓位检查(按市场检查仓位)
|
||||
// 订单簿只请求一次,返回给后续逻辑使用
|
||||
val filterResult = filterService.checkFilters(
|
||||
copyTrading,
|
||||
tokenId,
|
||||
copyTrading,
|
||||
tokenId,
|
||||
tradePrice = tradePrice,
|
||||
copyOrderAmount = copyOrderAmount,
|
||||
marketId = trade.market
|
||||
@@ -376,22 +370,72 @@ open class CopyOrderTrackingService(
|
||||
// 买入数量已在过滤检查前计算,这里直接使用
|
||||
// 如果数量为0或负数,跳过
|
||||
if (buyQuantity.lte(BigDecimal.ZERO)) {
|
||||
logger.warn("计算出的买入数量为0或负数,跳过: copyTradingId=${copyTrading.id}, tradeId=${trade.id}")
|
||||
logger.warn("计算得到的买入数量为0,跳过跟单: copyTradingId=${copyTrading.id}, tradeId=${trade.id}")
|
||||
continue
|
||||
}
|
||||
|
||||
if (buyQuantity.lt(BigDecimal.ONE)) {
|
||||
logger.warn("计算得到的买入数量小于1,自动调整为1 (Polymarket 最小下单数量): copyTradingId=${copyTrading.id}, tradeId=${trade.id}, originalQuantity=$buyQuantity")
|
||||
buyQuantity = BigDecimal.ONE
|
||||
}
|
||||
// 验证订单数量限制(仅比例模式)
|
||||
var finalBuyQuantity = buyQuantity
|
||||
if (copyTrading.copyMode == "RATIO") {
|
||||
val orderAmount = buyQuantity.multi(trade.price.toSafeBigDecimal())
|
||||
if (orderAmount.lt(copyTrading.minOrderSize)) {
|
||||
logger.warn("订单金额低于最小限制,跳过: copyTradingId=${copyTrading.id}, amount=$orderAmount, min=${copyTrading.minOrderSize}")
|
||||
continue
|
||||
val tradePrice = trade.price.toSafeBigDecimal()
|
||||
val rawOrderAmount = buyQuantity.multi(tradePrice)
|
||||
|
||||
// 对按比例计算的金额进行向上取整处理(确保满足最小限制)
|
||||
// 向上取整到 2 位小数(USDC 精度)
|
||||
val roundedOrderAmount = rawOrderAmount.setScale(2, java.math.RoundingMode.CEILING)
|
||||
|
||||
// 如果原始金额或向上取整后的金额小于最小限制,调整 buyQuantity 以满足最小限制
|
||||
// 这样可以避免精度问题导致订单被错误地跳过
|
||||
if (roundedOrderAmount.lt(copyTrading.minOrderSize)) {
|
||||
logger.debug("订单金额(向上取整后)低于最小限制,调整数量以满足最小限制: copyTradingId=${copyTrading.id}, rawAmount=$rawOrderAmount, roundedAmount=$roundedOrderAmount, min=${copyTrading.minOrderSize}")
|
||||
// 计算满足最小限制所需的数量(向上取整)
|
||||
val minQuantity =
|
||||
copyTrading.minOrderSize.div(tradePrice, 8, java.math.RoundingMode.CEILING)
|
||||
if (minQuantity.lte(BigDecimal.ZERO)) {
|
||||
logger.warn("计算出的最小数量为0或负数,跳过: copyTradingId=${copyTrading.id}")
|
||||
continue
|
||||
}
|
||||
// 使用调整后的数量
|
||||
finalBuyQuantity = minQuantity
|
||||
logger.debug(
|
||||
"已调整数量以满足最小限制: copyTradingId=${copyTrading.id}, originalQuantity=$buyQuantity, adjustedQuantity=$finalBuyQuantity, adjustedAmount=${
|
||||
finalBuyQuantity.multi(
|
||||
tradePrice
|
||||
)
|
||||
}"
|
||||
)
|
||||
} else if (rawOrderAmount.lt(copyTrading.minOrderSize)) {
|
||||
// 原始金额小于最小限制,但向上取整后满足,调整数量以满足最小限制
|
||||
logger.debug("订单金额(精度处理后)低于最小限制,调整数量以满足最小限制: copyTradingId=${copyTrading.id}, rawAmount=$rawOrderAmount, min=${copyTrading.minOrderSize}")
|
||||
// 计算满足最小限制所需的数量(向上取整)
|
||||
val minQuantity =
|
||||
copyTrading.minOrderSize.div(tradePrice, 8, java.math.RoundingMode.CEILING)
|
||||
if (minQuantity.lte(BigDecimal.ZERO)) {
|
||||
logger.warn("计算出的最小数量为0或负数,跳过: copyTradingId=${copyTrading.id}")
|
||||
continue
|
||||
}
|
||||
// 使用调整后的数量
|
||||
finalBuyQuantity = minQuantity
|
||||
logger.debug(
|
||||
"已调整数量以满足最小限制: copyTradingId=${copyTrading.id}, originalQuantity=$buyQuantity, adjustedQuantity=$finalBuyQuantity, adjustedAmount=${
|
||||
finalBuyQuantity.multi(
|
||||
tradePrice
|
||||
)
|
||||
}"
|
||||
)
|
||||
}
|
||||
if (orderAmount.gt(copyTrading.maxOrderSize)) {
|
||||
logger.warn("订单金额超过最大限制,调整数量: copyTradingId=${copyTrading.id}, amount=$orderAmount, max=${copyTrading.maxOrderSize}")
|
||||
|
||||
// 检查最大限制(使用调整后的数量)
|
||||
val finalOrderAmount = finalBuyQuantity.multi(tradePrice)
|
||||
if (finalOrderAmount.gt(copyTrading.maxOrderSize)) {
|
||||
logger.warn("订单金额超过最大限制,调整数量: copyTradingId=${copyTrading.id}, amount=$finalOrderAmount, max=${copyTrading.maxOrderSize}")
|
||||
// 调整数量到最大值
|
||||
val adjustedQuantity = copyTrading.maxOrderSize.div(trade.price.toSafeBigDecimal())
|
||||
val adjustedQuantity =
|
||||
copyTrading.maxOrderSize.div(tradePrice, 8, java.math.RoundingMode.DOWN)
|
||||
if (adjustedQuantity.lte(BigDecimal.ZERO)) {
|
||||
logger.warn("调整后的数量为0或负数,跳过: copyTradingId=${copyTrading.id}")
|
||||
continue
|
||||
@@ -416,7 +460,7 @@ open class CopyOrderTrackingService(
|
||||
|
||||
// 计算价格(应用价格容忍度)
|
||||
val buyPrice = calculateAdjustedPrice(trade.price.toSafeBigDecimal(), copyTrading, isBuy = true)
|
||||
|
||||
logger.debug("计算价格结果:$buyPrice")
|
||||
// 在创建订单前,检查订单簿中是否有可匹配的订单(避免 FAK 订单失败)
|
||||
// 如果过滤检查时已经获取了订单簿,直接使用;否则重新获取
|
||||
val orderbookForCheck = orderbook ?: run {
|
||||
@@ -427,21 +471,21 @@ open class CopyOrderTrackingService(
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 检查是否有可匹配的卖单(asks)
|
||||
if (orderbookForCheck != null) {
|
||||
val bestAsk = orderbookForCheck.asks
|
||||
.mapNotNull { it.price.toSafeBigDecimal() }
|
||||
.minOrNull()
|
||||
|
||||
|
||||
if (bestAsk == null) {
|
||||
logger.warn("订单簿中没有卖单,跳过创建订单: copyTradingId=${copyTrading.id}, tradeId=${trade.id}")
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
// 如果调整后的买入价格低于最佳卖单价格,无法匹配
|
||||
if (buyPrice.lt(bestAsk)) {
|
||||
logger.warn("调整后的买入价格 ($buyPrice) 低于最佳卖单价格 ($bestAsk),无法匹配,跳过创建订单: copyTradingId=${copyTrading.id}, tradeId=${trade.id}, leaderPrice=${trade.price}, tolerance=${copyTrading.priceTolerance}")
|
||||
logger.info("调整后的买入价格 ($buyPrice) 低于最佳卖单价格 ($bestAsk),无法匹配,跳过创建订单: copyTradingId=${copyTrading.id}, tradeId=${trade.id}, leaderPrice=${trade.price}, tolerance=${copyTrading.priceTolerance}")
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -471,6 +515,8 @@ open class CopyOrderTrackingService(
|
||||
// 解密私钥
|
||||
val decryptedPrivateKey = decryptPrivateKey(account)
|
||||
|
||||
logger.info("准备创建买入订单: copyTradingId=${copyTrading.id}, tradeId=${trade.id}, leaderPrice=${trade.price}, tolerance=${copyTrading.priceTolerance}, calculatedPrice=$buyPrice, quantity=$finalBuyQuantity")
|
||||
|
||||
// 调用API创建订单(带重试机制)
|
||||
// 重试策略:最多重试 MAX_RETRY_ATTEMPTS 次,每次重试前等待 RETRY_DELAY_MS 毫秒
|
||||
// 每次重试都会重新生成salt并重新签名,确保签名唯一性
|
||||
@@ -491,27 +537,7 @@ open class CopyOrderTrackingService(
|
||||
if (createOrderResult.isFailure) {
|
||||
// 提取错误信息(只保留 code 和 errorBody)
|
||||
val exception = createOrderResult.exceptionOrNull()
|
||||
val errorMsg = buildFullErrorMessage(
|
||||
exception,
|
||||
"BUY",
|
||||
buyPrice.toString(),
|
||||
finalBuyQuantity.toString(),
|
||||
trade.id
|
||||
)
|
||||
|
||||
// 记录失败交易到数据库
|
||||
// retryCount = MAX_RETRY_ATTEMPTS - 1,表示已重试的次数
|
||||
recordFailedTrade(
|
||||
leaderId = leaderId,
|
||||
trade = trade,
|
||||
copyTradingId = copyTrading.id!!,
|
||||
accountId = copyTrading.accountId,
|
||||
side = "BUY",
|
||||
price = buyPrice.toString(),
|
||||
size = finalBuyQuantity.toString(),
|
||||
errorMessage = errorMsg,
|
||||
retryCount = MAX_RETRY_ATTEMPTS - 1 // 已重试次数
|
||||
)
|
||||
logger.error("创建买入订单失败: copyTradingId=${copyTrading.id}, tradeId=${trade.id}, leaderPrice=${trade.price}, myPrice=$buyPrice, error=${exception?.message}")
|
||||
|
||||
// 发送订单失败通知(异步,不阻塞,仅在 pushFailedOrders 为 true 时发送)
|
||||
if (copyTrading.pushFailedOrders) {
|
||||
@@ -567,7 +593,7 @@ open class CopyOrderTrackingService(
|
||||
}
|
||||
|
||||
val realOrderId = createOrderResult.getOrNull() ?: continue
|
||||
|
||||
|
||||
// 验证 orderId 格式(必须以 0x 开头的 16 进制)
|
||||
if (!isValidOrderId(realOrderId)) {
|
||||
logger.warn("买入订单ID格式无效,跳过保存: orderId=$realOrderId")
|
||||
@@ -594,7 +620,7 @@ open class CopyOrderTrackingService(
|
||||
)
|
||||
|
||||
copyOrderTrackingRepository.save(tracking)
|
||||
|
||||
|
||||
logger.info("买入订单已保存,等待轮询任务获取实际数据后发送通知: orderId=$realOrderId, copyTradingId=${copyTrading.id}")
|
||||
} catch (e: Exception) {
|
||||
logger.error("处理买入交易失败: copyTradingId=${copyTrading.id}, tradeId=${trade.id}", e)
|
||||
@@ -653,8 +679,8 @@ open class CopyOrderTrackingService(
|
||||
private fun calculateBuyQuantity(trade: TradeResponse, copyTrading: CopyTrading): BigDecimal {
|
||||
return when (copyTrading.copyMode) {
|
||||
"RATIO" -> {
|
||||
// 比例模式:Leader 数量 × 比例
|
||||
trade.size.toSafeBigDecimal().multi(copyTrading.copyRatio)
|
||||
// 比例模式:Leader 数量 × (比例 / 100)
|
||||
trade.size.toSafeBigDecimal().multi(copyTrading.copyRatio.div(100))
|
||||
}
|
||||
|
||||
"FIXED" -> {
|
||||
@@ -686,7 +712,7 @@ open class CopyOrderTrackingService(
|
||||
val leader = leaderRepository.findById(copyTrading.leaderId).orElse(null)
|
||||
?: run {
|
||||
logger.warn("Leader 不存在,使用默认比例: leaderId=${copyTrading.leaderId}")
|
||||
return leaderSellQuantity.multi(copyTrading.copyRatio)
|
||||
return leaderSellQuantity.multi(copyTrading.copyRatio.div(100))
|
||||
}
|
||||
|
||||
// 创建不需要认证的 CLOB API 客户端(用于查询公开的交易数据)
|
||||
@@ -705,7 +731,7 @@ open class CopyOrderTrackingService(
|
||||
for (order in unmatchedOrders) {
|
||||
val copyQty = order.quantity.toSafeBigDecimal()
|
||||
var leaderQty: BigDecimal? = null
|
||||
|
||||
|
||||
// 优先使用存储的 leaderBuyQuantity
|
||||
if (order.leaderBuyQuantity != null) {
|
||||
leaderQty = order.leaderBuyQuantity.toSafeBigDecimal()
|
||||
@@ -716,7 +742,7 @@ open class CopyOrderTrackingService(
|
||||
logger.debug("Leader 买入数量未存储,尝试查询 API: leaderBuyTradeId=${order.leaderBuyTradeId}, copyOrderId=${order.buyOrderId}")
|
||||
try {
|
||||
val tradesResponse = clobApi.getTrades(id = order.leaderBuyTradeId)
|
||||
|
||||
|
||||
if (tradesResponse.isSuccessful && tradesResponse.body() != null) {
|
||||
val tradesData = tradesResponse.body()!!.data
|
||||
if (tradesData.isNotEmpty()) {
|
||||
@@ -742,7 +768,7 @@ open class CopyOrderTrackingService(
|
||||
failCount++
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 如果成功获取到 Leader 买入数量,累加
|
||||
if (leaderQty != null && leaderQty.gt(BigDecimal.ZERO)) {
|
||||
totalCopyQuantity = totalCopyQuantity.add(copyQty)
|
||||
@@ -751,23 +777,23 @@ open class CopyOrderTrackingService(
|
||||
logger.warn("无法获取 Leader 买入数量,跳过该订单: copyOrderId=${order.buyOrderId}, leaderBuyTradeId=${order.leaderBuyTradeId}")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
logger.info("固定金额模式计算结果汇总: copyTradingId=${copyTrading.id}, successCount=$successCount, failCount=$failCount, totalCopyQuantity=$totalCopyQuantity, totalLeaderQuantity=$totalLeaderQuantity")
|
||||
|
||||
// 如果无法计算总比例(查询失败),使用默认比例
|
||||
if (totalLeaderQuantity.lte(BigDecimal.ZERO)) {
|
||||
logger.warn("无法计算总比例(Leader 买入数量为 0),使用默认比例: copyTradingId=${copyTrading.id}")
|
||||
return leaderSellQuantity.multi(copyTrading.copyRatio)
|
||||
return leaderSellQuantity.multi(copyTrading.copyRatio.div(100))
|
||||
}
|
||||
|
||||
// 计算实际比例:跟单买入数量 / Leader 买入数量
|
||||
val actualRatio = totalCopyQuantity.div(totalLeaderQuantity)
|
||||
|
||||
|
||||
// 计算需要卖出的数量:Leader 卖出数量 × 实际比例
|
||||
val needMatch = leaderSellQuantity.multi(actualRatio)
|
||||
|
||||
|
||||
logger.debug("固定金额模式卖出数量计算: copyTradingId=${copyTrading.id}, leaderSellQuantity=$leaderSellQuantity, totalCopyQuantity=$totalCopyQuantity, totalLeaderQuantity=$totalLeaderQuantity, actualRatio=$actualRatio, needMatch=$needMatch")
|
||||
|
||||
|
||||
return needMatch
|
||||
}
|
||||
|
||||
@@ -831,16 +857,26 @@ open class CopyOrderTrackingService(
|
||||
copyTrading = copyTrading
|
||||
)
|
||||
}
|
||||
|
||||
"RATIO" -> {
|
||||
// 比例模式:直接使用配置的 copyRatio
|
||||
leaderSellTrade.size.toSafeBigDecimal().multi(copyTrading.copyRatio)
|
||||
// 比例模式:直接使用配置的 copyRatio (需要除以100)
|
||||
leaderSellTrade.size.toSafeBigDecimal().multi(copyTrading.copyRatio.div(100))
|
||||
}
|
||||
|
||||
else -> {
|
||||
logger.warn("不支持的 copyMode: ${copyTrading.copyMode},使用默认比例模式")
|
||||
leaderSellTrade.size.toSafeBigDecimal().multi(copyTrading.copyRatio)
|
||||
leaderSellTrade.size.toSafeBigDecimal().multi(copyTrading.copyRatio.div(100))
|
||||
}
|
||||
}
|
||||
|
||||
// 如果需要卖出的数量小于1(但大于0),自动调整为1(Polymarket 最小下单数量)
|
||||
// 注意:如果实际持有数量不足1,后续的 totalMatched 检查会拦截
|
||||
var finalNeedMatch = needMatch
|
||||
if (finalNeedMatch.gt(BigDecimal.ZERO) && finalNeedMatch.lt(BigDecimal.ONE)) {
|
||||
logger.warn("计算得到的卖出数量小于1,自动调整为1: copyTradingId=${copyTrading.id}, original=$needMatch")
|
||||
finalNeedMatch = BigDecimal.ONE
|
||||
}
|
||||
|
||||
// 4. 获取tokenId(直接使用outcomeIndex,支持多元市场)
|
||||
val tokenIdResult = blockchainService.getTokenId(leaderSellTrade.market, leaderSellTrade.outcomeIndex)
|
||||
if (tokenIdResult.isFailure) {
|
||||
@@ -864,7 +900,7 @@ open class CopyOrderTrackingService(
|
||||
// 6. 按FIFO顺序匹配,计算实际可以卖出的数量
|
||||
// 使用计算出的实际卖出价格(而不是 Leader 价格)来创建匹配明细
|
||||
var totalMatched = BigDecimal.ZERO
|
||||
var remaining = needMatch
|
||||
var remaining = finalNeedMatch
|
||||
val matchDetails = mutableListOf<SellMatchDetail>()
|
||||
|
||||
for (order in unmatchedOrders) {
|
||||
@@ -901,6 +937,11 @@ open class CopyOrderTrackingService(
|
||||
return
|
||||
}
|
||||
|
||||
if (totalMatched.lt(BigDecimal.ONE)) {
|
||||
logger.warn("卖出数量小于1,跳过卖出 (Polymarket 最小下单数量为 1): copyTradingId=${copyTrading.id}, tradeId=${leaderSellTrade.id}, quantity=$totalMatched")
|
||||
return
|
||||
}
|
||||
|
||||
// 7. 解密 API 凭证
|
||||
val apiSecret = try {
|
||||
decryptApiSecret(account)
|
||||
@@ -917,7 +958,7 @@ open class CopyOrderTrackingService(
|
||||
|
||||
// 8. 解密私钥(在方法开始时解密一次,后续复用)
|
||||
val decryptedPrivateKey = decryptPrivateKey(account)
|
||||
|
||||
|
||||
// 9. 创建并签名卖出订单
|
||||
val signedOrder = try {
|
||||
orderSigningService.createAndSignOrder(
|
||||
@@ -971,31 +1012,14 @@ open class CopyOrderTrackingService(
|
||||
)
|
||||
|
||||
if (createOrderResult.isFailure) {
|
||||
// 创建订单失败,记录到失败表
|
||||
// 创建订单失败,记录错误日志
|
||||
val exception = createOrderResult.exceptionOrNull()
|
||||
val errorMsg = buildFullErrorMessage(
|
||||
exception,
|
||||
"SELL",
|
||||
sellPrice.toString(),
|
||||
totalMatched.toString(),
|
||||
leaderSellTrade.id
|
||||
)
|
||||
recordFailedTrade(
|
||||
leaderId = copyTrading.leaderId,
|
||||
trade = leaderSellTrade,
|
||||
copyTradingId = copyTrading.id!!,
|
||||
accountId = copyTrading.accountId,
|
||||
side = "SELL", // 订单方向是SELL
|
||||
price = sellPrice.toString(),
|
||||
size = totalMatched.toString(),
|
||||
errorMessage = errorMsg,
|
||||
retryCount = 1 // 已重试一次
|
||||
)
|
||||
logger.error("创建卖出订单失败: copyTradingId=${copyTrading.id}, tradeId=${leaderSellTrade.id}, error=${exception?.message}")
|
||||
return
|
||||
}
|
||||
|
||||
val realSellOrderId = createOrderResult.getOrNull() ?: return
|
||||
|
||||
|
||||
// 12. 下单时直接使用下单价格保存,等待定时任务更新实际成交价
|
||||
// priceUpdated 统一由定时任务更新,下单时统一设置为 false(非0x开头的除外)
|
||||
val priceUpdated = !realSellOrderId.startsWith("0x", ignoreCase = true)
|
||||
@@ -1004,7 +1028,7 @@ open class CopyOrderTrackingService(
|
||||
} else {
|
||||
logger.debug("卖出订单ID为0x开头,等待定时任务更新价格: orderId=$realSellOrderId")
|
||||
}
|
||||
|
||||
|
||||
// 使用下单价格,等待定时任务更新实际成交价
|
||||
val actualSellPrice = sellPrice
|
||||
|
||||
@@ -1053,19 +1077,19 @@ open class CopyOrderTrackingService(
|
||||
val savedDetail = detail.copy(matchRecordId = savedRecord.id!!)
|
||||
sellMatchDetailRepository.save(savedDetail)
|
||||
}
|
||||
|
||||
|
||||
logger.info("卖出订单已保存,等待轮询任务获取实际数据后发送通知: orderId=$realSellOrderId, copyTradingId=${copyTrading.id}")
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建订单(带重试机制)
|
||||
*
|
||||
*
|
||||
* 重试策略:
|
||||
* - 最多重试 MAX_RETRY_ATTEMPTS 次(首次尝试 + 重试)
|
||||
* - 每次重试前等待 RETRY_DELAY_MS 毫秒
|
||||
* - 每次重试都重新生成salt并重新签名,确保签名唯一性
|
||||
*
|
||||
*
|
||||
* @param clobApi CLOB API 客户端
|
||||
* @param privateKey 私钥(用于签名)
|
||||
* @param makerAddress 代理钱包地址
|
||||
@@ -1131,10 +1155,10 @@ open class CopyOrderTrackingService(
|
||||
}
|
||||
val errorMsg = "code=${orderResponse.code()}, errorBody=${errorBody ?: "null"}"
|
||||
lastError = Exception(errorMsg)
|
||||
|
||||
|
||||
// 记录错误日志
|
||||
logger.error("创建订单失败 (尝试 $attempt/$MAX_RETRY_ATTEMPTS): copyTradingId=$copyTradingId, tradeId=$tradeId, $errorMsg")
|
||||
|
||||
|
||||
// 如果不是最后一次尝试,等待后重试
|
||||
if (attempt < MAX_RETRY_ATTEMPTS) {
|
||||
delay(RETRY_DELAY_MS)
|
||||
@@ -1148,10 +1172,10 @@ open class CopyOrderTrackingService(
|
||||
if (!response.success || response.orderId == null) {
|
||||
val errorMsg = "errorMsg=${response.errorMsg}"
|
||||
lastError = Exception(errorMsg)
|
||||
|
||||
|
||||
// 记录错误日志
|
||||
logger.error("创建订单失败 (尝试 $attempt/$MAX_RETRY_ATTEMPTS): copyTradingId=$copyTradingId, tradeId=$tradeId, $errorMsg")
|
||||
|
||||
|
||||
// 如果不是最后一次尝试,等待后重试
|
||||
if (attempt < MAX_RETRY_ATTEMPTS) {
|
||||
delay(RETRY_DELAY_MS)
|
||||
@@ -1163,14 +1187,17 @@ open class CopyOrderTrackingService(
|
||||
// 创建订单成功
|
||||
logger.info("创建订单成功: copyTradingId=$copyTradingId, tradeId=$tradeId, orderId=${response.orderId}, attempt=$attempt")
|
||||
return Result.success(response.orderId)
|
||||
|
||||
|
||||
} catch (e: Exception) {
|
||||
val errorMsg = "error=${e.message}"
|
||||
lastError = Exception(errorMsg, e)
|
||||
|
||||
|
||||
// 记录错误日志(包含堆栈)
|
||||
logger.error("创建订单异常 (尝试 $attempt/$MAX_RETRY_ATTEMPTS): copyTradingId=$copyTradingId, tradeId=$tradeId, $errorMsg", e)
|
||||
|
||||
logger.error(
|
||||
"创建订单异常 (尝试 $attempt/$MAX_RETRY_ATTEMPTS): copyTradingId=$copyTradingId, tradeId=$tradeId, $errorMsg",
|
||||
e
|
||||
)
|
||||
|
||||
// 如果不是最后一次尝试,等待后重试
|
||||
if (attempt < MAX_RETRY_ATTEMPTS) {
|
||||
delay(RETRY_DELAY_MS)
|
||||
@@ -1182,7 +1209,10 @@ open class CopyOrderTrackingService(
|
||||
|
||||
// 所有重试都失败
|
||||
val finalError = lastError ?: Exception("error=未知错误")
|
||||
logger.error("创建订单失败(所有重试都失败): copyTradingId=$copyTradingId, tradeId=$tradeId, side=$side, price=$price, size=$size", finalError)
|
||||
logger.error(
|
||||
"创建订单失败(所有重试都失败): copyTradingId=$copyTradingId, tradeId=$tradeId, side=$side, price=$price, size=$size",
|
||||
finalError
|
||||
)
|
||||
return Result.failure(finalError)
|
||||
}
|
||||
|
||||
@@ -1248,98 +1278,6 @@ open class CopyOrderTrackingService(
|
||||
return "code=$code, errorBody=$errorBody"
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录失败交易到数据库
|
||||
* 注意:此方法在 @Transactional 方法中被调用,会自动继承事务
|
||||
*/
|
||||
private suspend fun recordFailedTrade(
|
||||
leaderId: Long,
|
||||
trade: TradeResponse,
|
||||
copyTradingId: Long,
|
||||
accountId: Long,
|
||||
side: String,
|
||||
price: String,
|
||||
size: String,
|
||||
errorMessage: String,
|
||||
retryCount: Int
|
||||
) {
|
||||
try {
|
||||
// 确保错误信息不超过数据库字段限制(TEXT类型通常支持65535字符)
|
||||
val maxErrorMessageLength = 50000 // 保留一些余量
|
||||
val finalErrorMessage = if (errorMessage.length > maxErrorMessageLength) {
|
||||
errorMessage.substring(0, maxErrorMessageLength) + "... (截断)"
|
||||
} else {
|
||||
errorMessage
|
||||
}
|
||||
|
||||
val failedTrade = FailedTrade(
|
||||
leaderId = leaderId,
|
||||
leaderTradeId = trade.id,
|
||||
tradeType = trade.side.uppercase(),
|
||||
copyTradingId = copyTradingId,
|
||||
accountId = accountId,
|
||||
marketId = trade.market,
|
||||
side = side,
|
||||
price = price,
|
||||
size = size,
|
||||
errorMessage = finalErrorMessage,
|
||||
retryCount = retryCount,
|
||||
failedAt = System.currentTimeMillis()
|
||||
)
|
||||
failedTradeRepository.save(failedTrade)
|
||||
|
||||
// 记录日志,确认已保存到数据库
|
||||
logger.info("失败交易已保存到数据库: leaderId=$leaderId, tradeId=${trade.id}, errorMessageLength=${finalErrorMessage.length}")
|
||||
|
||||
// 标记为已处理(失败状态),避免重复处理
|
||||
// 注意:并发情况下可能多个请求同时处理同一笔交易,需要处理唯一约束冲突
|
||||
try {
|
||||
val processed = ProcessedTrade(
|
||||
leaderId = leaderId,
|
||||
leaderTradeId = trade.id,
|
||||
tradeType = trade.side.uppercase(),
|
||||
source = "polling",
|
||||
status = "FAILED",
|
||||
processedAt = System.currentTimeMillis()
|
||||
)
|
||||
processedTradeRepository.save(processed)
|
||||
} catch (e: Exception) {
|
||||
// 检查是否是唯一键冲突异常
|
||||
if (isUniqueConstraintViolation(e)) {
|
||||
// 唯一约束冲突,说明已经处理过了(可能是并发请求)
|
||||
// 检查现有记录的状态
|
||||
val existing = processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (existing != null) {
|
||||
if (existing.status == "SUCCESS") {
|
||||
logger.warn("交易已成功处理,但尝试记录为失败(并发冲突): leaderId=$leaderId, tradeId=${trade.id}")
|
||||
} else {
|
||||
logger.debug("交易已标记为失败(并发检测): leaderId=$leaderId, tradeId=${trade.id}")
|
||||
}
|
||||
} else {
|
||||
// 如果查询不到,等待一下再查询(可能是事务隔离级别问题)
|
||||
delay(100)
|
||||
val existingAfterDelay =
|
||||
processedTradeRepository.findByLeaderIdAndLeaderTradeId(leaderId, trade.id)
|
||||
if (existingAfterDelay != null) {
|
||||
logger.debug("延迟查询到记录(并发检测): leaderId=$leaderId, tradeId=${trade.id}, status=${existingAfterDelay.status}")
|
||||
} else {
|
||||
logger.warn(
|
||||
"保存ProcessedTrade失败记录时发生唯一约束冲突,但查询不到记录: leaderId=$leaderId, tradeId=${trade.id}",
|
||||
e
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 其他类型的异常,记录但不抛出(避免影响其他交易的处理)
|
||||
logger.warn("保存ProcessedTrade失败记录时发生异常: leaderId=$leaderId, tradeId=${trade.id}", e)
|
||||
}
|
||||
}
|
||||
|
||||
logger.warn("已记录失败交易: leaderId=$leaderId, tradeId=${trade.id}, error=$errorMessage")
|
||||
} catch (e: Exception) {
|
||||
logger.error("记录失败交易异常: leaderId=$leaderId, tradeId=${trade.id}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新订单状态
|
||||
@@ -1409,7 +1347,7 @@ open class CopyOrderTrackingService(
|
||||
|
||||
// 计算价格调整范围(百分比)
|
||||
val tolerancePercent = tolerance.div(100)
|
||||
val adjustment = originalPrice.multi(tolerancePercent)
|
||||
val adjustment = originalPrice.multi(tolerancePercent).max(0.01.toSafeBigDecimal())
|
||||
|
||||
return if (isBuy) {
|
||||
// 买入:可以稍微加价以确保成交(在原价格基础上加容忍度)
|
||||
@@ -1462,7 +1400,7 @@ open class CopyOrderTrackingService(
|
||||
/**
|
||||
* 验证订单ID格式
|
||||
* 订单ID必须以 0x 开头,且是有效的 16 进制字符串
|
||||
*
|
||||
*
|
||||
* @param orderId 订单ID
|
||||
* @return 如果格式有效返回 true,否则返回 false
|
||||
*/
|
||||
@@ -1478,11 +1416,11 @@ open class CopyOrderTrackingService(
|
||||
// 检查是否只包含 0-9, a-f, A-F
|
||||
return hexPart.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取订单的实际成交价
|
||||
* 通过查询订单详情和关联的交易记录,计算加权平均成交价
|
||||
*
|
||||
*
|
||||
* @param orderId 订单ID
|
||||
* @param clobApi CLOB API 客户端(已认证)
|
||||
* @param fallbackPrice 如果查询失败,使用此价格作为默认值
|
||||
@@ -1496,13 +1434,19 @@ open class CopyOrderTrackingService(
|
||||
return try {
|
||||
// 1. 查询订单详情
|
||||
val orderResponse = clobApi.getOrder(orderId)
|
||||
if (!orderResponse.isSuccessful || orderResponse.body() == null) {
|
||||
logger.warn("查询订单详情失败: orderId=$orderId, code=${orderResponse.code()}")
|
||||
if (!orderResponse.isSuccessful) {
|
||||
val errorBody = orderResponse.errorBody()?.string()?.take(200) ?: "无错误详情"
|
||||
logger.warn("查询订单详情失败: orderId=$orderId, code=${orderResponse.code()}, errorBody=$errorBody")
|
||||
return fallbackPrice
|
||||
}
|
||||
|
||||
val order = orderResponse.body()
|
||||
if (order == null) {
|
||||
// 响应体为空,可能是订单不存在或已过期
|
||||
logger.warn("查询订单详情失败: 响应体为空, orderId=$orderId, code=${orderResponse.code()}")
|
||||
return fallbackPrice
|
||||
}
|
||||
|
||||
val order = orderResponse.body()!!
|
||||
|
||||
// 2. 如果订单未成交,使用下单价格
|
||||
if (order.status != "FILLED" && order.sizeMatched.toSafeBigDecimal() <= BigDecimal.ZERO) {
|
||||
logger.debug("订单未成交,使用下单价格: orderId=$orderId, status=${order.status}")
|
||||
@@ -1543,7 +1487,7 @@ open class CopyOrderTrackingService(
|
||||
for (trade in trades) {
|
||||
val tradePrice = trade.price.toSafeBigDecimal()
|
||||
val tradeSize = trade.size.toSafeBigDecimal()
|
||||
|
||||
|
||||
if (tradeSize > BigDecimal.ZERO) {
|
||||
totalAmount = totalAmount.add(tradePrice.multiply(tradeSize))
|
||||
totalSize = totalSize.add(tradeSize)
|
||||
|
||||
+3
-3
@@ -341,9 +341,9 @@ class CopyTradingStatisticsService(
|
||||
// 传递 outcomeIndex 参数,确保获取对应 outcome 的价格
|
||||
val result = accountService.getMarketPrice(marketId, outcomeIndex)
|
||||
result.onSuccess { response ->
|
||||
// 使用中间价,如果没有则使用最后价格
|
||||
val price = response.midpoint ?: response.lastPrice
|
||||
if (price != null) {
|
||||
// 使用当前价格
|
||||
val price = response.currentPrice
|
||||
if (price.isNotBlank() && price != "0") {
|
||||
// 使用 "marketId:outcomeIndex" 作为 key
|
||||
val key = "$marketId:$outcomeIndex"
|
||||
prices[key] = price
|
||||
|
||||
+209
-15
@@ -56,10 +56,13 @@ class OrderStatusUpdateService(
|
||||
// 1. 清理已删除账户的订单
|
||||
cleanupDeletedAccountOrders()
|
||||
|
||||
// 2. 更新卖出订单的实际成交价并发送通知(priceUpdated 共用字段)
|
||||
// 2. 检查30秒前创建的订单,如果未成交则删除
|
||||
checkAndDeleteUnfilledOrders()
|
||||
|
||||
// 3. 更新卖出订单的实际成交价并发送通知(priceUpdated 共用字段)
|
||||
updatePendingSellOrderPrices()
|
||||
|
||||
// 3. 更新买入订单的实际数据并发送通知
|
||||
// 4. 更新买入订单的实际数据并发送通知
|
||||
updatePendingBuyOrders()
|
||||
} catch (e: Exception) {
|
||||
logger.error("订单状态更新异常: ${e.message}", e)
|
||||
@@ -130,6 +133,136 @@ class OrderStatusUpdateService(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查30秒前创建的订单,如果未成交则删除
|
||||
* 首次检测但加入缓存中30s后还没有成交,则删除
|
||||
*/
|
||||
@Transactional
|
||||
private suspend fun checkAndDeleteUnfilledOrders() {
|
||||
try {
|
||||
// 计算30秒前的时间戳
|
||||
val thirtySecondsAgo = System.currentTimeMillis() - 30000
|
||||
|
||||
// 查询30秒前创建的订单,并过滤掉已经完全匹配的订单
|
||||
// 已经完全匹配的订单(status = "fully_matched")不需要再检查
|
||||
// 使用数据库查询过滤,避免加载过多数据
|
||||
val ordersToCheck = copyOrderTrackingRepository.findByCreatedAtBeforeAndStatusNot(
|
||||
thirtySecondsAgo,
|
||||
"fully_matched"
|
||||
)
|
||||
|
||||
if (ordersToCheck.isEmpty()) {
|
||||
return
|
||||
}
|
||||
|
||||
logger.debug("检查 ${ordersToCheck.size} 个30秒前创建的订单是否成交")
|
||||
|
||||
// 按账户分组,避免重复创建 API 客户端
|
||||
val ordersByAccount = ordersToCheck.groupBy { it.accountId }
|
||||
|
||||
for ((accountId, orders) in ordersByAccount) {
|
||||
try {
|
||||
// 获取账户
|
||||
val account = accountRepository.findById(accountId).orElse(null)
|
||||
if (account == null) {
|
||||
logger.warn("账户不存在,跳过检查: accountId=$accountId")
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查账户是否配置了 API 凭证
|
||||
if (account.apiKey == null || account.apiSecret == null || account.apiPassphrase == null) {
|
||||
logger.debug("账户未配置 API 凭证,跳过检查: accountId=${account.id}")
|
||||
continue
|
||||
}
|
||||
|
||||
// 解密 API 凭证
|
||||
val apiSecret = try {
|
||||
cryptoUtils.decrypt(account.apiSecret!!)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("解密 API Secret 失败: accountId=${account.id}, error=${e.message}")
|
||||
continue
|
||||
}
|
||||
|
||||
val apiPassphrase = try {
|
||||
cryptoUtils.decrypt(account.apiPassphrase!!)
|
||||
} catch (e: Exception) {
|
||||
logger.warn("解密 API Passphrase 失败: accountId=${account.id}, error=${e.message}")
|
||||
continue
|
||||
}
|
||||
|
||||
// 创建带认证的 CLOB API 客户端
|
||||
val clobApi = retrofitFactory.createClobApi(
|
||||
account.apiKey!!,
|
||||
apiSecret,
|
||||
apiPassphrase,
|
||||
account.walletAddress
|
||||
)
|
||||
|
||||
// 检查每个订单
|
||||
for (order in orders) {
|
||||
try {
|
||||
// 查询订单详情
|
||||
val orderResponse = clobApi.getOrder(order.buyOrderId)
|
||||
|
||||
// 先检查 HTTP 状态码,非 200 的都跳过
|
||||
if (orderResponse.code() != 200) {
|
||||
// HTTP 非 200,记录日志并跳过,等待下次轮询
|
||||
// 不删除订单,因为可能是临时网络问题或 API 错误
|
||||
val errorBody = orderResponse.errorBody()?.string()?.take(200) ?: "无错误详情"
|
||||
logger.debug("订单查询失败(HTTP非200),等待下次轮询: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, code=${orderResponse.code()}, errorBody=$errorBody")
|
||||
continue
|
||||
}
|
||||
|
||||
// HTTP 200,检查响应体
|
||||
// 响应体也可能返回字符串 "null",Gson 解析时会返回 null
|
||||
val orderDetail = orderResponse.body()
|
||||
if (orderDetail == null) {
|
||||
// HTTP 200 且响应体为 null(或字符串 "null"),表示订单不存在
|
||||
// 检查订单是否已部分卖出,如果已部分卖出则保留订单用于统计
|
||||
val hasMatchedDetails = sellMatchDetailRepository.findByTrackingId(order.id!!).isNotEmpty()
|
||||
if (hasMatchedDetails || order.matchedQuantity > BigDecimal.ZERO) {
|
||||
logger.debug("订单不存在但已部分卖出,保留订单用于统计: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, matchedQuantity=${order.matchedQuantity}")
|
||||
continue
|
||||
}
|
||||
|
||||
// 订单不存在且未部分卖出,删除本地订单
|
||||
logger.info("订单不存在(HTTP 200 但响应体为空),删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
try {
|
||||
copyOrderTrackingRepository.deleteById(order.id!!)
|
||||
logger.info("已删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
} catch (e: Exception) {
|
||||
logger.error("删除本地订单失败: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, error=${e.message}", e)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查订单是否成交
|
||||
// 如果订单状态不是 FILLED 且已成交数量为0,说明未成交,删除
|
||||
val sizeMatched = orderDetail.sizeMatched?.toSafeBigDecimal() ?: BigDecimal.ZERO
|
||||
if (orderDetail.status != "FILLED" && sizeMatched <= BigDecimal.ZERO) {
|
||||
logger.info("订单30秒后仍未成交,删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, status=${orderDetail.status}, sizeMatched=$sizeMatched")
|
||||
try {
|
||||
copyOrderTrackingRepository.deleteById(order.id!!)
|
||||
logger.info("已删除未成交订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
} catch (e: Exception) {
|
||||
logger.error("删除未成交订单失败: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, error=${e.message}", e)
|
||||
}
|
||||
} else {
|
||||
logger.debug("订单已成交或部分成交,保留: orderId=${order.buyOrderId}, status=${orderDetail.status}, sizeMatched=$sizeMatched")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("检查订单失败: orderId=${order.buyOrderId}, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("检查账户订单失败: accountId=$accountId, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("检查未成交订单异常: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新待更新的卖出订单价格
|
||||
* 注意:priceUpdated 现在同时表示价格已更新和通知已发送(共用字段)
|
||||
@@ -194,16 +327,27 @@ class OrderStatusUpdateService(
|
||||
// 如果 orderId 不是 0x 开头,直接标记为已处理(priceUpdated = true 表示已处理,包括价格更新和通知发送)
|
||||
if (!record.sellOrderId.startsWith("0x", ignoreCase = true)) {
|
||||
logger.debug("卖出订单ID非0x开头,直接标记为已处理: orderId=${record.sellOrderId}")
|
||||
// 发送通知(使用临时数据)
|
||||
sendSellOrderNotification(
|
||||
record = record,
|
||||
useTemporaryData = true,
|
||||
account = account,
|
||||
copyTrading = copyTrading,
|
||||
clobApi = clobApi,
|
||||
apiSecret = apiSecret,
|
||||
apiPassphrase = apiPassphrase
|
||||
)
|
||||
|
||||
// 检查是否为自动生成的订单(AUTO_ 或 AUTO_FIFO_ 开头),如果是则不发送通知
|
||||
val isAutoOrder = record.sellOrderId.startsWith("AUTO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_FIFO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_WS_", ignoreCase = true)
|
||||
|
||||
if (!isAutoOrder) {
|
||||
// 非自动订单,发送通知(使用临时数据)
|
||||
sendSellOrderNotification(
|
||||
record = record,
|
||||
useTemporaryData = true,
|
||||
account = account,
|
||||
copyTrading = copyTrading,
|
||||
clobApi = clobApi,
|
||||
apiSecret = apiSecret,
|
||||
apiPassphrase = apiPassphrase
|
||||
)
|
||||
} else {
|
||||
logger.debug("自动生成的订单,跳过发送通知: orderId=${record.sellOrderId}")
|
||||
}
|
||||
|
||||
// 标记为已处理(priceUpdated = true 同时表示价格已更新和通知已发送)
|
||||
val updatedRecord = SellMatchRecord(
|
||||
id = record.id,
|
||||
@@ -223,6 +367,32 @@ class OrderStatusUpdateService(
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查是否为自动生成的订单(AUTO_ 或 AUTO_FIFO_ 开头),如果是则跳过发送通知
|
||||
val isAutoOrder = record.sellOrderId.startsWith("AUTO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_FIFO_", ignoreCase = true) ||
|
||||
record.sellOrderId.startsWith("AUTO_WS_", ignoreCase = true)
|
||||
|
||||
if (isAutoOrder) {
|
||||
logger.debug("自动生成的订单,跳过发送通知并直接标记为已处理: orderId=${record.sellOrderId}")
|
||||
// 直接标记为已处理,不发送通知
|
||||
val updatedRecord = SellMatchRecord(
|
||||
id = record.id,
|
||||
copyTradingId = record.copyTradingId,
|
||||
sellOrderId = record.sellOrderId,
|
||||
leaderSellTradeId = record.leaderSellTradeId,
|
||||
marketId = record.marketId,
|
||||
side = record.side,
|
||||
outcomeIndex = record.outcomeIndex,
|
||||
totalMatchedQuantity = record.totalMatchedQuantity,
|
||||
sellPrice = record.sellPrice,
|
||||
totalRealizedPnl = record.totalRealizedPnl,
|
||||
priceUpdated = true, // 标记为已处理
|
||||
createdAt = record.createdAt
|
||||
)
|
||||
sellMatchRecordRepository.save(updatedRecord)
|
||||
continue
|
||||
}
|
||||
|
||||
// 查询订单详情,获取实际成交价
|
||||
val actualSellPrice = trackingService.getActualExecutionPrice(
|
||||
orderId = record.sellOrderId,
|
||||
@@ -419,12 +589,36 @@ class OrderStatusUpdateService(
|
||||
|
||||
// 查询订单详情
|
||||
val orderResponse = clobApi.getOrder(order.buyOrderId)
|
||||
if (!orderResponse.isSuccessful || orderResponse.body() == null) {
|
||||
logger.debug("查询订单详情失败,等待下次轮询: orderId=${order.buyOrderId}, code=${orderResponse.code()}")
|
||||
|
||||
// 先检查 HTTP 状态码,非 200 的都跳过
|
||||
if (orderResponse.code() != 200) {
|
||||
val errorBody = orderResponse.errorBody()?.string()?.take(200) ?: "无错误详情"
|
||||
logger.debug("查询订单详情失败(HTTP非200),等待下次轮询: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, code=${orderResponse.code()}, errorBody=$errorBody")
|
||||
continue
|
||||
}
|
||||
|
||||
val orderDetail = orderResponse.body()!!
|
||||
// HTTP 200,检查响应体
|
||||
// 响应体也可能返回字符串 "null",Gson 解析时会返回 null
|
||||
val orderDetail = orderResponse.body()
|
||||
if (orderDetail == null) {
|
||||
// HTTP 200 且响应体为 null(或字符串 "null"),表示订单不存在
|
||||
// 检查订单是否已部分卖出,如果已部分卖出则保留订单用于统计
|
||||
val hasMatchedDetails = sellMatchDetailRepository.findByTrackingId(order.id!!).isNotEmpty()
|
||||
if (hasMatchedDetails || order.matchedQuantity > BigDecimal.ZERO) {
|
||||
logger.debug("订单不存在但已部分卖出,保留订单用于统计: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, matchedQuantity=${order.matchedQuantity}")
|
||||
continue
|
||||
}
|
||||
|
||||
// 订单不存在且未部分卖出,删除本地订单
|
||||
logger.info("订单不存在(HTTP 200 但响应体为空),删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
try {
|
||||
copyOrderTrackingRepository.deleteById(order.id!!)
|
||||
logger.info("已删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
} catch (e: Exception) {
|
||||
logger.error("删除本地订单失败: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, error=${e.message}", e)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取实际价格和数量
|
||||
val actualPrice = orderDetail.price?.toSafeBigDecimal() ?: order.price
|
||||
|
||||
+3
-21
@@ -28,8 +28,6 @@ class ApiHealthCheckService(
|
||||
private val dataApiBaseUrl: String,
|
||||
@Value("\${polymarket.gamma.base-url}")
|
||||
private val gammaBaseUrl: String,
|
||||
@Value("\${polygon.rpc.url:}")
|
||||
private val polygonRpcUrl: String,
|
||||
@Value("\${polymarket.rtds.ws-url}")
|
||||
private val polymarketWsUrl: String,
|
||||
@Value("\${polymarket.builder.relayer-url:}")
|
||||
@@ -187,27 +185,11 @@ class ApiHealthCheckService(
|
||||
|
||||
/**
|
||||
* 检查 Polygon RPC
|
||||
* 使用动态获取的可用节点,而不是固定的配置
|
||||
* 使用动态获取的可用节点(RpcNodeService 总是返回一个有效的 URL,包括默认节点)
|
||||
*/
|
||||
private suspend fun checkPolygonRpc(): ApiHealthCheckDto = withContext(Dispatchers.IO) {
|
||||
// 优先使用动态获取的可用节点
|
||||
val rpcUrl = try {
|
||||
rpcNodeService.getHttpUrl()
|
||||
} catch (e: Exception) {
|
||||
logger.debug("获取可用 RPC 节点失败,使用配置的默认值: ${e.message}")
|
||||
// 如果获取失败,使用配置的默认值作为兜底
|
||||
if (polygonRpcUrl.isNotBlank()) {
|
||||
polygonRpcUrl
|
||||
} else {
|
||||
return@withContext ApiHealthCheckDto(
|
||||
name = "Polygon RPC",
|
||||
url = "未配置",
|
||||
status = "skipped",
|
||||
message = "未配置 Polygon RPC URL 且没有可用的节点"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 使用 RpcNodeService 获取可用节点(总是返回有效值,包括默认节点)
|
||||
val rpcUrl = rpcNodeService.getHttpUrl()
|
||||
checkJsonRpcApi("Polygon RPC", rpcUrl)
|
||||
}
|
||||
|
||||
|
||||
+4
-15
@@ -333,15 +333,10 @@ class RelayClientService(
|
||||
// 打包签名(参考 builder-relayer-client/src/utils/index.ts 的 splitAndPackSig)
|
||||
val packedSignature = splitAndPackSig(safeSignature)
|
||||
|
||||
// 调试日志
|
||||
// 调试日志(地址已遮蔽)
|
||||
logger.debug("=== Builder Relayer 签名调试 ===")
|
||||
logger.debug("Safe Address: $proxyAddress")
|
||||
logger.debug("From Address: $fromAddress")
|
||||
logger.debug("To: ${safeTx.to}")
|
||||
logger.debug("Data: $redeemCallData")
|
||||
logger.debug("Nonce: $proxyNonce")
|
||||
logger.debug("Packed Signature: $packedSignature")
|
||||
logger.debug("Signature Length: ${packedSignature.length} (expected: 132 with 0x)")
|
||||
logger.debug("Safe: ${proxyAddress.take(10)}..., From: ${fromAddress.take(10)}..., Nonce: $proxyNonce")
|
||||
logger.debug("Signature Length: ${packedSignature.length}")
|
||||
|
||||
// 构建 TransactionRequest(参考 builder-relayer-client/src/builder/safe.ts)
|
||||
// 注意:根据 TypeScript 实现,data 和 signature 都应该带 0x 前缀
|
||||
@@ -364,13 +359,7 @@ class RelayClientService(
|
||||
metadata = "Redeem positions via Builder Relayer"
|
||||
)
|
||||
|
||||
logger.debug("Request Type: ${request.type}")
|
||||
logger.debug("Request From: ${request.from}")
|
||||
logger.debug("Request To: ${request.to}")
|
||||
logger.debug("Request ProxyWallet: ${request.proxyWallet}")
|
||||
logger.debug("Request Data Length: ${request.data.length}")
|
||||
logger.debug("Request Signature Length: ${request.signature.length}")
|
||||
logger.debug("Request Nonce: ${request.nonce}")
|
||||
logger.debug("Request: type=${request.type}, dataLen=${request.data.length}, sigLen=${request.signature.length}, nonce=${request.nonce}")
|
||||
|
||||
// 调用 Builder Relayer API(认证头通过拦截器添加)
|
||||
val response = relayerApi.submitTransaction(request)
|
||||
|
||||
+20
-7
@@ -25,6 +25,19 @@ class SystemConfigService(
|
||||
const val CONFIG_KEY_BUILDER_SECRET = "builder.secret"
|
||||
const val CONFIG_KEY_BUILDER_PASSPHRASE = "builder.passphrase"
|
||||
const val CONFIG_KEY_AUTO_REDEEM = "auto_redeem"
|
||||
|
||||
/**
|
||||
* 遮蔽敏感信息,仅显示前4位和后4位
|
||||
* 例如:abcd1234...wxyz5678
|
||||
*/
|
||||
fun maskSensitiveValue(value: String?): String? {
|
||||
if (value == null) return null
|
||||
return when {
|
||||
value.length <= 8 -> "****" // 太短则完全遮蔽
|
||||
value.length <= 16 -> "${value.take(2)}...${value.takeLast(2)}"
|
||||
else -> "${value.take(4)}...${value.takeLast(4)}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,26 +49,26 @@ class SystemConfigService(
|
||||
val builderPassphrase = getConfigValue(CONFIG_KEY_BUILDER_PASSPHRASE)
|
||||
val autoRedeem = isAutoRedeemEnabled()
|
||||
|
||||
// 获取完整的 API Key(用于前端展示)
|
||||
val builderApiKeyDisplay = builderApiKey?.let {
|
||||
// 获取遮蔽后的显示值(仅显示部分字符,用于前端确认配置)
|
||||
val builderApiKeyDisplay = builderApiKey?.let {
|
||||
try {
|
||||
cryptoUtils.decrypt(it)
|
||||
maskSensitiveValue(cryptoUtils.decrypt(it))
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
val builderSecretDisplay = builderSecret?.let {
|
||||
try {
|
||||
cryptoUtils.decrypt(it)
|
||||
maskSensitiveValue(cryptoUtils.decrypt(it))
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
val builderPassphraseDisplay = builderPassphrase?.let {
|
||||
try {
|
||||
cryptoUtils.decrypt(it)
|
||||
maskSensitiveValue(cryptoUtils.decrypt(it))
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
+155
-73
@@ -43,6 +43,25 @@ class TelegramNotificationService(
|
||||
// 协程作用域
|
||||
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
/**
|
||||
* 发送订单成功通知
|
||||
* @param orderId 订单ID(用于查询订单详情获取实际价格和数量)
|
||||
* @param marketTitle 市场标题
|
||||
* @param marketId 市场ID(conditionId),用于生成链接
|
||||
* @param marketSlug 市场slug,用于生成链接
|
||||
* @param side 订单方向(BUY/SELL),用于多语言显示
|
||||
* @param accountName 账户名称
|
||||
* @param walletAddress 钱包地址
|
||||
* @param clobApi CLOB API 客户端(可选,如果提供则查询订单详情获取实际价格和数量)
|
||||
* @param apiKey API Key(可选,用于查询订单详情)
|
||||
* @param apiSecret API Secret(可选,用于查询订单详情)
|
||||
* @param apiPassphrase API Passphrase(可选,用于查询订单详情)
|
||||
* @param walletAddressForApi 钱包地址(可选,用于查询订单详情)
|
||||
* @param locale 语言设置(可选,如果提供则使用,否则使用 LocaleContextHolder 获取)
|
||||
*/
|
||||
// 已发送通知的订单ID缓存(key: orderId, value: timestamp)
|
||||
private val sentOrderIds = java.util.concurrent.ConcurrentHashMap<String, Long>()
|
||||
|
||||
/**
|
||||
* 发送订单成功通知
|
||||
* @param orderId 订单ID(用于查询订单详情获取实际价格和数量)
|
||||
@@ -79,6 +98,26 @@ class TelegramNotificationService(
|
||||
leaderName: String? = null, // Leader 名称(备注)
|
||||
configName: String? = null // 跟单配置名
|
||||
) {
|
||||
// 1. 如果提供了 orderId,检查是否已发送过通知(去重)
|
||||
if (orderId != null) {
|
||||
val lastSentTime = sentOrderIds[orderId]
|
||||
if (lastSentTime != null) {
|
||||
// 如果5分钟内已发送过,跳过
|
||||
if (System.currentTimeMillis() - lastSentTime < 5 * 60 * 1000) {
|
||||
logger.info("订单通知已发送过(5分钟内),跳过: orderId=$orderId")
|
||||
return
|
||||
}
|
||||
}
|
||||
// 记录发送时间
|
||||
sentOrderIds[orderId] = System.currentTimeMillis()
|
||||
|
||||
// 简单的清理逻辑:如果缓存过大,清理过期的
|
||||
if (sentOrderIds.size > 1000) {
|
||||
val expiryTime = System.currentTimeMillis() - 5 * 60 * 1000
|
||||
sentOrderIds.entries.removeIf { it.value < expiryTime }
|
||||
}
|
||||
}
|
||||
|
||||
// 获取语言设置(优先使用传入的 locale,否则从 LocaleContextHolder 获取)
|
||||
val currentLocale = locale ?: try {
|
||||
LocaleContextHolder.getLocale()
|
||||
@@ -97,21 +136,28 @@ class TelegramNotificationService(
|
||||
if ((actualPrice == null || actualSize == null) && orderId != null && clobApi != null && apiKey != null && apiSecret != null && apiPassphrase != null && walletAddressForApi != null) {
|
||||
try {
|
||||
val orderResponse = clobApi.getOrder(orderId)
|
||||
if (orderResponse.isSuccessful && orderResponse.body() != null) {
|
||||
val order = orderResponse.body()!!
|
||||
if (actualPrice == null) {
|
||||
actualPrice = order.price
|
||||
}
|
||||
if (actualSize == null) {
|
||||
actualSize = order.originalSize // 使用 originalSize 作为订单数量
|
||||
}
|
||||
actualSide = order.side // 使用订单详情中的 side
|
||||
if (actualOutcome == null) {
|
||||
actualOutcome = order.outcome // 使用订单详情中的 outcome(市场方向)
|
||||
if (orderResponse.isSuccessful) {
|
||||
val order = orderResponse.body()
|
||||
if (order != null) {
|
||||
if (actualPrice == null) {
|
||||
actualPrice = order.price
|
||||
}
|
||||
if (actualSize == null) {
|
||||
actualSize = order.originalSize // 使用 originalSize 作为订单数量
|
||||
}
|
||||
actualSide = order.side // 使用订单详情中的 side
|
||||
if (actualOutcome == null) {
|
||||
actualOutcome = order.outcome // 使用订单详情中的 outcome(市场方向)
|
||||
}
|
||||
} else {
|
||||
logger.debug("查询订单详情失败: 响应体为空, orderId=$orderId")
|
||||
}
|
||||
} else {
|
||||
val errorBody = orderResponse.errorBody()?.string()?.take(200) ?: "无错误详情"
|
||||
logger.debug("查询订单详情失败: orderId=$orderId, code=${orderResponse.code()}, errorBody=$errorBody")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.warn("查询订单详情失败: ${e.message}", e)
|
||||
logger.warn("查询订单详情失败: orderId=$orderId, ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,18 +352,8 @@ class TelegramNotificationService(
|
||||
else -> filterType
|
||||
}
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
val time = DateUtils.formatDateTime()
|
||||
|
||||
@@ -369,13 +405,17 @@ class TelegramNotificationService(
|
||||
""
|
||||
}
|
||||
|
||||
// 格式化价格和数量
|
||||
val priceDisplay = formatPrice(price)
|
||||
val sizeDisplay = formatQuantity(size)
|
||||
|
||||
return """🚫 <b>$orderFiltered</b>
|
||||
|
||||
📊 <b>$orderInfo:</b>
|
||||
• $marketLabel: $marketDisplay$outcomeDisplay
|
||||
• $sideLabel: <b>$sideDisplay</b>
|
||||
• $priceLabel: <code>$price</code>
|
||||
• $quantityLabel: <code>$size</code> shares
|
||||
• $priceLabel: <code>$priceDisplay</code>
|
||||
• $quantityLabel: <code>$sizeDisplay</code> shares
|
||||
• $amountLabel: <code>$amountDisplay</code> USDC
|
||||
• $accountLabel: $escapedAccountInfo
|
||||
|
||||
@@ -580,6 +620,68 @@ class TelegramNotificationService(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化价格显示(保留最多4位小数,截断不四舍五入)
|
||||
*/
|
||||
private fun formatPrice(price: String): String {
|
||||
return try {
|
||||
val priceDecimal = price.toSafeBigDecimal()
|
||||
val formatted = if (priceDecimal.scale() > 4) {
|
||||
priceDecimal.setScale(4, java.math.RoundingMode.DOWN).stripTrailingZeros()
|
||||
} else {
|
||||
priceDecimal.stripTrailingZeros()
|
||||
}
|
||||
formatted.toPlainString()
|
||||
} catch (e: Exception) {
|
||||
price
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化数量显示(保留最多2位小数,截断不四舍五入)
|
||||
*/
|
||||
private fun formatQuantity(quantity: String): String {
|
||||
return try {
|
||||
val quantityDecimal = quantity.toSafeBigDecimal()
|
||||
val formatted = if (quantityDecimal.scale() > 2) {
|
||||
quantityDecimal.setScale(2, java.math.RoundingMode.DOWN).stripTrailingZeros()
|
||||
} else {
|
||||
quantityDecimal.stripTrailingZeros()
|
||||
}
|
||||
formatted.toPlainString()
|
||||
} catch (e: Exception) {
|
||||
quantity
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建账户信息显示(格式:账户名(钱包地址))
|
||||
*/
|
||||
private fun buildAccountInfo(
|
||||
accountName: String?,
|
||||
walletAddress: String?,
|
||||
unknownAccount: String
|
||||
): String {
|
||||
return when {
|
||||
!accountName.isNullOrBlank() && !walletAddress.isNullOrBlank() -> {
|
||||
// 有账户名和钱包地址:账户名(钱包地址)
|
||||
"${accountName}(${maskAddress(walletAddress)})"
|
||||
}
|
||||
!accountName.isNullOrBlank() -> {
|
||||
// 只有账户名
|
||||
accountName
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
// 只有钱包地址
|
||||
maskAddress(walletAddress)
|
||||
}
|
||||
else -> {
|
||||
// 都没有
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建订单成功消息
|
||||
*/
|
||||
@@ -623,18 +725,15 @@ class TelegramNotificationService(
|
||||
else -> side
|
||||
}
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
// 获取图标
|
||||
val icon = when (side.uppercase()) {
|
||||
"BUY" -> "🚀"
|
||||
"SELL" -> "💰"
|
||||
else -> "📣"
|
||||
}
|
||||
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
// 构建跟单信息(如果有)
|
||||
val copyTradingInfo = mutableListOf<String>()
|
||||
@@ -704,14 +803,18 @@ class TelegramNotificationService(
|
||||
""
|
||||
}
|
||||
|
||||
return """✅ <b>$orderCreatedSuccess</b>
|
||||
// 格式化价格和数量
|
||||
val priceDisplay = formatPrice(price)
|
||||
val sizeDisplay = formatQuantity(size)
|
||||
|
||||
return """$icon <b>$orderCreatedSuccess</b>
|
||||
|
||||
📊 <b>$orderInfo:</b>
|
||||
• $orderIdLabel: <code>${orderId ?: unknown}</code>
|
||||
• $marketLabel: $marketDisplay$outcomeDisplay
|
||||
• $sideLabel: <b>$sideDisplay</b>
|
||||
• $priceLabel: <code>$price</code>
|
||||
• $quantityLabel: <code>$size</code> shares
|
||||
• $priceLabel: <code>$priceDisplay</code>
|
||||
• $quantityLabel: <code>$sizeDisplay</code> shares
|
||||
• $amountLabel: <code>$amountDisplay</code> USDC
|
||||
• $accountLabel: $escapedAccountInfo$escapedCopyTradingInfo
|
||||
|
||||
@@ -758,18 +861,8 @@ class TelegramNotificationService(
|
||||
else -> side
|
||||
}
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
val time = DateUtils.formatDateTime()
|
||||
|
||||
@@ -828,13 +921,17 @@ class TelegramNotificationService(
|
||||
""
|
||||
}
|
||||
|
||||
// 格式化价格和数量
|
||||
val priceDisplay = formatPrice(price)
|
||||
val sizeDisplay = formatQuantity(size)
|
||||
|
||||
return """❌ <b>$orderCreatedFailed</b>
|
||||
|
||||
📊 <b>$orderInfo:</b>
|
||||
• $marketLabel: $marketDisplay$outcomeDisplay
|
||||
• $sideLabel: <b>$sideDisplay</b>
|
||||
• $priceLabel: <code>$price</code>
|
||||
• $quantityLabel: <code>$size</code> shares
|
||||
• $priceLabel: <code>$priceDisplay</code>
|
||||
• $quantityLabel: <code>$sizeDisplay</code> shares
|
||||
• $amountLabel: <code>$amountDisplay</code> USDC
|
||||
• $accountLabel: $escapedAccountInfo
|
||||
|
||||
@@ -899,18 +996,8 @@ class TelegramNotificationService(
|
||||
val timeLabel = messageSource.getMessage("notification.order.time", null, "时间", locale)
|
||||
val unknownAccount: String = messageSource.getMessage("notification.order.unknown_account", null, "未知账户", locale) ?: "未知账户"
|
||||
|
||||
// 优先使用账户名称,如果没有账户名称才显示钱包地址
|
||||
val accountInfo: String = when {
|
||||
!accountName.isNullOrBlank() -> {
|
||||
accountName!!
|
||||
}
|
||||
!walletAddress.isNullOrBlank() -> {
|
||||
maskAddress(walletAddress!!)
|
||||
}
|
||||
else -> {
|
||||
unknownAccount
|
||||
}
|
||||
}
|
||||
// 构建账户信息(格式:账户名(钱包地址))
|
||||
val accountInfo = buildAccountInfo(accountName, walletAddress, unknownAccount)
|
||||
|
||||
val time = DateUtils.formatDateTime()
|
||||
|
||||
@@ -933,12 +1020,7 @@ class TelegramNotificationService(
|
||||
|
||||
// 构建仓位列表
|
||||
val positionsText = positions.joinToString("\n") { position ->
|
||||
val quantityDisplay = try {
|
||||
val quantityDecimal = position.quantity.toSafeBigDecimal()
|
||||
quantityDecimal.stripTrailingZeros().toPlainString()
|
||||
} catch (e: Exception) {
|
||||
position.quantity
|
||||
}
|
||||
val quantityDisplay = formatQuantity(position.quantity)
|
||||
val valueDisplay = try {
|
||||
val valueDecimal = position.value.toSafeBigDecimal()
|
||||
val formatted = if (valueDecimal.scale() > 4) {
|
||||
@@ -953,7 +1035,7 @@ class TelegramNotificationService(
|
||||
" • ${position.marketId.substring(0, 8)}... (${position.side}): $quantityDisplay shares = $valueDisplay USDC"
|
||||
}
|
||||
|
||||
return """✅ <b>$redeemSuccess</b>
|
||||
return """💸 <b>$redeemSuccess</b>
|
||||
|
||||
📊 <b>$redeemInfo:</b>
|
||||
• $accountLabel: $escapedAccountInfo
|
||||
|
||||
@@ -19,7 +19,7 @@ object EthereumUtils {
|
||||
* @return 函数选择器,例如 "0x12345678"
|
||||
*/
|
||||
fun getFunctionSelector(functionSignature: String): String {
|
||||
val hash = keccak256(functionSignature.toByteArray())
|
||||
val hash = keccak256Hex(functionSignature.toByteArray())
|
||||
return "0x" + hash.substring(0, 8)
|
||||
}
|
||||
|
||||
@@ -77,16 +77,109 @@ object EthereumUtils {
|
||||
return BigInteger(cleanHex, 16)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 ABI 编码的响应中解析 uint256 数组
|
||||
* ABI 编码格式:
|
||||
* - offset (32 bytes): 数组数据的位置偏移量
|
||||
* - length (32 bytes): 数组长度
|
||||
* - data: 每个元素 32 字节
|
||||
* @param hexResult 十六进制结果(完整的 ABI 编码响应)
|
||||
* @param offset 数组数据的偏移位置(字节数,从 offset 位置开始读取)
|
||||
* @return BigInteger 数组
|
||||
*/
|
||||
fun decodeUint256Array(hexResult: String, offset: Int = 0): List<BigInteger> {
|
||||
val cleanHex = hexResult.removePrefix("0x")
|
||||
if (cleanHex.length < (offset + 1) * 64) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
// 从 offset 位置开始读取
|
||||
val startPos = offset * 64 // 每个 uint256 是 64 个十六进制字符
|
||||
val lengthHex = cleanHex.substring(startPos, startPos + 64)
|
||||
val length = BigInteger(lengthHex, 16).toInt()
|
||||
|
||||
if (length <= 0 || length > 100) { // 防止异常数据
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
val result = mutableListOf<BigInteger>()
|
||||
for (i in 0 until length) {
|
||||
val elementStart = startPos + 64 + (i * 64) // 跳过长度字段
|
||||
if (elementStart + 64 > cleanHex.length) {
|
||||
break
|
||||
}
|
||||
val elementHex = cleanHex.substring(elementStart, elementStart + 64)
|
||||
result.add(BigInteger(elementHex, 16))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 ABI 编码的元组响应中解析数据
|
||||
* 用于解析 getCondition 返回的 (uint256 payoutDenominator, uint256[] payouts)
|
||||
* @param hexResult 十六进制结果
|
||||
* @return Pair<payoutDenominator, payouts>
|
||||
*/
|
||||
fun decodeConditionResult(hexResult: String): Pair<BigInteger, List<BigInteger>> {
|
||||
val cleanHex = hexResult.removePrefix("0x")
|
||||
|
||||
// 第一个 32 字节:payoutDenominator
|
||||
val payoutDenominatorHex = cleanHex.substring(0, 64)
|
||||
val payoutDenominator = BigInteger(payoutDenominatorHex, 16)
|
||||
|
||||
// 第二个 32 字节:payouts 数组的偏移量(通常是 0x40 = 64 字节)
|
||||
val offsetHex = cleanHex.substring(64, 128)
|
||||
val offset = BigInteger(offsetHex, 16).toInt() / 32 // 转换为 32 字节单位
|
||||
|
||||
// 从 offset 位置解析数组
|
||||
val payouts = decodeUint256Array(hexResult, offset)
|
||||
|
||||
return Pair(payoutDenominator, payouts)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将十六进制字符串转换为字节数组
|
||||
* @param hex 十六进制字符串(带或不带 0x 前缀)
|
||||
* @return 字节数组
|
||||
*/
|
||||
fun hexToBytes(hex: String): ByteArray {
|
||||
val cleanHex = hex.removePrefix("0x")
|
||||
return ByteArray(cleanHex.length / 2) { i ->
|
||||
cleanHex.substring(i * 2, i * 2 + 2).toInt(16).toByte()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为十六进制字符串
|
||||
* @param bytes 字节数组
|
||||
* @return 十六进制字符串(带 0x 前缀)
|
||||
*/
|
||||
fun bytesToHex(bytes: ByteArray): String {
|
||||
return "0x" + bytes.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 Keccak-256 哈希(Ethereum 标准)
|
||||
* 使用 BouncyCastle 库实现真正的 Keccak-256
|
||||
* @param data 输入数据
|
||||
* @return 32 字节的哈希值
|
||||
*/
|
||||
private fun keccak256(data: ByteArray): String {
|
||||
fun keccak256(data: ByteArray): ByteArray {
|
||||
val digest = KeccakDigest(256)
|
||||
digest.update(data, 0, data.size)
|
||||
val hash = ByteArray(digest.digestSize)
|
||||
digest.doFinal(hash, 0)
|
||||
return hash.joinToString("") { "%02x".format(it) }
|
||||
return hash
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 Keccak-256 哈希并返回十六进制字符串
|
||||
* @param data 输入数据
|
||||
* @return 十六进制哈希字符串
|
||||
*/
|
||||
fun keccak256Hex(data: ByteArray): String {
|
||||
return keccak256(data).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,14 +2,16 @@ package com.wrbug.polymarketbot.util
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
/**
|
||||
* JSON 工具类
|
||||
* 用于解析 JSON 字符串
|
||||
*/
|
||||
object JsonUtils {
|
||||
|
||||
private val gson = Gson()
|
||||
@Component
|
||||
class JsonUtils(
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
/**
|
||||
* 解析 JSON 字符串数组
|
||||
|
||||
@@ -26,21 +26,23 @@ fun BigDecimal.multi(value: Any): BigDecimal {
|
||||
return BigDecimal.ZERO
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* BigDecimal除法扩展函数
|
||||
* BigDecimal除法扩展函数(带精度和舍入模式)
|
||||
* 安全地将BigDecimal与任意数值类型相除
|
||||
* @param value 除数,支持BigDecimal、BigInteger类型或可转换为BigDecimal的字符串
|
||||
* @return 除法结果,精度为18位小数,使用四舍五入模式,如果转换失败返回IllegalBigDecimal
|
||||
* @param scale 精度(小数位数)
|
||||
* @param roundingMode 舍入模式
|
||||
* @return 除法结果,如果转换失败返回IllegalBigDecimal
|
||||
*/
|
||||
fun BigDecimal.div(value: Any): BigDecimal {
|
||||
fun BigDecimal.div(value: Any, scale: Int = 18, roundingMode: RoundingMode = RoundingMode.HALF_UP): BigDecimal {
|
||||
kotlin.runCatching {
|
||||
if (value is BigDecimal) {
|
||||
return divide(value, 18, RoundingMode.HALF_UP).stripTrailingZeros()
|
||||
val divisor = when (value) {
|
||||
is BigDecimal -> value
|
||||
is BigInteger -> value.toBigDecimal()
|
||||
else -> BigDecimal(value.toString())
|
||||
}
|
||||
if (value is BigInteger) {
|
||||
return divide(value.toSafeBigDecimal(), 18, RoundingMode.HALF_UP).stripTrailingZeros()
|
||||
}
|
||||
return divide(BigDecimal(value.toString()), 18, RoundingMode.HALF_UP).stripTrailingZeros()
|
||||
return divide(divisor, scale, roundingMode)
|
||||
}
|
||||
return IllegalBigDecimal
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.wrbug.polymarketbot.util
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.wrbug.polymarketbot.api.BuilderRelayerApi
|
||||
import com.wrbug.polymarketbot.api.EthereumRpcApi
|
||||
import com.wrbug.polymarketbot.api.GitHubApi
|
||||
@@ -24,21 +23,116 @@ import org.springframework.stereotype.Component
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.gson.GsonConverterFactory
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import jakarta.annotation.PreDestroy
|
||||
|
||||
/**
|
||||
* Retrofit 客户端工厂
|
||||
* 用于创建带认证的 Polymarket CLOB API 客户端和 Ethereum RPC API 客户端
|
||||
*
|
||||
* 注意:为了避免内存泄漏,本类会缓存和复用客户端实例
|
||||
*/
|
||||
@Component
|
||||
class RetrofitFactory(
|
||||
@Value("\${polymarket.clob.base-url}")
|
||||
private val clobBaseUrl: String,
|
||||
@Value("\${polymarket.gamma.base-url}")
|
||||
private val gammaBaseUrl: String
|
||||
private val gammaBaseUrl: String,
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(RetrofitFactory::class.java)
|
||||
|
||||
// 共享的 OkHttpClient(用于不需要认证的 API)
|
||||
private val sharedOkHttpClient: OkHttpClient by lazy {
|
||||
createClient().build()
|
||||
}
|
||||
|
||||
// 共享的 OkHttpClient(用于需要跟随重定向的 API)
|
||||
private val sharedOkHttpClientWithRedirect: OkHttpClient by lazy {
|
||||
createClient()
|
||||
.followRedirects(true)
|
||||
.followSslRedirects(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
// 缓存 Gamma API 客户端(单例)
|
||||
private val gammaApi: PolymarketGammaApi by lazy {
|
||||
val baseUrl = if (gammaBaseUrl.endsWith("/")) {
|
||||
gammaBaseUrl.dropLast(1)
|
||||
} else {
|
||||
gammaBaseUrl
|
||||
}
|
||||
|
||||
Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(sharedOkHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketGammaApi::class.java)
|
||||
}
|
||||
|
||||
// 缓存 Data API 客户端(单例)
|
||||
private val dataApi: PolymarketDataApi by lazy {
|
||||
val baseUrl = "https://data-api.polymarket.com"
|
||||
|
||||
Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(sharedOkHttpClientWithRedirect)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketDataApi::class.java)
|
||||
}
|
||||
|
||||
// 缓存 GitHub API 客户端(单例)
|
||||
private val githubApi: GitHubApi by lazy {
|
||||
val baseUrl = "https://api.github.com"
|
||||
|
||||
// 添加拦截器,设置 Accept 头以获取 reactions 数据
|
||||
val githubInterceptor = object : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request().newBuilder()
|
||||
.header("Accept", "application/vnd.github+json")
|
||||
.build()
|
||||
return chain.proceed(request)
|
||||
}
|
||||
}
|
||||
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(githubInterceptor)
|
||||
.build()
|
||||
|
||||
Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(GitHubApi::class.java)
|
||||
}
|
||||
|
||||
// 缓存不带认证的 CLOB API 客户端(单例)
|
||||
private val clobApiWithoutAuth: PolymarketClobApi by lazy {
|
||||
Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.client(sharedOkHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
}
|
||||
|
||||
// 缓存带认证的 CLOB API 客户端:walletAddress -> PolymarketClobApi
|
||||
// 注意:每个账户使用不同的 API Key,需要不同的客户端
|
||||
private val clobApiCache = ConcurrentHashMap<String, PolymarketClobApi>()
|
||||
|
||||
// 缓存 RPC API 客户端:rpcUrl -> EthereumRpcApi
|
||||
private val rpcApiCache = ConcurrentHashMap<String, EthereumRpcApi>()
|
||||
|
||||
// 缓存 Builder Relayer API 客户端:relayerUrl -> BuilderRelayerApi
|
||||
private val builderRelayerApiCache = ConcurrentHashMap<String, BuilderRelayerApi>()
|
||||
|
||||
/**
|
||||
* 创建带认证的 Polymarket CLOB API 客户端
|
||||
* 按钱包地址缓存,避免重复创建
|
||||
* @param apiKey API Key
|
||||
* @param apiSecret API Secret
|
||||
* @param apiPassphrase API Passphrase
|
||||
@@ -51,67 +145,46 @@ class RetrofitFactory(
|
||||
apiPassphrase: String,
|
||||
walletAddress: String
|
||||
): PolymarketClobApi {
|
||||
val authInterceptor = PolymarketAuthInterceptor(apiKey, apiSecret, apiPassphrase, walletAddress)
|
||||
|
||||
// 添加响应日志拦截器,用于调试 JSON 解析错误
|
||||
val responseLoggingInterceptor = ResponseLoggingInterceptor()
|
||||
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(authInterceptor)
|
||||
.addInterceptor(responseLoggingInterceptor)
|
||||
.build()
|
||||
|
||||
// 创建 lenient 模式的 Gson,允许解析格式不严格的 JSON
|
||||
val gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
// 使用钱包地址作为缓存键(每个账户使用不同的 API Key)
|
||||
return clobApiCache.computeIfAbsent(walletAddress) {
|
||||
val authInterceptor = PolymarketAuthInterceptor(apiKey, apiSecret, apiPassphrase, walletAddress)
|
||||
|
||||
// 添加响应日志拦截器,用于调试 JSON 解析错误
|
||||
val responseLoggingInterceptor = ResponseLoggingInterceptor()
|
||||
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(authInterceptor)
|
||||
.addInterceptor(responseLoggingInterceptor)
|
||||
.build()
|
||||
|
||||
Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建不带认证的 Polymarket CLOB API 客户端
|
||||
* 用于不需要认证的查询接口
|
||||
* @return PolymarketClobApi 客户端
|
||||
* @return PolymarketClobApi 客户端(单例)
|
||||
*/
|
||||
fun createClobApiWithoutAuth(): PolymarketClobApi {
|
||||
// 添加响应日志拦截器,用于调试 JSON 解析错误
|
||||
val responseLoggingInterceptor = ResponseLoggingInterceptor()
|
||||
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(responseLoggingInterceptor)
|
||||
.build()
|
||||
|
||||
// 创建 lenient 模式的 Gson,允许解析格式不严格的 JSON
|
||||
val gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(clobBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketClobApi::class.java)
|
||||
return clobApiWithoutAuth
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 Ethereum RPC API 客户端
|
||||
* 使用固定的 baseUrl,通过拦截器动态替换为实际的 RPC URL
|
||||
* 如果 RPC 不可用,将抛出异常
|
||||
* 按 RPC URL 缓存,避免重复创建
|
||||
* @param rpcUrl RPC 节点 URL
|
||||
* @return EthereumRpcApi 客户端
|
||||
* @throws IllegalArgumentException 如果 RPC URL 无效或不可用
|
||||
*/
|
||||
fun createEthereumRpcApi(rpcUrl: String): EthereumRpcApi {
|
||||
// 使用固定的 baseUrl(Retrofit 要求 baseUrl 必须以 / 结尾)
|
||||
val fixedBaseUrl = "https://polyrpc.polyhermes/"
|
||||
|
||||
// 确保实际的 RPC URL 以 / 结尾
|
||||
val actualRpcUrl = if (rpcUrl.endsWith("/")) {
|
||||
rpcUrl
|
||||
@@ -119,27 +192,28 @@ class RetrofitFactory(
|
||||
"$rpcUrl/"
|
||||
}
|
||||
|
||||
// 验证 RPC 是否可用
|
||||
validateRpcAvailability(actualRpcUrl)
|
||||
|
||||
// 创建 URL 替换拦截器
|
||||
val urlReplaceInterceptor = RpcUrlReplaceInterceptor(fixedBaseUrl, actualRpcUrl)
|
||||
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(urlReplaceInterceptor)
|
||||
.build()
|
||||
|
||||
// 创建 lenient 模式的 Gson
|
||||
val gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl(fixedBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(EthereumRpcApi::class.java)
|
||||
// 使用 RPC URL 作为缓存键
|
||||
return rpcApiCache.computeIfAbsent(actualRpcUrl) {
|
||||
// 验证 RPC 是否可用(仅在新创建时验证)
|
||||
validateRpcAvailability(actualRpcUrl)
|
||||
|
||||
// 使用固定的 baseUrl(Retrofit 要求 baseUrl 必须以 / 结尾)
|
||||
val fixedBaseUrl = "https://polyrpc.polyhermes/"
|
||||
|
||||
// 创建 URL 替换拦截器
|
||||
val urlReplaceInterceptor = RpcUrlReplaceInterceptor(fixedBaseUrl, actualRpcUrl)
|
||||
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(urlReplaceInterceptor)
|
||||
.build()
|
||||
|
||||
Retrofit.Builder()
|
||||
.baseUrl(fixedBaseUrl)
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(EthereumRpcApi::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -149,8 +223,6 @@ class RetrofitFactory(
|
||||
* @throws IllegalArgumentException 如果 RPC 不可用
|
||||
*/
|
||||
private fun validateRpcAvailability(rpcUrl: String) {
|
||||
val logger = LoggerFactory.getLogger(RetrofitFactory::class.java)
|
||||
|
||||
try {
|
||||
// 解析 URL
|
||||
val httpUrl = rpcUrl.toHttpUrlOrNull()
|
||||
@@ -218,56 +290,24 @@ class RetrofitFactory(
|
||||
/**
|
||||
* 创建 Polymarket Gamma API 客户端
|
||||
* Gamma API 是公开 API,不需要认证
|
||||
* @return PolymarketGammaApi 客户端
|
||||
* @return PolymarketGammaApi 客户端(单例)
|
||||
*/
|
||||
fun createGammaApi(): PolymarketGammaApi {
|
||||
val baseUrl = if (gammaBaseUrl.endsWith("/")) {
|
||||
gammaBaseUrl.dropLast(1)
|
||||
} else {
|
||||
gammaBaseUrl
|
||||
}
|
||||
val okHttpClient = createClient().build()
|
||||
|
||||
// 创建 lenient 模式的 Gson
|
||||
val gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketGammaApi::class.java)
|
||||
return gammaApi
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 Polymarket Data API 客户端
|
||||
* Data API 是公开 API,不需要认证
|
||||
* @return PolymarketDataApi 客户端
|
||||
* @return PolymarketDataApi 客户端(单例)
|
||||
*/
|
||||
fun createDataApi(): PolymarketDataApi {
|
||||
val baseUrl = "https://data-api.polymarket.com"
|
||||
val okHttpClient = createClient()
|
||||
.followRedirects(true)
|
||||
.followSslRedirects(true)
|
||||
.build()
|
||||
|
||||
// 创建 lenient 模式的 Gson
|
||||
val gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(PolymarketDataApi::class.java)
|
||||
return dataApi
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 Builder Relayer API 客户端
|
||||
* 按 relayerUrl 缓存,避免重复创建
|
||||
* @param relayerUrl Builder Relayer URL
|
||||
* @param apiKey Builder API Key
|
||||
* @param secret Builder Secret
|
||||
@@ -286,57 +326,61 @@ class RetrofitFactory(
|
||||
relayerUrl
|
||||
}
|
||||
|
||||
// 添加 Builder 认证拦截器
|
||||
val builderAuthInterceptor = BuilderAuthInterceptor(apiKey, secret, passphrase)
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(builderAuthInterceptor)
|
||||
.build()
|
||||
|
||||
val gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(BuilderRelayerApi::class.java)
|
||||
// 使用 baseUrl 作为缓存键(注意:如果 API Key 变化,需要清理缓存)
|
||||
return builderRelayerApiCache.computeIfAbsent(baseUrl) {
|
||||
// 添加 Builder 认证拦截器
|
||||
val builderAuthInterceptor = BuilderAuthInterceptor(apiKey, secret, passphrase)
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(builderAuthInterceptor)
|
||||
.build()
|
||||
|
||||
Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(BuilderRelayerApi::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 GitHub API 客户端
|
||||
* GitHub API 是公开 API,不需要认证(但建议使用 token 提高速率限制)
|
||||
* 添加 Accept 头以获取 reactions 数据
|
||||
* @return GitHubApi 客户端
|
||||
* @return GitHubApi 客户端(单例)
|
||||
*/
|
||||
fun createGitHubApi(): GitHubApi {
|
||||
val baseUrl = "https://api.github.com"
|
||||
|
||||
// 添加拦截器,设置 Accept 头以获取 reactions 数据
|
||||
val githubInterceptor = object : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request().newBuilder()
|
||||
.header("Accept", "application/vnd.github+json")
|
||||
.build()
|
||||
return chain.proceed(request)
|
||||
}
|
||||
}
|
||||
|
||||
val okHttpClient = createClient()
|
||||
.addInterceptor(githubInterceptor)
|
||||
.build()
|
||||
|
||||
val gson = GsonBuilder()
|
||||
.setLenient()
|
||||
.create()
|
||||
|
||||
return Retrofit.Builder()
|
||||
.baseUrl("$baseUrl/")
|
||||
.client(okHttpClient)
|
||||
.addConverterFactory(GsonConverterFactory.create(gson))
|
||||
.build()
|
||||
.create(GitHubApi::class.java)
|
||||
return githubApi
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理缓存(用于测试或配置变更时)
|
||||
*/
|
||||
@PreDestroy
|
||||
fun destroy() {
|
||||
logger.info("清理 RetrofitFactory 缓存")
|
||||
clobApiCache.clear()
|
||||
rpcApiCache.clear()
|
||||
builderRelayerApiCache.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定钱包地址的 CLOB API 缓存
|
||||
* 用于 API Key 变更时
|
||||
*/
|
||||
fun clearClobApiCache(walletAddress: String) {
|
||||
clobApiCache.remove(walletAddress)
|
||||
logger.debug("已清理 CLOB API 缓存: $walletAddress")
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定 RPC URL 的 RPC API 缓存
|
||||
* 用于 RPC 节点变更时
|
||||
*/
|
||||
fun clearRpcApiCache(rpcUrl: String) {
|
||||
val actualRpcUrl = if (rpcUrl.endsWith("/")) rpcUrl else "$rpcUrl/"
|
||||
rpcApiCache.remove(actualRpcUrl)
|
||||
logger.debug("已清理 RPC API 缓存: $actualRpcUrl")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,22 +437,35 @@ class ResponseLoggingInterceptor : Interceptor {
|
||||
val responseBody = response.peekBody(2048)
|
||||
val responseBodyString = responseBody.string()
|
||||
|
||||
// 检查是否是有效的 JSON
|
||||
val isJson = responseBodyString.trim().startsWith("{") ||
|
||||
responseBodyString.trim().startsWith("[")
|
||||
// 检查响应体是否为空
|
||||
val isEmpty = responseBodyString.isBlank()
|
||||
|
||||
if (!isJson || !response.isSuccessful) {
|
||||
// 检查是否是有效的 JSON
|
||||
val trimmedBody = responseBodyString.trim()
|
||||
val isJson = !isEmpty && (
|
||||
trimmedBody.startsWith("{") ||
|
||||
trimmedBody.startsWith("[")
|
||||
)
|
||||
|
||||
// 如果响应体为空或不是 JSON,记录警告
|
||||
if (isEmpty || !isJson) {
|
||||
val bodyPreview = if (isEmpty) {
|
||||
"(空响应体)"
|
||||
} else {
|
||||
trimmedBody.take(500)
|
||||
}
|
||||
logger.warn(
|
||||
"API 响应异常: method=${request.method}, url=${request.url}, " +
|
||||
"code=${response.code}, isJson=$isJson, " +
|
||||
"responseBody=${responseBodyString.take(500)}"
|
||||
"code=${response.code}, isJson=$isJson, isEmpty=$isEmpty, " +
|
||||
"responseBody=$bodyPreview"
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// 如果读取响应体失败,记录异常但不影响响应
|
||||
logger.debug("读取响应体失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,23 +40,12 @@ polymarket.rtds.ws-url=wss://ws-subscriptions-clob.polymarket.com
|
||||
polymarket.data-api.base-url=https://data-api.polymarket.com
|
||||
polymarket.gamma.base-url=https://gamma-api.polymarket.com
|
||||
|
||||
# Polygon RPC 配置(用于查询链上余额)
|
||||
# 可选:如果未配置,将无acc法查询 USDC 余额,但仍可通过 Subgraph API 查询持仓
|
||||
# 示例:https://polygon-rpc.com 或 https://polygon-mainnet.infura.io/v3/YOUR_PROJECT_ID
|
||||
polygon.rpc.url=${POLYGON_RPC_URL:https://polygon-rpc.com}
|
||||
|
||||
# Builder Relayer 配置(用于 Gasless 交易)
|
||||
# 从 polymarket.com/settings?tab=builder 获取 Builder API 凭证
|
||||
# Builder API Key、Secret、Passphrase 现在通过系统设置页面配置,存储在数据库中
|
||||
# 如果未配置,将使用手动发送交易的方式(需要用户支付 gas)
|
||||
polymarket.builder.relayer-url=${POLYMARKET_BUILDER_RELAYER_URL:https://relayer-v2.polymarket.com/}
|
||||
|
||||
# 仓位推送配置
|
||||
# 轮询间隔(毫秒),默认3秒
|
||||
position.push.polling-interval=${POSITION_PUSH_POLLING_INTERVAL:3000}
|
||||
# 心跳超时时间(毫秒),默认60秒,超过此时间未收到心跳则清理连接
|
||||
position.push.heartbeat-timeout=${POSITION_PUSH_HEARTBEAT_TIMEOUT:60000}
|
||||
|
||||
# 跟单轮询配置
|
||||
# 轮询间隔(毫秒),默认2秒
|
||||
copy.trading.polling.interval=${COPY_TRADING_POLLING_INTERVAL:2000}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- ============================================
|
||||
-- V16: 删除失败交易记录表
|
||||
-- 移除下单失败存储到数据库的功能
|
||||
-- ============================================
|
||||
|
||||
-- 删除失败交易记录表
|
||||
DROP TABLE IF EXISTS failed_trade;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
-- ============================================
|
||||
-- 添加 wallet_type 字段到 wallet_accounts 表
|
||||
-- 用于区分 Magic 和 Safe 两种钱包类型
|
||||
-- ============================================
|
||||
|
||||
-- 使用存储过程检查并添加字段(如果不存在)
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE IF NOT EXISTS add_wallet_type_if_not_exists()
|
||||
BEGIN
|
||||
DECLARE column_exists INT DEFAULT 0;
|
||||
|
||||
SELECT COUNT(*) INTO column_exists
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'wallet_accounts'
|
||||
AND COLUMN_NAME = 'wallet_type';
|
||||
|
||||
IF column_exists = 0 THEN
|
||||
ALTER TABLE wallet_accounts
|
||||
ADD COLUMN wallet_type VARCHAR(20) NOT NULL DEFAULT 'magic' COMMENT '钱包类型:magic(邮箱/OAuth登录)或 safe(MetaMask浏览器钱包)' AFTER is_enabled;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
-- 执行存储过程
|
||||
CALL add_wallet_type_if_not_exists();
|
||||
|
||||
-- 删除存储过程
|
||||
DROP PROCEDURE IF EXISTS add_wallet_type_if_not_exists;
|
||||
|
||||
-- 为现有账户设置默认walletType为magic(如果值为NULL)
|
||||
UPDATE wallet_accounts SET wallet_type = 'magic' WHERE wallet_type IS NULL OR wallet_type = '';
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- ============================================
|
||||
-- V18: 增加 copy_ratio 字段的精度,支持更小的小数值
|
||||
-- ============================================
|
||||
|
||||
-- 修改 copy_trading 表的 copy_ratio 字段精度
|
||||
-- 从 DECIMAL(10, 2) 改为 DECIMAL(20, 8),支持更小的跟单比例值(如 0.001)
|
||||
ALTER TABLE copy_trading
|
||||
MODIFY COLUMN copy_ratio DECIMAL(20, 8) NOT NULL DEFAULT 1.00000000 COMMENT '跟单比例(仅在copyMode=RATIO时生效)';
|
||||
|
||||
-- 修改 copy_trading_templates 表的 copy_ratio 字段精度
|
||||
-- 从 DECIMAL(10, 2) 改为 DECIMAL(20, 8),支持更小的跟单比例值(如 0.001)
|
||||
ALTER TABLE copy_trading_templates
|
||||
MODIFY COLUMN copy_ratio DECIMAL(20, 8) NOT NULL DEFAULT 1.00000000 COMMENT '跟单比例(仅在copyMode=RATIO时生效)';
|
||||
|
||||
@@ -71,9 +71,6 @@ SERVER_PORT=80
|
||||
# MySQL 端口(可选,用于外部连接,默认 3307 避免与本地 MySQL 冲突)
|
||||
MYSQL_PORT=3307
|
||||
|
||||
# Polygon RPC
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
|
||||
# JWT 密钥(已自动生成随机值,生产环境建议修改)
|
||||
JWT_SECRET=${JWT_SECRET}
|
||||
|
||||
@@ -159,7 +156,18 @@ deploy() {
|
||||
# 注意:这里需要手动修改 docker-compose.yml,或者使用环境变量
|
||||
warn "请确保 docker-compose.yml 中已配置使用 image: wrbug/polyhermes:latest"
|
||||
else
|
||||
info "构建 Docker 镜像(本地构建,版本号将显示为 dev)..."
|
||||
# 获取当前分支名作为版本号
|
||||
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "dev")
|
||||
# 如果分支名包含 /,替换为 -(Docker tag 不支持 /)
|
||||
DOCKER_VERSION=$(echo "$CURRENT_BRANCH" | tr '/' '-')
|
||||
|
||||
info "构建 Docker 镜像(本地构建,版本号: ${DOCKER_VERSION})..."
|
||||
|
||||
# 设置构建参数(通过环境变量传递给 docker-compose.yml)
|
||||
export VERSION=${DOCKER_VERSION}
|
||||
export GIT_TAG=${DOCKER_VERSION}
|
||||
export GITHUB_REPO_URL=https://github.com/WrBug/PolyHermes
|
||||
|
||||
docker-compose build
|
||||
fi
|
||||
|
||||
@@ -199,7 +207,9 @@ main() {
|
||||
info "访问地址: http://localhost:${SERVER_PORT:-80}"
|
||||
echo ""
|
||||
if [ "$USE_DOCKER_HUB" != "true" ]; then
|
||||
info "提示:本地构建的版本号显示为 'dev'"
|
||||
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "dev")
|
||||
DOCKER_VERSION=$(echo "$CURRENT_BRANCH" | tr '/' '-')
|
||||
info "提示:本地构建的版本号为当前分支名: ${DOCKER_VERSION}"
|
||||
info "生产环境推荐使用 Docker Hub 镜像:"
|
||||
info " ./deploy.sh --use-docker-hub"
|
||||
info " 或修改 docker-compose.yml 使用 image: wrbug/polyhermes:latest"
|
||||
|
||||
@@ -38,12 +38,6 @@ SERVER_PORT=80
|
||||
# Optional, for external connections, default 3307 to avoid conflicts with local MySQL
|
||||
MYSQL_PORT=3307
|
||||
|
||||
# ============================================
|
||||
# Polygon RPC
|
||||
# ============================================
|
||||
# Polygon 网络 RPC 地址 / Polygon network RPC address
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
|
||||
# ============================================
|
||||
# 安全配置 / Security Configuration
|
||||
# ============================================
|
||||
|
||||
@@ -24,7 +24,6 @@ services:
|
||||
- DB_USERNAME=${DB_USERNAME:-root}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-}
|
||||
- SERVER_PORT=8000
|
||||
- POLYGON_RPC_URL=${POLYGON_RPC_URL:-https://polygon-rpc.com}
|
||||
# ⚠️ 安全警告:以下两个环境变量不能使用默认值,否则容器启动会失败
|
||||
# 请在 .env 文件中设置,或通过环境变量传入
|
||||
# 生成随机密钥:openssl rand -hex 32 (ADMIN_RESET_PASSWORD_KEY) 或 openssl rand -hex 64 (JWT_SECRET)
|
||||
|
||||
+5
-6
@@ -8,11 +8,11 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
# 本地构建时可以传递版本号参数(可选)
|
||||
# args:
|
||||
# VERSION: ${VERSION:-dev}
|
||||
# GIT_TAG: ${GIT_TAG:-}
|
||||
# GITHUB_REPO_URL: https://github.com/WrBug/PolyHermes
|
||||
# 本地构建时可以传递版本号参数(自动使用当前分支名)
|
||||
args:
|
||||
VERSION: ${VERSION:-dev}
|
||||
GIT_TAG: ${GIT_TAG:-${VERSION:-dev}}
|
||||
GITHUB_REPO_URL: ${GITHUB_REPO_URL:-https://github.com/WrBug/PolyHermes}
|
||||
container_name: polyhermes
|
||||
ports:
|
||||
- "${SERVER_PORT:-80}:80"
|
||||
@@ -22,7 +22,6 @@ services:
|
||||
- DB_USERNAME=${DB_USERNAME:-root}
|
||||
- DB_PASSWORD=${DB_PASSWORD:-}
|
||||
- SERVER_PORT=8000
|
||||
- POLYGON_RPC_URL=${POLYGON_RPC_URL:-https://polygon-rpc.com}
|
||||
# ⚠️ 安全警告:以下两个环境变量不能使用默认值,否则容器启动会失败
|
||||
# 请在 .env 文件中设置,或通过环境变量传入
|
||||
# 生成随机密钥:openssl rand -hex 32 (ADMIN_RESET_PASSWORD_KEY) 或 openssl rand -hex 64 (JWT_SECRET)
|
||||
|
||||
@@ -163,7 +163,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -393,7 +392,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=8000
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -554,7 +552,6 @@ serve -s dist -l 3000
|
||||
| `DB_USERNAME` | Database username | `root` | Yes (Production) |
|
||||
| `DB_PASSWORD` | Database password | - | Yes (Production) |
|
||||
| `SERVER_PORT` | Server port | `8000` | No |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC address | `https://polygon-rpc.com` | No |
|
||||
| `JWT_SECRET` | JWT secret key | - | Yes (Production) |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | Admin password reset key | - | Yes (Production) |
|
||||
|
||||
|
||||
@@ -100,9 +100,6 @@ spring.datasource.password=${DB_PASSWORD:password}
|
||||
# Server port
|
||||
server.port=${SERVER_PORT:8000}
|
||||
|
||||
# Polygon RPC
|
||||
polygon.rpc.url=${POLYGON_RPC_URL:https://polygon-rpc.com}
|
||||
|
||||
# JWT secret
|
||||
jwt.secret=${JWT_SECRET:change-me-in-production}
|
||||
|
||||
|
||||
@@ -165,7 +165,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=80
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -397,7 +396,6 @@ DB_USERNAME=root
|
||||
DB_PASSWORD=your_password_here
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
SERVER_PORT=8000
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
JWT_SECRET=your-jwt-secret-key-change-in-production
|
||||
ADMIN_RESET_PASSWORD_KEY=your-admin-reset-key-change-in-production
|
||||
EOF
|
||||
@@ -558,7 +556,6 @@ serve -s dist -l 3000
|
||||
| `DB_USERNAME` | 数据库用户名 | `root` | 是(生产) |
|
||||
| `DB_PASSWORD` | 数据库密码 | - | 是(生产) |
|
||||
| `SERVER_PORT` | 服务器端口 | `8000` | 否 |
|
||||
| `POLYGON_RPC_URL` | Polygon RPC 地址 | `https://polygon-rpc.com` | 否 |
|
||||
| `JWT_SECRET` | JWT 密钥 | - | 是(生产) |
|
||||
| `ADMIN_RESET_PASSWORD_KEY` | 管理员密码重置密钥 | - | 是(生产) |
|
||||
|
||||
|
||||
@@ -93,9 +93,6 @@ spring.datasource.password=${DB_PASSWORD:password}
|
||||
# 服务器端口
|
||||
server.port=${SERVER_PORT:8000}
|
||||
|
||||
# Polygon RPC
|
||||
polygon.rpc.url=${POLYGON_RPC_URL:https://polygon-rpc.com}
|
||||
|
||||
# JWT 密钥
|
||||
jwt.secret=${JWT_SECRET:change-me-in-production}
|
||||
|
||||
|
||||
@@ -0,0 +1,836 @@
|
||||
# Polymarket 聪明钱分析方案
|
||||
|
||||
## 1. 概述
|
||||
|
||||
聪明钱(Smart Money)分析是指识别和跟踪在 Polymarket 平台上表现优异的交易者,通过分析他们的交易行为、持仓和盈亏表现,来辅助投资决策。
|
||||
|
||||
## 2. 核心分析维度
|
||||
|
||||
### 2.1 交易表现指标
|
||||
|
||||
#### 2.1.1 胜率(Win Rate)
|
||||
- **定义**:盈利交易数 / 总交易数
|
||||
- **计算方式**:
|
||||
- 通过 `getUserActivity` API 获取用户历史交易
|
||||
- 筛选 `type = "TRADE"` 的活动
|
||||
- 计算每笔交易的盈亏(通过买入价和卖出价)
|
||||
- 统计盈利交易数和总交易数
|
||||
|
||||
#### 2.1.2 平均盈亏比(Average PnL Ratio)
|
||||
- **定义**:平均盈利金额 / 平均亏损金额
|
||||
- **计算方式**:
|
||||
- 分别计算盈利交易和亏损交易的平均金额
|
||||
- 计算比值
|
||||
|
||||
#### 2.1.3 总盈亏(Total PnL)
|
||||
- **定义**:所有已实现盈亏的总和
|
||||
- **数据来源**:
|
||||
- 通过 `getPositions` API 获取 `realizedPnl`
|
||||
- 或通过 `getUserActivity` API 计算历史交易的累计盈亏
|
||||
|
||||
#### 2.1.4 未实现盈亏(Unrealized PnL)
|
||||
- **定义**:当前持仓的浮动盈亏
|
||||
- **数据来源**:
|
||||
- 通过 `getPositions` API 获取 `cashPnl`(当前盈亏)
|
||||
- 或通过 `currentValue - initialValue` 计算
|
||||
|
||||
#### 2.1.5 收益率(Return Rate)
|
||||
- **定义**:总盈亏 / 总投入
|
||||
- **计算方式**:
|
||||
- 总投入 = 所有买入交易的总金额
|
||||
- 总盈亏 = 已实现盈亏 + 未实现盈亏
|
||||
- 收益率 = 总盈亏 / 总投入
|
||||
|
||||
### 2.2 交易行为指标
|
||||
|
||||
#### 2.2.1 交易频率(Trading Frequency)
|
||||
- **定义**:单位时间内的交易次数
|
||||
- **计算方式**:
|
||||
- 通过 `getUserActivity` API 获取指定时间范围内的交易数
|
||||
- 计算日均/周均交易次数
|
||||
|
||||
#### 2.2.2 持仓周期(Holding Period)
|
||||
- **定义**:平均持仓时间
|
||||
- **计算方式**:
|
||||
- 跟踪每笔买入和对应的卖出时间
|
||||
- 计算平均持仓天数
|
||||
|
||||
#### 2.2.3 市场偏好(Market Preference)
|
||||
- **定义**:交易者偏好的市场类型
|
||||
- **计算方式**:
|
||||
- 统计交易者在不同分类(sports、crypto)的交易分布
|
||||
- 统计交易者偏好的市场主题
|
||||
|
||||
#### 2.2.4 仓位规模(Position Size)
|
||||
- **定义**:平均单笔交易金额
|
||||
- **计算方式**:
|
||||
- 通过 `getUserActivity` API 获取 `usdcSize`
|
||||
- 计算平均交易金额
|
||||
|
||||
### 2.3 风险指标
|
||||
|
||||
#### 2.3.1 最大回撤(Maximum Drawdown)
|
||||
- **定义**:从峰值到谷值的最大跌幅
|
||||
- **计算方式**:
|
||||
- 跟踪账户价值的时序变化
|
||||
- 计算每个峰值的回撤幅度
|
||||
- 取最大值
|
||||
|
||||
#### 2.3.2 夏普比率(Sharpe Ratio)
|
||||
- **定义**:风险调整后的收益率
|
||||
- **计算方式**:
|
||||
- 收益率标准差 / 平均收益率
|
||||
- 需要足够的历史数据
|
||||
|
||||
#### 2.3.3 胜率稳定性(Win Rate Stability)
|
||||
- **定义**:不同时间段胜率的一致性
|
||||
- **计算方式**:
|
||||
- 按时间段(如每月)计算胜率
|
||||
- 计算胜率的方差或标准差
|
||||
|
||||
## 3. 数据收集方法
|
||||
|
||||
### 3.1 使用 Polymarket Data API
|
||||
|
||||
#### 3.1.1 获取用户仓位
|
||||
```kotlin
|
||||
// 接口:GET /positions
|
||||
// 参数:
|
||||
// - user: 用户钱包地址(必需)
|
||||
// - market: 市场ID(可选)
|
||||
// - limit: 限制数量(可选)
|
||||
// - offset: 偏移量(可选)
|
||||
// - sortBy: 排序字段(可选,如 "currentValue")
|
||||
// - sortDirection: 排序方向(可选,如 "desc")
|
||||
|
||||
val positions = dataApi.getPositions(
|
||||
user = walletAddress,
|
||||
limit = 100,
|
||||
sortBy = "currentValue",
|
||||
sortDirection = "desc"
|
||||
)
|
||||
```
|
||||
|
||||
**返回数据包含**:
|
||||
- `currentValue`: 当前仓位价值
|
||||
- `cashPnl`: 当前盈亏(未实现)
|
||||
- `realizedPnl`: 已实现盈亏
|
||||
- `percentPnl`: 盈亏百分比
|
||||
- `avgPrice`: 平均买入价
|
||||
- `curPrice`: 当前价格
|
||||
|
||||
#### 3.1.2 获取用户活动(交易历史)
|
||||
```kotlin
|
||||
// 接口:GET /activity
|
||||
// 参数:
|
||||
// - user: 用户钱包地址(必需)
|
||||
// - type: 活动类型(可选,如 ["TRADE"])
|
||||
// - side: 交易方向(可选,如 "BUY" 或 "SELL")
|
||||
// - start: 开始时间戳(可选)
|
||||
// - end: 结束时间戳(可选)
|
||||
// - limit: 限制数量(可选)
|
||||
// - offset: 偏移量(可选)
|
||||
|
||||
val activities = dataApi.getUserActivity(
|
||||
user = walletAddress,
|
||||
type = listOf("TRADE"),
|
||||
side = "BUY",
|
||||
start = startTimestamp,
|
||||
end = endTimestamp,
|
||||
limit = 1000
|
||||
)
|
||||
```
|
||||
|
||||
**返回数据包含**:
|
||||
- `type`: 活动类型(TRADE、SPLIT、MERGE、REDEEM等)
|
||||
- `side`: 交易方向(BUY、SELL)
|
||||
- `size`: 交易数量
|
||||
- `usdcSize`: 交易金额(USDC)
|
||||
- `price`: 交易价格
|
||||
- `timestamp`: 交易时间戳
|
||||
- `title`: 市场标题
|
||||
- `slug`: 市场标识
|
||||
|
||||
#### 3.1.3 获取仓位总价值
|
||||
```kotlin
|
||||
// 接口:GET /value
|
||||
// 参数:
|
||||
// - user: 用户钱包地址(必需)
|
||||
// - market: 市场ID列表(可选)
|
||||
|
||||
val totalValue = dataApi.getTotalValue(
|
||||
user = walletAddress,
|
||||
market = listOf("market1", "market2")
|
||||
)
|
||||
```
|
||||
|
||||
### 3.2 使用 Polymarket CLOB API
|
||||
|
||||
#### 3.2.1 获取交易记录
|
||||
```kotlin
|
||||
// 接口:GET /data/trades
|
||||
// 参数:
|
||||
// - maker_address: 交易者地址(可选)
|
||||
// - market: 市场ID(可选)
|
||||
// - before: 之前的时间戳(可选,用于分页)
|
||||
// - after: 之后的时间戳(可选,用于分页)
|
||||
// - next_cursor: 分页游标(可选)
|
||||
|
||||
val trades = clobApi.getTrades(
|
||||
maker_address = walletAddress,
|
||||
market = marketId,
|
||||
after = startTimestamp.toString()
|
||||
)
|
||||
```
|
||||
|
||||
**返回数据包含**:
|
||||
- `id`: 交易ID
|
||||
- `market`: 市场ID
|
||||
- `side`: 交易方向(BUY、SELL)
|
||||
- `price`: 交易价格
|
||||
- `size`: 交易数量
|
||||
- `timestamp`: 交易时间戳
|
||||
- `user`: 交易者地址
|
||||
|
||||
## 4. 聪明钱识别算法
|
||||
|
||||
### 4.1 基础筛选条件
|
||||
|
||||
#### 4.1.1 最低交易次数
|
||||
- **条件**:总交易数 >= 50
|
||||
- **目的**:确保有足够的数据进行统计分析
|
||||
|
||||
#### 4.1.2 最低胜率
|
||||
- **条件**:胜率 >= 55%
|
||||
- **目的**:筛选出表现优于随机交易者
|
||||
|
||||
#### 4.1.3 最低总盈亏
|
||||
- **条件**:总盈亏 >= 1000 USDC
|
||||
- **目的**:筛选出有实际盈利能力的交易者
|
||||
|
||||
#### 4.1.4 最低收益率
|
||||
- **条件**:收益率 >= 20%
|
||||
- **目的**:筛选出有良好回报的交易者
|
||||
|
||||
### 4.2 综合评分算法
|
||||
|
||||
```kotlin
|
||||
// 聪明钱评分算法
|
||||
fun calculateSmartMoneyScore(
|
||||
winRate: Double, // 胜率(0-1)
|
||||
totalPnl: Double, // 总盈亏(USDC)
|
||||
returnRate: Double, // 收益率(0-1)
|
||||
tradeCount: Int, // 交易次数
|
||||
avgPnlRatio: Double // 平均盈亏比
|
||||
): Double {
|
||||
// 权重配置
|
||||
val winRateWeight = 0.3
|
||||
val totalPnlWeight = 0.25
|
||||
val returnRateWeight = 0.25
|
||||
val tradeCountWeight = 0.1
|
||||
val avgPnlRatioWeight = 0.1
|
||||
|
||||
// 归一化处理
|
||||
val normalizedWinRate = winRate * 100 // 转换为百分比
|
||||
val normalizedTotalPnl = min(totalPnl / 10000, 1.0) * 100 // 归一化到0-100
|
||||
val normalizedReturnRate = returnRate * 100 // 转换为百分比
|
||||
val normalizedTradeCount = min(tradeCount / 200, 1.0) * 100 // 归一化到0-100
|
||||
val normalizedAvgPnlRatio = min(avgPnlRatio / 3.0, 1.0) * 100 // 归一化到0-100
|
||||
|
||||
// 加权求和
|
||||
val score = normalizedWinRate * winRateWeight +
|
||||
normalizedTotalPnl * totalPnlWeight +
|
||||
normalizedReturnRate * returnRateWeight +
|
||||
normalizedTradeCount * tradeCountWeight +
|
||||
normalizedAvgPnlRatio * avgPnlRatioWeight
|
||||
|
||||
return score
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 排名算法
|
||||
|
||||
1. **按综合评分排序**:计算所有候选交易者的综合评分,按降序排列
|
||||
2. **按分类排名**:分别计算 sports 和 crypto 分类的排名
|
||||
3. **按时间段排名**:分别计算最近7天、30天、90天的排名
|
||||
|
||||
## 5. 实时监控方案
|
||||
|
||||
### 5.1 监控目标
|
||||
|
||||
1. **新交易**:监控聪明钱交易者的新买入/卖出交易
|
||||
2. **持仓变化**:监控聪明钱交易者的持仓变化
|
||||
3. **市场关注**:监控聪明钱交易者关注的新市场
|
||||
|
||||
### 5.2 实现方式
|
||||
|
||||
#### 5.2.1 使用 WebSocket(推荐)
|
||||
- 订阅 Polymarket WebSocket 的 User Channel
|
||||
- 监听 `event_type = "trade"` 事件
|
||||
- 过滤出聪明钱交易者的交易
|
||||
|
||||
#### 5.2.2 使用轮询
|
||||
- 定期调用 `getUserActivity` API(如每5分钟)
|
||||
- 比较时间戳,识别新交易
|
||||
- 使用 `after` 参数只获取新数据
|
||||
|
||||
### 5.3 跟单集成
|
||||
|
||||
聪明钱分析可以与现有的跟单系统集成:
|
||||
|
||||
1. **自动添加 Leader**:识别到聪明钱交易者后,自动添加到 Leader 列表
|
||||
2. **智能跟单**:根据聪明钱交易者的表现,动态调整跟单比例
|
||||
3. **风险控制**:根据聪明钱交易者的风险指标,设置跟单限制
|
||||
|
||||
## 6. 实现示例
|
||||
|
||||
### 6.1 聪明钱分析服务
|
||||
|
||||
```kotlin
|
||||
@Service
|
||||
class SmartMoneyAnalysisService(
|
||||
private val retrofitFactory: RetrofitFactory,
|
||||
private val blockchainService: BlockchainService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(SmartMoneyAnalysisService::class.java)
|
||||
private val dataApi = retrofitFactory.createDataApi()
|
||||
|
||||
/**
|
||||
* 分析单个交易者的表现
|
||||
*/
|
||||
suspend fun analyzeTrader(walletAddress: String, days: Int = 90): Result<TraderAnalysis> {
|
||||
return try {
|
||||
val endTime = System.currentTimeMillis()
|
||||
val startTime = endTime - (days * 24 * 60 * 60 * 1000L)
|
||||
|
||||
// 1. 获取交易历史
|
||||
val activitiesResult = getTradeActivities(walletAddress, startTime, endTime)
|
||||
if (activitiesResult.isFailure) {
|
||||
return Result.failure(activitiesResult.exceptionOrNull() ?: Exception("获取交易历史失败"))
|
||||
}
|
||||
val activities = activitiesResult.getOrNull() ?: emptyList()
|
||||
|
||||
// 2. 获取当前仓位
|
||||
val positionsResult = blockchainService.getPositions(walletAddress)
|
||||
val positions = if (positionsResult.isSuccess) {
|
||||
positionsResult.getOrNull() ?: emptyList()
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
// 3. 计算指标
|
||||
val metrics = calculateMetrics(activities, positions)
|
||||
|
||||
// 4. 计算综合评分
|
||||
val score = calculateSmartMoneyScore(
|
||||
winRate = metrics.winRate,
|
||||
totalPnl = metrics.totalPnl,
|
||||
returnRate = metrics.returnRate,
|
||||
tradeCount = metrics.tradeCount,
|
||||
avgPnlRatio = metrics.avgPnlRatio
|
||||
)
|
||||
|
||||
Result.success(
|
||||
TraderAnalysis(
|
||||
walletAddress = walletAddress,
|
||||
metrics = metrics,
|
||||
score = score,
|
||||
positions = positions.size,
|
||||
lastTradeTime = activities.maxByOrNull { it.timestamp }?.timestamp
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
logger.error("分析交易者失败: ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取交易活动
|
||||
*/
|
||||
private suspend fun getTradeActivities(
|
||||
walletAddress: String,
|
||||
startTime: Long,
|
||||
endTime: Long
|
||||
): Result<List<UserActivityResponse>> {
|
||||
return try {
|
||||
val response = dataApi.getUserActivity(
|
||||
user = walletAddress,
|
||||
type = listOf("TRADE"),
|
||||
start = startTime,
|
||||
end = endTime,
|
||||
limit = 1000,
|
||||
sortBy = "timestamp",
|
||||
sortDirection = "desc"
|
||||
)
|
||||
|
||||
if (response.isSuccessful && response.body() != null) {
|
||||
Result.success(response.body()!!)
|
||||
} else {
|
||||
Result.failure(Exception("获取交易活动失败: ${response.code()} ${response.message()}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取交易活动异常: ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算交易指标
|
||||
*/
|
||||
private fun calculateMetrics(
|
||||
activities: List<UserActivityResponse>,
|
||||
positions: List<PositionResponse>
|
||||
): TraderMetrics {
|
||||
// 分离买入和卖出交易
|
||||
val buyTrades = activities.filter { it.side == "BUY" }
|
||||
val sellTrades = activities.filter { it.side == "SELL" }
|
||||
|
||||
// 计算总交易数
|
||||
val tradeCount = activities.size
|
||||
|
||||
// 计算总投入(买入金额总和)
|
||||
val totalInvested = buyTrades.sumOf { it.usdcSize ?: 0.0 }
|
||||
|
||||
// 计算已实现盈亏(从仓位数据)
|
||||
val realizedPnl = positions.sumOf { it.realizedPnl ?: 0.0 }
|
||||
|
||||
// 计算未实现盈亏(从仓位数据)
|
||||
val unrealizedPnl = positions.sumOf { it.cashPnl ?: 0.0 }
|
||||
|
||||
// 计算总盈亏
|
||||
val totalPnl = realizedPnl + unrealizedPnl
|
||||
|
||||
// 计算收益率
|
||||
val returnRate = if (totalInvested > 0) {
|
||||
totalPnl / totalInvested
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
|
||||
// 计算胜率(需要匹配买入和卖出交易)
|
||||
val winRate = calculateWinRate(buyTrades, sellTrades)
|
||||
|
||||
// 计算平均盈亏比
|
||||
val avgPnlRatio = calculateAvgPnlRatio(buyTrades, sellTrades)
|
||||
|
||||
return TraderMetrics(
|
||||
tradeCount = tradeCount,
|
||||
totalInvested = totalInvested,
|
||||
totalPnl = totalPnl,
|
||||
realizedPnl = realizedPnl,
|
||||
unrealizedPnl = unrealizedPnl,
|
||||
returnRate = returnRate,
|
||||
winRate = winRate,
|
||||
avgPnlRatio = avgPnlRatio
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算胜率
|
||||
* 通过匹配买入和卖出交易来计算
|
||||
*/
|
||||
private fun calculateWinRate(
|
||||
buyTrades: List<UserActivityResponse>,
|
||||
sellTrades: List<UserActivityResponse>
|
||||
): Double {
|
||||
// 按市场分组买入和卖出交易
|
||||
val buyByMarket = buyTrades.groupBy { it.conditionId }
|
||||
val sellByMarket = sellTrades.groupBy { it.conditionId }
|
||||
|
||||
var winCount = 0
|
||||
var totalCount = 0
|
||||
|
||||
// 遍历每个市场
|
||||
buyByMarket.forEach { (marketId, buys) ->
|
||||
val sells = sellByMarket[marketId] ?: emptyList()
|
||||
|
||||
// 简单匹配:按时间顺序匹配买入和卖出
|
||||
// 实际应该使用更精确的匹配算法(如 FIFO)
|
||||
var buyIndex = 0
|
||||
var sellIndex = 0
|
||||
|
||||
while (buyIndex < buys.size && sellIndex < sells.size) {
|
||||
val buy = buys[buyIndex]
|
||||
val sell = sells[sellIndex]
|
||||
|
||||
// 计算盈亏
|
||||
val buyPrice = buy.price ?: 0.0
|
||||
val sellPrice = sell.price ?: 0.0
|
||||
val pnl = (sellPrice - buyPrice) * (buy.size ?: 0.0)
|
||||
|
||||
if (pnl > 0) {
|
||||
winCount++
|
||||
}
|
||||
totalCount++
|
||||
|
||||
buyIndex++
|
||||
sellIndex++
|
||||
}
|
||||
}
|
||||
|
||||
return if (totalCount > 0) {
|
||||
winCount.toDouble() / totalCount
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算平均盈亏比
|
||||
*/
|
||||
private fun calculateAvgPnlRatio(
|
||||
buyTrades: List<UserActivityResponse>,
|
||||
sellTrades: List<UserActivityResponse>
|
||||
): Double {
|
||||
// 类似胜率计算,分别计算盈利和亏损的平均金额
|
||||
val buyByMarket = buyTrades.groupBy { it.conditionId }
|
||||
val sellByMarket = sellTrades.groupBy { it.conditionId }
|
||||
|
||||
val profits = mutableListOf<Double>()
|
||||
val losses = mutableListOf<Double>()
|
||||
|
||||
buyByMarket.forEach { (marketId, buys) ->
|
||||
val sells = sellByMarket[marketId] ?: emptyList()
|
||||
|
||||
var buyIndex = 0
|
||||
var sellIndex = 0
|
||||
|
||||
while (buyIndex < buys.size && sellIndex < sells.size) {
|
||||
val buy = buys[buyIndex]
|
||||
val sell = sells[sellIndex]
|
||||
|
||||
val buyPrice = buy.price ?: 0.0
|
||||
val sellPrice = sell.price ?: 0.0
|
||||
val pnl = (sellPrice - buyPrice) * (buy.size ?: 0.0)
|
||||
|
||||
if (pnl > 0) {
|
||||
profits.add(pnl)
|
||||
} else if (pnl < 0) {
|
||||
losses.add(-pnl)
|
||||
}
|
||||
|
||||
buyIndex++
|
||||
sellIndex++
|
||||
}
|
||||
}
|
||||
|
||||
val avgProfit = if (profits.isNotEmpty()) {
|
||||
profits.average()
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
|
||||
val avgLoss = if (losses.isNotEmpty()) {
|
||||
losses.average()
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
|
||||
return if (avgLoss > 0) {
|
||||
avgProfit / avgLoss
|
||||
} else {
|
||||
if (avgProfit > 0) Double.MAX_VALUE else 0.0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算聪明钱评分
|
||||
*/
|
||||
private fun calculateSmartMoneyScore(
|
||||
winRate: Double,
|
||||
totalPnl: Double,
|
||||
returnRate: Double,
|
||||
tradeCount: Int,
|
||||
avgPnlRatio: Double
|
||||
): Double {
|
||||
val winRateWeight = 0.3
|
||||
val totalPnlWeight = 0.25
|
||||
val returnRateWeight = 0.25
|
||||
val tradeCountWeight = 0.1
|
||||
val avgPnlRatioWeight = 0.1
|
||||
|
||||
val normalizedWinRate = winRate * 100
|
||||
val normalizedTotalPnl = min(totalPnl / 10000, 1.0) * 100
|
||||
val normalizedReturnRate = returnRate * 100
|
||||
val normalizedTradeCount = min(tradeCount / 200.0, 1.0) * 100
|
||||
val normalizedAvgPnlRatio = min(avgPnlRatio / 3.0, 1.0) * 100
|
||||
|
||||
val score = normalizedWinRate * winRateWeight +
|
||||
normalizedTotalPnl * totalPnlWeight +
|
||||
normalizedReturnRate * returnRateWeight +
|
||||
normalizedTradeCount * tradeCountWeight +
|
||||
normalizedAvgPnlRatio * avgPnlRatioWeight
|
||||
|
||||
return score
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量分析交易者
|
||||
*/
|
||||
suspend fun analyzeTraders(
|
||||
walletAddresses: List<String>,
|
||||
days: Int = 90
|
||||
): Result<List<TraderAnalysis>> {
|
||||
return try {
|
||||
val analyses = walletAddresses.mapNotNull { address ->
|
||||
analyzeTrader(address, days).getOrNull()
|
||||
}
|
||||
Result.success(analyses.sortedByDescending { it.score })
|
||||
} catch (e: Exception) {
|
||||
logger.error("批量分析交易者失败: ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 交易者分析结果
|
||||
*/
|
||||
data class TraderAnalysis(
|
||||
val walletAddress: String,
|
||||
val metrics: TraderMetrics,
|
||||
val score: Double,
|
||||
val positions: Int,
|
||||
val lastTradeTime: Long?
|
||||
)
|
||||
|
||||
/**
|
||||
* 交易者指标
|
||||
*/
|
||||
data class TraderMetrics(
|
||||
val tradeCount: Int,
|
||||
val totalInvested: Double,
|
||||
val totalPnl: Double,
|
||||
val realizedPnl: Double,
|
||||
val unrealizedPnl: Double,
|
||||
val returnRate: Double,
|
||||
val winRate: Double,
|
||||
val avgPnlRatio: Double
|
||||
)
|
||||
```
|
||||
|
||||
### 6.2 聪明钱排名服务
|
||||
|
||||
```kotlin
|
||||
@Service
|
||||
class SmartMoneyRankingService(
|
||||
private val smartMoneyAnalysisService: SmartMoneyAnalysisService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(SmartMoneyRankingService::class.java)
|
||||
|
||||
/**
|
||||
* 获取聪明钱排名
|
||||
*/
|
||||
suspend fun getRankings(
|
||||
category: String? = null, // sports 或 crypto
|
||||
days: Int = 90,
|
||||
limit: Int = 100
|
||||
): Result<List<TraderRanking>> {
|
||||
return try {
|
||||
// 1. 获取候选交易者列表
|
||||
// 这里需要从某个数据源获取(如数据库、API等)
|
||||
val candidates = getCandidateTraders(category)
|
||||
|
||||
// 2. 批量分析交易者
|
||||
val analysesResult = smartMoneyAnalysisService.analyzeTraders(candidates, days)
|
||||
if (analysesResult.isFailure) {
|
||||
return Result.failure(analysesResult.exceptionOrNull() ?: Exception("分析失败"))
|
||||
}
|
||||
val analyses = analysesResult.getOrNull() ?: emptyList()
|
||||
|
||||
// 3. 筛选和排序
|
||||
val rankings = analyses
|
||||
.filter { it.metrics.tradeCount >= 50 } // 最低交易次数
|
||||
.filter { it.metrics.winRate >= 0.55 } // 最低胜率
|
||||
.filter { it.metrics.totalPnl >= 1000 } // 最低总盈亏
|
||||
.sortedByDescending { it.score }
|
||||
.take(limit)
|
||||
.mapIndexed { index, analysis ->
|
||||
TraderRanking(
|
||||
rank = index + 1,
|
||||
walletAddress = analysis.walletAddress,
|
||||
score = analysis.score,
|
||||
metrics = analysis.metrics,
|
||||
positions = analysis.positions,
|
||||
lastTradeTime = analysis.lastTradeTime
|
||||
)
|
||||
}
|
||||
|
||||
Result.success(rankings)
|
||||
} catch (e: Exception) {
|
||||
logger.error("获取排名失败: ${e.message}", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取候选交易者列表
|
||||
* 这里需要实现具体的获取逻辑(如从数据库、API等)
|
||||
*/
|
||||
private suspend fun getCandidateTraders(category: String?): List<String> {
|
||||
// TODO: 实现获取候选交易者的逻辑
|
||||
// 可以从以下来源获取:
|
||||
// 1. 数据库中的 Leader 列表
|
||||
// 2. Polymarket 的公开数据
|
||||
// 3. 用户提交的交易者地址
|
||||
return emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 交易者排名
|
||||
*/
|
||||
data class TraderRanking(
|
||||
val rank: Int,
|
||||
val walletAddress: String,
|
||||
val score: Double,
|
||||
val metrics: TraderMetrics,
|
||||
val positions: Int,
|
||||
val lastTradeTime: Long?
|
||||
)
|
||||
```
|
||||
|
||||
## 7. 数据存储建议
|
||||
|
||||
### 7.1 数据库表设计
|
||||
|
||||
```sql
|
||||
-- 聪明钱交易者表
|
||||
CREATE TABLE smart_money_traders (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
wallet_address VARCHAR(42) NOT NULL UNIQUE,
|
||||
score DOUBLE NOT NULL,
|
||||
win_rate DOUBLE NOT NULL,
|
||||
total_pnl DECIMAL(20, 8) NOT NULL,
|
||||
return_rate DOUBLE NOT NULL,
|
||||
trade_count INT NOT NULL,
|
||||
category VARCHAR(20), -- sports 或 crypto
|
||||
last_analysis_time BIGINT NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL,
|
||||
INDEX idx_score (score DESC),
|
||||
INDEX idx_category (category),
|
||||
INDEX idx_last_analysis_time (last_analysis_time)
|
||||
);
|
||||
|
||||
-- 交易者历史指标表(用于追踪指标变化)
|
||||
CREATE TABLE trader_metrics_history (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
wallet_address VARCHAR(42) NOT NULL,
|
||||
win_rate DOUBLE NOT NULL,
|
||||
total_pnl DECIMAL(20, 8) NOT NULL,
|
||||
return_rate DOUBLE NOT NULL,
|
||||
trade_count INT NOT NULL,
|
||||
recorded_at BIGINT NOT NULL,
|
||||
INDEX idx_wallet_address (wallet_address),
|
||||
INDEX idx_recorded_at (recorded_at)
|
||||
);
|
||||
```
|
||||
|
||||
### 7.2 缓存策略
|
||||
|
||||
- **Redis 缓存**:缓存聪明钱排名列表,减少数据库查询
|
||||
- **缓存过期时间**:建议 1 小时
|
||||
- **缓存键**:`smart_money:rankings:{category}:{days}`
|
||||
|
||||
## 8. API 接口设计
|
||||
|
||||
### 8.1 获取聪明钱排名
|
||||
|
||||
```kotlin
|
||||
@PostMapping("/smart-money/rankings")
|
||||
fun getRankings(@RequestBody request: SmartMoneyRankingsRequest): ResponseEntity<ApiResponse<SmartMoneyRankingsResponse>> {
|
||||
// 实现逻辑
|
||||
}
|
||||
```
|
||||
|
||||
**请求参数**:
|
||||
```json
|
||||
{
|
||||
"category": "sports", // 可选:sports 或 crypto
|
||||
"days": 90, // 可选:分析时间范围(天)
|
||||
"limit": 100, // 可选:返回数量
|
||||
"minScore": 50 // 可选:最低评分
|
||||
}
|
||||
```
|
||||
|
||||
**响应数据**:
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"data": {
|
||||
"rankings": [
|
||||
{
|
||||
"rank": 1,
|
||||
"walletAddress": "0x...",
|
||||
"score": 85.5,
|
||||
"metrics": {
|
||||
"tradeCount": 150,
|
||||
"winRate": 0.65,
|
||||
"totalPnl": 5000.0,
|
||||
"returnRate": 0.35,
|
||||
"avgPnlRatio": 2.5
|
||||
},
|
||||
"positions": 10,
|
||||
"lastTradeTime": 1234567890
|
||||
}
|
||||
],
|
||||
"total": 100
|
||||
},
|
||||
"msg": ""
|
||||
}
|
||||
```
|
||||
|
||||
### 8.2 分析单个交易者
|
||||
|
||||
```kotlin
|
||||
@PostMapping("/smart-money/analyze")
|
||||
fun analyzeTrader(@RequestBody request: SmartMoneyAnalyzeRequest): ResponseEntity<ApiResponse<TraderAnalysisDto>> {
|
||||
// 实现逻辑
|
||||
}
|
||||
```
|
||||
|
||||
**请求参数**:
|
||||
```json
|
||||
{
|
||||
"walletAddress": "0x...",
|
||||
"days": 90
|
||||
}
|
||||
```
|
||||
|
||||
## 9. 注意事项
|
||||
|
||||
### 9.1 API 限制
|
||||
|
||||
- **Data API 速率限制**:注意 API 调用频率,避免触发限流
|
||||
- **数据延迟**:Data API 的数据可能有延迟,不是实时的
|
||||
- **数据完整性**:某些历史数据可能不完整,需要处理缺失数据
|
||||
|
||||
### 9.2 计算精度
|
||||
|
||||
- **价格精度**:Polymarket 使用 0.01-0.99 的价格范围,注意精度问题
|
||||
- **金额精度**:使用 `BigDecimal` 进行金额计算,避免浮点数误差
|
||||
- **时间精度**:注意时间戳的精度(毫秒 vs 秒)
|
||||
|
||||
### 9.3 性能优化
|
||||
|
||||
- **批量查询**:尽量批量查询多个交易者的数据
|
||||
- **缓存策略**:缓存分析结果,避免重复计算
|
||||
- **异步处理**:使用异步任务处理大量数据分析
|
||||
|
||||
### 9.4 数据质量
|
||||
|
||||
- **数据验证**:验证 API 返回的数据完整性
|
||||
- **异常处理**:处理 API 调用失败的情况
|
||||
- **数据清洗**:清洗异常数据(如价格为 0、数量为负数等)
|
||||
|
||||
## 10. 后续优化方向
|
||||
|
||||
1. **机器学习模型**:使用机器学习模型预测交易者未来表现
|
||||
2. **实时监控**:集成 WebSocket 实现实时监控聪明钱交易
|
||||
3. **跟单推荐**:根据聪明钱分析结果,推荐适合跟单的交易者
|
||||
4. **风险预警**:监控聪明钱交易者的风险指标,及时预警
|
||||
5. **多维度分析**:增加更多分析维度(如市场类型、时间分布等)
|
||||
|
||||
|
||||
Generated
+18
-5
@@ -11,7 +11,7 @@
|
||||
"antd": "^5.12.0",
|
||||
"antd-mobile": "^5.34.0",
|
||||
"axios": "^1.6.2",
|
||||
"ethers": "^6.9.0",
|
||||
"ethers": "^6.16.0",
|
||||
"i18next": "^25.7.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
@@ -158,6 +158,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz",
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1676,6 +1677,7 @@
|
||||
"version": "18.3.27",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
|
||||
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.2.2"
|
||||
@@ -1741,6 +1743,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.21.0.tgz",
|
||||
"integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==",
|
||||
"dev": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "6.21.0",
|
||||
"@typescript-eslint/types": "6.21.0",
|
||||
@@ -1937,6 +1940,7 @@
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -2255,6 +2259,7 @@
|
||||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
],
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.25",
|
||||
"caniuse-lite": "^1.0.30001754",
|
||||
@@ -2466,7 +2471,8 @@
|
||||
"node_modules/dayjs": {
|
||||
"version": "1.11.19",
|
||||
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz",
|
||||
"integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw=="
|
||||
"integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
@@ -2687,6 +2693,7 @@
|
||||
"integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==",
|
||||
"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
|
||||
"dev": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.6.1",
|
||||
@@ -2877,9 +2884,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ethers": {
|
||||
"version": "6.15.0",
|
||||
"resolved": "https://registry.npmjs.org/ethers/-/ethers-6.15.0.tgz",
|
||||
"integrity": "sha512-Kf/3ZW54L4UT0pZtsY/rf+EkBU7Qi5nnhonjUb8yTXcxH3cdcWrV2cRyk0Xk/4jK6OoHhxxZHriyhje20If2hQ==",
|
||||
"version": "6.16.0",
|
||||
"resolved": "https://registry.npmjs.org/ethers/-/ethers-6.16.0.tgz",
|
||||
"integrity": "sha512-U1wulmetNymijEhpSEQ7Ct/P/Jw9/e7R1j5XIbPRydgV2DjLVMsULDlNksq3RQnFgKoLlZf88ijYtWEXcPa07A==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
@@ -2890,6 +2897,7 @@
|
||||
"url": "https://www.buymeacoffee.com/ricmoo"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@adraffy/ens-normalize": "1.10.1",
|
||||
"@noble/curves": "1.2.0",
|
||||
@@ -3364,6 +3372,7 @@
|
||||
"url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
|
||||
}
|
||||
],
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.4"
|
||||
},
|
||||
@@ -5432,6 +5441,7 @@
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -5443,6 +5453,7 @@
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -6010,6 +6021,7 @@
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"devOptional": true,
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -6182,6 +6194,7 @@
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
|
||||
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
|
||||
"dev": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.21.3",
|
||||
"postcss": "^8.4.43",
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"antd": "^5.12.0",
|
||||
"antd-mobile": "^5.34.0",
|
||||
"axios": "^1.6.2",
|
||||
"ethers": "^6.9.0",
|
||||
"ethers": "^6.16.0",
|
||||
"i18next": "^25.7.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { useState } from 'react'
|
||||
import { Form, Input, Button, Radio, Space, Alert } from 'antd'
|
||||
import { Form, Input, Button, Radio, Space, Alert, Tooltip } from 'antd'
|
||||
import { QuestionCircleOutlined } from '@ant-design/icons'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useAccountStore } from '../store/accountStore'
|
||||
import {
|
||||
getAddressFromPrivateKey,
|
||||
import {
|
||||
getAddressFromPrivateKey,
|
||||
getAddressFromMnemonic,
|
||||
getPrivateKeyFromMnemonic,
|
||||
isValidWalletAddress,
|
||||
isValidWalletAddress,
|
||||
isValidPrivateKey,
|
||||
isValidMnemonic
|
||||
} from '../utils'
|
||||
import { useMediaQuery } from 'react-responsive'
|
||||
|
||||
type ImportType = 'privateKey' | 'mnemonic'
|
||||
type WalletType = 'magic' | 'safe'
|
||||
|
||||
interface AccountImportFormProps {
|
||||
form: any
|
||||
@@ -33,6 +35,7 @@ const AccountImportForm: React.FC<AccountImportFormProps> = ({
|
||||
const isMobile = useMediaQuery({ maxWidth: 768 })
|
||||
const { importAccount, loading } = useAccountStore()
|
||||
const [importType, setImportType] = useState<ImportType>('privateKey')
|
||||
const [walletType, setWalletType] = useState<WalletType>('safe')
|
||||
const [derivedAddress, setDerivedAddress] = useState<string>('')
|
||||
const [addressError, setAddressError] = useState<string>('')
|
||||
|
||||
@@ -141,7 +144,8 @@ const AccountImportForm: React.FC<AccountImportFormProps> = ({
|
||||
await importAccount({
|
||||
privateKey: privateKey,
|
||||
walletAddress: walletAddress,
|
||||
accountName: values.accountName
|
||||
accountName: values.accountName,
|
||||
walletType: walletType
|
||||
})
|
||||
|
||||
// 等待store更新
|
||||
@@ -189,8 +193,8 @@ const AccountImportForm: React.FC<AccountImportFormProps> = ({
|
||||
size={isMobile ? 'middle' : 'large'}
|
||||
>
|
||||
<Form.Item label={t('accountImport.importMethod')}>
|
||||
<Radio.Group
|
||||
value={importType}
|
||||
<Radio.Group
|
||||
value={importType}
|
||||
onChange={(e) => {
|
||||
setImportType(e.target.value)
|
||||
setDerivedAddress('')
|
||||
@@ -202,6 +206,32 @@ const AccountImportForm: React.FC<AccountImportFormProps> = ({
|
||||
<Radio value="mnemonic">{t('accountImport.mnemonic')}</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={
|
||||
<span>
|
||||
{t('accountImport.walletType')}{' '}
|
||||
<Tooltip
|
||||
title={t('accountImport.walletTypeHelp')}
|
||||
overlayInnerStyle={{ whiteSpace: 'pre-line', maxWidth: '300px' }}
|
||||
>
|
||||
<QuestionCircleOutlined style={{ color: '#999' }} />
|
||||
</Tooltip>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<Radio.Group
|
||||
value={walletType}
|
||||
onChange={(e) => setWalletType(e.target.value)}
|
||||
>
|
||||
<Radio value="safe">
|
||||
{t('accountImport.walletTypeSafe')}
|
||||
</Radio>
|
||||
<Radio value="magic">
|
||||
{t('accountImport.walletTypeMagic')}
|
||||
</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
|
||||
{importType === 'privateKey' ? (
|
||||
<>
|
||||
|
||||
@@ -199,7 +199,11 @@
|
||||
"importFailed": "Failed to import account",
|
||||
"derivedAddress": "Derived Address",
|
||||
"addressError": "Cannot derive address from private key",
|
||||
"addressErrorMnemonic": "Cannot derive address from mnemonic"
|
||||
"addressErrorMnemonic": "Cannot derive address from mnemonic",
|
||||
"walletType": "Wallet Type",
|
||||
"walletTypeHelp": "Web3 Wallet: Polymarket accounts connected via browser wallets like MetaMask\nMagic: Polymarket accounts logged in via email or social accounts (Google, Twitter, etc.)",
|
||||
"walletTypeMagic": "Magic (Email/Social Login)",
|
||||
"walletTypeSafe": "Web3 Wallet"
|
||||
},
|
||||
"leader": {
|
||||
"title": "Leader Management",
|
||||
|
||||
@@ -199,7 +199,11 @@
|
||||
"importFailed": "导入账户失败",
|
||||
"derivedAddress": "推导地址",
|
||||
"addressError": "无法从私钥推导地址",
|
||||
"addressErrorMnemonic": "无法从助记词推导地址"
|
||||
"addressErrorMnemonic": "无法从助记词推导地址",
|
||||
"walletType": "钱包类型",
|
||||
"walletTypeHelp": "Web3钱包:使用 MetaMask 等浏览器钱包连接的 Polymarket 账户\nMagic:通过邮箱或社交账号(如 Google、Twitter)登录的 Polymarket 账户",
|
||||
"walletTypeMagic": "Magic(邮箱/社交账号登录)",
|
||||
"walletTypeSafe": "Web3钱包"
|
||||
},
|
||||
"leader": {
|
||||
"title": "Leader 管理",
|
||||
@@ -1022,7 +1026,7 @@
|
||||
"remainingQuantity": "剩余",
|
||||
"sellStatus": "卖出状态",
|
||||
"status": "状态",
|
||||
"statusFilled": "已完成",
|
||||
"statusFilled": "未成交",
|
||||
"statusPartiallySold": "部分成交",
|
||||
"statusFullySold": "全部成交",
|
||||
"realizedPnl": "已实现盈亏",
|
||||
|
||||
@@ -199,7 +199,11 @@
|
||||
"importFailed": "導入賬戶失敗",
|
||||
"derivedAddress": "推導地址",
|
||||
"addressError": "無法從私鑰推導地址",
|
||||
"addressErrorMnemonic": "無法從助記詞推導地址"
|
||||
"addressErrorMnemonic": "無法從助記詞推導地址",
|
||||
"walletType": "錢包類型",
|
||||
"walletTypeHelp": "Web3錢包:使用 MetaMask 等瀏覽器錢包連接的 Polymarket 帳戶\nMagic:透過郵箱或社群帳號(如 Google、Twitter)登入的 Polymarket 帳戶",
|
||||
"walletTypeMagic": "Magic(郵箱/社群帳號登入)",
|
||||
"walletTypeSafe": "Web3錢包"
|
||||
},
|
||||
"leader": {
|
||||
"title": "Leader 管理",
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Card, Table, Button, Space, Tag, Popconfirm, message, Typography, Spin, Modal, Descriptions, Divider, Form, Input, Alert } from 'antd'
|
||||
import { PlusOutlined, ReloadOutlined, EditOutlined, CopyOutlined } from '@ant-design/icons'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
@@ -7,12 +6,12 @@ import { useAccountStore } from '../store/accountStore'
|
||||
import type { Account } from '../types'
|
||||
import { useMediaQuery } from 'react-responsive'
|
||||
import { formatUSDC } from '../utils'
|
||||
import AccountImportForm from '../components/AccountImportForm'
|
||||
|
||||
const { Title } = Typography
|
||||
|
||||
const AccountList: React.FC = () => {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const isMobile = useMediaQuery({ maxWidth: 768 })
|
||||
const { accounts, loading, fetchAccounts, deleteAccount, fetchAccountBalance, fetchAccountDetail, updateAccount } = useAccountStore()
|
||||
const [balanceMap, setBalanceMap] = useState<Record<number, { total: string; available: string; position: string }>>({})
|
||||
@@ -25,11 +24,20 @@ const AccountList: React.FC = () => {
|
||||
const [editAccount, setEditAccount] = useState<Account | null>(null)
|
||||
const [editForm] = Form.useForm()
|
||||
const [editLoading, setEditLoading] = useState(false)
|
||||
const [accountImportModalVisible, setAccountImportModalVisible] = useState(false)
|
||||
const [accountImportForm] = Form.useForm()
|
||||
|
||||
useEffect(() => {
|
||||
fetchAccounts()
|
||||
}, [fetchAccounts])
|
||||
|
||||
const handleAccountImportSuccess = async () => {
|
||||
message.success(t('accountImport.importSuccess'))
|
||||
setAccountImportModalVisible(false)
|
||||
accountImportForm.resetFields()
|
||||
fetchAccounts()
|
||||
}
|
||||
|
||||
// 加载所有账户的余额
|
||||
useEffect(() => {
|
||||
const loadBalances = async () => {
|
||||
@@ -494,7 +502,7 @@ const AccountList: React.FC = () => {
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => navigate('/accounts/import')}
|
||||
onClick={() => setAccountImportModalVisible(true)}
|
||||
size={isMobile ? 'middle' : 'large'}
|
||||
block={isMobile}
|
||||
style={isMobile ? { minHeight: '44px' } : undefined}
|
||||
@@ -836,6 +844,34 @@ const AccountList: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* 导入账户 Modal */}
|
||||
<Modal
|
||||
title={t('accountImport.title')}
|
||||
open={accountImportModalVisible}
|
||||
onCancel={() => {
|
||||
setAccountImportModalVisible(false)
|
||||
accountImportForm.resetFields()
|
||||
}}
|
||||
footer={null}
|
||||
width={isMobile ? '95%' : 600}
|
||||
style={{ top: isMobile ? 20 : 50 }}
|
||||
bodyStyle={{ padding: '24px', maxHeight: 'calc(100vh - 150px)', overflow: 'auto' }}
|
||||
destroyOnClose
|
||||
maskClosable
|
||||
closable
|
||||
>
|
||||
<AccountImportForm
|
||||
form={accountImportForm}
|
||||
onSuccess={handleAccountImportSuccess}
|
||||
onCancel={() => {
|
||||
setAccountImportModalVisible(false)
|
||||
accountImportForm.resetFields()
|
||||
}}
|
||||
showAlert={true}
|
||||
showCancelButton={true}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ const ApiHealthStatus: React.FC = () => {
|
||||
}}
|
||||
bodyStyle={{ padding: '12px' }}
|
||||
>
|
||||
<Space direction="vertical" size="small" style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '8px' }}>
|
||||
<Text strong style={{ fontSize: '14px' }}>
|
||||
{item.name}
|
||||
@@ -110,9 +111,28 @@ const ApiHealthStatus: React.FC = () => {
|
||||
)}
|
||||
<Badge
|
||||
status={item.status === 'success' ? 'success' : item.status === 'skipped' ? 'default' : 'error'}
|
||||
text={getStatusText(item.status)}
|
||||
/>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Text type="secondary" style={{ fontSize: '12px', wordBreak: 'break-all' }}>
|
||||
{item.url}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{item.message && item.message !== '连接成功' && (
|
||||
<div>
|
||||
<Text
|
||||
type={item.status === 'success' ? 'success' : item.status === 'skipped' ? 'secondary' : 'danger'}
|
||||
style={{ fontSize: '12px' }}
|
||||
>
|
||||
{item.message}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
</Card>
|
||||
) : (
|
||||
<Card
|
||||
|
||||
@@ -344,13 +344,51 @@ const CopyTradingAdd: React.FC = () => {
|
||||
tooltip={t('copyTradingAdd.copyRatioTooltip') || '跟单比例表示跟单金额相对于 Leader 订单金额的百分比。例如:100% 表示 1:1 跟单,50% 表示半仓跟单,200% 表示双倍跟单'}
|
||||
>
|
||||
<InputNumber
|
||||
min={10}
|
||||
max={1000}
|
||||
step={1}
|
||||
precision={0}
|
||||
min={0.01}
|
||||
max={10000}
|
||||
step={0.01}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="%"
|
||||
placeholder={t('copyTradingAdd.copyRatioPlaceholder') || '例如:100 表示 100%(1:1 跟单),默认 100%'}
|
||||
parser={(value) => {
|
||||
console.log('[CopyTradingAdd copyRatio parser] 输入值:', value, '类型:', typeof value)
|
||||
// 移除 % 符号和其他非数字字符(保留小数点和负号)
|
||||
const cleaned = (value || '').toString().replace(/%/g, '').trim()
|
||||
console.log('[CopyTradingAdd copyRatio parser] 清理后:', cleaned)
|
||||
const parsed = parseFloat(cleaned) || 0
|
||||
console.log('[CopyTradingAdd copyRatio parser] 解析后:', parsed)
|
||||
if (parsed > 10000) {
|
||||
console.log('[CopyTradingAdd copyRatio parser] 超过最大值,返回 10000')
|
||||
return 10000
|
||||
}
|
||||
if (parsed < 0.01) {
|
||||
console.log('[CopyTradingAdd copyRatio parser] 小于最小值,返回 0.01')
|
||||
return 0.01
|
||||
}
|
||||
console.log('[CopyTradingAdd copyRatio parser] 返回:', parsed)
|
||||
return parsed
|
||||
}}
|
||||
formatter={(value) => {
|
||||
console.log('[CopyTradingAdd copyRatio formatter] 输入值:', value, '类型:', typeof value)
|
||||
if (!value && value !== 0) {
|
||||
console.log('[CopyTradingAdd copyRatio formatter] 空值,返回空字符串')
|
||||
return ''
|
||||
}
|
||||
const num = parseFloat(value.toString())
|
||||
console.log('[CopyTradingAdd copyRatio formatter] 解析后:', num)
|
||||
if (isNaN(num)) {
|
||||
console.log('[CopyTradingAdd copyRatio formatter] NaN,返回空字符串')
|
||||
return ''
|
||||
}
|
||||
if (num > 10000) {
|
||||
console.log('[CopyTradingAdd copyRatio formatter] 超过最大值,返回 10000')
|
||||
return '10000'
|
||||
}
|
||||
const result = num.toString().replace(/\.0+$/, '')
|
||||
console.log('[CopyTradingAdd copyRatio formatter] 格式化后返回:', result)
|
||||
return result
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -383,6 +421,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.fixedAmountPlaceholder') || '固定金额,不随 Leader 订单大小变化,必须 >= 1'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -400,6 +444,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.maxOrderSizePlaceholder') || '仅在比例模式下生效(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -427,6 +477,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.minOrderSizePlaceholder') || '仅在比例模式下生效,必须 >= 1(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
@@ -443,6 +499,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.maxDailyLossPlaceholder') || '默认 10000 USDC(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -471,6 +533,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.priceTolerancePlaceholder') || '默认 5%(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -498,6 +566,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.minOrderDepthPlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -512,6 +586,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.maxSpreadPlaceholder') || '例如:0.05(5美分,可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -531,6 +611,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('copyTradingAdd.minPricePlaceholder') || '最低价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<span style={{ display: 'inline-block', width: '20px', textAlign: 'center', lineHeight: '32px' }}>-</span>
|
||||
@@ -542,6 +628,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('copyTradingAdd.maxPricePlaceholder') || '最高价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Input.Group>
|
||||
@@ -560,6 +652,12 @@ const CopyTradingAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingAdd.maxPositionValuePlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
|
||||
@@ -237,13 +237,51 @@ const CopyTradingEdit: React.FC = () => {
|
||||
tooltip={t('copyTradingEdit.copyRatioTooltip') || '跟单比例表示跟单金额相对于 Leader 订单金额的百分比'}
|
||||
>
|
||||
<InputNumber
|
||||
min={10}
|
||||
max={1000}
|
||||
step={1}
|
||||
precision={0}
|
||||
min={0.01}
|
||||
max={10000}
|
||||
step={0.01}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="%"
|
||||
placeholder={t('copyTradingEdit.copyRatioPlaceholder') || '例如:100 表示 100%(1:1 跟单)'}
|
||||
parser={(value) => {
|
||||
console.log('[CopyTradingEdit copyRatio parser] 输入值:', value, '类型:', typeof value)
|
||||
// 移除 % 符号和其他非数字字符(保留小数点和负号)
|
||||
const cleaned = (value || '').toString().replace(/%/g, '').trim()
|
||||
console.log('[CopyTradingEdit copyRatio parser] 清理后:', cleaned)
|
||||
const parsed = parseFloat(cleaned) || 0
|
||||
console.log('[CopyTradingEdit copyRatio parser] 解析后:', parsed)
|
||||
if (parsed > 10000) {
|
||||
console.log('[CopyTradingEdit copyRatio parser] 超过最大值,返回 10000')
|
||||
return 10000
|
||||
}
|
||||
if (parsed < 0.01) {
|
||||
console.log('[CopyTradingEdit copyRatio parser] 小于最小值,返回 0.01')
|
||||
return 0.01
|
||||
}
|
||||
console.log('[CopyTradingEdit copyRatio parser] 返回:', parsed)
|
||||
return parsed
|
||||
}}
|
||||
formatter={(value) => {
|
||||
console.log('[CopyTradingEdit copyRatio formatter] 输入值:', value, '类型:', typeof value)
|
||||
if (!value && value !== 0) {
|
||||
console.log('[CopyTradingEdit copyRatio formatter] 空值,返回空字符串')
|
||||
return ''
|
||||
}
|
||||
const num = parseFloat(value.toString())
|
||||
console.log('[CopyTradingEdit copyRatio formatter] 解析后:', num)
|
||||
if (isNaN(num)) {
|
||||
console.log('[CopyTradingEdit copyRatio formatter] NaN,返回空字符串')
|
||||
return ''
|
||||
}
|
||||
if (num > 10000) {
|
||||
console.log('[CopyTradingEdit copyRatio formatter] 超过最大值,返回 10000')
|
||||
return '10000'
|
||||
}
|
||||
const result = num.toString().replace(/\.0+$/, '')
|
||||
console.log('[CopyTradingEdit copyRatio formatter] 格式化后返回:', result)
|
||||
return result
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -276,6 +314,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.fixedAmountPlaceholder') || '固定金额,不随 Leader 订单大小变化,必须 >= 1'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -293,6 +337,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxOrderSizePlaceholder') || '仅在比例模式下生效(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -320,6 +370,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.minOrderSizePlaceholder') || '仅在比例模式下生效,必须 >= 1(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
@@ -336,6 +392,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxDailyLossPlaceholder') || '默认 10000 USDC(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -364,6 +426,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.priceTolerancePlaceholder') || '默认 5%(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -391,6 +459,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.minOrderDepthPlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -405,6 +479,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxSpreadPlaceholder') || '例如:0.05(5美分,可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -424,6 +504,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('copyTradingEdit.minPricePlaceholder') || '最低价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<span style={{ display: 'inline-block', width: '20px', textAlign: 'center', lineHeight: '32px' }}>-</span>
|
||||
@@ -435,6 +521,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('copyTradingEdit.maxPricePlaceholder') || '最高价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Input.Group>
|
||||
@@ -453,6 +545,12 @@ const CopyTradingEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxPositionValuePlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
|
||||
@@ -196,7 +196,7 @@ const CopyTradingList: React.FC = () => {
|
||||
render: (_: any, record: CopyTrading) => (
|
||||
<Tag color={record.copyMode === 'RATIO' ? 'blue' : 'green'}>
|
||||
{record.copyMode === 'RATIO'
|
||||
? `${t('copyTradingList.ratioMode') || '比例'} ${record.copyRatio}x`
|
||||
? `${t('copyTradingList.ratioMode') || '比例'} ${(parseFloat(record.copyRatio || '0') * 100).toFixed(2).replace(/\.0+$/, '')}%`
|
||||
: `${t('copyTradingList.fixedAmountMode') || '固定'} ${formatUSDC(record.fixedAmount || '0')}`
|
||||
}
|
||||
</Tag>
|
||||
@@ -466,7 +466,7 @@ const CopyTradingList: React.FC = () => {
|
||||
color: '#666'
|
||||
}}>
|
||||
{record.copyMode === 'RATIO'
|
||||
? `${t('copyTradingList.ratioMode') || '比例'} ${record.copyRatio}x`
|
||||
? `${t('copyTradingList.ratioMode') || '比例'} ${(parseFloat(record.copyRatio || '0') * 100).toFixed(2).replace(/\.0+$/, '')}%`
|
||||
: `${t('copyTradingList.fixedAmountMode') || '固定'} ${formatUSDC(record.fixedAmount || '0')}`
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -8,11 +8,14 @@ import type { BuyOrderInfo, OrderTrackingRequest, OrderTrackingListResponse } fr
|
||||
|
||||
const { Option } = Select
|
||||
|
||||
import { ReloadOutlined } from '@ant-design/icons'
|
||||
|
||||
interface BuyOrdersTabProps {
|
||||
copyTradingId: string
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId, active = false }) => {
|
||||
const { t } = useTranslation()
|
||||
const isMobile = useMediaQuery({ maxWidth: 768 })
|
||||
const [loading, setLoading] = useState(false)
|
||||
@@ -25,16 +28,16 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
side?: string
|
||||
status?: string
|
||||
}>({})
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (copyTradingId) {
|
||||
if (copyTradingId && active) {
|
||||
fetchOrders()
|
||||
}
|
||||
}, [copyTradingId, page, limit, filters])
|
||||
|
||||
}, [copyTradingId, active, page, limit, filters])
|
||||
|
||||
const fetchOrders = async () => {
|
||||
if (!copyTradingId) return
|
||||
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const request: OrderTrackingRequest = {
|
||||
@@ -44,7 +47,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
limit,
|
||||
...filters
|
||||
}
|
||||
|
||||
|
||||
const response = await apiService.orderTracking.list(request)
|
||||
if (response.data.code === 0 && response.data.data) {
|
||||
const data = response.data.data as OrderTrackingListResponse
|
||||
@@ -57,17 +60,17 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const getStatusTag = (status: string) => {
|
||||
const statusMap: Record<string, { color: string; text: string }> = {
|
||||
filled: { color: 'processing', text: t('copyTradingOrders.statusFilled') || '已完成' },
|
||||
filled: { color: 'processing', text: t('copyTradingOrders.statusFilled') || '未成交' },
|
||||
partially_matched: { color: 'warning', text: t('copyTradingOrders.statusPartiallySold') || '部分成交' },
|
||||
fully_matched: { color: 'success', text: t('copyTradingOrders.statusFullySold') || '全部成交' }
|
||||
}
|
||||
const config = statusMap[status] || { color: 'default', text: status }
|
||||
return <Tag color={config.color}>{config.text}</Tag>
|
||||
}
|
||||
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('copyTradingOrders.orderId') || '订单ID',
|
||||
@@ -76,7 +79,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -90,7 +93,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -104,7 +107,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -184,7 +187,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 120 : 160,
|
||||
render: (timestamp: number) => (
|
||||
<span style={{ fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? new Date(timestamp).toLocaleDateString('zh-CN')
|
||||
: new Date(timestamp).toLocaleString('zh-CN')
|
||||
}
|
||||
@@ -192,7 +195,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
)
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
|
||||
@@ -203,7 +206,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
value={filters.marketId}
|
||||
onChange={(e) => setFilters({ ...filters, marketId: e.target.value || undefined })}
|
||||
/>
|
||||
|
||||
|
||||
<Select
|
||||
placeholder={t('copyTradingOrders.filterSide') || '筛选方向'}
|
||||
allowClear
|
||||
@@ -213,10 +216,8 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
>
|
||||
<Option value="0">YES</Option>
|
||||
<Option value="1">NO</Option>
|
||||
<Option value="YES">YES</Option>
|
||||
<Option value="NO">NO</Option>
|
||||
</Select>
|
||||
|
||||
|
||||
<Select
|
||||
placeholder={t('copyTradingOrders.filterStatus') || '筛选状态'}
|
||||
allowClear
|
||||
@@ -224,14 +225,14 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
value={filters.status}
|
||||
onChange={(value) => setFilters({ ...filters, status: value || undefined })}
|
||||
>
|
||||
<Option value="filled">{t('copyTradingOrders.statusFilled') || '已完成'}</Option>
|
||||
<Option value="filled">{t('copyTradingOrders.statusFilled') || '未成交'}</Option>
|
||||
<Option value="partially_matched">{t('copyTradingOrders.statusPartiallySold') || '部分成交'}</Option>
|
||||
<Option value="fully_matched">{t('copyTradingOrders.statusFullySold') || '全部成交'}</Option>
|
||||
</Select>
|
||||
|
||||
<Button onClick={fetchOrders}>{t('common.search') || '查询'}</Button>
|
||||
|
||||
<Button type="primary" onClick={fetchOrders} icon={<ReloadOutlined />}>{t('common.refresh') || '刷新'}</Button>
|
||||
</div>
|
||||
|
||||
|
||||
{isMobile ? (
|
||||
<div>
|
||||
{loading ? (
|
||||
@@ -255,7 +256,7 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
})
|
||||
const amount = (parseFloat(order.quantity) * parseFloat(order.price)).toString()
|
||||
const displaySide = order.side === '0' ? 'YES' : order.side === '1' ? 'NO' : order.side
|
||||
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={order.orderId}
|
||||
@@ -267,9 +268,9 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
>
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
<div style={{
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
marginBottom: '8px',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
@@ -280,9 +281,9 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
{getStatusTag(order.status)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<Divider style={{ margin: '12px 0' }} />
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.buyInfo') || '买入信息'}</div>
|
||||
<div style={{ fontSize: '14px', fontWeight: '500' }}>
|
||||
@@ -292,28 +293,28 @@ const BuyOrdersTab: React.FC<BuyOrdersTabProps> = ({ copyTradingId }) => {
|
||||
{t('copyTradingOrders.amount') || '金额'}: {formatUSDC(amount)} USDC
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.matchInfo') || '匹配信息'}</div>
|
||||
<div style={{ fontSize: '13px', color: '#333' }}>
|
||||
{t('copyTradingOrders.matched') || '已匹配'}: {formatUSDC(order.matchedQuantity)} | {t('copyTradingOrders.remaining') || '剩余'}: {formatUSDC(order.remainingQuantity)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.leaderTradeId') || 'Leader 交易ID'}</div>
|
||||
<div style={{ fontSize: '12px', color: '#999', fontFamily: 'monospace' }}>
|
||||
{order.leaderTradeId.slice(0, 8)}...{order.leaderTradeId.slice(-6)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.marketId') || '市场ID'}</div>
|
||||
<div style={{ fontSize: '12px', color: '#999', fontFamily: 'monospace' }}>
|
||||
{order.marketId.slice(0, 8)}...{order.marketId.slice(-6)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#999' }}>
|
||||
{t('copyTradingOrders.createdAt') || '创建时间'}: {formattedDate}
|
||||
|
||||
@@ -237,13 +237,51 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
tooltip={t('copyTradingEdit.copyRatioTooltip') || '跟单比例表示跟单金额相对于 Leader 订单金额的百分比'}
|
||||
>
|
||||
<InputNumber
|
||||
min={10}
|
||||
max={1000}
|
||||
step={1}
|
||||
precision={0}
|
||||
min={0.01}
|
||||
max={10000}
|
||||
step={0.01}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="%"
|
||||
placeholder={t('copyTradingEdit.copyRatioPlaceholder') || '例如:100 表示 100%(1:1 跟单)'}
|
||||
parser={(value) => {
|
||||
console.log('[EditModal copyRatio parser] 输入值:', value, '类型:', typeof value)
|
||||
// 移除 % 符号和其他非数字字符(保留小数点和负号)
|
||||
const cleaned = (value || '').toString().replace(/%/g, '').trim()
|
||||
console.log('[EditModal copyRatio parser] 清理后:', cleaned)
|
||||
const parsed = parseFloat(cleaned) || 0
|
||||
console.log('[EditModal copyRatio parser] 解析后:', parsed)
|
||||
if (parsed > 10000) {
|
||||
console.log('[EditModal copyRatio parser] 超过最大值,返回 10000')
|
||||
return 10000
|
||||
}
|
||||
if (parsed < 0.01) {
|
||||
console.log('[EditModal copyRatio parser] 小于最小值,返回 0.01')
|
||||
return 0.01
|
||||
}
|
||||
console.log('[EditModal copyRatio parser] 返回:', parsed)
|
||||
return parsed
|
||||
}}
|
||||
formatter={(value) => {
|
||||
console.log('[EditModal copyRatio formatter] 输入值:', value, '类型:', typeof value)
|
||||
if (!value && value !== 0) {
|
||||
console.log('[EditModal copyRatio formatter] 空值,返回空字符串')
|
||||
return ''
|
||||
}
|
||||
const num = parseFloat(value.toString())
|
||||
console.log('[EditModal copyRatio formatter] 解析后:', num)
|
||||
if (isNaN(num)) {
|
||||
console.log('[EditModal copyRatio formatter] NaN,返回空字符串')
|
||||
return ''
|
||||
}
|
||||
if (num > 10000) {
|
||||
console.log('[EditModal copyRatio formatter] 超过最大值,返回 10000')
|
||||
return '10000'
|
||||
}
|
||||
const result = num.toString().replace(/\.0+$/, '')
|
||||
console.log('[EditModal copyRatio formatter] 格式化后返回:', result)
|
||||
return result
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -276,6 +314,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.fixedAmountPlaceholder') || '固定金额,不随 Leader 订单大小变化,必须 >= 1'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -293,6 +337,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxOrderSizePlaceholder') || '仅在比例模式下生效(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -320,6 +370,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.minOrderSizePlaceholder') || '仅在比例模式下生效,必须 >= 1(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
@@ -336,6 +392,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxDailyLossPlaceholder') || '默认 10000 USDC(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -364,6 +426,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.priceTolerancePlaceholder') || '默认 5%(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -391,6 +459,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.minOrderDepthPlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -405,6 +479,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxSpreadPlaceholder') || '例如:0.05(5美分,可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -424,6 +504,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('copyTradingEdit.minPricePlaceholder') || '最低价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<span style={{ display: 'inline-block', width: '20px', textAlign: 'center', lineHeight: '32px' }}>-</span>
|
||||
@@ -435,6 +521,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('copyTradingEdit.maxPricePlaceholder') || '最高价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Input.Group>
|
||||
@@ -453,6 +545,12 @@ const EditModal: React.FC<EditModalProps> = ({
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('copyTradingEdit.maxPositionValuePlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
|
||||
@@ -6,11 +6,14 @@ import { useMediaQuery } from 'react-responsive'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { MatchedOrderInfo, OrderTrackingRequest, OrderTrackingListResponse } from '../../types'
|
||||
|
||||
import { ReloadOutlined } from '@ant-design/icons'
|
||||
|
||||
interface MatchedOrdersTabProps {
|
||||
copyTradingId: string
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) => {
|
||||
const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId, active = false }) => {
|
||||
const { t } = useTranslation()
|
||||
const isMobile = useMediaQuery({ maxWidth: 768 })
|
||||
const [loading, setLoading] = useState(false)
|
||||
@@ -22,16 +25,16 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
sellOrderId?: string
|
||||
buyOrderId?: string
|
||||
}>({})
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (copyTradingId) {
|
||||
if (copyTradingId && active) {
|
||||
fetchOrders()
|
||||
}
|
||||
}, [copyTradingId, page, limit, filters])
|
||||
|
||||
}, [copyTradingId, active, page, limit, filters])
|
||||
|
||||
const fetchOrders = async () => {
|
||||
if (!copyTradingId) return
|
||||
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const request: OrderTrackingRequest = {
|
||||
@@ -41,7 +44,7 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
limit,
|
||||
...filters
|
||||
}
|
||||
|
||||
|
||||
const response = await apiService.orderTracking.list(request)
|
||||
if (response.data.code === 0 && response.data.data) {
|
||||
const data = response.data.data as OrderTrackingListResponse
|
||||
@@ -54,13 +57,13 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const getPnlColor = (value: string): string => {
|
||||
const num = parseFloat(value)
|
||||
if (isNaN(num)) return '#666'
|
||||
return num >= 0 ? '#3f8600' : '#cf1322'
|
||||
}
|
||||
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('copyTradingOrders.sellOrderId') || '卖出订单ID',
|
||||
@@ -69,7 +72,7 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -83,7 +86,7 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -123,8 +126,8 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
key: 'realizedPnl',
|
||||
width: isMobile ? 100 : 120,
|
||||
render: (value: string) => (
|
||||
<span style={{
|
||||
color: getPnlColor(value),
|
||||
<span style={{
|
||||
color: getPnlColor(value),
|
||||
fontWeight: 500,
|
||||
fontSize: isMobile ? 12 : 14
|
||||
}}>
|
||||
@@ -139,7 +142,7 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
width: isMobile ? 120 : 160,
|
||||
render: (timestamp: number) => (
|
||||
<span style={{ fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? new Date(timestamp).toLocaleDateString('zh-CN')
|
||||
: new Date(timestamp).toLocaleString('zh-CN')
|
||||
}
|
||||
@@ -147,7 +150,7 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
)
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
|
||||
@@ -158,7 +161,7 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
value={filters.sellOrderId}
|
||||
onChange={(e) => setFilters({ ...filters, sellOrderId: e.target.value || undefined })}
|
||||
/>
|
||||
|
||||
|
||||
<Input
|
||||
placeholder={t('copyTradingOrders.filterBuyOrderId') || '筛选买入订单ID'}
|
||||
allowClear
|
||||
@@ -166,10 +169,10 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
value={filters.buyOrderId}
|
||||
onChange={(e) => setFilters({ ...filters, buyOrderId: e.target.value || undefined })}
|
||||
/>
|
||||
|
||||
<Button onClick={fetchOrders}>{t('common.search') || '查询'}</Button>
|
||||
|
||||
<Button type="primary" onClick={fetchOrders} icon={<ReloadOutlined />}>{t('common.search') || '查询'}</Button>
|
||||
</div>
|
||||
|
||||
|
||||
{isMobile ? (
|
||||
<div>
|
||||
{loading ? (
|
||||
@@ -191,7 +194,7 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})
|
||||
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={`${order.sellOrderId}-${order.buyOrderId}-${order.matchedAt}`}
|
||||
@@ -204,8 +207,8 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
>
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.sellOrderId') || '卖出订单ID'}</div>
|
||||
<div style={{
|
||||
fontSize: '13px',
|
||||
<div style={{
|
||||
fontSize: '13px',
|
||||
fontWeight: '500',
|
||||
fontFamily: 'monospace',
|
||||
marginBottom: '8px'
|
||||
@@ -213,42 +216,42 @@ const MatchedOrdersTab: React.FC<MatchedOrdersTabProps> = ({ copyTradingId }) =>
|
||||
{order.sellOrderId.slice(0, 8)}...{order.sellOrderId.slice(-6)}
|
||||
</div>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.buyOrderId') || '买入订单ID'}</div>
|
||||
<div style={{
|
||||
fontSize: '13px',
|
||||
<div style={{
|
||||
fontSize: '13px',
|
||||
fontWeight: '500',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
{order.buyOrderId.slice(0, 8)}...{order.buyOrderId.slice(-6)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<Divider style={{ margin: '12px 0' }} />
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.matchedQuantity') || '匹配数量'}</div>
|
||||
<div style={{ fontSize: '14px', fontWeight: '500' }}>
|
||||
{formatUSDC(order.matchedQuantity)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.priceInfo') || '价格信息'}</div>
|
||||
<div style={{ fontSize: '13px', color: '#333' }}>
|
||||
{t('copyTradingOrders.buy') || '买入'}: {formatUSDC(order.buyPrice)} | {t('copyTradingOrders.sell') || '卖出'}: {formatUSDC(order.sellPrice)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.realizedPnl') || '盈亏'}</div>
|
||||
<div style={{
|
||||
fontSize: '16px',
|
||||
<div style={{
|
||||
fontSize: '16px',
|
||||
fontWeight: 'bold',
|
||||
color: getPnlColor(order.realizedPnl)
|
||||
}}>
|
||||
{formatUSDC(order.realizedPnl)} USDC
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#999' }}>
|
||||
{t('copyTradingOrders.matchedAt') || '匹配时间'}: {formattedDate}
|
||||
|
||||
@@ -8,11 +8,14 @@ import type { SellOrderInfo, OrderTrackingRequest, OrderTrackingListResponse } f
|
||||
|
||||
const { Option } = Select
|
||||
|
||||
import { ReloadOutlined } from '@ant-design/icons'
|
||||
|
||||
interface SellOrdersTabProps {
|
||||
copyTradingId: string
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId, active = false }) => {
|
||||
const { t } = useTranslation()
|
||||
const isMobile = useMediaQuery({ maxWidth: 768 })
|
||||
const [loading, setLoading] = useState(false)
|
||||
@@ -24,16 +27,16 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
marketId?: string
|
||||
side?: string
|
||||
}>({})
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (copyTradingId) {
|
||||
if (copyTradingId && active) {
|
||||
fetchOrders()
|
||||
}
|
||||
}, [copyTradingId, page, limit, filters])
|
||||
|
||||
}, [copyTradingId, active, page, limit, filters])
|
||||
|
||||
const fetchOrders = async () => {
|
||||
if (!copyTradingId) return
|
||||
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const request: OrderTrackingRequest = {
|
||||
@@ -43,7 +46,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
limit,
|
||||
...filters
|
||||
}
|
||||
|
||||
|
||||
const response = await apiService.orderTracking.list(request)
|
||||
if (response.data.code === 0 && response.data.data) {
|
||||
const data = response.data.data as OrderTrackingListResponse
|
||||
@@ -56,13 +59,13 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const getPnlColor = (value: string): string => {
|
||||
const num = parseFloat(value)
|
||||
if (isNaN(num)) return '#666'
|
||||
return num >= 0 ? '#3f8600' : '#cf1322'
|
||||
}
|
||||
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('copyTradingOrders.orderId') || '订单ID',
|
||||
@@ -71,7 +74,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -85,7 +88,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -99,7 +102,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 100 : 150,
|
||||
render: (text: string) => (
|
||||
<span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? `${text.slice(0, 6)}...${text.slice(-4)}`
|
||||
: `${text.slice(0, 8)}...${text.slice(-6)}`
|
||||
}
|
||||
@@ -153,8 +156,8 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
key: 'realizedPnl',
|
||||
width: isMobile ? 100 : 120,
|
||||
render: (value: string) => (
|
||||
<span style={{
|
||||
color: getPnlColor(value),
|
||||
<span style={{
|
||||
color: getPnlColor(value),
|
||||
fontWeight: 500,
|
||||
fontSize: isMobile ? 12 : 14
|
||||
}}>
|
||||
@@ -169,7 +172,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
width: isMobile ? 120 : 160,
|
||||
render: (timestamp: number) => (
|
||||
<span style={{ fontSize: isMobile ? 11 : 12 }}>
|
||||
{isMobile
|
||||
{isMobile
|
||||
? new Date(timestamp).toLocaleDateString('zh-CN')
|
||||
: new Date(timestamp).toLocaleString('zh-CN')
|
||||
}
|
||||
@@ -177,7 +180,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
)
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
|
||||
@@ -188,7 +191,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
value={filters.marketId}
|
||||
onChange={(e) => setFilters({ ...filters, marketId: e.target.value || undefined })}
|
||||
/>
|
||||
|
||||
|
||||
<Select
|
||||
placeholder={t('copyTradingOrders.filterSide') || '筛选方向'}
|
||||
allowClear
|
||||
@@ -201,10 +204,10 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
<Option value="YES">YES</Option>
|
||||
<Option value="NO">NO</Option>
|
||||
</Select>
|
||||
|
||||
<Button onClick={fetchOrders}>{t('common.search') || '查询'}</Button>
|
||||
|
||||
<Button type="primary" onClick={fetchOrders} icon={<ReloadOutlined />}>{t('common.refresh') || '刷新'}</Button>
|
||||
</div>
|
||||
|
||||
|
||||
{isMobile ? (
|
||||
<div>
|
||||
{loading ? (
|
||||
@@ -228,7 +231,7 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
})
|
||||
const amount = (parseFloat(order.quantity) * parseFloat(order.price)).toString()
|
||||
const displaySide = order.side === '0' ? 'YES' : order.side === '1' ? 'NO' : order.side
|
||||
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={order.orderId}
|
||||
@@ -240,9 +243,9 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
>
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
<div style={{
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
marginBottom: '8px',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
@@ -252,9 +255,9 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
<Tag>{displaySide}</Tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<Divider style={{ margin: '12px 0' }} />
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.sellInfo') || '卖出信息'}</div>
|
||||
<div style={{ fontSize: '14px', fontWeight: '500' }}>
|
||||
@@ -264,32 +267,32 @@ const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId }) => {
|
||||
{t('copyTradingOrders.amount') || '金额'}: {formatUSDC(amount)} USDC
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.realizedPnl') || '已实现盈亏'}</div>
|
||||
<div style={{
|
||||
fontSize: '16px',
|
||||
<div style={{
|
||||
fontSize: '16px',
|
||||
fontWeight: 'bold',
|
||||
color: getPnlColor(order.realizedPnl)
|
||||
}}>
|
||||
{formatUSDC(order.realizedPnl)} USDC
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.leaderTradeId') || 'Leader 交易ID'}</div>
|
||||
<div style={{ fontSize: '12px', color: '#999', fontFamily: 'monospace' }}>
|
||||
{order.leaderTradeId.slice(0, 8)}...{order.leaderTradeId.slice(-6)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.marketId') || '市场ID'}</div>
|
||||
<div style={{ fontSize: '12px', color: '#999', fontFamily: 'monospace' }}>
|
||||
{order.marketId.slice(0, 8)}...{order.marketId.slice(-6)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#999' }}>
|
||||
{t('copyTradingOrders.createdAt') || '创建时间'}: {formattedDate}
|
||||
|
||||
@@ -22,13 +22,13 @@ const CopyTradingOrdersModal: React.FC<CopyTradingOrdersModalProps> = ({
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
const [activeTab, setActiveTab] = useState<TabType>(defaultTab)
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setActiveTab(defaultTab)
|
||||
}
|
||||
}, [open, defaultTab])
|
||||
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('copyTradingOrders.title') || '订单列表'}
|
||||
@@ -38,25 +38,26 @@ const CopyTradingOrdersModal: React.FC<CopyTradingOrdersModalProps> = ({
|
||||
width="90%"
|
||||
style={{ top: 20 }}
|
||||
bodyStyle={{ padding: '24px', maxHeight: 'calc(100vh - 100px)', overflow: 'auto' }}
|
||||
destroyOnClose
|
||||
>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={(key) => setActiveTab(key as TabType)}
|
||||
items={[
|
||||
{
|
||||
key: 'buy',
|
||||
label: t('copyTradingOrders.buyOrders') || '买入订单',
|
||||
children: <BuyOrdersTab copyTradingId={copyTradingId} />
|
||||
children: <BuyOrdersTab copyTradingId={copyTradingId} active={activeTab === 'buy'} />
|
||||
},
|
||||
{
|
||||
key: 'sell',
|
||||
label: t('copyTradingOrders.sellOrders') || '卖出订单',
|
||||
children: <SellOrdersTab copyTradingId={copyTradingId} />
|
||||
children: <SellOrdersTab copyTradingId={copyTradingId} active={activeTab === 'sell'} />
|
||||
},
|
||||
{
|
||||
key: 'matched',
|
||||
label: t('copyTradingOrders.matchedOrders') || '匹配关系',
|
||||
children: <MatchedOrdersTab copyTradingId={copyTradingId} />
|
||||
children: <MatchedOrdersTab copyTradingId={copyTradingId} active={activeTab === 'matched'} />
|
||||
}
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -399,10 +399,10 @@ const PositionList: React.FC = () => {
|
||||
})
|
||||
if (response.data.code === 0 && response.data.data) {
|
||||
setMarketPrice(response.data.data)
|
||||
// 默认使用最优买价作为限价
|
||||
if (response.data.data.bestBid) {
|
||||
setLimitPrice(response.data.data.bestBid)
|
||||
form.setFieldsValue({ limitPrice: response.data.data.bestBid })
|
||||
// 默认使用当前价格作为限价
|
||||
if (response.data.data.currentPrice) {
|
||||
setLimitPrice(response.data.data.currentPrice)
|
||||
form.setFieldsValue({ limitPrice: response.data.data.currentPrice })
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
@@ -449,12 +449,10 @@ const PositionList: React.FC = () => {
|
||||
}
|
||||
|
||||
// 获取当前卖出价格(市价或限价)
|
||||
// 卖出操作应该使用 bestBid(最优买价),因为你要卖给愿意买入的人
|
||||
const getCurrentSellPrice = (): string => {
|
||||
if (orderType === 'MARKET') {
|
||||
// 市价订单(卖出):优先使用最优买价(bestBid),因为卖出是卖给买单
|
||||
// 如果没有 bestBid,则使用当前价格,最后使用最新成交价
|
||||
return marketPrice?.bestBid || selectedPosition?.currentPrice || marketPrice?.lastPrice || '0'
|
||||
// 市价订单(卖出):使用当前价格
|
||||
return marketPrice?.currentPrice || selectedPosition?.currentPrice || '0'
|
||||
}
|
||||
return limitPrice || '0'
|
||||
}
|
||||
@@ -1377,7 +1375,7 @@ const PositionList: React.FC = () => {
|
||||
// 切换订单类型时重新计算收益
|
||||
if (sellQuantity) {
|
||||
const price = e.target.value === 'MARKET'
|
||||
? (marketPrice?.bestBid || selectedPosition?.currentPrice || marketPrice?.lastPrice || '0')
|
||||
? (marketPrice?.currentPrice || selectedPosition?.currentPrice || '0')
|
||||
: limitPrice || '0'
|
||||
calculatePnl(sellQuantity, price)
|
||||
}
|
||||
@@ -1457,9 +1455,9 @@ const PositionList: React.FC = () => {
|
||||
}}
|
||||
placeholder="请输入限价价格"
|
||||
/>
|
||||
{marketPrice?.bestBid && (
|
||||
{marketPrice?.currentPrice && (
|
||||
<div style={{ marginTop: '4px', fontSize: '12px', color: '#999' }}>
|
||||
参考价格(最优买价,卖出参考): {formatNumber(marketPrice.bestBid, 4)}
|
||||
参考价格(卖出参考): {formatNumber(marketPrice.currentPrice, 4)}
|
||||
</div>
|
||||
)}
|
||||
</Form.Item>
|
||||
@@ -1469,21 +1467,14 @@ const PositionList: React.FC = () => {
|
||||
<div style={{ marginBottom: '16px', padding: '12px', background: '#f0f7ff', borderRadius: '8px' }}>
|
||||
<div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>市价参考(卖出)</div>
|
||||
<div style={{ fontSize: '14px' }}>
|
||||
{marketPrice?.bestBid ? (
|
||||
<>最优买价(卖出参考): <span style={{ fontWeight: '500' }}>{formatNumber(marketPrice.bestBid, 4)}</span></>
|
||||
{marketPrice?.currentPrice ? (
|
||||
<>当前价格: <span style={{ fontWeight: '500' }}>{formatNumber(marketPrice.currentPrice, 4)}</span></>
|
||||
) : selectedPosition?.currentPrice ? (
|
||||
<>当前价格: <span style={{ fontWeight: '500' }}>{formatNumber(selectedPosition.currentPrice, 4)}</span></>
|
||||
) : marketPrice?.lastPrice ? (
|
||||
<>最新成交价: <span style={{ fontWeight: '500' }}>{formatNumber(marketPrice.lastPrice, 4)}</span></>
|
||||
) : (
|
||||
<span style={{ color: '#999' }}>暂无价格数据</span>
|
||||
)}
|
||||
</div>
|
||||
{marketPrice?.bestAsk && (
|
||||
<div style={{ fontSize: '12px', color: '#999', marginTop: '4px' }}>
|
||||
最优卖价(买入参考): {formatNumber(marketPrice.bestAsk, 4)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -127,23 +127,24 @@ const TemplateAdd: React.FC = () => {
|
||||
tooltip={t('templateAdd.copyRatioTooltip') || '跟单比例表示跟单金额相对于 Leader 订单金额的百分比。例如:100% 表示 1:1 跟单,50% 表示半仓跟单,200% 表示双倍跟单'}
|
||||
>
|
||||
<InputNumber
|
||||
min={10}
|
||||
max={1000}
|
||||
step={1}
|
||||
precision={0}
|
||||
min={0.01}
|
||||
max={10000}
|
||||
step={0.01}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="%"
|
||||
placeholder={t('templateAdd.copyRatioPlaceholder') || '例如:100 表示 100%(1:1 跟单),默认 100%'}
|
||||
parser={(value) => {
|
||||
const parsed = parseFloat(value || '0')
|
||||
if (parsed > 1000) return 1000
|
||||
if (parsed > 10000) return 10000
|
||||
return parsed
|
||||
}}
|
||||
formatter={(value) => {
|
||||
if (!value) return ''
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (num > 1000) return '1000'
|
||||
return value.toString()
|
||||
if (isNaN(num)) return ''
|
||||
if (num > 10000) return '10000'
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
@@ -177,6 +178,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateAdd.fixedAmountPlaceholder') || '固定金额,不随 Leader 订单大小变化,必须 >= 1'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -194,6 +201,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateAdd.maxOrderSizePlaceholder') || '仅在比例模式下生效(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -221,6 +234,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateAdd.minOrderSizePlaceholder') || '仅在比例模式下生效,必须 >= 1(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
@@ -251,6 +270,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateAdd.priceTolerancePlaceholder') || '默认 5%(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -265,6 +290,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateAdd.minOrderDepthPlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -279,6 +310,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateAdd.maxSpreadPlaceholder') || '例如:0.05(5美分,可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -298,6 +335,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('templateAdd.minPricePlaceholder') || '最低价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<span style={{ display: 'inline-block', width: '20px', textAlign: 'center', lineHeight: '32px' }}>-</span>
|
||||
@@ -309,6 +352,12 @@ const TemplateAdd: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('templateAdd.maxPricePlaceholder') || '最高价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Input.Group>
|
||||
|
||||
@@ -162,23 +162,24 @@ const TemplateEdit: React.FC = () => {
|
||||
tooltip={t('templateEdit.copyRatioTooltip') || '跟单比例表示跟单金额相对于 Leader 订单金额的百分比。例如:100% 表示 1:1 跟单,50% 表示半仓跟单,200% 表示双倍跟单'}
|
||||
>
|
||||
<InputNumber
|
||||
min={10}
|
||||
max={1000}
|
||||
step={1}
|
||||
precision={0}
|
||||
min={0.01}
|
||||
max={10000}
|
||||
step={0.01}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="%"
|
||||
placeholder={t('templateEdit.copyRatioPlaceholder') || '例如:100 表示 100%(1:1 跟单),默认 100%'}
|
||||
parser={(value) => {
|
||||
const parsed = parseFloat(value || '0')
|
||||
if (parsed > 1000) return 1000
|
||||
if (parsed > 10000) return 10000
|
||||
return parsed
|
||||
}}
|
||||
formatter={(value) => {
|
||||
if (!value) return ''
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (num > 1000) return '1000'
|
||||
return value.toString()
|
||||
if (isNaN(num)) return ''
|
||||
if (num > 10000) return '10000'
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
@@ -213,6 +214,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateEdit.fixedAmountPlaceholder') || '固定金额,不随 Leader 订单大小变化,必须 >= 1'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -230,6 +237,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateEdit.maxOrderSizePlaceholder') || '仅在比例模式下生效(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -257,6 +270,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateEdit.minOrderSizePlaceholder') || '仅在比例模式下生效,必须 >= 1(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
@@ -287,6 +306,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateEdit.priceTolerancePlaceholder') || '默认 5%(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -301,6 +326,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateEdit.minOrderDepthPlaceholder') || '例如:100(可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -315,6 +346,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('templateEdit.maxSpreadPlaceholder') || '例如:0.05(5美分,可选,不填写表示不启用)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -334,6 +371,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('templateEdit.minPricePlaceholder') || '最低价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<span style={{ display: 'inline-block', width: '20px', textAlign: 'center', lineHeight: '32px' }}>-</span>
|
||||
@@ -345,6 +388,12 @@ const TemplateEdit: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder={t('templateEdit.maxPricePlaceholder') || '最高价(可选)'}
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Input.Group>
|
||||
|
||||
@@ -471,23 +471,24 @@ const TemplateList: React.FC = () => {
|
||||
tooltip="跟单比例表示跟单金额相对于 Leader 订单金额的百分比。例如:100% 表示 1:1 跟单,50% 表示半仓跟单,200% 表示双倍跟单"
|
||||
>
|
||||
<InputNumber
|
||||
min={10}
|
||||
max={1000}
|
||||
step={1}
|
||||
precision={0}
|
||||
min={0.01}
|
||||
max={10000}
|
||||
step={0.01}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="%"
|
||||
placeholder="例如:100 表示 100%(1:1 跟单),默认 100%"
|
||||
parser={(value) => {
|
||||
const parsed = parseFloat(value || '0')
|
||||
if (parsed > 1000) return 1000
|
||||
if (parsed > 10000) return 10000
|
||||
return parsed
|
||||
}}
|
||||
formatter={(value) => {
|
||||
if (!value) return ''
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (num > 1000) return '1000'
|
||||
return value.toString()
|
||||
if (isNaN(num)) return ''
|
||||
if (num > 10000) return '10000'
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
@@ -520,6 +521,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder="固定金额,不随 Leader 订单大小变化,必须 >= 1"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
@@ -537,6 +544,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder="仅在比例模式下生效(可选)"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -564,6 +577,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder="仅在比例模式下生效,必须 >= 1(可选)"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
@@ -594,6 +613,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
placeholder="默认 5%(可选)"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -619,6 +644,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder="例如:100(可选,不填写表示不启用)"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -633,6 +664,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '100%' }}
|
||||
placeholder="例如:0.05(5美分,可选,不填写表示不启用)"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -652,6 +689,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder="最低价(留空不限制)"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<span style={{ display: 'inline-block', width: '20px', textAlign: 'center', lineHeight: '32px' }}>-</span>
|
||||
@@ -663,6 +706,12 @@ const TemplateList: React.FC = () => {
|
||||
precision={4}
|
||||
style={{ width: '50%' }}
|
||||
placeholder="最高价(留空不限制)"
|
||||
formatter={(value) => {
|
||||
if (!value && value !== 0) return ''
|
||||
const num = parseFloat(value.toString())
|
||||
if (isNaN(num)) return ''
|
||||
return num.toString().replace(/\.0+$/, '')
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Input.Group>
|
||||
|
||||
@@ -181,18 +181,25 @@ export const apiService = {
|
||||
*/
|
||||
login: (data: { username: string; password: string }) =>
|
||||
apiClient.post<ApiResponse<{ token: string }>>('/auth/login', data),
|
||||
|
||||
|
||||
/**
|
||||
* 重置密码
|
||||
*/
|
||||
resetPassword: (data: { resetKey: string; username: string; newPassword: string }) =>
|
||||
apiClient.post<ApiResponse<void>>('/auth/reset-password', data),
|
||||
|
||||
|
||||
/**
|
||||
* 检查是否首次使用
|
||||
*/
|
||||
checkFirstUse: () =>
|
||||
apiClient.post<ApiResponse<{ isFirstUse: boolean }>>('/auth/check-first-use', {})
|
||||
apiClient.post<ApiResponse<{ isFirstUse: boolean }>>('/auth/check-first-use', {}),
|
||||
|
||||
/**
|
||||
* 获取 WebSocket 连接票据
|
||||
* 返回一个短期有效(30秒)的一次性票据
|
||||
*/
|
||||
getWebSocketTicket: () =>
|
||||
apiClient.post<ApiResponse<{ ticket: string }>>('/auth/ws-ticket', {})
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -51,30 +51,33 @@ class WebSocketManager {
|
||||
|
||||
/**
|
||||
* 连接 WebSocket(全局共享连接)
|
||||
* 使用短期票据认证,避免在 URL 中暴露 JWT
|
||||
*/
|
||||
connect(): void {
|
||||
async connect(): Promise<void> {
|
||||
// 检查是否有token,未登录不允许连接
|
||||
const token = this.getToken()
|
||||
if (!token) {
|
||||
console.log('[WebSocket] 未登录,不建立连接')
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 如果已经连接或正在连接,直接返回
|
||||
if (this.ws?.readyState === WebSocket.OPEN || this.isConnecting) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 如果正在卸载,不允许连接
|
||||
if (this.isUnmounting) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
this.isConnecting = true
|
||||
const wsUrl = this.getWebSocketUrl()
|
||||
console.log('[WebSocket] 正在连接:', wsUrl)
|
||||
|
||||
|
||||
try {
|
||||
// 获取短期票据
|
||||
const wsUrl = await this.getWebSocketUrl()
|
||||
console.log('[WebSocket] 正在连接...')
|
||||
|
||||
// 如果已经有连接(但状态不是 OPEN),先关闭
|
||||
if (this.ws) {
|
||||
try {
|
||||
@@ -84,10 +87,10 @@ class WebSocketManager {
|
||||
}
|
||||
this.ws = null
|
||||
}
|
||||
|
||||
|
||||
const ws = new WebSocket(wsUrl)
|
||||
this.ws = ws
|
||||
|
||||
|
||||
ws.onopen = () => {
|
||||
console.log('[WebSocket] 连接成功')
|
||||
this.isConnecting = false
|
||||
@@ -95,17 +98,17 @@ class WebSocketManager {
|
||||
this.startPing()
|
||||
this.resubscribeAll() // 重新订阅所有频道
|
||||
}
|
||||
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
this.handleMessage(event.data)
|
||||
}
|
||||
|
||||
|
||||
ws.onerror = (error) => {
|
||||
console.error('[WebSocket] 连接错误:', error)
|
||||
this.isConnecting = false
|
||||
this.notifyConnectionStatus(false)
|
||||
}
|
||||
|
||||
|
||||
ws.onclose = () => {
|
||||
console.log('[WebSocket] 连接关闭')
|
||||
this.isConnecting = false
|
||||
@@ -324,14 +327,14 @@ class WebSocketManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 WebSocket URL(带token认证)
|
||||
* 获取 WebSocket URL(使用短期票据认证)
|
||||
* 默认使用相对路径 /ws(通过反向代理转发)
|
||||
* 如果设置了 VITE_WS_URL 环境变量,则使用完整 URL(用于跨域场景)
|
||||
*/
|
||||
private getWebSocketUrl(): string {
|
||||
private async getWebSocketUrl(): Promise<string> {
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL
|
||||
let wsBaseUrl: string
|
||||
|
||||
|
||||
if (envWsUrl) {
|
||||
// 如果设置了环境变量,使用完整 URL(支持跨域)
|
||||
wsBaseUrl = envWsUrl
|
||||
@@ -341,10 +344,22 @@ class WebSocketManager {
|
||||
const host = window.location.host
|
||||
wsBaseUrl = `${protocol}//${host}`
|
||||
}
|
||||
|
||||
|
||||
// 获取短期票据(避免在 URL 中暴露 JWT)
|
||||
// 使用动态导入避免循环依赖
|
||||
try {
|
||||
const { apiService } = await import('./api')
|
||||
const response = await apiService.auth.getWebSocketTicket()
|
||||
if (response.data.code === 0 && response.data.data?.ticket) {
|
||||
return `${wsBaseUrl}/ws?ticket=${encodeURIComponent(response.data.data.ticket)}`
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[WebSocket] 获取票据失败,尝试使用 token 认证:', error)
|
||||
}
|
||||
|
||||
// 兼容旧方式:如果获取票据失败,回退到使用 token(不推荐)
|
||||
const token = this.getToken()
|
||||
if (token) {
|
||||
// 通过查询参数传递token
|
||||
return `${wsBaseUrl}/ws?token=${encodeURIComponent(token)}`
|
||||
}
|
||||
return `${wsBaseUrl}/ws`
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface Account {
|
||||
proxyAddress: string // Polymarket 代理钱包地址
|
||||
accountName?: string
|
||||
isEnabled?: boolean // 是否启用
|
||||
walletType?: string // 钱包类型:magic(邮箱/OAuth登录)或 safe(MetaMask浏览器钱包)
|
||||
apiKeyConfigured: boolean
|
||||
apiSecretConfigured: boolean
|
||||
apiPassphraseConfigured: boolean
|
||||
@@ -42,6 +43,7 @@ export interface AccountImportRequest {
|
||||
privateKey: string
|
||||
walletAddress: string
|
||||
accountName?: string
|
||||
walletType?: string // 钱包类型:magic(邮箱/OAuth登录)或 safe(MetaMask浏览器钱包)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -434,14 +436,11 @@ export interface MarketPriceRequest {
|
||||
}
|
||||
|
||||
/**
|
||||
* 市场价格响应
|
||||
* 市场当前价格响应
|
||||
*/
|
||||
export interface MarketPriceResponse {
|
||||
marketId: string
|
||||
lastPrice?: string
|
||||
bestBid?: string
|
||||
bestAsk?: string
|
||||
midpoint?: string
|
||||
currentPrice: string
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,3 +1,34 @@
|
||||
/**
|
||||
* 格式化数字,自动去除尾随零
|
||||
* @param value - 数字值(字符串或数字)
|
||||
* @param maxDecimals - 最大小数位数(默认不限制)
|
||||
* @returns 格式化后的字符串,如果值为空或无效则返回 ''
|
||||
* @example
|
||||
* formatNumber(100.00) => "100"
|
||||
* formatNumber(100.50) => "100.5"
|
||||
* formatNumber(100.55) => "100.55"
|
||||
*/
|
||||
export const formatNumber = (value: string | number | undefined | null, maxDecimals?: number): string => {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return ''
|
||||
}
|
||||
|
||||
const num = typeof value === 'string' ? parseFloat(value) : value
|
||||
if (isNaN(num)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
// 如果有最大小数位数限制,先截断
|
||||
if (maxDecimals !== undefined) {
|
||||
const multiplier = Math.pow(10, maxDecimals)
|
||||
const truncated = Math.floor(num * multiplier) / multiplier
|
||||
return truncated.toFixed(maxDecimals).replace(/\.?0+$/, '')
|
||||
}
|
||||
|
||||
// 直接转换为字符串,然后去除尾随零
|
||||
return num.toString().replace(/\.?0+$/, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化 USDC 金额
|
||||
* 最多显示 4 位小数,自动去除尾随零(截断,不四舍五入)
|
||||
|
||||
Reference in New Issue
Block a user