You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pine Script中计算往期K线的Supertrend值?提取倒数第3根示例

在Pine Script中获取往期K线的Supertrend值

要提取倒数第3根K线的Supertrend值,核心思路是先计算出每一根K线对应的Supertrend指标值,再通过历史引用的方式获取指定往期K线的数值。

实现步骤

  • 计算每根K线的Supertrend值:使用Pine Script内置的ta.supertrend()函数,传入周期和乘数参数,得到覆盖所有历史K线的Supertrend序列。
  • 引用倒数第3根K线的数值:在Pine Script中,用变量名[n]的格式可获取该变量在n根K线前的数值。倒数第3根K线对应n=2([1]是倒数第2根,[2]即为倒数第3根)。

完整代码示例

//@version=5
indicator("获取倒数第3根K线的Supertrend值", overlay=true)

// 自定义Supertrend参数
length = input.int(10, title="周期")
multiplier = input.float(3.0, title="乘数")

// 计算全序列的Supertrend值
st = ta.supertrend(multiplier, length)

// 提取倒数第3根K线的Supertrend数值
st_prev3 = st[2]

// 可选:在图表上标注该数值
label.new(bar_index, high, str.tostring(st_prev3), color=color.red, textcolor=color.white)
// 绘制Supertrend主趋势线
plot(st, color=color.blue, title="Supertrend")

代码说明

  • ta.supertrend(multiplier, length):生成包含每根K线Supertrend值的序列,当前K线对应st[0],历史K线依次往后偏移。
  • st[2]:精准定位到倒数第3根已闭合K线的Supertrend值,回测和实盘中均不会触发未来函数问题。
  • 可通过label.new()将数值标注在图表上,或用print()输出到控制台,方便查看验证。

内容的提问来源于stack exchange,提问作者Nithesh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:10:36