Pine Script v6 Beginner Guide: Indicator and Alert | SG Group
Skip to the article
TradingView guide · Content reviewed 日本語で読む
PINE SCRIPT · TV10

Pine Script v6 Beginner Guide: Build a TradingView Indicator and Alert

Pine Script is TradingView’s language for indicators, strategies and libraries. A few lines can draw a useful series, but historical and realtime execution, timeframe, data context, input reloads, alert snapshots and repainting determine what that series actually means. This guide builds a neutral indicator that displays the percentage distance between price and a moving-average baseline. It then verifies the version declaration, indicator role, inputs, series, plots, confirmed bars, alertcondition and QA. The objective is reproducible visualization—not a profitable signal.

Who this guide is for: Readers opening Pine Editor for the first time, users who want to understand a published script, and learners testing confirmed-bar alerts against historical and realtime behavior

Key points to understand first

SCRIPT QA GRID

Move from “it runs” to “its behavior is explained”

  1. 01
    Compile

    Check version and types; read every error and warning

    Editor message and script hash
  2. 02
    Data context

    Freeze symbol, provider, interval, session and adjustment

    Chart ID and image
  3. 03
    Historical

    Inspect warm-up, na values and the first valid bar

    Known-bar table
  4. 04
    Realtime

    Compare open-bar changes with the confirmed close

    Timestamped observations
  5. 05
    Inputs

    Test boundaries, reload and displayed units

    Test matrix
  6. 06
    Alert

    Reconcile condition, frequency, message and recreation

    Alert ID and log
A historical plot is not enough. Verify data context, realtime bars, input changes and the alert snapshot.
01 · CHOOSE THE SCRIPT TYPE

Choose indicator, strategy or library before coding

An indicator calculates series and displays plots or drawings on TradingView. A strategy uses a `strategy()` declaration and `strategy.*` features to simulate orders across historical and realtime bars. A library publishes reusable functions or types for import by other scripts. For a first project, one neutral indicator is easier to trace than an order simulation or a generalized library.

Beginning with a “buy signal” encourages the visual result to be confused with profitability. The sample here shows the closing price’s percentage distance from a simple moving average and marks a confirmed cross above zero. It does not select entry, exit, stop, quantity or suitability. Converting it into a strategy later creates a new specification for order timing, commission, slippage and bar assumptions.

Roles of Pine declarations
TypePrimary purposeTypical outputScope here
indicator()Calculation and visualizationPlots, shapes and alert eventsLearning sample
strategy()Simulated ordersTrades and tester reportsExisting backtest series
library()Reusable codeExported functions and typesConcept only

Changing script type changes execution and validation requirements; it is not a naming edit.

02 · EXECUTION MODEL

Pine executes bar by bar and repeats on an open realtime bar

When a script is added, it executes from older to newer bars in the accessible dataset. Built-in series such as `close` and `high` hold the values for the bar currently being processed, while `close[1]` refers to the previous bar. Historical bars contain confirmed values and are generally calculated once in sequence. On the open realtime bar, an indicator can execute repeatedly as updates arrive.

Before each realtime recalculation, rollback restores the bar to its last committed state. A condition can become true during the bar and be false at the close, making a temporary mark disappear. After reload, elapsed realtime bars become historical bars calculated from final values; temporary ticks may no longer be available. That is one route to behavior commonly described as repainting.

Execution context to preserveExecution context = script version + inputs + symbol ID + timeframe + session + data adjustmentsHistorical observation = confirmed bar values available after reloadRealtime observation = temporary updates before the bar closesThe same source code can produce different datasets and results in another context.
03 · BUILD THE INDICATOR

Read a neutral distance indicator one line at a time

`//@version=6` selects the language version. `indicator()` declares name and display location. `input.int()` creates a user-controlled length with a minimum of two. `ta.sma()` calculates the baseline on every bar, while `distancePct` expresses the close as a percentage away from it. The conditional returns `na` if a zero baseline were encountered, avoiding division by zero.

Pine Script v6 learning samplepine
//@version=6
indicator("Confirmed MA Distance — learning example", overlay = false)

int lengthInput = input.int(20, "Baseline length", minval = 2)
float baseline = ta.sma(close, lengthInput)
float distancePct = baseline == 0.0 ? na : (close / baseline - 1.0) * 100.0

bool crossedAbove = ta.crossover(distancePct, 0.0)
bool confirmedCross = barstate.isconfirmed and crossedAbove

plot(distancePct, "Distance from baseline (%)", color = color.teal, linewidth = 2)
hline(0.0, "Baseline", color = color.gray)
plotshape(confirmedCross, title = "Confirmed cross", style = shape.circle,
     location = location.bottom, color = color.orange, size = size.tiny)

alertcondition(confirmedCross, "Confirmed cross above baseline",
     "Confirmed MA-distance cross on {{exchange}}:{{ticker}} at {{close}}")

This educational visualization is not a trading signal, recommended setting or performance claim. Check the current manual and compiler messages before using it in Pine Editor.

`ta.crossover()` is evaluated on every bar, and its result is then combined with `barstate.isconfirmed`. Evaluating time-series functions consistently is easier to review than calling them only in a branch. `plot()` shows distance, `hline()` marks zero, and `plotshape()` marks a confirmed cross. `alertcondition()` exposes an event that a user can select when creating an alert; adding it to code does not automatically create a notification.

04 · INPUT & CONTEXT TEST

Treat input and chart changes as separate test cases

