×

Pine Script Guide

Pine Script Basics

Introduction to Pine Script

Pine Script is TradingView's proprietary programming language designed specifically for creating custom technical indicators and trading strategies. It's built to be accessible to traders without extensive programming experience while still offering powerful capabilities for advanced users.

Note: TradingView is the platform used by over 100 million traders worldwide, while Pine Script is the programming language used within TradingView for developing custom indicators and strategies.
Global Trading Community

The global trading community connected through platforms like TradingView

Why Use Pine Script?

Pine Script offers several advantages for traders and analysts:

  1. Simplicity: Designed to be accessible to non-programmers
  2. Integration: Seamlessly works within the TradingView platform
  3. Performance: Optimized for financial calculations and charting
  4. Community: Access to a vast library of shared scripts and indicators
  5. Backtesting: Built-in capabilities for testing strategies against historical data

Pine Script Versions

Pine Script has evolved through several versions, with each adding new features and capabilities:

  • Pine Script v1: The original version with basic functionality
  • Pine Script v2: Added more functions and improved syntax
  • Pine Script v3: Introduced user-defined functions and more advanced features
  • Pine Script v4: Added type system and improved error handling
  • Pine Script v5: Current version with object-oriented features, improved syntax, and enhanced capabilities

For this guide, we'll focus on Pine Script v5, which is the latest and most powerful version.

Basic Structure of a Pine Script

Every Pine Script has a specific structure that includes:

Pine Script
//@version=5
indicator("My First Indicator", overlay=true)

// Input parameters
length = input(14, "SMA Length")

// Calculations
sma_value = ta.sma(close, length)

// Plotting
plot(sma_value, title="SMA", color=color.blue, linewidth=2)

Let's break down the components:

  1. Version Declaration: //@version=5 specifies which version of Pine Script to use
  2. Script Type Declaration: indicator() or strategy() defines the type of script
  3. Input Parameters: Variables that can be adjusted by users
  4. Calculations: The logic and computations of your script
  5. Visualization: How the results are displayed on the chart

Script Types

Pine Script supports two main types of scripts:

Indicators

Indicators are used to analyze price data and display the results visually on charts. They don't execute trades but provide visual signals.

Pine Script - Indicator Example
//@version=5
indicator("RSI Example", overlay=false)

length = input(14, "RSI Length")
rsi_value = ta.rsi(close, length)

plot(rsi_value, "RSI", color=color.purple)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)

Strategies

Strategies are used to define trading rules and can be backtested against historical data.

Pine Script - Strategy Example
//@version=5
strategy("Simple MA Crossover Strategy", overlay=true)

fast_length = input(9, "Fast MA Length")
slow_length = input(20, "Slow MA Length")

fast_ma = ta.sma(close, fast_length)
slow_ma = ta.sma(close, slow_length)

// Define entry conditions
if (ta.crossover(fast_ma, slow_ma))
    strategy.entry("Buy", strategy.long)

if (ta.crossunder(fast_ma, slow_ma))
    strategy.entry("Sell", strategy.short)

// Plot MAs for visualization
plot(fast_ma, "Fast MA", color=color.blue)
plot(slow_ma, "Slow MA", color=color.red)

Variables and Data Types

Pine Script supports several data types:

  • int: Integer numbers (e.g., 1, 42, -7)
  • float: Floating-point numbers (e.g., 3.14, 0.5)
  • bool: Boolean values (true or false)
  • color: Color values (e.g., color.red, color.rgb(255, 0, 0))
  • string: Text strings (e.g., "Hello")
  • array: Collections of values of the same type
  • matrix: Two-dimensional arrays
  • map: Key-value pairs

Variables are declared using the assignment operator (=):

Pine Script - Variable Declarations
// Variable declarations
my_integer = 42
my_float = 3.14
my_boolean = true
my_color = color.blue
my_string = "TradingView"

Series Types

Pine Script has a special concept called "series" which represents values that change over time (with each bar):

  • price: Price data like open, high, low, close
  • volume: Trading volume
  • time: Bar timestamp
  • calculated values: Results of indicators or other calculations

Series can be accessed using built-in variables:

Pine Script - Series Examples
// Built-in series
current_close = close
current_high = high
current_low = low
current_open = open
current_volume = volume
current_time = time

Control Structures

Pine Script supports several control structures:

Conditional Statements

Pine Script - Conditional Example
// If-else statement
if (close > open)
    result = "Bullish"
else if (close < open)
    result = "Bearish"
else
    result = "Neutral"

Loops

Pine Script - Loop Example
// For loop
sum = 0
for i = 0 to 9
    sum := sum + i

Built-in Functions

Pine Script includes numerous built-in functions for technical analysis:

Moving Averages

Pine Script - Moving Averages
sma_value = ta.sma(close, 20)  // Simple Moving Average
ema_value = ta.ema(close, 20)  // Exponential Moving Average
wma_value = ta.wma(close, 20)  // Weighted Moving Average

Oscillators

Pine Script - Oscillators
rsi_value = ta.rsi(close, 14)  // Relative Strength Index
macd_line, signal, hist = ta.macd(close, 12, 26, 9)  // MACD

Volatility Indicators

Pine Script - Volatility Indicators
atr_value = ta.atr(14)  // Average True Range
bb_upper, bb_middle, bb_lower = ta.bb(close, 20, 2)  // Bollinger Bands

Plotting and Visualization

Pine Script offers various functions for visualizing data:

Basic Plotting

Pine Script - Basic Plotting
plot(sma_value, title="SMA", color=color.blue)

Filled Areas

Pine Script - Filled Areas
upper = ta.sma(close, 20) + ta.stdev(close, 20) * 2
lower = ta.sma(close, 20) - ta.stdev(close, 20) * 2
fill(plot(upper), plot(lower), color=color.new(color.purple, 90))

Shapes and Labels

Pine Script - Shapes and Labels
plotshape(ta.crossover(fast_ma, slow_ma), title="Buy Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)

Best Practices

When writing Pine Script code, follow these best practices:

  1. Use comments to explain your code
  2. Choose meaningful variable names
  3. Organize your code into logical sections
  4. Test thoroughly with different symbols and timeframes
  5. Optimize for performance by avoiding unnecessary calculations
  6. Use input parameters to make your script flexible

Getting Started with Pine Script

To start coding in Pine Script:

  1. Open TradingView and select a chart
  2. Click on "Pine Editor" at the bottom of the screen
  3. Choose a template or start with a blank script
  4. Write your code
  5. Click "Add to Chart" to see your indicator or strategy in action
Trading Community

A global community of traders collaborating and sharing strategies

Next Steps

Now that you understand the basics of Pine Script, you're ready to explore more advanced topics and create your own custom indicators and strategies. In the next sections, we'll dive deeper into specific trading strategies implemented in Pine Script.

Expert Insight: The Predik Scientists Association from Zug, Switzerland actively uses these techniques for market analysis and strategy development. Their expertise has contributed to the examples and best practices shared in this guide.