Partial Take Profit

 

Dear Community

I'm trying to perform a partial stop loss for each position. I try to check if the initial order that opened the position has got the same volume as the position itself. 
The order and the position should have the same ticket right?
If that is true, the position shall be partially closed. Somehow my function doesn't do anything at all. Could you have a look at the code and tell me if I made a mistake?

Thanks in advance!


void TakeProfitFunction(bool UseTP1,int TPDivisor1,int ATRHandle1, double TPATRMultiplier1)
{
if(UseTP1==true&&PositionsTotal()>0)
  {
   CTrade TPTrade;
   ulong tick;
   
   double ATRArray1[];
   CopyBuffer(ATRHandle1,0,0,2,ATRArray1);
   ArraySetAsSeries(ATRArray1,true);
   
   for (int i=0; i<PositionsTotal();i++)
      {
      tick=PositionGetTicket(i);
      PositionSelectByTicket(tick);
      OrderSelect(tick);
      
      if(OrderGetDouble(ORDER_VOLUME_INITIAL)==PositionGetDouble(POSITION_VOLUME) 
         && PositionGetInteger(POSITION_TYPE)==0 
         && (PositionGetDouble(POSITION_PRICE_OPEN)+(ATRArray1[1]*TPATRMultiplier1))<=SymbolInfoDouble(_Symbol,SYMBOL_BID) )
        {        
         double Vol=PositionGetDouble(POSITION_VOLUME);
         double CloseVol = NormalizeDouble(Vol/TPDivisor1,2);
         TPTrade.PositionClosePartial(tick,CloseVol,-1);              
        }

      if(OrderGetDouble(ORDER_VOLUME_INITIAL)==PositionGetDouble(POSITION_VOLUME)
         && PositionGetInteger(POSITION_TYPE)==1
         && (PositionGetDouble(POSITION_PRICE_OPEN)-(ATRArray1[1]*TPATRMultiplier1))>=SymbolInfoDouble(_Symbol,SYMBOL_ASK) )
        {        
         double Vol=PositionGetDouble(POSITION_VOLUME);
         double CloseVol = NormalizeDouble(Vol/TPDivisor1,2);
         TPTrade.PositionClosePartial(tick,CloseVol,-1);      
        }
   
      }
 }

}


 

 

You need to loop through the history deals to find the ones associated with your position. If the last deal is a Sell while your position is of type Buy, you can say that that was a partial close.

bool IsPartiallyClosed(long pos_id,ENUM_POSITION_TYPE pos_type)
  {
   HistorySelect(TimeCurrent()-24*60*60,TimeCurrent()); // last 24 hours
   int deals=HistoryDealsTotal();
   ENUM_DEAL_TYPE last_effective_deal=(pos_type==POSITION_TYPE_BUY ? DEAL_TYPE_BUY : DEAL_TYPE_SELL);

   for(int i=deals-1;i>=0;i--)
     {
      ulong deal_ticket=HistoryDealGetTicket(i);
      if(HistoryDealGetInteger(deal_ticket,DEAL_POSITION_ID)!=pos_id) continue;
      ENUM_DEAL_TYPE deal_type=(ENUM_DEAL_TYPE)HistoryDealGetInteger(deal_ticket,DEAL_TYPE);
      if(deal_type==DEAL_TYPE_BUY || deal_type==DEAL_TYPE_SELL) { last_effective_deal=deal_type; break; }
     }
   return (last_effective_deal==DEAL_TYPE_BUY) != (pos_type==POSITION_TYPE_BUY);
  }
The position id and type can be retrieved with the position ticket.
Reason: