Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 145

 
fxsaber:

ArraySort is easy to write for simple structures.

Written by
#include <TypeToBytes.mqh>

template <typename T>
void Swap( T &Value1, T &Value2 )
{
  const T Tmp = Value1;
  
  Value1 = Value2;
  Value2 = Tmp;
}

// Сортировка массива любого простого типа
template <typename T>
bool MyArraySort( T &Array[] )
{
  if (!ArraySort(Array))
  {
    const int Size = ArraySize(Array);
    
    for (int i = 0; i < Size - 1; i++)
    {
      const T Tmp = Array[i];
      
      for (int j = i + 1; j < Size; j++)
        if (_R(Tmp) == Array[j]) // TypeToBytes.mqh
        {
          Swap(Array[i + 1], Array[j]);
          
          i++;
        }
    }      
  }
  
  return(true);
}

// Возвращает количество различных элементов массива, которых не меньше Repeat
template <typename T>
int Strange( const T &InArray[], const int Repeat = 2 )
{
  int Res = 0;  
  
  T Array[];
  
  const int Size = ArraySize(InArray);
  
  if ((ArrayCopy(Array, InArray) == Size) && MyArraySort(Array))
  {    
    int Tmp = 1;
    
    for (int i = 1; i < Size; i++, Tmp++)
      if (_R(Array[i - 1]) != Array[i]) // TypeToBytes.mqh
      {
        if (Tmp >= Repeat)
          Res++;
        
        Tmp = 0;
      }
      
    if (Tmp >= Repeat)    
      Res++;
  }

  return(Res);
}

void OnStart()
{
  int Array[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};  
  const int Size = ArraySize(Array);

  MqlTick Ticks[], NullTick = {0};
  ArrayResize(Ticks, Size);        
  
  for (int i = 0; i < Size; i++)
  {
    Ticks[i] = NullTick;
    
    Ticks[i].time = Array[i];
  }
  
  for (int i = 1; i <= 4; i++)
  {
    Print(Strange(Array, i));
    
    Print(Strange(Ticks, i));
  }
}
 

Good evening, please help me with the EA I have written, if you can call it that.

In general, the EA does what I expected it to do. But there is one strange glitch.

1) In some cases, instead of pending orders it opens first a Sell position with 0.02 lot. Although according to the script it should not. (mistake somewhere). I cannot understand what it is related to, sometimes everything goes fine and sometimes the first one opens a Sell.

Please help with this error. I want to give my EA some general comments on my writings and errors. I have made my first Expert Advisor, judge for sure.

//+------------------------------------------------------------------+
//|                                               ALEXANDROS_001.mq4 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
input double perv_Lot=0.01;
input double  shag1=40;
input double  profit=20;
input double  koredor=10;
input int    magic=907;
input int    slipage=10;
int ret,ORD=0,ic;
//
void OnTick()
  {

//-----ищет цену последнего открытого ордера---------------------------------------------------------------
  double OpenPrice = 0.0;
  
     int    orders=OrdersTotal();    
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol())continue;
        if(  OrderType()==OP_SELL||OrderType()==OP_BUY)
        
           OpenPrice = OrderOpenPrice();
                    break;
        }

//------если нет открытых позиций открывает два отложника------------------------------------------------------
  int kolpos=0;
   for (int pos=0; pos<OrdersTotal(); pos++)
  {
   OrderSelect(pos,SELECT_BY_POS,MODE_TRADES);
   if(OrderSymbol()==Symbol()&&OrderMagicNumber()==magic)
   kolpos++;  
    }
    if (kolpos==0)
    {
    OrderSend(Symbol(),OP_BUYSTOP,perv_Lot,Ask+shag1*Point,slipage,0,0,NULL,magic,0,clrGreen);
    OrderSend(Symbol(),OP_SELLSTOP,perv_Lot,Bid-shag1*Point,slipage,0,0,NULL,magic,0,clrRed);
    }
//--------------определяет если есть открытые позиции---------------------------------------------------------------------  
    int order=0;
   for (int pos=0; pos<OrdersTotal(); pos++)
  {
   OrderSelect(pos,SELECT_BY_POS,MODE_TRADES);
   if(OrderSymbol()==Symbol()&&OrderMagicNumber()==magic)
  
   if(OrderType()==OP_SELL||OrderType()==OP_BUY) //если это продажи или покупки считаем что сделки открыты
  
   order++;
    }
    if(order>0)
//--------------- находит и удаляет отложки.---------------------------------------------------------------
    {
    
    for(ic=OrdersTotal()-1;ic>=0;ic--)
                   {
                  if(OrderSelect(ic,SELECT_BY_POS,MODE_TRADES)==false) continue;
                  if (OrderSymbol()==Symbol())
                  {                  
                  if (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP)//если это отложки то удаляем
                  {
                  ret=OrderDelete(OrderTicket());//удалил отложки
                  }
                  }}
//--------------ищем последний открытый ордер-------------------------------------    
                  for(ic=OrdersTotal()-1;ic>=0;ic--)
                   {
                  if(OrderSelect(ic,SELECT_BY_POS,MODE_TRADES)==false) continue;
                  if (OrderSymbol()==Symbol()&&OrderMagicNumber()==magic&&OrderOpenPrice()==OpenPrice)
                  
                  
                  {
                
                  double minus=NormalizeDouble( Ask-OpenPrice,Digits);
                  double plus= NormalizeDouble(Ask-OpenPrice,Digits);
                  if(Digits==3)
                   {
                    minus=minus*100;
                    plus=plus*100;
                   }
                   if(Digits==5)
                   {
                   minus=minus*10000;
                   plus=plus*10000;
                   }
  //-------------если последний открытый ордер SELL--------------------------------------------------------------                
                  if (OrderType()==OP_SELL)
                  {
                  if(plus<=-profit)
                  {
                  for(int i=OrdersTotal()-1;i>=0;i--)
                  {
                  OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
                  if(OrderType()==OP_BUY)OrderClose(OrderTicket(),OrderLots(),Bid,slipage,0);
                  if(OrderType()==OP_SELL)OrderClose(OrderTicket(),OrderLots(),Ask,slipage,0);
                  }
                  }
//---------------а если цена пошла в минус---------------------------------------------------------------------------                
                 if( minus>=koredor)
                  {
                  double Lot=OrderLots();
                  OrderSend(Symbol(),OP_BUY,Lot*2,Ask,slipage,0,0,NULL,magic,0,clrRed);// открываем BUY с удвоеным лотом
                  }
                  }
                  double minusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                  double plusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                   if(Digits==3)
                   {
                    minusbuy=minusbuy*100;
                    plusbuy=plusbuy*100;
                   }
                   if(Digits==5)
                   {
                   minusbuy=minusbuy*10000;
                   plusbuy=plusbuy*10000;
                   }
//-----------------если последний ордер Buy--------------------------------------------------------------------------------
                  if (OrderType()==OP_BUY)
                  {
                   if(plusbuy>=profit)//-------если цена пошла в плюс-------------------------------------------------------
                  {
                  for(int i=OrdersTotal()-1;i>=0;i--)
                  {
                  OrderSelect(i,SELECT_BY_POS,MODE_TRADES);//---находим и закрываем все открытые ордера--------------------
                  if(OrderType()==OP_BUY)OrderClose(OrderTicket(),OrderLots(),Bid,slipage,0);
                  if(OrderType()==OP_SELL)OrderClose(OrderTicket(),OrderLots(),Ask,slipage,0);
                  }
                  }
//-----------------------------а если цена пошла в минус------------------------------------------------------------------                
                  if(minusbuy<=-koredor)
                  {
                  Comment("Ордеров -",order);
                  double Lot=OrderLots();
                  OrderSend(Symbol(),OP_SELL,Lot*2,Bid,slipage,0,0,NULL,magic,0,clrRed);//открываем ордер SELL с удвоенным лотом----
                  }
                  }
   }}}}

 
Alexandr Nevadovschi:

Good evening, please help with the EA I have written, if you can call it that.

In general, the EA does what I expected it to do. But there is one strange glitch.

1) In some cases, instead of pending orders it opens first a Sell position with 0.02 lot. Although according to the script it should not. (mistake somewhere). I cannot understand what it is related to, sometimes everything goes fine and sometimes the first one opens a Sell.

Please help with this error. I want to give my EA some general comments on my writings and errors. This is my first EA, so please judge severely.


First use the styler (Ctrl +,) and fix all comments that the compiler, there are many.

Then, this:

                  double minusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                  double plusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                   if(Digits==3)
                   {
                    minusbuy=minusbuy*100;
                    plusbuy=plusbuy*100;
                   }
                   if(Digits==5)
                   {
                   minusbuy=minusbuy*10000;
                   plusbuy=plusbuy*10000;
                   }

is easily and effortlessly changed to this:

                  double minusbuy=NormalizeDouble((Ask-OpenPrice)/_Point,Digits);
                  double plusbuy=minusbuy;

Similarly and above the code.

Although, it's not clear why the Ask counts for both buys and sells, and the calculations are done BEFORE the order type is defined. And OpenPrice is somehow too far away to be detected several cycles earlier.

 
Vitalie Postolache:


First, use the styler (Ctrl+,) and fix all comments made by the compiler, there are many.

Then, this:

                  double minusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                  double plusbuy=NormalizeDouble(Ask-OpenPrice,Digits);
                   if(Digits==3)
                   {
                    minusbuy=minusbuy*100;
                    plusbuy=plusbuy*100;
                   }
                   if(Digits==5)
                   {
                   minusbuy=minusbuy*10000;
                   plusbuy=plusbuy*10000;
                   }

easily and effortlessly changes to this:

                  double minusbuy=NormalizeDouble((Ask-OpenPrice)/_Point,Digits);
                  double plusbuy=minusbuy;

Similarly and above by code.

Although it's not clear why the Ask counts for both purchases and sales, and the calculations are done BEFORE the order type is defined. OpenPrice is somehow too far determined and even a few cycles earlier.


Thanks, I'll try to fix it.
 

Greetings. Can you tell me why in testing it says " cannot open file 'E:\MT4-1\Alpari Limited MT4\MQL4\indicators/ Indicator parameters WmiFor.ex4' [2]"?

There is an indicator, it works. https://www.mql5.com/ru/code/10394

#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern string WmiFor             = "Параметры индикатора WmiFor";
extern bool IsTopCorner = true; // Информационный блок в верхнем углу?
extern int Offset = 1; // Смещение исходного образца в барах (для проверки надежности прогноза) [1..]
extern bool IsOffsetStartFixed = true; // Фиксировано ли начало образца
extern bool IsOffsetEndFixed = false; // Фиксирован ли конец образца
extern int PastBars = 24; // Размер образца в барах, который ищется на истории [3..]
extern int ForecastBars = 24; // На сколько баров вперед делать прогноз [1..]
extern int MaxAlts = 5; // Искать указанное кол-во лучших образцов [1..100]
extern bool ShowCloud = true; // Показывать ли облако
extern bool ShowBestPattern = true; // Показывать ли максимально близкий образец
extern bool IsExactTime = true; // Должно ли совпадать время образцов (для учета эффекта сессий)
extern datetime MinDate = D'01.01.2001'; // Минимальная дата образца
extern int PeriodMA = 2; // Периуд сглаженной средней
extern double ScalePercents = 90.0; // Рассматривать только образцы с этим минимальным процентом совпадения
extern color IndicatorCloudColor = Sienna; // Цвет облака похожих вариантов
extern color IndicatorBestPatternColor = DodgerBlue; // Цвет самого похожего образца
extern color IndicatorVLinesColor = Sienna; // Цвет вертикальных линий-границ образца
extern color IndicatorTextColor = MediumBlue; // Цвет текста инф.блока
extern color IndicatorTextWarningColor = Tomato; // Цвет предупреждений в тестовом инф.блоке
extern int XCorner = 5; // Отступ инф.блока индикатора от правой границы графика
extern int YCorner = 5; // Отступ инф.блока индикатора от верхней границы графика
extern string FontName = "Arial"; // Шрифт тестового инф.блока
extern int FontSize = 7; // Размер шрифта тестового инф.блока

double Index0, Index1, Index2, Index3, Index4, Index5;

void OnTick()
  {

Index0 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 0, 3);

Index1 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 1, 3);

Index2 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 2, 3);

Index3 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 3, 3);

Index4 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 4, 3);

Index5 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 5, 3);

Comment ( "0==", DoubleToString(Index0,Digits), "     1==", DoubleToString(Index1,Digits),  "      2==", DoubleToString(Index2,Digits),
"     3==", DoubleToString(Index3,Digits),"     4==", DoubleToString (Index4, Digits), "     5==", DoubleToString (Index5, Digits));
  
  }
//+------------------------------------------------------------------+


 
Andrey Sokolov:

Greetings. Can you tell me why in testing it says " cannot open file 'E:\MT4-1\Alpari Limited MT4\MQL4\indicators/ Indicator parameters WmiFor.ex4' [2]"?

There is an indicator, it works. https://www.mql5.com/ru/code/10394

#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern string WmiFor             = "Параметры индикатора WmiFor";

void OnTick()
  {

Index5 = iCustom(NULL, 0, WmiFor, IsTopCorner, Offset, IsOffsetStartFixed, IsOffsetEndFixed, PastBars, ForecastBars, MaxAlts, ShowCloud, ShowBestPattern, IsExactTime, MinDate, PeriodMA,
ScalePercents, IndicatorCloudColor, IndicatorBestPatternColor, IndicatorVLinesColor, IndicatorTextColor, IndicatorTextWarningColor, XCorner, YCorner, FontName, FontSize, 5, 3);

Comment ( "0==", DoubleToString(Index0,Digits), "     1==", DoubleToString(Index1,Digits),  "      2==", DoubleToString(Index2,Digits),
"     3==", DoubleToString(Index3,Digits),"     4==", DoubleToString (Index4, Digits), "     5==", DoubleToString (Index5, Digits));
  
  }
//+------------------------------------------------------------------+
Read in the documentation about"iCustom", and how to properly access the indicator
 
Vitaly Muzichenko:
Read the documentation about"iCustom", and how to properly access the indicator


Thank you.

I forgot the inverted commas, you loon.

 

Good afternoon!

Help me find out what's wrong. I need to output the price when the line is crossed by a bar. I have written the code.

int start() {

double pr=ObjectGetValueByShift("line",0);

Alert (pr);

return(0);}

line is the name of the line.

This code always shows "0". What's wrong?

 
Kot:

Good afternoon!

Help me find out what's wrong. I need to output the price when the line is crossed by a bar. I have written the code.

int start() {

double pr=ObjectGetValueByShift("line",0);

Alert (pr);

return(0);}

line is the name of the line.

This code always shows "0". What's wrong?


Do you havea Trend line?

And visually goes over(under) the 0 bar, no, check the box in properties, beam.

 

Good afternoon everyone!

Question, on insta when trying to send an order, it says that the stops are wrong.

Here is the line itself:

OrderSend(Symbol(),OP_BUYSTOP,Lots,HiP,3,0,0,NULL,111,0,clrBlue);

Stop Loss and Take Points have 0. If I set a number in Stop Loss, everything is normal.

I don't need Stop Loss. What should I do?

Reason: