Skip to main content

Libraries, UDTs & Advanced Architecture

Creating and using libraries, user-defined types, methods, tables for dashboards, the speed profiler, debugging techniques, error messages, and Pine limitations.

How PineScript Libraries Work

PineScript libraries let you package reusable functions and share them across scripts. A library is a special script type declared with library() instead of indicator() or strategy(). Functions you want to share must be prefixed with export. Other scripts import them using the import statement. Libraries solve the biggest maintenance headache in PineScript, instead of copying the same ATR trailing stop code into 15 scripts, you write it once in a library and import it everywhere.

pine-Creating and using a library
1// === LIBRARY FILE (publish as "RiskLib") ===
2//@version=5
3// @description Risk management utility functions for crypto trading
4library("RiskLib")
5
6// @function Calculate position size from risk percentage
7// @param equity Current account equity
8// @param riskPct Risk percentage (1.0 = 1%)
9// @param entryPrice Entry price
10// @param stopPrice Stop loss price
11// @returns Position size in base currency units
12export positionSize(float equity, float riskPct, float entryPrice,
13 float stopPrice) =>
14 riskAmount = equity * riskPct / 100
15 stopDist = math.abs(entryPrice - stopPrice)
16 stopDist > 0 ? riskAmount / stopDist : 0
17
18// @function Calculate reward-to-risk ratio
19// @param entry Entry price
20// @param stop Stop loss price
21// @param target Take profit price
22// @returns R:R ratio as float
23export rewardToRisk(float entry, float stop, float target) =>
24 risk = math.abs(entry - stop)
25 reward = math.abs(target - entry)
26 risk > 0 ? reward / risk : 0
27
28// === STRATEGY FILE (imports the library) ===
29//@version=5
30strategy("Strategy Using RiskLib", overlay=true,
31 initial_capital=10000, default_qty_type=strategy.fixed)
32
33import YourUsername/RiskLib/1 as risk
34
35atr = ta.atr(14)
36entryPrice = close
37stopPrice = close - atr * 2
38targetPrice = close + atr * 3
39
40qty = risk.positionSize(strategy.equity, 1.0, entryPrice, stopPrice)
41rr = risk.rewardToRisk(entryPrice, stopPrice, targetPrice)
42
43if ta.crossover(ta.ema(close, 9), ta.ema(close, 21)) and rr > 1.5
44 strategy.entry("Long", strategy.long, qty=qty)
45 strategy.exit("TP/SL", "Long", limit=targetPrice, stop=stopPrice)
export keywordOnly functions marked with export are accessible by importing scripts. Internal helper functions without export stay private to the library.
import statementFormat: import Username/LibraryName/version as alias. The version number increments each time you publish an update. Importing scripts pin to a specific version.
VersioningEach publish creates a new version (1, 2, 3...). Scripts that import version 1 keep using version 1 even if you publish version 5. They must manually update the import to get new code.
LimitationsLibraries cannot plot, create alerts, or use strategy functions. They can only export pure functions and user-defined types. All visual and trading logic stays in the importing script.

Finding Useful Community Libraries

TradingView hosts thousands of community-published libraries. To find them, go to the Pine Editor → Open → Libraries tab. You can search by functionality (e.g., "risk management," "statistics," "drawing"). Some high-quality libraries include math/statistics packages (correlation, regression, z-scores), drawing utilities (automatic support/resistance, trend lines), and data structure helpers (matrix operations, linked lists). Always read the source code before importing: libraries execute with the same permissions as your script.

1

Search the library directory

In the Pine Editor, click the folder icon → "Open" → filter by "Libraries." Browse by popularity, recency, or search by keyword. Read the description and documentation comments before importing.
2

Read the source code

Click on any library to view its full source. Check the exported functions, their parameters, and the documentation comments. Understand what the library does before using it.
3

Import and use

Copy the import statement from the library's page. Paste it at the top of your script. Use the alias to call exported functions: alias.functionName(args).

User-Defined Types (UDTs)

User-Defined Types (UDTs) let you create custom data structures, like structs in C or classes in Python. Instead of managing 6 separate variables for a trade (entry price, stop, target, direction, size, timestamp), you bundle them into a single Trade type. UDTs make complex scripts dramatically cleaner and are essential for building multi-signal or multi-position systems.

