Preventing Repainting
What repainting is, why it matters, every technique to prevent it, testing for repainting, and building indicators you can trust in live trading.
What Is Repainting and Why It Matters
Repainting is the most dangerous trap in PineScript development. A repainting indicator shows signals on historical bars that were not actually visible in real time. You scroll through your chart and see perfect buy signals at every bottom and perfect sell signals at every top, but when you trade it live, the signals appear and disappear, move to different bars, or never fire at all. The backtest looks incredible; live trading produces losses.
Repainting occurs because PineScript re-executes your script on every tick of the live bar. During the bar's formation, conditions can be true on one tick and false on the next. When the bar closes, only the final tick's values are saved to history. The signals that appeared and vanished during the bar's formation are gone, but in a backtest, you only see the final state, which makes the indicator look better than it actually performed.
The core problem
The Three Types of Repainting
Not all repainting is created equal. Understanding which type you are dealing with determines the fix. Some repainting is benign (an EMA updating in real time is expected). Some is catastrophic (signals that retroactively appear on past bars).
| Calculation-based | The script uses close, high, or low on the current live bar, which changes with every tick. A signal triggered at close = $65,200 might vanish when close drops to $65,100 before bar close. Most common type. |
| Security-based | request.security() returns the current (incomplete) higher-timeframe bar value. The daily close at 2 PM is not the daily close. It will change for 10 more hours. Appears correct on historical bars but repaints on live data. |
| Drawing-based | Labels, lines, and shapes placed at dynamic positions that get repositioned or deleted as conditions change. A support line that adjusts to each new low looks perfect in hindsight but was never stable enough to trade. |
Calculation-based repainting
close, high, or low can disappear by bar close.Security-based repainting
request.security() fetches the current higher-timeframe bar without using close[1] with lookahead. The daily EMA at 6 AM is calculated with only 6 hours of data. It will be materially different by midnight when the daily bar actually closes.Drawing-based repainting
Preventing Calculation-Based Repainting
The fix is simple: only act on confirmed bars. The built-in variable barstate.isconfirmed returns true only after the current bar has closed. By wrapping your signal logic in this check, you guarantee that every signal you generate is based on final, immutable data.
1//@version=52indicator("Non-Repainting Signals", overlay=true)34ema21 = ta.ema(close, 21)5rsi = ta.rsi(close, 14)67// REPAINTING: fires on every tick, might vanish before bar close8// badSignal = ta.crossover(close, ema21) and rsi > 50910// NON-REPAINTING: only fires after bar closes11goodSignal = ta.crossover(close, ema21) and rsi > 50 and barstate.isconfirmed1213plotshape(goodSignal, "Confirmed Buy", shape.triangleup,14 location.belowbar, color.green, size=size.small)1516// Alternative: use close[1] to reference the PREVIOUS completed bar17prevBarBull = close[1] > ema21[1] and close[2] <= ema21[2]18plotshape(prevBarBull, "Prev Bar Cross", shape.diamond,19 location.abovebar, color.blue, size=size.tiny)close[1] vs barstate.isconfirmed
barstate.isconfirmed waits for the current bar to close before executing. Your signal fires at the very end of the bar. close[1] references the previous completed bar. Your signal fires on the first tick of the next bar. In practice, the difference is negligible for most trading timeframes.Preventing Security-Based Repainting
The standard non-repainting pattern for request.security() is to fetch the previous completed bar using [1] on the expression combined with barmerge.lookahead_on. This ensures you always get data that is finalized and will never change.
1//@version=52indicator("Non-Repainting Security", overlay=true)34// REPAINTING: fetches current incomplete daily bar5// bad = request.security(syminfo.tickerid, "D", close)67// NON-REPAINTING: fetches yesterday's confirmed close8good = request.security(syminfo.tickerid, "D",9 close[1], lookahead=barmerge.lookahead_on)1011// NON-REPAINTING: fetch multiple confirmed values12[dHigh, dLow, dEma, dRsi] = request.security(syminfo.tickerid, "D",13 [high[1], low[1], ta.ema(close, 21)[1], ta.rsi(close, 14)[1]],14 lookahead=barmerge.lookahead_on)1516// NON-REPAINTING: weekly trend17weeklyTrend = request.security(syminfo.tickerid, "W",18 close[1] > ta.ema(close, 21)[1],19 lookahead=barmerge.lookahead_on)2021plot(good, "Daily Close (confirmed)", color.orange, 2, plot.style_stepline)22plot(dHigh, "Prev Day High", color.new(color.red, 30), 1, plot.style_stepline)23plot(dLow, "Prev Day Low", color.new(color.green, 30), 1, plot.style_stepline)24bgcolor(weeklyTrend ? color.new(color.green, 94) : color.new(color.red, 94))| close[1] + lookahead_on | The gold standard. [1] references the previous HTF bar. lookahead_on aligns it to the correct position on your chart. Together: non-repainting confirmed data. |
| close + lookahead_off (default) | Returns the current incomplete HTF bar value. Updates with every tick. Repaints. Only appropriate when you explicitly want live updating data and accept the trade-off. |
| close[1] + lookahead_off | Returns data from 2 HTF bars ago on your chart: too delayed. The [1] shifts back one bar, and without lookahead, it shifts back another. Rarely what you want. |
Preventing Drawing-Based Repainting
Drawing objects (labels, lines, boxes) should only be created when the underlying signal is confirmed. If you create a label on every tick and delete it when the condition changes, the label appears and disappears during live trading, but on historical bars, only the final state is visible, making it look like every signal was rock-solid.
1//@version=52indicator("Non-Repainting Drawings", overlay=true, max_labels_count=50)34ema21 = ta.ema(close, 21)5rsi = ta.rsi(close, 14)67// Only draw when bar is confirmed: immutable signal8bullSignal = ta.crossover(close, ema21) and rsi > 50 and barstate.isconfirmed910if bullSignal11 label.new(bar_index, low,12 "BUY\n" + str.tostring(close, "#.##"),13 color=color.new(color.green, 20),14 textcolor=color.white,15 style=label.style_label_up,16 size=size.small)1718// Support/resistance lines: only draw from confirmed pivots19pivH = ta.pivothigh(high, 5, 5)20if not na(pivH) and barstate.isconfirmed21 line.new(bar_index - 5, pivH, bar_index, pivH,22 color=color.new(color.red, 30), width=1,23 style=line.style_dashed, extend=extend.right)Testing for Repainting
You cannot test for repainting by looking at historical bars. That is the entire problem. Historical bars only show the final state. You must test on live data. Here is a systematic methodology for verifying that your indicator does not repaint.
Replay mode test
Screenshot comparison
The barstate.isconfirmed audit
plotshape(), label.new(), or alert() call. Trace the condition back to its source. If the condition depends on close, high, or low without barstate.isconfirmed or [1], it repaints.request.security() audit
request.security() call. If the expression does not use [1] with lookahead=barmerge.lookahead_on, the value may repaint. This is the single most common source of hidden repainting in community scripts.The RSI Superstack: Multi-TF RSI Without Repainting
The RSI superstack combines RSI readings from multiple timeframes into a single composite score, all without repainting. When the 1H, 4H, and daily RSI are all oversold simultaneously, you have a high-probability reversal setup on BTCUSDT. When all three are overbought, it is time to reduce exposure. This technique uses confirmed data only.
1//@version=52indicator("RSI Superstack", overlay=false)34rsiLen = input.int(14, "RSI Length")5obLevel = input.int(70, "Overbought")6osLevel = input.int(30, "Oversold")78// Current TF RSI (use [1] for confirmed value)9rsiCurrent = ta.rsi(close, rsiLen)[1]1011// Higher TF RSIs (all non-repainting)12rsi4h = request.security(syminfo.tickerid, "240",13 ta.rsi(close, rsiLen)[1],14 lookahead=barmerge.lookahead_on)15rsiD = request.security(syminfo.tickerid, "D",16 ta.rsi(close, rsiLen)[1],17 lookahead=barmerge.lookahead_on)1819// Composite score: average of all three20composite = (nz(rsiCurrent) + nz(rsi4h) + nz(rsiD)) / 32122// Individual plots23plot(nz(rsiCurrent), "RSI Current TF", color.white, 1)24plot(nz(rsi4h), "RSI 4H", color.blue, 1)25plot(nz(rsiD), "RSI Daily", color.purple, 1)26plot(composite, "Composite", color.yellow, 3)2728// Zones29hline(obLevel, "OB", color.new(color.red, 60))30hline(osLevel, "OS", color.new(color.green, 60))31hline(50, "Mid", color.new(color.gray, 80))3233// Superstack signals: all three in same zone34allOversold = rsiCurrent < osLevel and rsi4h < osLevel and rsiD < osLevel35allOverbought = rsiCurrent > obLevel and rsi4h > obLevel and rsiD > obLevel3637bgcolor(allOversold ? color.new(color.green, 80) :38 allOverbought ? color.new(color.red, 80) : na)3940plotshape(allOversold, "Stack Oversold", shape.triangleup,41 location.bottom, color.green, size=size.small, text="STACK OS")42plotshape(allOverbought, "Stack Overbought", shape.triangledown,43 location.top, color.red, size=size.small, text="STACK OB")Common Repainting Traps That Fool Beginners
These patterns look correct to beginners but contain subtle repainting. Learn to recognize them so you can spot them in community scripts before trusting your money to their signals.
Pivots are detected retroactively: ta.pivothigh(high, 5, 5) is confirmed 5 bars AFTER the pivot. Plotting without offset=-5 places the marker on the wrong bar.
The most common trap. "I'm using the daily close", but during the day, that close changes every tick. Only [1] with lookahead gives you yesterday's final close.
ta.highest(high, 20) includes the current forming bar. Today's high is not final until the bar closes. Use ta.highest(high, 20)[1] for confirmed data.
Checking volume > 2 * average on the live bar repaints because volume accumulates throughout the bar. Early in the bar, volume is always low.
Detecting "hammer" or "engulfing" patterns on the live bar repaints because the candle shape changes with every tick until the bar closes.
ta.crossover(ema9, ema21) can flip true and false multiple times during a single bar as price oscillates. Only trust it after barstate.isconfirmed.
Complete Build: Non-Repainting Signal System with Verification
This indicator is designed from the ground up to never repaint. Every data source uses confirmed values, every signal waits for bar close, and it includes a built-in verification table that shows the data source and confirmation status of each component. Use this as a template for all your signal-generating indicators.
1//@version=52indicator("Verified Signal System", overlay=true, max_labels_count=100)34emaLen = input.int(21, "EMA Length")5rsiLen = input.int(14, "RSI Length")6atrLen = input.int(14, "ATR Length")78// All calculations use confirmed data9ema = ta.ema(close, emaLen)10rsi = ta.rsi(close, rsiLen)11atr = ta.atr(atrLen)1213// HTF trend filter (non-repainting)14dailyTrend = request.security(syminfo.tickerid, "D",15 close[1] > ta.ema(close, emaLen)[1],16 lookahead=barmerge.lookahead_on)1718// Signals: ALL conditions must be confirmed19longCondition = close > ema and rsi > 40 and rsi < 70 and dailyTrend20shortCondition = close < ema and rsi < 60 and rsi > 30 and not dailyTrend2122// Entry trigger: EMA crossover on confirmed bar only23longEntry = ta.crossover(close, ema) and longCondition and barstate.isconfirmed24shortEntry = ta.crossunder(close, ema) and shortCondition and barstate.isconfirmed2526// Risk levels (calculated from confirmed ATR)27longStop = close - atr * 228longTP = close + atr * 329shortStop = close + atr * 230shortTP = close - atr * 33132// Signal markers33if longEntry34 label.new(bar_index, low,35 "LONG " + str.tostring(close, "#.##") +36 "\nSL: " + str.tostring(longStop, "#.##") +37 "\nTP: " + str.tostring(longTP, "#.##"),38 color=color.new(color.green, 10), textcolor=color.white,39 style=label.style_label_up, size=size.small)4041if shortEntry42 label.new(bar_index, high,43 "SHORT " + str.tostring(close, "#.##") +44 "\nSL: " + str.tostring(shortStop, "#.##") +45 "\nTP: " + str.tostring(shortTP, "#.##"),46 color=color.new(color.red, 10), textcolor=color.white,47 style=label.style_label_down, size=size.small)4849// EMA plot50plot(ema, "EMA", close > ema ? color.green : color.red, 2)5152// Verification table: proves non-repainting methodology53if barstate.islast54 t = table.new(position.bottom_left, 2, 5,55 bgcolor=color.new(#0d0b14, 10),56 border_width=1, border_color=color.new(color.gray, 70))5758 table.cell(t, 0, 0, "Component", text_color=color.gray, text_size=size.small)59 table.cell(t, 1, 0, "Status", text_color=color.gray, text_size=size.small)6061 table.cell(t, 0, 1, "Signal Gate", text_color=color.white, text_size=size.small)62 table.cell(t, 1, 1, "barstate.isconfirmed ✓",63 text_color=color.green, text_size=size.small)6465 table.cell(t, 0, 2, "HTF Data", text_color=color.white, text_size=size.small)66 table.cell(t, 1, 2, "close[1] + lookahead ✓",67 text_color=color.green, text_size=size.small)6869 table.cell(t, 0, 3, "Daily Trend", text_color=color.white, text_size=size.small)70 table.cell(t, 1, 3, dailyTrend ? "▲ Bullish" : "▼ Bearish",71 text_color=dailyTrend ? color.green : color.red, text_size=size.small)7273 table.cell(t, 0, 4, "RSI", text_color=color.white, text_size=size.small)74 table.cell(t, 1, 4, str.tostring(rsi, "#.#"),75 text_color=rsi > 70 ? color.red : rsi < 30 ? color.green : color.white,76 text_size=size.small)7778// Alerts (confirmed signals only: will not fire mid-bar)79alertcondition(longEntry, "Verified Long Entry",80 "Non-repainting long signal confirmed at bar close")81alertcondition(shortEntry, "Verified Short Entry",82 "Non-repainting short signal confirmed at bar close")The non-repainting guarantee
barstate.isconfirmed so they only fire after bar close, (2) all HTF data uses close[1] with lookahead_on so it references completed bars only, (3) all drawing objects are created inside confirmed-bar conditions so they never appear and disappear. If you follow this template for every indicator you build, repainting will never be a problem.1.What is 'repainting' in the context of PineScript indicators?
2.Which PineScript technique prevents signals from firing before a bar closes?
3.When using request.security() for higher-timeframe data, what is the correct non-repainting pattern?
4.What is 'timeframe alignment' and why does it matter in multi-timeframe PineScript?
5.How can you test whether a PineScript indicator repaints?
Put this lesson to work
Free on Thrive, no account needed.