Не связывается буфер при помощи SetIndexBuffer, помогите.

 

Вобщем, пишу индикатор по данным COT, но это не важно. Пока буфера у меня было три все было супер. Решил я значит добавить 4 буфер, вроде все правильно в пропертях увеличил число буферов, но четвертый буфер(под номером 3), не хочет связываться при помощи SetIndexBuffer и все тут. В чем дело не могу понять. Если назначить ему цифру от нуля до двух то он связывается, если цифру три дать другому буферу то тот перестает связываться, в проперти какаю бы цифру я не поставил, хоть 4 хоть 500, ничего не меняется, буфер с назначенным индексом три и больше не связывается данной функцией и все тут. Не могу понять в чем проблема то?



//+------------------------------------------------------------------+

//|                                                COT-Indicator.mq5 |

//|                                                           Volder |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Volder"

#property link      "https://www.mql5.com"

#property version   "1.00"



#property indicator_separate_window

#property indicator_buffers 4

#property indicator_plots   3

#property script_show_inputs



#property indicator_label1 "Commercial Long"

#property indicator_label2 "Commercial Short"

#property indicator_label3 "Commercial All"



#property indicator_width1 2

#property indicator_width2 2

#property indicator_width3 2



input ENUM_DRAW_TYPE styling1 = DRAW_NONE;               //Commercial Long

input ENUM_DRAW_TYPE styling2 = DRAW_NONE;               //Commercial Short

input ENUM_DRAW_TYPE styling3 = DRAW_LINE;               //Commercial All



//--- indicator buffers

double         ComLongBuf[];

double         ComShortBuf[];

double         ComAllBuf[];

double         OIBuf[];



string current_symbol;

string current_instr;



int file2017;

int file2018;

int file2019;

int file2020;

int file2021;



//+------------------------------------------------------------------+

//| Custom indicator initialization function                         |

//+------------------------------------------------------------------+

int OnInit()

  {

   Print("Запуск индикатора COT");

//--- indicator buffers mapping

   SetIndexBuffer(0, ComLongBuf, INDICATOR_DATA);

   SetIndexBuffer(1, ComShortBuf, INDICATOR_DATA);

   SetIndexBuffer(2, ComAllBuf, INDICATOR_DATA);

   SetIndexBuffer(3, OIBuf, INDICATOR_CALCULATIONS));

   

   PlotIndexSetInteger(0, PLOT_DRAW_TYPE, styling1);

   PlotIndexSetInteger(1, PLOT_DRAW_TYPE, styling2);

   PlotIndexSetInteger(2, PLOT_DRAW_TYPE, styling3);

   PlotIndexSetDouble (0, PLOT_EMPTY_VALUE, 0.0);

   PlotIndexSetDouble (1, PLOT_EMPTY_VALUE, 0.0);

   PlotIndexSetDouble (2, PLOT_EMPTY_VALUE, 0.0);

   

   current_symbol = Symbol();

   

   if (current_symbol == "EURUSD") current_instr = "\"EURO FX - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "GBPUSD") current_instr = "\"BRITISH POUND STERLING - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "AUDUSD") current_instr = "\"AUSTRALIAN DOLLAR - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "NZDUSD") current_instr = "\"NEW ZEALAND DOLLAR - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "USDJPY") current_instr = "\"JAPANESE YEN - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "USDCAD") current_instr = "\"CANADIAN DOLLAR - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "USDCHF") current_instr = "\"SWISS FRANC - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "USDRUB") current_instr = "\"RUSSIAN RUBLE - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "XAGUSD") current_instr = "\"SILVER - COMMODITY EXCHANGE INC.\"";

   else if (current_symbol == "XAUUSD") current_instr = "\"GOLD - COMMODITY EXCHANGE INC.\"";

   else if (current_symbol == "WHEAT") current_instr = "\"WHEAT-SRW - CHICAGO BOARD OF TRADE\"";

   else if (current_symbol == "BTCUSD") current_instr = "\"BITCOIN - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "NQ") current_instr = "\"NASDAQ-100 STOCK INDEX (MINI) - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "TF") current_instr = "\"E-MINI RUSSELL 2000 INDEX - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "ES") current_instr = "\"E-MINI S&P 500 STOCK INDEX - CHICAGO MERCANTILE EXCHANGE\"";

   else if (current_symbol == "COFFEE") current_instr = "\"COFFEE C - ICE FUTURES U.S.\"";

   else if (current_symbol == "CORN") current_instr = "\"CORN - CHICAGO BOARD OF TRADE\"";

   else if (current_symbol == "COCOA") current_instr = "\"COCOA - ICE FUTURES U.S.\"";

   else if (current_symbol == "SOYBEAN") current_instr = "\"SOYBEANS - CHICAGO BOARD OF TRADE\"";

   else if (current_symbol == "SUGAR") current_instr = "\"SUGAR NO. 11 - ICE FUTURES U.S.\"";

   else if (current_symbol == "CL") current_instr = "\"CRUDE OIL, LIGHT SWEET - NEW YORK MERCANTILE EXCHANGE\"";

   else if (current_symbol == "HG") current_instr = "\"COPPER-GRADE #1 - COMMODITY EXCHANGE INC.\"";

   else if (current_symbol == "PA") current_instr = "\"PALLADIUM - NEW YORK MERCANTILE EXCHANGE\"";

   else if (current_symbol == "PL") current_instr = "\"PLATINUM - NEW YORK MERCANTILE EXCHANGE\"";

   

   else current_instr = "\"EURO FX - CHICAGO MERCANTILE EXCHANGE\"";

   

   IndicatorSetString(INDICATOR_SHORTNAME, "COT: " + current_instr);

   

   

   file2017 = FileOpen("COT\\2017.txt", FILE_READ|FILE_SHARE_READ|FILE_TXT|FILE_ANSI, '\t');

   if(file2017 == INVALID_HANDLE) Print("Файл 2017.txt не окрылся");

   else Print("Файл 2017.txt успешно окрыт");

   file2018 = FileOpen("COT\\2018.txt", FILE_READ|FILE_SHARE_READ|FILE_TXT|FILE_ANSI, '\t');

   if(file2018 == INVALID_HANDLE) Print("Файл 2018.txt не окрылся");

   else Print("Файл 2018.txt успешно окрыт");

   file2019 = FileOpen("COT\\2019.txt", FILE_READ|FILE_SHARE_READ|FILE_TXT|FILE_ANSI, '\t');

   if(file2019 == INVALID_HANDLE) Print("Файл 2019.txt не окрылся");

   else Print("Файл 2019.txt успешно окрыт");

   file2020 = FileOpen("COT\\2020.txt", FILE_READ|FILE_SHARE_READ|FILE_TXT|FILE_ANSI, '\t');

   if(file2020 == INVALID_HANDLE) Print("Файл 2020.txt не окрылся");

   else Print("Файл 2020.txt успешно окрыт");

   file2021 = FileOpen("COT\\annual.txt", FILE_READ|FILE_SHARE_READ|FILE_TXT|FILE_ANSI, '\t');

   if(file2021 == INVALID_HANDLE) Print("Файл annual.txt не окрылся");

   else Print("Файл annual.txt успешно окрыт");

   

   return(INIT_SUCCEEDED);

  }

  

  



