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])
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=6andindicator(..., overlay=true)when drawing moving averages directly over price candles (useoverlay=falsefor separate lower oscillator panes). - Historical operator
[n]:close(orclose[0]) returns the current bar's close,close[1]returns one bar prior, andhigh[20]returns the high 20 bars ago. Negative offsets cannot peek into the future. - Handling
nawarmup bars: A 50-bar moving average producesnaacross bars 0 through 48. In Pine v6, checknot 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 Expression | Role & Return Series | Practical Engineering Note |
|---|---|---|
input.int(20, "Fast", minval=1) | Integer parameter slider in UI | minval prevents invalid zero/negative lookbacks |
ta.sma(close, 20) / ta.ema(close, 20) | Simple / Exponential moving average | Returns 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 scale | Keeps 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
- Suppose daily closes across
bar_index 0..4are100, 102, 101, 105, 108. Atbar_index == 4, what areclose[1],close[2], andta.sma(close, 3)? - A stock trades today with
high = $212.00,low = $204.00, andclose = $210.00, whileSPYcloses at$525.00. Compute today's single-day range percentage andRS Ratio, and check whether RS leadership holds if the 50-bar RS average sits at0.385. - 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)), andrs = close / request.security("AMEX:SPY", timeframe.period, close)with nonaguard.
Answers
- At
bar_index == 4,closeis108. Thusclose[1] = 105,close[2] = 101, andta.sma(close, 3) = (101 + 105 + 108) ÷ 3 = 104.67. - Today's daily range is
(212 − 204) ÷ 210 × 100 ≈ 3.81%, andRS Ratio = 210 ÷ 525 = 0.400. Since0.400 > 0.385, relative-strength leadership is confirmed. - First, change
overlay=falsetooverlay=trueso the SMA overlays the price candles rather than opening a separate pane. Second, guard against missing or zero benchmark bars on earlier history vianot na(benchClose) and benchClose > 0 ? close / benchClose : na.
Related lessons
- Lesson 248. How do you calculate and read a moving average?
- Lesson 253. How can you use ATR for stop-losses and position size?
- Lesson 245. Choosing strong stocks with relative strength
- Lesson 607. Configuring TradingView for Systematic Trading: Multi-Timeframe Layouts, Log Scale & Alerts
- Lesson 609. Coding Complete Trading Rules in Pine Script: Breakout Entries, ATR Stops & 1R Position Sizing

![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.](/en/courses/overseas-stocks/608/figure_01.png)