I need help on Expert Advisor based on Closing trades

 

 Hi,

I need your help regarding closing the current running trade. Then open a new trade after closing the previous.

here in this EA 1 trade got open then again next trade is opening without closing the previous one. It keeps moving lke that. 


Here is  the Code of my EA.

2 moving Average


Fast Ma crosses Slow Ma for opening Buy Trade

and Slow MA crosses Fast MA for opening sell Trade. 


Closing Trade Criteria for Buy Trade :

When slow Ma crosses fast Ma then Buy trade will close.


Closing Trade Criteria for Sell Trade:

When Fast Ma crosses Slow Ma then Sell trade closes.

#property description "EA trades two MA crossing."

#property strict

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

//|                                                                  |

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

enum yes_no

  {

   yes=0,   //yes

   no=1,    //no 

  };



extern int

   slip=50,             //Slippage (in pips)

   fast_MA=10,          //Fast ÌA

   slow_MA=20,          //Slow ÌÀ

   MovingShift=0,       //MA Shift

   max_deals=5,         //Maximum deals

   magic=1133;          //Magic number  



extern yes_no losses=1; //Close losses



extern double

   Lot=0.01;            //Lot size



int

   order_type=-1,

   ticket=-1;



double

   ma1,

   ma2;

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

//| OnTick function                                                  |

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

void OnTick()

  {

   ma1=iMA(NULL,0,fast_MA,MovingShift,MODE_SMA,PRICE_CLOSE,1);

   ma2=iMA(NULL,0,slow_MA,MovingShift,MODE_SMA,PRICE_CLOSE,1);



   if(ticket!=-1) CheckForCloseMA();



   if(CountDeals()==0) CheckForOpen();

   else

     {

      if(CountDeals()<max_deals && EnumToString(losses)=="no") CheckForOpen();

     }

  }

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

//| Check for open order conditions                                  |

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

void CheckForOpen()

  {

//sell conditions

   if(ma1<ma2 && order_type!=OP_SELL)

     {

      ticket=OrderSend(Symbol(),OP_SELL,Lot,Bid,slip,0,0,"",magic,0,Red);

      if(ticket==-1) return;



      if(!OrderSelect(ticket,SELECT_BY_TICKET)) {Print("Error during selection."); return;}

      else order_type=OrderType();



      return;

     }

//buy conditions

   if(ma1>ma2 && order_type!=OP_BUY)

     {

      ticket=OrderSend(Symbol(),OP_BUY,Lot,Ask,slip,0,0,"",magic,0,Blue);

      if(ticket==-1) return;



      if(!OrderSelect(ticket,SELECT_BY_TICKET)) {Print("Error during selection."); return;}

      else order_type=OrderType();



      return;

     }

  }

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

//| Check for close order conditions                                 |

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

void CheckForCloseMA()

  {

   if(OrderSelect(ticket,SELECT_BY_TICKET)==false) return;

   if(OrderMagicNumber()!=magic || OrderSymbol()!=Symbol()) return;



   if(OrderType()==OP_BUY)

     {

      if(ma1<ma2)

        {

         if(EnumToString(losses)=="yes")

           {

            if(!OrderClose(OrderTicket(),OrderLots(),Bid,slip,White)) Print("Error during order close.");

           }

         else

           {

            if(OrderProfit()>0)

              {

               if(!OrderClose(OrderTicket(),OrderLots(),Bid,slip,White)) Print("Error during order close.");

              }

            else

              {

               if(!OrderModify(ticket,OrderOpenPrice(),0,OrderOpenPrice()+MarketInfo(Symbol(),MODE_SPREAD)*Point,0)) Print("Error during order modify.");

              }

           }

         ticket=-1;

        }

     }



   if(OrderType()==OP_SELL)

     {

      if(ma1>ma2)

        {

         if(EnumToString(losses)=="yes")

           {

            if(!OrderClose(OrderTicket(),OrderLots(),Ask,slip,White)) Print("Error during order close.");

           }

         else

           {

            if(OrderProfit()>0)

              {

               if(!OrderClose(OrderTicket(),OrderLots(),Ask,slip,White)) Print("Error during order close.");

              }

            else

              {

               if(!OrderModify(ticket,OrderOpenPrice(),0,OrderOpenPrice()-MarketInfo(Symbol(),MODE_SPREAD)*Point,0)) Print("Error during order modify.");

              }

           }

         ticket=-1;

        }

     }

  }

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

//| Count the deals                                                  |

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

int CountDeals()

  {

   int h=0;



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

     {

      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue;

      if(OrderMagicNumber()==magic || OrderSymbol()==Symbol()) h++;

     }

   if(h==0) ticket=-1;

   return(h);

  }

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

Documentation on MQL5: Language Basics / Preprocessor / Program Properties (#property)
Documentation on MQL5: Language Basics / Preprocessor / Program Properties (#property)
  • www.mql5.com
Program Properties (#property) - Preprocessor - Language Basics - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

When you post code please use the CODE button (Alt-S)!

Use the CODE button

 
Sergey Golubev #:

When you post code please use the CODE button (Alt-S)!

Sure . I will do it from the next time. Thanks 

Do you have any suggestion on my given problem. ?

 
Ujjawal Banerjee #:

Sure . I will do it from the next time. 

Please edit your post and use the code button (Alt+S) when pasting code.

EDIT your original post, please do not just post the code correctly in a new post.

 
Ujjawal Banerjee #:

Sure . I will do it from the next time. Thanks 

Do you have any suggestion on my given problem. ?

I won't read your code, since it is unreadable.

But I would like to ask about this statement:


"Closing Trade Criteria for Buy Trade :

When slow Ma crosses fast Ma then Buy trade will close.


Closing Trade Criteria for Sell Trade:

When Fast Ma crosses Slow Ma then Sell trade closes."


This is mutual. How do you want to differentiate between what is crossing which?


And then this:

"Fast Ma crosses Slow Ma for opening Buy Trade

and Slow MA crosses Fast MA for opening sell Trade."


So basically you open and close a sell and a buy on the same signal. How do you differentiate?


 
Keith Watford #:

Please edit your post and use the code button (Alt+S) when pasting code.

EDIT your original post, please do not just post the code correctly in a new post.

Just now i did. Please have a look now.

 
Dominik Christian Egert #:
I won't read your code, since it is unreadable.

But I would like to ask about this statement:


"Closing Trade Criteria for Buy Trade :

When slow Ma crosses fast Ma then Buy trade will close.


Closing Trade Criteria for Sell Trade:

When Fast Ma crosses Slow Ma then Sell trade closes."


This is mutual. How do you want to differentiate between what is crossing which?


And then this:

"Fast Ma crosses Slow Ma for opening Buy Trade

and Slow MA crosses Fast MA for opening sell Trade."


So basically you open and close a sell and a buy on the same signal. How do you differentiate?




Just now i have updated my source code . Please have look into it. 


fast_ma: 10ema

Slow_ma: 20ema


When,

10ema > 20ema : Open Buy Trade

10ema < 20ema:  Open sell Trade


 when,

20ema > 10ema:  Closing Buy Trade 

10ema > 20ema:  Closing Sell Trade

 
  1. You already have an enumeration.
    Don't use strings, don't use ints.
    enum yes_no
      {
       yes=0,   //yes
       no=1,    //no 
      };
    ⋮
    extern yes_no losses=1; //Close losses
    ⋮
          if(CountDeals()<max_deals && EnumToString(losses)=="no") CheckForOpen();
    Use the enumeration.
    enum yes_no{ yes, no };
    ⋮
    extern yes_no losses=no; //Close losses
    ⋮
          if(CountDeals()<max_deals && losses==no) CheckForOpen();

  2. int ticket=-1;
    ⋮
       if(OrderSelect(ticket,SELECT_BY_TICKET)==false) return;

    EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static/global ticket variables will have been lost. You will have an open order but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover?

    Use a OrderSelect / Position select loop on the first tick, or persistent storage (GV+flush or files) of ticket numbers required.

  3. 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.


  4. Don't you mean && here? The EAs order and on the current chart?
          if(OrderMagicNumber()==magic || OrderSymbol()==Symbol()) h++;