error 141 - ERR_TOO_MANY_REQUESTS - page 2

 

Ah yea my mistake.

What can I do to change around that sign mismatch if statement. Annoys me when I have warnings when compiling :) 

 

The compiler is grumbling about the fact that StartWaitingTime is declared as an unsigned integer (it has to be a positive number) while MaxWaiting_sec is declared as a normal integer.

In order to get rid of the warning, you can declare both as 'int' or both as 'uint'.

GetTickCount() will fill up quickly. As it is always going to be a positive number, you can effectively double it's capacity by declaring it as uint.

MaxWaiting_sec will also be a positive number, so the solution is to change

int _IsTradeAllowed(int MaxWaiting_sec = 30)

 to 

int _IsTradeAllowed(uint MaxWaiting_sec = 30)
 
Thank you kindly sir and thanks for explaining that too. Makes complete sense :)
 
My pleasure.
 

Last question :)

As I have never used *.mqh before, I was wondering if you can tell me if I am using it correctly?

So I am creating a new "Include (*.mqh)"  named "TradeContext" template and then simply copying over what the kind chap has done in that article for everyone Error 146 ("Trade context busy") and How to Deal with It and then compiling.

This then sits within C:\MT4\MQL4\Include and in order to use the newly created "Include (*.mqh)" file I must add "#include <TradeContext.mqh>" within the global scope of my actual EA so that I can call upon "TradeContext" and any relevant functions?

 

I assume it makes more sense using a .mqh Include over a .mq4, right? This is the include file from that article above (i swapped it over to English notes).

INCLUDE FILE: "TradeContext"



//+------------------------------------------------------------------+
//|                                                 TradeContext.mq4 |
//|                                                        komposter |
//|                                             komposterius@mail.ru |
//+------------------------------------------------------------------+
#property copyright "komposter"
#property link      "komposterius@mail.ru"

/////////////////////////////////////////////////////////////////////////////////
// int _IsTradeAllowed( int MaxWaiting_sec = 30 )
//
// the function checks the trade context status. Return codes:
//  2 - end of while loop.
//  1 - trade context is free, trade allowed
//  0 - trade context was busy, but became free. Trade is allowed only after 
//      the market info has been refreshed.
// -1 - trade context is busy, waiting interrupted by the user (expert was removed from 
//      the chart, terminal was shut down, the chart period and/or symbol was changed, etc.)
// -2 - trade context is busy, the waiting limit is reached (MaxWaiting_sec). 
//      Possibly, the expert is not allowed to trade (checkbox "Allow live trading" 
//      in the expert settings).
//
// MaxWaiting_sec - time (in seconds) within which the function will wait 
// until the trade context is free (if it is busy). By default,30.
/////////////////////////////////////////////////////////////////////////////////
int _IsTradeAllowed(uint MaxWaiting_sec = 30)
  {
    // check whether the trade context is free
    if(!IsTradeAllowed())
      {
        uint StartWaitingTime = GetTickCount();
        Print("Trade context is busy! Wait until it is free...");
        // infinite loop
        while(true)
          {
            // if the expert was terminated by the user, stop operation
            if(IsStopped()) 
              { 
                Print("The expert was terminated by the user!"); 
                return(-1); 
              }
            // if the waiting time exceeds the time specified in the 
            // MaxWaiting_sec variable, stop operation, as well
            if(GetTickCount() - StartWaitingTime > MaxWaiting_sec * 1000)
              {
                Print("The waiting limit exceeded (" ,MaxWaiting_sec, " сек.)!");
                return(-2);
              }
            // if the trade context has become free,
            if(IsTradeAllowed())
              {
                Print("Trade context has become free!");
                return(0);
              }
            // if no loop breaking condition has been met, "wait" for 0.1 
            // second and then restart checking            Sleep(100);
          }
      }
    else
      {
        Print("Trade context is free!");
        return(1);
      }
return(2);
}

/////////////////////////////////////////////////////////////////////////////////
// int TradeIsBusy( int MaxWaiting_sec = 30 )
//
// The function replaces the TradeIsBusy value 0 with 1.
// If TradeIsBusy = 1 at the moment of launch, the function waits until TradeIsBusy is 0, 
// and then replaces.
// If there is no global variable TradeIsBusy, the function creates it.
// Return codes:
//  2 - End of while loop.
//  1 - successfully completed. The global variable TradeIsBusy was assigned with value 1
// -1 - TradeIsBusy = 1 at the moment of launch of the function, the waiting was interrupted by the user
//      (the expert was removed from the chart, the terminal was closed, the chart period and/or symbol 
//      was changed, etc.)
// -2 - TradeIsBusy = 1 at the moment of launch of the function, the waiting limit was exceeded
//      (MaxWaiting_sec)
/////////////////////////////////////////////////////////////////////////////////
int TradeIsBusy( uint MaxWaiting_sec = 30 )
  {
    // at testing, there is no resaon to divide the trade context - just terminate 
    // the function
    if(IsTesting()) 
        return(1);
    int _GetLastError = 0;
    uint StartWaitingTime = GetTickCount();
    //+------------------------------------------------------------------+
    //| Check whether a global variable exists and, if not, create it    |
    //+------------------------------------------------------------------+
    while(true)
      {
        // if the expert was terminated by the user, stop operation
        if(IsStopped()) 
          { 
            Print("The expert was terminated by the user!"); 
            return(-1); 
          }
        // if the waiting time exceeds that specified in the variable 
        // MaxWaiting_sec, stop operation, as well
        if(GetTickCount() - StartWaitingTime > MaxWaiting_sec * 1000)
          {
            Print("Waiting time (" , MaxWaiting_sec , " sec) exceeded!");
            return(-2);
          }
        // check whether the global variable exists
        // if it does, leave the loop and go to the block of changing 
        // TradeIsBusy value
        if(GlobalVariableCheck( "TradeIsBusy" )) 
            break;
        else
        // if the GlobalVariableCheck returns FALSE, it means that it does not exist or  
        // an error has occurred during checking
          {
            _GetLastError = GetLastError();
            // if it is still an error, display information, wait for 0.1 second, and 
            // restart checking
            if(_GetLastError != 0)
             {
              Print("TradeIsBusy()-GlobalVariableCheck(\"TradeIsBusy\")-Error #",
                    _GetLastError );
              Sleep(100);
              continue;
             }
          }
        // if there is no error, it means that there is just no global variable, try to create
        // it
        // if the GlobalVariableSet > 0, it means that the global variable has been successfully created. 
        // Leave the function
        if(GlobalVariableSet( "TradeIsBusy", 1.0 ) > 0 ) 
            return(1);
        else
        // if the GlobalVariableSet has returned a value <= 0, it means that an error 
        // occurred at creation of the variable
         {
          _GetLastError = GetLastError();
          // display information, wait for 0.1 second, and try again
          if(_GetLastError != 0)
            {
              Print("TradeIsBusy()-GlobalVariableSet(\"TradeIsBusy\",0.0 )-Error #",
                    _GetLastError );
              Sleep(100);
              continue;
            }
         }
      }
    //+----------------------------------------------------------------------------------+
    //| If the function execution has reached this point, it means that global variable  | 
    //| variable exists.                                                                 |
    //| Wait until the TradeIsBusy becomes = 0 and change the value of TradeIsBusy for 1 |
    //+----------------------------------------------------------------------------------+
    while(true)
     {
     // if the expert was terminated by the user, stop operation
     if(IsStopped()) 
       { 
         Print("The expert was terminated by the user!"); 
         return(-1); 
       }
     // if the waiting time exceeds that specified in the variable 
     // MaxWaiting_sec, stop operation, as well
     if((GetTickCount() - StartWaitingTime) > (MaxWaiting_sec * 1000))
       {
         Print("The waiting time (", MaxWaiting_sec , " sec) exceeded!");
         return(-2);
       }
     // try to change the value of the TradeIsBusy from 0 to 1
     // if succeed, leave the function returning 1 ("successfully completed")
     if(GlobalVariableSetOnCondition( "TradeIsBusy", 1.0, 0.0 )) 
         return(1);
     else
     // if not, 2 reasons for it are possible: TradeIsBusy = 1 (then one has to wait), or 

     // an error occurred (this is what we will check)
      {
      _GetLastError = GetLastError();
      // if it is still an error, display information and try again
      if(_GetLastError != 0)
      {
   Print("TradeIsBusy()-GlobalVariableSetOnCondition(\"TradeIsBusy\",1.0,0.0 )-Error #",
         _GetLastError );
       continue;
      }
     }
     //if there is no error, it means that TradeIsBusy = 1 (another expert is trading), then display 
     // information and wait...
     Comment("Wait until another expert finishes trading...");
     Sleep(1000);
     Comment("");
    }
    
return(2);
}

/////////////////////////////////////////////////////////////////////////////////
// void TradeIsNotBusy()
//
// The function sets the value of the global variable TradeIsBusy = 0.
// If the TradeIsBusy does not exist, the function creates it.
/////////////////////////////////////////////////////////////////////////////////
void TradeIsNotBusy()
  {
    int _GetLastError;
    // at testing, there is no sense to divide the trade context - just terminate 
    // the function
    if(IsTesting()) 
      { 
        return; 
      }
    while(true)
      {
        // if the expert was terminated by the user, прекращаем работу
        if(IsStopped()) 
          { 
            Print("The expert was terminated by the user!"); 
            return; 
          }
        // try to set the global variable value = 0 (or create the global 
        // variable)
        // if the GlobalVariableSet returns a value > 0, it means that everything 
        // has succeeded. Leave the function
        if(GlobalVariableSet( "TradeIsBusy", 0.0 ) > 0) 
            return;
        else
        // if the GlobalVariableSet returns a value <= 0, this means that an error has occurred. 
        // Display information, wait, and try again
         {
         _GetLastError = GetLastError();
         if(_GetLastError != 0 )
           Print("TradeIsNotBusy()-GlobalVariableSet(\"TradeIsBusy\",0.0)-Error #", 
                 _GetLastError );
         }
        Sleep(100);
      }
  }

 

 How I am using this above "Include" file is like this within my EA:

EA FILE

// Global Scope --------

#include <TradeContext.mqh>

//----------------------


...



//+------------------------------------------------------------------+
//| Order Entry function - Buy or Sell (pending orders)              |
//+------------------------------------------------------------------+

void OrderEntry(int direction)
{
   
...


...


//+-------------------------------------------------------------------------------------+
//| Order Buy Function                                                                  |
//+-------------------------------------------------------------------------------------+   

if(direction==0)
{//--Buy--// 
      
 // wait until the trade context is free and then occupy it (if an error occurs, leave it)
 //------------------------------
 
 if( TradeIsBusy() < 0 ) return;
 
 RefreshRates();
 
 //------------------------------      
 
...


...     

if( OpenOrdersThisPair(Symbol()) == 0 && LotSize_Buy >= minlot )
{ 
   BuyTicketOrder1 = OrderSend(Symbol(),OP_BUYSTOP,LotSize_Buy,Stored_BuyPrice,3,
                              BuyStopPrice,btp1,NULL,MagicNumber1,0,Green);Sleep(100);
            
      if(BuyTicketOrder1 == -1)Print("First Buy Order Last Error = ",GetLastError(), " On: ", Symbol());//return;
      if(BuyTicketOrder1 > 0)Print("First Buy Order Placed: ", Symbol(), " LotSize_Buy is: ", LotSize_Buy );
                                             
   BuyTicketOrder2 = OrderSend(Symbol(),OP_BUYSTOP,LotSize_Buy2,Stored_BuyPrice,3,
                              BuyStopPrice,btp2,NULL,MagicNumber1,0,Green);Sleep(100);
                                                                                       
      if(BuyTicketOrder2 == -1)Print("Second Buy Order Last Error = ",GetLastError(), " On: ", Symbol());//return;
      if(BuyTicketOrder2 > 0)Print("Second Buy Order Placed: ", Symbol(), " LotSize_Buy is: ", LotSize_Buy2 );


...

  TradeIsNotBusy(); // Set the trade context to "free".                                   
         
  return;                                    
}

...
 
DomGilberto:
     if( OpenOrdersThisPair(Symbol()) == 0 && LotSize_Buy >= minlot )
         { 
         BuyTicketOrder1 = OrderSend(
If this is resulting in error 141 I suggest your function OpenOrdersThisPair is broken.
 
//+------------------------------------------------------------------+
//| Check if there are current open orders on this pair              |
//+------------------------------------------------------------------+
int OpenOrdersThisPair(string pair)
  {
   int total=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      bool SelectOpenOrder = OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==pair) total++;
     }
   return(total);
  }
?
 

Here

if( OpenOrdersThisPair(Symbol()) == 0 && LotSize_Buy >= minlot )

is an ")"  too much!

This mostly  results in an error message of a wrong "{" or" }" !!

 
Actually, there is a more direct way in counting opened pairs. Less logic and faster calculation. Just a hint though.
 

I've never had an issue with OpenOrdersThisPair... As I said, this entire thread is about how FXCM's servers went down and upon calling tick value and tick size after they rebooted, it was all wrong for a while. On top of this, I am OrderSending too frequently so I am now using an Include file from the article, pasted above. All EA's use this for "green light" and wait on "red lights". I use pending orders so it's no biggy as I am placing quite far above or below current market price.

deysmacro (facepalm). Righto...

None the less, I appreciate everyone else's input. Gooly, I am not entirely sure what you're talking about? I never receive an error message regarding parenthesis.