help for Partial close at the end of code the order close continue to close order i can't stop the loop

 

I have a problem to ceck the orderselection. The orderclose function (partial)close always the operation, how can i stop like for partial close only 1 time ? i have ceck the lot but don't work

int digit = (int)MarketInfo(OrderSymbol(), MODE_DIGITS);
   int op[6] = {0, 0, 0, 0, 0, 0};
   for(int i_hit = OrdersTotal(); i_hit >= 0; i_hit--)
      {  Print("siamo qui");
      if(!OrderSelect(i_hit, SELECT_BY_POS))
      continue;
      if(OrderSymbol() != _Symbol)
         continue;
      if(OrderMagicNumber() != MagicNumber)
         continue;
         
      int t = OrderType();
     int tiket = OrderTicket();
     op[t]++;
     double otp = OrderTakeProfit(),
             osl = OrderStopLoss(),
             ocp = OrderClosePrice(),
             oop = OrderOpenPrice();
     
     double start_be = OrderOpenPrice()+((OrderTakeProfit()- OrderOpenPrice())*Breakeven_value/100);
     start_be=NormalizeDouble(start_be, _Digits); 
     double  partialclose_1a = OrderOpenPrice()+((OrderTakeProfit()- OrderOpenPrice())*partialclose1/100);
     partialclose_1a = NormalizeDouble(partialclose_1a, _Digits);  

     double jarak = MinimalProfit*pips ;
  
     
     double new_tp = otp;
     double newsl = oop+jarak;
    
    Print("SIamo qui due");
     
                 if (Ask>start_be)
                  {   Print("condizione Vera");
                                   
                    (OrderModify(tiket,oop,newsl,otp,0));
          
                    }
                    
          } Print("siamo qui 3 ");
          
                          int type=OrderType();
                          if (type==OP_BUY&&Bid>=partialclose_1a)//se prezzo sopra livello cut
                        
                          { Print("condizione vera : " + partialclose_1a);
                            if (olot=olot)
                             { Print("Lotto ugale al precedente");
                              
                              if(OrderSelect(tiket,SELECT_BY_POS,MODE_TRADES));
                             
                                 {Print("Ordine selezionato correttamente"+ olot + tiket);
                                 
                                   double olotnew =olot*(percentagecut/100) ;
                                   if(!OrderClose(tiket,olotnew,Bid,3,Green))Print("Fallimento nella chiusura ord");
                                  
                                  } //generazione nuovo ticket
                               }
                           }
 
Please don't create topics randomly in any section. It has been moved to the section: MQL4 e MetaTrader 4
 

Don't just post code. Please explain your issue in detail.

 
Thomas Bolognesi:

I have a problem to ceck the orderselection. The orderclose function (partial)close always the operation, how can i stop like for partial close only 1 time ? i have ceck the lot but don't work

You should set a flag, for example, when you open the order, set the level for partial profit … and save that value as global variable, so your EA can recover, and after you take partial on that level, set that variable to 0… put a condition.. if variable > 0 take partial… this way you only take it once… but also, your closing volume should be a multiple  of volume step… you cannot use OrderLotSize() /2
 
  1. Thomas Bolognesi: how can i stop like for partial close only 1 time ? i have ceck the lot but don't work

    You also must check if you have already done it, to avoid repeated closing. Alternatives:

    • Move SL to Break Even+1 before the partial close. That way, you know that you already did it.
    • Set a flag in persistent storage (files, global variables w/flush)
    • Open two orders initially, and close one (manually or by TP.)

  2.                                    double olotnew =olot*(percentagecut/100) ;
                                       if(!OrderClose(tiket,olotnew,Bid,3,Green))Print("Fallimento nella chiusura ord");

    You can't just use OrderLots()/2 because that is not a multiple of LotStep, and you can't close or have remaining less than MinLot.

  3.                             if (olot=olot)

    That is not a comparison, it's an assignment and test for non-zero. What are you trying to do there?

  4.                               if(OrderSelect(tiket,SELECT_BY_POS,MODE_TRADES));

    Why are you selecting by ticket, when you already selected a order in the main loop?

  5. Don't use negative logic
       for(int i_hit = OrdersTotal(); i_hit >= 0; i_hit--)
          {  Print("siamo qui");
          if(!OrderSelect(i_hit, SELECT_BY_POS))
          continue;
          if(OrderSymbol() != _Symbol)
             continue;
          if(OrderMagicNumber() != MagicNumber)
             continue;
    
    Simplify
       for(int i_hit = OrdersTotal(); i_hit >= 0; i_hit--) if(
          OrderSelect(i_hit, SELECT_BY_POS)
      && OrderMagicNumber() != MagicNumber
      && OrderSymbol() != _Symbol
      ){
    

 
William Roeder #:

Hi William,

Thanks for reply  

2.

 double olotnew =olot*(percentagecut/100) ;  

i use percentagecut as input in global 

 3.

  if (olot=olot)

i do some test but with no result obviously 


My condition is open 1 order at day and i use ordersend function with money menager but i can't return the value of lot calculated for openorder ? and make comparison with it ? 

i repost the code with your suggest but the Partialcut make me crazy

//+------------------------------------------------------------------+
//|                                        Breakoutstrategy.mq4 |
//|                        Copyright 2022, MetaQuotes Software Corp. |
//|                                        |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "capitalgain"
#property version   "1.00"
#property strict
 
// int periodRSI = 14;
 double multiplier = 2;


// input int maperiod= 50;
input double stoplosspercent = 1;
extern double StartTime1 = "09:00:";
extern double EndTime1 = "12:00:";
input int ncandletoceck= 
4 ;

//Money menagment
input bool Usemoneymenagment = true ;
input double RiskPercent = 1 ;
input double FixedLotSize = 0.01;

input bool UseBreakeven;//Use breakeven [%]
input double  Breakeven_value = 30; //breakeven [%] 
input double  MinimalProfit = 10; //Minimal Profit pip
input double partialclose1=50; //level to cut position in % from open price
input double percentagecut= 30; //ammount to cut in % 


sinput string moneymenager;
input string comment;
input int MagicNumber;
double pips;
int BarsCount = 0;
int digitlot ;


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- 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()
 {
 
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_MINLOT) ? MarketInfo(_Symbol, MODE_MINLOT) : Lots;
         Lots = Lots > MarketInfo(_Symbol, MODE_MAXLOT) ? MarketInfo(_Symbol, MODE_MAXLOT) : Lots;
         Lots = NormalizeDouble(Lots, digitlot);

   
double partialclose_1a =OrderOpenPrice()+(OrderTakeProfit()-OrderOpenPrice())*(partialclose1/100);

             
double start_be =OrderOpenPrice()+(OrderTakeProfit()-OrderOpenPrice())*(Breakeven_value/100);
                
int digit = (int)MarketInfo(OrderSymbol(), MODE_DIGITS);

   

 
 
 
 //calculate the current time 
 string CurrentTime=TimeToStr(TimeLocal(),TIME_SECONDS);
 string openingperiod=CurrentTime;
  
  
  
//if definedd time period is not found.deliver-1
  int EndopeningPeriodFound=StringFind(CurrentTime,openingperiod,0);
 //find the highest of the last x candle 
  int HighestCandle =iHighest(_Symbol,_Period,MODE_HIGH,ncandletoceck,2);
//find the lowest of the last x candle 
  int LowestCandle =iLowest(_Symbol,_Period,MODE_LOW,ncandletoceck,2);

//OUTPUT TIME
Comment ("CURRENT tIME:",CurrentTime);

if (EndopeningPeriodFound!=-1)
//delete rectangle
{ObjectDelete("Rectangle");
 ObjectCreate("Rectangle",OBJ_RECTANGLE,0,Time[0],High[HighestCandle],Time[ncandletoceck],Low[LowestCandle]);
 
}

//Draw vertical line
if (ObjectFind("vline") > -1 && ObjectFind("vline1") > -1)
    {
       ObjectDelete("vline");
       ObjectDelete("vline1");
    }
datetime time = StrToTime(TimeToStr(TimeCurrent(), TIME_DATE) + " " + StartTime1 + ":00");
datetime time2 = StrToTime(TimeToStr(TimeCurrent(), TIME_DATE) + " " + EndTime1 + ":00");
ObjectCreate("vline",OBJ_VLINE,0,time,0);
ObjectCreate("vline1",OBJ_VLINE,0,time2,0);


    


         



//Plot input 
int Deposit=AccountBalance();  
int Belance = AccountEquity();
double Growth= (AccountEquity()-Deposit)/100;
double bid = MarketInfo(Symbol(), MODE_BID);
double ask = MarketInfo(Symbol(), MODE_ASK);


//Normalization
Growth =NormalizeDouble(Growth,1);
bid=NormalizeDouble(bid, _Digits);
ask=NormalizeDouble(ask, _Digits);
partialclose_1a = NormalizeDouble(partialclose_1a, _Digits); 
start_be=NormalizeDouble(start_be, _Digits);  
Lots = NormalizeDouble(Lots, digitlot);
   



 

 //Table of some info  
 string name = "Equity"; 
 string name2 = "Lottostart";
 string name4= "Growth";
 string name5 = "start_be"; 
 string name6= "Profit";
 string name3= "Cut";
 
 {
ObjectCreate(name, OBJ_LABEL, 0, 0, 0);
ObjectSet(name, OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSet(name, OBJPROP_XDISTANCE,50 );
ObjectSet(name, OBJPROP_YDISTANCE, 30);
ObjectSetText(name,"Equity $ : "+Belance, 16, "Roboto", Blue);//mostra il bilancio

ObjectCreate(name4, OBJ_LABEL, 0, 0, 0);
ObjectSet(name4, OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSet(name4, OBJPROP_XDISTANCE,70 );
ObjectSet(name4, OBJPROP_YDISTANCE, 60);
ObjectSetText(name4,"Growth% : "+Growth, 16, "Roboto", Blue);//mostra il bilancio

ObjectCreate(name5, OBJ_LABEL, 0, 0, 0);
ObjectSet(name5, OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSet(name5, OBJPROP_XDISTANCE,50 );
ObjectSet(name5, OBJPROP_YDISTANCE, 90);
ObjectSetText(name5,"Level to start Breakeven:"+start_be, 12, "Corbel Bold", Blue);//livello di partenza Break
                
ObjectCreate(name6, OBJ_LABEL, 0, 0, 0);
ObjectSet(name6, OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSet(name6, OBJPROP_XDISTANCE,60 );
ObjectSet(name6, OBJPROP_YDISTANCE, 120);
ObjectSetText(name6,"Level to first cut % :"+partialclose_1a, 12, "Corbel Bold", Blue);//livello del primo taglio               

ObjectCreate(name3, OBJ_LABEL, 0, 0, 0);
ObjectSet(name3, OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSet(name3, OBJPROP_XDISTANCE,60 );
ObjectSet(name3, OBJPROP_YDISTANCE, 150);
ObjectSetText(name3,"Position Cut by % :"+percentagecut, 12, "Corbel Bold", Blue);// mostra percentual di taglio



ObjectCreate(name2, OBJ_LABEL, 0, 0, 0);
ObjectSet(name2, OBJPROP_CORNER,CORNER_RIGHT_UPPER);
ObjectSet(name2, OBJPROP_XDISTANCE,60 );
ObjectSet(name2, OBJPROP_YDISTANCE, 180);
ObjectSetText(name2,"Lottostart:"+Lots, 12, "Corbel Bold", Blue);// mostra percentual di taglio
 }
 
  
 //MODIFY ORDER
 double otp = OrderTakeProfit(),
        osl = OrderStopLoss(),
        ocp = OrderClosePrice(),
        oop = OrderOpenPrice(),
        lots=OrderLots();
       
       int tiket=OrderTicket();
       int type =OrderType();    
       double addtobreak = MinimalProfit*pips ;
       double newsl = oop+addtobreak;
       
       double olotnew =lots*(percentagecut/100) ;
              olotnew=NormalizeDouble(olotnew,digitlot);
     
       
      if ( OrdersTotal()>0)
      {  if(OrderSelect(0, SELECT_BY_POS,MODE_TRADES))
         {Print("Unable to Select the order");}
       
          if(bid>start_be&&osl<oop)
                {
                 (OrderModify(tiket,oop,newsl,otp,0));
                   { Print("order modify correct");      
                 } Print(" modify error"+GetLastError());          
                 }
      
           if (ask>=partialclose_1a&&osl>oop)
                    
         {
           if(OrderClose(OrderTicket(),olotnew,ocp,3,Green));
              {Print("Pos ",tiket,"PartialClose"+lots);} 
                     
               } Print("False go here");
        } 
     
     
  
    

     
    
 
     
     
           
           
           
          
       

               
      
  static string signal;
     if(OrdersTotal()<=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, digitlot);
         signal = "BUY " + (string)Lots;
         if(bar[0] != Bars)
         if (OrdersTotal()<=0);
            if(OrderSend(_Symbol, 0, Lots, Ask, 0, sl, tp, comment, MagicNumber, 0, clrBlue) > 0)
              {
               bar[0] = Bars;
               

             

              
              };
        }
   sl = 0;
   tp = 0;
   range_sl = 0;
   if(OrdersTotal()<=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, digitlot);
         signal = "Sell " + (string)Lots;
         if(bar[1] != Bars)
            if(OrderSend(_Symbol, 1, Lots, Bid, 0, sl, tp, comment, MagicNumber, 0, clrRed) > 0)
              {
               bar[1] = Bars;
             };      

  

  
  }
  }
 
int bar[2];
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//---
  }
//+------------------------------------------------------------------+

bool NoTradesToday()
  {
   datetime today = iTime(NULL,PERIOD_D1,0);

   for(int i=OrdersHistoryTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
      if(OrderSymbol()      != _Symbol)  continue;
      if(OrderMagicNumber() != MagicNumber) continue;
      if(OrderOpenTime()    >= today)    return(false);
     }

   for(int i=OrdersTotal()-1; i>=0; i--)           
     {
      if(!OrderSelect(i,SELECT_BY_POS))  continue;  
      if(OrderSymbol()      != _Symbol)  continue;  
      if(OrderMagicNumber() != MagicNumber) continue;  
      if(OrderOpenTime()    >= today)    return(false);
     }
 Print("posizione chiuse :1");
   return(true);
   
  }

bool bull(double &sl, double &tp, double &range_sl)
  {
   
   
  // double ma= iMA(NULL,0,maperiod,0,1,0,0);
  

   
   double periodhighest= iHighest(NULL,0,MODE_HIGH,ncandletoceck,2);//ricerca valore massimo
    periodhighest=MathAbs ( periodhighest );
  
   double close = iClose(NULL, 0, 1);
   double close2 = iClose(NULL, 0, 2);
   double high= iHigh(NULL,PERIOD_D1,1);
   double high2=iHigh(NULL,0,periodhighest);
   double open = iOpen(NULL, 0, 1);

   
   double bodyrange = MathAbs(iClose(NULL, 0, 1) - iOpen(NULL, 0, 1));
   double barrange = (iHigh(NULL, 0, 1) - iLow(NULL, 0, 1));
   
   double low1 = iLow(NULL, 0, 1);
   double stoploss= Ask-(Ask*stoplosspercent/100);
string StartTime = StartTime1;
string EndTime   = EndTime1;
double currentday = Day();//giorno di oggi 


    if (OrdersTotal()==0)
    { Print("numero di ordini sotto lo zero BUY");
      if (TimeCurrent() >= StringToTime(TimeToString(TimeCurrent(),TIME_DATE)+" "+StartTime) && TimeCurrent() < StringToTime(TimeToString(TimeCurrent(),TIME_DATE)+" "+EndTime)
         && close > high2 )
   
     
     
    
        
     {
      range_sl = Ask - stoploss; //32 invece di 3200
      tp = Ask + (range_sl * multiplier);
      sl = stoploss;
      return true;
     }
     
     }
   return false;
   
  }
//+------------------------------------------------------------------+




bool bear(double &sl, double &tp, double &range_sl)
  {
   string StartTime = StartTime1;
   string EndTime   = EndTime1;
   double periodlowest= iLowest(NULL,0,MODE_LOW,8,2);
   int periodlowest1=MathAbs ( periodlowest );
   
 //  double ma= iMA(NULL,0,maperiod,0,1,0,0);  
   double close = iClose(NULL, 0, 1);
   double open = iOpen(NULL, 0, 1);
   
   double bodyrange = MathAbs(iClose(NULL, 0, 1) - iOpen(NULL, 0, 1));
   double barrange = (iHigh(NULL, 0, 1) - iLow(NULL, 0, 1));
   
   double low = iLow(NULL, PERIOD_D1, 1);
   double low2 = iLow(NULL,0,periodlowest1);
   double stoploss= Bid+(Bid*stoplosspercent/100);
   
   if (OrdersTotal()==0)
    { Print("numero di ordini sotto lo zero SHORT");
      if (TimeCurrent() >= StringToTime(TimeToString(TimeCurrent(),TIME_DATE)+" "+StartTime) && TimeCurrent() < StringToTime(TimeToString(TimeCurrent(),TIME_DATE)+" "+EndTime)
         && close < low2 )
   
     
     
    
        
     {
      range_sl = stoploss - Bid ; //32 invece di 3200
      tp = Bid - (range_sl * multiplier);
      sl = stoploss;
      return true;
     }
     }
   return false;
  }
//+------------------------------------------------------------------+
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);
   }
   

in the picture i attached how ea do 

Reason: