Created TV Zero Lag MACD Indicator for ThinkorSwim

Status
Not open for further replies.

Likos

Member
2019 Donor
By far, my favorite substudy. I would love to use this on ThinkorSwim but I've no idea how to convert the script to TOS. Here are the details below. This code is for the Zero Lag MACD indicator from TradingView.

Rich (BB code):
// ENHANCED ZERO LAG MACD
// Version 1.1
//
// Based on ZeroLag EMA - see Technical Analysis of Stocks and Commodities, April 2000
// Original version by user Glaz. Thanks ! https://www.tradingview.com/chart/EURUSD/UV0YI6Wy-ZeroLag-Macd
// Ideas and code from @yassotreyo version.
// Tweaked by Albert Callisto (AC)
//
// Last Update 20.11.2016
// (AC - 1.0) Histogram with two colors, choice between SMA/EMA (SMA = "Glaz mode"),  names for sub-components, renaming of variables
// (AC - 1.1) Added choice between "Glaz" and legacy algorithm + introduced EMA on MACD (thanks @yassotreyo for your original version)

study(title="Zero Lag MACD Enhanced - Version 1.1", shorttitle="Zero Lag MACD Enhanced 1.1")
source = close

fastLength = input(12, minval=1)
slowLength = input(26, minval=1)
signalLength =input(9, minval=1)
MacdEmaLength =input(9, minval=1)
useEma = input(true, title="Use EMA (otherwise SMA)")
useOldAlgo = input(false, title="Use Glaz algo (otherwise 'real' original zero lag)")

// Fast line
ma1= useEma ? ema(source, fastLength) : sma(source, fastLength)
ma2 = useEma ?  ema(ma1,fastLength) :  sma(ma1,fastLength)
zerolagEMA = ((2 * ma1) - ma2)

// Slow line
mas1=  useEma ? ema(source , slowLength) :  sma(source , slowLength)
mas2 =  useEma ? ema(mas1 , slowLength): sma(mas1 , slowLength)
zerolagslowMA = ((2 * mas1) - mas2)

// MACD line
ZeroLagMACD = zerolagEMA - zerolagslowMA

// Signal line
emasig1 = ema(ZeroLagMACD, signalLength)
emasig2 = ema(emasig1, signalLength)
signal = useOldAlgo ? sma(ZeroLagMACD, signalLength) : (2 * emasig1) - emasig2

hist = ZeroLagMACD - signal

upHist = (hist > 0) ? hist : 0
downHist = (hist <= 0) ? hist : 0

p1 = plot(upHist, color=green, transp=40, style=columns, title='Positive delta')
p2 = plot(downHist, color=purple, transp=40, style=columns, title='Negative delta')

zeroLine = plot(ZeroLagMACD, color=black, transp=0, linewidth=2, title='MACD line')
signaLine = plot(signal, color=gray, transp=0, linewidth=2, title='Signal')

ribbonDiff = hist > 0 ? green : purple
fill(zeroLine, signaLine, color=ribbonDiff)

plot(ema(ZeroLagMACD,MacdEmaLength) , color=red, transp=0, linewidth=2, title='EMA on MACD line')
 
Last edited by a moderator:
Mobius©: Stan I prefer 5,13,3 and using a 5th derivative MACD. Which is the MACD / StDev(MACD, Long_Length)

Here's the Zero Lag MACD Indicator for ThinkorSwim

Rich (BB code):
# Super Zero Lag MACD
# Mobius

declare lower;
input Fast_Length = 5;
input Slow_Length = 13;
input MACD_Length = 3;
plot MACD5 = (MACD("fast length" = Fast_Length,
                   "slow length" = Slow_Length,
                   "macd length" = MACD_Length).Avg /
        StDev(MACD("fast length" = Fast_Length,
                   "slow length" = Slow_Length,
                   "macd length" = MACD_Length).Diff, Slow_Length));
MACD5.SetDefaultColor(Color.CYAN);
plot Squeeze = if BollingerBandsSMA().UpperBand < KeltnerChannels().Upper_Band
               then 0
               else Double.NaN;
Squeeze.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeeze.SetLineWeight(3);
Squeeze.SetDefaultColor(Color.GREEN);
plot zero = if IsNaN(close) or !IsNaN(Squeeze) then Double.NaN else 0;
zero.SetPaintingStrategy(PaintingStrategy.POINTS);
zero.SetLineWeight(2);
zero.SetDefaultColor(Color.BLUE);
AddCloud(zero, MACD5, Color.RED, Color.GREEN);
AddCloud(Squeeze, MACD5, Color.RED, Color.GREEN);
AddLabel(!IsNaN(Squeeze), "Squeeze", if MACD5 > MACD5[1] and
                                MACD5 < 0
                             then Color.GREEN
                             else Color.RED);
def day = GetValue(GetYYYYMMDD(), 1);
def trend = if close > (Highest(high, 21) + Lowest(low, 21)) / 2
            then 1
            else 0;
AddLabel(1, if trend == 1
            then "Trend Up"
            else "Trend Dn",
            if trend == 1
            then Color.Green
            else Color.Red);
 
Last edited:

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

@BenTen I love you. But personally, I like the TradingView one better because the orbs can share when it reaches its maximum potential, buying trend, or etc. The Mobius one I'm not too sure how to use this quite yet.
 
Last edited:
I bought a book that came with a free indicator for MT4 and also the codes. With the purchase of the book I have permission to use the codes to make an indicator for TOS.

Code:
//+------------------------------------------------------------------+

//|                                                MACD_Platinum.mq4 |

//|                                     [email protected] |

//|                               http//www.wix.com/wiseea/wise-ea#! |

//+------------------------------------------------------------------+

#property description   "Version 1.00"

#property description   "Updated on 08/29/2017"

//+------------------------------------------------------------------+

//| Setup & Include                                                  |

//+------------------------------------------------------------------+

#property indicator_separate_window

#property indicator_buffers 10

#property indicator_color1 RoyalBlue

#property indicator_color2 IndianRed

#property indicator_color3 Turquoise

#property indicator_color4 OrangeRed

#property indicator_width1 1

#property indicator_width2 2

#property indicator_width3 1

#property indicator_width4 1

#property indicator_level1 0.0

//+------------------------------------------------------------------+

//| Input parameters                                                 |

//+------------------------------------------------------------------+

input int  Fast               = 12;

input int  Slow               = 26;

input int  Smooth             = 9;

input bool ZeroLag            = true;

input bool ShowMarkersOnCross = true;

input bool PopUp_Alert        = true;

input bool PushNotifications  = false;

//+------------------------------------------------------------------+

//| Global variabels                                                 |

//+------------------------------------------------------------------+

double Macd[];             // = 0

double Avg[];              // = 1

double MarkersUp[];        // = 2

double MarkersDown[];      // = 3

//----

double fastEma[];    // = 4

double slowEma[];    // = 5

double avgEma[];     // = 6

double fastEmaEma[]; // = 7

double slowEmaEma[]; // = 8

double avgEmaEma[];  // = 9

//----

int    Multiplier = 10;   // forex multiplier from Ninja version

static datetime dt;

//+------------------------------------------------------------------+

//| Custom indicator initialization function                         |

//+------------------------------------------------------------------+

int init()

  {

//----

   SetIndexBuffer(0, Macd);

   SetIndexStyle (0, DRAW_LINE,STYLE_DOT,EMPTY);

   SetIndexLabel (0,"Macd");

   SetIndexBuffer(1, Avg);

   SetIndexStyle (1, DRAW_LINE,EMPTY,EMPTY);

   SetIndexLabel (1,"Avg");

   SetIndexBuffer(2, MarkersUp);

   SetIndexStyle (2, DRAW_ARROW,EMPTY,1);

   SetIndexArrow (2, 108);

   SetIndexLabel (2,"UpCross");

   SetIndexBuffer(3, MarkersDown);

   SetIndexStyle (3, DRAW_ARROW,EMPTY,1);

   SetIndexArrow (3, 108);

   SetIndexLabel (3,"DnCross");

//----  

   SetIndexBuffer(4, fastEma);

   SetIndexStyle (4, DRAW_NONE); SetIndexLabel (8,NULL);

   SetIndexBuffer(5, slowEma);

   SetIndexStyle (5, DRAW_NONE); SetIndexLabel (9,NULL);

   SetIndexBuffer(6, avgEma);

   SetIndexStyle (6, DRAW_NONE); SetIndexLabel (10,NULL);

   SetIndexBuffer(7, fastEmaEma);

   SetIndexStyle (7, DRAW_NONE); SetIndexLabel (11,NULL);

   SetIndexBuffer(8, slowEmaEma);

   SetIndexStyle (8, DRAW_NONE); SetIndexLabel (12,NULL);

   SetIndexBuffer(9, avgEmaEma);

   SetIndexStyle (9, DRAW_NONE); SetIndexLabel (13,NULL);

//---- name for DataWindow and indicator subwindow label

   string short_name="MACD_Platinum(" + Fast + ", " + Slow + ", " + Smooth +")";

   IndicatorShortName(short_name);

   IndicatorDigits(4);

   dt=0;

//----

   return(0);

  }

