Functions

As your Pine Script indicators grow, you will start noticing repeated patterns in your code. The same RSI calculation used three times. The same support/resistance logic copied across scripts. The same color-selection block appearing everywhere. Functions solve this by letting you write a piece of logic once and reuse it wherever you need it.

This tutorial covers both Pine Script's extensive library of built-in functions and how to create your own. By the end, you will build a complete custom indicator composed of small, focused functions.

Why Functions Matter

Functions provide three benefits that become critical as your scripts grow:

  1. DRY (Don't Repeat Yourself): Write the logic once, call it many times. If you need to change it, you change it in one place.
  2. Readability: isStrongBullish(close, volume) communicates intent far better than five lines of raw conditions.
  3. Testability: Small, isolated functions are easier to verify and debug than monolithic scripts.

Built-in Functions: The ta Library

Pine Script's ta namespace contains dozens of pre-built technical analysis functions. These are optimized internally and handle edge cases (like insufficient data on early bars) for you. Let's explore the most important ones with trading context.

Continue reading

Sign in or create a free account to unlock Functions and access the full academy.

Free account · No credit card required