pinescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePine Script Development
Pine Script 开发
Verify before implementing: For Pine Script version-specific syntax or new built-in functions, look up current docs via Context7 () before writing code. TradingView updates Pine Script frequently and training data may be stale.
query-docs实施前验证:针对Pine Script特定版本的语法或新内置函数,编写代码前请通过Context7()查阅最新文档。TradingView会频繁更新Pine Script,训练数据可能已过时。
query-docsCritical 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 | 500 plot calls | 64 drawing objects | 40 calls | 100KB compiled size
request.security()request.security()request.security()request.security()Performance
性能优化
- Tuple security calls -- one returning
request.security()instead of 3 separate calls[close, high, low] - Pre-allocate arrays with instead of push-and-resize
array.new<type>(size) - Short-circuit signals: build conditions incrementally, exit early when first condition fails
- Cache repeated calculations in variables -- Pine recalculates every bar
- 元组式security调用——一次返回
request.security(),而非3次单独调用[close, high, low] - 使用预分配数组,而非边推送边调整大小
array.new<type>(size) - 短路信号:逐步构建条件,当首个条件不满足时提前退出
- 将重复计算结果缓存到变量中——Pine会在每根K线重新计算
Debugging
调试方法
TradingView has no console or debugger. Use these patterns:
- Label debugging: to inspect values
label.new(bar_index, high, str.tostring(myVar)) - Table monitor: with
table.new()for real-time variable dashboardbarstate.islast - Debug mode toggle: wrap all debug code in -- remove before publishing
if input.bool("Debug", false) - Repainting detector: track , flag when historical values change
previousValue = value[1]
TradingView没有控制台或调试器,请使用以下模式:
- 标签调试:用于查看变量值
label.new(bar_index, high, str.tostring(myVar)) - 表格监控:结合使用
barstate.islast创建实时变量仪表盘table.new() - 调试模式开关:将所有调试代码包裹在中——发布前移除
if input.bool("Debug", false) - 重绘检测器:跟踪,当历史值变化时标记
previousValue = value[1]
Strategy & Backtesting
策略与回测
- Use functions:
strategy.*,strategy.wintrades,strategy.losstradesstrategy.grossprofit - Drawdown tracking: , then
maxEquity = math.max(strategy.equity, nz(maxEquity[1]))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 to measure prediction accuracy, track true/false positive rates
close[lookforward]
- 使用函数:
strategy.*、strategy.wintrades、strategy.losstradesstrategy.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
可视化技巧
- for trend strength coloring
color.from_gradient() - Adaptive text sizing: for intraday,
size.smallfor daily+size.normal - 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.smallsize.normal - 动态表格行——通过输入开关根据启用的功能调整大小
- 专业颜色常量:一次性定义BULL_COLOR、BEAR_COLOR、NEUTRAL_COLOR并设置透明度
Publishing
发布规范
- Documentation goes at TOP of .pine file as comments before /
indicator()strategy() - Use ,
@version,@descriptiontags@param - 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 with sensible defaults.
input() - Missing guard -- calculations on unconfirmed bars cause repainting. Always guard entry signals.
barstate.isconfirmed - Hardcoded thresholds without -- makes the script untestable across instruments.
input()
- 指标堆叠(RSI + 随机指标 + CCI)——这些指标都衡量同一类事物(动量)。应改用不同类别的指标。
- 参数过拟合:若最优值异常具体(如RSI设为23而非20),说明回测存在曲线拟合问题。请使用整数,并为设置合理默认值。
input() - 缺少防护——在未确认的K线上进行计算会导致重绘。务必为入场信号添加防护。
barstate.isconfirmed - 未使用而硬编码阈值——会导致脚本无法跨品种测试。
input()
Workflow
工作流程
- Write indicator/strategy in Pine Editor
- Test with bar replay and strategy tester on multiple timeframes
- Walk-forward validate before trusting backtest results (see Strategy & Backtesting above)
- Verify: run on 3+ symbols and 2+ timeframes
- 在Pine编辑器中编写指标/策略
- 使用K线回放和策略测试器在多个时间周期上测试
- 信任回测结果前进行滚动向前验证(参见上文“策略与回测”部分)
- 验证:在3个以上品种、2个以上时间周期上运行脚本
Verify
验证清单
- Indicator compiles without errors on TradingView
- No repainting: guard present where needed
barstate.isconfirmed - Walk-forward tested on 3+ symbols across different timeframes
- 指标在TradingView上编译无错误
- 无重绘问题:必要位置已添加防护
barstate.isconfirmed - 已在3个以上不同时间周期的品种上完成滚动向前验证