Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам - страница 2476

 

Так получается, что константы типов продаж и покупок для сделок и позиций одинаковы, а сделки с константой выше 1 откидывать.

Или не понял идеи вопроса

 
Aleksei Stepanenko #:
Так получается, что константы продаж и покупок для сделок и позиций одинаковы, а сделки с константой выше 1 откидывать.

И нарваться на внезапные грабли при каком-нибудь отдалённом обновлении MT5, где это из каких-то высших соображений вдруг поменяется ))

 
Ну да, логично.
 
JRandomTrader #:

И нарваться на внезапные грабли при каком-нибудь отдалённом обновлении MT5, где это из каких-то высших соображений вдруг поменяется ))

Ну, разве—что для перестраховки этим не пользоваться. Примерно как в ясную, солнечную погоду ходить с зонтом. Ведь дождь может пойти в любой момент. И вероятность дождя гораздо выше чем вероятность «высших соображений».

 
Aleksei Stepanenko #:

Так получается, что константы типов продаж и покупок для сделок и позиций одинаковы, а сделки с константой выше 1 откидывать.

Или не понял идеи вопроса

нельзя производить арифм.действия с перечислениями. Считайте что операции + - / * для enum не определены.

 
Alexey Viktorov #:

Ну, разве—что для перестраховки этим не пользоваться. Примерно как в ясную, солнечную погоду ходить с зонтом. Ведь дождь может пойти в любой момент. И вероятность дождя гораздо выше чем вероятность «высших соображений».

Можно и так: "Это как ездить в авто с пристёгнутыми ремнями безопасности"

 
Vitaly Muzichenko #:

Можно и так: "Это как ездить в авто с пристёгнутыми ремнями безопасности"

Убедительно.

Но, вот как быть если не применять перечисления. Получили в структуру тип сделки, пусть это будет 0. В свою структуру надо записать тип позиции… Это будет тоже 0… И как теперь изгаляться функциями, операторами или ещё каким-то колдовством чтобы не ошибиться… Типа тернарного оператора если==0 ? 0 : !0;

 
Alexey Viktorov #:

Убедительно.

Но, вот как быть если не применять перечисления. Получили в структуру тип сделки, пусть это будет 0. В свою структуру надо записать тип позиции… Это будет тоже 0… И как теперь изгаляться функциями, операторами или ещё каким-то колдовством чтобы не ошибиться… Типа тернарного оператора если==0 ? 0 : !0;

Я бы выбрал switch

 
Подскажите, пожалуйста, почему при добавлении Параболика в индикатор ТМА, стрелки ломаются?

Добавил параболик и добавил правило отрисовки стрелок по ТМА и параболику. 

В результате стрелки "раскидало по графику", особенно на новом ТФ. 

И на валютных парах типа ОТС. 

Стрелки начинают рисоваться на каждом баре линии ТМА, либо повторять параболик. Дичь какая-то. 

Хотя, у них конкретное значение. 

//+------------------------------------------------------------------+
//|                                           TMA-SAR OTC Arrows.mq5 |
//|                       |
//+------------------------------------------------------------------+
#property version      "1.0"
#property description "TMA-SAR OTC Arrows"
#property indicator_chart_window


#property indicator_chart_window
#property indicator_buffers 11
#property indicator_plots   8

#property indicator_label1  "Centered TMA"
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrLightSkyBlue,clrPink
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2
#property indicator_label2  "Centered TMA upper band"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrLightSkyBlue
#property indicator_style2  STYLE_DOT
#property indicator_label3  "Centered TMA lower band"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrPink
#property indicator_style3  STYLE_DOT



#property indicator_label4  "Rule 1 down"
#property indicator_type4   DRAW_ARROW
#property indicator_color4  clrRed
#property indicator_width4  3
#property indicator_label5  "Rule 1 up"
#property indicator_type5   DRAW_ARROW
#property indicator_color5  clrBlue
#property indicator_width5  3

#property indicator_label6  "Rule 2 down"
#property indicator_type6   DRAW_ARROW
#property indicator_color6  clrPink
#property indicator_width6  1
#property indicator_label7  "Rule 2 up"
#property indicator_type7   DRAW_ARROW
#property indicator_color7  clrLightSkyBlue
#property indicator_width7  1



#property indicator_label8  "SAR"
#property indicator_type8   DRAW_ARROW
#property indicator_color8  clrDodgerBlue
#property indicator_width8  1



// ---------------------------- НАСТРОЙКИ ИНДИКАТОРА ----------------------------

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+oprn+close)/4
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage   // Heiken ashi average
};

//
//
//
//
//
input string str_0  = "-------- Основные настройки --------"; // -------------------

//input int Bar_count = 5000;     // Количество баров отрисовки (1000 - минимум)
input bool Mode_1 = true;       // Правило Параболика
input bool Mode_2 = true;       // Правило Выхода за границы


//-------------------- НАСТРОЙКИ ИНДИКАТОРА TMA -------------------------------

input string str_1  = "-------- Настройки TMA --------"; // -------- TMA --------
input int       HalfLength    = 12;       // Centered TMA half period
input enPrices  Price         = pr_weighted; // Price to use
input int       AtrPeriod     = 100;      // Average true range period 
input double    AtrMultiplier = 2;        // Average true range multiplier
input int                TMAangle                       = 4;                            // Centered TMA angle caution. In pips

//-------------------- НАСТРОЙКИ ИНДИКАТОРА SAR -------------------------------

input string str_2  = "-------- Настройки SAR --------"; // -------- SAR --------
input double InpSARStep=0.02;    // Step
input double InpSARMaximum=0.2;  // Maximum





//--- Индикаторные буферы
double tmac[];
double tmau[];
double tmad[];

double ExtSARBuffer[];
double ExtEPBuffer[];
double ExtAFBuffer[];

double Rule_1_UP[], Rule_1_DN[];
double Rule_2_UP[], Rule_2_DN[];

//--- Переменные
int Bar_count_ = 0;
double colorBuffer[];
int    ExtLastRevPos;
bool   ExtDirectionLong;
double ExtSarStep;
double ExtSarMaximum;
double prices[];




//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
int OnInit()
  {   /*
        ArrayInitialize(tmac,EMPTY_VALUE);
        ArrayInitialize(tmau,EMPTY_VALUE);
        ArrayInitialize(tmad,EMPTY_VALUE);
        ArrayInitialize(ExtSARBuffer,EMPTY_VALUE);
        ArrayInitialize(Rule_1_UP,EMPTY_VALUE);
        ArrayInitialize(Rule_1_DN,EMPTY_VALUE);
        ArrayInitialize(Rule_2_UP,EMPTY_VALUE);
        ArrayInitialize(Rule_2_DN,EMPTY_VALUE);
        ArrayInitialize(Rule_2_DN,EMPTY_VALUE);
        */
        /*
        PlotIndexSetDouble (0, PLOT_EMPTY_VALUE, 0.0);
         PlotIndexSetDouble (1, PLOT_EMPTY_VALUE, 0.0);
         PlotIndexSetDouble (2, PLOT_EMPTY_VALUE, 0.0);
         PlotIndexSetDouble (3, PLOT_EMPTY_VALUE, 0.0);
         PlotIndexSetDouble (4, PLOT_EMPTY_VALUE, 0.0);
         PlotIndexSetDouble (5, PLOT_EMPTY_VALUE, 0.0);
         PlotIndexSetDouble (6, PLOT_EMPTY_VALUE, 0.0);
         PlotIndexSetDouble (7, PLOT_EMPTY_VALUE, 0.0);*/
    
    SetIndexBuffer(0, tmac,        INDICATOR_DATA); 
    SetIndexBuffer(1, colorBuffer, INDICATOR_COLOR_INDEX); 
    SetIndexBuffer(2, tmau,        INDICATOR_DATA); 
    SetIndexBuffer(3, tmad,        INDICATOR_DATA); 


    
    
    
    //------------- Стрелки ------------- 
    
    SetIndexBuffer(4,  Rule_1_DN, INDICATOR_DATA);     PlotIndexSetInteger(3, PLOT_ARROW, 226);
         SetIndexBuffer(5,  Rule_1_UP, INDICATOR_DATA);     PlotIndexSetInteger(4, PLOT_ARROW, 225);
        
         SetIndexBuffer(6,  Rule_2_DN, INDICATOR_DATA);     PlotIndexSetInteger(5, PLOT_ARROW, 226);
         SetIndexBuffer(7,  Rule_2_UP, INDICATOR_DATA);     PlotIndexSetInteger(6, PLOT_ARROW, 225);

         
         //------------- SAR ------------- 
    if(InpSARStep < 0.0)
      {
        ExtSarStep = 0.02;
        PrintFormat("Input parametr InpSARStep has incorrect value. Indicator will use value %d for calculations.",
                    ExtSarStep);
       }
    else
      ExtSarStep=InpSARStep;
    if(InpSARMaximum < 0.0)
      {
        ExtSarMaximum = 0.2;
        PrintFormat("Input parametr InpSARMaximum has incorrect value. Indicator will use value %d for calculations.",
                    ExtSarMaximum);
      }
    else
      ExtSarMaximum = InpSARMaximum;
  
    SetIndexBuffer(8, ExtSARBuffer);
    PlotIndexSetInteger(7,PLOT_ARROW,159);    
    string short_name=StringFormat("SAR(%.2f,%.2f)",ExtSarStep,ExtSarMaximum);
    PlotIndexSetString(7,PLOT_LABEL,short_name);    
    ExtLastRevPos=0;
    ExtDirectionLong=false;
         
    SetIndexBuffer(9,  ExtEPBuffer, INDICATOR_CALCULATIONS);
    SetIndexBuffer(10, ExtAFBuffer, INDICATOR_CALCULATIONS);

    // Установка пустых значний для буферов, чтобы не отриосвывались

            
    IndicatorSetString(INDICATOR_SHORTNAME," TMA-SAR OTC Arrows ("+string(HalfLength)+")");
    return(0);
  }





