Skip to content

PineScript Basic Syntax

Understanding PineScript’s syntax is the foundation for writing effective trading indicators and strategies. This guide covers the essential syntax rules you need to know.

Every PineScript follows a basic structure:

//@version=6
indicator("Script Title", overlay=true)
// 1. Variable declarations
myVariable = close
// 2. Calculations
result = myVariable * 2
// 3. Plotting or strategy logic
plot(result)

Always start with the version declaration:

//@version=6

This tells TradingView which version of PineScript you’re using. Version 5 is the latest and recommended version.

Declare whether your script is an indicator or strategy:

// For indicators
indicator("My Indicator", overlay=true)
// For strategies
strategy("My Strategy", overlay=true, initial_capital=10000)

Key Parameters:

  • overlay=true: Displays on the price chart
  • overlay=false: Displays in a separate pane
  • initial_capital: Starting capital for backtesting (strategies only)

Comments help document your code and are ignored during execution.

// This is a single-line comment
sma20 = ta.sma(close, 20) // Calculate 20-period SMA
// This is a longer explanation
// that spans multiple lines
// to describe complex logic

PineScript uses indentation to define code blocks (similar to Python).

if close > open
// This code runs when condition is true
bullish = true
plot(close, color=color.green)
else
// This code runs when condition is false
bullish = false
plot(close, color=color.red)

For long lines, break them logically:

// Break at natural points
longCondition = ta.crossover(fastMA, slowMA) and
rsi < 70 and
volume > ta.sma(volume, 20)
// Use parentheses for expressions
result = (close * 0.5) +
(open * 0.3) +
(high * 0.2)

PineScript uses = for variable assignment:

// Simple assignment
price = close
length = 14
// Assignment with calculation
average = (high + low) / 2
rsiValue = ta.rsi(close, length)

Valid Names:

myVariable
my_variable
myVariable2
_privateVar

Invalid Names:

2myVariable // Can't start with number
my-variable // No hyphens
my variable // No spaces

PineScript provides many built-in variables:

close // Current close price
open // Current open price
high // Current high price
low // Current low price
volume // Current volume
time // Current bar timestamp
bar_index // Current bar number
sum = 10 + 5 // Addition (15)
diff = 10 - 5 // Subtraction (5)
product = 10 * 5 // Multiplication (50)
quotient = 10 / 5 // Division (2)
remainder = 10 % 3 // Modulo (1)
equal = close == open // Equal to
notEqual = close != open // Not equal to
greater = close > open // Greater than
greaterOrEqual = close >= open // Greater than or equal
less = close < open // Less than
lessOrEqual = close <= open // Less than or equal
// AND: Both conditions must be true
longCondition = close > open and volume > 1000000
// OR: At least one condition must be true
exitCondition = close < lowThreshold or rsi > 70
// NOT: Inverts the condition
notBullish = not (close > open)
if close > open
barColor = color.green
else if close < open
barColor = color.red
else
barColor = color.gray
barcolor(barColor)

A shorthand for simple if-else statements:

// Syntax: condition ? valueIfTrue : valueIfFalse
barColor = close > open ? color.green : color.red
// Another example
trendDirection = close > ta.sma(close, 50) ? "Bullish" : "Bearish"

PineScript includes many built-in functions:

// Technical indicators
smaValue = ta.sma(close, 20)
rsiValue = ta.rsi(close, 14)
bbUpper = ta.bb(close, 20, 2)
// Math functions
absValue = math.abs(-10) // 10
maxValue = math.max(10, 20) // 20
sqrtValue = math.sqrt(16) // 4
// Utility functions
crossUp = ta.crossover(fastMA, slowMA)
highest = ta.highest(high, 20)

Define your own reusable functions:

// Simple function
getRangePercent() =>
(high - low) / low * 100
// Function with parameters
getEMA(source, length) =>
ta.ema(source, length)
// Using the functions
rangePercent = getRangePercent()
ema20 = getEMA(close, 20)
plot(close, color=color.blue, linewidth=2, title="Close Price")
// Only plot when condition is true
plotchar = close > open ? close : na
plot(plotchar, color=color.green, title="Bullish Bars Only")
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 20)
plot(fastMA, color=color.blue, title="Fast MA")
plot(slowMA, color=color.red, title="Slow MA")
// Wrong: Declaring variable type
float myVariable = 10 // Don't specify type unless using var
// Correct: Simple assignment
myVariable = 10
// Correct: Using var for persistent variables
var cumulativeVolume = 0.0
cumulativeVolume := cumulativeVolume + volume
// Wrong: No indentation
if close > open
plot(close, color=color.green) // Error!
// Correct: Proper indentation
if close > open
plot(close, color=color.green)

❌ Mistake #3: Using assignment in conditions

Section titled “❌ Mistake #3: Using assignment in conditions”
// Wrong: Using = instead of ==
if close = open // Error!
// Correct: Use == for comparison
if close == open
  1. Use Descriptive Names: movingAverage20 is better than ma or x
  2. Add Comments: Explain why you’re doing something, not what
  3. Keep It Simple: Break complex logic into smaller functions
  4. Test Incrementally: Add features one at a time and test
  5. Use Built-in Functions: Don’t reinvent the wheel

Copy this template to start coding:

//@version=5
indicator("My First Script", overlay=true)
// Your variables here
length = input.int(20, "MA Length")
// Your calculations here
ma = ta.sma(close, length)
// Your plotting here
plot(ma, color=color.blue, linewidth=2)
// Your alerts or strategy logic here
bullishCross = ta.crossover(close, ma)
alertcondition(bullishCross, title="Bullish Cross", message="Price crossed above MA!")

Now that you understand the basic syntax, learn about:


Need help with PineScript syntax? Try our AI-powered PineScript Editor for real-time syntax checking and intelligent suggestions.