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

 
The terminal simply discards all the extra characters.

If you open with this volume:
0.029

it will open 0.02 lots

and if it opens with that volume:

NormalizeDouble(0.029,2)
it will open 0.03 lots.
 
multiplicator:

How do I calculate the number of decimal places?

for example, i found out that the minimum lot is 0.01.

how do i deduce that the number of decimal places is 2?
to normalise the order volume to two decimal places.

here is the codeword:
void OnStart()
  {
  double minlot=MarketInfo(Symbol(),MODE_MINLOT);
  Alert(d(minlot));
  }




int d(double x)
{
   int n;
   for(n=0;n<8;n++)
   {
      if(x==NormalizeDouble(x,n))      
      {
         return(n);
      }
   }
return(n-1);
}
 
multiplicator:
The terminal simply discards all extra signs.

If we open with this volume:

it will open 0.02 lots.

and if you open with that volume:

it will open 0.03 lots.

What if you need to open 0.25 lots? Here are ready and working functions, read them and use them.

https://www.mql5.com/ru/forum/131859/page8#comment_3359730


multiplicator:

e.g. we put the value in the function: 7 lots.
The broker has a minimum lot volume of 5 and a lot increment of 2.

here's my lot normalization f-function, I've been using it for a long time, no one has complained yet. There you can find out the lot increment and then round it up to the number of digits of the lot increment.

//_______________________________________________________________________
//Нормализация объема лота для ордера up=true - в большую сторону, иначе в меньшую
//_______________________________________________________________________
double NormalizeLot(double value, bool up=false){
   double res,sizetable[9] = {1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001};
   double lotStep = MarketInfo(Symbol(),MODE_LOTSTEP);
   int lotdigits;
   for (lotdigits=8; lotdigits>=0 ; lotdigits--) if (lotStep <= sizetable[lotdigits]) break;
   if(up) res = NormalizeDouble(MathCeil(MathMin(MathMax(value, MarketInfo(Symbol(),MODE_MINLOT)), MarketInfo(Symbol(),MODE_MAXLOT))/lotStep)*lotStep,lotdigits); 
         else res = NormalizeDouble(MathFloor(MathMin(MathMax(value, MarketInfo(Symbol(),MODE_MINLOT)), MarketInfo(Symbol(),MODE_MAXLOT))/lotStep)*lotStep,lotdigits);
return(res);}
//_______________________________________________________________________
Well, if you found a server that has a lot step, for example, 0.37, then there is only addition and comparison to the required lot in the loop, but there were no such servers, it seems there are non-standard lots on bitcoin, not engaged, I do not know, you need a specific situation
Только "Полезные функции от KimIV".
Только "Полезные функции от KimIV".
  • 2011.02.18
  • www.mql5.com
Все функции взяты из этой ветки - http://forum.mql4...
 

Good day dear colleagues, please help me correctly spell the condition in my EA for entering a trade on SHI_silvertrend_signal indicator signals on binary options, only OP_SELL and OP_BUY. for M1 and M5. The signal comes at the close of the previous candle.


- To open an order at the moment of the signal from the indicator, only on the first candle after the signal

- not longer than 5 seconds from the moment the signal is received.

- Acceptable price change within Slippage



(The indicator has 2 buffers)

from the indicator comment// both buffers to be filled with zeros. Otherwise there will be rubbish when changing timeframe.

Thanks in advance for your help and support!

void OnTick()

{

.....

  if((CountSell() + CountBuy())== 0 && isTradeHours())

   {

      SignalBuy = iCustom(NULL, 0, "SST", AllBars, Otstup, Per, 0,0); //получаемое значение в формате 4546546549.0 

      SignalSell = iCustom(NULL, 0, "SST", AllBars, Otstup, Per, 1,0);



      if((Ask <= SignalBuy - Slippage*Point || Ask  <= SignalBuy + Slippage*Point) && iBarShift(NULL, 0,TimeSeconds(TimeCurrent())))    //<---- помогите дописать условие

      {

         if(OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0,IntegerToString(Expiration), Magic, 0, Blue) > 0)

         {

            Print("Ордер на покупку открыт!");

            return;

         }else Print("Ошибка открытия ордера на покупку!");

      }  

         

      if((Bid >= SignalSell - Slippage*Point || Bid >= SignalSell + Slippage*Point) && iBarShift(NULL, 0,TimeSeconds(TimeCurrent())))  //<---- помогите дописать условие

      {  

      if(OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0,IntegerToString(Expiration), Magic, 0, Red) > 0)

         {

            Print("Ордер на продажу открыт!");

            return;

         }else Print("Ошибка открытия ордера на продажу!");

      }

   }

}

.......

The code of the indicator itself (I found it on the internet, if publishing the code does not contradict the forum rules?)

//+------------------------------------------------------------------+
//|                                           SHI_SilverTrendSig.mq4 |
//|       Copyright © 2003, VIAC.RU, OlegVS, GOODMAN, © 2005, Shurka |
//|                                                 shforex@narod.ru |
//|                                                                  |
//|                                                                  |
//| Пишу программы на заказ                                          |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, Shurka"
#property link      "http://shforex.narod.ru"

#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 Red
#property indicator_color2 Blue
#define   SH_BUY   1
#define   SH_SELL  -1

