Learning logic - page 14

 

Alternate code:

// заменяем кучу одинаковых переменных на массивы -- 9 -- количество таймфреймов

bool TrBBTurnUP[9];
bool TrBBTurnDN[9];

bool TrMomTurnUP[9];
bool TrMomTurnDN[9];

int TimeFrames[9] = {1, 5, 15, 30, 60, 240, 1440, 10080, 43200};

int init()
{
   // не забываем инициализировать
   ArrayInitialize(TrBBTurnUP, false);
   ArrayInitialize(TrBBTurnDN, false);

   ArrayInitialize(TrMomTurnUP, false);
   ArrayInitialize(TrMomTurnDN, false);
}

int GetTFIndex(int TF)
{
   switch (TF)
   {
      case 1:     return (0);
      case 5:     return (1);
      case 15:    return (2);
      case 30:    return (3);
      case 60:    return (4);
      case 240:   return (5);
      case 1440:  return (6);
      case 10080: return (7);
      case 43200: return (8);
   }
   return (-1);
}

// обратное преобразование
int GetTFByIndex(int index)
{
   if (index < 0 || index > 8) return (-1);
   return (TimeFrames[index]);
}

int AnaliseFunc (string sy, int tf)
{
   CurAsk = MarketInfo(Symbol(), MODE_ASK);
   CurBid = MarketInfo(Symbol(), MODE_BID);
   
   OpnPrice = iOpen(NULL, PERIOD_M5, 0);
   OpnPrice1 = iOpen(NULL, PERIOD_M5, 1);
   ClsPrice1 = iClose(NULL, PERIOD_M5, 1);
   
   if (sy=="" || sy=="0") sy = Symbol();

   // лучше каждую переменную объявить отдельно, особенно если сразу есть присвоение.
   // так будет сразу видно какого типа переменная

   double BB_1  = iCustom(sy, tf, "BB_MA", 13, 1, 1, 1);
   double BB_2  = iCustom(sy, tf, "BB_MA", 13, 1, 1, 2);
   double BB_3  = iCustom(sy, tf, "BB_MA", 13, 1, 1, 3);
   
   double AO1   = iAO(sy, tf, 1);
   double AO2   = iAO(sy, tf, 2);
   double AO3   = iAO(sy, tf, 3);
   
   double AC1   = NormalizeDouble(iAC(sy, tf, 1), 8)*1000;
   double AC2   = NormalizeDouble(iAC(sy, tf, 2), 8)*1000;
   double AC3   = NormalizeDouble(iAC(sy, tf, 3), 8)*1000;
   double AC4   = NormalizeDouble(iAC(sy, tf, 4), 8)*1000;
   double AC5   = NormalizeDouble(iAC(sy, tf, 5), 8)*1000;
   
   double SpMan1= iCustom(sy, tf, "SpearmanRankCorr", 14, 1000, 30, true, 0, 1);
   double SpMan2= iCustom(sy, tf, "SpearmanRankCorr", 14, 1000, 30, true, 0, 2);
   
   double DeM_1 = iDeMarker(sy, tf, 14, 1);
   double DeM_2 = iDeMarker(sy, tf, 14, 2);
   
   double Mom_1 = iMomentum(sy, tf, 14, PRICE_CLOSE, 1);
   double Mom_2 = iMomentum(sy, tf, 14, PRICE_CLOSE, 2);
   double Mom_3 = iMomentum(sy, tf, 14, PRICE_CLOSE, 3);
   
   // прямой доступ по индексу всегда быстрее перебора значений. Здесь мы перебираем один раз -- когда ищем индекс ТФ
   int TFIndex = GetTFIndex(tf);
   if (TFIndex == -1)
   {
      Print("Wrong TF as parameter: ", tf);
      return (0);
   }

//---------------- Проверка на разворот BB_MA -------------------------------------------------------   
   
   if (BB_1>BB_2 && BB_2<=BB_3 && BB_1<0)                               // Найден разворот BB вверх
   {
      TrBBTurnUP[TFIndex] = true;
      TrBBTurnDN[TFIndex] = false;
   }

   if (BB_1<BB_2 && BB_2>=BB_3 && BB_1>0)                               // Найден разворот BB вниз
   {
      TrBBTurnUP[TFIndex] = false;
      TrBBTurnDN[TFIndex] = true;
   }
   
//---------------------- Проверка на разворот Momentum -----------------------------------------------
   
   if (Mom_1>Mom_2 && Mom_2<=Mom_3 && Mom_1<100.0)
   {
      TrMomTurnUP[TFIndex] = true;
      TrMomTurnDN[TFIndex] = false;
   }
      
   if (Mom_1<Mom_2 && Mom_2>=Mom_3 && Mom_1>100.0)
   {
      TrMomTurnUP[TFIndex] = false;
      TrMomTurnDN[TFIndex] = true;
   }
}
 
TheXpert:

Alternate code:


if(index>0 || index>8) return (-1);

Maybe if(index < 0 || ...) ...; ?

 
Yes. Corrected, thank you.
 
TheXpert:

The second version of the code is really better ... and prettier

--

It's true ... when it's harder to maintain a size-optimized code than a blurry one.

i.e., written more broadly is sometimes easier to maintain...

--

In SQL it's upside down... code optimization


putting it into a single query even hurts


what's interesting ...

for example the SQL code of one complex query is harder to read than a few successive SQL queries

and as strange as it may seem, the performance of three simple queries is often better than the performance of one complex (seemingly optimized) query


The logic of those who write complex SQL queries... suffers... just because...

1 - inconvenient to maintain

2-slower working

--

don't apply to your code

that's just from experience...

 

Here's something I liked a lot... Taken from Igor Kim's thread, his first code:

//+------------------------------------------------------------------+
//| Возвращает интервал установки сигнальных указателей              |
//+------------------------------------------------------------------+
int GetArrowInterval() {
  int p = Period();

  switch (p) {
    case 1:     return(4);
    case 5:     return(5);
    case 15:    return(6);
    case 30:    return(8);
    case 60:    return(10);
    case 240:   return(20);
    case 1440:  return(40);
    case 10080: return(80);
    case 43200: return(150);
  }
}

... and his second:

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 12.10.2007                                                     |
//+----------------------------------------------------------------------------+
//|  Описание : Возвращает интервал установки сигнальных указателей            |
//|  Параметры:                                                                |
//|    pr - процент относительно ценового размера окна                         |
//+----------------------------------------------------------------------------+
int GetArrowInterval(int pr=7) {
  if (pr<=0) pr=7;
  return((WindowPriceMax()-WindowPriceMin())/100*pr/Point);
}
How is it? It pleased me personally... :))
 

Made an indicator. But when ZZCount>1 the terminal hangs up. It seems that there are no errors.

Maybe someone will find the cause?

Files:
 
for (int j=0;   i   <ZZCount;j++) {
 
TheXpert:


You can be an old man, too.

Thank you very much!

 

Sometimes you need to sort the data in MQL4 without touching the data itself. There are no pointers in MQL4, and there are no structures either.

Here is an example of a script that sorts data by different parameters through emulation of pointers. Perhaps, someone will find this approach and the sorting function useful.

#define AMOUNT 5

string Symbols[AMOUNT] = {"EURUSD", "GBPUSD", "USDJPY", "USDCHF", "EURGBP"};
int Profit[AMOUNT] = {50, -130, 90, 2000, 0};
int Pos[AMOUNT] = {3, 0, 6, 7, 1};
int SL[AMOUNT] = {20, 60, 10, 80, 100};

void SortArrayINT( int Array[], int& Positions[], bool Increase = TRUE )
{
  int i, j, Tmp, Size = ArraySize(Array);
    
  if (ArraySize(Positions) != Size)
    ArrayResize(Positions, Size);
  
  for (i = 0; i < Size; i++)
    Positions[i] = i;

  if (Increase)
  {
    for (i = 0; i < Size - 1; i++)
      for (j = i + 1; j < Size; j++)
        if (Array[Positions[i]] > Array[Positions[j]])
        {
          Tmp = Positions[j];
          Positions[j] = Positions[i];
          Positions[i] = Tmp;
        }
  }
  else 
    for (i = 0; i < Size - 1; i++)
      for (j = i + 1; j < Size; j++)
        if (Array[Positions[i]] < Array[Positions[j]])
        {
          Tmp = Positions[j];
          Positions[j] = Positions[i];
          Positions[i] = Tmp;
        }
    
  
  return;
}

void PrintInfo( string SortName, int Array[] )
{
  int Positions[];
  
  SortArrayINT(Array, Positions);
  
  Print("Sort by " + SortName);
  Print("SYMBOL   PROFIT   POS   SL");

  for (int i = 0; i < AMOUNT; i++)
    Print(Symbols[Positions[i]] + "   " + Profit[Positions[i]] + "   " +
          Pos[Positions[i]] + "   " + SL[Positions[i]]);
          
  Print("");
          
  return;
}

void start()
{
  PrintInfo("PROFIT", Profit); // распечатали данные, отсортированные по параметру Profit
  PrintInfo("POS", Pos); // распечатали данные, отсортированные по параметру Pos
  PrintInfo("SL", SL); // распечатали данные, отсортированные по параметру SL
  
  return;
}

The result of the work:

 
Thank you, I will...