Getting current MA and Close[1] price

 

Hello, I am having trouble figuring out how to get the EA to use the latest prices to exit a trade once I enter.  In the backtester it not only doesn't recognize all possible trades, it exits a trade only when the stop loss is hit. I want to close the trade when the latest Close[1] closes above the shortMAvalue if I am short and an exit if the Close[1] closes below the longMAvalue if I am long. Here is the code. It think it may have to do with refreshrates function but it didn't work for me. The data I get is the data at the start of the EA. Anytime I reload the EA it gives me the current correct data. I appreciate the help very much!

nt shortmaPeriod = 8;
int longmaPeriod = 13;
int MN = 3;
int OrderID;
double maxRiskPerTrade = 0.02;
double shortmaValue = NormalizeDouble(iMA(NULL,0,shortmaPeriod,0,MODE_EMA,PRICE_CLOSE,0),Digits);
double longmaValue = NormalizeDouble(iMA(NULL,0,longmaPeriod,0,MODE_EMA,PRICE_CLOSE,0),Digits);
double ATR = NormalizeDouble(iATR(NULL,14,NULL,0),Digits);
double lastprice = Close[1];
int OnInit()
  {

   Alert("");
   Alert("The EA just started.");

   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {

   Alert("");
   Alert("The EA just closed.");
  }

void OnTick()
  {
    if(!CheckIfOpenOrdersByMagicNumber(MN))
    {
     if (shortmaValue>longmaValue && lastprice>shortmaValue)
     {   
      double entry = Ask;
      double takeProfitPrice = 0;
      double stoplevel = MarketInfo(NULL, MODE_STOPLEVEL)*GetPipValue();
      double stopLossPrice = entry - ATR;
     // if (MathAbs(entry - stopLossPrice) < stoplevel)
      // {entry = entry - (stoplevel-MathAbs(entry - stopLossPrice));}
      
       OrderID = OrderSend(NULL,OP_BUY,lotsize(maxRiskPerTrade,entry,stopLossPrice),entry,5,stopLossPrice,takeProfitPrice,NULL,MN);
       if (OrderID < 0) Alert("order rejected. Order error: " + GetLastError());
     }
     else if (shortmaValue<longmaValue && lastprice<shortmaValue)
     {
       double entry = Bid;
      double takeProfitPrice = 0;
      double stoplevel = MarketInfo(NULL, MODE_STOPLEVEL)*GetPipValue();
     double stopLossPrice = entry + ATR;
     // if (MathAbs(entry - stopLossPrice) < stoplevel)
      // {entry = entry - (stoplevel-MathAbs(entry - stopLossPrice));}
     
        OrderID = OrderSend(NULL,OP_SELL,lotsize(maxRiskPerTrade,entry,stopLossPrice),entry,5,stopLossPrice,takeProfitPrice,NULL,MN);
        if (OrderID < 0) Alert("order rejected. Order error: " + GetLastError());
     }
  }
while (NewBar() == true)
{
   for(int i = OrdersTotal()-1;i>=0;i--)
   {
     if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
     {
       if(OrderType() == OP_SELL && OrderMagicNumber() == MN && ChartSymbol() == Symbol())
       {
         if (Close[1] > shortmaValue )
         {
           bool res = OrderClose(OrderTicket(),OrderLots(),Ask,5);
      
             if (res != true)
              {
               int err = GetLastError(); Alert("LastError = ",err);
              }
        
         }
      }
      else if (OrderType() == OP_BUY && OrderMagicNumber() == MN && ChartSymbol() == Symbol())
      {
         if (Close[1]< longmaValue)
        {
          bool res = OrderClose(OrderTicket(),OrderLots(),Ask,5);
      
             if (res != true)
              {
               int err = GetLastError(); Alert("LastError = ",err);
              }   
         }
      
       }
    }
     }
      }
}
Documentation on MQL5: Constants, Enumerations and Structures / Chart Constants / Positioning Constants
Documentation on MQL5: Constants, Enumerations and Structures / Chart Constants / Positioning Constants
  • www.mql5.com
Positioning Constants - Chart Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
double shortmaValue = NormalizeDouble(iMA(NULL,0,shortmaPeriod,0,MODE_EMA,PRICE_CLOSE,0),Digits);
double longmaValue = NormalizeDouble(iMA(NULL,0,longmaPeriod,0,MODE_EMA,PRICE_CLOSE,0),Digits);
double ATR = NormalizeDouble(iATR(NULL,14,NULL,0),Digits);

These should all be in OnTick()

 

That is not an assignment; it's initialization of a common (globally declared), or static variable with a constant. They 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.
Reason: