Questions from Beginners MQL5 MT5 MetaTrader 5 - page 360

 

Good afternoon.

Can you please advise me how to write the code correctly when trading EA in MT4, I am very new to programming.

I have to select the last closed order and compare its profit. I have to do nothing if its profit is more than 0, if it is less than 0, I have to do something.

double GetSizeLot(double lastlot=0) //Функция возвращает значение лотов 
  {
   double Lot2,MinLots,MaxLots;
   int j=OrdersHistoryTotal();
   
   MinLots=Lots;
   MaxLots=MaxLot;
   if(!DynamicLot)Lot2=Lots;
   if(lastlot<Lot2)lastlot=Lot2;
   
   if(OrderSelect(j,SELECT_BY_POS,MODE_HISTORY))
     {
     if(OrderProfit()<0) lastlot=lastlot*Martin;
     if(OrderProfit()>0) lastlot=Lot2;
     }
   Lot2=lastlot;
   if(Lot2 < MinLots) Lot2 = MinLots;
   if(Lot2 > MaxLots) Lot2 = MaxLots;
   return(NormalizeDouble(Lot2,2));
  }

I have a lot of respect, Alexander.

 
Menshikov:

Good afternoon.

Can you please advise me how to write the code correctly when trading EA in MT4, I am very new to programming.

I need to select the last closed order and compare its profit. I have to do nothing if its profit is more than 0, if it is less than 0, I have to do something.

I have a lot of respect, Alexander.

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

datetime time=0; double profit=0,lots=0;
for(int i=OrdersHistoryTotal()-1; i>=0; i--)
   if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
      if(OrderSymbol()==_Symbol)
         if(OrderMagicNumber()==MagicNumber || MagicNumber==-1)
            if(OrderCloseTime()>time) // находим последний в истории ордер
              {
               time=OrderCloseTime(); // запомним время
               profit=OrderProfit();  // запомним профит
               his_lt=OrderLots();    // запомним лот
              }

if(profit<0) //если профит меньше нуля
   lots=his_lt*2; // Увеличим в два раза

//+------------------------------------------------------------------+
 
Vladimir Pastushak:
Thank you very much.
 
Vladimir Pastushak:
I wonder what the time is for, why do you remember the closing time, if you choose the last one in the list anyway, and what about the cycle? And why don't you consider swap and commission? Even if OrderProfit()>0, the actual profit may be negative. If you work directly with the list of orders, you shouldn't leave chunks of code from the loop searching for the last one by time of closing. One thing is either reliability and certainty or speed. And you have a mishmash.
 
Artyom Trishkin:
I wonder what the time is for, why do you remember the closing time, if you choose the last one in the list anyway, and what about the cycle? And why don't you consider swap and commission? Even if OrderProfit()>0, the actual profit may be negative. If you work directly with the list of orders, you shouldn't leave chunks of code from the loop searching for the last one by time of closing. One thing is either reliability and certainty or speed. What you have is a jumble.

What you are suggesting is that

   if(OrderSelect(OrdersHistoryTotal(),SELECT_BY_POS,MODE_HISTORY))

Do you do this?

The person only asked for a profit order, why impose what you didn't ask for ? But I agree with you ....

 

Please advise how to close an open order in MQL4 on MT4 after 20 bars, i.e. if an order is opened and 20 new bars appear, it is closed. (only 1 order is always open). For some reason, this code does not work in the strategy tester, and we need it to do so.


The code has the following meaning: we check if we have any open orders, if not, we open an order and record into the "z" variable the open price of the 1st bar and then with every tick we check the open price of the 20th bar and when the 1st bar eventually reaches the 20th bar, its price will be the same as the price recorded in the "z" variable and then the order will be closed. (of course during the process, prices can coincide, but it will be very rare, in addition, we can write more parameters of the 1st bar in the variables)


double z; //объявление переменной

           //ОТКРЫТИЕ ОРДЕРА
           if(OrdersTotal() == 0) // если нет открытых ордеров то открывать ордер
              {
               OrderSend(Symbol(), OP_SELL, 0.1, Bid, 3, Bid+150*Point, Bid-10*Point);
                   z = Open[1]; // здесь переменной "z" присваивается цена открытия 1-го бара
              }
            else

           Print("ORDER NE USTANOVLEN!!!");




           //ЗАКРЫТИЕ ОРДЕРА

    if (z==Open[20])  //если цена записанная в переменную "z" равна цене 20-го бара, то закрывать ордер
        {
           

            //-----------------код закрывает все ордера--------------------
   bool   result;
   int    error;

 while (OrdersTotal()>0)
 {
   if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES))
     {   if(OrderType()==OP_BUY)  result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),MarketInfo(OrderSymbol(),MODE_DIGITS)),3,CLR_NONE);
          if(OrderType()==OP_SELL) result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),MarketInfo(OrderSymbol(),MODE_DIGITS)),3,CLR_NONE);
          if (OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
           OrderDelete(OrderTicket());
         
           if(result!=TRUE) { error=GetLastError();
              Print("LastError = ",error, " ",Symbol()); }
           else error=0; }
   else Print( "Error when order select ", GetLastError());

  }
//------------конец кода закрывающего ордер------------------
           
           
        }
      else
      Print("ORDER NE ZAKRYT!!!");
 
BEGEMOT32:

Please advise how to close an open order in MQL4 on MT4 after 20 bars, i.e. when an order is opened and 20 new bars appear, it is closed. (Only 1 order is always open). This code does not work in the strategy tester for some reason.


The code has the following meaning: we check if we have any open orders; if not, we open an order and record into the "z" variable the open price of the 1st bar and then with every tick we check the open price of the 20th bar and when the 1st bar eventually reaches the 20th bar, its price will be the same as the price recorded in the "z" variable and then the order will be closed. (of course, prices can coincide during the process, but it will be very rare, in addition, we can write more parameters of the 1st bar into variables)


That's it, I figured it out myself, I should have declared the variable outside of int start() - now it works fine
 
BEGEMOT32:
That's it, I figured it out myself, I should have declared a variable outside of int start() - now it works fine

I have simplified your code a bit, but there are still errors in your code

//ОТКРЫТИЕ ОРДЕРА
if(OrdersTotal()==0) // если нет открытых ордеров то открывать ордер
   if(OrderSend(Symbol(),OP_SELL,0.1,Bid,3,Bid+150*Point,Bid-10*Point)<0)
      Print("ORDER NE USTANOVLEN!!!");

//-----------------код закрывает все ордера--------------------
   bool   result;
   int    error;
   while(OrdersTotal()>0)
     {
      if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES))
        {
         if(iBarShift(OrderSymbol(),Period(),OrderOpenTime())==20)
           {
            if(OrderType()==OP_BUY) result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),MarketInfo(OrderSymbol(),MODE_DIGITS)),3,CLR_NONE);
            if(OrderType()==OP_SELL) result=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),MarketInfo(OrderSymbol(),MODE_DIGITS)),3,CLR_NONE);
            if(OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
               OrderDelete(OrderTicket());
           }
         if(result!=TRUE)
           {
            error=GetLastError();
            Print("LastError = ",error," ",Symbol());
           }
         else error=0;
        }
      else Print("Error when order select ",GetLastError());

     }
 

I am writing a multi-currency EA but I cannot understand why it returns different prices at the same time if I link it to different currencies

In short, the code:

at Init

EventSetTimer(60);

in OnTimer()

MqlTick last_tick;
if(SymbolInfoTick("EURNZD",last_tick))
{
    Print("Last Ask: ", last_tick.ask);
}

If I test my EA on EURNZD, for example

2015.05.18 00:07:00 Lat Ask: 1.5370

If I use any other currency pair

2015.05.18 00:07:00 Lat Ask: 1.5323

This value is totally different, and in the second case, according to the chart, there could not be such a value for at least several hours

In the Strategy Tester all ticks are in trade mode, I get the feeling that if it is not the main pair, the values in the Strategy Tester are approximate

I forgot to add that this is Meta Trade 5

I have found out that the first time I do it, the price is wrong and the second time I do it, the price is normal

 
1.Can you find out from history how many ticks have been up and down in tick volume?

2.It's been a few months since I deleted autochartis, but the log messages keep popping up. The software keeps trying to open the files.

How to erase autochartis completely?

2015.05.25 15:36:42.983 Cannot open file 'C:\Users\asus\AppData\Roaming\MetaQuotes\Terminal\................................\MQL4\indicators\Autochartist Volatility.ex4' [2]
2015.05.25 15:36:42.983 Cannot open file 'C:\Users\asus\AppData\Roaming\MetaQuotes\Terminal\................................\MQL4\indicators\Autochartist Key Levels.ex4' [2]
2015.05.25 15:36:42.982 Cannot open file 'C:\Users\asus\AppData\Roaming\MetaQuotes\Terminal\................................\MQL4\indicators\Autochartist Chart Patterns.ex4' [2]

Reason: