Basic Syntax 📝
Script Structure
Every Pine Script follows a basic structure:
- Version declaration
- Script type declaration
- Inputs (optional)
- Calculations
- Plot statements
Version Declaration
//@version=5 // Always start with this
Script Types
// Indicator
indicator("My Indicator", overlay=true)
// Strategy
strategy("My Strategy", overlay=true)
// Library
library("My Library", overlay=true)
Comments
// Single line comment
/* Multi-line
comment
block */
Basic Script Examples
Simple Moving Average
//@version=5
indicator("Simple MA", overlay=true)
// Calculate 20-period SMA
sma = ta.sma(close, 20)
// Plot the SMA
plot(sma, color=color.blue)
Price Close vs Open
//@version=5
indicator("Close vs Open")
// Calculate if close is higher than open
isUp = close > open
// Plot different colors based on condition
plot(close, color = isUp ? color.green : color.red)
Naming Conventions
Variables
- Use camelCase
- Be descriptive
- Avoid reserved words
// Good
fastLength = 10
slowMovingAverage = ta.sma(close, 20)
// Bad
x = 10
sma = ta.sma(close, 20)
Common Mistakes
Avoid These
❌ Forgetting version declaration ❌ Using wrong script type ❌ Inconsistent naming ❌ Missing required parameters
Best Practices
✅ Always declare version ✅ Use meaningful variable names ✅ Comment your code ✅ Test on different timeframes
Practice Exercise
Create a script that:
- Shows a 20-period SMA
- Colors it based on slope
- Adds a label when trend changes
//@version=5
indicator("Practice Exercise", overlay=true)
// Calculate SMA
length = 20
sma = ta.sma(close, length)
// Calculate slope
slope = sma - sma[1]
// Plot with color based on slope
plot(sma, color = slope > 0 ? color.green : color.red)
// Add label on trend change
if (slope[1] <= 0 and slope > 0)
label.new(bar_index, sma, "⬆", color=color.green)
if (slope[1] >= 0 and slope < 0)
label.new(bar_index, sma, "⬇", color=color.red)
Pro Tip
Always start with a simple version of your script and add complexity gradually! 🎯
Next Steps
In the next chapter, we'll dive into variables and data types in Pine Script!