Can't pass for sell Expert some error 131

 
int OnInit()
  {
  
double str_up = iCustom(NULL, 0,indi_3,TimeFrame,atrPeriod,atrMultiplier,0,1);
double str_down = iCustom(NULL, 0,indi_3,TimeFrame,atrPeriod,atrMultiplier,1,1);
double volumedown = iCustom(NULL, 0,indi_4,MA_Period,MA_Shift,MA_Method,0,1);
double volumeup = iCustom(NULL, 0,indi_4,MA_Period,MA_Shift,MA_Method,1,1);
double volumema = iCustom(NULL, 0,indi_4,MA_Period,MA_Shift,MA_Method,2,1);
double volumedown_2 = iCustom(NULL, 0,indi_4,MA_Period,MA_Shift,MA_Method,0,2);
double volumeup_2 = iCustom(NULL, 0,indi_4,MA_Period,MA_Shift,MA_Method,1,2);
double vwap = iCustom(_Symbol, 0,indi_6,Show_Daily,Show_Weekly,Show_Monthly,0,1);
double obv_0 = iCustom(_Symbol,0,indi_5,MAPeriod,MAType,0,1);
double obvma_1 = iCustom(_Symbol,0,indi_5,MAPeriod,MAType,1,1);
   
 ObjectsDeleteAll();   
   
  
//--- create timer

   EventSetTimer(60);
   pips = _Point * 10;
   double    lotstep = MarketInfo(_Symbol, MODE_LOTSTEP);
   
   
   digitlot = (int)log10(1 / lotstep);
//---
   return(INIT_SUCCEEDED);
  }
  
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
 {  
 
 
  
  
int digit = (int)MarketInfo(OrderSymbol(), MODE_DIGITS);
double risk_money = RiskPercent * AccountBalance() / 100; 
double sl = 0, tp = 0, range_sl = 0;


  double Lots =  LOTMM(_Symbol, risk_money, range_sl / _Point);
       Lots= Lots>MarketInfo(Symbol(),MODE_MAXLOT)?MarketInfo(_Symbol, MODE_MAXLOT) : Lots;
       Lots= Lots<MarketInfo(Symbol(),MODE_MINLOT)? MarketInfo(_Symbol, MODE_MINLOT) : Lots;
      
        Lots = NormalizeDouble(Lots, 2);


for(PositionIndex=0;PositionIndex<TotalNumberOfOrders;PositionIndex++) // inizio ciclo for controllo ordini aperti
 
      
       
      {      if(OrderSelect(PositionIndex, SELECT_BY_POS,MODE_TRADES))
       if (OrderSymbol()==Symbol()&&OrderMagicNumber() == MagicNumber)
          {
           
            
        
       { Print("Ordine selezionato correttamente");
         Print(OrderSymbol());
         Print(OrderMagicNumber());    

        double  oop = OrderOpenPrice();
        double  ocp = OrderClosePrice();
        double  osl = OrderStopLoss();
        double  otp = OrderTakeProfit();

        int tiket = OrderTicket();
        double lotti=OrderLots();
        Print(tiket);
        
       
 //MODIFY ORDER     
       int t = OrderType();
       //op[t]++;

double partialclose_1a=OrderOpenPrice()+(OrderTakeProfit()-OrderOpenPrice())*(partialclose1/100);
double partialclose_2a=OrderOpenPrice()+(OrderTakeProfit()-OrderOpenPrice())*(partialclose2/100);
double partialclose_3a=OrderOpenPrice()+(OrderTakeProfit()-OrderOpenPrice())*(partialclose3/100);


       double addtobreak = MinimalProfit*pips ;
       double addtobreak_1=10*pips;
       double newsl = oop+addtobreak; // primo stop 
       double newsl1 = oop+addtobreak+addtobreak_1;//secondo stop+1pip
       double newsl2 = oop+addtobreak+addtobreak_1+addtobreak_1;
       double testbreakb = oop+((otp-oop)*(movebeaftercut/100));
       
        double newslshort = oop-addtobreak; // primo stop 
       double newsl1short = oop-(addtobreak+addtobreak_1);//secondo stop+1pip
       double newsl2sdhort = oop-(addtobreak+addtobreak_1+addtobreak_1);
       double testbreaks = oop-((oop-otp)*(movebeaftercut/100));

       double olotnew =lotti*(percentagecut1/100) ;
       double olotnew2 =lotti*(percentagecut2/100) ;
       double olotnew3 =lotti*(percentagecut3/100) ;
       double tpbuy3 = otp+(tpincrementpip*pips);//incremento x punti take profitbuy
       double tpshort3 =otp-(tpincrementpip*pips);//incremento x punti take profitshort
             
       
       
       
  
      
    
           
               
  {
   
  }
              
              olotnew=NormalizeDouble(olotnew,digitlot);
              olotnew2=NormalizeDouble(olotnew2,digitlot);
              olotnew3=NormalizeDouble(olotnew3,digitlot);
              
              Print(lotti);
           if (t==OP_BUY)  // se la posizione è a rilzo...
                       
           {Print("Operazione buy");
             if (changetrandbuy())
             {Print("il trand cambia puoi chiudere"+changetrandbuy());
             if(!OrderClose(tiket,OrderLots(),bid,3,Green))Comment("Error");}   
            if (bid>partialclose_1a&&osl<oop)//1 livello di taglio
             {Print("PRIMO LIVELLO DI TALGIO VERO"+osl+"-"+newsl+"-"+partialclose_1a+olotnew);// primo livello ti taglio
              if (OrderModify(tiket,oop,newsl,otp,0))
              if(!OrderClose(tiket,olotnew,bid,3,Green))Comment("Error");}   
              if (bid>partialclose_2a&&osl<newsl1)     // 2 livello di taglio
              { Print("Condizione secondo parziale vera");
                 if (OrderModify(tiket,oop,newsl1,otp,0))
                 if(!OrderClose(tiket,olotnew2,bid,3,Green))Comment("Error");} 
               if (bid>partialclose_3a&&osl<newsl2) // 3 livello di taglio 
                 {Print("Condizione TERZO parziale vera");
                 Print("livello to move be"+testbreakb+tpbuy3);
                 if (OrderModify(tiket,oop,testbreakb,tpbuy3,0))
                 if(!OrderClose(tiket,olotnew3,bid,3,Green))Comment("Error");
                     ObjectDelete("hline1");
                     ObjectDelete("hline2");
                     ObjectDelete("hline3");
       
       
      
    }
       
     
                    
                    
                   
            
             } else//fine codizione se rialzo          
              if (t==OP_SELL) // se la posizione è a ribasso
               {Print("Operazione SHORT");
               if (changetrandshort())
             {Print("il trand cambia puoi chiudere"+changetrandshort());
            if(!OrderClose(tiket,OrderLots(),ask,3,Green))Comment("ERROR");}
              if (ask<partialclose_1a&&osl>oop)//1 livello di taglio
             {Print("PRIMO LIVELLO DI TALGIO VERO"+osl+"-"+newsl+"-"+partialclose_1a+olotnew);// primo livello ti taglio
              if (OrderModify(tiket,oop,newslshort,otp,0));
              if(!OrderClose(tiket,olotnew,ask,3,Green))Comment("ERROR");}     
              if (ask<partialclose_2a&&osl>newsl1short)     // 2 livello di taglio
              { Print("Condizione secondo parziale vera");
                 if (OrderModify(tiket,oop,newsl1short,otp,0));
                  if(!OrderClose(tiket,olotnew2,ask,3,Green))Comment("ERROR");}
               if (ask<partialclose_3a&&osl>newsl2sdhort) // 3 livello di taglio 
                 {Print("Condizione TERZO parziale vera");
                  Print("livello to move be"+testbreaks);
                 if (OrderModify(tiket,oop,testbreaks,tpshort3,0));
                    if(!OrderClose(tiket,olotnew3,ask,3,Green))Comment("ERROR");
                    ObjectDelete("hline1");
                    ObjectDelete("hline2");
                    ObjectDelete("hline3");}
            
            //se heiken rosso e sotto supertrand chiudo tutto 
                    
             }   
                     
              
            
           
           
           
              
           
          }
         RefreshRates(); 
         
       return;  } // fine ciclo loop
           
           }
           
           
           
              
           
        
         
        
        
            
            
    if(IsNewCandle()==true)  
      {           
         
  
  //+------------------------------------------------------------------+
//|               OPEN BUY ORDER
//+------------------------------------------------------------------+
         
   static string signal;
   string Desc = "Correct Volume";
   if(op[0] == 0)
      if(bull(sl, tp, range_sl)&&NoTradesToday())
       {
         if(Usemoneymenagment)
           {
            Lots =  LOTMM(_Symbol, risk_money, range_sl / _Point);
           }
         Lots = Lots < MarketInfo(_Symbol, MODE_MINLOT) ? MarketInfo(_Symbol, MODE_MINLOT) : Lots;
        
         Lots = Lots > MarketInfo(_Symbol, MODE_MAXLOT) ? MarketInfo(_Symbol, MODE_MAXLOT) : Lots;
         Lots = NormalizeDouble(Lots, 2);
         double volume=Lots;
               double volumeStep=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
               double volumeMin=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
               double volumeMax=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
               double volumeNormalized=int(volume/volumeStep)*volumeStep;
               volumeNormalized=volumeNormalized<volumeMin?0.0:(volumeNormalized>volumeMax?volumeMax:volumeNormalized);
         
         signal = "BUY " + (string)Lots;
            if(bar[0] != Bars)
            if (volumeNormalized>0.0)
            {
            if(CheckVolumeValue(Lots,Desc))//Check size volume
            { if(CheckMoneyForTrade(Symbol(),Lots,0))//Check if money is enough for a trade
              {
                if(OrderSend(_Symbol, 0, Lots, Ask, 0, sl, tp, comment, MagicNumber, 0, clrBlue) > 0)
                 {
                   bar[0] = Bars;} else
                   Print("Error #",GetLastError(),"in BUY Order");  
         } else Print ("Error Money isn't enough to open trade"); 
        }else Print("volume size Error");
       }else Print("Too small volume, don't trade | 7B1");
      }   
      
 //+------------------------------------------------------------------+
//|                 OPEN SHORT ORDER 
//+------------------------------------------------------------------+  
      
   sl = 0;
   tp = 0;
   range_sl = 0;
   if(op[1] == 0)
      if(bear(sl, tp, range_sl)&&NoTradesToday())
        {
         if(Usemoneymenagment)
           {
            Lots =  LOTMM(_Symbol, risk_money, range_sl / _Point);
           }
         Lots = Lots < MarketInfo(_Symbol, MODE_MINLOT) ? MarketInfo(_Symbol, MODE_MINLOT) : Lots;
         Lots = Lots > MarketInfo(_Symbol, MODE_MAXLOT) ? MarketInfo(_Symbol, MODE_MAXLOT) : Lots;
         Lots = NormalizeDouble(Lots, 2);
          double volume=Lots;
          double volumeStep=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
          double volumeMin=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
          double volumeMax=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
          double volumeNormalized=int(volume/volumeStep)*volumeStep;
          volumeNormalized=volumeNormalized<volumeMin?0.0:(volumeNormalized>volumeMax?volumeMax:volumeNormalized);
         
         signal = "Sell " + (string)Lots;
        if(bar[1] != Bars)
         if (volumeNormalized>0.0)
            {
         if(CheckVolumeValue(Lots,Desc)) //Check size volume
         {   if(CheckMoneyForTrade(Symbol(),Lots,0))//Check if money is enough for a trade
            {
              if(OrderSend(_Symbol, 1, Lots, Bid, 0, sl, tp, comment, MagicNumber, 0, clrRed) > 0)
              {
               bar[1] = Bars;}
              else 
              Print("Error #",GetLastError(),"in short Order");
               
            }else Print ("Error Money isn't enough to open trade"); 
          }else Print("Volume size error");
          }else Print("Too small volume, don't trade | 7B1");
 
       }
    }
 }
int bar[2];
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---
  }
//+------------------------------------------------------------------+



 //+------------------------------------------------------------------+
//| Check the correctness of the order volume                        |
//+------------------------------------------------------------------+
bool CheckVolumeValue(double volume,string description)
  {
//--- minimal allowed volume for trade operations
   double min_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
   if(volume<min_volume)
     {
      description=StringFormat("Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f",min_volume);
      return(false);
     }

//--- maximal allowed volume of trade operations
   double max_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
   if(volume>max_volume)
     {
      description=StringFormat("Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f",max_volume);
      return(false);
     }

//--- get minimal step of volume changing
   double volume_step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);

   int ratio=(int)MathRound(volume/volume_step);
   if(MathAbs(ratio*volume_step-volume)>0.0000001)
     {
      description=StringFormat("Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f",
                               volume_step,ratio*volume_step);
      return(false);
     }
   description="Correct volume value";
   return(true);
}

//+------------------------------------------------------------------+
//|                 Check Money For Trade
//+------------------------------------------------------------------+
bool CheckMoneyForTrade(string symb, double lots,int type)
{
   double free_margin=AccountFreeMarginCheck(symb,type, lots);

//-- if there is not enough money
   if(free_margin<0)
     {
      string oper=(type==OP_BUY)? "Buy":"Sell";
      Print("Not enough money for ", oper," ",lots, " ", symb, " Error code=",GetLastError());
      return(false);
     }
 
   //--- checking successful
   return(true);
}  

  
//+------------------------------------------------------------------+
double LOTMM(string sym, double uang, double sl_dis) //jarak point
  {
   if(MarketInfo(sym, MODE_TICKSIZE) <= 0)
      return 0;
   double dis = sl_dis  * MarketInfo(sym, MODE_POINT);
   double PointValuePerLot = MarketInfo(sym, MODE_TICKVALUE) / MarketInfo(sym, MODE_TICKSIZE);
   return (dis * PointValuePerLot) == 0 ? 0 : uang / (dis * PointValuePerLot);
   }
   
       


For pass the seller phase i have this error also if i put the controlled required. Can you help me what i wrong ?


 
            if(!OrderClose(tiket,OrderLots(),ask,3,Green))Comment("ERROR");}
              if (ask<partialclose_1a&&osl>oop)//1 livello di taglio
             {Print("PRIMO LIVELLO DI TALGIO VERO"+osl+"-"+newsl+"-"+partialclose_1a+olotnew);// primo livello ti taglio
              if (OrderModify(tiket,oop,newslshort,otp,0));
              if(!OrderClose(tiket,olotnew,ask,3,Green))Comment("ERROR");}     
You closed tiket. You can't close it again.
 
William Roeder #:
You closed tiket. You can't close it again.

it's a partial close this loop: every time there is a closeorder stop is moved and ceck 

 
Thomas Bolognesi #: it's a partial close this loop: every time there is a closeorder stop is moved and ceck 
When you do a partial close, the remaining open order will have a different ticket number.
 
Fernando Carreiro #:
When you do a partial close, the remaining open order will have a different ticket number.

   yes but with loop  the tiket is recaculated, so he know the new tiket. in backtest work. You think that i change this ? I need to select order every time a partial order is closed ?

Thans in advance 

 
Thomas Bolognesi #: yes but with loop  the tiket is recaculated, so he know the new tiket. in backtest work. You think that i change this ? I need to select order every time a partial order is closed ?
Yes, obviously! When the ticket is closed and the remaining order has a different ticket, you can only modify the new ticket, not the old one.
 

Fernando Carreiro #:
Yes, obviously! When the ticket is closed and the remaining order has a different ticket, you can only modify the new ticket, not the old one.Ok thank you i correct the code but the error 131 remain but now no more error in orderclose in logs

code correct :  

             //normalize lot  
              olotnew=NormalizeDouble(olotnew,2);
              olotnew2=NormalizeDouble(olotnew2,2);
              olotnew3=NormalizeDouble(olotnew3,2);
              
             
           if (t==OP_BUY)  // if position buy
                       
           {Print("Operazione buy");
             if (changetrandbuy())
             {Print("il trand cambia puoi chiudere"+changetrandbuy());
             if(!OrderClose(tiket,OrderLots(),bid,3,Green))Comment("Error");}
             
             
 //1 LIVEL TO CUT            
            if (bid>partialclose_1a&&osl<oop)
             {Print("PRIMO LIVELLO DI TALGIO VERO"+osl+"-"+newsl+"-"+partialclose_1a+olotnew);// primo livello ti taglio
              if (OrderModify(tiket,oop,newsl,otp,0))//move stop loss
              if(!OrderClose(tiket,olotnew,bid,3,Green))Comment("Error");}  //partial close
           
           
//2 LIVEL TO CUT             
  if(OrderSelect(PositionIndex, SELECT_BY_POS,MODE_TRADES))
   if (OrderSymbol()==Symbol()&&OrderMagicNumber() == MagicNumber)
        { int tiket1 = OrderTicket();           
              if (bid>partialclose_2a&&osl<newsl1)    
              { Print("Condizione secondo parziale vera");
                 if (OrderModify(tiket1,oop,newsl1,otp,0)) //2 move stop loss
                 if(!OrderClose(tiket1,olotnew2,bid,3,Green))Comment("Error");} //2 cut partial close
              }
              
 //3 LIVEL TO CUT
               
  if(OrderSelect(PositionIndex, SELECT_BY_POS,MODE_TRADES))
  if (OrderSymbol()==Symbol()&&OrderMagicNumber() == MagicNumber)
     { int tiket3 = OrderTicket();            
              if (bid>partialclose_3a&&osl<newsl2) // 3 livello di taglio 
                 {Print("Condizione TERZO parziale vera");
                   Print("livello to move be"+testbreakb+tpbuy3);
                 if (OrderModify(tiket3,oop,testbreakb,tpbuy3,0))//3 move stop loss
                 if(!OrderClose(tiket3,olotnew3,bid,3,Green))Comment("Error"); //3 cut partial
                     ObjectDelete("hline1");
                     ObjectDelete("hline2");
                     ObjectDelete("hline3");}
                      }
                     }        
   
 else
           
 if (t==OP_SELL) // se la posizione è a ribasso
   {Print("Operazione SHORT");
     if (changetrandshort())
       {Print("il trand cambia puoi chiudere"+changetrandshort());
        if(!OrderClose(tiket,OrderLots(),ask,3,Green))Comment("ERROR");}
            
   //1 LIVEL TO CUT          
            if (ask<partialclose_1a&&osl>oop)//1 livello di taglio
             {Print("PRIMO LIVELLO DI TALGIO VERO"+osl+"-"+newsl+"-"+partialclose_1a+olotnew);// primo livello ti taglio
              if (OrderModify(tiket,oop,newslshort,otp,0));
              if(!OrderClose(tiket,olotnew,ask,3,Green))Comment("ERROR");} 
              
  //2 LIVEL TO CUT             
  if(OrderSelect(PositionIndex, SELECT_BY_POS,MODE_TRADES))
   if (OrderSymbol()==Symbol()&&OrderMagicNumber() == MagicNumber)
        { int tiket1 = OrderTicket();                    
              if (ask<partialclose_2a&&osl>newsl1short)     // 2 livello di taglio
              { Print("Condizione secondo parziale vera");
                 if (OrderModify(tiket1,oop,newsl1short,otp,0));
                  if(!OrderClose(tiket1,olotnew2,ask,3,Green))Comment("ERROR");}
              }
  //3 LIVEL TO CUT             
  if(OrderSelect(PositionIndex, SELECT_BY_POS,MODE_TRADES))
   if (OrderSymbol()==Symbol()&&OrderMagicNumber() == MagicNumber)
        { int tiket3 = OrderTicket();                
               if (ask<partialclose_3a&&osl>newsl2sdhort) // 3 livello di taglio 
                 {Print("Condizione TERZO parziale vera");
                  Print("livello to move be"+testbreaks);
                 if (OrderModify(tiket3,oop,testbreaks,tpshort3,0));
                    if(!OrderClose(tiket3,olotnew3,ask,3,Green))Comment("ERROR");
                    ObjectDelete("hline1");
                    ObjectDelete("hline2");
                    ObjectDelete("hline3");}
            }
  }   
 }
  RefreshRates(); 
         
 return;  } // end intial loop
           
  }