One of the most powerful yet misunderstood features in Pine Script—TradingView’s proprietary language—is the security() function. It allows traders and developers to pull data from different symbols, timeframes, or even conditions not directly visible on the current chart. However, improper use can lead to repainting, misleading signals, and inaccurate backtests.
In this comprehensive guide, we’ll dive deep into the critical parameters of the security() function: lookahead, gaps, and how to correctly fetch lower timeframe data on higher timeframes. Whether you're building custom indicators or automated strategies, understanding these concepts is essential for reliable results.
Understanding the security() Function
At its core, the security() function enables you to request data from a different symbol or timeframe:
security(syminfo.tickerid, "D", close)This line fetches the daily close price while your chart might be on a 1-hour basis.
But behind this simple syntax lies complexity—especially when dealing with real-time behavior, historical accuracy, and repainting risks.
Key Parameter 1: lookahead
The lookahead parameter controls whether future data is allowed in the calculation. By default, it's set to barmerge.lookahead_on, which can cause repainting—a major pitfall in strategy development.
Why Repainting Is Dangerous
Repainting occurs when an indicator uses future data to generate past signals. On a live chart, this means a signal appears before the conditions that trigger it actually occur—making backtest results unreliable.
To prevent this:
security(syminfo.tickerid, "D", close, lookahead=barmerge.lookahead_off)✅ Best Practice: Always disable lookahead in live strategies and backtests unless you have a specific reason (e.g., educational visualization).
👉 Discover how professional traders avoid repainting with clean Pine Script logic
Key Parameter 2: gaps (Gap Handling)
The gaps argument determines how missing data points are handled across non-trading periods (like weekends or after-hours). The two main options are:
gaps=barmerge.gaps_on: Fills gaps with interpolated values.gaps=barmerge.gaps_off: Preserves gaps, showing no data during closed markets.
For futures or crypto (which trade 24/7), turning gaps off ensures continuity. For stocks or forex, you may want gaps on to reflect real market closures.
Example:
dailyClose = security("AAPL", "D", close, gaps=barmerge.gaps_off)This preserves Apple’s actual trading days without artificial fills.
Fetching Lower Timeframes on Higher Timeframes
A common challenge: Can you access 5-minute data while on a daily chart?
Yes—but with caveats.
When pulling smaller timeframe data (e.g., 15min) into a larger timeframe (e.g., daily), each daily bar only updates once per day. So if you try to get real-time 15-minute prices inside a daily calculation, you’ll see stale or delayed data.
Solution: Use request.security_lower_tf()
Introduced in Pine Script v5, this function safely retrieves multiple lower-timeframe bars per higher-timeframe bar:
fiveMinCloses = request.security_lower_tf("AAPL", "5", close)This returns an array of all 5-minute closing prices within the current daily bar (if available).
⚠️ Note: This only works when the higher timeframe contains complete lower timeframe bars. Real-time partial bars may not be fully accessible.
Practical Example: Multi-Timeframe EMA Strategy
Let’s build a simple strategy that uses a fast EMA from a lower timeframe to enter trades on a higher one.
//@version=5
strategy("Multi-TF EMA Crossover", overlay=true)
// Input: Fast EMA period on lower timeframe
fastLength = input.int(9, "Fast EMA Length")
// Get 15-minute closes
lowerTF = request.security_lower_tf(syminfo.tickerid, "15", close)
// Only proceed if we have data
if not na(lowerTF)
// Calculate EMA on lower TF data
emaFast = ta.ema(array.get(lowerTF, array.size(lowerTF) - 1), fastLength)
// Plot on chart
plot(emaFast, color=color.blue, title="15min EMA on Daily")This approach lets you react faster to short-term momentum shifts without sacrificing your primary high-timeframe bias.
👉 Learn how top quant developers structure robust multi-timeframe logic
Common Pitfalls & Best Practices
| Issue | Solution |
|---|---|
| Signals appear before they should | Set lookahead=barmerge.lookahead_off |
| Missing weekend data for stocks | Use gaps=barmerge.gaps_on |
| Cannot access intraday data on daily charts | Use request.security_lower_tf() |
| Data mismatch between strategy and chart | Ensure consistent timezone and session settings |
Always test your script in bar-by-bar replay mode to verify signal timing and eliminate repainting.
Frequently Asked Questions (FAQ)
Q: What is repainting in Pine Script?
Repainting happens when an indicator or strategy uses future data to generate past signals. This makes performance look better than it really is. Disabling lookahead and avoiding forward-looking functions prevents this issue.
Q: Can I pull tick or minute-level data on monthly charts?
Directly? No. But using request.security_lower_tf(), you can access lower-TF data as long as the higher timeframe bar hasn’t closed. Once the monthly bar ends, all intra-month data becomes available retroactively.
Q: Is security() the same as request.security()?
Yes—but request.security() is the newer, preferred syntax in Pine Script v4 and v5. Older scripts use security(), which remains supported for backward compatibility.
Q: How do I avoid errors when switching symbols?
Always wrap cross-symbol requests in proper error handling:
data = request.security("BINANCE:BTCUSDT", "D", close, ignore_invalid_symbol=true)Setting ignore_invalid_symbol=true prevents crashes if the symbol doesn’t exist on the selected exchange.
Q: Does lookahead affect all users equally?
No. If you publish a script with lookahead=on, other users may see different results depending on their broker integration and data feed. For public scripts, always default to lookahead_off.
Final Thoughts: Build Smarter Indicators
Mastering the security() function—and its advanced siblings like request.security() and request.security_lower_tf()—is a milestone in any Pine Script developer’s journey. With proper configuration of lookahead, gaps, and cross-timeframe logic, you can create sophisticated, reliable tools that stand up to real-world trading conditions.
Whether you're analyzing Bitcoin on multiple timeframes or building a stock scanner with intermarket filters, these techniques form the backbone of professional-grade TradingView scripts.
👉 Access powerful trading tools to test your Pine Script strategies in real market environments
By combining precise data fetching with clean coding practices, you ensure your indicators don’t just look good—they perform well when it matters most.