Guide

How to Fetch Data From Another Symbol in Pine Script

Correlations, spreads, and relative value analysis require data from multiple symbols. Here is exactly how request.security fetches data from different instruments and the patterns that make it work reliably.

•12 min read

Most Pine Script indicators operate on a single chart. You load the script on AAPL and the indicator calculates based on AAPL's price. But some of the most powerful indicators require data from elsewhere. A correlation indicator needs two symbols. A spread indicator needs the relationship between a pair. A relative strength comparison needs a benchmark index. All of these require fetching external data, and that is where request.security becomes essential.

This post covers the complete pattern for fetching data from other symbols in Pine Script, including the syntax, the common pitfalls, and the specific use cases where this technique delivers the most value.

The request.security function explained

The request.security() function is Pine Script's gateway to data outside the current chart. Its basic form takes a symbol identifier and a timeframe, then returns the requested data series. The function has evolved significantly in Pine Script v6, with the most important change being support for dynamic symbol requests.

The classic static form looks like this:

[ohlc4, volume] = request.security("AAPL", "D", [close, volume])

This fetches the close price and volume from Apple's daily chart and makes it available on whatever chart you are currently viewing. The returned values align to the current chart's timeframe, with the barmerge settings controlling how that alignment works.

The syntax for different use cases

Fetching a single value is straightforward. Fetching multiple values or handling more complex scenarios requires understanding the full syntax. The function accepts an array of data requests, a timeframe, and barmerge parameters that control how the data aligns.

// Fetch daily close from another symbol
otherClose = request.security("MSFT", "D", close)

// Fetch multiple values at once
[otherOpen, otherHigh, otherLow, otherClose] = 
  request.security("SPY", "D", [open, high, low, close])

// Fetch from a higher timeframe on an intraday chart
dailyHigh = request.security("BTCUSD", "D", high, 
  barmerge.lookahead_off, 
  barmerge.gaps_off)

The barmerge parameters are critical. barmerge.lookahead_off is almost always what you want because it prevents the repainting that occurs when you look ahead to future data. The combination of request.security with barmerge.lookahead_off is the foundation of every non-repainting multi-symbol indicator.

Building a correlation indicator

One of the most common applications is correlation analysis. You want to know whether two symbols move together or in opposite directions. The Pearson correlation coefficient ranges from -1 (perfect inverse) through 0 (unrelated) to +1 (perfectly correlated).

Pine Script v6 includes a built-in ta.correlation() function, but it works on two series on the same chart. For cross-symbol correlation, you fetch both series separately and then compute the correlation:

// Fetch daily closes from both symbols
stockA = request.security("AAPL", "D", close)
stockB = request.security("MSFT", "D", close)

// Calculate 20-day correlation
correlation = ta.correlation(stockA, stockB, 20)

// Plot with color gradient based on correlation strength
plot(correlation, color=color.new(#22c55e, 0), title="Correlation")

This pattern extends to any number of symbols. You can compare a stock against the sector ETF, a currency against a basket, or any relationship you want to measure. The key is using the same lookback period for both fetches so the values align correctly.

Building a spread indicator

Spread trading assumes two related instruments should maintain a roughly constant relationship. When they diverge, one is likely overvalued and the other undervalued. The spread is the difference between them, and you can build an indicator that shows when the spread reaches extreme levels.

// Fetch both legs of a pair
leg1 = request.security("EURUSD", "D", close)
leg2 = request.security("USDJPY", "D", close)

// Calculate the spread (different methods depending on your pair)
spread = leg1 - leg2  // Direct difference for linear pairs
// or
ratio = leg1 / leg2   // Ratio for multiplicative pairs

// Calculate a moving average of the spread
spreadMa = ta.sma(spread, 20)
deviation = spread - spreadMa
stdDev = ta.stdev(spread, 20)

// Upper and lower bands
upperBand = spreadMa + 2 * stdDev
lowerBand = spreadMa - 2 * stdDev

The spread indicator shows when the two legs are significantly far apart, which is often the setup for a mean reversion trade. The standard deviation bands give you concrete levels to watch, and the historical distribution tells you how often the spread reaches those extremes.

Relative strength comparison

Relative strength analysis compares a symbol's performance against a benchmark. You calculate the ratio of the symbol to the benchmark, and a rising ratio means the symbol is outperforming. This is the foundation of relative strength investing, and it is straightforward to build in Pine Script.

// Fetch the benchmark (SPY for US stocks, or a sector ETF)
benchmark = request.security("SPY", "D", close)

// Calculate relative strength ratio
rs = close / benchmark

// Plot it
plot(rs, title="Relative Strength", color=color.blue)

// Add a moving average to see the trend
rsMa = ta.sma(rs, 50)
plot(rsMa, title="RS MA", color=color.orange)

When the RS line is above its moving average, the symbol is outperforming the benchmark. When it is below, it is underperforming. This is a long-only filter used by many traders to focus on strength and avoid weakness.

Dynamic symbol requests in v6

Pine Script v6 introduced the ability to construct symbol identifiers dynamically. This means you can build an indicator that adapts to whatever symbol you load it on, fetching a related symbol automatically.

// In v6, you can use variables in symbol requests
ticker = syminfo.tickerid  // Current symbol
baseTicker = str.replace(ticker, "US", "USD")  // Modify as needed

// Or build from parts
dynamicSymbol = syminfo.prefix + ":" + "SPY"

// Fetch dynamically
benchmarkClose = request.security(dynamicSymbol, "D", close)

This opens the door to building reusable indicators that automatically fetch the right benchmark or related symbol based on what you are trading. A crude oil indicator could automatically fetch the inverse instrument. A stock indicator could fetch the relevant sector ETF. The logic is limited only by what symbol identifiers you can construct.

Common mistakes and how to avoid them

The most common mistake is using lookahead_on and getting repainted data. Always use barmerge.lookahead_off for any indicator that will be used for trading signals. The lookahead setting is there for analysis purposes but produces unreliable signals.

A second common mistake is timeframe mismatch. When you fetch daily data onto an intraday chart, the daily bars do not align one-to-one with the intraday bars. The barmerge.gaps_off setting fills the gaps with the last known daily value, which is usually what you want for continuous comparison.

A third mistake is not accounting for the warmup period. When you request daily data on an intraday chart, the first several days will have na values because the daily bar has not closed yet. You need to handle this with na checks just like any other multi-timeframe indicator.

Performance considerations

Each request.security call adds to the execution time. A script that fetches data from three different symbols will run roughly three times slower than one that operates only on the current chart. If you are building a scanner that checks 50 symbols, you need to be careful about how many security requests you make per symbol.

The solution is to request multiple values in a single call whenever possible. Instead of three separate calls for open, high, low, and close, request them all at once in an array. This is significantly faster than making separate calls for each price component.

Building cross-symbol indicators is one of the more advanced Pine Script applications, and it is exactly where an AI coding assistant saves the most time. The PineScripter generates the correct request.security calls with proper barmerge settings, handles the na warmup automatically, and builds the full indicator from your description. You get a working correlation, spread, or relative strength indicator in seconds rather than debugging the multi-symbol syntax for hours.


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.