Skip to content

Functions & Methods

Function Definitions

Single-Line Functions

pine
double(x) => x * 2
add(a, b) => a + b

Multi-Line Functions

The last expression in the body is the return value. There is no return keyword:

pine
smaCustom(src, length) =>
    sum = 0.0
    for i = 0 to length - 1
        sum += src[i]
    sum / length

Functions Returning Tuples

pine
calcBands(src, length, mult) =>
    basis = ta.sma(src, length)
    dev = mult * ta.stdev(src, length)
    [basis, basis + dev, basis - dev]

[mid, upper, lower] = calcBands(close, 20, 2.0)

Default Parameters

pine
myPlot(src, length = 14, title = "Default") =>
    sma = ta.sma(src, length)
    plot(sma, title)
    sma

Named Arguments

When calling functions, you can use named arguments:

pine
plot(close, title = "Close", color = color.blue, linewidth = 2)

Function Overloading

Multiple functions can share the same name if they have different parameter types:

pine
format(int x) => str.tostring(x)
format(float x) => str.tostring(x, "#.##")
format(string x) => x

Methods

Methods are functions whose first parameter is the receiver (self). They can be called with dot syntax:

pine
method double(int self) =>
    self * 2

x = 5
x.double()  // 10

Methods work with custom types:

pine
type Position
    float entry
    float size

method pnl(Position self, float currentPrice) =>
    (currentPrice - self.entry) * self.size

method isProfit(Position self, float currentPrice) =>
    self.pnl(currentPrice) > 0

pos = Position.new(entry = 100.0, size = 10.0)
if pos.isProfit(close)
    label.new(bar_index, high, str.tostring(pos.pnl(close), "#.##"))

No Recursive Calls

Pine Script does not allow recursion. A function cannot call itself, either directly or indirectly through other functions. The compiler rejects any call cycle at compile time:

pine
// ERROR — direct recursion is not allowed
factorial(n) =>
    n <= 1 ? 1 : n * factorial(n - 1)

// ERROR — indirect recursion is also rejected
isEven(n) => n == 0 ? true : isOdd(n - 1)
isOdd(n)  => n == 0 ? false : isEven(n - 1)

This is a fundamental language constraint, not an implementation limitation. Use for or while loops for iterative computation instead:

pine
factorial(n) =>
    result = 1
    for i = 2 to n
        result *= i
    result

Built-in Functions

Pine Script provides many built-in functions:

pine
// Plotting
plot(close, "Close", color.blue)
plotshape(close > open, style = shape.triangleup)
bgcolor(close > open ? color.new(color.green, 90) : na)

// Technical Analysis
sma = ta.sma(close, 20)
ema = ta.ema(close, 12)
[macdLine, signal, hist] = ta.macd(close, 12, 26, 9)
rsi = ta.rsi(close, 14)

// Math
rounded = math.round(close, 2)
maxVal = math.max(open, close)

// String operations
text = str.tostring(close, "#.##")

// Input
length = input.int(14, "RSI Length", minval = 1)
src = input.source(close, "Source")

Next Steps

Released under the MIT License.