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

如何在印度股市日内图表绘制过去5日历史VWAP(代码优化需求)

如何在Pine Script中绘制过去5个交易日的历史VWAP(印度股市日内图表)

要实现过去5个交易日的历史VWAP显示,核心是用数组存储每日VWAP值替代原代码中单个变量的方式,以此保留多天的历史数据。以下是修改后的完整代码:

//@version=5
indicator("Current & Previous 5 Days VWAP", shorttitle = "VWAP (5D)", overlay = true, timezone = "Asia/Kolkata")

// 用户输入:选择显示过去N天的VWAP(最多5天)
showPrevDays = input.int(5, "显示过去N天的VWAP", minval=1, maxval=5)
showCurrentVWAP = input.bool(true, "显示当日VWAP")

// 检测新交易日(适配印度时区)
newSession = ta.change(time("D"))

// 当日VWAP计算
var float vwapSum = 0.0
var float volumeSum = 0.0
vwapSum := newSession ? hlc3 * volume : vwapSum[1] + hlc3 * volume
volumeSum := newSession ? volume : volumeSum[1] + volume
currentVWAP = vwapSum / volumeSum

// 存储历史VWAP的数组
var array<float> historicalVWAPs = array.new<float>()

// 新交易日开始时,将前一日的VWAP存入数组
if newSession
    // 仅当数组长度小于设定天数时添加,或替换最早的元素
    if array.size(historicalVWAPs) >= showPrevDays
        array.shift(historicalVWAPs)  // 移除最早的VWAP
    array.push(historicalVWAPs, currentVWAP[1])  // 存入前一日VWAP

// 绘制当日VWAP
plot(showCurrentVWAP ? currentVWAP : na, "当日VWAP", color=color.rgb(0, 68, 255), linewidth=2)

// 绘制历史VWAP(循环绘制每个存储的历史值)
var color[] lineColors = array.new(color, [color.white, color.orange, color.yellow, color.green, color.purple])
for i = 0 to array.size(historicalVWAPs)-1
    vwapVal = array.get(historicalVWAPs, i)
    // 仅在对应交易日之后的时段显示该VWAP线条
    plot(vwapVal, str.tostring(showPrevDays - i) + "日前VWAP", color=array.get(lineColors, i), linewidth=2)

关键修改说明:

  1. 时区适配:在indicator中添加timezone = "Asia/Kolkata",确保交易日判断符合印度股市的时间规则,避免UTC时区导致的交易日错位问题。
  2. 数组存储历史数据:用array<float>类型的数组historicalVWAPs保存每日VWAP值,新交易日自动存入前一日的VWAP,并通过array.shift()控制数组长度不超过用户设定的天数。
  3. 多线条循环绘制:通过for循环遍历数组中的每个历史VWAP值,为每条线条分配不同颜色,并标注对应的天数,清晰区分不同交易日的VWAP。
  4. 可配置显示数量:用户可以通过输入框选择1-5天的历史VWAP显示数量,灵活适配需求。

内容的提问来源于stack exchange,提问作者Deep Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:57:11