开发者指南
5 分钟写你的第一个策略
从零开始,用 Pine Script 编写一个双均线交叉策略,并在 A 股数据上运行回测。
第 1 步:打开脚本编辑器
在应用主界面底部,点击「脚本编辑器」面板标签,或使用快捷键 Ctrl+E 打开编辑器。
第 2 步:编写指标脚本
先从一个简单指标开始,熟悉语法:
我的第一个指标
//@version=5 indicator("我的双均线", overlay=true) // 计算快慢均线 fast = ta.sma(close, 5) slow = ta.sma(close, 20) // 绘制到图表上 plot(fast, "快线", color=color.blue, linewidth=2) plot(slow, "慢线", color=color.red, linewidth=2) // 标记金叉和死叉 if ta.crossover(fast, slow) label.new(bar_index, low, "金叉", color=color.green) if ta.crossunder(fast, slow) label.new(bar_index, high, "死叉", color=color.red)
//@version=5 声明 Pine Script 版本。indicator() 声明这是一个指标脚本,overlay=true 表示叠加在主图上。第 3 步:转换为策略脚本
把 indicator() 改为 strategy(),加入买卖逻辑:
双均线交叉策略
//@version=5 strategy("双均线策略", overlay=true) fast = ta.sma(close, 5) slow = ta.sma(close, 20) plot(fast, "快线", color=color.blue) plot(slow, "慢线", color=color.red) // 金叉买入 if ta.crossover(fast, slow) strategy.entry("做多", strategy.long) // 死叉卖出 if ta.crossunder(fast, slow) strategy.close("做多")
第 4 步:运行回测
点击编辑器上方的「运行」按钮。脚本会在当前图表的 K 线数据上执行,自动生成回测报告。 你会看到买卖点标记、权益曲线、以及详细的绩效指标(胜率、夏普比率、最大回撤等)。
观潮回测引擎与 TradingView Broker Emulator 语义一致 —— 从社区复制的策略可以直接运行,回测口径可与 TradingView 直接对照。
第 5 步:添加止盈止损
带止盈止损的完整策略
//@version=5 strategy("均线策略 + 止盈止损", overlay=true) fast = ta.sma(close, 5) slow = ta.sma(close, 20) if ta.crossover(fast, slow) strategy.entry("做多", strategy.long) // 止盈 8%,止损 3% strategy.exit("止盈止损", "做多", profit=close * 0.08, loss=close * 0.03) if ta.crossunder(fast, slow) strategy.close("做多")
下一步
恭喜!你已经写出了一个可运行的量化策略。接下来可以: