Skip to content

函数与方法

函数定义

单行函数

pine
double(x) => x * 2
add(a, b) => a + b

多行函数

函数体的最后一个表达式是返回值。没有 return 关键字:

pine
smaCustom(src, length) =>
    sum = 0.0
    for i = 0 to length - 1
        sum += src[i]
    sum / length

返回元组的函数

pine
calcBands(src, length, mult) =>
    basis = ta.sma(src, length)
    dev = mult * ta.stdev(src, length)
    [basis, basis + dev, basis - dev]

[mid, upper, lower] = calcBands(close, 20, 2.0)

默认参数

pine
myPlot(src, length = 14, title = "Default") =>
    sma = ta.sma(src, length)
    plot(sma, title)
    sma

命名参数

调用函数时可以使用命名参数:

pine
plot(close, title = "Close", color = color.blue, linewidth = 2)

函数重载

多个函数可以共享相同的名称,只要参数类型不同:

pine
format(int x) => str.tostring(x)
format(float x) => str.tostring(x, "#.##")
format(string x) => x

方法

方法是第一个参数为接收者(self)的函数。可以使用点语法调用:

pine
method double(int self) =>
    self * 2

x = 5
x.double()  // 10

方法可以用于自定义类型:

pine
type Position
    float entry
    float size

method pnl(Position self, float currentPrice) =>
    (currentPrice - self.entry) * 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), "#.##"))

禁止递归调用

Pine Script 不允许递归。函数不能直接或通过其他函数间接调用自身。编译器在编译时拒绝任何调用循环:

pine
// 错误 — 不允许直接递归
factorial(n) =>
    n <= 1 ? 1 : n * factorial(n - 1)

// 错误 — 间接递归也会被拒绝
isEven(n) => n == 0 ? true : isOdd(n - 1)
isOdd(n)  => n == 0 ? false : isEven(n - 1)

这是语言的基本约束,不是实现限制。请使用 forwhile 循环进行迭代计算:

pine
factorial(n) =>
    result = 1
    for i = 2 to n
        result *= i
    result

内置函数

Pine Script 提供了许多内置函数:

pine
// 绘图
plot(close, "Close", color.blue)
plotshape(close > open, style = shape.triangleup)
bgcolor(close > open ? color.new(color.green, 90) : na)

// 技术分析
sma = ta.sma(close, 20)
ema = ta.ema(close, 12)
[macdLine, signal, hist] = ta.macd(close, 12, 26, 9)
rsi = ta.rsi(close, 14)

// 数学
rounded = math.round(close, 2)
maxVal = math.max(open, close)

// 字符串操作
text = str.tostring(close, "#.##")

// 输入
length = input.int(14, "RSI Length", minval = 1)
src = input.source(close, "Source")

下一步

基于 MIT 许可证发布。