Wiki/Pine Script request.security(): Retrieving Multi-Timeframe Data
Pine Script request.security(): Retrieving Multi-Timeframe Data - Biturai Wiki Knowledge
ADVANCED | BITURAI KNOWLEDGE

Pine Script request.security(): Retrieving Multi-Timeframe Data

The request.security() function in Pine Script enables traders to access data from different symbols or timeframes than the one currently displayed on their chart. This capability is fundamental for conducting robust multi-timeframe

Biturai Knowledge
Biturai Knowledge
Research library
Updated: 7/2/2026
Technically checked

Structure, readability, internal linking, and SEO metadata were automatically checked. This article is continuously updated and is educational content, not financial advice.

Definition

The request.security() function in Pine Script is a powerful tool that allows scripts to retrieve data from a different symbol, timeframe, or context than the one the chart is currently displaying. This enables advanced analytical capabilities, particularly for multi-timeframe analysis, by fetching historical price data, indicator values, or custom calculations from alternative data streams. Instead of being limited to the chart's native timeframe, traders can integrate insights from daily, weekly, or even hourly charts into their minute-based strategies, creating a more holistic view of market dynamics. This function is a cornerstone for developing sophisticated trading indicators and strategies that require a broader market perspective.

The request.security() function in Pine Script is a core mechanism for fetching data from alternative market contexts, such as different symbols or timeframes, allowing for sophisticated multi-timeframe analysis within a single script.

This function is distinct from other data request functions like request.security_lower_tf(), which specifically retrieves intrabar data from a lower timeframe, or request.currency_rate(), which fetches daily currency conversion rates. request.security() offers broader utility, making it the primary choice for most cross-timeframe or cross-symbol data retrieval needs in Pine Script. It operates by essentially running a separate, hidden script on the requested data context and returning the result of an expression evaluated within that context. This allows for seamless integration of higher or lower timeframe information without altering the primary chart's display.

Key Takeaway

The primary utility of request.security() lies in its ability to facilitate comprehensive multi-timeframe analysis without requiring the user to manually switch chart timeframes. This leads to more informed and robust trading decisions by allowing strategies to consider broader market trends or higher-level support and resistance zones. When implemented correctly, request.security() is instrumental in preventing the common pitfall of repainting, ensuring that signals derived from higher timeframes are based on confirmed, historical data, thereby enhancing the reliability of algorithmic trading strategies. It empowers traders to build more resilient systems that account for market behavior across different temporal scales.

Its proper application transforms a single-timeframe strategy into a multi-dimensional analytical framework, enabling traders to align their short-term actions with long-term market narratives. This integration of different perspectives is often the difference between a reactive and a strategically proactive trading approach, providing a significant edge in volatile markets. By consolidating information from various timeframes, traders can confirm trends, identify divergences, and filter out noise that might be present on a single timeframe, leading to higher conviction trades and improved risk management.

Mechanics

The request.security() function operates by creating a separate data stream for the specified symbol and timeframe, on which it then evaluates a given expression. Its syntax is typically structured as request.security(symbol, timeframe, expression, gaps, lookahead). Understanding each parameter is vital for effective and error-free implementation.

  • symbol: This parameter defines the asset from which data should be retrieved. It can be the current chart's symbol, accessed via syminfo.tickerid, or a specific ticker string like "NASDAQ:NDX" or "EURUSD". Using syminfo.tickerid ensures the script dynamically adapts to the chart's current asset.
  • timeframe: This specifies the time resolution of the requested data, such as "1D" for daily, "1W" for weekly, "60" for hourly, or "15" for 15-minute data. It must be a string literal.
  • expression: This is the core of the function, representing the value or series of values to be calculated and returned from the requested context. It can be a simple price series like close, an indicator output like ta.sma(close, 20), or a complex custom calculation. The expression is evaluated on the symbol and timeframe specified.
  • gaps: A boolean parameter (default gaps = barmerge.gaps_off) that controls how gaps in the requested data are handled. If true (barmerge.gaps_on), the requested data will only be available on bars where it explicitly exists, leaving na (not available) for other bars. If false (barmerge.gaps_off), the last known value is carried forward, filling the gaps. For most multi-timeframe analysis, gaps = barmerge.gaps_on is preferred to avoid using stale data.
  • lookahead: A boolean parameter (default lookahead = barmerge.lookahead_off) that determines if the requested data can "look ahead" into future bars. If true (barmerge.lookahead_on), the function can return values that are not yet confirmed on the current bar, which can lead to repainting in real-time. For non-repainting strategies, lookahead = barmerge.lookahead_off is essential, ensuring only confirmed historical data is used.

