Too many orders

 

I tried writing a simple EA that buys whenever stochastics crosses up. The good news is that it buys at the correct time. The bad news is that it buys many, many times per bar.

I attempted to limit this by counting the total orders. It then makes sure that no orders are currently open before placing a trade. Or at last that's what I'm trying to do. How I restrict it to only place 1 trade at a time?

extern double Lots1 = 0.05;
extern double Lots2 = 0.05;
extern int Stop = 50;
extern int TP1 = 100;
extern int magic = 220349;

double nowK, nowD, prevK, prevD;

int ordTotal, ticket1, ticket2;

int init()
  {

   return(0);
  }

int deinit()
  {

   return(0);
  }

int start()
  {

   nowK = iStochastic(NULL,0,15,5,5,0,1,MODE_MAIN,1);
   prevK = iStochastic(NULL,0,15,5,5,0,1,MODE_MAIN,2);
   
   nowD = iStochastic(NULL,0,15,5,5,0,1,MODE_SIGNAL,1);
   prevD = iStochastic(NULL,0,15,5,5,0,1,MODE_SIGNAL,2);
   
   ordTotal = 0;
   
   // Count the number of open trades created with this magic number
   
   for (int i = OrdersTotal(); i >= 0; i--)
      {
         OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if (OrderSymbol()==Symbol() && OrderMagicNumber() == magic)
            { ordTotal++; }  // end of if statement
      }  // end of for loop
      
   // If Stochastics Crosses Up and there are 0 open orders, then buy   
   
   if (nowK > nowD && prevK < prevD && ordTotal == 0    )
   {
      // open the first half of the position   
      int ticket1 = OrderSend(Symbol(),OP_BUY,Lots1,Ask,0,Ask-Stop*Point,Ask+TP1*Point,NULL,0,0,Green);
      
      if(ticket1>0)
        {
          if(OrderSelect(ticket1,SELECT_BY_TICKET,MODE_TRADES)) 
            Print("BUY opened : " + OrderOpenPrice() + ", " + Symbol() + ", " + Time[0]);
        }
          else Print("Error opening BUY : ",GetLastError()); 
          
      // open the second half of the position    
//     int ticket2 = OrderSend(Symbol(),OP_BUY,Lots2,Ask,0,Ask-Stop*Point,0,NULL,0,0,Green);
   }
//----
   return(0);
  }
//+------------------------------------------------------------------+
Files:
 
texasnomad wrote >>

I tried writing a simple EA that buys whenever stochastics crosses up. The good news is that it buys at the correct time. The bad news is that it buys many, many times per bar.

I attempted to limit this by counting the total orders. It then makes sure that no orders are currently open before placing a trade. Or at last that's what I'm trying to do. How I restrict it to only place 1 trade at a time?

Look to your OrderSend, you dont add your MagicNumber here.

int OrderSend( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)

 
Thank you! That resolved my issue immediately. I really appreciate the help.
Reason: