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

如何限制带offset偏移的移动平均线(MA)不超出当前时间戳显示

解决偏移移动平均线超出当前时间戳的问题

核心原理

正offset参数会让指标向未来时间轴方向偏移绘制线条,若要截断超出当前最后一根K线的部分,只需在超出范围的位置返回空值na,plot函数遇到na时不会渲染对应位置的线条。

修改后的完整代码

//@version=4
study(title="Cloud", shorttitle="VP", overlay=true, resolution="")
// 参数定义
len = input(9, minval=1, title="EMA Length")
src = input(close, title="Source")
offset = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)
len1 = input(9, minval=1, title="MA Length")
src1 = input(close, title="Source")
offset1 = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)

// 指标计算
out = ema(src, len)
out1 = sma(src1, len1)

// 新增范围限制逻辑:超出当前最后一根K线范围时返回空值
out_limit = bar_index > last_bar_index - offset ? na : out
out1_limit = bar_index > last_bar_index - offset1 ? na : out1

// 绘图逻辑
plot(out_limit, title="EMA", color=color.blue, offset=offset)
plot(out1_limit, color=color.blue, title="MA", offset=offset1)

mashort = out_limit
malong = out1_limit
cloudcolour = mashort >= malong ? color.green : color.red

mashortcolor = mashort >= mashort[1] ? color.olive : color.maroon
mashortline = plot(out_limit, title="EMA", color = color.green,linewidth = 3, offset=offset)
malongcolor = malong >= malong[1] ? color.green : color.red
malongline = plot(out1_limit, color = color.red, linewidth = 3, title="MA", offset=offset1)
fill(mashortline, malongline, color = color.yellow, transp = 85, title = "MA Cloud")

highestHigh = highest(high,50)
lowestLow = lowest(low,50)
//plot(highestHigh)
//plot(lowestLow)

修改点说明

  • 新增out_limit和out1_limit两个限制输出的变量,通过bar_index(当前K线索引)和last_bar_index(图表上最后一根K线的索引)对比,当偏移后位置超出最后一根K线时返回na
  • 所有原先调用out、out1的绘图和填充逻辑,都替换为限制后的out_limit、out1_limit,保证线条和云层都不会超出当前时间戳范围

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:45:00