Pine Script v6
驗證之前,先別說它能用
Pine 在編譯時失敗的方式,在頁面上讀起來卻很合理。永遠不要交還未檢查過的腳本。
validate_pine_script # MCP 工具 — 回傳結構化錯誤訊息與行號
lookup_pine_reference # MCP 工具 — 任何 v6 符號的真實簽名
如果 MCP 伺服器不可用,請說明腳本未經驗證,而不是暗示它能編譯通過。
不要猜測參數名稱。 lookup_pine_reference 的存在是因為猜測是最常見的失敗原因:發明 colour 代替 color、shape= 代替 style=,或在需要 text_halign 的函數上使用 textalign。
執行模型決定一切
腳本每筆執行一次,從左到右遍歷歷史數據,然後在即時 K 棒的每個 tick 上執行。
// 錯誤 — 每個 K 棒重置,所以永遠為 1
int count = 0
count := count + 1
// 正確 — `var` 初始化一次並持續存在
var int count = 0
count := count + 1
= 用來宣告。:= 用來重新賦值。對同一個名稱使用兩次 = 是錯誤。
ta.* 函數必須在每個 K 棒上執行。 它們會保存內部狀態,因此在條件內部呼叫會悄悄破壞它:
// 錯誤 — ta.sma 只在條件為真時前進
value = condition ? ta.sma(close, 20) : na
// 正確 — 先無條件計算,再選擇
smaValue = ta.sma(close, 20)
value = condition ? smaValue : na
建構子多載
line.new、label.new 和 box.new 各自接受兩種形式。兩者皆有效:
line.new(x1=bar_index[1], y1=low[1], x2=bar_index, y2=high) // 座標
line.new(first_point=chart.point.now(low), second_point=chart.point.now(high))
label.new(x=bar_index, y=high, text="hi") // 座標
label.new(point=chart.point.now(high), text="hi")
box.new(left=bar_index[5], top=high, right=bar_index, bottom=low) // 座標
box.new(top_left=p1, bottom_right=p2)
參數名稱因函數而異,容易混淆:label.new 使用 textalign;box.new 和 table.cell 使用 text_halign / text_valign。
反重繪
// 重繪 — 當前較高時間框架的 K 棒仍在形成中
d = request.security(syminfo.tickerid, "D", close)
// 穩定 — 前一個已收盤的 K 棒
d = request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_off)
將呼叫快取在變數中;切勿重複內聯呼叫。對 security 推導出的值進行除法時,請使用 nz() 保護。
平台限制
| 限制 | 值 |
|---|---|
plot() 呼叫次數 | 64 |
request.*() 呼叫次數 | 40 |
| 腳本大小 | 80,000 個 token |
| 迴圈時間 | 500 毫秒 |
| 繪圖物件 | 每種 line/label/box 各 500 個(可透過 max_*_count 提高) |
2025 年後新增的 API — 常被忽略
| 功能 | 發布時間 |
|---|---|
box.set_xloc() | 2025 年 3 月 |
每個 input.*() 上的 active | 2025 年 7 月 |
time() / time_close() 上的 timeframe_bars_back | 2025 年 10 月 |
syminfo.isin | 2025 年 11 月 |
request.footprint()、footprint / volume_row 型別 | 2026 年 1 月 |
array.sort() / matrix.sort() 上的 sort_field | 2026 年 4 月 |
多行字串 """…""" | 2026 年 4 月 |
strategy() 上的 calc_on_every_history_tick | 2026 年 7 月 |
規則也被移除:TradingView 在 2025 年 12 月取消了換行縮排限制,因此使用四個空格縮排或完全不縮排的續行都是合法的。在斷言某個符號無效之前,請查閱版本說明。
腳本結構
//@version=6
indicator("Title", overlay=true) // 或 strategy(...)
// imports -> types -> constants -> inputs -> functions
// -> calculations -> orders -> plots -> alerts
常見編譯錯誤
| 訊息 | 原因 |
|---|---|
end of line without line continuation | 運算子後有尾隨空白,或中斷的換行表達式 |
Undeclared identifier | 變數僅在 if 內部賦值;請在之前用 var 或預設值宣告 |
Cannot call 'ta.sma' with 'series' where simple required | length 參數必須是 simple int — 輸入值可以,序列值不行 |
Mismatched input ... expecting | 需要 := 進行重新賦值時卻使用了 = |