變數和型別#
宣告變數#
在 Pine Script 中,宣告變數使用 = 號,型別由編譯器自動推斷:
myLength = 14 // 整數 (int)
myLevel = 50.5 // 浮點數 (float)
mySignal = true // 布林值 (bool)
myLabel = "突破訊號" // 字串 (string)變數一經宣告,每根 K 棒執行時都會重新計算並更新數值。
型別#
Pine Script 的基本型別:
| 型別 | 說明 | 範例值 |
|---|---|---|
int | 整數 | 14、-3、0 |
float | 浮點數 | 1.5、0.618、na |
bool | 布林值 | true、false |
string | 字串 | "buy"、"均線向上" |
color | 顏色 | color.red、#FF0000 |
na — 無效值#
na 是 Pine Script 特有的值,代表 資料不存在或尚未定義,類似其他語言的 null 或 NaN。
例如,計算 14 日 RSI 時,前 13 根 K 棒沒有足夠的數據,此時 RSI 的值為 na。
使用 na(x) 函數可以判斷一個值是否為 na:
rsiValue = ta.rsi(close, 14)
if na(rsiValue)
label.new(bar_index, high, "資料不足")var — 跨 K 棒保留變數#
預設情況下,變數在每根 K 棒執行時都會重新初始化。如果需要 跨 K 棒累積數值,使用 var 關鍵字宣告:
//@version=6
indicator("成交量累計示範")
// 沒有 var:每根 K 棒都重置為 0,計數永遠是 1
// count = 0
// 有 var:只有第一根 K 棒初始化為 0,之後保留前一根 K 棒的值
var count = 0
count := count + 1 // 使用 := 更新已宣告的變數
plot(count, title="K棒計數")var 變數的初始值只在 第一根 K 棒 時賦予一次,之後每根 K 棒執行時保留上一次的數值。
更新變數的值#
宣告變數後,若要 更新 其值(而非重新宣告),使用 := 運算子:
var highestHigh = high // 初始化
if high > highestHigh
highestHigh := high // 更新為更高的值注意:
=用於 宣告,:=用於 更新。混用會導致編譯錯誤。
序列型別 vs 簡單型別#
Pine Script 的變數有兩種「限定詞 (Qualifier)」:
- series:每根 K 棒都有獨立的數值,可以用
[N]存取歷史 - simple / const:整個腳本執行期間只有一個值,不隨 K 棒改變
// series float:每根 K 棒的收盤價不同
myClose = close // series float
// simple int:固定不變的參數
length = input.int(14, "週期") // simple int大多數情況下不需要手動指定,Pine Script 會自動推斷。但某些函數的參數要求 simple 型別,此時不能傳入隨 K 棒變化的 series 值。
input — 可調整的參數#
使用 input 系列函數可以建立可在圖表介面調整的參數,不需要修改程式碼:
//@version=6
indicator("RSI 指標")
// 建立可調整的參數
length = input.int(14, "RSI 週期", minval=1, maxval=100)
overbought = input.int(70, "超買線", minval=50, maxval=100)
oversold = input.int(30, "超賣線", minval=0, maxval=50)
rsiValue = ta.rsi(close, length)
plot(rsiValue, "RSI", color=color.purple)
hline(overbought, "超買", color=color.red)
hline(oversold, "超賣", color=color.green)常用的 input 函數:
| 函數 | 型別 | 說明 |
|---|---|---|
input.int(defval, title) | int | 整數輸入框 |
input.float(defval, title) | float | 浮點數輸入框 |
input.bool(defval, title) | bool | 勾選框 |
input.string(defval, title) | string | 下拉選單或文字框 |
input.source(defval, title) | series float | 資料來源選擇(close/open/hl2…) |
型別轉換#
Pine Script 在大多數情況下會自動轉換型別,但有時需要手動轉換:
myInt = 10
myFloat = float(myInt) // int → float
myFloat2 = 3.7
myInt2 = int(myFloat2) // float → int(直接截斷,結果為 3)
myNum = 42
myStr = str.tostring(myNum) // 數值 → 字串