Repaint Demo: Higher-Timeframe EMA, Both Ways

harrell.jordon · study · 40 行 · 点赞 4 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © harrell.jordon
//@version=6
indicator("Repaint Demo: Higher-Timeframe EMA, Both Ways", shorttitle = "RepaintEMA", overlay = true)
 
// What this shows
// Two lines from the SAME daily EMA, requested two different ways.
// Red can move while the day is still open. Blue does not move once drawn.
// On history they agree on every bar except each day's last one; live, red drifts.
 
htfTF  = input.timeframe("D",  "Higher timeframe")
emaLen = input.int(20, "EMA length (on higher-timeframe closes)", minval = 1)
 
// (1) FORMING value: the default request, lookahead_off, no offset.
//     On historical bars request.security() returns only confirmed values,
//     so this steps to each day's EMA on that day's last chart bar.
//     On realtime bars it returns the unconfirmed value and moves with every
//     tick. After a reload, the live path is replaced by the confirmed one.
emaForming = request.security(syminfo.tickerid, htfTF, ta.ema(close, emaLen),
     lookahead = barmerge.lookahead_off)
 
// (2) CONFIRMED value: the non-repainting idiom. [1] INSIDE the call so the
//     expression is the previous completed higher-timeframe value, plus
//     lookahead_on. Behaves the same on historical and realtime bars.
//     The two are interdependent; neither can be removed.
emaConfirmed = request.security(syminfo.tickerid, htfTF, ta.ema(close, emaLen)[1],
     lookahead = barmerge.lookahead_on)
 
plot(emaForming,   title = "Forming (repaints)",     color = color.red,  linewidth = 2)
plot(emaConfirmed, title = "Confirmed (no repaint)", color = color.blue, linewidth = 2)
 
// Zero on history except each day's last bar. Live, the gap the forming value opens.
spread = emaForming - emaConfirmed
plotchar(spread, title = "Forming minus confirmed", char = "", location = location.top)
 
// How old the honest version can be, in chart bars: counted, not assumed.
newHTFBar  = ta.change(time(htfTF)) != 0
barsPerHTF = ta.barssince(newHTFBar)
plotchar(barsPerHTF, title = "Chart bars since the HTF bar opened", char = "",
     location = location.top)

← 返回列表