void file_handler(int file, int &i, const datetime &time[])

{

   string string_array[];

   string filestring;

   string instr_name;

   string that_time;

   string instr_time;

   

   FileSeek(file, 0, SEEK_SET);

   

   while (true) {

      filestring = FileReadString(file);

      StringSplit(filestring, ',', string_array);

      instr_name = string_array[0];

      if (instr_name == current_instr)

         break;

      if (FileIsEnding(file))

         return;

   }

     

   while (true) {

      instr_time = string_array[2];

      StringReplace(instr_time, "-", ".");

      while (true) {

         that_time = TimeToString(time[i], TIME_DATE);

         if(that_time == instr_time) {

            ComLongBuf[i] = StringToDouble(string_array[11]);

            ComShortBuf[i] = StringToDouble(string_array[12]);

            OIBuf[i] = StringToDouble(string_array[7]);

            ComAllBuf[i] = ComLongBuf[i] - ComShortBuf[i];

            break;

         }

         else {

            

            --i;

            if (i < 0)

               return;

         }

      }

      filestring = FileReadString(file);

      StringSplit(filestring, ',', string_array);

      instr_name = string_array[0];

      if(instr_name != current_instr) 

         break;

  }

   

}    





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(prev_calculated == 0) {

      ArrayInitialize(ComLongBuf, 0);

      ArrayInitialize(ComShortBuf, 0);

      ArrayInitialize(ComAllBuf, 0);

      ArrayInitialize(OIBuf, 0);

      int i = rates_total - 1;

      

      

      while (true) {

         file_handler(file2021, i, time);

         if (i <=0) break;

         file_handler(file2020, i, time);

         if (i <=0) break;

         file_handler(file2019, i, time);

         if (i <=0) break;

         file_handler(file2018, i, time);

         if (i <=0) break;

         file_handler(file2017, i, time);

      }

         

      for(int i = 1; i < rates_total; ++i) {

         if(ComLongBuf[i] == 0)

            ComLongBuf[i] = ComLongBuf[i-1];

         if(ComShortBuf[i] == 0)

            ComShortBuf[i] = ComShortBuf[i-1];

         if(ComAllBuf[i] == 0)

            ComAllBuf[i] = ComAllBuf[i-1];

         if(OIBuf[i] == 0)

            OIBuf[i] = OIBuf[i-1];

      }

   }

   else {

      ComLongBuf[rates_total-1] = ComLongBuf[rates_total-2];

      ComShortBuf[rates_total-1] = ComShortBuf[rates_total-2];

      ComAllBuf[rates_total-1] = ComAllBuf[rates_total-2];

      OIBuf[rates_total-1] = OIBuf[rates_total-2];

   }





   return(rates_total);

}

//+------------------------------------------------------------------+

Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
 
А с чего вы взяли что не связывается?
 
TheXpert #:
А с чего вы взяли что не связывается?
Данная Функция возвращает true или false, в зависимости от результата своей работы. Соответственно проверяю возвращаемое значение и понимаю что там фейл. Потом при попытке работы с массивом возникает ошибка out of range
 

рекомендация всегда одна - через Создать новый индикатор, задать параметры и потом скопировать себе

где-то нарушена последовательность.

 
разобрался в чем проблема. В связанном файле .mqproj, поменял в нем количество буферов и все стало нормально. Честно говоря не понимаю нафиг он нужен. Раньше он вроде не создавался
 
Владимир Бут #:
Честно говоря не понимаю нафиг он нужен. 

Для того чтобы объединить все модули в проект, а также для управления режимом компиляции и т.п. Если проект вам не нужен, то кто мешает удалить файл в корзину?

 
Владимир Бут #:
разобрался в чем проблема. В связанном файле .mqproj, поменял в нем количество буферов и все стало нормально. Честно говоря не понимаю нафиг он нужен. Раньше он вроде не создавался

Всё просто. 

#property indicator_plots   3
Вы сами ограничили число отрисовываемых буферов. 
 
Алексей Тарабанов #:

Всё просто. 

Вы сами ограничили число отрисовываемых буферов. 

все правильно, 3 для рисования, и 1 калькуляция в коде