This commit is contained in:
薇薇安 2026-01-23 09:21:14 +08:00
parent 2ba8d69ee0
commit 84c4af5ff5

View File

@ -289,9 +289,10 @@ class RiskManager:
# 公式:仓位大小 = (总资金 * 每笔单子承受的风险%) / (入场价 - 止损价) # 公式:仓位大小 = (总资金 * 每笔单子承受的风险%) / (入场价 - 止损价)
use_fixed_risk = config.TRADING_CONFIG.get('USE_FIXED_RISK_SIZING', True) use_fixed_risk = config.TRADING_CONFIG.get('USE_FIXED_RISK_SIZING', True)
fixed_risk_percent = config.TRADING_CONFIG.get('FIXED_RISK_PERCENT', 0.02) # 默认2% fixed_risk_percent = config.TRADING_CONFIG.get('FIXED_RISK_PERCENT', 0.02) # 默认2%
quantity = None quantity = None # 初始化为None确保变量存在
if use_fixed_risk and entry_price and side: if use_fixed_risk and entry_price and side:
try:
# 如果未提供止损价格,先估算 # 如果未提供止损价格,先估算
if stop_loss_price is None: if stop_loss_price is None:
# 尝试使用ATR估算止损距离 # 尝试使用ATR估算止损距离
@ -308,15 +309,19 @@ class RiskManager:
# 先估算一个临时仓位来计算止损距离 # 先估算一个临时仓位来计算止损距离
temp_margin = total_balance * 0.05 # 临时使用5%保证金 temp_margin = total_balance * 0.05 # 临时使用5%保证金
temp_notional = temp_margin * actual_leverage temp_notional = temp_margin * actual_leverage
temp_quantity = temp_notional / entry_price temp_quantity = temp_notional / entry_price if entry_price > 0 else 0
if temp_quantity > 0:
stop_loss_amount = temp_margin * stop_loss_pct stop_loss_amount = temp_margin * stop_loss_pct
if side == 'BUY': if side == 'BUY':
estimated_stop_loss = entry_price - (stop_loss_amount / temp_quantity) estimated_stop_loss = entry_price - (stop_loss_amount / temp_quantity)
else: # SELL else: # SELL
estimated_stop_loss = entry_price + (stop_loss_amount / temp_quantity) estimated_stop_loss = entry_price + (stop_loss_amount / temp_quantity)
stop_loss_price = estimated_stop_loss stop_loss_price = estimated_stop_loss
else:
stop_loss_price = None
# 计算止损距离 # 计算止损距离
if stop_loss_price is not None and stop_loss_price > 0:
if side == 'BUY': if side == 'BUY':
stop_distance = entry_price - stop_loss_price stop_distance = entry_price - stop_loss_price
else: # SELL else: # SELL
@ -352,12 +357,16 @@ class RiskManager:
logger.info(f" ✓ 调整为最大仓位限制: {max_margin_value:.2f} USDT") logger.info(f" ✓ 调整为最大仓位限制: {max_margin_value:.2f} USDT")
margin_value = max_margin_value margin_value = max_margin_value
notional_value = margin_value * actual_leverage notional_value = margin_value * actual_leverage
quantity = notional_value / entry_price quantity = notional_value / entry_price if entry_price > 0 else None
else: else:
# 使用固定风险计算的仓位 logger.warning(f" ⚠️ 止损距离无效 (stop_distance={stop_distance:.4f}),将使用传统方法计算仓位")
pass # quantity已经计算好了 else:
logger.warning(f" ⚠️ 无法估算止损价格,将使用传统方法计算仓位")
except Exception as e:
logger.warning(f" ⚠️ 固定风险百分比计算失败: {e},将使用传统方法计算仓位")
quantity = None # 确保quantity为None使用传统方法
# 如果未使用固定风险计算,使用原来的方法 # 如果未使用固定风险计算或计算失败,使用原来的方法
if quantity is None: if quantity is None:
# ⚠️ 优化3信号强度分级 - 9-10分高权重8分轻仓 # ⚠️ 优化3信号强度分级 - 9-10分高权重8分轻仓
signal_multiplier = 1.0 signal_multiplier = 1.0