Self-learning the MQL5 language from scratch - page 14

 
MrBrooklin:

In the future, according to the self-study plan, the task is to modify the script step by step, namely:

  1. add Stop Loss and Take Profit;
  2. add trailing;
  3. add maximal risk;
  4. expand choice of pending orders.
Sincerely, Vladimir.
Of course it's a pity that you haven't followed the advice of the tutorial. You will learn how to put lines, orders, etc., but you won't be able to write a strategy anyway, because you have no theoretical base. All these lines and scripts will not help you to understand basic programming stuff, and you cannot go far without it. I spent the first 4 months just learning, not even trying to write anything. Of course, I could have brazenly, as you did, but the quality of such knowledge is low - there are many gaps in the basics, which will have to be filled in the future...
 
Реter Konow:
Of course, you should not have followed the tutorial advice. You may have got the knowledge how to set lines, orders, etc., but you won't be able to develop the strategy anyway, because you haven't got the theoretical base. All these lines and scripts will not help you to understand basic programming stuff, and you cannot go far without it. I spent the first 4 months just learning, not even trying to write anything. Of course I could have brazenly, like you, but the quality of such knowledge is poor. There are always gaps in the basics, which will have to be filled in the future...

Hello, Peter! I study the textbook as needed, i.e. when I see a gap in my knowledge. Now, I feel that I will have to take a little pause and study the textbook more closely. All recommendations from forum participants are taken into account and I'm trying to stick to them. And now I'm amazed that I have managed to write something using only MQL5 Reference book for such a short time.

Regards, Vladimir.

 
MrBrooklin:

Good evening to all and good mood!

I am pasting a new script New6.mq5 that helps you place one SellStop and one BuyStop pending order with a fixed lot size at a certain distance from the current price on the current chart. In this script, I tried to describe everything as I promised earlier, in clear and understandable form for a 1st grade programmer.

I used the information taken from the MQL5 Reference only when writing the script!

Best regards, Vladimir.

It's a good example. I suggest using it as a starting point. Basics.

MrBrooklin:

In the future, according to the self-study plan, the task is to modify the script step by step, i.e:

  1. add Stop Loss and Take Profit;
  2. add trailing;
  3. add maximal risk;
  4. expand choice of pending orders.
Sincerely, Vladimir.

No, no. Do not connect the new functionality yet. Now improve the existing logic. At the same time, get rid of the problems in the script implementation (they are already showing). If you want to know what to rewrite, I'll tell you.

 
Vasiliy Sokolov:

The example is a good one. I suggest using it as a starting point. Baseline.

No, no. Don't plug in any new functionality just yet. Now improve the existing logic. At the same time get rid of problems in script implementation (they are already showing). What exactly you need to rewrite, if you will be interested, I'll tell you.

Hello Vasily! Of course, tell me what you need to rewrite, it would be interesting to me!

Sincerely, Vladimir.

 
MrBrooklin:

Hello Vasily! Of course tell me what you need to rewrite, I'm very interested!

Sincerely, Vladimir.

Programmers have two problems: errors produced by the compiler and architecture problems. While you are a novice, you concentrate on fighting with the compiler while your ultimate goal is a program that works correctly. However, very quickly a beginner's program turns into so-called spaghetti code, which the author himself can't figure out soon enough. That's why I suggest that you focus not on the compiler and correctness of the final script but on architectural issues. It is like learning to play the piano: first you learn how to hold fingers correctly and sit at the instrument properly, no one demands playing Bach from a beginner.

//+------------------------------------------------------------------+
//|                                                         New6.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//---
#property script_show_inputs
//---

#define       orderType1 "BUY_STOP"   //Тип ордера UP
#define       orderType2 "SELL_STOP"  //Тип ордера DOWN
input int    Distance=100;           //Отступ отложенного ордера от текущей цены
input double Lots=0.01;              //Фиксированный размер лота
input long   Pending_magic=86513;    //Магический номер ордера

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()                                                    
  {
   MqlTradeRequest request={0};
   MqlTradeResult result={0};
   request.action=TRADE_ACTION_PENDING;
   request.symbol=Symbol();
   request.volume=Lots;
   request.deviation=2;
   request.magic=Pending_magic;
   double price;
   double point=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
   int digits=(int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
   if(orderType1=="BUY_STOP")
     {
      request.type=ORDER_TYPE_BUY_STOP;
      price=SymbolInfoDouble(Symbol(),SYMBOL_ASK)+Distance*point;
      request.price=NormalizeDouble(price,digits);
     }
   if(!OrderSend(request,result))
      PrintFormat("OrderSend error %d",GetLastError());
   if(orderType2=="SELL_STOP")
     {
      request.type=ORDER_TYPE_SELL_STOP; 
      price=SymbolInfoDouble(Symbol(),SYMBOL_BID)-Distance*point;
      request.price=NormalizeDouble(price,digits);
     }
   if(!OrderSend(request,result))
      PrintFormat("OrderSend error %d",GetLastError());
   PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
  }

You have two groups of parameters which determine the behavior of your script: the first is set statically, as a macro. The second is set by the user when loading the script on the chart. Now the user will not be able to select the type of the order to be placed without recompiling this script. This is not good. Therefore, it would be better to abandon these macros in favor of the additional parameter:

enum ENUM_ORDER_TYPE_FLAGS
{
    BuyStop = 1,                // Только BuyStop
    SellStop = 2,               // Только SellStop
    BuyStopAndSellStop = 4      // BuyStop и SellStop
};

input ENUM_ORDER_TYPE_FLAGS TypeSendOrders = BuyStop;   // Тип Выставляемого ордера(ов)

Accordingly, we have defined a new enumeration, which we have implemented as a selection parameter for the user.

 
Vasiliy Sokolov:

Programmers have two problems: compiler errors and architecture problems. While you are a beginner, you focus on fighting the compiler, and your ultimate goal is a program that works correctly. However, very quickly a beginner's program turns into so-called spaghetti code, which the author himself can't figure out soon enough. That's why I suggest that you focus not on the compiler and correctness of the final script but on architectural issues. It is like learning to play the piano: first you learn how to hold fingers correctly and sit at the instrument properly, no one demands playing Bach from a beginner.

You have two groups of parameters which determine the behavior of your script: the first is set statically, as a macro. The second is set by the user when loading the script on the chart. Now the user will not be able to select the type of the order to be placed without recompiling this script. This is not good. Therefore, it would be better to abandon these macros in favor of the additional parameter:

Accordingly, we have defined a new enumeration, which we have implemented as a selection parameter for the user.

Great, in fact, you have prompted me what is written in step 4 of the step-by-step modification of the script, namely to expand the selection of pending orders.

Thank you!

Regards, Vladimir.

 

The next problem with your code is that it sprawls out into a long procedural sheet. All beginners write this way. And this is a problem that stays with them for years. Learn to break your algorithm into parts, starting from the basics like this script. There are two ways to do this: through functions and classes. The concept of classes is too difficult to grasp at first, so I suggest you focus on working with functions. Think about the importance of functions:

  • All code written in MQL (and this is all scripts, indicators and Expert Advisors in CodeBase for example) is either inside system functions or inside user functions.
  • Any MQL code calls dozens of built in MQL functions. All interactions with MetaTrader and its trading environment are carried out through the call of a system function.
  • Any function that doesn't depend on external parameters always returns the same result. Such a function can be simply copied from one script/indicator/advisor to another and it will work properly. Copying an arbitrary piece of procedural code, on the other hand, is unlikely to work.
  • You can write any custom function that does useful work. And by doing so, it will expand the standard MQL functionality in the way you need. For example, you think: "How cool it would be if MQL had such function....". - But why not write it yourself?
 
Vasiliy Sokolov:

The next problem with your code is that it sprawls out into a long procedural sheet. All beginners write this way. And this is a problem that stays with them for years. Learn to break your algorithm into parts, starting from the basics like this script. There are two ways to do this: through functions and classes. The concept of classes is too difficult to grasp at first, so I suggest you focus on working with functions. Think about the importance of functions:

  • All code written in MQL (and this is all scripts, indicators and Expert Advisors in CodeBase for example) is either inside system functions or inside user functions.
  • Any MQL code calls dozens of built in MQL functions. All interactions with MetaTrader and its trading environment are carried out through the call of a system function.
  • Any function that doesn't depend on external parameters always returns the same result. Such a function can be simply copied from one script/indicator/advisor to another and it will work properly. Copying an arbitrary piece of procedural code, on the other hand, is unlikely to work.
  • You can write any custom function that does useful work. And by doing so, it will expand the standard MQL functionality in the way you need. For example, you think: "How cool it would be if MQL had such function....". - But why not write it yourself?

Thank you, Vasily for such a comprehensive advice. I will certainly take it into account and try to do my best.

Regards, Vladimir.

 
Vasiliy Sokolov:

The next problem with your code is that it sprawls out into a long procedural sheet. All beginners write this way. And this is a problem that stays with them for years. Learn to break your algorithm into parts, starting from the basics like this script. There are two ways to do this: through functions and classes. The concept of classes is too difficult to grasp at first, so I suggest you focus on working with functions. Think about the importance of functions:

  • All code written in MQL (and this is all scripts, indicators and Expert Advisors in CodeBase for example) is either inside system functions or inside user functions.
  • Any MQL code calls dozens of built in MQL functions. All interactions with MetaTrader and its trading environment are carried out through the call of a system function.
  • Any function that doesn't depend on external parameters always returns the same result. Such a function can be simply copied from one script/indicator/advisor to another and it will work properly. Copying an arbitrary piece of procedural code, on the other hand, is unlikely to work.
  • You can write any custom function that does useful work. And by doing so, it will expand the standard MQL functionality in the way you need. For example, you think: "How cool it would be if MQL had such function....". - But why not write it yourself?
Vasily, the man hasn't even mastered arrays yet. It is too early for him to listen to such lectures).
 
Реter Konow:
Vasily, the man has not even mastered arrays yet. It is too early for him to listen to such lectures).

Peter, all constructive advice is important to me, including yours!

Regards, Vladimir.

Reason: