Skip to main content
TradingView Pine Script 入门
blog 中级 · ~2 min read

TradingView Pine Script 入门

Pine Script 是 TradingView 的领域专用语言,用来建自定义指标和策略,本指南带新手从第一行代码走到一个能跑的 EMA 交叉。

· Lead Editor · · ~2 min read
#platforms#tools
本文为英文。需要查看中文翻译吗?

交互工具在翻译视图中可能无法使用。

TradingView Pine Script 入门

Pine Script 让你不用离开浏览器、不配 Python 环境、不开 IDE、不要 API key,就能把一个图表想法变成代码。

Pine Script 是什么

Pine Script 是一种声明式语言,跑在 TradingView 里。你描述每根 K 线该算什么,引擎就画出来。没有事件循环,没有内存管理,不用手动遍历 K 线——运行时替你处理逐 K 线迭代。

版本要紧:Pine Script v5 是当前版。永远在第一行声明版本,避免静默行为差异。

第一个指标:EMA 缎带

打开 TradingView,点底部的 Pine Editor,粘贴下面这段,然后点 Add to chart

//@version=5
indicator("EMA Ribbon", overlay = true)

fast = input.int(20, "Fast EMA")
slow = input.int(50, "Slow EMA")

emaFast = ta.ema(close, fast)
emaSlow = ta.ema(close, slow)

plot(emaFast, color = color.aqua, linewidth = 2)
plot(emaSlow, color = color.orange, linewidth = 2)

fill(plot1, plot2, color = emaFast > emaSlow ? color.new(color.green, 80) : color.new(color.red, 80))

从上往下读:

  1. //@version=5 声明语言版本。
  2. indicator() 注册脚本类型,并标记它叠加在价格图上。
  3. input.int() 暴露一个用户不改代码也能调的设置。
  4. ta.ema() 是内置技术分析函数。
  5. plot() 画线;fill() 给两条线之间填色。

核心概念

概念 干什么的
indicator() 画一个研究(不交易)
strategy() 回测进出场
input.* 用户可配参数
ta.* 内置 TA 库(RSI、ATR、MACD
[] 运算符 引用过去 K 线值:close[1] 是前一根收盘
:= 重新赋值变量
= 初始化变量

策略示例:EMA 交叉

indicator(...) 换成 strategy(...) 就能回测:

//@version=5
strategy("EMA Cross", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 10)

fast = ta.ema(close, 20)
slow = ta.ema(close, 50)

longCondition = ta.crossover(fast, slow)
if longCondition
    strategy.entry("Long", strategy.long)

shortCondition = ta.crossunder(fast, slow)
if shortCondition
    strategy.entry("Short", strategy.short)

Add to chart,再点 Strategy Tester 标签看交易、权益曲线和指标。

该知道的局限

  • 脚本逐 K 线跑;你不能在 K 线之间暂停或等待。
  • 变量作用域严格——var 初始化一次,varip 每次实时更新初始化。
  • 免费版不能建私有脚本,部分类别函数超过 40 个受限。
  • Pine 策略回测默认在下一根 K 线开盘成交——用 process_orders_on_close = true 要谨慎。

学习路径

  1. 读官方 Pine Script v5 Reference——每个函数都带例子。
  2. 重造一个内置指标(RSI、MACD)学惯用法。
  3. 给它套个策略壳,看权益曲线。
  4. 然后才把你的主观 setup 转成代码。

常见坑

  • if 块里 plot 会藏信号——先算逻辑再画。
  • 硬编码长度而不是用 input.* 会让你没法优化。
  • strategy() 里忽略手续费和滑点会让回测结果虚高。

下篇:把 Pine Script 策略配上正经的回测方法学,让权益曲线可信。

相关市场数据由 TradingView 提供。

分享:
𝕏 f in r/
·
📝

我的笔记

登录后可在本文保存笔记并与社区分享。

✓ 已核查事实 审阅人 Timi Chen, 编辑顾问 · 发布于: 2026-06-04 · 编辑政策
由 Marcus Cole 起草 · 由 Timi Chen 于 2026-06-04 审核 · 最后检查于 2026-06-04

教育内容 · 非财务建议 · 风险自担

下一篇推荐

platformstools 2026-07-01

TradingView Chart Setup Best Practices

Configure TradingView for fast decision-making with multi-timeframe layouts, indicator templates, watchlists, and alert rules that survive restarts.

阅读更多 →

Smart Recommendations