如何用bgcolor标记当前蜡烛往前第10根蜡烛的背景?代码问题排查
问题:用bgcolor标记当前蜡烛往前数第10根蜡烛的背景色
原代码及问题
用户尝试为当前蜡烛往前数第10根添加红色背景,但代码无效果:
// Define the number of candles to count back candlesToCountBack = 10 // Calculate the index of the 5th candle from the current candle candleIndex = bar_index - candlesToCountBack // Condition to check if the current candle is the 5th candle isTenthCandle = bar_index == candleIndex bgcolor(color = isTenthCandle ? color.red: na)
错误原因
- 逻辑条件完全不成立:
isTenthCandle = bar_index == candleIndex等价于bar_index == bar_index - 10,这个等式永远为假(10≠0),因此不会触发任何背景色。 - 注释与变量不匹配:注释写的是“第5根蜡烛”,但变量实际设置的是10,容易造成逻辑混淆。
可行的实现方案
有两种简单的实现方式:
方案1:利用offset参数(推荐)
通过offset参数直接将背景色偏移到目标蜡烛位置,代码简洁高效:
// 定义往前数的蜡烛数量 candlesToCountBack = 10 // 在最新蜡烛位置,将红色背景偏移到往前第10根蜡烛 bgcolor(ta.barstate.islast ? color.red : na, offset = -candlesToCountBack)
方案2:通过bar索引判断
通过获取最新蜡烛的索引,判断当前处理的蜡烛是否为目标蜡烛:
// 定义往前数的蜡烛数量 candlesToCountBack = 10 // 获取最新蜡烛的bar索引 latestBarIdx = ta.bar_index[ta.barssince(ta.barstate.islast)] // 判断当前蜡烛是否是最新蜡烛往前数第10根 isTargetCandle = bar_index == latestBarIdx - candlesToCountBack // 设置背景色 bgcolor(isTargetCandle ? color.red : na)
说明
- 方案1更简洁,适合仅标记最新蜡烛往前数第N根的场景。
- 方案2更灵活,如果需要标记历史中每一根蜡烛的往前第N根,可以调整逻辑(比如去掉
ta.barstate.islast相关判断,改为针对每一根蜡烛的前N根)。
内容的提问来源于stack exchange,提问作者user22668351
相关产品推荐
相关产品推荐

