I'm twisting the code and can't figure out how to color the mouwing.
If one colour is growing and another is falling.
Can someone show me an example?
//+------------------------------------------------------------------+//| ColorMA.mq5 |//| Copyright 2018, MetaQuotes Software Corp. |//| https://mql5.com/ru/users/artmedia70 |//+------------------------------------------------------------------+#property copyright"Copyright 2018, MetaQuotes Software Corp."#property link"https://mql5.com/ru/users/artmedia70"#property version"1.00"#property description"Colored Moving Average"#property indicator_chart_window#property indicator_buffers2// Всего буферов 2 - рисуемый буфер и буфер цвета#property indicator_plots1// Один рисуемый буфер//--- plot ClrMA#property indicator_label1"Colored MA"#property indicator_type1DRAW_COLOR_LINE#property indicator_color1clrBlue,clrRed,clrDarkGray#property indicator_style1STYLE_SOLID#property indicator_width12//--- input parametersinputuint InpPeriod = 14; // Период расчётаinputENUM_MA_METHOD InpMethod = MODE_SMA; // Метод расчётаinputENUM_APPLIED_PRICE InpAppliedPrice = PRICE_CLOSE; // Цена расчёта//--- indicator buffersdouble BufferMA[]; // Рисуемый буферdouble BufferColors[]; // Буфер цвета//--- global variablesint period;
int handle_ma;
//+------------------------------------------------------------------+//| Custom indicator initialization function |//+------------------------------------------------------------------+intOnInit()
{
//--- set global variables
period=int(InpPeriod<1 ? 1 : InpPeriod);
//--- indicator buffers mappingSetIndexBuffer(0,BufferMA,INDICATOR_DATA); // Рисуемый буферSetIndexBuffer(1,BufferColors,INDICATOR_COLOR_INDEX); // Буфер цвета//--- setting indicator parametersIndicatorSetString(INDICATOR_SHORTNAME,"Colored MA");
IndicatorSetInteger(INDICATOR_DIGITS,Digits());
//--- setting buffer arrays as timeseriesArraySetAsSeries(BufferMA,true);
ArraySetAsSeries(BufferColors,true);
//--- create MA's handlesResetLastError();
handle_ma=iMA(NULL,PERIOD_CURRENT,period,0,InpMethod,InpAppliedPrice);
if(handle_ma==INVALID_HANDLE)
{
Print("Не удалось создать хэндл iMA(",(string)period,") ",EnumToString(InpAppliedPrice),". Ошибка: ",GetLastError());
returnINIT_FAILED;
}
//---return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Custom indicator iteration function |//+------------------------------------------------------------------+intOnCalculate(constint rates_total,
constint prev_calculated,
constdatetime &time[],
constdouble &open[],
constdouble &high[],
constdouble &low[],
constdouble &close[],
constlong &tick_volume[],
constlong &volume[],
constint &spread[])
{
//--- Проверка и расчёт количества просчитываемых баровif(rates_total<fmax(period,4)) return0; // три бара и меньше в расчёт не берём//--- Проверка и расчёт количества просчитываемых баровint limit=rates_total-prev_calculated;
if(limit>1)
{
/*
Почему больше 1. Например, загрузилась история, и разница будет больше одного.
Если все нормально, то разница rates_total-prev_calculated равна или 0, или 1
0 - пришел новый тик, новый бар формироваться не начал.
1 - пришел новый тик и начал формироваться новый бар
*/
limit=rates_total-2; // rates_total - это Bars для текущего символа и периода// Если не требуется проверять в цикле расчёта i+число, то limit=rates_total-1 (чтобы не вылететь за пределы массива), // иначе, если требуется проверять, например, i+period, то limit=rates_total-period-1ArrayInitialize(BufferMA,EMPTY_VALUE);
ArrayInitialize(BufferColors,2);
}
//--- Подготовка данных - в данном случае это и есть расчёт МА - копирование в буфер её значений из хэндлаint count=(limit>1 ? rates_total : 1); // если новый бар, то копируем всю доступную историю, иначе - только один текущийint copied=CopyBuffer(handle_ma,0,0,count,BufferMA);
if(copied!=count) return0; // Если скопировать не удалось - выходим до следующего тика//--- Установка цвета линииfor(int i=limit; i>=0 && !IsStopped(); i--)
{
// Тут всё просто: // У нас задано три цвета: #property indicator_color1 clrBlue,clrRed,clrDarkGray// 1. если МА на текущем баре выше чем МА на прошлом, то цвет под номером 0// 2. если МА на текущем баре ниже чем МА на прошлом, то цвет под номером 1// 3. иначе - цвет под номером 2 (в блоке инициализации в строке 86 задаётся этот цвет начальным для отображения линии, что, впрочем делать там не обязательно)
BufferColors[i]=(BufferMA[i]>BufferMA[i+1] ? 0 : BufferMA[i]<BufferMA[i+1] ? 1 : 2);
}
//--- return value of prev_calculated for next callreturn(rates_total);
}
//+------------------------------------------------------------------+
I've emailed you a slightly awkward example (I haven't corrected the Copy-Paste errors)
There is an error in the cigar service. When you change the leverage, it shows the opposite. For example if you change it from 1:500 to 1:100 it shows that leverage was changed from 1:100 to 1:500. I have to do something about it... )
So the situation here is completely different - there's no template.
The previous example works in C++... so the signatures are somehow taken care of there
What is C++ giving out here?
template<typename T>
void f( T& ) { Print(__FUNCSIG__); }
void g1() { class A { int i; } a; f( a ); }
void g2() { class A { double d; } a; f( a ); }
To make it work in MQL5, the output should contain two different strings, not the same one. But the signature generation mechanism will have to be quite different in this case. If C++ produces the same result in print, the __FUNCSIG__ value will drop dramatically.
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
What is the difference
SetIndexBuffer(1,ValuesPainting,INDICATOR_COLOR_INDEX);
и
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrBlue);
?
I'm twisting the code and can't figure out how to color the mouwing.
If one colour is growing and another is falling.
Can someone show me an example?
I'm spinning the code and I can't figure out how to colour the mouwing.
If one colour rises, if another falls.
Can anybody show me an example?
I am just learning MQL5, but it should look like this:
What is the fundamental difference between (1) and (2) ? Why is there an error in one case and a normal error in the other?
And what is the fundamental difference between (1) and (2) ? Why is there an error in one case and normal in the other?
So classes within functions can have the same name but different contents. The signature f is not clear in the second variant.
After the first one it is defined. And after the second one it is not redefined with the same name.
What is the difference
SetIndexBuffer(1,ValuesPainting,INDICATOR_COLOR_INDEX);
и
PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrBlue);
?
I'm twisting the code and can't figure out how to color the mouwing.
If one colour is growing and another is falling.
Can someone show me an example?
I've emailed you a slightly awkward example (I haven't corrected the Copy-Paste errors)
So classes within functions can have the same name but different contents. The signature f is not clear in the second variant.
Here, everything is the same... and it works
The previous example in C++ works... so the signatures are sorted out there somehow.
What is the fundamental difference between (1)(2) and (3)(4)?
Here it's all the same... and it works.
So the situation here is completely different - there's no template.
The previous example works in C++... so the signatures are somehow taken care of there
What is C++ giving out here?
To make it work in MQL5, the output should contain two different strings, not the same one. But the signature generation mechanism will have to be quite different in this case. If C++ produces the same result in print, the __FUNCSIG__ value will drop dramatically.
What can the following behavior be related to
compile indicator works correctly, compile again indicator does not work correctly. Does it work correctly in the tester?