Questions from Beginners MQL5 MT5 MetaTrader 5 - page 80

 
ksbr:
I want to put a stock (futures) into MT5 to test mine, how?
you can't. look for a brokerage house with the futures
 
sergeev:
No way. look for a brokerage house with this futures

%))) There is no DC with this fuchs))) It has to be glued together...

It's a pity, it's a pity, and it all started so beautifully...

 

Greetings all!

I am trying to implement two functions in my EA, the first defines profit of the last trade, the second defines lot of the last trade.

I searched through this site from A to Z and made several functions, following the examples in articles and other EAs, but no result - both functions always return 0.00.

Here seems to me to be the closest to the correct variant but the result is always 0:

double LossLastPos(){
// --- определение границ требуемой торговой истории
   datetime end=TimeCurrent();                 // текущее серверное время
   datetime start=end-PeriodSeconds(PERIOD_D1);// установим начало на сутки назад
//--- запросим в кэш программы торговую историю за день
   HistorySelect(start,end);
//--- получим количество ордеров в истории
   int history_orders=HistoryOrdersTotal();
//--- получим тикет ордера из истории, имеющего последний индекс в списке
   ulong order_ticket=HistoryOrderGetTicket(history_orders-1);
   if(order_ticket>0) // получили в кэш исторический ордер, работаем с ним
     {
      //Получаем значение прибыли последнего ордера
      double  profit = HistoryDealGetDouble(order_ticket,DEAL_PROFIT);
      return(profit);
     }
}

I try to get the lot size in the same way:

double  volume = HistoryDealGetDouble(order_ticket,DEAL_VOLUME);
      return(volume);

And nothing works, the values are always zero.

I myself have just started migration from mql4 to mql5. Implementation of such functions in mql4 was not very difficult, but here is a deadlock.

Please advise me a real, working solution.

 
karakos:

...

Please suggest a real, working solution.

Use HistoryDealGetTicket() and HistoryDealsTotal().

And do the validation:

   if(HistorySelect(start,end))
     {
      // ...
     }
 

tol64 thank you very much! Everything is working.

Here is a 100% working solution - the function returns the profit of the last closed position in terminal history:

//+------------------------------------------------------------------+       
//|Функция возвращает профит последней позиции                       |
//+------------------------------------------------------------------+
double ProfitLastPos()
  {
// --- определение границ требуемой торговой истории
   datetime end=TimeCurrent();                 // текущее серверное время
   datetime start=end-PeriodSeconds(PERIOD_D1);// установим начало на сутки назад
//--- запросим в кэш программы торговую историю за день
   if(HistorySelect(start,end))
     {
      //--- получим количество сделок в истории
      int history_orders=HistoryDealsTotal();
      //--- получим тикет сделки из истории, имеющей последний индекс в списке
      ulong order_ticket=HistoryDealGetTicket(history_orders-1);

      if(order_ticket>0) // получили в кэш историческую сделку, работаем с ней
        {
         profit=HistoryDealGetDouble(order_ticket,DEAL_PROFIT);
        }
     }
   return(profit);
  }

By analogy we get the lot size of the last trade:

 Volume = HistoryDealGetDouble(order_ticket,DEAL_VOLUME);
 
karakos:

tol64 thank you very much! It's all working.

...

And if you also press Ctrl+ in the editor, you'll get neatly formatted code. Especially important before uploading the example to the forum (better readability). ))
 
tol64:
If you also press Ctrl+ in the editor, you will get neatly formatted code. This is especially important before uploading the example to the forum (better readability). ))
Styled the code, thanks again!
 

Good day! I have recently started to learn MQL5. I have a problem with position closing. In code: if(!m_Trade.PositionClose(_Symbol,100))//--- close position by current symbol. The result is that the position is reversed! I would be very grateful for a hint, how can I close a position?

 
//_____________________________________________________________________________________________________________________________________________
//--------  блок работы с длинной позицией  ---------------------------------------------------------------------------------------------------
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
                          
         if( p_close1 <  buy_stop_level   )// если бар 1 закрылся ниже уровня стоп
         {
          if(!m_Trade.PositionClose(_Symbol,100))//--- закрываем позицию по текущему символу
         {
      //--- сообщим о неудаче
      Print("Метод PositionClose() потерпел неудачу. Код возврата=",m_Trade.ResultRetcode(),
            ". Описание кода: ",m_Trade.ResultRetcodeDescription());
         }
   else
         {
       Print("Метод PositionClose() выполнен успешно. Код возврата=",m_Trade.ResultRetcode(),
            " (",m_Trade.ResultRetcodeDescription(),")");       
          }
    
     
           }          
            }
 

EA log after the bar has closed below the stop level. Long position = 1 lot, short position = 1 lot)