Questions from Beginners MQL4 MT4 MetaTrader 4 - page 58

 
I want to learn how to write code myself... So I thought I'd ask for some advice. I thought maybe someone could give me a sample... Thanks!
 
Stafort:
I want to learn how to write code myself... So I thought I'd ask for some advice. I thought maybe someone could give me a sample... Thank you!
Here you have a lot of samples, pick up the most suitable, and it has edits to fit your needs. If you can not, you can always ask questions on this forum, and get answers.
 
The client complains that the Expert Advisor keeps opening trades even if it was removed from the chart. This cannot be the case, right?
And if you don't remove it from the chart and just close the Expert Advisor window, will it work?
Thank you.
 
Vladimir Tkach:
The client complains that the Expert Advisor keeps opening trades even if it has been removed from the chart. This cannot be the case, right?
And if you don't remove it from the chart and just close the Expert Advisor window, will it work?
Thank you.

If deleted and written correctly, it should not. Unloading with deinitialization code - 1. If the Expert Advisor latches... We have to deal with it...

If you close the EA window, the EA will be unloaded with deinitialization code - 4:

REASON_CHARTCLOSE

4

Chart is closed


https://www.mql5.com/ru/docs/constants/namedconstants/uninit

Документация по MQL5: Стандартные константы, перечисления и структуры / Именованные константы / Причины деинициализации
Документация по MQL5: Стандартные константы, перечисления и структуры / Именованные константы / Причины деинициализации
  • www.mql5.com
Стандартные константы, перечисления и структуры / Именованные константы / Причины деинициализации - справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
MONTE_CRISTO:
Well, that's right, there are metaquote quotes there, as far as I remember, and Tickstory is of good quality.
If you open an account with a brokerage company with MT5, the quotes will be "not torn", what is the question? I've never learned how to prepare them, while with MT5 it's easier and faster to export.
 
Sergey Gritsay:
At least a screenshot to understand what rows you want to merge
Sergey Gritsay:
At least a screenshot to understand what rows you want to merge.
Sergey Gritsay:
At least a screenshot to understand what kind of lines you want to combine. Thank you for your reply! I want to join two upper tool rows into one on MT4.
 

What could the red colour of the variable dT mean?


 
Andrei:

What could the red colour of the variable dT mean?


is declared as an "extern" input variable
 
Folks, a hint. Tester gives error: 2017.02.08 18:24:43.751 TestGenerator: unmatched data error (low value 1.09860 at 2016.07.27 19:30 is not reached from the lowest timeframe, low price 1.09880 mismatches)
What does this mean and how can it be fixed? What have I done wrong?
double Margin_Percent=AccountFreeMargin()*Percent/100; //Используемые средства для открытия ордеров
double Lots=Margin_Percent/MarketInfo(Symbol(),MODE_MARGINREQUIRED);//Определение общего количества лотов
double Lots_Volume=(MathFloor(Lots)+MarketInfo(Symbol(),MODE_LOTSTEP));
double MacdCurrent=iMACD(NULL,0,Fast_EMA_Period,Slow_EMA_Period,Signal_Period,PRICE_CLOSE,MODE_MAIN,1); //Параметры MACD основной линии текущего бара
double MacdPrevious1=iMACD(NULL,0,Fast_EMA_Period,Slow_EMA_Period,Signal_Period,PRICE_CLOSE,MODE_MAIN,2);//Параметры MACD основной линии предыдущего бара
double MacdPrevious2=iMACD(NULL,0,Fast_EMA_Period,Slow_EMA_Period,Signal_Period,PRICE_CLOSE,MODE_MAIN,3);//Параметры MACD основной линии со смещением на 2 бара
double StopLoss=iSAR(NULL,0,Step_PSAR,Maximum_PSAR,0);//Параметры Трейлинг стоп по параметрам ParabolicSAR текущего бара
double Previous_StopLoss=iSAR(NULL,0,Step_PSAR,Maximum_PSAR,1);//Параметры СтопЛосс по параметрам ParabolicSAR предыдущего бара
double CurrentPSAR=iSAR(NULL,0,Step_PSAR,Maximum_PSAR,1);//Параметры СтопЛосс по параметрам ParabolicSAR предыдущего бара
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   static datetime New_Time=TimeCurrent();// Время текущего бара
   bool New_Bar=false;                    // Флаг нового бара
   int ticket,total,cnt;
