如何在Pine Script中每隔40根K线在均线旁绘制带文字的形状?
问题解决方案:在移动平均线旁每隔40根K线绘制带文字的标签
核心错误分析
你的代码中for循环的步长写法完全错误,by i + 40会导致步长随循环迭代不断增大,循环根本无法正常执行,这是标签不显示的直接原因。此外,直接在循环内创建标签会在每根K线重复生成大量冗余标签,既影响效率,还可能触发索引越界问题。
修正后的可运行代码
以下是包含移动平均线计算、间隔标签绘制的完整实现:
//@version=5 indicator("MA with Periodic Labels", overlay=true) // 配置移动平均线参数 maLength = input.int(20, title="MA周期") _m1 = ta.sma(close, maLength) _m1value = _m1 // 设置标签间隔参数 barSpacing = input.int(40, title="标签间隔(K线数)") // 仅在符合间隔条件的K线创建标签 if bar_index % barSpacing == 0 label.new(bar_index, _m1, style=label.style_label_left, color=color.rgb(255, 82, 82, 100), text="MA " + str.tostring(_m1value, "#.##"), textcolor=color.white) // 绘制移动平均线 plot(_m1, color=color.blue, title="MA")
额外优化方案
如果需要批量为历史K线生成标签(仅在脚本初始化时执行一次),可以使用数组存储标签对象避免重复创建:
//@version=5 indicator("MA with Periodic Labels", overlay=true) maLength = input.int(20, title="MA周期") _m1 = ta.sma(close, maLength) barSpacing = input.int(40, title="标签间隔(K线数)") // 用数组存储标签,仅在最后一根K线生成所有历史标签 var labels[] labelArray = array.new_label() if barstate.islast for i = 0 to bar_index by barSpacing array.push(labelArray, label.new(bar_index[i], _m1[i], style=label.style_label_left, color=color.rgb(255, 82, 82, 100), text="MA " + str.tostring(_m1[i], "#.##"), textcolor=color.white)) plot(_m1, color=color.blue, title="MA")
内容的提问来源于stack exchange,提问作者Eduardo Moreira
相关产品推荐
相关产品推荐

