Pine Script v5:如何仅当满足前置条件时绘制longEntry信号图形?
Pine Script多单入场信号限制优化
要解决入场信号过于频繁的问题,只需给longEntry添加「过去5根K线内出现过longSetup」的判断条件即可。以下是两种直观的实现方式,适合刚接触编程的你理解:
方法一:用ta.highest()检查近期信号(推荐)
这种写法逻辑更直白,通过数值化判断过去5根K线内是否触发过建仓准备信号:
longSetup = src < lower and src < slsma and src < EMA50 and macd < signal // 生成判断条件:过去5根K线内(含当前)至少出现过一次longSetup hasRecentLongSetup = ta.highest(longSetup ? 1 : 0, 5) == 1 // 新增限制条件后的入场判断 longEntry = ta.crossover(src, slsma) and src < EMA50 and rsi < 40 and k > d and hasRecentLongSetup plotshape(longSetup, title="Long Setup", style=shape.cross, color=color.new(color.green, 40), size=size.small, location=location.bottom) plotshape(longEntry, title="Long Entry", style=shape.circle, color=color.new(color.yellow, 40), size=size.small, location=location.bottom)
代码说明
longSetup ? 1 : 0:将布尔类型的longSetup转换为数值,满足条件时为1,不满足时为0ta.highest(..., 5):提取过去5根K线内的最大值,若最大值为1,说明这段时间内至少有一次触发了longSetup- 将
hasRecentLongSetup加入longEntry的条件列表,即可实现仅在近期有建仓准备信号时才触发入场提示
方法二:用ta.barssince()计算信号间隔
通过计算距离上次longSetup的K线数,判断是否在5根范围内:
longSetup = src < lower and src < slsma and src < EMA50 and macd < signal // 判断距离上次longSetup的K线数不超过4(即过去5根内),同时排除从未触发过的情况 hasRecentLongSetup = ta.barssince(longSetup) <= 4 and not na(ta.barssince(longSetup)) longEntry = ta.crossover(src, slsma) and src < EMA50 and rsi < 40 and k > d and hasRecentLongSetup plotshape(longSetup, title="Long Setup", style=shape.cross, color=color.new(color.green, 40), size=size.small, location=location.bottom) plotshape(longEntry, title="Long Entry", style=shape.circle, color=color.new(color.yellow, 40), size=size.small, location=location.bottom)
代码说明
ta.barssince(longSetup):返回距离上次满足longSetup条件的K线数量(当前满足则返回0,上一根满足返回1,以此类推)not na(...):过滤从未触发过longSetup的场景,避免无意义的信号触发
内容的提问来源于stack exchange,提问作者Jack Falbey
相关产品推荐
相关产品推荐

