Functions are reusable blocks of code that perform specific tasks. Pine Script provides hundreds of built-in functions and allows you to create custom ones.
Built-in Functions Overview
Pine Script includes many built-in functions organized by category:
//@version=6indicator("Custom Functions")// Define a functionmyFunction(param1, param2) => result = param1 + param2 result// Use the functionsum = myFunction(10, 5)plot(close)
Function with Multiple Returns
//@version=6indicator("Multi-Return Function")// Function that returns multiple valuesgetLevels(price, atr) => stopLoss = price - atr * 2 takeProfit = price + atr * 3 [stopLoss, takeProfit]// Use the functionatrValue = ta.atr(14)[sl, tp] = getLevels(close, atrValue)plot(close)plot(sl, color=color.red)plot(tp, color=color.green)
Function with Conditional Logic
//@version=6indicator("Conditional Function")// Calculate position size based on riskcalculatePositionSize(accountBalance, riskPercent, stopLoss) => riskAmount = accountBalance * (riskPercent / 100) positionSize = riskAmount / stopLoss positionSize// Use itaccountSize = 10000risk = 2.0stopDistance = close * 0.02 // 2% stopsize = calculatePositionSize(accountSize, risk, stopDistance)plot(close)
Practical Function Examples
Example 1: Custom Moving Average
//@version=6indicator("Custom MA")// Create custom moving average functioncustomSMA(src, length) => sum = 0.0 for i = 0 to length - 1 sum := sum + src[i] sum / length// Use itma20 = customSMA(close, 20)ma50 = customSMA(close, 50)plot(ma20, color=color.green, title="Custom SMA 20")plot(ma50, color=color.red, title="Custom SMA 50")
// Good - single responsibilitycalculateSMA(src, length) => ta.sma(src, length)calculateATR(length) => ta.atr(length)// Good - composed functionsmyIndicator(src, length) => sma = calculateSMA(src, length) atr = calculateATR(length) [sma, atr]
2. Use Type Annotations
//@version=6indicator("Typed Functions")// Explicitly typed functionaddIntegers(int a, int b) => int a + b// Series typed functioncalculateSMA(series float src, int length) => series float ta.sma(src, length)sma = calculateSMA(close, 20)plot(sma)
3. Document Complex Functions
//@version=6indicator("Documented Function")// Calculate position size based on risk management rules// Parameters:// accountBalance: Total account size// riskPercent: Percentage of account to risk (0.01 - 0.1)// stopLoss: Price distance for stop loss// Returns: Position size in unitscalculateRiskPosition(float accountBalance, float riskPercent, float stopLoss) => riskAmount = accountBalance * riskPercent positionSize = riskAmount / stopLoss positionSize