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.
The global trading community connected through platforms like TradingView
Why Use Pine Script?
Pine Script offers several advantages for traders and analysts:
- Simplicity: Designed to be accessible to non-programmers
- Integration: Seamlessly works within the TradingView platform
- Performance: Optimized for financial calculations and charting
- Community: Access to a vast library of shared scripts and indicators
- 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:
//@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:
- Version Declaration:
//@version=5specifies which version of Pine Script to use - Script Type Declaration:
indicator()orstrategy()defines the type of script - Input Parameters: Variables that can be adjusted by users
- Calculations: The logic and computations of your script
- 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.
//@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.
//@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 (
trueorfalse) - 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 (=):
// 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:
// 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
// If-else statement
if (close > open)
result = "Bullish"
else if (close < open)
result = "Bearish"
else
result = "Neutral"
Loops
// 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
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
rsi_value = ta.rsi(close, 14) // Relative Strength Index
macd_line, signal, hist = ta.macd(close, 12, 26, 9) // MACD
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
plot(sma_value, title="SMA", color=color.blue)
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
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:
- Use comments to explain your code
- Choose meaningful variable names
- Organize your code into logical sections
- Test thoroughly with different symbols and timeframes
- Optimize for performance by avoiding unnecessary calculations
- Use input parameters to make your script flexible
Getting Started with Pine Script
To start coding in Pine Script:
- Open TradingView and select a chart
- Click on "Pine Editor" at the bottom of the screen
- Choose a template or start with a blank script
- Write your code
- Click "Add to Chart" to see your indicator or strategy in action
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.