How can I insert ADX code in existing MQL4 code?

 

Hi I have an existing EA and I'd like to add a filter for opening position. The filter is the ADX. I'd like to tell to the EA:

  • if ADX is higher than 50 ->  if DI+>DI-   -> Then open buy trade
  • if ADX is higher than 50  -> if DI->DI+   -> Then open sell trade

here the code I'd like to implement in the EA

double a; double b; double c; int period = 14;

int OnInit() {

a = iADX(NULL,0,14,PRICE_CLOSE,MODE_MAIN,0);

b=iADX(NULL,0,14,PRICE_CLOSE,MODE_PLUSDI,0);

c=iADX(NULL,0,14,PRICE_CLOSE,MODE_MINUSDI,0);

if(a>50&&b>c)

{........}

}


BUT i GET ALWAY ERROR

 
Claudio Lasso:

Hi I have an existing EA and I'd like to add a filter for opening position. The filter is the ADX. I'd like to tell to the EA:

  • if ADX is higher than 50 ->  if DI+>DI-   -> Then open buy trade
  • if ADX is higher than 50  -> if DI->DI+   -> Then open sell trade

here the code I'd like to implement in the EA

double a; double b; double c; int period = 14;

int OnInit() {

a = iADX(NULL,0,14,PRICE_CLOSE,MODE_MAIN,0);

b=iADX(NULL,0,14,PRICE_CLOSE,MODE_PLUSDI,0);

c=iADX(NULL,0,14,PRICE_CLOSE,MODE_MINUSDI,0);

if(a>50&&b>c)

{........}

}


BUT i GET ALWAY ERROR

MQL4? The iADX() lines must not be in OnInit(), try moving them to OnTick() (or any function called by OnTick()).

Also, be more specific in your error description if you still get error.

 
  1. Global and static variables work exactly the same way in MT4/MT5/C/C++.
    1. They are initialized once on program load.
    2. They don't update unless you assign to them.
    3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5 (or MT4 with strict which you should always use.)

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:

      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
    4. Unlike indicators, EAs are not reloaded on chart change so you must reinitialize them, if necessary.
                external static variable - Inflation - MQL4 programming forum
  2. Claudio Lasso: BUT i GET ALWAY ERROR
    Do you really expect an answer? There are no mind readers here and our crystal balls are cracked.
Reason: