Home » Pinescript Syntax » Collecting Objects in Pine Script

Collecting Objects in Pine Script

Photo of author
Published on

Arrays, Matrices, and Maps Containing Objects

In Pine Script™, collections like arrays, matrices, and maps can include objects. This feature allows users to structure their data more intricately and manage complex information efficiently.

Declaring Collections of Objects

To create a collection that holds objects of a user-defined type (UDT), you specify the UDT in the collection’s type template.

Example: Creating an Array of pivotPoint Objects

Empty Array Declaration

pivotHighArray = array.new<pivotPoint>()

Explicit Type Declaration

var array<pivotPoint> pivotHighArray = na
pivotHighArray := array.new<pivotPoint>()

Script Example: Detecting High Pivot Points

Let’s create a script that identifies high pivot points, stores them in an array, and then uses that data to draw labels and lines on the chart.

Script Overview

Indicator Declaration

indicator("Pivot Points High", overlay = true)
int legsInput = input(10)

Defining pivotMarker UDT

type pivotMarker
    int entryTime
    float height

Creating an Empty Array

var pivotHighArray = array.new<pivotMarker>()

Detecting and Storing Pivots

pivotHighPrice = ta.pivothigh(legsInput, legsInput)
if not na(pivotHighPrice)
    newMarker = pivotMarker.new(bar_index[legsInput], pivotHighPrice)
    array.push(pivotHighArray, newMarker)

Drawing Labels and Lines on the Last Historical Bar:

if barstate.islastconfirmedhistory
    var pivotMarker lastMarker = na
    for marker in pivotHighArray
        label.new(marker.entryTime, marker.height, str.tostring(marker.height, format.mintick), xloc.bar_time, textcolor = color.white)
        if not na(lastMarker)
            line.new(lastMarker.entryTime, lastMarker.height, marker.entryTime, marker.height, xloc = xloc.bar_time)
        lastMarker := marker
Collecting Objects

In this script, an array of pivotMarker objects (pivotHighArray) is used to store the time and price of high pivot points detected by ta.pivothigh. The script then iterates through this array on the last historical bar to draw labels at each pivot point and connect them with lines.

Conclusion and Key Takeaways

  • Collections of Objects: Pine Script allows for the creation of arrays, matrices, and maps containing objects, enhancing the script’s data handling capabilities.
  • Practical Application: Using collections of objects is beneficial for scripts that need to process and visualize complex or multi-dimensional data.

Leave a Comment