Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a custom Class in Pine Script?

Tags:

pine-script

Is it possible to create a custom class in Pine and how can I create one? I have searched the web on how to make a class in Pine Script, but I have not found a single page.

Here is a class example made in Python:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)
like image 977
Marcus Cazzola Avatar asked Sep 15 '25 21:09

Marcus Cazzola


1 Answers

As of v5, Pine Script does not support classes. Types are the closest thing to a class in the Pine Script.

For example:

// @version=5
library('mylib')

// Custom types can only have attributes. No methods are allowed.
export type person        // lower first case is just a convention as seen in builtin objects
    string  name
    int     age
    over18  boolean
    bool    isVip = false // Only constant literals, no expressions historical access allowed in default value.

export new(string name, int age) =>
    isOver18 = age >= 18
    person   = person.new(name, age, isOver18)
    person

You can use it as below after you published your library. (You don't have to make it a library, you can just add it to your code, but when used as a library, it is closer to a class.)

import your_username/mylib/1

// Create with our factory/constructor
john         = mylib.new("John", 25)
isJohnOver18 = john.over18                  // true

// Unfortunately there is nothing to prevent direct object creation
mike         = mylib.person.new("Mike", 25) // Create object with type's builtin constructor.
isMikeOver18 = mike.over18                  // na

Edit: I see strange behavior currently I couldn't understand the reason when used typed arguments and access their historical value. See the example below:


weirdFunction(person user) =>
    // This is somehow not working as expected in the function.
    // However it works flawlessly in a global context.
    previousAge = user.age[1] // Gets wrong value

// Workaround

correctFunction(person user) =>
    previousUser = user[1]
    previousAge = previousUser.age
like image 128
ozm Avatar answered Sep 19 '25 15:09

ozm