Skip to content

Custom Types & Enums

User-Defined Types (UDTs)

Define custom types with the type keyword. Fields must have explicit types and can have optional default values:

pine
type Order
    int id
    string symbol
    float price = na
    varip int updateCount = 0

Fields can use:

  • An explicit type (required)
  • An optional default value with =
  • An optional varip declaration mode (makes the field persist across intrabar updates)

Creating Instances

Use .new() to create an instance:

pine
Order myOrder = Order.new(id = 1, symbol = "AAPL")

Accessing and Modifying Fields

pine
orderPrice = myOrder.price
myOrder.price := 155.0
myOrder.quantity := 200

Copying

pine
Order clone = Order.copy(myOrder)
clone.price := 160.0

Methods on Types

pine
type Position
    float entry
    float size
    bool isLong = true

method pnl(Position self, float currentPrice) =>
    diff = currentPrice - self.entry
    self.isLong ? diff * self.size : -diff * self.size

method isProfit(Position self, float currentPrice) =>
    self.pnl(currentPrice) > 0

pos = Position.new(entry = 100.0, size = 10.0)
if pos.isProfit(close)
    label.new(bar_index, high, str.tostring(pos.pnl(close), "#.##"))

varip on Type Fields

Individual fields can use varip to persist across intrabar updates while other fields still roll back:

pine
type Counter
    int       bars  = 0
    varip int ticks = 0

var Counter counter = Counter.new()
counter.bars  += 1    // subject to rollback on unconfirmed bars
counter.ticks += 1    // NOT subject to rollback

Enums

Define enumerations with the enum keyword. Variants are simple names (no associated data):

pine
enum Direction
    long
    short
    both = "Both Directions"  // optional string title

Using Enums

Access variants via the enum name:

pine
Direction d = Direction.long

if d == Direction.long
    strategy.entry("L", strategy.long)
else if d == Direction.short
    strategy.entry("S", strategy.short)

Import and Export

Exporting

Mark functions, types, and enums with export to make them visible to importing modules:

pine
//@version=6
library("MyLib")

export type Config
    int length
    float multiplier

export calcSMA(series float src, simple int length) =>
    ta.sma(src, length)

export enum Side
    left
    right

Importing

pine
//@version=6
indicator("My Indicator")
import MyLib.pine as lib

config = lib.Config.new(length = 20, multiplier = 2.0)
sma = lib.calcSMA(close, config.length)
plot(sma)

Access exported members via the module name:

pine
import utils.pine
utils.add(1, 2)                  // call exported function
utils.MyType obj = na            // use exported type
value = utils.MyEnum.A           // access exported enum variant

Next Steps

Released under the MIT License.