ia-pinescript
Pine Script v6: syntax, performance, error diagnosis, backtesting, visualization. Use when writing or debugging `.pine` files or TradingView Pine indicators/strategies.
Ilia Alshanetsky
@iliaal
Install
$ openclaw skills install @iliaal/compound-eng-pinescriptPine Script Development
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.
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 outside parentheses MUST be indented by a non-multiple of 4 -- same indentation as the start errors, and 4/8/12 spaces parse as a local block and error too (2 spaces is the conventional choice). Inside parentheses (function calls, parenthesized expressions) any indentation works, including multiples of 4
- 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
Platform Limits
500 bars history for request.security() | 500 plot calls | 64 drawing objects | 40 request.security() calls | 100KB compiled size
- Drawings positioned with
xloc.bar_indexreach at most 9,999 bars into the past and 500 into the future; for anything older, switch the drawing toxloc.bar_timeand pass a timestamp (a time value withoutxloc.bar_timeis treated as a future bar index and errors) - Cap drawing growth with a rolling buffer: push each new object into an array, then
line.delete(arr.shift())oncearr.size()exceeds the intended count -- otherwise the oldest drawings silently vanish at the 64-object limit
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
- Iterate collections with
for item in myArray(orfor [i, item] in myArray) instead offor i = 0 to array.size(...) - 1-- the indexed form re-evaluates the bound each pass and breaks when the loop mutates the array's size - Model related values as a user-defined type, not parallel arrays:
type Tradewithfloat entry,int startBar, plusmethodfunctions, stored in onearray<Trade>. Parallel arrays (entries,startBars, ...) desync on any missed push/remove and every operation must be repeated per array; one typed array keeps each object's fields together
Debugging
TradingView has no console or debugger. Use these patterns:
- Label debugging:
label.new(bar_index, high, str.tostring(myVar))to inspect values -- cap with the rolling-buffer pattern from Platform Limits, or older labels silently vanish at the 64-object limit - Table monitor:
table.new()withbarstate.islastfor 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
Strategy & Backtesting
- Use
strategy.*functions:strategy.wintrades,strategy.losstrades,strategy.grossprofit - Drawdown tracking:
maxEquity = math.max(strategy.equity, nz(maxEquity[1])), thendd = (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
Visualization
color.from_gradient()for trend strength coloring- Adaptive text sizing:
size.smallfor intraday,size.normalfor daily+ - Dynamic table rows -- resize based on enabled features via input toggles
input.*(..., active = condition)greys out an input when its controlling toggle is off (e.g. a smoothing length only editable while "Use smoothing" is checked) -- clearer than a tooltip saying "ignored unless..."- Professional color constants: define BULL_COLOR, BEAR_COLOR, NEUTRAL_COLOR once with transparency
Publishing
- Documentation goes at TOP of .pine file as comments before
indicator()/strategy() - Use
@version,@description,@paramtags - 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
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.isconfirmedguard -- calculations on unconfirmed bars cause repainting. Always guard entry signals. - Hardcoded thresholds without
input()-- makes the script untestable across instruments.
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
Verify
- Indicator compiles without errors on TradingView
- No repainting:
barstate.isconfirmedguard present where needed - Walk-forward tested on 3+ symbols across different timeframes
Top skills in this category
Skill Vetter
@spclaudehomeSecurity-first skill vetting for AI agents. Use before installing any skill from ClawdHub, GitHub, or other sources. Checks for red flags, permission scope, and suspicious patterns.
Github
@steipeteInteract with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Humanizer
@biostartechnologyRemove signs of AI-generated writing from text. Use when editing or reviewing text to make it sound more natural and human-written. Based on Wikipedia's comprehensive "Signs of AI writing" guide. Detects and fixes patterns including: inflated symbolism, promotional language, superficial -ing analyses, vague attributions, em dash overuse, rule of three, AI vocabulary words, negative parallelisms, and excessive conjunctive phrases.
Free Ride - Unlimited free AI
@shaivpidadiManages free AI models from OpenRouter for OpenClaw. Automatically ranks models by quality, configures fallbacks for rate-limit handling, and updates opencla...
Elite Longterm Memory
@nextfrontierbuildsUltimate AI agent memory system for Cursor, Claude, ChatGPT & Copilot. WAL protocol + vector search + git-notes + cloud backup. Never lose context again. Vibe-coding ready.