Whenever you reference a previous post or some other resource from another site it's very polite to include a link to that resource. Many of our viewers will be wondering where that code came from and would like to be able to click straight through to view the solution in full context.
So before we go any further I will provide a link to that post here:
https://www.hahn-tech.com/ans/scanning-macd-crossing-the-zero-line-in-a-range-of-periods-for-the-first-time/
In that post we find the request was to find the first cross within a specified number of bars. Since you are including that code as a reference point then we will make sure to include that in this solution. Viewers can click that link I just provided to get a full explanation of how the code works.
I see that you want this solution to work as a custom chart study, but display the two lines without the histogram. So I will:
- copy the code from that previous post,
- remove the lines pertaining to the histogram,
- change the def statements for Value and Avg, to display as plots,
- add a new plot for the zero line,
- then add new lines of code to facilitate the crossover signals and alerts
Whew!
declare lower;
input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input lookBack = 60;
input averageType = AverageType.EXPONENTIAL;
plot Value = MovingAverage(averageType, close, fastLength) – MovingAverage(averageType, close, slowLength);
plot Avg = MovingAverage(averageType, Value, MACDLength);
plot centerLine = 0;
def crossAbove = value[1] < 0 and value > 0;
def crossBelow = value[1] > 0 and value < 0;
plot crossAboveSignal = if Highest(crossAbove[1], lookBack) < 1 and crossAbove then centerLine else Double.NaN;
crossAboveSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
crossAboveSignal.SetDefaultColor(Color.CYAN);
plot crossBelowSignal = if Highest(crossBelow[1], lookBack) < 1 and crossBelow then centerLine else Double.NaN;
crossBelowSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOwN);
crossBelowSignal.SetDefaultColor(Color.MAGENTA);
Alert(Highest(crossAbove[1], lookBack) < 1 and crossAbove, "Value Crossing Above Zero", Alert.BAR, Sound.RING);
Alert(Highest(crossBelow[1], lookBack) < 1 and crossBelow, "Value Crossing Below Zero", Alert.BAR, Sound.RING);