LearnTradingView & ChartingIntroduction to Pine Script
    Article 28 of 34

    Introduction to Pine Script

    The basics of TradingView's proprietary programming language for building custom indicators.

    Rohit Singh
    Rohit SinghMr. Chartist
    April 1, 2026
    19 min read

    Mr. Chartist Workflow

    Read with a trading desk mindset.

    Every TradingView article now follows a practical pattern: understand the tool, map it to a charting workflow, apply it on Indian market instruments, and turn it into a repeatable workspace habit.

    9

    Sections

    8m

    Read

    bottom

    Level

    01

    Open a clean chart and locate the exact TradingView area covered in "Introduction to Pine Script".

    02

    Apply it on one liquid NSE stock, one index, and one weekly timeframe so the concept is not learned in isolation.

    03

    Save the layout, write one note about what improved your decision-making, and remove anything that adds noise.

    Pine Script is TradingView's proprietary programming language, purpose-built for creating custom indicators, strategies, and alert conditions. Unlike general-purpose languages like Python or JavaScript, Pine Script is designed exclusively for financial markets—making it dramatically simpler to learn while being incredibly powerful for its domain.

    Whether you want to build a custom moving average crossover indicator, create an automated strategy with backtesting, code a complex multi-timeframe scanner, or publish a monetizable indicator in TradingView's marketplace—Pine Script is your gateway. Over 100,000 community scripts have been published, making TradingView home to the world's largest open-source trading code library.

    In this comprehensive tutorial, we will walk you through the entire Pine Script journey: from understanding the language architecture and the Pine Editor workspace, to writing your first indicator, mastering the type system, building practical RSI and MACD indicators with alerts, and charting a clear learning path from beginner to expert.

    01

    1. What is Pine Script?

    Pine Script is a domain-specific language (DSL) created by TradingView for writing custom technical analysis tools. The current version is Pine Script v6, which introduced significant improvements in type safety, error handling, user-defined types, and library support.

    The language runs entirely on TradingView's cloud servers—there is nothing to install, no dependencies to manage, no environment to configure, and no local runtime. You write code in the built-in Pine Editor (bottom panel), click 'Add to Chart', and your indicator renders instantly on the live chart.

    Pine Script is intentionally simpler than Python or JavaScript for trading applications. A simple moving average indicator that would take 50+ lines in Python (importing libraries, fetching data, calculating, plotting) takes just 3-4 lines in Pine Script. This radical simplicity has made it the world's most-used trading scripting language by a significant margin.

    tradingview.com
    1. What is Pine Script?
    v6Current Version
    100K+Community Scripts
    FreeOn All Plans
    CloudZero Setup Required

    Critical Warning

    Common Pine Script mistake: Using request.security() on lower timeframes (e.g., requesting 1-minute data on a 5-minute chart) can produce unpredictable results. Always request equal or higher timeframes.

    Ctrl+Enter

    02

    2. The Two Script Types: indicator() vs strategy()

    Every Pine Script must declare itself as one of two types using a declaration statement. Understanding the difference is essential before writing a single line of code.

    An `indicator()` script calculates and displays visual data on the chart—moving averages, oscillators, background colors, labels, lines, and shapes. It can define alert conditions using `alertcondition()`, but it cannot simulate trades. Indicators are for analysis and visualization.

    A `strategy()` script gains access to the entire `strategy.*` namespace—functions like `strategy.entry()`, `strategy.exit()`, and `strategy.close()` that simulate actual order execution. When you add a strategy to your chart, TradingView automatically runs it against historical data and generates a full backtesting report in the Strategy Tester panel (Net Profit, Profit Factor, Drawdown, Equity Curve).

    The third, less common type is `library()`, which allows you to publish reusable Pine Script functions that other scripts can import. Libraries are for code sharing, not for direct chart visualization.

    FeaturesTradingViewTraditional Brokers
    Declarationindicator("Name", overlay=true)strategy("Name", overlay=true)
    PurposeVisualize data on the chartSimulate trades and generate backtesting reports
    Can Plot?Yes — plot(), label.new(), line.new()Yes — same plotting capabilities
    Can Trade?No — can only define alertcondition()Yes — strategy.entry(), strategy.exit(), strategy.close()
    Generates Backtest?NoYes — full Strategy Tester report (P&L, Drawdown, Equity Curve)
    Use CaseCustom indicators, visual tools, alert systemsAutomated strategy backtesting and optimization
    03

    3. The Pine Editor: Your Cloud IDE

    TradingView's Pine Editor is a full-featured cloud IDE located in the bottom panel of the chart (click the 'Pine Editor' tab). It provides everything you need to write, test, debug, and publish custom scripts.

    The editor features Pine Script v6 syntax highlighting, real-time auto-complete for all built-in functions and variables, inline error checking with descriptive messages, and a hover-to-view documentation system (hover over any function name to see its full signature and description).

    Pine EditorAdd to chart123456789101112//@version=5indicator("RSI Strategy")length = input(14)src = closersiVal = ta.rsi(src, length)plot(rsiVal, "RSI", color.blue)hline(70, "Overbought")hline(30, "Oversold")

    Editor Capabilities

    • Syntax highlighting with v6 language awareness.
    • Auto-complete for built-in functions, variables, and types.
    • Real-time error checking with descriptive messages.
    • Hover any function for inline documentation.
    • Version history — automatically saves code revisions.
    1,5601,5201,4801,4401,4001,3601,430.80RELIANCE, 1D

    Debugging & Profiling

    • plot() and label.new() for visual debugging on the chart.
    • log.info() for text-based console output (v6 feature).
    • Runtime error messages with exact line numbers.
    • Pine Profiler for performance bottleneck identification.
    RELIANCE — Price vs RevenueRevenue (₹ Cr)PriceEPSQ1 24Q2 24Q3 24Q4 24Q1 25Q2 25Q3 251,6001,5001,4001,3001,200

    Publishing & Monetization

    • Open-Source: Publish with full code visible to the community.
    • Protected: Publish with code hidden (obfuscated).
    • Invite-Only: Restrict access to specific users.
    • Paid Spaces: Monetize your indicators via TradingView's marketplace.
    Financials — RELIANCENSE · QuarterlyIncome statementBalance sheetCash flowRatiosQ4 2025Q3 2025Q2 2025Q1 2025Q4 2024Total revenue2,43,8642,35,0932,31,4592,16,2572,32,722Cost of goods sold1,56,2901,51,8421,49,8101,38,4261,50,965Gross profit87,57483,25181,64977,83181,757Operating expenses28,45027,83026,95025,60027,200Operating income59,12455,42154,69952,23154,557Net income21,93019,87818,95117,61219,299EPS — basic32.3729.3427.9726.0028.49EPS — diluted32.3729.3427.9726.0028.49₹ Cr · All values in Crores
    04

    4. Your First Pine Script — Hello World

    Let us write your very first Pine Script indicator—a Simple Moving Average that plots on your chart with dynamic background coloring. Open the Pine Editor (bottom panel → Pine Editor tab) and replace the default code with the following:

    Pine EditorAdd to chart123456789101112//@version=5indicator("RSI Strategy")length = input(14)src = closersiVal = ta.rsi(src, length)plot(rsiVal, "RSI", color.blue)hline(70, "Overbought")hline(30, "Oversold")
    pine
    1//"text-[#">2962ff] font-bold">@version="text-[#089981]">6
    2indicator("My First Indicator", overlay=true)
    3
    4// Input: Let user choose MA length
    5length = input.int("text-[#089981]">20, "MA Length", minval="text-[#089981]">1, maxval="text-[#089981]">500)
    6
    7// Calculate Simple Moving Average
    8sma_value = ta.sma(close, length)
    9
    10// Plot the MA on the chart
    11"text-[#">2962ff] font-bold">plot(sma_value, "SMA", color=color.blue, linewidth="text-[#089981]">2)
    12
    13// Color the background when price is above MA (bullish)
    14bgcolor(close > sma_value ? color.new(color.green, "text-[#089981]">90) : color.new(color.red, "text-[#089981]">90))

    A complete Pine Script v6 indicator: SMA with dynamic background coloring

    Snapshot & Takeaways

    1
    //@version=6 — Declares Pine Script version 6. Always use the latest version for new scripts.
    2
    indicator("Name", overlay=true) — Declares this as an indicator. overlay=true places it on the price chart (overlay=false places it in a separate pane below).
    3
    input.int() — Creates a user-configurable input that appears in the indicator's settings panel. Users can change this without editing code.
    4
    ta.sma(close, length) — Built-in function for Simple Moving Average. 'close' is the data source, 'length' is the period.
    5
    plot() — Renders a line on the chart with customizable color, width, and style.
    6
    bgcolor() — Colors the chart background conditionally using the ternary operator (condition ? true_value : false_value).

    Professional Tip

    After pasting this code, click 'Add to Chart' (or press Ctrl+Enter). You will see a blue SMA line with a green background when price is above the MA and a red background when below. Open the indicator settings (gear icon) to change the MA length without editing code.

    05

    5. Variables, Types & Built-in Data

    Understanding Pine Script's variable system and built-in data access is essential before writing more complex indicators. Pine Script v6 uses a strict type system where every variable has a defined type.

    Built-in Variables (OHLCV)

    • open, high, low, close — Current bar's OHLC values.
    • volume — Current bar's trading volume.
    • time — Current bar's timestamp (Unix epoch milliseconds).
    • bar_index — Sequential bar number (0 = first bar on chart).
    • syminfo.ticker — Current symbol name (e.g., 'RELIANCE').
    • timeframe.period — Current chart timeframe (e.g., '15', 'D', 'W').

    Data Types

    • int — Integer numbers (e.g., 20, 50, 200).
    • float — Decimal numbers (e.g., 3.14, 0.618).
    • bool — true/false values for conditional logic.
    • string — Text values (e.g., 'Bullish', 'Bearish').
    • color — Color values (color.red, #FF0000, color.new()).

    Key Operators

    • = (assignment), := (reassignment of existing variable).
    • +, -, *, / (arithmetic operations).
    • >, <, >=, <=, == (comparison operators).
    • and, or, not (logical operators).
    • ? : (ternary/conditional expression).
    • var — Keyword that makes a variable persist across bars.
    RELIANCE2,950+1.25% TodayStrong Buy

    Professional Tip

    The `var` keyword is critical. Without it, variables are re-initialized on every bar. With `var`, a variable is initialized only once (on the first bar) and retains its value across all subsequent bars. This is essential for counters, accumulators, and state tracking.

    06

    6. The ta.* Namespace: Built-in Technical Functions

    Pine Script provides a comprehensive library of pre-built technical analysis functions under the `ta.*` namespace. These functions are the building blocks of every indicator and strategy.

    Instead of manually coding the RSI formula from scratch (which involves calculating average gains, average losses, relative strength, and then normalizing), you simply call `ta.rsi(close, 14)` and Pine Script handles the entire calculation. This is the power of a domain-specific language.

    Indicators, Metrics & StrategiesSearch…FavoritesBuilt-insCommunityMy scriptsVolumeShows trading volume barsRelative Strength IndexRSI oscillator (14)MACDMoving Avg Convergence DivergenceBollinger BandsVolatility bands (20, 2)Moving AverageSimple Moving AverageEMAExponential Moving AverageStochasticStochastic Oscillator (14,3,3)VWAPVolume Weighted Average PriceType to Search Instantly★ Star = Favorite

    Moving Averages

    • ta.sma(source, length) — Simple Moving Average.
    • ta.ema(source, length) — Exponential Moving Average.
    • ta.wma(source, length) — Weighted Moving Average.
    • ta.vwma(source, length) — Volume-Weighted MA.
    • ta.hma(source, length) — Hull Moving Average.
    1,5601,5201,4801,4401,4001,3601,430.80RELIANCE, 1D

    Oscillators & Momentum

    • ta.rsi(source, length) — Relative Strength Index.
    • ta.macd(src, fast, slow, signal) — MACD (returns tuple).
    • ta.stoch(close, high, low, length) — Stochastic.
    • ta.cci(source, length) — Commodity Channel Index.
    • ta.atr(length) — Average True Range.
    RELIANCE — Price vs RevenueRevenue (₹ Cr)PriceEPSQ1 24Q2 24Q3 24Q4 24Q1 25Q2 25Q3 251,6001,5001,4001,3001,200

    Crossover & Pivot Functions

    • ta.crossover(a, b) — Returns true when 'a' crosses above 'b'.
    • ta.crossunder(a, b) — Returns true when 'a' crosses below 'b'.
    • ta.pivothigh(len, len) — Identifies pivot highs.
    • ta.pivotlow(len, len) — Identifies pivot lows.
    • ta.highest(source, len) — Highest value in N bars.
    Financials — RELIANCENSE · QuarterlyIncome statementBalance sheetCash flowRatiosQ4 2025Q3 2025Q2 2025Q1 2025Q4 2024Total revenue2,43,8642,35,0932,31,4592,16,2572,32,722Cost of goods sold1,56,2901,51,8421,49,8101,38,4261,50,965Gross profit87,57483,25181,64977,83181,757Operating expenses28,45027,83026,95025,60027,200Operating income59,12455,42154,69952,23154,557Net income21,93019,87818,95117,61219,299EPS — basic32.3729.3427.9726.0028.49EPS — diluted32.3729.3427.9726.0028.49₹ Cr · All values in Crores
    07

    7. Building a Real Indicator — RSI with Alerts

    Let us build something practical: a custom RSI indicator that visually highlights overbought/oversold zones and fires TradingView alerts when conditions are met. This is one of the most commonly used setups among Indian F&O traders.

    Indicators, Metrics & StrategiesSearch…FavoritesBuilt-insCommunityMy scriptsVolumeShows trading volume barsRelative Strength IndexRSI oscillator (14)MACDMoving Avg Convergence DivergenceBollinger BandsVolatility bands (20, 2)Moving AverageSimple Moving AverageEMAExponential Moving AverageStochasticStochastic Oscillator (14,3,3)VWAPVolume Weighted Average PriceType to Search Instantly★ Star = Favorite
    pine
    1//"text-[#">2962ff] font-bold">@version="text-[#089981]">6
    2indicator("RSI Alert System", overlay=false)
    3
    4// Inputs
    5rsi_length = input.int("text-[#089981]">14, "RSI Length")
    6overbought = input.float("text-[#089981]">70.0, "Overbought Level")
    7oversold = input.float("text-[#089981]">30.0, "Oversold Level")
    8
    9// Calculate RSI
    10rsi_value = ta.rsi(close, rsi_length)
    11
    12// Plot RSI line
    13"text-[#">2962ff] font-bold">plot(rsi_value, "RSI", color=color.purple, linewidth="text-[#089981]">2)
    14
    15// Plot reference levels
    16hline(overbought, "Overbought", color=color.red, linestyle=hline.style_dashed)
    17hline(oversold, "Oversold", color=color.green, linestyle=hline.style_dashed)
    18hline("text-[#089981]">50, "Midline", color=color.gray, linestyle=hline.style_dotted)
    19
    20// Color the RSI zones
    21bgcolor(rsi_value >= overbought ? color.new(color.red, "text-[#089981]">85) :
    22 rsi_value <= oversold ? color.new(color.green, "text-[#089981]">85) : na)
    23
    24// Alert conditions
    25alertcondition(ta.crossover(rsi_value, oversold), "RSI Oversold Cross", "RSI crossed above oversold level")
    26alertcondition(ta.crossunder(rsi_value, overbought), "RSI Overbought Cross", "RSI crossed below overbought level")

    RSI Alert System with visual zones and configurable alert triggers

    Professional Tip

    After adding this indicator to your chart, right-click the indicator name in the status line → 'Add Alert'. Select one of the two alert conditions you defined (Oversold Cross or Overbought Cross). TradingView will notify you via push notification, email, or webhook whenever the condition triggers—even when your computer is off.

    Professional Tip

    The `alertcondition()` function only defines the condition. You must still create the actual alert via TradingView's alert dialog to activate it.

    08

    8. Your First Strategy — EMA Crossover Backtest

    Now let us build a `strategy()` script that automatically backtests a simple EMA crossover system. When you add this script to a chart, TradingView will simulate every trade on historical data and generate a full performance report.

    Equity CurvePerformanceNet Profit+₹48,250Win Rate64.3%Profit Factor2.14Max Drawdown-12.8%Sharpe Ratio1.87Total Trades142Trade List#SymbolSideEntryExitP&L1RELIANCELong2,8402,950+₹1,1002HDFCBANKShort1,5201,450+₹7003TCSLong3,9003,820-₹800
    pine
    1//"text-[#">2962ff] font-bold">@version="text-[#089981]">6
    2"text-[#">2962ff] font-bold">strategy("EMA Crossover Strategy", overlay=true, default_qty_type="text-[#">2962ff] font-bold">strategy.percent_of_equity, default_qty_value="text-[#089981]">10)
    3
    4// Inputs
    5fast_len = input.int("text-[#089981]">9, "Fast EMA Length")
    6slow_len = input.int("text-[#089981]">21, "Slow EMA Length")
    7
    8// Calculate EMAs
    9fast_ema = ta.ema(close, fast_len)
    10slow_ema = ta.ema(close, slow_len)
    11
    12// Plot EMAs
    13"text-[#">2962ff] font-bold">plot(fast_ema, "Fast EMA", color=color.blue, linewidth="text-[#089981]">2)
    14"text-[#">2962ff] font-bold">plot(slow_ema, "Slow EMA", color=color.orange, linewidth="text-[#089981]">2)
    15
    16// Entry conditions
    17long_condition = ta.crossover(fast_ema, slow_ema)
    18short_condition = ta.crossunder(fast_ema, slow_ema)
    19
    20// Execute trades
    21"text-[#">2962ff] font-bold">if long_condition
    22 "text-[#">2962ff] font-bold">strategy.entry("Long", "text-[#">2962ff] font-bold">strategy.long)
    23
    24"text-[#">2962ff] font-bold">if short_condition
    25 "text-[#">2962ff] font-bold">strategy.close("Long")

    EMA Crossover Strategy with automatic backtesting

    Snapshot & Takeaways

    1
    strategy() replaces indicator() — this enables the Strategy Tester panel.
    2
    default_qty_type=strategy.percent_of_equity — Each trade uses 10% of the simulated account.
    3
    strategy.entry("Long", strategy.long) — Opens a long position with a specific ID.
    4
    strategy.close("Long") — Closes the position identified by 'Long'.
    5
    After adding to chart, open the Strategy Tester tab to see Net Profit, Profit Factor, Max Drawdown, Win Rate, and the Equity Curve.
    09

    9. Pine Script Learning Path: Beginner to Expert

    Here is the recommended progression for mastering Pine Script, from absolute beginner to advanced developer capable of publishing monetizable indicators.

    Pine EditorAdd to chart123456789101112//@version=5indicator("RSI Strategy")length = input(14)src = closersiVal = ta.rsi(src, length)plot(rsiVal, "RSI", color.blue)hline(70, "Overbought")hline(30, "Oversold")

    Week 1-2: Foundations

    • Modify existing community scripts to learn syntax.
    • Master plot(), input(), bgcolor(), and ta.* functions.
    • Build a custom moving average indicator.
    • Read the Pine Script v6 User Manual (built into the editor).

    Week 3-4: Intermediate

    • Build multi-indicator systems (MA + RSI + Volume filter).
    • Learn conditional logic and alertcondition().
    • Create visual elements with label.new() and line.new().
    • Study top-rated community scripts' open-source code.
    RELIANCE2,950+1.25% TodayStrong Buy

    Month 2-3: Advanced

    • Write strategy() scripts for automated backtesting.
    • Build screeners using request.security() for multi-symbol data.
    • Create reusable libraries with the library() declaration.
    • Implement webhook integrations for semi-automated trading.
    1,5601,5201,4801,4401,4001,3601,430.80RELIANCE, 1D

    Month 4+: Expert

    • Build complex algorithms (harmonic pattern detectors, ML classifiers).
    • Publish and monetize via TradingView's Paid Spaces marketplace.
    • Contribute to the Pine Script community library ecosystem.
    • Apply for TradingView's Pine Script Wizard recognition badge.
    RELIANCE — Price vs RevenueRevenue (₹ Cr)PriceEPSQ1 24Q2 24Q3 24Q4 24Q1 25Q2 25Q3 251,6001,5001,4001,3001,200
    "

    Pine Script is the most accessible path from 'trading idea' to 'working indicator'. What takes weeks in Python takes hours in Pine Script.

    Unlock TradingView Pro

    Gain unrestricted access to multiple charts, custom timeframes, and unlimited technical indicators to perfect your edge.

    Claim TradingView Upgrade

    Frequently Asked Questions

    Common questions about this topic

    Pine Script is significantly easier than Python or JavaScript for trading applications. A functional moving average indicator takes 3-4 lines of code. TradingView provides a full cloud IDE with auto-complete, inline documentation, and real-time error highlighting. Most traders with no programming experience can write basic indicators within 1-2 weeks of focused practice.

    Official TradingView Resources

    Curated links from TradingView's Help Center & Blog

    I see the &#34;The script executes too many unique `request.*()` function calls&#34; error

    This error occurs if a Pine script executes too many unique request.*() function calls. Whether a request.*() call is unique depends on its specified ...

    Script or strategy gives different results after refreshing the page (repainting)

    Historical data does not include records of intra-bar movements of price; only open, high, low and close (OHLC). This leads to a script sometimes work...

    I&#39;ve successfully added a strategy to my chart, but it doesn&#39;t generate orders

    If the &#34;List of Trades&#34; and &#34;Overview&#34; tabs of the Strategy Report display &#34;No data&#34; after you&#39;ve added a strategy to the chart, it&#39;s likely that it d...

    I believe that the strategy is giving the wrong results

    Please note that there are many factors that can affect strategy calculation results and even the tiniest of discrepancies may lead to a big differenc...

    Our 2026 Pine Script® Wizards

    Read fresh TradingView updates: Our 2026 Pine Script® Wizards. Discover more in our blog and stay connected with the latest platform news.

    Add tooltips to the inputs of your Pine scripts

    Read fresh TradingView updates: Add tooltips to the inputs of your Pine scripts. Discover more in our blog and stay connected with the latest platform news.

    We’re Adding Built-In Financial Functions and Metrics to Pine

    Read fresh TradingView updates: We’re Adding Built-In Financial Functions and Metrics to Pine. Discover more in our blog and stay connected with the latest platform news.

    Unwrap the Christmas spirit in Pine Script®

    Read fresh TradingView updates: Unwrap the Christmas spirit in Pine Script®. Discover more in our blog and stay connected with the latest platform news.

    Rohit Singh — Mr. Chartist

    Written By

    Rohit Singh

    Mr. Chartist

    With 14+ years of experience in Indian financial markets, Rohit Singh (Mr. Chartist) is a SEBI Registered Research Analyst, Amazon #1 bestselling author, and the founder of Investology — a premium trading ecosystem trusted by a 1.5 Lakh+ strong community across India.

    INH000015297Full Bio

    TradingView is a registered trademark of TradingView, Inc. All screenshots, logos, and platform imagery are the property of TradingView, Inc. and are used here for educational purposes only under fair use. This content is not affiliated with, endorsed, or sponsored by TradingView.

    (c) 2026 TradingView, Inc. All rights reserved. - www.tradingview.com