OrderClose error 4051

 

Hi, I have been trying out two EAs in S/Tester;  one is a BUY oriented EA, the other is exactly the same but SELL oriented.  The Buy oriented works fine fine but the Sell gives 'OrderClose error 4051'

I've narrowed this down to the specific area of code but, apart from long/short trade difference, can't why one works and not the other.

This is the first time I've asked this forum for help, but just about given up on this one.

All comments welcome.  Many thanks.

<Code deleted>

 

Forum on trading, automated trading systems and testing trading strategies

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

Use the CODE button



 
Why am I getting an Error 4051?
Why am I getting an Error 4051?
  • 2017.02.20
  • www.mql5.com
I'm somewhat frustrated but I'm getting the a. m. error but I can't find the souce. Proboblyblind to from staring so long...
 
Topics concerning MT4 and MQL4 have their own section.
In future please post in the correct section.
I have moved your topic to the MQL4 and Metatrader 4 section.
 
I'm happy to send through full EAs to anyone nice enough to help.  I've tried over and over to find the problem, just can't see it.  Sorry, I feel like such a pain asking.
 
hughog49:

Did you read Sergey's post?

Sergey Golubev:

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

Use the CODE button

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.

 
Keith Watford:

Did you read Sergey's post?

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.

Re-post it.  Yes okay.

 

This is a re-post.

Hi, I have been trying out two EAs in S/Tester;  one is a BUY oriented EA, the other is exactly the same but SELL oriented.  The Buy oriented works fine fine but the Sell gives 'OrderClose error 4051'

I've narrowed this down to the specific area of code but, apart from long/short trade difference, can't why one works and not the other.

The two sets of code are:-

Buy Oriented EA that works:

//+------------------------------------------------------------------+
//|                                             AskArrayComments.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright     "Paul E Lloyd"
#property link  "http://www.karamuvalleylodge.co.nz"
#property description "Simple Trend Betting robot using 33 Tick sequencing M33TNonSavBuy+r"
#property strict


//Input variables
input int       MagicNumber = 3333;
input int       Slippage = 10;
input double    Percent = 0.01;
input double    LotSize = 0.01;
//input double  gTradeSpread    = 2.0;
input double   TrailingStop = 1.0;
input double   MinimumProfit = 10;
input double   Retracement = 100;
input double   Buffer = 5;

//Global variables
int gBuyTicket, gSellTicket;
bool    ManageLotSize = true;
double gSpread;


//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
 
//-----------------------------------------------------
// Current order counts
   int buyCount = 0, sellCount = 0;
   for (int order = 0; order <= OrdersTotal()-1; order++)
   {
      bool select = OrderSelect(order, SELECT_BY_POS);
      if(OrderMagicNumber() == MagicNumber && select == true)
           {
           if(OrderType() == OP_BUY) buyCount++;
           else if (OrderType() == OP_SELL) sellCount++;
           }
   }
//-----------------------------------------------------
//Apply Trailing Stop Loss
   for(int order=0; order<=OrdersTotal()-1; order++)
   {
      bool select = OrderSelect(order, SELECT_BY_POS);
      if(TrailingStop>0 && OrderMagicNumber() == MagicNumber && select == true)
      {

//Check trailing stops
          if(OrderType()==OP_BUY)
          {
              RefreshRates();
              double trailStopPrice = Bid-(TrailingStop*_Point);
              trailStopPrice = NormalizeDouble(trailStopPrice,5);

              double currentStopLoss = NormalizeDouble(OrderStopLoss(),5);
              double currentProfit = Bid - OrderOpenPrice();
              double minProfit = MinimumProfit *_Point;

              if(trailStopPrice > currentStopLoss && currentProfit>=minProfit )
              {
                  bool modify = OrderModify(OrderTicket(),OrderOpenPrice(),trailStopPrice,0,0);
              }
            }
         }
     }
//-----------------------------------------------------
 
//INDICATORS:-
// - Tick Array
//Declare Tick Array

