Pine Script Higher Timeframe Filter
Filters entries against a higher-timeframe trend using request.security with [1] and lookahead_off — confirmed HTF data only, with no repainting.
Pine Script
//@version=6
strategy("Target Filled - HTF Filter Example", overlay=true, calc_on_every_tick=false)
// --- Inputs ---------------------------------------------------
htfRes = input.timeframe("60", "Higher Timeframe")
htfLen = input.int(50, "HTF SMA Length", minval=1)
// --- Non-repainting HTF value --------------------------------------
// [1] plus lookahead_off returns only the last CONFIRMED higher-timeframe
// bar — never the one still forming.
htfSMA = request.security(syminfo.tickerid, htfRes, ta.sma(close, htfLen)[1],
lookahead=barmerge.lookahead_off)
aboveHTF = close > htfSMA
belowHTF = close < htfSMA
// --- Sample signal — replace with your own entry logic ---------
fastMA = ta.ema(close, 9)
slowMA = ta.ema(close, 21)
canLong = ta.crossover(fastMA, slowMA) and aboveHTF
canShort = ta.crossunder(fastMA, slowMA) and belowHTF
if canLong
strategy.entry("Long", strategy.long)
strategy.exit("Long Exit", "Long", profit=20, loss=10)
if canShort
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", "Short", profit=20, loss=10)
// Visual: the HTF SMA drawn on the trading timeframe
plot(htfSMA, "HTF SMA", color=color.new(color.orange, 0), linewidth=2) Settings
| Input | Default | Purpose |
|---|---|---|
| htfRes | 60 (1 hour) | The higher timeframe requested for the trend check. |
| htfLen | 50 | SMA length computed on that higher timeframe. |
How to use
- Paste into the Pine Editor and swap the EMA-crossover placeholder for your own entry conditions.
- Longs only trigger above the HTF SMA and shorts only below it — a one-line regime filter layered on top of whatever signal is already in place.
- Never drop the
[1]or flip lookahead back on — either change quietly reintroduces repainting. - The orange line is the HTF SMA drawn on the trading timeframe, so every filtered signal can be audited visually.
Frequently Asked Questions
How do I add a higher timeframe filter in Pine Script?
Pull the higher-timeframe value with request.security, then require price to sit on the correct side of it before an entry is allowed — longs only above a 1-hour SMA, shorts only below it. Since the higher timeframe is passed in as a string input, the exact same code can filter against a 15-minute, hourly, or daily reference just by changing that one setting.
How do I stop request.security from repainting?
Index the requested expression with [1] and pass lookahead=barmerge.lookahead_off. That pairing guarantees only the last fully confirmed higher-timeframe bar comes back — never the bar that is still forming. Skip either half of that and the HTF value can shift mid-bar once trading live, even though the backtest looked perfectly clean.