// 9/23/07     Modified from pmurfin SignalTrendFollower.  Added UseSlope, TradeOn, Lots, StopLoss, and 
//             TakeProfit parameters and accompanying functionality.  With TradeOn = false and UseSlope = false,
//             this version should behave the same as the original

#property copyright "Paul Murfin."
#property link      ""

#define   MODEL "Trend Follower3"

#define   STARTBAR  1
#define	LONG         1
#define	SHORT        -1
#define	FLAT         0
#define  ALLLONG     2
#define  ALLSHORT    -2

#define	strLONG      "LONG"
#define	strSHORT     "SHORT"
#define	strFLAT      "FLAT"
#define  strALLLONG  "ALL LONG"
#define  strALLSHORT "ALL SHORT"

#define  REDNUM      16
#define  GREENNUM  12    
#define  BLUENUM     11
#define  ORANGENUM 13
#define  YELLOWNUM 14


extern   bool AlertOn = true;
extern   bool EmailOn = true;

extern   bool TradeOn = true;
//==================================================
extern string TM= "Trade and Account managment";
extern bool    AccountIsMicro=False;
extern bool    MM               = false;// Use Money Management or not
extern int     Risk             = 2;    // Percentage of account balance
extern double  Lots         = 1;   //Lot size
extern double  DecreaseFactor =0;
extern int     TakeProfit       = 60;    
extern int     StopLoss         = 40; 
extern bool    OnlyTrailAfterProfit=false;    // Trailing Stop will only trail when order is profitable
extern int     TrailingStop     = 15; 
extern int     BreakEven=15; //Pips to move stoploss to breakeven at
extern int     PipsToLock       =1;   //When Breakeven after pips is reached, it will move to that plus this many pips
extern string IS= "Indicator Settings";
extern   bool UseSlope = False;
extern string MA= "Moving average cross settings";
extern int FastMaPeriod = 4;
extern int FastMaMode = 1;
extern int SlowMaPeriod = 8;
extern int SlowMaMode = 1;
extern string SDL= "Slope Direction Line settings";
extern int SDLPeriod = 80;
extern string MACD= "MACD settings";
extern int FEmaPeriod = 5;
extern int SEmaPeriod = 35;
extern int SignalPeriod = 5;
extern string L= "Laguerre settings";
extern double Gamma = 0.66;
extern string IT= "Investor trend, True=normal,False=All just Long";
extern bool UseInvestorTrend = true;
//===

double   RedMax;
double   RedMin;
int       RedTrend;
int      RedPeriods[REDNUM] = {125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200};

double   GreenMax;
double   GreenMin;
int         GreenTrend;
int       GreenPeriods[GREENNUM] = {78, 82, 86, 90, 94, 98, 102, 106, 110, 114, 118, 122};

double   BlueMax;
double   BlueMin;
int        BlueTrend;
int        BluePeriods[BLUENUM] = {44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74};

double   OrangeMax;
double   OrangeMin;
int        OrangeTrend;
int        OrangePeriods[ORANGENUM] = {17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41};

double   YellowMax;
double   YellowMin;
int        YellowTrend;
int        YellowPeriods[YELLOWNUM] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
						
int	SignalTrend;
int	SlopeTrend;
int	MACDTrend;
int	LaguerreTrend;
int	GuppyTrend;
int	InvestorTrend;
int   TradingIndicator;
int MagicNumber; 
string	strTrends;
int ExistOrder;
int TicketLots;
int TicketNo;


//FirstBarTime=StrToTime("00:05"); 
//string lotstring;//=DoubleToStr(Lots, Digits);

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int init () {

	SignalTrend = FLAT;
	SlopeTrend = FLAT;
	MACDTrend = FLAT;
	LaguerreTrend = FLAT;
	InvestorTrend = FLAT;
	GuppyTrend = FLAT;
	TradingIndicator = FLAT;

	NewBar();
	CalculateIndicators(STARTBAR);
	DisplayComment();
	
	return (0);
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int deinit () {

	return (0);
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int start () { 

   if (MM==true) Lots = CalculateLots(Risk);
   MagicNumber=CalcMagic  (Symbol(),Period());
   
   bool OpenOrders;
   int cnt;
   
	if (NewBar()) { 
	  CalculateIndicators(STARTBAR);
	  
	//lotstring=DoubleToStr(Lots, Digits);
		
	  //Any current trades for this symbol	
     for(cnt=0;cnt<OrdersTotal();cnt++)   
     {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if ((OrderSymbol()==Symbol()) && (OrderMagicNumber() == MagicNumber))
         {
              if (OrderType() == OP_BUY) ExistOrder = LONG;
              if (OrderType() == OP_SELL) ExistOrder = SHORT;
              TicketNo = OrderTicket();
              TicketLots = OrderLots();
  	           OpenOrders = true;
         }	  	           
  	      else 
  	           OpenOrders = false;
     } 
     
     if (TradingIndicator == LONG) 
     {
         if (OpenOrders == false)
         {
		        if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG");
		        if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG");
		        if (TradeOn) PlaceTrade(TradingIndicator);
         }
         else
         {
            //already in a position this direction
            if (ExistOrder == LONG) { //already in a position this direction
               if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG. Trade already open for this symbol.");
               if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG. Trade already open for this symbol.");      
            }
            //Need to reverse position
            else
            {
               //close open Order
               OrderClose(TicketNo,TicketLots,Ask,3,Red);
               
               if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG.  Existing trade closed, position reversed.");
		         if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG. Existing trade closed, position reversed.");
		         if (TradeOn) PlaceTrade(TradingIndicator);
            }
         }            
     }         
     else if (TradingIndicator == SHORT) 
     {
         if (OpenOrders == false)
         {
              if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT");
		        if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT");
		        if (TradeOn) PlaceTrade(TradingIndicator);
         }
         else
         {
            //already in a position this direction
            if (ExistOrder == SHORT) {
               if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT. Trade already open for this symbol.");
               if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT. Trade already open for this symbol.");      
            }
            //Need to reverse position
            else               
            {
               //close open OrderClose
               OrderClose(TicketNo,TicketLots,Ask,3,Red);
               
               //open new order
               if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT.  Existing trade closed, position reversed.");
		         if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT. Existing trade closed, position reversed.");
		         if (TradeOn) PlaceTrade(TradingIndicator);
            }               
         } 		        
	 }
	}

	DisplayComment();
	breakEvenManager();
	trailingStopManager();

	
	return (0);

}

////////////////////////////////////////////////////////

////////////////////////////////////////////////////////



////////////////////////////////////////////////////////

void CalculateIndicators (int BarNo) {

	double  up;
	double  dn;
	double  L0;
	double  L1;
	double  f1;
	double  f2;
	double  s1;
	double  s2;
	double  MACD0;
	double  MACD1;

	SignalTrend = FLAT;
	SlopeTrend = FLAT;
	MACDTrend = FLAT;
	LaguerreTrend = FLAT;
	InvestorTrend = FLAT;
	GuppyTrend = FLAT;
	TradingIndicator = FLAT;

//	Signal Direction

	f1 = iMA(NULL, 0, FastMaPeriod, 0, FastMaMode, PRICE_CLOSE, BarNo);
	s1 = iMA(NULL, 0, SlowMaPeriod, 0, SlowMaMode, PRICE_CLOSE, BarNo);
	f2 = iMA(NULL, 0, FastMaPeriod, 0, FastMaMode, PRICE_CLOSE, BarNo+1);
	s2 = iMA(NULL, 0, SlowMaPeriod, 0, SlowMaMode, PRICE_CLOSE, BarNo+1);

	if (f1 > s1 && f2 < s2) 
		SignalTrend = LONG;
	else if (f1 < s1 && f2 > s2) 
		SignalTrend = SHORT;
	
	if (SignalTrend == FLAT) {

	f1 = iMA(NULL, 0, FastMaPeriod, 0, FastMaMode, PRICE_CLOSE, BarNo+1);
	s1 = iMA(NULL, 0, SlowMaPeriod, 0, SlowMaMode, PRICE_CLOSE, BarNo+1);
	f2 = iMA(NULL, 0, FastMaPeriod, 0, FastMaMode, PRICE_CLOSE, BarNo+2);
	s2 = iMA(NULL, 0, SlowMaPeriod, 0, SlowMaMode, PRICE_CLOSE, BarNo+2);

	if (f1 > s1 && f2 < s2) 
		SignalTrend = LONG;
	else if (f1 < s1 && f2 > s2) 
		SignalTrend = SHORT;
	
	}

//	Slope Direction

	up = iCustom(NULL,0,"Slope Direction Line",SDLPeriod,3,0,BarNo);
	dn = iCustom(NULL,0,"Slope Direction Line",SDLPeriod,3,1,BarNo);

	if (up == EMPTY_VALUE && dn != EMPTY_VALUE) 
		SlopeTrend = SHORT;
   else if (dn == EMPTY_VALUE && up != EMPTY_VALUE) 
		SlopeTrend = LONG;


//	MACD

	MACD0 = iMACD(NULL,0,FEmaPeriod,SEmaPeriod,SignalPeriod,PRICE_CLOSE,0,BarNo);
	
	if (MACD0 > 0) 
		MACDTrend = LONG;
   else if (MACD0 < 0) 
		MACDTrend = SHORT;
	

//	Laguerre

	L0 = iCustom(NULL,0,"Laguerre",Gamma,9500,0,BarNo);
	L1 = iCustom(NULL,0,"Laguerre",Gamma,9500,0,BarNo+1);

	if (L0 > 0.15 && L1 < 0.15) 
		LaguerreTrend = LONG;
	else if (L0 < 0.75 && L1 > 0.75)  
		LaguerreTrend = SHORT;
	

	if (LaguerreTrend == FLAT) {

	L0 = iCustom(NULL,0,"Laguerre",Gamma,9500,0,BarNo+1);
	L1 = iCustom(NULL,0,"Laguerre",Gamma,9500,0,BarNo+2);

	if (L0 > 0.15 && L1 < 0.15) 
		LaguerreTrend = LONG;
	else if (L0 < 0.75 && L1 > 0.75)  
		LaguerreTrend = SHORT;
	

	}


//	Guppy

	CalculateGuppy(BarNo);

//	Trading Indicator
if (UseSlope == true)
{
	if (SignalTrend == LONG && LaguerreTrend == LONG && MACDTrend == LONG && GuppyTrend == LONG && SlopeTrend == LONG) TradingIndicator = LONG;
	else if (SignalTrend == SHORT && LaguerreTrend == SHORT && MACDTrend == SHORT && GuppyTrend == SHORT && SlopeTrend == SHORT) TradingIndicator = SHORT;
}
else
{
	if (SignalTrend == LONG && LaguerreTrend == LONG && MACDTrend == LONG && GuppyTrend == LONG) TradingIndicator = LONG;
	else if (SignalTrend == SHORT && LaguerreTrend == SHORT && MACDTrend == SHORT && GuppyTrend == SHORT) TradingIndicator = SHORT;
}

//	Display string

strTrends = "\nRed : "+GSD(RedTrend)+"  Green : "+GSD(GreenTrend)+ "  Blue : "+GSD(BlueTrend)+ "  Orange : "+GSD(OrangeTrend)+ "  Yellow : "+GSD(YellowTrend)+
"\n\nSignal : "+GSD(SignalTrend)+"  Slope : "+GSD(SlopeTrend)+"  MACD : "+GSD(MACDTrend)+"  Laguerre : "+GSD(LaguerreTrend)+"  Guppy : "+GSD(GuppyTrend)+"       TRADE : "+GSD(TradingIndicator);




}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int CalculateGuppy (int BarNo) {

   int      i;
   double   curr;
   double   prev;
   int      count;
     
   RedTrend = FLAT;
   RedMin = 0;
   RedMax = 0;
   GreenTrend = FLAT;
   GreenMin = 0;
   GreenMax = 0;
   BlueTrend = FLAT;
   BlueMin = 0;
   BlueMax = 0;
   OrangeTrend = FLAT;
   OrangeMin = 0;
   OrangeMax = 0;
   YellowTrend = FLAT;
   YellowMin = 0;
   YellowMax = 0;
   InvestorTrend = FLAT;
   GuppyTrend = FLAT;

   // Red Trends

   count = 0;   
   for (i=0;i<REDNUM;i++) {
      curr = iMA(NULL, 0, RedPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, RedPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (RedMax == 0 || curr > RedMax) RedMax = curr;
      if (RedMin == 0 || curr < RedMin) RedMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == REDNUM) RedTrend = ALLLONG;
   else if (count == -REDNUM) RedTrend = ALLSHORT;
   else RedTrend = FLAT;
   
   // Green Trends

   count = 0;   
   for (i=0;i<GREENNUM;i++) {
      curr = iMA(NULL, 0, GreenPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, GreenPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (GreenMax == 0 || curr > GreenMax) GreenMax = curr;
      if (GreenMin == 0 || curr < GreenMin) GreenMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == GREENNUM) GreenTrend = ALLLONG;
   else if (count == -GREENNUM) GreenTrend = ALLSHORT;
   else GreenTrend = FLAT;
   
  // Blue Trends

   count = 0;   
   for (i=0;i<BLUENUM;i++) {
      curr = iMA(NULL, 0, BluePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, BluePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (BlueMax == 0 || curr > BlueMax) BlueMax = curr;
      if (BlueMin == 0 || curr < BlueMin) BlueMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == BLUENUM) BlueTrend = ALLLONG;
   else if (count == -BLUENUM) BlueTrend = ALLSHORT;
   else BlueTrend = FLAT;
 
// Orange Trends

   count = 0;   
   for (i=0;i<ORANGENUM;i++) {
      curr = iMA(NULL, 0, OrangePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, OrangePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (OrangeMax == 0 || curr > OrangeMax) OrangeMax = curr;
      if (OrangeMin == 0 || curr < OrangeMin) OrangeMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == ORANGENUM) OrangeTrend = ALLLONG;
   else if (count == -ORANGENUM) OrangeTrend = ALLSHORT;
   else OrangeTrend = FLAT;
    
// Yellow Trends

   count = 0;   
   for (i=0;i<YELLOWNUM;i++) {
      curr = iMA(NULL, 0, YellowPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, YellowPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (YellowMax == 0 || curr > YellowMax) YellowMax = curr;
      if (YellowMin == 0 || curr < YellowMin) YellowMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == YELLOWNUM) YellowTrend = ALLLONG;
   else if (count == -YELLOWNUM) YellowTrend = ALLSHORT;
   else YellowTrend = FLAT;    
      
// InvestorTrend

     if (RedTrend == ALLLONG &&  GreenTrend == ALLLONG && RedMax < GreenMin) InvestorTrend = LONG;
     else if (RedTrend == ALLSHORT && GreenTrend == ALLSHORT && RedMin > GreenMax) InvestorTrend = SHORT;
     else InvestorTrend = FLAT;

// Guppy Trend
 
     if (UseInvestorTrend == true)
{
	if (YellowTrend == ALLLONG && OrangeTrend == ALLLONG && BlueTrend == ALLLONG && InvestorTrend == LONG) GuppyTrend = LONG;
     else if (YellowTrend == ALLSHORT && OrangeTrend == ALLSHORT && BlueTrend == ALLSHORT && InvestorTrend == SHORT) GuppyTrend = SHORT;
     else GuppyTrend = FLAT;
}
else
{
	if (YellowTrend == ALLLONG && OrangeTrend == ALLLONG && BlueTrend == ALLLONG && RedTrend == ALLLONG &&  GreenTrend == ALLLONG) GuppyTrend = LONG;
     else if (YellowTrend == ALLSHORT && OrangeTrend == ALLSHORT && BlueTrend == ALLSHORT && RedTrend == ALLSHORT && GreenTrend == ALLSHORT) GuppyTrend = SHORT;
     else GuppyTrend = FLAT;
}
    
	
}


////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

string GSD(int D) {

	switch (D) {
		case LONG : return (strLONG);
		case SHORT : return (strSHORT);
		case ALLLONG : return (strALLLONG);
		case ALLSHORT : return (strALLSHORT);
	}
	return (strFLAT);

}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
void breakEvenManager() 
{

   for(int cnt=0;cnt<OrdersTotal();cnt++)
   {
   OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

      if ((BreakEven>0)&& (OrderMagicNumber()==MagicNumber ))
      {
         if (OrderType()==OP_BUY)
         {
            if (MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice()>=Point*BreakEven)
            {
               if (OrderStopLoss()<OrderOpenPrice() + PipsToLock*Point)
                  OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice() + PipsToLock*Point,OrderTakeProfit(),0,Green); 
            }
         }
         else if (OrderType()==OP_SELL)
         {
            if (OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK)>=Point*BreakEven)
            {
               if (OrderStopLoss()>OrderOpenPrice() - PipsToLock*Point)
                  OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice() - PipsToLock*Point,OrderTakeProfit(),0,Red); 
            }
         }
      }
   }


}     
   
 void trailingStopManager() 
{
   
   int cnt, total = OrdersTotal();

   for(cnt=0;cnt<total;cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

      if ((TrailingStop>0) && (OrderMagicNumber()==MagicNumber))
      {
         if (OrderType()==OP_BUY)
         {
            if ((MarketInfo(OrderSymbol(),MODE_BID)-OrderOpenPrice()>Point*TrailingStop) || OnlyTrailAfterProfit==false)
            {
               if (OrderStopLoss()<MarketInfo(OrderSymbol(),MODE_BID)-Point*TrailingStop)
                  OrderModify(OrderTicket(),OrderOpenPrice(),MarketInfo(OrderSymbol(),MODE_BID)-Point*TrailingStop,OrderTakeProfit(),0,Green); 
            }
         }
         else if (OrderType()==OP_SELL)
         {
            if ((OrderOpenPrice()-MarketInfo(OrderSymbol(),MODE_ASK)>Point*TrailingStop) || OnlyTrailAfterProfit==false)
            {
               if ((OrderStopLoss()>(MarketInfo(OrderSymbol(),MODE_ASK)+Point*TrailingStop)) || (OrderStopLoss()==0))
                  OrderModify(OrderTicket(),OrderOpenPrice(),MarketInfo(OrderSymbol(),MODE_ASK)+Point*TrailingStop,OrderTakeProfit(),0,Red); 
            }
         }
      }  
   }

}  

double CalculateLots(int Risk)
{
if(MM==false) return(Lots);
double lot=Lots;
int orders=HistoryTotal();
int losses=0;
int decimalPlaces=1;

if(AccountIsMicro==true) decimalPlaces=2;

lot=NormalizeDouble((AccountFreeMargin()*Risk/1000.0)/100,decimalPlaces);
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,decimalPlaces);
}

if(lot<0.1 && AccountIsMicro==false) lot=0.1;
if(lot<0.01 && AccountIsMicro==true) lot=0.01;
if(lot>99) lot=99;
return(lot);

}


////////////////////////////////////////////////////////

bool NewBar() {

	static datetime LastTime = 0;

	if (Time[0] != LastTime) {
		LastTime = Time[0];		
		return (true);
	} else
		return (false);
}



void DisplayComment() {

   Comment(strTrends);
}

void PlaceTrade (int TradingIndicator) {
   int ticket;
   double StopPrice;
   double TakeProfitPrice;
   bool OpenOrders;
   int cnt;

   //Sell   
   if (TradingIndicator == SHORT)
      {
        //Calculate stop and takeprofit ... needs to be much more robust but this is a start
        StopPrice = Bid + (StopLoss * Point);
        TakeProfitPrice = Bid - (TakeProfit * Point);
        
        //Place order
        ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,StopPrice,TakeProfitPrice,"",MagicNumber,0,Red);
        if(ticket<0)
          {
           Print("OrderSend failed with error #",GetLastError());
          }
      }
      
   //Buy      
   else
   {
        //Calculate stop and takeprofit ... needs to be much more robust but this is a start
        StopPrice = Ask - (StopLoss * Point);
        TakeProfitPrice = Ask + (TakeProfit * Point);
        
        //Place Order
        ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,StopPrice,TakeProfitPrice,"",MagicNumber,0,Green);
        if(ticket<0)
          {
           Print("OrderSend failed with error #",GetLastError());
          }     
   }  

 
   
   return(0);
}

int CalcMagic(string CurrPair, int CurrPeriod)
 {       if (CurrPair=="EURUSD" || CurrPair=="EURUSDm") {return(1000+CurrPeriod);}
   else if (CurrPair=="GBPUSD" || CurrPair=="GBPUSDm") {return(2000+CurrPeriod);}
   else if (CurrPair=="USDCHF" || CurrPair=="USDCHFm") {return(3000+CurrPeriod);}
   else if (CurrPair=="USDJPY" || CurrPair=="USDJPYm") {return(4000+CurrPeriod);}
   else if (CurrPair=="EURJPY" || CurrPair=="EURJPYm") {return(5000+CurrPeriod);}
   else if (CurrPair=="EURCHF" || CurrPair=="EURCHFm") {return(6000+CurrPeriod);}
   else if (CurrPair=="EURGBP" || CurrPair=="EURGBPm") {return(7000+CurrPeriod);}
   else if (CurrPair=="USDCAD" || CurrPair=="USDCADm") {return(8000+CurrPeriod);}
   else if (CurrPair=="AUDUSD" || CurrPair=="AUDUSDm") {return(9000+CurrPeriod);}
   else if (CurrPair=="GBPCHF" || CurrPair=="GBPCHFm") {return(10000+CurrPeriod);}
   else if (CurrPair=="GBPJPY" || CurrPair=="GBPJPYm") {return(11000+CurrPeriod);}
   else if (CurrPair=="CHFJPY" || CurrPair=="CHFJPYm") {return(12000+CurrPeriod);}
   else if (CurrPair=="NZDUSD" || CurrPair=="NZDUSDm") {return(13000+CurrPeriod);}
   else if (CurrPair=="EURCAD" || CurrPair=="EURCADm") {return(14000+CurrPeriod);}
   else if (CurrPair=="AUDJPY" || CurrPair=="AUDJPYm") {return(15000+CurrPeriod);}
   else if (CurrPair=="EURAUD" || CurrPair=="EURAUDm") {return(16000+CurrPeriod);}
   else if (CurrPair=="AUDCAD" || CurrPair=="AUDCADm") {return(17000+CurrPeriod);}
   else if (CurrPair=="AUDNZD" || CurrPair=="AUDNZDm") {return(18000+CurrPeriod);}
   else if (CurrPair=="NZDJPY" || CurrPair=="NZDJPYm") {return(19000+CurrPeriod);}
   else if (CurrPair=="CADJPY" || CurrPair=="CADJPYm") {return(20000+CurrPeriod);}
   else if (CurrPair=="XAUUSD" || CurrPair=="XAUUSDm") {return(21000+CurrPeriod);}
   else if (CurrPair=="XAGUSD" || CurrPair=="XAGUSDm") {return(22000+CurrPeriod);}
   else if (CurrPair=="GBPAUD" || CurrPair=="GBPAUDm") {return(23000+CurrPeriod);}
   else if (CurrPair=="GBPCAD" || CurrPair=="GBPCADm") {return(24000+CurrPeriod);}
   else if (CurrPair=="AUFCHF" || CurrPair=="AUFCHFm") {return(25000+CurrPeriod);}
   else if (CurrPair=="CADCHF" || CurrPair=="CADCHFm") {return(26000+CurrPeriod);}
   else if (CurrPair=="NZDCHF" || CurrPair=="NZDCHFm") {return(27000+CurrPeriod);}
 }