//---- Входные параметры
extern int     AllBars=0;//Для скольки баров считать. 0 - для всех.
extern int     Otstup=30;//Отступ.
extern int     Per=9;//Период.
int            SH,NB,i,UD;
double         R,SHMax,SHMin;
double         BufD[];
double         BufU[];
//+------------------------------------------------------------------+
//| Функция инициализации                                            |
//+------------------------------------------------------------------+
int init()
{
   //В NB записываем количество баров для которых считаем индикатор
   if (Bars<AllBars+Per || AllBars==0) NB=Bars-Per; else NB=AllBars;
   IndicatorBuffers(2);
   IndicatorShortName("SST");
   SetIndexStyle(0,DRAW_ARROW,0,1);
   SetIndexStyle(1,DRAW_ARROW,0,1);
   SetIndexArrow(0,159);
   SetIndexArrow(1,159);
   SetIndexBuffer(0,BufU);
   SetIndexBuffer(1,BufD);
   SetIndexDrawBegin(0,Bars-NB);//Индикатор будет отображаться только для NB баров
   SetIndexDrawBegin(1,Bars-NB);
   ArrayInitialize(BufD,0.0);//Забьём оба буфера ноликами. Иначе будет мусор при смене таймфрейма.
   ArrayInitialize(BufU,0.0);
   return(0);
}
//+------------------------------------------------------------------+
//| Функция деинициализации                                          |
//+------------------------------------------------------------------+
int deinit()
{
   return(0);
}
//+------------------------------------------------------------------+
//| Собсна индикатор                                                 |
//+------------------------------------------------------------------+
int start()
{
   int CB=IndicatorCounted();
   /* Тут вот та самая оптимизационная фишка. В язык введена функция, которая возвращает количество
   посчитанных баров, причём очень хитро. При первом вызове индикатора это 0, всё понятно, ещё ничего
   не считалось, а затем выдаёт количество обсчитанных баров минус один. Т.е. если всего баров 100,
   то функция вернёт 99. Я ввёл такой код, выше у меня определялась NB - кол-во баров подлежащих
   обсчёту. В принципе этот параметр можно и выкинуть, однако для тех кто в танке (I80286) можно
   и оставить. Так вот, здесь, при первом вызове NB остаётся прежней, а при последующих уменьшается
   до последнего бара, т.е. 1 или 2, ну или сколько там осталось посчитать*/
   if(CB<0) return(-1); else if(NB>Bars-CB) NB=Bars-CB;
   for (SH=1;SH<NB;SH++)//Прочёсываем график от 1 до NB
   {
      for (R=0,i=SH;i<SH+10;i++) {R+=(10+SH-i)*(High[i]-Low[i]);}      R/=55;

      SHMax = High[Highest(NULL,0,MODE_HIGH,Per,SH)];
      SHMin = Low[Lowest(NULL,0,MODE_LOW,Per,SH)];
      if (Close[SH]<SHMin+(SHMax-SHMin)*Otstup/100 && UD!=SH_SELL) { BufD[SH]=High[SH]+R*0.5; UD=SH_SELL; }
      if (Close[SH]>SHMax-(SHMax-SHMin)*Otstup/100 && UD!=SH_BUY) { BufU[SH]=Low[SH]-R*0.5; UD=SH_BUY; }
   }
   return(0);
}
 

Igor Makanu:

res = NormalizeDouble(MathFloor(MathMin(MathMax(value, MarketInfo(Symbol(),MODE_MINLOT)), MarketInfo(Symbol(),MODE_MAXLOT))/lotStep)*lotStep,lotdigits);


(What a twist. matmax, then matmin. )

 

where is the optimisation key missing?



how to optimise???


 

Please advise how to correctly specify the condition for entering a trade on the indicator signal.


I wrote a simple advisor for Renko charts that looks like this:

extern double LotSize = 0.01;
extern int Magic = 1;

int prevtime = 0;

int start() {
 
   
//При образовании нового кубика ренко проверка на Buy или Sell и заключение ордера
   if (prevtime != Time[0]) {

   if (Close[1] > Open[1]) {
      OrderSend(Symbol(), OP_BUY, LotSize, ND(Ask), 3, 0, 0,  "RG", Magic, 0, Blue);
      }
   if (Close[1] < Open[1]) {
      OrderSend(Symbol(), OP_SELL, LotSize, ND(Bid), 3, 0, 0, "RG", Magic, 0, Red);
      }
      Magic++;
   prevtime = Time[0];
    }
        return(0);
} 

double ND(double np) {
  return(NormalizeDouble(np,Digits));
}


I am not very happy with the offline chart and have decided to combine it with the AG_Renko_Chart indicator. I am attaching it to my message.

But here is how the function that returns the renko value on the right edge:

iCustom(_Symbol,TF,"AG_Renko_Chart",Step,false,false,Revers,0,0);

I can't figure out how to distinguish between downward or upward bar... And how to properly prescribe a function that would not make a lot of trades ...


In general, my head is not thinking straight. Help please!!!!

Files:
 
Roman Shiredchenko:

where is the optimisation key missing?



how to optimise???


Is this a joke or a social joke???


 
Alexey Viktorov:

Is this a joke or are you making fun of society?


It's not a joke and that's not how I'm mocking society.

Take a good look at the picture before you post heresy.

 
Roman Shiredchenko:

it's not a joke and that's not how I mock.

Look at the picture carefully before you post heresy.

The problem is the screen resolution.