Нужна помощь в переделке индикатора (в место стандартной синусойды отрисовывает прямоугольную синусойду)
Игорь:
Должно быть вот так (мт4)
вот сам рабочий код (мт4)
вот, что у меня получается в мт5
вот код в мт5
В МТ5 iMA возвращает хендл индикатора, а не значения. И должно использоваться в функции OnInit. А в функции OnCalculate используем CopyBuffer
Dmitriy Gizlyk #:
В МТ5 iMA возвращает хендл индикатора, а не значения. И должно использоваться в функции OnInit. А в функции OnCalculate используем CopyBuffer
код стал править "и началось в колхозе утро")
//+------------------------------------------------------------------+ //| Palpite_MACD.mq5 | //| Copyright © 2016, Palpite | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, Palpite" #property link "" #property indicator_separate_window #property indicator_height 150 #property indicator_buffers 5 #property indicator_plots 3 //--- plot MACD #property indicator_label1 "MACD" #property indicator_type1 DRAW_LINE #property indicator_color1 clrForestGreen #property indicator_style1 STYLE_SOLID #property indicator_width1 1 #property indicator_style1 STYLE_SOLID #property indicator_width1 1 //--- plot Signal #property indicator_label2 "MACD" #property indicator_type2 DRAW_LINE #property indicator_color2 clrYellow #property indicator_style2 STYLE_DOT #property indicator_width2 1 //--- plot Histogram #property indicator_label3 "Histogram" #property indicator_type3 DRAW_HISTOGRAM #property indicator_color3 clrGreen #property indicator_style3 STYLE_SOLID #property indicator_width3 2 //---- input parameters input int FastMAPeriod = 12,//FastMAPeriod SlowMAPeriod = 26,// SlowMAPeriod SignalMAPeriod = 9;//SignalMAPeriod input ENUM_APPLIED_PRICE InpAppliedPrice = PRICE_CLOSE; // Applied price //---- buffers double BufferMACD[]; double BufferSignal[]; double BufferHistogram[]; double BufferHistogram1[]; double BufferColors[]; double BufferMA[]; double Signal, Signal_1; //--- global variables int period_fma; int period_sma; int period_sig; int period_max; int handle_ma; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ void OnInit() { //--- set global variables period_fma=int(FastMAPeriod<1 ? 1 : FastMAPeriod); period_sma=int(SlowMAPeriod==period_fma ? period_fma+1 : SlowMAPeriod<1 ? 1 : SlowMAPeriod); period_sig=int(SignalMAPeriod<1 ? 1 : SignalMAPeriod); period_max=fmax(period_sig,fmax(period_fma,period_sma)); //--- indicator buffers mapping SetIndexBuffer(0,BufferMACD,INDICATOR_DATA); SetIndexBuffer(1,BufferSignal,INDICATOR_DATA); SetIndexBuffer(2,BufferHistogram,INDICATOR_DATA); SetIndexBuffer(3,BufferColors,INDICATOR_COLOR_INDEX); SetIndexBuffer(4,BufferMA,INDICATOR_CALCULATIONS); //--- setting indicator parameters IndicatorSetString(INDICATOR_SHORTNAME,"VAMA MACD ("+(string)period_fma+","+(string)period_sma+","+(string)period_sig+")"); IndicatorSetInteger(INDICATOR_DIGITS,Digits()); //--- setting plot buffer parameters PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0); PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0); PlotIndexSetDouble(2,PLOT_EMPTY_VALUE,0); //--- setting buffer arrays as timeseries ArraySetAsSeries(BufferMACD,true); ArraySetAsSeries(BufferSignal,true); ArraySetAsSeries(BufferHistogram,true); ArraySetAsSeries(BufferColors,true); ArraySetAsSeries(BufferMA,true); //--- create MA's handles ResetLastError(); handle_ma=iMA(NULL,PERIOD_CURRENT,1,0,MODE_SMA,InpAppliedPrice); if(handle_ma==INVALID_HANDLE) { Print("The iMA(1) object was not created: Error ",GetLastError()); } //--- } //+------------------------------------------------------------------+ //| 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[]) { //--- Установка массивов буферов как таймсерий ArraySetAsSeries(tick_volume,true); //--- Проверка и расчёт количества просчитываемых баров if(rates_total<SignalMAPeriod) return 0; //--- Проверка и расчёт количества просчитываемых баров int calculated=BarsCalculated(ExtFastMaHandle); if(calculated<rates_total) { Print("Not all data of ExtFastMaHandle is calculated (",calculated,"bars ). Error",GetLastError()); return(0); } calculated=BarsCalculated(ExtSlowMaHandle); if(calculated<rates_total) { Print("Not all data of ExtSlowMaHandle is calculated (",calculated,"bars ). Error",GetLastError()); return(0); } //--- we can copy not all data ; мы можем скопировать не все данные int to_copy; if(prev_calculated>rates_total || prev_calculated<0) to_copy=rates_total; else { to_copy=rates_total-prev_calculated; if(prev_calculated>0) to_copy++; } //--- get Fast EMA buffer if(IsStopped()) return(0); //Checking for stop flag if(CopyBuffer(ExtFastMaHandle,0,0,to_copy,ExtFastMaBuffer)<=0) { Print("Getting fast EMA is failed! Error",GetLastError()); return(0); } //--- get SlowSMA buffer if(IsStopped()) return(0); //Checking for stop flag if(CopyBuffer(ExtSlowMaHandle,0,0,to_copy,ExtSlowMaBuffer)<=0) { Print("Getting slow SMA is failed! Error",GetLastError()); return(0); } int limit; if(prev_calculated==0) limit=0; else limit=prev_calculated-1; { limit=rates_total-period_max-2; ArrayInitialize(BufferMACD,0); ArrayInitialize(BufferSignal,0); ArrayInitialize(BufferHistogram,0); ArrayInitialize(BufferMA,0); } //---- double value=0; for(int i = limit; i >= 0; i--) { BufferMACD[i] = iMA(NULL, 0, FastMAPeriod, 0, MODE_EMA,InpAppliedPrice) - iMA(NULL, 0, SlowMAPeriod, 0, MODE_EMA,InpAppliedPrice); BufferSignal[i]= Signal*BufferMACD[i] + Signal_1*BufferSignal[i+1]; BufferHistogram[i] = BufferMACD[i] - BufferSignal[i]/100; BufferHistogram1[i] = BufferHistogram[i]; if (value>BufferSignal[i] - BufferMACD[i]) BufferHistogram[i]=value; if (value<BufferSignal[i] - BufferMACD[i]) BufferHistogram1[i]=value; } //---- return(rates_total); } //+------------------------------------------------------------------+
Люди пните меня в нужном направленнн).
Люди если не трудно, посмотрите, всё у меня в порядке в этом куске кода.
#property copyright "Copyright © 2005, Palpite" #property link "" #include <MovingAverages.mqh> #property indicator_separate_window //#property indicator_height 150 #property indicator_buffers 6 #property indicator_plots 4 //--- plot MACD #property indicator_type1 DRAW_LINE #property indicator_color1 White #property indicator_width1 1 #property indicator_label1 "DIFF" #property indicator_type2 DRAW_LINE #property indicator_color2 Yellow #property indicator_width2 1 #property indicator_label2 "DEA" #property indicator_type3 DRAW_HISTOGRAM #property indicator_color3 Red #property indicator_width3 1 #property indicator_label3 "MACD" #property indicator_type4 DRAW_HISTOGRAM #property indicator_color4 Turquoise #property indicator_width4 1 #property indicator_label4 "MACD" //---- input parameters input int FastMAPeriod = 12,//FastMAPeriod SlowMAPeriod = 26,//SlowMAPeriod SignalMAPeriod = 9;//SignalMAPeriod input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price //---- buffers double ExtDIFFBuffer[]; double ExtDEABuffer[]; double ExtMACDRBuffer[]; double ExtMACDGBuffer[]; double ExtFastMaBuffer[]; double ExtSlowMaBuffer[]; //--- MA handles int ExtFastMaHandle; int ExtSlowMaHandle; int period_fma; int period_sma; int period_sig; int period_max; int handle_ma; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ void OnInit() { //--- set global variables period_fma=int(FastMAPeriod<1 ? 1 : FastMAPeriod); period_sma=int(SlowMAPeriod==period_fma ? period_fma+1 : SlowMAPeriod<1 ? 1 : SlowMAPeriod); period_sig=int(SignalMAPeriod<1 ? 1 : SignalMAPeriod); period_max=fmax(period_sig,fmax(period_fma,period_sma)); // IndicatorDigits(Digits + 1); IndicatorSetInteger(INDICATOR_DIGITS,_Digits+1); //---- indicators SetIndexBuffer(0,ExtDIFFBuffer,INDICATOR_DATA); SetIndexBuffer(1,ExtDEABuffer,INDICATOR_DATA); SetIndexBuffer(2,ExtMACDRBuffer,INDICATOR_DATA); SetIndexBuffer(3,ExtMACDGBuffer,INDICATOR_DATA); SetIndexBuffer(4,ExtFastMaBuffer,INDICATOR_CALCULATIONS); SetIndexBuffer(5,ExtSlowMaBuffer,INDICATOR_CALCULATIONS); //--- sets first bar from what index will be drawn PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,SignalMAPeriod-1); // New //--- name for Dindicator subwindow label IndicatorSetString(INDICATOR_SHORTNAME,"MACD_DL("+string(FastMAPeriod)+","+string(SlowMAPeriod)+","+string(SignalMAPeriod)+")"); //--- get MA handles ExtFastMaHandle=iMA(NULL,0,FastMAPeriod,0,MODE_EMA,InpAppliedPrice); ExtSlowMaHandle=iMA(NULL,0,SlowMAPeriod,0,MODE_EMA,InpAppliedPrice); }
Ну всё код подправил ошибок и предупреждений нет. Однако выявил разницу в отрисовки индикатора.
должно быть так
после переделки на мт5, выглядит так
вот сам код (возможны ошибки по логике)
//+------------------------------------------------------------------+ //| Palpite_MACD.mq5 | //| Copyright © 2016, Palpite | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, Palpite" #property link "" #include <MovingAverages.mqh> #property indicator_separate_window //#property indicator_height 150 #property indicator_buffers 6 #property indicator_plots 4 //--- plot MACD #property indicator_type1 DRAW_LINE #property indicator_color1 White #property indicator_width1 1 #property indicator_label1 "DIFF" #property indicator_type2 DRAW_LINE #property indicator_color2 Yellow #property indicator_width2 1 #property indicator_label2 "DEA" #property indicator_type3 DRAW_HISTOGRAM #property indicator_color3 Red #property indicator_width3 1 #property indicator_label3 "MACD" #property indicator_type4 DRAW_HISTOGRAM #property indicator_color4 Turquoise #property indicator_width4 1 #property indicator_label4 "MACD" //---- input parameters input int FastMAPeriod = 12,//FastMAPeriod SlowMAPeriod = 26,//InpSlowEMA SignalMAPeriod = 9;//SlowMAPeriod input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price //---- buffers double ExtDIFFBuffer[]; double ExtDEABuffer[]; double ExtMACDRBuffer[]; double ExtMACDGBuffer[]; double ExtFastMaBuffer[]; double ExtSlowMaBuffer[]; //--- MA handles int ExtFastMaHandle; int ExtSlowMaHandle; int period_fma; int period_sma; int period_sig; int period_max; int handle_ma; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ void OnInit() { //--- set global variables period_fma=int(FastMAPeriod<1 ? 1 : FastMAPeriod); period_sma=int(SlowMAPeriod==period_fma ? period_fma+1 : SlowMAPeriod<1 ? 1 : SlowMAPeriod); period_sig=int(SignalMAPeriod<1 ? 1 : SignalMAPeriod); period_max=fmax(period_sig,fmax(period_fma,period_sma)); // IndicatorDigits(Digits + 1); IndicatorSetInteger(INDICATOR_DIGITS,_Digits+1); //---- indicators SetIndexBuffer(0,ExtDIFFBuffer,INDICATOR_DATA); SetIndexBuffer(1,ExtDEABuffer,INDICATOR_DATA); SetIndexBuffer(2,ExtMACDRBuffer,INDICATOR_DATA); SetIndexBuffer(3,ExtMACDGBuffer,INDICATOR_DATA); SetIndexBuffer(4,ExtFastMaBuffer,INDICATOR_CALCULATIONS); SetIndexBuffer(5,ExtSlowMaBuffer,INDICATOR_CALCULATIONS); //--- sets first bar from what index will be drawn PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,SignalMAPeriod-1); // New //--- name for Dindicator subwindow label IndicatorSetString(INDICATOR_SHORTNAME,"MACD_DL("+string(FastMAPeriod)+","+string(SlowMAPeriod)+","+string(SignalMAPeriod)+")"); //--- get MA handles ExtFastMaHandle=iMA(NULL,0,FastMAPeriod,0,MODE_EMA,InpAppliedPrice); ExtSlowMaHandle=iMA(NULL,0,SlowMAPeriod,0,MODE_EMA,InpAppliedPrice); } //+------------------------------------------------------------------+ //| 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 &TickVolume[], const long &Volume[], const int &Spread[]) { //--- check for data //проверка наличия данных if(rates_total<SlowMAPeriod) return(0); //--- not all data may be calculated //не все данные могут быть рассчитаны int calculated=BarsCalculated(ExtFastMaHandle); if(calculated<rates_total) { Print("Not all data of ExtFastMaHandle is calculated (",calculated,"bars ). Error",GetLastError()); return(0); } calculated=BarsCalculated(ExtSlowMaHandle); if(calculated<rates_total) { Print("Not all data of ExtSlowMaHandle is calculated (",calculated,"bars ). Error",GetLastError()); return(0); } //--- we can copy not all data //мы можем скопировать не все данные int to_copy; if(prev_calculated>rates_total || prev_calculated<0) to_copy=rates_total; else { to_copy=rates_total-prev_calculated; if(prev_calculated>0) to_copy++; } //--- get Fast EMA buffer //получите быстрый буфер EMA if(CopyBuffer(ExtFastMaHandle,0,0,to_copy,ExtFastMaBuffer)<=0) { Print("Getting fast EMA is failed! Error",GetLastError()); return(0); } //--- get SlowSMA buffer //получить буфер SlowSMA if(CopyBuffer(ExtSlowMaHandle,0,0,to_copy,ExtSlowMaBuffer)<=0) { Print("Getting slow SMA is failed! Error",GetLastError()); return(0); } //--- int limit; if(prev_calculated==0) limit=0; else limit=prev_calculated-1; //--- calculate DIFF //вычислить РАЗНИЦУ for(int i=limit;i<rates_total;i++) ExtDIFFBuffer[i]=ExtFastMaBuffer[i]-ExtSlowMaBuffer[i]; //--- calculate DEA //рассчитать DEA SimpleMAOnBuffer(rates_total,prev_calculated,0,SlowMAPeriod,ExtDIFFBuffer,ExtDEABuffer); //--- calculate MACD //рассчитать MACD for(int i=limit;i<rates_total;i++) { if(ExtDIFFBuffer[i] > ExtDEABuffer[i]) { ExtMACDRBuffer[i] = 2*(ExtDIFFBuffer[i]-ExtDEABuffer[i]); ExtMACDGBuffer[i] = 0; } else { ExtMACDGBuffer[i] = 2*(ExtDIFFBuffer[i]-ExtDEABuffer[i]); ExtMACDRBuffer[i] = 0; } } //--- OnCalculate done. Return new prev_calculated. //На расчетном. Возвращает новый prev_calculated. return(rates_total); } //+----------------------------
Вы упускаете торговые возможности:
- Бесплатные приложения для трейдинга
- 8 000+ сигналов для копирования
- Экономические новости для анализа финансовых рынков
Регистрация
Вход
Вы принимаете политику сайта и условия использования
Если у вас нет учетной записи, зарегистрируйтесь
Должно быть вот так (мт4)
вот сам рабочий код (мт4)
вот, что у меня получается в мт5
вот код в мт5