Skip to main content

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

A repainting indicator lies about the past. It shows you what the signal looks like after the bar closed, not what it looked like while the bar was forming. This makes backtesting results completely unreliable. If you cannot trust your historical signals, you cannot trust your strategy's performance metrics.

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-basedThe 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-basedrequest.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-basedLabels, 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.
1

Calculation-based repainting

Occurs when your script makes decisions using data from the current, still-forming bar. The close of a 4H candle on BTCUSDT changes hundreds of times as new trades come in. Any signal that fires mid-bar based on close, high, or low can disappear by bar close.
2

Security-based repainting

Occurs when 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.
3

Drawing-based repainting

Occurs when drawing objects (labels, lines, boxes) are created or modified based on unconfirmed conditions. A "buy" label placed when RSI crosses 30 mid-bar might get deleted when RSI drops back below 30 before bar close. Historically, you only see the labels that survived, giving a false impression of accuracy.

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.

pine-barstate.isconfirmed: the primary defense
1//@version=5
2indicator("Non-Repainting Signals", overlay=true)
3
4ema21 = ta.ema(close, 21)
5rsi = ta.rsi(close, 14)
6
7// REPAINTING: fires on every tick, might vanish before bar close
8// badSignal = ta.crossover(close, ema21) and rsi > 50
9
10// NON-REPAINTING: only fires after bar closes
11goodSignal = ta.crossover(close, ema21) and rsi > 50 and barstate.isconfirmed
12
13plotshape(goodSignal, "Confirmed Buy", shape.triangleup,
14 location.belowbar, color.green, size=size.small)
15
16// Alternative: use close[1] to reference the PREVIOUS completed bar
17prevBarBull = 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

Both prevent repainting, but they work differently. 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.

pine-Non-repainting request.security() patterns
1//@version=5
2indicator("Non-Repainting Security", overlay=true)
3
4// REPAINTING: fetches current incomplete daily bar
5// bad = request.security(syminfo.tickerid, "D", close)
6
7// NON-REPAINTING: fetches yesterday's confirmed close
8good = request.security(syminfo.tickerid, "D",
9 close[1], lookahead=barmerge.lookahead_on)
10
11// NON-REPAINTING: fetch multiple confirmed values
12[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)
15
16// NON-REPAINTING: weekly trend
17weeklyTrend = request.security(syminfo.tickerid, "W",
18 close[1] > ta.ema(close, 21)[1],
19 lookahead=barmerge.lookahead_on)
20
21plot(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_onThe 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_offReturns 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.

pine-Confirmed-only drawing objects
1//@version=5
2indicator("Non-Repainting Drawings", overlay=true, max_labels_count=50)
3
4ema21 = ta.ema(close, 21)
5rsi = ta.rsi(close, 14)
6
7// Only draw when bar is confirmed: immutable signal
8bullSignal = ta.crossover(close, ema21) and rsi > 50 and barstate.isconfirmed
9
10if bullSignal
11 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)
17
18// Support/resistance lines: only draw from confirmed pivots
19pivH = ta.pivothigh(high, 5, 5)
20if not na(pivH) and barstate.isconfirmed
21 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.

1

Replay mode test

Use TradingView's bar replay feature. Step through bars one at a time and watch your signals. If a signal appears and then disappears on the next bar, the indicator repaints. Replay mode simulates live bar-by-bar execution without waiting for real-time data.
2

Screenshot comparison

Take a screenshot of the current live bar showing a signal. Wait for the bar to close. Take another screenshot. If the signal moved, changed, or disappeared, it repainted. Do this for at least 10 signals across different market conditions.
3

The barstate.isconfirmed audit

Search your entire script for any 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.
4

request.security() audit

Check every 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.

pine-RSI Superstack: non-repainting MTF RSI
1//@version=5
2indicator("RSI Superstack", overlay=false)
3
4rsiLen = input.int(14, "RSI Length")
5obLevel = input.int(70, "Overbought")
6osLevel = input.int(30, "Oversold")
7
8// Current TF RSI (use [1] for confirmed value)
9rsiCurrent = ta.rsi(close, rsiLen)[1]
10
11// 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)
18
19// Composite score: average of all three
20composite = (nz(rsiCurrent) + nz(rsi4h) + nz(rsiD)) / 3
21
22// Individual plots
23plot(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)
27
28// Zones
29hline(obLevel, "OB", color.new(color.red, 60))
30hline(osLevel, "OS", color.new(color.green, 60))
31hline(50, "Mid", color.new(color.gray, 80))
32
33// Superstack signals: all three in same zone
34allOversold = rsiCurrent < osLevel and rsi4h < osLevel and rsiD < osLevel
35allOverbought = rsiCurrent > obLevel and rsi4h > obLevel and rsiD > obLevel
36
37bgcolor(allOversold ? color.new(color.green, 80) :
38 allOverbought ? color.new(color.red, 80) : na)
39
40plotshape(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.

ta.pivothigh() without offset

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.

request.security() without [1]

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.

Highest/lowest on current bar

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.

Volume spike detection

Checking volume > 2 * average on the live bar repaints because volume accumulates throughout the bar. Early in the bar, volume is always low.

Candle pattern detection

Detecting "hammer" or "engulfing" patterns on the live bar repaints because the candle shape changes with every tick until the bar closes.

EMA crossover without confirmation

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.

pine-Verified non-repainting signal system (complete)
1//@version=5
2indicator("Verified Signal System", overlay=true, max_labels_count=100)
3
4emaLen = input.int(21, "EMA Length")
5rsiLen = input.int(14, "RSI Length")
6atrLen = input.int(14, "ATR Length")
7
8// All calculations use confirmed data
9ema = ta.ema(close, emaLen)
10rsi = ta.rsi(close, rsiLen)
11atr = ta.atr(atrLen)
12
13// HTF trend filter (non-repainting)
14dailyTrend = request.security(syminfo.tickerid, "D",
15 close[1] > ta.ema(close, emaLen)[1],
16 lookahead=barmerge.lookahead_on)
17
18// Signals: ALL conditions must be confirmed
19longCondition = close > ema and rsi > 40 and rsi < 70 and dailyTrend
20shortCondition = close < ema and rsi < 60 and rsi > 30 and not dailyTrend
21
22// Entry trigger: EMA crossover on confirmed bar only
23longEntry = ta.crossover(close, ema) and longCondition and barstate.isconfirmed
24shortEntry = ta.crossunder(close, ema) and shortCondition and barstate.isconfirmed
25
26// Risk levels (calculated from confirmed ATR)
27longStop = close - atr * 2
28longTP = close + atr * 3
29shortStop = close + atr * 2
30shortTP = close - atr * 3
31
32// Signal markers
33if longEntry
34 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)
40
41if shortEntry
42 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)
48
49// EMA plot
50plot(ema, "EMA", close > ema ? color.green : color.red, 2)
51
52// Verification table: proves non-repainting methodology
53if barstate.islast
54 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))
57
58 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)
60
61 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)
64
65 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)
68
69 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)
72
73 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)
77
78// 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

This system uses three layers of protection: (1) all signal conditions include 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.
Module Quiz

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?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.