Questions from Beginners MQL5 MT5 MetaTrader 5 - page 64

 
Leser: Please advise how and where to specify in the EA the MA belonging to the No.2 window. For example, I added MA to MFI and I want to register this MA in my EA. I don't know where and how to do it.
Do you want to go into details? Your Expert Advisor is already using the MFI indicator and you want it to use the second indicator - the MA indicator? Or, your Expert Advisor does not use any indicators at all and you need it to use MA indicator?
 
Yedelkin:

1. I would say this: use someone else's code with great care. Because someone else's code means someone else's mistakes too.

2. Here(https://www.mql5.com/ru/forum/6343/page64#comment_357008) I suggested that you try to correctly zero variables before using them. But your code hasn't implemented this suggestion yet. Moreover, your code contains constructs of the following type:

You see, in this construct the request and result variables are zeroed not before they are used but after they are used. Moreover, when these local variables are zeroed, the function stops operating, i.e. such zeroing itself is meaningless. In other words, such a construction is a good example of how MqlTradeRequest and MqlTradeResult variables should not be zeroed. So, if you are eager, please, try to clear the variables correctly. If something goes wrong, please, describe in details what is "not working".

3. The Standard Library has a trade class"MQL5 Reference / Standard Library / Trade Classes / CTrade". Try to figure out how to apply it in practice. At the initial stage of immersion into the language, this class may be quite sufficient. For example, this class has the following method:"MQL5 Reference / Standard Library / Trade Classes / 2CTrade/ PositionModify". It is implemented as follows:

The 'ClearStructures();' line in it clears the m_request variable before using it.

Yedelkin,

Thanks a lot :)

I looked it up and saw my mistake.

I can do it this way:

//+------------------------------------------------------------------+
//| Clear structures request,result and check_result                 |
//+------------------------------------------------------------------+
void ClearStructures()
  {
   MqlTradeRequest request;
   MqlTradeResult result;
   MqlTradeCheckResult check_result;
   ZeroMemory(request);
   ZeroMemory(result);
   ZeroMemory(check_result);
  } 

But I liked your suggestions:

   MqlTradeRequest request={0};
   MqlTradeResult result={0};
All the same, the results are the same.

Now the position is not found, I will strain myself with this task.

Thank you.

 

Yedelkin,

I am writing to you because you are answering adequately.

I have two sors-MT4 and MT5.

Why doesn't it work on MT5, they are the same.

Files:
MTB_1E.mq4  4 kb
MTB_E.mq5  9 kb
 
mario065: Two sors-MT4 and MT5. Why does it not work on MT5-they are the same.

Unfortunately, I don't understand MT4 at all. I'll have a look and if I catch anything, I'll let you know.

Addendum. In general, you will wait for the market opening and report what exactly should have worked, but did not.

 
Yedelkin:

Unfortunately, I don't understand MT4 at all. I'll have a look and if I catch anything, I'll let you know.

Addendum. In general, you wait until the market opens and describe what should have worked, but did not.

So I do it for myself and for whom, if necessary.

Here are the comments:

If the indication of the pips bolshego zero for modification for two yazikas (MT4 and MT5):

if(TradeTrailing>0)

if(MStop > 0)

If these pips (Bid - pips) bolshe open posishon:

if((NormalizeDouble(Bid, Digits)-TradeTrailing)>=OrderOpenPrice())

if(NormalizeDouble(Bid - MStop,4) >= Open)
If stop = 0 or Bid - pipsi dal trailing >= from Open Posishon + pips definition:
if(OrderStopLoss()==0 || (NormalizeDouble(Bid, Digits)-TradeTrailing)>=(OrderStopLoss()+0.0005))

if(SL == 0 || NormalizeDouble(Bid - MStop,4) >= NormalizeDouble(SL + MStop,4))

modification:

ОrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid, Digits)-TradeTrailing,OrderTakeProfit(),0,Blue);

ModifyPosition(Symbol(),NormalizeDouble(Bid - MStop,4),TP);

That's it.

I want to make a separate function for the modification.

 
Yedelkin:
Can you be more specific? Your Expert Advisor is already using the MFI indicator and you now need it to use the second indicator - the MA indicator? Or, your Expert Advisor does not use any indicators at all, but you need it to use MA indicator?
My Expert Advisor uses MFI, but I cannot figure out how to write the MA indicator! The main condition is the location of MA. The MA is not on the chart (window 1), but in the window with the MFI indicator (window 2).
 
Leser: My Expert Advisor uses MFI, but I can't figure out how to write the MA indicator! The main condition is the location of the MA. The MA is not on the chart (window #1), but in the window with the MFI indicator (window #2).

If the Expert Advisor uses MFI, then its code must contain a line with getting the handle of this indicator:"MQL5 Reference / Technical Indicators / iMFI ". Accordingly, getting a handle on the moving average indicator is described here:"MQL5 Reference Guide / Technical Indicators / iMA ".

Try also to read the article"Indicator by Indicator in MQL5".

 
mario065: Here is the comment: If a Bid-STOPS_LEVEL is more than zero for modification: If this Bid-STOPS is more than Open Positions: If Stop = 0 or Bid-STOPS is trailing >= from Open Positions + definition of Pips: Modification: That is all. I would like to make a separate function for modification.

1. Unfortunately, you haven't specified what "doesn't work". You have stated the logic of the program (how it should work), but you have not stated where the logic is broken and how it is broken. Without a detailed description of the problem, you can only make comments about the code.

2. The bool ModifyPosition(const string symbol,double StopLoss,double Takeprofit) function contains such lines:

   if(!OrderSend(request,result) || result.deal==0)
     {
      Print("Modify error =", GetLastError());
      return(false);
     }

If you look at the description of MqlTradeResult structure, you can see that the deal field is described as follows

deal

Deal ticket, if a deal has been executed. It is reported during a trade operation TRADE_ACTION_DEAL

Since your ModifyPosition() function performs a completely different operation, the value of result.deal should always be zero. Consequently, the operator
if(!OrderSend(request,result) || result.deal==0)

will always be triggered, even if the modification was successful, and at the same time it will print an error message.

2. Look at the lines from the previous point 2. You use function GetLastError() there which is intended to return the code of the last error. But you don't clear the variable containing the error code before using it at all, so even if the modification is successful, you print out an error that might have occurred long before the request to modify the position was sent. It should go something like this:

ResetLastError();   
if(!OrderSend(request,result))
   { 
    ... 
    Print("Modify error =", GetLastError());
    ...
   }

3. Look at these lines:

          if(SL == 0 || NormalizeDouble(Bid - MStop,4) >= SL) 
           {
            ModifyPosition(Symbol(),NormalizeDouble(Bid - MStop,4),TP);
           }

Suppose that on the next tick your conditionNormalizeDouble(Bid - MStop,4) == SL triggered. Suppose that SL==1.11110. But then also ModifyPosition(Symbol(),1.11110,TP). I.e. this modification will specify the previously set levels.

And what will happen, if equality NormalizeDouble(Bid - MStop,4) == SL will work again on the next tick?) Especially if we consider that (a) normalization is carried out on four digits, when there may be five-digit quotes, (b) trade requests can be executed on the server with some delay.

4. There is also such a character property as SYMBOL_TRADE_STOPS_LEVEL. But this level is not checked in your code. That is, if the candidate for a new stop loss for a Buy position is specified as SL_new, it would be useful to check the condition if(Bid-STOPS_LEVEL>SL_new).

 

In fact, try looking in the Reference Manual for comparison of real numbers. As far as I remember, it strongly advises against comparing two real numbers like this: if(double_1 == double_2).

 

Yedelkin,

Thank you very much. Reshetov also showed me where the error is.

Here is the function itself:

//+------------------------------------------------------------------+
//| Modify position.                                                 |
//+------------------------------------------------------------------+
bool ModifyPosition(const string symbol,double StopLoss,double Takeprofit){
//---- обявяване на структурата и резултата на търговското искане
   MqlTradeRequest request={0};
   MqlTradeResult result={0};
//---- структурна инициализация на  търговското искане MqlTradeRequest за модифициране на  позиция
   request.action       = TRADE_ACTION_SLTP;
   request.symbol       = symbol;
   request.sl           = StopLoss;
   request.tp           = Takeprofit;
   string word          = "";
   StringConcatenate(word,
                     "<<< ============ Modifyposition():   Модифицираме позицията  ",
                     symbol," ============ >>>");
   Print(word);
//---- модифицираме позицията и  проверяваме резултата от търговското искане
   if(!OrderSend(request,result))
     {
      Print("Modify error =", GetLastError());
      return(false);
     }
   return(true);
  }

And here is how I should have done the function itself:

  double buy_trail = 0;
  double sel_trail = 0;
  double SL,TP,Open;
  if(PositionSelect(Symbol())){
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
      {
      Open = PositionGetDouble(POSITION_PRICE_OPEN);
      SL   = PositionGetDouble(POSITION_SL);
      TP   = PositionGetDouble(POSITION_TP);
      Bid  = SymbolInfoDouble(Symbol(),SYMBOL_BID);
      buy_trail = NormalizeDouble(Bid - Open,Digits());
      if(buy_trail > MStop)
       {
        if(NormalizeDouble((Bid - MStop),Digits()) >= Open && Open > SL)
          {
           ModifyPosition(Symbol(),Open,TP);
          }
          if(NormalizeDouble((Bid - MStop),Digits()) > SL && Open <= SL)
           {
            ModifyPosition(Symbol(),NormalizeDouble((SL + 0.001),Digits()),TP);
           }
        }
      }
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
      {
      Open = PositionGetDouble(POSITION_PRICE_OPEN);
      SL   = PositionGetDouble(POSITION_SL);
      TP   = PositionGetDouble(POSITION_TP);
      Ask  = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
      sel_trail = NormalizeDouble(Open - Ask,Digits());
      if(sel_trail > MStop)
       { 
        if(NormalizeDouble((Ask + MStop),Digits()) <= Open && Open < SL)
          {
           ModifyPosition(Symbol(),Open,TP);
          }
          if(NormalizeDouble((Ask + MStop),Digits()) < SL && Open >= SL)
           {
            ModifyPosition(Symbol(),NormalizeDouble((SL - 0.001),Digits()),TP);
           }
        }
      }
     }

Now everything is working fine.

Thank you.