feat: 实现回测功能

## 功能概述
实现完整的回测功能,支持基于历史数据模拟跟单策略的执行效果。

## 后端实现
- 数据库:新增 backtest_task 和 backtest_trade 表(V27迁移脚本)
- 实体类:BacktestTask、BacktestTrade
- Repository:BacktestTaskRepository、BacktestTradeRepository
- Service:
  - BacktestService:回测任务管理(CRUD)
  - BacktestDataService:从 Polymarket Data API 获取历史交易数据
  - BacktestExecutionService:回测算法核心实现
  - BacktestPollingService:定时轮询执行回测任务
- Controller:BacktestController(6个API接口)
- DTO:BacktestDto、TradeData
- 错误码:新增回测相关错误码和国际化消息

## 前端实现
- 页面组件:
  - BacktestList:回测任务列表
  - BacktestCreate:创建回测任务
  - BacktestDetail:回测详情(含图表)
  - BacktestChart:资金曲线图表(使用 ECharts)
- 类型定义:backtest.ts
- API 服务:集成所有回测接口
- 国际化:支持中英文

## 核心特性
- 回测天数限制:1-15 天
- 数据获取:直接从 Polymarket Data API 获取历史交易(不使用缓存表)
- 任务执行:同一时刻只执行一个任务,按创建时间顺序执行最早创建的任务
- 回测算法:完整实现市场结算、卖出匹配、价格容忍度、每日订单限制等规则
- 实时进度:支持任务进度更新和实时轮询

## 文档更新
- BACKTEST_PRD.md:产品需求文档
- BACKTEST_TECHNICAL_DESIGN.md:技术设计文档
- BACKTEST_REVIEW_CHECKLIST.md:设计评审检查清单

## 其他修改
- 移除 max_position_count 配置(V26迁移脚本)
- 移除 BacktestSyncService(不再需要实时同步)
- 修复前后端编译错误
This commit is contained in:
WrBug
2026-01-31 07:27:36 +08:00
parent fabbd81f22
commit cdd02e9f3d
34 changed files with 4880 additions and 76 deletions
+216
View File
@@ -0,0 +1,216 @@
import { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { useTranslation } from 'react-i18next'
interface BacktestChartProps {
trades: {
tradeTime: number
balanceAfter: string
}[]
}
const BacktestChart: React.FC<BacktestChartProps> = ({ trades }) => {
const { t } = useTranslation()
const chartRef = useRef<HTMLDivElement>(null)
const chartInstance = useRef<echarts.ECharts | null>(null)
useEffect(() => {
if (!chartRef.current) return
// 初始化图表
chartInstance.current = echarts.init(chartRef.current)
// 监听窗口大小变化
const handleResize = () => {
chartInstance.current?.resize()
}
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
chartInstance.current?.dispose()
}
}, [])
useEffect(() => {
if (!chartInstance.current || trades.length === 0) return
// 准备数据
const data = trades.map((trade) => ({
time: new Date(trade.tradeTime).toLocaleString(),
value: parseFloat(trade.balanceAfter)
}))
// 初始余额(第一笔交易前的余额)
const initialBalance = data[0]?.value || 0
// 数据压缩:如果数据点太多,进行采样
const maxPoints = 500 // 最多显示500个点
let compressedData = data
if (data.length > maxPoints) {
const step = Math.ceil(data.length / maxPoints)
compressedData = data.filter((_, index) => index % step === 0)
// 确保最后一个点被包含
if (compressedData[compressedData.length - 1] !== data[data.length - 1]) {
compressedData.push(data[data.length - 1])
}
}
const times = compressedData.map(item => item.time)
const values = compressedData.map(item => item.value)
const option: EChartsOption = {
tooltip: {
trigger: 'axis',
formatter: (params: any) => {
const param = params[0]
const value = parseFloat(param.value).toFixed(2)
const diffValue = param.value - initialBalance
const diff = diffValue.toFixed(2)
const diffPercent = (diffValue / initialBalance * 100).toFixed(2)
const color = diffValue >= 0 ? '#52c41a' : '#ff4d4f'
return `
<div>
<div>${t('backtest.tradeTime')}: ${param.name}</div>
<div>${t('backtest.balanceAfter')}: ${value} USDC</div>
<div style="color: ${color}">
${t('backtest.profitLoss')}: ${diff} USDC (${diffPercent}%)
</div>
</div>
`
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
top: '8%',
containLabel: true
},
xAxis: {
type: 'category',
data: times,
axisLabel: {
rotate: 45,
formatter: (value: string) => {
// 简化时间显示,只显示 HH:mm
const parts = value.split(' ')
if (parts.length > 1) {
const timeParts = parts[1].split(':')
if (timeParts.length >= 2) {
return `${timeParts[0]}:${timeParts[1]}`
}
}
return value
}
},
axisLine: {
lineStyle: {
color: '#e0e0e0'
}
},
axisTick: {
alignWithLabel: true,
lineStyle: {
color: '#e0e0e0'
}
}
},
yAxis: {
type: 'value',
name: 'USDC',
nameLocation: 'end',
nameGap: 10,
axisLabel: {
formatter: (value: number) => value.toFixed(2)
},
splitLine: {
lineStyle: {
color: '#f0f0f0'
}
},
axisLine: {
lineStyle: {
color: '#e0e0e0'
}
}
},
series: [
{
name: t('backtest.balanceAfter'),
type: 'line',
data: values,
smooth: true,
symbol: 'circle',
symbolSize: 4,
lineStyle: {
width: 2,
color: '#1890ff'
},
itemStyle: {
color: '#1890ff'
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
{ offset: 1, color: 'rgba(24, 144, 255, 0.05)' }
]
}
},
markLine: {
data: [
{
name: t('backtest.initialBalance'),
yAxis: initialBalance,
label: {
formatter: `${t('backtest.initialBalance')}: ${initialBalance.toFixed(2)}`
},
lineStyle: {
type: 'dashed',
color: '#999',
width: 1
}
}
]
}
}
],
dataZoom: [
{
type: 'inside',
start: 0,
end: 100
},
{
type: 'slider',
start: 0,
end: 100,
height: 20,
bottom: 20
}
]
}
chartInstance.current.setOption(option)
}, [trades, t])
return (
<div
ref={chartRef}
style={{
width: '100%',
height: 400
}}
/>
)
}
export default BacktestChart
+408
View File
@@ -0,0 +1,408 @@
import { useState, useEffect } from 'react'
import { Card, Form, Button, Input, InputNumber, Select, Switch, message, Space, Row, Col } from 'antd'
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { backtestService } from '../services/api'
import { apiService } from '../services/api'
import type { Leader } from '../types'
import type { BacktestCreateRequest } from '../types/backtest'
const { Option } = Select
const BacktestCreate: React.FC = () => {
const { t } = useTranslation()
const navigate = useNavigate()
const [form] = Form.useForm()
const [loading, setLoading] = useState(false)
const [leaders, setLeaders] = useState<Leader[]>([])
const [copyMode, setCopyMode] = useState<'RATIO' | 'FIXED'>('RATIO')
// 获取 Leader 列表
useEffect(() => {
const fetchLeaders = async () => {
try {
const response = await apiService.leaders.list({})
if (response.data.code === 0 && response.data.data) {
setLeaders(response.data.data.list || [])
}
} catch (error) {
console.error('Failed to fetch leaders:', error)
}
}
fetchLeaders()
}, [])
// 提交表单
const handleSubmit = async () => {
try {
const values = await form.validateFields()
setLoading(true)
const request: BacktestCreateRequest = {
taskName: values.taskName,
leaderId: values.leaderId,
initialBalance: values.initialBalance,
backtestDays: values.backtestDays,
copyMode: values.copyMode || 'RATIO',
copyRatio: values.copyMode === 'RATIO' ? values.copyRatio : undefined,
fixedAmount: values.copyMode === 'FIXED' ? values.fixedAmount : undefined,
maxOrderSize: values.maxOrderSize,
minOrderSize: values.minOrderSize,
maxDailyLoss: values.maxDailyLoss,
maxDailyOrders: values.maxDailyOrders,
priceTolerance: values.priceTolerance,
delaySeconds: values.delaySeconds,
supportSell: values.supportSell,
minOrderDepth: values.minOrderDepth,
maxSpread: values.maxSpread,
minPrice: values.minPrice,
maxPrice: values.maxPrice,
maxPositionValue: values.maxPositionValue,
keywordFilterMode: values.keywordFilterMode,
keywords: values.keywords,
maxMarketEndDate: values.maxMarketEndDate
}
const response = await backtestService.create(request)
if (response.data.code === 0) {
message.success(t('backtest.createSuccess'))
navigate('/backtest/list')
} else {
message.error(response.data.msg || t('backtest.createFailed'))
}
} catch (error) {
console.error('Failed to create backtest task:', error)
message.error(t('backtest.createFailed'))
} finally {
setLoading(false)
}
}
// 返回
const handleBack = () => {
navigate('/backtest/list')
}
// 初始化表单默认值
useEffect(() => {
form.setFieldsValue({
copyMode: 'RATIO',
copyRatio: 1.0,
maxOrderSize: 1000,
minOrderSize: 1,
maxDailyLoss: 500,
maxDailyOrders: 50,
priceTolerance: 5,
delaySeconds: 0,
supportSell: true,
keywordFilterMode: 'DISABLED',
backtestDays: 7
})
}, [form])
return (
<div style={{ padding: 24, maxWidth: 1200, margin: '0 auto' }}>
<Card
title={t('backtest.createTask')}
extra={
<Button icon={<ArrowLeftOutlined />} onClick={handleBack}>
{t('common.back')}
</Button>
}
>
<Form
form={form}
layout="vertical"
onFinish={handleSubmit}
initialValues={{
copyMode: 'RATIO',
copyRatio: 1.0,
maxOrderSize: 1000,
minOrderSize: 1,
maxDailyLoss: 500,
maxDailyOrders: 50,
priceTolerance: 5,
delaySeconds: 0,
supportSell: true,
keywordFilterMode: 'DISABLED',
backtestDays: 7
}}
>
<Row gutter={24}>
<Col span={12}>
<Form.Item
label={t('backtest.taskName')}
name="taskName"
rules={[{ required: true, message: t('backtest.taskNameRequired') || '请输入任务名称' }]}
>
<Input placeholder={t('backtest.taskName')} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
label={t('backtest.leader')}
name="leaderId"
rules={[{ required: true, message: t('backtest.leaderRequired') || '请选择 Leader' }]}
>
<Select placeholder={t('backtest.leader')} showSearch>
{leaders.map((leader) => (
<Option key={leader.id} value={leader.id}>
{leader.leaderName || leader.leaderAddress}
</Option>
))}
</Select>
</Form.Item>
</Col>
</Row>
<Row gutter={24}>
<Col span={12}>
<Form.Item
label={t('backtest.initialBalance') + ' (USDC)'}
name="initialBalance"
rules={[
{ required: true, message: t('backtest.initialBalanceRequired') || '请输入初始资金' },
{ type: 'number', min: 1, message: t('backtest.initialBalanceInvalid') || '初始资金必须大于 0' }
]}
>
<InputNumber
style={{ width: '100%' }}
placeholder={t('backtest.initialBalance')}
precision={2}
min={1}
/>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
label={t('backtest.backtestDays') + ` (1-15 ${t('common.day')})`}
name="backtestDays"
rules={[
{ required: true, message: t('backtest.backtestDaysRequired') || '请输入回测天数' },
{ type: 'number', min: 1, max: 15, message: t('backtest.backtestDaysInvalid') || '回测天数必须在 1-15 之间' }
]}
>
<InputNumber
style={{ width: '100%' }}
placeholder={t('backtest.backtestDays')}
precision={0}
min={1}
max={15}
/>
</Form.Item>
</Col>
</Row>
{/* 跟单配置 */}
<div style={{ marginBottom: 24 }}>
<h3 style={{ marginBottom: 16 }}>{t('backtest.config')}</h3>
<Form.Item
label={t('backtest.copyMode')}
name="copyMode"
>
<Select onChange={(value) => setCopyMode(value)}>
<Option value="RATIO">{t('backtest.copyModeRatio')}</Option>
<Option value="FIXED">{t('backtest.copyModeFixed')}</Option>
</Select>
</Form.Item>
{copyMode === 'RATIO' && (
<Form.Item
label={t('backtest.copyRatio')}
name="copyRatio"
rules={[
{ required: true, message: t('backtest.copyRatioRequired') || '请输入跟单比例' },
{ type: 'number', min: 0.01, max: 10, message: t('backtest.copyRatioInvalid') || '跟单比例必须在 0.01-10 之间' }
]}
>
<InputNumber
style={{ width: '100%' }}
placeholder={t('backtest.copyRatio')}
precision={2}
min={0.01}
max={10}
step={0.01}
/>
</Form.Item>
)}
{copyMode === 'FIXED' && (
<Form.Item
label={t('backtest.fixedAmount') + ' (USDC)'}
name="fixedAmount"
rules={[
{ required: true, message: t('backtest.fixedAmountRequired') || '请输入固定金额' },
{ type: 'number', min: 1, message: t('backtest.fixedAmountInvalid') || '固定金额必须大于 0' }
]}
>
<InputNumber
style={{ width: '100%' }}
placeholder={t('backtest.fixedAmount')}
precision={2}
min={1}
/>
</Form.Item>
)}
<Row gutter={24}>
<Col span={12}>
<Form.Item
label={t('backtest.maxOrderSize') + ' (USDC)'}
name="maxOrderSize"
rules={[{ required: true }]}
>
<InputNumber style={{ width: '100%' }} precision={2} min={1} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
label={t('backtest.minOrderSize') + ' (USDC)'}
name="minOrderSize"
rules={[{ required: true }]}
>
<InputNumber style={{ width: '100%' }} precision={2} min={1} />
</Form.Item>
</Col>
</Row>
<Row gutter={24}>
<Col span={12}>
<Form.Item
label={t('backtest.maxDailyLoss') + ' (USDC)'}
name="maxDailyLoss"
rules={[{ required: true }]}
>
<InputNumber style={{ width: '100%' }} precision={2} min={0} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
label={t('backtest.maxDailyOrders')}
name="maxDailyOrders"
rules={[{ required: true }]}
>
<InputNumber style={{ width: '100%' }} precision={0} min={1} />
</Form.Item>
</Col>
</Row>
<Form.Item
label={t('backtest.priceTolerance') + ' (%)'}
name="priceTolerance"
>
<InputNumber style={{ width: '100%' }} precision={2} min={0} max={100} />
</Form.Item>
<Form.Item
label={t('backtest.delaySeconds')}
name="delaySeconds"
>
<InputNumber style={{ width: '100%' }} precision={0} min={0} />
<span style={{ fontSize: 12, color: '#888' }}>{t('backtest.delaySecondsHint') || '延迟执行模拟真实跟单延迟'}</span>
</Form.Item>
<Form.Item
label={t('backtest.supportSell')}
name="supportSell"
valuePropName="checked"
>
<Switch />
<span style={{ fontSize: 12, color: '#888', marginLeft: 8 }}>{t('backtest.supportSellHint') || '是否跟随 Leader 的卖出操作'}</span>
</Form.Item>
<h4 style={{ marginTop: 24, marginBottom: 16 }}>{t('backtest.advancedFilters')}</h4>
<Row gutter={24}>
<Col span={12}>
<Form.Item
label={t('backtest.minOrderDepth') + ' (USDC)'}
name="minOrderDepth"
>
<InputNumber style={{ width: '100%' }} precision={2} min={0} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
label={t('backtest.maxSpread') + ' (%)'}
name="maxSpread"
>
<InputNumber style={{ width: '100%' }} precision={2} min={0} />
</Form.Item>
</Col>
</Row>
<Row gutter={24}>
<Col span={12}>
<Form.Item
label={t('backtest.minPrice')}
name="minPrice"
>
<InputNumber style={{ width: '100%' }} precision={4} min={0} max={1} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
label={t('backtest.maxPrice')}
name="maxPrice"
>
<InputNumber style={{ width: '100%' }} precision={4} min={0} max={1} />
</Form.Item>
</Col>
</Row>
<Form.Item
label={t('backtest.maxPositionValue') + ' (USDC)'}
name="maxPositionValue"
>
<InputNumber style={{ width: '100%' }} precision={2} min={0} />
</Form.Item>
<Form.Item
label={t('backtest.keywordFilterMode')}
name="keywordFilterMode"
>
<Select>
<Option value="DISABLED">{t('backtest.keywordFilterModeDisabled')}</Option>
<Option value="WHITELIST">{t('backtest.keywordFilterModeWhitelist')}</Option>
<Option value="BLACKLIST">{t('backtest.keywordFilterModeBlacklist')}</Option>
</Select>
</Form.Item>
<Form.Item
label={t('backtest.keywords')}
name="keywords"
>
<Select
mode="tags"
style={{ width: '100%' }}
placeholder={t('backtest.keywordsPlaceholder') || '请输入关键字,按回车添加'}
/>
</Form.Item>
</div>
{/* 底部按钮 */}
<Form.Item>
<Space>
<Button onClick={handleBack}>
{t('common.cancel')}
</Button>
<Button
type="primary"
htmlType="submit"
icon={<SaveOutlined />}
loading={loading}
>
{t('common.save')}
</Button>
</Space>
</Form.Item>
</Form>
</Card>
</div>
)
}
export default BacktestCreate
+470
View File
@@ -0,0 +1,470 @@
import { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Card, Descriptions, Button, Tag, Space, Table, message, Row, Col, Statistic, Spin } from 'antd'
import { ArrowLeftOutlined, ReloadOutlined, DeleteOutlined, StopOutlined } from '@ant-design/icons'
import { useTranslation } from 'react-i18next'
import { formatUSDC } from '../utils'
import { backtestService } from '../services/api'
import type { BacktestTaskDto, BacktestConfigDto, BacktestStatisticsDto, BacktestTradeDto } from '../types/backtest'
import BacktestChart from './BacktestChart'
const BacktestDetail: React.FC = () => {
const { t } = useTranslation()
const { id } = useParams<{ id: string }>()
const [loading, setLoading] = useState(false)
const [task, setTask] = useState<BacktestTaskDto | null>(null)
const [, setConfig] = useState<BacktestConfigDto | null>(null)
const [statistics, setStatistics] = useState<BacktestStatisticsDto | null>(null)
const [trades, setTrades] = useState<BacktestTradeDto[]>([])
const [tradesLoading, setTradesLoading] = useState(false)
const [tradesTotal, setTradesTotal] = useState(0)
const [tradesPage, setTradesPage] = useState(1)
const [tradesSize] = useState(20)
const [polling, setPolling] = useState<NodeJS.Timeout | null>(null)
// 获取回测任务详情
const fetchTaskDetail = async () => {
setLoading(true)
try {
const response = await backtestService.detail({ id: parseInt(id!) })
if (response.data.code === 0 && response.data.data) {
setTask(response.data.data.task)
setConfig(response.data.data.config)
setStatistics(response.data.data.statistics)
} else {
message.error(response.data.msg || t('backtest.fetchTaskDetailFailed'))
}
} catch (error) {
console.error('Failed to fetch backtest task detail:', error)
message.error(t('backtest.fetchTaskDetailFailed'))
} finally {
setLoading(false)
}
}
// 获取交易记录
const fetchTrades = async (page: number) => {
setTradesLoading(true)
try {
const response = await backtestService.trades({
taskId: parseInt(id!),
page,
size: tradesSize
})
if (response.data.code === 0 && response.data.data) {
setTrades(response.data.data.list)
setTradesTotal(response.data.data.total)
} else {
message.error(response.data.msg || t('backtest.fetchTradesFailed'))
}
} catch (error) {
console.error('Failed to fetch backtest trades:', error)
message.error(t('backtest.fetchTradesFailed'))
} finally {
setTradesLoading(false)
}
}
useEffect(() => {
fetchTaskDetail()
fetchTrades(tradesPage)
// 如果任务正在运行,启动轮询
const startPolling = () => {
const timer = setInterval(() => {
fetchTaskDetail()
// 如果任务已完成或失败,停止轮询
if (task?.status === 'COMPLETED' || task?.status === 'FAILED' || task?.status === 'STOPPED') {
stopPolling()
}
}, 3000) // 每3秒轮询一次
setPolling(timer)
}
// 延迟启动轮询,等待任务状态加载完成
setTimeout(() => {
if (task?.status === 'RUNNING' || task?.status === 'PENDING') {
startPolling()
}
}, 1000)
return () => {
stopPolling()
}
}, [id, task?.status])
const stopPolling = () => {
if (polling) {
clearInterval(polling)
setPolling(null)
}
}
// 返回
const handleBack = () => {
window.location.href = '/backtest/list'
}
// 停止任务
const handleStop = () => {
if (!window.confirm(t('backtest.stopConfirm'))) return
const stop = async () => {
try {
const response = await backtestService.stop({ id: parseInt(id!) })
if (response.data.code === 0) {
message.success(t('backtest.stopSuccess'))
fetchTaskDetail()
stopPolling()
} else {
message.error(response.data.msg || t('backtest.stopFailed'))
}
} catch (error) {
console.error('Failed to stop backtest task:', error)
message.error(t('backtest.stopFailed'))
}
}
stop()
}
// 删除任务
const handleDelete = () => {
if (!window.confirm(t('backtest.deleteConfirm'))) return
const del = async () => {
try {
const response = await backtestService.delete({ id: parseInt(id!) })
if (response.data.code === 0) {
message.success(t('backtest.deleteSuccess'))
window.location.href = '/backtest/list'
} else {
message.error(response.data.msg || t('backtest.deleteFailed'))
}
} catch (error) {
console.error('Failed to delete backtest task:', error)
message.error(t('backtest.deleteFailed'))
}
}
del()
}
// 刷新
const handleRefresh = () => {
fetchTaskDetail()
fetchTrades(tradesPage)
}
// 状态标签颜色
const getStatusColor = (status: string) => {
switch (status) {
case 'PENDING': return 'blue'
case 'RUNNING': return 'processing'
case 'COMPLETED': return 'success'
case 'STOPPED': return 'warning'
case 'FAILED': return 'error'
default: return 'default'
}
}
// 状态标签文本
const getStatusText = (status: string) => {
switch (status) {
case 'PENDING': return t('backtest.statusPending')
case 'RUNNING': return t('backtest.statusRunning')
case 'COMPLETED': return t('backtest.statusCompleted')
case 'STOPPED': return t('backtest.statusStopped')
case 'FAILED': return t('backtest.statusFailed')
default: return status
}
}
const columns = [
{
title: t('backtest.tradeTime'),
dataIndex: 'tradeTime',
key: 'tradeTime',
width: 180,
render: (timestamp: number) => new Date(timestamp).toLocaleString()
},
{
title: t('backtest.marketTitle'),
dataIndex: 'marketTitle',
key: 'marketTitle',
width: 250,
ellipsis: true
},
{
title: t('backtest.side'),
dataIndex: 'side',
key: 'side',
width: 100,
render: (side: string) => (
<Tag color={side === 'BUY' ? 'green' : side === 'SELL' ? 'orange' : 'blue'}>
{side === 'BUY' ? t('backtest.sideBuy') : side === 'SELL' ? t('backtest.sideSell') : t('backtest.sideSettlement')}
</Tag>
)
},
{
title: t('backtest.outcome'),
dataIndex: 'outcome',
key: 'outcome',
width: 100
},
{
title: t('backtest.quantity'),
dataIndex: 'quantity',
key: 'quantity',
width: 100,
render: (value: string) => parseFloat(value).toFixed(4)
},
{
title: t('backtest.price'),
dataIndex: 'price',
key: 'price',
width: 100,
render: (value: string) => parseFloat(value).toFixed(4)
},
{
title: t('backtest.amount') + ' (USDC)',
dataIndex: 'amount',
key: 'amount',
width: 120,
render: (value: string) => formatUSDC(value)
},
{
title: t('backtest.fee') + ' (USDC)',
dataIndex: 'fee',
key: 'fee',
width: 120,
render: (value: string) => formatUSDC(value)
},
{
title: t('backtest.profitLoss') + ' (USDC)',
dataIndex: 'profitLoss',
key: 'profitLoss',
width: 120,
render: (value: string | null) => value ? (
<span style={{ color: parseFloat(value) >= 0 ? '#52c41a' : '#ff4d4f' }}>
{formatUSDC(value)}
</span>
) : '-'
},
{
title: t('backtest.balanceAfter') + ' (USDC)',
dataIndex: 'balanceAfter',
key: 'balanceAfter',
width: 120,
render: (value: string) => formatUSDC(value)
},
{
title: t('backtest.leaderTradeId'),
dataIndex: 'leaderTradeId',
key: 'leaderTradeId',
width: 150,
ellipsis: true
}
]
if (!task) {
return <div style={{ padding: 24, textAlign: 'center' }}><Spin /></div>
}
return (
<div style={{ padding: 24 }}>
<Card>
{/* 头部操作栏 */}
<Space direction="vertical" size="large" style={{ width: '100%' }}>
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
<Space>
<Button icon={<ArrowLeftOutlined />} onClick={handleBack}>
{t('common.back')}
</Button>
<Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
{t('common.refresh')}
</Button>
</Space>
<Space>
{(task.status === 'RUNNING' || task.status === 'PENDING') && (
<Button danger icon={<StopOutlined />} onClick={handleStop}>
{t('backtest.statusStopped')}
</Button>
)}
{(task.status === 'COMPLETED' || task.status === 'STOPPED' || task.status === 'FAILED') && (
<Button danger icon={<DeleteOutlined />} onClick={handleDelete}>
{t('common.delete')}
</Button>
)}
</Space>
</Space>
{/* 任务基本信息 */}
<Card title={t('backtest.taskDetail')} size="small">
<Descriptions column={2} bordered size="small">
<Descriptions.Item label={t('backtest.taskName')}>{task.taskName}</Descriptions.Item>
<Descriptions.Item label={t('backtest.leader')}>
{task.leaderName || task.leaderAddress}
</Descriptions.Item>
<Descriptions.Item label={t('backtest.initialBalance')}>
{formatUSDC(task.initialBalance)} USDC
</Descriptions.Item>
<Descriptions.Item label={t('backtest.finalBalance')}>
{task.finalBalance ? formatUSDC(task.finalBalance) + ' USDC' : '-'}
</Descriptions.Item>
<Descriptions.Item label={t('backtest.profitAmount')}>
<span style={{ color: task.profitAmount && parseFloat(task.profitAmount) >= 0 ? '#52c41a' : '#ff4d4f' }}>
{task.profitAmount ? formatUSDC(task.profitAmount) + ' USDC' : '-'}
</span>
</Descriptions.Item>
<Descriptions.Item label={t('backtest.profitRate')}>
<span style={{ color: task.profitRate && parseFloat(task.profitRate) >= 0 ? '#52c41a' : '#ff4d4f' }}>
{task.profitRate ? task.profitRate + '%' : '-'}
</span>
</Descriptions.Item>
<Descriptions.Item label={t('backtest.backtestDays')}>
{task.backtestDays} {t('common.day')}
</Descriptions.Item>
<Descriptions.Item label={t('backtest.status')}>
<Tag color={getStatusColor(task.status)}>{getStatusText(task.status)}</Tag>
</Descriptions.Item>
<Descriptions.Item label={t('backtest.progress')}>
{task.progress}%
</Descriptions.Item>
<Descriptions.Item label={t('backtest.totalTrades')}>
{task.totalTrades}
</Descriptions.Item>
<Descriptions.Item label={t('backtest.startTime')}>
{new Date(task.startTime).toLocaleString()}
</Descriptions.Item>
<Descriptions.Item label={t('backtest.endTime')}>
{task.endTime ? new Date(task.endTime).toLocaleString() : '-'}
</Descriptions.Item>
<Descriptions.Item label={t('backtest.createdAt')}>
{new Date(task.createdAt).toLocaleString()}
</Descriptions.Item>
</Descriptions>
</Card>
{/* 统计信息 */}
{statistics && (
<Row gutter={16}>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.buyTrades')}
value={statistics.buyTrades}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.sellTrades')}
value={statistics.sellTrades}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.winTrades')}
value={statistics.winTrades}
valueStyle={{ color: '#52c41a' }}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.lossTrades')}
value={statistics.lossTrades}
valueStyle={{ color: '#ff4d4f' }}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.winRate')}
value={statistics.winRate}
suffix="%"
valueStyle={{ color: parseFloat(statistics.winRate) >= 50 ? '#52c41a' : '#ff4d4f' }}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.maxProfit')}
value={formatUSDC(statistics.maxProfit)}
valueStyle={{ color: '#52c41a' }}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.maxLoss')}
value={formatUSDC(statistics.maxLoss)}
valueStyle={{ color: '#ff4d4f' }}
/>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={t('backtest.maxDrawdown')}
value={formatUSDC(statistics.maxDrawdown)}
valueStyle={{ color: '#ff4d4f' }}
/>
</Card>
</Col>
{statistics.avgHoldingTime && (
<Col span={6}>
<Card>
<Statistic
title={t('backtest.avgHoldingTime')}
value={(statistics.avgHoldingTime / 1000 / 60).toFixed(2)}
suffix=" min"
/>
</Card>
</Col>
)}
</Row>
)}
{/* 资金变化图表 */}
{trades.length > 0 && (
<Card title={t('backtest.balanceChart')}>
<BacktestChart trades={trades} />
</Card>
)}
{/* 交易记录 */}
<Card title={t('backtest.tradeRecords')}>
<Table
columns={columns}
dataSource={trades}
rowKey="id"
loading={tradesLoading}
pagination={{
current: tradesPage,
pageSize: tradesSize,
total: tradesTotal,
showSizeChanger: false,
showTotal: (total) => `${t('common.total')} ${total} ${t('common.items')}`,
onChange: (newPage) => {
setTradesPage(newPage)
fetchTrades(newPage)
}
}}
scroll={{ x: 1800 }}
/>
</Card>
</Space>
</Card>
</div>
)
}
export default BacktestDetail
+364
View File
@@ -0,0 +1,364 @@
import { useState, useEffect } from 'react'
import { Table, Card, Button, Select, Tag, Space, Modal, message, Row, Col } from 'antd'
import { useTranslation } from 'react-i18next'
import { PlusOutlined, ReloadOutlined, DeleteOutlined, StopOutlined, EyeOutlined } from '@ant-design/icons'
import { formatUSDC } from '../utils'
import { backtestService } from '../services/api'
import type { BacktestTaskDto, BacktestListRequest } from '../types/backtest'
const BacktestList: React.FC = () => {
const { t } = useTranslation()
const [loading, setLoading] = useState(false)
const [tasks, setTasks] = useState<BacktestTaskDto[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [size] = useState(10)
const [statusFilter, setStatusFilter] = useState<string | undefined>()
const [leaderIdFilter] = useState<number | undefined>()
const [sortBy, setSortBy] = useState<'profitAmount' | 'profitRate' | 'createdAt'>('createdAt')
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
// 获取回测任务列表
const fetchTasks = async () => {
setLoading(true)
try {
const request: BacktestListRequest = {
leaderId: leaderIdFilter,
status: statusFilter as any,
sortBy,
sortOrder,
page,
size
}
const response = await backtestService.list(request)
if (response.data.code === 0 && response.data.data) {
setTasks(response.data.data.list)
setTotal(response.data.data.total)
} else {
message.error(response.data.msg || t('backtest.fetchTasksFailed'))
}
} catch (error) {
console.error('Failed to fetch backtest tasks:', error)
message.error(t('backtest.fetchTasksFailed'))
} finally {
setLoading(false)
}
}
useEffect(() => {
fetchTasks()
}, [page, statusFilter, leaderIdFilter, sortBy, sortOrder])
// 刷新
const handleRefresh = () => {
fetchTasks()
}
// 删除任务
const handleDelete = (id: number) => {
Modal.confirm({
title: t('backtest.deleteConfirm'),
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: async () => {
try {
const response = await backtestService.delete({ id })
if (response.data.code === 0) {
message.success(t('backtest.deleteSuccess'))
fetchTasks()
} else {
message.error(response.data.msg || t('backtest.deleteFailed'))
}
} catch (error) {
console.error('Failed to delete backtest task:', error)
message.error(t('backtest.deleteFailed'))
}
}
})
}
// 停止任务
const handleStop = (id: number) => {
Modal.confirm({
title: t('backtest.stopConfirm'),
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: async () => {
try {
const response = await backtestService.stop({ id })
if (response.data.code === 0) {
message.success(t('backtest.stopSuccess'))
fetchTasks()
} else {
message.error(response.data.msg || t('backtest.stopFailed'))
}
} catch (error) {
console.error('Failed to stop backtest task:', error)
message.error(t('backtest.stopFailed'))
}
}
})
}
// 查看详情
const handleViewDetail = (id: number) => {
window.location.href = `/backtest/detail?id=${id}`
}
// 创建新任务
const handleCreate = () => {
window.location.href = '/backtest/create'
}
// 状态标签颜色
const getStatusColor = (status: string) => {
switch (status) {
case 'PENDING': return 'blue'
case 'RUNNING': return 'processing'
case 'COMPLETED': return 'success'
case 'STOPPED': return 'warning'
case 'FAILED': return 'error'
default: return 'default'
}
}
// 状态标签文本
const getStatusText = (status: string) => {
switch (status) {
case 'PENDING': return t('backtest.statusPending')
case 'RUNNING': return t('backtest.statusRunning')
case 'COMPLETED': return t('backtest.statusCompleted')
case 'STOPPED': return t('backtest.statusStopped')
case 'FAILED': return t('backtest.statusFailed')
default: return status
}
}
const columns = [
{
title: t('backtest.taskName'),
dataIndex: 'taskName',
key: 'taskName',
width: 150
},
{
title: t('backtest.leader'),
dataIndex: 'leaderName',
key: 'leaderName',
width: 150
},
{
title: t('backtest.initialBalance'),
dataIndex: 'initialBalance',
key: 'initialBalance',
width: 120,
render: (value: string) => formatUSDC(value)
},
{
title: t('backtest.finalBalance'),
dataIndex: 'finalBalance',
key: 'finalBalance',
width: 120,
render: (value: string | null) => value ? formatUSDC(value) : '-'
},
{
title: t('backtest.profitAmount'),
dataIndex: 'profitAmount',
key: 'profitAmount',
width: 120,
render: (value: string | null) => value ? (
<span style={{ color: parseFloat(value) >= 0 ? '#52c41a' : '#ff4d4f' }}>
{formatUSDC(value)}
</span>
) : '-'
},
{
title: t('backtest.profitRate'),
dataIndex: 'profitRate',
key: 'profitRate',
width: 100,
render: (value: string | null) => value ? (
<span style={{ color: parseFloat(value) >= 0 ? '#52c41a' : '#ff4d4f' }}>
{value}%
</span>
) : '-'
},
{
title: t('backtest.backtestDays'),
dataIndex: 'backtestDays',
key: 'backtestDays',
width: 100,
render: (value: number) => `${value} ${t('common.day')}`
},
{
title: t('backtest.status'),
dataIndex: 'status',
key: 'status',
width: 100,
render: (status: string) => (
<Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
)
},
{
title: t('backtest.progress'),
dataIndex: 'progress',
key: 'progress',
width: 120,
render: (progress: number) => (
<div style={{ width: '100%' }}>
<div style={{ marginBottom: 4 }}>{progress}%</div>
<div style={{ width: '100%', height: 6, backgroundColor: '#f0f0f0', borderRadius: 3 }}>
<div
style={{
width: `${progress}%`,
height: '100%',
backgroundColor: progress === 100 ? '#52c41a' : '#1890ff',
borderRadius: 3,
transition: 'width 0.3s ease'
}}
/>
</div>
</div>
)
},
{
title: t('backtest.totalTrades'),
dataIndex: 'totalTrades',
key: 'totalTrades',
width: 100
},
{
title: t('backtest.createdAt'),
dataIndex: 'createdAt',
key: 'createdAt',
width: 180,
render: (timestamp: number) => new Date(timestamp).toLocaleString()
},
{
title: t('common.actions'),
key: 'actions',
fixed: 'right' as const,
width: 150,
render: (_: any, record: BacktestTaskDto) => (
<Space size="small">
<Button
type="link"
size="small"
icon={<EyeOutlined />}
onClick={() => handleViewDetail(record.id)}
>
{t('common.viewDetail')}
</Button>
{(record.status === 'RUNNING' || record.status === 'PENDING') && (
<Button
type="link"
size="small"
danger
icon={<StopOutlined />}
onClick={() => handleStop(record.id)}
>
{t('backtest.statusStopped')}
</Button>
)}
{(record.status === 'COMPLETED' || record.status === 'STOPPED' || record.status === 'FAILED') && (
<Button
type="link"
size="small"
danger
icon={<DeleteOutlined />}
onClick={() => handleDelete(record.id)}
>
{t('common.delete')}
</Button>
)}
</Space>
)
}
]
return (
<div style={{ padding: 24 }}>
<Card>
<Space direction="vertical" size="large" style={{ width: '100%' }}>
{/* 头部操作栏 */}
<Row justify="space-between" align="middle">
<Col>
<Space size="middle">
<Select
style={{ width: 150 }}
placeholder={t('backtest.status')}
allowClear
onChange={(value) => setStatusFilter(value)}
value={statusFilter}
>
<Select.Option value="PENDING">{t('backtest.statusPending')}</Select.Option>
<Select.Option value="RUNNING">{t('backtest.statusRunning')}</Select.Option>
<Select.Option value="COMPLETED">{t('backtest.statusCompleted')}</Select.Option>
<Select.Option value="STOPPED">{t('backtest.statusStopped')}</Select.Option>
<Select.Option value="FAILED">{t('backtest.statusFailed')}</Select.Option>
</Select>
<Select
style={{ width: 150 }}
placeholder={t('backtest.sortBy')}
onChange={(value) => setSortBy(value)}
value={sortBy}
>
<Select.Option value="profitAmount">{t('backtest.profitAmount')}</Select.Option>
<Select.Option value="profitRate">{t('backtest.profitRate')}</Select.Option>
<Select.Option value="createdAt">{t('backtest.createdAt')}</Select.Option>
</Select>
<Select
style={{ width: 120 }}
placeholder={t('backtest.sortOrder')}
onChange={(value) => setSortOrder(value)}
value={sortOrder}
>
<Select.Option value="asc">{t('common.ascending')}</Select.Option>
<Select.Option value="desc">{t('common.descending')}</Select.Option>
</Select>
</Space>
</Col>
<Col>
<Space>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={handleCreate}
>
{t('backtest.createTask')}
</Button>
<Button
icon={<ReloadOutlined />}
onClick={handleRefresh}
loading={loading}
>
{t('common.refresh')}
</Button>
</Space>
</Col>
</Row>
{/* 数据表格 */}
<Table
columns={columns}
dataSource={tasks}
rowKey="id"
loading={loading}
pagination={{
current: page,
pageSize: size,
total,
showSizeChanger: false,
showTotal: (total) => `${t('common.total')} ${total} ${t('common.items')}`,
onChange: (newPage) => setPage(newPage)
}}
scroll={{ x: 1400 }}
/>
</Space>
</Card>
</div>
)
}
export default BacktestList