迴圈#

Pine Script 提供兩種迴圈結構:forwhile。由於 Pine Script 是逐根 K 棒執行的語言,迴圈通常用於 在單根 K 棒內 重複計算,例如尋找過去 N 根 K 棒的最高點、對陣列元素做批次處理等。

注意:迴圈會增加每根 K 棒的運算時間。在大量 K 棒的圖表上使用過深的迴圈可能導致腳本超時,建議優先使用 Pine Script 內建的 ta.* 系列函式,它們已針對序列計算做過最佳化。

for 迴圈#

基本語法#

for 變數 = 起始值 to 結束值
    // 迴圈本體

for 迴圈從起始值遞增到結束值(含),每次遞增 1:

//@version=6
indicator("for 迴圈示範")

// 手動計算過去 5 根 K 棒收盤價的總和
var float total = 0.0
total := 0.0
for i = 0 to 4
    total := total + close[i]

plot(total / 5, "5根均價")

by — 自訂步長#

使用 by 可以指定每次的遞增量(可以是負數,用於倒序迴圈):

// 每次遞增 2
for i = 0 to 10 by 2
    // i = 0, 2, 4, 6, 8, 10

// 倒序:從 10 遞減到 0
for i = 10 to 0 by -1
    // i = 10, 9, 8, ..., 0

for…in — 迭代陣列#

for...in 用於逐一取出陣列的每個元素:

//@version=6
indicator("for-in 示範")

prices = array.from(close, close[1], close[2], close[3], close[4])

var float sum = 0.0
sum := 0.0
for price in prices
    sum := sum + price

plot(sum / array.size(prices), "平均價格")

如果同時需要索引和值,使用 for [index, value] in array

prices = array.from(10.0, 20.0, 30.0)

for [i, val] in prices
    // i = 0, 1, 2
    // val = 10.0, 20.0, 30.0
    label.new(bar_index - i, val, str.tostring(val))

while 迴圈#

while 在條件成立時持續執行:

while 條件
    // 迴圈本體

範例:找出最近一次收盤價高於 20 日均線的 K 棒距離現在幾根:

//@version=6
indicator("while 示範")

ma20 = ta.sma(close, 20)

// 從當前 K 棒往回找,找到第一根收盤在均線以上的 K 棒
barsAgo = 0
while close[barsAgo] <= ma20[barsAgo] and barsAgo < 50
    barsAgo := barsAgo + 1

plot(barsAgo, "距離上次均線以上的根數")

注意while 迴圈必須確保條件最終會變為 false,否則會造成無限迴圈而使腳本超時。建議加上最大迭代次數限制(如上例的 barsAgo < 50)。

break — 提前跳出迴圈#

break 立即結束迴圈,不再執行後續的迭代:

//@version=6
indicator("break 示範")

// 找出最近收盤價為最高的那根 K 棒是幾根前
highestBar = 0
for i = 1 to 50
    if close[i] > close[highestBar]
        highestBar := i
    // 找到超過 1% 的回落就停止搜尋
    if close[0] - close[i] > close[0] * 0.01
        break

plot(highestBar, "最高收盤距今根數")

continue — 跳過本次迭代#

continue 跳過當次迭代,直接進入下一次:

//@version=6
indicator("continue 示範")

// 只累計陽線(收盤 > 開盤)的成交量
var float bullVolume = 0.0
bullVolume := 0.0

for i = 0 to 9
    if close[i] <= open[i]
        continue  // 陰線跳過
    bullVolume := bullVolume + volume[i]

plot(bullVolume, "近10根陽線總成交量")

實用範例:手動計算最高/最低價#

雖然 ta.highestta.lowest 已可直接使用,但以下範例展示迴圈的完整應用:

//@version=6
indicator("迴圈找高低點", overlay=true)

lookback = input.int(20, "回顧根數", minval=1)

// 用 for 迴圈找最高和最低收盤價
var float myHighest = na
var float myLowest  = na
myHighest := close
myLowest  := close

for i = 1 to lookback - 1
    if close[i] > myHighest
        myHighest := close[i]
    if close[i] < myLowest
        myLowest := close[i]

plot(myHighest, "最高收盤", color=color.green)
plot(myLowest,  "最低收盤", color=color.red)

Reference#