//+------------------------------------------------------------------+
//|                                 DoubleMA_Crossover_EA.mq4        |
//|                                              Copyright © 2005    |
//|    Written by MrPip from idea of Jason Robinson for Eric         |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MrPip"
#include <stdlib.mqh>

extern string  Expert_Name    = "DMAC_EA";
extern int     MagicNumberBase = 200000;
extern string UserComment = "DMAC";

extern string  stf0 = "---TimeFrames---";
extern string  stf1 = "1. Month";
extern string  stf2 = "2. Week";
extern string  stf3 = "3. Day";
extern string  stf4 = "4. 4 Hour";
extern string  stf5 = "5. 1 Hour";
extern string  stf6 = "6. 30 minute";
extern string  stf7 = "7. 15 minute";
extern string  stf8 = "8. 5 minute";
extern string  stf9 = "9. 1 minute";
extern int     TradeTimeFrame  = 5;
//+---------------------------------------------------+
//|Indicator Variables                                |
//| Change these to try your own system               |
//| or add more if you like                           |
//+---------------------------------------------------+
extern string ma0 = "Moving Average Modes";
extern string ma1 = " 0=sma, 1=ema, 2=smma";
extern string ma2 = " 3=lwma, 4=LSMA";
extern int FastMA_Mode = 1;          //0=sma, 1=ema, 2=smma, 3=lwma, 4=LSMA
extern int FastMA_Period =   5;
extern string  p = "--Applied Price Types--";
extern string  p0 = " 0 = close";
extern string  p1 = " 1 = open";
extern string  p2 = " 2 = high";
extern string  p3 = " 3 = low";
extern string  p4 = " 4 = median(high+low)/2";
extern string  p5 = " 5 = typical(high+low+close)/3";
extern string  p6 = " 6 = weighted(high+low+close+close)/4";
extern int FastMA_AppliedPrice = 0;  // 0=close, 1=open, 2=high, 3=low, 4=median((h+l/2)), 5=typical((h+l+c)/3), 6=weighted((h+l+c+c)/4)
extern int SlowMA_Mode = 1;           //0=sma, 1=ema, 2=smma, 3=lwma, 4=LSMA
extern int SlowMA_Period =   12;
extern int SlowMA_AppliedPrice = 0;  // 0=close, 1=open, 2=high, 3=low, 4=median((h+l/2)), 5=typical((h+l+c)/3), 6=weighted((h+l+c+c)/4)
extern int SignalCandle=1;

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

//+---------------------------------------------------+
//|Profit controls                                    |
//+---------------------------------------------------+
extern string  st6 = "--Profit Controls--";
extern double StopLoss = 250;       // Maximum pips willing to lose per position.
extern int TakeProfit = 0;          // Maximum profit level achieved.

//*****************************************************
// These inputs are used by the trailing stop function
//*****************************************************
extern string  tsp0 = "--Trailing Stop Types--";
extern string  tsp1 = " 1 = Trail immediately";
extern string  tsp2 = " 2 = Wait to trail";
extern string  tsp3 = " 3 = Uses 3 levels before trail";
extern bool    UseTrailingStop = true;
extern int     TrailingStopType = 3;    // Type 1 moves stop immediately, Type 2 waits til value of TS is reached

extern string  ts2 = "Settings for Type 2";
extern double  TrailingStop = 40;    // 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 = 15;       // Move Stop to Breakeven
extern double SecondMove = 30;      // Type 3 second level pip gain
extern double SecondStopLoss = 20;      // 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 int Slippage = 10;           // Possible fix for not getting closed    

extern string  sm0="--Trading Hours Filter--";
extern string  sm1=" Times are GMT when UseDST=false";
extern string  sm2="UseTradingHours - Enter 0 for false, 1 for true";
extern int    UseTradingHours = 0;
extern string  sm4="TradeAsian - Enter 0 for false, 1 for true";
extern int    TradeAsianMarket = 1;
extern int     AsianStart = 100;       // Start trades after time
extern int     AsianStop = 300;      // Stop trading after time
extern string  sm5="Trade Europe - Enter 0 for false, 1 for true";
extern int    TradeEuropeanMarket = 1;
extern int     EurStart = 900;       // Start trades after time
extern int     EurStop = 1100;      // Stop trading after time
extern string  sm6="Trade NY - Enter 0 for false, 1 for true";
extern int    TradeNewYorkMarket = 0;
extern int     NYStart = 1300;       // Start trades after time
extern int     NYStop = 1500;      // Stop trading after time


bool     YesStop;

//+---------------------------------------------------+
//|General controls                                   |
//+---------------------------------------------------+
int            MagicNumber=0;
string setup;
double lotMM;
int TradesInThisSymbol;
double   myPoint;

int allTF[9]={PERIOD_MN1,PERIOD_W1,PERIOD_D1,PERIOD_H4,PERIOD_H1,PERIOD_M30,PERIOD_M15,PERIOD_M5,PERIOD_M1};
int tf1;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
	MagicNumber = MagicNumberBase + func_Symbol2Val(Symbol())*100 + func_TimeFrame_Const2Val(Period()); 
   setup=Expert_Name + Symbol() + "_" + func_TimeFrame_Val2String(func_TimeFrame_Const2Val(Period()));
   setup = UserComment;
   tf1=allTF[TradeTimeFrame-1];
   myPoint = SetPoint(Symbol());
   return(0);
  }
  
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
  }

double SetPoint(string mySymbol)
{
   double mPoint, myDigits;
   
   myDigits = MarketInfo (mySymbol, MODE_DIGITS);
   if (myDigits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}

//+------------------------------------------------------------------------+
//| LSMA - Least Squares Moving Average function calculation               |
//| LSMA_In_Color Indicator plots the end of the linear regression line    |
//| Modified to use any timeframe                                          |
//+------------------------------------------------------------------------+

double LSMA(int TimeFrame, int LSMAPeriod, int LSMAPrice,int shift)
{
   double wt;
   
   double ma1=iMA(NULL,TimeFrame,LSMAPeriod,0,MODE_SMA ,LSMAPrice,shift);
   double ma2=iMA(NULL,TimeFrame,LSMAPeriod,0,MODE_LWMA,LSMAPrice,shift);
   wt = MathFloor((3.0*ma2-2.0*ma1)/myPoint)*myPoint;
   return(wt);
}  

//+------------------------------------------------------------------+
//| CheckExitCondition                                               |
//| Check if any exit condition is met                               |
//+------------------------------------------------------------------+
bool CheckExitCondition(int TradeType)
{
   bool YesClose;
   double fMA, myClose;
   
   YesClose = false;
   if (FastMA_Mode == 4)
   {
     fMA = LSMA(tf1,FastMA_Period,FastMA_AppliedPrice,SignalCandle);
   }
   else
   {
     fMA = iMA(NULL, tf1, FastMA_Period, 0, FastMA_Mode, FastMA_AppliedPrice, SignalCandle);
   }
    // Check for cross down
   myClose =  iClose(Symbol(), tf1, SignalCandle);
   if (TradeType == OP_BUY && myClose < fMA ) YesClose = true;
   // Check for cross up
   if (TradeType == OP_SELL && myClose > fMA) YesClose = true;

   return (YesClose);
}

//+------------------------------------------------------------------+
//| CheckEntryCondition                                              |
//| Check if entry condition is met                                  |
//+------------------------------------------------------------------+
bool CheckEntryCondition(int TradeType)
{
   bool YesTrade;
   double fMA, sMA, myClose;
   
   YesTrade = false;
   if (FastMA_Mode == 4)
   {
     fMA = LSMA(tf1,FastMA_Period,FastMA_AppliedPrice,SignalCandle);
   }
   else
   {
     fMA = iMA(NULL, tf1, FastMA_Period, 0, FastMA_Mode, FastMA_AppliedPrice, SignalCandle);
   }
   if (SlowMA_Mode == 4)
   {
     sMA = LSMA(tf1,SlowMA_Period,SlowMA_AppliedPrice,SignalCandle);
   }
   else
   {
     sMA = iMA(NULL, tf1, SlowMA_Period, 0, SlowMA_Mode, SlowMA_AppliedPrice, SignalCandle);
   }
   
   myClose =  iClose(Symbol(), tf1, SignalCandle);
   
     // Check for cross up
     if (TradeType == OP_BUY && fMA > sMA && myClose > fMA)  YesTrade = true;
    // Check for cross down
     if (TradeType == OP_SELL && fMA < sMA && myClose < fMA) YesTrade = true;
   
   return (YesTrade);
}
  

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//---- 


// Check for valid inputs

   if (CheckValidUserInputs()) return(0);   

//+------------------------------------------------------------------+
//| Check for Open Position                                          |
//+------------------------------------------------------------------+

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

     TradesInThisSymbol = CheckOpenPositions();
     
//+------------------------------------------------------------------+
//| Check if OK to make new trades                                   |
//+------------------------------------------------------------------+

// Only allow 1 trade per Symbol

   if(TradesInThisSymbol > 0) {
     return(0);}

   YesStop = false;
      
   if (UseTradingHours == 1)
   {
     YesStop = CheckTradingTimes();
   
     if (YesStop == true)
     {
       Comment ("Trading has been stopped - wrong time of day");
     }
     else
     {
       Comment ("Trading has resumed - time is OK");
     }
   }
   else
       Comment ("Trading Time Filter not in use");

   if (YesStop == false)
   {
      lotMM = GetLots();
   
	   if(CheckEntryCondition(OP_BUY))
	   {
		   OpenTrade(OP_BUY, lotMM);
		   return(0);
	   }

   
	   if(CheckEntryCondition(OP_SELL))
	   {
		   OpenTrade(OP_SELL, lotMM);
	   }
	}
	
//----
   return(0);
  }

//+------------------------------------------------------------------+
//| Functions beyond this point should not need to be modified       |
//| Eventually will be placed in include file                        |
//+------------------------------------------------------------------+



void OpenTrade(int signal, double myLots)
{  
  int res, ticket, err;
  double TPprice,STprice;

   RefreshRates();
   
   if (signal==OP_BUY) 
   {
      res=OrderSend(Symbol(), OP_BUY, myLots, Ask, Slippage, 0, 0, UserComment, MagicNumber, 0, Green);
      if (res > 0)
      {
         ticket = res;
         OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES);
         if (StopLoss != 0 || TakeProfit != 0)
	      {
            TPprice = 0.0;
            if (TakeProfit > 0) TPprice=TakeLong(OrderOpenPrice(), TakeProfit, myPoint);
            STprice = 0.0;
            if (StopLoss > 0)
            {
              STprice=StopLong(OrderOpenPrice(), StopLoss, myPoint);
		        STprice = ValidStopLoss(Symbol(), OP_BUY,Bid, STprice, myPoint);
		      }   
 // 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 if (signal==OP_SELL) 
   {
      res=OrderSend(Symbol(), OP_SELL, myLots, Bid, Slippage, 0, 0, UserComment, MagicNumber, 0, Red);
      if (res > 0)
      {
         ticket = res;
         OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES);
         if (StopLoss != 0 || TakeProfit != 0)
	      {
            TPprice = 0.0;
            if (TakeProfit > 0) TPprice=TakeShort(OrderOpenPrice(),TakeProfit, myPoint);
            STprice = 0.0;
            if (StopLoss > 0)
            {
              STprice=StopShort(OrderOpenPrice(), StopLoss, myPoint);
		        STprice = ValidStopLoss(Symbol(), OP_SELL,Ask, STprice, myPoint); 
		      }  
 // 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);
		   }
       }
   }
      
   if(res<0)
   {
     err = GetLastError();
     Print("OrderSend failed with error(" + err + ") " + ErrorDescription(err) + " Lots:" + DoubleToStr(myLots, 2) );
   }
   return;
}

//+------------------------------------------------------------------+
//| Check Open Position Controls                                     |
//+------------------------------------------------------------------+
  
int CheckOpenPositions()
{
   int cnt, NumPositions;
   int NumBuyTrades, NumSellTrades;   // Number of buy and sell trades in this symbol
   
   NumBuyTrades = 0;
   NumSellTrades = 0;
   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 )  NumBuyTrades++;
      if(OrderType() == OP_SELL ) NumSellTrades++;
             
     }
     NumPositions = NumBuyTrades + NumSellTrades;
     return (NumPositions);
  }


//+------------------------------------------------------------------+
//| Handle Open Positions                                            |
//| Check if any open positions need to be closed or modified        |
//+------------------------------------------------------------------+
int HandleOpenPositions()
{
   int cnt;
   bool YesClose;
   double pt;
   
   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(),Bid);
          }
          else
          {
//*****************************************************
// This is where the trailing stop function is called
//*****************************************************
            if (UseTrailingStop)
            {
               HandleTrailingStop(OP_BUY,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
            }
          }
      }

      if(OrderType() == OP_SELL)
      {
          if (CheckExitCondition(OP_SELL))
          {
             CloseOrder(OrderTicket(),OrderLots(),Ask);
          }
          else
          {
//*****************************************************
// This is where the trailing stop function is called
//*****************************************************
             if(UseTrailingStop)  
             {                
               HandleTrailingStop(OP_SELL,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
             }
          }
       }
   }
}

//+------------------------------------------------------------------+
//| Close Open Position Controls                                     |
//|  Try to close position 3 times                                   |
//+------------------------------------------------------------------+
void CloseOrder(int ticket,double numLots,double close_price)
{
   int CloseCnt, err;
   
   // try to close 3 Times
      
    CloseCnt = 0;
    while (CloseCnt < 3)
    {
       if (OrderClose(ticket,numLots,close_price,Slippage,Violet))
       {
         CloseCnt = 3;
       }
       else
       {
         err=GetLastError();
         Print(CloseCnt," Error closing order : (", err , ") " + ErrorDescription(err));
         if (err > 0) CloseCnt++;
       }
    }
}

//*****************************************************
// This function is used by the trailing stop function
//*****************************************************
//+------------------------------------------------------------------+
//| Modify Open Position Controls                                    |
//|  Try to modify position 3 times                                  |
//+------------------------------------------------------------------+
void 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++;
       }
    }
}

//+------------------------------------------------------------------+
//| 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      |
//| Possible future types                                            |
//| Type 4 uses 2 for 1, every 2 pip move moves stop 1 pip           |
//| Type 5 uses 3 for 1, every 3 pip move moves stop 1 pip           |
//+------------------------------------------------------------------+
int HandleTrailingStop(int type, int ticket, double op, double os, double tp)
{
    double pt, TS=0, myAsk, myBid;
    
    if (type == OP_BUY)
    {
       myBid = MarketInfo(Symbol(),MODE_BID);
       switch(TrailingStopType)
       {
        case 1: pt = myPoint*StopLoss;
                if(myBid-os > pt) ModifyOrder(ticket,op,myBid-pt,tp, Aqua);
                break;
        case 2: pt = myPoint*TrailingStop;
                if(myBid-op > pt && os < myBid - pt) ModifyOrder(ticket,op,myBid - pt,tp, Aqua);
                break;
        case 3: if (myBid - op > FirstMove * myPoint)
                {
                   TS = op + FirstMove*myPoint - FirstStopLoss * myPoint;
                   if (os < TS)
                   {
                    ModifyOrder(ticket,op,TS,tp, Aqua);
                   }
                }
                 
                if (myBid - op > SecondMove * myPoint)
                {
                   TS = op + SecondMove*myPoint - SecondStopLoss * myPoint;
                   if (os < TS)
                   {
                    ModifyOrder(ticket,op,TS,tp, Aqua);
                   }
                }
                 
                if (myBid - op > ThirdMove * myPoint)
                {
                   TS = myBid  - TrailingStop3*myPoint;
                   if (os < TS)
                   {
                     ModifyOrder(ticket,op,TS,tp, Aqua);
                   }
                }
                break;
       }
       return(0);
    }
       
    if (type ==  OP_SELL)
    {
       myAsk = MarketInfo(Symbol(),MODE_ASK);
       switch(TrailingStopType)
       {
        case 1: pt = myPoint*StopLoss;
                if(os - myAsk > pt) ModifyOrder(ticket,op,myAsk+pt,tp, Aqua);
                break;
        case 2: pt = myPoint*TrailingStop;
                if(op - myAsk > pt && os > myAsk+pt) ModifyOrder(ticket,op,myAsk+pt,tp, Aqua);
                break;
        case 3: if (op - myAsk > FirstMove * myPoint)
                {
                   TS = op - FirstMove * myPoint + FirstStopLoss * myPoint;
                   if (os > TS)
                   {
                    ModifyOrder(ticket,op,TS,tp, Aqua);
                   }
                }
                if (op - myAsk > SecondMove * myPoint)
                {
                   TS = op - SecondMove * myPoint + SecondStopLoss * myPoint;
                   if (os > TS)
                   {
                    ModifyOrder(ticket,op,TS,tp, Aqua);
                   }
                }
                if (op - myAsk > ThirdMove * myPoint)
                {
                  TS = myAsk + TrailingStop3 * myPoint;               
                  if (os > TS)
                  {
                    ModifyOrder(ticket,op,TS,tp, Aqua);
                  }
                }
                break;
       }
    }
    return(0);
}

//+------------------------------------------------------------------+
//| Get number of lots for this trade                                |
//+------------------------------------------------------------------+
double GetLots()
{
   double lot;
   
   if(UseMoneyManagement == true)
   {
     lot = LotsOptimized();
   }
   else
   {
      lot = Lots;
   }

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

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

   return(lot);
}


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

double LotsOptimized()
  {
   double lot=Lots;
//---- select lot size
   lot=NormalizeDouble(MathFloor(AccountFreeMargin()*TradeSizePercent/10000)/10,1);
   
  
  // lot at this point is number of standard lots
  
//  if (Debug) Print ("Lots in LotsOptimized : ",lot);
  
  // Check if mini or standard Account
  
  if(AccountIsMini)
  {
    lot = MathFloor(lot*10)/10;
    
// Use at least 1 mini lot

   if(lot<0.1) lot=0.1;
   if (lot > MaxLots) lot = MaxLots;

  }else
  {
    if (lot < 1.0) lot = 1.0;
    if (lot > MaxLots) lot = MaxLots;
  }

   return(lot);
  }

// Return true if time is not in session for trading
bool CheckOutsideSession( int StartHour, int EndHour, int ct)
{
  if(StartHour<=EndHour)
  {
    if(ct < StartHour || ct > EndHour) return(true) ;
  }
  else
  {
    if(ct > EndHour && ct < StartHour) return(true) ;
  }
  return(false) ;
}

bool CheckTradingTimes()
{
   bool StopTrading;
   int ct;
   ct = Hour() * 100 + Minute();
   
     StopTrading = true;
// Check trading Asian Market
     if (TradeAsianMarket == 1)
     {
        StopTrading = CheckOutsideSession(AsianStart, AsianStop, ct);
     }
     if (StopTrading == true)
     {
// Check trading European Market
       if (TradeEuropeanMarket == 1)
       {
         StopTrading = CheckOutsideSession(EurStart, EurStop, ct);
       }
     }
     if (StopTrading == true)
     {
// Check trading New York Market
       if (TradeNewYorkMarket == 1)
       {
         StopTrading = CheckOutsideSession(NYStart, NYStop, ct);
       }
     }
     
     return(StopTrading);
}

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

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

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

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

double ValidStopLoss(string mySymbol, int type, double price, double SL, double mPoint)
{

   double minstop;
   
   if (SL < 0.1) return(SL);
   
   minstop = MarketInfo(mySymbol,MODE_STOPLEVEL);
   if (type == OP_BUY)
   {
		 if((price - SL) < minstop*mPoint) SL = price - minstop*mPoint;
   }
   if (type == OP_SELL)
   {
       if((SL-price) < minstop*mPoint)  SL = price + minstop*mPoint;  
   }

   return(SL);   
}


//+------------------------------------------------------------------+
//| CheckValidUserInputs                                             |
//| Check if User Inputs are valid for ranges allowed                |
//| return true if invalid input, false otherwise                    |
//| Also display an alert for invalid input                          |
//+------------------------------------------------------------------+
bool CheckValidUserInputs()
{
   if (CheckMAMethod(FastMA_Mode))
   {
     Alert("FastMA_Mode(0 to 4) You entered ",FastMA_Mode);
     return(true);
   }
   if (CheckMAMethod(SlowMA_Mode))
   {
     Alert("SlowMA_Mode(0 to 4) You entered ",SlowMA_Mode);
     return(true);
   }
   if (CheckAppliedPrice(FastMA_AppliedPrice))
   {
     Alert("FastMA_AppliedPrice( 0 to 6) You entered ",FastMA_AppliedPrice);
     return(true);
   }
   if (CheckAppliedPrice(SlowMA_AppliedPrice))
   {
     Alert("SlowMA_AppliedPrice(0 to 6) You entered ",SlowMA_AppliedPrice);
     return(true);
   }

   if (CheckTrailingStopType(TrailingStopType))
   {
     Alert("TrailingStopType( 1 to 3) You entered ",TrailingStopType);
     return(true);
   }
   
}

//+------------------------------------------------+
//| Check for valid Moving Average methods         |
//|  0=sma, 1=ema, 2=smma, 3=lwma , 3=lsma         |
//|  return true if invalid, false if OK           |
//+------------------------------------------------+
bool CheckMAMethod(int method)
{
   if (method < 0) return (true);
   if (method > 4) return (true);
   return(false);
}

//+-----------------------------------------------------+
//| Check for valid Applied Price enumerations          |
//|   0=close, 1=open, 2=high, 3=low, 4=median((h+l/2)) |
//|   5=typical((h+l+c)/3), 6=weighted((h+l+c+c)/4)     |
//|  return true if invalid, false if OK                |
//+-----------------------------------------------------+
bool CheckAppliedPrice(int applied_price)
{
   if (applied_price < 0) return (true);
   if (applied_price > 6) return (true);
   return(false);
}

//+------------------------------------------------+
//| Check for valid TrailingStopType               |
//|  |
//|  return true if invalid, false if OK           |
//+------------------------------------------------+
bool CheckTrailingStopType(int stop_type)
{
   if (stop_type < 0 ) return(true);
   if (stop_type > 3) return(true);
     return(false);

}

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


//+------------------------------------------------------------------+




