Strategy · Pine Script v6 · On the chart

MTF Trend Guardian

by propuchon· code credited to ExpertPineQuant

A strategy that combines a higher-timeframe trend filter with an RSI trigger.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code91
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update9 months ago1 Feb 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

91 lines of Pine Script v6 from week 3/mtf_trend_guardian.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

mtf_trend_guardian.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ExpertPineQuant

//@version=6
strategy("[CUCEDT-W33] MTF Trend Guardian", overlay = true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10)

//------------------------------------------------------------------------------
// TABLE OF CONTENTS 
// 1. Constants
// 2. Inputs
// 3. Calculations
// 4. Strategy Logic
// 5. Visuals
//-----------------------------------------------------------------------------{

//------------------------------------------------------------------------------
// 1. Constants
//-----------------------------------------------------------------------------{
color BULL_COLOR = color.new(color.teal, 0)
color BEAR_COLOR = color.new(color.maroon, 0)

//-----------------------------------------------------------------------------}
// 2. Inputs
//-----------------------------------------------------------------------------{
grp_trend = "Trend Filter (HTF)"
htfTimeframeInput = input.timeframe("1D", "Higher Timeframe", group = grp_trend)
htfLengthInput    = input.int(50, "HTF EMA Length", minval = 1, group = grp_trend)

grp_entry = "Entry Settings"
rsiLengthInput    = input.int(14, "RSI Length", minval = 1, group = grp_entry)
rsiLongThreshold  = input.float(50.0, "RSI Long Threshold", group = grp_entry)
rsiShortThreshold = input.float(50.0, "RSI Short Threshold", group = grp_entry)

grp_exit = "Exit Settings"
rsiExitLongLevel  = input.float(40.0, "RSI Exit Level for Long", group = grp_exit)
rsiExitShortLevel = input.float(60.0, "RSI Exit Level for Short", group = grp_exit)

//-----------------------------------------------------------------------------}
// 3. Calculations
//-----------------------------------------------------------------------------{
// --- Indicators ---
float rsiValue = ta.rsi(close, rsiLengthInput)
float htfEma   = request.security(syminfo.tickerid, htfTimeframeInput, ta.ema(close, htfLengthInput)[1], lookahead = barmerge.lookahead_on)

// --- Entry Conditions ---
bool isTrendBullish = close > htfEma
bool isTrendBearish = close < htfEma

bool isRsiLongTrigger  = ta.crossover(rsiValue, rsiLongThreshold)
bool isRsiShortTrigger = ta.crossunder(rsiValue, rsiShortThreshold)

bool longCondition  = isTrendBullish and isRsiLongTrigger
bool shortCondition = isTrendBearish and isRsiShortTrigger

// --- Exit Conditions ---
bool exitLongCondition  = ta.crossunder(rsiValue, rsiExitLongLevel)
bool exitShortCondition = ta.crossover(rsiValue, rsiExitShortLevel)

//-----------------------------------------------------------------------------}
// 4. Strategy Logic
//-----------------------------------------------------------------------------{
// --- Entries ---
if longCondition
    strategy.entry("Long Entry", strategy.long, comment = "Long Trend")

if shortCondition
    strategy.entry("Short Entry", strategy.short, comment = "Short Trend")

// --- Exits ---
if strategy.position_size > 0 and exitLongCondition
    strategy.close("Long Entry", comment = "RSI Weakness")

if strategy.position_size < 0 and exitShortCondition
    strategy.close("Short Entry", comment = "RSI Strength")

//-----------------------------------------------------------------------------}
// 5. Visuals
//-----------------------------------------------------------------------------{
// Determine EMA Color based on price relation
color emaColor = close >= htfEma ? color.green : color.red

// Plot the HTF EMA with dynamic color
plot(htfEma, "Daily EMA", color = emaColor, linewidth = 2)

bgcolor(strategy.position_size > 0 ? color.new(color.teal, 90) : 
        strategy.position_size < 0 ? color.new(color.maroon, 90) : na, title = "Trade Active Background")

plotshape(longCondition, title = "Long Signal", style = shape.triangleup, location = location.belowbar, color = BULL_COLOR, size = size.small)
plotshape(shortCondition, title = "Short Signal", style = shape.triangledown, location = location.abovebar, color = BEAR_COLOR, size = size.small)

//-----------------------------------------------------------------------------}

Overview

MTF Trend Guardian goes long when price is above the previous higher-timeframe EMA and RSI crosses above its long threshold, and short in the mirror case. Positions close when RSI falls below or rises above set exit levels. The higher timeframe, EMA length and RSI levels are adjustable. Sizing is ten percent of equity, and there is no stop loss or take profit.

Details

Published by

propuchon on GitHub

Code credit

ExpertPineQuant, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Higher Timeframetimeframe1DhtfTimeframeInput
HTF EMA Lengthint50htfLengthInput
RSI Lengthint14rsiLengthInput
RSI Long Thresholdfloat50.0rsiLongThreshold
RSI Short Thresholdfloat50.0rsiShortThreshold
RSI Exit Level for Longfloat40.0rsiExitLongLevel
RSI Exit Level for Shortfloat60.0rsiExitShortLevel
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy
228 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers