用 AI 写 Pine Script:TradingView 自动交易教学
你不会写程序,但想用 TradingView 的 Pine Script(也就是 TradingView 内置的脚本语言)自动交易?现在不用从零学语法——用 AI prompt 就能产出可回测、能发 webhook(也就是自动传信号的网址)的策略。关键不在写 code,而在「怎么问」。
本文带你走一遍完整路径:用 AI 产生第一支 Pine 指标 → 转成 strategy 回测 → 加 alert 发信号 → 接 webhook 到 TVSBot 自动下单。每个阶段都有可直接拷贝的 prompt,改个参数就能换策略。
为什么「会问 AI」比「会写 Pine」更重要
Pine Script(TradingView 内置的脚本语言)语法简单到一个程度:声明变量用 =、画图用 plot()、条件判断用 if。但真正卡住新手的不是语法,是不知道要写什么逻辑才能赚钱——这才是 AI 切入的时机。
你给 AI 的 prompt 越具体,产出的代码越可用。本文每个步骤的 prompt 都已经过验证,直接贴进 ChatGPT、Claude 或其他 AI 工具就能跑。
不过要先讲清楚一件事:AI 不会替你决定交易逻辑。它只能把你的想法转成代码。如果你的策略本身有问题,AI 产出的就是「能跑但赔钱」的代码——这点跟传统写 code 一模一样。
第一步:用 AI prompt 产生第一支 Pine 指标
打开 TradingView → 下方点 Pine Editor → New → Blank Indicator。如果你还不熟悉 Pine Script 的语法,可以先看我们的 Pine Script 入门教学 再回来。在 AI 工具里粘贴这段 prompt:
请用 Pine Script v6 写一支 RSI 指标。
需求:
1. 使用 input.int 让用户可以调整 RSI 周期(预设 14)、超买值(预设 70)、超卖值(预设 30)
2. 画出 RSI 线,在超买超卖区间加水平线
3. overlay=false,画在下方面板AI 会回传一段类似这样的代码:
//@version=6
indicator("RSI 指标", overlay=false)
length = input.int(14, "RSI 周期")
oversold = input.int(30, "超卖值")
overbought = input.int(70, "超买值")
rsiValue = ta.rsi(close, length)
plot(rsiValue, "RSI", color=color.purple)
hline(overbought, "超买", color=color.red)
hline(oversold, "超卖", color=color.green)按 Save → Add to chart,你就看到 RSI 出现在图表下方。这支指标现在可以回测、也可以发 alert——但还不能自动交易,因为它不是 strategy。
第二步:把指标转成 strategy(能回测的那种)
indicator 和 strategy 只差在第一行:indicator() 改成 strategy(),然后多几个参数。但更重要的是,strategy 多了下单函数,让 TradingView 自动帮你算回测结果。
以下是 strategy 独有的函数与它们的用途:
| 函数 | 用途 | 在 indicator 里 |
|---|---|---|
| strategy.entry() | 开仓(多/空) | 不存在 |
| strategy.exit() | 出场(止损/止盈) | 不存在 |
| strategy.close() | 平仓 | 不存在 |
| plotshape() | 画信号标记 | 可用 |
Pine Script v6 策略函数速查,2026-10-20 查证
indicator 没有这些函数,所以即使你加上 alert() 发 webhook,也无法在 TradingView 内置的回测工具里看到绩效。strategy 则会自动计算净利、胜率、最大回撤等所有指标。
回到 AI prompt,改成这样:
请用 Pine Script v6 写一支 RSI 反转策略。
需求:
1. 使用 strategy() 声明,initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10
2. 当 RSI 从 30 以下穿到上面时做多;从 70 以上穿到下面时平仓
3. 加上 plotshape 画出进场和平仓的三角形标记
4. commission_type = strategy.commission.percent, commission_value = 0.1(每次交易收 0.1%)
5. overlay=true,RSI 画在下方面板产出的代码会长这样:
//@version=6
strategy("RSI 反转策略", overlay=true,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=10,
commission_type=strategy.commission.percent,
commission_value=0.1)
// === 参数 ===
length = input.int(14, "RSI 周期")
oversold = input.int(30, "超卖值")
overbought = input.int(70, "超买值")// === 计算 ===
rsiValue = ta.rsi(close, length)
// === 信号 ===
longCondition = ta.crossover(rsiValue, oversold)
shortCondition = ta.crossunder(rsiValue, overbought)
// === 下单 ===
if longCondition
strategy.entry("Long", strategy.long)
if shortCondition
strategy.close("Long")
// === 视觉 ===
plot(rsiValue, "RSI", color=color.purple, display=display.pane)
hline(oversold, "超卖", color=color.green)
hline(overbought, "超买", color=color.red)
plotshape(longCondition, "进场", shape.triangleup,
location.belowbar, color=color.green, size=size.small)
plotshape(shortCondition, "平仓", shape.triangledown,
location.abovebar, color=color.red, size=size.small)存盘后点图表右上角的 策略测试器,就能看到历史回测结果——净利、胜率、最大回撤。
when= 参数从 strategy.entry() 拿掉了。旧版写法 strategy.entry("Buy", strategy.long, when=condition) 在 v6 会编译失败。正确写法是把 if condition 包在外面(上面的代码已经示范)。第三步:加上止损与仓位大小控制
上面的策略有一个问题:每次固定用 10% 资金,不管波动率多大。专业交易者会用 ATR(平均真实波幅)来动态计算仓位大小——波动大就缩小仓位,波动小就放大。
ATR 是 TradingView 内置的指标函数,ta.atr(14) 回传过去 14 根 K 棒的平均真实波幅。把它乘以一个倍数(比如 2.0),就是止损距离。
把 prompt 改成这样:
请在上面的 RSI 策略中加入 ATR 止损和动态仓位大小:
1. 加入 input.float("ATR 倍数", minval=0.5, maxval=5.0) 预设 2.0
2. 加入 input.float("风险百分比", minval=0.1, maxval=5.0) 预设 1.0
3. 止损距离 = ATR × ATR 倍数
4. 仓位大小 = 账户权益 × 风险百分比 / 止损距离
5. 加上 strategy.exit() 设置止损这段逻辑的代码:
// === ATR 止损 + 动态仓位 ===
atrLength = input.int(14, "ATR 周期")
atrMult = input.float(2.0, "ATR 倍数", minval=0.5, maxval=5.0)
riskPct = input.float(1.0, "风险百分比 %", minval=0.1, maxval=5.0)
atrValue = ta.atr(atrLength)
if longCondition and atrValue > 0
stopDistance = atrValue * atrMult
riskAmount = strategy.equity * (riskPct / 100)
qty = riskAmount / stopDistance
strategy.entry("Long", strategy.long, qty=qty)
strategy.exit("Long SL", "Long", stop=strategy.position_avg_price - stopDistance)这里的数学很直观:你愿意亏 riskPct 的账户金额,除以止损距离(ATR × 倍数),就是该买多少。ATR 越大(市场越乱),仓位越小——这是一套完整的风险管理。
| 参数 | 建议值 | 说明 |
|---|---|---|
| RSI 周期 | 14 | 标准值,适合大多数市场 |
| 超卖/超买 | 30/70 | 经典门槛,趋势市可调到 20/80 |
| ATR 倍数 | 1.5–2.5 | 越大小止损越宽,但也会放进更多亏损 |
| 风险百分比 | 0.5–2.0 | 每笔交易不超过账户的 2% 是业界常见守则 |
RSI + ATR 策略参数建议范围,2026-10-20 查证
第四步:让策略发 webhook 信号
回测漂亮只是第一步。要把信号送到交易所自动下单,需要在 Pine 代码里加上 alert() 或 strategy.entry() 的 alert_message 参数。这里的关键是 API(也就是 Application Programming Interface,应用程序界面)——TradingView 透过它把信号传给 TVSBot。
两种做法:
// 方式 A:strategy.entry 带 alert_message(推荐,因为只在进场时发信号)
if longCondition
strategy.entry("Long", strategy.long, qty=qty)
strategy.exit("Long SL", "Long", stop=stopLossPrice)
alert('{"action":"buy","symbol":"' + syminfo.ticker + '",'
+ '"exchange":"binance"}', alert.freq_once_per_bar_close)这里的关键是 alert_message 里的 JSON——TradingView 会把这段文字 POST 到你的 webhook URL。如果用 strategy.entry() 的 alert_message 参数,消息内容会在 Alert 设置时的 {{strategy.order.alert_message}} 占位符里自动带出去。
方式 B 则是在 TradingView 的 Alert 对话框里手动填 JSON:
{
"action": "{{strategy.order.action}}",
"symbol": "{{ticker}}",
"price": {{close}},
"exchange": "binance"
}两种方式效果一样,差别在于:方式 A 的 JSON 写在代码里,换策略时一起改;方式 B 的 JSON 在 Alert 设置画面,不用动到 Pine 代码。
alert() 函数控制的是代码内的频率(alert.freq_once_per_bar_close),而 Alert 对话框的 Frequency 下拉菜单是另一套字面(Once only、Once per bar、Once per bar close、Once per minute or every time)。两者不共用,设置时要看清楚你在调的是哪一个。第五步:在 TradingView 创建 Alert + Webhook
代码写好后,到 TradingView 图表右上角点铃铛 → Create Alert:如果你想知道更详细的 webhook 设置步骤(包含 JSON 格式、错误排除),可以先看我们的 TradingView Webhook 完整教学。
代码写好后,到 TradingView 图表右上角点铃铛 → Create Alert:
- 1选 Condition如果是 indicator,选你设置的 alertcondition;如果是 strategy,选 "Any alert() function call"。
- 2设置 Frequency自动交易强烈建议选 <Code>Once Per Bar Close</Code>,避免 K 棒收盘前信号消失造成假信号。
- 3切到 Notifications 分页勾选 <Code>Webhook URL</Code>,粘贴你的 TVSBot webhook 网址。
- 4填 Message如果代码用了方式 A(alert_message),这里留空或填 <Code>{{strategy.order.alert_message}}</Code>。如果用方式 B,贴入 JSON。
最后点 Test 测试一下——TradingView 会模拟触发一次,你可以在 TVSBot 的 webhook log 看到回传。
| 方式 A(代码内置) | 方式 B(Alert 手动填) | |
|---|---|---|
| JSON 位置 | Pine 代码 | TradingView Alert 对话框 |
| 换策略时 | 改代码即可 | 不用改 JSON,但每次要重贴 |
| 推荐时机 | 固定策略、长期使用 | 快速测试、不确定策略前 |
Webhook 信号两种写法比较
第六步:接 TVSBot 自动下单
TVSBot 的工作流程很直:你注册 → 贴交易所 API key(也就是应用程序界面的密钥,让不同软件之间能沟通)(只开 Trade 权限,禁止 Withdraw)→ 创建 strategy 拿到 webhook URL → 贴到 TradingView Alert。整个过程大约 5 分钟。
具体步骤如下:
| 步骤 | 做什么 | 时间 |
|---|---|---|
| 1 | 在 TVSBot 注册账号 | 1 分钟 |
| 2 | 绑定交易所 API key(只读 + 交易,禁止提领) | 3–5 分钟 |
| 3 | 创建 strategy 拿到专属 webhook URL | 1 分钟 |
| 4 | 回到 TradingView 粘贴 webhook URL + JSON | 1 分钟 |
| 5 | 用 Dry-run 模式测试 | 实时 |
TVSBot 串接流程与时间估算
API key 的权限设置是整个自动交易最关键的一环。无论你用哪间交易所,原则都是:
- ✓ 开 Trade / Spot 权限
- ✓ 禁 Withdraw(提领)
- '禁 IP 白名单(如果交易所支持)'
- ✓ 打开 2FA
TVSBot 支持 Binance、OKX、Bybit、Bitget、Gate.io、BingX 和 Hyperliquid DEX,全部走 ccxt 统一抽象层。每间交易所的 API key 格式不同,但权限原则一样——能下单但不能提钱。
200,这个请求会被取消。所以你的 webhook 接收端(或是像 TVSBot 这种中介服务)必须在收到信号后立刻回 200,实际下单动作交给背景处理。第七步:前向测试(forward test)再做实盘
回测再漂亮也不代表实盘会赚钱——历史数据有延迟、滑价、手续费偏差等各种变因。最保险的做法是先用 TVSBot 的 Dry-run 模式跑一段时间,确认信号链完整无误再考虑上实盘。
Dry-run 是 TVSBot 内置的功能:策略会正常接收 TradingView 的 webhook 信号,运行完整的决策逻辑(包括风控、每日上限检查),但实际上下单时只是模拟成交,不会真的送单到交易所。TVSBot 官方写「Dry-run sandbox: Validate webhook + risk wiring with virtual capital before going live」。
测试期间检查三件事:
常见问题
免费的 TradingView 方案可以用 webhook 吗?
Pine Script v5 和 v6 差很多吗?
AI 产出的代码可以直接用在实盘吗?
同一个策略可以同时接多家交易所吗?
Webhook 没反应怎么办?
我该用 indicator 还是 strategy?
Get started
把 AI 生好的 Pine Script 策略带过来,webhook 到交易所这段交给 TVSBot——用你自己的 API key,先 dry-run,风控自己设。
免费开始使用