Questions des débutants MQL5 MT5 MetaTrader 5 - page 1355

 
Je l'ai. Chers collègues, merci pour votre aide.
 
Oleg Kolesov #:

SanAlex, merci pour votre aide. Je suis un peu confus. Pas le numéro de tampon, mais l'indice de couleur ?

Dans Indicateur.

Dans l'Expert Advisor. 3 -couleurs. 3 situations.

Je ne connais pas très bien - mais il me semble que vous devez ajouter ou changer 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];

Et ici, vous devez le relever si vous utilisez trois couleurs.

//+------------------------------------------------------------------+
//| 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  >  <



     {
 

Pour ne pas réinventer la roue, donnez-moi une solution.

Il y a un fichier csv avec le contenu suivant :
1,2,3
4,5,6
7,8,9

J'ai besoin d'obtenir un tableau :
[
[1 2 3]
[4 5 6]
[7 8 9]
]

 

Bonjour. Messieurs les programmeurs expérimentés, veuillez me conseiller. Comment colorier une ligne ? La condition while >= bleu, while <= rouge.

Dossiers :
ss9e1.png  16 kb
 
Oleg Kolesov #:

Bonjour. Messieurs les programmeurs expérimentés, veuillez me conseiller. Comment colorier une ligne ? La condition while >= bleu, while <= rouge.

Utiliser le style de dessinDRAW_COLOR_LINE

Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
  • www.mql5.com
DRAW_COLOR_LINE - Стили индикаторов в примерах - Пользовательские индикаторы - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Vladimir, j'utilise le style de dessinDRAW_COLOR_LINE. Que faire avec les conditions while >= blue, while <= red. Une boucle dans une boucle ?

ArrayBsearch ? ArraySort ?

Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
Документация по MQL5: Пользовательские индикаторы / Стили индикаторов в примерах / DRAW_COLOR_LINE
  • www.mql5.com
DRAW_COLOR_LINE - Стили индикаторов в примерах - Пользовательские индикаторы - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Oleg Kolesov #:
Vladimir, j'utilise le style de dessinDRAW_COLOR_LINE. Que faire avec les conditions while >= blue, while <= red. Une boucle dans une boucle ?

ArrayBsearch ? ArraySort ?

Placez une condition sur la ligne 130.

 

Je l'ai un peu nettoyé :

//+------------------------------------------------------------------+
//|                                                           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);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+


Le code fonctionne, il change de couleur.

 

Je suis perplexe depuis trois jours. L'appartement est à gauche, DimGray ? Besoin si haut ou égal bleu. Si en bas ou égal rouge.

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

Je me suis posé la question pendant trois jours. L'appartement est à gauche, DimGray ? Besoin si haut ou égal bleu. Si inférieur ou égal à rouge.

Vous ne pouvez pas comparer des nombres doubles à l'aide de "=="(voir référence).

Il faut le comparer comme ceci :

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
  }


C'est ainsi que cela se passe dans l'indicateur :

//+------------------------------------------------------------------+
//|                                                           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);
  }
//+------------------------------------------------------------------+


Résultat :

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