//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
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[])
  {    
    double atr = 0;
    
   if (ArraySize(prices)!=rates_total) ArrayResize(prices,rates_total);
   for (int i=(int)MathMax(prev_calculated-1,         0); i<rates_total; i++) prices[i] = getPrice(Price,open,close,high,low,i,rates_total);
   for (int i=(int)MathMax(prev_calculated-HalfLength,0); i<rates_total; i++)
   {
      atr = 0;
         for (int j=0; j<AtrPeriod && (i-j-11)>=0; j++) atr += MathMax(high[i-j-10],close[i-j-11])-MathMin(low[i-j-10],close[i-j-11]);
                                                        atr /= AtrPeriod;
      
      double sum  = (HalfLength+1)*prices[i];
      double sumw = (HalfLength+1);
      for(int j=1, k=HalfLength; j<=HalfLength; j++, k--)
      {
         if ((i-j)>=0)
         {
            sum  += k*prices[i-j];
            sumw += k;
         }            
         if ((i+j)<rates_total)
         {
            sum  += k*prices[i+j];
            sumw += k;
         }
      }
      tmac[i] = sum/sumw;   
      if (i>0)
      {
         colorBuffer[i] = colorBuffer[i-1];
           if (tmac[i] > tmac[i-1]) colorBuffer[i]= 0;
           if (tmac[i] < tmac[i-1]) colorBuffer[i]= 1;
      }                     
      tmau[i] = tmac[i]+AtrMultiplier*atr;
      tmad[i] = tmac[i]-AtrMultiplier*atr;
      

   }
        
        
    // ------------------- SAR -------------------
        
    if(rates_total<3)
      return(0);
//--- detect current position
   int pos=prev_calculated-1;
//--- correct position
   if(pos<1)
     {
      //--- first pass, set as SHORT
      pos=1;
      ExtAFBuffer[0]=ExtSarStep;
      ExtAFBuffer[1]=ExtSarStep;
      ExtSARBuffer[0]=high[0];
      ExtLastRevPos=0;
      ExtDirectionLong=false;
      ExtSARBuffer[1]=GetHigh(pos,ExtLastRevPos,high);
      ExtEPBuffer[0]=low[pos];
      ExtEPBuffer[1]=low[pos];
     }
//---main cycle
   for(int i=pos; i<rates_total-1 && !IsStopped(); i++)
     {
      //--- check for reverse
      if(ExtDirectionLong)
        {
         if(ExtSARBuffer[i]>low[i])
           {
            //--- switch to SHORT
            ExtDirectionLong=false;
            ExtSARBuffer[i]=GetHigh(i,ExtLastRevPos,high);
            ExtEPBuffer[i]=low[i];
            ExtLastRevPos=i;
            ExtAFBuffer[i]=ExtSarStep;
           }
        }
      else
        {
         if(ExtSARBuffer[i]<high[i])
           {
            //--- switch to LONG
            ExtDirectionLong=true;
            ExtSARBuffer[i]=GetLow(i,ExtLastRevPos,low);
            ExtEPBuffer[i]=high[i];
            ExtLastRevPos=i;
            ExtAFBuffer[i]=ExtSarStep;
           }
        }
      //--- continue calculations
      if(ExtDirectionLong)
        {
         //--- check for new High
         if(high[i]>ExtEPBuffer[i-1] && i!=ExtLastRevPos)
           {
            ExtEPBuffer[i]=high[i];
            ExtAFBuffer[i]=ExtAFBuffer[i-1]+ExtSarStep;
            if(ExtAFBuffer[i]>ExtSarMaximum)
               ExtAFBuffer[i]=ExtSarMaximum;
           }
         else
           {
            //--- when we haven't reversed
            if(i!=ExtLastRevPos)
              {
               ExtAFBuffer[i]=ExtAFBuffer[i-1];
               ExtEPBuffer[i]=ExtEPBuffer[i-1];
              }
           }
         //--- calculate SAR for tomorrow
         ExtSARBuffer[i+1]=ExtSARBuffer[i]+ExtAFBuffer[i]*(ExtEPBuffer[i]-ExtSARBuffer[i]);
         //--- check for SAR
         if(ExtSARBuffer[i+1]>low[i] || ExtSARBuffer[i+1]>low[i-1])
            ExtSARBuffer[i+1]=MathMin(low[i],low[i-1]);
        }
      else
        {
         //--- check for new Low
         if(low[i]<ExtEPBuffer[i-1] && i!=ExtLastRevPos)
           {
            ExtEPBuffer[i]=low[i];
            ExtAFBuffer[i]=ExtAFBuffer[i-1]+ExtSarStep;
            if(ExtAFBuffer[i]>ExtSarMaximum)
               ExtAFBuffer[i]=ExtSarMaximum;
           }
         else
           {
            //--- when we haven't reversed
            if(i!=ExtLastRevPos)
              {
               ExtAFBuffer[i]=ExtAFBuffer[i-1];
               ExtEPBuffer[i]=ExtEPBuffer[i-1];
              }
           }
         //--- calculate SAR for tomorrow
         ExtSARBuffer[i+1]=ExtSARBuffer[i]+ExtAFBuffer[i]*(ExtEPBuffer[i]-ExtSARBuffer[i]);
         //--- check for SAR
         if(ExtSARBuffer[i+1]<high[i] || ExtSARBuffer[i+1]<high[i-1])
            ExtSARBuffer[i+1]=MathMax(high[i],high[i-1]);
        }
     }
        
        
        
    // ------------------- СТРЕЛКИ -------------------
           
         pos = prev_calculated-1;
    if (pos < 1) pos = 6;
          
    for (int i = pos; i < rates_total - 1 && !IsStopped(); i++)
      {
        // Режим работы - С ПАРАБОЛИКОМ
        if (Mode_1)
          {
                 // Проверяем параболик: есть ли > 4 свечек параболика в одном направлении 
            if (ExtSARBuffer[i-1] > high[i-1]       && ExtSARBuffer[i-2] < low[i-2] && ExtSARBuffer[i-2] > tmac[i-2]       
                                                   && ExtSARBuffer[i-3] < low[i-3] && ExtSARBuffer[i-4] < low[i-4] && ExtSARBuffer[i-5] < low[i-5] && ExtSARBuffer[i-6] < low[i-6])
                             {
                Rule_1_DN[i] = high[i] + AtrMultiplier * atr;
              }
             
            if (ExtSARBuffer[i-1] < low[i-1]       && ExtSARBuffer[i-2] > high[i-2] && ExtSARBuffer[i-2] < tmac[i-2]       
                                                  && ExtSARBuffer[i-3] > high[i-3] && ExtSARBuffer[i-4] > high[i-4] && ExtSARBuffer[i-5] > high[i-5] && ExtSARBuffer[i-6] > high[i-6])
                             {
                Rule_1_UP[i] = low[i] - AtrMultiplier * atr;
              }
          } 
         
        // Режим работы - ПРАВИЛО 3
        if (Mode_2)
          {
            if (high[i-2] > tmau[i-2] && close[i-2] > tmau[i-2]       && close[i-1] < tmau[i-1]      && close[i-1] < open[i-1])
                             { 
                               Rule_2_DN[i] = high[i] + AtrMultiplier * atr;
                        }
                          
            // Зеркально
            if (low[i-2] < tmad[i-2] && close[i-2] < tmad[i-2]       && close[i-1] > tmad[i-1]       && close[i-1] > open[i-1])
              {
                Rule_2_UP[i] = low[i] - AtrMultiplier * atr;
              } 
          }       
      } 
      
    return(rates_total);
  }



//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//


double workHa[][4];
double getPrice(enPrices price, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars)
{
  if (price>=pr_haclose && price<=pr_haaverage)
   {
      if (ArrayRange(workHa,0)!= bars) ArrayResize(workHa,bars);

         //
         //
         //
         //
         //
         
         double haOpen;
         if (i>0)
                haOpen  = (workHa[i-1][2] + workHa[i-1][3])/2.0;
         else   haOpen  = open[i]+close[i];
         double haClose = (open[i] + high[i] + low[i] + close[i]) / 4.0;
         double haHigh  = MathMax(high[i], MathMax(haOpen,haClose));
         double haLow   = MathMin(low[i] , MathMin(haOpen,haClose));

         if(haOpen  <haClose) { workHa[i][0] = haLow;  workHa[i][1] = haHigh; } 
         else                 { workHa[i][0] = haHigh; workHa[i][1] = haLow;  } 
                                workHa[i][2] = haOpen;
                                workHa[i][3] = haClose;
         //
         //
         //
         //
         //
         
         switch (price)
         {
            case pr_haclose:     return(haClose);
            case pr_haopen:      return(haOpen);
            case pr_hahigh:      return(haHigh);
            case pr_halow:       return(haLow);
            case pr_hamedian:    return((haHigh+haLow)/2.0);
            case pr_hatypical:   return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:  return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:   return((haHigh+haLow+haClose+haOpen)/4.0);
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (price)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
   }
   return(0);
}













//+------------------------------------------------------------------+
//| Find highest price from start to current position                |
//+------------------------------------------------------------------+
double GetHigh(int curr_pos,int start,const double& high[])
  {
   double result=high[start];
//---
   for(int i=start+1; i<=curr_pos; i++)
      if(result<high[i])
         result=high[i];
//---
   return(result);
  }
//+------------------------------------------------------------------+
//| Find lowest price from start to current position                 |
//+------------------------------------------------------------------+
double GetLow(int curr_pos,int start,const double& low[])
  {
   double result=low[start];
//---
   for(int i=start+1; i<=curr_pos; i++)
      if(result>low[i])
         result=low[i];
//---
   return(result);
  }
//+------------------------------------------------------------------+







UPD

Причём, Параболик - на месте, ТМА - на месте. 

А вот стрелки - колбасит. Хотя они тоже имеют тип Arrow, как и у параболика. 

 
Ivan Butko #:
Подскажите, пожалуйста, почему при добавлении Параболика в индикатор ТМА, стрелки ломаются?


Причём, Параболик - на месте, ТМА - на месте. 

А вот стрелки - колбасит. Хотя они тоже имеют тип Arrow, как и у параболика. 

Нужно обязательно чистить буфера при первом запуске