939 lines
42 KiB
Python
939 lines
42 KiB
Python
"""
|
||
账户实时数据API - 从币安API获取实时账户和订单数据
|
||
"""
|
||
from fastapi import APIRouter, HTTPException
|
||
import sys
|
||
from pathlib import Path
|
||
import logging
|
||
|
||
project_root = Path(__file__).parent.parent.parent.parent
|
||
sys.path.insert(0, str(project_root))
|
||
sys.path.insert(0, str(project_root / 'backend'))
|
||
sys.path.insert(0, str(project_root / 'trading_system'))
|
||
|
||
from database.models import TradingConfig
|
||
|
||
logger = logging.getLogger(__name__)
|
||
router = APIRouter()
|
||
|
||
|
||
async def get_realtime_account_data():
|
||
"""从币安API实时获取账户数据"""
|
||
logger.info("=" * 60)
|
||
logger.info("开始获取实时账户数据")
|
||
logger.info("=" * 60)
|
||
|
||
try:
|
||
# 从数据库读取API密钥
|
||
logger.info("步骤1: 从数据库读取API配置...")
|
||
api_key = TradingConfig.get_value('BINANCE_API_KEY')
|
||
api_secret = TradingConfig.get_value('BINANCE_API_SECRET')
|
||
use_testnet = TradingConfig.get_value('USE_TESTNET', False)
|
||
|
||
logger.info(f" - API密钥存在: {bool(api_key)}")
|
||
if api_key:
|
||
logger.info(f" - API密钥长度: {len(api_key)} 字符")
|
||
logger.info(f" - API密钥前缀: {api_key[:10]}...")
|
||
else:
|
||
logger.warning(" - API密钥为空!")
|
||
|
||
logger.info(f" - API密钥存在: {bool(api_secret)}")
|
||
if api_secret:
|
||
logger.info(f" - API密钥长度: {len(api_secret)} 字符")
|
||
logger.info(f" - API密钥前缀: {api_secret[:10]}...")
|
||
else:
|
||
logger.warning(" - API密钥为空!")
|
||
|
||
logger.info(f" - 使用测试网: {use_testnet}")
|
||
|
||
if not api_key or not api_secret:
|
||
error_msg = "API密钥未配置,请在配置界面设置BINANCE_API_KEY和BINANCE_API_SECRET"
|
||
logger.error(f" ✗ {error_msg}")
|
||
raise HTTPException(
|
||
status_code=400,
|
||
detail=error_msg
|
||
)
|
||
|
||
# 导入交易系统的BinanceClient
|
||
logger.info("步骤2: 导入BinanceClient...")
|
||
try:
|
||
from binance_client import BinanceClient
|
||
logger.info(" ✓ 从当前路径导入BinanceClient成功")
|
||
except ImportError as e:
|
||
logger.warning(f" - 从当前路径导入失败: {e}")
|
||
# 如果直接导入失败,尝试从trading_system导入
|
||
trading_system_path = project_root / 'trading_system'
|
||
sys.path.insert(0, str(trading_system_path))
|
||
logger.info(f" - 添加路径到sys.path: {trading_system_path}")
|
||
try:
|
||
from binance_client import BinanceClient
|
||
logger.info(" ✓ 从trading_system路径导入BinanceClient成功")
|
||
except ImportError as e2:
|
||
logger.error(f" ✗ 导入BinanceClient失败: {e2}")
|
||
raise
|
||
|
||
# 创建客户端
|
||
logger.info("步骤3: 创建BinanceClient实例...")
|
||
client = BinanceClient(
|
||
api_key=api_key,
|
||
api_secret=api_secret,
|
||
testnet=use_testnet
|
||
)
|
||
logger.info(f" ✓ 客户端创建成功 (testnet={use_testnet})")
|
||
|
||
# 连接币安API
|
||
logger.info("步骤4: 连接币安API...")
|
||
try:
|
||
await client.connect()
|
||
logger.info(" ✓ 币安API连接成功")
|
||
except Exception as e:
|
||
logger.error(f" ✗ 币安API连接失败: {e}", exc_info=True)
|
||
raise
|
||
|
||
# 读取持仓模式(单向/对冲),用于前端“重点说明/自检”
|
||
dual_side_position = None
|
||
position_mode = None
|
||
try:
|
||
mode_res = await client.client.futures_get_position_mode()
|
||
if isinstance(mode_res, dict):
|
||
dual_side_position = bool(mode_res.get("dualSidePosition"))
|
||
position_mode = "hedge" if dual_side_position else "one_way"
|
||
except Exception as e:
|
||
logger.warning(f"读取持仓模式失败(将显示为未知): {e}")
|
||
|
||
# 获取账户余额
|
||
logger.info("步骤5: 获取账户余额...")
|
||
try:
|
||
balance = await client.get_account_balance()
|
||
logger.info(" ✓ 账户余额获取成功")
|
||
logger.info(f" - 返回数据类型: {type(balance)}")
|
||
logger.info(f" - 返回数据内容: {balance}")
|
||
if balance:
|
||
logger.info(f" - 总余额: {balance.get('total', 'N/A')} USDT")
|
||
logger.info(f" - 可用余额: {balance.get('available', 'N/A')} USDT")
|
||
logger.info(f" - 保证金: {balance.get('margin', 'N/A')} USDT")
|
||
|
||
if balance.get('total', 0) == 0:
|
||
logger.warning(" ⚠ 账户余额为0,可能是API权限问题或账户确实无余额")
|
||
else:
|
||
logger.warning(" ⚠ 返回的余额数据为空")
|
||
except Exception as e:
|
||
logger.error(f" ✗ 获取账户余额失败: {e}", exc_info=True)
|
||
raise
|
||
|
||
# 获取持仓
|
||
logger.info("步骤6: 获取持仓信息...")
|
||
try:
|
||
positions = await client.get_open_positions()
|
||
logger.info(" ✓ 持仓信息获取成功")
|
||
logger.info(f" - 返回数据类型: {type(positions)}")
|
||
logger.info(f" - 持仓数量: {len(positions)}")
|
||
|
||
if positions:
|
||
logger.info(" - 持仓详情:")
|
||
for i, pos in enumerate(positions[:5], 1): # 只显示前5个
|
||
logger.info(f" {i}. {pos.get('symbol', 'N/A')}: "
|
||
f"数量={pos.get('positionAmt', 0)}, "
|
||
f"入场价={pos.get('entryPrice', 0)}, "
|
||
f"盈亏={pos.get('unRealizedProfit', 0)}")
|
||
if len(positions) > 5:
|
||
logger.info(f" ... 还有 {len(positions) - 5} 个持仓")
|
||
else:
|
||
logger.info(" - 当前无持仓")
|
||
except Exception as e:
|
||
logger.error(f" ✗ 获取持仓信息失败: {e}", exc_info=True)
|
||
raise
|
||
|
||
# 计算总仓位价值和总盈亏
|
||
logger.info("步骤7: 计算仓位统计...")
|
||
# total_position_value:历史上这里代表“名义仓位价值(notional)”(按标记价)
|
||
total_position_value = 0
|
||
# total_margin_value:更贴近风控配置语义(保证金占用)
|
||
total_margin_value = 0
|
||
total_pnl = 0
|
||
open_positions_count = 0
|
||
|
||
for pos in positions:
|
||
position_amt = float(pos.get('positionAmt', 0))
|
||
if position_amt == 0:
|
||
continue
|
||
|
||
entry_price = float(pos.get('entryPrice', 0))
|
||
mark_price = float(pos.get('markPrice', 0))
|
||
unrealized_pnl = float(pos.get('unRealizedProfit', 0))
|
||
|
||
if mark_price == 0:
|
||
# 如果没有标记价格,使用入场价
|
||
mark_price = entry_price
|
||
|
||
position_value = abs(position_amt * mark_price)
|
||
total_position_value += position_value
|
||
|
||
# 保证金占用(粗略口径):名义/杠杆(币安页面的展示会更复杂,但这个口径与 MAX_TOTAL_POSITION_PERCENT 对齐)
|
||
try:
|
||
lv = float(pos.get('leverage', 0) or 0)
|
||
if lv <= 0:
|
||
lv = 1.0
|
||
except Exception:
|
||
lv = 1.0
|
||
total_margin_value += (position_value / lv)
|
||
total_pnl += unrealized_pnl
|
||
open_positions_count += 1
|
||
|
||
logger.debug(f" - {pos.get('symbol')}: 价值={position_value:.2f}, 盈亏={unrealized_pnl:.2f}")
|
||
|
||
logger.info(" ✓ 仓位统计计算完成")
|
||
logger.info(f" - 总名义仓位: {total_position_value:.2f} USDT")
|
||
logger.info(f" - 总保证金占用(估算): {total_margin_value:.2f} USDT")
|
||
logger.info(f" - 总盈亏: {total_pnl:.2f} USDT")
|
||
logger.info(f" - 持仓数量: {open_positions_count}")
|
||
|
||
# 断开连接
|
||
logger.info("步骤8: 断开币安API连接...")
|
||
try:
|
||
await client.disconnect()
|
||
logger.info(" ✓ 连接已断开")
|
||
except Exception as e:
|
||
logger.warning(f" ⚠ 断开连接时出错: {e}")
|
||
|
||
# 构建返回结果
|
||
result = {
|
||
"total_balance": balance.get('total', 0) if balance else 0,
|
||
"available_balance": balance.get('available', 0) if balance else 0,
|
||
# 名义仓位(按标记价汇总)
|
||
"total_position_value": total_position_value,
|
||
# 保证金占用(名义/杠杆汇总)
|
||
"total_margin_value": total_margin_value,
|
||
"total_pnl": total_pnl,
|
||
"open_positions": open_positions_count,
|
||
# 账户持仓模式(重点:建议使用 one_way)
|
||
"position_mode": position_mode,
|
||
"dual_side_position": dual_side_position,
|
||
}
|
||
|
||
logger.info("=" * 60)
|
||
logger.info("账户数据获取成功!")
|
||
logger.info(f"最终结果: {result}")
|
||
logger.info("=" * 60)
|
||
|
||
return result
|
||
|
||
except HTTPException as e:
|
||
logger.error("=" * 60)
|
||
logger.error(f"HTTP异常: {e.status_code} - {e.detail}")
|
||
logger.error("=" * 60)
|
||
raise
|
||
except Exception as e:
|
||
error_msg = f"获取账户数据失败: {str(e)}"
|
||
logger.error("=" * 60)
|
||
logger.error(f"异常类型: {type(e).__name__}")
|
||
logger.error(f"错误信息: {error_msg}")
|
||
logger.error("=" * 60, exc_info=True)
|
||
raise HTTPException(status_code=500, detail=error_msg)
|
||
|
||
|
||
@router.get("/realtime")
|
||
async def get_realtime_account():
|
||
"""获取实时账户数据"""
|
||
return await get_realtime_account_data()
|
||
|
||
|
||
@router.get("/positions")
|
||
async def get_realtime_positions():
|
||
"""获取实时持仓数据"""
|
||
client = None
|
||
try:
|
||
# 从数据库读取API密钥
|
||
api_key = TradingConfig.get_value('BINANCE_API_KEY')
|
||
api_secret = TradingConfig.get_value('BINANCE_API_SECRET')
|
||
use_testnet = TradingConfig.get_value('USE_TESTNET', False)
|
||
|
||
logger.info(f"尝试获取实时持仓数据 (testnet={use_testnet})")
|
||
|
||
if not api_key or not api_secret:
|
||
error_msg = "API密钥未配置"
|
||
logger.warning(error_msg)
|
||
raise HTTPException(
|
||
status_code=400,
|
||
detail=error_msg
|
||
)
|
||
|
||
# 导入BinanceClient
|
||
try:
|
||
from binance_client import BinanceClient
|
||
except ImportError:
|
||
trading_system_path = project_root / 'trading_system'
|
||
sys.path.insert(0, str(trading_system_path))
|
||
from binance_client import BinanceClient
|
||
|
||
client = BinanceClient(
|
||
api_key=api_key,
|
||
api_secret=api_secret,
|
||
testnet=use_testnet
|
||
)
|
||
|
||
logger.info("连接币安API获取持仓...")
|
||
await client.connect()
|
||
positions = await client.get_open_positions()
|
||
|
||
logger.info(f"获取到 {len(positions)} 个持仓")
|
||
|
||
# 格式化持仓数据
|
||
formatted_positions = []
|
||
for pos in positions:
|
||
position_amt = float(pos.get('positionAmt', 0))
|
||
if position_amt == 0:
|
||
continue
|
||
|
||
entry_price = float(pos.get('entryPrice', 0))
|
||
mark_price = float(pos.get('markPrice', 0))
|
||
unrealized_pnl = float(pos.get('unRealizedProfit', 0))
|
||
|
||
if mark_price == 0:
|
||
mark_price = entry_price
|
||
|
||
# === 名义/保证金口径说明(与币安展示更接近)===
|
||
# - 币安的名义价值/仓位价值通常随标记价(markPrice)变动
|
||
# - DB 中的 notional_usdt/margin_usdt 通常是“开仓时”写入,用于复盘/统计
|
||
# - 若发生部分止盈/减仓:币安 positionAmt 会变小,但 DB 里的 notional/margin 可能仍是“原始开仓量”
|
||
# → 会出现:数量=6.8,但名义/保证金像是 13.6 的两倍(与你反馈一致)
|
||
#
|
||
# 因此:实时持仓展示统一使用“当前数量×标记价”的实时名义/保证金,
|
||
# 并额外返回 original_* 字段保留 DB 开仓口径,避免混用导致误解。
|
||
|
||
# 兼容旧字段:entry_value_usdt 仍保留(但它是按入场价计算的名义)
|
||
entry_value_usdt = abs(position_amt) * entry_price
|
||
|
||
leverage = float(pos.get('leverage', 1))
|
||
if leverage <= 0:
|
||
leverage = 1.0
|
||
|
||
# 当前持仓名义价值(USDT):按标记价
|
||
notional_usdt_live = abs(position_amt) * mark_price
|
||
# 当前持仓保证金(USDT):名义/杠杆
|
||
margin_usdt_live = notional_usdt_live / leverage
|
||
pnl_percent = 0
|
||
if margin_usdt_live > 0:
|
||
pnl_percent = (unrealized_pnl / margin_usdt_live) * 100
|
||
|
||
# 尝试从数据库获取开仓时间、止损止盈价格(以及交易规模字段)
|
||
entry_time = None
|
||
stop_loss_price = None
|
||
take_profit_price = None
|
||
take_profit_1 = None
|
||
take_profit_2 = None
|
||
atr_value = None
|
||
db_margin_usdt = None
|
||
db_notional_usdt = None
|
||
entry_order_id = None
|
||
entry_order_type = None
|
||
try:
|
||
from database.models import Trade
|
||
db_trades = Trade.get_by_symbol(pos.get('symbol'), status='open')
|
||
if db_trades:
|
||
# 找到匹配的交易记录(优先通过 entry_price 近似匹配;否则取最新一条 open 记录兜底)
|
||
matched = None
|
||
for db_trade in db_trades:
|
||
try:
|
||
if abs(float(db_trade.get('entry_price', 0)) - entry_price) < 0.01:
|
||
matched = db_trade
|
||
break
|
||
except Exception:
|
||
continue
|
||
if matched is None:
|
||
matched = db_trades[0]
|
||
|
||
entry_time = matched.get('entry_time')
|
||
stop_loss_price = matched.get('stop_loss_price')
|
||
take_profit_price = matched.get('take_profit_price')
|
||
take_profit_1 = matched.get('take_profit_1')
|
||
take_profit_2 = matched.get('take_profit_2')
|
||
atr_value = matched.get('atr')
|
||
db_margin_usdt = matched.get('margin_usdt')
|
||
db_notional_usdt = matched.get('notional_usdt')
|
||
entry_order_id = matched.get('entry_order_id')
|
||
except Exception as e:
|
||
logger.debug(f"获取数据库信息失败: {e}")
|
||
|
||
# 如果数据库中有 entry_order_id,尝试从币安查询订单类型(LIMIT/MARKET)
|
||
if entry_order_id:
|
||
try:
|
||
info = await client.client.futures_get_order(symbol=pos.get('symbol'), orderId=int(entry_order_id))
|
||
if isinstance(info, dict):
|
||
entry_order_type = info.get("type")
|
||
except Exception:
|
||
entry_order_type = None
|
||
|
||
# 如果没有从数据库获取到止损止盈价格,前端会自己计算
|
||
# 注意:数据库可能没有存储止损止盈价格,这是正常的
|
||
|
||
formatted_positions.append({
|
||
"symbol": pos.get('symbol'),
|
||
"side": "BUY" if position_amt > 0 else "SELL",
|
||
"quantity": abs(position_amt),
|
||
"entry_price": entry_price,
|
||
# 兼容旧字段:entry_value_usdt 仍保留(前端已有使用)
|
||
"entry_value_usdt": entry_value_usdt,
|
||
# 实时展示字段:与币安更一致(按当前数量×标记价)
|
||
"notional_usdt": notional_usdt_live,
|
||
"margin_usdt": margin_usdt_live,
|
||
# 额外返回“开仓记录口径”(用于排查部分止盈/减仓导致的不一致)
|
||
"original_notional_usdt": db_notional_usdt,
|
||
"original_margin_usdt": db_margin_usdt,
|
||
"mark_price": mark_price,
|
||
"pnl": unrealized_pnl,
|
||
"pnl_percent": pnl_percent, # 基于保证金的盈亏百分比
|
||
"leverage": int(pos.get('leverage', 1)),
|
||
"entry_time": entry_time, # 开仓时间
|
||
"stop_loss_price": stop_loss_price, # 止损价格(如果可用)
|
||
"take_profit_price": take_profit_price, # 止盈价格(如果可用)
|
||
"take_profit_1": take_profit_1,
|
||
"take_profit_2": take_profit_2,
|
||
"atr": atr_value,
|
||
"entry_order_id": entry_order_id,
|
||
"entry_order_type": entry_order_type, # LIMIT / MARKET(用于仪表板展示“限价/市价”)
|
||
})
|
||
|
||
logger.info(f"格式化后 {len(formatted_positions)} 个有效持仓")
|
||
return formatted_positions
|
||
except HTTPException:
|
||
raise
|
||
except Exception as e:
|
||
error_msg = f"获取持仓数据失败: {str(e)}"
|
||
logger.error(error_msg, exc_info=True)
|
||
raise HTTPException(status_code=500, detail=error_msg)
|
||
finally:
|
||
# 确保断开连接(避免连接泄漏)
|
||
try:
|
||
if client is not None:
|
||
await client.disconnect()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
@router.post("/positions/{symbol}/close")
|
||
async def close_position(symbol: str):
|
||
"""手动平仓指定交易对的持仓"""
|
||
try:
|
||
logger.info(f"=" * 60)
|
||
logger.info(f"收到平仓请求: {symbol}")
|
||
logger.info(f"=" * 60)
|
||
|
||
# 从数据库读取API密钥
|
||
api_key = TradingConfig.get_value('BINANCE_API_KEY')
|
||
api_secret = TradingConfig.get_value('BINANCE_API_SECRET')
|
||
use_testnet = TradingConfig.get_value('USE_TESTNET', False)
|
||
|
||
if not api_key or not api_secret:
|
||
error_msg = "API密钥未配置"
|
||
logger.warning(error_msg)
|
||
raise HTTPException(status_code=400, detail=error_msg)
|
||
|
||
# 导入必要的模块
|
||
try:
|
||
from binance_client import BinanceClient
|
||
logger.info("✓ 成功导入交易系统模块")
|
||
except ImportError as import_error:
|
||
logger.warning(f"首次导入失败: {import_error},尝试从trading_system路径导入")
|
||
trading_system_path = project_root / 'trading_system'
|
||
sys.path.insert(0, str(trading_system_path))
|
||
from binance_client import BinanceClient
|
||
logger.info("✓ 从trading_system路径导入成功")
|
||
|
||
# 导入数据库模型
|
||
from database.models import Trade
|
||
|
||
# 创建客户端
|
||
logger.info(f"创建BinanceClient (testnet={use_testnet})...")
|
||
client = BinanceClient(
|
||
api_key=api_key,
|
||
api_secret=api_secret,
|
||
testnet=use_testnet
|
||
)
|
||
|
||
logger.info("连接币安API...")
|
||
await client.connect()
|
||
logger.info("✓ 币安API连接成功")
|
||
|
||
try:
|
||
# 检查币安是否有持仓(使用原始 position_information,确保能拿到 positionSide 以处理 -4061)
|
||
logger.info(f"检查 {symbol} 在币安的持仓状态...")
|
||
|
||
# 读取持仓模式:dualSidePosition=True => 对冲模式(必须传 positionSide=LONG/SHORT)
|
||
dual_side = None
|
||
try:
|
||
mode_res = await client.client.futures_get_position_mode()
|
||
if isinstance(mode_res, dict):
|
||
dual_side = bool(mode_res.get("dualSidePosition"))
|
||
except Exception as e:
|
||
logger.warning(f"读取持仓模式失败(将按单向模式兜底): {e}")
|
||
dual_side = None
|
||
|
||
raw_positions = await client.client.futures_position_information(symbol=symbol)
|
||
nonzero_positions = []
|
||
for p in raw_positions or []:
|
||
try:
|
||
amt = float(p.get("positionAmt", 0))
|
||
except Exception:
|
||
continue
|
||
if abs(amt) > 0:
|
||
nonzero_positions.append((amt, p))
|
||
|
||
# 兼容旧逻辑:如果原始接口异常,回退到封装方法
|
||
if not nonzero_positions:
|
||
try:
|
||
positions = await client.get_open_positions()
|
||
position = next((p for p in positions if p['symbol'] == symbol and float(p['positionAmt']) != 0), None)
|
||
if position:
|
||
nonzero_positions = [(float(position["positionAmt"]), {"positionAmt": position["positionAmt"]})]
|
||
except Exception:
|
||
nonzero_positions = []
|
||
|
||
if not nonzero_positions:
|
||
logger.warning(f"⚠ {symbol} 币安账户中没有持仓,可能已被平仓")
|
||
# 检查数据库中是否有未平仓的记录,如果有则更新
|
||
open_trades = Trade.get_by_symbol(symbol, status='open')
|
||
if open_trades:
|
||
trade = open_trades[0]
|
||
# 获取当前价格作为平仓价格
|
||
ticker = await client.get_ticker_24h(symbol)
|
||
exit_price = float(ticker['price']) if ticker else float(trade['entry_price'])
|
||
|
||
# 计算盈亏
|
||
entry_price = float(trade['entry_price'])
|
||
quantity = float(trade['quantity'])
|
||
if trade['side'] == 'BUY':
|
||
pnl = (exit_price - entry_price) * quantity
|
||
pnl_percent = ((exit_price - entry_price) / entry_price) * 100
|
||
else:
|
||
pnl = (entry_price - exit_price) * quantity
|
||
pnl_percent = ((entry_price - exit_price) / entry_price) * 100
|
||
|
||
# 更新数据库
|
||
Trade.update_exit(
|
||
trade_id=trade['id'],
|
||
exit_price=exit_price,
|
||
exit_reason='manual',
|
||
pnl=pnl,
|
||
pnl_percent=pnl_percent,
|
||
exit_order_id=None
|
||
)
|
||
logger.info(f"✓ 已更新数据库记录(币安无持仓但数据库有记录)")
|
||
|
||
return {
|
||
"message": f"{symbol} 平仓操作完成(币安账户中没有持仓,可能已被平仓)",
|
||
"symbol": symbol,
|
||
"status": "closed"
|
||
}
|
||
|
||
# 获取交易对精度信息,调整数量精度(平仓不要向上补 minQty,避免超过持仓数量)
|
||
symbol_info = None
|
||
try:
|
||
symbol_info = await client.get_symbol_info(symbol)
|
||
except Exception:
|
||
symbol_info = None
|
||
|
||
def _adjust_close_qty(qty: float) -> float:
|
||
if qty is None:
|
||
return 0.0
|
||
q = float(qty)
|
||
if not symbol_info:
|
||
return q
|
||
quantity_precision = symbol_info.get('quantityPrecision', 8)
|
||
step_size = float(symbol_info.get('stepSize', 0) or 0)
|
||
if step_size and step_size > 0:
|
||
# 向下取整,避免超过持仓
|
||
q = float(int(q / step_size)) * step_size
|
||
else:
|
||
q = round(q, quantity_precision)
|
||
q = round(q, quantity_precision)
|
||
return q
|
||
|
||
# 组装平仓订单(对冲模式可能同币种有 LONG/SHORT 两个仓位,这里一并平掉)
|
||
orders = []
|
||
order_ids = []
|
||
|
||
# 如果 dual_side 无法读取,按 raw_positions 是否包含 positionSide 来推断
|
||
if dual_side is None:
|
||
if any(isinstance(p, dict) and (p.get("positionSide") in ("LONG", "SHORT")) for _, p in nonzero_positions):
|
||
dual_side = True
|
||
else:
|
||
dual_side = False
|
||
|
||
logger.info(f"{symbol} 持仓模式: {'HEDGE(对冲)' if dual_side else 'ONE-WAY(单向)'}")
|
||
|
||
# 构造待平仓列表:[(positionSide, amt)]
|
||
to_close = []
|
||
if dual_side:
|
||
for amt, p in nonzero_positions:
|
||
ps = (p.get("positionSide") or "").upper()
|
||
if ps not in ("LONG", "SHORT"):
|
||
ps = "LONG" if amt > 0 else "SHORT"
|
||
to_close.append((ps, amt))
|
||
else:
|
||
# 单向模式只应存在一个净仓位;如果有多个,按合计处理
|
||
net_amt = sum([amt for amt, _ in nonzero_positions])
|
||
if abs(net_amt) > 0:
|
||
to_close.append(("BOTH", net_amt))
|
||
|
||
logger.info(f"✓ 币安账户中 {symbol} 待平仓: {to_close}")
|
||
|
||
for ps, amt in to_close:
|
||
side = 'SELL' if float(amt) > 0 else 'BUY'
|
||
quantity = abs(float(amt))
|
||
quantity = _adjust_close_qty(quantity)
|
||
if quantity <= 0:
|
||
logger.warning(f"{symbol} 平仓数量调整后为0,跳过该仓位: positionSide={ps}, amt={amt}")
|
||
continue
|
||
|
||
order_params = {
|
||
"symbol": symbol,
|
||
"side": side,
|
||
"type": "MARKET",
|
||
"quantity": quantity,
|
||
}
|
||
# 对冲模式必须传 positionSide=LONG/SHORT;并且某些账户会 -1106,因此这里不再传 reduceOnly
|
||
if dual_side and ps in ("LONG", "SHORT"):
|
||
order_params["positionSide"] = ps
|
||
else:
|
||
# 单向模式用 reduceOnly 防止反向开仓
|
||
order_params["reduceOnly"] = True
|
||
|
||
logger.info(
|
||
f"开始执行平仓下单: {symbol} side={side} qty={quantity} "
|
||
f"positionSide={order_params.get('positionSide')} reduceOnly={order_params.get('reduceOnly')}"
|
||
)
|
||
try:
|
||
order = await client.client.futures_create_order(**order_params)
|
||
if not order:
|
||
raise RuntimeError("币安API返回 None")
|
||
orders.append(order)
|
||
oid = order.get("orderId")
|
||
if oid:
|
||
order_ids.append(oid)
|
||
except Exception as order_error:
|
||
error_msg = f"{symbol} 平仓失败:下单异常 - {str(order_error)}"
|
||
logger.error(error_msg)
|
||
logger.error(f" 错误类型: {type(order_error).__name__}")
|
||
import traceback
|
||
logger.error(f" 完整错误堆栈:\n{traceback.format_exc()}")
|
||
raise HTTPException(status_code=500, detail=error_msg)
|
||
|
||
if not orders:
|
||
raise HTTPException(status_code=400, detail=f"{symbol} 无可平仓的有效仓位(数量调整后为0或无持仓)")
|
||
|
||
logger.info(f"✓ {symbol} 平仓订单已提交: {order_ids}")
|
||
|
||
# 等待订单成交,获取实际成交价格
|
||
import asyncio
|
||
await asyncio.sleep(1)
|
||
|
||
# 获取订单详情(可能多个订单,按订单号分别取价)
|
||
exit_prices = {}
|
||
for oid in order_ids:
|
||
try:
|
||
order_info = await client.client.futures_get_order(symbol=symbol, orderId=oid)
|
||
if order_info:
|
||
p = float(order_info.get('avgPrice', 0)) or float(order_info.get('price', 0))
|
||
if p <= 0 and order_info.get('fills'):
|
||
total_qty = 0
|
||
total_value = 0
|
||
for fill in order_info.get('fills', []):
|
||
qty = float(fill.get('qty', 0))
|
||
price = float(fill.get('price', 0))
|
||
total_qty += qty
|
||
total_value += qty * price
|
||
if total_qty > 0:
|
||
p = total_value / total_qty
|
||
if p > 0:
|
||
exit_prices[oid] = p
|
||
except Exception as e:
|
||
logger.warning(f"获取订单详情失败 (orderId={oid}): {e}")
|
||
|
||
# 兜底:如果无法获取订单价格,使用当前价格
|
||
fallback_exit_price = None
|
||
try:
|
||
ticker = await client.get_ticker_24h(symbol)
|
||
fallback_exit_price = float(ticker['price']) if ticker else None
|
||
except Exception:
|
||
fallback_exit_price = None
|
||
|
||
# 更新数据库记录
|
||
open_trades = Trade.get_by_symbol(symbol, status='open')
|
||
if open_trades:
|
||
# 对冲模式可能有多条 trade(BUY/LONG 和 SELL/SHORT),尽量按方向匹配订单更新
|
||
used_order_ids = set()
|
||
for trade in open_trades:
|
||
try:
|
||
entry_price = float(trade['entry_price'])
|
||
trade_quantity = float(trade['quantity'])
|
||
except Exception:
|
||
continue
|
||
|
||
# 选择一个未使用的 orderId(如果只有一个,就复用)
|
||
chosen_oid = None
|
||
for oid in order_ids:
|
||
if oid not in used_order_ids:
|
||
chosen_oid = oid
|
||
break
|
||
if chosen_oid is None and order_ids:
|
||
chosen_oid = order_ids[0]
|
||
if chosen_oid:
|
||
used_order_ids.add(chosen_oid)
|
||
|
||
exit_price = exit_prices.get(chosen_oid) if chosen_oid else None
|
||
if not exit_price:
|
||
exit_price = fallback_exit_price or entry_price
|
||
|
||
# 计算盈亏(数据库侧依旧按名义盈亏;收益率展示用保证金口径在前端/统计里另算)
|
||
if trade['side'] == 'BUY':
|
||
pnl = (exit_price - entry_price) * trade_quantity
|
||
pnl_percent = ((exit_price - entry_price) / entry_price) * 100
|
||
else:
|
||
pnl = (entry_price - exit_price) * trade_quantity
|
||
pnl_percent = ((entry_price - exit_price) / entry_price) * 100
|
||
|
||
Trade.update_exit(
|
||
trade_id=trade['id'],
|
||
exit_price=exit_price,
|
||
exit_reason='manual',
|
||
pnl=pnl,
|
||
pnl_percent=pnl_percent,
|
||
exit_order_id=chosen_oid
|
||
)
|
||
logger.info(f"✓ 已更新数据库记录 trade_id={trade['id']} order_id={chosen_oid} (盈亏: {pnl:.2f} USDT, {pnl_percent:.2f}%)")
|
||
|
||
logger.info(f"✓ {symbol} 平仓成功")
|
||
return {
|
||
"message": f"{symbol} 平仓成功",
|
||
"symbol": symbol,
|
||
"status": "closed"
|
||
}
|
||
finally:
|
||
logger.info("断开币安API连接...")
|
||
await client.disconnect()
|
||
logger.info("✓ 已断开连接")
|
||
|
||
except HTTPException:
|
||
raise
|
||
except Exception as e:
|
||
error_msg = f"平仓失败: {str(e)}"
|
||
logger.error("=" * 60)
|
||
logger.error(f"平仓操作异常: {error_msg}")
|
||
logger.error(f"错误类型: {type(e).__name__}")
|
||
logger.error("=" * 60, exc_info=True)
|
||
raise HTTPException(status_code=500, detail=error_msg)
|
||
|
||
|
||
@router.post("/positions/sync")
|
||
async def sync_positions():
|
||
"""同步币安实际持仓状态与数据库状态"""
|
||
try:
|
||
logger.info("=" * 60)
|
||
logger.info("收到持仓状态同步请求")
|
||
logger.info("=" * 60)
|
||
|
||
# 从数据库读取API密钥
|
||
api_key = TradingConfig.get_value('BINANCE_API_KEY')
|
||
api_secret = TradingConfig.get_value('BINANCE_API_SECRET')
|
||
use_testnet = TradingConfig.get_value('USE_TESTNET', False)
|
||
|
||
if not api_key or not api_secret:
|
||
error_msg = "API密钥未配置"
|
||
logger.warning(error_msg)
|
||
raise HTTPException(status_code=400, detail=error_msg)
|
||
|
||
# 导入必要的模块
|
||
try:
|
||
from binance_client import BinanceClient
|
||
except ImportError:
|
||
trading_system_path = project_root / 'trading_system'
|
||
sys.path.insert(0, str(trading_system_path))
|
||
from binance_client import BinanceClient
|
||
|
||
# 导入数据库模型
|
||
from database.models import Trade
|
||
|
||
# 创建客户端
|
||
client = BinanceClient(
|
||
api_key=api_key,
|
||
api_secret=api_secret,
|
||
testnet=use_testnet
|
||
)
|
||
|
||
logger.info("连接币安API...")
|
||
await client.connect()
|
||
|
||
try:
|
||
# 1. 获取币安实际持仓
|
||
binance_positions = await client.get_open_positions()
|
||
binance_symbols = {p['symbol'] for p in binance_positions if float(p.get('positionAmt', 0)) != 0}
|
||
logger.info(f"币安实际持仓: {len(binance_symbols)} 个")
|
||
if binance_symbols:
|
||
logger.info(f" 持仓列表: {', '.join(binance_symbols)}")
|
||
|
||
# 2. 获取数据库中状态为open的交易记录
|
||
db_open_trades = Trade.get_all(status='open')
|
||
db_open_symbols = {t['symbol'] for t in db_open_trades}
|
||
logger.info(f"数据库open状态: {len(db_open_symbols)} 个")
|
||
if db_open_symbols:
|
||
logger.info(f" 持仓列表: {', '.join(db_open_symbols)}")
|
||
|
||
# 3. 找出在数据库中open但在币安已不存在的持仓(需要更新为closed)
|
||
missing_in_binance = db_open_symbols - binance_symbols
|
||
updated_count = 0
|
||
|
||
if missing_in_binance:
|
||
logger.info(f"发现 {len(missing_in_binance)} 个持仓在数据库中是open但币安已不存在: {', '.join(missing_in_binance)}")
|
||
|
||
for symbol in missing_in_binance:
|
||
try:
|
||
# 尝试从币安历史订单获取“真实平仓信息”(价格/时间/原因/订单号)
|
||
latest_close_order = None
|
||
try:
|
||
end_time_ms = int(time.time() * 1000)
|
||
start_time_ms = end_time_ms - (7 * 24 * 60 * 60 * 1000)
|
||
orders = await client.client.futures_get_all_orders(
|
||
symbol=symbol,
|
||
startTime=start_time_ms,
|
||
endTime=end_time_ms,
|
||
)
|
||
if isinstance(orders, list) and orders:
|
||
close_orders = [
|
||
o for o in orders
|
||
if isinstance(o, dict)
|
||
and o.get("reduceOnly") is True
|
||
and o.get("status") == "FILLED"
|
||
]
|
||
if close_orders:
|
||
close_orders.sort(key=lambda x: x.get("updateTime", 0), reverse=True)
|
||
latest_close_order = close_orders[0]
|
||
except Exception:
|
||
latest_close_order = None
|
||
|
||
# 获取该交易对的所有open记录
|
||
open_trades = Trade.get_by_symbol(symbol, status='open')
|
||
|
||
for trade in open_trades:
|
||
trade_id = trade['id']
|
||
entry_price = float(trade['entry_price'])
|
||
quantity = float(trade['quantity'])
|
||
|
||
# 获取当前价格作为平仓价格
|
||
exit_price = None
|
||
exit_order_id = None
|
||
exit_time_ts = None
|
||
exit_reason = "sync"
|
||
otype = ""
|
||
|
||
if latest_close_order and isinstance(latest_close_order, dict):
|
||
try:
|
||
exit_price = float(latest_close_order.get("avgPrice", 0) or 0) or None
|
||
except Exception:
|
||
exit_price = None
|
||
exit_order_id = latest_close_order.get("orderId") or None
|
||
otype = str(
|
||
latest_close_order.get("type")
|
||
or latest_close_order.get("origType")
|
||
or ""
|
||
).upper()
|
||
try:
|
||
ms = latest_close_order.get("updateTime") or latest_close_order.get("time")
|
||
if ms:
|
||
exit_time_ts = int(int(ms) / 1000)
|
||
except Exception:
|
||
exit_time_ts = None
|
||
|
||
if "TRAILING" in otype:
|
||
exit_reason = "trailing_stop"
|
||
elif "TAKE_PROFIT" in otype:
|
||
exit_reason = "take_profit"
|
||
elif "STOP" in otype:
|
||
exit_reason = "stop_loss"
|
||
elif otype in ("MARKET", "LIMIT"):
|
||
exit_reason = "manual"
|
||
|
||
if not exit_price or exit_price <= 0:
|
||
ticker = await client.get_ticker_24h(symbol)
|
||
exit_price = float(ticker['price']) if ticker else entry_price
|
||
|
||
# 计算盈亏
|
||
if trade['side'] == 'BUY':
|
||
pnl = (exit_price - entry_price) * quantity
|
||
else:
|
||
pnl = (entry_price - exit_price) * quantity
|
||
|
||
# 计算基于保证金的盈亏百分比
|
||
leverage = float(trade.get('leverage', 10))
|
||
entry_value = entry_price * quantity
|
||
margin = entry_value / leverage if leverage > 0 else entry_value
|
||
pnl_percent_margin = (pnl / margin * 100) if margin > 0 else 0
|
||
|
||
# 更新数据库记录
|
||
duration_minutes = None
|
||
try:
|
||
et = trade.get("entry_time")
|
||
if et is not None and exit_time_ts is not None:
|
||
et_i = int(et)
|
||
if exit_time_ts >= et_i:
|
||
duration_minutes = int((exit_time_ts - et_i) / 60)
|
||
except Exception:
|
||
duration_minutes = None
|
||
|
||
Trade.update_exit(
|
||
trade_id=trade_id,
|
||
exit_price=exit_price,
|
||
exit_reason=exit_reason,
|
||
pnl=pnl,
|
||
pnl_percent=pnl_percent_margin, # 使用基于保证金的盈亏百分比
|
||
exit_order_id=exit_order_id,
|
||
duration_minutes=duration_minutes,
|
||
exit_time_ts=exit_time_ts,
|
||
)
|
||
updated_count += 1
|
||
logger.info(
|
||
f"✓ {symbol} 已更新为closed (ID: {trade_id}, "
|
||
f"盈亏: {pnl:.2f} USDT, {pnl_percent_margin:.2f}% of margin, "
|
||
f"原因: {exit_reason}, 类型: {otype or '-'}"
|
||
f")"
|
||
)
|
||
except Exception as e:
|
||
logger.error(f"❌ {symbol} 更新失败: {e}")
|
||
import traceback
|
||
logger.error(f" 错误详情:\n{traceback.format_exc()}")
|
||
else:
|
||
logger.info("✓ 数据库与币安状态一致,无需更新")
|
||
|
||
# 4. 检查币安有但数据库没有记录的持仓
|
||
missing_in_db = binance_symbols - db_open_symbols
|
||
if missing_in_db:
|
||
logger.info(f"发现 {len(missing_in_db)} 个持仓在币安存在但数据库中没有记录: {', '.join(missing_in_db)}")
|
||
logger.info(" 这些持仓可能是手动开仓的,建议手动处理")
|
||
|
||
result = {
|
||
"message": "持仓状态同步完成",
|
||
"binance_positions": len(binance_symbols),
|
||
"db_open_positions": len(db_open_symbols),
|
||
"updated_to_closed": updated_count,
|
||
"missing_in_binance": list(missing_in_binance),
|
||
"missing_in_db": list(missing_in_db)
|
||
}
|
||
|
||
logger.info("=" * 60)
|
||
logger.info("持仓状态同步完成!")
|
||
logger.info(f"结果: {result}")
|
||
logger.info("=" * 60)
|
||
|
||
return result
|
||
|
||
finally:
|
||
await client.disconnect()
|
||
logger.info("✓ 已断开币安API连接")
|
||
|
||
except HTTPException:
|
||
raise
|
||
except Exception as e:
|
||
error_msg = f"同步持仓状态失败: {str(e)}"
|
||
logger.error(error_msg, exc_info=True)
|
||
raise HTTPException(status_code=500, detail=error_msg)
|