//+------------------------------------------------------------------+

//| Custom indicator deinitialization function                       |

//+------------------------------------------------------------------+

int deinit()

  {

//----

//----

   return (0);

  }

//+------------------------------------------------------------------+

//| MACD_Platinum main function                                      |

//+------------------------------------------------------------------+

int start()

  {

//----

   int limit, counted_bars=IndicatorCounted();

   limit=Bars-Slow+1;

   if(counted_bars>0) limit=Bars-counted_bars-1;

//----  

   for (int i=limit; i>=0; i--)

     {

      double macd=0;

      double macdAvg=0;

      //----

      if (!ZeroLag)

        {

         fastEma = ((2.0 / (1 + Fast)) * (Multiplier*Close) + (1 - (2.0 / (1 + Fast))) * fastEma[i+1]);

            slowEma = ((2.0 / (1 + Slow)) * (Multiplier*Close) + (1 - (2.0 / (1 + Slow))) * slowEma[i+1]);

            macd          = fastEma[i+0] - slowEma[i+0];

            macdAvg      = (2.0 / (1 + Smooth)) * macd + (1 - (2.0 / (1 + Smooth))) * Avg[i+1];

           Macd    = macd;

            Avg     = macdAvg;

          }

       else

          {  

         fastEma    = ((2.0 / (1 + Fast)) * (Multiplier*Close) + (1 - (2.0 / (1 + Fast))) * fastEma[i+1]);

            slowEma    = ((2.0 / (1 + Slow)) * (Multiplier*Close) + (1 - (2.0 / (1 + Slow))) * slowEma[i+1]);

         fastEmaEma = (2.0 / (1 + Fast)) * fastEma + (1 - (2.0 / (1 + Fast))) * fastEmaEma[i+1];

         slowEmaEma = (2.0 / (1 + Slow)) * slowEma + (1 - (2.0 / (1 + Slow))) * slowEmaEma[i+1];

         double differenceFast = fastEma - fastEmaEma;

         double differenceSlow = slowEma - slowEmaEma;

         macd          = ((fastEma+differenceFast) - (slowEma+differenceSlow));            

         Macd       = (macd);

         avgEma     = (2.0 / (1 + Smooth)) * Macd   + (1 - (2.0 / (1 + Smooth))) * avgEma[i+1];

            avgEmaEma  = (2.0 / (1 + Smooth)) * avgEma + (1 - (2.0 / (1 + Smooth))) * avgEmaEma[i+1];

         double differenceAvg = avgEma - avgEmaEma;

         macdAvg = avgEma + differenceAvg;

         Avg  = (macdAvg);

        }

      //---- markers

      MarkersUp  = EMPTY_VALUE;

      MarkersDown= EMPTY_VALUE;  

      if (i>=1 && ShowMarkersOnCross)

        {

         if (Macd > Avg && Macd[i+1] <= Avg[i+1])

           {

            MarkersUp = Avg;

            if (i==1 && dt<Time[0]) alert_sig("Up Cross!");

           }  

         else if (Macd < Avg && Macd[i+1] >= Avg[i+1])

           {

            MarkersDown = Avg;

            if (i==1 && dt<Time[0]) alert_sig("Dn Cross!");

           }

        }

     }

//----

   return(0);

  }

//**

//**

//+------------------------------------------------------------------+

//| FUNCTIONS: Send alerts                                           |

//+------------------------------------------------------------------+

void alert_sig(string comstr)

  {

//----

   string body=TimeToStr(TimeCurrent(),TIME_DATE|TIME_MINUTES)+" | MACD_Platinum | "+comstr;

   if (PopUp_Alert) Alert(body);

   if (PushNotifications) SendNotification(body);

   dt=Time[0];

  }
 
There are so many MACD variations already. Hard to believe it could be something much different than one of those. Why not show a chart or the code and see what happens.
 
I bought a book that came with a free indicator for MT4 and also the codes. With the purchase of the book I have permission to use the codes to make an indicator for TOS.

Code:
//+------------------------------------------------------------------+

//|                                                MACD_Platinum.mq4 |

//|                                     [email protected] |

//|                               http//www.wix.com/wiseea/wise-ea#! |

//+------------------------------------------------------------------+

#property description   "Version 1.00"

#property description   "Updated on 08/29/2017"

//+------------------------------------------------------------------+

//| Setup & Include                                                  |

//+------------------------------------------------------------------+

#property indicator_separate_window

#property indicator_buffers 10

#property indicator_color1 RoyalBlue

#property indicator_color2 IndianRed

#property indicator_color3 Turquoise

#property indicator_color4 OrangeRed

#property indicator_width1 1

#property indicator_width2 2

#property indicator_width3 1

#property indicator_width4 1

#property indicator_level1 0.0

//+------------------------------------------------------------------+

//| Input parameters                                                 |

//+------------------------------------------------------------------+

input int  Fast               = 12;

input int  Slow               = 26;

input int  Smooth             = 9;

input bool ZeroLag            = true;

input bool ShowMarkersOnCross = true;

input bool PopUp_Alert        = true;

input bool PushNotifications  = false;

//+------------------------------------------------------------------+

//| Global variabels                                                 |

//+------------------------------------------------------------------+

double Macd[];             // = 0

double Avg[];              // = 1

double MarkersUp[];        // = 2

double MarkersDown[];      // = 3

//----

double fastEma[];    // = 4

double slowEma[];    // = 5

double avgEma[];     // = 6

double fastEmaEma[]; // = 7

double slowEmaEma[]; // = 8

double avgEmaEma[];  // = 9

//----

int    Multiplier = 10;   // forex multiplier from Ninja version

static datetime dt;

//+------------------------------------------------------------------+

//| Custom indicator initialization function                         |

//+------------------------------------------------------------------+

int init()

  {

//----

   SetIndexBuffer(0, Macd);

   SetIndexStyle (0, DRAW_LINE,STYLE_DOT,EMPTY);

   SetIndexLabel (0,"Macd");

   SetIndexBuffer(1, Avg);

   SetIndexStyle (1, DRAW_LINE,EMPTY,EMPTY);

   SetIndexLabel (1,"Avg");

   SetIndexBuffer(2, MarkersUp);

   SetIndexStyle (2, DRAW_ARROW,EMPTY,1);

   SetIndexArrow (2, 108);

   SetIndexLabel (2,"UpCross");

   SetIndexBuffer(3, MarkersDown);

   SetIndexStyle (3, DRAW_ARROW,EMPTY,1);

   SetIndexArrow (3, 108);

   SetIndexLabel (3,"DnCross");

//---- 

   SetIndexBuffer(4, fastEma);

   SetIndexStyle (4, DRAW_NONE); SetIndexLabel (8,NULL);

   SetIndexBuffer(5, slowEma);

   SetIndexStyle (5, DRAW_NONE); SetIndexLabel (9,NULL);

   SetIndexBuffer(6, avgEma);

   SetIndexStyle (6, DRAW_NONE); SetIndexLabel (10,NULL);

   SetIndexBuffer(7, fastEmaEma);

   SetIndexStyle (7, DRAW_NONE); SetIndexLabel (11,NULL);

   SetIndexBuffer(8, slowEmaEma);

   SetIndexStyle (8, DRAW_NONE); SetIndexLabel (12,NULL);

   SetIndexBuffer(9, avgEmaEma);

   SetIndexStyle (9, DRAW_NONE); SetIndexLabel (13,NULL);

//---- name for DataWindow and indicator subwindow label

   string short_name="MACD_Platinum(" + Fast + ", " + Slow + ", " + Smooth +")";

   IndicatorShortName(short_name);

   IndicatorDigits(4);

   dt=0;

//----

   return(0);

  }