The function returns a series of values corresponding to the expression evaluated on the specified symbol and timeframe. It's crucial to manage the gaps and lookahead parameters carefully to ensure the integrity and reliability of the data, especially in live trading scenarios. Incorrect usage of lookahead is a primary cause of repainting issues, where historical signals appear perfect but fail in real-time.

Trading Relevance

Multi-timeframe analysis is a cornerstone of robust trading strategies, and request.security() is the primary tool in Pine Script to implement it effectively. By integrating data from higher timeframes, traders can gain a clearer understanding of the overarching market trend, identify significant support and resistance levels, and confirm signals generated on their primary trading timeframe. For instance, a short-term strategy might generate a buy signal on a 15-minute chart, but if the daily trend is strongly bearish, request.security() can be used to fetch the daily trend direction, allowing the strategy to filter out counter-trend signals and avoid potentially losing trades. This approach significantly enhances the quality and reliability of trading signals.

Furthermore, request.security() enables the creation of sophisticated market regime filters. Traders can define market conditions (e.g., trending vs. ranging, bullish vs. bearish) based on higher timeframe indicators like moving averages or RSI, and then only execute trades on the lower timeframe when these conditions align. This prevents taking trades against the dominant market force, which is a common cause of losses. For example, a strategy could use request.security() to check if the weekly EMA is above the weekly price, indicating a bullish long-term trend, before considering any long entries on an hourly chart. This layered analysis provides a strategic advantage by aligning tactical entries with strategic market direction.

Risks

While request.security() is incredibly powerful, its improper use can introduce significant risks, primarily repainting and performance issues. Repainting occurs when an indicator or strategy's historical signals change as new data becomes available, making backtest results appear much better than real-time performance. This is often caused by setting lookahead = barmerge.lookahead_on or by using expressions that inherently look into the future without proper synchronization. To mitigate repainting, always ensure lookahead = barmerge.lookahead_off and understand how the expression parameter behaves across different timeframes.

Another significant risk is the potential for performance degradation. Each request.security() call creates a separate data stream, which consumes computational resources. Using too many request.security() calls, especially with very low timeframes or complex expressions, can slow down script execution and even lead to "too many security calls" errors on TradingView. To manage performance, minimize redundant calls, consider passing tuples to request.security() to fetch multiple values in a single call, and optimize the expression to be as efficient as possible. Additionally, be mindful of data synchronization; if the requested timeframe's bars do not align perfectly with the chart's timeframe, careful handling of na values and gaps is necessary to avoid misinterpretations.

History and Examples

The request.security() function has been a staple in Pine Script for many years, evolving to become more robust and efficient with each version. Its introduction revolutionized multi-timeframe analysis on TradingView, moving from complex workarounds to a streamlined, dedicated function. Early versions of Pine Script had more limitations, but request.security() in Pine Script v5 offers advanced features and better performance, allowing for more intricate multi-timeframe strategies.

A common and simple example is pulling the daily close price onto an intraday chart: pinescript //@version=5 indicator("Daily Close on Intraday Chart", overlay=true) daily_close = request.security(syminfo.tickerid, "1D", close) plot(daily_close, "Daily Close", color.blue, style=plot.style_linebr)

This snippet fetches the close price from the daily timeframe for the current symbol and plots it on any intraday chart. The style=plot.style_linebr ensures the daily value is held constant until the next daily bar closes.

A more advanced example involves multi-timeframe trend analysis, where a higher timeframe moving average is used to filter trades: pinescript //@version5 indicator("MTF Trend Filter Example", overlay=true) // User inputs for higher timeframe and EMA length higherTF = input.timeframe("1D", "Higher Timeframe") emaLength = input.int(20, "EMA Length")

// Get EMA from higher timeframe higherTF_ema = request.security(syminfo.tickerid, higherTF, ta.ema(close, emaLength)[barstate.isconfirmed ? 0 : 1], barmerge.gaps_on, barmerge.lookahead_off)

// Check if current price is above higher timeframe EMA isBullishHigherTF = close > higherTF_ema

// Plot higher timeframe EMA and background color for trend plot(higherTF_ema, "Higher TF EMA", color.purple, linewidth=2) bgcolor(isBullishHigherTF ? color.new(color.green, 90) : color.new(color.red, 90))

This example demonstrates how to fetch an EMA from a higher timeframe and use it to color the background, visually indicating the higher timeframe trend. The [barstate.isconfirmed ? 0 : 1] ensures that only confirmed historical data is used, preventing repainting.

Common Misunderstandings

One of the most frequent misunderstandings regarding request.security() is related to repainting. Many traders, especially beginners, are confused when their backtested strategies show perfect results, but fail miserably in live trading. This often stems from using lookahead = barmerge.lookahead_on (or omitting the lookahead parameter, which defaults to barmerge.lookahead_off but can be overridden by the expression itself if not careful) or by referencing future data within the expression without proper barstate checks. It's crucial to remember that for non-repainting behavior, lookahead should always be barmerge.lookahead_off, and any expression should only reference [1] (previous bar) or [0] (current bar, but only if barstate.isconfirmed is true for the requested timeframe's bar).

Another common issue is performance optimization. Users often make multiple request.security() calls for different data points from the same symbol and timeframe, unaware that this can be inefficient. Pine Script allows passing tuples as the expression parameter, enabling the retrieval of multiple values (e.g., [open, high, low, close]) in a single request.security() call, which significantly reduces resource consumption. For example, instead of daily_open = request.security(..., open) and daily_close = request.security(..., close), one can use [daily_open, daily_close] = request.security(..., [open, close]). Understanding the nuances of gaps and na values is also important; if gaps = barmerge.gaps_on, the requested data will be na on bars where the higher timeframe bar has not yet closed, requiring explicit na checks in the script.

Summary

The request.security() function is an indispensable tool in Pine Script for any trader or developer looking to implement sophisticated multi-timeframe analysis. It provides the flexibility to fetch data from any symbol or timeframe, enabling a holistic view of market dynamics that goes beyond the confines of a single chart. By understanding its parameters—symbol, timeframe, expression, gaps, and lookahead—users can harness its power to build robust, non-repainting indicators and strategies.

While offering immense capabilities, it's imperative to be aware of potential pitfalls such as repainting and performance issues. Adhering to best practices, such as setting lookahead = barmerge.lookahead_off, managing gaps appropriately, and optimizing calls by using tuples, ensures that request.security() is used effectively and reliably. When applied correctly, this function transforms basic trading ideas into advanced analytical frameworks, providing a significant edge in understanding and navigating complex market environments.

OKX · Official Biturai Partner

OKX

Explore the current OKX offering through the official Biturai partner link. Products and availability may vary by country.

Explore OKX

Partner link · Biturai may receive compensation when it is used · not investment advice

OKX

Disclaimer

This article is for informational purposes only. The content does not constitute financial advice, investment recommendation, or solicitation to buy or sell securities or cryptocurrencies. Biturai assumes no liability for the accuracy, completeness, or timeliness of the information. Investment decisions should always be made based on your own research and considering your personal financial situation.

Transparency

Biturai may use AI-assisted tools to research, structure, or update Wiki articles. Editorially reviewed articles are marked separately; all content remains educational and does not replace your own review.