MACD Format, Triggers, Scan, Label, Watchlist For ThinkOrSwim

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

@kshires4 You're looking for a watchlist column that displays whether the stock is above 200 EMA or below?
 
@trinimore Its been a bit since you asked, but here is a MACD watchlist column. The columns are'nt exactly "plug-and-play"; you will have to do a bit of work to get the MTF appearance.
1) When you copy and paste the code, you will need to create three separate watchlist columns.
2) Change the timeframe of each column to the different timeframes of your preference.
3) In the code, where is says " input name = "MACD Short"; " change the quoted text as appropriate to "MACD Mid" and "MACD Long".
Here is the watchlist code -
Code:
#Watchlist Column
#change timeframe settings above by the column name

input length1 = 12;
input length2 = 26;
input length3 = 9;
input name = "MACD Short";

def value = ExpAverage(close, length1) - ExpAverage(close, length2);
def average = ExpAverage(value, length3);

AddLabel(1,name,color.black);

AssignBackgroundColor(if value > average then color.green
                      else if value == average then color.gray
                      else color.red);



@yman Is this similar to what you want?
Code:
#Chart Label
input length1 = 12;
input length2 = 26;
input length3 = 9;
input agg = aggregationperiod.FIVE_MIN;

def c = close(period = agg);

def value = ExpAverage(c, length1) - ExpAverage(c, length2);
def average = ExpAverage(value, length3);

AddLabel(1,if value > average then "MACD is crossed above"
             else if value == average then "MACD is Equal"
             else "MACD is crossed below",
         if value > average then color.green
             else if value == average then color.gray
             else color.red);



@kshires4 How exactly do you want the 200 EMA condition to be stated? Are you looking only for a cross up of the MACD when price is also above the 200 EMA? I dont understand exactly how you want the 200 EMA as part of your condition.
 
@trinimore Its been a bit since you asked, but here is a MACD watchlist column. The columns are'nt exactly "plug-and-play"; you will have to do a bit of work to get the MTF appearance.
1) When you copy and paste the code, you will need to create three separate watchlist columns.
2) Change the timeframe of each column to the different timeframes of your preference.
3) In the code, where is says " input name = "MACD Short"; " change the quoted text as appropriate to "MACD Mid" and "MACD Long".
Here is the watchlist code -
Code:
#Watchlist Column
#change timeframe settings above by the column name

input length1 = 12;
input length2 = 26;
input length3 = 9;
input name = "MACD Short";

def value = ExpAverage(close, length1) - ExpAverage(close, length2);
def average = ExpAverage(value, length3);

AddLabel(1,name,color.black);

AssignBackgroundColor(if value > average then color.green
                      else if value == average then color.gray
                      else color.red);



@yman Is this similar to what you want?
Code:
#Chart Label
input length1 = 12;
input length2 = 26;
input length3 = 9;
input agg = aggregationperiod.FIVE_MIN;

def c = close(period = agg);

def value = ExpAverage(c, length1) - ExpAverage(c, length2);
def average = ExpAverage(value, length3);

AddLabel(1,if value > average then "MACD is crossed above"
             else if value == average then "MACD is Equal"
             else "MACD is crossed below",
         if value > average then color.green
             else if value == average then color.gray
             else color.red);



@kshires4 How exactly do you want the 200 EMA condition to be stated? Are you looking only for a cross up of the MACD when price is also above the 200 EMA? I dont understand exactly how you want the 200 EMA as part of your condition.
If price is above the 200 EMA and MACD turns positive then the watchlist turns green. If price is below 200 EMA and MACD turns negative thens watchlist turns red.
 
@kshires4 Here is a watchlist code with the MACD and 200 EMA conditions. Please verify that it displays the correct information; I didnt check the display results.

Code:
#Watchlist Column
#displays "Buy" when price is above the 200 EMA and the MACD value is above the MACD average, and the opposite for "Sell"
#change timeframe settings above by column name

input length1 = 12;
input length2 = 26;
input length3 = 9;

def value = ExpAverage(close, length1) - ExpAverage(close, length2);
def average = ExpAverage(value, length3);

def ema = ExpAverage(close,200);

def condition_up = close > ema and value > average;
def condition_dn = close < ema and value < average;

AddLabel(1,if condition_up then "Buy"
         else if condition_dn then "Sell"
         else " --- ", color.black);

AssignBackgroundColor(if condition_up then color.green
                      else if condition_dn then color.red
                      else color.gray);
# end code
 
Hi, I want to add a label (green/red) to a watchlist column regarding MACD. I am not good with writing code and I have searched around but came up empty.

My premise is that I want the label to be green based on if the MACD, set to 50/100/9, has value above the average and both are above the 0 line. And the inverse of red if that statement is not true.

Any help would be much appreciated. Thanks in advance.

* something like this but with labels :
MACD("fast length" = 50, "slow length" = 100)."Value" is greater than MACD("fast length" = 50, "slow length" = 100)."Avg" and

MACD("fast length" = 50, "slow length" = 100)."Value" is greater than MACD("fast length" = 50, "slow length" = 100)."ZeroLine"
 
@jezzer46 Take the watchlist column code from this post above, and replace the AssignBackgroundColor() line with the line below. You may also want to change the quoted text to something else. ;)
Code:
AssignBackgroundColor(if value > average and average > 0 then color.green else color.red);
 
I hope all of you are doing well. I am trying to create a scanner that would look for a change in color on the bars. I can't for the life of me figure out how to make a scan. I believe it would be the Diff but no luck. I would really appreciate some help. Thank you everyone.
 
Code:
declare lower;
input length  = 21;
input length2 = 34;
input length3 = 21;

script G 
    {
    input iData = close;
    input length = 21;
    def h = high;
    def l = low;
    def c = close;
    def betaDenom = 10 * (Log(Sum((Max(h, c[1]) - Min(l, c[1])), length) /
            (Highest(h, length) - Lowest(l, length)))
            / Log(length));
    def w = (2 * Double.Pi / length);
    def beta = (1 - Cos(w)) / (Power(1.414, 2.0 / betaDenom) - 1 );
    def alpha = (-beta + Sqrt(beta * beta + 2 * beta));
    def G = Power(alpha, 4) * iData + 
                 4 * (1 – alpha) * G[1] – 6 * Power( 1 - alpha, 2 ) * G[2]+ 
                 4 * Power( 1 - alpha, 3 ) * G[3] - Power( 1 - alpha, 4 ) * G[4];
plot data = G;
}
plot a = G(close, length) - G(close, length2);
plot b = G(a, length3);
plot d = a - b;

plot "0" = if IsNaN(close) 
           then Double.NaN 
           else 0;
"0".SetDefaultColor(Color.WHITE);
"0".HideTitle();
a.AssignValueColor(if a > b 
                        then Color.GREEN 
                        else Color.RED);
a.HideBubble();
a.HideTitle();
b.AssignValueColor(if a > b 
                        then Color.GREEN 
                        else Color.RED);
b.HideBubble();
b.HideTitle();
d.SetLineWeight(4);
d.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
d.AssignValueColor(if d > 0 and d > d[1] 
                        then Color.GREEN
                        else if d > 0 and d < d[1] 
                             then Color.BLUE
                             else if d < 0 and d < d[1] 
                             then Color.RED
                        else Color.YELLOW);
d.HideBubble();
AddCloud(a, b, Color.GREEN, Color.RED);
AddVerticalLine(d crosses 0, "", if d crosses above 0 
                                 then Color.GREEN 
                                 else Color.RED);
AddCloud(if Max(a, b) < 0 
         then Max(a, b) 
         else Double.NaN, 0, Color.LIGHT_RED, Color.LIGHT_RED);
AddCloud(if Min(a, b) > 0
         then 0 
         else Double.NaN, Min(a, b), Color.LIGHT_GREEN, Color.LIGHT_GREEN);
AddLabel(1, if Max(a, b) < 0 and a < b
            then "Trend Down"
            else if Max(a, b) < 0 and a > b
            then "Trend Down Slowing"
            else if between(0, b, a) and d > d[1]
            then "Trend Reversing"
            else if Min(a, b) > 0 and a > b
            then "Trend Up"
            else if Min(a, b) > 0 and a < b
            then "Trend Up Slowing"
            else if Min(a, b) > 0 and d > d[1]
            then "Trend Up Accelerating"
            else if Min(a, b) > 0 and a < b and  d < d[1]
            then "Trend Up decelerating"
            else "Undetermined Trend", if Max(a, b) < 0
                                       then color.light_red
                                       else if Min(a, b) > 0
                                       then color.light_green
                                       else color.white);

           

# End Code GACD
 
I did this thing after finding the watchlist macd code a little while ago.
Its a MACD paintbar nothing fancy. Let me know what you guys think?

Code:
#MACD paintbars by MauiC

input price = close;
input fastLength = 5;
input slowLength = 20;
input MACDLength = 30;
input averageType = AverageType.EXPONENTIAL;
input paintbars = yes;


def Value = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def Avg = MovingAverage(averageType, Value, MACDLength);

def Diff = Value - Avg;
def ZeroLine = 0;

def M1 = value > avg and value and avg >= zeroline;
def M2 = value > avg and value  <= zeroline;
def M3 = value < avg and value  >= zeroline;
def M4 = value < avg and value and avg <= zeroline;
def M5 = Value > avg and value > zeroline and avg < zeroline;
def M6 = Value < avg and value < zeroline and avg > zeroline;

def M7 = M1+ M1[0];
def M8 = M2+ M2[0];
def M9 = M3+ M3[0];
def M10 = M4+ M4[0];
def M11 = M5+ M5[0];
def M12 = M6+ M6[0];

assignPriceColor (if M7 then color.Dark_green else if m8 then color.yellow else if m9 then color.dark_orange else if m10 then color.red else if m11 then color.cyan else if m12 then color.magenta else color.current);


addlabel(M1, "MACD: Strong Bull", color.green);
addlabel(M2, "MACD: Weak Bull", color.yellow);
addlabel(M3, "MACD: Weak Bear ", color.dark_orange);
addlabel(M4, "MACD: Strong Bear ", color.red);
addlabel(M5, "MACD: Shift Bull Strong", color.cyan);
addlabel(M6, "MACD: Shift Bear Strong", color.pink);

#Strong Bullish
AddVerticalLine(M7[0] > M7[1], "Strong Bullish", Color.green, Curve.SHORT_DASH);

#Strong Bearish
AddVerticalLine(M10[0] > M10[1], "Strong Bearish", Color.red, Curve.SHORT_DASH);


#Weak Bull
AddVerticalLine(M8[0] > M8[1], "V UPCross A", Color.yellow, Curve.SHORT_DASH);

#Weak Bear
AddVerticalLine(M9[0] > M9[1], "V DNCross A", Color.dark_orange, Curve.SHORT_DASH);

#Shift Bullish
AddVerticalLine(M11[0] > M11[1], "V UPCross Z", Color.Cyan, Curve.SHORT_DASH);

#Shift Bearish
AddVerticalLine(M12[0] > M12[1], "V DNCross Z", Color.pink, Curve.SHORT_DASH);

###END CODE###
 
Last edited:
How do i turn the below into a dynamic scan? This is actually a default strategy in ToS

Code:
input fastLength = 12;
input slowLength = 26;
input macdLength = 9;
input averageType = AverageType.EXPONENTIAL;
def diff = reference MACD(fastLength, slowLength, macdLength, averageType).Diff;
AddOrder(OrderType.BUY_AUTO, diff crosses above 0, tickColor = GetColor(0), arrowColor = GetColor(0), name = "MACDStratLE");
AddOrder(OrderType.SELL_AUTO, diff crosses below 0, tickColor = GetColor(1), arrowColor = GetColor(1), name = "MACDStratSE");

Someone made it into a chart alert at this link below, I'm looking to create a scan https://www.hahn-tech.com/ans/generate-alerts-from-macdstrat-chart-strategy/
 
Hello I'm trying to write scanner using think script which will calculate daily MACD(12,26,9). Since prices usually always already go higher by the time it crossovers, I was planning to check hourly MACD when daily MACD has not crossed yet. And once hourly MACD crosses then I would get alert via this scanner immediately ahead of daily MACD. So far, I came up with this code below but it doesn't seem to trigger any alerts. I've set it up to run it as hourly so that it will get triggered as soon as hourly MACD crosses signal. Can someone help in fixing this script?

Code:
declare lower;

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

input averageType = AverageType.EXPONENTIAL;

def DailyMACDValue = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def DailyMACDSignal = MovingAverage(averageType, DailyMACDValue, MACDLength);

def HourlyMACDValue = MovingAverage(averageType, close(period = AggregationPeriod.HOUR), fastLength) - MovingAverage(averageType, close(period = AggregationPeriod.HOUR), slowLength);
def HourlyMACDSignal = MovingAverage(averageType, HourlyMACDValue, MACDLength);

def DailyDiff = DailyMACDValue - DailyMACDSignal;
def HourlyDiff = HourlyMACDValue - HourlyMACDSignal;
def ZeroLine = 0;

def DailyMACDCrossover = if DailyDiff is less than ZeroLine then ZeroLine else Double.NaN;
def HourlyMACDCrossover = if HourlyDiff crosses above ZeroLine then ZeroLine else Double.NaN;

plot UpSignal = DailyMACDCrossover and HourlyMACDCrossover;
UpSignal.SetDefaultColor(Color.UPTICK);
UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
 
@serendipity2020 Since the hourly is shorter than the daily timeframe, the crossover will certainly happen on the lower timeframe first. You probably don't need to do anything except scan for the MACD crossover on the hourly chart.
 
Below is the original MACD indicator with a few adjustments such as the crossover colors, alerts function to notify you of bullish and bearish MACD crossovers.

O5dT4kv.png


Code:
#
# TD Ameritrade IP Company, Inc. (c) 2007-2020
#

declare lower;

input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input averageType = AverageType.EXPONENTIAL;
input showBreakoutSignals = no;

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

plot Diff = Value - Avg;
plot ZeroLine = 0;

plot UpSignal = if Diff crosses above ZeroLine then ZeroLine else Double.NaN;
plot DownSignal = if Diff crosses below ZeroLine then ZeroLine else Double.NaN;

UpSignal.SetHiding(!showBreakoutSignals);
DownSignal.SetHiding(!showBreakoutSignals);

Value.SetDefaultColor(GetColor(1));
Avg.SetDefaultColor(GetColor(8));
Diff.SetDefaultColor(GetColor(5));
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"));
ZeroLine.SetDefaultColor(GetColor(0));
UpSignal.SetDefaultColor(Color.UPTICK);
UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
DownSignal.SetDefaultColor(Color.DOWNTICK);
DownSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


Value.AssignValueColor(if value< avg

                     then color.cyan

                     else if avg> value

                     then color.yellow

                     else createColor(0, 0, 204));

# Alerts
Alert(UpSignal, "Bullish MACD Alert", Alert.Bar, Sound.Chimes);
Alert(DownSignal, "Bearish MACD Alert", Alert.Bar, Sound.Bell);

Bubble Containing Date And Price Of MACD Crossover (credit _ZZZ)

Code:
# BubbleContainingDateAndPriceOfMACD_Crossover_ZZZ
#


input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input averageType = AverageType.EXPONENTIAL;

def Value = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def Avg = MovingAverage(averageType, Value, MACDLength);

def Diff = Value - Avg;
def ZeroLine = 0;
def crossover = diff crosses 0;
addchartBubble(crossover,close * 1.05,asprice(getYYYYMMDD())+"\n"+asDollars(close),color.white);
 
Last edited by a moderator:
Awesome bro, Can you suggest me an indicator script that would alert me when the MACD line crosses the Signal line. Would be even better if the alert is displayed as text on the chart!
 
MACD Histogram Crossover

Rich (BB code):
#MACDHistogramCrossover_Paris
#Chatroom Request
#8.30.2018
#Displays number of bars since the last MACDHistogram Crossover signal
#Added logic to display direction of last crossover signal

input ShowEducationLabels = yes;  added by JQ for education purposes

input fastLength = 12;

input slowLength = 26;

input MACDLength = 9;

input averageType = AverageType.EXPONENTIAL;

def Diff = MACD(fastLength, slowLength, MACDLength, averageType).Diff;

def XUp;

def XDn;

if Crosses(Diff, 0, CrossingDirection.BELOW) {

    XUp = no;

    XDn = yes;
}


else if (Crosses(Diff, 0, CrossingDirection.ABOVE)) {

    XUp = yes;

    XDn = no;

}

else {

    XUp = XUp[1];

    XDn = XDn[1];

}

def crossBarUp = if XUp and !XUp[1] then BarNumber() else crossBarUp[1];

def crossBarDn = if XDn and !XDn[1] then BarNumber() else crossBarDn[1];

addlabel(yes,"crossBarUp: " + crossBarUp, color.lime);  added by JQ for education

addlabel(yes,"crossBarDn: " + crossBarDn, color.lime);  added by JQ for education

addlabel(yes,"BarNumber(): " + BarNumber(), color.lime);  added by JQ for education

plot bullSig = if XUp and !XUp[1] then low else Double.NaN;

     bullSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

     bullSig.SetDefaultColor(Color.YELLOW);

     bullSig.SetLineWeight(3);

plot bearSig = if XDn and !XDn[1] then high else Double.NaN;

     bearSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

     bearSig.SetDefaultColor(Color.CYAN);

     bearSig.SetLineWeight(3);

AddLabel(1, "Bars since last MACD Histogram " +

    (if crossBarUp > crossBarDn then "BULLISH"

                                else "BEARISH") + " Crossover:  " +

    (if crossBarUp > crossBarDn then BarNumber() - crossBarUp

                                else BarNumber() - crossBarDn),

    if crossBarUp > crossBarDn then Color.YELLOW else Color.CYAN);

# END STUDY

RvcOxEh.png


A really simple indicator which plot MACD breakout signals directly on your upper chart.

MACD Signals on the Upper Chart

Rich (BB code):
MACD Signals Upper Chart
Mobius
Chat Room Request 03.03.2016
input fastLength = 8;
input slowLength = 21;
input MACDLength = 5;
input averageType = AverageType.EXPONENTIAL;

def Value = MACD(fastLength, slowLength, MACDLength, averageType).Value;
def Avg = MACD(fastLength, slowLength, MACDLength, averageType).Avg;


plot upArrow = if Value < 0 and
                  Value crosses above Avg
                then low
                else double.nan;
upArrow.SetPaintingStrategy(paintingStrategy.Arrow_UP);
upArrow.SetDefaultColor(Color.Green);
upArrow.SetLineWeight(3);


plot dnArrow = if Value > 0 and
                  Value crosses below Avg
                then high
                else double.nan;
dnArrow.SetPaintingStrategy(paintingStrategy.Arrow_DOWN);
dnArrow.SetDefaultColor(Color.Red);
dnArrow.SetLineWeight(3);

Alert(upArrow, "UP", Alert.Bar, Sound.Chimes);
Alert(dnArrow, "DN", Alert.Bar, Sound.Ring);
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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