Multi-timeframe (MTF) Moving Average Indicator for ThinkorSwim

@SaltyDog251 Is this what you're looking for...???

Ruby:
# EMA20D
# Plots and displays chart label for Daily 20 period EMA

input plot_average = yes;
input show_label = yes;

plot Data = if plot_average then ExpAverage(close(period = AggregationPeriod.DAY), 20) else Double.NaN;
AddLabel(show_label, "EMA20D: " + ExpAverage(close(period = AggregationPeriod.DAY), 20), Color.CYAN);
 
Last edited by a moderator:
hello, MTF is great but can you make it to look like this"

kWRdUD5.png


i'm a pattern trader, and is hard for me to see what pattern is in the chart with the MTF
now it looks like this

1jce42A.png


i want it to look like this

kWRdUD5.png
You can find an average that matches closely to the upper timeframe on the lower timeframe. For instance, if you’re wanting to see a 10 period ema from the week chart on a day chart and not have the stair step affect, you could use a 45 period ema on the day chart (gets pretty close). Just a thought. Also, you can’t scan an MTF code so knowing how to find viable non-mtf substitutes can be really helpful.
 
Last edited:
lqv4ssG.jpg


Hello! Please write an indicator with 6 EMA. Tradingview code:

Code:
// @version=4
// authors Vincent Bollaert //

study(title="MA EMA MTF ribbon", shorttitle="MA EMA MTF ribbon", overlay = true)

ticker_id = tickerid(syminfo.prefix, syminfo.ticker)


// ----- colors ----- //

color_transparent = color.new(color.white, 100)

color_green = color.new(color.green, 65)
color_green_transparent = color.new(color.green, 90)

color_red = color.new(color.red, 65)
color_red_transparent = color.new(color.red, 90)



// ----- EMA ----- //
input_ema_1 = input(title="Ribbon 1 low (EMA)", type=input.integer, defval=72)
input_ema_1_tf = input(title="timeframe", type=input.resolution, defval="240")

input_ema_2 = input(title="Ribbon 1 high (EMA)", type=input.integer, defval=89)
input_ema_2_tf = input(title="timeframe", type=input.resolution, defval="240")

input_ema_3 = input(title="Ribbon 2 low (EMA)", type=input.integer, defval=72)
input_ema_3_tf = input(title="timeframe", type=input.resolution, defval="5")

input_ema_4 = input(title="Ribbon 2 high (EMA)", type=input.integer, defval=89)
input_ema_4_tf = input(title="timeframe", type=input.resolution, defval="5")

input_ema_5 = input(title="200(EMA)", type=input.integer, defval=200)
input_ema_5_tf = input(title="timeframe", type=input.resolution, defval="240")

input_ema_6 = input(title="200(EMA)", type=input.integer, defval=600)
input_ema_6_tf = input(title="timeframe", type=input.resolution, defval="240")

ema_1 = ema(close, input_ema_1)
ema_2 = ema(close, input_ema_2)
ema_3 = ema(close, input_ema_3)
ema_4 = ema(close, input_ema_4)
ema_5 = ema(close, input_ema_5)
ema_6 = ema(close, input_ema_6)

output_ema_1 = security(ticker_id, input_ema_1_tf, ema_1)
output_ema_2 = security(ticker_id, input_ema_2_tf, ema_2)
output_ema_3 = security(ticker_id, input_ema_3_tf, ema_3)
output_ema_4 = security(ticker_id, input_ema_4_tf, ema_4)
output_ema_5 = security(ticker_id, input_ema_5_tf, ema_5)
output_ema_6 = security(ticker_id, input_ema_6_tf, ema_6)

ema_plot_1 = plot(output_ema_1, color=color_transparent, title="Ribbon 1 low (EMA)")
ema_plot_2 = plot(output_ema_2, color=color_transparent, title="Ribbon 1 high (EMA)")
ema_plot_3 = plot(output_ema_3, color=color_transparent, title="Ribbon 2 low (EMA)")
ema_plot_4 = plot(output_ema_4, color=color_transparent, title="Ribbon 2 high (EMA)")
ema_plot_5 = plot(output_ema_5, color=color_transparent, title="200(EMA)")
ema_plot_6 = plot(output_ema_6, color=color_transparent, title="200(EMA)")


fill(ema_plot_1, ema_plot_2, color = output_ema_1 > output_ema_2 ? color_green : color_red)
fill(ema_plot_3, ema_plot_4, color = output_ema_3 > output_ema_4 ? color_green: color_red)
Can you come up same code for TOS please, if it possible.
 
Can you come up same code for TOS please, if it possible.

See if this helps. It is using TOS 'enableapproximation()' function to smooth the lines of the fast and slow multi-timeframe averages on the following chart. You can choose whether to display the unsmoothed or smoothed or both methods for comparison purposes. The chart below shows both methods.

Capture.jpg

Code:
#Example Smooth Plot HigherAgg on LowerAgg
#Usethinkscript request
#Sleepyz

input show_original_plot = yes;
input show_smooth_plot   = yes;

input aggperiod   = AggregationPeriod.THIRTY_MIN;
input fastlength  = 6;
input slowlength  = 20;
input price       = FundamentalType.CLOSE;
input averageType = AverageType.EXPONENTIAL;

plot Fast = MovingAverage(averageType, Fundamental(price, period = aggperiod), fastlength);
Fast.SetHiding(show_original_plot == no);

plot Slow = MovingAverage(averageType, Fundamental(price, period = aggperiod), slowlength);
Slow.SetHiding(show_original_plot == no);


#Smoothed Plots
def minutes = aggperiod / 60000;
def bar = BarNumber();
def x = if bar == 1 or bar[1] % ((Ceil(minutes) ) / (GetAggregationPeriod() / 60000)) == 0
        then Fast
        else x[1];

def xx = (if x != x[1] then xx[1] + 1 else xx[1]);
def xxx = if  xx != xx[1] then x else Double.NaN;
plot xsmooth = if !show_smooth_plot then Double.NaN else  if IsNaN(close[-1]) then Fast else xxx;
xsmooth.EnableApproximation();

def x1 = if bar == 1 or bar[1] % ((Ceil(minutes) ) / (GetAggregationPeriod() / 60000)) == 0
        then Slow
        else x1[1];

def xx1 = (if x1 != x1[1] then xx1[1] + 1 else xx[1]);
def xxx1 = if  xx1 != xx1[1] then x1 else Double.NaN;
plot x1smooth = if !show_smooth_plot then Double.NaN else if IsNaN(close[-1]) then Slow else xxx1;
x1smooth.EnableApproximation();
 
@wcsharron Here's something simple I put together a while back. It plots three daily moving averages of your choice and identifies them on the chart. The identifying bubbles can be turned off. It may do what you want.

Code:
#Daily Simple Moving Averages with Identifying Bubbles
#Pensar

#Simple Moving Averages
input avg_1 = 20;
input avg_2 = 50;
input avg_3 = 200;
input avg_type = AverageType.SIMPLE;

def c = close(period = AggregationPeriod.DAY);

plot ma1 = MovingAverage(avg_type,c,avg_1);
     ma1.SetDefaultColor(Color.YELLOW);
plot ma2 = MovingAverage(avg_type,c,avg_2);
     ma2.SetDefaultColor(Color.DARK_ORANGE);
plot ma3 = MovingAverage(avg_type,c,avg_3);
     ma3.SetDefaultColor(Color.GREEN);

#Bubbles
input show_bubbles = yes;

def x = !IsNaN(close[-25]) and IsNaN(close[-26]);

AddChartBubble(show_bubbles and x, ma1, avg_1 + " MA", Color.YELLOW, if ma1 > c then yes else no);
AddChartBubble(show_bubbles and x, ma2, avg_2 + " MA", Color.DARK_ORANGE, if ma2 > c then yes else no);
AddChartBubble(show_bubbles and x, ma3, avg_3 + " MA", Color.GREEN, if ma3 > c then yes else no);

#end code


I really like this one, but wanted to use it on other time frames besides daily and allow different moving averages and display nonoverlapping bubbles (when the MA lines get close, the bubbles overlap). Note that SuryaKiranC and prolab also made a nice alternative version of Pensar's script for Daily charts in this same thread.

As has been noted by others here, one can put higher time frame MAs on a lower time frame simply by adjusting the numbers, e.g., a 120 period MA on a 5 minute chart is equivalent to the 10 period MA on an hourly chart, etc.

Hopefully a chart and the new code are shown below.

Chart-Mov-Avg-3-Bubbles2.png



Code:
# Modification of Pensar’s Daily Simple Moving Averages with Identifying Bubbles
# Can be used on any time frame & the MAs can be different types
# MovAvg_3Bubbles2

input avg_1 = 20;
input avg_2 = 50;
input avg_3 = 200;
input avg_type1 = AverageType.SIMPLE;
input avg_type2 = AverageType.SIMPLE;
input avg_type3 = AverageType.SIMPLE;


plot ma1 = MovingAverage(avg_type1,close,avg_1);
ma1.SetDefaultColor(Color.DARK_ORANGE);
ma1.SetLineWeight(2);


plot ma2 = MovingAverage(avg_type2,close,avg_2);
ma2.SetDefaultColor(Color.MAGENTA);
ma2.SetLineWeight(2);


plot ma3 = MovingAverage(avg_type3,close,avg_3);
ma3.SetDefaultColor(Color.BLUE);
ma3.SetLineWeight(2);


#Bubbles
input show_bubbles = yes;

def x = !IsNaN(close[-50]) and IsNaN(close[-51]);
def y = !IsNaN(close[-40]) and IsNaN(close[-41]);
def z = !IsNaN(close[-30]) and IsNaN(close[-31]);

AddChartBubble(show_bubbles and x, ma1, avg_1 + " MA", Color.DARK_ORANGE);
AddChartBubble(show_bubbles and y, ma2, avg_2 + " MA", Color.MAGENTA);
AddChartBubble(show_bubbles and z, ma3, avg_3 + " MA", Color.CYAN);

#end code
 
Hi, new guy here. For six months I’ve been trying to get the daily 20 EMA level to show up on the 5 minute chart.

I’m told it’s possible but just can’t get it done! Help please

Hi SaltyDog,

Another way to look at it would be -

1. A 20 period EMA on a daily chart is 20 x 6.5 trading hours/day = a 130 period EMA on a 1 hour chart

2. A 130 period EMA on a 1 hour chart is 130 x 12 five-minute bars/hour = a 1560 period EMA on a 5 minute chart.

Hope I did that right… the chart below shows the 1560 period SMA, EMA and Hull MA on a 5 minute chart of /NQ.


1560-MAs-on-a-5-min-chart.png
 
Hello

Can we set up a scanner where "price close" on 1min candle "crosses above or below" a 1hr ema9 on a 1 min chart within the last 3 bars?


Thank you
 
@JOE8302 Unfortunately TOS does not allow secondary aggregation periods in the Scanners or in Custom Watchlist Columns, therefore what you are requesting cannot be done...
 
thank you @rad14733.... what if i wanted the EMA 9 of a 1HR chart to show in my watchlist, is that possible?

Yes... You just can't use multiple timeframes/aggregation periods in the same Custom Watchlist Column... The same goes for Scans in that you can't have multiples in a single condition but can use different ones in separate conditions within the same scan... See Chapter 11 of the Thinkscript Learning Center for a full explanation...
 
Poster's Request: MTF EMA Cloud
Ruby:
input price = close;
input displace = 0;
input length1 = 9;
input length2 = 21;
input period = AggregationPeriod.FIFTEEN_MIN;
input averageType = AverageType.EXPONENTIAL;

plot EMA1 = MovingAverage(averageType, close(period = period) [-displace], length = length1);
plot EMA2 = MovingAverage(averageType, close(period = period) [-displace], length = length2);

AddCloud(ema1, ema2, color.green, color.red);
 
See if this helps. It is using TOS 'enableapproximation()' function to smooth the lines of the fast and slow multi-timeframe averages on the following chart. You can choose whether to display the unsmoothed or smoothed or both methods for comparison purposes. The chart below shows both methods.
Hi, i see couple of different versions here. Not sure which one to use.
Also looking for EMA Cloud setup similar to Trading view for both 5-12 and 34-50 EMA. Appreciate your help. Thank u
 
@shop00
Yes, there are endless flavors of plots of moving averages. Try them all. See what works best for you.
Yes, you can have more than one cloud. Add the cloud script from post#158 to your chart, two times. Change the lengths to what works for you.

Want hundreds of more choices? Here are two of the most popular moving average threads on the forum:
Crossover of Moving Averages --> https://usethinkscript.com/threads/101-flavors-of-moving-average-crossovers.229/
Stacked Moving Averages --> https://usethinkscript.com/threads/all-flavors-of-stacked-moving-averages.4719/

Keep in mind that moving averages are slow to respond to rapid price changes that often occur at market reversal points.
 
Last edited:
Hi all,

Is there a way to scan for stock on a higher time frame's moving average. For example i am i wish to scan for stock of moving average of 21 weekly chart on lower time frame daily chart.
 
Is there any way to make this indicator for multi time frame? Trying to display a 4 hour cloud on my 5 min chart. I have tried but I am no programmer... Thanks in advance and thanks Rich for the original code.
Ruby:
# Moving Average Crossover With Arrows, Alerts, Crossing Count and Bubble at Cross
# Mobius
# Chat Room Request 01.25.2017
# Modified a bit by BenTen

input price = close;
input fastLength = 8;
input slowLength = 21;
input averageType = AverageType.EXPONENTIAL;

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType, price, slowLength);
FastMA.SetDefaultColor(GetColor(1));
SlowMA.SetDefaultColor(GetColor(2));

plot ArrowUp = if FastMA crosses above SlowMA
then low
else double.nan;
ArrowUP.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
ArrowUP.SetLineWeight(3);
ArrowUP.SetDefaultColor(Color.Green);
plot ArrowDN = if FastMA crosses below SlowMA
then high
else double.nan;
ArrowDN.SetPaintingStrategy(PaintingStrategy.Arrow_DOWN);
ArrowDN.SetLineWeight(3);
ArrowDN.SetDefaultColor(Color.Red);
Alert(ArrowUp, " ", Alert.Bar, Sound.Chimes);
Alert(ArrowDN, " ", Alert.Bar, Sound.Bell);

AddCloud(FastMA, SlowMA, Color.GREEN, Color.RED);
# End Code
 
Last edited by a moderator:
MTF Moving Average Crossover With Arrows, Alerts, Crossing Count and Bubble at Cross by Mobius
@Shane
Ruby:
# MTF Moving Average Crossover With Arrows, Alerts, Crossing Count and Bubble at Cross
# Mobius
# Chat Room Request 01.25.2017
# Modified a bit by BenTen

input AGG = AggregationPeriod.FOUR_HOURS ;
input fastLength = 8;
input slowLength = 21;
input averageType = AverageType.EXPONENTIAL;
def price = close(period = AGG);

plot FastMA = MovingAverage(averageType, price, fastLength);
plot SlowMA = MovingAverage(averageType, price, slowLength);
FastMA.SetDefaultColor(GetColor(1));
SlowMA.SetDefaultColor(GetColor(2));

plot ArrowUp = if FastMA crosses above SlowMA
then low
else double.nan;
ArrowUP.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
ArrowUP.SetLineWeight(3);
ArrowUP.SetDefaultColor(Color.Green);
plot ArrowDN = if FastMA crosses below SlowMA
then high
else double.nan;
ArrowDN.SetPaintingStrategy(PaintingStrategy.Arrow_DOWN);
ArrowDN.SetLineWeight(3);
ArrowDN.SetDefaultColor(Color.Red);
Alert(ArrowUp, " ", Alert.Bar, Sound.Chimes);
Alert(ArrowDN, " ", Alert.Bar, Sound.Bell);

AddCloud(FastMA, SlowMA, Color.GREEN, Color.RED);
a1.png
 
I'm building an MTF Moving Average cross over indicator and can't seem to prevent it from painting multiple arrows per alert(5 for 5 min TF, 10 for 10 min TF, etc).
I ran into this before building a Conquistador indicator but I don't recall how I fixed it. Any ideas?

Code:
declare once_per_bar;

input showMa = yes;
input ma_1_type = AverageType.EXPONENTIAL;
input ma_1 = 9; # 9 or 10
input ma_2_type = AverageType.EXPONENTIAL;
input ma_2 = 20; # 20

input useAggregationPeriod = no;
input aggregationPeriod = AggregationPeriod.five_min;

def aggPeriod = if useAggregationPeriod then aggregationPeriod else getAggregationPeriod();

plot ma1 = MovingAverage(ma_1_type, Fundamental(FundamentalType.close, period = aggPeriod), ma_1);
#plot ma1 = MovingAverage(ma_1_type, close(period = aggPeriod), ma_1);
ma1.SetDefaultColor(createColor(225,225,170));
ma1.HideBubble();
ma1.SetStyle(Curve.firm);
ma1.SetLineWeight(1);
ma1.setHiding(!showMa);

plot ma2 = MovingAverage(ma_2_type, Fundamental(FundamentalType.close, period = aggPeriod), ma_2);
#plot ma2 = MovingAverage(ma_2_type, close(period = aggPeriod), ma_2);
ma2.SetDefaultColor(createColor(100,180,235));
ma2.HideBubble();
ma2.SetStyle(Curve.firm);
ma2.SetLineWeight(1);
ma2.setHiding(!showMa);


# clouds

input enable_cloud = no;
AddCloud(if enable_cloud then ma1 else double.nan, if enable_cloud then ma2 else double.nan, Color.GREEN, Color.RED);


# signals

def upTrigger = if ma1 crosses above ma2 then 1 else 0;
def dnTrigger = if ma1 crosses below ma2 then 1 else 0;


input offset = .03; #1

plot up = If upTrigger then low + (TickSize() - offset) else Double.NaN;
plot down = If dnTrigger then high - (TickSize() - offset) else Double.NaN;
#plot up = if MovingAverage(ma_1_type, Fundamental(FundamentalType.close, period = aggPeriod), ma_1) crosses above MovingAverage(ma_2_type, Fundamental(FundamentalType.close, period = aggPeriod), ma_2) then low + (TickSize() - offset) else Double.NaN;
#plot down = if MovingAverage(ma_1_type, Fundamental(FundamentalType.close, period = aggPeriod), ma_1) crosses below MovingAverage(ma_2_type, Fundamental(FundamentalType.close, period = aggPeriod), ma_2) then high - (TickSize() - offset) else Double.NaN;

up.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
up.SetDefaultColor(Color.lime);
up.setHiding(up[1] or up[2] or up[3] or up[4]);
down.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
down.SetDefaultColor(Color.pink);
down.setHiding(down[1] or down[2] or down[3] or down[4]);

input alerts = yes;
def aUp = if up and alerts == yes then up else double.nan;
def aDown = if down and alerts == yes then down else double.nan;

Alert(aUp, "MAX BUY", Alert.BAR, Sound.Bell );
Alert(aDown, "MAX SELL", Alert.BAR, Sound.Bell );
 
Last edited by a moderator:
@Tidan
Posters have many favorite variations to limit the number of arrows.
Here is a version that states only print the 1st of the series of arrows.

Replace these two lines:
Ruby:
plot up   = If upTrigger then low + (TickSize() - offset) else Double.NaN;
plot down = If dnTrigger then high - (TickSize() - offset) else Double.NaN;
With these two lines:
Ruby:
plot up   = If upTrigger and !upTrigger[1] then low + (TickSize() - offset) else Double.NaN;
plot down = If dnTrigger and !dnTrigger[1] then high - (TickSize() - offset) else Double.NaN;

Keep in mind arrows are not recommended for MTF Indicators
6urj716.png
 
Last edited:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
576 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top