//---------------------------------------------------------------------------
   total=OrdersTotal();// Опредление количства ордеров
   if(total<1)
     {
      //--- нет открытых ордеров
      if(Margin_Percent<MarketInfo(Symbol(),MODE_MARGINREQUIRED)*(MarketInfo(Symbol(),MODE_MINLOT)))
         //Проверка на наличие денежных средств для открытия минимального лота
        {
         Print("Не хватает средств. Свободные средства = ",AccountFreeMargin());
         return;
        }
      if(Time[0]==New_Time) // Сравниваем время
        {
         New_Bar=true;      // Поймался новый бар
         if(New_Bar==false)    // Если бар не новый..
            return;            // ..то уходим  
        }
      //Определение количества лотов
      if(Lots>Lots_Volume)
         Lots=Lots_Volume;
      else if(Lots<Lots_Volume)
         Lots=MathFloor(Lots);
      return;
      //--- условие для открытия длинной позиции (BUY)
      if(CurrentPSAR<iOpen(NULL,0,1) &&
         ((MacdPrevious1>0 && MacdPrevious2<0) ||
         (MacdCurrent>0 && MacdPrevious1<0) ||
         (MacdCurrent>0 && MacdPrevious1==0 && MacdPrevious2<0)||
         (MacdCurrent>0 && MacdPrevious1==0 && MacdPrevious2==0)))
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,StopLoss+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,0,NULL,MAGICNUMBER,0,Green);
         if(ticket>0)//проверка отрытия позиции
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
               Print("BUY ордер открыт : ",OrderOpenPrice());
            else Print("Ошибка открытия ордера BUY : ",GetLastError());
            return;
           }
        }
      //--- условие для открытия короткой позиции (SELL)
      if(CurrentPSAR>iOpen(NULL,0,1) &&
         ((MacdCurrent<0 && MacdPrevious1>0) ||
         (MacdPrevious1<0 && MacdPrevious2>0) ||
         (MacdCurrent<0 && MacdPrevious1<0 && MacdPrevious2>0) ||
         (MacdCurrent<0 && MacdPrevious1==0 && MacdPrevious2==0)))
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,StopLoss-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,0,NULL,MAGICNUMBER,0,Red);
         if(ticket>0)//проверка открытия позиции
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
               Print("SELL ордер открыт : ",OrderOpenPrice());
            else Print("Ошибка открытия ордера SELL : ",GetLastError());
            return;
           }
        }
      return; //--- выход из блока "нет открытых ордеров"
     }
//--- важно правильно войти в рынок, но более важно правильно из него выйти  
   for(cnt=0;cnt<total;cnt++)
     {
      if(!OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
         continue;
      if(OrderMagicNumber()==MAGICNUMBER && // проверка магического номера ордера
         OrderSymbol()==Symbol()) // проверка символа ордера
        {
         //--- длинная позиция открыта
         if(OrderType()==OP_BUY)
           {
            //--- должен быть закрыт?
            if(CurrentPSAR>iOpen(NULL,0,1) &&
               ((MacdCurrent<0 && MacdPrevious1>0) ||
               (MacdPrevious1<0 && MacdPrevious2>0) ||
               (MacdCurrent<0 && MacdPrevious1<0 && MacdPrevious2>0) ||
               (MacdCurrent<0 && MacdPrevious1==0 && MacdPrevious2==0)))
              {
               //--- закрытие ордера и выход
               if(OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet))
                 {
                  Print("Ордер закрыт");
                  ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,StopLoss-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,0,NULL,MAGICNUMBER,0,Red);
                  if(ticket>0)//проверка открытия позиции
                    {
                     if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                        Print("SELL ордер открыт : ",OrderOpenPrice());
                     else Print("Ошибка открытия ордера SELL : ",GetLastError());
                     return;
                    }
                 }
              else Print("Ошибка закрытия ордера ",GetLastError());

              }
            //------------------Модификация ордера по СтопЛоссу
            else if(StopLoss>Previous_StopLoss && StopLoss<iOpen(NULL,0,0))
              {
               if(OrderModify(OrderTicket(),OrderOpenPrice(),StopLoss+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,0,0,Blue))
                  Print("Цена Stop Loss ордера успешно модифицирована.");
               else Print("Ошибка модификации ордера. Код ошибки=",GetLastError());
               return;
              }
            return;
           }
         // идём на короткую позицию
         else if(OrderType()==OP_SELL)
           {
            //--- должен быть закрыт?
            if(CurrentPSAR<iOpen(NULL,0,1) &&
               ((MacdPrevious1>0 && MacdPrevious2<0) ||
               (MacdCurrent>0 && MacdPrevious1<0) ||
               (MacdCurrent>0 && MacdPrevious1==0 && MacdPrevious2<0)||
               (MacdCurrent>0 && MacdPrevious1==0 && MacdPrevious2==0)))
              {
               //--- закрытие ордера и выход
               if(OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet))
                 {
                  Print("Ордер закрыт");
                  ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,StopLoss+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,0,NULL,MAGICNUMBER,0,Green);
                  if(ticket>0)//проверка отрытия позиции
                    {
                     if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
                        Print("BUY ордер открыт : ",OrderOpenPrice());
                     else Print("Ошибка открытия ордера BUY : ",GetLastError());
                     return;
                    }
                 }
               else Print("Ошибка закрытия ордера ",GetLastError());
              }
            //-----------------Модификация ордера по СтопЛоссу            
            else if(StopLoss<Previous_StopLoss && StopLoss>iOpen(NULL,0,0))
              {
               if(OrderModify(OrderTicket(),OrderOpenPrice(),StopLoss-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,0,0,Blue))
                  Print("Цена Stop Loss ордера успешно модифицирована.");
               else Print("Ошибка модификации ордера. Код ошибки=",GetLastError());
               return;
              }
           }
        }
     }
//------
  }
//-------------------------------------------------------------------------------------------------------
 
Michail_David:
Folks, a hint. Tester gives error: 2017.02.08 18:24:43.751 TestGenerator: unmatched data error (low value 1.09860 at 2016.07.27 19:30 is not reached from the lowest timeframe, low price 1.09880 mismatches)
What does this mean and how can it be fixed? What have I done wrong?
It's the quotes, they are of poor quality.
Reason: