Lógica de aprendizagem - 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(index>0 || index>8) retorno (-1);

Talvez se(índice < 0 || ...) ...; ?

 
Sim. Corrigido, obrigado.
 
TheXpert:

A segunda versão do código é realmente melhor ... e mais bonita

--

É verdade ... quando é mais difícil manter um código de tamanho otimizado do que um código borrado.

ou seja, escrever de forma mais ampla às vezes é mais fácil de manter...

--

Em SQL está de cabeça para baixo... otimização de código


colocá-lo em uma única consulta até dói


o que é interessante ...

por exemplo, o código SQL de uma consulta complexa é mais difícil de ler do que algumas consultas SQL sucessivas

e por mais estranho que possa parecer, o desempenho de três consultas simples é frequentemente melhor do que o desempenho de uma consulta complexa (aparentemente otimizada)


A lógica daqueles que escrevem consultas SQL complexas... sofre... só porque...

1 - inconveniente para manter

2-baixo trabalho

--

não se aplique ao seu código

isso é apenas por experiência...

 

Eis algo que eu gostei muito... Extraído do fio do Igor Kim, seu primeiro 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);
  }
}

... e sua segunda:

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. 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);
}
Como é isso? Isso me agradou pessoalmente... :))
 

Feito um indicador. Mas quando ZZCount>1 o terminal desliga. Parece que não há erros.

Talvez alguém encontre a causa?

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


Você também pode ser um homem velho.

Muito obrigado!

 

Às vezes é necessário classificar os dados na MQL4 sem tocar nos próprios dados. Não há indicadores na MQL4, e também não há estruturas.

Aqui está um exemplo de um roteiro que ordena os dados por diferentes parâmetros através da emulação de ponteiros. Talvez alguém ache útil esta abordagem e a função de classificação.

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

O resultado do trabalho:

 
Obrigado, eu vou...