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