Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1207

 

why this loop does not end when ... (I added the second condition for i < 2000 when I realized that the loop is infinite) MQL4

cv * tvp * (double)stop < ml


double tvp  = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE_PROFIT),
          vm   = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN),
          vs   = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP),
          ml   = AccountEquity() * (risk / 100.0),
          cv   = -1.0;
   
   for(int i = 0; cv * tvp * (double)stop < ml && i < 2000; i++)
     {
      if( (vm + vs * (double)i) * tvp * (double)stop < ml ) { cv = vm + vs * (double)i; Print(i," ",cv,"/",ml); };
     };


 
Alexandr Sokolov:

why this loop does not end when ... (I added the second condition for i < 2000 when I realized that the loop is infinite)



The loop will not end until

cv * tvp * (double)stop < ml

To make the loop end when this condition is met, we can write the following in the loop's body

for(int i = 0; i < 2000; i++)
{
  if(cv * tvp * (double)stop < ml)
    break
  ...
}

or

for(int i = 0; cv * tvp * (double)stop >= ml; i++)
{
  if(i >= 2000)
    break;
  ...
}
 
Mihail Matkovskij:

In MQL4 only in this way:

Result:


Thanks again for your help. I would be very grateful if you could also tell me how to do the following...
What function or language construct can be used to calculate the index value of an array element that had the index before sorting.

Here, I have array A[] before sorting (the upper line) and the same array after sorting. An element with value 5 before sorting was at index 9
, and an element with value 5 after sorting is at index 3.

I find a cell with value 5 in the sorted array and the function saves the index number of this cell in the sorted array to W, which is equal to index 3

ArraySort(А,10,0,MODE_ASCEND);

W = ArrayBsearch( A,5,WHOLE_ARRAY,0,MODE_ASCEND);

QUESTION: After ArrayBsearch(), how can the value of index of a cell with value 5 be stored in a variable which has an unsorted array.

That is, save the value of 9.
Thank you for your help.

 
 

Hi all. Who knows how to set a negative value in a custom indicator and make it work? i.e. "Shift the indicator relative to the price chart."

Example: If you put a -4 value in the Moving Average indicator, it shifts relative to the chart to the left - and works.

But if you put this value in the code of the indicator - then the indicator stops working. and shows all TF values red.

Files:
 
ANDREY:

Thank you again for your help. I would be very grateful if you could also tell me how to do the following...
What function or language construct can be used to calculate the index value of an array element, which this element had before sorting.

Here, I have array A[] before sorting (the upper line) and the same array after sorting. An element with value 5 before sorting was at index 9
, and an element with value 5 after sorting is at index 3.

I find a cell with value 5 in the sorted array and the function saves the index number of this cell in the sorted array to W, which is equal to index 3

ArraySort(А,10,0,MODE_ASCEND);

W = ArrayBsearch( A,5,WHOLE_ARRAY,0,MODE_ASCEND);

QUESTION: After ArrayBsearch(), how can the value of index of a cell with value 5 be stored in a variable which has an unsorted array.

That is, save the value of 9.
Thanks for your help.

but don't sort the data at random and just for no global purpose.

From the current project: take a (short) array, the output will be element indices in the right order:

void BubleSortIndex5(double &data[5],int &index[5])
{
   for(int i=0;i<5;i++)
      index[i]=i;
   for(int i=0;i<4;i++) {
      for(int j=1;j<5;j++) {
         if (data[index[i]]>data[index[j]]) {
            int tmp=index[i];
            index[i]=index[j];
            index[j]=tmp;
         }
      }
   }
}


for larger arrays we need to change sorting algorithm (bubbling doesn't work for larger arrays) - change it.

The main message is: don't touch the source data. Operate either with references or, even better, with array indices. Otherwise information is lost, which will be very much needed later.

 
ANDREY:

Thank you again for your help. I would be very grateful if you could also tell me how to do the following...
What function or language construct can be used to calculate the index value of an array element, which this element had before sorting.

Here, I have array A[] before sorting (the upper line) and the same array after sorting. An element with value 5 before sorting was at index 9
, and an element with value 5 after sorting is at index 3.

I find a cell with value 5 in the sorted array and the function saves the index number of this cell in the sorted array to W, which is equal to index 3

ArraySort(А,10,0,MODE_ASCEND);

W = ArrayBsearch( A,5,WHOLE_ARRAY,0,MODE_ASCEND);

QUESTION: After ArrayBsearch(), how can the value of index of a cell with value 5 be stored in a variable which has an unsorted array.

That is to save the value of 9.
Thank you for your help.

For this you need to answer two questions.what will you do if:

1. There will be multiple values of 5, in different cells of the array.

2. There will be no value 5 in the array.

BecauseArrayBsearch function(for sorted data), in the first case, will give the first index found where cell value is 5, in the second case, it will give an element close to value 5. How you would want to deal with an unsorted array is not clear to me.

 
sla100:

Hi all. Who knows how to set a negative value in a custom indicator and make it work? i.e. "Shift the indicator relative to the price chart."

Example: If you put a -4 value in the Moving Average indicator, it shifts relative to the chart to the left - and works.

But if you put such a value in the indicator code, the indicator stops working. and shows all TF values red.

SetIndexShift.

The shift is also specified in iMA:

iMA

Returns the value ofthe Moving Average technical indicator.

doubleiMA(
stringsymbol,// symbol name
inttimeframe,// timeframe
intma_period,// period
intma_shift,// shift average
intma_method,// averaging method
intapplied_price,//price type
intshift// shift
);

Parameters

symbol

[in] Symbol name of the symbol which data will be used to calculate the indicator.NULL means current symbol.

timeframe

[in] Period. Can be one of the values of enumerationENUM_TIMEFRAMES. 0 means period of the current chart.

ma_period

[in] Averaging period for the indicator calculation.

ma_shift

[in] Shift of indicator relative to the price chart.

ma_method

[in] Averaging method. Can be any of values of the enumerationENUM_MA_METHOD.

applied_price

[in] Price applied. Can be any value of theENUM_APPLIED_PRICE enumeration.

shift

[in] Index of the value obtained from the indicator buffer (shift relative to the current bar by a specified number of periods back).

Returned value

Valueof Moving Average technical indicator.

Example:

AlligatorJawsBuffer[i]=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i);

https://docs.mql4.com/ru/indicators/ima

Here is a ready-made example, but in MQL5: https://www.mql5.com/ru/docs/indicators/ima ,

which can be easily translated into MQL4.

SetIndexShift - Пользовательские индикаторы - Справочник MQL4
SetIndexShift - Пользовательские индикаторы - Справочник MQL4
  • docs.mql4.com
При положительном значении изображение линии смещается вправо, при отрицательном - влево. Значение, рассчитанное на текущем баре, рисуется с указанным смещением относительно текущего бара.
 

There is no shift in the indicator settings. I went into the code and put shift -4 in the code and the indicator stopped working - it shows all TFs are red. I'm sitting here wondering why.

Торговые советники и собственные индикаторы - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
Торговые советники и собственные индикаторы - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
  • www.metatrader5.com
Среди программ для автоматического трейдинга можно выделить две большие категории: торговые роботы и индикаторы. Первые предназначены для совершения торговых операций на рынках, а вторые — для анализа котировок и выявления закономерностей в их изменении. При этом индикаторы могут использоваться непосредственно в роботах, образуя полноценную...
 
Mihail Matkovskij:

To do this, you need to answer two questions.What will you do if

1. There will be several values of 5, in different cells of the array.

2. The value 5 will not be in the array.

BecauseArrayBsearch function(for sorted data), in the first case, will give the first index found where cell value is 5, in the second case, it will give an element close to value 5. How you would want to deal with an unsorted array is not clear to me.

Thank you very much for your quick response. In my case each value of an array element is unique and exists in a single instance. That is, value 5, like other values, is not repeated.

In my case value 5 may not exist in an unsorted array. It means, some cells in unsorted array may be empty.
But if value 5 is not in unsorted array, then I cannot specify value 5 as second parameter in ArrayBsearch() function. Only values which necessarily exist in unsorted array get into this function.
Thanks for your help

Reason: