The security function is one of Pine Script’s most powerful tools, enabling developers to fetch data from different symbols and timeframes within a single script. This capability is fundamental for creating complex multi-timeframe indicators, comparing performance across instruments, or implementing intricate trading strategies that react to conditions on charts other than the one currently displayed. However, despite its utility, security is frequently a source of confusion and frustration when it doesn’t behave as expected. If you’ve encountered issues with your security calls, you’re not alone. This article delves into the common pitfalls and provides practical debugging strategies to get your scripts running smoothly.
Introduction to the security Function in Pine Script
At its core, the security function allows you to request the value of a variable from a symbol and timeframe different from the one the script is currently running on. This breaks the limitation of accessing data only from the chart’s current context, opening up a vast array of possibilities for analysis and strategy development.
Purpose and Basic Syntax of security
The primary purpose is to retrieve ‘foreign’ data – data from a different chart context. The basic syntax looks like this:
[returned_data] = security(symbol, timeframe, source)
symbol: A string specifying the ticker symbol (e.g.,"BTCUSD","NASDAQ:AAPL"). Usesyminfo.tickeridfor the current symbol.timeframe: A string specifying the timeframe (e.g.,"D"for daily,"60"for 60 minutes,"W"for weekly). Usetimeframe.periodfor the current timeframe.source: The variable or expression from which you want to fetch data (e.g.,close,ta.sma(close, 20),volume).
The function returns the value of source corresponding to the symbol and timeframe requested. It’s crucial to understand that security aligns the foreign data to the current chart’s bars, interpolating or extrapolating as needed. This alignment process is often the source of issues.
Common Use Cases: Fetching Data from Different Timeframes/Symbols
The power of security becomes evident in typical use cases:
- Multi-Timeframe Analysis: Displaying a higher timeframe moving average on a lower timeframe chart.
pine
htf_ma = security(syminfo.tickerid, "W", ta.sma(close, 20))
plot(htf_ma, color=color.blue, title="Weekly MA on Current Chart")
- Cross-Symbol Comparison: Fetching the close price of a related asset.
pine
spy_close = security("AMEX:SPY", timeframe.period, close)
plot(spy_close, color=color.purple, title="SPY Close")
- Complex Strategy Conditions: Using indicators calculated on a different timeframe as entry/exit signals.
pine
htf_rsi = security(syminfo.tickerid, "4H", ta.rsi(close, 14))
long_condition = htf_rsi < 30 and ta.crossover(close, ta.sma(close, 50))
// ... strategy implementation
When these basic applications fail, it’s time to troubleshoot.
Common Reasons Why the security Function Might Not Be Working
Several factors can prevent security from returning valid data or behaving as expected.
Incorrect Symbol or Timeframe Specification
A frequent cause of security failure is simply requesting data using incorrect or unsupported strings for the symbol or timeframe arguments.
- Case Sensitivity: Symbol tickers are generally case-sensitive. Ensure you use the correct case (e.g.,
"BTCUSD"is not the same as"btcusd"). Usingsyminfo.tickeridfor the current symbol is the safest approach. - Exchange Prefix: Many symbols require an exchange prefix (e.g.,
"NASDAQ:AAPL","CME_TI1:CL1!"). If you omit it or use the wrong one,securitywon’t find the symbol. - Timeframe Format: Timeframe strings must adhere to Pine Script’s expected formats (
"1","5","60","D","W","M"). Custom timeframes or incorrect syntax will fail. - Unsupported Pairs/Timeframes: Not all symbols are available on all timeframes across all exchanges supported by TradingView. A less common pair might not have historical data on a very granular timeframe, or vice-versa.
Data Availability and Exchange Restrictions
Even with correct syntax, data might not be available for the requested combination.
- Historical Depth: The exchange or data provider might not have historical data reaching back as far as your chart for the requested symbol/timeframe.
securitycan only fetch data that TradingView’s backend has access to. - Symbol Delisting or Name Changes: If a symbol has been delisted or undergone a name change, historical data might be unavailable or accessible only under the old ticker.
- Exchange-Specific Data: Some data, like pre-market or post-market information, might be specific to certain exchanges or data feeds and not uniformly available via
securityfor all symbols.
Requesting Data Outside of TradingView’s Data Range
TradingView charts display a finite amount of historical data. While security can sometimes access slightly more data than is currently loaded on the chart, it is fundamentally limited by the total historical data available on the platform for that specific symbol and timeframe.
If your script requests data from a point in time or a total historical depth that TradingView does not provide for the foreign security, the security call will return na values for those periods.
Rate Limiting and Data Request Limits
While less common with modern Pine Script versions and TradingView infrastructure, excessive or improperly managed security calls could theoretically lead to performance issues or temporary data request throttling. This is more likely if you are requesting data from a very large number of different securities within a single script, though typical use cases involving a few security calls are usually fine.
Troubleshooting and Debugging Strategies
When security isn’t working, a systematic approach to debugging is essential.
Checking for Errors in the Pine Editor Console
The first step is always to check the Pine Editor console (at the bottom of the editor). Pine Script compiler and runtime errors related to security will often appear here.
- Compilation Errors: Errors like
Could not find symbol ...orInvalid timeframe ...indicate issues with your symbol or timeframe string inputs. - Runtime Errors: Errors might appear if data lookup fails during script execution, although
securityoften returnsnasilently instead of crashing.
Verifying Symbol and Timeframe Inputs
Double-check the strings you are passing to the symbol and timeframe arguments.
- If using user inputs (
input.symbol,input.timeframe), verify the values selected in the script’s settings panel. Users might select unsupported combinations. - Temporarily replace variables with hardcoded, known-working strings (e.g.,
security("BINANCE:BTCUSDT", "D", close)) to see if the issue lies with how your inputs are being generated or passed.
Using na (Not Available) Checks to Identify Data Issues
When security cannot retrieve data for a specific bar (often due to data gaps, the foreign bar not existing at that point relative to the current bar, or hitting data limits), it returns na. You can use na checks to detect this.
foreign_data = security(symbol, timeframe, source)
// Check if data is available
if na(foreign_data)
label.new(bar_index, high, "No data from security", color=color.red)
// Use nz() to treat na as 0 or some other default value
valid_foreign_data = nz(foreign_data, 0)
plot(valid_foreign_data)
Plotting the output of security directly, potentially with na checks highlighted, can visually show where data is missing.
Simplifying the Script to Isolate the Problem
If security is part of a complex script, create a minimal test script that only contains the security call you suspect is failing. Plot its output directly.
// Minimal test script
// Define the potentially problematic security call
test_symbol = "AMEX:SPY"
test_timeframe = "W"
test_source = close
security_output = security(test_symbol, test_timeframe, test_source)
// Plot the raw output to see where it's na or unexpected
plot(security_output, title="Security Test Output")
// Optionally, plot the nz() version
// plot(nz(security_output), title="Security Test Output (nz)")
// Add a label to indicate na bars
if na(security_output)
label.new(bar_index, high, "NA", yloc=yloc.below_bar, color=color.yellow)
This helps confirm whether the security call itself is the issue or if the problem lies in how you are using the returned data within your larger script logic.
Advanced Considerations and Limitations
Working with security requires understanding its nuances, especially regarding data alignment and script execution.
Repainting and Lookahead Bias with security
One of the most critical issues with security is the potential for repainting and lookahead bias. By default, security uses lookahead=barmerge.lookahead_on. This means that when requesting data from a higher timeframe, the value returned by security for the current lower timeframe bar will be the final value of the higher timeframe bar once it closes. On historical bars, this works correctly, as the higher timeframe bar has already closed. However, on the real-time bar (the very last bar), the higher timeframe bar might still be forming. If your security call returns the current, incomplete value of the higher timeframe source, and this value changes as the higher timeframe bar develops, your indicator or strategy will appear to change its past signals on the lower timeframe – this is repainting.
Using lookahead=barmerge.lookahead_off tells security to only use data that was available at the close of the corresponding higher timeframe bar. This prevents lookahead bias and repainting in real-time but can cause plots to appear to ‘step’ or lag behind the current price on the lowest timeframes.
// Example: Potential repainting issue with lookahead_on (default)
htf_value_on = security(syminfo.tickerid, "15", close)
plot(htf_value_on, color=color.green, title="HTF Close (lookahead_on)") // Can repaint!
// Safer: Prevent repainting with lookahead_off
htf_value_off = security(syminfo.tickerid, "15", close[1], lookahead=barmerge.lookahead_off)
plot(htf_value_off, color=color.red, title="HTF Close (lookahead_off)") // Safer, but lags by 1 bar
Note the use of close[1] with lookahead=barmerge.lookahead_off. This is a common pattern to get the closed value of the higher timeframe bar aligned to the current bar. Understanding and managing repainting is paramount for reliable script performance, especially in strategies.
Impact of security on Script Performance and Execution Time
Each security call involves fetching and processing data from a potentially different chart context. Multiple security calls, especially to different symbols or very granular timeframes with long history, can increase script execution time and potentially impact performance.
- Optimize Calls: Request only the data you truly need. Avoid redundant
securitycalls for the same symbol/timeframe/source. - Complexity: Scripts with many
securitycalls might approach Pine Script’s resource limits.
Alternative Approaches for Data Retrieval
In some cases, security might not be the only or best tool:
- Built-in Functions: Many common multi-timeframe calculations (like higher timeframe moving averages) can sometimes be achieved more efficiently or safely using built-in functions designed for that purpose, if available.
- Avoid Cross-TF: Re-evaluate if cross-timeframe analysis is strictly necessary for your objective. Can the same trading logic be implemented purely on the current chart’s timeframe data?
Best Practices for Using the security Function Effectively
To minimize issues and write robust scripts using security:
Optimizing Data Requests to Minimize Errors
- Use
barmerge.gaps_offorbarmerge.gaps_onappropriately in thesecuritycall (the default isbarmerge.gaps_off, which interpolates). Understand how these modes affect data alignment, especially when the foreign timeframe’s bars don’t align perfectly with the current timeframe’s bars. - Request only the minimum necessary data points (e.g.,
source[1]if you only need the previous bar’s value).
Error Handling and Data Validation Techniques
- Always check for
navalues returned bysecurity. Wrap dependent calculations withif na(foreign_data)...or usenz(). - Consider adding checks for the validity of user inputs (
input.symbol,input.timeframe) if they could lead to unsupportedsecuritycalls.
Staying Updated with TradingView’s Pine Script Documentation and Updates
Pine Script is continuously evolving. Reading the official documentation on security is crucial, as are the release notes for new Pine Script versions. Changes to data handling, function behavior, or the introduction of new features can impact how security works or how you should use it.
By understanding the security function’s purpose, common failure points, and employing rigorous debugging and best practices, you can leverage its power effectively and build more sophisticated and reliable trading tools in Pine Script.