Introduction to Pine Script
The basics of TradingView's proprietary programming language for building custom indicators.
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
Open a clean chart and locate the exact TradingView area covered in "Introduction to Pine Script".
Apply it on one liquid NSE stock, one index, and one weekly timeframe so the concept is not learned in isolation.
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.
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.

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
Official Resources
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.
| Features | TradingView | Traditional Brokers |
|---|---|---|
| Declaration | indicator("Name", overlay=true) | strategy("Name", overlay=true) |
| Purpose | Visualize data on the chart | Simulate 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? | No | Yes — full Strategy Tester report (P&L, Drawdown, Equity Curve) |
| Use Case | Custom indicators, visual tools, alert systems | Automated strategy backtesting and optimization |
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).
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.
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.
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.
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:
1//"text-[#">2962ff] font-bold">@version="text-[#089981]">62indicator("My First Indicator", overlay=true)34// Input: Let user choose MA length5length = input.int("text-[#089981]">20, "MA Length", minval="text-[#089981]">1, maxval="text-[#089981]">500)67// Calculate Simple Moving Average8sma_value = ta.sma(close, length)910// Plot the MA on the chart11"text-[#">2962ff] font-bold">plot(sma_value, "SMA", color=color.blue, linewidth="text-[#089981]">2)1213// 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
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.
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.
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.
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.
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.
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.
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.
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.
1//"text-[#">2962ff] font-bold">@version="text-[#089981]">62indicator("RSI Alert System", overlay=false)34// Inputs5rsi_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")89// Calculate RSI10rsi_value = ta.rsi(close, rsi_length)1112// Plot RSI line13"text-[#">2962ff] font-bold">plot(rsi_value, "RSI", color=color.purple, linewidth="text-[#089981]">2)1415// Plot reference levels16hline(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)1920// Color the RSI zones21bgcolor(rsi_value >= overbought ? color.new(color.red, "text-[#089981]">85) : 22 rsi_value <= oversold ? color.new(color.green, "text-[#089981]">85) : na)2324// Alert conditions25alertcondition(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.
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.
1//"text-[#">2962ff] font-bold">@version="text-[#089981]">62"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)34// Inputs5fast_len = input.int("text-[#089981]">9, "Fast EMA Length")6slow_len = input.int("text-[#089981]">21, "Slow EMA Length")78// Calculate EMAs9fast_ema = ta.ema(close, fast_len)10slow_ema = ta.ema(close, slow_len)1112// Plot EMAs13"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)1516// Entry conditions17long_condition = ta.crossover(fast_ema, slow_ema)18short_condition = ta.crossunder(fast_ema, slow_ema)1920// Execute trades21"text-[#">2962ff] font-bold">if long_condition22 "text-[#">2962ff] font-bold">strategy.entry("Long", "text-[#">2962ff] font-bold">strategy.long)2324"text-[#">2962ff] font-bold">if short_condition25 "text-[#">2962ff] font-bold">strategy.close("Long")EMA Crossover Strategy with automatic backtesting
Snapshot & Takeaways
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.
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.
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.
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.
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.
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 "The script executes too many unique `request.*()` function calls" 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've successfully added a strategy to my chart, but it doesn't generate orders
If the "List of Trades" and "Overview" tabs of the Strategy Report display "No data" after you've added a strategy to the chart, it'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.
Related Articles
Continue your learning journey
Stock Screener & Pine Script Editor
Filtering thousands of stocks and building custom indicators with Pine Script.
ModuleStrategy Tester & Replay Trading
Backtesting strategies, paper trading, and connecting to live brokers.
ModuleThe TradingView Community
Leveraging the social trading network to accelerate your learning and refine strategies.
ModuleConnecting Indian Brokers
A step-by-step guide to connecting Dhan, Fyers, and others directly to the Trading Panel.
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.
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
