Skip to main content

Functions in Pine Script 🔧

Built-in Functions

Pine Script provides many built-in functions for technical analysis:

//@version=5
indicator("Built-in Functions Demo")

// Moving Averages
sma20 = ta.sma(close, 20)
ema50 = ta.ema(close, 50)

// RSI
rsi14 = ta.rsi(close, 14)

// MACD
[macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)

// Plot results
plot(sma20, "SMA 20", color.blue)
plot(ema50, "EMA 50", color.red)
plot(rsi14, "RSI", color.purple)

Creating Custom Functions

Basic Function Structure

//@version=5
indicator("Custom Functions")

// Simple function
myMA(src, len) =>
sum = 0.0
for i = 0 to len - 1
sum := sum + src[i]
sum / len

// Using the function
customMA = myMA(close, 20)
plot(customMA, "Custom MA", color.green)

Functions with Multiple Returns

//@version=5
indicator("Multiple Returns")

// Function returning multiple values
priceRange(len) =>
highest = ta.highest(high, len)
lowest = ta.lowest(low, len)
avg = (highest + lowest) / 2
[highest, lowest, avg]

// Using multiple returns
[hi, lo, mid] = priceRange(14)
plot(hi, "High", color.green)
plot(lo, "Low", color.red)
plot(mid, "Mid", color.blue)

Method Functions

//@version=5
indicator("Method Functions")

// Array method example
var arr = array.new_float(0)
array.push(arr, close)
array.push(arr, high)
array.push(arr, low)

// Matrix method example
var matrix = matrix.new<float>(2, 2, 0.0)
matrix.set(matrix, 0, 0, close)

Function Scope and Variables

//@version=5
indicator("Function Scope")

// Global variable
var float globalValue = 0

// Function with local scope
calculateRange() =>
// Local variables
localHigh = high
localLow = low
localRange = localHigh - localLow
globalValue := localRange // Can modify global
localRange // Return value

range = calculateRange()
plot(range)

Advanced Function Techniques

Default Parameters

//@version=5
indicator("Default Parameters")

// Function with default values
customIndicator(src = close, len = 14, mult = 2.0) =>
basis = ta.sma(src, len)
dev = mult * ta.stdev(src, len)
[basis, basis + dev, basis - dev]

[mid, upper, lower] = customIndicator()
plot(mid, "Middle", color.blue)
plot(upper, "Upper", color.green)
plot(lower, "Lower", color.red)

Function Overloading

//@version=5
indicator("Function Overloading")

// Simple version
average(price) =>
price

// Complex version
average(price1, price2) =>
(price1 + price2) / 2

// Most complex version
average(price1, price2, price3) =>
(price1 + price2 + price3) / 3

plot(average(close), "Simple")
plot(average(close, open), "Two prices")
plot(average(close, open, high), "Three prices")

Practice Examples

1. Custom RSI Function

//@version=5
indicator("Custom RSI")

customRSI(src, len) =>
// Calculate price changes
upMove = math.max(src - src[1], 0)
downMove = math.max(src[1] - src, 0)

// Calculate averages
avgUp = ta.sma(upMove, len)
avgDown = ta.sma(downMove, len)

// Calculate RS and RSI
rs = avgUp / avgDown
100 - (100 / (1 + rs))

myRSI = customRSI(close, 14)
plot(myRSI, "Custom RSI", color.purple)

2. Volatility Function

//@version=5
indicator("Volatility Function")

volatility(src, len, mult = 1.0) =>
// Calculate standard deviation
dev = ta.stdev(src, len)

// Calculate Bollinger Bands
basis = ta.sma(src, len)
upper = basis + mult * dev
lower = basis - mult * dev

// Return all values
[basis, upper, lower, dev]

[base, up, down, vol] = volatility(close, 20, 2.0)
plot(base, "Base", color.blue)
plot(up, "Upper", color.green)
plot(down, "Lower", color.red)
Pro Tips
  • Keep functions simple and focused
  • Use meaningful parameter names
  • Document complex functions
  • Consider performance impact

Common Pitfalls

Watch Out For

❌ Recursive functions (not supported) ❌ Accessing future bars ❌ Modifying input parameters ❌ Complex calculations in frequently called functions

Next Steps

Ready to learn about plotting and visualization? Move on to the next chapter! 🚀