mql5

Trailing stoploss mq5


Ive been working on setting a trailing stop 10pips above the current price and it doesnt seem to be working

i want it to firstly update after 15pips to 5pips above entry then scaling up

void ApplyTrailingStop(string symbol, int magicNumber, double stopLoss)
{
   static int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);   
   // trailing from close prices 
   double buyStopLoss = NormalizeDouble(SymbolInfoDouble(symbol, SYMBOL_BID)-stopLoss, digits);
   double sellStopLoss = NormalizeDouble(SymbolInfoDouble(symbol, SYMBOL_ASK)+stopLoss, digits);
      
   int count=PositionsTotal();
   for (int i=count-1; i>=0; i--)
   {
      ulong ticket = PositionGetTicket(i);
      if (ticket>0)
      {
         if (PositionGetString(POSITION_SYMBOL)==symbol && PositionGetInteger(POSITION_MAGIC)==InpMagicnumber)
         {
            if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY && buyStopLoss>PositionGetDouble(POSITION_PRICE_OPEN)
                  && (PositionGetDouble(POSITION_SL)==0 || buyStopLoss>PositionGetDouble(POSITION_SL)))
            {
               trade.PositionModify(ticket, buyStopLoss, PositionGetDouble(POSITION_TP));
            }
            else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL && sellStopLoss<PositionGetDouble(POSITION_PRICE_OPEN)
                        && (PositionGetDouble(POSITION_SL)==0 || sellStopLoss<PositionGetDouble(POSITION_SL)))
            {
                      trade.PositionModify(ticket, sellStopLoss, PositionGetDouble(POSITION_TP));
            }
         }
      }
   }
}

Solution

  • If I would face this kind of problem, I would focus on one side (e.g. BUY) and break up that if statement by printing out the expected result for each step. So:

    `
    
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY) Print("We have a BUY position"`);
    

    And:

       if(Buy Stop Loss>PositionGetDouble(POSITION_SL))
        PrintFormat("buyStopLoss %g > PositionGetDouble(POSITION_SL) %g",buyStopLoss,PositionGetDouble(POSITION_SL)));
    

    And so on.