Download MetaTrader 5

OrderModify failed 0 (using Market Orders for backtesting = quicker)

To add comments, please log in or register
Dominic Gilbert
1639
Dominic Gilbert  
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
 {
  CheckHistory(); // This NEEDS to be checked every tick

   if( IsNewCandle() ) 
      {  
       if( Bar1Time > HistoryBarTime )
         {
         CheckForMaTrade();
         } 
      }    

   if( OpenOrdersThisPair(Symbol()) > 0 )
      {
      MA_Trail(); 
      Move_To_BreakEven();
      Check_Position_Parameters();
      }  


    if( Bar1Time > HistoryBarTime && OpenOrdersThisPair(Symbol()) == 0 && 
         H1_Buy_Touch == "H1 Buy Touch" && Ask > Stored_BuyPrice + Point )
         {
         OrderEntry(0);
         }

...
So I am using Market Orders now as Pending Orders (that recalculate each applicable bar) is slowing my back-testing down SO much.

Anyway, OrderEntry(0); is the buy side and gets called... I am getting the error in the for loop below (i'I've deleted prints to make it easier to read but kept the OrderModify prints):


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

void OrderEntry(int direction)
{
   
   // Padding for Stop & Entry ------------
   ATR_Pad = iATR(NULL,low,ATR_Period,1)/2;
   Buy_Pad = NormalizeDouble(ATR_Pad,Digits); 
   Sell_Pad = NormalizeDouble(ATR_Pad,Digits);
   //Stop calculations  -------------------
   ATR = iATR(NULL,low,ATR_Period,1);
   MA = iMA(NULL,low,MA_Period,0,1,0,1);
   //Market Information -------------------  
   Lot_Step = MarketInfo(Symbol(), MODE_LOTSTEP); 
   ts = MarketInfo(Symbol(), MODE_TICKSIZE); 
   tv = MarketInfo(Symbol(), MODE_TICKVALUE);
   minlot = MarketInfo(Symbol(), MODE_MINLOT);
   freezelevel = MarketInfo(Symbol(), MODE_FREEZELEVEL);   
   //Risk applied per trade --------------
   risk_amount = AccountBalance( )*RiskPercent/100;
   risk_amount2 = AccountBalance( )*RiskPercent2/100;
   risk_amount3 = AccountBalance( )*RiskPercent3/100;
   risk_amount4 = AccountBalance( )*RiskPercent4/100;

   D1_ATR = NormalizeDouble(iATR(NULL,1440,D1_ATR_Period,1),Digits);
   Todays_Range = NormalizeDouble(Todays_D1_high - Todays_D1_low, Digits);
         
//+-------------------------------------------------------------------------------------+
//| Order Buy Function                                                                  |
//+-------------------------------------------------------------------------------------+   

if(direction==0)
{//--Buy--// 
      
    //Get Buy Stop price
    double BuyStopPriceMath = MA - ATR, 
           BuyStopPrice = NormalizeDouble(BuyStopPriceMath,Digits); 
         
    //Get Take Profit price for FIRST TARGET
    if( Stored_BuyPrice > BuyStopPrice - Point || BuyStopPrice > Stored_BuyPrice - Point ) {
       pips_to_bsl = Stored_BuyPrice - BuyStopPrice;
       }
 
    double buy_tp_price1 = (pips_to_bsl*First_Target_Ratio) + Stored_BuyPrice, 
           buy_takeprofit_price1 = NormalizeDouble(buy_tp_price1,Digits), 
           btp1 = buy_takeprofit_price1;

      
     //Get Take Profit price for SECOND TARGET
     double buy_tp_price2 =(pips_to_bsl*Second_Target_Ratio)+Stored_BuyPrice, 
            buy_takeprofit_price2 = NormalizeDouble(buy_tp_price2, Digits), 
            btp2 = buy_takeprofit_price2;
      
     //Get Take Profit price for THIRD TARGET
     double buy_tp_price3 =(pips_to_bsl*Third_Target_Ratio)+Stored_BuyPrice, 
            buy_takeprofit_price3 = NormalizeDouble(buy_tp_price3, Digits), 
            btp3 = buy_takeprofit_price3;   
      
     //Get Take Profit price for FOURTH TARGET
     double buy_tp_price4 =(pips_to_bsl*Fourth_Target_Ratio)+Stored_BuyPrice, 
            buy_takeprofit_price4 = NormalizeDouble(buy_tp_price4, Digits), 
            btp4 = buy_takeprofit_price4;
             
      
     //What is loss for 1 lot?
     double loss_for_1_lot = pips_to_bsl / ts * tv ;
      
     //Get Lot Size calculations for all FOUR Trades                   
     double LotSize_Buy  = MathFloor( risk_amount / loss_for_1_lot/ Lot_Step) * Lot_Step, 
            LotSize_Buy2 = MathFloor( risk_amount2 / loss_for_1_lot/ Lot_Step) * Lot_Step,
            LotSize_Buy3 = MathFloor( risk_amount3 / loss_for_1_lot/ Lot_Step) * Lot_Step, 
            LotSize_Buy4 = MathFloor( risk_amount4 / loss_for_1_lot/ Lot_Step) * Lot_Step;
    
//+------------------------------------------------------------------+
//---Buy---//
    if( minlot > LotSize_Buy - Point )LotSize_Buy = minlot; 
    if( minlot > LotSize_Buy2 - Point )LotSize_Buy2 = minlot; 
    if( minlot > LotSize_Buy3 - Point )LotSize_Buy3 = minlot; 
    if( minlot > LotSize_Buy4 - Point )LotSize_Buy4 = minlot;    
     
     
     if( OpenOrdersThisPair(Symbol()) == 0 && LotSize_Buy - minlot > Point / 2. )
         { 
         BuyTicketOrder1 = OrderSend(Symbol(),OP_BUY,LotSize_Buy,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
         BuyTicketOrder2 = OrderSend(Symbol(),OP_BUY,LotSize_Buy2,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
         BuyTicketOrder3 = OrderSend(Symbol(),OP_BUY,LotSize_Buy3,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
         BuyTicketOrder4 = OrderSend(Symbol(),OP_BUY,LotSize_Buy4,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
   
         }          
                       
   
   RefreshRates(); 
   
   for(int b=OrdersTotal()-1; b>=0; b--)
   {
     if( !OrderSelect(b,SELECT_BY_POS,MODE_TRADES))continue;
     {
      if( OrderMagicNumber()== MagicNumber1  )
      if(OrderSymbol() == Symbol())
       if( OrderType() == OP_BUY )
        if( OrderStopLoss() == 0 || OrderTakeProfit() == 0 )
        { 
         bool ModifyBuy1 = OrderModify(BuyTicketOrder1,OrderOpenPrice(),BuyStopPrice,btp1,0,clrNONE);
          Print(" ModifyBuy1 failed: ", GetLastError() );
         bool ModifyBuy2 = OrderModify(BuyTicketOrder2,OrderOpenPrice(),BuyStopPrice,btp2,0,clrNONE);
          Print(" ModifyBuy2 failed: ", GetLastError() ); 
         bool ModifyBuy3 = OrderModify(BuyTicketOrder3,OrderOpenPrice(),BuyStopPrice,btp3,0,clrNONE);
          Print(" ModifyBuy3 failed: ", GetLastError() );
         bool ModifyBuy4 = OrderModify(BuyTicketOrder4,OrderOpenPrice(),BuyStopPrice,btp4,0,clrNONE);
          Print(" ModifyBuy4 failed: ", GetLastError() );
        } 
      }
    } 

} // end of  if(direction==0)
whroeder1
15331
whroeder1  
         BuyTicketOrder1 = OrderSend(Symbol(),OP_BUY,LotSize_Buy,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
         BuyTicketOrder2 = OrderSend(Symbol(),OP_BUY,LotSize_Buy2,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
         BuyTicketOrder3 = OrderSend(Symbol(),OP_BUY,LotSize_Buy3,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
         BuyTicketOrder4 = OrderSend(Symbol(),OP_BUY,LotSize_Buy4,Ask + Point,3,
                                             0,0,NULL,MagicNumber1,0,Green);
  1. Check your return codes (OrderSelect) What are Function return values ? How do I use them ? - MQL4 forum and Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
  2. Server call takes time, you must refreshRates() between them.
  3. How do you expect to open an order other than market price?
  4. What is MarketInfo(market_pair, MODE_STOPLEVEL)? You can't put pending orders closer than that and you're using 1.
Dominic Gilbert
1639
Dominic Gilbert  

Yeah I've deleted the prints to make it easier to read. Thanks for your advice. I've changed that mistake above.

I'm not using pending orders...? I thought I am using a market order... 

The errors seem to be coming from the ordermodify's error "0". 

Dominic Gilbert
1639
Dominic Gilbert  

I've got it sorted. As usual, thanks for your help WHRoeder! :) (I was being a bit - no surprise - of a dingbat) 

 This is what I now use for the for loop part - slapping continue; when one of the ordermodify was successful meant that ALL the orders will then being properly selected and modified:

   for(int b=OrdersTotal()-1; b>=0; b--)
   {
     if( !OrderSelect(b,SELECT_BY_POS,MODE_TRADES))continue;
     {
      if( OrderMagicNumber()== MagicNumber1  )
      if(OrderSymbol() == Symbol())
       if( OrderType() == OP_BUY )
        if( OrderStopLoss() == 0 || OrderTakeProfit() == 0 )
        { 
        if( OrderTicket() == BuyTicketOrder1 ){ 
         bool ModifyBuy1 = OrderModify(BuyTicketOrder1,OrderOpenPrice(),BuyStopPrice,btp1,0,clrNONE);
          if(ModifyBuy1 == False )Print(" ModifyBuy1 failed: ", GetLastError() );
          if(ModifyBuy1 == True )Print(" ModifyBuy1 Success: ", OrderSymbol() );continue;}
        if( OrderTicket() == BuyTicketOrder2 ){  
         bool ModifyBuy2 = OrderModify(BuyTicketOrder2,OrderOpenPrice(),BuyStopPrice,btp2,0,clrNONE);
          if(ModifyBuy2 == False )Print(" ModifyBuy2 failed: ", GetLastError() );
          if(ModifyBuy2 == True )Print(" ModifyBuy2 Success: ", OrderSymbol() );continue;}
        if( OrderTicket() == BuyTicketOrder3 ){   
         bool ModifyBuy3 = OrderModify(BuyTicketOrder3,OrderOpenPrice(),BuyStopPrice,btp3,0,clrNONE);
          if(ModifyBuy3 == False )Print(" ModifyBuy3 failed: ", GetLastError() );
          if(ModifyBuy3 == True )Print(" ModifyBuy3 Success: ", OrderSymbol() );continue;}
        if( OrderTicket() == BuyTicketOrder4 ){  
         bool ModifyBuy4 = OrderModify(BuyTicketOrder4,OrderOpenPrice(),BuyStopPrice,btp4,0,clrNONE);
          if(ModifyBuy4 == False )Print(" ModifyBuy4 failed: ", GetLastError() );
          if(ModifyBuy4 == True )Print(" ModifyBuy4 Success: ", OrderSymbol() );continue;}
        } 
      }
    break;
    }
Dominic Gilbert
1639
Dominic Gilbert  
Hmmm... so it looks like it hasn't worked. I am getting error code 131 on the order modify and sometimes none of the orders are actually modified at all (i.e. no stops or targets placed). Not sure where I am going wrong here? As soon as the Market Order is placed, I want to modify my trade immediately with the stops and targets - Not all trades are being modified... only a few. I need to make 100% certain that as long as the terminal is open, all open trades on the corresponding pair is modified correctly AND that all x4 trades are actually placed.

...     

if( OpenOrdersThisPair(Symbol()) == 0 && LotSize_Buy - minlot > Point / 2. )//&& D1_ATR > Todays_Range - Point)
         { 
         BuyTicketOrder1 = OrderSend(Symbol(),OP_BUY,LotSize_Buy,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
         BuyTicketOrder2 = OrderSend(Symbol(),OP_BUY,LotSize_Buy2,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
         BuyTicketOrder3 = OrderSend(Symbol(),OP_BUY,LotSize_Buy3,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
         BuyTicketOrder4 = OrderSend(Symbol(),OP_BUY,LotSize_Buy4,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
         
         
         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 );
         
         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 );
         
         if(BuyTicketOrder3 == -1)Print("Third Buy Order Last Error = ",GetLastError(), " On: ", Symbol());//return;
         //if(BuyTicketOrder3 > 0)Print("Third Buy Order Placed: ", Symbol(), " LotSize_Buy is: ", LotSize_Buy3 );
         
         if(BuyTicketOrder4 == -1)Print("Fourth Buy Order Last Error = ",GetLastError(), " On: ", Symbol());//return;
         //if(BuyTicketOrder4 > 0)Print("Fourth Buy Order Placed: ", Symbol(), " LotSize_Buy is: ", LotSize_Buy4 );    
         }          
                       

   for(int b=OrdersTotal()-1; b>=0; b--)
   {
     if( !OrderSelect(b,SELECT_BY_TICKET))continue;
     {
      if( OrderMagicNumber()== MagicNumber1  )
      if(OrderSymbol() == Symbol())
       if( OrderType() == OP_BUY )
        { 

        if( OrderTicket() == BuyTicketOrder1 ){ 
         bool ModifyBuy1 = OrderModify(BuyTicketOrder1,OrderOpenPrice(),BuyStopPrice,btp1,0,clrNONE);
          if(ModifyBuy1 == False )Print(" ModifyBuy1 failed: ", GetLastError() );
          if(ModifyBuy1 == True )Print(" ModifyBuy1 Success: ", OrderSymbol() );continue;}
        if( OrderTicket() == BuyTicketOrder2 ){  
         bool ModifyBuy2 = OrderModify(BuyTicketOrder2,OrderOpenPrice(),BuyStopPrice,btp2,0,clrNONE);
          if(ModifyBuy2 == False )Print(" ModifyBuy2 failed: ", GetLastError() );
          if(ModifyBuy2 == True )Print(" ModifyBuy2 Success: ", OrderSymbol() );continue;}
        if( OrderTicket() == BuyTicketOrder3 ){   
         bool ModifyBuy3 = OrderModify(BuyTicketOrder3,OrderOpenPrice(),BuyStopPrice,btp3,0,clrNONE);
          if(ModifyBuy3 == False )Print(" ModifyBuy3 failed: ", GetLastError() );
          if(ModifyBuy3 == True )Print(" ModifyBuy3 Success: ", OrderSymbol() );continue;}
        if( OrderTicket() == BuyTicketOrder4 ){  
         bool ModifyBuy4 = OrderModify(BuyTicketOrder4,OrderOpenPrice(),BuyStopPrice,btp4,0,clrNONE);
          if(ModifyBuy4 == False )Print(" ModifyBuy4 failed: ", GetLastError() );
          if(ModifyBuy4 == True )Print(" ModifyBuy4 Success: ", OrderSymbol() );continue;}

        } 
      }
    //break;
    }

...
Dominic Gilbert
1639
Dominic Gilbert  
I have no idea why my market orders are not modified correctly. Some stops are at different levels. When price develops, the stops eventually re-align as I have a trail function. But on this first modify, the stops are different. Take profits works. Stops are exactly the same though :s!?
Dominic Gilbert
1639
Dominic Gilbert  
It runs through, first 4 trades work perfectly and get modified, the second set (x4 trades per setup) do not modify at all?
Dominic Gilbert
1639
Dominic Gilbert  

Ok, I got rid of the for loop. That was unnecessary. I do it like this now...

 

     if( OpenOrdersThisPair(Symbol()) == 0 && LotSize_Buy >= minlot )//&& D1_ATR > Todays_Range - Point)
         { 
         BuyTicketOrder1 = OrderSend(Symbol(),OP_BUY,LotSize_Buy,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
                                                if( OrderSelect(BuyTicketOrder1,SELECT_BY_TICKET)){
                                                      if(OrderSymbol() == Symbol() && OrderType() == OP_BUY )
                                                         bool ModifyBuy1 = OrderModify(BuyTicketOrder1,OrderOpenPrice(),BuyStopPrice,btp1,0,clrNONE);}
                                                
                                                
         BuyTicketOrder2 = OrderSend(Symbol(),OP_BUY,LotSize_Buy2,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
                                                if( OrderSelect(BuyTicketOrder2,SELECT_BY_TICKET)){
                                                     if(OrderSymbol() == Symbol() && OrderType() == OP_BUY )
                                                        bool ModifyBuy2 = OrderModify(BuyTicketOrder2,OrderOpenPrice(),BuyStopPrice,btp2,0,clrNONE);}
                                             
         BuyTicketOrder3 = OrderSend(Symbol(),OP_BUY,LotSize_Buy3,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
                                                 if( OrderSelect(BuyTicketOrder3,SELECT_BY_TICKET)){
                                                     if(OrderSymbol() == Symbol() && OrderType() == OP_BUY )
                                                        bool ModifyBuy3 = OrderModify(BuyTicketOrder3,OrderOpenPrice(),BuyStopPrice,btp3,0,clrNONE);}
                                                        
         BuyTicketOrder4 = OrderSend(Symbol(),OP_BUY,LotSize_Buy4,Ask ,3,
                                             0,0,NULL,MagicNumber1,0,Green);RefreshRates();
                                                   if( OrderSelect(BuyTicketOrder4,SELECT_BY_TICKET)){
                                                     if(OrderSymbol() == Symbol() && OrderType() == OP_BUY )
                                                        bool ModifyBuy4 = OrderModify(BuyTicketOrder4,OrderOpenPrice(),BuyStopPrice,btp4,0,clrNONE);}
whroeder1
15331
whroeder1  
 if(BuyTicketOrder1 == -1)Print("First Buy Order Last Error = ",GetLastError(),
Does GetLastError refer to the error on order1 or order2 or order3 or order4?  Of course you have no idea. If the open fails you must capture the error right there and then. What are Function return values ? How do I use them ? - MQL4 forum and Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
Dominic Gilbert
1639
Dominic Gilbert  

Yea I see what I am doing wrong with regards to print.

 With regards to above, sometimes on a rare occasion the OrderSend does not actually successfully modify, well, at least 1 OP_BUY || OP_SELL is not modified. How do I make sure that the trade is modified? 

Dominic Gilbert
1639
Dominic Gilbert  
Im getting ordermodify error 130 on the first BuyTicketOrder1 ?
12
To add comments, please log in or register