static double Tick[33];


//Start recording Ask Prices
Tick[0] = Ask;


//Increment Ask records
Tick[32] = Tick[31];
Tick[31] = Tick[30];
Tick[30] = Tick[29];
Tick[29] = Tick[28];
Tick[28] = Tick[27];
Tick[27] = Tick[26];
Tick[26] = Tick[25];
Tick[25] = Tick[24];
Tick[24] = Tick[23];
Tick[23] = Tick[22];
Tick[22] = Tick[21];
Tick[21] = Tick[20];
Tick[20] = Tick[19];
Tick[19] = Tick[18];
Tick[18] = Tick[17];
Tick[17] = Tick[16];
Tick[16] = Tick[15];
Tick[15] = Tick[14];
Tick[14] = Tick[13];
Tick[13] = Tick[12];
Tick[12] = Tick[11];
Tick[11] = Tick[10];
Tick[10] = Tick[9];
Tick[9] = Tick[8];
Tick[8] = Tick[7];
Tick[7] = Tick[6];
Tick[6] = Tick[5];
Tick[5] = Tick[4];
Tick[4] = Tick[3];
Tick[3] = Tick[2];
Tick[2] = Tick[1];
Tick[1] = Tick[0];




//See whats happening

Comment
(
"RUNNING",
"\n Tick[9] = ", Tick[9],
"\n Tick[8] = ", Tick[8],
"\n Tick[7] = ", Tick[7],
"\n Tick[6] = ", Tick[6],
"\n Tick[5] = ", Tick[5],
"\n Tick[4] = ", Tick[4],
"\n Tick[3] = ", Tick[3],
"\n Tick[2] = ", Tick[2],
"\n Tick[1] = ", Tick[1],
"\n Tick[0] = ", Tick[0],
"\n "
"\n Spread Size =", gSpread
);

 
//==================================================================

// BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY 


//Buy Order Condition

   if(buyCount == 0 )
   {
     if(Tick[12]>0 && Tick[1]>Tick[2] && Tick[2]>=Tick[3] && Tick[3]>=Tick[4] && Tick[4]>=Tick[5] && Tick[5]>=Tick[6] && Tick[6]>=Tick[7] && Tick[7]>=Tick[8] && Tick[8]>=Tick[9] && Tick[9]>=Tick[10] && Tick[10]>=Tick[11] && Tick[11]>=Tick[12] && Tick[12]>=Tick[13]&& Tick[13]>=Tick[14] && Tick[14]>=Tick[15] && Tick[15]>=Tick[16] && Tick[16]>=Tick[17] && Tick[17]>=Tick[18]  && Tick[18]>=Tick[19]  && Tick[19]>=Tick[20]  && Tick[20]>=Tick[21] && Tick[21]>=Tick[22]  && Tick[22]>=Tick[23] && Tick[23]>=Tick[24] && Tick[24]>=Tick[25] && Tick[25]>=Tick[26] && Tick[26]>=Tick[27] && Tick[27]>=Tick[28] && Tick[28]>=Tick[29] && Tick[29]>=Tick[30] && Tick[30]>=Tick[31] && Tick[31]>=Tick[32])
      {
//-----------------------------------------------------
//Buy order stuff
//Buy Lot Size
         double BuyLotSize=0;

//if(ManageLotSize=false)

 BuyLotSize=LotSize;
/*
   else if(ManageLotSize=true)
     {
      BuyLotSize=AccountInfoDouble(ACCOUNT_EQUITY)*Percent*AccountLeverage()/100000;

      if(BuyLotSize<MarketInfo(_Symbol,MODE_MINLOT)) BuyLotSize=MarketInfo(_Symbol,MODE_MINLOT);

      else if(BuyLotSize>MarketInfo(_Symbol,MODE_MAXLOT)) BuyLotSize=MarketInfo (_Symbol, MODE_MAXLOT);

      if(MarketInfo(_Symbol,MODE_LOTSTEP)==0.1) BuyLotSize=NormalizeDouble(BuyLotSize,1); 
      else BuyLotSize=NormalizeDouble(BuyLotSize,2);
     }
*/
//-----------------------------------------------------

//Open buy order
            gBuyTicket = OrderSend(_Symbol, OP_BUY, BuyLotSize, Ask, Slippage, 0, 0, "Buy Order", MagicNumber,0,clrGreen);
            gSellTicket = 0;


//BUY STOPLOSS & TAKE PROPFIT BUY STOPLOSS & TAKE PROPFIT BUY STOPLOSS & TAKE PROPFIT BUY STOPLOSS & TAKE PROPFIT 
            int StopLoss = 20000;
            int TakeProfit = 0;

//Add BUY Stop Loss & Take Profit
                 if(gBuyTicket > 0 && (StopLoss > 0 || TakeProfit >0))
                 {
                    bool select = OrderSelect(gBuyTicket, SELECT_BY_TICKET);

//Calculate BUY Stop Loss & BUY Take Profit

               double buyStopLoss = 0;
               double buyTakeProfit = 0;

                    if(StopLoss > 0) buyStopLoss = OrderOpenPrice() - (StopLoss * _Point);
                    if(TakeProfit > 0) buyTakeProfit = OrderOpenPrice() + (TakeProfit * _Point);
                    {
                    

//Verify BUY stop loss & take profit
                       double stopLevel = MarketInfo(_Symbol, MODE_STOPLEVEL) * _Point;

                       RefreshRates();
                       double upperStopLevel = Ask + stopLevel;
                       double lowerStopLevel = Bid - stopLevel;
        
                            if(buyStopLoss >= lowerStopLevel && buyStopLoss != 0) buyStopLoss = lowerStopLevel -_Point;
                            if(buyTakeProfit<=  upperStopLevel && buyTakeProfit != 0) buyTakeProfit = upperStopLevel +_Point;
                            {

//Modify order
                               bool modify = OrderModify(gBuyTicket, 0, buyStopLoss, buyTakeProfit, 0);
                      
                            }
                     }

               }
            }
          }  

//=======================================================================

//SELL SELL SELL SELL SELL SELL SELL SELL 
//Sell Order Condition
         if (buyCount ==1 && sellCount ==0)
         {
            for (int order = 0; order <= OrdersTotal()-1; order++)
            {
               bool buyselect = OrderSelect(order, SELECT_BY_POS);
               if(OrderMagicNumber() == MagicNumber && buyselect == true && OrderType() == OP_BUY)
               {
                  double RetracementPrice= (OrderOpenPrice()-(Retracement*_Point));
                  RetracementPrice = NormalizeDouble(RetracementPrice,5);

                  RefreshRates();
                  if(Ask<=RetracementPrice)

                  {
//-----------------------------------------------------

//Sell order stuff

//Sell Lot Size
                     double SellLotSize=0;

//if(ManageLotSize=false) 

SellLotSize=LotSize;
/*
   else if(ManageLotSize=true)
     {
      SellLotSize=AccountInfoDouble(ACCOUNT_EQUITY)*Percent*AccountLeverage()/100000;

      if(SellLotSize<MarketInfo(_Symbol,MODE_MINLOT)) SellLotSize=MarketInfo(_Symbol, MODE_MINLOT);

      else if(SellLotSize>MarketInfo(_Symbol,MODE_MAXLOT)) SellLotSize=MarketInfo(_Symbol, MODE_MAXLOT);

      if(MarketInfo(_Symbol,MODE_LOTSTEP)==0.1) SellLotSize=NormalizeDouble(SellLotSize,1); 
      else SellLotSize=NormalizeDouble(SellLotSize,2);
     }

*/
//-----------------------------------------------------

//Open Sellorder
                      gSellTicket = OrderSend(_Symbol, OP_SELL, SellLotSize, Bid, Slippage, 0, 0, "Sell order", MagicNumber, 0, clrRed);
                  }
        
                      }
                     }
               }

//Close Sell orders
             if(sellCount>0 && buyCount==0)
             {
// Find Sell Order
                  bool select=OrderSelect(gSellTicket,SELECT_BY_TICKET);
                  if(Ask<=(OrderOpenPrice()-Buffer*_Point))
                       {
      
// Close Sell Order
                     bool close=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,clrOrange);
                     if(close==true) gSellTicket=0;
                    }
              }

 }


Sell Oriented EA Code giving Errors: "OrderClose error 4051" and  "invalid ticket for OrderClose function":

//+------------------------------------------------------------------+
//|                                             AskArrayComments.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright     "Paul E Lloyd"
#property link  "http://www.karamuvalleylodge.co.nz"
#property description "Simple Trend Betting robot using Tick sequencing M33TNonSavSell+r"
#property strict


//Input variables
input int       MagicNumber = 4444;
input int       Slippage = 10;
input double    Percent = 0.01;
input double    LotSize = 0.01;
//input double  gTradeSpread    = 2.0;
input double   TrailingStop = 1.0;
input double   MinimumProfit = 10;
input double   Retracement = 100;
input double   Buffer = 5;

//Global variables
int gBuyTicket, gSellTicket;
bool    ManageLotSize = false;
double gSpread;


//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
 
//-----------------------------------------------------
// Current order counts
int buyCount = 0, sellCount = 0;
for (int order = 0; order <= OrdersTotal()-1; order++)
{
bool select = OrderSelect(order, SELECT_BY_POS);
if(OrderMagicNumber() == MagicNumber && select == true)
        {
        if(OrderType() == OP_BUY) buyCount++;
        else if (OrderType() == OP_SELL) sellCount++;
        }
}
//-----------------------------------------------------
//Apply Trailing Stop Loss
      for(int order=0; order<=OrdersTotal()-1; order++)
        {
         bool select = OrderSelect(order, SELECT_BY_POS);

         if(TrailingStop>0 && OrderMagicNumber() == MagicNumber && select == true)
           {

//Check trailing stops
               if (OrderType()==OP_SELL)
               {
                         RefreshRates();

               double trailStopPrice = Ask+(TrailingStop*_Point);
               trailStopPrice = NormalizeDouble(trailStopPrice,5);

               double currentStopLoss = NormalizeDouble(OrderStopLoss(),5);
               double currentProfit = OrderOpenPrice()-Ask;
               double minProfit = MinimumProfit *_Point;

               if(trailStopPrice < currentStopLoss && currentProfit>=minProfit)
                 {
                  bool modify = OrderModify(OrderTicket(),OrderOpenPrice(),trailStopPrice,0,0);
                  }
               }
           }
         }
         
//INDICATORS:-
// - Tick Array
//Declare Tick Array

static double Tick[33];


//Start recording Ask Prices
Tick[0] = Ask;


//Increment Ask records
Tick[32] = Tick[31];
Tick[31] = Tick[30];
Tick[30] = Tick[29];
Tick[29] = Tick[28];
Tick[28] = Tick[27];
Tick[27] = Tick[26];
Tick[26] = Tick[25];
Tick[25] = Tick[24];
Tick[24] = Tick[23];
Tick[23] = Tick[22];
Tick[22] = Tick[21];
Tick[21] = Tick[20];
Tick[20] = Tick[19];
Tick[19] = Tick[18];
Tick[18] = Tick[17];
Tick[17] = Tick[16];
Tick[16] = Tick[15];
Tick[15] = Tick[14];
Tick[14] = Tick[13];
Tick[13] = Tick[12];
Tick[12] = Tick[11];
Tick[11] = Tick[10];
Tick[10] = Tick[9];
Tick[9] = Tick[8];
Tick[8] = Tick[7];
Tick[7] = Tick[6];
Tick[6] = Tick[5];
Tick[5] = Tick[4];
Tick[4] = Tick[3];
Tick[3] = Tick[2];
Tick[2] = Tick[1];
Tick[1] = Tick[0];




//See whats happening

Comment
(
"RUNNING",
"\n Tick[9] = ", Tick[9],
"\n Tick[8] = ", Tick[8],
"\n Tick[7] = ", Tick[7],
"\n Tick[6] = ", Tick[6],
"\n Tick[5] = ", Tick[5],
"\n Tick[4] = ", Tick[4],
"\n Tick[3] = ", Tick[3],
"\n Tick[2] = ", Tick[2],
"\n Tick[1] = ", Tick[1],
"\n Tick[0] = ", Tick[0],
"\n "
"\n Spread Size =", gSpread
);



 
//=======================================================================


//SELL SELL SELL SELL SELL SELL SELL SELL 
//Sell Order Condition

if(sellCount == 0)
{

if (Tick[12]>0 && Tick[1]<Tick[2] && Tick[2]<=Tick[3] && Tick[3]<=Tick[4] && Tick[4]<=Tick[5] && Tick[5]<=Tick[6] && Tick[6]<=Tick[7] &&Tick[7]<=Tick[8] && Tick[8]<=Tick[9] && Tick[9]<=Tick[10] && Tick[10]<=Tick[11] && Tick[11]<=Tick[12] && Tick[12]<=Tick[13]&& Tick[13]<=Tick[14] && Tick[14]<=Tick[15] && Tick[15]<=Tick[16]  && Tick[16]<=Tick[17] && Tick[17]<=Tick[18] && Tick[18]<=Tick[19] && Tick[19]<=Tick[20] && Tick[20]<=Tick[21] && Tick[21]<=Tick[22] && Tick[22]<=Tick[23] && Tick[23]<=Tick[24] && Tick[24]<=Tick[25] && Tick[25]<=Tick[26] && Tick[26]<=Tick[27] && Tick[27]<=Tick[28] && Tick[28]<=Tick[29] && Tick[29]<=Tick[30] && Tick[30]<=Tick[31] && Tick[31]<=Tick[32])
{


//Sell order stuff

//-----------------------------------------------------
//Sell Lot Size
   double SellLotSize=0;

//if(ManageLotSize=false) 
      SellLotSize=LotSize;
/*
   else if(ManageLotSize=true)
     {
      SellLotSize=AccountInfoDouble(ACCOUNT_EQUITY)*Percent*AccountLeverage()/100000;

      if(SellLotSize<MarketInfo(_Symbol,MODE_MINLOT)) SellLotSize=MarketInfo(_Symbol, MODE_MINLOT);

      else if(SellLotSize>MarketInfo(_Symbol,MODE_MAXLOT)) SellLotSize=MarketInfo(_Symbol, MODE_MAXLOT);

      if(MarketInfo(_Symbol,MODE_LOTSTEP)==0.1) SellLotSize=NormalizeDouble(SellLotSize,1); 
      else SellLotSize=NormalizeDouble(SellLotSize,2);
     }
*/
//-----------------------------------------------------

//Open Sellorder
gSellTicket = OrderSend(_Symbol, OP_SELL, SellLotSize, Bid, Slippage, 0, 0, "Sell order", MagicNumber, 0, clrRed);
gBuyTicket = 0;



//SELL STOPLOSS & TAKE PROFIT SELL STOPLOSS & TAKE PROFIT SELL STOPLOSS & TAKE PROFIT SELL STOPLOSS & TAKE PROFIT 
   int  StopLoss = 20000;
   int  TakeProfit = 0;

//Add SELL Stop Loss & Take Profit
        if(gSellTicket > 0 && (StopLoss > 0 || TakeProfit >0))
           {
           bool select = OrderSelect(gSellTicket, SELECT_BY_TICKET);

//Calculate SELL Stop Loss & SELL Take Profit
           double sellStopLoss = 0;
           double sellTakeProfit = 0;
           if(StopLoss > 0) sellStopLoss = OrderOpenPrice() + (StopLoss * _Point);
           if(TakeProfit > 0) sellTakeProfit = OrderOpenPrice() - (TakeProfit * _Point);
           
          
              {

//Verify SELL stop loss & take profit
              double stopLevel = MarketInfo(_Symbol, MODE_STOPLEVEL) * _Point;

              RefreshRates();
              double upperStopLevel = Ask + stopLevel;
              double lowerStopLevel = Bid - stopLevel;

              if(sellTakeProfit >=  lowerStopLevel && sellTakeProfit != 0) sellTakeProfit = lowerStopLevel -_Point;
              if(sellStopLoss <= upperStopLevel && sellStopLoss != 0) sellStopLoss = upperStopLevel +_Point;
                      {

//Modify order
                      bool modify = OrderModify(gSellTicket, 0, sellStopLoss, sellTakeProfit, 0);            

                    }
              }
            }
          }  
         } 
//=======================================================================

//BUY  BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY BUY 
//Buy Order Condition
         if (sellCount ==1 && buyCount ==0)
         {
            for (int order = 0; order <= OrdersTotal()-1; order++)
            {
               bool sellselect = OrderSelect(order, SELECT_BY_POS);
               if(OrderMagicNumber() == MagicNumber && sellselect == true && OrderType() == OP_SELL)
               {
                  double RetracementPrice= (OrderOpenPrice()+(Retracement*_Point));
                  RetracementPrice = NormalizeDouble(RetracementPrice,5);

                  RefreshRates();
                  if(Bid>=RetracementPrice)

                  {
//-----------------------------------------------------

//Buy order stuff

//Buy Lot Size
                 double BuyLotSize=0;
                 
//if(ManageLotSize=false) 

      BuyLotSize=LotSize;
      
/*
   else if(ManageLotSize=true)
     {
      BuyLotSize=AccountInfoDouble(ACCOUNT_EQUITY)*Percent*AccountLeverage()/100000;

      if(BuyLotSize<MarketInfo(_Symbol,MODE_MINLOT)) BuyLotSize=MarketInfo(_Symbol, MODE_MINLOT);

      else if(BuyLotSize>MarketInfo(_Symbol,MODE_MAXLOT)) BuyLotSize=MarketInfo(_Symbol, MODE_MAXLOT);

      if(MarketInfo(_Symbol,MODE_LOTSTEP)==0.1) BuyLotSize=NormalizeDouble(BuyLotSize,1); 
      else BuyLotSize=NormalizeDouble(BuyLotSize,2);
     }

*/
//-----------------------------------------------------

//Open Buyorder
                      gBuyTicket = OrderSend(_Symbol, OP_BUY, BuyLotSize, Ask, Slippage, 0, 0, "Buy order", MagicNumber, 0, clrGreen);
                     
                        }
                  }
                 }
               }


//Close Buy orders
             if(buyCount>0 && sellCount==0)
             {
// Find Buy Order
                  bool select=OrderSelect(gBuyTicket,SELECT_BY_TICKET);
                  if(Bid>=(OrderOpenPrice()+Buffer*_Point))
                       {
      
// Close Buy Order
                     bool close=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,clrOrange);
                     if(close==true) gBuyTicket=0;
                    }
              }
}

 So far as I can see it's the 'Retracement' part of the code which is giving the problem.  All contributions gratefully received.  Many thanks

 
So.  I've put the full code in so you can run it for yourself.  Hope someone can please help.  Many thanks.
 
hughog49:

Re-post it.  Yes okay.

Hello Keith,

I've re-posted as requested and used the 'code button'.  Do you suppose anyone might take a look at this for me, or should I approach one of the site's registered contractors?

 
hughog49:

Hello Keith,

I've re-posted as requested and used the 'code button'.  

I didn't ask you to re-post.

Keith Watford:

Did you read Sergey's post?

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.

Something about  EDIT your original post that you didn't understand?

Reason: