82 lines
2.6 KiB
Python
82 lines
2.6 KiB
Python
"""
|
|
统计分析API
|
|
"""
|
|
from fastapi import APIRouter, Query
|
|
import sys
|
|
from pathlib import Path
|
|
from datetime import datetime, timedelta
|
|
|
|
project_root = Path(__file__).parent.parent.parent.parent
|
|
sys.path.insert(0, str(project_root))
|
|
sys.path.insert(0, str(project_root / 'backend'))
|
|
|
|
from database.models import AccountSnapshot, Trade, MarketScan, TradingSignal
|
|
from fastapi import HTTPException
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/performance")
|
|
async def get_performance_stats(days: int = Query(7, ge=1, le=365)):
|
|
"""获取性能统计"""
|
|
try:
|
|
# 账户快照
|
|
snapshots = AccountSnapshot.get_recent(days)
|
|
|
|
# 交易统计
|
|
start_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
|
trades = Trade.get_all(start_date=start_date)
|
|
|
|
return {
|
|
"snapshots": snapshots,
|
|
"trades": trades,
|
|
"period": f"Last {days} days"
|
|
}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.get("/dashboard")
|
|
async def get_dashboard_data():
|
|
"""获取仪表板数据"""
|
|
try:
|
|
account_data = None
|
|
|
|
# 优先尝试获取实时账户数据
|
|
try:
|
|
from api.routes.account import get_realtime_account_data
|
|
account_data = await get_realtime_account_data()
|
|
except Exception as e:
|
|
logger.warning(f"获取实时账户数据失败,使用数据库快照: {e}")
|
|
# 回退到数据库快照
|
|
snapshots = AccountSnapshot.get_recent(1)
|
|
account_data = snapshots[0] if snapshots else None
|
|
|
|
# 获取持仓数据(优先实时,回退到数据库)
|
|
open_trades = []
|
|
try:
|
|
from api.routes.account import get_realtime_positions
|
|
positions = await get_realtime_positions()
|
|
# 转换为前端需要的格式
|
|
open_trades = positions
|
|
except Exception as e:
|
|
logger.warning(f"获取实时持仓失败,使用数据库记录: {e}")
|
|
# 回退到数据库记录
|
|
open_trades = Trade.get_all(status='open')[:10]
|
|
|
|
# 最近的扫描记录
|
|
recent_scans = MarketScan.get_recent(10)
|
|
|
|
# 最近的信号
|
|
recent_signals = TradingSignal.get_recent(20)
|
|
|
|
return {
|
|
"account": account_data,
|
|
"open_trades": open_trades,
|
|
"recent_scans": recent_scans,
|
|
"recent_signals": recent_signals
|
|
}
|
|
except Exception as e:
|
|
logger.error(f"获取仪表板数据失败: {e}", exc_info=True)
|
|
raise HTTPException(status_code=500, detail=str(e))
|