如何确保高时间周期指标数值在低时间周期不重绘?——Pine Script日线收盘价指标低周期定时更新方案问询
解决低周期指标仅在日线收盘时更新的问题
我来帮你搞定这个问题——你想要在1小时/15分钟这类低时间周期里,用日线收盘价计算指标,而且要求指标数值只在日线蜡烛完全收盘后才更新。之前你写的f_secureSecurity函数没生效,核心问题是没准确判断日线bar是否已经完成收盘,导致实时行情下提前获取了未收盘的日线数据。
问题根源分析
你原来的函数逻辑是security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0]),这种写法只是简单在实时状态下取前一根bar的数值,但没法区分“当前日线bar是否已经收盘”——哪怕日线还在运行,它还是会取到实时更新的日线数据,自然达不到“仅收盘时更新”的效果。
可行解决方案
我们需要修改安全获取数据的函数,核心是通过barstate.isconfirmed判断日线bar是否已经确认收盘,再结合实时行情状态来控制返回值:
修正后的安全数据获取函数
f_secureSecurity(_symbol, _res, _src) => // 获取目标周期数据,关闭前瞻模式,保留数据缺口(避免自动填充未收盘数据) src = security(_symbol, _res, _src, barmerge.gaps_on, barmerge.lookahead_off) // 判断目标周期的bar是否已经确认收盘 isTargetBarClosed = security(_symbol, _res, barstate.isconfirmed) // 实时行情下,如果目标bar未收盘,返回上一次的有效值;否则返回当前数据 barstate.isrealtime and not isTargetBarClosed ? nz(src[1]) : src
整合到你的指标函数中
把上面的函数替换掉原来的f_secureSecurity,再结合你的指标逻辑,完整代码如下:
//@version=5 indicator("仅日线收盘更新的相对强度指标", overlay=false) f_secureSecurity(_symbol, _res, _src) => src = security(_symbol, _res, _src, barmerge.gaps_on, barmerge.lookahead_off) isTargetBarClosed = security(_symbol, _res, barstate.isconfirmed) barstate.isrealtime and not isTargetBarClosed ? nz(src[1]) : src period = input(50, title="计算周期") getStatus(ticker) => securityClose = f_secureSecurity(ticker, 'D', close) norm_price = normalize(securityClose, 0, 1) benchmark = f_secureSecurity("USD", 'D', close) relative_strength = norm_price / benchmark relative_strength_ratio = 100 + ((relative_strength - ta.sma(relative_strength, period)) / ta.stdev(relative_strength, period)) momentum = ta.mom(securityClose, 10) momentum_rolling_mean = ta.sma(momentum, period) momentum_rolling_std = ta.stdev(momentum, period) relative_strength_momentum = 100 + ((momentum - momentum_rolling_mean)/momentum_rolling_std) smoothed_RS_Ratio = ta.sma(relative_strength_ratio, 10) smoothed_RS_Momentum_Ratio = ta.sma(relative_strength_momentum, 10) [smoothed_RS_Ratio, smoothed_RS_Momentum_Ratio] // 调用函数并绘制指标 rs_ratio, rs_momentum = getStatus(syminfo.tickerid) plot(rs_ratio, color=color.blue, title="平滑相对强度比率") plot(rs_momentum, color=color.red, title="平滑相对强度动量比率")
关键逻辑说明
barmerge.lookahead_off:关闭前瞻模式,确保不会提前获取未来的日线数据。barstate.isconfirmed:这个函数会返回true当且仅当目标周期(这里是日线)的bar已经完全收盘,不再更新。nz(src[1]):当日线未收盘时,返回上一次的日线收盘数据,保证指标数值不会随实时行情波动,直到日线收盘才更新。
测试方法
切换到1小时或15分钟周期,观察指标曲线:
- 日线运行期间,指标数值会保持不变;
- 当日线蜡烛完全收盘后,指标会一次性更新到最新计算值。
内容的提问来源于stack exchange,提问作者Ethan Lam
相关产品推荐
相关产品推荐

