OPEN-SOURCE SCRIPT

MACD-X, More Than MACD by DGT

Aggiornato
Moving Average Convergence Divergence – MACD

The most popular indicator used in technical analysis, the moving average convergence divergence (MACD), created by Gerald Appel. MACD is a trend-following momentum indicator, designed to reveal changes in the strength, direction, momentum, and duration of a trend in a financial instrument’s price

Historical evolution of MACD,
- Gerald Appel created the MACD line,
- Thomas Aspray added the histogram feature to MACD
- Giorgos E. Siligardos created a leader of MACD


MACD employs two Moving Averages of varying lengths (which are lagging indicators) to identify trend direction and duration. Then, MACD takes the difference in values between those two Moving Averages (MACD Line) and an EMA of those Moving Averages (Signal Line) and plots that difference between the two lines as a histogram which oscillates above and below a center Zero Line. The histogram is used as a good indication of a security's momentum.

Mathematically expressed as;
macd = ma(source, fast_length) – ma(source, slow_length)
signal = ma(macd, signal_length)
histogram = macd – signal

where exponential moving average (ema) is in common use as a moving average (ma)
fast_length = 12
slow_length = 26
signal_length = 9


The MACD indicator is typically good for identifying three types of basic signals;

Signal Line Crossovers
A Signal Line Crossover is the most common signal produced by the MACD. On the occasions where the MACD Line crosses above or below the Signal Line, that can signify a potentially strong move. The standard interpretation of such an event is a recommendation to buy if the MACD line crosses up through the Signal Line (a "bullish" crossover), or to sell if it crosses down through the Signal Line (a "bearish" crossover). These events are taken as indications that the trend in the financial instrument is about to accelerate in the direction of the crossover.

Zero Line Crossovers
Zero Line Crossovers occur when the MACD Line crossed the Zero Line and either becomes positive (above 0) or negative (below 0). A change from positive to negative MACD is interpreted as "bearish", and from negative to positive as "bullish". Zero crossovers provide evidence of a change in the direction of a trend but less confirmation of its momentum than a signal line crossover

Divergence
Divergence is another signal created by the MACD. Simply, divergence occurs when the MACD and actual price are not in agreement. A "positive divergence" or "bullish divergence" occurs when the price makes a new low but the MACD does not confirm with a new low of its own. A "negative divergence" or "bearish divergence" occurs when the price makes a new high but the MACD does not confirm with a new high of its own. A divergence with respect to price may occur on the MACD line and/or the MACD Histogram

Moving Average Crossovers, another hidden signal that MACD Indicator identifies
Many traders will watch for a short-term moving average to cross above a longer-term moving average and use this to signal increasing upward momentum. This bullish crossover suggests that the price has recently been rising at a faster rate than it has in the past, so it is a common technical buy sign. Conversely, a short-term moving average crossing below a longer-term average is used to illustrate that the asset's price has been moving downward at a faster rate and that it may be a good time to sell.
Moving Average Crossovers in reality is Zero Line Crossovers, the value of the MACD indicator is equal to zero each time the two moving averages cross over each other. For easy interpretation by trades, Zero Line Crossovers are simply described as positive or negative MACD

False signals
Like any forecasting algorithm, the MACD can generate false signals. A false positive, for example, would be a bullish crossover followed by a sudden decline in a financial instrument. A false negative would be a situation where there is bearish crossover, yet the financial instrument accelerated suddenly upwards


What is “MACD-X” and Why it is “More Than MACD”

In its simples form, MACD-X implements variety of different calculation techniques applied to obtain MACD Line, ability to use of variety of different sources, including Volume related sources, and can be plotted along with MACD in the same window and all those features are available and presented within a single indicator, MACD-X

Different calculation techniques lead to different values for MACD Line, as will further discuss below, and as a consequence the signal line and the histogram values will differentiate accordingly. Mathematical calculation of both signal line and the histogram remain the same.

Main features of MACD-X ;

1- Introduces different proven techniques applied on MACD calculation, such as MACD-Histogram, MACD-Leader and MACD-Source, besides the traditional MACD (MACD-TRADITIONAL)

MACD-Traditional, by Gerald Appel

It is the MACD that we know, stated as traditional just to avoid confusion with other techniques used with this study

