Why does this EA sometimes open another order randomly?!

 

I am brand new to coding and have written this program to open orders quickly as my trade management requires that i exit portions of my trade at different takeprofit levels therefor i am need to open 3 positions when i get into a trade, all of different sizes.

The idea of the program is to give you the option of getting in either "at market" or "limit". Long or Short. Adjustment of TP's and Stoploss is also available but defaults are in place in the code if TP's are left 0.0. The program also works out the risk based on current account balance and tick value and opens the appropriate lot sizes.

The program works perfectly all except for 1 bug that i can't seem to work out. Sometimes randomly it opens a duplicate of the trade again at a random point in the future. I came back to the computer today and noticed that it had opened a trade another 2 times (totaling an extra 6 positions). I have not re-compiled or restarted MT4.

I am temporarily combating this by running the EA and then removing the EA from the chart so it cant open another one. The issue with doing this is it doesnt allow the "Move stop to Break even" feature to take place after the first "take Proft" is hit which is an important feature of this program and it obviously needs to still be attached to the chart for this.

I am using a boolean called "Traded" which is initiated up the top of the code as false. The trades are only supposed to be run if "Traded" == False. This bool idea definitely works otherwise it would keep opening orders endlessly on every tick, it is the random thing out of nowhere that is doing my head in....... Is it possible that this bool is resting itself to false somehow?

If anyone has any ideas to help make this program better and or fix this bug, i would very much appreciate your help and opinions.

Thanks in advance.

//+------------------------------------------------------------------+
//|                                                     Entry EA.mq4 |
//|                              Marty Asher - asher.marty@gmail.com |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "M.Asher 2011"
#property link      "http://www.metaquotes.net"

extern bool Longs = True;
extern bool Alpha = True;
extern double Entry = 0.0;
extern int StopLoss = 300;
extern double RiskPercentage = 0.02;
extern double TakeProfitLevel_1 = 0.0;
extern double TakeProfitLevel_2 = 0.0;
extern double TakeProfitLevel_3 = 0.0;
extern bool SignalMail = False;
extern bool MoveStopToBE = True;

bool StopMoved = False;
bool ReadyToBE = False;
bool LimitOrder = False;
bool Traded = False;

double Lots = 0;
double StopLossLevel = 0;
double StopLossLevel2;
double StopSize;
double StopToBEPoint;

int Slippage = 3;
int MagicNumber = 0;
int BarCount;
int Pos1Percent;
int Pos3Percent;
int Ticket1 = 0;
int Ticket2 = 0;
int Ticket3 = 0;

string AlertWav="alert.wav";

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{



double tickvalue = (MarketInfo(Symbol(),MODE_TICKVALUE));

if(Digits == 3)
   {
      tickvalue = tickvalue/100;
   }

if (Alpha == true)
   {
   Pos1Percent = 60;
   Pos3Percent = 20;
   }
else  
   {
   Pos1Percent = 70;
   Pos3Percent = 10;
   }
   
     
   
if (Traded == False && Longs == True) 

// ----------------------------------------  INITIATE LONGS --------------------------------------
{


//Check free margin
if (AccountBalance() < 500) 
{
Print("We have no money. Free Margin = ", AccountBalance());
return(0);
}
//Check free margin finshed    


if (Entry <= 0) 

// Entering Market order
{   
StopLossLevel = Ask - StopLoss * Point;
StopSize = Ask - StopLossLevel;    
   if (TakeProfitLevel_1 == 0)
    {
   TakeProfitLevel_1 = (Ask + StopSize*1.5);
    }
   if (TakeProfitLevel_2 == 0)
    {
   TakeProfitLevel_2 = (Ask + (StopSize*2.5));
    }
   TakeProfitLevel_1 = NormalizeDouble(TakeProfitLevel_1,5);
   TakeProfitLevel_2 = NormalizeDouble(TakeProfitLevel_2,5);
   TakeProfitLevel_3 = NormalizeDouble(TakeProfitLevel_3,5);
   Lots = ((AccountBalance() * RiskPercentage)/(StopSize*100000)/tickvalue);
   Ticket1 = OrderSend(Symbol(), OP_BUY, ((Lots/100)*Pos1Percent), Ask, Slippage, 0.0 , 0.0, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket2 = OrderSend(Symbol(), OP_BUY, ((Lots/100)*20), Ask, Slippage, 0.0 , 0.0, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket3 = OrderSend(Symbol(), OP_BUY, ((Lots/100)*Pos3Percent), Ask, Slippage, 0.0 , 0.0, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   ReadyToBE = True;
}

// Entering Market order Finished

else

// Entering Limit order
{ 
   StopLossLevel = Entry - StopLoss * Point;
   StopSize = Entry - StopLossLevel;      
   if (TakeProfitLevel_1 == 0)
    {
   TakeProfitLevel_1 = (Entry + StopSize*1.5);
    }
   if (TakeProfitLevel_2 == 0)
    {
   TakeProfitLevel_2 = (Entry + (StopSize*2.5));
    }
   TakeProfitLevel_1 = NormalizeDouble(TakeProfitLevel_1,5);
   TakeProfitLevel_2 = NormalizeDouble(TakeProfitLevel_2,5);
   TakeProfitLevel_3 = NormalizeDouble(TakeProfitLevel_3,5);
   Lots = ((AccountBalance() * RiskPercentage)/(StopSize*100000)/tickvalue);
   Ticket1 = OrderSend(Symbol(), OP_BUYLIMIT, ((Lots/100)*Pos1Percent), Entry, Slippage, 0.0 , 0.0, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket2 = OrderSend(Symbol(), OP_BUYLIMIT, ((Lots/100)*20), Entry, Slippage, 0.0 , 0.0, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket3 = OrderSend(Symbol(), OP_BUYLIMIT, ((Lots/100)*Pos3Percent), Entry, Slippage, 0.0 , 0.0, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);  
   LimitOrder = True;
}

// Entering Limit order fnished



PlaySound(AlertWav);
      


//Adding stops and take profits
      
OrderModify(Ticket1, OrderOpenPrice(), StopLossLevel, TakeProfitLevel_1, 0, MediumSeaGreen);
OrderModify(Ticket2, OrderOpenPrice(), StopLossLevel, TakeProfitLevel_2, 0, MediumSeaGreen);
OrderModify(Ticket3, OrderOpenPrice(), StopLossLevel, TakeProfitLevel_3, 0, MediumSeaGreen);

//Adding stops and take profits finished



Traded = True; //Used later to control multiple orders opening

}

// ---------------------------------------- LONGS FINISH --------------------------------------


if (Traded == False && Longs == False)

// ----------------------------------------  INITIATE SHORTS --------------------------------------

{


//Check free margin
if (AccountBalance() < 500) 
{
Print("We have no money. Free Margin = ", AccountBalance());
return(0);
}
//Check free margin finshed    
   
   
// Entering market order

if (Entry <= 0)
{ 
   StopLossLevel = Bid + StopLoss * Point;
   StopSize = StopLossLevel - Bid;    
   if (TakeProfitLevel_1 == 0)
   {
   TakeProfitLevel_1 = (Bid - StopSize*1.5);
   }
   if (TakeProfitLevel_2 == 0)
   {
   TakeProfitLevel_2 = (Bid - (StopSize*2.5));
   }
   TakeProfitLevel_1 = NormalizeDouble(TakeProfitLevel_1,5);
   TakeProfitLevel_2 = NormalizeDouble(TakeProfitLevel_2,5);
   TakeProfitLevel_3 = NormalizeDouble(TakeProfitLevel_3,5); 
   Lots = ((AccountBalance() * RiskPercentage)/(StopSize*100000)/tickvalue);
   Ticket1 = OrderSend(Symbol(), OP_SELL, ((Lots/100)*Pos1Percent), Bid, Slippage, 0.0 , 0.0, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket2 = OrderSend(Symbol(), OP_SELL, ((Lots/100)*20), Bid, Slippage, 0.0 , 0.0, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket3 = OrderSend(Symbol(), OP_SELL, ((Lots/100)*Pos3Percent), Bid, Slippage, 0.0 , 0.0, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   ReadyToBE = True; 
}

// Entering market order finished


// Entering Limit order

else
{   
   StopLossLevel = Entry + StopLoss * Point;
   StopSize = StopLossLevel - Entry;  
   if (TakeProfitLevel_1 == 0)
    {
   TakeProfitLevel_1 = (Entry - StopSize*1.5);
    }
   if (TakeProfitLevel_2 == 0)
    {
   TakeProfitLevel_2 = (Entry - (StopSize*2.5));
    }
   TakeProfitLevel_1 = NormalizeDouble(TakeProfitLevel_1,5);
   TakeProfitLevel_2 = NormalizeDouble(TakeProfitLevel_2,5);
   TakeProfitLevel_3 = NormalizeDouble(TakeProfitLevel_3,5); 
   Lots = ((AccountBalance() * RiskPercentage)/(StopSize*100000)/tickvalue);
   Ticket1 = OrderSend(Symbol(), OP_SELLLIMIT, ((Lots/100)*Pos1Percent), Entry, Slippage, 0.0 , 0.0, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket2 = OrderSend(Symbol(), OP_SELLLIMIT, ((Lots/100)*20), Entry, Slippage, 0.0 , 0.0, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   Ticket3 = OrderSend(Symbol(), OP_SELLLIMIT, ((Lots/100)*Pos3Percent), Entry, Slippage, 0.0 , 0.0, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
   LimitOrder = True;
}

// Entering Limit order finished

PlaySound(AlertWav);


            //Print any ticket errors

            if(Ticket1 > 0) 
            {
            if (OrderSelect(Ticket1, SELECT_BY_TICKET, MODE_TRADES)) 
            {
                    Print("BUY order opened : ", OrderOpenPrice());
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
                 } 
                 else 
                     {
                Print("Error opening BUY order : ", GetLastError());
                      }
            }
              if(Ticket2 > 0) 
            {
            if (OrderSelect(Ticket2, SELECT_BY_TICKET, MODE_TRADES)) 
            {
                    Print("BUY order opened : ", OrderOpenPrice());
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
                 } 
                 else 
                     {
                Print("Error opening BUY order : ", GetLastError());
                      }
            }
              if(Ticket3 > 0) 
            {
            if (OrderSelect(Ticket3, SELECT_BY_TICKET, MODE_TRADES)) 
            {
                    Print("BUY order opened : ", OrderOpenPrice());
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
                 } 
                 else 
                     {
                Print("Error opening BUY order : ", GetLastError());
                      }
            }
            
            //Print any ticket errors finished
      
//Adding stops and take profits
      
OrderModify(Ticket1, OrderOpenPrice(), StopLossLevel, TakeProfitLevel_1, 0, MediumSeaGreen);
OrderModify(Ticket2, OrderOpenPrice(), StopLossLevel, TakeProfitLevel_2, 0, MediumSeaGreen);
OrderModify(Ticket3, OrderOpenPrice(), StopLossLevel, TakeProfitLevel_3, 0, MediumSeaGreen);

//Adding stops and take profits finished

Traded = True; //Used later to control multiple orders opening
}

// ---------------------------------------- SHORTS FINISH --------------------------------------

//checking to see if limits are open yet and allowing following break even process below to take place if they are

if (LimitOrder == True && Longs == True && Ask <= Entry) ReadyToBE = True;
if (LimitOrder == True && Longs == False && Bid >= Entry) ReadyToBE = True;

//checking to see if limits are open yet and allowing following break even process below to take place if they are finished

   
if (Longs == true && ReadyToBE == True) //for longs that are ready to have stop moved to break even
{ 
   if (MoveStopToBE == True && StopMoved == False && Ask >= TakeProfitLevel_1)
   {
   OrderModify(Ticket2, OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, MediumSeaGreen);
   OrderModify(Ticket3, OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, MediumSeaGreen);
   StopMoved = True;
   }
}

if (Longs == false && ReadyToBE == True) //for shorts that are ready to have stop moved to break even
{ 
   if (MoveStopToBE == True && StopMoved == False && Bid <= TakeProfitLevel_1)
   {
   OrderModify(Ticket2, OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, MediumSeaGreen);
   OrderModify(Ticket3, OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, MediumSeaGreen);
   StopMoved = True;
   }
}
 
 
return(0);


}
//+------------------------------------------------------------------+
Files:
 

You need to check placing, modifying, deleting, closing, etc of Orders and report any errors immediately . . you need to read up on how GetLastError works: https://docs.mql4.com/check/GetLastError once called it is reset back to 0 . . .

You need to add some Print statements to your EA so you can see what is going on . . .

 
RaptorUK:

You need to check placing, modifying, deleting, closing, etc of Orders and report any errors immediately . . you need to read up on how GetLastError works: https://docs.mql4.com/check/GetLastError once called it is reset back to 0 . . .

You need to add some Print statements to your EA so you can see what is going on . . .


Hi Raptor,

Thanks for the assistance. i will learn up about error reporting and see where it takes me.

Reason: