Pine Script技术问题:满足前K线条件却在当前K线绘制箭头需修正
问题描述
目标:当某根K线的最低价高于5期EMA时,在该K线上方绘制向下箭头。
问题:代码中判断的是前一根K线([1])满足条件,但箭头却绘制在当前K线上,而非对应的前一根K线。
原始代码:
//EMA5 alert //@version=5 indicator("EMA 5 Alert", overlay=true) // Calculate 5-period EMA ema_5 = ta.ema(close, 5) // Check if previous candle's low is higher than EMA 5 prev_low = low[1] ema_5_prev = ta.ema(close, 5)[1] condition = prev_low > ema_5_prev // Plot shape and send alert if condition is true plotshape(condition, style=shape.arrowdown, location=location.abovebar, color=color.red, transp=0, size=size.auto, text="5",textcolor=color.red) alertcondition(condition, title="EMA 5 Detected", message="Previous candle didn't touch EMA5") // Plot EMA 5 plot(ema_5, color=color.rgb(66, 239, 245), linewidth=2) plot(close)
解决方案
问题核心是plotshape默认在当前K线绘制图形,而你的条件针对的是前一根K线。以下两种方法可以解决:
方法1:用offset参数偏移图形位置
保留原有的前K线判断逻辑,通过offset=-1让箭头向左偏移1根K线,精准对应满足条件的那根K线:
//EMA5 alert //@version=5 indicator("EMA 5 Alert", overlay=true) // Calculate 5-period EMA ema_5 = ta.ema(close, 5) // Check if previous candle's low is higher than EMA 5 prev_low = low[1] ema_5_prev = ema_5[1] // 复用已计算的EMA,避免重复运算 condition = prev_low > ema_5_prev // 添加offset=-1,将箭头偏移到前一根K线上方 plotshape(condition, style=shape.arrowdown, location=location.abovebar, color=color.red, transp=0, size=size.auto, text="5",textcolor=color.red, offset=-1) alertcondition(condition, title="EMA 5 Detected", message="Previous candle didn't touch EMA5") // Plot EMA 5 plot(ema_5, color=color.rgb(66, 239, 245), linewidth=2) plot(close)
方法2:直接判断当前K线的条件(更直观)
如果需求是“某根K线满足条件时,在它自身上方画箭头”,可以直接判断当前K线的最低价是否高于当期EMA,箭头会直接绘制在目标K线上:
//EMA5 alert //@version=5 indicator("EMA 5 Alert", overlay=true) // Calculate 5-period EMA ema_5 = ta.ema(close, 5) // 判断当前K线的最低价高于当期EMA condition = low > ema_5 // 无需偏移,直接绘制在当前K线上 plotshape(condition, style=shape.arrowdown, location=location.abovebar, color=color.red, transp=0, size=size.auto, text="5",textcolor=color.red) alertcondition(condition, title="EMA 5 Detected", message="Current candle didn't touch EMA5") // Plot EMA 5 plot(ema_5, color=color.rgb(66, 239, 245), linewidth=2) plot(close)
关键提示
offset参数控制图形的横向偏移,负数表示向左(历史方向)偏移,正数表示向右(未来方向)偏移。- 复用
ema_5[1]代替重新计算ta.ema(close,5)[1],能减少重复计算,提升代码运行效率。
内容的提问来源于stack exchange,提问作者amor de la vida
相关产品推荐
相关产品推荐