pine-User-defined types with methods
1//@version=5
2indicator("UDT Demo", overlay=true)
3
4// === DEFINE A TRADE TYPE ===
5type Trade
6 float entryPrice
7 float stopPrice
8 float targetPrice
9 string direction // "long" or "short"
10 int entryBar
11 bool isActive
12
13// === METHOD: calculate R:R ===
14method riskReward(Trade t) =>
15 risk = math.abs(t.entryPrice - t.stopPrice)
16 reward = math.abs(t.targetPrice - t.entryPrice)
17 risk > 0 ? reward / risk : 0.0
18
19// === METHOD: check if stop hit ===
20method isStopHit(Trade t) =>
21 t.direction == "long" ? low <= t.stopPrice : high >= t.stopPrice
22
23// === METHOD: check if target hit ===
24method isTargetHit(Trade t) =>
25 t.direction == "long" ? high >= t.targetPrice : low <= t.targetPrice
26
27// === USAGE ===
28var Trade currentTrade = na
29atr = ta.atr(14)
30
31if ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
32 currentTrade := Trade.new(
33 close,
34 close - atr * 2,
35 close + atr * 3,
36 "long",
37 bar_index,
38 true)
39
40// Check exits
41if not na(currentTrade) and currentTrade.isActive
42 if currentTrade.isStopHit()
43 currentTrade.isActive := false
44 label.new(bar_index, low, "SL Hit", style=label.style_label_up,
45 color=color.red, textcolor=color.white)
46 else if currentTrade.isTargetHit()
47 currentTrade.isActive := false
48 label.new(bar_index, high, "TP Hit\nR:R=" +
49 str.tostring(currentTrade.riskReward(), "#.#"),
50 style=label.style_label_down,
51 color=color.green, textcolor=color.white)

Tables for Complex Dashboards

PineScript tables allow you to display structured data in a fixed panel on the chart. Tables are pinned to a corner (top-left, top-right, bottom-left, bottom-right, or middle) and do not scroll with price. This is perfect for building multi-column dashboards showing cross-timeframe data, portfolio summaries, risk metrics, or market scanners.

pine-Multi-column market dashboard
1//@version=5
2indicator("Market Dashboard", overlay=true)
3
4// === FETCH MULTI-TIMEFRAME DATA ===
5[d_close, d_rsi, d_vol] = request.security(syminfo.tickerid, "D",
6 [close[1], ta.rsi(close, 14)[1], volume[1]],
7 lookahead=barmerge.lookahead_on)
8
9[w_close, w_rsi] = request.security(syminfo.tickerid, "W",
10 [close[1], ta.rsi(close, 14)[1]],
11 lookahead=barmerge.lookahead_on)
12
13ema21 = ta.ema(close, 21)
14ema50 = ta.ema(close, 50)
15atr = ta.atr(14)
16
17// === BUILD TABLE ===
18var table dash = table.new(position.top_right, 3, 7,
19 bgcolor=color.new(#1a1a2e, 10),
20 border_color=color.new(color.gray, 70),
21 border_width=1)
22
23if barstate.islast
24 // Header
25 table.cell(dash, 0, 0, "Metric", text_color=#5ce1e6,
26 text_size=size.small, text_halign=text.align_left)
27 table.cell(dash, 1, 0, "Daily", text_color=#5ce1e6, text_size=size.small)
28 table.cell(dash, 2, 0, "Weekly", text_color=#5ce1e6, text_size=size.small)
29
30 // RSI
31 table.cell(dash, 0, 1, "RSI(14)", text_color=color.white, text_size=size.small)
32 table.cell(dash, 1, 1, str.tostring(d_rsi, "#.#"),
33 text_color=d_rsi > 70 ? color.red : d_rsi < 30 ? color.green : color.white,
34 text_size=size.small)
35 table.cell(dash, 2, 1, str.tostring(w_rsi, "#.#"),
36 text_color=w_rsi > 70 ? color.red : w_rsi < 30 ? color.green : color.white,
37 text_size=size.small)
38
39 // Trend
40 dTrend = d_close > ema50 ? "BULL" : "BEAR"
41 table.cell(dash, 0, 2, "Trend", text_color=color.white, text_size=size.small)
42 table.cell(dash, 1, 2, dTrend,
43 text_color=dTrend == "BULL" ? color.green : color.red,
44 text_size=size.small)
45 table.cell(dash, 2, 2, w_close > ema50 ? "BULL" : "BEAR",
46 text_color=w_close > ema50 ? color.green : color.red,
47 text_size=size.small)
48
49 // ATR
50 table.cell(dash, 0, 3, "ATR(14)", text_color=color.white, text_size=size.small)
51 table.cell(dash, 1, 3, str.tostring(atr, "#.##"), text_color=color.white,
52 text_size=size.small)
53 table.cell(dash, 2, 3, "-", text_color=color.gray, text_size=size.small)
54
55 // ATR %
56 atrPct = atr / close * 100
57 table.cell(dash, 0, 4, "ATR %", text_color=color.white, text_size=size.small)
58 table.cell(dash, 1, 4, str.tostring(atrPct, "#.##") + "%",
59 text_color=atrPct > 5 ? color.orange : color.white,
60 text_size=size.small)
61 table.cell(dash, 2, 4, "-", text_color=color.gray, text_size=size.small)

The Speed Profiler Tool

Complex PineScript indicators can become slow, especially with multiple request.security() calls, large arrays, or nested loops. TradingView provides a built-in speed profiler that shows execution time per line. To enable it, click the three-dot menu in the Pine Editor and select "Show Performance." Each line shows its execution time in microseconds. Lines highlighted in red are performance bottlenecks.

request.security()The most expensive function. Each call adds significant overhead. Use tuple returns to minimize the number of calls. Aim for fewer than 20 per script.
Loops (for)Loops over large arrays or many iterations are slow. PineScript has a 500ms execution time limit per bar. If your loop processes 10,000 elements, it will timeout.
String operationsString concatenation inside loops is expensive. Build strings outside loops when possible, or use arrays to collect values and join at the end.
table.cell()Table rendering is slow when called on every bar. Wrap table updates in if barstate.islast to only render on the most recent bar.
label/line creationCreating labels or lines on every bar and deleting old ones is expensive. Use var to persist objects and update them instead of recreating.

Debugging PineScript Code

PineScript has no debugger, no breakpoints, and no console.log. Debugging requires creative use of plot(), label.new(), bgcolor(), and log.info(). These are your printf-debugging tools. The key is to make invisible values visible so you can verify your logic.

pine-Debugging techniques
1//@version=5
2indicator("Debug Techniques", overlay=true)
3
4ema9 = ta.ema(close, 9)
5ema21 = ta.ema(close, 21)
6rsi = ta.rsi(close, 14)
7
8// TECHNIQUE 1: Plot intermediate values in a separate pane
9// Uncomment and set overlay=false to debug
10// plot(rsi, "RSI Debug")
11// hline(30) ; hline(70)
12
13// TECHNIQUE 2: bgcolor to verify conditions
14bullCondition = ta.crossover(ema9, ema21) and rsi > 50
15bgcolor(bullCondition ? color.new(color.green, 80) : na)
16
17// TECHNIQUE 3: Labels with variable values
18if bullCondition
19 label.new(bar_index, high,
20 "RSI: " + str.tostring(rsi, "#.#") +
21 "\nEMA9: " + str.tostring(ema9, "#.##") +
22 "\nEMA21: " + str.tostring(ema21, "#.##"),
23 style=label.style_label_down, color=color.green,
24 textcolor=color.white, size=size.tiny)
25
26// TECHNIQUE 4: log.info(), check Pine Logs panel
27log.info("Bar {0}: close={1}, rsi={2}, bull={3}",
28 bar_index, close, rsi, bullCondition)
29
30// TECHNIQUE 5: Plotshape for boolean verification
31plotshape(bullCondition, "Bull Signal", shape.circle,
32 location.abovebar, color.green, size=size.tiny)

Common Error Messages and Fixes

PineScript error messages are generally helpful, but some are cryptic to beginners. Here are the most common errors and exactly how to fix them:

Script has too many local scopesYou have too many if/for/while blocks nested or in sequence. PineScript limits local scopes to ~500. Solution: refactor logic into functions or simplify conditionals with ternary operators.
Cannot call 'X' with series argumentFunctions like ta.sma() require the length parameter to be a "simple int": known at bar 0. Using input.int() works, but using a calculated series does not. Wrap dynamic lengths in ta.sma(close, math.max(1, fixedLen)) or use a switch statement.
Max bars backReferencing historical data too far back (e.g., close[1000]) exceeds the buffer. Use max_bars_back(close, 1000) at the top of your script to increase the buffer for that variable.
Loop takes too longYour for loop exceeded the 500ms time limit. Reduce iterations, move calculations outside the loop, or use built-in functions like ta.highest() instead of manual loops.
Cannot use 'strategy' in indicatorYou declared the script with indicator() but are trying to use strategy.entry(). Change the declaration to strategy() or remove the strategy functions.
Undeclared identifierYou referenced a variable that doesn't exist yet. PineScript is top-to-bottom. You cannot use a variable before defining it. Move the definition above its first use.

Pine Limitations and Workarounds

PineScript is powerful within its domain but has hard limits. Understanding these upfront saves hours of frustrated debugging when you hit a wall. Here are the key limitations and how experienced Pine coders work around them:

Plot Limit: 64

You can have at most 64 plot outputs per script. Workaround: use tables for data display instead of plots, or combine multiple signals into a single plot using color coding.

request.security() Limit: 40

Maximum 40 security calls per script. Workaround: use tuple returns to fetch multiple values per call. One call returning [open, high, low, close, volume] replaces 5 calls.

No Internet Access

PineScript cannot make HTTP requests, read files, or access external APIs. All external data must come through TradingView's data feeds or manual input. Workaround: use alerts with webhooks for outbound communication.

Execution Time: 500ms/bar

Each bar must process within 500ms. Complex loops and array operations can exceed this. Workaround: pre-calculate values, use built-in functions, and minimize loop iterations.

Max Bars Back: 5000 default

Historical referencing is limited. Workaround: use max_bars_back() annotation to increase for specific variables, up to the chart's total available history.

No Object-Oriented Programming

UDTs provide struct-like types but there is no inheritance, polymorphism, or encapsulation. Workaround: use composition, UDTs containing other UDTs, and methods for behavior.

String Limit: 4096 characters

Tooltip and label text is capped at 4096 characters. For large data displays, use tables instead of labels.

Optimization Techniques

When your script approaches execution limits, these techniques squeeze more performance out of PineScript:

pine-Performance optimization patterns
1//@version=5
2indicator("Optimized Patterns", overlay=true)
3
4// BAD: Recalculating EMA every time it's used
5// plot(ta.ema(close, 21))
6// bgcolor(close > ta.ema(close, 21) ? color.green : na) // Calculated TWICE
7
8// GOOD: Calculate once, reference many times
9ema21 = ta.ema(close, 21)
10plot(ema21)
11bgcolor(close > ema21 ? color.new(color.green, 90) : na)
12
13// BAD: Creating and deleting labels every bar
14// label.new(bar_index, high, "X") // Creates thousands of labels
15// if array.size(labelArray) > 50
16// label.delete(array.shift(labelArray))
17
18// GOOD: Use var to persist, update instead of recreate
19var label myLabel = label.new(na, na, "")
20if barstate.islast
21 label.set_xy(myLabel, bar_index, high)
22 label.set_text(myLabel, "Last: " + str.tostring(close))
23
24// BAD: String concatenation in a loop
25// result = ""
26// for i = 0 to 99
27// result := result + str.tostring(i) + "," // Slow: creates 100 string objects
28
29// GOOD: Use array and join
30strs = array.new_string(0)
31for i = 0 to 99
32 array.push(strs, str.tostring(i))
33result = array.join(strs, ",")
34
35// BAD: Multiple request.security() for same timeframe
36// d_close = request.security(syminfo.tickerid, "D", close)
37// d_open = request.security(syminfo.tickerid, "D", open)
38// d_high = request.security(syminfo.tickerid, "D", high)
39
40// GOOD: Tuple return, one call instead of three
41[d_close, d_open, d_high] = request.security(syminfo.tickerid, "D",
42 [close[1], open[1], high[1]], lookahead=barmerge.lookahead_on)

Graduation: Your PineScript Learning Path Complete

You have now covered the entire PineScript curriculum, from writing your first indicator() declaration to building risk-managed strategies with trailing stops, portfolio backtesting, webhook automation, libraries, and user-defined types. Here is a summary of what you have learned and where to go next:

Foundations

PineScript syntax, data types, variables, operators, control flow, functions, the execution model, and how bar-by-bar processing works.

Indicators

Building custom MA, RSI, MACD, ATR, and Bollinger Band indicators. Multi-timeframe analysis with request.security(). Plotting, coloring, shapes, and visual tools.

Candle Patterns

Detecting engulfing, pin bar, doji, inside bar, and custom patterns programmatically. Filtering patterns by context for higher probability setups.

Timeframes & Inputs

Multi-timeframe dashboards, security tuple optimization, input types, conditional logic across timeframes, and non-repainting MTF data.

Strategies

The strategy() function, entry/exit order management, position sizing, pyramiding, trailing stops, backtesting methodology, and automation via webhooks.

Advanced

Libraries for code reuse, user-defined types for clean architecture, tables for dashboards, performance optimization, debugging techniques, and Pine limitations.

The real learning starts now

Completing this curriculum makes you a competent PineScript developer. Becoming an expert requires building real tools for your own trading. Start by coding the strategy you actually trade manually. Convert your discretionary rules into PineScript logic. Backtest it. Break it. Fix it. Every bug you encounter and every limitation you work around deepens your understanding more than any tutorial. The TradingView Pine reference manual and community forums are your ongoing resources. Build, test, iterate.
Module Quiz

1.What is the key difference between 'strategy()' and 'indicator()' in PineScript?

2.In a PineScript strategy, what does 'strategy.entry("Long", strategy.long)' do?

3.Why should you NEVER blindly trust the PineScript Strategy Tester results?

4.What is the purpose of 'strategy.exit()' with 'profit' and 'loss' parameters?

5.How do PineScript libraries improve indicator and strategy development?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.