Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1326

 
Aleksandr Egorov:
how to calculate the commission for open orders in mt5 for each pair separately?

for some reason it won't - it shows zeros

//+------------------------------------------------------------------+
//|                                                   Commission.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#include <Trade\PositionInfo.mqh>
CPositionInfo     m_position;            // : trade position object
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   double Commission=0.00;
   int total=PositionsTotal();
   for(int i=total-1; i>=0; i--)
     {
      string   position_GetSymbol=PositionGetSymbol(i); //
      if(position_GetSymbol==Symbol())
        {
         Commission=Commission+m_position.Commission();
        }
     }
   string msg=DoubleToString(Commission,2);
   Print(msg);
  }
//+------------------------------------------------------------------+
 
SanAlex:

For some reason it doesn't want to - it shows zeros.

As far as I remember, this thing never worked, and you can't get the commission for the position, you have to go through all the trades from the history, check if they belong to the selected position, and sum it up, it gets pretty messy, but somewhere there was an example code, I think from fxsaber.

 
transcendreamer:

As far as I remember, this thing never worked, and you can't get the commission for the position, you have to go through all the trades from the history, check if they belong to the selected position, and sum it up, it gets pretty messy, but somewhere there was a code example, I think from fxsaber.

fxsaber showed it as a calculation of all open pairs and that is the total commission

 
Aleksandr Egorov:

fxsaber was sending us the calculation of all the open pairs, i.e. the total commission

Right, here's the link:https://www.mql5.com/ru/forum/93879/page5

Трудности перевода :)
Трудности перевода :)
  • 2016.09.05
  • www.mql5.com
Хочу рассказать, как я перевел свой проект с MQL4 на 5-ку за одну ночь...
 
Well, here is the question )) Why can't they make simple things simple and not on the contrary to calculate the commission to swell?
 
Aleksandr Egorov:
well, that's the question )) why can't they make simple things simple and not calculate the commission?

Well yes, it's unclear why the developers wouldn't make a ready-made function... maybe one day they will... there used to be no i-functions and everyone was struggling too... now there is... maybe we'll wait for commissions...

 
transcendreamer:

Well yes, it's unclear why the developers wouldn't make a ready-made function... maybe one day they will... there used to be no i-functions and everyone was struggling too... now there is... maybe we'll wait for the commissions...

it's probably faster to do it yourself...

 
SanAlex:

for some reason does not want to show zeros

still zeros and does not want to show commission

//+------------------------------------------------------------------+
//|                                                   Commission.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   double Commission=::PositionGetDouble(POSITION_COMMISSION);
// На случай, если POSITION_COMMISSION не работает
   if(Commission==0)
     {
      const ulong Ticket=GetPositionDealIn();
      if(Ticket>0)
        {
         const double LotsIn=::HistoryDealGetDouble(Ticket,DEAL_VOLUME);
         if(LotsIn>0)
            Commission=::HistoryDealGetDouble(Ticket,DEAL_COMMISSION)*::PositionGetDouble(POSITION_VOLUME)/LotsIn;
        }
     }
