//+------------------------------------------------------------------+
//|                                                  ft_prohvost.mq4 |
//|                                     Copyright 2012, FORTRADER.RU |
//|                                              http://fortrader.ru |
//+------------------------------------------------------------------+
//url: http://fortrader.ru/services/ea/single?id=4
//Стратегия работы советника описана в 78 выпуске журнала. 
#property copyright "Copyright 2012, FORTRADER.RU"
#property link      "http://fortrader.ru"

extern int    golovamax=50;  
extern int    golovamin=10;

extern int    telomax=50;
extern int    telomin=10;  

extern int    hvostmax=50;
extern int    hvostmin=10;

extern int    numbarclose=0;

extern double InpLots      =0.1; 
extern int      EA_Magic=12354;  

int barnb,barns;

extern int    InpStopLoss  =50;  

extern int maxopenbuy = 0;
extern bool aofilter=true;
extern bool aoclose=true;
extern bool fractalstop=true;
extern bool atrstop=false;

int bars;

int start()
  { double sl;
  
    if(Bars!=bars)
  {
    bars=Bars;
  
     double s_golova_min = golovamin;
     double s_telo_min = telomin;

     double s_golova_max = golovamax;
     double s_telo_max = telomax;
     
     double s_hvost_max = hvostmax;
     double s_hvost_min = hvostmin;
     
    double TKP = InpStopLoss;

   if(Digits==5 || Digits==3)
     {
      s_golova_min = golovamin*10;
      s_telo_min = telomin*10;
    
      s_golova_max = golovamax*10;
      s_telo_max = telomax*10;
      
      s_hvost_max = hvostmax*10;
      s_hvost_min = hvostmin*10;


      TKP = TKP*10;
     }
     
    double ao1=iAO(NULL, 0, 1);
    double ao2=iAO(NULL, 0, 2);
    
    sl=Ask-TKP*Point;
    if(fractalstop==true){sl=ftStopLoss(0,"fr", Ask);}
    if(atrstop==true){sl=ftStopLoss(0,"atr", Ask);}
    
   if(Close[1]>Open[1])
   {
         if(  ((ao1 > ao2 && aofilter==true) || aofilter==false ) && High[1]-Close[1]>s_golova_min*Point && High[1]-Close[1]<s_golova_max*Point && Close[1]-Open[1]>s_telo_min*Point && Close[1]-Open[1]<s_telo_max*Point && timecontrol()==1 && (CountPos(1)<=maxopenbuy))
         {
         barnb=0;
         OpenOrderOnMarket(0,sl,High[1]);
         }
   }
       
   /*
      if(Close[1]<Open[1])
   {
         if( High[1]-Open[1]>s_golova_min*Point && High[1]-Open[1]<s_golova_max*Point && Open[1]-Close[1]>s_telo_min*Point && Open[1]-Close[1]<s_telo_max*Point && timecontrol()==1 && (CountPos(1)<=maxopenbuy) )
         {
         barnb=0;
         OpenOrderOnMarket(0,TKP,Open[1]);
         }
   }    
    
  
   if(Close[1]<Open[1])
   {
         if(Close[1]-Low[1]>s_hvost_min*Point && Close[1]-Low[1]<s_hvost_max*Point && Open[1]-Close[1]>s_telo_min*Point && Open[1]-Close[1]<s_telo_max*Point && timecontrol()==1 && (CountPos(0)<=maxopenbuy))
       {
       barns=0;
    //   OpenOrderOnMarket(1,TKP,Low[1]);
       }
   } */ 
  
  
  if(ao1<ao2 && aoclose==true){CloseAllPos(1);}
 // if((barns>=numbarclose && SummPos(0)<0 && numbarclose>0) /*|| Ask<=ma*/){CloseAllPos(0);}

   
   barnb++; barns++;
  } 
   return(0);
  }
  
//Цена последней открытия последней закрытой сделки
double ProfitLastPosHist(int type) 
{int i;datetime time;double price;
   for( i=1; i<=OrdersHistoryTotal(); i++)         
   {
      if(OrderSelect(i-1,SELECT_BY_POS,MODE_HISTORY)==true) 
       {                                   
           if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && type==1 && OrderOpenTime()>time){time=OrderOpenTime();price=OrderProfit();}
           if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && type==0 && OrderOpenTime()>time){time=OrderOpenTime();price=OrderProfit();}
       }
    }   
return(price);
}  

//Цена последней открытия последней закрытой сделки
double LotLastPosHist(int type) 
{int i;datetime time;double price;
   for( i=1; i<=OrdersHistoryTotal(); i++)         
   {
      if(OrderSelect(i-1,SELECT_BY_POS,MODE_HISTORY)==true) 
       {                                   
           if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && type==1 && OrderOpenTime()>time){time=OrderOpenTime();price=OrderLots();}
           if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && type==0 && OrderOpenTime()>time){time=OrderOpenTime();price=OrderLots();}
       }
    }   
return(price);
}  
  
//количество позиций
int CountPos(int type) 
{int i,b,s;
   for( i=1; i<=OrdersTotal(); i++)         
   {
      if(OrderSelect(i-1,SELECT_BY_POS)==true) 
       {                                   
           if(OrderType()==OP_BUY && OrderSymbol()==Symbol()){b=b+1;}
           if(OrderType()==OP_SELL && OrderSymbol()==Symbol()){s=s+1;}
       }
    }   
    if(type==0){return(s);}
    if(type==1){return(b);}
}

  
extern int starttime = 0; 
extern int stoptime = 0; 

//Ограничение по времени
int timecontrol()
{// Подробное описание http://fxnow.ru/blog.php?user=Yuriy&blogentry_id=1
   if ( ( (Hour()>=0 && Hour()<=stoptime-1) ||  (Hour()>=starttime && Hour()<=23)) && starttime>stoptime)
      {
      return(1);
      }  
      if ( (Hour()>=starttime && Hour()<=stoptime-1) && starttime<stoptime)
      {
      return(1);
      }  
      
   if(starttime==0 && stoptime==0){ return(1);}
     
return(0);
}
  
 //суммирует результат позиций по типу
double SummPos(int type) 
{//подробное описание: http://fxnow.ru/blog.php?user=Yuriy&blogentry_id=100

   int i;double summ;
   for( i=0; i<=OrdersTotal(); i++)         
   {
           if(true==OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

       {                                   
           if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && type==1){summ=summ+OrderProfit();}
           if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && type==0){summ=summ+OrderProfit();}
       }
    }   
return(summ);
}  

//Закрываем все позиции по типу
int CloseAllPos(int type)
{//Описание функции: http://fxnow.ru/blog.php?user=Yuriy&blogentry_id=72
int buy=1; int sell=1;
int i,b=0;int ordertiket;
 
 if(type==1)
   {
   while(buy==1)
     {
        buy=0;
        for( i=0;i<OrdersTotal();i++)
         {
           if(true==OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
           {
           if(OrderType()==OP_BUY && OrderSymbol()==Symbol() ){buy=1; OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet);}
           }else{buy=0;}
         }  
         if(buy==0){return(0);}
      } 
   }
   
   if(type==0)
   {
      while(sell==1)
     {
        sell=0;
        for( i=0;i<OrdersTotal();i++)
         {
           if(true==OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
           {
           if(OrderType()==OP_SELL && OrderSymbol()==Symbol() ){sell=1;OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); }
           }else{sell=0;}
         }  
         
        if(sell==0){return(0);}
      } 
     }
   return(0);
   }  

int OpenOrderOnMarket(int type,double slpips,double tppips)
{double op,sl,tp;int err;

double LotB=InpLots;
double LotS=InpLots;

   
   if(type==0)
   {
   op=Ask;if(slpips>0){sl=slpips;}if(tppips>0){tp=tppips;}
   err=OrderSend(Symbol(),OP_BUY,LotB,NormalizeDouble(op,Digits),3,NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),"56 FORTRADER.RU",EA_Magic,0,Red);
   if(err<0){Print("OrderSend()-  Ошибка OP_BUY.  op "+op+" sl "+sl+" tp "+tp+" "+" LOT "+LotB+" "+GetLastError());return(-1);}
   }
   
   if(type==1)
   {
    op=Bid;if(slpips>0){sl=op+slpips*Point;}if(tppips>0){tp=tppips;}
    err=OrderSend(Symbol(),OP_SELL,LotS,NormalizeDouble(op,Digits),3,NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),"56 FORTRADER.RU",EA_Magic,0,Red);
    if(err<0){Print("OrderSend()-  Ошибка OP_SELL.  op "+op+" sl "+sl+" tp "+tp+" "+" LOT "+LotS+" "+GetLastError());return(-1);}
   }
return(0);
}

extern int ATRPeriod=12;
double ftStopLoss(int typePos, string typeStoploss, double enterprice){
double stoploss;double value;
 
  /*fracrals*/
   int frcounter=0;
   if(typePos==0 && typeStoploss=="fr")
   { 
     while(value==0)
     {
     value=iFractals(NULL, 0, MODE_LOWER, frcounter);
     frcounter++;
     }
     stoploss=value;
   }
   
   if(typePos==1 && typeStoploss=="fr")
   {  
     
     while(value==0)
     {
     value=iFractals(NULL, 0, MODE_UPPER, frcounter);
     frcounter++;
     }

   }
   /*end fractals*/
   
   /*atr*/
   if(typeStoploss=="atr")
   {
   value = enterprice-iATR(NULL,0,ATRPeriod,1);
   }
   
stoploss=value;
return(stoploss);
}