TradingView Pine Script v6 Price Rate of Change Indicator: Measure Percentage Momentum on Confirmed Bars

Beginner Trading Tutorial | TradingView | Pine Script v6

A chart can show that a market has moved higher or lower, but comparing the magnitude of that movement across time or across symbols requires a consistent measurement. A rise of five price units is quite different for an instrument trading near 50 than for one trading near 500. The price Rate of Change indicator, usually abbreviated ROC, converts a simple price comparison into a percentage that is easier to interpret.

In this tutorial we will build a complete Pine Script v6 indicator that compares the current closing price with the closing price a configurable number of bars earlier. We will also distinguish confirmed observations from developing-bar previews, guard against undefined calculations, and explain why two very different price paths can produce exactly the same ROC reading.

What ROC measures — and what it leaves out

Let C(t) be the current closing price and C(t−N) be the close N bars earlier. The formula is ROC = 100 × (C(t) − C(t−N)) / C(t−N). For positive prices, a positive reading indicates that the current close exceeds its historical reference, a negative reading indicates that it is lower, and zero means the two closes match. The result is expressed in percentage points.

Notice that only two closing prices enter this formula. ROC does not directly incorporate intrabar ranges, volume, the highest price reached during the interval, or the sequence of intermediate movements. It therefore measures net percentage movement rather than the smoothness or consistency of a trend.

TradingView Pine Script v6 Price Rate of Change Indicator: Measure Percentage Momentum on Confirmed Bars
Figure 1. Two hypothetical price paths start at 100 and finish at 105 four bars later. Both have a four-bar ROC of +5%, even though the second path initially declines.

In the illustration, Path A rises relatively steadily from 100 to 105. Path B drops to 96 before recovering to the same final close of 105. Both return +5% under a four-bar ROC calculation. A trader using ROC alone would not see the different interim drawdowns. This is a useful reminder that a momentum feature should not be mistaken for a complete description of risk.

Reference close Current close Price difference ROC
100 105 +5 +5.00%
200 210 +10 +5.00%
100 95 −5 −5.00%
100 100 0 0.00%
0 10 +10 Undefined

All examples are hypothetical. The last row is not a zero-momentum observation: the percentage is mathematically undefined. The indicator will leave that bar empty instead of substituting an arbitrary value.

Complete Pine Script v6 source

//@version=6
indicator("PatternSmart Price ROC", shorttitle="PS ROC",
     overlay=false, precision=2)

int lengthInput = input.int(12, "Lookback bars",
     minval=1, maxval=500)
bool confirmedOnly = input.bool(true, "Confirmed bars only")

// Compare the current close with the close N bars ago.
float pastClose = close[lengthInput]

// Reject missing data and unsupported nonpositive prices.
bool valid = not na(pastClose) and pastClose > 0 and
     not na(close) and close > 0

float roc = valid ?
     100.0 * (close - pastClose) / pastClose : na

// Suppress the developing bar when confirmation is required.
float shown = (not confirmedOnly or barstate.isconfirmed) ?
     roc : na

// Color represents the sign, not a buy or sell instruction.
color rocColor = na(shown) ? color.gray :
     shown >= 0 ? color.teal : color.maroon

plot(shown, title="ROC (%)", color=rocColor,
     style=plot.style_columns, histbase=0)
hline(0, "Zero reference", color=color.gray)

How the script works

The indicator declaration creates a separate pane with two decimal places of display precision. The Lookback bars input defaults to 12 and allows values from one to 500. The confirmation option defaults to true, making the completed-bar presentation the standard behavior.

Pine's history-referencing operator retrieves close[lengthInput]. At any given execution this means the close the specified number of bars earlier, not a reference to the future. The first N observations in a dataset do not have that much prior history. Pine represents unavailable values with na; the valid expression checks availability and positive prices before division. The latter restriction is intentional because the percentage interpretation used here assumes a positive reference price and a positive current price.

The formula then produces the full-precision result. A value of 5.0 means 5%, not 0.05%. We color nonnegative values teal and negative values maroon. These colors describe the sign of the calculation, not a recommendation to enter or exit. A horizontal zero reference helps visually distinguish the two regimes. A zero-height column may be hard to see, so check the Data Window when the result is close to zero.

Why the confirmation option matters

On historical bars, the script sees the final available closing price for each observation. A realtime indicator, however, can execute repeatedly as market updates arrive. On the developing bar, its close represents the latest price. The reference close N bars earlier is normally already confirmed, while the numerator changes with every price update. As a result, an intrabar ROC may move from positive to negative and back before the bar closes.

When Confirmed bars only is enabled, we use barstate.isconfirmed to suppress the unfinished bar. At the closing update, the indicator displays the final value. This is not the same as permanently shifting every observation back one bar: the plotted reading is attached to the bar whose close was used. Disable confirmation if you intentionally want a live preview. A preview can fluctuate and should not be treated as a committed historical signal.

This example calculates on the chart's own timeframe; it does not request higher-timeframe data or use future references. Data-provider revisions, corporate-action adjustments or changes in the chart dataset can still change historical observations. Confirmation controls normal intrabar changes, not all possible data changes.

Selecting the lookback period

Lookback Typical interpretation
1 Percentage change from the previous bar
5 Short-window net price movement
12 (default) Moderate rolling comparison
50 Longer-window movement with more lag relative to recent changes

A shorter lookback is usually more responsive to recent moves, while a longer lookback can retain the influence of an older reference price for longer. The correct setting depends on the research question. A 12-bar ROC on a five-minute chart compares closes one hour apart in uninterrupted trading, but gaps or session breaks can make elapsed wall-clock time longer. On a daily chart it compares 12 trading bars, not necessarily 12 calendar days. Changing the timeframe changes what an observation means.

Another subtlety is that ROC can increase even when the current close is unchanged: a different historical reference enters the calculation as each new bar arrives. For example, with a current close of 105, changing the reference from 100 to 98 changes ROC from 5.00% to about 7.14%. The denominator and the rolling comparison window matter as much as the latest close.

Installation and verification

  1. Open a standard time-based chart in TradingView and open Pine Editor.
  2. Create a new indicator and replace its template with the complete source above.
  3. Save the script, add it to the chart and inspect any compiler messages.
  4. Set Lookback bars to four and leave confirmation enabled.
  5. Select a completed candle, obtain its close and the close four bars earlier, and calculate the percentage manually.
  6. Compare the result with the plotted value in the Data Window. Test rising, falling and flat examples, then repeat with another lookback.

Observe a live market with confirmation enabled and disabled. The confirmed version should not display the open bar's changing value; the preview version may. Check that the first N bars with insufficient history have no result. Repeat on different symbols and verify that a higher nominal price does not by itself imply higher ROC. Nonstandard charts such as Heikin Ashi can use synthetic closing prices, so use standard candles when you intend to measure actual traded-close changes.

Using ROC responsibly

ROC can be useful in a watchlist research process, a momentum filter, or as a feature in a broader model. A positive value does not guarantee that the next bar rises, and a negative value does not guarantee a decline. A large reading may reflect a trend, an event-driven gap or an exhausted move. Compare volatility, liquidity, market structure and costs independently. Avoid selecting thresholds solely because they performed well on the same historical sample used to design them.

If you are interested in extending this free indicator with smoothing, volatility-aware thresholds, confirmed-bar alerts or strategy integration, contact us through our Custom Trading Software Development Services.

The implementation was checked against the Pine Script v6 documentation but has not been compiled or run in TradingView. Test it on your own chart before use. Trading involves risk, and historical momentum does not guarantee future performance.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.