Close Position by profit

shelvio massaete  

Hi

I have this code to close position when reach a specific profit(0.50) e loss(-10) buy when i run strategy tester i get profits like 2,3,4 and losses like -23,-12

Can someone help me, 


  double TargetLoss=-10;
  double TargetProfit=0.50;
  double profit=AccountInfoDouble(ACCOUNT_EQUITY)-AccountInfoDouble(ACCOUNT_BALANCE);
   bool isProfit=profit>=TargetProfit;
   bool isLoss=profit<=TargetLoss;
  if(isProfit || isLoss)
    {
    for(int i=PositionsTotal()-1;i>=0;i--)
      {
       ulong ticket=PositionGetTicket(i);
       if(PositionSelectByTicket(ticket))
         {
          if(trade.PositionClose(ticket))
            {
             Print(__FUNCTION__,"Closed Succesful");
            }else
               {
                 Print(__FUNCTION__,GetLastError());
               }
            }
        }
   }

   

phade  

try to use PositionGetDouble and constant POSITION_PROFIT to get the profit of the current position

/zh/docs/trading/positiongetdouble


double TargetLoss = -10;
double TargetProfit = 0.50;

for (int i = PositionsTotal() - 1; i >= 0; i--)
{
    ulong ticket = PositionGetTicket(i);
    if (PositionSelectByTicket(ticket))
    {
        double positionProfit = PositionGetDouble(POSITION_PROFIT);

        if (positionProfit >= TargetProfit || positionProfit <= TargetLoss)
        {
            if (trade.PositionClose(ticket))
            {
                Print(__FUNCTION__, " Closed Successfully");
            }
            else
            {
                Print(__FUNCTION__, " Error closing position: ", GetLastError());
            }
        }
    }
}


Don't need to do:

  double profit=AccountInfoDouble(ACCOUNT_EQUITY)-AccountInfoDouble(ACCOUNT_BALANCE);
Documentation on MQL5: Trade Functions / PositionGetDouble
Documentation on MQL5: Trade Functions / PositionGetDouble
  • www.mql5.com
PositionGetDouble - Trade Functions - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Reason: