PineScript V5替换when为if后保留通知告警的方案求助
PineScript升级:替换
when参数并修正策略逻辑 关于when参数替换的疑问
把when参数换成if包裹策略调用完全不会丢失通知或告警功能,两者的信号触发逻辑完全一致,只是Pine Script v5之后推荐使用if语法来控制策略动作,废弃when参数是为了语法统一。
原代码的核心问题
- 条件表达式错误:多个条件中仅写了指标函数(如
ta.ema(close, 20)),未添加比较运算符,导致条件被错误解析为"只要指标值非零就为真",完全不符合策略逻辑。 strategy.exit对应关系混乱:原代码在多头区块设置空头订单的exit,空头区块设置多头订单的exit,属于逻辑错误,且重复设置exit会导致策略行为异常。
修正后的完整代码
//@version=5 strategy("修正后的多空策略", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000) // 定义输入参数(原代码缺失,补充后可正常调节参数) useTakeProfit = input.float("止盈点数", 50) useStopLoss = input.float("止损点数", 30) useTrailStop = input.float("追踪止损点数", 20) useTrailOffset = input.float("追踪止损偏移", 10) // 多头入场条件(补充EMA比较逻辑) longEntry() => ta.rsi(close, 2) <= 20 and close >= ta.sma(close, 200) and close >= ta.ema(close, 20) // 多头出场条件(补充EMA比较逻辑) longExit() => close <= ta.ema(close, 80) and ta.rsi(close, 2) >= 80 // 空头入场条件(补充EMA比较逻辑) shortEntry() => ta.rsi(close, 2) >= 80 and close <= ta.sma(close, 200) and close <= ta.ema(close, 80) // 空头出场条件 shortExit() => low <= ta.ema(close, 20) and ta.rsi(close, 2) <= 10 // 用if替代when参数,控制策略动作 if (longEntry()) strategy.entry(id='Compra', direction=strategy.long) // 为多头开仓绑定止损止盈与追踪止损 strategy.exit('Salir Compra', from_entry='Compra', profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset) if (longExit()) strategy.close(id='Compra') if (shortEntry()) strategy.entry(id='Venda', direction=strategy.short) // 为空头开仓绑定止损止盈与追踪止损 strategy.exit('Salir Venda', from_entry='Venda', profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset) if (shortExit()) strategy.close(id='Venda')
关键修正说明
when转if:将strategy.entry(..., when=xxx)改写为if (xxx) strategy.entry(...),功能完全等价,不会影响任何信号通知或告警。- 条件逻辑修复:所有指标必须配合比较运算符(
>=/<=等)才能作为有效布尔条件,否则策略会触发错误的开平仓信号。 strategy.exit规范:每个开仓订单对应专属的exit订单,放在同一个if块中,确保开仓时同步挂出止损止盈,避免逻辑混乱。- 补充输入参数:原代码中使用的
useTakeProfit等变量未定义,补充input.float后可在界面上调节参数,符合Pine Script规范。
内容的提问来源于stack exchange,提问作者yeerliin
相关产品推荐
相关产品推荐

