Using Higher Timeframe Indicator Filters

This lesson demonstrates how to use higher timeframe indicator values as market condition filters for your trading strategies.

Check out my other free lessons!

Source Code

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading / www.PineScriptMastery.com
// @version=5
strategy("PineScriptMastery.com", overlay=true, initial_capital=10000)

// Import Zen library (for easy candle pattern detection)
import ZenAndTheArtOfTrading/ZenLibrary/5 as zen

// Get user inputs
i_emaLength = input.int(title="EMA Length", defval=200)
i_rsiLength = input.int(title="RSI Length", defval=5)
i_timeframe = input.timeframe(title="Higher Timeframe", defval="1D")

// Define non-repainting security function
f_nrpSecurity(_exp) =>
    request.security(syminfo.tickerid, i_timeframe, _exp[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]

// Get current timeframe indicator value expressions
emaValue_CTF = ta.ema(close, i_emaLength)
rsiValue_CTF = ta.rsi(close, i_rsiLength)

// Get higher-timeframe values without repainting
emaValue_HTF = f_nrpSecurity(emaValue_CTF)
rsiValue_HTF = f_nrpSecurity(rsiValue_CTF)

// Detect required market conditions
buyCondition = close > emaValue_HTF and rsiValue_HTF < 30
profitCondition = close < open and close > strategy.position_avg_price
stopCondition = close < low[1]

// Detect only LONG entries
if (buyCondition and zen.isBullishEC())
    qty = syminfo.currency == "JPY" ? 1000 : 100000
    strategy.entry("Long", strategy.long, qty)

// Exit for profit
if (profitCondition)
    strategy.close_all("Take Profit")

// Exit for stop loss
if (stopCondition)
    strategy.close_all("Stop Loss")

// Draw data to chart
plot(emaValue_HTF, "EMA Value", color.red, 2)
plot(rsiValue_HTF, "RSI Value", color.blue, display=display.status_line)
plotshape(1, color=rsiValue_HTF < 30 and close > emaValue_HTF ? color.green : color.red, style=shape.square, location=location.top, display=display.pane)