Other Timeframes and Data in Pine Script

·

When developing trading strategies or technical indicators on TradingView, accessing data beyond your current chart’s context is often essential. Pine Script® empowers developers with a suite of powerful request.*() functions that allow seamless retrieval of data from alternative symbols, timeframes, financial reports, and even external repositories. Whether you're analyzing multi-timeframe trends, comparing cross-asset correlations, or integrating economic data into your strategy, understanding these tools is key to building robust and insightful scripts.

This guide dives deep into the request.* namespace, covering core functions like request.security(), request.security_lower_tf(), request.financial(), and more. We’ll explore their parameters, behaviors, and best practices — all while maintaining clean, efficient, and forward-compatible code.


Core Functions for Data Retrieval

Pine Script’s request.* family enables flexible data fetching across multiple contexts. These include:

👉 Discover how to integrate real-time market data into your strategies

Each function follows a consistent design pattern but serves a specialized purpose. Together, they form the backbone of advanced Pine Script development.


Common Characteristics Across Request Functions

Despite their varied use cases, all request.*() functions share several behavioral traits and parameters.

Behavior and Execution Model

Every request.*() call fetches data from a defined context — typically a symbol and timeframe — then evaluates an expression over that dataset. For example:

float dailySlope = request.security("AMEX:SPY", "1D", ta.linreg(hl2, 20, 0) - ta.linreg(hl2, 20, 1))

This line retrieves daily hl2 prices for SPY and calculates the slope of a 20-period linear regression. The first two arguments define the context; the third defines the computation.

Functions like request.financial() restrict context definition internally since they serve specific purposes — such as pulling quarterly earnings — so you don’t specify timeframes directly.

A script can make up to 40 unique requests. Repeated calls with identical arguments reuse cached results, improving performance without redundant network fetches.

Managing Gaps in Series Data

The gaps parameter controls how missing values are handled when requesting data from other timeframes. Two options exist:

For instance, when fetching hourly closes on a 1-minute chart:

Using plot.style_linebr visually highlights gaps by breaking lines at na points.

Handling Invalid Symbols Gracefully

Set ignore_invalid_symbol = true to prevent runtime errors when requesting non-existent tickers or invalid financial fields. Instead of crashing, the function returns na, allowing safe fallback logic.

This is especially useful when estimating metrics like market cap:

float tso = request.financial(tickerID, "TOTAL_SHARES_OUTSTANDING", "FQ", ignore_invalid_symbol = true)

If the symbol lacks financials (e.g., forex pairs), the script continues instead of failing.

Currency Conversion Made Easy

Use the currency parameter to convert returned values into a target currency. For example:

request.security("TSLA", "1D", close, currency = currency.EUR)

This returns Tesla’s closing price in Euros, converted using the previous day’s EUR/USD rate from major exchanges.

👉 Learn how to analyze global markets with cross-currency insights


Advanced Features: Dynamic Requests

Starting in Pine Script v6, all request.*() calls are dynamic by default — meaning they can adapt during execution based on changing inputs.

Using Series Arguments

Dynamic requests allow series-type arguments for symbol and timeframe, enabling runtime switching:

string symbolSeries = switch int(bar_index / 5) % 4
    => "AMEX:SPY"
    => "NASDAQ:MSFT"
    => "NASDAQ:AMD"
    => "NASDAQ:INTC"

float price = request.security(symbolSeries, timeframe.period, close)

This cycles through four stocks every five bars. Without dynamic requests enabled (dynamic_requests = false), this would cause a compile error.

⚠️ Important: All required datasets must be accessed during historical processing. Realtime bars cannot initiate new data requests.

Local Scope Execution

Dynamic requests can run inside conditionals, loops, and functions:

for symbol in symbols
    float vol = request.security("OANDA:" + symbol, timeframe.period, volume)
    requestedData.push(vol)

This loop fetches volume from multiple forex pairs. However, the expression cannot depend on loop variables — doing so triggers a compilation error.

Nested and Library-Based Requests

You can nest request.security() calls. If one request uses another’s result in its expression, it inherits the outer context — unless dynamic requests are disabled.

Libraries can export functions containing request.*() calls, enabling reusable cross-context logic across scripts.


Working with Different Timeframes

Accessing higher or lower timeframes expands analytical depth significantly.

Higher Timeframe Analysis

Fetching HTF data helps identify trend direction or filter noise:

float htfPrice = request.security(syminfo.tickerid, "240", hl2[1], lookahead = barmerge.lookahead_on)

To avoid repainting:

Lower Timeframe Insights

While request.security() can access LTF data, it only returns one intrabar per chart bar. For full intrabar detail, use:

array ltfData = request.security_lower_tf(syminfo.tickerid, "5", close)

This returns an array of all 5-minute closes within each chart bar — ideal for volume profiling or microstructure analysis.


Retrieving Diverse Data Types

request.security() supports rich data types beyond simple prices:

For example, retrieve both correlation signals and price rank in one call:

[rnk, crossoverSignal] = request.security(syminfo.tickerid, "240", [rank, ta.crossover(rank, 50)])

This reduces request count and improves efficiency.


Data Feed Considerations

Be aware that:

Also note: Requested series align to the chart’s time axis, so non-overlapping symbols (like BTCUSD on SPY chart) will show gaps.


Frequently Asked Questions

Q: What happens if I exceed 40 unique requests?
A: The script will fail to compile. Optimize by reusing expressions and avoiding redundant calls.

Q: Can I use request.security() inside a loop?
A: Yes — if dynamic requests are enabled. But the expression cannot reference loop variables directly.

Q: How do I avoid repainting with HTF data?
A: Combine lookahead = barmerge.lookahead_on with [1] offset in your expression to use confirmed prior values.

Q: Why does my LTF request return fewer bars than expected?
A: Intrabar limits depend on your TradingView plan and calc_bars_count. Free accounts have lower caps.

Q: Is request.financial() available for crypto assets?
A: No — it only works with equities that publish financial statements.

Q: Can I fetch live forex rates between any two currencies?
A: Use request.currency_rate("USD", "JPY") for daily conversion rates derived from major exchange pairs.


👉 Start building smarter trading algorithms today