HomePine Script Snippets › Higher Timeframe Filter

Pine Script Higher Timeframe Filter

Filters entries by higher-timeframe trend using request.security with [1] and lookahead_off — confirmed HTF data only, no repaint.

//@version=6
strategy("HTF Trend Filter", overlay=true, calc_on_every_tick=false)

// ── Inputs ──────────────────────────────────────────────
htf   = input.timeframe("60", "Higher Timeframe")
maLen = input.int(50, "HTF SMA Length", minval=1)

// ── Non-repainting HTF value ─────────────────────────────
// [1] + lookahead_off returns the last CONFIRMED HTF bar only.
htfMa = request.security(syminfo.tickerid, htf, ta.sma(close, maLen)[1],
     lookahead=barmerge.lookahead_off)

trendUp   = close > htfMa
trendDown = close < htfMa

// ── Entry logic (replace with your own conditions) ───────
longCondition  = ta.crossover(ta.ema(close, 9), ta.ema(close, 21)) and trendUp
shortCondition = ta.crossunder(ta.ema(close, 9), ta.ema(close, 21)) and trendDown

if longCondition
    strategy.entry("Long", strategy.long)
    strategy.exit("Long Exit", "Long", profit=20, loss=10)

if shortCondition
    strategy.entry("Short", strategy.short)
    strategy.exit("Short Exit", "Short", profit=20, loss=10)

// Visual
plot(htfMa, "HTF MA", color=color.new(color.orange, 0), linewidth=2)

Settings

How to use

Frequently Asked Questions

How do I add a higher timeframe filter in Pine Script?

Request the higher-timeframe value with request.security, then require price to be on the right side of it before entering — long only above the 1-hour SMA, short only below. The HTF string is an input, so the same code filters against 15-minute, hourly, or daily data.

How do I stop request.security from repainting?

Index the requested expression with [1] and set lookahead=barmerge.lookahead_off. That combination returns only the last confirmed higher-timeframe bar, never the still-forming one. Without it, the HTF value shifts mid-bar in live trading while looking clean in backtests — a classic repaint.

Related

Want a complete eval-ready strategy with HTF alignment built in?

This snippet is a building block. Our paid scripts are complete strategies — entries, non-repainting HTF filters, kill switch, and EOD flatten verified on 3 years of MES/NQ data. Instant delivery from $50.

View Plans — From $50