possible help with EA code

 

good evening people, i was wondering if i could get some advice off anybody regarding my code (see below) 

so one of the basic but important factors in my strategy is the EMAs (50 &200) when 50>200 buy and when 200>50 sell. i was wondering how i could exit a buy trade if the EMAs switch over while i am in the trade. I have been learning to code for a few months now so i do apologise if its something ridiculously simple that ive missed .


#include  <customfunctions01.mqh>



int rsiPeriod = 7;

input double riskPerTrade = 0.01;

input int rsiLowerLevel = 20;

input int rsiUpperLevel = 80;



input int stoplosspips = 150;



input int takeprofitpips = 500;

//input int breakeven = 40;

input int SlowMA = 200;

input int FastMA = 50;

input int StoUpperlevel = 80;

input int StoLowerLevel = 20;





input int ticket = 0;



input    string      TRAILING       = "========= TRAILING =========";

input    bool        useTS          = true;    // Use Trailing

input    double      tsstop         = 150;       // Trailing Stop

input    double      tsstart        = 150;       // Trailing Start

input    double      tsstep         = 1;        // Trailing Step



int openOrderID;

int magic = magicNB;

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

   Alert("");

   Alert("Starting Strategy johnstrategy");



   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

   Alert("Stopping johnstrategy");

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

  

   InitiateTrailing(useTS);

  



  

   

   double FastMA = iMA(NULL,0,50,0,MODE_SMA,PRICE_CLOSE,0);

   double SlowMA= iMA(NULL,0,200,0,MODE_SMA,PRICE_CLOSE,1);

   double rsiValue = iRSI(NULL,0,rsiPeriod,PRICE_CLOSE,0);

   double currentRSI = iRSI(NULL,0,7,0,0);

   double previousRSI = iRSI(NULL,0,7,0,5);

   double Stovalue = iStochastic(NULL, 0, 14 , 3, 3, MODE_SMA, MODE_MAIN, 0, 0);

   double currentStovalue = iStochastic(NULL, 0, 14 , 3, 3, MODE_SMA, MODE_MAIN, 0, 0);

   double previousStovalue = iStochastic (NULL, 0, 14 , 3, 3, MODE_SMA, MODE_MAIN, 0, 1);

   double MACD = iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);

   

 

  //if(!checkifopenordersbymagicnb(magicNB))&&//if no open orders try to enter new position

  

  if (isnewcandle())

   {

if (rsiValue<20 &&  FastMA>SlowMA&& currentStovalue< 20 && Ask<SlowMA) //buying

  

      {

         Print("MA's show a bullish market and rsiValue is lower than " + rsiLowerLevel+ " , Sending buy order");

       double stopLossPrice = Ask - stoplosspips * getpipvalue();

         double takeProfitPrice = Ask + takeprofitpips * getpipvalue();

         Print("Entry Price = " + Ask);

         Print("Stop Loss Price = " + stopLossPrice);

       Print("Take Profit Price = " + takeProfitPrice);

         

         double lotSize = optimallotsize(riskPerTrade,Ask,stopLossPrice);

         

        openOrderID = OrderSend(NULL,OP_BUYLIMIT,lotSize,Ask,10,stopLossPrice,takeProfitPrice,NULL,magicNB);

        if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());

        

        

   

      }

   else if(rsiValue > 80  &&  SlowMA>FastMA&& currentStovalue>80  && Bid>SlowMA )//shorting

     

      {

         

      

      Print("MA's show a bearish market and rsiValue is above  " + rsiUpperLevel+ " , Sending short order");

 double stopLossPrice = Bid + stoplosspips * getpipvalue();

     double takeProfitPrice = Bid - takeprofitpips * getpipvalue();

      Print("Entry Price = " + Bid);

     Print("Stop Loss Price = " + stopLossPrice);

      Print("Take Profit Price = " + takeProfitPrice);

   

    double lotSize = optimallotsize(riskPerTrade,Bid,stopLossPrice);



    openOrderID = OrderSend(NULL,OP_SELLLIMIT,lotSize,Bid,10,stopLossPrice,takeProfitPrice,NULL,magicNB);

    if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());



}















}

}







    double PipsToPrice(double pips)

{

   double PointValue;

   if (Digits == 5 || Digits == 3) PointValue = 10.0 * Point;

   else PointValue = Point;

   if (Symbol() == "GOLD" || Symbol() == "SILVER" || Digits==2) 

   {

      return pips/10;

      PointValue = Point*10;// / 100.0;

   }

   if (Symbol() == "GOLDEURO"|| Symbol() == "SILVEREURO")

   {

      PointValue = Point;

   }

   return pips*PointValue;



   double P=1;

   if(Digits==5 || Digits==3)P=10;else P=1;

   return pips*(Point*P);

}              

                  

                  

//+------------------------------------------------------------------+

//| Trailing Functions                                               |

//+------------------------------------------------------------------+

void InitiateTrailing(bool allowTS)

{

   if(allowTS)

   {

      TrailingPositionBuy(tsstop,tsstart,tsstep);

      TrailingPositionSell(tsstop,tsstart,tsstep);

   }

}



//+------------------------------------------------------------------+

void TrailingPositionBuy(double trailingStop,double activatePoint,double step)

{

   for(int i=0;i<OrdersTotal();i++)

   {

      if (OrderSelect(i, SELECT_BY_POS)  &&  (OrderMagicNumber()==magic)   &&  OrderSymbol()== Symbol() )

      { 

         if(NormalizeDouble((Bid-OrderOpenPrice()),Digits)>PipsToPrice(activatePoint))

         {

            if(OrderType()==OP_BUY)

            {

               if(OrderStopLoss()==0)

               {

                  ModifyStopLoss(Bid-trailingStop*Point*150);

               }

               else if(OrderStopLoss()<Bid-trailingStop*Point*150)

               {

                  //ModifyStopLoss(Bid-trailingStop*Point*10);

                  ModifyStopLoss(OrderStopLoss()+(step)*Point*10);

               }

            }

         }   

      }

   }

}

//+------------------------------------------------------------------+

void TrailingPositionSell(double trailingStop,double activatePoint,double step)

{

   for(int i=0;i<OrdersTotal();i++)

   {

      if (OrderSelect(i, SELECT_BY_POS)  &&  (OrderMagicNumber()== magic)   &&  OrderSymbol()== Symbol() )

      { 

         if(NormalizeDouble((OrderOpenPrice()-Ask),Digits)>PipsToPrice(activatePoint))

         {

            if(OrderType()==OP_SELL)

            {

               if(OrderStopLoss()==0)

               {

                  ModifyStopLoss(Ask+trailingStop*Point*150);

               }

               else if(OrderStopLoss()>Ask+trailingStop*Point*150)

               {

                  //ModifyStopLoss(Ask+trailingStop*Point*10);

                  ModifyStopLoss(OrderStopLoss()-step*Point*10);

               }   

            } 

         }

      }

   }

}

//+------------------------------------------------------------------+

void ModifyStopLoss(double sl)

{

   bool fm;

   fm = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0);

}

//+------------------------------------------------------------------+   
 
  1. John James Holmes: . i was wondering how i could exit a buy trade if the EMAs switch over while i am in the trade.

    If slow is above the fast, close all buy orders (pending or otherwise), then test for opening.

  2.     openOrderID = OrderSend(NULL,OP_SELLLIMIT,lotSize,Bid,10,stopLossPrice,takeProfitPrice,NULL,magicNB);
    

    You can not open pending orders at the market.

    You can't move stops (or pending prices) closer to the market than the minimum: MODE_STOPLEVEL * _Point or SymbolInfoInteger(SYMBOL_TRADE_STOPS_LEVEL).
              Requirements and Limitations in Making Trades - Appendixes - MQL4 Tutorial

    On some ECN type brokers the value might be zero (the broker doesn't know). Use a minimum of two (2) PIPs.

    The checks a trading robot must pass before publication in the Market - MQL5 Articles (2016)

 
William Roeder #:
  1. If slow is above the fast, close all buy orders (pending or otherwise), then test for opening.

  2. You can not open pending orders at the market.

thank you mate, will try this out. Much appreciated