PART XIII · Chapter 108 · 608 / 660

Lesson 608. Pine Script Fundamentals: Writing Custom Moving-Average, ATR & Relative-Strength Indicators

Chapter 108. TradingView Setup & Hands-On Pine Script Strategy Coding Lab

Learn Pine Script v6 fundamentals—bar-by-bar series indexing (close[1]), user inputs, ta.sma, ta.ema, ta.atr(14), safe benchmark relative strength, and a runnable custom indicator. Lesson 248 and Lesson 253 introduced moving averages and Average True Range (ATR), while Lesson 245 and Lesson 257 showed how to turn relative strength and volatility into rule components. This lesson translates those ideas into clean Pine Script v6 code.

Run every indicator on top of the standardized Log scale · RTH regular-hours chart built in Lesson 607.

1. //@version=6 series execution and historical indexing ([1])

Pine Script v6 bar-by-bar series execution diagram moving from bar_index 0 to the live bar, applying [1] historical lookbacks, ta.sma/ta.atr calculations, request.security benchmark RS, and bgcolor regime shading.

Unlike vectorized Python/Pandas tables evaluated all at once, TradingView's Pine Script runtime executes your entire script sequentially one bar at a time from the earliest historical bar (bar_index == 0) up to the live bar:

  • Version & declaration: Begin with //@version=6 and indicator(..., overlay=true) when drawing moving averages directly over price candles (use overlay=false for separate lower oscillator panes).
  • Historical operator [n]: close (or close[0]) returns the current bar's close, close[1] returns one bar prior, and high[20] returns the high 20 bars ago. Negative offsets cannot peek into the future.
  • Handling na warmup bars: A 50-bar moving average produces na across bars 0 through 48. In Pine v6, check not na(x) explicitly before boolean comparisons or division.

2. User inputs (input.*), moving averages, ATR, and ADR%

Never hardcode parameter numbers deep inside expressions. Declaring input.int(), input.float(), and input.symbol() exposes clean UI controls inside the indicator's Settings gear.

Pine Script v6 ExpressionRole & Return SeriesPractical Engineering Note
input.int(20, "Fast", minval=1)Integer parameter slider in UIminval prevents invalid zero/negative lookbacks
ta.sma(close, 20) / ta.ema(close, 20)Simple / Exponential moving averageReturns na until enough historical bars accumulate
ta.atr(14)14-bar Average True Range (RMA smoothed)Captures overnight price gaps unlike raw High−Low (Lesson 253)
ta.sma((high-low)/close*100, 20)20-bar Average Daily Range % (ADR%)Normalizes volatility across $20 and $500 stocks cleanly
plot(..., display=display.data_window)Prints values to Data Window without flattening scaleKeeps ATR ($4) from squashing a $500 price chart

Pairing dollar ta.atr(14) with percentage ADR% lets you compare volatility uniformly across stocks of any nominal share price.

3. Safe benchmark relative strength (RS Ratio) and normalization

Relative strength (Lesson 245) divides the target stock's close by a market benchmark such as AMEX:SPY via request.security(). When querying the identical timeframe (timeframe.period) with gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, Pine aligns each bar cleanly by timestamp (cross-timeframe higher-TF anti-repainting rules are covered in Lesson 610).

Because raw ratios vary across tickers (e.g., 0.24 vs. 1.85), comparing rsRatio > ta.sma(rsRatio, 50) creates a scale-free trend test indicating whether the stock is outperforming the benchmark over the trailing 50 bars.

4. Regime shading (bgcolor) and complete Pine Script v6 indicator

Visualizing regime state with bgcolor()—light translucent green (color.new(color.green, 88)) when both trend (close > 50 SMA and 20 SMA > 50 SMA) and relative strength (rsRatio > rsSma) align, soft blue when trend alone holds, and faint red below the 50 SMA—lets you read market leadership immediately. Meanwhile, routing ATR(14), ADR%, and RS Ratio to display=display.data_window preserves a clean price y-axis.

Paste the complete //@version=6 script below directly into TradingView's Pine Editor and click Add to chart:

//@version=6
indicator("Trend, ATR & Benchmark RS Regime", shorttitle="HR Trend+RS", overlay=true)

// 1. User inputs
fastLen  = input.int(20, "Fast SMA Length", minval=1)
slowLen  = input.int(50, "Slow SMA Length", minval=2)
atrLen   = input.int(14, "ATR Length", minval=1)
benchSym = input.symbol("AMEX:SPY", "Benchmark Symbol")

// 2. Core series indicators and ADR%
smaFast = ta.sma(close, fastLen)
smaSlow = ta.sma(close, slowLen)
emaFast = ta.ema(close, fastLen)
atrVal  = ta.atr(atrLen)
adrPct  = ta.sma((high - low) / close * 100.0, fastLen)

// 3. Same-timeframe benchmark Relative Strength ratio
benchClose = request.security(
    benchSym, timeframe.period, close,
    gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off
)
rsRatio = not na(benchClose) and benchClose > 0 ? close / benchClose : na
rsSma   = ta.sma(rsRatio, slowLen)

// 4. Combined Trend + Relative Strength regime flags
isBullTrend = close > smaSlow and smaFast > smaSlow
isRsLeader  = not na(rsRatio) and not na(rsSma) and rsRatio > rsSma
isStrong    = isBullTrend and isRsLeader

// 5. Plots, Data Window outputs, and regime background
plot(smaFast, "20 SMA", color=color.teal, linewidth=2)
plot(smaSlow, "50 SMA", color=color.blue, linewidth=2)
plot(emaFast, "20 EMA", color=color.new(color.orange, 35), linewidth=1)
plot(atrVal,  "ATR(14)", display=display.data_window)
plot(adrPct,  "ADR% (20)", display=display.data_window)
plot(rsRatio, "RS Ratio", display=display.data_window)

bgCol = isStrong ? color.new(color.green, 88) : isBullTrend ? color.new(color.blue, 92) : color.new(color.red, 92)
bgcolor(bgCol, title="Trend and RS Regime Shading")

Next, Lesson 609 upgrades this passive diagnostic indicator into a complete executable strategy() engine with breakout triggers, ATR stops, and 1R position sizing.

Try it yourself

  1. Suppose daily closes across bar_index 0..4 are 100, 102, 101, 105, 108. At bar_index == 4, what are close[1], close[2], and ta.sma(close, 3)?
  2. A stock trades today with high = $212.00, low = $204.00, and close = $210.00, while SPY closes at $525.00. Compute today's single-day range percentage and RS Ratio, and check whether RS leadership holds if the 50-bar RS average sits at 0.385.
  3. Spot two bugs in this snippet intended to plot a 20 SMA over price candles: indicator("My MA", overlay=false), plot(ta.sma(close, 20)), and rs = close / request.security("AMEX:SPY", timeframe.period, close) with no na guard.

Answers

  1. At bar_index == 4, close is 108. Thus close[1] = 105, close[2] = 101, and ta.sma(close, 3) = (101 + 105 + 108) ÷ 3 = 104.67.
  2. Today's daily range is (212 − 204) ÷ 210 × 100 ≈ 3.81%, and RS Ratio = 210 ÷ 525 = 0.400. Since 0.400 > 0.385, relative-strength leadership is confirmed.
  3. First, change overlay=false to overlay=true so the SMA overlays the price candles rather than opening a separate pane. Second, guard against missing or zero benchmark bars on earlier history via not na(benchClose) and benchClose > 0 ? close / benchClose : na.

Related lessons