//+------------------------------------------------------------------+
//|                                                        Lager.mq4 |
//|                                                                  |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+

//ИГРАЕМ НА ЧАСОВКЕ H1

extern double MaximumRisk        = 0.01;
extern double DecreaseFactor     = 3;
extern double OrderPeriod=300;
extern double StopL=1000;
extern double Ga=0.9;
extern double UpLine=0.95;
extern double MiddleLine=0.5;
extern double DownLine=0.05;
extern int prevbars;


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---- 
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//---- 
   
//----
   return(0);
  }
 
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/500,1);
//---- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//---- return lot size
   if(lot<1) lot=1;
   if(lot>10000) lot=10000;
   return(lot);
  }  
  
double LaGuerre(double gamma, int shift)
{
	double RSI;
	double L0[100];
	double L1[100];
	double L2[100];
	double L3[100];
	double CU, CD;

	for (int i=shift+99; i>=shift; i--)
	{
		L0[i] = (1.0 - gamma)*Close[i] + gamma*L0[i+1];
		L1[i] = -gamma*L0[i] + L0[i+1] + gamma*L1[i+1];
		L2[i] = -gamma*L1[i] + L1[i+1] + gamma*L2[i+1];
		L3[i] = -gamma*L2[i] + L2[i+1] + gamma*L3[i+1];

		CU = 0;
		CD = 0;
		if (L0[i] >= L1[i])  CU = L0[i] - L1[i];
		else 		 		CD = L1[i] - L0[i];
		
		if (L1[i] >= L2[i])  CU = CU + L1[i] - L2[i];
		else 		 		CD = CD + L2[i] - L1[i];
		if (L2[i] >= L3[i])  CU = CU + L2[i] - L3[i];
		else 		 		CD = CD + L3[i] - L2[i];

		if (CU + CD != 0)		RSI = CU / (CU + CD);
	}
   return(RSI);
}  

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   double Laguerre, LaguPrev;
     
//+--   double Juice;
   int cnt, ticket, total;
   bool est_s, est_b, wend;
        
//  Print ("prevbars=", prevbars, "; Bars=", Bars);
  if (prevbars==Bars) return(0);
  prevbars=Bars;
//  Laguerre=LaGuerre(Ga, 0);
//  LaguPrev=LaGuerre(Ga, 1);
  Laguerre=iCustom(NULL, 0, "Laguerre", 0, 0);
  LaguPrev=iCustom(NULL, 0, "Laguerre", 0, 1);
  wend=((DayOfWeek()==5) && (Hour()>12));
  
  total=OrdersTotal();

// it is important to enter the market correctly, 
   // but it is more important to exit it correctly...   
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==Symbol())  // check for symbol
        {
         if(OrderType()==OP_BUY)   // long position is opened
           {
            // should it be closed?
//            if(Laguerre==0)
//                {
//                 OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
//                 Print("вернулся");
//                 return(0); // exit
//                }
//            if((Laguerre>=(MiddleLine-0.05)) && ((Bid-OrderOpenPrice())>0))
              if((Bid-OrderOpenPrice())>0)
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
//                 Print("клоз с профитом");
                 return(0); // exit
                }
            // check for stop
//            if(wend && (Hour()>22 && (Minute()>45)))
//               {
//                OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
//                return(0); // exit
//               }
           }
         else // go to short position
           {
            // should it be closed?
//            if(Laguerre==1)
//              {
//               OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
//               Print("вернулся");
//               return(0); // exit
//              }
//            if((Laguerre>=(MiddleLine+0.05)) && ((OrderOpenPrice()-Ask)>0))
              if((OrderOpenPrice()-Ask)>0)
                {
                 OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
//                 Print("клоз с профитом");
                 return(0); // exit
                }
            // check for stop
//            if(wend && (Hour()>22 && (Minute()>45)))
//               {
//                OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
//                return(0); // exit
//               }
           }
        }
     }
  if (total<50)
  {
  est_s=true;
  est_b=true;
   for(cnt=0;cnt<total;cnt++)
     {
       OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
       if((OrderType()==OP_SELL) && (OrderSymbol()==Symbol()) && ((CurTime()-OrderOpenTime()<OrderPeriod))) est_s=false;
       if((OrderType()==OP_BUY) && (OrderSymbol()==Symbol()) && ((CurTime()-OrderOpenTime()<OrderPeriod))) est_b=false;
     }
//Print (Laguerre, "; ", LaguPrev, "; ", wend, "; ", est_s, "; ", est_b, "; ");
//Print ("(Laguerre>DownLine)=", (Laguerre>DownLine), "; (Laguerre<UpLine)=", (Laguerre<UpLine), "; (Laguerre>LaguPrev)=", (Laguerre>LaguPrev));
      if(AccountFreeMargin()<(1000*LotsOptimized()))
        {
//         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // check for long position (BUY) possibility
      if(!wend && (Laguerre>DownLine) && (Laguerre<UpLine) && (LaguPrev<DownLine) && (Laguerre>LaguPrev) && est_b)
        {
         Print("  ", LaguPrev, "  ", Laguerre);
         ticket=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,Ask-StopL*Point,0,"lager",16384,0,Green);
        }
      // check for short position (SELL) possibility
      if(!wend && (Laguerre>DownLine) && (Laguerre<UpLine) && (LaguPrev>UpLine) && (Laguerre<LaguPrev) && est_s)
        {
         Print("  ", LaguPrev, "  ", Laguerre);
         ticket=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,Bid+StopL*Point,0,"starter",16384,0,Red);
        } 
   }
   return(0);
  }
// the end.

