Lógica de aprendizaje - página 14

 

Código alternativo:

// заменяем кучу одинаковых переменных на массивы -- 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:

Código alternativo:


if(índice>0 || índice>8) devuelve (-1);

Quizás if(index < 0 || ...) ...; ?

 
Sí. Corregido, gracias.
 
TheXpert:

La segunda versión del código es realmente mejor... y más bonita

--

Es cierto... cuando es más difícil mantener un código de tamaño optimizado que uno borroso.

es decir, escribir más ampliamente es a veces más fácil de mantener...

--

En SQL está al revés... optimización del código


ponerlo en una sola consulta incluso duele


lo que es interesante ...

por ejemplo, el código SQL de una consulta compleja es más difícil de leer que unas cuantas consultas SQL sucesivas

y, por extraño que parezca, el rendimiento de tres consultas simples suele ser mejor que el de una consulta compleja (aparentemente optimizada)


La lógica de los que escriben consultas SQL complejas... sufre... sólo porque...

1 - inconveniente para el mantenimiento

2-funcionamiento más lento

--

no se aplican a su código

eso es sólo por experiencia...

 

Aquí hay algo que me gustó mucho... Tomado del hilo de Igor Kim, su primer código:

//+------------------------------------------------------------------+
//| Возвращает интервал установки сигнальных указателей              |
//+------------------------------------------------------------------+
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);
  }
}

... y su segundo:

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. 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);
}
¿Cómo es? A mí personalmente me ha gustado... :))
 

Hizo un indicador. Pero cuando ZZCount>1 el terminal se cuelga. Parece que no hay errores.

¿Tal vez alguien encuentre la causa?

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


Tú también puedes ser un anciano.

¡Muchas gracias!

 

A veces es necesario ordenar los datos en MQL4 sin tocar los datos mismos. No hay punteros en MQL4, y tampoco hay estructuras.

He aquí un ejemplo de un script que ordena los datos por diferentes parámetros mediante la emulación de punteros. Tal vez, alguien encuentre útil este enfoque y la función de clasificación.

#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;
}

El resultado del trabajo:

 
Gracias, lo haré...