Вопросы от "чайника" - страница 253

 
lucky_teapot:

Господа, подскажите плиз, почему у меня тестер использует только половину одного из 4-х ядер проца при тестировании?


При тестировании только 1\8 проца загружно по полной, это не гуд.

Жутко медленно выходит...

Спасибо.

если вы про тест с визуализацией - то это вроде норм

если про одиночный прогон - то для 1 прогона используется 1 процессор

если про тестирование стратегии с множеством проходов, то тут 1 скриншотом ваших процессоров не обойдешься, сделали бы хотя бы скриншот во время тестирования

 

 Первый раз попробовал переделать индикатор из MQL4 в MQL5 по статье на этом форуме, но завершить не могу.

Последние ошибки никак не одолею.

 https://www.mql5.com/ru/articles/66

Подскажите, пожалуйста, чего ему ещё не хватает 

 

//+------------------------------------------------------------------+
//|                                                           FT.mq5 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
//--- plot Fisher
#property indicator_label1  "Fisher"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1

#include <mql4_2_mql5.mqh>
//--- input parameters
input  ENUM_APPLIED_PRICE Mode =PRICE_CLOSE;
input int      StochPeriod=21;
int StochMode = 0;
int SmoothType1 = 3;
int SmoothPeriod1 = 4;
double K = 1;
int SmoothType2 = 3;
int SmoothPeriod2 = 4;
int Buffers = 0;
int DrawBegin = 0;


//--- indicator buffers
double FisherBuffer[];
double Stoch[];
double Value1[];
double F[];

//int init() 
//{
//   if (StochPeriod < 3) 
 //     StochPeriod = 3;
//   drawBegin = StochPeriod;      
  // initBuffer(Fisher, "Fisher", DRAW_LINE);
  // initBuffer(Value1);
   //initBuffer(stoch);
  // initBuffer(f);
  // IndicatorBuffers(buffers);
  // string name = "FT("+PriceMode+","+StochPeriod+","+StochMode+","
  //    +SmoothType1+","+SmoothPeriod1+","
  //    +DoubleToStr(k,2)+","+SmoothType2+","+SmoothPeriod2+")";
  //IndicatorShortName(name);
  // SetIndexLabel(0,name);
 //  return (0);
//}

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,FisherBuffer,INDICATOR_DATA);
SetIndexBuffer(1,Value1,INDICATOR_DATA);
SetIndexBuffer(2,Stoch,INDICATOR_DATA);
SetIndexBuffer(3,F,INDICATOR_DATA);
   
    
InitMql4();

   ArraySetAsSeries(FisherBuffer,true);
ArraySetAsSeries(Value1,true);
ArraySetAsSeries(Stoch,true);
ArraySetAsSeries(F,true);
   
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
  int bars=MQL4Run(rates_total,prev_calculated);
//---
  start(bars,
      CountedMQL4,
      FisherBuffer,
      Stoch,
      Value1,
      F,
      Mode,
      StochPeriod,
      StochMode,
      SmoothType1,
      SmoothPeriod1,
      K,
      SmoothType2,
      SmoothPeriod2,
      Buffers,
      DrawBegin); 
//--- return value of prev_calculated for next call

   return(rates_total);
   }
   //+--------------------+------------------+
//|              MQL4  | MQL5             |
//+--------------------+------------------+
//|IndicatorCounted()  | prev_calculated  |
//|              Bars  | rates_total      |
//|              iMA(  | iMAMql4(         |
//|       iMAOnArray(  | iMAOnArrayMql4(  |
//+--------------------+------------------+ 
      int start(int rates_total,
         int prev_calculated, 
         double &fisher[],
         double &stoch[],
         double &value1[],
         double &f[],
         int mode,
         int stochPeriod,
         int stochMode,
         int smoothType1,
         int smoothPeriod1,
         double k,
         int smoothType2,
         int smoothPeriod2,
         int buffers,
         int drawBegin)


{
   if (rates_total <= stochPeriod)  
      return (0);
   int countedBars = prev_calculated;
   if (countedBars < 0) 
      return (-1);
   if (countedBars > 0) 
      countedBars--;
   int s, limit = rates_total - countedBars - 1;
   for (s = limit; s >= 0; s--) 
   {
      double price = P(s);
      double MaxH = price;
      double MinL = price;
      for (int i = 0; i < stochPeriod; i++) 
      {
         if (stochMode == 0)
         {
         price = P(s + i);
         if (price > MaxH) 
            MaxH = price;
         if (price < MinL) 
            MinL = price;
         }
         else
         {
            MaxH = MathMax(MaxH,High[s+i]);
            MinL = MathMin(MinL,Low[s+i]);
         }
      }
      stoch[s] = 2.0 * ((P(s) - MinL) / (MaxH - MinL) - 0.5);
   }
  smooth(stoch,value1,smoothType1,smoothPeriod1,limit);
   for (s = limit; s >= 0; s--)
   {
      f[s] = MathLog((1.0 + val(Value1[s])) / (1.0 - val(Value1[s]))) / 2.0;
   }    
   smooth(f,fisher,smoothType2,smoothPeriod2,limit);
   return (0);
}

double P(int index) 
{
   return (iMAMql4(NULL,0,1,0,MODE_SMA,Mode,index));
}

//void initBuffer(double &array[], string label = "", 
 //  int type = DRAW_NONE, int arrow = 0, int style = EMPTY, 
 //  int width = EMPTY, color clr = CLR_NONE) 
//   SetIndexBuffer(buffers, array);
 //  SetIndexLabel(buffers, label);
//   SetIndexEmptyValue(buffers, EMPTY_VALUE);
//   SetIndexDrawBegin(buffers, drawBegin);
//   SetIndexShift(buffers, 0);
//   SetIndexStyle(buffers, type, style, width);
//  SetIndexArrow(buffers, arrow);
 //  buffers++;
//}

double val(double v)
{
   return (MathMax(MathMin(K * v,0.999),-0.999));
}


void smooth(int rates_total, double &inp[], double &out[], int type, int len, int limit)
{
   switch(type)
   {
      case 0:
         HTMA(rates_total-StochPeriod,len,inp,out);
         break;
      case 1:
        // HMA(len,inp,out);
         break;
      case 2:
        // LWMA(len,inp,out);
         break;
      case 3:
        // EMA(len,inp,out);
         break;
   }
}

void HTMA(int N,int HMALen,double &onput[],double &output[])
{
   double ma1,ma2,hma,mix,mixprime;
   ma1=onput[N-1];
   ma2=ma1;
   mix=3.0/(2.0 + HMALen);
   mixprime=1.0-mix;
   for(int i=N-2;i>=0;i--)
   {
      ma1=mixprime*ma1 + mix*onput[i];
      ma2=mixprime*ma2 + mix*ma1;
      output[i]=3.0*ma1-2.0*ma2;
   }
}

void HMA(int rates_total, int per, double &array[], double &out[])
{
   double tmp[];
   ArrayResize(tmp,rates_total);
   ArraySetAsSeries(tmp,true);
   for(int i = rates_total-1; i >= 0; i--)
   {
      tmp[i] =
         2*iMAOnArrayMql4(array,0,per/2,0,MODE_LWMA,i)
         -iMAOnArrayMql4(array,0,per,0,MODE_LWMA,i);
   }
   for(int i = rates_total-1; i >= 0; i--)
   {
      out[i] = iMAOnArrayMql4(tmp,0,MathSqrt(per),0,MODE_LWMA,i);
   }
}

void LWMA(int rates_total, int len, double &inp[], double &out[])
{
   for(int i = rates_total-1; i >= 0; i--)
   {
      out[i] = iMAOnArrayMql4(inp,0,len,0,MODE_LWMA,i);
   }
}

void EMA(int rates_total, int len, double &inp[], double &out[])
{
   for(int i =rates_total -1; i >= 0; i--)
   {
      out[i] = iMAOnArrayMql4(inp,0,len,0,MODE_EMA,i);
   }
}

  
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
  {
//---
   
  }
//+------------------------------------------------------------------+

 


Перенос индикаторов из MQL4 в MQL5
Перенос индикаторов из MQL4 в MQL5
  • 2010.07.21
  • Vasily
  • www.mql5.com
Статья посвящена особенностям переноса в MQL5 ценовых конструкций, используемых в индикаторах, написанных на MQL4. Для упрощения переноса индикаторных расчетов из MQL4 в MQL5 предложена библиотека функций mql4_2_mql5.mqh, применение которой рассмотрено на примере переноса индикаторов MACD, Stochastic и RSI.
Файлы:
FT.mq5  8 kb
FT.mq4  5 kb
 

 Вот этот блок к примеру.

int start(int rates_total,
         int prev_calculated, 
         double &fisher[],
         double &stoch[],
         double &value1[],
         double &f[],
         int mode,
         int stochPeriod,
         int stochMode,
         int smoothType1,
         int smoothPeriod1,
         double k,
         int smoothType2,
         int smoothPeriod2,
         int buffers,
         int drawBegin)


{
   if (rates_total <= stochPeriod)  
      return (0);
   int countedBars = prev_calculated;
   if (countedBars < 0) 
      return (-1);
   if (countedBars > 0) 
      countedBars--;
   int s, limit = rates_total - countedBars - 1;
   for (s = limit; s >= 0; s--) 
   {
      double price = P(s);
      double MaxH = price;
      double MinL = price;
      for (int i = 0; i < stochPeriod; i++) 
      {
         if (stochMode == 0)
         {
         price = P(s + i);
         if (price > MaxH) 
            MaxH = price;
         if (price < MinL) 
            MinL = price;
         }
         else
         {
            MaxH = MathMax(MaxH,High[s+i]);
            MinL = MathMin(MinL,Low[s+i]);
         }
      }
      stoch[s] = 2.0 * ((P(s) - MinL) / (MaxH - MinL) - 0.5);
   }
  smooth(stoch,value1,smoothType1,smoothPeriod1,limit);

///'stoch' - parameter conversion not allowed   FT.mq5  173     10

   for (s = limit; s >= 0; s--)
   {
      f[s] = MathLog((1.0 + val(Value1[s])) / (1.0 - val(Value1[s]))) / 2.0;
   }    
   smooth(f,fisher,smoothType2,smoothPeriod2,limit);

///'f' - parameter conversion not allowed       FT.mq5  178     11

   return (0);
}

 Сообщения компилятора я вставил после соотв. строчек.

stoch, f вроде определены заранее как элементы массива. Если поставить после них квадратные скобки, то ошибка переходит дальше по строчке- типа

 'smoothType1' - parameter conversion not allowed FT .mq5 173 25


, а это уж точно просто переменная. В чём загвоздка?

 
Agat:

 Вот этот блок к примеру...

if (stochMode == 0)
         {

         }
         else
         {

         };

Попробуйте перепроверить правильность ";" , из-за них и скобок (пропущенных/лишних) ошибка может "плавать" по коду.

Upd проще может быть написать сразу в 5-ом, чем переносить с помощью библиотек. Короче будет и проблем меньше.

 

 Да здесь в базе есть аналогичный вроде Fisher Transform, но без настроек вообще. Мне бы хотя бы ENUM_APPLIED_PRICE нужно менять, а там не получается.

Не подскажете, как можно переделать?

 

 https://www.mql5.com/ru/code/537?source=terminal5_mql5


Индикатор Fisher Transform
Индикатор Fisher Transform
  • голосов: 8
  • 2011.10.10
  • Witold Wozniak
  • www.mql5.com
Индикатор Fisher, рассчитывая минимальные и максимальные уровни цены в предыдущей истории, определяет силу и направление тренда, прогнозируя его смену.
 

В  Fisher Transform получается если добавить пару строчек и  вручную выбрать одну из них

      //price=(high[bar]+low[bar])/2.0;
      //price=(high[bar]+low[bar]+close[bar])/3.0;

      //price=(high[bar]+low[bar]+close[bar]+close[bar])/4.0;

 

 А через Input  клёпок не хватает вставить

 
Agat:

В  Fisher Transform получается если добавить пару строчек и  вручную выбрать одну из них

      //price=(high[bar]+low[bar])/2.0;
      //price=(high[bar]+low[bar]+close[bar])/3.0;

      //price=(high[bar]+low[bar]+close[bar]+close[bar])/4.0;

 

 А через Input  клёпок не хватает вставить

//+------------------------------------------------------------------+
//| inputs                                                           |
//+------------------------------------------------------------------+
enum var_ratio
  {
   O_HLC,                                 // Open
   O_H_LC                                 // Hight
// продолжите список
  };

input var_ratio             OHLC_var=O_HLC;            // variant
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
if(OHLC_var==O_HLC)
{};

как то так можно
 

 Спасибо! Я попробую конечно, но это не главное. Картинка совсем не та, что в МТ-4- вот в чём проблема. То ли настроек не хватает, то ли алгоритм расчёта другой

 

 

 

 

 

 

 

 
Или это потому что на нижнем рисунке намного больше баров?
Документация по MQL5: Стандартные константы, перечисления и структуры / Константы индикаторов / Стили рисования
Документация по MQL5: Стандартные константы, перечисления и структуры / Константы индикаторов / Стили рисования
  • www.mql5.com
Стандартные константы, перечисления и структуры / Константы индикаторов / Стили рисования - Документация по MQL5
 
Agat:
Или это потому что на нижнем рисунке намного больше баров?

Если индикатор - не перевод с 4-ки, почему картинка должна совпадать, тем более на разном кол-ве баров?

Сверяйте формулы и параметры настроек. И попробуйте к автору индикатора обратиться, в обсуждении индикатора,  может подскажет что.

Причина обращения: