Repaints Multi-timeframe (MTF) Moving Average Indicator for ThinkorSwim

Repaints
@Hurrikane Reading through the 7 pages of this thread can provide you with information that you haven't even thought to ask, yet.
In answer to your specific question, I looked through the thread for you. See if the answers starting around post#67 give you a starting point and then start experimenting.
HTH
 

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

If you are viewing a daily chart, A MTF study will only show you the higher TIME FRAMES!,

So open a 5 Min Chart, add THE MTF STUDY, Now you have to Click on the BEAKER, Click on the GEARS , and ADJUST and Select which Time Frames you want, Click apply and OK
 
Provided below is thinkscript someone helped me build. It is a lower chart study that shows Green Dots if the EMA is Greater than another EMA for multiple timeframes. This is great if you have a trend based strategy and you only want to take trades when a short-term EMA (e.g. 9) is above the long-term EMA (e.g. 20) on multiple-timeframes. You could do this with multiple charts using the standard EMA lines, but that takes up a lot of space. This allows you to see the same info in a different visualization.

There's one problem... It doesn't show multiple rows. It combines everything into one row. If that works for you then great. If you know how to break each chart timeframe into multiple dot rows, please reply.

Hopefully, you might find the following code useful.

Code:
#MTF_MovingAverage_LowerStudy_Dots
#Caution: Anytime a higher timeframe row changes color between the white dots, the entire row between the white dots will change to the new color. This will include dots that have previously plotted another color during that span between the white dots. This could give you a misleading impression when viewing the lower timeframe chart.

declare lower;

input showchartbubbles = yes;
input show_white_dots  = yes;

input timeFrame1 = AggregationPeriod.FIVE_MIN;
input timeFrame2 = AggregationPeriod.FIFTEEN_MIN;
input timeFrame3 = AggregationPeriod.THIRTY_MIN;

input maLength1 = 5;
input maType1 = AverageType.EXPONENTIAL;
input maLength2 = 20;
input maType2 = AverageType.EXPONENTIAL;

def ma1 = MovingAverage(maType1, close(period = timeFrame1), maLength1);
def ma2 = MovingAverage(maType2, close(period = timeFrame1), maLength2);

def ma3 = MovingAverage(maType1, close(period = timeFrame2), maLength1);
def ma4 = MovingAverage(maType2, close(period = timeFrame2), maLength2);

def ma5 = MovingAverage(maType1, close(period = timeFrame3), maLength1);
def ma6 = MovingAverage(maType2, close(period = timeFrame3), maLength2);

#White Dots plotted, marking the last Higher Timeframe bar on the Lower Timeframe
input begin   = 0930;
def minutes1 = timeFrame1 / 60000;
def minutes2 = timeFrame2 / 60000;
def minutes3 = timeFrame3 / 60000;

def barSeq    = if SecondsTillTime(begin) == 0 and
                   SecondsFromTime(begin) == 0
                then 0
                else barSeq[1] + 1;
def bar = barSeq;

def bar1 = if (bar) % (minutes1 / (GetAggregationPeriod() / 60000)) == 0 then bar1[1] + 1 else bar1[1];
def bar1ext = if !IsNaN(close) and IsNaN(close[-1]) then bar1 else Double.NaN;
def bar2 = if (bar) % (minutes2 / (GetAggregationPeriod() / 60000)) == 0 then bar2[1] + 1 else bar2[1];
def bar2ext = if !IsNaN(close) and IsNaN(close[-1]) then bar2 else Double.NaN;
def bar3 = if (bar) % (minutes3 / (GetAggregationPeriod() / 60000)) == 0 then bar3[1] + 1 else bar3[1];
def bar3ext = if !IsNaN(close) and IsNaN(close[-1]) then bar3 else Double.NaN;

plot dot1 = if show_white_dots and between(bar1, highestall(bar1ext), highestall(bar1ext)+1) and (bar) % (minutes1 / (GetAggregationPeriod() / 60000)) == 0 then .9 else Double.NaN;
dot1.SetPaintingStrategy(PaintingStrategy.POINTS);
dot1.SetDefaultColor(Color.WHITE);
plot dot2 = if show_white_dots and between(bar2, highestall(bar2ext), highestall(bar2ext)+1) and (bar) % (minutes2 / (GetAggregationPeriod() / 60000)) == 0 then 1.9 else Double.NaN;
dot2.SetPaintingStrategy(PaintingStrategy.POINTS);
dot2.SetDefaultColor(Color.WHITE);
plot dot3 = if show_white_dots and between(bar3, highestall(bar3ext), highestall(bar3ext)+1) and (bar) % (minutes3 / (GetAggregationPeriod() / 60000)) == 0 then 2.9 else Double.NaN;
dot3.SetPaintingStrategy(PaintingStrategy.POINTS);
dot3.SetDefaultColor(Color.WHITE);

#Red/Green Dots plotted comparing the the Two Higher Moving Averages to each other
#Row 1
plot row1 = if !IsNaN(close) then 1 else Double.NaN;
row1.SetPaintingStrategy(PaintingStrategy.POINTS);
row1.AssignValueColor(if ma1 > ma2 then Color.GREEN else Color.RED);
row1.SetLineWeight(3);

#Row 2
plot row2 = if !IsNaN(close) then 2 else Double.NaN;
row2.SetPaintingStrategy(PaintingStrategy.POINTS);
row2.AssignValueColor(if ma3 > ma4 then Color.GREEN else Color.RED);
row2.SetLineWeight(3);

#Row 3
plot row3 = if !IsNaN(close) then 3 else Double.NaN;
row3.SetPaintingStrategy(PaintingStrategy.POINTS);
row3.AssignValueColor(if ma5 > ma6 then Color.GREEN else Color.RED);
row3.SetLineWeight(3);

#Chart Bubbles indicating the timeframe of each row
input b = 5; #Increase to move bubble to the right and Decrease to move bubble to the left
def bm = b + 1;

plot lowerline = 0;#Plotted to orient the Dots within the Lower Chart Panel
lowerline.SetDefaultColor(Color.GRAY);
plot upperline = 4;#Plotted to orient the Dots within the Lower Chart Panel
upperline.SetDefaultColor(Color.GRAY);

AddChartBubble(showchartbubbles and IsNaN(close[b]) and !IsNaN(close[bm]), row1[bm], timeFrame1 / 60000, if ma1[bm] > ma2[bm] then Color.GREEN else Color.RED);
AddChartBubble(showchartbubbles and IsNaN(close[b]) and !IsNaN(close[bm]), row2[bm], timeFrame2 / 60000, if ma3[bm] > ma4[bm] then Color.GREEN else Color.RED);
AddChartBubble(showchartbubbles and IsNaN(close[b]) and !IsNaN(close[bm]), row3[bm], timeFrame3 / 60000, if ma5[bm] > ma6[bm] then Color.GREEN else Color.RED);
 
Hi, request for assistance, the first pic shows a very simple script to plot a 10Weekly MA on a Daily Chart. I am having some challenges to create a plot when Prices CLOSES above the 10Week MA on the Daily Chart as shown by the dotted lines.

KhR3sOc.jpg


Code:
#To plot the 10Week MA on Daily Chart.
input Period = aggregationPeriod.WEEK;
input AvgType = averageType.SIMPLE;
input Length = 10;
Def price = low;
plot AVG = MovingAverage(AvgType, close(period = Period), Length);
AVG.setdefaultcolor(color.white);

This is the scanner I tried to create but the scan results from the scanner provides signal that are plotted on the Weekly chart and sometimes on Daily Chart. This is the confusion I am getting.

teWMkc7.jpg


Hope to get some help here.
Thanks
 
@Nick You won't be able to run that because ThinkorSwim does not allow secondary aggregation period in their scanner.
 
Hi - I am trying to make this script working in TOS Scan...basically I want to get a list of stocks which fulfills the following conditions:
1. price is below 100-week MVA(Exponential) and above 200-week MVA(Exponential).
2. 100-week MVA(Exponential) is above 200-week MVA(Exponential).

The following stocks will fall under the criteria: AC, AEE, AEM.

In Yahoo Finance I set the chart as 5Y and interval=1 week and trying to replicate the same using think script.

In www.marketinout.com/stock-screener I get the stock list using below conditions and it works in that website perfectly:
EMA(100) Is Above EMA(200)
Price Is Below EMA(100)
Price Is Above EMA(200)

Code:
def price = close( period=AggregationPeriod.WEEK );
input avgType = AverageType.EXPONENTIAL;

