Pine Script 实现全看多信号触发后背景持绿至全看空信号触发问题
TradingView指标背景逻辑修改方案
你需要新增一个带状态记忆的变量控制背景色,仅在满足全绿、全红的临界条件时才切换背景,其余时间保持上一轮的背景状态即可。
修改核心逻辑
- 保留原有
bull(8个圆点全绿)、bear(8个圆点全红)的判断条件,作为背景切换的唯一触发阈值 - 用
var关键字声明背景色变量,该关键字修饰的变量会在K线刷新时保留上一轮的赋值,不会被自动重置 - 背景色仅在
bull触发时切换为绿色、bear触发时切换为红色,其余混合状态下保持原有值不变
修改后完整代码
bull = (ha_diff==2 and ha_diff2==2 and ha_diff3==2 and ha_diff4==2 and ha_diff5==2 and ha_diff6==2 and ha_diff7==2 and ha_diff8==2 ) bear = (ha_diff==1 and ha_diff2==1 and ha_diff3==1 and ha_diff4==1 and ha_diff5==1 and ha_diff6==1 and ha_diff7==1 and ha_diff8==1 ) plot(15, title="TF1", color=iff(ha_diff==1, red, iff(ha_diff==2, green, white)), style=circles, linewidth=5, join=true) plot(14, title="TF2", color=iff(ha_diff2==1, red, iff(ha_diff2==2, green, white)), style=circles, linewidth=5, join=true) plot(13, title="TF3", color=iff(ha_diff3==1, red, iff(ha_diff3==2, green, white)), style=circles, linewidth=5, join=true) plot(12, title="TF4", color=iff(ha_diff4==1, red, iff(ha_diff4==2, green, white)), style=circles, linewidth=5, join=true) plot(11, title="TF5", color=iff(ha_diff5==1, red, iff(ha_diff5==2, green, white)), style=circles, linewidth=5, join=true) plot(10, title="TF6", color=iff(ha_diff6==1, red, iff(ha_diff6==2, green, white)), style=circles, linewidth=5, join=true) plot(9, title="TF7", color=iff(ha_diff7==1, red, iff(ha_diff7==2, green, white)), style=circles, linewidth=5, join=true) plot(8, title="TF8", color=iff(ha_diff8==1, red, iff(ha_diff8==2, green, white)), style=circles, linewidth=5, join=true) // 带状态记忆的背景色变量,初始默认设为红色,可根据需求调整初始值 var color backgroundColour = red // 仅全绿/全红时切换状态,其余时间保持上一轮值 backgroundColour := bull ? green : bear ? red : backgroundColour bgcolor(color=backgroundColour, transp=40, title="Conditionally coloured background")
验证说明
修改后逻辑完全匹配需求:
- 8个圆点首次全部变绿时,背景立刻切换为绿色
- 绿色背景生效期间,部分圆点变红不会触发背景切换,直到8个圆点全部变红才会切为红色背景
- 红色背景生效期间同理,仅当8个圆点再次全部变绿时才切回绿色
内容的提问来源于stack exchange,提问作者Thierry Verhaegen
相关产品推荐
相关产品推荐