MACD-Histogram, by Thomas Aspray

The MACD-Histogram measures the distance between MACD and its signal line (the 9-day EMA of MACD). Aspray developed the MACD-Histogram to anticipate signal line crossovers in MACD. Because MACD uses moving averages and moving averages lag price, signal line crossovers can come late and affect the reward-to-risk ratio of a trade. Bullish or bearish divergences in the MACD-Histogram can alert chartists to an imminent signal line crossover in MACD

The MACD-Histogram represents the difference between MACD and its 9-day EMA, the signal line. Mathematically,

macdx = macd - ma(macd, signal_length)

Aspray's contribution served as a way to anticipate (and therefore cut down on lag) possible MACD crossovers which are a fundamental part of the indicator.

Here come a question, what if repeat the same calculations once more (macdh2 = macdh - ma(macdh, signal_length), will it be even better, this question will remain to be tested

MACD-Leader, by Giorgos E. Siligardos, PhD

MACD Leader has the ability to lead MACD at critical situations. Almost all smoothing methods encounter in technical analysis are based on a relative-weighted sum of past prices, and the Leader is no exception. The concealed weights of MACD Leader are such that more relative weight is used in the more recent prices than the respective weights used by the components of MACD. In effect, the Leader expresses more changes in average price dynamics for the recent price movement than MACD, thus eventually leading MACD, especially when significant trend changes are about to take place.

Siligardos creates two less-laggard moving averages indicators in its formula using the same periods as follows

Indicator1 = ma(source, fast_length) + ma(source - ma(source, fast_length), fast_length)
Indicator2 = ma(source, slow_length) + ma(source - ma(source, slow_length), slow_length)

and then take the difference:

Indicator1 - Indicator2

The result is a new MACD Leader indicator

macdx = macd + ma(source - fast_ma, fast_length) - ma(source - slow_ma, slow_length)


MACD-Source, a custom experimental interpretation of mine,

MACD Source, presents an application of MACD that evaluates Source/MA Ratio, relatively with less lag, as a basis for MACD Line, also can be expressed as source convergence/divergence to its moving average. Among the various techniques for removing the lag between price and moving average (MA) of the price, one in particular stands out: the addition to the moving average of a portion of the difference between the price and MA. MACD Source, is based on signal length mean of the difference between Source and average value of shot length and long length moving average of the source (Source/MA Ratio), where the source is actual value and hence no lag and relatively less lag with the average value of moving average of the source . Mathematically expressed as,

macdx = ma(source - avg( ma(source, fast_length), ma(source, slow_length) ), signal_length)

MACD Source provides relatively early crossovers comparing to MACD and better momentum direction indications, assuming the lengths are set to same values

For further details, you are invited to check the following two studies, where the first seeds were sown of the MACD-Source idea
Price Distance to its Moving Averages study, adapts the idea of “Prices high above the moving average (MA) or low below it are likely to be remedied in the future by a reverse price movement", presented in an article by Denis Alajbeg, Zoran Bubas and Dina Vasic published in International Journal of Economics, Commerce and Management
First MACD like interpretation comes with the second study named as “P-MACD”, where P stands for price, P-MACD study attempts to display relationship between Price and its 20 and 200-period moving average. Calculations with P-MACD were based on price distance (convergence/divergence) to its 200-period moving average, and moving average convergence/divergence of 20-period moving average to 200-period moving average of price.
Now as explained above, MACD Source is a one adapted with traditional MACD, where Source stands for Price, Volume Indicator etc, any source applicable with MACD concept


2- Allows usage of variety of different sources, including Volume related indicators

The most common usage of Source for MACD calculation is close value of the financial instruments price. As an experimental approach, this study will allow source to be selected as one of the following series;
• Current Close Price (close)
• Average of High, Low, and Close Price (hlc3)
• On Balance Volume (obv)
• Accumulation Distribution (accdist)
• Price Volume Trend (pvt)

Where,
-Current Close Price and Average of High, Low, and Close Price are price actions of the financial instrument
-Accumulation Distribution is a volume based indicator designed to measure underlying supply and demand
-On Balance Volume (OBV), is a momentum indicator that measures positive and negative volume flow
-Price Volume Trend (PVT) is a momentum based indicator used to measure money flow


3- Can be plotted along with MACD in the same window using the same scaling

Default setting of MACD-X will display MACD-Source with Current Close Price as a source and traditional MACD can be plotted eighter as a companion of MACD-X or can be selected to be plotted alone.
Applying both will add ability to compare, or use as a confirmation of one other

In case, traditional MACD Is plotted along with MACD-X to avoid misinterpreting, the lines plotted, the area between MACD-X Line and Signal-X Line is highlighted automatically, even if the highlight option not selected. Otherwise highlight will be applied only if that option selected

4- 4C Histogram

Histogram is plotted with four colors to emphasize the momentum and direction

5- Customizable

Additional to ability of selecting Calculation Method, Source, plotting along with MACD, there are few other option that allows users to customize the MACD-X indicator

Lengths are configurable, default values are set as 12, 26, 9 respectively for fast, slow and smoothing length. Setting lengths to 8,21,5 respectively Is worth checking, slower length moving averages will lead to less lag and earlier reaction to price actions but yet requires a caution and back testing before applying

Highlight the area between MACD-X Line and Signal-X Line, with colors emphasising the direction

Label can be added to display Calculation Method, Source and Length settings, the aim of this label is to server only as a reminder to trades to be aware of settings while they are occupied with charts, analysis etc.

Here comes another question, which is of more importance having the reminder or having the indicators with multi timeframe feature? Build-in Multi Time Frame features of Pine is not supported when labels and lines introduced in the script, there are other methods but brings complexity. To be studied further, this version will be with labels for time being.



Epilogue

MACD-X is an alternative variant of MACD, the insight/signals provided by MACD are also applicable to MACD-X with early and clear warnings for the changes in the trend.

If MACD is essential to your analysis, then it is my guess that after using the MACD-X for a while and familiarizing yourself with its unique character and personality, you will make it an inseparable companion to other indicators in your charts.

The various signals generated by MACD/MACD-X are easily interpreted and very few indicators in technical analysis have proved to be more reliable than the MACD, and this relatively simple indicator can quickly be incorporated into any short-term trading strategy



Disclaimer: Trading success is all about following your trading strategy and the indicators should fit within your trading strategy, and not to be traded upon solely

The script is for informational and educational purposes only. Use of the script does not constitutes professional and/or financial advice. You alone the sole responsibility of evaluating the script output and risks associated with the use of the script. In exchange for using the script, you agree not to hold dgtrd TradingView user liable for any possible claim for damages arising from any decision you make based on use of the script


Note di rilascio
Squeeze Indicator Add-On:
The applied approach below is derived from John Carter's TTM Squeeze indicator
The Squeeze Indicator measures the relationship between Bollinger Bands and Keltner's Channels to help identify consolidations and signal when prices are likely to break out (whether up or down). The Squeeze Indicator finds sections of the Bollinger Bands which fall inside the Keltner's Channels and in this case the market is said to be in a squeeze (indicator turns off, displayed with grey diamond shapes in MACD-X study). When the volatility increases, so does the distance between the bands, conversely, when the volatility declines, the distance also decreases and in such cases the squeeze is said to be released (indicator turns on, displayed with triangle up or triangle down shapes)
To produce Buy/Sell signals, the Squeeze indicator is plotted along with Momentum Oscillator and with this study it is assumed MACD-X Histogram. When the indicator is on and the MACD-X Histogram is green, it is considered a Buy signal (this signal is supposed to be correct until two green bars in a row). When the indicator is on and the MACD-X Histogram is red, it is considered a Sell signal (this signal is supposed to be correct until two red bars in a row). When the market finishes a move, the indicator turns off (grey) and no trade is recommended

RSI Add-On:
The relative strength indicator (RSI) aims to signal whether a market is considered to be overbought or oversold in relation to recent price levels. MACD measures the relationship between two EMAs (not the case for MACD-Source), while the RSI measures price change in relation to recent price highs and lows. These two indicators are often used together to provide analysts a more complete technical picture of a market.
with this add-on, MACD-X Line will be colored differently when RSI is overbought or oversold zones

thanks @hjsjshs for your valuable suggestion 🙏
Note di rilascio
major update :

* volume based colored bar add-on added - change color of bars based on the current volume compared to its volume average (avearage period : slow length of macd)

* threshold bands for macd histogram add-on added - this may help trades who considers histogram heights as a signal of exhaustion

* label readings enhanced and label position moved away
Note di rilascio
minor update :

TRIX is adapted to MACD-X, where TRIX is a versatile technical analysis tool that combines trend and momentum into one indicator

PS: displaying MACD-TRIX along with Traditional MACD may not be effective due to their different scaling

hugoticu, thanks for suggestion
Note di rilascio
backtest and alertcondition ability added. conditions are macd signal crosses
Note di rilascio
merged labels
Note di rilascio
exit price calculation error fixed when stop loss condition meets

many many thanks for your highly valuable comments sotiri 🙏
Note di rilascio
alert condition enchanced
Note di rilascio
minor update

volume weighted colored bars made configurable
Note di rilascio
Enhancements in BackTest Framework

1-) Historical Data Evaluation
in the real-time processing when the condition is satisfied to avoid repainting the signals are presented on the next bar, this feature was already available with this study
change implemented with this update is to made historical data evaluation behavior same as real-time behavior and all plottings, statistical panel calculations are performed based on the next bar

Hence;
- traders will observe the same behavior both in real-time and in historical bars (even when the study is reloaded)
- trade statistics will display whatever the user traded on the real-time bars with the signals generated
- since the signals are generated on the next bar, “Entry/Exit Price Assumption” input necessity is no longer required, trades with the backtest framework will be assumed as open price on the next candle

2-) Early Warning : Alert + Label
As a rule as explained above, signals are triggered on the next bar in case the condition is still valid and the logic of the study is already aware of the likelihood of an signal occurrence on the next bar but the trader who is analyzing the chart is not (according to this study’s logic of course). So to increase the awareness, with this update ;
 - a label with a warning sign is going to be plotted which of course is subject to repaint but will warn the trader to keep eyes closer on the instrument and proceed trading immediately on the next bar if the signal is confirmed and presented on the chart.
 - for the same warning also an alert is defined (using new alert() function call), so the trader will be able to be notified with the probable not yet confirmed trade opportunity in advance, even if the trader is not monitoring the instrument.
Having said that, I would like to remind : Trading success is all about following your trading strategy and the indicators should fit within your trading strategy, and not to be traded upon solely.

3-) Improved Conditions
 Avoid Sudden Price Changes : Since the long/short conditions are triggered on next bar there might be cases where a sudden change in price direction and hence signal change may occur especially in sideway market conditions with low volatility, this option is to avoid such cases

 Candle Direction as Confirmation : confirms signal if the candle formation is in favor of the trade

Please note : selecting the above options will cause the signals to be executed on the second bar so to have the study non-repaint. For test purposes only you may enable "❗❗❗ Simulate Trade on Next Bar : Only For Test Purpose (REPAINTS)" option to simulate the trade on the next bar.

Important note : stop loss condition will be executed when price fall below the calculated value and trade will be closed with the close price on bar close (not yet able to get the price value at the moment of the cross). Stop loss condition is subject to repainting and to avoid any further loss an alert can be triggered at the moment the first cross is observed. Since stop loss is subject to repaint and in case it happens the statistical panel calculation will not be able to calculate till the bar is closed. You may disable application of stop loss from user dialog box to avoid any inconsistency that may appear on statistical panel and observe results of the trades executed without stop loss.

Other updates in Study
• Enhanced Alerts setup to have two alerts settings for bull condition and two for bear condition, one with the repaint version (early warning) and one non-repaint version (on the next bar if still condition holds true).
backtestDGTExponential Moving Average (EMA)Moving Average Convergence / Divergence (MACD)macd-asmacdcrossmacd-histogrammacd-leadersqueezemomentumttmsqueezeVolume Indicatorvolumebasedbars

Script open-source

In pieno spirito TradingView, l'autore di questo script lo ha pubblicato open-source, in modo che i trader possano comprenderlo e verificarlo. Un saluto all'autore! È possibile utilizzarlo gratuitamente, ma il riutilizzo di questo codice in una pubblicazione è regolato dal nostro Regolamento. Per aggiungerlo al grafico, mettilo tra i preferiti.

Vuoi usare questo script sui tuoi grafici?

Declinazione di responsabilità