Pine Script:背景色切换时创建竖线及类型报错问题解决
问题解决:背景色切换时绘制竖线
报错原因
你代码里的ta.crossover(bggreen, bgred)会报错,因为ta.crossover()要求两个参数都是数值型序列(series float),但你传入的bggreen和bgred是布尔型序列(series bool),类型不匹配导致报错。
解决方案
你已经定义了is_new_green和is_new_red这两个切换信号,直接用它们来触发竖线绘制即可,不需要再用ta.crossover。以下是两种实现方式:
方式1:用plot.style_vbar快速绘制竖线
这种方式代码简洁,适合快速生成竖线:
indicator('IS V1', overlay = true) varLo = input.int(title="Fast (Conversion) Line", defval=9, minval=1, maxval=99999) varHi = input.int(title="Slow (Base) Line", defval=26, minval=1, maxval=99999) emafreq = input.int(title="Ema on price frequency", defval=2, minval=1, maxval=99999) a = ta.lowest(varLo) b = ta.highest(varLo) c = (a + b ) / 2 d = ta.lowest(varHi) e = ta.highest(varHi) f = (d + e) / 2 z = ta.ema(close, emafreq) bggreen = (z > c and z > f) bgred = (z < c and z < f) is_new_green = not bggreen[1] and bggreen is_new_red = not bgred[1] and bgred // 保留背景色(可选,不需要可注释) bgcolor(bggreen ? color.green : bgred ? color.red: na) // 绘制绿色切换竖线 plot(is_new_green ? high * 1.02 : na, style=plot.style_vbar, color=color.green, linewidth=2) // 绘制红色切换竖线 plot(is_new_red ? high * 1.02 : na, style=plot.style_vbar, color=color.red, linewidth=2)
方式2:用line.new自定义竖线范围
如果需要让竖线覆盖当前K线的最低价到最高价,用line.new更灵活:
indicator('IS V1', overlay = true) varLo = input.int(title="Fast (Conversion) Line", defval=9, minval=1, maxval=99999) varHi = input.int(title="Slow (Base) Line", defval=26, minval=1, maxval=99999) emafreq = input.int(title="Ema on price frequency", defval=2, minval=1, maxval=99999) a = ta.lowest(varLo) b = ta.highest(varLo) c = (a + b ) / 2 d = ta.lowest(varHi) e = ta.highest(varHi) f = (d + e) / 2 z = ta.ema(close, emafreq) bggreen = (z > c and z > f) bgred = (z < c and z < f) is_new_green = not bggreen[1] and bggreen is_new_red = not bgred[1] and bgred // 保留背景色(可选) bgcolor(bggreen ? color.green : bgred ? color.red: na) // 绘制覆盖K线高低点的竖线 if is_new_green line.new(bar_index, low, bar_index, high, color=color.green, width=2) if is_new_red line.new(bar_index, low, bar_index, high, color=color.red, width=2)
关键说明
is_new_green和is_new_red已经精准捕捉了背景色的切换节点,直接作为触发条件即可实现需求。- 两种方式都可以和原背景色代码共存,竖线会叠加显示在背景之上。
内容的提问来源于stack exchange,提问作者chprot
相关产品推荐
相关产品推荐

