The request.security() Value T... Note

The request.security() Value That Isn't There Yet

When a strategy profits in backtesting but loses live, slippage is often blamed, but a specific cause in Pine Script's request.security() function should be checked first. This issue, documented by TradingView, concerns how higher timeframe data is used. By default, request.security() uses barmerge.lookahead_off, preventing future data leaks. However, setting lookahead=barmerge.lookahead_on to avoid a perceived one-bar lag introduces a critical flaw.This setting allows historical backfills to incorporate data not yet available in live trading. For instance, a strategy comparing current price to a higher timeframe's close will use the future close in backtesting for intraday bars. Live, this future data isn't present, leading to discrepancies.The problem is insidious because it's hard to spot live. During real-time trading, both lookahead_on and lookahead_off series show the same values, as no future data exists. Yet, once a real-time bar closes and becomes historical, it "repaints," recalculating with the full historical record, diverging from what was observed live. This means a seemingly working live session can completely change when the chart is reloaded.A related variant occurs when request.security() is used for timeframes at or below the chart's own resolution. The lookahead setting then determines which intrabar's value is returned, potentially creating a mismatch between backtest and live execution. To diagnose this, script users should examine all request.security() calls for "lookahead_on." If found, verify an explicit historical offset is applied.Additionally, confirm the intrabar selection for same or lower timeframe requests. A direct symptom of repainting is if values on recently closed bars change after a script reload. This crucial distinction between historically available data and what's knowable live is vital for reliable strategy performance.