pinescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pine Script Development

Pine Script 开发

Verify before implementing: For Pine Script version-specific syntax or new built-in functions, look up current docs via Context7 (
query-docs
) before writing code. TradingView updates Pine Script frequently and training data may be stale.
实施前验证:针对Pine Script特定版本的语法或新内置函数,编写代码前请通过Context7(
query-docs
)查阅最新文档。TradingView会频繁更新Pine Script,训练数据可能已过时。

Critical Syntax Rules

关键语法规则

  • Ternary operators MUST stay on one line -- splitting across lines causes "end of line without line continuation" error. For complex ternaries, use intermediate variables:
    isBull = close > open
    barColor = isBull ? color.green : color.red
  • Continuation lines MUST be indented MORE than the starting line -- same indentation = error
  • NEVER use plot() inside local scopes (if/for/functions) -- use conditional value instead:
    plot(condition ? value : na)
  • barstate.isconfirmed -- use to prevent repainting on real-time bars
  • 三元运算符必须保持在同一行——跨行拆分会导致“未使用行延续符的行结束”错误。对于复杂的三元表达式,请使用中间变量:
    isBull = close > open
    barColor = isBull ? color.green : color.red
  • 续行必须比起始行缩进更多——相同缩进会引发错误
  • 切勿在局部作用域内使用plot()(if/for/函数中)——改用条件值:
    plot(condition ? value : na)
  • barstate.isconfirmed——用于防止实时K线出现重绘

Platform Limits

平台限制

500 bars history for
request.security()
| 500 plot calls | 64 drawing objects | 40
request.security()
calls | 100KB compiled size
request.security()
的500根K线历史记录 | 500次plot调用 | 64个绘图对象 | 40次
request.security()
调用 | 100KB编译后大小

Performance

性能优化

  • Tuple security calls -- one
    request.security()
    returning
    [close, high, low]
    instead of 3 separate calls
  • Pre-allocate arrays with
    array.new<type>(size)
    instead of push-and-resize
  • Short-circuit signals: build conditions incrementally, exit early when first condition fails
  • Cache repeated calculations in variables -- Pine recalculates every bar
  • 元组式security调用——一次
    request.security()
    返回
    [close, high, low]
    ,而非3次单独调用
  • 使用
    array.new<type>(size)
    预分配数组,而非边推送边调整大小
  • 短路信号:逐步构建条件,当首个条件不满足时提前退出
  • 将重复计算结果缓存到变量中——Pine会在每根K线重新计算

Debugging

调试方法

TradingView has no console or debugger. Use these patterns:
  • Label debugging:
    label.new(bar_index, high, str.tostring(myVar))
    to inspect values
  • Table monitor:
    table.new()
    with
    barstate.islast
    for real-time variable dashboard
  • Debug mode toggle: wrap all debug code in
    if input.bool("Debug", false)
    -- remove before publishing
  • Repainting detector: track
    previousValue = value[1]
    , flag when historical values change
TradingView没有控制台或调试器,请使用以下模式:
  • 标签调试
    label.new(bar_index, high, str.tostring(myVar))
    用于查看变量值
  • 表格监控:结合
    barstate.islast
    使用
    table.new()
    创建实时变量仪表盘
  • 调试模式开关:将所有调试代码包裹在
    if input.bool("Debug", false)
    中——发布前移除
  • 重绘检测器:跟踪
    previousValue = value[1]
    ,当历史值变化时标记

Strategy & Backtesting

策略与回测

  • Use
    strategy.*
    functions:
    strategy.wintrades
    ,
    strategy.losstrades
    ,
    strategy.grossprofit
  • Drawdown tracking:
    maxEquity = math.max(strategy.equity, nz(maxEquity[1]))
    , then
    dd = (maxEquity - strategy.equity) / maxEquity * 100
  • Sharpe:
    dailyReturn * 252 / (stdDev * math.sqrt(252))
  • Walk-forward validation -- optimize on period 1, test on period 2, re-optimize on period 2, test on period 3. If metrics degrade > 30%, parameters are overfit.
  • Indicator accuracy testing -- use forward-looking
    close[lookforward]
    to measure prediction accuracy, track true/false positive rates
  • 使用
    strategy.*
    函数:
    strategy.wintrades
    strategy.losstrades
    strategy.grossprofit
  • 回撤跟踪:
    maxEquity = math.max(strategy.equity, nz(maxEquity[1]))
    ,然后计算
    dd = (maxEquity - strategy.equity) / maxEquity * 100
  • 夏普比率:
    dailyReturn * 252 / (stdDev * math.sqrt(252))
  • 滚动向前验证——在周期1上优化参数,在周期2上测试;在周期2上重新优化,在周期3上测试。若指标下降超过30%,说明参数过拟合。
  • 指标准确性测试——使用前瞻性的
    close[lookforward]
    衡量预测准确性,跟踪真阳性/假阳性率

