stock-ai-agent/check_bitget_tp_sl.py
2026-03-29 10:35:22 +08:00

164 lines
5.6 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
"""
Bitget 止盈止损诊断工具
检查当前持仓、挂单、以及待设置的 TP/SL
"""
import sys
import os
import asyncio
# 添加后端路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))
from app.config import get_settings
from app.services.bitget_live_trading_service import get_bitget_live_service
from app.services.bitget_trading_api_sdk import get_bitget_trading_api
def diagnose():
"""诊断 Bitget 止盈止损状态"""
settings = get_settings()
print("=" * 80)
print("🔍 Bitget 止盈止损诊断工具")
print("=" * 80)
# 1. 检查配置
print("\n📋 1. 检查配置")
print(f" Bitget 交易已启用: {settings.bitget_trading_enabled}")
if not settings.bitget_trading_enabled:
print(" ❌ Bitget 交易未启用")
return
# 2. 获取服务实例
print("\n🔧 2. 初始化服务")
bitget_service = get_bitget_live_service()
if not bitget_service:
print(" ❌ Bitget 服务初始化失败")
return
print(" ✅ Bitget 服务已初始化")
# 3. 检查账户状态
print("\n💰 3. 账户状态")
account_state = bitget_service.get_account_state()
if account_state:
print(f" 账户价值: ${account_state.get('account_value', 0):,.2f}")
print(f" 已用保证金: ${account_state.get('total_margin_used', 0):,.2f}")
print(f" 可用余额: ${account_state.get('available_balance', 0):,.2f}")
else:
print(" ⚠️ 无法获取账户状态")
# 4. 检查持仓
print("\n📊 4. 当前持仓")
positions = bitget_service.get_open_positions()
if not positions:
print(" 📭 无持仓")
else:
print(f" 发现 {len(positions)} 个持仓:")
for pos in positions:
symbol = pos.get('coin', pos.get('symbol', 'Unknown'))
size = pos.get('size', 0)
entry_price = pos.get('entry_price', 0)
unrealized_pnl = pos.get('unrealized_pnl', 0)
leverage = pos.get('leverage', 1)
side = '做多' if size > 0 else '做空'
size_abs = abs(size)
print(f"\n 🎯 {symbol} {side}")
print(f" 大小: {size_abs:.4f}")
print(f" 入场价: ${entry_price:,.2f}")
print(f" 杠杆: {leverage}x")
print(f" 未实现盈亏: ${unrealized_pnl:,.2f}")
# 检查是否有 TP/SL
tp_sl = bitget_service.get_tp_sl_prices(symbol)
tp_price = tp_sl.get('take_profit')
sl_price = tp_sl.get('stop_loss')
if tp_price or sl_price:
print(f" ✅ 止盈止损已设置:")
if tp_price:
print(f" 止盈: ${tp_price:,.2f}")
if sl_price:
print(f" 止损: ${sl_price:,.2f}")
else:
print(f" ❌ 止盈止损未设置!")
# 5. 检查挂单
print("\n📌 5. 当前挂单")
trading_api = get_bitget_trading_api()
if not trading_api:
print(" ❌ Bitget Trading API 初始化失败")
return
open_orders = trading_api.get_open_orders()
if not open_orders:
print(" 📭 无挂单")
else:
print(f" 发现 {len(open_orders)} 个挂单:")
for order in open_orders:
symbol = order.get('symbol', 'Unknown')
order_id = order.get('id', 'Unknown')
side = order.get('side', 'Unknown')
amount = order.get('amount', 0)
price = order.get('price', 0)
order_type = order.get('type', 'Unknown')
reduce_only = order.get('reduceOnly', False)
side_text = '买入' if side == 'buy' else '卖出'
order_type_text = '限价' if order_type == 'limit' else order_type
print(f"\n 📝 订单 #{order_id}")
print(f" 交易对: {symbol}")
print(f" 类型: {order_type_text} {side_text}")
print(f" 数量: {amount}")
print(f" 价格: ${price:,.2f}")
print(f" 只平仓: {'' if reduce_only else ''}")
# 6. 总结
print("\n" + "=" * 80)
print("📝 诊断总结:")
print("=" * 80)
if positions:
no_tp_sl_count = 0
for pos in positions:
symbol = pos.get('coin', pos.get('symbol', 'Unknown'))
tp_sl = bitget_service.get_tp_sl_prices(symbol)
if not tp_sl.get('take_profit') and not tp_sl.get('stop_loss'):
no_tp_sl_count += 1
if no_tp_sl_count > 0:
print(f"\n⚠️ 警告: {no_tp_sl_count} 个持仓没有设置止盈止损!")
print("\n可能的原因:")
print(" 1. 挂单刚刚成交定期检查还未运行每5分钟检查一次")
print(" 2. 止盈止损设置失败,查看日志确认")
print(" 3. 挂单还在等待成交")
print("\n建议:")
print(" • 等待下一个 5 分钟检查周期")
print(" • 或手动在 Bitget 网页/App 设置止盈止损")
print(" • 或重启后端服务,立即触发检查")
else:
print("\n✅ 所有持仓都已设置止盈止损")
else:
print("\n✅ 当前无持仓")
print("\n" + "=" * 80)
if __name__ == "__main__":
try:
diagnose()
except KeyboardInterrupt:
print("\n\n👋 诊断已取消")
except Exception as e:
print(f"\n❌ 诊断失败: {e}")
import traceback
traceback.print_exc()