def mva100 = MovingAverage(avgType, price, 100);
def mva200 = MovingAverage(avgType, price, 200);

plot signal = if (price < mva100 and price > mva200 and mva100 > mva200 ) then 1 else 0;

The issues I'm having:
1. TOS doesn't let me set AggregationPeriod.WEEK
2. If I make it AggregationPeriod.DAY I don't get those stocks in scan results

Appreciate your help in advance. Thanks!
 
1. TOS doesn't let me set AggregationPeriod.WEEK

You can change it to not specify the AggregationPeriod in code and instead select Week from the the Aggregation list at the top of the window where the code is or to the right of that study on the main scan window.
 
Hi Slippage - Thanks for your reply. I did as you advised by selecting Aggregation as Week but I only get one stock CSPCY as the result. Basically its not showing the correct results.
 
Hi Slippage - Thanks for your reply. I did as you advised by selecting Aggregation as Week but I only get one stock CSPCY as the result. Basically its not showing the correct results.

I can't guarantee TOS has the correct data. I can only tell you how to work around the timeframe issue. TOS doesn't allow scans to access secondary timeframes. You likely had the default of Day selected and then put in code that accesses Week. That issue is solved now.

I get 208 results running this on weekly with "Scan in" set to "All Stocks", including AEM from your example but not the other two. For AC, 100 is below 200 and it closed below the 200 so it shouldn't be in the results. AEE, though, when I put those averages on a chart AEE meets the criteria. You can complain to customer support about that one. It's out of my hands.
Ruby:
def ema100 = MovAvgExponential(close, 100);
def ema200 = MovAvgExponential(close, 200);
plot scan = close < ema100 and close > ema200 and ema100 > ema200;
 
By specifying all your steps helped out to identify what I was doing wrong. My "Scan in" was pointing to something else. After setting to "All Stocks" it was all good!....thank you Slippage for inadvertently pointing out where I slipped :)
 
Higher Time frame moving average
once you add the code you can configure it to use whatever unit of time you want, the default is DAY
NOTE: The study time frame (aggregationPeriod) must be equal to or larger than the "charted" time frame
Code:
input time = aggregationPeriod.DAY;
input type = averageType.EXPONENTIAL;
input length = 9;
plot average = MovingAverage(averageType = Type, data = close(period = time), length = length);
 
@SuryaKiranC I see what you are saying and yes, your code achieves exactly that. But what I am trying to accomplish is to use the study that paints the candles green, yellow, or red, based on the study I provided. The idea is to use somewhat of a trend and stay in a trade, as long as the candles are at least yellow on different timeframes. Are you able to change the code to use the candle colors based on that study I provided, for the different timeframes? Thank you very much for your efforts!

The idea is that when i see the 5min become yellow, followed by the 15min becoming yellow and the 30min. becoming yellow (based on the 8/13/21 EMA study I provided ), then I know that there is a trend change most likely and to get out of a position. That's what I am trying to find out. Thank you!

Hi @SuryaKiranC , hope all is well. I found this piece of code that plots the Squeeze indicator colors on the top of the page, with the different timeframes. Was wondering if this would be easier for you, if you could replace the parts of the code that are for the squeeze and replace with the triple EMA study I provided.
Thanks again for all your help, much appreciated!

Code:
input dStr ="4 hours";


script MySqueeze{
def length  = 20;
def AtrMult = 1.4;
def SdMult  = 2;

input period ="Daily";


def valueClose   =  close(period = period);
def valueHigh   =  high(period = period);
def valueLow   =  low(period = period);

def SD = StDev(valueClose, length);

def Avg = Average(valueClose, length);

def ATR = Average(TrueRange(valueHigh, valueClose, valueLow), length);

def SDup = Avg + (SdMult * SD);

def ATRup = Avg + (AtrMult * ATR);



plot Squeeze = if SDup < ATRup

               then 1

               else 0;


}


def dSQ= MySqueeze(dStr);
AddLabel(yes, dStr, if dSQ
then  Color.RED else  Color.GREEN); # display label red if has squeeze
Hi @SuryaKiranC hope all is well! Was wondering if you had any time to check this out and help me with the boxes getting painted on the color of the bars at different timeframes, based on the triple EMA code we had discussed.
Thank you once again for your help.
 
Please Help me coding this moving average... I have done coding the main part and stuck with last two line

What i am trying do to ....

Add chart bubble when current candle is (4H Candle) is closed over Daily 21 Exponential Average saying ... "Over Daily Avarage"
Add chart label saying .... "Long Trade" ... if current candle is (4H Candle) is closed over Daily 21 Exponential Average or "DO not trade" if the

current candle is (4H Candle) closed under Daily 21 Exponential Average

Thank is Advance and I will greatly appreciate your help ....

Code:
# Moving Average

input Period = AggregationPeriod.DAY;
input AvgType = AverageType.EXPONENTIAL;
input Length = 21;
input priceclose = close;

plot AVG = MovingAverage(AvgType, close(period = Period), Length);
AVG.SetDefaultColor(Color.YELLOW);

AddChartBubble "I am lost here"
AddLabel "I am lost here"

===============================================
SCAN CODE
plot signal = if close > ExponentialMovingAvg(length=21) then 1 else 0;
===============================================
Is this correct ?
 
Last edited:
@Topas You will not be able to use this code as a scan because TOS don't allow secondary aggregation period in their scanner.

As for chart bubbles, this should work.

Code:
# Moving Average

input Period = AggregationPeriod.DAY;
input AvgType = AverageType.EXPONENTIAL;
input Length = 21;
input priceclose = close;

plot AVG = MovingAverage(AvgType, close(period = Period), Length);
AVG.SetDefaultColor(Color.YELLOW);

def signal = close crosses above Avg;
AddChartBubble(signal, low, "Long trade", Color.light_green, no);
 
Hey guys,

I am looking to synchronize the EMAs on my charts. Basically, I want the 1min chart and 5min chart to have the same EMA.
 
Last edited:
I have put together for my own use a Moving Average Ribbon using 6 Moving Averages. Each Moving average has inputs for both length and aggregation period, so you can mix and match. Image below shows the 6 averages, set of three with aggregation period of 1 minute, and second set with aggregation period of 5 minutes. On a 1 minute chart.
Might be useful for someone. Code is below image.
ReBf1FI.jpg

Code:
#rlohmeyer Multi-Aggregation Moving Average Ribbon
#code ideas came from shared code on UseThinkscript

input AvgType = averageType.EXPONENTIAL;
input avg1_agg = aggregationPeriod.FIVE_MIN;
input avg1_lngth = 5;
input avg2_agg = aggregationPeriod.FIVE_MIN;
input avg2_lngth = 10;
input avg3_agg = aggregationPeriod.FIVE_MIN;
input avg3_lngth = 20;
input avg4_agg = aggregationPeriod.day;
input avg4_lngth = 5;
input avg5_agg = aggregationPeriod.day;
input avg5_lngth = 10;
input avg6_agg = aggregationPeriod.day;
input avg6_lngth = 20;


plot AVG1 = MovingAverage(AvgType, close(period = avg1_agg), avg1_lngth);
AVG1.setdefaultcolor(color.yellow);
AVG1.hidebubble();
Avg1.hidetitle();
plot AVG2 = MovingAverage(AvgType, close(period = avg2_agg), avg2_lngth);
AVG2.SetDefaultColor(CreateColor(255,204,0));
AVG2.hidebubble();
Avg2.hidetitle();
plot AVG3 = MovingAverage(AvgType, close(period = avg3_agg), avg3_lngth);
AVG3.SetDefaultColor(CreateColor(255, 153, 0));
AVG3.hidebubble();
Avg3.hidetitle();
plot AVG4 = MovingAverage(AvgType, close(period = avg4_agg), avg4_lngth);
AVG4.SetDefaultColor(CreateColor(255, 102, 0));
AVG4.hidebubble();
Avg4.hidetitle();
plot AVG5 = MovingAverage(AvgType, close(period = avg5_agg), avg5_lngth);
AVG5.SetDefaultColor(CreateColor(255, 51, 0));
AVG5.hidebubble();
Avg5.hidetitle();
plot AVG6 = MovingAverage(AvgType, close(period = avg6_agg), avg6_lngth);
AVG6.SetDefaultColor(CreateColor(204, 51, 0));
AVG6.hidebubble();
Avg6.hidetitle();
 
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
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
361 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