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

 
Alexey Viktorov:

Well, I'll try to do my bit more to educate you.

I'll address you as "you" when I send it. I have a snapshot of the pointer...

Please tell me, doesn't it seem wrong to call the same function 5 times on the same tick? But that's half the trouble. This function goes through all the orders. And all this 5 times in one tick... And I count 4 such functions. We cannot think hard enough how to fit 3 more functions with the loop to search all the orders in one cycle.

Here are two of them.

This is

It's not even close to trailing.

To understand this, we need to clearly understand the definition of trailing. I cannot remember verbatim, but it is approximately "Moving StopLoss level following the price in order to decrease possible losses or increase "guaranteed" profit.

And this

what does it look like when you run the Expert Advisor? Probably four lines... are they needed?

And the last thing for today: you don't have to have a library in your head. It is enough to have documentation and know how to use it. I still can't remember all parameters of iMA(_Symbol, _Period, ,,,,,) and I can't go further without studying the documentation. And so almost all functions. Fortunately, they made tooltips not so long ago which don't help much. I'm not trying to memorize how to write these or those enums. So I have to look at the documentation every time.


Alexey, thank you for the information. Yes, I admit that the code is not optimal, I'm just not a programmer and I don't know subtleties you've described. I simply don't understand such nuances, I don't understand how to optimize it all, maybe I will do it later, if I will move forward. Now I know exactly that if I start optimizing, I'll only break everything. I have seen codes of other EAs on my website - there is so much stuff there! - For sure if you are a pro coder, maybe his code is less demanding for terminal than mine, but for now I cannot take your comments into account as I really don't understand these nuances of programming optimization. And if you remove some calls to functions in the code - for sure, the Expert Advisor would start chaos there and would open orders when it was not necessary. I coded there, tested - nothing went wrong or went wrong, I corrected and as a result the final code turned out like this, I had no time for optimization, as you understand with my baggage of knowledge.

As for trailing - the most important thing is that it trails profit, at this stage of development I'm satisfied with it)))) For sure the old and new trailing code trails equally and quantity of deals is the same - of course I've concluded that trailing has worked, but how to do it correctly in this environment where trailing works nobody told me, and I have no thoughts on it - all my code is Lego constructor - that is, I assembled it from video tutorials materials. Of course, there is a little bit of my own - it is actually the algorithm of the Expert Advisor itself, while the entire code and functions are not my invention, but came from video tutorials from TradeLikeaPro and I "edited" the code exactly by analogy and for my needs - for my algorithm. In the end, I got what I had.

 
geratdc:   All my code is a Lego constructor - i.e. I assembled it from video tutorials materials from TradeLikeaPro, moreover, I "edited" the code exactly by analogy and for my needs - for my own algorithm. In the end, I have what I have.

Looked at the deposit graph - got interested and downloaded the first version. Copied it into MetaEdit. I have two warnings. First one, I have eliminated it by replacing int timeprev=0; by datetime timeprev=0; Because this variable contains date. The second one indicates on

tp=TakeProfit;             // В переменную tp заносится значение переменной TakeProfit
if(tp>TakeProfit)          // А тут они сравниваются. А с чего им быть разными, если только что уравняли?
{
   TakeProfit+=tp;
}

I have removed the last three strings. It translates cleanly. Let's go further...

//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(Digits == 3 || Digits == 5)  // После этой строки нужны фигурные скобки.
      TakeProfit     *= 10;        // иначе эта строка будет выполняться по условию

      // а следующие строки будут выполняться всегда
      Step           *= 10;
      TrailingStep   *= 10;
      TrailingStop   *= 10;
      Slippage       *= 10;

      
   return(INIT_SUCCEEDED);
  }

has redone (for clarification, I have attached the script - run it, it will explain) so

//| Инициализация на пятизнак или иену                               |
//+------------------------------------------------------------------+
void OnInit()
{
   if(Digits == 3 || Digits == 5)
   {
      TakeProfit     *= 10;
      Step           *= 10;
      TrailingStep   *= 10;
      TrailingStop   *= 10;
      Slippage       *= 10;
   }
}
//+-------------------------------------------------------+
//| Демонстрация назначения фигурных скобок      PROBA.mq4|
//+-------------------------------------------------------+
#property strict

void OnStart()
{
  // Без фигурных скобок
  if(2==5)
    Alert("Это сообщение будет пропущено");
    Alert("Без фигурных скобок это сообщается, хотя по логике зря");

  Alert("-------------------------------");
  Alert("А вот со скобками - полный молчок");
  if(2==5)
  {
    Alert("Это сообщение будет пропущено");
    Alert("Со скобками это тоже пропускается");
  }
}
Here is the result


This function is removed - there are no calls of it and its body is empty.

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }

I tried to run it and saw:

It was

I changed it only when running the EA on two charts with the same tool and Slippage - why change this parameter? Then I thought about it and increased the parameters by 10 times. And I removed the function OnInit. After all, I only use the five-digit code. Why? Because the four-digit spread is 3 points, so it's 30. And the five-digit spread is only 12.

it became clearer.

extern double  Lots           = 0.01;  // Размер лота
extern int     TakeProfit     = 5 0;    // Ограничение прибыли Take Profit
extern int     Step           = 2 0;    // Шаг - чего, выясним позже

extern int     TrailingStep   = 3 0;    // Шаг трала
extern int     TrailingStop   = 10;    // Ограничение убытка

extern int     MaPeriod       = 200;   // Период МА (надо поменьше?)
extern int     MaShift        = 1;     // Сдвиг МА (взял бы 0)

       int     Magic          = 123;   // Магик - нужен ли он?
       int     Slippage       = 50;    // Проскальзывание

datetime timeprev=0;

double price,op,cn,tp;  // Убрал extern

I trimmed the top of the header. That's what I left:

//+------------------------------------------------------------------+
//|                                                      -Э-1111.mq4 |
//+------------------------------------------------------------------+
#property strict

this line right here.

   op=CalculateProfit();
   if (CalculateProfit()>=tp) CloseAll();

moved it down to the claim. It's like this.

   op=CalculateProfit();
   if (op>=tp)
   {
         CloseAll();    
   }

Then I threw out the description of the op variable at the beginning and replaced it with this

   if (CalculateProfit()>=tp) CloseAll();

At the beginning of the OnTick function there are a couple of lines. This is to ensure that the processing is performed only once per bar instead of every tick

   if(timeprev == Time[0]) return;   // сравнить  время начала последнего бара с временем обработанного бара. Если равны, то выход
   timeprev = Time[0];               // Запомнить время начала следующего бара      На часовом и далее это будет слабо

Then the MA is calculated. This must be studied in details. For this purpose I made a script and displayed the result

   double maprice=iMA(Symbol(),0,MaPeriod,MaShift,MODE_SMA,PRICE_CLOSE,1);
//+-------------------------------------------------------+
//| Проверка функции iMA                         PROBA.mq4|
//+-------------------------------------------------------+
#property strict

void OnStart()
{
  int MaPeriod=200;
  int MaShift=1;

  Alert("MaShift = ", MaShift);
  for(int Бар=0; Бар<5; Бар++)
  Alert("Бар = ", Бар, "   Ma = ",
    iMA(Symbol(),0,MaPeriod,MaShift,MODE_SMA,PRICE_CLOSE,Бар));

  Alert("-------------------------");
  MaShift=0;
  Alert("MaShift = ", MaShift);
  for(int Бар=0; Бар<5; Бар++)
  Alert("Бар = ", Бар, "   Ma = ",
    iMA(Symbol(),0,MaPeriod,MaShift,MODE_SMA,PRICE_CLOSE,Бар));
} 

We can see that the fourth MaShift parameter and the last one are summed, i.e. bar number = their sum. We take the MA from bar 2, the third from the end.

I will look at it further. Interested?

 
STARIJ:
...

I'll keep looking. Interested?

Do you keep bringing it up?

Enough already - people follow the topic for those who are interested and it is wasted.

If you want a person to answer you, call them into the thread. Like this: @STARIJ. But you don't have to keep bringing up the topic by editing your last post.


 
Victor Nikolaev:

It means that someone is out of luck. Once again. This is a script, not an Expert Advisor or indicator

Figured it out - apparently the terminal didn't have enough memory - closed a couple of charts and it worked.

Thank you - indeed, the calculations take place.

And if variables are not int type, but bool , what to do?

 

Hello, could you tell me please:

1 - is registration only as a natural person or can it be as a legal person too and are there any restrictions and conditions

2 - Is there any synchronisation with the social networks, to have a single account (username and password)

3 - I also saw a function "put a widget on your page, share the signal" - are we talking about the site or something else


 
Hello, I have only recently started to learn Mql4. If I have asked you a question in the wrong place, please direct me to the right subject. My question is as follows: how to work with indicators that build various zones, rectangles, etc. I may program a cross of lines or price higher or lower, e.g. MA.) I attached an indicator at the bottom, buffer is four and there are eight types of zones. So I actually can't figure out how to code a break or break of these zones.
 
STARIJ:

Looked at the deposit graph - got interested and downloaded the first version. Copied it into MetaEdit. I have two warnings. First one, I have eliminated it by replacing int timeprev=0; by datetime timeprev=0; Because this variable contains date. The second one points to

*

Response

Perhaps, it has to do with the fact that the TP was of int type in the video lesson but I have converted it to double and hence int timeprev remains as it is. OK, I will fix it. But how does it affect the EA operation? In fact, these bars and time were relevant to TrailingStop function from the video tutorial, but since I replaced this function with my own, it simply remains as a relic of the source code and in fact my trailing stop is not based on bar time.


I have removed the last three lines. It translates cleanly. I went further...

I have changed it (for clarification I have attached a script - run it, it will explain) like this

Here is the result

*Answer.

Where has this bit of code gone?

   return(INIT_SUCCEEDED);
  }

Maybe it should be like this?


void OnInit()

{

if(Digits == 3 || Digits == 5)

{

Step *= 10;

TrailingStep *= 10;

TrailingStop *= 10;

Slippage *= 10;

}

return(INIT_SUCCEED);

}

But why did you make TakeProfit of int type? It means that it will be profit in points, while the CalculateProfit() function is of double type, so I made TakeProfit of the same type to make them consistent.


I deleted this function - there are no calls of it and its body is empty

*

Response

In the code, there is the void CloseAll() function. I thought it was somehow related to this function

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }

*

Response

Ok, let's remove it.


Tried to run it and saw:

It was

by making changes - well, just added comments and deleted extern from Magic

*

Response

Yes, maybe extern is redundant because I have never changed it and neither has Slippage - it's all from the source code of the video tutorial

- we change it only when running the EA on two charts with the same tool and Slippage - why change this parameter? Then I thought about it and increased the parameters 10 times. And I removed the function OnInit. After all, I only use the five-digit code. Why? Because the four-digit spread is 3 points, so it's 30. On a five-digit spread, it's only 12.

*

The answer is .

This is the default setting for the EA to work on all currencies. I will keep Oninit ().

it became clearer.

I have trimmed the header at the top. Here is what I left:

*

Reply

This header is made by default editor. I'll leave it as it was, in case something doesn't go through at the broker or in the terminal because of the absence of these lines.

I've moved this line

moved down to the claim. It went like this

Then I removed the description of variable op at the beginning and replaced it with

*

Response

It's pretty logical.



At the beginning of the OnTick function, there are a couple of lines. This is to ensure that processing is performed only once per bar instead of every tick

Then the MA is calculated. This must be studied in details. For this purpose I made a script and output the result.


You can see that the fourth parameter MaShift and the last parameter are summed, i.e. bar number = their sum. We take the MA from bar 2, the third from the end.

*

Response

Due to the fact that I have changed trailing - date-time Moving Average is not relevant I think. It's a relic of the source code, I used to try to trawl by the last of 3 (three) open orders. The thing is that if the market goes in a wrong direction by the value of STep, the EA opens a counter-order and then if the market continues to go in the opposite direction, a third order of the type of the second position is added, Or vice versa, if the price returned direction then the third order will be opened with the first order type (buy or sell). There, trailing is performed on three orders using the CalculateProfit() function; however, if the first order opens successfully and the price moves as it should, in this situation, trailing on the bar would be done using datetime as in the video tutorial - I repeat, even on 1 order trailing using the calculateprofit() function

I will look further. Interested?

*

Response

Yeah, I have some issues with trawling. It seems to trail but I do not want anyone to understand what I have made with it. Trailing() functions without bars and datetime - it works with Trailing().

The MA period is about 200, but the point is that it is an adjustable value. And the key parameter Value seems to be missing - I've explained its meaning in the README file description.



Thank you for taking the trouble with it all. In fact, the Expert Advisor is not really that good, mechanical I would say. But basically, if you set it up and occasionally monitor its work, it may be quite good. Time will tell. Probably, they can earn something, but they will go bust without even blinking an eye and will not send a text message. I have not even bothered with it, although my idea was to send an SMS if the drawdown is more than 30% of the deposit has happened - this means that 3 orders have already been opened and the market started counter-movement, in this situation, it smells of paraffin. All other cases are solved by the Expert Advisor, if it is adjusted for the behavioural history of the trade instrument chart.


I have made recommended (but not all) changes in the code in Notepad for now. Please check if I have corrected the code?

I am for optimization, only I have not considered moments when you have removed oninit - I need it to be able to test and work on all currencies)))

 
Aleksandr Verkhozin:
Hello, I have only recently started to learn Mql4. If I have asked you a question in the wrong place, please direct me to the right subject. My question is as follows: how to work with indicators that build various zones, rectangles, etc. I may program a cross of lines or price higher or lower, e.g. MA.) I attached an indicator at the bottom, buffer is four and there are eight types of zones. So I can't figure out how to code a break or breakout of these zones.

If you want to know more about the programmer, you should look through the examples and use the colored buttons. You may ask: How do you spend a lot of time with the mql4 programmer, but you don't want to be foolish with the mql4.) Maybe you will progress.
 

geratdc:

...
Yeah, I've got some questions about the trawl. It seems to trawl, but nobody wants to know what I've done with it.

...

If you know, right in this thread I posted a template for trawl that uses indicator value sent to it in its calculations. Look it up, don't be lazy.
 
geratdc:

You may need to download mql4 programming video tutorials from TradeLikeApro on RuTracker. They have a good idea of how to get the mql4 indicators right away, but if you don't know how to do it, you may get an error message.) Maybe you will progress.


Watched the video on working with the external indicator, wrote a little code to see the values of the buffers in the tester:

void OnTick()

{

double Buf1=iCustom(NULL,0, "Shved-Supply-and-Demand-e600",0,1);

double Buf2=iCustom(NULL,0, "Shved-Supply-and-Demand-e600",1,1);

double Buf3=iCustom(NULL,0, "Shved-Supply-and-Demand-e600",2,1);

double Buf4=iCustom(NULL,0, "Shved-Supply-and-Demand-e600",3,1);

Comment("Buf1=",Buf1,"\n", "Buf2=",Buf2,"\n","Buf3=",Buf3,"\n","Buf4=",Buf4);

}

The zones appear and disappear in visualization mode. But the value of the buffers is always zero anyway. Is there no way to formalize these zones in the code?

Maybe there is a function, other than iCustom, that would be suitable for such indicators? Maybe someone has written owls with such indicators?

Reason: