Please help with Error 4107

 

Hi,


I'm a newbie semi-programmer wannabe (have been playing with code for a while now, can do only as far as amend and create new entry/exit rules in a template that a friend has put together for me, but he is unavailable at the moment to help me with this error). I get the following problem (from strategy tester):


2009.11.02 23:14:53 2009.10.01 06:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: *** ERROR *** with order sent to CLOSE SHORT position @ Market for EURUSD Ticket Number : 1 Last Price : 1.4561 Position Size : 0.1 Max Slippage : 3 Error (0): no error
2009.11.02 23:14:53 2009.10.01 06:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: OrderClose error 4107
2009.11.02 23:14:53 2009.10.01 06:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: invalid price 1.45614000 for OrderClose function
2009.11.02 23:14:53 2009.10.01 05:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: *** ERROR *** with order sent to CLOSE SHORT position @ Market for EURUSD Ticket Number : 1 Last Price : 1.4616 Position Size : 0.1 Max Slippage : 3 Error (0): no error
2009.11.02 23:14:53 2009.10.01 05:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: OrderClose error 4107
2009.11.02 23:14:53 2009.10.01 05:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: invalid price 1.46156000 for OrderClose function
2009.11.02 23:14:53 2009.10.01 04:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: *** ERROR *** with order sent to CLOSE SHORT position @ Market for EURUSD Ticket Number : 1 Last Price : 1.4626 Position Size : 0.1 Max Slippage : 3 Error (0): no error
2009.11.02 23:14:53 2009.10.01 04:00 MeanReversalTest3.5.1nobarreverseBarExitONv.ErrorFix EURUSD,H1: OrderClose error 4107

Judging by this forum, the error is with the following part of the code. I replaced 'lastPrice' with 'OrderClosePrice()' but it made no difference to above error, this is where my amazing wanabee expertise withered away completely. I looked at an existing thread on 4107 error but it loses me completely. Please help.

//==================================
//
// CLOSE POSITION Function
//
//===================================

bool ClosePosition(string SymbolCode, int TicketNbr)
{
int orderType;
double positionSize;
bool status;  
double lastPrice;
string directionStr;
int numRetrys = 0;
bool tryToCloseOrder = true;
int errNum;

  
    if (OrderSelect(TicketNbr,SELECT_BY_TICKET))
    {
        positionSize = OrderLots();  
        orderType = OrderType();

        while (tryToCloseOrder)
        {
           if (orderType == OP_BUY)
           {
              directionStr = "LONG";
              lastPrice = MarketInfo(SymbolCode,MODE_BID);
           }
    
           if (orderType == OP_SELL)
           {
              directionStr = "SHORT";
              lastPrice = MarketInfo(SymbolCode,MODE_ASK);
           }  
            
            
           status = OrderClose(TicketNbr, positionSize, lastPrice, MAX_SLIPPAGE,LightGray);         //i replaced 'lastPrice' with OrderClosePrice()
           if (status == false)  // Order close was not successful.
           {
              errNum = GetLastError();  // get the type of error and error message number
              if ((errNum == ERR_REQUOTE || errNum ==ERR_BROKER_BUSY)&& numRetrys < MAX_NUM_RETRYS) // If requote or broker busy, try again
              {
                 numRetrys +=1;
                 Print("**RETRY - Attempt to close order for ", SymbolCode, "  ", ErrorDescription(errNum), ". Number of Retrys ", numRetrys);
                 Sleep(RETRY_WAIT_TIME * 1000); //wait for RETRY_WAIT_TIME seconds. 
                 RefreshRates(); // Update last price to current market price.
              }
              else
                 tryToCloseOrder = False;
           }
           else
             tryToCloseOrder = False;
       
        } //End of "while try to close order" loop

        if (status == true) // Order closed succesfully
        {
           Print("Order sent to CLOSE ", directionStr, " position @ Market for ",SymbolCode, "  Ticket Number : ", TicketNbr,
                  "   Last Price : ", lastPrice);
           //Comment(""); // clear any information about previous order from the screen
        }
        else // Report the error
        { 
           errNum = GetLastError();
            Print("*** ERROR *** with order sent to CLOSE ", directionStr, " position @ Market for ", SymbolCode ,"  Ticket Number : ",TicketNbr,
                  " Last Price : ", lastPrice, " Position Size : ", positionSize, 
                  " Max Slippage : ", MAX_SLIPPAGE," Error (" ,errNum,"): ",ErrorDescription(errNum));   
        }
     }
     return(status);
}
// End of CLOSE  POSITION Function

What happens is if I run the strategy live it closes trades at end of each bar (as it should), but when I run it in strategy tester it won't close a trade for multiple bars. very strange


So the generous free spirited gurus of coding, any ideas what I can do to solve the error :) please be very specific as my level really is super basic :)

 
Hey don#'t worry about it guys, I'l play around with Normalise function a little to see if I can figure it out (i just found more threads on the error here, thanks to Cloudbreaker reminding us to do some more 'searching' :) speak soon
 

Niko

Good effort :)

Its not obvious where the problem is but in any case I would move the RefreshRates() to just after the

        while (tryToCloseOrder)
        {

You should have a fresh reset as close (and prior) to the OrderClose as possible

As to the basic error, I would check the derivation of

TicketNbr

as being valid, also MAX_SLIPPAGE

As a general rule, it is best to NormaliseDouble to the Digits of the order pair at every stage, if its a multi-currency EA, use

digits=MarketInfo(YourSymbol, MODE_DIGITS);

I'm quite paranoid about this, as not doing it can cause difficult-to-find problems...

BTW - Is this a multi-currency EA?

Good Luck

-BB-

 

Hey BB,

Really appreciate your 1:1 help with this :)

1. 'check derivation of TicketNbr' as being valid, what do you mean by that (compiler doesn't produce any errors)? same applies to max_slippage

2. Yep it's a multi-currency EA, but from how i understood it I just attach it to each chart I want it to run on, it is not currency specific (it has Symbol() instead of a specific symbol or instead of a list of symbols to pull out from) - is this what you meant by multi-currency

Nick

ps: i'm still at work so i'm preparing as much possible here b4 i get home and test this for real

 

Hi BB/ Others,


I spent like 3 hours trying to figure out how to make it work without any progress, i simply don't know enough about coding to do it properly. so I come back asking for help.

I made a note below what happens if I change the line to MODE_DIGITS instead of MODE_ASK or MODE_BID, there is simply 1 trade and it won't close at all.

Is it possible for someone to input into the code below the changes you think we should make as for the life of me I can't figure it out. I added the refreshrates function but it makes no difference :(


Help guys, please



//==================================
//
// CLOSE POSITION Function
//
//===================================

bool ClosePosition(string SymbolCode, int TicketNbr)
{
 int orderType;
 double positionSize;
 bool status;  
 double lastPrice;
 string directionStr;
 int numRetrys = 0;
 bool tryToCloseOrder = true;
 int errNum;

  
    if (OrderSelect(TicketNbr,SELECT_BY_TICKET))
    {
        positionSize = OrderLots();  
        orderType = OrderType();

        while (tryToCloseOrder)
        {
           RefreshRates(); // Update last price to current market price.
           if (orderType == OP_BUY)
           {
              directionStr = "LONG";
              lastPrice = MarketInfo(SymbolCode,MODE_BID);  //***changed to MODE_DIGITS before it was MODE_BID, but then we only get 1 trade which doesn't Close
           }

           if (orderType == OP_SELL)
           {
              directionStr = "SHORT";
              lastPrice = MarketInfo(SymbolCode,MODE_ASK);
           }  
            
           RefreshRates(); // Update last price to current market price.
           status = OrderClose(TicketNbr, positionSize, lastPrice, MAX_SLIPPAGE,LightGray);

           if (status == false)  // Order close was not successful.
           {
              errNum = GetLastError();  // get the type of error and error message number
              if ((errNum == ERR_REQUOTE || errNum ==ERR_BROKER_BUSY)&& numRetrys < MAX_NUM_RETRYS) // If requote or broker busy, try again
              {
                 numRetrys +=1;
                 Print("**RETRY - Attempt to close order for ", SymbolCode, "  ", ErrorDescription(errNum), ". Number of Retrys ", numRetrys);
                 Sleep(RETRY_WAIT_TIME * 1000); //wait for RETRY_WAIT_TIME seconds. 
                 RefreshRates(); // Update last price to current market price.
              }
              else
                 tryToCloseOrder = False;
           }
           else
             tryToCloseOrder = False;
       
        } //End of "while try to close order" loop

        if	(status == true) // Order closed succesfully
        {
           Print("Order sent to CLOSE ", directionStr, " position @ Market for ",SymbolCode, "  Ticket Number : ", TicketNbr,
                  "   Last Price : ", lastPrice);
           //Comment(""); // clear any information about previous order from the screen
        }
        else // Report the error
        { 
           errNum = GetLastError();
            Print("*** ERROR *** with order sent to CLOSE ", directionStr, " position @ Market for ", SymbolCode ,"  Ticket Number : ",TicketNbr,
                  " Last Price : ", lastPrice, " Position Size : ", positionSize, 
                  " Max Slippage : ", MAX_SLIPPAGE," Error (" ,errNum,"): ",ErrorDescription(errNum));   
        }
     }
     return(status);
}
// End of CLOSE  POSITION Function


help help help

 

1. Your error report is returning a zero because GetLastError() only works once and then zeroes. Remove the 2nd occurrence of "errNum = GetLastError();"

2. Your RefreshRates() call has no effect as it is placed after lastPrice is assigned. Move RefreshRates() call to immediately before you assign lastPrice.

3. Normalize lastPrice by assigning it as lastPrice = NormalizeDouble(MarketInfo(SymbolCode,MODE_ASK),Digits);

4. Ensure that SymbolCode is equal to the chart you are backtesting against - the strategy tester can not perform cross-currency testing.


CB

 

Hello pilot programmer! Long time no chat!

You came to my rescue once again man, saved me as I was pulling my hair out trying to figure out how to fix it, even started building new code from scratch using Code Guru's guide.


Whoever thinks writing code for mt4 is easy is a complete moron, it's incredibly difficult, so high amount of resepct for all you guys who knows this stuff.


I did what you said and it worked in strategy tester, each trade is closed at end of bar as it should. I'l go through them in depth to see if I introduced any other errors, and see if it can be replicated on live account.


Thank you,

nick
 
/*                lastPrice = MarketInfo(SymbolCode,MODE_ASK);
 *          }  
 *           
 *          RefreshRates(); // Update last price to current market price.
 *          status = OrderClose(TicketNbr, positionSize, lastPrice, MAX_SLIPPAGE,LightGray);
 */
     if (!OrderClose(ticket,         OrderLots(),    OrderOpenPrice(),
                     slippagePoints, clr )) { ...
wrong value in call.
 
WHRoeder:
wrong value in call.

WHRoeder, I'm not sure where you're coming from here, but if you're suggesting Niko swaps what you've highlighted in Red (the current price) with what you've highlighted in Green (the price at which the order was opened) - you're wrong.

https://docs.mql4.com/trading/OrderClose

To exactly play back your own phraseology at you (ref your post on the "Serious MT4 Bug Re GlobalVariables ??!!" thread) - what part of niko's response did you not understand? ;-) "I did what you said and it worked in strategy tester, each trade is closed at end of bar as it should".


Niko, ignore this. The correct parameter to supply is the preferred closing price which you are indeed attempting to assign to lastPrice.


CB

 

Hey guys,


I looked into more detail into the trades produced by the method. The following happens:

trades are executed as normal (i.e. close position at end of each bar, open position at start of bar) but this only happens for 20 or so trades, after which we are starting to get the following errors, and lot's of them:


2009.11.08 14:43:34 TestGenerator: unmatched data error (volume limit 1308 at 2009.10.30 14:00 exceeded)

2009.11.08 14:43:34 TestGenerator: unmatched data error (low value 1.4723 at 2009.10.30 17:00 is not reached from the least timeframe, low price 1.4727 mismatches)

2009.11.08 14:43:34 TestGenerator: unmatched data error (high value 1.4735 at 2009.10.30 19:00 is not reached from the least timeframe, high price 1.4728 mismatches)


And no more trades are done :(
(ps: i'm gonna search this forum for what this means, but meanwhile if you have any ideas please do share


 

Unmatched data error means that (just for example) you may have a high in an M5 candle which is higher than the high of the M30 candle which should include that M5 candle.

To resolve the issue, you can regenerate the lower-resolution time-period data using the period-converter script.


CB

Reason: