//+------------------------------------------------------------------+
//|                                                                  |
//|                                   FiveSimpleStrategies_EA.mq4    |
//|                                    Copyright © 2009, Robert Hill |
//|                                                                  |
//+------------------------------------------------------------------+


#property  copyright "Copyright © 2009, Robert Hill"
#property link      "None"
#include <stdlib.mqh>
#include <stderror.mqh>

#define LONG 1
#define SHORT -1
#define FLAT 0

extern string  Expert_Name    = "FiveSimpleStrategies";
extern int MagicBase = 200000;

extern string  ma1="--Basic Entry/Exit settings--";
extern int     MaTrend_Period = 200;
extern int     RSI_Period = 2;       // input value to be optimized
extern int     ExitMA_Period = 5;   

extern string  met0 = "---Simple Entry Methods--";
extern string  met1 = " 1. RSI(2) under 5";
extern string  met2 = " 2. RSI(2) X day Sum";
extern string  met3 = " 3. 7 day HighLow";
extern string  met4 = " 4. RSI(2) 3 day Sum";
extern string  met5 = " 5. Reversal";
extern string  met6 = " 6. VIX";
extern int     SimpleMethod = 1;

extern string  me1="--Method 1 settings--";
extern string  rsi1="-- RSI settings--";
extern int     BuyWhenRsiBelow = 5;
extern int     SellWhenRsiAbove = 95;

extern string  me2="--Method 2 settings--";
extern string  rsi2="-- RSI settings--";
extern int     BuyWhenRsiSumBelowY2 = 30;
extern int     SellWhenRsiSumAboveY2 = 270;
extern int     NumDaysToSum2 = 3;

extern string  me3="--Method 3 settings--";
extern int     NumDaysForHighLow = 7;

extern string  me4="--Method 4 settings--";
extern string  rs4="-- RSI settings--";
extern int     BuyWhenRsiSumBelowY4 = 45;
extern int     SellWhenRsiSumAboveY4 = 255;
extern int     CloseBuyWhenRSIabove4 = 65;
extern int     CloseSellWhenRSIbelow4 = 35;
extern int     NumDaysToSum4 = 3;

extern string  me5="--Method 5 settings--";
extern int     NumDaysCloseUpDown = 4;

extern string  me6="--Method 6 settings--";
extern string  VIX_IndicatorName = "Synthetic_VIX_rev_MA";
extern int     VIX_Period = 22;
extern int     SMA_Period = 10;
extern int     CloseBuyWhenRSIabove6 = 65;
extern int     CloseSellWhenRSIbelow6 = 35;

extern string  hd = " --Limit 1 trade per day --";
extern int     useDelay = 1;

//+---------------------------------------------------+
//|Profit controls                                    |
//+---------------------------------------------------+
extern string  st6 = "--Profit Controls--";
extern double  StopLoss=0;
extern double  TakeProfit=0;
extern int     Slippage=3;

extern string  tsp = "--Trailing Stop Types--";
extern string  tsp0 = " 0. None";
extern string  tsp1 = " 1 = Trail immediately";
extern string  tsp2 = " 2 = Wait to trail";
extern string  tsp3 = " 3 = Uses 3 levels before trail";
extern string  tsp4 = " 4 = Breakeven + Lockin";
extern string  tsp5 = " 5 = Step trail";
extern string  tsp6 = " 6 = MA trail";
extern string  tsp7 = " 7 = pSAR trail";
extern int     TrailingStopType = 0;

extern string  ts2 = "Settings for Type 2";
extern double  TrailingStop = 15;      // Change to whatever number of pips you wish to trail your position with.

extern string  ts3 = "Settings for Type 3";
extern double  FirstMove = 20;        // Type 3  first level pip gain
extern double  FirstStopLoss = 50;    // Move Stop to Breakeven
extern double  SecondMove = 30;       // Type 3 second level pip gain
extern double  SecondStopLoss = 30;   // Move stop to lock is profit
extern double  ThirdMove = 40;        // type 3 third level pip gain
extern double  TrailingStop3 = 20;    // Move stop and trail from there

extern string  ts4 = "Settings for Type 4";
extern double  BreakEven = 30;
extern int     LockInPips = 5;        // Profit Lock in pips

extern string  ts5 = "Settings for Type 5";
extern int     eTrailingStop   = 10;
extern int     eTrailingStep   = 2;

extern string  ts6 = "Settings for Type 6";
extern int     TrailMA_TimeFrame    =  15;
extern int     TrailMA_Period       = 10;
extern int     TrailMA_Shift        =  0;    
extern string  t3="--Moving Average settings--";
extern string  tm = "--Moving Average Types--";
extern string  tm0 = " 0 = SMA";
extern string  tm1 = " 1 = EMA";
extern string  tm2 = " 2 = SMMA";
extern string  tm3 = " 3 = LWMA";
extern int     TrailMA_Type = 1;
extern string  tp = "--Applied Price Types--";
extern string  tp0 = " 0 = close";
extern string  tp1 = " 1 = open";
extern string  tp2 = " 2 = high";
extern string  tp3 = " 3 = low";
extern string  tp4 = " 4 = median(high+low)/2";
extern string  tp5 = " 5 = typical(high+low+close)/3";
extern string  tp6 = " 6 = weighted(high+low+close+close)/4";
extern int     TrailMA_AppliedPrice = 0;
extern int     InitialStop     =  0;
 
extern string  ts7 = "Settings for Type 7";
extern double  StepParabolic = 0.02;
extern double  MaxParabolic  = 0.2;
extern int     Interval      = 5;

//+---------------------------------------------------+
//|Money Management                                   |
//+---------------------------------------------------+
extern string  mm = "---Money Management---";
extern double  Lots=0.1;
extern bool    UseMoneyManagement = false;
//extern double  MaxLots = 30;
extern bool    BrokerIsIBFX = false;
extern bool    BrokerIsCrownForex = false;
extern string  m1="Set mini and micro to false for standard account";
extern bool    AccountIsMini = true;
extern bool    AccountIsMicro = false;
//extern string  fm="UseFreeMargin = false to use Account Balance";
//extern bool    UseFreeMargin = false;
extern double  TradeSizePercent = 1;  // Change to whatever percent of equity you wish to risk.
extern bool    BrokerPermitsFractionalLots = true;

//+---------------------------------------------------+
//|General controls                                   |
//+---------------------------------------------------+
int            MagicNumber=0;
string         setup;
int            TradesInThisSymbol = 0;
double         mLots;
double         myPoint;
int            totalTries 		= 5; 
int            retryDelay 		= 1000;
int            OrderErr;


//+------------------------------------------------------------------+
//| Calculate MagicNumber, setup comment and assign RSI Period       |
//|                                                                  |
//+------------------------------------------------------------------+
int init()
{

	MagicNumber = MagicBase + func_Symbol2Val(Symbol())*100 + func_TimeFrame_Const2Val(Period()); 
   setup=Expert_Name + Symbol() + "_" + func_TimeFrame_Val2String(func_TimeFrame_Const2Val(Period()));
     myPoint = SetPoint();
    
 return(0);
}

int deinit()
{
 return(0);
}

//+------------------------------------------------------------------+
//| CheckMAExit                                                      |
//| Close Buy if price closes below SMA 5                            |
//| Close Sell if price closes above SMA 5                           |
//|                                                                  |
//+------------------------------------------------------------------+
bool CheckExitMA(int cmd)
{
  double SMA;
  
  SMA = iMA(Symbol(),0,ExitMA_Period, 0, MODE_SMA, PRICE_CLOSE, 1);
  switch (cmd)
  {
  case OP_BUY : if (iClose(Symbol(),0,1) < SMA) return(true);
                break;
  case OP_SELL : if (iClose(Symbol(),0,1) > SMA) return (true);
  }
  return(false);
}

//+------------------------------------------------------------------+
//| CheckMethod3_Exit                                                |
//| Exit buy when price closes at NumDaysForHighLow high default 7   |
//| Exit sell when price closes at NumDaysForHighLow low default 7   |
//|                                                                  |
//+------------------------------------------------------------------+
bool CheckMethod3_Exit(int cmd)
{
   int HighInd, LowInd;

   if (cmd == OP_BUY)
   {
      HighInd =iHighest(NULL, 0, MODE_HIGH,NumDaysForHighLow,1);
      if (HighInd == 1) return(true);
   }
   if (cmd == OP_SELL)
   {
      LowInd =iLowest(NULL, 0, MODE_LOW, NumDaysForHighLow,1); 
      if (LowInd == 1) return(true);
   }

   return(false);
}

//+------------------------------------------------------------------+
//| CheckRSI_Exit                                                    |
//| Exit buy when RSI crosses above buy exit level default 65        |
//| Exit sell when RSI crosses below sell exit level default 35      |
//|                                                                  |
//+------------------------------------------------------------------+
bool CheckMethod4_Exit(int cmd)
{
   double RSIcur, RSIprev;
   
   RSIcur = iRSI(Symbol(),0, RSI_Period, PRICE_CLOSE, 1);
   RSIprev = iRSI(Symbol(),0, RSI_Period, PRICE_CLOSE, 2);
   
   switch (cmd)
   {
     case OP_BUY  : if (RSIcur > CloseBuyWhenRSIabove4 && RSIprev < CloseBuyWhenRSIabove4) return(true);
                    break;
     case OP_SELL : if (RSIcur < CloseSellWhenRSIbelow4 && RSIprev > CloseSellWhenRSIbelow4) return(true);
   }
   return(false);
}

//+------------------------------------------------------------------+
//| CheckRSI_Exit                                                    |
//| Exit buy when RSI crosses above buy exit level default 65        |
//| Exit sell when RSI crosses below sell exit level default 35      |
//|                                                                  |
//+------------------------------------------------------------------+
bool CheckMethod6_Exit(int cmd)
{
   double RSIcur, RSIprev;
   
   RSIcur = iRSI(Symbol(),0, RSI_Period, PRICE_CLOSE, 1);
   RSIprev = iRSI(Symbol(),0, RSI_Period, PRICE_CLOSE, 2);
   
   switch (cmd)
   {
     case OP_BUY  : if (RSIcur > CloseBuyWhenRSIabove6 && RSIprev < CloseBuyWhenRSIabove6) return(true);
                    break;
     case OP_SELL : if (RSIcur < CloseSellWhenRSIbelow6 && RSIprev > CloseSellWhenRSIbelow6) return(true);
   }
   return(false);
}

//+------------------------------------------------------------------+
//| CheckExitCondition                                               |
//|                                                                  |
//+------------------------------------------------------------------+
bool CheckExitCondition(int cmd)
{
   double RSI;
  
   RSI = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, 1);
   
   switch (SimpleMethod)
   {
    case 1  : return (CheckExitMA(cmd));
              break;
    case 2  : return (CheckExitMA(cmd));
              break;
    case 3  : return (CheckMethod3_Exit(cmd));
              break;
    case 4  : return (CheckMethod4_Exit(cmd));
              break;
    case 5  : return (CheckExitMA(cmd));
              break;
    case 6  : return (CheckMethod6_Exit(cmd));
              break;
   }
   
   return (false);
}

//+------------------------------------------------------------------+
//| CheckMAEntry                                                     |
//| Buy if price closes above SMA 200                                |
//| Sell if price closes below SMA 200                               |
//|                                                                  |
//+------------------------------------------------------------------+
bool CheckEntryMA(int cmd)
{
  double SMA;
  
  SMA = iMA(Symbol(),0,MaTrend_Period, 0, MODE_SMA, PRICE_CLOSE, 1);
  switch (cmd)
  {
  case OP_BUY : if (iClose(Symbol(),0,1) > SMA) return(true);
                break;
  case OP_SELL : if (iClose(Symbol(),0,1) < SMA) return (true);
  }
  return(false);
}

//+------------------------------------------------------------------+
//| GetSignalMethod1                                                 |
//| Buy when RSI is below buy level (5) and close above SMA 200      |
//| Sell when RSI is above sell level (95) and close below SMA 200   |
//+------------------------------------------------------------------+
int GetSignalMethod1()
{
  double RSIcur;

  RSIcur = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, 1);
  
  if (RSIcur < BuyWhenRsiBelow)
  {
     if (CheckEntryMA(OP_BUY))
     {
        if (CheckExitCondition(OP_BUY) == false) return(LONG);
     }
  }
  if (RSIcur > SellWhenRsiAbove)
  {
     if (CheckEntryMA(OP_SELL))
     {
        if (CheckExitCondition(OP_SELL) == false) return(SHORT);
     }
  }

  return(FLAT);
}

//+------------------------------------------------------------------+
//| GetSignalMethod2                                                 |
//| Use Sum of RSI for past X days                                   |
//| Buy when RSI sum is below buy sum level (30)                     |
//|   and close above SMA 200                                        |
//| Sell when RSI sum is above sell sum level (270)                  |
//|   and close below SMA 200                                        |
//+------------------------------------------------------------------+
int GetSignalMethod2()
{
  double RSIcur;
  double sum;

  sum = 0;
  for (int i = 0; i < NumDaysToSum2; i++)
  {
     RSIcur = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, i+1);
     sum += RSIcur;
  }
  
  if (sum < BuyWhenRsiSumBelowY2)
  {
     if (CheckEntryMA(OP_BUY))
     {
        if (CheckExitCondition(OP_BUY) == false) return(LONG);
     }
  }
  if (RSIcur > SellWhenRsiSumAboveY2)
  {
     if (CheckEntryMA(OP_SELL))
     {
         if (CheckExitCondition(OP_SELL) == false) return(SHORT);
     }
  }

  return(FLAT);
}
//+------------------------------------------------------------------+
//| GetSignalMethod3                                                 |
//| Buy when close is at 7 day low and close above SMA 200           |
//| Sell when close is at 7 day high and close below SMA 200         |
//+------------------------------------------------------------------+
int GetSignalMethod3()
{
   int HighInd, LowInd;

   if (CheckEntryMA(OP_BUY))
   {
      LowInd =iLowest(NULL, 0, MODE_LOW, NumDaysForHighLow,1); 
      if (LowInd == 1)
      {
          if (CheckExitCondition(OP_BUY) == false) return(LONG);
      }
   }
   if (CheckEntryMA(OP_SELL))
   {
      HighInd =iHighest(NULL, 0, MODE_HIGH,NumDaysForHighLow,1);
      if (HighInd == 1)
      {
         if (CheckExitCondition(OP_SELL) == false) return(SHORT);
      }
   }

  return(FLAT);
}

//+------------------------------------------------------------------+
//| GetSignalMethod2                                                 |
//| Use Sum of RSI for past 3 days                                   |
//| Buy when RSI sum is below buy sum level (45)                     |
//|   and close above SMA 200                                        |
//| Sell when RSI sum is above sell sum level (255)                  |
//|   and close below SMA 200                                        |
//+------------------------------------------------------------------+
int GetSignalMethod4()
{
  double RSIcur;
  double sum;

  sum = 0;
  for (int i = 0; i < NumDaysToSum4; i++)
  {
     RSIcur = iRSI(Symbol(), 0, RSI_Period, PRICE_CLOSE, i+1);
     sum += RSIcur;
  }
  
  if (sum < BuyWhenRsiSumBelowY4)
  {
     if (CheckEntryMA(OP_BUY))
     {
         if (CheckExitCondition(OP_BUY) == false) return(LONG);
     }
  }
  if (RSIcur > SellWhenRsiSumAboveY4)
  {
     if (CheckEntryMA(OP_SELL))
     {
         if (CheckExitCondition(OP_SELL) == false) return(SHORT);
     }
  }

  return(FLAT);
}
//+------------------------------------------------------------------+
//| GetSignalMethod5                                                 |
//| Buy when closes down 4 or more days in a row                     |
//|   and close above SMA 200                                        |
//| Sell when closes up 4 or more days in a row                      |
//|  and close below SMA 200                                         |
//+------------------------------------------------------------------+
int GetSignalMethod5()
{
  double Close1, Close2, Close3, Close4;
  double Open1, Open2, Open3, Open4;
  
  if (CheckEntryMA(OP_BUY))
  {
     if (Open[1] > Close[1])
     {
        if (Open[2] > Close[2] && Close[2] < Close[1])
        {
          if (Open[3] > Close[3] && Close[3] < Close[2])
          {
            if (Open[4] > Close[4] && Close[4] < Close[3])
              {
                 if (CheckExitCondition(OP_BUY) == false) return(LONG);
              }
          }
        }
     }
  }
  if (CheckEntryMA(OP_SELL))
  {
     if (Open[1] < Close[1])
     {
        if (Open[2] < Close[2] && Close[2] > Close[1])
        {
          if (Open[3] < Close[3] && Close[3] > Close[2])
          {
            if (Open[4] < Close[4] && Close[4] > Close[3])
              {
                 if (CheckExitCondition(OP_SELL) == false) return(SHORT);
              }
          }
        }
     }
  }

  return(FLAT);
}

int GetSignalMethod6()
{
   double Vix, MA;
   
    if (CheckEntryMA(OP_BUY))
    {
      Vix = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,0,1);
      MA = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,1,1);
      if (MA < Vix)
      {
        if ((Vix - MA) > MathAbs(Vix * 0.05))
        {
         Vix = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,0,2);
         MA = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,1,2);
         if (MA < Vix)
         {
           if ((Vix - MA) > MathAbs(Vix * 0.05))
           {
            Vix = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,0,3);
            MA = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,1,3);
            if (MA < Vix)
            {
              if ((Vix - MA) > MathAbs(Vix * 0.05))
              {
                 if (CheckExitCondition(OP_BUY) == false) return(LONG);
              }
            }
           }
         }
       }
      }
    }
    if (CheckEntryMA(OP_SELL))
    {
      Vix = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,0,1);
      MA = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,1,1);
      if (MA > Vix)
      {
        if ((MA - Vix) > MathAbs(Vix * 0.05))
        {
         Vix = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,0,2);
         MA = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,1,2);
         if (MA > Vix)
         {
           if ((MA - Vix) > MathAbs(Vix * 0.05))
           {
            Vix = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,0,3);
            MA = iCustom(Symbol(), 0, VIX_IndicatorName, VIX_Period, SMA_Period,1,3);
            if (MA > Vix)
            {
              if ((MA - Vix) > MathAbs(Vix * 0.05))
              {
                 if (CheckExitCondition(OP_SELL) == false) return(SHORT);
              }
            }
           }
         }
        }
      }
    }
    
  return(FLAT);
}

//+------------------------------------------------------------------+
//| GetSignal                                                        |
//|                                                                  |
//+------------------------------------------------------------------+
int GetSignal()
{
   int mSignal;
   switch (SimpleMethod)
   {
      case 1 : mSignal = GetSignalMethod1();
               break;
      case 2 : mSignal = GetSignalMethod2();
               break;
      case 3 : mSignal = GetSignalMethod3();
               break;
      case 4 : mSignal = GetSignalMethod4();
               break;
      case 5 : mSignal = GetSignalMethod5();
               break;
      case 6 : mSignal = GetSignalMethod6();
               break;
   }
   
   
   return (mSignal);
}
  
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Start                                                            |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
int start()
{
    int signal; 

    RefreshRates();
//+------------------------------------------------------------------+
//| Check for Open Position                                          |
//+------------------------------------------------------------------+

     HandleOpenPositions();
     
// Check if any open positions were not closed

     TradesInThisSymbol = CheckOpenPositions();
  
// Only allow 1 trade per Symbol

     if(TradesInThisSymbol > 0) return(0);
   
// Check if last trade stopped out

   if (useDelay == 1)
   {
       if (LastTradeClosedToday()) return(0);
   }

   if (!NewBar()) return(0); // wait until first tick after bar close to take any action; 
   
   signal=GetSignal();
   if (signal != FLAT)
   {
     mLots = GetLots();

	  if(signal == LONG) OpenBuyOrder(mLots);
	  if(signal == SHORT) OpenSellOrder(mLots);
	}

  return(0);
}

//+------------------------------------------------------------------+
//| OpenBuyOrder                                                     |
//| If Stop Loss or TakeProfit are used the values are calculated    |
//| for each trade                                                   |
//+------------------------------------------------------------------+
int OpenBuyOrder(double mLots)
{
   int err,ticket;
   double TPprice,STprice;
   
   RefreshRates();
   ticket=OrderSend(Symbol(),OP_BUY,mLots,Ask,Slippage,0,0,setup,MagicNumber,0,Green); 
   if (ticket > 0)
   {
    if (OrderSelect( ticket,SELECT_BY_TICKET, MODE_TRADES) ) 
     {
      Print("BUY order opened : ", OrderOpenPrice( ));
         if (StopLoss != 0 || TakeProfit != 0)
	      {
            TPprice = 0;
            if (TakeProfit > 0) TPprice=TakeLong(OrderOpenPrice(), TakeProfit);
            STprice = 0;
            if (StopLoss > 0)
            {
              STprice=StopLong(OrderOpenPrice(), StopLoss);
		        STprice = ValidStopLoss(OP_BUY,Bid, STprice);
		      }   
            
 // Normalize stoploss / takeprofit to the proper # of digits.
            if (Digits > 0) 
            {
              STprice = NormalizeDouble( STprice, Digits);
              TPprice = NormalizeDouble( TPprice, Digits); 
            }
		      ModifyOrder(ticket, OrderOpenPrice(), STprice, TPprice, LightGreen);
		   }
     }
   }
   else
   {
      err = GetLastError();
      if(err==0)
      { 
         return(ticket);
      }
      else
      {
         if(err==4 || err==137 ||err==146 || err==136) //Busy errors
         {
            Sleep(5000);
         }
         else //normal error
         {
           Print("Error opening BUY order [" + setup + "]: (" + err + ") " + ErrorDescription(err)); 
         }  
      }
   }
   
   return(ticket);
}

//+------------------------------------------------------------------+
//| OpenSellOrder                                                    |
//| If Stop Loss or TakeProfit are used the values are calculated    |
//| for each trade                                                   |
//+------------------------------------------------------------------+
void OpenSellOrder(double mLots)
{
   int err, ticket;
   double TPprice,STprice;
   
   RefreshRates();
   ticket=OrderSend(Symbol(),OP_SELL,mLots,Bid,Slippage,0,0,setup,MagicNumber,0,Red); 
   if (ticket > 0)
   {
     if (OrderSelect( ticket,SELECT_BY_TICKET, MODE_TRADES) ) 
     {
      Print("Sell order opened : ", OrderOpenPrice());
         if (StopLoss != 0 || TakeProfit != 0)
	      {
            TPprice = 0;
            if (TakeProfit > 0) TPprice=TakeShort(OrderOpenPrice(),TakeProfit);
            STprice = 0;
            if (StopLoss > 0)
            {
              STprice=StopShort(OrderOpenPrice() ,StopLoss);
		        STprice = ValidStopLoss(OP_SELL,Ask, STprice); 
		      }
 // Normalize stoploss / takeprofit to the proper # of digits.
            if (Digits > 0) 
            {
               STprice = NormalizeDouble( STprice, Digits);
               TPprice = NormalizeDouble( TPprice, Digits); 
            }
		      ModifyOrder(ticket, OrderOpenPrice(), STprice, TPprice, LightGreen);
		   }
     }
   }
   else
   {
      err = GetLastError();
      if(err==0)
      { 
         return(ticket);
      }
      else
      {
        if(err==4 || err==137 ||err==146 || err==136) //Busy errors
        {
           Sleep(5000);
        }
        else //normal error
        {
           Print("Error opening Sell order [" + setup + "]: (" + err + ") " + ErrorDescription(err));
        }
      } 
   }
   
   return(ticket);
}

//+------------------------------------------------------------------+
//| LastTradeClosedToday                                             |
//| Check History to see if last trade closed today                  |
//+------------------------------------------------------------------+
  
bool LastTradeClosedToday()
{
   int cnt, total;
   bool Closed;
   
   
   total = HistoryTotal();
   for (cnt = total - 1; cnt >= 0; cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS, MODE_HISTORY);
      
      if(OrderSymbol()!=Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;

        Closed = false;
        if (OrderType() == OP_BUY)
        {
          if (TimeDay(OrderCloseTime()) == TimeDay(TimeCurrent()))
          {
             Closed = true;
          }
          cnt = 0;
        }
        if (OrderType() == OP_SELL)
        {
          if (TimeDay(OrderCloseTime()) == TimeDay(TimeCurrent()))
          {
             Closed = true;
          }
          cnt = 0;
        }

   }
   
   return (Closed);
}

//+------------------------------------------------------------------+
//|                                                       MM_inc.mqh |
//|                                                 Copyright © 2007 |
//|                                                                  |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Get number of lots for this trade                                |
//+------------------------------------------------------------------+
double GetLots()
{
   double lot;
   double myMaxLot = MarketInfo(Symbol(), MODE_MAXLOT);
   
  if (UseMoneyManagement == false) return(Lots);
   if (BrokerIsIBFX == true)
   {
     lot = Calc_IBFX_Money_Management();
     return(lot);
   }
   
   if (BrokerIsCrownForex == true)
   {
     lot = Calc_CrownMoney_Management();
     return(lot);
   }
//   lot = LotsOptimized();
   lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,2);

//   lot = MathRound( lot/myStep ) * myStep;

// Use at least 1 micro lot
   if (AccountIsMicro == true)
   {
      lot = MathFloor(lot*100)/100;
      if (lot < 0.01) lot = 0.01;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }

// Use at least 1 mini lot
   if(AccountIsMini == true)
   {
      lot = MathFloor(lot*10)/10;
      if (lot < 0.1) lot = 0.1;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }
   
// Standard account   
   if( BrokerPermitsFractionalLots == false)
   {
      if (lot >= 1.0) lot = MathFloor(lot); else lot = 1.0;
   }
   
   if (lot < 1.0) lot = 1.0;
   if (lot > myMaxLot) lot = myMaxLot;

   return(lot);
}

//+------------------------------------------------------------------+
//| Calculate optimal lot size 
//+------------------------------------------------------------------+

/*
double LotsOptimized()
  {
   double lot=Lots;
//---- select lot size

   if (UseFreeMargin == true)
        lot=NormalizeDouble(MathFloor(AccountMargin()*TradeSizePercent/10000)/10,1);
   else
        lot=NormalizeDouble(MathFloor(AccountBalance()*TradeSizePercent/10000)/10,1);

   return(lot);
} 
*/

double Calc_CrownMoney_Management()
{
   double lot;

   lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,1);

//   lot = MathRound( lot/myStep ) * myStep;

// Use at least 1 mini lot
   if(AccountIsMini == true)
   {
      lot = MathFloor(lot*10)/10 * 10000;
      if (lot < 10000) lot = 10000;
//      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }
   
// Standard account   
   
   lot = lot * 100000;
   if (lot < 100000) lot = 100000;
//   if (lot > myMaxLot) lot = myMaxLot;

   return(lot);
}

double Calc_IBFX_Money_Management()
{
// variables used for money management
   double lot;
   double myMaxLot = MarketInfo(Symbol(), MODE_MAXLOT);

   lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,2);
   
// Use at least 1 micro lot
   if (AccountIsMicro == true)
   {
      lot = lot * 10;
      lot = MathFloor(lot*100)/100;
      if (lot < 0.1) lot = 0.1;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }

// Use at least 1 mini lot
   if(AccountIsMini == true)
   {
      lot = lot * 10;
      lot = MathFloor(lot*10)/10;
      if (lot < 1) lot = 1;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }
   
   // Standard Account
   
   if(BrokerPermitsFractionalLots == true)
        lot = StrToDouble(DoubleToStr(lot, 2));
   else
        lot = MathFloor(lot);
   
   if (lot > myMaxLot) lot = myMaxLot;

   return(lot); 
}



double StopLong(double price,int stop)
{
 if(stop==0)
  return(0);
 else
  return(price-(stop*myPoint));
}

double StopShort(double price,int stop)
{
 if(stop==0)
  return(0);
 else
  return(price+(stop*myPoint));
}

double TakeLong(double price,int take)
{
 if(take==0)
  return(0);
 else
  return(price+(take*myPoint));
}

double TakeShort(double price,int take)
{
 if(take==0)
  return(0);
 else
  return(price-(take*myPoint));
}

//+------------------------------------------------------------------+
//| Handle Open Positions                                            |
//| Check if any open positions need to be closed or modified        |
//+------------------------------------------------------------------+
int HandleOpenPositions()
{
   int cnt;
   
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol() != Symbol()) continue;
      if ( OrderMagicNumber() != MagicNumber)  continue;
      
      if(OrderType() == OP_BUY)
      {
            
         if (CheckExitCondition(OP_BUY))
          {
              CloseOrder(OrderTicket(),OrderLots(),OP_BUY);
          }
          else
          {
            if (TrailingStopType > 0)
            {
               HandleTrailingStop(OP_BUY,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
            }
          }
      }

      if(OrderType() == OP_SELL)
      {
          if (CheckExitCondition(OP_SELL))
          {
             CloseOrder(OrderTicket(),OrderLots(),OP_SELL);
          }
          else
          {
            if (TrailingStopType > 0)
            {
               HandleTrailingStop(OP_SELL,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
            }
          }
      }
   }
}

//+------------------------------------------------------------------+
//| Check Open Position Controls                                     |
//+------------------------------------------------------------------+
  
int CheckOpenPositions()
{
   int cnt, total;
   int NumTrades;
   
   NumTrades = 0;
   total=OrdersTotal();
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
      OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
      if ( OrderSymbol() != Symbol()) continue;
      if ( OrderMagicNumber() != MagicNumber)  continue;
      
      if(OrderType() == OP_BUY )  NumTrades++;
      if(OrderType() == OP_SELL )  NumTrades++;
             
     }
     return (NumTrades);
  }
  
int CloseOrder(int ticket,double numLots,int cmd)
{
	bool exit_loop = false, result;
   int cnt, err, digits;
   double myPrice;
   
   if (cmd == OP_BUY) myPrice = MarketInfo(Symbol( ), MODE_BID);
   if (cmd == OP_SELL) myPrice = MarketInfo(Symbol( ), MODE_ASK);
   digits = MarketInfo(Symbol( ), MODE_DIGITS) ;
   if (digits > 0)  myPrice = NormalizeDouble( myPrice, digits);
      
    cnt = 0;
    while (!exit_loop)
    {
		if (IsTradeAllowed()) 
		{
       result = OrderClose(ticket,numLots,myPrice,Slippage,Violet);
		 err = GetLastError();
      }
        else cnt++;
		if (result == true) 
			exit_loop = true;

         err=GetLastError();
		switch (err) 
		{
			case ERR_NO_ERROR:
				exit_loop = true;
				break;
			case ERR_SERVER_BUSY:
			case ERR_NO_CONNECTION:
			case ERR_INVALID_PRICE:
			case ERR_OFF_QUOTES:
			case ERR_BROKER_BUSY:
			case ERR_TRADE_CONTEXT_BUSY: 
			case ERR_TRADE_TIMEOUT:		// for modify this is a retryable error, I hope. 
				cnt++; 	// a retryable error
				break;
			case ERR_PRICE_CHANGED:
			case ERR_REQUOTE:
				RefreshRates();
				continue; 	// we can apparently retry immediately according to MT docs.
			default:
				// an apparently serious, unretryable error.
				exit_loop = true;
				break; 
		}  // end switch 

		if (cnt > totalTries) 
			exit_loop = true; 
			
		if (!exit_loop) 
		{
         Sleep(retryDelay);
			RefreshRates(); 
		}
	}  
	// we have now exited from loop. 
	if ((result == true) || (err == ERR_NO_ERROR)) 
	{
		OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES); 
		return(true); // SUCCESS! 
	}
	 
   Print(" Error closing order : (", err , ") " + ErrorDescription(err));
   return(false);

}


int ModifyOrder(int ord_ticket,double op, double price,double tp, color mColor)
{
    int CloseCnt, err;
    
    CloseCnt=0;
    while (CloseCnt < 3)
    {
       if (OrderModify(ord_ticket,op,price,tp,0,mColor))
       {
         CloseCnt = 3;
       }
       else
       {
          err=GetLastError();
          Print(CloseCnt," Error modifying order : (", err , ") " + ErrorDescription(err));
         if (err>0) CloseCnt++;
       }
    }
}

double ValidStopLoss(int type, double price, double SL)
{

   double minstop;
   double newSL;
   
   minstop = MarketInfo(Symbol(),MODE_STOPLEVEL);
   if (Digits == 3 || Digits == 5) minstop = minstop / 10;
   newSL = SL;
   if (type == OP_BUY)
   {
		 if((price - SL) < minstop*myPoint) newSL = price - minstop*myPoint;
   }
   if (type == OP_SELL)
   {
       if((SL-price) < minstop*myPoint)  newSL = price + minstop*myPoint;  
   }
   newSL = NormalizeDouble(newSL,Digits);   

   return(newSL);   
}

//+------------------------------------------------------------------+
//| HandleTrailingStop                                               |
//| Type 1 moves the stoploss without delay.                         |
//| Type 2 waits for price to move the amount of the trailStop       |
//| before moving stop loss then moves like type 1                   |
//| Type 3 uses up to 3 levels for trailing stop                     |
//|      Level 1 Move stop to 1st level                              |
//|      Level 2 Move stop to 2nd level                              |
//|      Level 3 Trail like type 1 by fixed amount other than 1      |
//| Type 4 Move stop to breakeven + Lockin, no trail                 |
//| Type 5 uses steps for 1, every step pip move moves stop 1 pip    |
//| Type 6 Uses EMA to set trailing stop                             |
//| Type 7 Uses Paraboloc SAR                                        |
//| Type 8 Uses Parabolic SAR coded by bluto from original EA        |
//+------------------------------------------------------------------+
int HandleTrailingStop(int type, int ticket, double op, double os, double tp)
{
   switch (TrailingStopType)
   {
     case 1 : Immediate_TrailingStop (type, ticket, op, os, tp);
              break;
     case 2 : Delayed_TrailingStop (type, ticket, op, os, tp);
              break;
     case 3 : ThreeLevel_TrailingStop (type, ticket, op, os, tp);
              break;
     case 4 : BreakEven_TrailingStop (type, ticket, op, os, tp);
              break;
	  case 5 : eTrailingStop (type, ticket, op, os, tp);
              break;
	  case 6 : MA_TrailingStop (type, ticket, op, os, tp);
              break;
	  case 7 : pSAR_TrailingStop (type, ticket, op, os, tp);
              break;
	}
   return(0);
}

//+------------------------------------------------------------------+
//|                                           BreakEvenExpert_v1.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by IgorAD,igorad2003@yahoo.co.uk |   
//|            http://finance.groups.yahoo.com/group/TrendLaboratory |                                      
//+------------------------------------------------------------------+
void BreakEven_TrailingStop(int type, int ticket, double op, double os, double tp)
{

   int digits;
   double pBid, pAsk, BuyStop, SellStop;

   digits = MarketInfo(Symbol(), MODE_DIGITS);
   
  if (type==OP_BUY)
  {
    pBid = MarketInfo(Symbol(), MODE_BID);
    if ( pBid-op > myPoint*BreakEven ) 
    {
       BuyStop = op + LockInPips * myPoint;
       if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
		 BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop);   
       if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
		 return;
	 }
  }
  if (type==OP_SELL)
  {
    pAsk = MarketInfo(Symbol(), MODE_ASK);
    if ( op - pAsk > myPoint*BreakEven ) 
    {
       SellStop = op - LockInPips * myPoint;
       if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
       SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
       if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
		 return;
    }
  }   

}

//+------------------------------------------------------------------+
//|                                                   e-Trailing.mq4 |
//|                                           Ким Игорь В. aka KimIV |
//|                                              http://www.kimiv.ru |
//|                                                                  |
//| 12.09.2005 Автоматический Trailing Stop всех открытых позиций    |
//|            Вешать только на один график                          |
//+------------------------------------------------------------------+
void eTrailingStop(int type, int ticket, double op, double os, double tp)
{

  int digits;
  double pBid, pAsk, BuyStop, SellStop;

  digits = MarketInfo(Symbol(), MODE_DIGITS) ;
  if (type==OP_BUY)
  {
    pBid = MarketInfo(Symbol(), MODE_BID);
    if ((pBid-op)>eTrailingStop*myPoint)
    {
      if (os<pBid-(eTrailingStop+eTrailingStep-1)*myPoint)
      {
        BuyStop = pBid-eTrailingStop*myPoint;
        if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
		  BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
        ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
        return;
      }
    }
  }
  if (type==OP_SELL)
  {
    pAsk = MarketInfo(Symbol(), MODE_ASK);
    if (op - pAsk > eTrailingStop*myPoint)
    {
      if (os > pAsk + (eTrailingStop + eTrailingStep-1)*myPoint || os==0)
      {
        SellStop = pAsk + eTrailingStop * myPoint;
        if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
        SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
        ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
        return;
      }
    }
  }

}

//+------------------------------------------------------------------+
//|                                           EMATrailingStop_v1.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by IgorAD,igorad2003@yahoo.co.uk |   
//|            http://finance.groups.yahoo.com/group/TrendLaboratory |
//|                                                                  |
//|  Modified to use any MA                                          |                                      
//+------------------------------------------------------------------+
void MA_TrailingStop(int type, int ticket, double op, double os, double tp)
{
   int digits;
   double pBid, pAsk, BuyStop, SellStop, ema;

   digits = MarketInfo(Symbol(), MODE_DIGITS) ;
   ema = iMA(Symbol(),TrailMA_TimeFrame,TrailMA_Period,0,TrailMA_Type,TrailMA_AppliedPrice,TrailMA_Shift);
   
   if (type==OP_BUY) 
   {
	   BuyStop = ema;
      pBid = MarketInfo(Symbol(),MODE_BID);
		if(os == 0 && InitialStop>0 ) BuyStop = pBid-InitialStop*myPoint;
		if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
		BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
		if ((op <= BuyStop && BuyStop > os) || os==0) 
		{
          ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
			 return;
      }
   }   

   if (type==OP_SELL)
   {
	   SellStop = ema;
      pAsk = MarketInfo(Symbol(),MODE_ASK);
      if (os==0 && InitialStop > 0) SellStop = pAsk+InitialStop*myPoint;
		if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);
      if( (op >= SellStop && os > SellStop) || os==0) 
      {
          ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
			 return;
      }
   }
}

//+------------------------------------------------------------------+
//|                                                b-TrailingSAR.mqh |
//|                                           Ким Игорь В. aka KimIV |
//|                                              http://www.kimiv.ru |
//|                                                                  |
//|    21.11.2005  Библиотека функций трала по параболику.           |
//|  Для использования добавить строку в модуле start                |
//|  if (UseTrailing) TrailingPositions();                           |
//+------------------------------------------------------------------+
void pSAR_TrailingStop(int type, int ticket, double op, double os, double tp)
{
   int digits;
   double pBid, pAsk, BuyStop, SellStop, spr;
   double sar1, sar2;
  
   digits = MarketInfo(Symbol(), MODE_DIGITS) ;
   pBid = MarketInfo(Symbol(), MODE_BID);
   pAsk = MarketInfo(Symbol(), MODE_ASK);
   sar1=iSAR(NULL, 0, StepParabolic, MaxParabolic, 1);
   sar2=iSAR(NULL, 0, StepParabolic, MaxParabolic, 2);
   spr = pAsk - pBid;
   if (digits > 0) spr = NormalizeDouble(spr, digits); 
   
   if (type==OP_BUY)
   {
     pBid = MarketInfo(Symbol(), MODE_BID);
     if (sar2 < sar1)
     {
        BuyStop = sar1-Interval*myPoint;
        if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
	     BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
        if (os<BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
     }
   }
   if (type==OP_SELL)
   {
     if (sar2 > sar1)
     {
        SellStop = sar1 + Interval * myPoint + spr;
        if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
	     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
        if (os>SellStop || os==0) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
     }
   }
}

//+------------------------------------------------------------------+
//|                                      ThreeLevel_TrailingStop.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by MrPip,robydoby314@yahoo.com   |   
//|                                                                  |
//| Uses up to 3 levels for trailing stop                            |
//|      Level 1 Move stop to 1st level                              |
//|      Level 2 Move stop to 2nd level                              |
//|      Level 3 Trail like type 1 by fixed amount other than 1      |
//+------------------------------------------------------------------+
void ThreeLevel_TrailingStop(int type, int ticket, double op, double os, double tp)
{

   int digits;
   double pBid, pAsk, BuyStop, SellStop;

   digits = MarketInfo(Symbol(), MODE_DIGITS) ;

   if (type == OP_BUY)
   {
      pBid = MarketInfo(Symbol(), MODE_BID);
      if (pBid - op > FirstMove * myPoint)
      {
         BuyStop = op + FirstMove*myPoint - FirstStopLoss * myPoint;
         if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
		   BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
         if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
      }
              
      if (pBid - op > SecondMove * myPoint)
      {
         BuyStop = op + SecondMove*myPoint - SecondStopLoss * myPoint;
         if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
		   BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
         if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
      }
                
      if (pBid - op > ThirdMove * myPoint)
      {
         BuyStop = pBid  - TrailingStop3*myPoint;
         if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
		   BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
         if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
      }
   }
       
    if (type ==  OP_SELL)
    {
        pAsk = MarketInfo(Symbol(), MODE_ASK);
        if (op - pAsk > FirstMove * myPoint)
        {
           SellStop = op - FirstMove * myPoint + FirstStopLoss * myPoint;
           if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
           if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
        }
        if (op - pAsk > SecondMove * myPoint)
        {
           SellStop = op - SecondMove * myPoint + SecondStopLoss * myPoint;
           if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
           if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
        }
        if (op - pAsk > ThirdMove * myPoint)
        {
           SellStop = pAsk + TrailingStop3 * myPoint;               
           if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
           if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
        }
    }

}

//+------------------------------------------------------------------+
//|                                       Immediate_TrailingStop.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by MrPip,robydoby314@yahoo.com   |
//|                                                                  |   
//| Moves the stoploss without delay.                                |
//+------------------------------------------------------------------+
void Immediate_TrailingStop(int type, int ticket, double op, double os, double tp)
{

   int digits;
   double pt, pBid, pAsk, BuyStop, SellStop;

   digits = MarketInfo(Symbol( ), MODE_DIGITS);
   
   if (type==OP_BUY)
   {
     pBid = MarketInfo(Symbol(), MODE_BID);
     pt = StopLoss * myPoint;
     if(pBid-os > pt)
     {
       BuyStop = pBid - pt;
       if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
		 BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop);   
       if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
		 return;
	  }
   }
   if (type==OP_SELL)
   {
     pAsk = MarketInfo(Symbol(), MODE_ASK);
     pt = StopLoss * myPoint;
     if(os - pAsk > pt)
     {
       SellStop = pAsk + pt;
       if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
       SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
       if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
		 return;
     }
   }   
}

//+------------------------------------------------------------------+
//|                                         Delayed_TrailingStop.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by MrPip,robydoby314@yahoo.com   |
//|                                                                  |   
//| Waits for price to move the amount of the TrailingStop           |
//| Moves the stoploss pip for pip after delay.                      |
//+------------------------------------------------------------------+
void Delayed_TrailingStop(int type, int ticket, double op, double os, double tp)
{
   int digits;
   double pt, pBid, pAsk, BuyStop, SellStop;

   pt = TrailingStop * myPoint;
   digits = MarketInfo(Symbol(), MODE_DIGITS);
   
   if (type==OP_BUY)
   {
     pBid = MarketInfo(Symbol(), MODE_BID);
     BuyStop = pBid - pt;
     if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
	  BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop);   
     if (pBid-op > pt && os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
	  return;
   }
   if (type==OP_SELL)
   {
     pAsk = MarketInfo(Symbol(), MODE_ASK);
     pt = TrailingStop * myPoint;
     SellStop = pAsk + pt;
     if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
     if (op - pAsk > pt && os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
	  return;
   }   
}

int func_Symbol2Val(string symbol)
 {
   string mySymbol = StringSubstr(symbol,0,6);
   
	if(mySymbol=="AUDCAD") return(1);
	if(mySymbol=="AUDJPY") return(2);
	if(mySymbol=="AUDNZD") return(3);
	if(mySymbol=="AUDUSD") return(4);
	if(mySymbol=="CHFJPY") return(5);
	if(mySymbol=="EURAUD") return(6);
	if(mySymbol=="EURCAD") return(7);
	if(mySymbol=="EURCHF") return(8);
	if(mySymbol=="EURGBP") return(9);
	if(mySymbol=="EURJPY") return(10);
	if(mySymbol=="EURUSD") return(11);
	if(mySymbol=="GBPCHF") return(12);
	if(mySymbol=="GBPJPY") return(13);
	if(mySymbol=="GBPUSD") return(14);
	if(mySymbol=="NZDJPY") return(15);
	if(mySymbol=="NZDUSD") return(16);
	if(mySymbol=="USDCAD") return(17);
	if(mySymbol=="USDCHF") return(18);
	if(mySymbol=="USDJPY") return(19);
   Comment("unexpected Symbol");
	return(999);
}

//+------------------------------------------------------------------+
//| Time frame interval appropriation  function                      |
//+------------------------------------------------------------------+

int func_TimeFrame_Const2Val(int Constant ) {
   switch(Constant) {
      case 1:  // M1
         return(1);
      case 5:  // M5
         return(2);
      case 15:
         return(3);
      case 30:
         return(4);
      case 60:
         return(5);
      case 240:
         return(6);
      case 1440:
         return(7);
      case 10080:
         return(8);
      case 43200:
         return(9);
   }
}

//+------------------------------------------------------------------+
//| Time frame string appropriation  function                               |
//+------------------------------------------------------------------+

string func_TimeFrame_Val2String(int Value ) {
   switch(Value) {
      case 1:  // M1
         return("PERIOD_M1");
      case 2:  // M1
         return("PERIOD_M5");
      case 3:
         return("PERIOD_M15");
      case 4:
         return("PERIOD_M30");
      case 5:
         return("PERIOD_H1");
      case 6:
         return("PERIOD_H4");
      case 7:
         return("PERIOD_D1");
      case 8:
         return("PERIOD_W1");
      case 9:
         return("PERIOD_MN1");
   	default: 
   		return("undefined " + Value);
   }
}

double SetPoint()
{
   double mPoint;
   
   if (Digits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}

bool NewBar()
{
   static datetime dt = 0;
   
   if (Time[0] != dt)
   {
      dt = Time[0];
      return(true);
   }
   return(false);
}





