Skip to content

自定义类型与枚举

用户定义类型(UDT)

使用 type 关键字定义自定义类型。字段必须有显式类型,可以有可选的默认值:

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

字段可以使用:

  • 显式类型(必需)
  • 可选的默认值,使用 =
  • 可选的 varip 声明模式(使字段在 K 线内更新间持久化)

创建实例

使用 .new() 创建实例:

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

访问和修改字段

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

复制

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

类型上的方法

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 用于类型字段

单个字段可以使用 varip 在 K 线内更新间持久化,而其他字段仍然会回滚:

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

var Counter counter = Counter.new()
counter.bars  += 1    // 在未确认 K 线上会回滚
counter.ticks += 1    // 不会回滚

枚举

使用 enum 关键字定义枚举。枚举变体是简单的名称(没有关联数据):

pine
enum Direction
    long
    short
    both = "Both Directions"  // 可选的字符串标题

使用枚举

通过枚举名称访问变体:

pine
Direction d = Direction.long

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

导入和导出

导出

使用 export 标记函数、类型和枚举,使它们对导入模块可见:

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

导入

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)

通过模块名称访问导出的成员:

pine
import utils.pine
utils.add(1, 2)                  // 调用导出的函数
utils.MyType obj = na            // 使用导出的类型
value = utils.MyEnum.A           // 访问导出的枚举变体

下一步

基于 MIT 许可证发布。