How Can We Help?
Pine Script: Creating Custom Indicators and Strategies
Pine Script is TradingView’s proprietary programming language that allows users to create custom indicators and trading strategies. This powerful feature sets TradingView apart from many other platforms.
Getting Started with Pine Script
Accessing the Pine Editor
- Click on “Pine Editor” at the bottom of your chart
- A code editing panel will open at the bottom of the screen
- You’ll see options for:
- Creating a new script
- Opening existing scripts
- Accessing Pine Script documentation
- Saving your work
Pine Script Basics
Script Structure
Every Pine Script has a specific structure:
//@version=5
indicator("My Custom Indicator", overlay=true)
// Calculate your values here
myValue = close
// Plot the result
plot(myValue, color=color.blue, linewidth=2, title="My Line")
The key components:
//@version=5
: Specifies the Pine Script versionindicator()
: Declares an indicator with a name and properties- Calculation logic: Where you process data and create values
- Visualization: How your calculations appear on the chart
Common Functions and Variables
Built-in Variables:
open
,high
,low
,close
: Price data for each barvolume
: Trading volumetime
: Bar timestampbar_index
: Sequential bar numberhl2
: (high + low) / 2hlc3
: (high + low + close) / 3ohlc4
: (open + high + low + close) / 4
Time Functions:
timeframe.period
: Current chart timeframetimeframe.multiplier
: Current chart timeframe multipliertimenow
: Current time in Unix format
Mathematical Functions:
ta.sma(source, length)
: Simple Moving Averageta.ema(source, length)
: Exponential Moving Averageta.rsi(source, length)
: Relative Strength Indexta.macd(source, fastlen, slowlen, siglen)
: MACD
Visualization Functions:
plot()
: Draw a lineplotshape()
: Draw symbols (arrows, triangles, etc.)plotcandle()
: Custom candlesticksbgcolor()
: Change background colorfill()
: Fill area between two plots
Creating a Simple Indicator
Let’s walk through creating a basic 2-line moving average crossover indicator:
- Open Pine Editor
- Create a new script
- Enter this code:
//@version=5
indicator("MA Crossover", overlay=true)
// Input parameters
fastLength = input.int(9, title="Fast MA Length", minval=1)
slowLength = input.int(21, title="Slow MA Length", minval=1)
// Calculate moving averages
fastMA = ta.sma(close, fastLength)
slowMA = ta.sma(close, slowLength)
// Detect crossover
crossover = ta.crossover(fastMA, slowMA)
crossunder = ta.crossunder(fastMA, slowMA)
// Plot moving averages
plot(fastMA, color=color.blue, linewidth=2, title="Fast MA")
plot(slowMA, color=color.red, linewidth=2, title="Slow MA")
// Plot crossover signals
plotshape(crossover, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Buy Signal")
plotshape(crossunder, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="Sell Signal")
// Add alert conditions
alertcondition(crossover, title="MA Crossover Buy", message="Fast MA crossed above Slow MA")
alertcondition(crossunder, title="MA Crossover Sell", message="Fast MA crossed below Slow MA")
- Click “Save” and name your script
- Click “Add to Chart” to apply the indicator
Creating a Trading Strategy
Pine Script also allows you to create and backtest trading strategies:
- Instead of
indicator()
, usestrategy()
in your code:
//@version=5
strategy("My MA Strategy", overlay=true)
// Input parameters
fastLength = input.int(9, title="Fast MA Length", minval=1)
slowLength = input.int(21, title="Slow MA Length", minval=1)
// Calculate moving averages
fastMA = ta.sma(close, fastLength)
slowMA = ta.sma(close, slowLength)
// Detect crossover
crossover = ta.crossover(fastMA, slowMA)
crossunder = ta.crossunder(fastMA, slowMA)
// Plot moving averages
plot(fastMA, color=color.blue, linewidth=2, title="Fast MA")
plot(slowMA, color=color.red, linewidth=2, title="Slow MA")
// Execute trades
if (crossover)
strategy.entry("Buy", strategy.long)
if (crossunder)
strategy.close("Buy")
- Click “Add to Chart” to apply and backtest your strategy
- View performance in the “Strategy Tester” panel at the bottom
Advanced Pine Script Features
User Inputs
Create customizable scripts with input parameters:
len = input.int(14, title="Length", minval=1)
src = input.source(close, title="Source")
Conditional Logic
if condition
// Do something
else if another_condition
// Do something else
else
// Default action
Functions
Create reusable code blocks:
myFunc(param1, param2) =>
result = param1 + param2
result // Return value
Labels and Tables
Add dynamic text and data to your charts:
// Create a label
lbl = label.new(bar_index, high, text="Peak", color=color.red, style=label.style_label_down)
// Create a table
myTable = table.new(position.top_right, columns=2, rows=3, bgcolor=color.black, border_width=1)
table.cell(myTable, 0, 0, text="RSI", bgcolor=color.gray)