Changing an input reloads the script across the dataset. Lengths 2, 20 and 200 can have different warm-up, smoothness and cross counts under the same indicator name. Selecting the best-looking length after seeing one period can overfit the display. Predefine default, minimum, representative and extreme tests; inspect `na`, scale, first valid bar and calculation behavior.

Minimum test matrix
CaseChangeVerifyFailure example
AMinimum lengthCompile and first valid valueTreats na as zero
BDefault lengthHand calculation and plotMissing unit label
CLong lengthWarm-up and history depthIgnores insufficient bars
DAnother timeframeBar boundary and cross timeAssumes same event
EAnother provider/sessionDataset differenceStores ticker text only

The purpose is specification testing, not selection of a superior parameter.

Changing timeframe or symbol changes the bar sequence. Adding `request.security()` introduces gaps, lookahead, higher- or lower-timeframe confirmation and another data context. This sample intentionally uses only the chart context. Before adding requests, consult the current versionless Pine manual for recommended patterns and limitations.

05 · ALERT CONTRACT

Separate alertcondition from the alert instance

`alertcondition()` defines a condition that an indicator user can select in the Create Alert dialog. To run notifications, create an alert instance with script, symbol, timeframe, inputs, condition, frequency, message, expiration and delivery method. TradingView treats the instance as a server-side snapshot of the script and inputs at creation. Do not assume that later chart or code changes automatically update an existing instance.

The sample combines the cross with `barstate.isconfirmed`, targeting the close rather than an intrabar cross. This does not remove feed revisions, session differences, reload behavior or requested-data issues. Align alert frequency with the condition under current options, and preserve alert ID in the ledger from the TradingView alerts guide.

06 · REPAINTING QA

Compare historical, open realtime, confirmed and reload states

TradingView uses repainting broadly for historical versus realtime calculations or plots that behave differently. A live RSI or moving average changing on an open bar is common. Future-leaking lookahead, plotting into the past, unconfirmed higher-timeframe values, non-standard-chart strategies or intrabar dependence can be more misleading. Replace the binary question “does it repaint?” with a description of what changes, when and why.

  1. Save historical state

    Record confirmed values and marks immediately after reload.

  2. Observe the open bar

    Log temporary distance and intrabar crosses separately.

  3. Confirm the close

    Check whether the condition and marker remain.

  4. Reload

    Compare the same bar after it is recalculated as historical.

  5. Change one context field

    Vary input, timeframe or session separately to isolate causes.

Apply the same checklist to scripts from the SG Group free TradingView indicator collection. A polished plot is not a quality guarantee. For a published script, review the author explanation, source availability, update history, permissions and alert behavior.

07 · DOCUMENT & NEXT STEP

Document code, inputs, limitations and alert recreation together

Before saving or sharing, document purpose, formula, inputs, units, assumed symbol and timeframe, `na` handling, realtime behavior, repainting possibilities, alert condition and change history. State what the script calculates and does not calculate instead of claiming high accuracy or profit. Respect third-party source and licenses; do not publish copied logic as original when it is not understood.

After conversion to a strategy, use the existing TradingView Backtesting Guide to progress through data quality, costs, trade lists, robustness and out-of-sample review, then import suitable results into the Backtest & Robustness Lab. This article ends when the indicator and alert execute according to a documented specification; it does not duplicate strategy-performance analysis.

Frequently asked questions

What can Pine Script v6 create?

It can define TradingView indicators, strategies and libraries. Check the current manual for available features and limitations, and validate each script type differently.

Does barstate.isconfirmed eliminate all repainting?

No. It helps with open-bar confirmation but does not automatically solve lookahead, unconfirmed requested data, provider revisions or plot offsets.

Does alertcondition start notifications automatically?

No. After defining the event, a user creates an alert instance in the UI with symbol, timeframe, inputs, frequency, message and delivery settings.

Does changing code update an existing alert?

Do not assume it does. An alert instance runs from a creation-time snapshot, so review whether it must be recreated after code or input changes.

Is the sample a trading signal?

No. It is a neutral educational visualization of distance from a baseline and a confirmed cross. It does not define entry, exit, quantity, forecast or profitability.

Primary sources and verification links

  1. TradingView | Pine Script User ManualOfficial entry point for Pine Script v6 language, concepts, visuals and writing guidance
  2. TradingView Pine Script | Execution modelOfficial bar-by-bar execution, realtime updates, rollback and reload behavior
  3. TradingView Pine Script | InputsOfficial input types, settings and recalculation behavior
  4. TradingView Pine Script | AlertsOfficial alertcondition, alert, order-fill and alert-instance concepts
  5. TradingView Pine Script | RepaintingOfficial treatment of historical/realtime differences and misleading patterns

Edited and published by: SG Group · Editorial approach: We prioritize official TradingView Help Center and Pine Script documentation, then use exchange, regulator and other primary materials for market and product context. Features, data, pricing and connection terms change, so verify the current interface and linked sources before use.

Important notice: This article provides general education about TradingView interfaces, charts, alerts, screeners, paper trading and Pine Script. It is not investment advice, a trading signal, a recommendation of any instrument, data source or broker, or a guarantee of future price or profit. Features, pricing, data, exchange coverage, notifications, order integrations and Pine Script behavior vary by plan, region, connection and date and may change. Before risking money, verify current TradingView documentation and the terms of the relevant data source and connected provider, then rehearse the workflow with fictional data or paper trading.