返回《給 CFD 交易者的 TradingView PineScript》
第二部分

陣列與矩陣:處理多條序列

Pine 的陣列在執行期是固定的,矩陣是二維的。兩者都是你拿來做 Pine 向量模型無法直接表達的工作的方法。

中級閱讀時間約 10 分鐘初學 → 進階第 09 / 17 堂
在 TradingView 實際跑一次
上漲 K 線收盤價的滾動最高價

那個陣列只接受上漲 K 線的收盤價,並在達到 50 個時丟掉最舊的。綠線是那些裡面的最高價——沒有任何單一內建函式給得了你這個。

//@version=5
indicator("Lesson 9 - Arrays", overlay=true)

// Keep the last 50 closes, but only from up bars.
var float[] upCloses = array.new_float(50)

if close > close[1]
    array.push(upCloses, close)
    if array.size(upCloses) > 50
        array.shift(upCloses)

// array.max of an empty array errors — guard with na.
float highestUpClose = array.size(upCloses) > 0 ? array.max(upCloses) : na

plot(highestUpClose, "Highest up-close (last 50)", color=color.green, linewidth=2)
plot(close, "Close", color=color.gray, linewidth=1)
如何執行
  1. 1. 在 TradingView 打開任一圖表,點選下方的 Pine Editor
  2. 2. 把編輯器裡的內容全選,用這段程式覆蓋過去,然後按 Save
  3. 3. 點選 Add to chart。如果是策略, 再打開 Strategy Tester 分頁。

陣列是動態的,但有上限

與 Python 的 list 不同,Pine 的陣列在你建立它時就設好了最大尺寸:

var float[] prices = array.new_float(20)
array.push(prices, close)
array.shift(prices)

這會保留最近 20 根收盤價。array.push 附加到尾端,array.shift 從前端移除。當陣列到達最大尺寸時,最舊的元素會被自動丟掉。

常見的陣列操作

array.size(a)array.get(a, i)array.set(a, i, value)array.sum(a)array.avg(a)array.max(a)array.min(a)array.includes(a, v)。完整參考在 Pine v5 手冊裡。

為什麼陣列在 Pine 裡重要

向量模型一次給你所有 K 線——但它沒給你一個方法去做「最近 20 根上漲 K 線的最高價」這種事。為了那個,你把相關的值推進一個陣列再掃它。

二維工作用矩陣

array.new_matrix(rows, cols, initValue) 給你一個二維結構。對投資組合層級的指標、相關係數表,以及盤口近似很有用。

一個實作範例:上漲 K 線收盤價的滾動最高價

var float[] upCloses = array.new_float(50)
if close > close[1]
    array.push(upCloses, close)
if array.size(upCloses) > 50
    array.shift(upCloses)

highestUpClose = array.max(upCloses)
plot(highestUpClose)

該從這裡帶走什麼

當 Pine 的向量模型不合用時,陣列與矩陣是逃生門。對 90% 的 CFD 指標你不會需要它們——但當你需要時,它們就是你讓腳本保持快速、而不是逐根跑迴圈的方法。

你剛完成了什麼

給 CFD 交易者的 TradingView PineScript》的第 09 / 17 堂課。跑完範例或讀完這段之後, 把它勾起來,然後進下一堂課。