Logica di apprendimento - pagina 14

 

Codice 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:

Codice alternativo:


se(indice>0 || indice>8) ritorna (-1);

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

 
Sì, corretto, grazie.
 
TheXpert:

La seconda versione del codice è davvero migliore... e più bella

--

È vero... quando è più difficile mantenere un codice ottimizzato per le dimensioni che uno sfocato.

cioè, scritto in modo più ampio è a volte più facile da mantenere...

--

In SQL è al contrario... ottimizzazione del codice


metterlo in una singola query fa addirittura male


quello che è interessante ...

per esempio il codice SQL di una query complessa è più difficile da leggere di alcune query SQL successive

e per quanto strano possa sembrare, la performance di tre query semplici è spesso migliore di quella di una query complessa (apparentemente ottimizzata)


La logica di coloro che scrivono complesse query SQL... soffre... solo perché...

1 - scomodo da mantenere

2-lento lavoro

--

non si applicano al tuo codice

questo è solo per esperienza...

 

Ecco qualcosa che mi è piaciuto molto... Preso dal thread di Igor Kim, il suo primo codice:

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

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. 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);
}
Com'è? Mi ha fatto piacere personalmente... :))
 

Fatto un indicatore. Ma quando ZZCount>1 il terminale si blocca. Sembra che non ci siano errori.

Forse qualcuno troverà la causa?

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


Anche tu puoi essere un vecchio.

Grazie mille!

 

A volte è necessario ordinare i dati in MQL4 senza toccare i dati stessi. Non ci sono puntatori in MQL4, e non ci sono nemmeno strutture.

Ecco un esempio di uno script che ordina i dati secondo diversi parametri attraverso l'emulazione di puntatori. Forse qualcuno troverà utile questo approccio e la funzione di ordinamento.

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

Il risultato del lavoro:

 
Grazie, lo farò...