主要变更: - 重构 models: 统一使用 SQLAlchemy ORM,分离 Pydantic schemas - 新增 service_manager: 服务启动/停止统一管理 - 新增 data_downloader: 基于 xtquant 的数据下载服务 - 简化 main.py: 只启动必要服务 (Redis, Database) - 更新 .gitignore: 排除 xtquant 数据目录
234 lines
7.9 KiB
Python
234 lines
7.9 KiB
Python
"""
|
|
资金管理服务
|
|
|
|
处理资金查询与调整
|
|
"""
|
|
|
|
from typing import Any, Optional
|
|
from datetime import datetime as dt
|
|
from decimal import Decimal
|
|
|
|
from sqlalchemy import select, func
|
|
|
|
from src.core.database import db
|
|
from src.core.logger import get_logger
|
|
from src.core.models import Pairing, Position, BalanceLog, BalanceLogType
|
|
|
|
logger = get_logger("core_service.balance_service")
|
|
|
|
|
|
class BalanceService:
|
|
"""资金管理服务"""
|
|
|
|
async def get_balance(self, pairing_id: str) -> Optional[dict[str, Any]]:
|
|
"""
|
|
获取配对资金
|
|
|
|
Args:
|
|
pairing_id: 配对ID
|
|
|
|
Returns:
|
|
资金信息
|
|
"""
|
|
async with db.session() as session:
|
|
stmt = select(Pairing).where(Pairing.id == pairing_id)
|
|
result = await session.execute(stmt)
|
|
pairing = result.scalar_one_or_none()
|
|
|
|
if not pairing:
|
|
return None
|
|
|
|
initial_capital = (
|
|
float(pairing.initial_capital) if pairing.initial_capital else 0
|
|
)
|
|
available_capital = (
|
|
float(pairing.available_capital) if pairing.available_capital else 0
|
|
)
|
|
|
|
# 计算持仓市值
|
|
position_stmt = select(
|
|
func.sum(Position.quantity * Position.avg_cost)
|
|
).where(
|
|
Position.pairing_id == pairing_id,
|
|
Position.quantity > 0,
|
|
)
|
|
position_result = await session.execute(position_stmt)
|
|
position_value = float(position_result.scalar() or 0)
|
|
|
|
# 总资产 = 可用资金 + 持仓市值
|
|
total_assets = available_capital + position_value
|
|
|
|
# 盈亏 = 总资产 - 初始资金
|
|
pnl = total_assets - initial_capital
|
|
pnl_ratio = pnl / initial_capital if initial_capital > 0 else 0
|
|
|
|
return {
|
|
"pairing_id": pairing.id,
|
|
"symbol": pairing.symbol,
|
|
"strategy_id": pairing.strategy_id,
|
|
"initial_capital": initial_capital,
|
|
"available_capital": available_capital,
|
|
"position_value": position_value,
|
|
"total_assets": total_assets,
|
|
"pnl": pnl,
|
|
"pnl_ratio": pnl_ratio,
|
|
"status": pairing.status.value if pairing.status else None,
|
|
"created_at": pairing.created_at.isoformat()
|
|
if pairing.created_at
|
|
else None,
|
|
"updated_at": pairing.updated_at.isoformat()
|
|
if pairing.updated_at
|
|
else None,
|
|
}
|
|
|
|
async def list_balances(
|
|
self,
|
|
strategy_id: Optional[str] = None,
|
|
) -> dict[str, Any]:
|
|
"""查询资金列表"""
|
|
async with db.session() as session:
|
|
stmt = select(Pairing)
|
|
if strategy_id:
|
|
stmt = stmt.where(Pairing.strategy_id == strategy_id)
|
|
stmt = stmt.order_by(Pairing.created_at.desc())
|
|
|
|
result = await session.execute(stmt)
|
|
pairings = result.scalars().all()
|
|
|
|
items = []
|
|
for pairing in pairings:
|
|
initial_capital = (
|
|
float(pairing.initial_capital) if pairing.initial_capital else 0
|
|
)
|
|
available_capital = (
|
|
float(pairing.available_capital) if pairing.available_capital else 0
|
|
)
|
|
|
|
# 计算持仓市值
|
|
position_stmt = select(
|
|
func.sum(Position.quantity * Position.avg_cost)
|
|
).where(
|
|
Position.pairing_id == pairing.id,
|
|
Position.quantity > 0,
|
|
)
|
|
position_result = await session.execute(position_stmt)
|
|
position_value = float(position_result.scalar() or 0)
|
|
|
|
total_assets = available_capital + position_value
|
|
pnl = total_assets - initial_capital
|
|
|
|
items.append(
|
|
{
|
|
"pairing_id": pairing.id,
|
|
"symbol": pairing.symbol,
|
|
"strategy_id": pairing.strategy_id,
|
|
"initial_capital": initial_capital,
|
|
"available_capital": available_capital,
|
|
"position_value": position_value,
|
|
"total_assets": total_assets,
|
|
"pnl": pnl,
|
|
"status": pairing.status.value if pairing.status else None,
|
|
}
|
|
)
|
|
|
|
return {
|
|
"items": items,
|
|
"total": len(items),
|
|
}
|
|
|
|
async def get_summary(self) -> dict[str, Any]:
|
|
"""获取资金汇总"""
|
|
async with db.session() as session:
|
|
# 汇总所有配对资金
|
|
stmt = select(
|
|
func.count(Pairing.id).label("pairing_count"),
|
|
func.sum(Pairing.initial_capital).label("total_initial"),
|
|
func.sum(Pairing.available_capital).label("total_available"),
|
|
)
|
|
result = await session.execute(stmt)
|
|
row = result.one()
|
|
|
|
total_initial = float(row.total_initial) if row.total_initial else 0
|
|
total_available = float(row.total_available) if row.total_available else 0
|
|
|
|
# 计算所有持仓市值
|
|
position_stmt = select(
|
|
func.sum(Position.quantity * Position.avg_cost)
|
|
).where(Position.quantity > 0)
|
|
position_result = await session.execute(position_stmt)
|
|
total_position_value = float(position_result.scalar() or 0)
|
|
|
|
total_assets = total_available + total_position_value
|
|
total_pnl = total_assets - total_initial
|
|
total_pnl_ratio = total_pnl / total_initial if total_initial > 0 else 0
|
|
|
|
return {
|
|
"pairing_count": row.pairing_count or 0,
|
|
"total_initial_capital": total_initial,
|
|
"total_available_capital": total_available,
|
|
"total_position_value": total_position_value,
|
|
"total_assets": total_assets,
|
|
"total_pnl": total_pnl,
|
|
"total_pnl_ratio": total_pnl_ratio,
|
|
}
|
|
|
|
async def adjust_balance(
|
|
self,
|
|
pairing_id: str,
|
|
amount: float,
|
|
reason: str,
|
|
) -> Optional[dict[str, Any]]:
|
|
"""
|
|
调整资金
|
|
|
|
Args:
|
|
pairing_id: 配对ID
|
|
amount: 调整金额(正数增加,负数减少)
|
|
reason: 调整原因
|
|
|
|
Returns:
|
|
调整后的资金信息
|
|
"""
|
|
now = dt.now()
|
|
amount_decimal = Decimal(str(amount))
|
|
|
|
async with db.session() as session:
|
|
# 检查配对是否存在
|
|
stmt = select(Pairing).where(Pairing.id == pairing_id)
|
|
result = await session.execute(stmt)
|
|
pairing = result.scalar_one_or_none()
|
|
|
|
if not pairing:
|
|
return None
|
|
|
|
new_initial = (pairing.initial_capital or Decimal(0)) + amount_decimal
|
|
new_available = (pairing.available_capital or Decimal(0)) + amount_decimal
|
|
|
|
if new_initial < 0 or new_available < 0:
|
|
raise ValueError("资金不足,无法调整")
|
|
|
|
# 更新资金
|
|
pairing.initial_capital = new_initial
|
|
pairing.available_capital = new_available
|
|
pairing.updated_at = now
|
|
|
|
# 记录调整日志
|
|
log = BalanceLog(
|
|
pairing_id=pairing_id,
|
|
log_type=BalanceLogType.ADJUST,
|
|
amount=amount_decimal,
|
|
balance_after=new_available,
|
|
description=reason,
|
|
created_at=now,
|
|
)
|
|
session.add(log)
|
|
await session.commit()
|
|
|
|
logger.info(f"资金调整: {pairing_id}, {amount}, {reason}")
|
|
|
|
return await self.get_balance(pairing_id)
|
|
|
|
|
|
# 单例
|
|
balance_service = BalanceService()
|