This commit is contained in:
薇薇安 2026-01-16 17:40:09 +08:00
parent e06687b7a5
commit 9b0f35bce2

View File

@ -184,7 +184,61 @@ class PositionManager:
if entry_order_id:
logger.info(f"{symbol} [开仓] 币安订单号: {entry_order_id}")
# 记录到数据库
# 等待订单成交,然后从币安获取实际成交价格
actual_entry_price = None
try:
# 等待一小段时间让订单成交
await asyncio.sleep(1)
# 从币安获取订单详情,获取实际成交价格
try:
order_info = await self.client.client.futures_get_order(symbol=symbol, orderId=entry_order_id)
if order_info:
# 优先使用平均成交价格avgPrice如果没有则使用价格字段
actual_entry_price = float(order_info.get('avgPrice', 0)) or float(order_info.get('price', 0))
if actual_entry_price > 0:
logger.info(f"{symbol} [开仓] 从币安订单获取实际成交价格: {actual_entry_price:.4f} USDT")
else:
# 如果订单还没有完全成交,尝试从成交记录获取
if order_info.get('status') == 'FILLED' 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:
actual_entry_price = total_value / total_qty
logger.info(f"{symbol} [开仓] 从成交记录计算平均成交价格: {actual_entry_price:.4f} USDT")
except Exception as order_error:
logger.warning(f"{symbol} [开仓] 获取订单详情失败: {order_error},使用备用方法")
# 如果无法从订单获取价格,使用当前价格作为备用
if not actual_entry_price or actual_entry_price <= 0:
ticker = await self.client.get_ticker_24h(symbol)
if ticker:
actual_entry_price = float(ticker['price'])
logger.warning(f"{symbol} [开仓] 使用当前价格作为入场价格: {actual_entry_price:.4f} USDT")
else:
actual_entry_price = float(order.get('avgPrice', 0)) or float(order.get('price', 0))
if actual_entry_price <= 0:
logger.error(f"{symbol} [开仓] 无法获取入场价格,使用订单价格字段")
actual_entry_price = float(order.get('price', 0)) or entry_price
except Exception as price_error:
logger.warning(f"{symbol} [开仓] 获取成交价格时出错: {price_error},使用当前价格")
ticker = await self.client.get_ticker_24h(symbol)
actual_entry_price = float(ticker['price']) if ticker else entry_price
# 使用实际成交价格(如果获取成功)
if actual_entry_price and actual_entry_price > 0:
# 记录下单时的价格(用于对比)
original_entry_price = entry_price
entry_price = actual_entry_price
logger.info(f"{symbol} [开仓] 使用实际成交价格: {entry_price:.4f} USDT (下单时价格: {original_entry_price:.4f})")
# 记录到数据库(使用实际成交价格)
trade_id = None
if DB_AVAILABLE and Trade:
try:
@ -193,12 +247,12 @@ class PositionManager:
symbol=symbol,
side=side,
quantity=quantity,
entry_price=entry_price,
entry_price=entry_price, # 使用实际成交价格
leverage=leverage,
entry_reason=entry_reason,
entry_order_id=entry_order_id # 保存币安订单号
)
logger.info(f"{symbol} 交易记录已保存到数据库 (ID: {trade_id}, 订单号: {entry_order_id})")
logger.info(f"{symbol} 交易记录已保存到数据库 (ID: {trade_id}, 订单号: {entry_order_id}, 成交价: {entry_price:.4f})")
except Exception as e:
logger.error(f"❌ 保存交易记录到数据库失败: {e}")
logger.error(f" 错误类型: {type(e).__name__}")