Home » Pinescript Syntax » Understanding User-Defined Methods in Pine Script

Understanding User-Defined Methods in Pine Script

Photo of author
Published on

In Pine Script™, defining user-specific methods enhances code readability, encapsulation, and reusability. This guide delves into creating custom methods, highlighting their application in organizing Bollinger Bands calculations more efficiently.

User-Defined Methods in Pine Script

User-defined methods in Pine Script™ share similarities with functions but are distinct in two main ways:

  • They must be preceded by the method keyword.
  • The type of the first parameter must be declared explicitly, indicating the object type the method is associated with.

Here’s the basic syntax for defining a method:

[export] method <functionName>(<paramType> <paramName> [= <defaultValue>], …) =>
    <functionBlock>

Simplifying Bollinger Bands Calculations with Custom Methods

To illustrate, let’s refine the Bollinger Bands example by encapsulating operations within user-defined methods.

The maintainQueue Method

First, we introduce maintainQueue, a method that simplifies array management by combining push and shift operations into a single call:

method maintainQueue(array<float> srcArray, float value, bool takeSample = true) =>
    if takeSample
        srcArray.push(value)
        srcArray.shift()
    srcArray
  • Objective: Manage an array as a queue by adding a new value and removing the oldest one.
  • Parameters: srcArray (the array to manage), value (the new value to add), and takeSample (a flag to control the operation).

The calcBB Method

Next, we define calcBB, a method that performs all Bollinger Band calculations, updating mean and standard deviation values, and returning the bands:

method calcBB(array<float> srcArray, float mult, bool calculate = true) =>
    var float mean = na
    var float dev  = na
    if calculate
        mean := srcArray.avg()
        dev  := srcArray.stdev() * mult
    [mean, mean + dev, mean - dev]
  • Objective: Compute Bollinger Band values from an array.
  • Parameters: srcArray (data array), mult (multiplier for standard deviation), and calculate (a flag to initiate calculation).

Implementing the Methods in the Script

With these methods, the script is significantly streamlined:

//@version=5
indicator("Custom Sample BB", overlay = true)

float sourceInput  = input.source(close, "Source")
int   samplesInput = input.int(20, "Samples")
int   n            = input.int(10, "Bars")
float multiplier   = input.float(2.0, "StdDev")

var array<float> sourceArray = array.new<float>(samplesInput)

bool newSample = bar_index % n == 0

[sampleMean, highBand, lowBand] = sourceArray.maintainQueue(sourceInput, newSample).calcBB(multiplier, newSample)

plot(sampleMean, "Basis", color.orange)
plot(highBand, "Upper", color.lime)
plot(lowBand, "Lower", color.red)
Methods in the Script

Explanation

  1. Indicator Declaration: //@version=5 indicator("Custom Sample BB", overlay = true) specifies the script uses Pine Script version 5 and creates a new indicator named “Custom Sample BB” that overlays on the price chart.
  2. Input Variables:
    • float sourceInput = input.source(close, "Source"): Defines the source price (e.g., closing price) for the Bollinger Bands calculation.
    • int samplesInput = input.int(20, "Samples"): Sets the number of periods (e.g., 20) for calculating the moving average.
    • int n = input.int(10, "Bars"): Determines the interval (e.g., every 10 bars) at which the indicator updates.
    • float multiplier = input.float(2.0, "StdDev"): Specifies the multiplier for the standard deviation to calculate the upper and lower bands.
  3. Array Initialization: var array<float> sourceArray = array.new<float>(samplesInput) creates a new floating-point array sourceArray to store the specified number of sample inputs for calculations.
  4. New Sample Detection: bool newSample = bar_index % n == 0 checks if the current bar index is a multiple of n, indicating it’s time to update the indicator values (i.e., a new sample period has been reached).
  5. Method Calls:
    • The code uses maintainQueue to update sourceArray with the new sourceInput value and remove the oldest value from the array, maintaining its size. This operation occurs only if newSample is true.
    • calcBB calculates the Bollinger Bands values by computing the average (sampleMean) and applying the multiplier to the standard deviation for the highBand and lowBand.
  6. Tuple Assignment: [sampleMean, highBand, lowBand] = sourceArray.maintainQueue(sourceInput, newSample).calcBB(multiplier, newSample) assigns the calculated mean, upper band, and lower band values to respective variables in a single line, showcasing method chaining.
  7. Plotting:
    • plot(sampleMean, "Basis", color.orange): Plots the moving average (basis) line in orange.
    • plot(highBand, "Upper", color.lime): Plots the upper Bollinger Band in lime.
    • plot(lowBand, "Lower", color.red): Plots the lower Bollinger Band in red.

Key Features and Takeaways

  • Enhanced Code Organization: User-defined methods promote cleaner and more organized code, making it easier to read and maintain.
  • Encapsulation and Reusability: By encapsulating specific operations within methods, we facilitate code reuse across different parts of the script or in entirely different scripts.
  • Simplified Code Logic: The newSample variable and method chaining (maintainQueue followed by calcBB) streamline the script’s logic, removing the need for repetitive if-blocks.

By adopting user-defined methods in Pine Script™, developers can significantly improve the structure and readability of their scripts, enhancing both development efficiency and code maintainability.

Leave a Comment