PineScript Basic Syntax
PineScript Basic Syntax
Section titled “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.
Script Structure
Section titled “Script Structure”Every PineScript follows a basic structure:
//@version=6indicator("Script Title", overlay=true)
// 1. Variable declarationsmyVariable = close
// 2. Calculationsresult = myVariable * 2
// 3. Plotting or strategy logicplot(result)Version Declaration
Section titled “Version Declaration”Always start with the version declaration:
//@version=6This tells TradingView which version of PineScript you’re using. Version 5 is the latest and recommended version.
Script Type Declaration
Section titled “Script Type Declaration”Declare whether your script is an indicator or strategy:
// For indicatorsindicator("My Indicator", overlay=true)
// For strategiesstrategy("My Strategy", overlay=true, initial_capital=10000)Key Parameters:
overlay=true: Displays on the price chartoverlay=false: Displays in a separate paneinitial_capital: Starting capital for backtesting (strategies only)
Comments
Section titled “Comments”Comments help document your code and are ignored during execution.
Single-Line Comments
Section titled “Single-Line Comments”// This is a single-line commentsma20 = ta.sma(close, 20) // Calculate 20-period SMAMulti-Line Comments
Section titled “Multi-Line Comments”// This is a longer explanation// that spans multiple lines// to describe complex logicIndentation and Line Breaks
Section titled “Indentation and Line Breaks”PineScript uses indentation to define code blocks (similar to Python).
Correct Indentation
Section titled “Correct Indentation”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)Line Continuation
Section titled “Line Continuation”For long lines, break them logically:
// Break at natural pointslongCondition = ta.crossover(fastMA, slowMA) and rsi < 70 and volume > ta.sma(volume, 20)
// Use parentheses for expressionsresult = (close * 0.5) + (open * 0.3) + (high * 0.2)Variables
Section titled “Variables”Variable Assignment
Section titled “Variable Assignment”PineScript uses = for variable assignment:
// Simple assignmentprice = closelength = 14
// Assignment with calculationaverage = (high + low) / 2rsiValue = ta.rsi(close, length)Variable Naming Rules
Section titled “Variable Naming Rules”✅ Valid Names:
myVariablemy_variablemyVariable2_privateVar❌ Invalid Names:
2myVariable // Can't start with numbermy-variable // No hyphensmy variable // No spacesBuilt-in Variables
Section titled “Built-in Variables”PineScript provides many built-in variables:
close // Current close priceopen // Current open pricehigh // Current high pricelow // Current low pricevolume // Current volumetime // Current bar timestampbar_index // Current bar numberOperators
Section titled “Operators”Arithmetic Operators
Section titled “Arithmetic Operators”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)Comparison Operators
Section titled “Comparison Operators”equal = close == open // Equal tonotEqual = close != open // Not equal togreater = close > open // Greater thangreaterOrEqual = close >= open // Greater than or equalless = close < open // Less thanlessOrEqual = close <= open // Less than or equalLogical Operators
Section titled “Logical Operators”// AND: Both conditions must be truelongCondition = close > open and volume > 1000000
// OR: At least one condition must be trueexitCondition = close < lowThreshold or rsi > 70
// NOT: Inverts the conditionnotBullish = not (close > open)Conditional Statements
Section titled “Conditional Statements”If Statement
Section titled “If Statement”if close > open barColor = color.greenelse if close < open barColor = color.redelse barColor = color.gray
barcolor(barColor)Ternary Operator
Section titled “Ternary Operator”A shorthand for simple if-else statements:
// Syntax: condition ? valueIfTrue : valueIfFalsebarColor = close > open ? color.green : color.red
// Another exampletrendDirection = close > ta.sma(close, 50) ? "Bullish" : "Bearish"Functions
Section titled “Functions”Built-in Functions
Section titled “Built-in Functions”PineScript includes many built-in functions:
// Technical indicatorssmaValue = ta.sma(close, 20)rsiValue = ta.rsi(close, 14)bbUpper = ta.bb(close, 20, 2)
// Math functionsabsValue = math.abs(-10) // 10maxValue = math.max(10, 20) // 20sqrtValue = math.sqrt(16) // 4
// Utility functionscrossUp = ta.crossover(fastMA, slowMA)highest = ta.highest(high, 20)Custom Functions
Section titled “Custom Functions”Define your own reusable functions:
// Simple functiongetRangePercent() => (high - low) / low * 100
// Function with parametersgetEMA(source, length) => ta.ema(source, length)
// Using the functionsrangePercent = getRangePercent()ema20 = getEMA(close, 20)Plotting
Section titled “Plotting”Basic Plot
Section titled “Basic Plot”plot(close, color=color.blue, linewidth=2, title="Close Price")Conditional Plotting
Section titled “Conditional Plotting”// Only plot when condition is trueplotchar = close > open ? close : naplot(plotchar, color=color.green, title="Bullish Bars Only")Multiple Plots
Section titled “Multiple Plots”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")Common Syntax Mistakes
Section titled “Common Syntax Mistakes”❌ Mistake #1: Using var incorrectly
Section titled “❌ Mistake #1: Using var incorrectly”// Wrong: Declaring variable typefloat myVariable = 10 // Don't specify type unless using var
// Correct: Simple assignmentmyVariable = 10
// Correct: Using var for persistent variablesvar cumulativeVolume = 0.0cumulativeVolume := cumulativeVolume + volume❌ Mistake #2: Forgetting indentation
Section titled “❌ Mistake #2: Forgetting indentation”// Wrong: No indentationif close > openplot(close, color=color.green) // Error!
// Correct: Proper indentationif 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 comparisonif close == openBest Practices
Section titled “Best Practices”- Use Descriptive Names:
movingAverage20is better thanmaorx - Add Comments: Explain why you’re doing something, not what
- Keep It Simple: Break complex logic into smaller functions
- Test Incrementally: Add features one at a time and test
- Use Built-in Functions: Don’t reinvent the wheel
Try It Now
Section titled “Try It Now”Copy this template to start coding:
//@version=5indicator("My First Script", overlay=true)
// Your variables herelength = input.int(20, "MA Length")
// Your calculations herema = ta.sma(close, length)
// Your plotting hereplot(ma, color=color.blue, linewidth=2)
// Your alerts or strategy logic herebullishCross = ta.crossover(close, ma)alertcondition(bullishCross, title="Bullish Cross", message="Price crossed above MA!")Next Steps
Section titled “Next Steps”Now that you understand the basic syntax, learn about:
- Data Types & Variables - Deep dive into PineScript’s type system
- Operators - Master all operators and their precedence
- Your First Strategy - Build a complete trading strategy
Need help with PineScript syntax? Try our AI-powered PineScript Editor for real-time syntax checking and intelligent suggestions.