Skip to content
FactorQX
beginnerpine-scripttradingviewindicators

Getting Started with Pine Script v5

A practical introduction to Pine Script v5: scripts vs. studies, the execution model, and writing your first indicator on TradingView.

2 min read

Pine Script is TradingView's domain-specific language for building indicators and strategies. This guide explains the mental model you need before writing real scripts, then walks through a minimal indicator.

This is educational material about programming. Nothing here is investment advice, a trading signal, or a recommendation.

The execution model

The single most important idea in Pine Script is that your script runs once per bar, from the first historical bar to the most recent. Variables are recalculated on every bar, and series values are indexed backward with []: close[1] is the previous bar's close.

hello-pine.pine
//@version=5
indicator("Hello FactorQX", overlay = true)
 
// `close` is a series: its value changes on every bar.
length = input.int(20, "MA Length", minval = 1)
ma = ta.sma(close, length)
 
plot(ma, color = color.teal, linewidth = 2, title = "SMA")

The overlay = true flag draws the plot on the price chart rather than in a separate pane. input.int exposes a user-editable setting in the indicator's settings dialog.

var and persistent state

By default, a variable is reassigned every bar. Use var when you want a value to persist across bars and only initialize once:

//@version=5
indicator("Bar counter")
 
var int barsSeen = 0
barsSeen := barsSeen + 1
 
plot(barsSeen)

Without var, barsSeen would reset to 0 on every bar and the plot would be flat at 1.

Avoiding repainting

A script "repaints" when its historical values differ from what you would have seen in real time. A common cause is reading values that are only final at the bar's close while acting on the still-forming current bar. When you need confirmed values, gate logic on barstate.isconfirmed or reference close[1].

// Only act on the previous, fully-closed bar.
crossedUp = ta.crossover(close[1], ma[1])

Where to go next

  • Study the built-in ta.* namespace for technical calculations.
  • Learn request.security() for multi-timeframe data — and its repainting caveats.
  • Move from indicator() to strategy() once you understand the execution model, so backtest results reflect realistic fills.

Pine Script rewards a clear understanding of when code runs. Get the execution model right and the rest of the language is small and learnable.

Educational content. This article covers software development and research methods only. It is not investment advice, a trading signal, or a recommendation. See our disclaimer.