Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1355

 
Got it. Colleagues, thank you for your help.
 
Oleg Kolesov #:

SanAlex thanks for your help. I'm a little confused. Not the buffer number, but the colour index?

In Indicator.

In the Expert Advisor. 3 -colours. 3 situations.

I don't know very well - but it seems to me you need to add or change 0-1-2

//+------------------------------------------------------------------+
//| main function returns true if any position processed             |
//+------------------------------------------------------------------+
bool CSampleExpert::Processing(void)
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
//--- refresh indicators
   if(BarsCalculated(m_handle_macd)<2)
      return(false);
   if(CopyBuffer(m_handle_macd,1,0,2,m_buff_MACD_main)  !=2)
      return(false);
//   m_indicators.Refresh();
//--- to simplify the coding and speed up access
//--- data are put into internal variables
   m_macd_current   =m_buff_MACD_main[0];
   m_macd_previous  =m_buff_MACD_main[1];
   m_macd_previous_2  =m_buff_MACD_main[2];

And here, you need to pick it up if you use three colours.

//+------------------------------------------------------------------+
//| Check for short position opening                                 |
//+------------------------------------------------------------------+
bool CSampleExpert::ShortOpened(void)
  {
   bool res=false;
//--- check for short position (SELL) possibility
   if(m_macd_current>m_macd_previous)  ---- тут m_macd_previous_2  >  <



     {
 

So as not to reinvent the wheel, give me a solution.

There is a csv file with the following contents:
1,2,3
4,5,6
7,8,9

I need to get an array:
[
[1 2 3]
[4 5 6]
[7 8 9]
]

 

Hello. Gentlemen experienced programmers, please advise. How do I colour a line? The condition while >= blue, while <= red.

Files:
ss9e1.png  16 kb
 
Oleg Kolesov #:

Hello. Gentlemen experienced programmers, please advise. How do I colour a line? The condition while >= blue, while <= red.

UseDRAW_COLOR_LINE drawing style

Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
  • www.mql5.com
DRAW_COLOR_LINE - Стили индикаторов в примерах - Пользовательские индикаторы - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Vladimir I am usingDRAW_COLOR_LINE drawing style. What to do with conditions while >= blue, while <= red. A loop in a loop?

ArrayBsearch? ArraySort?

Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
  • www.mql5.com
DRAW_COLOR_LINE - Стили индикаторов в примерах - Пользовательские индикаторы - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Oleg Kolesov #:
Vladimir I am usingDRAW_COLOR_LINE drawing style. What to do with conditions while >= blue, while <= red. A loop in a loop?

ArrayBsearch? ArraySort?

Place a condition on line 130.

 

Cleaned it up a bit:

//+------------------------------------------------------------------+
//|                                                           V2.mq5 |
//|                                                            Koles |
//|                                             www.koles-33@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Koles"
#property link      "www.koles-33@mail.ru"
#property version   "3.00"
#property indicator_chart_window
#property indicator_buffers 2            // Количество буферов
#property indicator_plots   1            //  
//---- plot
#property indicator_label1  "малый"
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrDeepSkyBlue,clrDimGray,clrRed
#property indicator_style1  STYLE_DOT
#property indicator_width1  1
//---- input parameters
input int Period1=24;                                             // Period1
input int PeriodSh=2;                                             // PeriodSh
//-------------------------------------------------------------------+
double level1[];
double levelcol1[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorSetInteger(INDICATOR_DIGITS,Digits());                  // Точки после запятой
//---
   SetIndexBuffer(0,level1,INDICATOR_DATA);                        // Назначение массива буферу
   SetIndexBuffer(1,levelcol1,INDICATOR_COLOR_INDEX);
//--- задаем количество индексов цветов для графического построения
   PlotIndexSetInteger(0,PLOT_COLOR_INDEXES,3);
//--- задаем цвет для каждого индекса
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,clrDeepSkyBlue);
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrDimGray);
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,clrRed);
//---  короткое имя индикатора
   string short_name="V2("+IntegerToString(Period1)+","+IntegerToString(PeriodSh)+")";
//---
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
   PlotIndexSetString(0,PLOT_LABEL,"малый");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| 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[])
  {
//--- проверка количества баров на достаточность для расчёта
   if(rates_total<Period1+1)
      return(0);
//--- индексация элементов в массивах как в таймсериях
   ArraySetAsSeries(high,true); // Смена направления индексации
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
   ArraySetAsSeries(level1,true);
   ArraySetAsSeries(levelcol1,true);
//--- объявления локальных переменных
   int i,limit;
   double max1,min1;      //
   double v1;
//--- расчёт стартового номера limit для цикла пересчёта баров
   if(prev_calculated==0)                     // проверка на первый старт расчёта индикатора
      limit=rates_total-Period1-1;            // стартовый номер для расчёта всех баров
   else
      limit=rates_total-prev_calculated;      // стартовый номер для расчёта новых баров
//--- основной цикл расчёта индикатора
   for(i=limit; i>=0; i--)
     {
      max1=high[ArrayMaximum(high,i+1,Period1)];
      min1=low[ArrayMinimum(low,i+1,Period1)];
      //---------------------------------------------+
      v1=(max1-min1)/2.0;                                           // Половина волатильности
      //---------------------------------------------+
      level1[i]=max1-v1;
      //---------------------------------------------+
      if(level1[i]>level1[i+PeriodSh])
         levelcol1[i]=0.0;
      if(level1[i]==level1[i+PeriodSh])
         levelcol1[i]=1.0;
      if(level1[i]<level1[i+PeriodSh])
         levelcol1[i]=2.0;
     }  //--- Возвращаемое значение prev_calculated для следующего вызова
   return(rates_total);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+


The code works, it changes colour.

 

I've been puzzled for three days. Is the flat left DimGray? Need if up or equal blue. If down or equal red.

if(level1[i]==level1[i+PeriodSh])
         levelcol1[i]=1.0;
 
Oleg Kolesov #:

I've been puzzled for three days. Is the flat left DimGray? Need if up or equal blue. If down or equal to red.

You cannot compare double numbers via '=='(see reference).

It should be compared like this:

bool CompareDoubles(double number1,double number2)
  {
   if(NormalizeDouble(number1-number2,8)==0) 
      return(true);
   else 
      return(false);
  }
void OnStart()
  {
   double d_val=0.3;
   float  f_val=0.3;
   if(CompareDoubles(d_val,f_val)) 
      Print(d_val,"equals",f_val);
   else 
      Print("Different: d_val = ",DoubleToString(d_val,16),"  f_val = ",DoubleToString(f_val,16));
// Результат: Different: d_val= 0.3000000000000000   f_val= 0.3000000119209290
  }


This is how it is in the indicator:

//+------------------------------------------------------------------+
//|                                                           V2.mq5 |
//|                                                            Koles |
//|                                             www.koles-33@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Koles"
#property link      "www.koles-33@mail.ru"
#property version   "3.00"
#property indicator_chart_window
#property indicator_buffers 2            // Количество буферов
#property indicator_plots   1            //  
//---- plot
#property indicator_label1  "малый"
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrDeepSkyBlue,clrDimGray,clrRed
#property indicator_style1  STYLE_DOT
#property indicator_width1  1
//---- input parameters
input int Period1=24;                                             // Period1
input int PeriodSh=2;                                             // PeriodSh
//-------------------------------------------------------------------+
double level1[];
double levelcol1[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
   IndicatorSetInteger(INDICATOR_DIGITS,Digits());                  // Точки после запятой
//---
   SetIndexBuffer(0,level1,INDICATOR_DATA);                        // Назначение массива буферу
   SetIndexBuffer(1,levelcol1,INDICATOR_COLOR_INDEX);
//--- задаем количество индексов цветов для графического построения
   PlotIndexSetInteger(0,PLOT_COLOR_INDEXES,3);
//--- задаем цвет для каждого индекса
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,0,clrDeepSkyBlue);
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrDimGray);
   PlotIndexSetInteger(0,PLOT_LINE_COLOR,2,clrRed);
//---  короткое имя индикатора
   string short_name="V2("+IntegerToString(Period1)+","+IntegerToString(PeriodSh)+")";
//---
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
   PlotIndexSetString(0,PLOT_LABEL,"малый");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| 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[])
  {
//--- проверка количества баров на достаточность для расчёта
   if(rates_total<Period1+1)
      return(0);
//--- индексация элементов в массивах как в таймсериях
   ArraySetAsSeries(high,true); // Смена направления индексации
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
   ArraySetAsSeries(level1,true);
   ArraySetAsSeries(levelcol1,true);
//--- объявления локальных переменных
   int i,limit;
   double max1,min1;      //
   double v1;
//--- расчёт стартового номера limit для цикла пересчёта баров
   if(prev_calculated==0)                     // проверка на первый старт расчёта индикатора
      limit=rates_total-Period1-1;            // стартовый номер для расчёта всех баров
   else
      limit=rates_total-prev_calculated;      // стартовый номер для расчёта новых баров
//--- основной цикл расчёта индикатора
   for(i=limit; i>=0; i--)
     {
      max1=high[ArrayMaximum(high,i+1,Period1)];
      min1=low[ArrayMinimum(low,i+1,Period1)];
      //---------------------------------------------+
      v1=(max1-min1)/2.0;                                           // Половина волатильности
      //---------------------------------------------+
      level1[i]=max1-v1;
      //---------------------------------------------+
      levelcol1[i]=0.0;
      if(level1[i]>level1[i+PeriodSh])
        {
         levelcol1[i]=0.0;
         continue;
        }
      if(CompareDoubles(level1[i],level1[i+PeriodSh]))
        {
         levelcol1[i]=1.0;
         continue;
        }
      if(level1[i]<level1[i+PeriodSh])
        {
         levelcol1[i]=2.0;
         continue;
        }
     }  //--- Возвращаемое значение prev_calculated для следующего вызова
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| CompareDoubles                                                   |
//+------------------------------------------------------------------+
bool CompareDoubles(double number1,double number2)
  {
   if(NormalizeDouble(number1-number2,8)==0)
      return(true);
   else
      return(false);
  }
//+------------------------------------------------------------------+


Result:

Документация по MQL5: Основы языка / Типы данных / Вещественные типы (double, float)
Документация по MQL5: Основы языка / Типы данных / Вещественные типы (double, float)
  • www.mql5.com
Вещественные типы (double, float) - Типы данных - Основы языка - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
Reason: