Как найти среднюю цену?

 

Приветствую достойных.

Помогите найти среднюю цену mql5. Пожалуйста, есть 4 позиции разными лотами, по разной цене, в одном направлении, хочу узнать где их цена Б.У.

 

Вопрос непонятен.

Что значит "цена Б.У." для нескольких позиций ? Цена БУ бывает для одной позиции - это, фактически, цена ее открытия. А если позиций несколько - о какой ОДНОЙ "цене БУ" может идти речь ?

 
George Merts:

Вопрос непонятен.

Что значит "цена Б.У." для нескольких позиций ? Цена БУ бывает для одной позиции - это, фактически, цена ее открытия. А если позиций несколько - о какой ОДНОЙ "цене БУ" может идти речь ?


Имеется в виду, если на hedge счете открыть BUY 0.30 lot по цене 1.18470 и BUY 0.15 lot по цене 1.18740 - где будет неттинговая цена этих двух позиций?

 
Vladimir Karputov:

Совершенно верно )

 

(Ценв1 * Объем1 + ... + ЦенаN * ОбъемN) / (Объем1 +...+ ОбъемN)

 
Dmitriy Skub:

(Ценв1 * Объем1 + ... + ЦенаN * ОбъемN) / (Объем1 +...+ ОбъемN)


Непонятно, а если позиций будет десяток. Как это в цикле посчитать?

 
lil_lil:

Непонятно, а если позиций будет десяток. Как это в цикле посчитать?

Прямо так и посчитать - Цикл (1...N)

Попробуйте сообразить, у Вас все получится.

 

Примерно так:

Calculation Net Price

//+------------------------------------------------------------------+
//|                                        Calculation Net Price.mq5 |
//|                              Copyright © 2017, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2017, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
CPositionInfo  m_position;                   // trade position object
//--- input parameters
input ENUM_POSITION_TYPE   InpPostions=POSITION_TYPE_SELL;   // Position type
//---
string   m_hline_name="net price";
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   m_hline_name=(InpPostions==POSITION_TYPE_SELL)?"Sell "+m_hline_name:"Buy "+m_hline_name;
   m_hline_name=Symbol()+" "+m_hline_name;
   HLineCreate(0,m_hline_name);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   HLineDelete(0,m_hline_name);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   CalculationNetPrice(InpPostions);
  }
//+------------------------------------------------------------------+
//| Calculation Net Price                                            |
//+------------------------------------------------------------------+
double CalculationNetPrice(const ENUM_POSITION_TYPE pos_type)
  {
   double total_price_multiply_volume  = 0.0;
   double total_volume                 = 0.0;
   double net_price                    = 0.0;
   bool   first_find                   = true;
   double last_price                   = 0.0;

   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
         break;
      if(m_position.Symbol()==Symbol() /*&& m_position.Magic()==m_magic*/)
        {
         if(m_position.PositionType()==pos_type)
           {
            total_price_multiply_volume+=m_position.PriceOpen()*m_position.Volume();
            total_volume+=m_position.Volume();
           }
        }
     }
   if(total_price_multiply_volume!=0 && total_volume!=0)
     {
      net_price=total_price_multiply_volume/total_volume;
      HLineMove(0,m_hline_name,net_price);
     }
   return(net_price);
  }
//+------------------------------------------------------------------+ 
//| Create the horizontal line                                       | 
//+------------------------------------------------------------------+ 
bool HLineCreate(const long            chart_ID=0,        // chart's ID 
                 const string          name="HLine",      // line name 
                 const int             sub_window=0,      // subwindow index 
                 double                price=0,           // line price 
                 const color           clr=clrRed,        // line color 
                 const ENUM_LINE_STYLE style=STYLE_SOLID, // line style 
                 const int             width=1,           // line width 
                 const bool            back=false,        // in the background 
                 const bool            selection=true,    // highlight to move 
                 const bool            hidden=true,       // hidden in the object list 
                 const long            z_order=0)         // priority for mouse click 
  {
//--- if the price is not set, set it at the current Bid price level 
   if(!price)
      price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value 
   ResetLastError();
//--- create a horizontal line 
   if(!ObjectCreate(chart_ID,name,OBJ_HLINE,sub_window,0,price))
     {
      Print(__FUNCTION__,
            ": failed to create a horizontal line! Error code = ",GetLastError());
      return(false);
     }
//--- set line color 
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style 
   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width 
   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true) 
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse 
//--- when creating a graphical object using ObjectCreate function, the object cannot be 
//--- highlighted and moved by default. Inside this method, selection parameter 
//--- is true by default making it possible to highlight and move the object 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list 
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart 
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution 
   return(true);
  }
//+------------------------------------------------------------------+ 
//| Move horizontal line                                             | 
//+------------------------------------------------------------------+ 
bool HLineMove(const long   chart_ID=0,   // chart's ID 
               const string name="HLine", // line name 
               double       price=0)      // line price 
  {
//--- if the line price is not set, move it to the current Bid price level 
   if(!price)
      price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value 
   ResetLastError();
//--- move a horizontal line 
   if(!ObjectMove(chart_ID,name,0,0,price))
     {
      Print(__FUNCTION__,
            ": failed to move the horizontal line! Error code = ",GetLastError());
      return(false);
     }
//--- successful execution 
   return(true);
  }
//+------------------------------------------------------------------+ 
//| Delete a horizontal line                                         | 
//+------------------------------------------------------------------+ 
bool HLineDelete(const long   chart_ID=0,   // chart's ID 
                 const string name="HLine") // line name 
  {
//--- reset the error value 
   ResetLastError();
//--- delete a horizontal line 
   if(!ObjectDelete(chart_ID,name))
     {
      Print(__FUNCTION__,
            ": failed to delete a horizontal line! Error code = ",GetLastError());
      return(false);
     }
//--- successful execution 
   return(true);
  }
//+------------------------------------------------------------------+
Файлы:
 
lil_lil:

Непонятно, а если позиций будет десяток. Как это в цикле посчитать?

Я считаю так, тогда учитываются все свопы и комиссии.

// _Get.Pos.Buy._Profit = общий профит Buy

// _Get.Pos.Sell._Profit = общий профит Sell

// _Get.Pos.Buy._Lots= общий Lot Buy

// _Get.Pos.Sell._Lots= общий Lot Sell

double TickValue=SymbolInfoDouble(mSymbol,SYMBOL_TRADE_TICK_VALUE); if(TickValue==0) return; double ask=SymbolInfoDouble(mSymbol,SYMBOL_ASK); double bid=SymbolInfoDouble(mSymbol,SYMBOL_BID); double poi=SymbolInfoDouble(mSymbol,SYMBOL_ASK); int dig=(int)SymbolInfoInteger(mSymbol,SYMBOL_DIGITS);   BuyAwerage=0; SellAwerage=0; AllAwerage=0;   if(_Get.Pos.Buy._Lots>0) BuyAwerage= bid-(_Get.Pos.Buy._Profit/(TickValue*_Get.Pos.Buy._Lots))*poi;   if(_Get.Pos.Sell._Lots>0) SellAwerage= ask+(_Get.Pos.Sell._Profit/(TickValue*_Get.Pos.Sell._Lots))*poi;   if(_Get.Pos.Buy._Lots-_Get.Pos.Sell._Lots!=0) AllAwerage= ((_Get.Pos.Buy._Lots>_Get.Pos.Sell._Lots)?bid:ask)-((_Get.Pos.Buy._Profit+_Get.Pos.Sell._Profit)/(TickValue*(_Get.Pos.Buy._Lots-_Get.Pos.Sell._Lots))*poi);

 

HLineCreate, HLineMove, HLineDelete взяты из справки - создание горизонтальной линии: OBJ_HLINE.

Советник (для примера) работает только с одним типом позиций - который задаётся во входных параметрах.

 
Vitaly Muzichenko:

Я считаю так, тогда учитываются все свопы и комиссии.


А что это за точки в именах переменных? (_Get.Pos.Buy._Lots) - это запрещённые имена. Так нельзя именовать переменные.

Причина обращения: