Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1054

 

Igor Makanu:

standard CTrade does not provide an out-of-the-box service

On MT4 there are trading things that are coded in one line. On MT5 you can't do the same thing through SB even in a hundred lines. On pure MQL5 it's even worse. That's ok.

 

Thanks, good example I'll look into it, here's a script for MT4 - determine profit in pips:

//+------------------------------------------------------------------+
//|                                        LastOrderProfitInPips.mq4 |
//|                                                            IgorM |
//|                              https://www.mql5.com/ru/users/igorm |
//+------------------------------------------------------------------+
#property copyright "IgorM"
#property link      "https://www.mql5.com/ru/users/igorm"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   printf("Прибыль последнего закрытого ордера %d пунктов",LastHistoryProfit());

  }
//+------------------------------------------------------------------+
int LastHistoryProfit(int magic_=-1)
  {
   datetime t=0;
   int profit=0;
   for(int i=0; i<OrdersHistoryTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
        {
         if((OrderMagicNumber()==magic_ || magic_==-1) && (OrderSymbol()==_Symbol))
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(OrderCloseTime()>t)
                 {
                  t=OrderCloseTime();
                  profit= (int)(fabs(OrderOpenPrice()-OrderClosePrice())/_Point);
                  profit= OrderProfit()>=0.0 ? profit : -profit;
                 }
              }
           }
        }
     }
   return(profit);
  }
//+------------------------------------------------------------------+

I wrote it from scratch in 10 minutes? - Well, about that, the logic is simple and straightforward - you take it and write it, in MT5 so far we only discuss a spherical horse in a vacuum... if trades and whether there are orders, left to discuss types of accounts netting or hedge.... and we will write something by morning.

 
Igor Makanu:

Thank you, good example, I will study it, I made a script for MT4 - determine profit in pips

I do not need to tell you how to run this script in MT5. However, the script itself has errors.

First I will show you the history

and the result of the execution

Прибыль последнего закрытого ордера -259 пунктов


Here are errors

int LastHistoryProfit(int magic_=-1)
  {
   datetime t=0;
   int profit=0;
   for(int i=0; i<OrdersHistoryTotal(); i++) // Надо бежать в обратную сторону, т.к. последняя позиция может быть закрыта в ту же секунду, что и предпоследняя.
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
        {
         if((OrderMagicNumber()==magic_ || magic_==-1) && (OrderSymbol()==_Symbol))
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(OrderCloseTime()>t) // В отличие от MT4, в MT5 это можно не делать - сортировка по времени закрытия есть.
                 {
                  t=OrderCloseTime();
                  profit= (int)(fabs(OrderOpenPrice()-OrderClosePrice())/_Point); // При таком вычислении легко потерять один пункт.
                  profit= OrderProfit()>=0.0 ? profit : -profit;
                 }
              }
           }
        }
     }
   return(profit);
  }
 
fxsaber:

And the errors here.

При таком вычислении легко потерять один пункт.

How to fix? I've never thought about it, the scheme seems to be standard: 2 prices - find the difference and divide by points

i agree with the rest, but i need to think, the scheme of order search is classic and i want to compare the time to the highest.... just in case. i need to think, although it's the first time i have to do it - 99.99% of the time nobody even tries to trade hft TS on MT4

 
Igor Makanu:

How to fix it? I never thought about it, the scheme seems to be standard: 2 prices - find the difference and divide by points

Loss when casting double -> int.

I agree with the rest, but I need to think, the scheme of enforcing orders is classic, and I want to compare the time to the highest.... just in case. i need to think, although this is the first time i've encountered such a problem - in 99.99% of cases no one even tries to trade hft TS on MT4

HFT has nothing to do with it. CloseAll script may well close two positions within one second. In MT4 you have to compare, in MT5 it's unnecessary. And it is probably easier to compare via ArraySort (if, for example, you want to quickly change to the penultimate closed position).

 
fxsaber:

The loss when casting double -> int.

this is all clear, but how do I correctly calculate the difference of 2 prices in integer points?

 
Igor Makanu:

This is all clear, but how do I calculate the difference in pips between 2 prices?

Forum on trading, automated trading systems and testing trading strategies

need help for calculated total pips for order closed today (Mql5)

fxsaber, 2017.10.25 01:00

#include <MT4Orders.mqh> // https://www.mql5.com/en/code/16006

int PriceToInteger( const double Price, const double point )
{
  return((int)(Price / point + 0.1));
}

int GetTotalPips( const datetime From = 0 )
{
  int Res = 0;
  
  for (int i = OrdersHistoryTotal() - 1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
      if (OrderCloseTime() < From)
        break;
      else if (OrderType() <= OP_SELL)
      {
        const double point = SymbolInfoDouble(OrderSymbol(), SYMBOL_POINT);
        
        Res += OrderType() ? PriceToInteger(OrderOpenPrice(), point) - PriceToInteger(OrderClosePrice(), point)
                           : PriceToInteger(OrderClosePrice(), point) - PriceToInteger(OrderOpenPrice(), point);
      }
        
  return(Res);
}

void OnStart()
{
  datetime Today = TimeCurrent();
  
  Today -= Today % PeriodSeconds(PERIOD_D1);
  
  Alert(GetTotalPips(Today));
}
 
fxsaber:

Thank you!

I especially liked it.

const double point = SymbolInfoDouble(OrderSymbol(), SYMBOL_POINT);

I'll keep that in mind, I usually write everything in global visibility, your example reads much better


....


And this is correct? In the order loop, would SymbolInfoDouble(OrderSymbol(), SYMBOL_POINT); be recalculated each time, becauseOrderSymbol() will be different each time?

 

Forum on Trading, Automated Trading Systems and Strategy Tests

Questions from Beginners MQL5 MT5 MetaTrader 5

Igor Makanu, 2019.06.04 18:43

Thanks, good example i'll look into it, here's a script i drafted for MT4 - determine profit in pips:

//+------------------------------------------------------------------+
//|                                        LastOrderProfitInPips.mq4 |
//|                                                            IgorM |
//|                              https://www.mql5.com/ru/users/igorm |
//+------------------------------------------------------------------+
#property copyright "IgorM"
#property link      "https://www.mql5.com/ru/users/igorm"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   printf("Прибыль последнего закрытого ордера %d пунктов",LastHistoryProfit());

  }
//+------------------------------------------------------------------+
int LastHistoryProfit(int magic_=-1)
  {
   datetime t=0;
   int profit=0;
   for(int i=0; i<OrdersHistoryTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
        {
         if((OrderMagicNumber()==magic_ || magic_==-1) && (OrderSymbol()==_Symbol))
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               if(OrderCloseTime()>t)
                 {
                  t=OrderCloseTime();
                  profit= (int)(fabs(OrderOpenPrice()-OrderClosePrice())/_Point);
                  profit= OrderProfit()>=0.0 ? profit : -profit;
                 }
              }
           }
        }
     }
   return(profit);
  }
//+------------------------------------------------------------------+

Written from scratch in 10 minutes? - Well, approximately so, the logic is simple and straightforward - you take it and write it, in MT5 we are discussing only a spherical horse in a vacuum... if trades and whether there are orders, left to discuss types of accounts netting or hedge.... and we will write something in the morning.

And may I ask why we should take the absolute value of the difference between the opening and closing price and then, if the profit of the position is less than zero, substitute a minus sign for the value.
 
Alexey Viktorov:
And may I ask why we should take the absolute value of the difference between the opening and closing price, and then, if the profit of the position is less than zero, substitute the minus sign for the value.

I wrote it on the fly, as I wanted - I wanted to output +100 points or -100 points, it was a matter of taste - I had no specific task, but to write conditions to determine the order type and compare the opening and closing price, it seemed that there would be too many extra lines...

ZS: This is a forum for programmers, isn't it? - They are like that. They can optimize one code (especially someone else's) 10 times over, to replace 5 lines with 4 )))

Reason: