Method syntax comes to Pine Script®

Mar 7, 2023

The dot notation used for extension methods in other languages is now available in Pine Script®. Programmers can use this new syntax in two different ways:

  • With user-defined methods, which are special functions declared with the new method keyword.
  • With built-in functions from namespaces of array, box, label, line, linefill, matrix, and table types when the first parameter is the ID of an object of that type.

Let’s look at this simple example where we calculate the average of the low for a rolling window of rising bars:

//@version=5
indicator("Long stop", "", true)
int lengthInput = input(20)
var pricesArray = array.new<float>(lengthInput)

method maintainQueue(array<float> srcArray, float value) =>
    // Append a new value to the end of the array.
    srcArray.push(value)
    // Remove the oldest value from the beginning of the array.
    srcArray.shift()

if close > open
    // Track the `low` values of up bars.
    pricesArray.maintainQueue(low)

plot(pricesArray.avg(), "Stop")

Our maintainQueue() method is very similar to a regular function and can be used as such, but the method keyword also allows it to be used with dot notation after a variable of the first parameter’s type. When we do so, we omit the first argument from the method call, as in pricesArray.maintainQueue(low).

Also note how we use method notation with functions from the array namespace in calls such as srcArray.push() and srcArray.shift() inside the method’s code, and pricesArray.avg() in the example’s last line.

You will find more information on this new feature in our User Manual’s page on methods.

To see methods in action, you can view the updated code of our built-in Gaps indicator that uses both built-in and user-defined methods to highlight chart gaps with boxes:

Additionally, we have updated the code of our ZigZag library to use built-in and user-defined methods:

ZigZag by TradingView

See objects and methods used in the following scripts by some of our PineCoders:

Flare by Fikira

Recursive Zigzag [Trendoscope] by HeWhoMustNotBeNamed

Recursive Auto-Pitchfork [Trendoscope] by HeWhoMustNotBeNamed

To stay informed of new Pine Script® features, keep an eye on the User Manual’s Release notes. The PineCoders account also broadcasts updates from its Squawk Box on Telegram, its Twitter account, and from the Pine Script® Q&A public chat on TradingView.

We hope you find this highly-requested feature useful. Please keep sending us your feedback and suggestions for improvement. We build TradingView for you, and we’re always keen to hear from you.

Look first Then leap

TradingView is built for you, so make sure you're getting the most of our awesome features
Launch Chart