Help me learn how to program. - page 2

 
Alexey Viktorov:

Thanks for that example.

I thought I was the only one who preferred laying things out that way, rather than writing dickishly.

hz - translated into Russian as "I'd like to know"... don't think badly...

It's better to use classes from the standard library so you don't have to write all those long PositionGet... etc.

 
Dmitry Fedoseev:
Thank you. Digesting.
 
Alexey Viktorov:

Thanks for that example.

I thought I was the only one who preferred to lay things out that way instead of writing it in a dumbed-down way.

What's the problem?

Don't take this asa "coder nazi", but I, for one, find such constructions disturbing:

for(int index=PositionsTotal()-1; index>=0; index--) { /* тело цикла */ }

It's a nuisance to the eye. Wouldn't it be better to make it not"zaz how", but like this:

int index = PositionsTotal();

while (index-- > 0) { /* тело цикла */ }

Or this kind of "shithcoddling":

for(int i=0;i<PositionsTotal();i++)

WherePositionsTotal()is called at each loop iteration!

A normal coder would never manipulate the body of the loop that goes through the positions by their index (which, thank God, is absent here) leading to a change of their number. This is just the height of illiteracy and glitchy code. You have to restart the whole loop if you're supposed to do something like this.

Also some people like something like this:

double Lot;

// где-то вычисляется значение Lot, финальная проверка и приведение к допустимым границам фееричны:
if(Lot > MaxLot) Lot = MaxLot;
if(Lot < MinLot) Lot = MinLot;

// а то и вовсе:
if(Lot > MaxLot) Lot = MaxLot;
  else
    if(Lot < MinLot) Lot = MinLot;

// а не проще ли сделать так?
Lot = MathMin(MathMax(Lot, MinLot), MaxLot);

Although, to a beginner and not concerned with extra hours of CPU time for optimization, such "if-then-otherwise-all" constructions from school lessons of "programming" in BASIC, are clearer.

And all this isreplicated from code to code by the principle of copy-paste.

So there you go...

 
Tio Nisla:

...

Or this kind of "shithcoding":

WherePositionsTotal()is called per loop iteration!

...

Are you sure? You wanted to be clever, but you're in a rut...

And you registered for that purpose? Just like that - from the first post and get lost...

 
Dmitry Fedoseev:

Are you sure? You were trying to be clever, but you've gone rogue...

And you registered for this on purpose? Just like that, from the first post, you're in the toilet...

Oh, dear. "Learn the math," Elger and Knut. Don't get personal.

All right, I'll explain:

    for  (            int i=0            ;          i<PositionsTotal()            ;    i++     )    { }
    ^^^               ^^^^^^^                       ^^^^^^^^^^^^^^^^^^                 ^^^          ^^^
объявление   |   объявление переменной   | проверка условия выполнения цикла:     | инкремент  | тело цикла
  цикла      | типа "int", инициализация | 'i' < значения, возвращаемого функцией | переменной |
типа "for"   |       значением '0'       | которая вызывается на каждую итерацию  |

Is that clear, dear?

If not, thoughtfully read https://learnc.info/c/loop.html starting somewhere from [ctrl+f , look for "Cycle for"].

Here's not even lazy to find the link.

And learn to write literate, nice, concise code. You should have started with assembler, with microcontrollers where every byte counts.

P.S.

Here I was even too lazy to show the expert a simple example of his loop "for".

int OnInit()
{
   for(int i=0;i<somefunc();i++) PrintFormat("array[%d]\n", i);
   return(INIT_SUCCEEDED);
}

int somefunc() {
   static int count = 0;
   PrintFormat("Туточки уже %d-й раз!\n", ++count);
   return 3; // это типа количество чего-то там, элементов массива например
}

And this is the result of the sample run:

2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: initialized
2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: Туточки уже 4-й раз!
2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: array[2]
2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: Туточки уже 3-й раз!
2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: array[1]
2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: Туточки уже 2-й раз!
2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: array[0]
2021.05.03 08:01:36.343 show_the_shitz EURJPY,H1: Туточки уже 1-й раз!

You can see that the function is not only called at each iteration, but even +1 time in the end.

So there you go.

Циклы в Си. Циклы с постусловием, предусловием, Цикл for со счётчиком.
Циклы в Си. Циклы с постусловием, предусловием, Цикл for со счётчиком.
  • 1989.04.14
  • Sypachev S.S. 1989-04-14 sypachev_s_s@mail.ru Stepan Sypachev
  • learnc.info
Циклы в Си: цикл while с предусловием, цикл do while с постусловием, цикл for со сщётчиком. Бесконечный цикл. Оператор break. Оператор continue. Примеры работы с циклами
 
Tio Nisla:

Eh, darling. "Learn your maths," Elger and Knut. Don't get personal.

All right, I'll explain:

Is that clear, dearie?

If not, thoughtfully read https://learnc.info/c/loop.html starting somewhere from [ctrl+f , look for "Cycle for"].

Here's not even lazy to find the link.

And learn to write literate, nice, concise code. You should have started with assembler, with microcontrollers where every byte counts.

P.S.

Here I was even too lazy to show the expert a simple example of his loop "for".

And this is the result of the sample run:

You can see that the function is not only called at each iteration, but even +1 time in the end.

So there you go.

I applaud! Carry on...


 
Dmitry Fedoseev:

I applaud! Carry on...


Why did you make such a mess? And put it on the Net. Your mother will scold you!
 
If some code is stressful, eye-rolling, there are many other professions in the world: janitor, loader, cleaner, sanitary worker...
 
Dmitry Fedoseev:

Are you sure? You were trying to be clever, but you've gone rogue...

And you registered for this on purpose? Just like that - from the first post and into a puddle...

Whatan interesting conversation you're having) ))

Gentlemen, personalities are personalities, but let's find out the truth.

Using the example, I can see thatPositionsTotal()is called at each loop iteration.

But Dimitri, on the contrary, you are saying that the compiler does it in a different way - I don't understand it. Explain.

//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
CTrade         m_trade;
CSymbolInfo    m_symbol;
//-------------------------------------------------------------------+
void OnInit()
  {
   m_symbol.Name(Symbol());
   m_symbol.RefreshRates();

   for(int i = 0; i < 10; i++)
     {
      m_trade.Buy(1, _Symbol, m_symbol.Ask() + i * 2 * _Point, 0, 0);
     }

//---закомментировать не нужное
   for(int i = 5; i < PositionsTotal(); i++) // так удаляются только 3 сделки
     {
      m_trade.PositionClose(_Symbol);
     }
//---закомментировать не нужное
   int index = PositionsTotal();
   for(int i = 5; i < index; i++) // так удаляются 5 сделок
     {
      m_trade.PositionClose(_Symbol);
     }

//вывод: PositionsTotal() вызывается на каждой итерации
  }
//+------------------------------------------------------------------+

If you want to say that thePositionsTotal() function does not recalculate positions each time, but simply returns the value of a variable containing the number of open positions, then yes, you are right, there is no sense in declaring one more variable, but then what does the compiler have to do with it?

And if this function recalculates open positions every time, then it turns out that the compiler has to understand if the value of this function affects further calculations and uses either a function or a variable.

Something doesn't add up for me.

 
Aleksandr Slavskii:

Interesting conversation you are having)))

I wanted to add earlier that if somefunc() function performs some other manipulations besides returning some amount or something, calculates trade parameters, for example, such use causes hard-to-catch artifacts and may lead a code's author into a stupor: "Ht??? How come 4 times??? O_o F$#@!!! Isn't it supposed to be there three times? Why is my EA lying to me?". That's what I called "shithcod," which an expert was outraged to the roots of his hair. I didn't bring it up, for it's obvious, but you did it for me. But you failed to take into account that addressing by an index dynamically calculated without array reinitialization is something else. In bare sys this usually leads to GPF, in pluses with smart pointers and arrays to an exception and its handler. In mql it is not clear what it leads to.