Search code examples
algorithmic-tradingexpert-systemmql5forexmetatrader5

Adding a trailing Stop loss to an expert advisor using MQL5


Hi I'm new to MQL5 and I wanted to add a trailing stop loss to my expert advisor but some reason it does not add. Here is the code:

 if(PositionSelect(_Symbol) && UseTrailingStop == true)
  {
   double TrailingStop = (atr[1] * 3) + close[1];
   Trail.TrailingStop(_Symbol,TrailingStop,0,0);
  } 

Please note that close[1] is for the close price of the previous bar and atr[1] is for the value of the average true range. What am i doing wrong?????


Solution

  • There you go: hope this is helpful.

    //--- trailing position  
       for(i=0;i<PositionsTotal();i++)
         {
          if(Symbol()==PositionGetSymbol(i))
            {
             if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
               {
                sl=MathMax(PositionGetDouble(POSITION_PRICE_OPEN)+Spread*_Point,Bid-SL*_Point);
    
                if(sl>PositionGetDouble(POSITION_SL) && (Bid-StopLevel*_Point-Spread*_Point)>PositionGetDouble(POSITION_PRICE_OPEN))
                  {
                   request.action = TRADE_ACTION_SLTP;
                   request.symbol = _Symbol;
                   request.sl = NormalizeDouble(sl,_Digits);
                   request.tp = PositionGetDouble(POSITION_TP);
                   OrderSend(request,result);
                   if(result.retcode==10009 || result.retcode==10008) // request executed
                      Print("Moving Stop Loss of Buy position #",request.order);
                   else
                     {
                      Print(ResultRetcodeDescription(result.retcode));
                      return;
                     }
                   return;
                  }
               }
    
             if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
               {
                sl=MathMin(PositionGetDouble(POSITION_PRICE_OPEN)-Spread*_Point,Ask+SL*_Point);
    
                if(sl<PositionGetDouble(POSITION_SL) && (PositionGetDouble(POSITION_PRICE_OPEN)-StopLevel*_Point-Spread*_Point)>Ask)
                  {
                   request.action = TRADE_ACTION_SLTP;
                   request.symbol = _Symbol;
                   request.sl = NormalizeDouble(sl,_Digits);
                   request.tp = PositionGetDouble(POSITION_TP);
                   OrderSend(request,result);
                   if(result.retcode==10009 || result.retcode==10008) // request executed
                      Print("Moving Stop Loss of Sell position #",request.order);
                   else
                     {
                      Print(ResultRetcodeDescription(result.retcode));
                      return;
                     }
                   return;
                  }
               }
            }
         }