官方的 Pine Script 語言參考手冊有幾百個型別、變數和函式,新手一打開就想關掉。其實你九成的時間只會用到一小把。這篇把新手最常用的挑出來,每個配一句白話 + 迷你範例,當速查用。語法以 v6 為準。
這是「新手最常用」的精選,不是完整清單。想查完整內容,直接看 TradingView 官方 Pine Script 參考手冊(最完整、最新)。先從 Pine Script 入門 開始也可以。
1. 腳本結構(每支都要)
//@version=6 // 第一行:宣告用 v6 語法(一定要寫) indicator("名稱", overlay=true) // 宣告「指標」;overlay=true 畫在K線上 strategy("名稱") // 宣告「策略」(可回測、會下單)
2. 價格資料(內建變數)
close // 收盤價(open 開、high 高、low 低 同理) volume // 成交量 hl2 // =(high+low)/2 hlc3=(高+低+收)/3 ohlc4=(開高低收)/4 close[1] // 前一根的收盤價([] 取歷史,[2] 是前兩根) bar_index // 這是第幾根K棒,從 0 開始數
3. 常用技術函式(ta.*)
ta.sma(close, 20) // 簡單移動平均(20 日均線) ta.ema(close, 20) // 指數移動平均 ta.rsi(close, 14) // RSI 相對強弱指標 ta.stoch(close, high, low, 9) // KD 的 RSV ta.crossover(a, b) // a 由下往上穿過 b(黃金交叉)→ true ta.crossunder(a, b) // a 由上往下跌破 b(死亡交叉)→ true ta.highest(high, 20) // 近 20 根的最高價(ta.lowest 最低)
*點前面的 ta. 是「命名空間」=函式的分類。技術函式在 ta.、數學在 math.(如 math.max)、字串在 str.。
4. 輸入參數(input.*,做成可調設定)
len = input.int(20, "均線天數") // 整數輸入,預設 20 mult = input.float(2.0, "倍數") // 小數輸入 on = input.bool(true, "開關") // 開關(true/false)
5. 畫圖與標記
plot(ta.sma(close,20), "MA", color=color.orange) // 畫線 hline(70, "超買") // 畫水平線 plotshape(cond, style=shape.triangleup, // 條件成立時畫箭頭 location=location.belowbar, color=color.red) bgcolor(cond ? color.new(color.red,90) : na) // 依條件把背景上色
6. 條件與 K 棒狀態
if ta.crossover(fast, slow) // 條件式(下一行要縮排) // 這裡放條件成立要做的事 barstate.islast // 是不是最後一根K棒 → true/false barstate.isconfirmed // 這根K棒是否已收盤定案 var float x = 0.0 // var:變數只在第一根初始化一次 x := close // := 是「重新賦值」 na(close[1]) ? 0 : close[1] // na() 測有沒有值;nz(x,0) 沒值就給0
7. 策略回測(strategy.*)
strategy.entry("做多", strategy.long) // 進場做多(strategy.short 做空) strategy.close("做多") // 平掉這個部位 strategy.exit("出場", "做多", stop=90, limit=110) // 停損/停利出場 strategy.netprofit // 目前總淨利 strategy.position_size // 目前部位(正=多、負=空、0=空手)
💡 記憶小訣竅
不用死背。記住「分類(命名空間)」就好:要算指標找 ta.、要輸入參數找 input.、要畫東西找 plot / label / line、要下單找 strategy.。在編輯器打字時 TradingView 也會自動提示,忘了就查 官方手冊。
常見問題
Pine Script 新手一定要記哪些語法?▾
大概二十個:腳本結構(//@version=6、indicator、strategy)、價格資料(close、hl2)、技術函式(ta.sma、ta.rsi、ta.crossover)、input.int、plot/plotshape/hline、if/barstate.islast、strategy.entry/close。涵蓋新手九成需求。
ta.、math.、input. 這些點是什麼?▾
點前面是「命名空間」=函式分類。技術函式在 ta.、數學在 math.、輸入在 input.、字串在 str.。記住分類就好找函式。
close[1] 的中括號是什麼?▾
[] 是歷史運算子,取前幾根 K 棒的值。close 是這根收盤、close[1] 前一根、close[2] 前兩根。判斷「今天比昨天高」之類都會用到。
這份速查是完整的嗎?▾
不是,是「新手最常用」的精選。完整型別、變數與函式請以 TradingView 官方 Pine Script 參考手冊為準(本文以 v6 為準)。
本文為 Pine Script 常用語法的新手精選速查,非完整參考,也非投資建議。語法以 TradingView Pine Script v6 為準,若因官方改版而異動,請以 TradingView 官方參考手冊為準。程式與指標有其限制,不保證獲利。TradingView 連結為聯盟連結,不影響你的費用與本文中立。