Pine Script is TradingView’s cloud-based coding language for building custom chart indicators, automated price alerts, and historical strategy tests on TradingView charts. Because scripts run on TradingView’s servers rather than your own computer (per TradingView’s Pine Script documentation), you can write and test ideas without installing local software.
This beginner guide explains the three Pine Script v6 (//@version=6) file types, how scripts run one candlestick at a time, how to avoid signals that change past results, and when to use Pine Script instead of MetaTrader MQL5 or Python.
Indicators vs strategies vs libraries in Pine Script v6
Per TradingView’s script-structure documentation, a modern Pine Script file starts with a version line (//@version=6) followed by one declaration function that sets what the script is allowed to do on a chart. The table below compares the three core script types, their declaration line, main job, and key limit.
| Type | Declaration | Main Job | Key Limit |
|---|---|---|---|
| Indicator | indicator() |
Plots visuals & alerts | No Strategy Tester report |
| Strategy | strategy() |
Simulates orders & costs | Chart-bar fills by default |
| Library | library() |
Exports reusable functions | No alerts on its own |
Separating indicators from strategies early keeps scripts clean: use indicator() for visual filters, chart tables, and webhook alerts (automated web messages sent to an external app when an alert triggers, per TradingView’s webhooks guide), and reserve strategy() for backtesting (testing trading rules on past charts; walk through full commission settings in the Pine Script strategy handbook).

Example of what an indicator script can draw on a chart: two moving average lines (blue and red) and green and red signal markers where the two lines cross.
How Pine Script runs your code one price bar at a time
Traders coming from Python or JavaScript often expect to write manual loops across arrays of prices. Per TradingView’s execution-model documentation, Pine Script works differently: its runtime executes your entire script sequentially from left to right once on every historical bar:
- Price Series & Past-Bar Lookups: Built-in series (lists of values stored bar by bar across the chart) such as
close,high,low, andvolumetrack each candle automatically. Writingclose[n](wheren = 1reads the previous finished bar’s close) and built-inta.*indicator functions such asta.ema(close, 50)andta.rsi(close, 14)compute an indicator across every bar in one line. - Keeping Values Across Bars With
var: Per TradingView’s variable-declarations guide, ordinary variables reset on every bar unless declared withvar—useful when tracking a session high or an active stop-loss across consecutive candles. - Finished Bars vs Live Ticks: On historical candles, an indicator runs once per bar; on the live rightmost candle, it updates on every incoming price tick. Without checking
barstate.isconfirmed, a crossing signal can flash mid-candle and disappear before the bar closes. - What is different in Pine Script version 6: Per TradingView’s Pine v6 migration guide, version 6 allows pulling data from other symbols or timeframes dynamically with
request.*()calls, stops automatically converting numbers into true/false values, forbids emptynabooleans (booleans are alwaystrueorfalse), sets default strategy long and short margin to 100% (unleveraged by default), and evaluatesand/orconditions lazily (skipping the second check when the first already decides the result)—so history-dependent calls such asta.rsi()must run outside conditional branches at the top level of the script (global scope).
The biggest Pine Script trap: charts that change past signals
Repainting happens when a script changes, moves, or erases past signals after new price bars arrive. Per TradingView’s official repainting documentation, scripts that leak future information into past bars (a look-ahead leak), strategies run on non-standard chart types, and scripts using live intrabar ticks (price updates arriving before a candle closes) to fire alerts or orders can show historical signals that vanish in live markets. Three recurring mistakes account for common repainting problems:
- Unsafe Multi-Timeframe
request.security()Calls: Pulling an unshifted Daily close onto a 1-hour chart withlookahead = barmerge.lookahead_onleaks the Daily candle’s future closing price onto earlier hourly bars of that day, creating unrealistic backtest accuracy. Per TradingView’s repainting guide, read confirmed higher-timeframe data cleanly by shifting the source back one closed bar with[]alongsidebarmerge.lookahead_on. - Testing Strategies on Non-Standard Charts (Heikin Ashi / Renko): Heikin Ashi and Renko are non-standard chart types that plot averaged or smoothed synthetic bars instead of real market quotes. Per TradingView’s strategy documentation, running a Pine strategy directly on those charts simulates trades at synthetic prices rather than real market prices, distorting test results.
- Mid-Bar Real-Time Alerts Without
barstate.isconfirmed: Firing webhook alerts on live mid-bar crosses can trigger repeated false messages during choppy candles that close back below the trigger level.
Pine Script vs MetaTrader MQL5 and Python: choosing the right tool
You can open the Pine Editor on TradingView’s Supercharts to start writing, and most of TradingView’s built-in scripts are written in Pine Script and available for free (per TradingView’s documentation), while feature limits vary by plan, and paid tiers expand active alert limits. However, TradingView’s Strategy FAQs state explicitly that Pine Script strategies and indicators cannot directly place orders on exchanges, unlike MetaTrader Expert Advisors (automated trading programs in MetaTrader) or Python scripts connected through broker APIs (application programming interfaces — direct software links to a broker). The table below compares Pine Script v6 with MetaTrader MQL5 and Python.
| Area | Pine Script v6 | MT5 (MQL5) | Python (Broker APIs) |
|---|---|---|---|
| Code Style | Built-in ta.* |
C++-like code | General coding |
| Live Automation | Alert webhooks | Expert Advisors | Direct broker API |
| Past-Data Tests | Chart bars / Deep* | Real-tick tester | Custom tick code |
| Best Fit | Research & alerts | Expert Advisors | Multi-broker code |
*TradingView’s pricing page lists Deep backtesting and detailed historical bars.
Because Pine Script cannot send orders directly to exchanges, traders needing automated execution often route TradingView webhook alerts to an external app or move tested rules into MetaTrader Expert Advisors (MetaTrader 5 also provides a real-tick Strategy Tester per MetaQuotes) or Python algorithmic scripts (MetaQuotes also offers Python integration for MetaTrader 5; compare full platforms in the TradingView alternatives guide and best TradingView brokers overview).
Five practical habits for writing clean, reliable Pine Script v6 code
Following five simple coding habits from your first Pine Editor script helps avoid repainting errors, zero-cost strategy reports, and noisy webhook alerts:
- Start With
//@version=6on Line 1: Avoid copying old v2–v4 snippets from forums; Pine v6 enforces stricter booleans and supports dynamic data requests. - Wait for Bar Confirmation on Signals and Alerts: Require finished bar closes (
barstate.isconfirmed) so historical chart markers line up more closely with live alerts. - Add Commissions and Slippage to Strategies: Per TradingView’s strategy documentation, strategies apply zero commission unless configured; add realistic broker fees and slippage (an order filling at a different, usually worse, price than the one you set; follow full testing steps in the strategy backtesting guide).
- Keep Indicators Simple and Non-Overlapping: Combine a small set of distinct signals—such as trend slope, momentum pullbacks (short moves against the main trend), and Average True Range (ATR, a measure of average price movement per bar) volatility sizing—rather than building 15-condition curve-fitted (over-tuned to past noise) scripts (see clean setups in the trading indicators guide).
- Check Live Sizing and Hard Broker Stops Separately: Use TradingView scripts for research and alerts while checking lot size (a standard unit of trade size) and verifying hard stop-loss orders directly in your regulated broker platform with the position size calculator.
Start by editing one open-source TradingView indicator, for example by adding a band based on ATR or an alert to a 50-period exponential moving average. Check whether signals change between the open and close of a bar before building strategies with more conditions. Before using community code with real money, check it line by line for barmerge.lookahead_on, alerts that fire before a bar closes, or calculated Heikin Ashi prices. Keep a dated log of live setting changes so you can reproduce your alerts.
Sources: TradingView (Pine Script documentation: Welcome, Script Structure, First Steps, Execution Model, Variable Declarations, Strategies, Libraries, Repainting, Migration to Pine v6, and Strategy FAQs; Support articles on What is Pine Script, Webhooks, and Active Alerts; Pricing) and MetaQuotes (MQL5 Documentation, MetaTrader 5 Strategy Tester, and Python Integration).
Frequently asked questions about Pine Script
Is TradingView Pine Script free to learn and use?
Yes—you can open the Pine Editor on TradingView’s Supercharts to start writing, and most of TradingView’s built-in scripts are written in Pine Script and available for free. Feature limits differ by plan, and paid TradingView tiers expand active alert limits.
Can Pine Script execute live trades automatically on my broker account?
No—TradingView states that Pine Script strategies and indicators cannot directly place orders on exchanges. Common approaches include sending alert webhooks to an external app or implementing your rules in a MetaTrader 5 Expert Advisor or a Python script connected to a broker.
How hard is Pine Script to learn for beginners with zero coding background?
Many beginners find Pine Script approachable because common chart formulas take a single line—such as ta.ema(close, 50) or ta.atr(14)—and scripts run on TradingView’s servers, so there is no local compiler or software environment to set up.
What changed in Pine Script version 6 compared with version 5?
Per TradingView’s official v6 migration guide, Pine Script v6 lets request.*() functions run dynamically, stops implicit number-to-boolean conversion while disallowing na booleans (keeping them true or false), evaluates and/or conditions lazily, and sets default strategy long and short margin to 100%.
Why do some free community Pine Script indicators look profitable historically yet lose live?
Many overly smooth community scripts either repaint—for instance, by pulling unclosed higher-timeframe closes with lookahead_on or simulating trades on synthetic Heikin Ashi candles—or leave brokerage commissions and slippage at zero in Strategy Tester. Inspect open-source code line by line and test on standard candlesticks with realistic costs.




