//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#property link "http://forexbig.ru"
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//+------------------------------------------------------------------+
//|                                                  MultiCharts.mq4 |
//|                                           Copyright © 2009, Koss |
//|                                                  kosmic@inbox.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, Koss"
#property link      "kosmic@inbox.ru"

#property indicator_separate_window
#property indicator_buffers 8
#property indicator_minimum -15
#property indicator_maximum 115

#import "user32.dll"
   int GetWindowDC(int dc);
   int ReleaseDC(int h, int dc);
  bool GetWindowRect(int h, int& pos[4]);
   /*int GetParent(int h);
   int GetTopWindow(int h);*/
#import
#import "gdi32.dll"
   int GetPixel(int dc, int x, int y);
#import



extern color  BearCandleColor    = Lime;
extern color  BullCandleColor    = White;
extern color  TextColor          = Gold;
extern color  ProfitColor        = ForestGreen;
extern color  LossColor          = Red;
extern color  TakeProfitColor    = LimeGreen;
extern color  StopLossColor      = IndianRed;
extern color  FastMA_Color       = Gold;
extern color  SlowMA_Color       = OrangeRed;
extern int    FastMA_Period      = 21;
extern int    SlowMA_Period      = 38;
extern int    MA_Metod           = 0;
extern int    Applied_Price      = 0;
extern bool   UseMovingAverages  =false;
extern bool   UseHeikenAshiChart =false;
extern bool   ViewOHLC           =true;
extern bool   FifthDigit         =true;
extern bool   ViewOrders         =true;
extern int    ProfitCalcMode     = 0;                               // способ расчета прибыли 0-в пунктах, 1-в валюте депозита    
extern int    Charts             =5;
extern string Chart1             ="EURUSD";
extern string Chart2             ="GBPUSD";
extern string Chart3             ="AUDUSD";
extern string Chart4             ="USDCAD";
extern string Chart5             ="USDCHF";

//+------------------------------------------------------------------+
//| константы                                                        |
//+------------------------------------------------------------------+
#define TotalCharts                                        5

//---- buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];
double ExtMapBuffer5[];
double ExtMapBuffer6[];
double SlowMABuffer[];
double FastMABuffer[];


//----
int    CandelsCountOnWindow=0,
       Frame,
       hWnd,
       Win_Charts,
       CandleWidth,
       HistoWidth,
       MAWidth=1,
       TimeFrame,
       MA,
       Ap_Price,
       idWnd;

       
color  Win_color;
color  clNames[TotalCharts];                            // Массив цвета
double ChartValues[6][4];                               // Массив для хранения min,max,(max-min)/100;
double TotalOrders[6][31][8];                           // масив для учета ордеров по каждому инструменту
   int TotalBars[TotalCharts];                          // Массив хранит количество баров подкаченной истории 
datetime FrameThresolds[6][3];                          // Массив для хранения границ ячейки (дата/время)
     
static datetime ТicTime[TotalCharts],
                ZeroBarTime[TotalCharts];
int    Hystory[TotalCharts];
string Win_Name,
       ChartNames[TotalCharts];
string Periods[9][2]    ={  "1", ",M1",
                            "5", ",M5",
                           "15", ",M15",
                           "30", ",M30",
                           "60", ",H1",
                          "240", ",H4",
                         "1440", ",Daily",
                        "10080", ",Weekly",
                        "43200", ",Monthly"}; 
int    Accounts[]   ={0,0,0};                           // Массив для хранения номеров счетов                              
bool   StartTerminal=true;
bool   Work=true;
bool   ViewCandleCodes=false;
double open,close,high,low,min,max,point,price,haopen, hahigh, halow, haclose,FastMA,SlowMA;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
   TimeFrame=Period();
   Win_Name             = "TFS";
   IndicatorShortName(Win_Name);
   idWnd=WindowFind(Win_Name);
   DeleteAllObjects(OBJ_TEXT); 
   DeleteAllObjects(OBJ_LABEL); 
   DeleteAllObjects(OBJ_TREND);
         Win_color   = GetWndColor(Symbol()); 
         CandleWidth = GetCandleWidth(Symbol());
          
         if (Charts<1 || Charts>5)                Win_Charts=5;
           else Win_Charts  = Charts; 
          
         if (MA_Metod<0 || MA_Metod>3)            MA=0;
           else MA=MA_Metod;
           
         if (Applied_Price<0 || Applied_Price>6)  Ap_Price=0;
           else Ap_Price=Applied_Price;
           
        
   if (!IsDllsAllowed())
   {
    Alert("Для нормальной работы индикатора необходимо разрешить импорт из DLL");
    return(0);
   }
   else
   { 
     if (WindowBarsPerChart()!=0)
        {
         ChartsInit();
         CandelsCountOnWindow=WindowBarsPerChart();
         Frame = MathRound((CandelsCountOnWindow-3)/Win_Charts);
         switch(CandleWidth)
            {
             case 1:  HistoWidth=0;
                      MAWidth=1;    break;
             case 2:  HistoWidth=0;
                      MAWidth=1;    break;
             case 4:  HistoWidth=2;
                      MAWidth=1;    break;
             case 8:  HistoWidth=3; 
                      MAWidth=2;    break;
             case 16: HistoWidth=7; 
                      MAWidth=2;    break;
             case 32: HistoWidth=13;
                      MAWidth=3;    break;
            }
        IndicatorSets(false); 
         
        } 
        
    return(0);
   }
   
  }
  
   
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   if(IsConnected() && WindowBarsPerChart()!=0 && Bars!=0 && AccountNumber()!=0 && Work) 
      {
       if  (StartTerminal)
        {
         if (SearchAccount(AccountNumber()))
           {
            int counted_bars=IndicatorCounted();
            if(counted_bars<=0)
             { 
              Print("Обновление....");
              return(0);
             } 
             else 
             {
              StartTerminal=false;
             } 
           }
           else 
           {
            Work=false;
            Print("Неверный счет!");
            return(0);
           } 
          
        } 
        else 
        {
         if (!WndRepaint())
          {
           SymbolТic();
          }
        }
        
       }  
       else
       {
        if (Work)
         {
          CleanHisto();
          init();
         } 
       } 
       return(0);     
       
  }  
  
int deinit()
   {
    if (UninitializeReason()==REASON_CHARTCHANGE)
     {
      Print("Смена периода");
     }
   } 
   
//+------------------------------------------------------------------+
//|Поиск № счета, если счет найден то продолжаем работу              |
//+------------------------------------------------------------------+
   
bool SearchAccount(int Number)
   {
    bool result=false;
    if (Number!=0)
     {
      /*for (int i=0;i<=2;i++)
       {
        if (Accounts[i]==Number)
         {
          result=true;
          break;
         } 
       }*/
       result=true; 
     }
     return(result);
   }
   
//+------------------------------------------------------------------+
//|возвращает цвет фона окна текущего грфика                         |
//+------------------------------------------------------------------+
  
int GetWndColor(string sy)
   { 
     int hWnd = WindowHandle(sy, Period());
     int hDC = GetWindowDC(hWnd);
     int rect[4];
     GetWindowRect(hWnd, rect);
     int wW = rect[2] - rect[0];         // ширина окна
     int wH = rect[3] - rect[1];         // высота окна
     
     int col = GetPixel(hDC, 2, 2);
     if(col==-1)                         // левый верхний угол не виден
     {
       col = GetPixel(hDC, wW-3, wH-3); 
       if(col==-1)                       // правый нижний угол не виден
       col = GetPixel(hDC, 2, wH-3); 
       if(col==-1)                       // левый нижний угол не виден
       col = GetPixel(hDC, wW-3, 2);     
       if(col==-1)                       // правый верхний угол не виден
       {
         ReleaseDC(hWnd, hDC);
         return(Win_color);
       }
      }
     ReleaseDC(hWnd, hDC);
     return(col);
   }
   

void ChartsInit()
   {
    LoadChartsNames();
    InitArrays();
   } 
 
void LoadChartsNames()
   {
    ChartNames[0]=Chart1;
    ChartNames[1]=Chart2;
    ChartNames[2]=Chart3;
    ChartNames[3]=Chart4;
    ChartNames[4]=Chart5;
   }
   
void InitArrays()
   {
    ArrayInitialize(Hystory,0);
    ArrayInitialize(TotalBars,0);
    ArrayInitialize(TotalOrders,0);
    ArrayInitialize(FrameThresolds,0);
    for(int i=0;i<=Win_Charts-1;i++)
      {
       ZeroBarTime[i]=0;
       ТicTime[i]=0;
       clNames[i]=BullCandleColor;
       continue;
      }
   }    
   
void LoadChartsValues()
   {
    DeleteAllObjects(OBJ_TREND);
    for(int i=0;i<=Win_Charts-1;i++) 
     {
      UpgradeCharts(i);
      continue;
     }
    
   }

void UpgradeCharts(int ChartListPosition)
   { 
     int j;
     double min,max;
     string Symb=ChartNames[ChartListPosition];
     if (Hystory[ChartListPosition]==1)
      {
       max=iHigh(Symb,0,0);
       min=iLow(Symb,0,0);
       for (j=0;j<=Frame-4;j++)
         {
          if (iHigh(Symb,0,j)>max) 
           {
            max=iHigh(Symb,0,j);
           }
          if (iLow(Symb,0,j)<min) 
           {
            min=iLow(Symb,0,j);
           }
         }
       ChartValues[ChartListPosition+1,1]=((max-min)/100);
       ChartValues[ChartListPosition+1,2]= max;
       ChartValues[ChartListPosition+1,3]= min;
       CleanFrame(ChartListPosition+1);
       DrawChart(ChartListPosition);
       if (ViewOHLC) OHLC(ChartListPosition);
       MonitoringOpenPositions(ChartListPosition);
      } 
      else
      {
       ChartValues[ChartListPosition+1,1]=0;
       ChartValues[ChartListPosition+1,2]=0;
       ChartValues[ChartListPosition+1,3]=0;
       CleanFrame(ChartListPosition+1);
       ChartName(ChartListPosition,clNames[ChartListPosition]," ");
      }
       DrawSeparateLines(ChartListPosition);
       ChartValues[0,0]=ChartListPosition+1;
       CellThresolds(ChartListPosition);
      
   }
      
//+------------------------------------------------------------------+
//|Обновление данных                                                 |
//+------------------------------------------------------------------+
   
int RefreshRate(int ChartListPosition)
   {
     string   Symb;
     Symb=ChartNames[ChartListPosition];
     return(CopyRates(Symb,ChartListPosition));
   }
   
int CopyRates(string Symb, int ChartListPosition )
   {
    datetime times[];
    int error,CountedBars=0;
   CountedBars=ArrayCopySeries(times,MODE_TIME,Symb,0);
    error=GetLastError();
    if(error==4066)
     {
      Print(Symb+",Запрошенные данные в процессе обновления!");
      return(0);
     }
    if((iTime(Symb,0,0)==times[0] && iTime(Symb,0,0)==Time[0])&& 
       (iTime(Symb,0,1)==times[1] && iTime(Symb,0,1)==Time[1])&& 
       (iTime(Symb,0,2)==times[2] && iTime(Symb,0,2)==Time[2]) )
       {
       if (!UseHeikenAshiChart)
         {
           ZeroBarTime[ChartListPosition]=iTime(Symb,0,0);
           TotalBars[ChartListPosition]=CountedBars; 
         
         }  
           return(1);
       }
       else
       {
        Print(Symb+",Отсутствие исторических данных");
        return(0); 
       }
  
   }   
//+------------------------------------------------------------------+
//|отрисовка названий инструментов и прочих надписей                 |
//+------------------------------------------------------------------+

void ChartName(int ChartListPosition,color clPosition,string txPosition)
   {
   
    int k=MathRound(Frame/2);
   
      if (ChartListPosition==0)
       {
        DrawChartsName(ChartListPosition,k,clPosition,txPosition);
       }
        else
       {
        DrawChartsName(ChartListPosition,k+ChartListPosition*Frame,clPosition,txPosition);
       }
    }
    
void DrawChartsName(int ChartListPosition,int Bar,color clPosition,string txPosition)
   {
    
    string TF,name,Symb=ChartNames[ChartListPosition];                     
    
    for(int p=0; p<9; p++)
       {
        if(Periods[p][0]==DoubleToStr(TimeFrame,0)) TF=Periods[p][1];
       }
    
    name="Chart"+Symb; 
   
    if (!UseHeikenAshiChart)
         {
          CleanText(name);
          CleanText("Update "+name);
          CreateTextObject(name, Time[Bar],113,Symb+TF+txPosition,clPosition,Bar,"tahoma",7); 
          if (Hystory[ChartListPosition]==0 || !IsConnected())
           {
            CreateTextObject("Update "+name, Time[Bar],55,"ОЖИДАНИЕ ОБНОВЛЕНИЯ...",BullCandleColor,Bar,"tahoma",7); 
           }
         }
         else
         {
          CleanText(name);
          CleanText("Update "+name);
          CreateTextObject(name, Time[Bar],113,Symb+TF+" (HA)"+txPosition,clPosition,Bar,"tahoma",7); 
           if (Hystory[ChartListPosition]==0 || !IsConnected())
           {
            CreateTextObject("Update "+name, Time[Bar],55,"ОЖИДАНИЕ ОБНОВЛЕНИЯ...",BullCandleColor,Bar,"tahoma",7); 
           } 
         } 
   }   


void OHLC(int ChartListPosition)
   {

    int k=MathRound(Frame/2),p=Frame-(Frame-5);
   
      if (ChartListPosition==0)
       {
        DrawOHLC(ChartListPosition,k);
        DrawMaxMinValues(ChartListPosition,p);
       }
        else
       {
        DrawOHLC(ChartListPosition,k+ChartListPosition*Frame);
        DrawMaxMinValues(ChartListPosition,p+ChartListPosition*Frame);
       }
      InfoPosition(ChartListPosition);
   }
   
void DrawOHLC(int ChartListPosition,int Bar)
   { 
    double dig,high,open,low,close,Zlow,Zhigh;
       string Symb=ChartNames[ChartListPosition],ohlc,name,codes,cc;
       name="OHLC "+Symb;
       RefreshRates();
       dig=MarketInfo(Symb,MODE_DIGITS);
    
       if (!UseHeikenAshiChart)
         {
          high=NormalizeDouble(Hi(Symb,0,0),dig);
          open=NormalizeDouble(Op(Symb,0,0),dig);
          close=NormalizeDouble(Cl(Symb,0,0),dig);
          low=NormalizeDouble(Lo(Symb,0,0),dig);
          ohlc=DoubleToStr(open,dig)+"  "+DoubleToStr(high,dig)+"  "+DoubleToStr(low,dig)+"  "+DoubleToStr(close,dig);
          /*ohlc=TimeToStr(FrameThresolds[ChartListPosition+1][1],TIME_DATE|TIME_MINUTES)+" "+TimeToStr(FrameThresolds[ChartListPosition+1][2],TIME_DATE|TIME_MINUTES);*/
          CleanText(name);
          CreateTextObject(name, Time[Bar],-7,ohlc,clNames[ChartListPosition],Bar,"tahoma",8); 
         }
         else
         {
          high=NormalizeDouble(Hi(Symb,0,0),dig);
          low=NormalizeDouble(Lo(Symb,0,0),dig);
          open=iCustom(Symb,0,"Heiken Ashi",2,0);
          close=iCustom(Symb,0,"Heiken Ashi",3,0);
          Zhigh=MathMax(high, MathMax(open, close));
          Zlow=MathMin(low, MathMin(open, close));
          ohlc=DoubleToStr(open,dig)+"  "+DoubleToStr(Zhigh,dig)+"  "+DoubleToStr(Zlow,dig)+"  "+DoubleToStr(close,dig);
          CleanText(name);
          CreateTextObject(name, Time[Bar],-7,ohlc,clNames[ChartListPosition],Bar,"tahoma",8); 
         }  
   } 
   

void InfoPosition(int ChartListPosition)
   {
     int pos=Frame-3;
      if (ChartListPosition==0)
       {
         DrawInfoPosition(ChartListPosition,pos);   
       }
        else
       {
         DrawInfoPosition(ChartListPosition,pos+ChartListPosition*Frame); 
       }
   }
     
void DrawInfoPosition(int ChartListPosition,int Bar)     
   {
    string name,text,Symb=ChartNames[ChartListPosition];
     name=" Spread "+Symb;
     double percent=GetPercent(ChartListPosition);
     if (FifthDigit)
      {
       text=DoubleToStr(MarketInfo(Symb,MODE_SPREAD),0);
      }
      else
      {
       text=DoubleToStr(MarketInfo(Symb,MODE_SPREAD)/10,1);
      } 
     CleanText(name);
     CreateTextObject(name, Time[Bar],106,text,TextColor,Bar,"tahoma",7);

     name=" Percent "+Symb;
     CleanText(name);
     text=DoubleToStr(percent,2)+"%"; 
     if (percent>0)
      {     
       CreateTextObject(name, Time[Bar-2],-1,text,ProfitColor,Bar,"tahoma",7);
      } 
      else
      {
       if (percent<0)
        {
          CreateTextObject(name, Time[Bar-2],-1,text,LossColor,Bar,"tahoma",7);
        }
       if (percent==0) 
        {
          CreateTextObject(name, Time[Bar-2],-1,text,TextColor,Bar,"tahoma",7);
        }
      }
   }
   

      
void DrawMaxMinValues(int ChartListPosition,int Bar)
   {
    string name,name1,Value,Symb=ChartNames[ChartListPosition];
     name="Max "+Symb;
     name1="Min "+Symb;
     
     Value=DoubleToStr(ChartValues[ChartListPosition+1,2],MarketInfo(Symb,MODE_DIGITS));
     CleanText(name);
     CreateTextObject(name, Time[Bar],106,Value,TextColor,Bar,"tahoma",7);
     
     Value=DoubleToStr(ChartValues[ChartListPosition+1,3],MarketInfo(Symb,MODE_DIGITS));
     CleanText(name1); 
     CreateTextObject(name1, Time[Bar],-1,Value,TextColor,Bar,"tahoma",7);
   } 

void CleanText(string objName)
   {
    ObjectDelete(objName);
   }
 
//+------------------------------------------------------------------+
//|удаление графика определенного инструмента                        |
//+------------------------------------------------------------------+
   
void CleanFrame(int ChartListPosition)
   {
    int i;
    if (ChartListPosition==1)
     {
       if (ChartListPosition!=Win_Charts)
        {
         for(i=0;i<=Frame;i++)
           {
            CleanBuffers(i);
           }
         }  
        else
        {
         for(i=0;i<=Bars;i++)
           {
            CleanBuffers(i);
           }
        } 
       
     }
     else
     {
      if (ChartListPosition!=Win_Charts)
        {
         for(i=ChartListPosition*Frame;i>=(ChartListPosition-1)*Frame;i--)
         {
          CleanBuffers(i);
         } 
        }
        else
        {
         for(i=(ChartListPosition-1)*Frame;i<=Bars;i++)
         {
          CleanBuffers(i);
         } 
        } 
     }
    
   }  
   
//+------------------------------------------------------------------+
//|функция слежения за изменениями  окна текущего графика            |
//+------------------------------------------------------------------+
      
bool WndRepaint()
   {
     if ( Win_color   != GetWndColor(Symbol())    || 
          CandleWidth != GetCandleWidth(Symbol()) || 
          CandelsCountOnWindow!=WindowBarsPerChart() )
       { 
         CleanHisto();
         CandelsCountOnWindow=WindowBarsPerChart();
         Frame = MathRound((CandelsCountOnWindow-3)/Win_Charts); 
         Win_color   = GetWndColor(Symbol());
         CandleWidth=GetCandleWidth(Symbol());
         switch(CandleWidth)
            {
             case 1:  HistoWidth=0;
                      MAWidth=1;    break;
             case 2:  HistoWidth=0;
                      MAWidth=1;    break;
             case 4:  HistoWidth=2;
                      MAWidth=1;    break;
             case 8:  HistoWidth=3; 
                      MAWidth=2;    break;
             case 16: HistoWidth=7; 
                      MAWidth=2;    break;
             case 32: HistoWidth=13;
                      MAWidth=3;    break;
            }
    
         IndicatorSets(true);
         return(true);
        }
        
      return(false);  
   }    
   
//+------------------------------------------------------------------+
//|установки индикатора                                              |
//+------------------------------------------------------------------+
   
void IndicatorSets(bool Repaint)
   {
        
         /*ArrayInitialize(ChartValues,0.0); */       
         SetIndexStyle(0,DRAW_HISTOGRAM, 0, HistoWidth, BearCandleColor);
         SetIndexBuffer(0, ExtMapBuffer1);
         SetIndexDrawBegin(0,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(0,"");
          
         SetIndexStyle(1,DRAW_HISTOGRAM, 0, HistoWidth, BullCandleColor);
         SetIndexBuffer(1, ExtMapBuffer2);
         SetIndexDrawBegin(1,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(1,"");
         
         SetIndexStyle(2,DRAW_HISTOGRAM, 0, HistoWidth, Win_color);
         SetIndexBuffer(2, ExtMapBuffer3);
         SetIndexDrawBegin(2,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(2,"");
         
         SetIndexStyle(3,DRAW_HISTOGRAM, 0, 1, BearCandleColor);
         SetIndexBuffer(3, ExtMapBuffer4);
         SetIndexDrawBegin(3,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(3,"");
         
         SetIndexStyle(4,DRAW_HISTOGRAM, 0, 1, BullCandleColor);
         SetIndexBuffer(4, ExtMapBuffer5);
         SetIndexDrawBegin(4,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(4,"");
         
         SetIndexStyle(5,DRAW_HISTOGRAM, 0, 1, Win_color);
         SetIndexBuffer(5, ExtMapBuffer6);
         SetIndexDrawBegin(5,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(5,"");
         
         SetIndexStyle(6,DRAW_LINE, 0, MAWidth, SlowMA_Color);
         SetIndexBuffer(6, SlowMABuffer);
         SetIndexDrawBegin(6,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(6,"");
          
         SetIndexStyle(7,DRAW_LINE,0,MAWidth,FastMA_Color);
         SetIndexBuffer(7, FastMABuffer);
         SetIndexDrawBegin(7,Bars-CandelsCountOnWindow-4);
         SetIndexLabel(7,"");
         
        if (Repaint)
         {
          LoadChartsValues();
         }
   }
 

          
//+------------------------------------------------------------------+
//|Возвращает ширину бара                                            |
//+------------------------------------------------------------------+
          
int GetCandleWidth(string sy)
{
 
  int rect[4];
  int h=WindowHandle(sy, Period());
  if(h==0) return(-1);
  GetWindowRect(h, rect);
  int wW  = rect[2] - rect[0]; // ширина окна
  int bpc = CandelsCountOnWindow;
  if(bpc==0) return(-1);
  return(MathFloor((wW-48)/bpc));
}  
 
/*bool isActive(string sy)
{
   int hCurrWindow = WindowHandle(sy,0);                      //хедл текущего окна графика
   int hNextParent = GetParent(hCurrWindow);
       hNextParent = GetParent(hNextParent);                  //хендп родительского окно для всех графиков
   int hNextActiveWindow = GetTopWindow(hNextParent);
       hNextActiveWindow = GetTopWindow(hNextActiveWindow);   //хедл текущего окна графика
   if (hCurrWindow==hNextActiveWindow) return(true);
   else return(false); 
} */

   
double Op(string Symb,int period,int Bar)
   {
    return(iOpen(Symb,period,Bar));
   }     
 
double Cl(string Symb,int period,int Bar)
   {
    return(iClose(Symb,period,Bar));
   } 
   
double Hi(string Symb,int period,int Bar)
   {
    return(iHigh(Symb,period,Bar));
   }   
   
double Lo(string Symb,int period,int Bar) 
   {
    return(iLow(Symb,period,Bar));
   } 
    
//+------------------------------------------------------------------+
//|функция очистки индикаторных массивов                             |
//+------------------------------------------------------------------+
   
void CleanBuffers(int i)
   {
    
      ExtMapBuffer1[i]=EMPTY_VALUE;
      ExtMapBuffer2[i]=EMPTY_VALUE;
      ExtMapBuffer3[i]=EMPTY_VALUE;
      ExtMapBuffer4[i]=EMPTY_VALUE;
      ExtMapBuffer5[i]=EMPTY_VALUE;
      ExtMapBuffer6[i]=EMPTY_VALUE;
      SlowMABuffer[i]=EMPTY_VALUE;
      FastMABuffer[i]=EMPTY_VALUE;
   
   }
   
//+------------------------------------------------------------------+
//|прорисовка инструмента(всех баров)                                |
//+------------------------------------------------------------------+

void DrawChart(int ChartListPosition)
   {
     int j;
     for(j=Frame-4;j>=0;j--)
       { 
         SetValues(j,ChartListPosition);
       }
       
   }
   
//+------------------------------------------------------------------+
//|прорисовка инструмента(нулевого бара)                             |
//+------------------------------------------------------------------+ 

void DrawZeroBar(int ChartListPosition)   
   {
    double Zmin,Zmax,LastPrice; 
    string Symb=ChartNames[ChartListPosition];
       LastPrice=MarketInfo(Symb,MODE_BID);
       Zmin=ChartValues[ChartListPosition+1][3];
       Zmax=ChartValues[ChartListPosition+1][2];
             
       if (LastPrice<Zmin || LastPrice>Zmax)
        {
         UpgradeCharts(ChartListPosition);
        }
     
       SetValues(0,ChartListPosition);  
   }
   
void SetValues(int Bar,int ChartListPosition)
   {

    string Symb=ChartNames[ChartListPosition];

    min=ChartValues[ChartListPosition+1][3];
    point=ChartValues[ChartListPosition+1][1];
    if (!UseHeikenAshiChart)
        { 
         open = (Op(Symb,0,Bar)-min)/point;
         close= (Cl(Symb,0,Bar)-min)/point;
         high = (Hi(Symb,0,Bar)-min)/point;
         low  = (Lo(Symb,0,Bar)-min)/point;
         if (UseMovingAverages)
          {
            FastMA=(iMA(Symb,0,FastMA_Period,0,MA,Ap_Price,Bar)-min)/point;
            if (FastMA<0 || FastMA>100)
             {
              FastMA=EMPTY_VALUE;
             } 
          
            SlowMA=(iMA(Symb,0,SlowMA_Period,0,MA,Ap_Price,Bar)-min)/point;
            if (SlowMA<0 || SlowMA>100)
             {
              SlowMA=EMPTY_VALUE;
             }
          }
          else
          {
           FastMA=EMPTY_VALUE;
           SlowMA=EMPTY_VALUE;
          } 
          
         if (ChartListPosition==0)
          {
           DrawHisto(open,high,low,close,FastMA,SlowMA,Bar+2);
          }
          else
          {
           DrawHisto(open,high,low,close,FastMA,SlowMA,Bar+ChartListPosition*Frame+2); 
          }
        } 
        else
        { 
          high = (Hi(Symb,0,Bar)-min)/point;
          low  = (Lo(Symb,0,Bar)-min)/point;
          haopen=(iCustom(Symb,0,"Heiken Ashi",2,Bar)-min)/point;
          haclose=(iCustom(Symb,0,"Heiken Ashi",3,Bar)-min)/point;
          hahigh=MathMax(high, MathMax(haopen, haclose));
          halow=MathMin(low, MathMin(haopen, haclose));
          /*HaClose[ChartListPosition*Frame+Bar]=haclose;*/
          if (!UseMovingAverages)
           {
            FastMA=EMPTY_VALUE;
            SlowMA=EMPTY_VALUE;
           }
           else
           {
            FastMA=EMPTY_VALUE;
            SlowMA=EMPTY_VALUE; 
           } 
          
          if (ChartListPosition==0)
          {
           DrawHisto(haopen,hahigh,halow,haclose,FastMA,SlowMA,Bar+2);
          }
          else
          {
           DrawHisto(haopen,hahigh,halow,haclose,FastMA,SlowMA,Bar+ChartListPosition*Frame+2); 
          }
        } 
                 
   }  
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void CellThresolds(int ChartListPosition)
   {
    FrameThresolds[ChartListPosition+1][1]=iTime(NULL,0,(ChartListPosition+1)*Frame-2);
    FrameThresolds[ChartListPosition+1][2]=iTime(NULL,0,(ChartListPosition+1)*Frame-2-(Frame-4));
   }    
//+------------------------------------------------------------------+
//| Удаление всех чартов                                             |
//+------------------------------------------------------------------+
   
void CleanHisto()
   {
    if (Bars!=0)
    {
    for(int i=0;i<=Bars-1;i++)
      {
       CleanBuffers(i);
       continue;
      }
    }  
   }
   
//+------------------------------------------------------------------+
//|прорисовка разделительных линий                                   |
//+------------------------------------------------------------------+
   
void DrawSeparateLines(int ChartListPosition)
   { 
    int value;
       value=ChartListPosition*Frame;
       ExtMapBuffer5[value]=106;
       value+=Frame;
       ExtMapBuffer5[value]=106;
   }  
       
//+------------------------------------------------------------------+
//|заполнение индикаторных массивов                                  |
//+------------------------------------------------------------------+

void DrawHisto(double O,double H,double L,double C,double ma,double ma1,int Bar)
   {
           
            if (O > C) 
             {
              ExtMapBuffer1[Bar]=O;
              ExtMapBuffer2[Bar]=EMPTY_VALUE; 
              ExtMapBuffer3[Bar]=C;
              ExtMapBuffer4[Bar]=H;
              ExtMapBuffer5[Bar]=EMPTY_VALUE;
              
             }
          
            if (O < C) 
             {
              ExtMapBuffer1[Bar]=EMPTY_VALUE;
              ExtMapBuffer2[Bar]=C; 
              ExtMapBuffer3[Bar]=O;
              ExtMapBuffer4[Bar]=EMPTY_VALUE;
              ExtMapBuffer5[Bar]=H;
              
             
             } 
          
            if (O == C) 
             {
              ExtMapBuffer1[Bar]=O;
              ExtMapBuffer2[Bar]=EMPTY_VALUE; 
              ExtMapBuffer3[Bar]=O; 
              ExtMapBuffer4[Bar]=EMPTY_VALUE;
              ExtMapBuffer5[Bar]=H;
              
           
             }   
             ExtMapBuffer6[Bar]=L;
             FastMABuffer[Bar]=ma;
             SlowMABuffer[Bar]=ma1; 
   } 
//+------------------------------------------------------------------+
//|Создает объект-трендовая линия                                    |
//+------------------------------------------------------------------+

void CreateTrendLine(string obj,int position,int position1,double price,color cl,int idWnd)
   {
    ObjectCreate(obj,OBJ_TREND,idWnd,Time[position],price,Time[position1],price);
    ObjectSet(obj,OBJPROP_COLOR,cl);
    ObjectSet(obj,OBJPROP_STYLE,STYLE_DOT);
    ObjectSet(obj,OBJPROP_RAY,false);
   }        
//+------------------------------------------------------------------+
//| Создает объект-текст                                             |
//+------------------------------------------------------------------+
     
void CreateTextObject(string obj, double x, double y,string Text,color cl,int Bar,string FontName,int FontSize) 
  {
   int ChartWindow;
   ChartWindow=WindowFind(Win_Name);
   ObjectCreate(obj, OBJ_TEXT, ChartWindow, x, y);
   ObjectSetText(obj,Text,FontSize, FontName, cl);
  }
        
//+------------------------------------------------------------------+
//|Поиск объекта в окне индикатора                                   |
//+------------------------------------------------------------------+
    
bool FindObject(string Object, int idWnd)
   {
     if (ObjectFind(Object)==idWnd) return(true);
      else return(false);
   }  
   
void DeleteAllObjects(int Type)
   {
    if (idWnd!=-1) ObjectsDeleteAll(idWnd,Type);
   } 

//+-------------------------------------------------------------------+
//|возвращает признак появления нового бара для выбраного инструмента |
//+-------------------------------------------------------------------+
   
bool  isNewBar(int ChartsListPosition)   
  {
     bool res=false; 
     RefreshRates();   
     string  Symb=ChartNames[ChartsListPosition];
     datetime BT=iTime(Symb,0,0);
     
   if ( ZeroBarTime[ChartsListPosition] !=BT || ZeroBarTime[ChartsListPosition] ==0 )
        {
          ZeroBarTime[ChartsListPosition] = BT;
          res=true;
        } 
    return(res);
  }
   
bool isNewТic(int ChartsListPosition) 
 { 
   bool res=false;  
   RefreshRates();
   string Symb=ChartNames[ChartsListPosition];
   datetime TT = MarketInfo(Symb,MODE_TIME);
    
   if ( ТicTime[ChartsListPosition] != TT )  
     {
       ТicTime[ChartsListPosition] = TT ;
       res=true;
     } 
   return(res);  
 }  

void SymbolТic()  
   {
    for(int i=0; i<=Win_Charts-1; i++)      
      {  
       if (Hystory[i]==0)  
        {
         UpgradeCharts(i);
         Hystory[i]=RefreshRate(i);
        }
        else
        {
         MonitoringOpenPositions(i);
          if (isNewТic(i))                     
             { 
              if (isNewBar(i))
               {
                LoadChartsValues();
                CellThresolds(i);
               }   
               else
               {
                DrawZeroBar(i);
               }                                      
             } 
         } 
        continue; 
      }  
   }
   
//+------------------------------------------------------------------+
//|возвращает процент изменения цены от предыдущего дня              |
//+------------------------------------------------------------------+
double GetPercent( int ChartListPosition)
   {
        string Symb=ChartNames[ChartListPosition];
        double yesterday=iClose(Symb , PERIOD_D1,  1);
        double today=0;
        if (yesterday!= 0 ) 
           today=(iClose(Symb,PERIOD_D1  ,0) * 100 ) / yesterday - 100;
      return (today);
   }
   

 
//+------------------------------------------------------------------+
//| Мониторинг открытых позиций по каждому инструменту               |
//+------------------------------------------------------------------+
   
void MonitoringOpenPositions(int ChartsListPosition)
   {
    int SellCount=0,BuyCount=0;
    double Profit=0;
    string Symb=ChartNames[ChartsListPosition],Result;
    
    if (ExistPositions(Symb,OP_SELL)==-1 && ExistPositions(Symb,OP_BUY)==-1 ) 
     {
        clNames[ChartsListPosition]=BullCandleColor;
        Result=" ";
     }     
     else
     {
          if (ExistPositions(Symb,OP_SELL)==OP_SELL) 
           {
                   SellCount=NumberOfOrders(ChartsListPosition,OP_SELL);
                   Profit=Profit(Symb); 
                   if (SellCount>1)
                    {
                      Result   =StringConcatenate(" [ Sell (",SellCount,"): ",Profit," ]");
                    }  
                    else
                    {
                      Result   =StringConcatenate(" [ Sell: ",Profit," ]");
                    } 
                   clNames[ChartsListPosition]=ColorChartName(ChartsListPosition,Profit,SellCount);
           }
    
          if (ExistPositions(Symb,OP_BUY)==OP_BUY) 
           { 
                   BuyCount =NumberOfOrders(ChartsListPosition,OP_BUY);
                   Profit=Profit(Symb);           
                   if (BuyCount>1)
                    {
                      Result   =StringConcatenate(" [ Buy (",BuyCount,"): ",Profit," ]");
                    }  
                    else
                    {
                      Result   =StringConcatenate(" [ Buy: ",Profit," ]");
                    }
                   clNames[ChartsListPosition]=ColorChartName(ChartsListPosition,Profit,BuyCount);
           }
     }    
         if (ViewOrders)
          {
           if (ExistPositions(Symb,OP_BUYSTOP)==OP_BUYSTOP) 
            { 
             NumberOfOrders(ChartsListPosition,OP_BUYSTOP);
            }
    
           if (ExistPositions(Symb,OP_BUYLIMIT)==OP_BUYLIMIT) 
            { 
             NumberOfOrders(ChartsListPosition,OP_BUYLIMIT);
            }
     
           if (ExistPositions(Symb,OP_SELLSTOP)==OP_SELLSTOP) 
            { 
             NumberOfOrders(ChartsListPosition,OP_SELLSTOP);
            }
    
           if (ExistPositions(Symb,OP_SELLLIMIT)==OP_SELLLIMIT) 
            { 
             NumberOfOrders(ChartsListPosition,OP_SELLLIMIT);
            }  
          }
   
     
        ChartName(ChartsListPosition,clNames[ChartsListPosition],Result);
        if (ViewOHLC) OHLC(ChartsListPosition); 
        DeleteOldTrendLines(ChartsListPosition);
   }
   
int CalcMode()
   {
    if (ProfitCalcMode!=0 && ProfitCalcMode!=1)
     {
      return(0);
     }
     else
     {
      return(ProfitCalcMode);
     }   
    } 
    
double Profit(string Symb)
   {
     if (CalcMode()==0)
                    {
                     return(GetProfitOpenPosInPoint(Symb, -1));
                    }
                    else
                    { 
                     return(GetProfitOpenPosInCurrency(Symb, -1,-1));
                    } 
   }    
   
//+------------------------------------------------------------------+
//|Цветовая индикация открытых позиций                               |
//+------------------------------------------------------------------+
                
color ColorChartName(int ChartsListPosition,double Profit,int OrdersCount)    
   {
    string Symb=ChartNames[ChartsListPosition];
    double StopLevel;
    double point    =MarketInfo(Symb,MODE_POINT);
    double bid      =MarketInfo(Symb,MODE_BID);
    double ask      =MarketInfo(Symb,MODE_ASK);
    int    dig      =MarketInfo(Symb,MODE_DIGITS);
    color  test     =Win_color;
    
    if (FifthDigit)
     {
      StopLevel=100;
     }
     else 
     {
      StopLevel=10;
     }
    for(int j=1;j<=OrdersCount;j++)  
      {
       
         switch(TotalOrders[ChartsListPosition+1][j][6])
          {
           case OP_SELL: 
               if (TotalOrders[ChartsListPosition+1][j][2]!=0 && 
                   ask>=(TotalOrders[ChartsListPosition+1][j][2]-NormalizeDouble(StopLevel*point,dig)))  
                   {
                    test=StopLossColor;
                   } 
                   else
                   {
                   if (TotalOrders[ChartsListPosition+1][j][3]!=0 && 
                       ask<=(TotalOrders[ChartsListPosition+1][j][3]+NormalizeDouble(StopLevel*point,dig)))
                      {
                       test=TakeProfitColor;
                      }
                   }
             break;       
             
           case OP_BUY:     
                if (TotalOrders[ChartsListPosition+1][j][2]!=0 && 
                    bid<=(TotalOrders[ChartsListPosition+1][j][2]+NormalizeDouble(StopLevel*point,dig))) 
                   {
                    test=StopLossColor;
                   } 
                   else 
                   {
                     if (TotalOrders[ChartsListPosition+1][j][3]!=0 && 
                         bid>=(TotalOrders[ChartsListPosition+1][j][3]-NormalizeDouble(StopLevel*point,dig)))
                      {
                       test=TakeProfitColor;
                      }
                   }
            break;            
        }
      }   
        
        if (test==Win_color)
          {
           if (Profit>0)
            {
             test=ProfitColor; 
            }
            else 
            {
             if (Profit==0)
              {
               test=TextColor; 
              }
              else
              {
               test=LossColor; 
              }
            } 
          } 
        return(test);
                          
    }
//+------------------------------------------------------------------+
//|Возвращает флаг существования открытых позиций по инструменту     |
//+------------------------------------------------------------------+

int ExistPositions(string Symb,int op=-1) 
{
  int i, k=OrdersTotal();

  for (i=0; i<k; i++) 
  {
    if (OrderSelect(i, SELECT_BY_POS,MODE_TRADES))
    {
      if (OrderSymbol()==Symb && (OrderType()==op || op<0) ) 
      {
        
         return(OrderType());          
       
      }
    }
  }
  return(-1);
}  

//+----------------------------------------------------------------------------+
//|  Версия   : 28.06.2009                                                     |
//|  Описание : Возвращает количество открытых позиций                         |
//|             Устанавливает линии ордеров                                    |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    op - операция                   (-1   - любой ордер)                    |
//|    ChartListPosition-позиция фин.инструмента в массиве инструментов        |
//+----------------------------------------------------------------------------+
int NumberOfOrders(int ChartListPosition, int op=-1)
 {
  int i, k=OrdersTotal(), ko=0, ot,idWnd,pos,pos1,f,tp,sl;
  string Symb=ChartNames[ChartListPosition],objName,Type;
  int dig=MarketInfo(Symb,MODE_DIGITS);
  double orderprice=0,chartmin=0,chartpoint=0; 
  for (i=1; i<=30; i++)
   {
    TotalOrders[ChartListPosition+1][i][1]=0;
    TotalOrders[ChartListPosition+1][i][2]=0;
    TotalOrders[ChartListPosition+1][i][3]=0;
    TotalOrders[ChartListPosition+1][i][4]=0;
    TotalOrders[ChartListPosition+1][i][5]=0;
    TotalOrders[ChartListPosition+1][i][6]=0;
    TotalOrders[ChartListPosition+1][i][7]=0;
   }
   TotalOrders[ChartListPosition+1][0][0]=ko;
   idWnd=WindowFind(Win_Name);
   f=Frame-1;
   pos=(ChartListPosition+1)*Frame-f;
   pos1=(ChartListPosition+1)*Frame-1;
   chartpoint=ChartValues[ChartListPosition+1][1];
   chartmin=ChartValues[ChartListPosition+1][3]; 
   
  for (i=0; i<k; i++)
   {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
    {
      if ((OrderSymbol()==Symb) && (OrderType()==op))
        {
            ko++;
            TotalOrders[ChartListPosition+1][ko][1]=NormalizeDouble(OrderOpenPrice(),dig);
            TotalOrders[ChartListPosition+1][ko][2]=NormalizeDouble(OrderStopLoss(),dig);
            TotalOrders[ChartListPosition+1][ko][3]=NormalizeDouble(OrderTakeProfit(),dig);
            TotalOrders[ChartListPosition+1][ko][4]=OrderTicket();
            TotalOrders[ChartListPosition+1][ko][5]=OrderLots();
            TotalOrders[ChartListPosition+1][ko][6]=OrderType();
            TotalOrders[ChartListPosition+1][ko][7]=OrderMagicNumber();
            TotalOrders[ChartListPosition+1][0][0]=ko;
            if (ViewOrders)
             {
              switch(TotalOrders[ChartListPosition+1][ko][6])
              {
               case OP_BUY:
                        Type="Buy";
                break;
                
               case OP_BUYSTOP:
                        Type="Buy Stop";
                break;
                
               case OP_BUYLIMIT:
                        Type="Buy Limit";
                break; 
                 
               case OP_SELL:
                        Type="Sell";
                break;
                
               case OP_SELLSTOP:
                        Type="Sell Stop";
                break; 
                
              case OP_SELLLIMIT:
                        Type="Sell Limit";
                break;  
              }           
              objName=StringConcatenate("#",TotalOrders[ChartListPosition+1][ko][4]," ",Type);
              
//+------------------------------------------------------------------+
//|Линия ордеров Sell,Buy и для всех типов отложенных ордеров        |
//+------------------------------------------------------------------+
                     
              if (chartpoint!=0)
               {
                orderprice=NormalizeDouble((TotalOrders[ChartListPosition+1][ko][1]-chartmin)/chartpoint,dig);
                if (!FindObject(objName,idWnd) && (orderprice<=100 && orderprice>=0) )
                 {
                  if (TotalOrders[ChartListPosition+1][ko][6]==OP_SELL ||
                      TotalOrders[ChartListPosition+1][ko][6]==OP_BUY) 
                   {               
                    CreateTrendLine(objName,pos,pos1,orderprice,TextColor,idWnd);
                   }
                   else
                   {
                    CreateTrendLine(objName,pos,pos1,orderprice,BullCandleColor,idWnd);
                   } 
                 }
                 else
                 {
                  if (ObjectGet(objName,OBJPROP_PRICE1)!=orderprice)
                   {
                    if (orderprice<=100 && orderprice>=0)
                         {
                          ObjectSet(objName,OBJPROP_PRICE1,orderprice);
                          ObjectSet(objName,OBJPROP_PRICE2,orderprice);
                         } 
                         else
                         {
                          ObjectDelete(objName);
                         } 
                   }
                 }  
               }  
               
//+------------------------------------------------------------------+
//|Линия ордера Тэйк-профит                                          |
//+------------------------------------------------------------------+
               
               if (chartpoint!=0)
                {    
                  if (TotalOrders[ChartListPosition+1][ko][3]!=0)
                   {
                    tp=NormalizeDouble((TotalOrders[ChartListPosition+1][ko][3]-chartmin)/chartpoint,dig);
                    if (!FindObject("TP "+objName,idWnd))
                     {
                       if (tp<=100 && tp>=0)
                        {
                         CreateTrendLine("TP "+objName,pos,pos1,tp,TakeProfitColor,idWnd);
                        } 
                     }
                     else
                     {
                      if (ObjectGet("TP "+objName,OBJPROP_PRICE1)!=tp)
                       {
                        if (tp<=100 && tp>=0)
                         {
                          ObjectSet("TP "+objName,OBJPROP_PRICE1,tp);
                          ObjectSet("TP "+objName,OBJPROP_PRICE2,tp);
                         } 
                         else
                         {
                          ObjectDelete("TP "+objName);
                         } 
                       }
                     }   
                   }
                   else
                   {
                    if (FindObject("TP "+objName,idWnd))
                     {
                      ObjectDelete("TP "+objName);
                     }
                   }
                 }  
                 
//+------------------------------------------------------------------+
//|Линия ордера Стоп-лосс                                            |
//+------------------------------------------------------------------+

               if (chartpoint!=0)
                {    
                  if (TotalOrders[ChartListPosition+1][ko][2]!=0)
                   {
                    sl=NormalizeDouble((TotalOrders[ChartListPosition+1][ko][2]-chartmin)/chartpoint,dig);
                    if (!FindObject("SL "+objName,idWnd))
                     {
                      if (sl<=100 && sl>=0)
                       {
                        CreateTrendLine("SL "+objName,pos,pos1,sl,StopLossColor,idWnd);
                       } 
                     }
                     else
                     {
                      if (ObjectGet("SL "+objName,OBJPROP_PRICE1)!=sl)
                       {
                        if (sl<=100 && sl>=0)
                         {
                          ObjectSet("SL "+objName,OBJPROP_PRICE1,sl);
                          ObjectSet("SL "+objName,OBJPROP_PRICE2,sl);
                         } 
                         else
                         {
                          ObjectDelete("SL "+objName);
                         }
                       }
                     }  
                   }
                   else
                   {
                     if (FindObject("SL "+objName,idWnd))
                      {
                       ObjectDelete("SL "+objName);
                      } 
                   } 
                 }  
             }
          }
       }  
    }
    return(TotalOrders[ChartListPosition+1][0][0]);
 }  
 
//+------------------------------------------------------------------+
//|Удаление линий(если ордер был закрыт или удален)                  |
//+------------------------------------------------------------------+

void DeleteOldTrendLines(int ChartListPosition)
   {
    if (ViewOrders)
     {
      int i, k=OrdersHistoryTotal(), ko=0,idWnd,ticket;
      string Symb=ChartNames[ChartListPosition],objName,Type;
    
      idWnd=WindowFind(Win_Name);
     
     for (i=0; i<k; i++) 
     {
      if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) 
       {
        if (OrderSymbol()==Symb)
         {
          
            switch(OrderType())
             {
              case OP_BUY:
                     Type="Buy";
               break;
               
              case OP_BUYSTOP:
                     Type="Buy Stop";
               break; 
               
              case OP_BUYLIMIT:
                     Type="Buy Limit";
               break;   
               
              case OP_SELL:
                     Type="Sell";
               break;
              
              case OP_SELLSTOP:
                     Type="Sell Stop";
               break;
               
              case OP_SELLLIMIT:
                     Type="Sell Limit";
               break;     
             }           
             ticket=OrderTicket();
             objName=StringConcatenate("#",ticket," ",Type);
             if (FindObject(objName,idWnd))
              {
               ObjectDelete(objName);
              }
             objName=StringConcatenate("TP ","#",ticket," ",Type); 
             if (FindObject(objName,idWnd))
              {
               ObjectDelete(objName);
              }
             objName=StringConcatenate("SL ","#",ticket," ",Type); 
             if (FindObject(objName,idWnd))
              {
               ObjectDelete(objName);
              } 
          }
        }
      }
    }
  }
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает суммарный профит открытых позиций в валюте депозита |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
double GetProfitOpenPosInCurrency(string sy="", int op=-1, int mn=-1)
 {
  double p=0;
  int    i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) 
  {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) 
    {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op))
       {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL)
         {
          if (mn<0 || OrderMagicNumber()==mn) 
          {
            p+=OrderProfit()+OrderCommission()+OrderSwap();
          }
        }
      }
    }
  }
  return(p);
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.08.2008                                                     |
//|  Описание : Возвращает суммарный профит открытых позиций в пунктах         |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//+----------------------------------------------------------------------------+
int GetProfitOpenPosInPoint(string sy="", int op=-1) 
{
  int    i, k=OrdersTotal();
  double pr=0,point=MathPow(10,MarketInfo(sy,MODE_DIGITS));
  
  for (i=0; i<k; i++)
   {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
     {
      if ((OrderSymbol()==sy ) && (op<0 || OrderType()==op)) 
      {
        if (OrderType()==OP_BUY)
          {
            pr+=(MarketInfo(OrderSymbol(), MODE_BID)-OrderOpenPrice())*point;
          }
          if (OrderType()==OP_SELL) 
          {
            pr+=(OrderOpenPrice()-MarketInfo(OrderSymbol(), MODE_ASK))*point;
          }
       }
    }
  }
  return(pr);
}   



