Trailing stop и Stop loss.

 

Можно ли добавить в советник Stop loss если в нём уже есть Trailing stop?

Можно ли влепить Stop loss вот сюда?

//+------------------------------------------------------------------+

//|                                   Советник с Trailing stop 2.mq4 |

//|                        Copyright 2022, MetaQuotes Software Corp. |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Copyright 2022, MetaQuotes Software Corp."

#property link      "https://www.mql5.com"

#property version   "1.00"

#property strict


extern double Lots       = 0.1;

extern int TrailingStop  =  30;

extern int TrailingStep  =  10;

extern int Magic         = 123;

extern int Slippage      =5;


//extern int StopL = 21;//Добавил.До этого Работало нормально.


extern int MaPeriod = 20;

extern int MaShift   =1;


double maprice, SL, mapricep, mapricepp;

int timeprev;


//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int Init()

  {

   if(Digits ==3 || Digits == 5)

      TrailingStop *=10;

   TrailingStep *=10;

   Slippage     *=10;

//}


   return(0);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

int deInit()

  {

   return (0);

  }

//+------------------------------------------------------------------+

//| Expert start function                                             |

//+------------------------------------------------------------------+

int CountBuy();

int CountSell();


//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int start()

  {

   if(timeprev == Time[0])

      return (0);

   timeprev = Time [0];//Был один знак равно.

//+------------------------------------------------------------------+

//| Индикаторы. Параметры индикаторов.Start.                          |      |

//+-------------------------------------------------------------------+

//double maprice, SL;

   double MacdC,MacdP,SignalC,SignalP;

   double stohs,stohm,stohs2,stohm2;

   double stc,stp;//----------------------------------------------------ТРЕНДОВЫЙ ИНДИКАТОР.ВЕРНЫЕ ПАРАЕТРЫ.-------------------ОБРАТИТЬ ВНАНИЕ НА ЭТО.

   double ac, ac2, ac3, ac4;

   

// if (OrdersTotal () < 77 )//Будут открываться ордера, если открыто меньше 7 ордеров.                                        //Эксперимент с OrdersTotal.


   stohs = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_SIGNAL,0); //Верные пы араетрСтохастка (Stohatic).

   stohm =iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0);

   stohm2 = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_SIGNAL,1);

   stohs2 = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,1);


   MacdC=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);//Current - текущий

   MacdP=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);//Previous - предидущий

   SignalC=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);//Current - текущий

   SignalP=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);//Previouus - предидущий


   stc = iStdDev(NULL,20,0,0,0,PRICE_CLOSE,0); //-------------------Current StdDev------ТР. ИНД. ВЕРНЫЕ ПАРАЕТРЫ.-------------------------------ЕЩЕ ОДИН ТРЕНДОВЫЙ ИНДИКАТОР.

   stp  = iStdDev(NULL,20,0,0,0,PRICE_CLOSE,1); //------------------Preious StdDev - Предыдущий StdDeV.


   maprice = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 0);//Индикатор Moving Average.Предыдущий.

   mapricep = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 1);//Индикатор Moving Average.Предыдущий.Текущий Moving Average.

  mapricepp = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 2);




   ac =iAC(NULL,0,0);  //AC Current

   ac2= iAC(NULL,0,1);  //AC Previos

   ac3=iAC(NULL,0,2);    //AC PrePreVious

   ac3=iAC(NULL,0,3);    //AC PrePrePreVious

   ac4=iAC(NULL,0,4);    //AC PrePrePreVious

//+---------------------------------------------------------------------+

//| Индикаторы. Параметры индикаторов.End.                              |     |

//+---------------------------------------------------------------------+


 //if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious && 

         //MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MaCurrent>MaPrevious)



//Сonditions for purchase (Long position).

if(CountBuy() + CountSell() ==0 && maprice > mapricep && mapricep > mapricepp && Ask <= Open[0]+5)//ВАЖНО:НЕДНЛЬНЫЙ ТАЙМФРЕЙМ. CAMA > PreviousSMA && PreviousSMA > PrePreviousSMA!

OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "", Magic, 0, Red);//БЫЛО Ask.Добавил Ask-StopL.

//OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "", Magic, 0, Red);//БЫЛО^^^.

//Conditions for sale (Short position).

 if(CountBuy() + CountSell() ==0 && maprice < mapricep && mapricep < mapricepp && Bid >= Open[0]-5) //&& Ask >= Open[0]-4/Чисто я добавлю.Это условие для открытия ордера на продажу.

      OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "", Magic, 0, Red);


   Trailing();



   return(0);

  }

//+------------------------------------------------------------------+

void Trailing()

  {

   for(int i=0; i<OrdersTotal(); i++)

     {

      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

        {

         if(OrderSymbol() == Symbol()&& OrderMagicNumber()== Magic) //ВЕРНУТЬСЯ И ПЕРЕСМОЬРЕТЬ С 18-Й ПО 23-УЮ МИНУТЫ ПРО КОЛ-ВО ФИГУРНЫХ СКОБОК.

           {

            if(OrderType()== OP_BUY)

              {

               if(Bid - OrderOpenPrice()> TrailingStop*Point)//

                 {

                  if(OrderStopLoss() < Bid - (TrailingStop+TrailingStep)*Point)//Было: if(OrderStopLoss() < Bid - (TrailingStop+TrailingStep)*Point)

                    {

                     SL = NormalizeDouble(Bid - TrailingStop*Point, Digits);

                     if(OrderStopLoss() !=SL)

                        OrderModify(OrderTicket(),OrderOpenPrice(), SL, 0, 0);

                    }


                 }

              }

            //if (OrderSend (_Symbol,OP_SELL,Lot,Bid,Slip,NormalizeDouble(Bid+StopL*_Point,_Digits),NormalizeDouble(Bid-TakeP*_Point,_Digits),Com,Magic,0))//<21)

            if(OrderType()== OP_SELL)

              {

               if(OrderOpenPrice() - Ask > TrailingStop*Point)

                 {

                  if(OrderStopLoss() >Ask +(TrailingStop + TrailingStep)*Point)

                     if(OrderStopLoss() >(Ask -SL));

                    {

                     SL = NormalizeDouble(Ask + TrailingStop*Point, Digits);

                     if(OrderStopLoss() != SL)

                        OrderModify(OrderTicket(),OrderOpenPrice(), SL, 0, 0);//ПЕРЕСМОТРЕТЬ С 29-Й МИНУТЫ.

                     //if (OrderSend (_Symbol,OP_BUY,Lot,Ask,Slip,NormalizeDouble(Ask-StopL*_Point,_Digits),NormalizeDouble(Ask+TakeP*_Point,_Digits),Com,Magic,0,Red)>-1)


                    }

                 }

              }

           }

        }

     }

  }

//+------------------------------------------------------------------+

int CountBuy()

  {


   int count = 0;


   for(int i = OrdersTotal() -1; i >=0; i --)

     {

      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

        {

         if(OrderSymbol()== Symbol() && OrderMagicNumber()== Magic && OrderType()==OP_BUY)

            count++;

        }

     }

   return(count);

  }

//+------------------------------------------------------------------+

int CountSell()

  {


   int count = 0;


   for(int i = OrdersTotal() -1; i >=0; i --)

     {

      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

        {

         if(OrderSymbol()== Symbol() && OrderMagicNumber()== Magic && OrderType()== OP_SELL)

            count++;

        }

     }

   return(count);

  }

//+------------------------------------------------------------------+

//+------------------------------------------------------------------+


Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2022.09.09
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 

Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

...

Sergey Golubev, 2020.03.23 16:08

Вставляйте правильно код -

----------------‌

MQL5.community - Памятка пользователя 

Кнопка  Исходный кодпредназначена для вставки исходного кода в текст сообщения. При нажатии появляется пустое окно, в которое необходимо вставить код и далее нажать кнопку Вставить. Для отмены вставки кода необходимо нажать кнопку Отмена.


 

Можно ли добавить в советник Stop loss если в нём уже есть Trailing stop?

Можно ли влепить Stop loss вот сюда?

//+------------------------------------------------------------------+
//|                                   Советник с Trailing stop 2.mq4 |
//|                        Copyright 2022, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern double Lots       = 0.1;
extern int TrailingStop  =  30;
extern int TrailingStep  =  10;
extern int Magic         = 123;
extern int Slippage      =5;

extern int MaPeriod = 20;
extern int MaShift   =1;

double maprice, SL, mapricep, mapricepp;
int timeprev;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int Init()
  {
   if(Digits ==3 || Digits == 5)
      TrailingStop *=10;
   TrailingStep *=10;
   Slippage     *=10;
//}

   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deInit()
  {
   return (0);
  }
//+------------------------------------------------------------------+
//| Expert start function                                             |
//+------------------------------------------------------------------+
int CountBuy();
int CountSell();

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   if(timeprev == Time[0])
      return (0);
   timeprev = Time [0];//Был один знак равно.
//+------------------------------------------------------------------+
//| Индикаторы. Параметры индикаторов.Start.                          |      |
//+-------------------------------------------------------------------+
//double maprice, SL;
   double MacdC,MacdP,SignalC,SignalP;
   double stohs,stohm,stohs2,stohm2;
   double stc,stp;
   double ac, ac2, ac3, ac4;
   

   stohs = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_SIGNAL,0);
   stohm =iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0);
   stohm2 = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_SIGNAL,1);
   stohs2 = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,1);

   MacdC=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdP=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   SignalC=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalP=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);

   stc = iStdDev(NULL,20,0,0,0,PRICE_CLOSE,0); 
   stp  = iStdDev(NULL,20,0,0,0,PRICE_CLOSE,1); 

   maprice = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 0);
   mapricep = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 1);
  mapricepp = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 2);



   ac =iAC(NULL,0,0);  //AC Current
   ac2= iAC(NULL,0,1);  //AC Previos
   ac3=iAC(NULL,0,2);    //AC PrePreVious
   ac3=iAC(NULL,0,3);    //AC PrePrePreVious
   ac4=iAC(NULL,0,4);    //AC PrePrePreVious
//+---------------------------------------------------------------------+
//| Индикаторы. Параметры индикаторов.End.                              |     |
//+---------------------------------------------------------------------+


if(CountBuy() + CountSell() ==0 && maprice > mapricep && mapricep > mapricepp && Ask <= Open[0]+5)
OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "", Magic, 0, Red);
 if(CountBuy() + CountSell() ==0 && maprice < mapricep && mapricep < mapricepp && Bid >= Open[0]-5) 
      OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "", Magic, 0, Red);

   Trailing();


   return(0);
  }
//+------------------------------------------------------------------+
void Trailing()
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol() == Symbol()&& OrderMagicNumber()== Magic) 
           {
            if(OrderType()== OP_BUY)
              {
               if(Bid - OrderOpenPrice()> TrailingStop*Point)//
                 {
                  if(OrderStopLoss() < Bid - (TrailingStop+TrailingStep)*Point)
                    {
                     SL = NormalizeDouble(Bid - TrailingStop*Point, Digits);
                     if(OrderStopLoss() !=SL)
                        OrderModify(OrderTicket(),OrderOpenPrice(), SL, 0, 0);
                    }

                 }
              }
           
            if(OrderType()== OP_SELL)
              {
               if(OrderOpenPrice() - Ask > TrailingStop*Point)
                 {
                  if(OrderStopLoss() >Ask +(TrailingStop + TrailingStep)*Point)
                     if(OrderStopLoss() >(Ask -SL));
                    {
                     SL = NormalizeDouble(Ask + TrailingStop*Point, Digits);
                     if(OrderStopLoss() != SL)
                        OrderModify(OrderTicket(),OrderOpenPrice(), SL, 0, 0);
                    

                    }
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
int CountBuy()
  {

   int count = 0;

   for(int i = OrdersTotal() -1; i >=0; i --)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol()== Symbol() && OrderMagicNumber()== Magic && OrderType()==OP_BUY)
            count++;
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
int CountSell()
  {

   int count = 0;

   for(int i = OrdersTotal() -1; i >=0; i --)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol()== Symbol() && OrderMagicNumber()== Magic && OrderType()== OP_SELL)
            count++;
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
 
Ну и код. Жесть.
 
Vitaly Murlenko #:
Ну и код. Жесть.

нормальный старинный код. Можно сказать местная готика

 

Я его тут малость подправил. Вот код со встроенным СтопЛоссом. Только он депозит всё равно сливает.

//+------------------------------------------------------------------+
//|                                   Советник с Trailing stop 2.mq4 |
//|                        Copyright 2022, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern double Lots       = 0.1;
extern int              StopLoss=20;//SL. Если ноль или меньше, то стоп не ставится.
extern int TrailingStop  =  30;
extern int TrailingStep  =  10;
extern int Magic         = 123;
extern int Slippage      =5;

extern int MaPeriod = 20;
extern int MaShift   =1;

double maprice, SL, mapricep, mapricepp;
int timeprev;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int Init(){
        if(Digits ==3 || Digits == 5){
                TrailingStop *=10;
                TrailingStep *=10;
                Slippage     *=10;
        }
        return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deInit(){
        return (0);
}
//+------------------------------------------------------------------+
//| Expert start function                                            |
//+------------------------------------------------------------------+

int start(){
        if(timeprev == Time[0])
        return (0);
        timeprev = Time[0];//Был один знак равно.
        //+------------------------------------------------------------------+
        //| Индикаторы. Параметры индикаторов.Start.                          |      |
        //+-------------------------------------------------------------------+
        
        double MacdC,MacdP,SignalC,SignalP;
        double stohs,stohm,stohs2,stohm2;
        double stc,stp;
        double ac, ac2, ac3, ac4;
   

        stohs = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_SIGNAL,0);
        stohm =iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0);
        stohm2 = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_SIGNAL,1);
        stohs2 = iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,1);

        MacdC=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
        MacdP=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
        SignalC=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
        SignalP=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);

        stc = iStdDev(NULL,20,0,0,0,PRICE_CLOSE,0); 
        stp  = iStdDev(NULL,20,0,0,0,PRICE_CLOSE,1); 

        maprice = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 0);
        mapricep = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 1);
        mapricepp = iMA(Symbol(), 0, MaPeriod, MaShift, MODE_SMA, PRICE_CLOSE, 2);



        ac =iAC(NULL,0,0);  //AC Current
        ac2= iAC(NULL,0,1);  //AC Previos
        ac3=iAC(NULL,0,2);    //AC PrePreVious
        ac3=iAC(NULL,0,3);    //AC PrePrePreVious
        ac4=iAC(NULL,0,4);    //AC PrePrePreVious
        //+---------------------------------------------------------------------+
        //| Индикаторы. Параметры индикаторов.End.                              |
        //+---------------------------------------------------------------------+


        if(CountBuy() + CountSell() ==0 && maprice > mapricep && mapricep > mapricepp && Ask <= Open[0]+5){
                if(StopLoss<=0){
                        SL=0;
                }
                else{
                        SL=Ask-StopLoss*Point;
                }
                SL=NormalizeDouble(SL,Digits);
                Print("SL Buy = ",SL);
                OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, SL, 0, "", Magic, 0, Red);
        }
        if(CountBuy() + CountSell() ==0 && maprice < mapricep && mapricep < mapricepp && Bid >= Open[0]-5){
                if(StopLoss<=0){
                        SL=0;
                }
                else{
                        SL=Bid+StopLoss*Point;
                }
                SL=NormalizeDouble(SL,Digits);
                Print("SL Sell = ",SL);
                OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, SL, 0, "", Magic, 0, Red);
        }
        Trailing();
        return(0);
}
        
//+------------------------------------------------------------------+
//|               Пользовательские подпрограммы                      |
//+------------------------------------------------------------------+

void Trailing(){
        for(int i=0; i<OrdersTotal(); i++){
                if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
                        if(OrderSymbol() == Symbol()&& OrderMagicNumber()== Magic){
                                if(OrderType()== OP_BUY){
          if(Bid-OrderOpenPrice()> TrailingStop*Point){
            if(OrderStopLoss() < Bid - (TrailingStop+TrailingStep)*Point){
              SL = NormalizeDouble(Bid - TrailingStop*Point, Digits);
              if(OrderStopLoss() !=SL)
                                                                OrderModify(OrderTicket(),OrderOpenPrice(), SL, 0, 0);
                                                }
                                        }
                                }
        if(OrderType()== OP_SELL){
                                        if(OrderOpenPrice()-Ask > TrailingStop*Point){
                                                if(OrderStopLoss()>Ask +(TrailingStop + TrailingStep)*Point){
                                                        SL = NormalizeDouble(Ask + TrailingStop*Point, Digits);
                                                                if(OrderStopLoss() != SL)
                                                                        OrderModify(OrderTicket(),OrderOpenPrice(), SL, 0, 0);
                    

                                                }
                                        }
                                }
                        }
                }
        }
}
//+------------------------------------------------------------------+
int CountBuy(){
        int count = 0;
        for(int i = OrdersTotal() -1; i >=0; i --){
                if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
                        if(OrderSymbol()== Symbol() && OrderMagicNumber()== Magic && OrderType()==OP_BUY)
                                count++;
                }
        }
        return(count);
}
//+------------------------------------------------------------------+
int CountSell(){
        int count = 0;
        for(int i = OrdersTotal() -1; i >=0; i --){
                if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
                        if(OrderSymbol()== Symbol() && OrderMagicNumber()== Magic && OrderType()== OP_SELL)
                                count++;
    }
        }
        return(count);
}
 

Свежак:

#property copyright "Copyright 2022, MetaQuotes Software Corp."
 
Aleksei Stepanenko #:

Свежак:

Судя по этой строчке, именно метаквотесы в исходном коде ошибок понаделали :)

 
Vitaly Murlenko #:

Я его тут малость подправил.

.

 
Aleksei Stepanenko #:

.

От души спасибо :))))

Причина обращения: