PineScript编写1:3风险回报比策略遇止盈失效问题求助
问题分析与解决方案
你的代码止盈不触发的核心问题是在开仓同一根K线中,无法正确获取刚开仓订单的入场价格,同时strategy.exit仅在开仓K线执行一次,若后续价格波动导致参数逻辑偏差,也无法动态调整。以下是具体修正方案:
核心错误点
strategy.entry执行后,当前K线内strategy.opentrades的状态尚未完成更新,直接调用strategy.opentrades.entry_price(strategy.opentrades - 1)会获取到错误的价格(可能是上一笔订单价格或空值),导致止盈价计算错误。- 仅在开仓K线设置
strategy.exit,若lowestLow或入场价的逻辑在后续K线有变化,无法同步更新止损止盈参数。
修正代码
//@version=5 strategy("1:3 Risk-Reward Long Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, commission_type=strategy.commission.percent, commission_value=0.1) // 示例:替换为你实际的lowestLow和longcondition逻辑 lowestLow = ta.lowest(low, 20) // 近20根K线的低点 longcondition = ta.crossover(ta.sma(close, 5), ta.sma(close, 20)) // 均线金叉示例入场条件 var float entry_low = na // 持久化保存入场时的低点 var float entry_price = na // 持久化保存入场价格 // 开仓逻辑 if (longcondition and strategy.opentrades == 0) strategy.entry(id="MR_Long", direction=strategy.long) entry_low := lowestLow // 记录开仓瞬间的低点 entry_price := strategy.position_avg_price // 用持仓均价获取可靠入场价 // 持仓期间动态维护止损止盈 if (strategy.position_size > 0) if not na(entry_price) and not na(entry_low) profit_price = entry_price + (entry_price - entry_low) * 3 strategy.exit("Exit Long", "MR_Long", limit=profit_price, stop=entry_low)
关键优化说明
- 用
var变量持久化存储开仓时的低点和入场价,避免开仓K线内获取错误值。 - 在持仓期间的每一根K线都执行
strategy.exit,确保止损止盈始终基于开仓时的固定风险比计算,不会随后续K线的lowestLow变化而偏移。 - 改用
strategy.position_avg_price获取可靠的入场均价,替代开仓K线内直接调用strategy.opentrades.entry_price的不稳定方式。
内容的提问来源于stack exchange,提问作者BirdstudioNZ
相关产品推荐
相关产品推荐