//---
   string msg_1=DoubleToString(Commission,2);
   string msg=DoubleToString(GetPositionCommission(),2);
   Print(msg_1,"     ",msg);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double GetPositionCommission(void)
  {
   double Commission=::PositionGetDouble(POSITION_COMMISSION);
// На случай, если POSITION_COMMISSION не работает
   if(Commission==0)
     {
      const ulong Ticket=GetPositionDealIn();
      if(Ticket>0)
        {
         const double LotsIn=::HistoryDealGetDouble(Ticket,DEAL_VOLUME);
         if(LotsIn>0)
            Commission=::HistoryDealGetDouble(Ticket,DEAL_COMMISSION)*::PositionGetDouble(POSITION_VOLUME)/LotsIn;
        }
     }
   return(Commission);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
ulong GetPositionDealIn(const ulong HistoryTicket=0)
  {
   ulong Ticket=0;
   if((HistoryTicket==0) ? ::HistorySelectByPosition(::PositionGetInteger(POSITION_TICKET)) : ::HistorySelectByPosition(HistoryTicket))
     {
      const int Total=::HistoryDealsTotal();
      for(int i=0; i<Total; i++)
        {
         const ulong TicketDeal=::HistoryDealGetTicket(i);
         if(TicketDeal>0)
            if((ENUM_DEAL_ENTRY)::HistoryDealGetInteger(TicketDeal,DEAL_ENTRY)==DEAL_ENTRY_IN)
              {
               Ticket=TicketDeal;
               break;
              }
        }
     }
   return(Ticket);
  }
//+------------------------------------------------------------------+
 
I've done it halfway, but there is an error here.
I think I have half done it, put iClose, but there is an error. it opens a new position after every bar


I have it like this



   bool Buy_Condition = (close1 > EMA0[0]);

     {  
       if(Buy_Condition) //Buy
            {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      my_TP = m_symbol.Ask() + ExtTakeProfit*Point();
      my_SL = m_symbol.Ask() - ExtStopLoss*Point();
      my_lot = Lots;
      OPENORDER("Sell");
            }
      }

   bool Sell_Condition = (close1 < EMA0[0]);

    {
    if(Sell_Condition )
         {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      my_TP  = m_symbol.Bid() - ExtTakeProfit*Point();
      my_SL  = m_symbol.Bid() + ExtStopLoss*Point();

      my_lot= Lots;
      OPENORDER("Buy");
         }
     }
 } 
   if(colorBuffer[m_bar_current+1]>colorBuffer[m_bar_current] ) //Buy
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      CLOSEORDER("Sell");
     }
 
  if(colorBuffer[m_bar_current+1]<colorBuffer[m_bar_current] ) //Sell
     {
      if(!RefreshRates())
         return;
      TimeBar=time_0;
      CLOSEORDER("Buy");
     }
 
   return;
  }
  
//--------------------------------------------------------------------
void CLOSEORDER(string ord)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)  // returns the number of open positions
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY && ord=="Buy")
               m_trade.PositionClose(m_position.Ticket());  // Close Buy
            if(m_position.PositionType()==POSITION_TYPE_SELL && ord=="Sell")
               m_trade.PositionClose(m_position.Ticket()); // Close Sell
           }
  }
//--------------------------------------------------------------------

void OPENORDER(string ord)
  {
  if(ord=="Sell")
   if(all_positions==1)
  
      for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
         if(m_position.SelectByIndex(i))
           if(m_position.PositionType()==POSITION_TYPE_SELL)
            //if(m_position.PositionType()==POSITION_TYPE_SELL)
               return;                          // Если buy, то не открываемся
 
      if(!m_trade.Sell(my_lot,Symbol(),m_symbol.Bid(),my_SL,my_TP,""))
         Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription(),
               ", ticket of deal: ",m_trade.ResultDeal());
   if(ord=="Buy")
   if(all_positions==1)
 
      for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
         if(m_position.SelectByIndex(i))
            //if(m_position.PositionType()==POSITION_TYPE_BUY)
            if(m_position.PositionType()==POSITION_TYPE_BUY)
               return;                          // Если buy, то не открываемся
 

      if(!m_trade.Buy(my_lot,Symbol(),m_symbol.Ask(),my_SL,my_TP,""))
         Print("BUY_STOP -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of Retcode: ",m_trade.ResultRetcodeDescription(),
               ", ticket of order: ",m_trade.ResultOrder());
   return;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
 
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
      return(false);
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Get Time for specified bar index                                 |
//+------------------------------------------------------------------+
datetime iTime(const int index,string symbol=NULL,ENUM_TIMEFRAMES timeframe=PERIOD_CURRENT)
  {
   if(symbol==NULL)
      symbol=Symbol();
   if(timeframe==0)
      timeframe=Period();
   datetime Time[];
   datetime time=0;
   ArraySetAsSeries(Time,true);
   int copied=CopyTime(symbol,timeframe,index,1,Time);
   if(copied>0)
      time=Time[0];
   return(time);
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
bool iGetArray(const int handle,const int buffer,const int start_pos,
               const int count,double &arr_buffer[])
  {
   bool result=true;
   if(!ArrayIsDynamic(arr_buffer))
     {
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);
      return(false);
     }
   ArrayFree(arr_buffer);
//--- reset error code
   ResetLastError();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);
   if(copied!=count)
     {
      //--- if the copying fails, tell the error code
      PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",
                  __FILE__,__FUNCTION__,count,copied,GetLastError());
      //--- quit with zero result - it means that the indicator is considered as not calculated
      return(false);
     }
   return(result);
 
 
}


i.e. it does not check if there is an open order?




Files:
Unbenannt5.PNG  28 kb
 
Eugen8519:
I've done it halfway, but there is an error here.
I seem to have done it halfway, put iClose, but there is an error. it opens a new position after every bar

The best way is to create a signal in the Indicator and then enter it into the Expert Advisor

Fx10

//+------------------------------------------------------------------+
//|                                                         Fx10.mq5 |
//|                                   Copyright © 2000-2007, palanka |
//|                                         http://www.metaquotes.ru |
//+------------------------------------------------------------------+
//---- авторство индикатора
#property copyright "Copyright © 2000-2007, palanka"
//---- ссылка на сайт автора
#property link      ""
//---- номер версии индикатора
#property version   "1.02"
//---- отрисовка индикатора в главном окне
#property indicator_chart_window
//---- для расчета и отрисовки индикатора использовано два буфера
#property indicator_buffers 2
//---- использовано всего два графических построения
#property indicator_plots   2
//+----------------------------------------------+
//|  Объявление констант                         |
//+----------------------------------------------+
#define  RESET  0 // константа для возврата терминалу команды на пересчет индикатора
//+----------------------------------------------+
//|  Параметры отрисовки медвежьего индикатора   |
//+----------------------------------------------+
//---- отрисовка индикатора 1 в виде символа
#property indicator_type1   DRAW_ARROW
//---- в качестве цвета индикатора использован цвет Magenta
#property indicator_color1  Magenta
//---- толщина линии индикатора 1 равна 4
#property indicator_width1  4
//---- отображение метки индикатора
#property indicator_label1  "Fx10 Sell"
//+----------------------------------------------+
//|  Параметры отрисовки бычьего индикатора      |
//+----------------------------------------------+
//---- отрисовка индикатора 2 в виде символа
#property indicator_type2   DRAW_ARROW
//---- в качестве цвета индикатора использован цвет Lime
#property indicator_color2  Lime
//---- толщина линии индикатора 2 равна 4
#property indicator_width2  4
//---- отображение метки индикатора
#property indicator_label2 "Fx10 Buy"
//+----------------------------------------------+
//| Входные параметры индикатора                 |
//+----------------------------------------------+
input double ParmMult=1.0; // multiply the standard parameters by this scale factor
//+----------------------------------------------+
//---- объявление динамических массивов, которые в дальнейшем
//---- будут использованы в качестве индикаторных буферов
double SellBuffer[];
double BuyBuffer[];
//---- объявление целочисленных переменных начала отсчета данных
int min_rates_total;
//---- объявление целочисленных переменных для хендлов индикаторов
int MA5_Handle,MA10_Handle,RSI_Handle,STO_Handle,MACD_Handle,ATR_Handle;
int OldTrend;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
//---- инициализация глобальных переменных
   min_rates_total=int(ParmMult*26+1);
//---- получение хендла индикатора MA5
   MA5_Handle=iMA(NULL,0,int(ParmMult*5),0,MODE_LWMA,PRICE_CLOSE);
   if(MA5_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора iMA5");
//---- получение хендла индикатора MA10
   MA10_Handle=iMA(NULL,0,int(ParmMult*10),0,MODE_SMA,PRICE_CLOSE);
   if(MA10_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора iMA10");
//---- получение хендла индикатора RSI
   RSI_Handle=iRSI(NULL,0,int(ParmMult*14),PRICE_CLOSE);
   if(RSI_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора iRSI");
//---- получение хендла индикатора Stochastic
   STO_Handle=iStochastic(NULL,0,int(5*ParmMult),int(3*ParmMult),int(3*ParmMult),MODE_SMA,STO_LOWHIGH);
   if(STO_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора iStochastic");
//---- получение хендла индикатора MACD
   MACD_Handle=iMACD(NULL,0,int(12*ParmMult),int(26*ParmMult),int(9*ParmMult),PRICE_CLOSE);
   if(MACD_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора iMACD");
//---- получение хендла индикатора ATR
   ATR_Handle=iATR(NULL,0,15);
   if(ATR_Handle==INVALID_HANDLE)
      Print(" Не удалось получить хендл индикатора ATR");
//---- превращение динамического массива SellBuffer[] в индикаторный буфер
   SetIndexBuffer(0,SellBuffer,INDICATOR_DATA);
//---- осуществление сдвига начала отсчета отрисовки индикатора 1
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,min_rates_total);
//---- символ для индикатора
   PlotIndexSetInteger(0,PLOT_ARROW,119);
//---- установка значений индикатора, которые не будут видимы на графике
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---- индексация элементов в буфере, как в таймсерии
   ArraySetAsSeries(SellBuffer,true);
//---- превращение динамического массива BuyBuffer[] в индикаторный буфер
   SetIndexBuffer(1,BuyBuffer,INDICATOR_DATA);
//---- осуществление сдвига начала отсчета отрисовки индикатора 2
   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,min_rates_total);
//---- символ для индикатора
   PlotIndexSetInteger(1,PLOT_ARROW,119);
//---- установка значений индикатора, которые не будут видимы на графике
   PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0);
//---- индексация элементов в буфере, как в таймсерии
   ArraySetAsSeries(BuyBuffer,true);
//---- установка формата точности отображения индикатора
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//---- имя для окон данных и метка для подокон
   string short_name="Fx10";
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//----
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---- проверка количества баров на достаточность для расчета
   if(BarsCalculated(MA5_Handle)<rates_total
      || BarsCalculated(MA10_Handle)<rates_total
      || BarsCalculated(RSI_Handle)<rates_total
      || BarsCalculated(STO_Handle)<rates_total
      || BarsCalculated(MACD_Handle)<rates_total
      || BarsCalculated(ATR_Handle)<rates_total
      || rates_total<min_rates_total)
      return(RESET);
//---- объявления локальных переменных
   int to_copy,limit,bar;
   double MA5[],MA10[],RSI[],STO[],MACD[],STOS[],MACDS[],ATR[];
   bool RsiUp,RsiDn,StochUp,StochDn,MacdUp,MacdDn;
//---- расчеты необходимого количества копируемых данных и
//---- и стартового номера limit для цикла пересчета баров
   if(prev_calculated>rates_total || prev_calculated<=0)// проверка на первый старт расчета индикатора
      limit=rates_total-min_rates_total;   // стартовый номер для расчета всех баров
   else
      limit=rates_total-prev_calculated; // стартовый номер для расчета новых баров
   to_copy=limit+1;
//---- копируем вновь появившиеся данные в массивы
   if(CopyBuffer(MA5_Handle,0,0,to_copy,MA5)<=0)
      return(RESET);
   if(CopyBuffer(MA10_Handle,0,0,to_copy,MA10)<=0)
      return(RESET);
   if(CopyBuffer(RSI_Handle,0,0,to_copy,RSI)<=0)
      return(RESET);
   if(CopyBuffer(STO_Handle,0,0,to_copy,STO)<=0)
      return(RESET);
   if(CopyBuffer(STO_Handle,1,0,to_copy,STOS)<=0)
      return(RESET);
   if(CopyBuffer(MACD_Handle,0,0,to_copy,MACD)<=0)
      return(RESET);
   if(CopyBuffer(MACD_Handle,1,0,to_copy,MACDS)<=0)
      return(RESET);
   if(CopyBuffer(ATR_Handle,0,0,to_copy,ATR)<=0)
      return(RESET);
//---- индексация элементов в массивах, как в таймсериях
   ArraySetAsSeries(MA5,true);
   ArraySetAsSeries(MA10,true);
   ArraySetAsSeries(RSI,true);
   ArraySetAsSeries(STO,true);
   ArraySetAsSeries(STOS,true);
   ArraySetAsSeries(MACD,true);
   ArraySetAsSeries(MACDS,true);
   ArraySetAsSeries(ATR,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
//---- основной цикл расчета индикатора
   for(bar=limit; bar>=0 && !IsStopped(); bar--)
     {
      BuyBuffer[bar]=0.0;
      SellBuffer[bar]=0.0;
      if(MA5[bar]>MA10[bar])
        {
         RsiUp=RSI[bar]>=55.0;
         StochUp=STO[bar]>STOS[bar];
         MacdUp=MACD[bar]>MACDS[bar];
         if(StochUp && RsiUp && MacdUp)
           {
            if(OldTrend<0)
               BuyBuffer[bar]=low[bar]-ATR[bar]*3/8;
            if(bar!=0)
               OldTrend=+1;
           }
        }
      if(MA5[bar]<MA10[bar])
        {
         RsiDn=RSI[bar]<=45.0;
         StochDn=STO[bar]<STOS[bar];
         MacdDn=MACD[bar]<MACDS[bar];
         if(StochDn && RsiDn && MacdDn)
           {
            if(OldTrend>0)
               SellBuffer[bar]=high[bar]+ATR[bar]*3/8;
            if(bar!=0)
               OldTrend=-1;
           }
        }
     }
//----
   return(rates_total);
  }
//+------------------------------------------------------------------+
Fx10 3
Files:
Exp_Fx10.mq5  16 kb
Reason: