My expert starts a long position and finishes it in a few seconds, why?

 

I really don’t understand why my expert buy and sell the same symbol in 2 or 3 seconds, there is no reason for that in my formula. But, for sure I’m doing a mistake, I only don’t know where.

Can you help me out with it?

Thanks

#property copyright ""
#property link      ""

//---- EMAAngle indicator parameters ----//
                                         //
extern int EMAPeriod=50;                 //    
extern double AngleTreshold=1;           //
extern int StartEMAShift=6;              //
extern int EndEMAShift=0;                //
                                         //
//---------------------------------------//

//----Q_Against_Good_Wishs indicator parameters ----//
                                                   //
extern int Per_Trend_Direct=50;                    //
extern int Per_Fast_Trend=10;                      // 
extern int Per_Slow_Trend=21;                      //
                                                   //      
//-------------------------------------------------//

//---- Fractal_dimension -----------------------//
extern int    e_period       = 30;              //
extern int    e_type_data    = PRICE_CLOSE;     //
extern double e_random_line  = 1.5;             //
//----------------------------------------------//

//---------------------------------------------------------------------------//
//                       EXPERT Input Parameters                             //
//---------------------------------------------------------------------------//
datetime barTime; // global variable

extern double Lots=0.1;
extern int Buy_MagicNumber= 4984151211;
extern int Sell_MagicNumber=4984151222;
extern double TakeProfit=80;
extern double StopLoss=300;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+


int start()
  {
   double Compra;
   double Venda;
   int Orders_total, ticket, cnt;
   bool Reject_entry;
   
  
//---- initial data checks----//

if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   
//----Indicator Reference----//

Compra=  iCustom(Symbol(),
                 0,
                 "Q Against God Wishes V2",
                 EMAPeriod,
                 AngleTreshold,
                 StartEMAShift,
                 EndEMAShift,
                 Per_Trend_Direct,
                 Per_Fast_Trend,
                 Per_Slow_Trend,
                 e_period,
                 e_type_data,
                 e_random_line,
                 0,
                 1);
                 
Venda=   iCustom(Symbol(),
                 0,
                 "Q Against God Wishes V2",
                 EMAPeriod,
                 AngleTreshold,
                 StartEMAShift,
                 EndEMAShift,
                 Per_Trend_Direct,
                 Per_Fast_Trend,
                 Per_Slow_Trend,
                 e_period,
                 e_type_data,
                 e_random_line,
                 1,
                 1);
                 
Orders_total=OrdersTotal();

//---- Checking for orders ----//
   for( int z = Orders_total - 1; z >= 0; z -- ) // checking for orders
      {
         if(Orders_total>0) // If there is orders opened check there magic number
            {
               if(OrderSelect( z, SELECT_BY_POS )==true && (OrderMagicNumber( ) ==Buy_MagicNumber || OrderMagicNumber( ) == Sell_MagicNumber))
                  {
                     Reject_entry=1;
                  }
            }
      }
      
     if(Orders_total<1 || Reject_entry==0) // no opened orders identified or open positions was not generated by this expert
      {
      // no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
//---- check for long position (BUY) possibility ----//
        if( barTime < Time[0] ) 
        {
            barTime = Time[0]; // keep the new bar open time
            
        if(Compra==1)
        {
         ticket=OrderSend(Symbol(),
                          OP_BUY,
                          Lots,
                          Ask,
                          1.5,
                          Ask-(StopLoss*Point),
                          Ask+ (TakeProfit*Point),
                          "Q Against God Wishes",
                          Buy_MagicNumber,
                          0,
                          Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
           }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
//---- check for short position (SELL) possibility ----//
       if(Venda==-1)
         {
         ticket=OrderSend(Symbol(),
                           OP_SELL,
                           Lots,
                           Bid,
                           1.5,
                           Bid+(StopLoss*Point),
                           Bid-(TakeProfit*Point),
                           "Q Against God Wishes",
                           Sell_MagicNumber,
                           0,
                           Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
           }
         else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
        
       }    
      }
       
      

CheckForClose();

return(0);      
   }
   
   
//----------------------------------------------------------------------------------------------------//
//                              Close Position                                           //
//----------------------------------------------------------------------------------------------------//

   void CheckForClose()
   {
   bool Close_Long;
   bool Close_Short; 
         
   
                                       
   
   for(int cnt=0; cnt < OrdersTotal(); cnt++)
         {
         
         //--------------- Sending order --------------//
         if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)==true) 
            {  
               
                //------ Flag to Close Long Trades ------//
          
               if( Ask >= (OrderOpenPrice( )+80*Point))
               {
                  Close_Long=1;
               }                   
         
                //------ Flag to Close Short Trades ------//
                         
               if( Bid <= (OrderOpenPrice( )-80*Point))
               {
                  Close_Short=1;
               }   
                              
               if(OrderType()==OP_BUY &&  OrderSymbol()==Symbol() && Close_Long==1) //  check for opened BUY position // check for symbol // check for the stop Loss condition
               { Print(" Close Buy ok");
                  OrderClose(OrderTicket(),
                           Lots,
                           Ask,
                           3,
                           Red);  
               } 
               
               if(OrderType()==OP_SELL &&  OrderSymbol()==Symbol() && Close_Short==1 )
               {  Print(" Close Sell ok");
                  OrderClose(OrderTicket(),
                           Lots,
                           Bid,
                           3,
                           Red);
               }
            }
         }
  }

 

Your code sets close flags to true, but not to to false.



void CheckForClose()
   {
   bool Close_Long;
   bool Close_Short; 

Try this

void CheckForClose()
   {
   bool Close_Long=0; // or Close_Long=false;
   bool Close_Short=0; // or Close_Short=false;
 
 

I thought I was initializing the bool variable. I didn’t know the default parameter was “true”. Now it makes sense.

I will test it on real time and I’m going to post the result here as soon a get it.

Thank you Abstract mind

 
  1. for( int z = Orders_total - 1; z >= 0; z -- ) // checking for orders
          {
             if(Orders_total>0) // If there is orders opened check there magic number
    The IF is useless (always true.) You can't get to the IF when Orders_total is zero because the for won't iterate.
  2. Reject_entry=1;
    ..
    if(Orders_total<1 || Reject_entry==0) 
    Reject_entry is a bool, initialize it to true, set it to false, not integers
    if (Orders_total<1 makes this EA incompatible with any other EA including itself on other charts.
       Orders_total = 0;
       for( int z = OrdersTotal() - 1; z >= 0; z -- ) if(
           OrderSelect( z, SELECT_BY_POS )
       && (OrderMagicNumber()==Buy_MagicNumber || OrderMagicNumber() == Sell_MagicNumber)
       &&  OrderSymbol()       == Symbol()
        ) Orders_total++;
       if(Orders_total<1) // no opened orders identified or open positions was not generated by this expert

  3. You MUST count down when closing orders. Use true/false not 0/1 or just get rid of the bools entirely
    void CheckForClose(){
       for( int z = OrdersTotal() - 1; z >= 0; z -- ) if(
           OrderSelect( z, SELECT_BY_POS )
       && (OrderMagicNumber()==Buy_MagicNumber || OrderMagicNumber() == Sell_MagicNumber)
       &&  OrderSymbol()       == Symbol()
       && MathAbs(OrderClosePrice() - OrderOpenPrice()) > 80*point){
           if(!OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(),3,Red) )
              Alert("OrderClose(",OrderTicket(),") failed: ",GetLastError();
       }
    }
    

  4. There's no reason to have two magic numbers. Filter on one, then look at the type.
  5. EA's should adjust to 5 digit brokers TP, SL, AND slippage) On ECN brokers you open the order and then set the tp/sl
    //++++ These are adjusted for 5 digit brokers.
    int     pips2points;    // slippage  3 pips    3=points    30=points
    double  pips2dbl;       // Stoploss 15 pips    0.0015      0.00150
    int     Digits.pips;    // DoubleToStr(dbl/pips2dbl, Digits.pips)
    int     init(){
        if (Digits == 5 || Digits == 3){    // Adjust for five (5) digit brokers.
                    pips2dbl    = Point*10; pips2points = 10;   Digits.pips = 1;
        } else {    pips2dbl    = Point;    pips2points =  1;   Digits.pips = 0; }
        // OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl
    

 

WHRoeder

Thank you a lot, you really studied my code and found all errors I‘ve done. That is helpful, once I’m not programmer, and nobody see what I build. I’m sure it will correct my problem. Tomorrow I going to do those changes that you wrote above.

Thank you again.

 


int start()
  {
   double Compra;
   double Venda;
   int Orders_total, ticket, cnt;
   bool time_ok=false;
   
  
//---- initial data checks----//

if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   
//----Indicator Reference----//

Compra=  iCustom(Symbol(),
                 0,
                 "Q Against God Wishes V2",
                 EMAPeriod,
                 AngleTreshold,
                 StartEMAShift,
                 EndEMAShift,
                 Per_Trend_Direct,
                 Per_Fast_Trend,
                 Per_Slow_Trend,
                 e_period,
                 e_type_data,
                 e_random_line,
                 0,
                 1);
                 
Venda=   iCustom(Symbol(),
                 0,
                 "Q Against God Wishes V2",
                 EMAPeriod,
                 AngleTreshold,
                 StartEMAShift,
                 EndEMAShift,
                 Per_Trend_Direct,
                 Per_Fast_Trend,
                 Per_Slow_Trend,
                 e_period,
                 e_type_data,
                 e_random_line,
                 1,
                 1);
                 

//---- Checking for orders ----//
        
        time_ok=false;
        
        if( barTime < Time[0] ) 
        {
            barTime = Time[0]; // keep the new bar open time
            
            time_ok=true; // flag to enter only once per bar
        }
        
         Orders_total = 0;
        
         for( int z = OrdersTotal() - 1; z >= 0; z -- ) 
         {
            if( OrderSelect( z, SELECT_BY_POS ) && (OrderMagicNumber()==Buy_MagicNumber || OrderMagicNumber() == Sell_MagicNumber) &&  OrderSymbol()== Symbol() )
             {
               Orders_total++;
             }
         }
//--------------------------------------------------------------------------------

      if(Orders_total<1 && time_ok==true) // no opened orders identified or open positions was not generated by this expert
      {

            if(Compra==1)
            {
                     ticket=OrderSend(Symbol(),
                                      OP_BUY,
                                      Lots,
                                      Ask,
                                      1.5,
                                      Bid-(StopLoss*Point),
                                      Bid+ (TakeProfit*Point),
                                      "Q Against God Wishes",
                                      Buy_MagicNumber,
                                      0,
                                      Green);
                     if(ticket>0)
                       {
                        if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
                       }
                     else Print("Error opening BUY order : ",GetLastError()); 
                     return(0); 
            }
            
//---- check for short position (SELL) possibility ----//
         if(Venda==-1)
           {
                     ticket=OrderSend(Symbol(),
                                       OP_SELL,
                                       Lots,
                                       Bid,
                                       1.5,
                                       Ask+(StopLoss*Point),
                                       Ask-(TakeProfit*Point),
                                       "Q Against God Wishes",
                                       Sell_MagicNumber,
                                       0,
                                       Red);
                     if(ticket>0)
                       {
                        if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
                       }
                     else Print("Error opening SELL order : ",GetLastError()); 
                     return(0); 
            }

   }

I did all the changes needed, but the problem still there, cutting the trades early. I decided to remove the “CheckForClose()”, once I want to close at the tp or sl.

Any idea what’s happening?

Reason: