stock-ai-agent/backend/close_other_symbols.py
2026-02-08 14:16:19 +08:00

81 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
关闭非 BTCUSDT/ETHUSDT 的订单(包括挂单和持仓)
"""
import sys
import os
# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from app.services.paper_trading_service import get_paper_trading_service
from app.services.binance_service import binance_service
def main():
# 允许的交易对
allowed_symbols = {'BTCUSDT', 'ETHUSDT'}
service = get_paper_trading_service()
active_orders = service.get_active_orders()
print(f"当前活跃订单数: {len(active_orders)}")
# 统计各状态订单
pending_count = len([o for o in active_orders if o.get('status') == 'pending'])
open_count = len([o for o in active_orders if o.get('status') == 'open'])
print(f" - 挂单 (pending): {pending_count}")
print(f" - 持仓 (open): {open_count}")
# 找出需要处理的订单
orders_to_close = [
order for order in active_orders
if order.get('symbol') not in allowed_symbols
]
if not orders_to_close:
print("\n没有需要处理的订单")
return
print(f"\n需要处理的订单数: {len(orders_to_close)}")
success_count = 0
fail_count = 0
for order in orders_to_close:
symbol = order.get('symbol')
order_id = order.get('order_id')
side = order.get('side')
status = order.get('status')
entry_price = order.get('entry_price', 0)
# 获取当前价格
current_price = binance_service.get_current_price(symbol)
if not current_price:
# 如果无法获取价格使用入场价盈亏为0
print(f"无法获取 {symbol} 价格,使用入场价")
current_price = entry_price
action = "取消挂单" if status == 'pending' else "平仓"
print(f"\n{action}: {order_id[:12]}...")
print(f" 交易对: {symbol} | 方向: {side} | 状态: {status}")
print(f" 入场价: ${entry_price:,.2f} | 当前价: ${current_price:,.2f}")
result = service.close_order_manual(order_id, current_price)
if result:
if status == 'pending':
print(f" 结果: 挂单已取消")
else:
pnl = result.get('pnl_percent', 0)
print(f" 结果: 平仓成功,盈亏 {pnl:+.2f}%")
success_count += 1
else:
print(f" 结果: 操作失败")
fail_count += 1
print(f"\n完成!成功: {success_count}, 失败: {fail_count}")
if __name__ == "__main__":
main()