//+------------------------------------------------------------------+
//|                                            Уровень безубытка.mq4 |
//+------------------------------------------------------------------+
#property copyright "Nikolai Shalashov"
#property link      "http://forexii.blogspot.com/"
#property indicator_chart_window
extern bool OneWayTicket = true; //true - расчитывать уровень безубытка отдельно для buy и sell
                                  //false- расчитывать уровень безубытка с учётом всех открытых позиций
extern double Profit=0.0;         //Сумма стредств в валюте депозита, которую нужно получить после закрытия позиций
extern int MagicNumber = 0;       //Фильтр по идентификатору советников
extern color ColorBuy = DarkBlue;
extern color ColorSell = FireBrick;
string NameBuy = "LineBuy";
string NameSell = "LineSell";

//double LotsBuy, LotsSell;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void init() {
   return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void deinit() {
   if (ObjectFind(NameBuy)!=-1)  ObjectDelete(NameBuy);
   if (ObjectFind(NameSell)!=-1) ObjectDelete(NameSell);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
void start() {
   int    counted_bars=IndicatorCounted();
   double PB = ProfitPrice(Symbol(), OP_BUY,  MagicNumber, Profit);
   double PS = ProfitPrice(Symbol(), OP_SELL, MagicNumber, Profit);
   if(OneWayTicket){
      SetPriceLine(PB, NameBuy,  ColorBuy);
      SetPriceLine(PS, NameSell, ColorSell);
   }else{
      ProfitPrice2(Symbol(), MagicNumber, Profit);
   }
   
} //start()
//+------------------------------------------------------------------+
double ProfitPrice(string fSymbol, int fType, int fMagic=0, double MyProfit=0.0){
   //Функция возвращает цену, на которую необходимо установить уровень TakeProfit, чтобы получить прибыль MyProfit
   double SummPrice=0.0, SummLots=0.0, Formula=0.0, SummLoss=0.0;
   int k;
   int total = OrdersTotal();
   for (int i = total-1; i >= 0; i--) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()==fSymbol) {
         if(OrderMagicNumber()==fMagic || fMagic==0) {
            if(OrderType()==fType) {
               k++;
               SummLots=SummLots+OrderLots();
               SummPrice=SummPrice+OrderOpenPrice()*OrderLots();
               SummLoss=SummLoss+OrderCommission()+OrderSwap();
            }
         }
      }
   }//Next i  
   
   if(k>0){
      if(fType==OP_BUY){
         Formula = SummPrice/SummLots + 
         (MyProfit-SummLoss) * MarketInfo(fSymbol, MODE_POINT) / 
         (MarketInfo(fSymbol, MODE_TICKVALUE) * SummLots);
      } else {
         Formula = SummPrice/SummLots - 
         (MyProfit-SummLoss) * MarketInfo(fSymbol, MODE_POINT) / 
         (MarketInfo(fSymbol, MODE_TICKVALUE) * SummLots);
      }
   }
   
   return(Formula);
}//ProfitPrice()
//+------------------------------------------------------------------+
void ProfitPrice2(string fSymbol, int fMagic=0, double MyProfit=0.0){
   double BuyLots=0.0, SellLots=0.0, BuyProfit=0.0, SellProfit=0.0, BuyPrice=0.0, SellPrice=0.0;
   int total = OrdersTotal();
   for (int i = total-1; i >= 0; i--) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()==fSymbol) {
         if(OrderMagicNumber()==fMagic || fMagic==0) {
            if(OrderType()==OP_BUY){
               BuyLots = BuyLots + OrderLots();
               BuyProfit = BuyProfit + OrderProfit() + OrderCommission() + OrderSwap();
            }else if(OrderType()==OP_SELL){
               SellLots = SellLots + OrderLots();
               SellProfit = SellProfit + OrderProfit() + OrderCommission() + OrderSwap();
            }
         }
      }
   }//Next i  
   double TickValue = MarketInfo(fSymbol, MODE_TICKVALUE);
   if ((BuyLots - SellLots) > 0) {
      BuyPrice = Bid - ((BuyProfit + SellProfit - MyProfit) / (TickValue * (BuyLots - SellLots)) * Point);
   }
   if ((SellLots - BuyLots) > 0) {
      SellPrice = Ask + ((BuyProfit + SellProfit - MyProfit) / (TickValue * (SellLots - BuyLots)) * Point);
   }
   if((BuyLots - SellLots) == 0.0){
      if(BuyLots>0) BuyPrice = Bid - ((BuyProfit + SellProfit - MyProfit) / (TickValue * BuyLots) * Point); //уровень безубытка для всех BUY ордеров
      if(SellLots>0) SellPrice = Ask + ((SellProfit + BuyProfit - MyProfit) / (TickValue * SellLots) * Point); //уровень безубытка для всех SELL ордеров
   }
   SetPriceLine(BuyPrice, NameBuy, ColorBuy);
   SetPriceLine(SellPrice, NameSell, ColorSell);   
}//ProfitPrice2()
//+------------------------------------------------------------------+
void SetPriceLine(double Price=0.0, string NameLine = "MyLine", color ColorLine = DarkOliveGreen){
   int indWnd=0;
   //hWnd = WindowFind(window);
   if (ObjectFind(NameLine)==-1) ObjectCreate(NameLine, OBJ_HLINE, indWnd, 0, Price);
   if(Price==0.0){
      ObjectDelete(NameLine);
   }else{
      ObjectSet(NameLine, OBJPROP_PRICE1, Price);
      ObjectSet(NameLine, OBJPROP_COLOR, ColorLine);
   }
}//SetPriceLine()
//+------------------------------------------------------------------+


