Close Failing - when compared to moving average

 

Why would these closes fail? 

The close should occur when the open and close prices of the previous candelstick enclose the moving average. 


void CheckForClose()
  {
   double ma;
//--- go trading only for first tiks of new bar
   if(Volume[0]>4) return;
//--- get Moving Average 
   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//---
   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((Open[1]>ma && Close[1]<ma))// || (MathAbs(Bid - OrderOpenPrice()) > TPMax/10000))
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Bid,15,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if((Open[1]<ma && Close[1]>ma))// || (MathAbs(Ask - OrderOpenPrice()) > TPMax/10000))
           {
            if(!OrderClose(OrderTicket(),OrderLots(),Ask,15,White))
               Print("OrderClose error ",GetLastError());
           }
         break;
        }
     }
//---
  }
 
  1. 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 and MetaTrader 4 - MQL4 programming forum.) Always use time.
    I disagree with making a new bar function, because it can only be called once per tick. A variable can be tested multiple times.
              New candle - MQL4 and MetaTrader 4 - MQL4 programming forum

  2. 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 (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 and MetaTrader 4 - MQL4 programming forum
      For FIFO (US brokers,) and you (potentially) process multiple orders per symbol, you must count up and on a successful operation, reprocess all positions (set index to -1 before continuing.)
    2. and check OrderSelect in case earlier positions were deleted. (Continue not break.)
                What are Function return values ? How do I use them ? - MQL4 and MetaTrader 4 - MQL4 programming forum
                Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
    3. and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use the Predefined Variables (Bid/Ask) or OrderClosePrice() instead, on the next order/server call.
 
Also, what would happen when the open or close is equal to the moving average? What happens if the price gaps across the moving average? What happens if your internet connection is sketchy and the order doesn't go through? What happens if there is a lot of volatility when you try to close and the broker can't fill your order within the slippage you've defined, or disables trading for a couple seconds, minutes, etc. to prevent a flash crash?
 
Matthew Colter:
Also, what would happen when the open or close is equal to the moving average? What happens if the price gaps across the moving average? What happens if your internet connection is sketchy and the order doesn't go through? What happens if there is a lot of volatility when you try to close and the broker can't fill your order within the slippage you've defined, or disables trading for a couple seconds, minutes, etc. to prevent a flash crash?
Great Questions! I've noticed that forward testing reveals all of these things. Watching these little algorithms go in the real world of trading is a wonderful learning process.  I always test with real money - learning by failure is so much more impactful.
Reason: