Questions from Beginners MQL5 MT5 MetaTrader 5 - page 899

 
lil_lil:
Thank you.

Or just iHighest() - the latest builds already have it.

 
Ihor Herasko:

In accounts like Netting, a position and a trade are different concepts. You have now shown the selection of a position.

How do youselect the trade included in that position?

long ID=PositionGetInteger(POSITION_IDENTIFIER);

 
Sile Si:

And howto select the trade included in this position



bool  HistoryDealSelect(
   ulong  ticket     // тикет сделки
   );
Документация по MQL5: Торговые функции / HistoryDealSelect
Документация по MQL5: Торговые функции / HistoryDealSelect
  • www.mql5.com
Выбирает в истории сделку для дальнейших обращений к ней  через соответствующие функции. Возвращает true при успешном завершении функции. Возвращает false при неудачном завершении функции. Чтобы получить информацию об ошибке, необходимо вызвать функцию GetLastError(). Не следует путать между собой ордера, сделки и позиции. Каждая сделка...
 
Alexey Viktorov:


Thank you, there are several deals, so I decided to use HistoryDealGetTicket().

I commented out everything, can you please tell me where I am going wrong. Where am I wrong?

double Aver_Pr_nett()
  {
   double total_price_multiply_volume_sell   = 0.0;
   double total_volume_sell                  = 0.0;
   double net_price_sell_=0.0;
   string symb=_Symbol;
   int    total       =0;  // 
   for(int i=0; i<PositionsTotal(); i++)
     {
      ulong pt=PositionGetTicket(i);//  тикет позиции
      long ID=PositionGetInteger(POSITION_IDENTIFIER);//id позиции
      if(PositionGetString(POSITION_SYMBOL)==symb && //символ позиции
      HistorySelect(PositionGetInteger(POSITION_TIME),TimeCurrent()+60))//промежуток времени для поиска сделок
        {
         total=HistoryDealsTotal();//количество сделок
         
         for(int i=0; i<total; i++)// цикл по всем сделкам
           {
            ulong dt = HistoryDealGetTicket(i);//тикет сделки, возможно нужно использовать HistoryDealSelect()
            long did = HistoryDealGetInteger(dt, DEAL_POSITION_ID);//id сделки
            ENUM_DEAL_ENTRY in_out=HistoryDealGetInteger(dt,DEAL_ENTRY);//
            if(did==pt &&          //id сделки равно тикету позиции
            in_out==DEAL_ENTRY_IN) //сделка открыла позицию либо добавила объём
              {
               if(HistoryDealGetString(dt,DEAL_SYMBOL)==symb)//символ сделки равен текущему графику
                 {//дальше нахожу среднюю цену сделок
                  total_price_multiply_volume_sell+=HistoryDealGetDouble(dt,DEAL_PRICE)*HistoryDealGetDouble(dt,DEAL_VOLUME);
                  total_volume_sell+=HistoryDealGetDouble(dt,DEAL_VOLUME);
                  if(total_price_multiply_volume_sell!=0 && total_volume_sell!=0)
                    {
                    net_price_sell_=total_price_multiply_volume_sell/total_volume_sell;
                    };
                 }
              }
           }
        }
     }
//---
   return(net_price_sell_);
  }

 
Sile Si:

Thank you, there are several deals, so I decided to use HistoryDealGetTicket().

I commented out everything, can you please tell me where I am going wrong. Where am I wrong?


I was very wrong. I gave a wrong reference in a hurry. I was thinking about one thing and chose the wrong one.

Here's the right link.

Документация по MQL5: Торговые функции / HistorySelectByPosition
Документация по MQL5: Торговые функции / HistorySelectByPosition
  • www.mql5.com
Не следует путать между собой ордера из торговой истории и действующие отложенные ордера, которые отображаются на вкладке "Торговля" в панели "Инструменты". Список ордеров, которые были отменены или привели к проведению торговой операции, можно посмотреть  в закладке "История" на панели "Инструменты" клиентского терминала. Функция...
 
Alexey Viktorov:

I was very wrong. I gave the wrong link in a hurry. I was thinking of one thing and I picked the wrong one.

Here's the right link.

Thank you. (chuckles)

 
How do I draw a line on an indicator, e.g. iAO,iDem, by 2 points and get the value of the line at point X ?
 
Сергей:
How to draw a line on an indicator, e.g. iAO,iDem, by 2 points and get the line value at point X ?

Each indicator is drawn either in the main window or in a sub-window. So step 1: find out the sub-window number in which the indicator is drawn. Look in the direction ofOperations with charts.

Step 2: when there is a subwindow number, it is easy to draw a line. SeeOBJ_TREND help, and"TrendCreate" function parameters

//+------------------------------------------------------------------+ 
//| Создает линию тренда по заданным координатам                     | 
//+------------------------------------------------------------------+ 
bool TrendCreate(const long            chart_ID=0,        // ID графика 
                 const string          name="TrendLine",  // имя линии 
                 const int             sub_window=0,      // номер подокна 
                 datetime              time1=0,           // время первой точки 
                 double                price1=0,          // цена первой точки 
                 datetime              time2=0,           // время второй точки 
                 double                price2=0,          // цена второй точки 
                 const color           clr=clrRed,        // цвет линии 
                 const ENUM_LINE_STYLE style=STYLE_SOLID, // стиль линии 
                 const int             width=1,           // толщина линии 
                 const bool            back=false,        // на заднем плане 
                 const bool            selection=true,    // выделить для перемещений 
                 const bool            ray_left=false,    // продолжение линии влево 
                 const bool            ray_right=false,   // продолжение линии вправо 
                 const bool            hidden=true,       // скрыт в списке объектов 
                 const long            z_order=0)         // приоритет на нажатие мышью 
  { 
 
Artyom Trishkin:

Or just iHighest() - the latest builds already have it.

Oh, I see they've finally added these new-old functions to the help too.

 

No doubt, the EA attached to si modifies vtbr. Places T/P positions on the quotes of its instrument "si".

llo

If I attach an EA to vtbr, it does not modify si, it works only on its instrument

ppv

Any explanation for this?

There is no modification in the code except this one:

   if(TakeProfit>0)
     {
     if(!RefreshRates())
            return;
      int total=PositionsTotal();
      for(int i=total-1;i>=0;i--)
        {
         if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
           {
            if(m_position.Symbol()==Symbol())
              {
               //if(m_position.PositionType()==POSITION_TYPE_BUY)
               if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
                 {
                  if(m_symbol.NormalizePrice(Aver_Pr_sell_nett()+ExtTakeProfit)!=m_position.TakeProfit())
                    {
                     m_trade.PositionModify(m_position.Ticket(),
                                            m_position.StopLoss(),
                                            m_symbol.NormalizePrice(Aver_Pr_sell_nett()+ExtTakeProfit)
                                            );
                     Sleep(300);

                    }
                 }
               //==//
               //if(m_position.PositionType()==POSITION_TYPE_SELL)
               else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
                 {
                  if(m_symbol.NormalizePrice(Aver_Pr_sell_nett()-ExtTakeProfit)!=m_position.TakeProfit())
                    {
                       {
                        m_trade.PositionModify(m_position.Ticket(),
                                               m_position.StopLoss(),
                                               m_symbol.NormalizePrice(Aver_Pr_sell_nett()-ExtTakeProfit)
                                               );
                        Sleep(300);
                       }
                    }
                 }
              }
           }
        }
     }
Reason: