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 线运行一次,从左到右遍历历史数据,然后在实时 K 线的每个跳点上运行。
// 错误——每根 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 月 |
active 在所有 input.*() 上 | 2025 年 7 月 |
timeframe_bars_back 在 time() / time_close() 上 | 2025 年 10 月 |
syminfo.isin | 2025 年 11 月 |
request.footprint()、footprint / volume_row 类型 | 2026 年 1 月 |
sort_field 在 array.sort() / matrix.sort() 上 | 2026 年 4 月 |
多行字符串 """…""" | 2026 年 4 月 |
calc_on_every_history_tick 在 strategy() 上 | 2026 年 7 月 |
规则也会被移除:TradingView 在 2025 年 12 月取消了折行缩进限制,因此连续行缩进四个空格或不缩进都是合法的。在断言某个符号无效之前,请先查阅发布说明。
脚本结构
//@version=6
indicator("标题", overlay=true) // 或 strategy(...)
// 导入 -> 类型 -> 常量 -> 输入 -> 函数
// -> 计算 -> 订单 -> 绘图 -> 警报
常见编译错误
| 消息 | 原因 |
|---|---|
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 | 在需要 := 的地方使用了 = 进行重新赋值 |