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

 
MakarFX

Thanks for the reply, crutch and not a bad solution, but in terms of my idea it works a bit incorrect, because the balance is floating, probably it does not do it instantly and in some cases my orders started to close with minus for some reason. But the growth was as it should be, but the drawdown with those minuses increased as well. I gave up on everything and decided to manually set the pullback limits, so I would have to adjust them daily.

 
Порт-моне тв:

Thanks for the reply, crutch and not a bad solution, but in terms of my idea it works a bit incorrect, because the balance is floating, probably it does not do it instantly and in some cases my orders started to close with minus for some reason. But the growth was as it should be, but the drawdown with those minuses increased as well. I have decided to give up and manually set trading limits and have to adjust it daily.

The function works properly.

Try it like this

//+--------------------------------------------------------------------------------------------------------------------+

sb1 = StartBalance();
................

//+--------------------------------------------------------------------------------------------------------------------+
//|  Баланс на начало периода                                                                                          |
//+--------------------------------------------------------------------------------------------------------------------+
double StartBalance()
  { double b = 0;
   if(AccountBalance()>0) {b = AccountBalance()-DayProfit();}
   return(b);
  }
//+--------------------------------------------------------------------------------------------------------------------+
//|  Суммарный профит на начало периода                                                                                |
//+--------------------------------------------------------------------------------------------------------------------+
double DayProfit()
  { double p = 0; datetime st=iTime(_Symbol,PERIOD_D1,0);
   for(int pos=OrdersHistoryTotal()-1;pos>=0;pos--)
     {
      if(OrderSelect(pos,SELECT_BY_POS,MODE_HISTORY)==true)
        {
         if(OrderSymbol() == _Symbol)
           { 
            if(OrderCloseTime()>=st){p+=OrderProfit()+OrderSwap()+OrderCommission();}
           }
        }
     }
   return(p);
  }
//+--------------------------------------------------------------------------------------------------------------------+

and add balance update to the order closing function

   if(OrderClose(бла бла бла))
     {
      StartBalance(); Print("Order Close");
     }
 
Maxim Kuznetsov:

catch the change of the day and calculate the balance value at that moment.

It's not for nothing that they said "get the right indicator" - it won't fit into a couple of lines of code. It's quite a capacious algorithm.

catching the change of day is easy, "known day number is not equal to the number of the day before", but it's more complicated


Alg. " calculate balance at time D" (excluding withdrawals/replenishments and some bug about swaps and commissions)

Balance:=current account balance. That is AccountBalance().

For all closed market orders in the history:

if closing time falls between D and current, Balance -= OrderProfit()+OrderSwap()+OrderCommision();

on completion of the enumeration, the Balance is the desired value...

BUT, commission is charged (i.e. it affects the balance line) at opening, and we take it into account at closing, and swaps are taken at day change, and we will again take it into account only at closing

and in case of great depth D, there is a chance of not getting all of the required orders in an overshoot

 
Порт-моне тв:

Thanks for the reply, crutch and not a bad solution, but in terms of my idea it works a bit incorrect, because the balance is floating, probably it does not do it instantly and in some cases my orders started to close with minus for some reason. But the growth was as it should be, but the drawdown with those minuses increased as well. I gave up and decided to manually set trading limits and had to adjust it daily.

I'm already lost in your suggestions and advice, so maybe my advice is completely beside the point, but sorry...

I understand what I need at the beginning of the day to fix the balance and for the day to count the profit/loss in accordance with which I need to make a decision on whether to continue trading ...

So here is the decision

datetime dayTime;
double dayBalance;
// Дальше в функции OnTick()
if(dayTime != iTime(_Symbol, PERIOD_D1, 0);
 {
  dayBalance = AccountInfoDouble(ACCOUNT_BALANCE));
  dayTime = iTime(_Symbol, PERIOD_D1, 0);
 }
// Дальше текущий баланс можно сравнивать с балансом на начало дня…
// В начале следующего дня в переменной dayBalance будет другое значение баланса…

If the Expert Advisor will be restarted during the day, you should consider calculation of profits/losses of today's orders taking into account swaps and commissions and calculate the balance for the beginning of the day in OnInit().

I believe in Makar's abilities, he can show all this already in the code...

 

Hello. Can you tell me how to determine the current bar number from the beginning of the day?

How do I determine the number of the current bar from the beginning of the day?

Thank you.

 
prom18:

Hello. Can you tell me how to determine the current bar number from the beginning of the day?

How do I determine the number of the current bar from the beginning of the day?

Thank you.

      double BarNumber=NormalizeDouble((TimeCurrent()-iTime(_Symbol,PERIOD_D1,0))/60/Period()+0.5,0);

this is the current bar, if the last bar closed, then -0.5

 
MakarFX:

is the current bar, if the last bar closed, then -0.5

Thank you. I'll give it a try.

 
MakarFX:

this is the current bar, if last closed, -0.5

it will not work on minutes and exotics.

number of bars != number of_counts

bars are just skipped at a time, in 15 min there may be 12 minute bars

better to use iBarShift()

 
Maxim Kuznetsov:

it is better to use the built-in iBarShift()

I don't know how(

 
MakarFX:

I don't know how(

Function

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 26.02.2008                                                     |
//|  Описание : Возвращает реальный номер бара от начала суток.                |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (NULL или "" - текущий символ)          |
//|    tf - таймфрейм                  (          0 - текущий таймфрейм)       |
//|    dt - дата и время открытия бара (          0 - текущее время)           |
//+----------------------------------------------------------------------------+
int iBarOfDayReal(string sy="", int tf=0, datetime dt=0) {
  if (sy=="" || sy=="0") sy=Symbol();
  if (tf<=0) tf=Period();
  if (dt<=0) dt=TimeCurrent();
  if (tf>PERIOD_D1) {
    Print("iBarOfDayReal(): Таймфрейм должен быть меньше или равен D1");
    return(0);
  }

  int cd=TimeDay(dt);                       // текущий день месяца
  int nb=iBarShift(sy, tf, dt, False);      // номер текущего бара
  int bd=0;                                 // номер бара от начала суток

  while(TimeDay(iTime(sy, tf, nb))==cd) {
    nb++;
    bd++;
  }

  return(bd);
}
Reason: