Multi-TimeFrame (MTF) MACD Indicator for ThinkorSwim

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

I’ve been scalping options the past couple of months and have recently started using the MACD Histogram and have had success with it. Since i scalp, I use a 1/2/3 min chart...speed is critical for me. I also use a 3 and 9 SMA. I wait till the 3 and 9 cross and then my next signal is for all 3 time frames on the MACD Histogram to match up and I enter my trade. What I’d love to have is an all in one chart. Would need to see the 1/2/3 MACD on one histogram. The moment the 1/2/3 histogram is green or red at the same time....have that reflected on one histogram. The signal of 3 and 9 crossing would still need to be the first signal as well...if possible. Is this something anyone here could create? I have ZERO idea how to create these scripts.

Let me see if I can do a better job explaining:

On the 1min chart the 3 and 9 SMA crossing over...up or down...AND 2 consistent colored candles after that crossing, is my first signal to see if the 1min, 2min and 3min MACD histogram have matching bars for the direction the SMA crossed over. I'd like to have the 1/2/3 min MACD histogram populate the color on just one histogram once the 3/9 SMA has crossed over.
 
Hi All,

Happy Sunday!

I used the MTF MACD study (https://usethinkscript.com/threads/multi-timeframe-mtf-macd-indicator-for-thinkorswim.474/) and it worked perfectly.
I'm planning it use it in scan. I understand that scan does not allow secondary aggregation period.I kept a single aggregation period that is HOUR, and converted the DAILY and WEEKLY to hours (i.e. 7 HOURLY bars in a DAILY, and 35 HOURLY bars in a WEEKLY). I get the scan results (woohoo!), but it shows the entry/exit points that are pretty far away in past, (i.e. ~20-35+ bars ago in hourly chart) (as shown in screenshot here - ToS Chart).

Here is the my code for scan. I'm looking for stocks where these entry/exit points are much recent, say just 1 or 2 (hourly) bar from current.



Code:
input fastLength = 12;

input slowLength = 26;

input MACDLength = 9;


#1day = 7 hourly bar

input midTermFastLength = 84;

input midTermSlowLength = 182;

input midTermMACDLength = 63;


#1week = 35 hourly bar

input longTermFastLength = 420;

input longTermSlowLength = 910;

input longTermMACDLength = 315;



# This section is for the chart level MACD

def fastAvg = ExpAverage(close, fastLength);

def slowAvg = ExpAverage(close, slowLength);


def Value = fastAvg - slowAvg;

def Avg = ExpAverage(Value, MACDLength);

def Diff = (Value - Avg) * 3;


# This section is for the medium term MACD

def midTermFastAvg = ExpAverage(close , midTermFastLength);

def midTermSlowAvg = ExpAverage(close , midTermSlowLength);


def midTermValue = midTermFastAvg - midTermSlowAvg;

def midTermAvg = ExpAverage(midTermValue, midTermMACDLength);

def midTermDiff = (midTermValue - midTermAvg) *3;


def midTermLower = midTermDiff < midTermDiff[7];

def midTermHigher = midTermDiff > midTermDiff[7];

rec midTermSignal = if midTermLower then  yes  else if midTermSignal[7] == yes and midTermHigher == no then yes else no;


# This section is for the long term MACD

def longTermFastAvg = ExpAverage(close, longTermFastLength);

def longTermSlowAvg = ExpAverage(close, longTermSlowLength);


def longTermValue = longTermFastAvg - longTermSlowAvg;

def longTermAvg = ExpAverage(longTermValue, longTermMACDLength);

def longTermDiff = (longTermValue - longTermAvg) * 3;



def longTermLower = longTermDiff < longTermDiff[35];

def longTermHigher = longTermDiff > longTermDiff[35];

rec longTermSignal = if longTermLower then  yes  else if longTermSignal[35] == yes and longTermHigher == no then yes else no;


plot entry = Diff > Diff[1] and midTermSignal == no and longTermSignal == no;


#similar for exit scan (only one plot per scan)##

#plot exit = Diff < Diff[1] and midTermSignal == yes and longTermSignal == yes;
 

you can set it up to scan within the last 2 bars using built in tos condition wizard, that video will teach you how to use the condition wizard to scan against your custom codes.
 

you can set it up to scan within the last 2 bars using built in tos condition wizard, that video will teach you how to use the condition wizard to scan against your custom codes.
Actually, custom wizard is disabled in this case due to complex script. Also, can you please highlight in my code (above) where should I put "within last 2 bar" condition(s)?
 
watch the video it will show you how to add custom study's to do what you are trying to do. Insteady of choosing the study he chooses all you have to do is choose your study instead.


Capture.jpg
 
Last edited:
@Jtopaz I am not sure that you are going to generate a great deal of enthusiasm for another MTF MACD indicator given the multitude of existing ones in this forum. Is this one similar to what you posted?
https://usethinkscript.com/threads/multi-timeframe-mtf-macd-indicator-for-thinkorswim.474/#post-8961

In the above thread there are many many versions of MTF MACD. If you really want to garner some interest in your indicator, your best bet would be to explain in detail why you think yours is superior and to illustrate with screenshots: the comparisons, and differences between yours and the ones on this forum. When you put effort into providing the images, the differences, and in explaining how this will improve our trading. It makes it feel more like a team effort. Then armed with all those details, some enterprising poster might become interested in making enhancements to our current indicator.
https://usethinkscript.com/threads/how-to-insert-image-in-a-post-thread.277/

Lastly, keep in mind when using MTF indicators that the current candle will repaint until the higher period closes unless you are doing analysis of the previous candle not the current candle.
Read more here:
https://usethinkscript.com/threads/answers-to-commonly-asked-questions.6006/
 
Last edited:
borrowing the MTF MACD study. I'm halfway there. how do I add a 3rd time frame? can anyone help? :). thanks!

declare lower;
input shortTermPeriod = {"30 min", default "60 min", "120 min", "Daily", "Weekly"};
input midTermPeriod = {"60 min", default "120 min", "Daily", "Weekly", "Monthly"};
input longTermPeriod = {"120 min", default "240 min", "Daily", "Weekly", "Monthly"};

input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;

input shortTermFastLength = 12;
input shortTermFastLength = 26;
input shortTermMACDLength = 9;

input midTermFastLength = 12;
input midTermSlowLength = 26;
input midTermMACDLength = 9;

input longTermFastLength = 12;
input longTermSlowLength = 26;
input longTermMACDLength = 9;

def middleAggregation;

switch (midTermPeriod) {
case "1 min":
middleAggregation = AggregationPeriod.MIN;
case "3 min":
middleAggregation = AggregationPeriod.THREE_MIN;
case "5 min":
middleAggregation = AggregationPeriod.FIVE_MIN;
case "15 min":
middleAggregation = AggregationPeriod.FIFTEEN_MIN;
case "30 min":
middleAggregation = AggregationPeriod.THIRTY_MIN;
case "60 min":
middleAggregation = AggregationPeriod.HOUR;
case "120 min":
middleAggregation = AggregationPeriod.TWO_HOURS;
case "Daily":
middleAggregation = AggregationPeriod.DAY;
case "Weekly":
middleAggregation = AggregationPeriod.WEEK;
case "Monthly":
middleAggregation = AggregationPeriod.MONTH;
}

def highestAggregation;
switch (longTermPeriod) {
case "3 min":
highestAggregation = AggregationPeriod.THREE_MIN;
case "5 min":
highestAggregation = AggregationPeriod.FIVE_MIN;
case "15 min":
highestAggregation = AggregationPeriod.FIFTEEN_MIN;
case "30 min":
highestAggregation = AggregationPeriod.THIRTY_MIN;
case "60 min":
highestAggregation = AggregationPeriod.HOUR;
case "120 min":
highestAggregation = AggregationPeriod.TWO_HOURS;
case "Daily":
highestAggregation = AggregationPeriod.DAY;
case "Weekly":
highestAggregation = AggregationPeriod.WEEK;
case "Monthly":
highestAggregation = AggregationPeriod.MONTH;
}

DefineGlobalColor("UpTrend", color.GREEN);
DefineGlobalColor("DownTrend", color.RED);
DefineGlobalColor("NoTrend", color.LIGHT_GRAY);

def timeFrame = getAggregationPeriod();
def testTimeFrames = if timeFrame < middleAggregation and middleAggregation < highestAggregation then yes else no;

AddLabel(yes, if testTimeFrames then "Indicator is Correct" else "Indicator is Wrong", if testTimeFrames then color.GREEN else color.RED);

def fastAvg = ExpAverage(close, fastLength);
def slowAvg = ExpAverage(close, slowLength);

plot Value = fastAvg - slowAvg;
Value.SetDefaultColor(color.CYAN);
plot Avg = ExpAverage(Value, MACDLength);
Avg.SetDefaultColor(color.YELLOW);
plot Diff = (value - avg)*3;

def midTermFastAvg = ExpAverage(close(period = middleAggregation) , midTermFastLength);
def midTermSlowAvg = ExpAverage(close(period = middleAggregation) , midTermSlowLength);

def midTermValue = midTermFastAvg - midTermSlowAvg;
def midTermAvg = ExpAverage(midTermValue, midTermMACDLength);
plot midTermDiff = (midTermValue - midTermAvg)*3;
midTermDiff.Hide();
midTermDiff.HideBubble();

def longTermFastAvg = ExpAverage(close(period = highestAggregation) , longTermFastLength);
def longTermSlowAvg = ExpAverage(close(period = highestAggregation) , longTermSlowLength);

def longTermValue = longTermFastAvg - longTermSlowAvg;
def longTermAvg = ExpAverage(longTermValue, longTermMACDLength);
plot longTermDiff = (longTermValue - longTermAvg)*3;
longTermDiff.Hide();
longTermDiff.HideBubble();


def midTermLower = midTermDiff < midTermDiff[1];
def midTermHigher = midTermDiff > midTermDiff[1];
rec midTermSignal = if midTermLower then yes else if midTermSignal[1] == yes and midTermHigher == no then yes else no;
#plot test = midTermSignal;
def longTermLower = longTermDiff < longTermDiff[1];
def longTermHigher = longTermDiff > longTermDiff[1];
rec longTermSignal = if longTermLower then yes else if longTermSignal[1] == yes and longTermHigher == no then yes else no;

midTermDiff.AssignValueColor(if midTermSignal then color.RED else color.BLUE);
longTermDiff.AssignValueColor(if longTermSignal then color.RED else color.BLUE);

Diff.AssignValueColor(if Diff > Diff[1] and midTermSignal == no and longTermSignal == no then GlobalColor("UpTrend") else if Diff < Diff[1] and midTermSignal == yes and longTermSignal == yes then GlobalColor("DownTrend") else GlobalColor("NoTrend") );
Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff.SetLineWeight(3);

plot zeroLine = if close[-1] > 0 then 0 else Double.Nan;
zeroLine.AssignValueColor(if Diff > Diff[1] and midTermSignal == no and longTermSignal == no then GlobalColor("UpTrend") else if Diff < Diff[1] and midTermSignal == yes and longTermSignal == yes then GlobalColor("DownTrend") else GlobalColor("NoTrend") );
zeroLine.SetPaintingStrategy(PaintingStrategy.POINTS);
zeroLine.SetLineWeight(3);
 
Last edited:
yes. that's why i posted. I need some help.
I found this script was freely made available by Han Tech, so I tried to help you with the following modified script.

To help understand why you were getting errors, the changes made to the switch statements caused the most errors. You used less timeframes than Han's original. The cases in the switch must match those in the input. I added the short term code that you can test. In essence you now have 4 macd's, the chart agg and the short, middle and long term one's.

Ruby:
#Han Tech script modified to include an additonal short term period requested by usethinkscript member @vro3 
declare lower;
input shortTermPeriod = {"30 min", default "60 min", "120 min", "Daily", "Weekly"};
input midTermPeriod   = {"60 min", default "120 min", "Daily", "Weekly", "Monthly"};
input longTermPeriod  = {"120 min", default "240 min", "Daily", "Weekly", "Monthly"};

input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;

input shortTermFastLength = 12;
input shortTermSlowLength = 26;
input shortTermMACDLength = 9;

input midTermFastLength = 12;
input midTermSlowLength = 26;
input midTermMACDLength = 9;

input longTermFastLength = 12;
input longTermSlowLength = 26;
input longTermMACDLength = 9;

def shorttermaggregation;
switch (shortTermPeriod) {
case "30 min":
    shorttermaggregation = AggregationPeriod.THIRTY_MIN;
case "60 min":
    shorttermaggregation = AggregationPeriod.HOUR;
case "120 min":
    shorttermaggregation = AggregationPeriod.TWO_HOURS;
case "Daily":
    shorttermaggregation = AggregationPeriod.DAY;
case "Weekly":
    shorttermaggregation = AggregationPeriod.WEEK;
}

def middleaggregation;
switch (midTermPeriod) {
case "60 min":
    middleaggregation = AggregationPeriod.HOUR;
case "120 min":
    middleaggregation = AggregationPeriod.TWO_HOURS;
case "Daily":
    middleaggregation = AggregationPeriod.DAY;
case "Weekly":
    middleaggregation = AggregationPeriod.WEEK;
case "Monthly":
    middleaggregation = AggregationPeriod.MONTH;
}

def highestaggregation;
switch (longTermPeriod) {
case "120 min":
    highestaggregation = AggregationPeriod.TWO_HOURS;
case "240 min":
    highestaggregation = AggregationPeriod.FOUR_HOURS;
case "Daily":
    highestaggregation = AggregationPeriod.DAY;
case "Weekly":
    highestaggregation = AggregationPeriod.WEEK;
case "Monthly":
    highestaggregation = AggregationPeriod.MONTH;
}


DefineGlobalColor("UpTrend", Color.GREEN);
DefineGlobalColor("DownTrend", Color.RED);
DefineGlobalColor("NoTrend", Color.LIGHT_GRAY);


def timeFrame      = GetAggregationPeriod();
def testTimeFrames = if timeFrame < shorttermaggregation and shorttermaggregation <middleaggregation and middleaggregation < highestaggregation then yes else no;

AddLabel(yes, if testTimeFrames then "Indicator is Correct" else "Indicator is Wrong", if testTimeFrames then Color.GREEN else Color.RED);

def fastAvg = ExpAverage(close, fastLength);
def slowAvg = ExpAverage(close, slowLength);

plot Value = fastAvg - slowAvg;
Value.SetDefaultColor(Color.CYAN);
plot Avg = ExpAverage(Value, MACDLength);
Avg.SetDefaultColor(Color.YELLOW);
plot Diff = (Value - Avg) * 3;

def shortTermFastAvg = ExpAverage(close(period = shorttermaggregation) , shortTermFastLength);
def shortTermSlowAvg = ExpAverage(close(period = shorttermaggregation) , shortTermSlowLength);

def shortTermValue = shortTermFastAvg - shortTermSlowAvg;
def shortTermAvg   = ExpAverage(shortTermValue, shortTermMACDLength);
plot shortTermDiff = (shortTermValue - shortTermAvg) * 3;
shortTermDiff.Hide();
shortTermDiff.HideBubble();

def midTermFastAvg = ExpAverage(close(period = middleaggregation) , midTermFastLength);
def midTermSlowAvg = ExpAverage(close(period = middleaggregation) , midTermSlowLength);

def midTermValue = midTermFastAvg - midTermSlowAvg;
def midTermAvg   = ExpAverage(midTermValue, midTermMACDLength);
plot midTermDiff = (midTermValue - midTermAvg) * 3;
midTermDiff.Hide();
midTermDiff.HideBubble();

def longTermFastAvg = ExpAverage(close(period = highestaggregation) , longTermFastLength);
def longTermSlowAvg = ExpAverage(close(period = highestaggregation) , longTermSlowLength);

def longTermValue = longTermFastAvg - longTermSlowAvg;
def longTermAvg   = ExpAverage(longTermValue, longTermMACDLength);
plot longTermDiff = (longTermValue - longTermAvg) * 3;
longTermDiff.Hide();
longTermDiff.HideBubble();

def shortTermLower  = shortTermDiff < shortTermDiff[1];
def shortTermHigher = shortTermDiff > shortTermDiff[1];
rec shortTermSignal = if shortTermLower
                      then yes
                      else if shortTermSignal[1] == yes and shortTermHigher == no
                      then yes else no;

def midTermLower  = midTermDiff < midTermDiff[1];
def midTermHigher = midTermDiff > midTermDiff[1];
rec midTermSignal = if midTermLower
                    then yes
                    else if midTermSignal[1] == yes and midTermHigher == no
                    then yes else no;

#plot test = midTermSignal;
def longTermLower  = longTermDiff < longTermDiff[1];
def longTermHigher = longTermDiff > longTermDiff[1];
rec longTermSignal = if longTermLower
                     then yes
                     else if longTermSignal[1] == yes and longTermHigher == no
                     then yes else no;

shortTermDiff.AssignValueColor(if shortTermSignal then Color.RED else Color.BLUE);
midTermDiff.AssignValueColor(if midTermSignal then Color.RED else Color.BLUE);
longTermDiff.AssignValueColor(if longTermSignal then Color.RED else Color.BLUE);

Diff.AssignValueColor(if Diff > Diff[1] and shorttermsignal == no and
                         midTermSignal == no and longTermSignal == no
                      then GlobalColor("UpTrend")
                      else if Diff < Diff[1] and shorttermsignal == yes and
                              midTermSignal == yes and longTermSignal == yes
                      then GlobalColor("DownTrend")
                      else GlobalColor("NoTrend") );
Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff.SetLineWeight(3);

plot zeroLine = if close[-1] > 0 then 0 else Double.NaN;
zeroLine.AssignValueColor(if Diff > Diff[1] and shorttermsignal == no and
                             midTermSignal == no and longTermSignal == no
                          then GlobalColor("UpTrend")
                          else if Diff < Diff[1] and shorttermsignal == yes and
                                  midTermSignal == yes and longTermSignal == yes
                          then GlobalColor("DownTrend")
                          else GlobalColor("NoTrend") );
zeroLine.SetPaintingStrategy(PaintingStrategy.POINTS);
zeroLine.SetLineWeight(3);
 
Last edited:
So, my two cents: I've seen backed tested the confluence of hourly, 2 hour and 4 hour MACD in the same direction being really solid buy / sell signals. I don't use TV, and I know there's a indie that does that, I'm trying me best to recreate, but found my limitations. @SleepyZ - yours is great! I'm trying to weed through the difference. Looks like its an avg of the three. which, might be fine if I can translate! :). Thank you so so much for the help! I'll keep trying too, and if anyone has more input, always willing to learn! Thank you!
 
So, my two cents: I've seen backed tested the confluence of hourly, 2 hour and 4 hour MACD in the same direction being really solid buy / sell signals. I don't use TV, and I know there's a indie that does that, I'm trying me best to recreate, but found my limitations. @SleepyZ - yours is great! I'm trying to weed through the difference. Looks like its an avg of the three. which, might be fine if I can translate! :). Thank you so so much for the help! I'll keep trying too, and if anyone has more input, always willing to learn! Thank you!

This might help your analysis. This code has 3 macd aggregations you can choose. These use the 'diff' above/below zero as the criteria, however you can use any of the 3 plots available (value, avg and diff) to create other results. Just name a plot for example, plot value1 = macd(agg1).value; instead of the diff1 plot, etc to use the macd value per aggregation.

I have the script added to the upper panel with the plots unchecked to display at the input screen and also in the lower panel. When all 3 plot's colors align in one direction, I have added a cloud that will stay until all 3 plots align in the opposite direction.

Capture.jpg

Ruby:
declare lower;
script macd {
    input agg        = AggregationPeriod.TWO_MIN;
    input fastLength = 12;
    input slowLength = 26;
    input MACDLength = 9;

    input averageType = AverageType.EXPONENTIAL;

    plot Value = MovingAverage(averageType, close(period = agg), fastLength) - MovingAverage(averageType, close(period = agg), slowLength);
    plot Avg = MovingAverage(averageType, Value, MACDLength);

    plot Diff = Value - Avg;
}

input agg1 = AggregationPeriod.HOUR;
input agg2 = AggregationPeriod.TWO_HOURS;
input agg3 = AggregationPeriod.FOUR_HOURS;
plot diff1 = MACD(agg1).Diff;
plot diff2 = MACD(agg2).Diff;
plot diff3 = MACD(agg3).Diff;
diff1.AssignValueColor(if diff1 >= 0 then Color.GREEN else Color.RED);
diff2.AssignValueColor(if diff2 >= 0 then Color.GREEN else Color.RED);
diff3.AssignValueColor(if diff3 >= 0 then Color.GREEN else Color.RED);

def xdiff1 = diff1 >= 0;
def xdiff2 = diff2 >= 0;
def xdiff3 = diff3 >= 0;
def sumdiff = xdiff1 + xdiff2 + xdiff3;

input showcloud = yes;
def cloudcolor  = if sumdiff == 3 then 1 else if cloudcolor[1] == 1 and sumdiff != 0 then 1 else 0;
def ccolor = cloudcolor;
AddCloud(if showcloud and ccolor == 1 then Double.POSITIVE_INFINITY else Double.NaN, Double.NEGATIVE_INFINITY, Color.LIGHT_GREEN, Color.LIGHT_GREEN);
AddCloud(if showcloud and ccolor == 0 then Double.POSITIVE_INFINITY else Double.NaN, Double.NEGATIVE_INFINITY, Color.LIGHT_RED, color2 = Color.LIGHT_RED);
 
This might help your analysis. This code has 3 macd aggregations you can choose. These use the 'diff' above/below zero as the criteria, however you can use any of the 3 plots available (value, avg and diff) to create other results. Just name a plot for example, plot value1 = macd(agg1).value; instead of the diff1 plot, etc to use the macd value per aggregation.

I have the script added to the upper panel with the plots unchecked to display at the input screen and also in the lower panel. When all 3 plot's colors align in one direction, I have added a cloud that will stay until all 3 plots align in the opposite direction.
god bless this is amazing. Thank you so much for your help! This is different than what I was watching, but i think I'll be able to figure it out. so far - I can't get it to work on a time frame higher than 1hr. I've been used to using a daily chart, and watching the three MACDs. been hiding and enabling different lines in the original code. Not writing all this to complain - just to update on my process! attached is an example of when the TV code triggered on MARA, and I'm trying to figure out what the equivalent is on TOS. Are my eyes missing something? (also, partially colorblind, will admit that. lol) Thanks!!
 
updated the imgur with a couple real world use cases below the side by side. @SleepyZ - looks like your color cloud turns black on the moment they all agree, yes? then, stays in that same color. so, the alert would be from color to no color, yes? I'll do the research, but is that moment, when all three match color alterable, or able to make a drawing, color cloud, etc? that's what I'm personally watching for. THANK YOU! :
 
god bless this is amazing. Thank you so much for your help! This is different than what I was watching, but i think I'll be able to figure it out. so far - I can't get it to work on a time frame higher than 1hr. I've been used to using a daily chart, and watching the three MACDs. been hiding and enabling different lines in the original code. Not writing all this to complain - just to update on my process! attached is an example of when the TV code triggered on MARA, and I'm trying to figure out what the equivalent is on TOS. Are my eyes missing something? (also, partially colorblind, will admit that. lol) Thanks!!

You cannot use a higher chart aggregation than the aggregations in the code. So if you want to view that code on a Daily chart aggregation then you would have to use Daily or Above for the code aggregations.

So here is the Daily chart of AAPL with the inputs changed to Day,, 2 Days and 3 Days

 
I’ve been scalping options the past couple of months and have recently started using the MACD Histogram and have had success with it. Since i scalp, I use a 1/2/3 min chart...speed is critical for me. I also use a 3 and 9 SMA. I wait till the 3 and 9 cross and then my next signal is for all 3 time frames on the MACD Histogram to match up and I enter my trade. What I’d love to have is an all in one chart. Would need to see the 1/2/3 MACD on one histogram. The moment the 1/2/3 histogram is green or red at the same time....have that reflected on one histogram. The signal of 3 and 9 crossing would still need to be the first signal as well...if possible. Is this something anyone here could create? I have ZERO idea how to create these scripts.

Let me see if I can do a better job explaining:

On the 1min chart the 3 and 9 SMA crossing over...up or down...AND 2 consistent colored candles after that crossing, is my first signal to see if the 1min, 2min and 3min MACD histogram have matching bars for the direction the SMA crossed over. I'd like to have the 1/2/3 min MACD histogram populate the color on just one histogram once the 3/9 SMA has crossed over.

@Hypoluxa I made an attempt to code a single MACD histogram based on your idea. Don't know if it works or not as it hasn't been tested, but here's what I got. Hope this helps:

Code:
# Experimental MTF MACD indicator
# based on code from Hahn Tech MTF MACD
# from https://usethinkscript.com/threads/multi-timeframe-mtf-macd-indicator-for-thinkorswim.474/post-3434

declare lower;

input avgType = {SMP, default EXP, HULL, Weighted, Wilders};
input midTermPeriod = {"1 min", "3 min", "5 min", "15 min", "30 min", "60 min", "120 min", "Daily", default "Weekly", "Monthly"};
input longTermPeriod = {"3 min", "5 min", "15 min", "30 min", "60 min", "120 min", "Daily", "Weekly", default "Monthly"};

input shortTermFastLength = 12;
input shortTermSlowLength = 26;
input shortTermMACDLength = 9;

input midTermFastLength = 12;
input midTermSlowLength = 26;
input midTermMACDLength = 9;

input longTermFastLength = 12;
input longTermSlowLength = 26;
input longTermMACDLength = 9;

input showBreakoutSignals = no;

def middleAggregation;

switch (midTermPeriod) {
    case "1 min":
        middleAggregation = AggregationPeriod.MIN;
    case "3 min":
        middleAggregation = AggregationPeriod.THREE_MIN;
    case "5 min":
        middleAggregation = AggregationPeriod.FIVE_MIN;
    case "15 min":
        middleAggregation = AggregationPeriod.FIFTEEN_MIN;
    case "30 min":
        middleAggregation = AggregationPeriod.THIRTY_MIN;
    case "60 min":
        middleAggregation = AggregationPeriod.HOUR;
    case "120 min":
        middleAggregation = AggregationPeriod.TWO_HOURS;
    case "Daily":
        middleAggregation = AggregationPeriod.DAY;
    case "Weekly":
        middleAggregation = AggregationPeriod.WEEK;
    case "Monthly":
        middleAggregation = AggregationPeriod.MONTH;
}

def highestAggregation;
switch (longTermPeriod) {
    case "3 min":
        highestAggregation = AggregationPeriod.THREE_MIN;
    case "5 min":
        highestAggregation = AggregationPeriod.FIVE_MIN;
    case "15 min":
        highestAggregation = AggregationPeriod.FIFTEEN_MIN;
    case "30 min":
        highestAggregation = AggregationPeriod.THIRTY_MIN;
    case "60 min":
        highestAggregation = AggregationPeriod.HOUR;
    case "120 min":
        highestAggregation = AggregationPeriod.TWO_HOURS;
    case "Daily":
        highestAggregation = AggregationPeriod.DAY;
    case "Weekly":
        highestAggregation = AggregationPeriod.WEEK;
    case "Monthly":
        highestAggregation = AggregationPeriod.MONTH;
}


def timeFrame = getAggregationPeriod();
def testTimeFrames = if timeFrame < middleAggregation and middleAggregation < highestAggregation then yes else no;

AddLabel(yes, if testTimeFrames then "Time Frames Are Correct" else "Time Frames Are Wrong", if testTimeFrames then color.GREEN else color.RED);

# for the short term macd
def shortTermValue;
def shortTermAvg;
# for the midterm macd
def midTermValue;
def midTermAvg;
# for the long term macd
def longTermValue;
def longTermAvg;
switch (avgType){
    case SMP:
        shortTermValue = Average(close, shortTermFastLength) - Average(close, shortTermSlowLength);
        shortTermAvg = Average(shortTermValue, shortTermMACDLength);
        midTermValue = Average(close(period = middleAggregation), midTermFastLength) - Average(close(period = middleAggregation), midTermSlowLength);
        midTermAvg = Average(midTermValue, midTermMACDLength);
        longTermValue = Average(close(period = highestAggregation), longTermFastLength) - Average(close(period = highestAggregation), longTermSlowLength);
        longTermAvg = Average(longTermValue, longTermMACDLength);
    case Weighted:
        shortTermValue = WMA(close, shortTermFastLength) - WMA(close, shortTermSlowLength);
        shortTermAvg = WMA(shortTermValue, shortTermMACDLength);
        midTermValue = WMA(close(period = middleAggregation), midTermFastLength) - WMA(close(period = middleAggregation), midTermSlowLength);
        midTermAvg = WMA(midTermValue, midTermMACDLength);
        longTermValue = WMA(close(period = highestAggregation), longTermFastLength) - WMA(close(period = highestAggregation), longTermSlowLength);
        longTermAvg = WMA(longTermValue, longTermMACDLength);
    case Hull:
        shortTermValue = HullMovingAvg(close, shortTermFastLength) - HullMovingAvg(close, shortTermSlowLength);
        shortTermAvg = HullMovingAvg(shortTermValue, shortTermMACDLength);
        midTermValue = HullMovingAvg(close(period = middleAggregation), midTermFastLength) - HullMovingAvg(close(period = middleAggregation), midTermSlowLength);
        midTermAvg = HullMovingAvg(midTermValue, midTermMACDLength);
        longTermValue = HullMovingAvg(close(period = highestAggregation), longTermFastLength) - HullMovingAvg(close(period = highestAggregation), longTermSlowLength);
        longTermAvg = HullMovingAvg(longTermValue, longTermMACDLength);
    case Wilders:
        shortTermValue = WildersAverage(close, shortTermFastLength) - WildersAverage(close, shortTermSlowLength);
        shortTermAvg = WildersAverage(shortTermValue, shortTermMACDLength);
        midTermValue = WildersAverage(close(period = middleAggregation), midTermFastLength) - WildersAverage(close(period = middleAggregation), midTermSlowLength);
        midTermAvg = WildersAverage(midTermValue, midTermMACDLength);
        longTermValue = WildersAverage(close(period = highestAggregation), longTermFastLength) - WildersAverage(close(period = highestAggregation), longTermSlowLength);
        longTermAvg = WildersAverage(longTermValue, longTermMACDLength);
    default:
        shortTermValue = ExpAverage(close, shortTermFastLength) - ExpAverage(close, shortTermSlowLength);
        shortTermAvg = ExpAverage(shortTermValue, shortTermMACDLength);
        midTermValue = ExpAverage(close(period = middleAggregation), midTermFastLength) - ExpAverage(close(period = middleAggregation), midTermSlowLength);
        midTermAvg = ExpAverage(midTermValue, midTermMACDLength);
        longTermValue = ExpAverage(close(period = highestAggregation), longTermFastLength) - ExpAverage(close(period = highestAggregation), longTermSlowLength);
        longTermAvg = ExpAverage(longTermValue, longTermMACDLength);
}

def shortDiff = (shortTermValue - shortTermAvg);
def midTermDiff = (midTermValue - midTermAvg);
def longTermDiff = (longTermValue - longTermAvg);

# This section is for the actual elements that show on the lower study
plot ZeroLine = 0;
ZeroLine.SetStyle(Curve.Short_Dash);
ZeroLine.SetDefaultColor(Color.Light_Gray);
ZeroLine.HideBubble();
ZeroLine.HideTitle();

plot Avg = (shortTermAvg + midTermAvg + longTermAvg) / 3;
Avg.HideBubble();

plot Value = (shortTermValue + midTermValue + longTermValue) / 3;
Value.HideBubble();

plot Diff = (shortDiff + midTermDiff + longTermDiff) / 3;
Diff.DefineColor("UpTrend", color.GREEN);
Diff.DefineColor("UpTrend Down", color.Light_GREEN);
Diff.DefineColor("DownTrend", color.RED);
Diff.DefineColor("DownTrend Up", color.Light_RED);
Diff.DefineColor("NoTrend", color.LIGHT_GRAY);
Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff.AssignValueColor(if Diff > ZeroLine && Diff > Diff[1] then Diff.Color("UpTrend") else if Diff > ZeroLine && Diff < Diff[1] then Diff.Color("UpTrend Down") else if Diff < ZeroLine && Diff < Diff[1] then Diff.Color("DownTrend") else if Diff < ZeroLine && Diff > Diff[1] then Diff.Color("DownTrend Up") else Diff.Color("NoTrend"));
Diff.SetLineWeight(5);
Diff.HideBubble();

# Breakout signals
plot UpSignal = if Diff crosses above ZeroLine then ZeroLine else Double.NaN;
UpSignal.SetHiding(!showBreakoutSignals);
UpSignal.HideBubble();
UpSignal.HideTitle();
UpSignal.SetDefaultColor(Color.UPTICK);
UpSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
plot DownSignal = if Diff crosses below ZeroLine then ZeroLine else Double.NaN;
DownSignal.SetHiding(!showBreakoutSignals);
DownSignal.HideBubble();
DownSignal.HideTitle();
DownSignal.SetDefaultColor(Color.DOWNTICK);
DownSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
 
Last edited:
@horserider is there a way to remove the longer time frame and just leave the weekly. what I want is to plot the weekly MACD onto the daily chart.

It would be really helpful if we could show the daily MACD bar within the weekly bar something like what @RedToGreen did with his volume study.
Ruby:
declare lower;
input midTermPeriod = {"1 min", "3 min", "5 min", "15 min", "30 min", "60 min", "120 min", "Daily", default "Weekly", "Monthly"};
input longTermPeriod = {"3 min", "5 min", "15 min", "30 min", "60 min", "120 min", "Daily", "Weekly", default "Monthly"};

input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;

input midTermFastLength = 12;
input midTermSlowLength = 26;
input midTermMACDLength = 9;

input longTermFastLength = 12;
input longTermSlowLength = 26;
input longTermMACDLength = 9;

def middleAggregation;

switch (midTermPeriod) {
    case "1 min":
        middleAggregation = AggregationPeriod.MIN;
    case "3 min":
        middleAggregation = AggregationPeriod.THREE_MIN;
    case "5 min":
        middleAggregation = AggregationPeriod.FIVE_MIN;
    case "15 min":
        middleAggregation = AggregationPeriod.FIFTEEN_MIN;
    case "30 min":
        middleAggregation = AggregationPeriod.THIRTY_MIN;
    case "60 min":
        middleAggregation = AggregationPeriod.HOUR;
    case "120 min":
        middleAggregation = AggregationPeriod.TWO_HOURS;
    case "Daily":
        middleAggregation = AggregationPeriod.DAY;
    case "Weekly":
        middleAggregation = AggregationPeriod.WEEK;
    case "Monthly":
        middleAggregation = AggregationPeriod.MONTH;
}

def highestAggregation;
switch (longTermPeriod) {
    case "3 min":
        highestAggregation = AggregationPeriod.THREE_MIN;
    case "5 min":
        highestAggregation = AggregationPeriod.FIVE_MIN;
    case "15 min":
        highestAggregation = AggregationPeriod.FIFTEEN_MIN;
    case "30 min":
        highestAggregation = AggregationPeriod.THIRTY_MIN;
    case "60 min":
        highestAggregation = AggregationPeriod.HOUR;
    case "120 min":
        highestAggregation = AggregationPeriod.TWO_HOURS;
    case "Daily":
        highestAggregation = AggregationPeriod.DAY;
    case "Weekly":
        highestAggregation = AggregationPeriod.WEEK;
    case "Monthly":
        highestAggregation = AggregationPeriod.MONTH;
}

DefineGlobalColor("UpTrend", color.GREEN);
DefineGlobalColor("DownTrend", color.RED);
DefineGlobalColor("NoTrend", color.LIGHT_GRAY);

def timeFrame = getAggregationPeriod();
def testTimeFrames = if timeFrame < middleAggregation and middleAggregation < highestAggregation then yes else no;

AddLabel(yes, if testTimeFrames  then "Time Frames Are Correct" else "Time Frames Are Wrong", if testTimeFrames  then color.GREEN else color.RED);

# This section is for the chart level MACD
def fastAvg = ExpAverage(close, fastLength);
def slowAvg = ExpAverage(close, slowLength);

plot Value = fastAvg - slowAvg;
Value.SetDefaultColor(color.CYAN);
plot Avg = ExpAverage(Value, MACDLength);
Avg.SetDefaultColor(color.YELLOW);
plot Diff = (value - avg)*3;

# This section is for the medium term MACD
def midTermFastAvg = ExpAverage(close(period = middleAggregation)[1] , midTermFastLength);
def midTermSlowAvg = ExpAverage(close(period = middleAggregation)[1] , midTermSlowLength);

def midTermValue = midTermFastAvg - midTermSlowAvg;
def midTermAvg = ExpAverage(midTermValue, midTermMACDLength);
plot midTermDiff = (midTermValue - midTermAvg)*3;
midTermDiff.Hide();
midTermDiff.HideBubble();

# This section is for the long term MACD
def longTermFastAvg = ExpAverage(close(period = highestAggregation)[1] , longTermFastLength);
def longTermSlowAvg = ExpAverage(close(period = highestAggregation)[1] , longTermSlowLength);

def longTermValue = longTermFastAvg - longTermSlowAvg;
def longTermAvg = ExpAverage(longTermValue, longTermMACDLength);
plot longTermDiff = (longTermValue - longTermAvg)*3;
longTermDiff.Hide();
longTermDiff.HideBubble();


def midTermLower = midTermDiff < midTermDiff[1];
def midTermHigher = midTermDiff > midTermDiff[1];
rec midTermSignal = if midTermLower then  yes  else if midTermSignal[1] == yes and midTermHigher == no then yes else no;
#plot test = midTermSignal;
def longTermLower = longTermDiff < longTermDiff[1];
def longTermHigher = longTermDiff > longTermDiff[1];
rec longTermSignal = if longTermLower then  yes  else if longTermSignal[1] == yes and longTermHigher == no then yes else no;

midTermDiff.AssignValueColor(if midTermSignal then color.RED else color.BLUE);
longTermDiff.AssignValueColor(if longTermSignal then color.RED else color.BLUE);

def upTrend = Diff > Diff[1] and midTermSignal == no and longTermSignal == no;
def downTrend = Diff < Diff[1] and midTermSignal == yes and longTermSignal == yes;

Diff.AssignValueColor(if upTrend then GlobalColor("UpTrend") else if downTrend then GlobalColor("DownTrend") else GlobalColor("NoTrend") );
Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff.SetLineWeight(3);

def longSignal = upTrend[1] == 1;
plot upTrendAlert = if longSignal  then 0 else Double.NaN;
upTrendAlert.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
upTrendAlert.SetDefaultColor(Color.CYAN);
upTrendAlert.SetLineWeight(3);
Alert(upTrendAlert == 0, "MTF Uptrend", Alert.BAR, Sound.RING);

def shortSignal = downTrend[1] == 1;
plot downTrendAlert = if shortSignal then 0 else Double.NaN;
downTrendAlert.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
downTrendAlert.SetDefaultColor(Color.MAGENTA);
downTrendAlert.SetLineWeight(3);
Alert(downTrendAlert == 0, "MTF Downtrend", Alert.BAR, Sound.RING);


plot zeroLine = if close[-1] > 0 then 0 else Double.Nan;
zeroLine.AssignValueColor(if Diff > Diff[1] and midTermSignal == no and longTermSignal == no then GlobalColor("UpTrend") else if Diff < Diff[1] and midTermSignal == yes and longTermSignal == yes then GlobalColor("DownTrend") else GlobalColor("NoTrend") );
zeroLine.SetPaintingStrategy(PaintingStrategy.POINTS);
zeroLine.SetLineWeight(3);
 
Last edited by a moderator:
@horserider is there a way to remove the longer time frame and just leave the weekly. what I want is to plot the weekly MACD onto the daily chart.

It would be really helpful if we could show the daily MACD bar within the weekly bar something like what @RedToGreen did with his volume study.

See if this helps

Screenshot-2021-08-25-110727.jpg
Ruby:
declare lower;

input aggPeriod = AggregationPeriod.DAY;
input fastLength = 12;
input slowLength = 26;
input signalLength = 9;
input displace = 0;

def MACD = ExpAverage(close(period = aggPeriod)[displace], fastLength) -
ExpAverage(close(period = aggPeriod)[displace], slowLength);
def Signal = ExpAverage(ExpAverage(close(period = aggPeriod)[displace],
fastLength) - ExpAverage(close(period = aggPeriod)[displace], slowLength),
signalLength);
plot Diff = MACD - Signal;
plot ZeroLine = 0;

#MACD.SetDefaultColor(GetColor(1));
#Signal.SetDefaultColor(GetColor(8));
#Diff.SetDefaultColor(color.black);
Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff.SetLineWeight(3);
Diff.DefineColor("Positive and Up", Color.GREEN);
Diff.DefineColor("Positive and Down", Color.DARK_GREEN);
Diff.DefineColor("Negative and Down", Color.RED);
Diff.DefineColor("Negative and Up", Color.DARK_RED);
Diff.AssignValueColor(if Diff >= 0 then if Diff > Diff[1] then Diff.Color("Positive and Up") else Diff.Color("Positive and Down") else if Diff < Diff[1] then Diff.Color("Negative and Down") else Diff.Color("Negative and Up"));
Diff.setlineWeight(2);
ZeroLine.SetDefaultColor(GetColor(0));

#-----------------------------------------------

input aggPeriod1 = AggregationPeriod.WEEK;
input fastLength1 = 12;
input slowLength1 = 26;
input signalLength1 = 9;
input displace1 = 0;

def MACD1 = ExpAverage(close(period = aggPeriod1)[displace1], fastLength1) -
ExpAverage(close(period = aggPeriod1)[displace1], slowLength1);
def Signal1 = ExpAverage(ExpAverage(close(period = aggPeriod1)[displace1],
fastLength1) - ExpAverage(close(period = aggPeriod1)[displace1], slowLength1),
signalLength1);
plot Diff1 = MACD1 - Signal1;


#MACD1.SetDefaultColor(GetColor(1));
#Signal1.SetDefaultColor(GetColor(8));
Diff1.SetDefaultColor(color.black);
Diff1.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff1.SetLineWeight(3);
Diff1.DefineColor("Positive and Up", Color.GREEN);
Diff1.DefineColor("Positive and Down", Color.DARK_GREEN);
Diff1.DefineColor("Negative and Down", Color.RED);
Diff1.DefineColor("Negative and Up", Color.DARK_RED);
#Diff1.AssignValueColor(if Diff1 >= 0 then if Diff1 > Diff1[1] then Diff1.Color("Positive and Up") else Diff1.Color("Positive and Down") else if Diff1 < Diff1[1] then Diff1.Color("Negative and Down") else Diff1.Color("Negative and Up"));
Diff1.setlineWeight(2);
 
Hypoluxa said:
I’ve been scalping options the past couple of months and have recently started using the MACD Histogram and have had success with it. Since i scalp, I use a 1/2/3 min chart...speed is critical for me. I also use a 3 and 9 SMA. I wait till the 3 and 9 cross and then my next signal is for all 3 time frames on the MACD Histogram to match up and I enter my trade. What I’d love to have is an all in one chart. Would need to see the 1/2/3 MACD on one histogram. The moment the 1/2/3 histogram is green or red at the same time....have that reflected on one histogram. The signal of 3 and 9 crossing would still need to be the first signal as well...if possible. Is this something anyone here could create? I have ZERO idea how to create these scripts.

Let me see if I can do a better job explaining:

On the 1min chart the 3 and 9 SMA crossing over...up or down...AND 2 consistent colored candles after that crossing, is my first signal to see if the 1min, 2min and 3min MACD histogram have matching bars for the direction the SMA crossed over. I'd like to have the 1/2/3 min MACD histogram populate the color on just one histogram once the 3/9 SMA has crossed over.

Following is a MACD script that I modified to include the EMAs you are using.

It currently will color the MACD squares and labels according to the DIFF color scheme of the MACDs at the 3 aggs. If all are the same color then the MACD label will be either green/red, if not, then white. Likewise, the EMA label will either be green/red.

The squares are from the top are:
1. Overall - it will only display if all colors are in agreement
2. EMA green/red based on ema1 > ema2
3. Squeeze and divider line
4. Agg1
5. Agg2
6. Agg3

The script header has some additional information.

Screenshot-2021-08-25-121123.jpg
Ruby:
# Choose how the candles are being colored (green/red) in Multiple user defined TimeFrames by one of 4 methods.
# Labels show current color status
# Trend method is similar but not exactly like TTM_Trend
# Move study from lower to upper and select "upper" at the input useupperlower to display dots on upper price panel. Uncheck at input screen "use left axis"
# Using the study on the lower panel, select "lower" at the input useupperlower to lower to display dots on lower panel
# Dots can be turned off/on at the input screen
# Summary line shows only if all colors are the same, otherwise blank.
declare lower;
input method         = {default "MACD", "Close_Close[1]", "HAOpen_HAClose", "Trend", "HHLLS"};
input lineweight     = 2;
input useupper_lower = {default lower, upper};
input showdotplot    = yes;
input agg1           = AggregationPeriod.MIN;
input agg2           = AggregationPeriod.TWO_MIN;
input agg3           = AggregationPeriod.THREE_MIN;

#Heiken Ashi defined
def HAclose1 = ohlc4(period = agg1);
def HAopen1  = CompoundValue( 1, ( HAopen1[1] + HAclose1[1] ) / 2, HAclose1 );
def HAclose2 = ohlc4(period = agg2);
def HAopen2  = CompoundValue( 1, ( HAopen2[1] + HAclose2[1] ) / 2, HAclose2 );
def HAclose3 = ohlc4(period = agg3);
def HAopen3  = CompoundValue( 1, ( HAopen3[1] + HAclose3[1] ) / 2, HAclose3 );

#Trend defined
input trend_lookback = 6;
def HH1      = (Highest(high(period = agg1) , trend_lookback) + Lowest(low(period = agg1), trend_lookback)) / 2;
def Trend1   = close(period = agg1) > HH1;
def HH2      = (Highest(high(period = agg2) , trend_lookback) + Lowest(low(period = agg2), trend_lookback)) / 2;
def Trend2   = close(period = agg2) > HH2;
def HH3      = (Highest(high(period = agg3) , trend_lookback) + Lowest(low(period = agg3), trend_lookback)) / 2;
def Trend3   = close(period = agg3) > HH3;

#MACD
input fastlength = 12;
input slowlength = 26;
input macdlength = 9;
input averagetype = AverageType.EXPONENTIAL;
def Value1 = MovingAverage(averagetype, close(period = agg1), fastlength) - MovingAverage(averagetype, close(period = agg1), slowlength);
def Avg1  = MovingAverage(averagetype, Value1, macdlength);
def MACD1  = Value1 - Avg1;
def Value2 = MovingAverage(averagetype, close(period = agg2), fastlength) - MovingAverage(averagetype, close(period = agg2), slowlength);
def Avg2  = MovingAverage(averagetype, Value2, macdlength);
def MACD2  = Value2 - Avg2;
def Value3 = MovingAverage(averagetype, close(period = agg3), fastlength) - MovingAverage(averagetype, close(period = agg3), slowlength);
def Avg3  = MovingAverage(averagetype, Value3, macdlength);
def MACD3  = Value3 - Avg3;

#HHLLS
input length = 20;
input over_bought = 60;
input signal_line = 50;
input over_sold = 10;
input averageTypehhlls = AverageType.EXPONENTIAL;

Assert(length > 1, "'length' must be greater than one: " + length);

def HS1 = if high (period = agg1) > high(period= agg1)[1] then (high (period= agg1) - Lowest(high (period= agg1), length)) / (Highest(high (period= agg1), length) - Lowest(high (period= agg1), length)) else 0;
def LS1 = if low (period= agg1)< low(period= agg1)[1] then (Highest(low(period= agg1), length) - low(period= agg1)) / (Highest(low(period= agg1), length) - Lowest(low(period= agg1), length)) else 0;

def HHS1 = 100 * MovingAverage(averageTypehhlls, HS1, length);
def LLS1 = 100 * MovingAverage(averageTypehhlls, LS1, length);

def HS2 = if high (period = agg2) > high(period= agg2)[1] then (high (period= agg2) - Lowest(high (period= agg2), length)) / (Highest(high (period= agg2), length) - Lowest(high (period= agg2), length)) else 0;
def LS2 = if low (period= agg2)< low(period= agg2)[1] then (Highest(low(period= agg2), length) - low(period= agg2)) / (Highest(low(period= agg2), length) - Lowest(low(period= agg2), length)) else 0;

def HHS2 = 100 * MovingAverage(averageTypehhlls, HS2, length);
def LLS2 = 100 * MovingAverage(averageTypehhlls, LS2, length);

def HS3 = if high (period = agg3) > high(period= agg3)[1] then (high (period= agg3) - Lowest(high (period= agg3), length)) / (Highest(high (period= agg3), length) - Lowest(high (period= agg3), length)) else 0;
def LS3 = if low (period= agg3)< low(period= agg3)[1] then (Highest(low(period= agg3), length) - low(period= agg3)) / (Highest(low(period= agg3), length) - Lowest(low(period= agg3), length)) else 0;

def HHS3 = 100 * MovingAverage(averageTypehhlls, HS3, length);
def LLS3 = 100 * MovingAverage(averageTypehhlls, LS3, length);

#Method applied to each aggregation

def Agg1per;
def Agg2per;
def Agg3per;
plot Agg1lower;
plot Agg2lower;
plot Agg3lower;
plot Agg4lower;

if method == method."Close_Close[1]" {
    Agg1per = close(period = agg1) > close(period = agg1)[1];
    Agg2per = close(period = agg2) > close(period = agg2)[1];
    Agg3per = close(period = agg3) > close(period = agg3)[1];
} else if method == method."HAOpen_HAClose" {
    Agg1per = HAclose1 > HAopen1;
    Agg2per = HAclose2 > HAopen2;
    Agg3per = HAclose3 > HAopen3;
} else if method == method."Trend" {
    Agg1per = Trend1;
    Agg2per = Trend2;
    Agg3per = Trend3;
} else if method == method."HHLLS" {
    Agg1per = HHS1 > LLS1;
    Agg2per = HHS2 > LLS2;
    Agg3per = HHS3 > LLS3;
} else {
    Agg1per = Value1 > Avg1;
    Agg2per = Value2 > Avg2;
    Agg3per = Value3 > Avg3;
}
        
#Labels with selection to turn them on/off
input showlabels = yes;
AddLabel(showlabels,
            if agg1 / 60000 <= 240
            then (agg1 / 60000 + " Min")
            else if agg1 / 60000 == 1440
            then "Day"
            else if agg1 / 60000 == 10080
            then "Week"
            else if agg1 / 60000 == 43200
            then "Month"
            else " ",
            if (Agg1per == 1 and method == method."HHLLS") or (Agg1per == 1 and method == method."MACD" and Value1 > 0) or (Agg1per == 1 and method != method."MACD" and method != method."HHLLS")
            then Color.GREEN
            else if (Agg1per == 1 and method == method."MACD" and Value1 < 0)
            then Color.DARK_GREEN
            else if (Agg1per == 0 and method == method."MACD" and Value1 < 0)
            then Color.DARK_RED 
            else Color.RED);
AddLabel(showlabels,
            if agg2 / 60000 <= 240
            then (agg2 / 60000 + " Min")
            else if agg2 / 60000 == 1440
            then "Day"
            else if agg2 / 60000 == 10080
            then "Week"
            else if agg2 / 60000 == 43200
            then "Month"
            else " ",
            if (Agg2per == 1 and method == method."HHLLS") or (Agg2per == 1 and method == method."MACD" and Value2 > 0) or (Agg2per == 1 and method != method."MACD" and method != method."HHLLS")
            then Color.GREEN
            else if (Agg2per == 1 and method == method."MACD" and Value2 < 0)
            then Color.DARK_GREEN
            else if (Agg2per == 0 and method == method."MACD" and Value2 < 0)
            then Color.DARK_RED 
            else Color.RED);
AddLabel(showlabels,
            if agg3 / 60000 <= 240
            then (agg3 / 60000 + " Min")
            else if agg3 / 60000 == 1440
            then "Day"
            else if agg3 / 60000 == 10080
            then "Week"
            else if agg3 / 60000 == 43200
            then "Month"
            else " ",
            if (Agg3per == 1 and method == method."HHLLS") or (Agg3per == 1 and method == method."MACD" and Value3 > 0) or (Agg3per == 1 and method != method."MACD" and method != method."HHLLS")
            then Color.GREEN
            else if (Agg3per == 1 and method == method."MACD" and Value3 < 0)
            then Color.DARK_GREEN
            else if (Agg3per == 0 and method == method."MACD" and Value3 < 0)
            then Color.DARK_RED 
            else Color.RED);
#----------------------------------------
#EMA
input length1 = 3;
input length2 = 9;
def ema1 = expaverage(close, length1);
def ema2 = expaverage(close, length2);
def Agg4per = ema1>ema2;

#---------------------------------------

# Label identifying method and color green/red if all green/red otherwise white
def aggsum = Agg1per + Agg2per + Agg3per + Agg4per;
AddLabel(showlabels,
            if method == method."Close_Close[1]"
                  then "C_C[1]"
                  else if method == method."HAOpen_HAClose"
                  then "HAC_HAO"
                  else if method == method."Trend"
                  then "Trend"
                  else if method == method."HHLLS"
                  then "HHLLS"
                  else "MACD" ,
            if Agg1per + Agg2per + Agg3per == 3
            then Color.GREEN
            else if Agg1per + Agg2per + Agg3per == 0
            then Color.RED 
            else Color.WHITE);
addlabel(showlabels, "EMA", if Agg4per == 1 then color.green else color.red);

plot lineh = if IsNaN(close) or showdotplot == no
             then Double.NaN
             else if useupper_lower == useupper_lower.upper then 8  else Double.NaN;
plot linel = if IsNaN(close) or showdotplot == no
             then Double.NaN
             else if useupper_lower == useupper_lower.upper then -8 else Double.NaN;
lineh.SetDefaultColor(Color.DARK_GRAY);
linel.SetDefaultColor(Color.DARK_GRAY);
if IsNaN(close) or showdotplot == no {
    Agg1lower = Double.NaN;
    Agg2lower = Double.NaN;
    Agg3lower = Double.NaN; 
    Agg4lower = Double.NaN;
} else {
    Agg1lower = if !IsNaN(Agg1per) then if useupper_lower == useupper_lower.upper then -8.75 else  6 else Double.NaN;
    Agg2lower = if !IsNaN(Agg2per) then if useupper_lower == useupper_lower.upper then -9.00 else  5 else Double.NaN;
    Agg3lower = if !IsNaN(Agg3per) then if useupper_lower == useupper_lower.upper then -9.25 else  4 else Double.NaN;
    Agg4lower = if !IsNaN(Agg4per) then if useupper_lower == useupper_lower.upper then -7.50 else  8 else Double.NaN;
}

Agg1lower.SetPaintingStrategy(PaintingStrategy.SQUARES);
Agg1lower.SetLineWeight(lineweight);
Agg1lower.AssignValueColor(if (Agg1per == 1 and method != method."MACD") or (Agg1per == 1 and method == method."MACD" and Value1 > 0)
                           then Color.GREEN
                           else if (Agg1per == 1 and method == method."MACD" and Value1 < 0)
                           then Color.DARK_GREEN
                           else if (Agg1per == 0 and method == method."MACD" and Value1 < 0)
                           then Color.DARK_RED 
                           else Color.RED);
Agg2lower.SetPaintingStrategy(PaintingStrategy.SQUARES);
Agg2lower.setlineWeight(lineweight);
Agg2lower.AssignValueColor(if (Agg2per == 1 and method != method."MACD") or (Agg2per == 1 and method == method."MACD" and Value2 > 0)
                           then Color.GREEN
                           else if (Agg2per == 1 and method == method."MACD" and Value2 < 0)
                           then Color.DARK_GREEN
                           else if (Agg2per == 0 and method == method."MACD" and Value2 < 0)
                           then Color.DARK_RED 
                           else Color.RED);
Agg3lower.SetPaintingStrategy(PaintingStrategy.SQUARES);
Agg3lower.setlineWeight(lineweight);
Agg3lower.AssignValueColor(if (Agg3per == 1 and method != method."MACD") or (Agg3per == 1 and method == method."MACD" and Value3 > 0)
                           then Color.GREEN
                           else if (Agg3per == 1 and method == method."MACD" and Value3 < 0)
                           then Color.DARK_GREEN
                           else if (Agg3per == 0 and method == method."MACD" and Value3 < 0)
                           then Color.DARK_RED 
                           else Color.RED);

Agg4lower.SetPaintingStrategy(PaintingStrategy.SQUARES);
Agg4lower.setlineWeight(lineweight);
Agg4lower.AssignValueColor(if Agg4per == 1
                           then Color.GREEN
                           else Color.RED);

plot linediv  =  if IsNaN(close) or showdotplot == no
                 then Double.NaN
                 else if useupper_lower == useupper_lower.upper then -8.0 else 7.0;
plot sumagg   = if IsNaN(close) or showdotplot == no
                 then Double.NaN
                 else if aggsum == 4 or aggsum == 0 then if useupper_lower == useupper_lower.upper then -7.25 else  8.5 else Double.NaN;
sumagg.SetPaintingStrategy(PaintingStrategy.SQUARES);
sumagg.setlineWeight(lineweight);
sumagg.AssignValueColor(if aggsum == 4
                           then Color.GREEN
                           else if aggsum == 0
                           then Color.RED 
                           else Color.WHITE);

#Squeeze Added
input showsqueeze = yes;
def bbupper = reference BollingerBands().UpperBand;
def kcupper = KeltnerChannels().Upper_Band;
def Squeeze  = bbupper - kcupper < 0;
plot Squeezeplot = if showsqueeze and Squeeze then linediv else Double.NaN;
Squeezeplot.SetDefaultColor(Color.BLACK);
Squeezeplot.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeezeplot.SetLineWeight(1);
Squeezeplot.HideBubble();

#Count of Periods in consecutive squeeze
rec countsq = if Squeeze then countsq[1] + 1 else 0;
rec count1sq = if !Squeeze then count1sq[1] + 1 else 0;

#Expansion Bubbles
input n = 5;
def n1  = n + 1;
def c = close;
input showsqueezebubble = yes;

AddChartBubble(showsqueezebubble and !IsNaN(c[n1]) and IsNaN(c[n]),
               linediv[n1] ,
             ( if Squeeze[n1] then "S \n" + Round(countsq[n1], 2) else "NS \n" + count1sq[n1]) ,
               if aggsum[n1] == 4
               then Color.GREEN
               else if aggsum[n1] == 0
               then Color.RED
               else Color.WHITE, up = No);

Alert(Between(aggsum[1], 0, 2) and aggsum == 4 and !Squeeze, "Candles - All Green", Alert.BAR, Sound.Ding);
Alert(Between(aggsum[1], 1, 3) and aggsum == 0 and !Squeeze, "Candles - All Red  ", Alert.BAR, Sound.Ding);
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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