自訂類型與枚舉
使用者定義類型(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 // 存取匯出的枚舉變體下一步
- 標準函式庫 — 探索內建函式
- OpenPine 擴充 — getter、staticmethod、運算子多載、泛型
- 整合 — 以程式方式執行指令碼