Visualization

可视化技巧

  • color.from_gradient()
    for trend strength coloring
  • Adaptive text sizing:
    size.small
    for intraday,
    size.normal
    for daily+
  • Dynamic table rows -- resize based on enabled features via input toggles
  • Professional color constants: define BULL_COLOR, BEAR_COLOR, NEUTRAL_COLOR once with transparency
  • 使用
    color.from_gradient()
    实现趋势强度着色
  • 自适应文本大小:日内图表用
    size.small
    ,日线及以上用
    size.normal
  • 动态表格行——通过输入开关根据启用的功能调整大小
  • 专业颜色常量:一次性定义BULL_COLOR、BEAR_COLOR、NEUTRAL_COLOR并设置透明度

Publishing

发布规范

  • Documentation goes at TOP of .pine file as comments before
    indicator()
    /
    strategy()
  • Use
    @version
    ,
    @description
    ,
    @param
    tags
  • Multi-line tooltips:
    tooltip="Line 1" + "\n" + "Line 2"
  • TradingView House Rules: no financial advice, no performance guarantees, no external links, no obfuscated code, no donation requests
  • 文档需放在.pine文件顶部,作为
    indicator()
    /
    strategy()
    之前的注释
  • 使用
    @version
    @description
    @param
    标签
  • 多行提示框:
    tooltip="Line 1" + "\n" + "Line 2"
  • TradingView社区规则:不得提供金融建议、不得做出业绩保证、不得包含外部链接、不得使用混淆代码、不得请求捐赠

Common Coding Mistakes

常见编码错误

  • Indicator stacking (RSI + Stochastics + CCI) -- all measure the same thing (momentum). Use indicators from different categories instead.
  • Overfitting parameters: if optimal values are oddly specific (RSI 23 instead of 20), the backtest is curve-fitted. Use round numbers and
    input()
    with sensible defaults.
  • Missing
    barstate.isconfirmed
    guard -- calculations on unconfirmed bars cause repainting. Always guard entry signals.
  • Hardcoded thresholds without
    input()
    -- makes the script untestable across instruments.
  • 指标堆叠(RSI + 随机指标 + CCI)——这些指标都衡量同一类事物(动量)。应改用不同类别的指标。
  • 参数过拟合:若最优值异常具体(如RSI设为23而非20),说明回测存在曲线拟合问题。请使用整数,并为
    input()
    设置合理默认值。
  • 缺少
    barstate.isconfirmed
    防护——在未确认的K线上进行计算会导致重绘。务必为入场信号添加防护。
  • 未使用
    input()
    而硬编码阈值——会导致脚本无法跨品种测试。

Workflow

工作流程

  1. Write indicator/strategy in Pine Editor
  2. Test with bar replay and strategy tester on multiple timeframes
  3. Walk-forward validate before trusting backtest results (see Strategy & Backtesting above)
  4. Verify: run on 3+ symbols and 2+ timeframes
  1. 在Pine编辑器中编写指标/策略
  2. 使用K线回放和策略测试器在多个时间周期上测试
  3. 信任回测结果前进行滚动向前验证(参见上文“策略与回测”部分)
  4. 验证:在3个以上品种、2个以上时间周期上运行脚本

Verify

验证清单

  • Indicator compiles without errors on TradingView
  • No repainting:
    barstate.isconfirmed
    guard present where needed
  • Walk-forward tested on 3+ symbols across different timeframes
  • 指标在TradingView上编译无错误
  • 无重绘问题:必要位置已添加
    barstate.isconfirmed
    防护
  • 已在3个以上不同时间周期的品种上完成滚动向前验证