- Вопросы от начинающих MQL5 MT5 MetaTrader 5
- Любые вопросы новичков по MQL4 и MQL5, помощь и обсуждение по алгоритмам и кодам
- Как сделать закрытие ордеров в определенный день недели,каждый день,или закрытие ордеров отключено
Доброго времени суток всем ответившим,да и всем форумчанам. Я чето совсем запутался, и решил заново взять стандартный код и снова начать разбираться. Я вывожу значение значение индикатора, и по идеи оно должно совпадать с закрытием свечи которую я указал (в моем случае 10-ый бар),но смотрю на значение бара и оно не совпадает. Я не пойму в чем ошибка, откуда он берет это значение Close ??? Я просто только начал изучать mql5 и хочу сделать простое пересечение скользящих. Но для этого нужно получить значения скользящих. А в моем случае какая-то белиберда получается! Конечно понимаю,что это я не могу допетрить нормально. Подскажите кто знает в чем причина?! ЗАранее спасибо всем за ответы.
//---- indicator buffers double MA[]; // массив для индикатора iMA //---- handles for indicators int MA_handle; // указатель на индикатор iMA //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { Comment(" "); //--- создание указателя на объект - индикатор iMA MA_handle=iMA(NULL,0,21,0,MODE_EMA,PRICE_CLOSE); //--- если произошла ошибка при создании объекта, то выводим сообщение if(MA_handle<0) { Print("Объект iMA не создан: MA_handle= ",INVALID_HANDLE); Print("Ошибка исполнения = ",GetLastError()); //--- принудительное завершение программы return(-1); } return(0); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- заполнение массива MA[] текущими значениями индикатора iMA //--- в массив будет записано 100 элементов, а если произошла //--- ошибка, то прекращаем выполнение дальнейших операций if(CopyBuffer(MA_handle,0,0,100,MA)<=0) return; //--- задаём порядок индексации массива MA[] как в таймсерии ArraySetAsSeries(MA,true); Comment("MA_1 = "+DoubleToString(MA[10],_Digits)); //--- а дальше делайте с этими данными всё что угодно } Вот к примеру запускаю код на EURUSD,H1 и у меня выводит значение MA_1 = 1.21170, смотрю назначения 10-го бара, Close 21.21261, а по идеи должно быть закрытие 10-бара 1.21170,или я что то путаю? Говорю же уже запутался пипец!
Пример кода:
//+------------------------------------------------------------------+ //| Example Intersection of two iMAs.mq5 | //| Copyright 2021, MetaQuotes Software Corp. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2021, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.000" //--- input parameters input group "Moving Average 'Fast'" input int Inp_MA_Fast_ma_period = 3; // MA Fast: averaging period input int Inp_MA_Fast_ma_shift = 0; // MA Fast: horizontal shift input ENUM_MA_METHOD Inp_MA_Fast_ma_method = MODE_SMA; // MA Fast: smoothing type input ENUM_APPLIED_PRICE Inp_MA_Fast_applied_price = PRICE_CLOSE; // MA Fast: type of price input group "Moving Average 'Slow'" input int Inp_MA_Slow_ma_period = 12; // MA Slow: averaging period input int Inp_MA_Slow_ma_shift = 1; // MA Slow: horizontal shift input ENUM_MA_METHOD Inp_MA_Slow_ma_method = MODE_SMA; // MA Slow: smoothing type input ENUM_APPLIED_PRICE Inp_MA_Slow_applied_price = PRICE_CLOSE; // MA Slow: type of price input group "Additional features" input bool InpPrintLog = false; // Print log //--- bool m_init_error = false; // error on InInit int handle_iMA_Fast; // variable for storing the handle of the iMA indicator int handle_iMA_Slow; // variable for storing the handle of the iMA indicator //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- create handle of the indicator iMA handle_iMA_Fast=iMA(Symbol(),Period(),Inp_MA_Fast_ma_period,Inp_MA_Fast_ma_shift, Inp_MA_Fast_ma_method,Inp_MA_Fast_applied_price); //--- if the handle is not created if(handle_iMA_Fast==INVALID_HANDLE) { //--- tell about the failure and output the error code PrintFormat("Failed to create handle of the iMA indicator (\"Fast\") for the symbol %s/%s, error code %d", Symbol(),Period(),GetLastError()); //--- the indicator is stopped early return(INIT_FAILED); } //--- create handle of the indicator iMA handle_iMA_Slow=iMA(Symbol(),Period(),Inp_MA_Slow_ma_period,Inp_MA_Slow_ma_shift, Inp_MA_Slow_ma_method,Inp_MA_Slow_applied_price); //--- if the handle is not created if(handle_iMA_Slow==INVALID_HANDLE) { //--- tell about the failure and output the error code PrintFormat("Failed to create handle of the iMA indicator (\"Slow\") for the symbol %s/%s, error code %d", Symbol(),Period(),GetLastError()); //--- the indicator is stopped early return(INIT_FAILED); } //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- double ma_fast[],ma_slow[]; ArraySetAsSeries(ma_fast,true); ArraySetAsSeries(ma_slow,true); int start_pos=0,count=3; if(!iGetArray(handle_iMA_Fast,0,start_pos,count,ma_fast) || !iGetArray(handle_iMA_Slow,0,start_pos,count,ma_slow)) return; string ima_values=""; for(int i=0; i<count; i++) ima_values=ima_values+IntegerToString(i)+": Fast "+DoubleToString(ma_fast[i],Digits()+1)+", Slow "+DoubleToString(ma_slow[i],Digits()+1)+"\n"; string ima_intersections="no crossing"; if(ma_fast[1]<ma_slow[1] && ma_fast[0]>ma_slow[0]) ima_intersections="crossing up"; else if(ma_fast[1]>ma_slow[1] && ma_fast[0]<ma_slow[0]) ima_intersections="crossing down"; Comment(ima_values+"\n"+ima_intersections); } //+------------------------------------------------------------------+ //| Get value of buffers | //+------------------------------------------------------------------+ bool iGetArray(const int handle,const int buffer,const int start_pos, const int count,double &arr_buffer[]) { bool result=true; if(!ArrayIsDynamic(arr_buffer)) { if(InpPrintLog) PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__); return(false); } ArrayFree(arr_buffer); //--- reset error code ResetLastError(); //--- fill a part of the iBands array with values from the indicator buffer int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer); if(copied!=count) { //--- if the copying fails, tell the error code if(InpPrintLog) PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d", __FILE__,__FUNCTION__,count,copied,GetLastError()); //--- quit with zero result - it means that the indicator is considered as not calculated return(false); } return(result); } //+------------------------------------------------------------------+
И результат работы:
Пример кода:
И результат работы:
О! По моему это самое то!) Но теперь нужно в этом коде разобраться и думаю тогда все станет понятно!! Спасибо Вам большое Владимир!!!!
- Бесплатные приложения для трейдинга
- 8 000+ сигналов для копирования
- Экономические новости для анализа финансовых рынков
Вы принимаете политику сайта и условия использования