Help with MA cross over Price IN EA

 

I am attempting to create a simple EA that uses only the Close Price of the Previous bar compared to an MA of 'x' periods.

Parameters:

If the Close Price of the Previous bar is Higher than MA, then Buy.  Close the trade when the Close Price of the Previous bar is below the MA.


If the Close Price of the Previous bar is Lower than the MA, then Sell.  Close the trade when the Close Price of the Previous bar is above the MA.


So far, the Opening and Closing of the Trades is happening at the wrong times.  I cannot tell why.  I suspect it has something to do with my MA creation.


Any help is appreciated.


Thank you


The following is my code:

#property description "First, check to see if there is an open Trade."
#property description "If price is Higher than MA, then Buy; "
#property description "Close the trade when the price is Lower than the MA."
#property description "If price is Lower than MA, then Sell; "
#property description "Close the trade when the price is Higher than the MA."
 


//--- input parameters
input double   MaximumRisk=0.02;
input double   MinimumLotSize=0.01;
input int      MAPeriod=10;
input int      slippage=3;
input int      StopLoss=0;
input int      TakeProfit=0;

//---Global Variables
double freemargin = AccountInfoDouble(ACCOUNT_FREEMARGIN);
double symbolmargin = SymbolInfoDouble(Symbol(), SYMBOL_MARGIN_INITIAL);

double current_bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double current_ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); 




#define MA_MAGIC 842617



//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

   

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

//**MA Array Creation
   double ma[];
   ArraySetAsSeries(ma, true);
   int maHandle=iMA(_Symbol,PERIOD_CURRENT,MAPeriod,0,MODE_SMMA,PRICE_WEIGHTED);
   CopyBuffer(maHandle,0,0,MAPeriod,ma);
   
//**Get Close Prices
   double Close[];
   ArraySetAsSeries(Close, true);
   CopyClose(_Symbol,0,0,1,Close);

//**Trade Structures
   MqlTradeRequest request = {0};
   MqlTradeResult result = {0};
   ZeroMemory(request);

//**Current Position Information - If there is one open and if Buy or Sell
   bool openPosition = PositionSelect(_Symbol);
   long positionType = PositionGetInteger(POSITION_TYPE);

//**If there is an Open Position, this retrieves the size of the Position
   double currentVolume = 0;
   if(openPosition == true) currentVolume = PositionGetDouble(POSITION_VOLUME);
   

//**Trade Algorithms
  //**Open a Long
  //**If the Close of the previous bar is Higher than the Moving Average and there is No Open Position
   if(Close[1] > ma[0] && openPosition == false)
   {
            
      //Trade Placement
      request.action = TRADE_ACTION_DEAL;
      request.type = ORDER_TYPE_BUY;
      request.symbol = _Symbol;
      request.volume = MinimumLotSize;
      request.type_filling = ORDER_FILLING_FOK;
      request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      request.sl = StopLoss;
      request.tp = TakeProfit;
      request.deviation = slippage;
      request.magic = MA_MAGIC;
      request.comment = "Open Long Position";
      
      OrderSend(request,result);
      
      //**This will attempt to prevent the positions from closing prematurely
      if(Close[1] > ma[0])
         {Sleep(60000); //Sleep 1 minutes
         }
      
   } 
   //**Close the Long
   //**If the Close of the previous bar is Lower than the Moving Average and there IS an Open Buy Position
   if (Close[1] < ma[0] && openPosition == true && positionType == POSITION_TYPE_BUY)
   {
            
      //Get Position Information
      PositionSelect(_Symbol);
      PositionGetDouble(POSITION_VOLUME, currentVolume);
      
      //Trade Placement
      request.action = TRADE_ACTION_DEAL;
      request.type = ORDER_TYPE_SELL;
      request.symbol = _Symbol;
      request.volume = currentVolume;
      request.type_filling = ORDER_FILLING_FOK;
      request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      request.sl = StopLoss;
      request.tp = TakeProfit;
      request.deviation = slippage;
      request.magic = MA_MAGIC;
      request.comment = "Close Long Position";
      
      OrderSend(request,result);
      
   }   
   //Open a Short
   //**If the Close of the previous bar is Lower than the Moving Average and there is No Open Position
   if (Close[1] > ma[0] && openPosition == false)
   {
            
      //Trade Placement
      request.action = TRADE_ACTION_DEAL;
      request.type = ORDER_TYPE_SELL;
      request.symbol = _Symbol;
      request.volume = MinimumLotSize;
      request.type_filling = ORDER_FILLING_FOK;
      request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      request.sl = StopLoss;
      request.tp = TakeProfit;
      request.deviation = slippage;
      request.magic = MA_MAGIC;
      request.comment = "Open Short Position";
      
      OrderSend(request,result);

      //**This will attempt to prevent the positions from closing prematurely
      if(Close[1] < ma[0])
         {Sleep(60000); //Sleep 1 minutes
         }      
   }
   //Close the Short
   //**If the Close of the previous bar is Higher than the Moving Average and there IS an Open Sell Position
   if (Close[1] > ma[0] && openPosition == true && positionType == POSITION_TYPE_SELL)
   {
      
      
      //Trade Placement
      request.action = TRADE_ACTION_DEAL;
      request.type = ORDER_TYPE_BUY;
      request.symbol = _Symbol;
      request.volume = currentVolume;
      request.type_filling = ORDER_FILLING_FOK;
      request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      request.sl = StopLoss;
      request.tp = TakeProfit;
      request.deviation = slippage;
      request.magic = MA_MAGIC;
      request.comment = "Close Short Position";
      
      OrderSend(request,result);
      
            
   }
   
  }
//+------------------------------------------------------------------+
//| Trade function                                                   |
//+------------------------------------------------------------------+
void OnTrade()
  {
//---

  }
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   
  }
//+------------------------------------------------------------------+
 
What is the index of "previous bar" ?
 
Alain Verleyen:
What is the index of "previous bar" ?
I have it set to One in the 'Close' array.

  The original post showed it set to zero because I had been playing with the numbers to understand what was happening.  Forgot to set it back before posting.  Sorry for confusion, I made an edit to correct it.
 

Hi Randy. Any idea why I get this error when trying to compile the MT5 script in this thread. Regards. Wayne

 
wayneae #: Any idea why I get this error when trying to compile the MT5 script in this thread. Regards. Wayne
  1. Because zero is not one of the ENUM_TRADE_REQUEST_ACTIONS ; exactly what the message says.

  2. Because you are calling OrderSend and not checking its return code; exactly what the message says.

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


Reason: