Alert - Price > A then Price < B

 

Hi All,

I want to build a price alert that tracks the following,


First, price has to move above A, then price has to move below B, then alert.


I am a noob in MT4 programming, any help is much appreciated.


Thanks

 
hsun85:

Hi All,

I want to build a price alert that tracks the following,
First, price has to move above A, then price has to move below B, then alert.

static bool priceA = false,
            priceB = false;

void pattern(double a, double b) {
   MqlTick tick;
   SymbolInfoTick(_Symbol,tick);

   if(tick.bid>=a) priceA = true;
   if(priceA && tick.ask<=b) priceB = true;
   
   if(priceA && priceB) {
      string msg = "Price hit "+DoubleToString(a,_Digits)+" and "+DoubleToString(a,_Digits);
      Alert(msg);
      priceA = false,
      priceB = false;
   }
}
 
  1. You should be able to read your code out loud and have it make sense. Code becomes self documenting when you use meaningful variable names. PriceA sounds like a price  and "if priceA" is an incomplete sentence.
  2. Global variables never need to be static. No need for priceB. Self-doc price to string. Your msg has a bug.

  3. void pattern(double a, double b) {
       MqlTick tick;  SymbolInfoTick(_Symbol,tick);
    
       static bool wasPriceAbove = false;
       if(tick.bid>=a) wasPriceAbove = true;
       if(wasPriceAbove && tick.ask<=b){   wasPriceAbove=false; // reset
          Alert(StringFormat("Price hit %s and %s",PriceToStr(a),PriceToStr(b)));
          ⋮
       }
    }
    string   PriceToStr(double p){   return( DoubleToStr(p, _Digits) );           }
    

Reason: