< All Topics

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

  1. Click on “Pine Editor” at the bottom of your chart
  2. A code editing panel will open at the bottom of the screen
  3. 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 version
  • indicator(): 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 bar
  • volume: Trading volume
  • time: Bar timestamp
  • bar_index: Sequential bar number
  • hl2: (high + low) / 2
  • hlc3: (high + low + close) / 3
  • ohlc4: (open + high + low + close) / 4
Time Functions:
  • timeframe.period: Current chart timeframe
  • timeframe.multiplier: Current chart timeframe multiplier
  • timenow: Current time in Unix format
Mathematical Functions:
  • ta.sma(source, length): Simple Moving Average
  • ta.ema(source, length): Exponential Moving Average
  • ta.rsi(source, length): Relative Strength Index
  • ta.macd(source, fastlen, slowlen, siglen): MACD
Visualization Functions:
  • plot(): Draw a line
  • plotshape(): Draw symbols (arrows, triangles, etc.)
  • plotcandle(): Custom candlesticks
  • bgcolor(): Change background color
  • fill(): Fill area between two plots

Creating a Simple Indicator

Let’s walk through creating a basic 2-line moving average crossover indicator:

  1. Open Pine Editor
  2. Create a new script
  3. 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")
  1. Click “Save” and name your script
  2. Click “Add to Chart” to apply the indicator

Creating a Trading Strategy

Pine Script also allows you to create and backtest trading strategies:

  1. Instead of indicator(), use strategy() 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")
  1. Click “Add to Chart” to apply and backtest your strategy
  2. 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)
Table of Contents