My EA Does Not Run Please Help - SOS

 

Hello I have been working on an EA for the past couple of days and I'm pretty new to mql4. I have no idea what is wrong with the code or any idea on how to fix it and was wondering if someone could help me 

It would be extremely appreciated. I have yet been able to set the conditions for the take profits however the EA should still run.   I thank anyone in advance for helping me. :)


//--- Inputs
input double Lots          =0.01;
input double MaximumRisk   =0.02;
input double DecreaseFactor=3;
input int    MovingPeriod  =12;
input int    MovingShift   =6;
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//---
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//--- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//--- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//--- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
           {
            Print("Error in history!");
            break;
           }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
            continue;
         //---
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1)
         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//--- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }

void CheckForOpen()
{
  int res;
  //--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
  
 //we calculate a EMA for All 5 
  double MyMovingAverageYellow = iMA(_Symbol, _Period, 5, 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageRed = iMA(_Symbol, _Period, 13, 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageAqua = iMA(_Symbol,  _Period, 30 , 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageGrey = iMA(_Symbol,  _Period, 20, 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageBlue = iMA(_Symbol,  _Period, 80, 0, MODE_EMA, PRICE_CLOSE, 0);
   
  
  //Conditions For The Buy
  
  
  bool bullishEC = false;
  bool redCrossBuy = false;
  bool belowCandle = false;
  bool pipDifferenceAquaLongEMA = false;
  
  if(Close[1] >= Open[2] &&  Close[2] < Open[2])
  {
  bullishEC = true;
  }
  if((MyMovingAverageRed >= Open[1] && MyMovingAverageRed <= Close[1])&& (MyMovingAverageRed <= Open[2] && MyMovingAverageRed >= Close[2]))
  {
  redCrossBuy = true;
  }
  if(Open[1] > MyMovingAverageAqua && Close[2] > MyMovingAverageAqua)
  {
  belowCandle = true;
  }
  if(((Ask - MyMovingAverageAqua) /Point)<=10)
  {
  pipDifferenceAquaLongEMA = true;
  }
  
  if(bullishEC == true && redCrossBuy == true && belowCandle == true && pipDifferenceAquaLongEMA == true)
  {
  Alert("Buy signal");
  res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      return;
  }
  
  
  //Conditions For Sell
  bool bearishEC = false;
  bool redCrossSell = false;
  bool aboveCandle = false;
  bool pipDifferenceAquaShortEMA = false;
  
  if(Close[1] <= Open[2] && Close[2] > Open[2])
  {
  bearishEC=true;
  }
  if((MyMovingAverageRed <= Open[1] && MyMovingAverageRed >= Close[1]) && (MyMovingAverageRed >= Open[2] && MyMovingAverageRed <= Close[2]))
  {
  redCrossSell=true;
  }
  if(Close[1] < MyMovingAverageAqua && Close[2] < MyMovingAverageAqua)
  {
  aboveCandle=true;
  }
  if(((MyMovingAverageAqua - Close[0])/Point)> 10)
  {
  pipDifferenceAquaShortEMA=true;
  }
  
  if(bearishEC == true && redCrossBuy == true && aboveCandle==true && pipDifferenceAquaShortEMA == true)
  {
  Alert("Sell Signal");
  res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
      return;
  }
  
 
 }
 
void CheckForClose()
{
  //--- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
   
  //we calculate a EMA for All 5 
  double MyMovingAverageYellow = iMA(_Symbol, _Period, 5, 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageRed = iMA(_Symbol, _Period, 13, 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageAqua = iMA(_Symbol,  _Period, 20 , 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageGrey = iMA(_Symbol,  _Period, 20, 0, MODE_EMA, PRICE_CLOSE, 0);
  double MyMovingAverageBlue = iMA(_Symbol,  _Period, 80, 0, MODE_EMA, PRICE_CLOSE, 0);


  //Stop Loss For Buy
  bool lowerLowSL = false;
  bool AquaEMASL = false;
  bool DefultTenPips = false;
  double StopLossBuy = false;
 
  //Finds Lowest Price in The Last X Amount Of Candles
  int LowestCandel = iLowest(_Symbol, _Period, MODE_LOW, 50, 0);
    
  //Finds difference In Price From Current Price To Lower Low
  double lowerLowTen = ((Open[1] - Low[LowestCandel])/Point);
    
  //Finds Difference In Price From Price To Aqua EMA
  double AquaEMATen = ((Open[1] - MyMovingAverageAqua)/Point);
    
  //Finds value 10 pips above
  double autoTen = (Open[1] + 0.001);
 
   if(lowerLowTen >= 10)
    {
     lowerLowSL = true;
     StopLossBuy = Low[LowestCandel];
    }
   if(AquaEMATen >= 10)
    {
    AquaEMASL = true;
    StopLossBuy = MyMovingAverageAqua;
    }
   else
    {
    StopLossBuy = autoTen;
    DefultTenPips = true;
 
    }
    
  //Stop Loss For Sell
  
  bool higherHighSL = false;
  bool AquaEMASLSell = false;
  bool DefultTenPipsSell = false;
  double StopLossSell = false;
 
  //Finds Highest Price in The Last X Amount Of Candles
  int HighestCandle = iHighest(_Symbol, _Period, MODE_HIGH, 50, 0);;
    
  //Finds difference In Price From Current Price To Lower Low
  double higherThanTen = ((Open[1] - High[HighestCandle])/Point);
    
  //Finds Difference In Price From Price To Aqua EMA
  double AquaEMATenSell = ((MyMovingAverageAqua-Open[1])/Point);
    
  //Finds value 10 pips above
  double autoTenSell = (Open[1] + 0.001);
 
   if(higherThanTen >= 10)
    {
     higherHighSL = true;
     StopLossSell = Low[HighestCandle];
    }
   if(AquaEMATenSell >= 10)
    {
    AquaEMASLSell = true;
    StopLossSell = MyMovingAverageAqua;
    }
   else
    {
    StopLossSell = autoTenSell;
    DefultTenPipsSell = true;
    }
    
    for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //--- check order type 
      if(OrderType()==OP_BUY)
        {
         if(lowerLowSL == true && Bid >= Low[LowestCandel])
         {
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         
         if(AquaEMASL == true && Bid >= MyMovingAverageAqua)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         if(DefultTenPips == true && Bid >= autoTen)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
               Print("OrderClose error ",GetLastError());
           }
         }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(higherHighSL == true && Ask >= High[HighestCandle])
         
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         if(AquaEMASLSell == true && Ask >= MyMovingAverageAqua)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         if(DefultTenPipsSell == true && Ask >= autoTenSell)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
               Print("OrderClose error ",GetLastError());
           }
         }
         break;   
     }       
}

  


void OnTick()
{

//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//--


 
}
   
Basic Principles - Trading Operations - MetaTrader 5 Help
Basic Principles - Trading Operations - MetaTrader 5 Help
  • www.metatrader5.com
is an instruction given to a broker to buy or sell a financial instrument. There are two main types of orders: Market and Pending. In addition, there are special Take Profit and Stop Loss levels. is the commercial exchange (buying or selling) of a financial security. Buying is executed at the demand price (Ask), and Sell is performed at the...
 
Anna U: I have no idea what is wrong with the code or any idea on how to fix it 
  1. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?

  2.    lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);

    Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin and leverage. No SL means you have infinite risk. Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% total.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce the stop goes below the support.

    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/pip but it takes account of the exchange rates of the pair vs. your account currency.)

    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum 2017.10.10
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum 2018.02.11
                Lot value calculation off by a factor of 100 - MQL5 programming forum 2019.07.19

    4. You must normalize lots properly and check against min and max.

    5. You must also check FreeMargin to avoid stop out

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

  3. You used NormalizeDouble, It's use is usually wrong, as it is in your case.
    1. Floating point has infinite number of decimals, it's your not understanding floating point and that some numbers can't be represented exactly. (like 1/10.)
                Double-precision floating-point format - Wikipedia, the free encyclopedia

      See also The == operand. - MQL4 programming forum

    2. Print out your values to the precision you want with DoubleToString - Conversion Functions - MQL4 Reference.

    3. SL/TP (stops) need to be normalized to tick size (not Point) — code fails on metals. (On 5Digit Broker Stops are only allowed to be placed on full pip values. How to find out in mql? - MQL4 programming forum) and abide by the limits Requirements and Limitations in Making Trades - Appendixes - MQL4 Tutorial and that requires understanding floating point equality Can price != price ? - MQL4 programming forum

    4. Open price for pending orders need to be adjusted. On Currencies, Point == TickSize, so you will get the same answer, but it won't work on Metals. So do it right: Trailing Bar Entry EA - MQL4 programming forum or Bid/Ask: (No Need) to use NormalizeDouble in OrderSend - MQL4 programming forum

    5. Lot size must also be adjusted to a multiple of LotStep and check against min and max. If that is not a power of 1/10 then NormalizeDouble is wrong. Do it right.

    6. MathRound() and NormalizeDouble() are rounding in a different way. Make it explicit.
                MT4:NormalizeDouble - MQL5 programming forum
                How to Normalize - Expert Advisors and Automated Trading - MQL5 programming forum

    7. Prices you get from the terminal are already normalized.

    8. PIP, Point, or Tick are all different in general.
                What is a TICK? - MQL4 programming forum 2014.08.03

  4.    if(Volume[0]>1) return;

    For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart,) volume is unreliable (miss ticks,) Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
              New candle - MQL4 programming forum #3 2014.04.04

    I disagree with making a new bar function, because it can only be called once per tick. A variable can be tested multiple times.
              Running EA once at the start of each bar - MQL4 programming forum 2011.05.06

  5. Your code
     bool bullishEC = false;
      if(Close[1] >= Open[2] &&  Close[2] < Open[2])
      {
      bullishEC = true;
      }
    Simplified
     bool bullishEC = Close[1] >= Open[2] &&  Close[2] < Open[2];
              Increase Order after stoploss - MQL4 programming forum #1.3 2017.05.29

  6.   if(bullishEC == true && redCrossBuy == true && belowCandle == true && pipDifferenceAquaLongEMA == true)
    

    You should be able to read your code out loud and have it make sense. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled where as Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.

  7.   res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
    

    Check your return codes, and report your errors. Don't look at GLE/LE unless you have an error. Don't just silence the compiler, it is trying to help you.
              What are Function return values ? How do I use them ? - MQL4 programming forum
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles

  8. No SL means you have infinite risk. See № 1.

  9.     for(int i=0;i<OrdersTotal();i++){
          ⋮
           if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
    In the presence of multiple orders (one EA multiple charts, multiple EAs, manual trading,) while you are waiting for the current operation (closing, deleting, modifying) to complete, any number of other operations on other orders could have concurrently happened and changed the position indexing:
    1. For non-FIFO (non-US brokers), (or the EA only opens one order per symbol,) you can simply count down, in a position loop, and you won't miss orders. Get in the habit of always counting down.
                Loops and Closing or Deleting Orders - MQL4 programming forum
    2. For In First Out (FIFO rules — US brokers,) and you (potentially) process multiple orders per symbol, you must find the earliest order (count up,) close it, and on a successful operation, reprocess all positions.
                CloseOrders by FIFO Rules - Strategy Tester - MQL4 programming forum - Page 2 #16
                MetaTrader 5 platform beta build 2155: MQL5 scope, global Strategy Tester and built-in Virtual Hosting updates - Best Expert Advisors - General - MQL5 programming forum #1 № 11 ACCOUNT_FIFO_CLOSE

    3. and check OrderSelect in case earlier positions were deleted.
                What are Function return values ? How do I use them ? - MQL4 programming forum
                Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
    4. and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use, on the next order / server call, the Predefined Variables (Bid/Ask.) Or instead, be direction independent and just use OrderClosePrice().

 
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
  • Always go back to front:
    for(int i=OrdersTotal()-1;i>=0;i--)
  • Don't leave the loop if an OrderSelect fails, but continue:
    if(! OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;

Just 2 things, there are probably others to consider.