You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

TradingView Pine Script:如何在不使用offset的情况下实现指标左移?

在TradingView Pine Script中实现左移(不使用offset)的解决方案

我懂你遇到的困扰了——在Pine Script里,用shift[25]实现右移(显示25根K线之前的收盘价)完全正常,但尝试用shift[-25]做左移操作时,直接弹出了Index cannot be a negative value的错误。这是因为Pine Script的索引规则不允许用负数访问“未来”的K线数据,直接用负索引走不通。

那不用offset怎么实现左移效果?这里给你两个可行的方案:

方案一:用数组缓存数据实现左移

我们可以用var关键字创建一个持久化数组,用来存储每一根K线的收盘价。等数组长度足够覆盖要左移的周期后,就能在对应的历史K线位置调用后续的收盘价,达到左移显示的效果。

代码示例:

//@version=5
indicator("right_left_shift", overlay=true)
shift_period = 25

// 创建持久化数组存储收盘价
var float[] price_cache = array.new_float()
// 每根K线更新时,把当前收盘价存入数组
array.push(price_cache, close)

// 数组长度足够时,取出对应位置的未来收盘价
left_shifted_close = na
if array.size(price_cache) > shift_period
    if bar_index + shift_period < array.size(price_cache)
        left_shifted_close = array.get(price_cache, bar_index + shift_period)

// 绘制各线条
plot(close, color=color.blue, title="Original Price")
plot(close[shift_period], color=color.green, title="Right Shifted")
plot(left_shifted_close, color=color.red, title="Left Shifted")

方案二:利用request.security函数获取未来数据

另一种思路是用request.security函数指定目标K线索引,直接获取未来shift_period根K线的收盘价,以此实现左移效果。

代码示例:

//@version=5
indicator("right_left_shift", overlay=true)
shift_period = 25

// 通过request.security获取未来shift_period根K线的收盘价
left_shifted_close = request.security(syminfo.tickerid, timeframe.period, close[bar_index - (bar_index + shift_period)])

// 绘制各线条
plot(close, color=color.blue, title="Original Price")
plot(close[shift_period], color=color.green, title="Right Shifted")
plot(left_shifted_close, color=color.red, title="Left Shifted")

需要注意的是,这两种方案本质上都是在获取“未来”数据,所以实盘交易中要谨慎使用——毕竟真实行情里无法提前获取未来数据,这类指标更多用于回溯分析。

内容的提问来源于stack exchange,提问作者rohan sawant

火山引擎 最新活动