Forex Blog

First-hand Forex trading experience and information about foreign exchange market that will be useful to traders

Archives

How to Add Alerts to MetaTrader Indicators

March 22, 2016 (Last updated on September 13, 2018) by

Originally, I intended this post as a do-it-yourself guide on how to add alerts to MetaTrader indicators without knowing how to code at all. But writing it, I came to realization that even if a trader knows nothing about MQL language and coding he will have to learn some basics through this guide because adding alerts does require deep understanding of how MetaTrader code works.

One important thing to understand is that it is not possible to add alerts to indicator without at least some coding. The good thing is that what you will require is so simple that even a 5-year old could do it after reading this post. You have to do three things to add an alert to an indicator:

  1. Add input parameters for turning alerts on/off and adjusting some alert settings — all entirely optional but it is better to have some easy way of configuring things than to re-code everything each time your needs shift.
  2. Identify indicator buffers that are used by an indicator and contain the data you want to be alerted about.
  3. Formulate conditions for alerts to fire up. For example, a classic condition for MACD buy alert could be formulated as: current MACD Signal below current MACD Main and previous MACD Signal above previous MACD Main and both current MACD Signal and MACD Main are below zero. Conditions can be simpler or more complex, but you should already know what you want to be alerted about if you are looking to add alerts to an indicator.

Prerequisites

Before you proceed, make sure that the prerequisites listed below are met:

  • You will need access the indicator’s source code — .mq4 file for MetaTrader 4 and .mq5 file for MetaTrader 5. Sometimes indicators use more than one file for their source code. In such case, you would need .mqh files as well. You will not be able to add alerts to an indicator if you lack its source code. You can ask the indicator’s author for the source code if you only have a compiled file (.ex4 or .ex5).
  • Although you do not need to have prior coding experience to follow this tutorial, you still need to have some understanding of coding basics, for example: how to compile an indicator or what a variable is.
  • You need to pay attention to every step listed in this tutorial. Thoughtless copy/paste will not work here at all.

Input parameters

Theory

You are probably familiar with the different types alerts that exist in MetaTrader:

  • Native alert (popup)
  • Sound alert
  • Email alert
  • Push notifications (mobile)

Most of the time, traders want the plain native alerts but it is a good practice to implement all four at once and to give a choice (via input parameters) to enable and disable certain types of alert. You will learn to add four input parameters: EnableNativeAlerts, EnableSoundAlerts, EnableEmailAlerts, EnablePushAlerts.

Another important input parameter is the candle to use for triggering the alert. Normally, you want the alert to be triggered on the close of the candle #1 when the latest candle (#0) has just started forming — that way you get a final and true alert (unless your indicator repaints itself). Sometimes, traders want to receive their alerts as fast as possible, then looking for alert conditions on candle #0 can be a better choice. Of course, the alert may turn out to be false as the indicator values on candle #0 a susceptible to changes with each new tick. The input parameter that controls the number of trigger candle will be called TriggerCandle. It will be equal to 1 by default, but a trader will be able to change it to 0.

If you plan using email alerts, adding an input parameter for an email subject is also a must. EmailAlertSubject can be set to some fixed string or it can be modified by the alert code during run time. The former case is much simpler of course. Do not forget to enable and configure email alerts in your platform via menu Tools->Options->Email.

If you plan using push notifications to your phone or other mobile device, you need to enable and configure them in your platform via menu Tools->Options->Notifications.

All types of alerts need some text to display or send. AlertText parameter can contain some preset text, which will also be modified according to the particular alert’s parameters.

One additional parameter is useful when using sound alerts — SoundAlertFile. It can be used to set the name of the audio file for the platform to play during alert.

Practice

Find the last line starting with extern (older MT4 indicators) or input (MT5 and newer MT4 indicators) statement. Insert the following code after that line:

input int    TriggerCandle 	= 1;
input bool   EnableNativeAlerts = true;
input bool   EnableSoundAlerts  = true;
input bool   EnableEmailAlerts  = true;
input bool   EnablePushAlerts  = true;
input string AlertEmailSubject  = "";
input string AlertText  	= "";
input string SoundFileName	= "alert.wav";
 
datetime LastAlertTime = D'01.01.1970';
int LastAlertDirection = 0;

This code uses empty initial alert text and email subject. They will be filled during alert evaluation.

Identifying indicator buffers

Explanation

Indicator buffers are the vital part of almost any MetaTrader indicator. They contain the data, which is displayed on the chart or is used in calculations. Finding indicator buffers is very easy. Search for SetIndexBuffer call. You will see one or more lines that look like this (in old MT4 indicators):

SetIndexBuffer(N, Buffer_Name);

or like this (in newer MT4 or MT5 indicators):

SetIndexBuffer(N, Buffer_Name, INDICATOR_*);

Where N is the buffer’s number (you do not need it for alerts) and Buffer_Name is the buffer’s name, which you need to formulate the alert conditions.

Now, the tricky part is to find the right buffers if there are more than one. In MT5 and newer MT4 indicators, you will see this INDICATOR_* parameter in SetIndexBuffer call, which can help determining the right buffers for alert – you will want those with INDICATOR_DATA (they produce the actual display on the chart).

In some cases, determining the right buffer is easy – there might be only one, or it is called appropriately, or you know how the indicator works. In other cases, I would recommend some trial and error work if you do not want to study the code.

Examples

Looking at some real life examples of SetIndexBuffer calls might help you finding the buffer names in the indicators you work on.

Lines 40-41 of the default MACD indicator in MetaTrader 4 show two buffers:

SetIndexBuffer(0,ExtMacdBuffer);
SetIndexBuffer(1,ExtSignalBuffer);

Obviously, ExtMacdBuffer is the main line buffer and ExtSignalBuffer is the signal line buffer.

If you look at the lines 29-31 of the .mq4 source of the CCI Arrows indicator, you will see three buffers there:

SetIndexBuffer(0,dUpCCIBuffer);
SetIndexBuffer(1,dDownCCIBuffer);  
SetIndexBuffer(2,dSellBuffer);

Naturally, you would think that dUpCCIBuffer is for Up-arrows and dDownCCIBuffer is for Down-arrows. But what is dSellBuffer? The thing is that if you search the code for it, you will find that it is not used anywhere at all. It means that you can safely ignore it and base all your alerts on the former two buffers.

The MT5 version of the Aroon Up & Down indicator contains the following lines:

SetIndexBuffer(0, AroonUpBuffer, INDICATOR_DATA);
SetIndexBuffer(1, AroonDnBuffer, INDICATOR_DATA);

Both SetIndexBuffer function calls have INDICATOR_DATA parameters, which means that both buffers (AroonUpBuffer and AroonDnBuffer) contain values plotted on the chart. Clearly, AroonUpBuffer is used for calculation of the Up-line and AroonDnBuffer is used for the Down-line.

Lines 46-47 of the MT5 Coppock indicator also show two buffers:

SetIndexBuffer(0, Coppock, INDICATOR_DATA);
SetIndexBuffer(1, ROCSum, INDICATOR_CALCULATIONS);

The INDICATOR_CALCULATIONS parameter tells us that ROCSum is not an indicator buffer used for display but rather a buffer used for intermediate calculations. Coppock is the only buffer that can be used for alerts here – unsurprisingly so because Coppock indicator is represented by a single histogram.

Alert conditions

Where

Now after you have successfully identified the names of the indicator buffers that you plan using in your alerts, it is time to add the actual alert conditions.

All alerts are appended to the end of the indicator’s main calculation function. In older MetaTrader 4 indicators, it is called int start(). The alert conditions code should be inserted just above the last return(0); statement inside that function. In newer MT4 and in MT5 indicators, the function is called OnCalculate and its declaration can vary from one indicator to another. You have to insert the alert conditions code just above the last return(rates_total); statement inside that function.

What

The actual conditions will differ depending on the alert type you wish to add to the given indicator. This guide will cover the three most popular cases: signal, level, and cross.

Signal

Signal is a type of alert that is triggered when some indicator buffer assumes some non-zero level. Arrow indicators would use this kind of alert normally. Adding alert to the aforementioned MT4 CCI Arrows indicator would look like this:

if (((TriggerCandle > 0) && (Time[0] > LastAlertTime)) || (TriggerCandle == 0))
{
	string Text;
	// Up Arrow Alert
	if ((dUpCCIBuffer[TriggerCandle] > 0) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
	{
		Text = AlertText + "CCI Arrows: " + Symbol() + " - " + EnumToString((ENUM_TIMEFRAMES)Period()) + " - Up.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "CCI Arrows Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = Time[0];
		LastAlertDirection = 1;
	}
	// Down Arrow Alert
	if ((dUpCCIBuffer[TriggerCandle] > 0) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))
	{
		Text = AlertText + "CCI Arrows: " + Symbol() + " - " + EnumToString((ENUM_TIMEFRAMES)Period()) + " - Down.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "CCI Arrows Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = Time[0];
		LastAlertDirection = -1;
	}
}

The code should be added just before the latest return(0); statement inside the start() function.

Adding the same alerts to MT5 version of CCI Arrows is only marginally different:

if (((TriggerCandle > 0) && (time[rates_total - 1] > LastAlertTime)) || (TriggerCandle == 0))
{
	string Text;
	// Up Arrow Alert
	if ((dUpCCIBuffer[rates_total - 1 - TriggerCandle] > 0) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
	{
		Text = AlertText + "CCI Arrows: " + Symbol() + " - " + EnumToString(Period()) + " - Up.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "CCI Arrows Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = time[rates_total - 1];
		LastAlertDirection = 1;
	}
	// Down Arrow Alert
	if ((dUpCCIBuffer[rates_total - 1 - TriggerCandle] > 0) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))
	{
		Text = AlertText + "CCI Arrows: " + Symbol() + " - " + EnumToString(Period()) + " - Down.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "CCI Arrows Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = time[rates_total - 1];
		LastAlertDirection = -1;
	}
}

That code should be inserted just above the latest return(rates_total); statement inside the OnCalculate function. It assumes that the time and buffer arrays are not set as series. If they are, you would need to substitute TriggerCandle for rates_total - 1 - TriggerCandle and time[0] for time[rates_total - 1].

Level

Level alerts are also very simple. If an indicator reaches a certain value (from above or from below), the alert is triggered. Single-line indicators shown in separate window use this kind of alert normally. Here is how the alert conditions for crossing of zero level would look in the MT4 version of Coppock indicator:

if (((TriggerCandle > 0) && (Time[0] > LastAlertTime)) || (TriggerCandle == 0))
{
	string Text;
	// Above Zero Alert
	if (((Coppock[TriggerCandle] > 0) && (Coppock[TriggerCandle+ 1] <= 0)) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
	{
		Text = AlertText + "Coppock: " + Symbol() + " - " + EnumToString((ENUM_TIMEFRAMES)Period()) + " - Above Zero.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Coppock Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = Time[0];
		LastAlertDirection = 1;
	}
	// Below Zero Alert
	if (((Coppock[TriggerCandle] < 0) && (Coppock[TriggerCandle+ 1] >= 0)) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))
	{
		Text = AlertText + "Coppock: " + Symbol() + " - " + EnumToString((ENUM_TIMEFRAMES)Period()) + " - Below Zero.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Coppock Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = Time[0];
		LastAlertDirection = -1;
	}
}

The same for the MT5 version would look like this:

if (((TriggerCandle > 0) && (time[rates_total - 1] > LastAlertTime)) || (TriggerCandle == 0))
{
	string Text;
	// Above Zero Alert
	if (((Coppock[rates_total - 1 - TriggerCandle] > 0) && (Coppock[rates_total - 2 - TriggerCandle] <= 0)) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
	{
		Text = AlertText + "Coppock: " + Symbol() + " - " + EnumToString(Period()) + " - Above Zero.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Coppock Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = time[rates_total - 1];
		LastAlertDirection = 1;
	}
	// Below Zero Alert
	if (((Coppock[rates_total - 1 - TriggerCandle] < 0) && (Coppock[rates_total - 2 - TriggerCandle] >= 0)) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))
	{
		Text = AlertText + "Coppock: " + Symbol() + " - " + EnumToString(Period()) + " - Below Zero.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Coppock Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = time[rates_total - 1];
		LastAlertDirection = -1;
	}
}

As is the case with the previously discussed signal alert for MT5, you would need to substitute TriggerCandle for rates_total - 1 - TriggerCandle and time[0] for time[rates_total - 1] if the indicator sets its buffers as series. Also, rates_total - 2 - TriggerCandle would have to be changed to TriggerCandle+ 1.

Cross

Cross alerts are more complex than the previous two types. They are triggered when some indicator buffer crosses the price line or when two lines of an indicator cross each other, or when several lines cross each other. Let’s look at the cross alert implementation for MT4 Aroon Up & Down indicator. We will look for the Up-line crossing the Down-line from below and from above as two distinct alerts:

if (((TriggerCandle > 0) && (Time[0] > LastAlertTime)) || (TriggerCandle == 0))
{
	string Text;
	// Up-Line Crosses Down-Line from Below
	if (((AroonUpBuffer[TriggerCandle] > AroonDnBuffer[TriggerCandle]) && (AroonUpBuffer[TriggerCandle+ 1] <= AroonDnBuffer[TriggerCandle+ 1])) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
	{
		Text = AlertText + "Aroon Up & Down: " + Symbol() + " - " + EnumToString((ENUM_TIMEFRAMES)Period()) + " - Up-Line Crosses Down-Line from Below.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Aroon Up & Down Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = Time[0];
		LastAlertDirection = 1;
	}
	// Up-Line Crosses Down-Line from Above
	if (((AroonUpBuffer[TriggerCandle] < AroonDnBuffer[TriggerCandle]) && (AroonUpBuffer[TriggerCandle+ 1] >= AroonDnBuffer[TriggerCandle+ 1])) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))
	{
		Text = AlertText + "Aroon Up & Down: " + Symbol() + " - " + EnumToString((ENUM_TIMEFRAMES)Period()) + " - Up-Line Crosses Down-Line from Above.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Aroon Up & Down Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = Time[0];
		LastAlertDirection = -1;
	}
}

The same code for MT5 Aroon Up & Down looks like this:

if (((TriggerCandle > 0) && (time[rates_total - 1] > LastAlertTime)) || (TriggerCandle == 0))
{
	string Text;
	// Up-Line Crosses Down-Line from Below
	if (((AroonUpBuffer[rates_total - 1 - TriggerCandle] > AroonDnBuffer[rates_total - 1 - TriggerCandle]) && (AroonUpBuffer[rates_total - 2 - TriggerCandle] <= AroonDnBuffer[rates_total - 2 - TriggerCandle])) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
	{
		Text = AlertText + "Aroon Up & Down: " + Symbol() + " - " + EnumToString(Period()) + " - Up-Line Crosses Down-Line from Below.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Aroon Up & Down Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = time[rates_total - 1];
		LastAlertDirection = 1;
	}
	// Up-Line Crosses Down-Line from Above
	if (((AroonUpBuffer[rates_total - 1 - TriggerCandle] < AroonDnBuffer[rates_total - 1 - TriggerCandle]) && (AroonUpBuffer[rates_total - 2 - TriggerCandle] >= AroonDnBuffer[rates_total - 2 - TriggerCandle])) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))
	{
		Text = AlertText + "Aroon Up & Down: " + Symbol() + " - " + EnumToString(Period()) + " - Up-Line Crosses Down-Line from Above.";
		if (EnableNativeAlerts) Alert(Text);
		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Aroon Up & Down Alert", Text);
		if (EnableSoundAlerts) PlaySound(SoundFileName);
		if (EnablePushAlerts) SendNotification(Text);
		LastAlertTime = time[rates_total - 1];
		LastAlertDirection = -1;
	}
}

Same as before, substitute TriggerCandle for rates_total — 1 — TriggerCandle and time[0] for time[rates_total — 1] if the indicator uses buffers that are set as series. Again, rates_total — 2 — TriggerCandle would have to be changed to TriggerCandle+ 1 in that case too.

Let’s illustrate the alert generated with these conditions with this screenshot:

Adding Alerts to Aroon Up & Down - Cross Conditions Example

Complex

Of course, the variety of alerts is not limited by the three types described above. Some alerts can have multiple dependencies (e.g. one line crossing the price while two other lines cross each other), other alerts might depend on time, volume, additional calculations, or a combination of various factors. It is even possible to add alerts to indicators that do not use buffers or plot anything on chart.

Such cases are not covered by this DIY guide. Some basic cases can be easily derived from the code snippets offered above while difficult cases are nontrivial ones and demand special approach and extra attention. However, you will certainly learn to add such complex alerts after some practice with the elementary ones.

Summary

In the end, I would like to summarize the alert-adding process with a simple list of steps:

  1. Add the predefined input parameters just below the latest extern or input statement in the indicator’s source code.
  2. Identify the buffer names that represent the indicator’s plot on chart.
  3. Insert the appropriate alert conditions code just above the latest return(0); inside start() function or return(rates_total); inside OnCalculate function.
  4. Replace the buffer names with those that you identified in the second step.

Update 2016-12-21: I have updated the code snippets with correct examples. Previous versions would produce unlimited number of alerts if TriggerCandle was set to 0 (alert on the most current candle).

Update 2018-02-20: Listed the requirements for adding alerts to an indicator and provided instructions for adding push notification alerts to mobile devices.

If you still have some general question about adding alerts to custom MetaTrader indicators or if you want to share your own tips for doing it, please use the commentary form below. If you want help with adding alerts to a specific indicator, please post about it in the forum. All requests for help posted via commentaries to this post will be ignored.

150 Responses to “How to Add Alerts to MetaTrader Indicators”

  1. Maria

    Muchas Gracias, lo entendi todo.

    Reply

  2. zaki

    dear sir ,
    i have one problem my indicator shows repaint…..
    i want to add extra source code file like … source code file of refresh in every minute …is that possible…
    plz kindly reply me.
    i am waiting u r reply.
    thanks

    Reply

    Andriy Moraru Reply:

    Sorry, but I don’t understand your request. Why would you want to add some extra code files to your repainting indicator?

    Reply

  3. zen

    Hi I have a question,
    I’m trying to get an alert to my ADX, everytime DI+ and DI- hitting a value, say 20, I wish to get notified. However the alert is acting strangely it is reapeating the alert over and over again when it does cross the value, it would be realy awesome if you could explain to me what exactly I have to do to fix the problem.

    Thanks in regards

    Reply

    Andriy Moraru Reply:

    Could you please share your indicator source code file and post a link here? So I could look at the problem?

    Reply

  4. zen

    Thank you for your fast response, I’m using the casual Average Directional Movement Index, you can find the whole script in your mt5 Indicators>Examples, I don’t know how to link it but I linked all the critical parts you mentioned in the blog

    inputs & buffers
    https://postimg.org/image/o9wx7vwml/

    alert condition
    https://postimg.org/image/a2i9sesx9/

    Reply

    Andriy Moraru Reply:

    You can share your whole code via http://pastebin.com/ or a similar website.

    Reply

  5. zen

    ah great, there we go

    http://pastebin.com/hRpeCwRc

    Reply

    Andriy Moraru Reply:

    Thanks! I have found an error in the code (mine). Fixed version is here:
    http://pastebin.com/qYnZQ7Ep

    I have also updated the post to prevent such problems with alerts for other users.

    Thanks for reporting the problem!

    Reply

    zen Reply:

    Thank you for your fast response. I hope I set all the parameters correctly, your code is a lifesaver!

    Reply

  6. syed yasir alam

    HELO
    AS u have shown how to add alert for aroon UP and DOWN
    I want to create MACD cross over alert what shoild I do..?

    Reply

    Andriy Moraru Reply:

    Look at the AroonUpDown example and replace the AroonUpDown buffers with the MACD’s signal and main line buffers.

    Reply

  7. Wolfgang

    Thank you very much for your comprehensive post regarding how to code alerts for MT4/MT5 custom indicators.

    Unfortunately, I am currently stuck trying to add an alert to a channel indicator. What I want to do is fairly straight-forward. The alert should be triggered by price on the current candle equaling a certain channel level (in some instances only when price approaches from above, in others only from below).

    To illustrate, please see: http://pastebin.com/McTZw0F6

    I would be grateful, if you could give me advise on how to manipulate the code in order to create said alert.

    Reply

    Andriy Moraru Reply:

    You need to change “==” to “>=” when you want an alert of a price crossing a level from above. And you need to change “==” to “< =" when you want an alert of a price crossing a level from below. Also, you need to check whether the price was above/below the level a period before. For example, the first alert condition in your code should be changed like this:

    if ((MA_upper_Buffer1[TriggerCandle] >= Bid) && (MA_upper_Buffer1[TriggerCandle + 1] < Bid) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))

    Reply

  8. Wolfgang

    That did the trick! A great many thanks to you.

    Despite the risk of coming across as impertinent, could I ask you to give me an idea on how to add a function that pauses the alert for a certain time period (say five minutes, or until the current bar has finished) after it has been triggered?

    Merci beaucoup.

    Reply

    Andriy Moraru Reply:

    Just add LastAlertTime != Time[0] to the conditions. Like this:

    if ((MA_upper_Buffer1[TriggerCandle] >= Bid) && (MA_upper_Buffer1[TriggerCandle + 1] < Bid) && (LastAlertTime != Time[0]) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))

    It will make it trigger only once on the current bar.

    Reply

  9. Wolfgang

    Again, vielen Dank.

    Really, having at least some basic understanding of computer code seems to be indispensable.

    Reply

  10. Patrick

    Great article, thanks for sharing.

    What I would like to know is, is it possible to add the option so you can select custom alert sounds instead of the default alert.wav?

    Reply

    Andriy Moraru Reply:

    Yes, just replace alert.wav with the filename of your choice.

    Reply

    Enigma Misterio Reply:

    so is it possible to add different alert sounds to different indicators?

    Reply

    Andriy Moraru Reply:

    Yes, it is possible. PlaySound() functions takes a sound filename as an argument. Most indicators with alerts (and also the code examples in this post) use an input parameter for the sound filename, which is usually “alert.wav”. You can set a different sound file name for different indicators and have them alert you with different sounds.

    Reply

  11. Mel

    I am a complete technophobe, but I would like to set up an alert when 10ema crosses 20ema. I would appreciate your help

    Reply

    Andriy Moraru Reply:

    You would probably need a custom indicator coded for that.

    Reply

  12. Tricia

    I have a channel indicator that works well, but I would like to add alerts to it when the candle enters the retracement zone of the channel. I understand your steps, but how do I access the code on the indicator so as to add the alerts? Hope you understand my question.

    Reply

    Andriy Moraru Reply:

    Right-click on the indicator in the Navigator window of your platform and select Modify:

    If you there is the source code file for the indicator in your platform, it will open it. Otherwise, you have only an executable (.ex4) and you have to ask the author of the indicator for the source code file (.mq4).

    Reply

  13. Ice

    Thank you sir! But I have a problem: the alert repeats on every new bar:(

    https://pastebin.com/9c84G2YF

    Reply

    Andriy Moraru Reply:

    The problem is because the indicator is written incorrectly – the alert code you’ve added is fine. To fix the issue, just add these two lines to between the current lines 117 and 118:

             ExtMapBuffer5[i] = 0;
             ExtMapBuffer6[i] = 0;

    Also, in case you do not know, this indicator is repainting the arrows – it only draws them 3 bars into the future. E.g., if there is a turn in line, it waits 3 bars to confirm it and then draws an arrow like it appeared 3 bars ago. This also means that you will never get an alert for such an arrow if you set TriggerCandle to 1. If you want to get arrow alerts here, your TriggerCandle should be equal to SignalHP.

    Reply

  14. Ice

    Wow, thanks a lot!

    Reply

  15. justin

    I can get the alert to sound in my own chosen wav file, can you look through it? The wav i want to be played when the pop up box also comes is “Bicycle-Bell-Ringing.wav”

    heres the whole code, it for when stochastics above/below 80/20 and cross back below
    https://pastebin.com/NSbDriRS

    Reply

    Andriy Moraru Reply:

    Please do not submit such huge pieces of code in comments. Either upload your indicator somewhere and share a link or use pastebin.

    As for your questions:

    For PlaySound() to work with your custom .wav file, the file has to be located in /Sounds/ subfolder of your platform’s data folder.

    To change what sound is used when Alert() function is called, go to Toos->OptionsE->Events and change the sound file near Alert:
    How to change default alert sound in MetaTrader 4

    Reply

  16. Daniel Demian

    Andriy.. first of all thanks for sharing your knowledge!
    i use an indicator that have alert code but did not work
    tried to fix as you wrote here, but couldn’t compile then

    Would you mind to help me with it?
    here’s the link
    https://www.mql5.com/pt/code/1910?utm_campaign=codebase.list&utm_medium=special&utm_source=mt5terminal&utm_link=c23d219487dcc91964731d98bd1cdd42&utm_codepage=1046&utm_gid=8881070706134349491&utm_uniq=66D6D7AD-0E29-T-170507

    thank you!!!

    Reply

    Andriy Moraru Reply:

    I do not code on request. As far as I can see, that indicator already has alerts added.

    Reply

    Daniel Demian Reply:

    I did not want to be disrespectful, I do not know anyone who program mql5, the way you explained with this post just thought that at a quick glance you could see what is wrong in the code that does not work the alert and give me a tip How to fix it! Forgive me if I was pretentious, here was the only place I found some good material for this problem !!! thank you

    Reply

    Andriy Moraru Reply:

    You can start a thread about it in our forum about MetaTrader indicators – perhaps, someone will be able to help you out there.

    Reply

    Daniel Demian Reply:

    thank so much

    Reply

  17. DougW

    Thanks for taking the time and patience to write this out. I’ve been trying to understand it for quite awhile. It takes someone like you to completely explain it and that’s not easy to find. I appreciate it.

    Reply

  18. Robert

    Thanks for the post, unfortunately I think I may have made an erro, as I cannot seem to get the script to work. I have pasted it at and would love if you could let me know where I have gone wrong. Apologies for the most likely silly error!
    https://pastebin.com/70UG9t3B

    Reply

    Andriy Moraru Reply:

    Why do you do this?

       ArraySetAsSeries(ExtMainBuffer,false);
       ArraySetAsSeries(ExtSignalBuffer,false);
       ArraySetAsSeries(ExtHighesBuffer,false);
       ArraySetAsSeries(ExtLowesBuffer,false);
       ArraySetAsSeries(low,false);
       ArraySetAsSeries(high,false);
       ArraySetAsSeries(close,false);

    It will not work if arrays are not set as series. If you want to use such arrays, then you have to modify the alert conditions accordingly. For example, the number of the latest bar is no longer 0, it is rates_total-1, and the number of the pre-last bar is no longer 1, it is rates_total-2.

    Reply

  19. Nick

    Hey buddy,
    Great article. I would like to attach a file with this message. How do I do that?

    Reply

    Nick Reply:

    I keep getting errors. How do you add alerts for red or blue dot signals?

    #property description "Draws signals based on the cross of the stochastic above 80(blue) below 20(red) default"
    #property description" K Period and D Period / Main Line & signal line."
    #property description "User can set the level the signal is drawn on the inputs tab."
     
     
    //----
    #property indicator_separate_window
    #property indicator_buffers   6
    //----
    #property indicator_minimum   0
    #property indicator_maximum 100
    #property indicator_color1 Yellow
    #property indicator_style1 STYLE_DOT
    #property indicator_color2 White
    #property indicator_color3 DodgerBlue
    #property indicator_color4 Red
    #property indicator_width3 2
    #property indicator_width4 2
    #property indicator_level1 80
    #property indicator_level2 20
    //---- input parameters
    //nice setings for trend = 35,10,1
    extern string note1="Stochastic settings";
    extern int       KPeriod   =5;
    extern int       KPeriod2 = 5;
    extern int       Slowing   =3;
    extern int       DPeriod   =3;
    extern int       DPeriod2 = 3;
    extern string note4="0=sma, 1=ema, 2=smma, 3=lwma";
    extern int       MAMethod =0;
    extern string note5="0=high/low, 1=close/close";
    extern int       PriceField= 1;
    extern string note6="overbought level";
    extern int       overBought=80;
    extern string note7="oversold level";
    extern int       overSold  =20;
    //--- Inputs for stochastic cross level 
    input color Buy_Dot_Color = clrDodgerBlue;
    input color Sell_Dot_Color = clrRed;
    double input Cross_From_Below_Level = 10;
    double input Cross_From_Above_Level = 90;
     
    //---- buffers
    double KFull[];
    double DFull[];
    double Upper[];
    double Lower[];
    double Buy_Point[];
    double Sell_Point[];
    //+------------------------------------------------------------------+
    //| Custom indicator initialization function                         |
    //+------------------------------------------------------------------+
    int init()
      {
       SetIndexBuffer(0,DFull);
       SetIndexBuffer(1,KFull);
       SetIndexBuffer(2,Upper);
       SetIndexBuffer(3,Lower);
       SetIndexBuffer(4,Buy_Point);
       SetIndexBuffer(5,Sell_Point);
       SetIndexStyle(4,DRAW_ARROW,EMPTY,3,Buy_Dot_Color);
       SetIndexStyle(5,DRAW_ARROW,EMPTY,3,Sell_Dot_Color);
       SetIndexArrow(4,159);
       SetIndexArrow(5,159);
       SetIndexLabel(1,"Fast");
       SetIndexLabel(2,NULL);
       SetIndexLabel(3,NULL);
    //----
       DPeriod=MathMax(DPeriod,1);
         if (DPeriod==1) 
         {
          SetIndexStyle(0,DRAW_NONE);
          SetIndexLabel(0,NULL);
         }
         else 
         {
          SetIndexStyle(0,DRAW_LINE);
          SetIndexLabel(0,"Slow");
         }
       string shortName="Stochastic X ("+KPeriod+","+Slowing+","+DPeriod+","+maDescription(MAMethod)+","+priceDescription(PriceField);
       if (overBought < overSold) overBought=overSold;
       if (overBought    0)      shortName =shortName+","+overSold;
       IndicatorShortName(shortName+")");
       return(0);
      }
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    int deinit()
      {
       return(0);
      }
    //+------------------------------------------------------------------+
    //| Custom indicator iteration function                              |
    //+------------------------------------------------------------------+
    int start()
      {
       int    limit;
       int    i;
    //----   
       int counted_bars = IndicatorCounted();
       if(counted_bars  0)   counted_bars--;
       limit = Bars - counted_bars;
       double Rsi_rule = iRSI(Symbol(),0,14,0,i);
     
       if(counted_bars==0) limit-=1+MathMax(2,MathMax(KPeriod,DPeriod));
     
       for(i=limit; i>=0; i--)
         {
          KFull[i]=iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MAMethod,PriceField,MODE_MAIN,i);
          DFull[i]=iStochastic(NULL,0,KPeriod2,DPeriod2,Slowing,MAMethod,PriceField,MODE_SIGNAL,i);
    //----
          if (KFull[i] > overBought) { Upper[i]=KFull[i]; Upper[i+1]=KFull[i+1]; }
            else                       
            { 
             Upper[i]=EMPTY_VALUE;
             if (Upper[i+2]==EMPTY_VALUE)
               Upper[i+1] =EMPTY_VALUE; 
            }
          if (KFull[i] < overSold)   { Lower[i]=KFull[i]; Lower[i+1]=KFull[i+1]; }
            else                       
            { 
             Lower[i]=EMPTY_VALUE;
             if (Lower[i+2]==EMPTY_VALUE)
               Lower[i+1] =EMPTY_VALUE; 
            }
     
            //--- Stochastic Crossing Up Below 10 Signal
     
           if( KFull[i] DFull[i] )
     
           {
             Buy_Point[i] = KFull[i];
     
           } 
           //--- Stochastic Crossing Down Above 80 Signal 
     
           if ( KFull[i] > Cross_From_Above_Level && KFull[i] < DFull[i])
           {
             Sell_Point[i] =KFull[i];
           }
     
         }
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    string priceDescription(int mode)
      {
       string answer;
       switch(mode)
         {
          case 0:  answer="Low/High"   ;break;
          case 1:  answer="Close/Close";break;
          default: answer="Invalid price field requested";
             Alert(answer);
         }
       return(answer);
      }
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    string maDescription(int mode)
      {
       string answer;
       switch(mode)
         {
          case MODE_SMA:  answer="SMA" ;break;
          case MODE_EMA:  answer="EMA" ;break;
          case MODE_SMMA: answer="SMMA";break;
          case MODE_LWMA: answer="LWMA";break;
          default:        answer="Invalid MA mode requested";
             Alert(answer);
         }
       return(answer);
      }
    //+------------------------------------------------------------------+

    Reply

    Andriy Moraru Reply:

    I don’t see any code here that would add alerts.

    Reply

    Andriy Moraru Reply:

    Please use pastebin.com to share large pieces of code.

    Reply

  20. Bruce L

    Great article !!!! I successfully added alerts to my Keltner indie :)

    Reply

  21. Nigel

    Hi,
    Thanks for the article, it’s great! I would like to add a sound alert to the force index (mt5), but I’m having difficulty understanding step 3, alert conditions, where exactly to add it and how to change the code to get a sound alert when price crosses levels at 6000 and -6000, please could you help me?
    Thanks…

    Reply

    Andriy Moraru Reply:

    In case of Forex Index, ExtForceBuffer is the buffer name. You should be placing your alert conditions after this line:

    ExtForceBuffer[i]=tick_volume[i]*(ExtMABuffer[i]-ExtMABuffer[i-1]);

    And repeat them after this line:

    ExtForceBuffer[i]=volume[i]*(ExtMABuffer[i]-ExtMABuffer[i-1]);

    Reply

    Nigel Reply:

    I tried to add the code you gave for levels into the force index code in the positions you advised with the intension of editing where nessecary to get the desired results but when i hit compile it brings up number of errors and warnings, errors are all ‘undeclared identifier’ and warnings are all ‘implicit conversion of ‘number’ to ‘string”.

    Reply

    Andriy Moraru Reply:

    You need to make sure you follow the instructions provided in the tutorial.

    Reply

    Nigel Reply:

    I’ve gone over the instructions again and copied the code verbatim, but I’m still getting 2 errors, both ”Coppock’ – undeclared identifier’. I’m not any good with coding so I have no idea how to fix these errors…

    Reply

    Andriy Moraru Reply:

    Unfortunately, I cannot read people’s minds. If you share your code via pastebin.com, I would be able to look at it and help you.

    Reply

    Nigel Reply:

    https://pastebin.com/8UWdWxgn Here is the code in pastebin.com. Hope you can help. Thanks…

    Andriy Moraru Reply:

    What is that Coppock buffer you are trying to use in your alert conditions?

    Nigel Reply:

    Sorry, I have been trying to embed the code from pastebin.com but it doesn’t seem to be working. I copied the code from metaeditor, pasted into pastebin, copied the embed code, pasted it here but nothing is happening. I tried both the embed options, but I don’t know what’s going on. I’m sorry for taking up your time with my lack of knowledge but I am honestly stuck right now…

    Reply

    Andriy Moraru Reply:

    You don’t need to embed anything here. Just copy and paste the link to the pastebin share you created.

  22. Nigel

    I copied the section of code in the tutorial and added the conditions to the force index indicator. I didn’t add or remove anything just applied the example code in the appropriate places.

    Reply

    Andriy Moraru Reply:

    You need to follow the steps 2 and 3 of the tutorial. I have already replied to you with the buffer name you need to check, so you can skip step 2. Copying example code into a different indicator will not work.

    Reply

  23. Ravi

    Hi Andriy,
    You taught me ‘how to fish’. Now I just created alert for two indicators with your instructions here and it’s working fine. Thank you very much for your great post.

    Reply

    Andriy Moraru Reply:

    I am glad it helped you!

    Reply

  24. bhupinder singh

    Hi Andriy,
    i have added successfully email and sound alert into indicator, but why it is not attached on chart.my mt4 version is 4 and build 1090.
    i have also attached code here. plz fix it

    CODE REMOVED

    Reply

    Andriy Moraru Reply:

    I have removed the indicator’s code as it looks like a decompiled one. I am not going to discuss decompiled code here.

    As for your question, check if there are any compilation errors in MetaEditor when you compile it. It looks like it did not compile. If it does compile without errors, check the Expert tab output in the platform when you try to attach the indicator to the chart.

    Reply

  25. Ravi

    Dear Andriy Moraru,
    Appreciations for this great post.
    I just added alert for “stepma color” indicator. Everything works well except it gives alert on each new candle. Could you please guide me to correct the issue.
    here is the code: https://pastebin.com/ka4r2J04

    Reply

    Andriy Moraru Reply:

    Nice work! But you should have used the Level type of alert from the post instead of Signal. Your indicator’s buffer changes to Up or Down and stays there. Try changing the alert conditions so that they are similar to those in the Level alert example in my post.

    Reply

    Ravi Reply:

    Dear Andriy Moraru,
    Thanks for your kind reply. I used only the first example CCI arrow signal alert code. Please see in the line no: 119 it is “// Up Arrow Alert”. In the CCI arrow example there is only one signal for trend change. But in my indicator signal dots displays on every candle and only changes color when trend change. I do not know how to get alert only at color change and to stop alert on next candle(trigger candle+2).

    Reply

    Andriy Moraru Reply:

    As I have said, you need to use Level example, not Signal.

    Reply

  26. Ravi

    Dear Andriy,
    oops, i misunderstood. Now i am clear on that point now, but still have doubts in logic.
    Coppock has separate window indicator and had used zero cross. Here, step ma is on-chart indicator and have no cross value except price. In the code there are only two buffers blue and red dots and not crossing anything.
    If you have spare time please clarify.
    It will be very useful for all on-chart color change trend indicators like HMA, Non-lag ma etc.

    Reply

    Andriy Moraru Reply:

    You need to use the Coppock (Level) example because you want alerts on indicator’s level change – from no signal (-1.0 value) to some price level. The colors and chart/separate window don’t matter at all here. Just make sure that your alert condition checks that the current value is above zero (it already does that in your pastebin) AND that the previous value was below zero.

    Reply

  27. Ravi

    Dear Andriy,
    Thank you very much. I successfully added alert. I think this page is very precious for non-programmers.
    https://pastebin.com/VQqnWfNa

    Reply

    Andriy Moraru Reply:

    I am glad it worked for you!

    Reply

  28. Kobby

    Great info but I’m still experiencing some challenges after trying for a few days now to adds alerts to these particular indicators:

    1. WATR

    //----
    #property indicator_chart_window
    #property indicator_buffers 2
    #property indicator_color1 Coral
    #property indicator_color2 DodgerBlue
    //---- input parameters
    extern int    WATR_K = 10;
    extern double WATR_M = 4.0;
    extern int    ATR = 21;
    //---- buffers
    double ExtMapBufferUp[];
    double ExtMapBufferDown[];
    //+------------------------------------------------------------------+
    //| Custom indicator initialization function                         |
    //+------------------------------------------------------------------+
    int init()
      {  
       IndicatorBuffers(2);  
       SetIndexBuffer(0, ExtMapBufferUp); 
       ArraySetAsSeries(ExtMapBufferUp, true);      
       SetIndexStyle(0, DRAW_LINE, STYLE_SOLID, 2);
       SetIndexBuffer(1, ExtMapBufferDown); 
       ArraySetAsSeries(ExtMapBufferDown, true);      
       SetIndexStyle(1, DRAW_LINE, STYLE_SOLID, 2);
       IndicatorShortName("WATR(" + WATR_K + ", " + WATR_M + ")"); 
       SetIndexLabel(0, "WATR_Up");
       SetIndexLabel(1, "WATR_Dn");    
       return(0); 
      }
    //+------------------------------------------------------------------+
    //| Custom indicator deinitialization function                       |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| Custom indicator function                                        |
    //+------------------------------------------------------------------+
    bool AntiTrendBar(int i)
      {
       bool res = (TrendUp(i) && (Close[i]  Open[i]));    
       return(res);
      }
    //+------------------------------------------------------------------+
    //| Custom indicator function                                        |
    //+------------------------------------------------------------------+
    double CalcIndicValue(int i, bool trend)
      {
       double res = Close[i];  
       if(trend)
           res -= (WATR_K*Point + WATR_M*iATR(NULL, 0, ATR, i));
       else
           res += (WATR_K*Point + WATR_M*iATR(NULL, 0, ATR, i));        
       return(res);
      }
    //+------------------------------------------------------------------+
    //| Custom indicator function                                        |
    //+------------------------------------------------------------------+
    bool TrendUp(int i)
      {
       return((Close[i+1] > ExtMapBufferUp[i+1]) && 
              (ExtMapBufferUp[i+1] != EMPTY_VALUE));
      }
    //+------------------------------------------------------------------+
    //| Custom indicator iteration function                              |
    //+------------------------------------------------------------------+
    int start()
      {
       int limit;
       int counted_bars = IndicatorCounted();
    //---- последний посчитанный бар будет пересчитан
    //---- первое значение индикатора == цене-1 point, 
    //     то есть считает тренд восходящим
       ExtMapBufferUp[Bars-1] = Close[Bars-1] - WATR_K*Point;     
    // limit = (counted_bars > 0) ? (Bars - counted_bars) : (Bars - 1);
       limit = Bars - counted_bars;
       if(counted_bars==0) limit-=2;
    //---- основной цикл
       for(int i = limit; i >= 0; i--)
         {
           if(AntiTrendBar(i))
             {
               ExtMapBufferUp[i] = ExtMapBufferUp[i+1];            
               ExtMapBufferDown[i] = ExtMapBufferDown[i+1];            
             }
           else
             {
               if(TrendUp(i))
                 {
                   ExtMapBufferUp[i] = CalcIndicValue(i, true);
                   if(ExtMapBufferUp[i]  ExtMapBufferDown[i+1])
                       ExtMapBufferDown[i] = ExtMapBufferDown[i+1];                                             
                   ExtMapBufferUp[i] = EMPTY_VALUE;
                 }
             }
           // пересечения с ценой                 
           if(TrendUp(i) && (Close[i]  ExtMapBufferDown[i]))
             {
               ExtMapBufferUp[i] = CalcIndicValue(i, true);                  
               ExtMapBufferDown[i] = EMPTY_VALUE; 
             }
         }
       return(0);
      }
    //+------------------------------------------------------------------+

    2. Extreme RSI

    #property indicator_chart_window
    #property indicator_buffers 2
    #property indicator_width1 1
    #property indicator_width2 1
    #property indicator_color1 DodgerBlue
    #property indicator_color2 DodgerBlue
    extern int rsiperiod = 14;
    double buffy1[];
    double buffy2[];
    int cb=0;
    int bar;
    //+------------------------------------------------------------------+
    //| Custom indicator initialization function                         |
    //+------------------------------------------------------------------+
    int init()
      {
       int  draw;
       SetIndexStyle(0,DRAW_ARROW);
       SetIndexArrow(0,233);
       SetIndexStyle(1,DRAW_ARROW);
       SetIndexArrow(1,234);
       SetIndexEmptyValue(0,0.0);
       SetIndexLabel(0,"buy");
       SetIndexLabel(1,"sell");
       SetIndexDrawBegin(0,draw);
       SetIndexDrawBegin(1,draw);
       SetIndexBuffer(0,buffy1);
       SetIndexBuffer(1,buffy2);
       return(0);
      }
    //+------------------------------------------------------------------+
    int deinit()
      {
       ObjectsDeleteAll(0,OBJ_ARROW);
       return(0);
      }
    //+------------------------------------------------------------------+
    int start()
      {
       if (bar==Time[0]) return(0);
       int cb=IndicatorCounted();
       int x;
       if(Bars<=100) return(0);
       if (cb0) cb--;
       x=Bars-cb;
       for(int i=0; i30 && r2<30)
          buffy1[i] = Low[i+1]-15*Point;
         bar=Time[0]; 
         if (r170)
          buffy2[i] = High[i+1]+15*Point;
         bar=Time[0]; 
       } 
     
       return(0);
      }
    //+------------------------------------------------------------------+

    Reply

    Andriy Moraru Reply:

    It does not look like you tried to add the alerts here.

    Also, the second indicator is clearly a decompiled source code, which is against the MetaQuotes EULA, – I will not discuss adding alerts to the decompiled indicator.

    Reply

  29. Kenni Siu

    Hello, Can somebody help me add an alert with my indicator? thank you so much

    Reply

    Andriy Moraru Reply:

    Have you tried following the tutorial provided in this post? Also linking to your indicator (via Pastebin for example) would be helpful.

    Reply

    Kenni Siu Reply:

    #property indicator_chart_window
    #property indicator_buffers 2
    #property indicator_color1 Blue
    #property indicator_color2 Red
     
    double G_ibuf_76[];
    double G_ibuf_80[];
    double G_ma_method_84 = 3.0;
    double G_ma_method_92 = 3.0;
    extern int LevelEn = 3;
    extern int TradeTer = 3;
     
    int init() {
       SetIndexStyle(0, DRAW_ARROW, EMPTY);
       SetIndexArrow(0, 233);
       SetIndexBuffer(0, G_ibuf_76);
       SetIndexStyle(1, DRAW_ARROW, EMPTY);
       SetIndexArrow(1, 234);
       SetIndexBuffer(1, G_ibuf_80);
       return (0);
    }
     
    int deinit() {
       return (0);
    }
     
    int start() {
       int Li_8;
       double ima_12;
       double ima_20;
       double ima_28;
       double ima_36;
       double ima_44;
       double ima_52;
       double Ld_60;
       double Ld_68;
       int Li_76 = IndicatorCounted();
       if (Li_76  0) Li_76--;
       int Li_0 = Bars - Li_76;
       for (int Li_4 = 0; Li_4 &lt;= Li_0; Li_4++) {
          Li_8 = Li_4;
          Ld_60 = 0;
          Ld_68 = 0;
          for (Li_8 = Li_4; Li_8  ima_20 &amp;&amp; ima_28  ima_52) G_ibuf_76[Li_4] = Low[Li_4] - 0.3 * Ld_60;
          else
             if (ima_12  ima_36 &amp;&amp; ima_44 &lt; ima_52) G_ibuf_80[Li_4] = High[Li_4] + 0.3 * Ld_60;
       }
       return (0);
    }

    Reply

  30. Kenni Siu

    can you add in the code for the alert? thank you..

    Reply

    Andriy Moraru Reply:

    First, please do not post such big pieces of code as comments. Publish them via pastebin.com or similar websites. Second, it is a decompiled indicator. I do not discuss decompiled indicators as it is against the MetaTrader’s EULA to decompile the .ex4 files. You need to contact the author of the original indicator and ask him or her to add the alerts to the indicator.

    Reply

  31. Raphael

    I got a custom indicator on the MQL5 Community and will like to add alarm to it. can that be possible?

    Reply

    Andriy Moraru Reply:

    Probably, yes. Did you try following this tutorial?

    Reply

  32. Don Munro

    Good Day, as a newbie i am keen to learn, i have an indicator that i fished off the net and see potential for it, in that i am looking for low time frame entry opportunities in conjunction with higher time frame technical analysis, i have a career in electronics and currently have a vague idea about coding, it is a histogram that needs an audible alert at condition
    change, there are two buffers, i currently have to visually monitor entry points .

    Are you interested in helping?

    Reply

  33. Don Munro

    Oh yes i gave your tutorial a go but stumble after the first step

    Reply

    Andriy Moraru Reply:

    So, you failed to identify the names of the buffers used in the indicator? You can recognize them by finding the calls to SetIndexBuffer() function and looking at the variables it refers to.

    Reply

    Don Munro Reply:

    Thanks Andriy, i’ll give it a go

    Reply

    Don Munro Reply:

    i am pulling my few hairs out here.. can i send you the MQL4 Source File?

    Reply

    Andriy Moraru Reply:

    You can upload it to pastebin.com and post the link here.

    Reply

    Don Munro Reply:

    Here we go, thanks Andriy https://pastebin.com/ph0j9Dg6

    Reply

    Andriy Moraru Reply:

    The names of the indicator buffers are upBuffer and dnBuffer.

    Reply

    Don Munro Reply:

    Hi Andriy, i have identified (rates_total-counted_bars,rates_total-1);
    and i must add code just above, man now i am cofused, please help..

    Andriy Moraru Reply:

    What do you mean?

    Don Munro Reply:

    The alert must be on the 2nd “barlock”/”signal lock” when the histogram changes from red to green

    Reply

  34. Gilberto

    Hi Andriy,

    Thank you for creating this post, this was the only really helpful article I found online on this subject. Keep it up.

    I added the alerts to a indicator. It works. Yeayy. That is 1 step to the right direction.

    However, I have 2 challenges with it.
    1) It gives for one alert both arrow’s texts, making it confusing.
    2) When I attach the same indicator to more charts at the same time, if one chart gives a alert, the app gives me alerts for all charts the indicator is attached to (with the same confusion as challenge 1).

    Can you share with me some pointers of how to fix it?
    The code you can find here https://pastebin.com/3QstgTR0

    Reply

    Andriy Moraru Reply:

    Adding these two lines after the line #75 will probably help with your first issue:

    up[i]=0;
    down[i]=0;

    As for your second issue, what do you mean by “the app”? There is no way, this indicator can give alerts based on data from the other charts. Unless there is some serious bug in MetaTrader 4 itself, which I highly doubt.

    Reply

  35. Nje

    Hey Andriy

    I followed you instructions to add an alert to a pinbar indicator. Problem is, it keeps poping the alert even when the arrow has not appeared on the chart. Could you kindly help fix it and only give a pop up alert when the indicator makes an arrow in the chart?

    HEre is the link to the code: https://pastebin.com/jyFZ7k2C

    Reply

    Andriy Moraru Reply:

    The problem is that the Up[] and Dn[] buffers are not assigned zero values by default (the actual default values used are 2147483647), which means that they will always be greater than 0. To fix this, you can do the following. Add this on line 106:

    else Dn[i] = 0;

    and this on line 101:

    else Up[i] = 0;

    Reply

  36. Nje

    Thanks Adriy

    I have added the two lines you suggested and it works perfectly now. However, i still have one more problem. I have another Pinbar indicator which is slightly more sensitive than the one i sent you but the code is almost similar. I added the codes just like i did in the first one including the two lines you suggested later. However it is not popping an alert but its putting an arrow on the chart. I have attached the original code(the one without an alert) and the modified code(the one i tried adding an alert) in the modified code, you will notice i added these two lines:
    datetime LastAlertTime = D’01.01.1970′;
    int LastAlertDirection = 0;
    on line 20 and 21 after it gave me an error. Could you help me identify why its not poping an alert?

    Original code: https://pastebin.com/5EFRSUDt
    Modified code: https://pastebin.com/C1HdjZTq

    Also, my compiler is giving me two warnings:
    variable “highest” not used – line 62
    Variable “lowest” not used -line62

    Kindly help me resolve that as well. Looking forward to hearing from you.
    Thanks alot

    Reply

    Andriy Moraru Reply:

    Remove return(0); on line 112. This line prevents anything below it from ever executing by telling the program to return from the current function.

    You can get rid of the warnings by removing the declaration of those variables. However, these warnings are harmless and will not affect the execution of your indicator.

    Reply

    Nje Reply:

    Thanks, Man. This has helped a lot

    Reply

  37. Christopher

    please i have tried the process but i only get alert when i change timeframe it does not show alert when chart is running

    Reply

    Andriy Moraru Reply:

    That probably means that you have done something wrong. It is difficult to say what without seeing the code.

    Reply

  38. Predescu Florin

    Hello, i’m new in this things, i use mt4 and an indicator for binary option. But i need to put an alert when the arrow appear on grafic. I’m from romania and also i don’t speak very good english so i dont’ know hot to write all the code. Need some help please.

    https://pastebin.com/QUyLJpmp

    Reply

    Andriy Moraru Reply:

    It should not be difficult to add the alerts to this indicator if you follow my tutorial. You can learn how to do it if you study the examples for the signal type alerts.

    Reply

    Predescu Florin Reply:

    https://pastebin.com/AYtqX10y

    can you tell me what it’s wrong here to try to change this?

    Reply

    Andriy Moraru Reply:

    The tutorial is pretty straightforward:
    1. Add input parameters.
    2. Identify indicator buffers.
    3. Formulate alert conditions.

    It does look like you’ve made it through these steps. You just copied the code from the example.

    Reply

    Predescu Florin Reply:

    Hello, I just try to follow your steps..first one it’s done, second one i find the indicator buffer:
    SetIndexBuffer(0,b1);
    SetIndexBuffer(1,b2);
    But after the step nr 3, i don’t know what to change in your example from arrows. i put the example jut before the last return..please, if you have some time, tell me what to change at the step nr 3, and if the step 1 and 2 are good. Thx
    https://pastebin.com/ggFJsBbK

    Reply

    Andriy Moraru Reply:

    I think that you would get better results if you were using the names of the indicator buffers that you have found instead of the names you copied from the example in the alert checking conditions code.

    Reply

  39. Predescu Florin

    https://pastebin.com/AYtqX10y

    i tried just like you said in examples for arrows..but it’s not working

    Reply

    Andriy Moraru Reply:

    Sorry, but you have to follow the whole tutorial rather than just copy and paste a piece of the example code.

    Reply

  40. Maria

    Please i need help in getting an alert to EMA indicator arrow. Please help me https://pastebin.com/KxPACBy3

    Reply

    Andriy Moraru Reply:

    You can try following the tutorial. Actually, it is posted here to help you add the alerts.

    Reply

  41. Yanga

    Hi guys, anyone knows how to code an alert in mq4 please..I need to have an alert for when there is a color change signalling a reversal. Please have a look at the pic attached. At point 1 we can see that as the candle reversed into an uptrend there was a color change in the 2FMA’s (from red to blue and at the same time from pink to cyan colour)..the change occured SIMULTANEOUSLY, THAT IS CYAN AND BLUE COLORS APPEARED SIMULTANEOUSLY ON BOTH FMA’S. In point 2 you can see that the opposite happened (PINK COLOUR APPEARED FIRST BEFORE THE RED). I need an alert for ONLY WHEN THE COLORS APPEAR SIMULTANEOUSLY, ONLY SIMULTANEOUSLY (CYAN AND BLUE SIMULTANEOUSLY AND PINK AND RED SIMULTANEOUSLY). I need urgent assistance.

    Reply

  42. Ricky

    Hello
    I tried the alert indicator but I am getting errors as I tried to compile.
    here is my code
    https://pastebin.com/8KVc2cWf

    Reply

    Andriy Moraru Reply:

    Sorry, your pastebin page is not opening.

    Reply

  43. Yanga

    Hi Adriy,

    Here is the coding in term of my last comment. Id be appreciative if i can get the correct coding, that is, WHEN THE CYAN (AQUA) CHANGES COLOR EXACTLY AT THE SAME TIME AS THE BLUE COLOR IN AN UPWARD AND THE FUCHSIA (MAGENTA) COLOR CHANGES COLOR EXACTLY AT THE SAME TIME AS THE RED COLOR IN A DOWNWARD TREND. These are 2 moving averages (one with cyan and aqua color and the second with blue and red colors).

    (Code removed.)

    Reply

    Andriy Moraru Reply:

    Yanga, please do not insert large pieces of code into comments. You can use pastebin.com to share the source code and imgur.com to share images.

    However, your code is a decompiled indicator. I will not help with any modifications to decompiled indicators and will not allow discussing decompiled code here. Please contact the author of the original indicator and ask him or her to modify it.

    Reply

  44. Trevor

    Hi,
    Sort of new to this , I got the RSIoMA cross Ok, but having trouble with editing a level 50 alert

    https://pastebin.com/eBYv4qwS

    any advise would be appreciated

    Reply

    Andriy Moraru Reply:

    You should not compare TriggerCandle to ’50’. You only need to compare the indicator’s buffer with the alert level. TriggerCandle is number of the candle, which should be checked for the alert condition. Usually, it is either 0 or 1.

    Also, your code is checking RSI values, not RSIoMA – not sure if that is what you want to achieve.

    Reply

  45. Alabi Christopher

    hello, i tried yout method of adding alert to this indicator but it stopped working the moment i add the alert code, i mean it does not display again untill i removed the alert code. The name is Beginner indicator.

    https://pastebin.com/LnRRFVe6

    Reply

    Andriy Moraru Reply:

    It does not look like anyone have tried adding any alerts to this indicator.

    PS: By the way, there is little point in adding alerts to Beginner as the indicator repaints itself.

    Reply

    Alabi Christopher Reply:

    does that mean alert will not work with it? or adding alert is not an option

    Reply

    Andriy Moraru Reply:

    That means that the alerts would be useless because they would appear either too late (alerting about the dots which the indicator draws in the past – beyond the period of repainting), or on the dots that would soon disappear as the indicator repaints them. Just launch the Beginner indicator in the Strategy Tester fast forward to see what I mean.

    Reply

  46. batal

    can you help me please pray with a good signal indicator? which one do you use? he attached one here, so there is no one who does what. Thanks and I’m awaiting a reply by mail .. a good day

    #property indicator_chart_window
    #property indicator_buffers 2
    #property indicator_color1 Red
    #property indicator_width1 2
    #property indicator_color2 Lime
    #property indicator_width2 2
     
    extern int SignalGap = 4;
     
    int dist=24;
    double b1[];
    double b2[];
     
    int init()  {
       SetIndexStyle(0,DRAW_ARROW,STYLE_SOLID,1);
       SetIndexStyle(1,DRAW_ARROW,STYLE_SOLID,1);
       SetIndexArrow(1,233);
       SetIndexArrow(0,234);
       SetIndexBuffer(0,b1);
       SetIndexBuffer(1,b2);
       return(0);
    }
    int start() {
       int counted_bars=IndicatorCounted();
       int k,i,j,limit,hhb,llb;
     
       if (counted_bars0) counted_bars--;
       limit=Bars-1;
       if(counted_bars&gt;=1) limit=Bars-counted_bars-1;
       if (limit=0;i--)   {
          b1[i]=EMPTY_VALUE;
          b2[i]=EMPTY_VALUE;
          hhb = iHighest(NULL,0,MODE_HIGH,dist,i-dist/2);
          llb = iLowest(NULL,0,MODE_LOW,dist,i-dist/2);
     
          if (i==hhb)
             b1[i]=High[hhb]+SignalGap*Point;
          if (i==llb)
             b2[i]=Low[llb]-SignalGap*Point;
       }
       return(0);
    }

    Reply

  47. Muti

    Thanks a lot. This post is very helpful.

    Reply

  48. Aphelele

    Hi Andriy

    After reading your great article on adding alerts on MT4 and MT5 indicators, i tried a few for myself successfully ie ADX and Stochastic which are my favorite indicators, however i am still learning without success how to combiine these two indicators into one.

    What brings me here today is this https://pastebin.com/bj5H5LiC a free stochastic x8 indicator i got from MQL5 community and added two alert conditions to it, however my intention is to have one alert when all the lines are above the 80 level and on a different alert when all the lines are below the 20 level.

    as of now it seems to send an alert for every different line which is not how i need it to work.

    i have identified: Ind[numb].IndBuffer as this indicators buffer but that didnt work until i substituted “[numb] for [0].

    Reply

    Andriy Moraru Reply:

    Nice job on adding alerts here! There were three problems with the code:

    1. There are several lines check (the default number is 5 and it is defined using LINES_TOTAL macro). So a simple condition would not work. You have to cycle through all 5 lines each time and check whether all are above 80 or all are below 20.

    2. The indicator buffers are set as timeseries using this line in the OnInit() function:

    ArraySetAsSeries(Ind[numb].IndBuffer,true);

    This means that to access the latest bar you write Ind[numb].IndBuffer[0] instead of Ind[numb].IndBuffer[rates_totale - 1].

    3. LastAlertDirection should be compared to -1 on line 171 of your code:

         && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))

    should be:

         && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))

    This condition is needed to avoid alert popping up each tick when working with the latest bar – LastAlertDirection remembers the previous alert direction (-1 for “below 20” alert) and checks all further alerts if they are of the same direction.

    You can download the fixed indicator here:
    https://www.earnforex.com/blog/files/multistoch_alert.mq5
    I have added code commentaries to explain the cycles.

    Reply

    Aphelele Reply:

    Thank you very much Andriy

    Indicator works well especially on higher time frame.

    your assistance is highly appreciated.

    Reply

  49. vadvid

    Hello Andriy,
    I was so happy to find your article…I read it carefully and tried to add the alerts several time(adding input parameters, identify indicator buffers, set alert conditions) but did not get to work them. The other problem, after modified the original mq4 file, it could not be added to the chart.

    Dear Andriy…this indicator (Symphonie SentimentEmotion Combi Indikator v1.0) is my most favorite one. Please help me and add the alerts, specially the E-MAIL ALERT by changing the colors. I do not get ahead of that.

    Here is the link of the original mq4 file:
    https://www.forexfactory.com/attachment.php/2098330?attachmentid=2098330&d=1481300362

    Thank you very much for your assistance
    best
    VV

    Reply

    Andriy Moraru Reply:

    I don’t quite get it. There is currently a normal popup alert coded in this indicator. Do you want email alert to trigger at the same time as the current popup alert? Or do you want it under different conditions?

    Reply

    vadvid Reply:

    Dear Andriy. As you see the indi produce three different colors. I’d like to have an e-mail alert only in case the color becomes BLUE or RED. (the color yellow is uninteresting).
    Thanks
    VV

    Reply

    Andriy Moraru Reply:

    You can replace this condition:

    if (findChosenIndex(1) != findChosenIndex(2))

    with something like this:

    if (((findChosenIndex(1) == 0) && (findChosenIndex(2) == 1)) || ((findChosenIndex(1) == 1) && (findChosenIndex(2) == 0)))

    Reply

  50. vadvid

    Thanks a lot Andriy,
    I’ll try to use is it incl. your instructions.

    Thanks again
    VV

    Reply

  51. Shedrack

    I understand your explanation but according to my indicator I want the alert only once after the condition meet. I use 3 exponential moving Average and the parabolic SAR all in mq5. Please can you help me how to deal with this.

    Reply

    Andriy Moraru Reply:

    By “only once” you mean that the alert is triggered only once in the indicator’s lifetime (after you attach it and before you detach or close the platform)? Or once for each instance of conditions met (e.g. 3 EMAs cross – alert; after a few bars, the EMAs cross again – new alert)? If you are talking about the latter, then the tutorial explains just that case. If you check and update LastAlertTime variable, the indicator will not issue more than one alert per bar.

    Reply

  52. MUKSKING

    hELP ME INSERT A SOUND ALERT WHEN THE IN INCATOR CHANGES COLOUR

    //+------------------------------------------------------------------+
    //|                                                     Muksking.mq4 |
    //|                        Copyright 2018, MetaQuotes Software Corp. |
    //|                                             https://www.mql5.com |
    //+------------------------------------------------------------------+
     
    #property copyright "Copyright © 2012, Marketcalls "
     
    #property link      "http://www.marketcalls.in"
     
     
     
    #property indicator_chart_window
     
    #property indicator_color1 Aqua
     
    #property indicator_color2 Orange
     
    #property indicator_width1 1
     
    #property indicator_width2 1
     
    #property indicator_color3 Aqua
     
    #property indicator_color4 Orange
     
    #property indicator_width3 1
     
    #property indicator_width4 1
     
    #property indicator_buffers 4
     
    double TrendUp[],TrendDown[];
     
    double UpBuffer[];
     
    double DnBuffer[];
     
     
     
    int changeOfTrend;
     
    extern int Nbr_Periods=10;
     
    extern double Multiplier=3.0;
     
     
     
    /*//---- input parameters
     
    extern int sidFontSize=30;
     
    extern string sidFontName="Ariel";
     
    extern string NoteRedGreenBlue="Red/Green/Blue each 0..255";
     
    extern int sidRed=30;
     
    extern int sidGreen= 30;
     
    extern int sidBlue = 30;
     
    extern int sidXPos = 30;
     
    extern int sidYPos = 150;
     
     
     
    extern bool tagDisplayText=true;
     
    extern string tagText="www.marketcalls.in";
     
    extern int tagFontSize=15;
     
    extern string tagFontName="Ariel";
     
    extern int tagRed=30;
     
    extern int tagGreen= 30;
     
    extern int tagBlue = 30;
     
    extern int tagXPos = 200;
     
    extern int tagYPos = 300;
    */
     
    //---- data
     
    string SID = "Symbol";
     
    int sidRGB = 0;
     
    string TAG = "Tag";
     
    int tagRGB = 0;
     
    string tf;
     
    //+------------------------------------------------------------------+
     
    //| Custom indicator initialization function                         |
     
    //+------------------------------------------------------------------+
     
    int init()
     
      {
     
    //---- indicators
     
       SetIndexBuffer(0,TrendUp);
     
       SetIndexStyle(0,DRAW_LINE,1,1);
     
       SetIndexLabel(0,"Trend Up");
     
       SetIndexBuffer(1,TrendDown);
     
       SetIndexStyle(1,DRAW_LINE,1,1);
     
       SetIndexLabel(1,"Trend Down");
     
     
     
       SetIndexStyle(2,DRAW_ARROW,EMPTY);
     
       SetIndexStyle(3,DRAW_ARROW,EMPTY);
     
     
     
       SetIndexBuffer(2,UpBuffer);
     
       SetIndexBuffer(3,DnBuffer);
     
     
     
       SetIndexArrow(2,233);
     
       SetIndexArrow(3,234);
     
     
     
       SetIndexLabel(2,"Up Signal");
     
       SetIndexLabel(3,"Down Signal");
     
     
     
    //----
     
       return(0);
     
      }
     
    //+------------------------------------------------------------------+
     
    //| Custom indicator deinitialization function                       |
     
    //+------------------------------------------------------------------+
     
    int deinit()
     
      {
     
    //----
     
       ObjectDelete(SID);
     
       ObjectDelete(TAG);
     
     
     
    //----
     
       return(0);
     
      }
     
    //+------------------------------------------------------------------+
     
    //| Custom indicator iteration function                              |
     
    //+------------------------------------------------------------------+
     
    int start()
     
      {
     
     
     
       double ClosePrice=Close[0];
     
     
     
    //      watermark(TAG, tagText, tagFontSize, tagFontName, tagRGB, tagXPos, tagYPos); 
     
       //string str=StringConcatenate("www.marketcalls.in      LTP : ",ClosePrice);
     
       //watermarkclose(TAG,str,22,tagFontName,tagRGB,80,20);
     
     
     
       int i,flag,flagh,trend[];
     
       double up[],dn[],medianPrice,atr;
     
     
     
       int counted_bars=IndicatorCounted();
     
       if(counted_bars 0) counted_bars--;
     
       int limit=Bars-counted_bars;
     
       if(counted_bars==0) limit-=1+1;
     
     
     
    //Print(limit);
     
     
     
       int size=ArraySize(TrendUp);
     
       ArrayResize(trend,size);
     
       ArrayResize(up,size);
     
       ArrayResize(dn,size);
     
    //----
     
       for(i=limit; i&gt;=1; i--) 
     
         {
     
          TrendUp[i]=EMPTY_VALUE;
     
          TrendDown[i]=EMPTY_VALUE;
     
          atr=iATR(NULL,0,Nbr_Periods,i);
     
          //Print("atr: "+atr[i]);
     
          medianPrice=(High[i]+Low[i])/2;
     
          //Print("medianPrice: "+medianPrice[i]);
     
          up[i]=medianPrice+(Multiplier*atr);
     
          //Print("up: "+up[i]);
     
          dn[i]=medianPrice-(Multiplier*atr);
     
          //Print("dn: "+dn[i]);
     
          trend[i]=1;
     
     
     
          if(Close[i]&gt;up[i+1]) 
     
            {
     
             trend[i]=1;
     
             if(trend[i+1]==-1) changeOfTrend=1;
     
             //Print("trend: "+trend[i]);
     
     
     
            }
     
          else if(Close[i]&lt;dn[i+1]) 
     
            {
     
             trend[i]=-1;
     
             if(trend[i+1]==1) changeOfTrend=1;
     
             //Print(&quot;trend: &quot;+trend[i]);
     
            }
     
          else if(trend[i+1]==1) 
     
            {
     
             trend[i]=1;
     
             changeOfTrend=0;
     
            }
     
          else if(trend[i+1]==-1) 
     
            {
     
             trend[i]=-1;
     
             changeOfTrend=0;
     
            }
     
     
     
          if(trend[i]0) 
     
            {
     
             flag=1;
     
             //Print("flag: "+flag);
     
            }
     
          else 
     
            {
     
             flag=0;
     
             //Print("flagh: "+flag);
     
            }
     
     
     
          if(trend[i]&gt;0 &amp;&amp; trend[i+1]0 &amp;&amp; dn[i]&lt;dn[i+1])
     
             dn[i]=dn[i+1];
     
     
     
          if(trend[i]up[i+1])
     
             up[i]=up[i+1];
     
     
     
          if(flag==1)
     
             up[i]=medianPrice+(Multiplier*atr);
     
     
     
          if(flagh==1)
     
             dn[i]=medianPrice-(Multiplier*atr);
     
     
     
          //-- Draw the indicator
     
          if(trend[i]==1) 
     
            {
     
             TrendUp[i]=dn[i];
     
             if(changeOfTrend==1) 
     
               {
     
                TrendUp[i+1] = TrendDown[i+1];
     
                changeOfTrend= 0;
     
               }
     
            }
     
          else if(trend[i]==-1) 
     
            {
     
             TrendDown[i]=up[i];
     
             if(changeOfTrend==1) 
     
               {
     
                TrendDown[i+1]= TrendUp[i+1];
     
                changeOfTrend = 0;
     
               }
     
     
     
            }
     
          if(trend[i]==1 &amp;&amp; trend[i+1]==-1) 
     
            {
     
             UpBuffer[i] = iLow(Symbol(),0,i)-(3*Point);
     
             DnBuffer[i] = EMPTY_VALUE;
     
     
     
            }
     
          if(trend[i]==-1 &amp;&amp; trend[i+1]==1) 
     
            {
     
             UpBuffer[i] = EMPTY_VALUE;
     
             DnBuffer[i] = iHigh(Symbol(),0,i)+(3*Point);
     
            }
     
     
     
         }
     
       WindowRedraw();
     
     
     
    //----
     
       return(0);
     
      }
     
    //+------------------------------------------------------------------+
     
     
     
    void watermarkclose(string obj,string text,int fontSize,string fontName,color colour,int xPos,int yPos)
     
      {
     
       ObjectCreate(obj,OBJ_LABEL,0,0,0);
     
       ObjectSetText(obj,text,fontSize,fontName,Red);
     
       ObjectSet(obj,OBJPROP_CORNER,0);
     
       ObjectSet(obj,OBJPROP_XDISTANCE,xPos);
     
       ObjectSet(obj,OBJPROP_YDISTANCE,yPos);
     
       ObjectSet(obj,OBJPROP_BACK,true);
     
      }
     
    //+------------------------------------------------------------------+

    Reply

    Andriy Moraru Reply:

    Before you add alerts to an indicator, you should first fix the errors, which prevent its compilation.

    Reply

  53. Renan

    You can help me put the alert on the gauge, I’m doing as in the tutorial but it’s not working.

    //+------------------------------------------------------------------+
    //|                                                    Sequencia.mq5 |
    //|                                                  Henrique Vilela |
    //|                                               http://vilela.one/ |
    //+------------------------------------------------------------------+
    #property copyright "Henrique Vilela"
    #property link      "http://vilela.one/"
    #property version   "1.00"
     
    #property indicator_chart_window
     
    #property indicator_buffers 3
    #property indicator_plots   3
     
    #property indicator_label1  "Venda"
    #property indicator_type1   DRAW_ARROW
    #property indicator_color1  clrRed
    #property indicator_style1  STYLE_SOLID
    #property indicator_width1  1
     
    #property indicator_label2  "Compra"
    #property indicator_type2   DRAW_ARROW
    #property indicator_color2  clrDodgerBlue
    #property indicator_style2  STYLE_SOLID
    #property indicator_width2  1
     
    double         VendaBuffer[];
    double         CompraBuffer[];
     
    double         SequenciaBuffer[];
     
    input ushort   Conta=3; // Contagem 
     
    input int    TriggerCandle 	= 1;
    input bool   EnableNativeAlerts = true;
    input bool   EnableSoundAlerts  = true;
    input bool   EnableEmailAlerts  = true;
    input bool   EnablePushAlerts  = true;
    input string AlertEmailSubject  = "";
    input string AlertText  	= "";
    input string SoundFileName	= "alert.wav";
     
    datetime LastAlertTime = D'01.01.1970';
    int LastAlertDirection = 0;
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    int OnInit()
      {
       SetIndexBuffer(0,VendaBuffer,INDICATOR_DATA);
       SetIndexBuffer(1,CompraBuffer,INDICATOR_DATA);
       SetIndexBuffer(2,SequenciaBuffer,INDICATOR_DATA);
     
       PlotIndexSetInteger(0,PLOT_ARROW,234);
       PlotIndexSetInteger(1,PLOT_ARROW,233);
     
       PlotIndexSetInteger(0,PLOT_ARROW_SHIFT,-10);
       PlotIndexSetInteger(1,PLOT_ARROW_SHIFT,10);
     
       return(INIT_SUCCEEDED);
      }
    //+------------------------------------------------------------------+
    //|                                                                  |
    //+------------------------------------------------------------------+
    int OnCalculate(const int rates_total,
                    const int prev_calculated,
                    const datetime &time[],
                    const double &open[],
                    const double &high[],
                    const double &low[],
                    const double &close[],
                    const long &tick_volume[],
                    const long &volume[],
                    const int &spread[])
      {
       for(int i=MathMax(1,prev_calculated-1); iopen[i]) // Positivo
            {
     
             if(close[i-1]<open[i-1]) // Anterior Positivo
               {
                SequenciaBuffer[i]=SequenciaBuffer[i-1]+1;
               }
             else  // Anterior Negativo
               {
                SequenciaBuffer[i]=0;
               }
            }
          else if(close[i]open[i-1]) //  // Anterior Negativo
               {
                SequenciaBuffer[i]=SequenciaBuffer[i-1]+1;
               }
             else  // Anterior Positivo
               {
                SequenciaBuffer[i]=0;
               }
            }
          else // Doji (nem positivo, nem negativo)
            {
             SequenciaBuffer[i]=0;
            }
     
          CompraBuffer[i]= SequenciaBuffer[i] == Conta ? low[i] : EMPTY_VALUE;
          VendaBuffer[i] = -SequenciaBuffer[i] == Conta ? high[i] : EMPTY_VALUE;
          }
       if (((TriggerCandle > 0) && (time[rates_total - 1] > LastAlertTime)) || (TriggerCandle == 0))
    {
    	string Text;
    	// Up Arrow Alert
    	if ((CompraBuffer[rates_total - 1 - TriggerCandle] > 0) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
    	{
    		Text = AlertText + "CCI Arrows: " + Symbol() + " - " + EnumToString(Period()) + " - Up.";
    		if (EnableNativeAlerts) Alert(Text);
    		if (EnableEmailAlerts) SendMail(AlertEmailSubject + "CCI Arrows Alert", Text);
    		if (EnableSoundAlerts) PlaySound(SoundFileName);
    		if (EnablePushAlerts) SendNotification(Text);
    		LastAlertTime = time[rates_total - 1];
    		LastAlertDirection = 1;
    	}
    }
       return(rates_total);
      }
    //+------------------------------------------------------------------+

    Reply

    Andriy Moraru Reply:

    The code seems to have gotten corrupted when you inserted it in a comment. Please share it via pastebin.com or some file-sharing website.

    By the way, why don’t you ask the indicator’s author – perhaps, he already has a version with the alerts.

    Reply

    Renan Reply:

    https://pastebin.com/HXX5Psv8

    I already sent a message to the creator he told me that incador counted the number of candles followed and he sent me saying that he could change to count alternating candles and he does not support.
    If you could help me, I would appreciate it.

    Reply

    Andriy Moraru Reply:

    OK. Now I see the problem. In your alert condition, you have to compare BuyBuffer[rates_total - 1 - TriggerCandle] against Account, not just BuyBuffer. The latter is just the name of the buffer, whereas the former is the particular value in that buffer (the last finished candle if TriggerCandle is set to 1).

    Reply

    Renan Reply:

    https://pastebin.com/X8Xs7mPa

    I did as you said and the alert does not work, you can look at what’s wrong please.

    Reply

    Andriy Moraru Reply:

    No idea, you can try asking in the forums.

    Reply

  54. Shawn Sherrill

    Great Post. I Followed the instructions and created some signal alerts for my Arrow Chart. However they keep repeating and when i open a new chart both signals show on the chart. Can you help me adjust it to where the alert only happens when one arrow shows on the chart.

    https://pastebin.com/g42D0aCY

    thanks

    Reply

    Andriy Moraru Reply:

    No, but you can post your question in the indicators forum.

    Reply

  55. lakeside jaywon

    Please can you help add an arrow pop up alert to Bears and Bulls MT4 indicator? It’ll apply to close of candle to avoid repainting. The arrow and alert show up only for the bear indicator when and only if the histogram crosses from positive to negative value and also show up only for the bear indicator when and only if the histogram crosses from negativeto positive value.

    Thanks

    Reply

    Andriy Moraru Reply:

    No, but you can post your question in the indicators forum.

    Reply

  56. Matt

    Hi there! Can you please help me out with adding alerts for RSI indicator? I actually did copy and pasted one of the codes above, and I still dont recieve alerts even if the code does not show any problems after compiling. Im just starting to learn how to do this. I hope you guys can help me out. Thanks in advance! :-))

    Reply

    Andriy Moraru Reply:

    Copy and pasting wnon’t work. You will have to follow the tutorial.

    Reply

  57. Matt

    Thanks for responding… Actually, I did make it send alerts but it crashes my mt4 due to it sending too much alerts since i coded this…

    {
     
    diff=close[i]-close[i-1];
     
    ExtPosBuffer[i]=(ExtPosBuffer[i-1]*(InpRSIPeriod-1)+(diff>0.0?diff:0.0))/InpRSIPeriod;
    Alert((string)Period()+”M “,Symbol(),” “+”alert”);
    LastAlertDirection = -1;
    LastAlertTime = Time[0];
    ExtNegBuffer[i]=(ExtNegBuffer[i-1]*(InpRSIPeriod-1)+(diff<0.0?-diff:0.0))/InpRSIPeriod ;
    Alert((string)Period()+"M ",Symbol()," "+"alert");
    LastAlertDirection = -1;
    LastAlertTime = Time[0];

    Reply

    Andriy Moraru Reply:

    You should follow the tutorial to make that work correctly. If you need help, you should ask at the for it in the forum.

    Reply

  58. PW

    Hi, thankyou very much for taking the time to share this. : ) Its great to be able to add the push notifications!

    Reply

  59. Emmanuel Udokaku Harry

    can you help me put alert to my indicator

    Reply

    Andriy Moraru Reply:

    No, but you can ask here if you find following the tutorial difficult:
    https://www.earnforex.com/forum/forums/metatrader-indicators.12/

    Reply

  60. Mugilan

    Please help me in provide a code for the following specification.
    If i have 3 EMA’s. for example; fast Ma- 2, medium MA – 4 and Slow MA-25. i want indicator to alert me with the signal in the chart.
    it should alert as:
    1) if fast Ma and medium MA cross above 50 MA then it should alert as Buy.2) vice versa of 1
    Can any one of you help me in writing mt4 code

    Reply

    Andriy Moraru Reply:

    Do you have the code for the indicator that shows the three EMAs on the chart? If not, then this tutorial won’t help you. You have to code an indicator somehow first.

    Reply

Leave a Reply

required
required (will not be published)
optional