//+------------------------------------------------------------------+

//| Custom indicator deinitialization function                       |

//+------------------------------------------------------------------+

int deinit()

  {

//----

//----

   return (0);

  }

//+------------------------------------------------------------------+

//| MACD_Platinum main function                                      |

//+------------------------------------------------------------------+

int start()

  {

//----

   int limit, counted_bars=IndicatorCounted();

   limit=Bars-Slow+1;

   if(counted_bars>0) limit=Bars-counted_bars-1;

//---- 

   for (int i=limit; i>=0; i--)

     {

      double macd=0;

      double macdAvg=0;

      //----

      if (!ZeroLag)

        {

         fastEma = ((2.0 / (1 + Fast)) * (Multiplier*Close) + (1 - (2.0 / (1 + Fast))) * fastEma[i+1]);

            slowEma = ((2.0 / (1 + Slow)) * (Multiplier*Close) + (1 - (2.0 / (1 + Slow))) * slowEma[i+1]);

            macd          = fastEma[i+0] - slowEma[i+0];

            macdAvg      = (2.0 / (1 + Smooth)) * macd + (1 - (2.0 / (1 + Smooth))) * Avg[i+1];

           Macd    = macd;

            Avg     = macdAvg;

          }

       else

          { 

         fastEma    = ((2.0 / (1 + Fast)) * (Multiplier*Close) + (1 - (2.0 / (1 + Fast))) * fastEma[i+1]);

            slowEma    = ((2.0 / (1 + Slow)) * (Multiplier*Close) + (1 - (2.0 / (1 + Slow))) * slowEma[i+1]);

         fastEmaEma = (2.0 / (1 + Fast)) * fastEma + (1 - (2.0 / (1 + Fast))) * fastEmaEma[i+1];

         slowEmaEma = (2.0 / (1 + Slow)) * slowEma + (1 - (2.0 / (1 + Slow))) * slowEmaEma[i+1];

         double differenceFast = fastEma - fastEmaEma;

         double differenceSlow = slowEma - slowEmaEma;

         macd          = ((fastEma+differenceFast) - (slowEma+differenceSlow));           

         Macd       = (macd);

         avgEma     = (2.0 / (1 + Smooth)) * Macd   + (1 - (2.0 / (1 + Smooth))) * avgEma[i+1];

            avgEmaEma  = (2.0 / (1 + Smooth)) * avgEma + (1 - (2.0 / (1 + Smooth))) * avgEmaEma[i+1];

         double differenceAvg = avgEma - avgEmaEma;

         macdAvg = avgEma + differenceAvg;

         Avg  = (macdAvg);

        }

      //---- markers

      MarkersUp  = EMPTY_VALUE;

      MarkersDown= EMPTY_VALUE; 

      if (i>=1 && ShowMarkersOnCross)

        {

         if (Macd > Avg && Macd[i+1] <= Avg[i+1])

           {

            MarkersUp = Avg;

            if (i==1 && dt<Time[0]) alert_sig("Up Cross!");

           } 

         else if (Macd < Avg && Macd[i+1] >= Avg[i+1])

           {

            MarkersDown = Avg;

            if (i==1 && dt<Time[0]) alert_sig("Dn Cross!");

           }

        }

     }

//----

   return(0);

  }

//**

//**

//+------------------------------------------------------------------+

//| FUNCTIONS: Send alerts                                           |

//+------------------------------------------------------------------+

void alert_sig(string comstr)

  {

//----

   string body=TimeToStr(TimeCurrent(),TIME_DATE|TIME_MINUTES)+" | MACD_Platinum | "+comstr;

   if (PopUp_Alert) Alert(body);

   if (PushNotifications) SendNotification(body);

   dt=Time[0];

  }
This code has a lot of errors in it. Even after making assumptions for the corrections it's unclear how much benefit this would be. It appears from the code that it's using a double EMA (DEMA) vice and EMA.
 
Status
Not open for further replies.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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