//+------------------------------------------------------------------+
//|                                                   EK Starter.mq4 |
//|                                                     Emerald King |
//|                                     mailto:info@emerald-king.com |
//|                                     built from the code posted   |
//|                                     by Starter on the Forums     |
//+------------------------------------------------------------------+

// Notes ************************************************************
// Added code to have a Stop Loss
// Added code to allow more than one trade if on different pair 
// Code Clean up
// 
// Version 1.0.0
// Last Modified Date: Sept., 28th, 2005

#property copyright "Emerald King"
#property link      "mailto:info@emerald-king.com"

//---- input parameters
extern int Lots = 1;
extern int StopLoss=70;                // Use 0 to Disable Stop Loss
extern int Slippage=3;                 // Maximum Slippage we are willing to tolerate
extern int DecreaseFactor = 3;
extern int MagicNumber = 77777;
extern double Stop = 10;
extern double MAPeriod=10;
extern double MaximumRisk = 0.08;
extern string EA_Name = "EK Starter";

// Globals
int Spread = 0;
string FX_Symbol = "";

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
   FX_Symbol = Symbol();
   Spread = MarketInfo(FX_Symbol, MODE_SPREAD);
   
   return(0);
}

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
{
   return(0);
}

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
   int cnt = 0;
   int Ticket = 0;
   int TotalOrders = 0;
   int OpenTrades = 0;   
   
   double Lag = 0;
   double AlphaC = 0;
   double MA = 0.0;
   double OldMA = 0.0;
   double OLots = 0.0;
   double MyStopLoss = 0.0;
   
   if (TimeYear(CurTime()) < 2005)
      return(0);

   TotalOrders = 0;   
   OpenTrades = 0;
   
//   Lag=iCustom(NULL, 0, "Laguerre", 0, 0);
   Lag=LaGuerre(0.7,0);
   AlphaC=iCCI(NULL, 0, 14, PRICE_CLOSE, 0);
   MA=iMA(NULL,0,MAPeriod,0,MODE_EMA,PRICE_MEDIAN,0);
   OldMA=iMA(NULL,0,MAPeriod,0,MODE_EMA,PRICE_MEDIAN,1);
   
   TotalOrders = OrdersTotal();
   for(cnt=0; cnt < TotalOrders; cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol()== FX_Symbol )
         OpenTrades = OpenTrades + 1;
   }
         
   if ( OpenTrades < 1 )   
   {
      if ( (Lag == 0) && (MA > OldMA) && (AlphaC < -5) )
      {
         OLots = LotsOptimized();
         if ( OLots >= 0.1 )
         {
            if ( StopLoss > 15 )
               MyStopLoss = Ask - ((StopLoss+Spread) * Point);
            else
               MyStopLoss = 0;
               
            Ticket = OrderSend(FX_Symbol,OP_BUY,OLots, Ask , Slippage, MyStopLoss, 0, EA_Name, MagicNumber, 0, Green);
         }
      }
         
      if ( (Lag == 1) && (MA < OldMA) && (AlphaC > 5) )
      {
         OLots = LotsOptimized();
         if ( OLots >= 0.1 )
         {
            if ( StopLoss > 15 )
               MyStopLoss = Bid + ((StopLoss+Spread) * Point);
            else
               MyStopLoss = 0;
               
            Ticket = OrderSend(FX_Symbol,OP_SELL,OLots, Bid , Slippage, MyStopLoss, 0, EA_Name, MagicNumber, 0, Red);  
         }
      }
   }
   
   TotalOrders = OrdersTotal();
   for ( cnt = 0; cnt < TotalOrders; cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol() == FX_Symbol )
      {
         if(OrderType()==OP_BUY)   // long position is opened
         {
            if(Lag>0.9)
            {
               OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Violet); // close position
               return(0); // exit
            }
            // check for stop
            if(Stop>0)  
            {                 
               if(Bid-OrderOpenPrice()>Point*Stop)
               {
                  OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Violet); // close position
                  return(0);
               }
            }
         }
         else
         {
            if(Lag<0.1)
            {
               OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Violet); // close position
               return(0); // exit
            }
            // check for stop
            if(Stop>0)  
            {                 
               if(OrderOpenPrice()-Ask>Point*Stop)
               {
                  OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Violet); // close position
                  return(0);
               }
            }  
         } 
      }
   }
   
   return(0);
}

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);
}

//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
{
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break

   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/500,1);

   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()!= FX_Symbol || OrderType()>OP_SELL) continue;
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
      }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
   }

   if(lot<0.1)
      lot=0.1;
      
   return(1);
}  
//+------------------------------------------------------------------+