diff --git a/backend/app/services/paper_trading_service.py b/backend/app/services/paper_trading_service.py index 2c0a15d..c7a5d5b 100644 --- a/backend/app/services/paper_trading_service.py +++ b/backend/app/services/paper_trading_service.py @@ -297,8 +297,11 @@ class PaperTradingService: # 确保不超过可用空间 position_value = min(position_value, available_position_value) + # 修正浮点数精度问题,保留 2 位小数 + position_value = round(position_value, 2) + # 计算对应的保证金 - margin = position_value / max_leverage + margin = round(position_value / max_leverage, 2) logger.info(f"动态仓位计算: {position_size} | 可用空间: ${available_position_value:,.0f} | " f"目标仓位: ${position_value:,.0f} | 保证金: ${margin:,.0f}") @@ -521,7 +524,9 @@ class PaperTradingService: else: pnl_percent = ((db_order.filled_price - exit_price) / db_order.filled_price) * 100 - pnl_amount = db_order.quantity * pnl_percent / 100 + # 修正浮点数精度,先四舍五入百分比 + pnl_percent = round(pnl_percent, 4) + pnl_amount = round(db_order.quantity * pnl_percent / 100, 2) # 计算持仓时间 hold_duration = datetime.utcnow() - db_order.opened_at if db_order.opened_at else timedelta(0) @@ -1371,9 +1376,9 @@ class PaperTradingService: if close_percent is None or close_percent <= 0 or close_percent > 100: return {'success': False, 'error': f'无效的平仓比例: {close_percent}'} - # 计算平仓数量 - close_quantity = order.quantity * (close_percent / 100) - remaining_quantity = order.quantity - close_quantity + # 计算平仓数量(修正浮点数精度) + close_quantity = round(order.quantity * (close_percent / 100), 2) + remaining_quantity = round(order.quantity - close_quantity, 2) if remaining_quantity < 10: # 剩余数量太小,直接全部平仓 return self._close_order_llm(order, db, 'PARTIAL_CLOSE', '部分平仓后剩余过少,直接全部平仓')