Strategy · Pine Script v5 · On the chart

MTF - Multi-Time Frame Strategy

by Basant1Saini· code credited to TradingTools

This strategy trades moving-average crossovers only when the higher timeframe agrees.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code67
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago4 Mar 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

67 lines of Pine Script v5 from 2_MTF/2_MTF.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

2_MTF.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © TradingTools

//@version=5
strategy("MTF - Multi-Time Frame Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ─── Inputs ───
htfPeriod       = input.timeframe("D", "Higher Timeframe", group="MTF Settings")
fastMA          = input.int(9, "Fast MA Length", group="Moving Averages")
slowMA          = input.int(21, "Slow MA Length", group="Moving Averages")
htfMA           = input.int(50, "HTF Trend MA Length", group="Moving Averages")
maType          = input.string("EMA", "MA Type", options=["EMA", "SMA"], group="Moving Averages")
useAtrSL        = input.bool(true, "Use ATR Stop Loss", group="Risk Management")
atrLength       = input.int(14, "ATR Length", group="Risk Management")
atrMult         = input.float(2.0, "ATR Multiplier", step=0.1, group="Risk Management")
rrRatio         = input.float(2.0, "Risk:Reward Ratio", step=0.1, group="Risk Management")

// ─── MA Calculation Function ───
maCalc(src, len, typ) =>
    typ == "EMA" ? ta.ema(src, len) : ta.sma(src, len)

// ─── Current Timeframe MAs ───
fastLine = maCalc(close, fastMA, maType)
slowLine = maCalc(close, slowMA, maType)

// ─── Higher Timeframe Trend ───
htfClose    = request.security(syminfo.tickerid, htfPeriod, close)
htfTrendMA  = request.security(syminfo.tickerid, htfPeriod, maCalc(close, htfMA, maType))
htfBullish  = htfClose > htfTrendMA
htfBearish  = htfClose < htfTrendMA

// ─── ATR ───
atrVal = ta.atr(atrLength)

// ─── Entry Conditions ───
// Long:  HTF bullish + fast crosses above slow on current TF
// Short: HTF bearish + fast crosses below slow on current TF
longCondition  = htfBullish and ta.crossover(fastLine, slowLine)
shortCondition = htfBearish and ta.crossunder(fastLine, slowLine)

// ─── Execute Trades ───
if longCondition and strategy.position_size == 0
    sl = useAtrSL ? close - atrVal * atrMult : slowLine
    tp = close + (close - sl) * rrRatio
    strategy.entry("MTF Long", strategy.long)
    strategy.exit("MTF Long Exit", "MTF Long", stop=sl, limit=tp)

if shortCondition and strategy.position_size == 0
    sl = useAtrSL ? close + atrVal * atrMult : slowLine
    tp = close - (sl - close) * rrRatio
    strategy.entry("MTF Short", strategy.short)
    strategy.exit("MTF Short Exit", "MTF Short", stop=sl, limit=tp)

// ─── Plotting ───
plot(fastLine, "Fast MA", color=color.new(color.teal, 0), linewidth=2)
plot(slowLine, "Slow MA", color=color.new(color.orange, 0), linewidth=2)

// HTF Trend Background
bgcolor(htfBullish ? color.new(color.green, 92) : htfBearish ? color.new(color.red, 92) : na, title="HTF Trend")

// Entry markers
plotshape(longCondition, title="Long Signal", location=location.belowbar, style=shape.triangleup, color=color.green, size=size.small)
plotshape(shortCondition, title="Short Signal", location=location.abovebar, style=shape.triangledown, color=color.red, size=size.small)

// ─── Alerts ───
alertcondition(longCondition, title="MTF Long Entry", message="MTF: Bullish HTF + Fast MA crossed above Slow MA")
alertcondition(shortCondition, title="MTF Short Entry", message="MTF: Bearish HTF + Fast MA crossed below Slow MA")

Overview

MTF - Multi-Time Frame Strategy requests the higher-timeframe close and a trend moving average, then goes long when that trend is bullish and the fast average crosses above the slow average, and short when the trend is bearish and the fast average crosses below. Position size is 100 percent of equity. An optional ATR stop or the slow average sets the stop, and a risk-reward ratio sets the take profit. It plots both averages, a trend background, and entry markers on the price chart. Only one position is allowed at a time.

Details

Published by

Basant1Saini on GitHub

Code credit

TradingTools, as written in the script's header

Draws

On the price chart

Markets

Stocks

Timeframes

M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

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

SettingTypeDefaultVariable
Higher TimeframetimeframeDhtfPeriod
Fast MA Lengthint9fastMA
Slow MA Lengthint21slowMA
HTF Trend MA Lengthint50htfMA
MA TypestringEMAmaType
Use ATR Stop LossbooltrueuseAtrSL
ATR Lengthint14atrLength
ATR Multiplierfloat2.0atrMult
Risk:Reward Ratiofloat2.0rrRatio
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated 2 days ago · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
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
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 7 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

EMA Crossover Strategy

by TradersPost
228 stars

EMA Crossover Strategy plots a fast and a slow exponential moving average on the price chart. It treats a confirmed fast-over-slow cross as a long condition and a confirmed cross under as a short condition. Position size is a percentage of equity. Optional per

Strategy v6 TrendMoving averages
Updated 3 months ago · None stated GitHub repository of EMA Crossover 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