auto_trade_sys/WEBSOCKET_HOLD_TIME_MINUTES_FIX.md
薇薇安 1032295052 a
2026-01-25 09:16:16 +08:00

104 lines
3.8 KiB
Markdown
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.

# WebSocket监控 hold_time_minutes 变量未初始化修复
## 🔍 问题描述
**错误信息**
```
trading_system.position_manager - WARNING - FLUIDUSDT WebSocket监控出错 (重试 1/5):
cannot access local variable 'hold_time_minutes' where it is not associated with a value
```
**问题根源**
`_check_single_position()` 方法中,`hold_time_minutes` 变量只在**止损分支**第2725-2734行中被初始化但在**止盈分支**第2889行中也被使用。当代码走止盈路径时变量未被初始化导致 `UnboundLocalError`
## ✅ 修复方案
### 修复位置
`trading_system/position_manager.py``_check_single_position()` 方法
### 修复内容
在止盈分支第2877行之后添加 `hold_time_minutes` 的初始化逻辑:
**修复前**
```python
# 直接比较当前盈亏百分比与止盈目标(基于保证金)
if pnl_percent_margin >= take_profit_pct_margin:
should_close = True
exit_reason = 'take_profit'
# 详细诊断日志:记录平仓时的所有关键信息
logger.info("=" * 80)
logger.info(f"{symbol} [实时监控-平仓诊断日志] ===== 触发止盈平仓 =====")
# ...
logger.info(f" 持仓时间: {hold_time_minutes:.1f} 分钟") # ❌ 变量未初始化
# ...
```
**修复后**
```python
# 直接比较当前盈亏百分比与止盈目标(基于保证金)
if pnl_percent_margin >= take_profit_pct_margin:
should_close = True
exit_reason = 'take_profit'
# 计算持仓时间(用于日志)
entry_time = position_info.get('entryTime')
hold_time_minutes = 0
if entry_time:
try:
if isinstance(entry_time, datetime):
hold_time_sec = int((get_beijing_time() - entry_time).total_seconds())
else:
hold_time_sec = int(time.time() - (float(entry_time) if isinstance(entry_time, (int, float)) else 0))
hold_time_minutes = hold_time_sec / 60.0
except Exception:
hold_time_minutes = 0
# 详细诊断日志:记录平仓时的所有关键信息
logger.info("=" * 80)
logger.info(f"{symbol} [实时监控-平仓诊断日志] ===== 触发止盈平仓 =====")
# ...
logger.info(f" 持仓时间: {hold_time_minutes:.1f} 分钟") # ✅ 变量已初始化
# ...
```
## 📊 修复效果
### 修复前
- ❌ 止盈触发时 → 尝试使用 `hold_time_minutes``UnboundLocalError` → WebSocket监控出错 → 重试
### 修复后
- ✅ 止盈触发时 → `hold_time_minutes` 已初始化 → 正常记录日志 → WebSocket监控正常
## 🔄 相关代码路径
1. **止损分支**第2725-2734行已正确初始化 `hold_time_minutes`
2. **止盈分支**第2877-2907行**已修复**,现在也会初始化 `hold_time_minutes`
3. **第二目标止盈分支**第2838-2846行未使用 `hold_time_minutes`,无需修复
## ⚠️ 注意事项
1. **变量作用域**`hold_time_minutes` 是局部变量,只在各自的代码分支内有效。
2. **初始化逻辑**:与止损分支的初始化逻辑保持一致,确保计算方式统一。
3. **异常处理**:如果计算持仓时间失败,默认设置为 0避免程序崩溃。
## 🚀 部署建议
1. **重启交易进程**:修复后需要重启所有 `trading_system` 进程才能生效。
```bash
supervisorctl restart auto_sys_acc1 auto_sys_acc2 auto_sys_acc3 ...
```
2. **验证修复**:查看日志,确认 WebSocket 监控不再出现 `hold_time_minutes` 相关错误。
## 📝 相关文件
- `trading_system/position_manager.py`:主要修复文件
- `_check_single_position()` 方法第2580-2960行
- `_monitor_position_price()` 方法第2499-2578行
## ✅ 修复完成时间
2026-01-25