如何在TradingView的Pine Script中拼接两个以上的SMA?
Pine Script 拼接多个SMA的实现方案
1. 是否可行?
完全可行,Pine Script提供了多种方式处理多个SMA的拼接需求,不管是把数值整合到数据结构里,还是在图表上叠加展示都能实现。
2. 具体实现方法
方法一:用数组存储多个SMA值(数值拼接)
如果需要把多个SMA的数值整合到一个数组里,可以通过数组操作实现:
//@version=5 indicator("多SMA数值拼接示例", overlay=true) // 计算三个不同周期的SMA sma_10 = ta.sma(close, 10) sma_20 = ta.sma(close, 20) sma_50 = ta.sma(close, 50) // 创建空数组存储SMA值 var sma_collection = array.new_float() // 在最后一根K线将三个SMA值依次加入数组完成拼接 if barstate.islast array.push(sma_collection, sma_10) array.push(sma_collection, sma_20) array.push(sma_collection, sma_50) // 在图表上显示数组内容 label.new(bar_index, high, str.tostring(sma_collection), color=color.blue)
方法二:图表上叠加多个SMA(视觉拼接)
如果你的“拼接”是指在图表上同时展示多个SMA,直接分别计算后调用plot()函数即可,这是最常用的方式:
//@version=5 indicator("多SMA叠加展示", overlay=true) // 计算三个周期的SMA sma_short = ta.sma(close, 10) sma_mid = ta.sma(close, 20) sma_long = ta.sma(close, 50) // 分别绘制每个SMA,实现视觉上的拼接展示 plot(sma_short, color=color.red, title="10周期SMA") plot(sma_mid, color=color.blue, title="20周期SMA") plot(sma_long, color=color.green, title="50周期SMA")
方法三:按K线整合多SMA值
如果需要把每根K线上的多个SMA值打包成一个数组元素,方便后续批量处理,可以这么写:
//@version=5 indicator("单K线多SMA组合", overlay=false) sma1 = ta.sma(close, 10) sma2 = ta.sma(close, 20) sma3 = ta.sma(close, 50) // 创建数组存储每根K线的SMA组合 var bar_sma_groups = array.new_array() if barstate.islast // 将当前K线的三个SMA值打包成小数组 current_bar_smas = array.new_float(3, sma1, sma2, sma3) array.push(bar_sma_groups, current_bar_smas) // 在图表上显示当前K线的SMA组合 label.new(bar_index, high, str.tostring(current_bar_smas), color=color.purple)
内容的提问来源于stack exchange,提问作者Antônio Chagas
相关产品推荐
相关产品推荐

