RSI_R2_EA_v2.2





//+------------------------------------------------------------------+
//|                                                                  |
//|             RSI-R2.mq4 - Ver 1.0 @ 03/22/2007 by Bluto           |
//|                                                                  |
//|  Changes by Robert Hill                                          |
//|  4/3/2007 added input for RSI_Period                             |
//|           Modified code for MagicNumber calculation              |
//|           Added function to set value for RSI_Period             |
//|           Set value of AssignRSI to false during optimization    |
//|           Use optimized value in function AssignRSI_Period       |
//|           Set value of AssignRSI to true when running live       |
//|  4/5/2007 Fixed bug that caused no more trades after a stoploss  |
//|           added 2 variable to hold pSar values to reduce calls   |
//|           Added GetLots as a function using MM code from start   |
//|  4/6/2007 Combined with RSI_R2_AnyTimeFrame_Optimzable.mq4       |
//|           Made more modular                                      |
//|           Added code for possible MA Angle filter                |
//|           Added 7 Trailing stop functions for testing            |
//|           Combined Bluots open trade code with mine              |
//| 4/15/2007 Added optimized values for RSI period from bluto       |
//|           Added change to moneymanagement from bluto             |
//| 4/16/2007 Added code to check RSI 4 bars back for confirmation   |
//|           Added new exit ideas from Gideon                       |
//|           Both are selectable by input switches.                 |
//| 4/27/2007 Added check to prevent another trade from opening      |
//|           on the same dat a trade is closed                      |
//| 5/6/2007  Added new exit strategies                              |
//|           RSI 14 as described by Loren                           |
//|           My idea to use CCI 50                                  |
//+------------------------------------------------------------------+


#property copyright "Bluto and Robert"
#property link      "None"
#include <stdlib.mqh>

// This makes code easier to read
#define AUDCAD 1
#define AUDJPY 2
#define AUDNZD 3
#define AUDUSD 4
#define CHFJPY 5
#define EURAUD 6
#define EURCAD 7
#define EURCHF 8
#define EURGBP 9
#define EURJPY 10
#define EURUSD 11
#define GBPCHF 12
#define GBPJPY 13
#define GBPUSD 14
#define NZDJPY 15
#define NZDUSD 16
#define USDCAD 17
#define USDCHF 18
#define USDJPY 19
#define UNEXPECTED 999

extern string  Expert_Name    = "---- RSI_R2_EA_v2.1 ----";
//+---------------------------------------------------+
//|Money Management                                   |
//+---------------------------------------------------+
extern double  LotSize=1.0;
extern double  RiskPercent=2.0;
extern bool    UseMoneyMgmt=false;
extern bool    BrokerPermitsFractionalLots = true;

//+---------------------------------------------------+
//|Indicator Variables                                |
//| Change these to try your own system               |
//| or add more if you like                           |
//+---------------------------------------------------+
extern string  mi="--Moving Average settings--";
extern int     MaTrend_Period = 200;

extern string  ri="--RSI settings--";
extern int     RSI_Period = 4;       // input value to be optimized
extern bool    UseDefaultRSI_Period = false;
extern int     BuyWhenRsiBelow = 65;
extern int     SellWhenRsiAbove = 35;
extern double  RSI_Overbought_Value = 75.0; 
extern double  RSI_Oversold_Value = 25.0;
// Added to test confirmation of trend
extern int     useRSI4BarsBack = 0;
extern int     BuyWhenAbove = 55;
extern int     SellWhenBelow = 45;
// Added to test new exit strategy
extern int     useNewExitStrategy = 0;
extern int     RSI_High_OverBought_Exit = 98;
extern int     RSI_Low_OverSold_Exit = 2;
// Added Blutos newest exit using Price close vs SMA 200
extern int     use200SMA_Exit = 1;
extern int     useRSI14_Exit = 1;
extern int     useCCI50_Exit = 1;
extern int     CCI_ExitLevel = 0;

extern string  st1="--Signal_TimeFrame--";
extern int     Signal_TimeFrame = 0;

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

// Added this for possible filter for flat markets
extern string  ai="--Moving Average Angle filter settings--";
extern string  a2=" Set switch to 1 to use filter";
extern int     useMaAngleFilter = 0;
extern int     TrendTimeFrame = 0;
extern double  Threshold=20;
extern int     PrevShift=3;
extern int     CurShift=1;
//+---------------------------------------------------+
//|Profit controls                                    |
//+---------------------------------------------------+
extern string  st6 = "--Profit Controls--";
extern double  StopLoss=0;
extern double  TakeProfit=700;
extern int     Slippage=3;

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 string  tsp4 = " 4 = Breakeven + Lockin";
extern string  tsp5 = " 5 = Step trail";
extern string  tsp6 = " 6 = EMA trail";
extern string  tsp7 = " 7 = pSAR trail";
extern string  tsp8 = " 8 = Blutos pSar trail";
extern bool    UseTrailingStop = true;
extern int     TrailingStopType = 8;

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 = 1;        // 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     EMATimeFrame    =  30;
extern int     Price           =  0;
extern int     EMAPeriod       = 13;
extern int     EMAShift        =  2;    
extern int     InitialStop     =  0;
 
extern string  ts7 = "Settings for Type 7";
extern string  pi="--pSAR settings--";
extern double  StepParabolic = 0.02;
extern double  MaxParabolic  = 0.2;
extern int     Interval      = 5;

extern string  ts8 = "Settings for Type 8";
extern string  pi2="--pSAR settings--";
extern double  SarStep = 0.02;
extern double  SarMax = 0.20;

//+---------------------------------------------------+
//|General controls                                   |
//+---------------------------------------------------+
int            MagicNumber=0;
string         setup;
int            SignalCandle = 1;
int            TradesInThisSymbol = 0;
double         MM_OrderLotSize=0;
datetime       StopTime;                 // Time to wait after a trade is stopped out
bool           StoppedOut=false;

//+---------------------------------------------------+
//|  Indicator values for signals and filters         |
//|  Add or Change to test your system                |
//+---------------------------------------------------+
int            myRSI_Period = 2;     // Used by RSI indicator call
double         RSI_Day_0 = 0, RSI_Day_1=0, RSI_Day_2=0, RSI_Day_3=0, SMA_Day3=0;



int init()
{
/*
   if (Symbol()=="AUDCADm" || Symbol()=="AUDCAD") {MagicNumber=200001;}
   if (Symbol()=="AUDJPYm" || Symbol()=="AUDJPY") {MagicNumber=200002;}
   if (Symbol()=="AUDNZDm" || Symbol()=="AUDNZD") {MagicNumber=200003;}
   if (Symbol()=="AUDUSDm" || Symbol()=="AUDUSD") {MagicNumber=200004;}
   if (Symbol()=="CHFJPYm" || Symbol()=="CHFJPY") {MagicNumber=200005;}
   if (Symbol()=="EURAUDm" || Symbol()=="EURAUD") {MagicNumber=200006;}
   if (Symbol()=="EURCADm" || Symbol()=="EURCAD") {MagicNumber=200007;}
   if (Symbol()=="EURCHFm" || Symbol()=="EURCHF") {MagicNumber=200008;}
   if (Symbol()=="EURGBPm" || Symbol()=="EURGBP") {MagicNumber=200009;}
   if (Symbol()=="EURJPYm" || Symbol()=="EURJPY") {MagicNumber=200010;}
   if (Symbol()=="EURUSDm" || Symbol()=="EURUSD") {MagicNumber=200011;}
   if (Symbol()=="GBPCHFm" || Symbol()=="GBPCHF") {MagicNumber=200012;}   
   if (Symbol()=="GBPJPYm" || Symbol()=="GBPJPY") {MagicNumber=200013;}
   if (Symbol()=="GBPUSDm" || Symbol()=="GBPUSD") {MagicNumber=200014;}
   if (Symbol()=="NZDJPYm" || Symbol()=="NZDJPY") {MagicNumber=200015;}
   if (Symbol()=="NZDUSDm" || Symbol()=="NZDUSD") {MagicNumber=200016;}
   if (Symbol()=="USDCHFm" || Symbol()=="USDCHF") {MagicNumber=200017;}
   if (Symbol()=="USDJPYm" || Symbol()=="USDJPY") {MagicNumber=200018;}
   if (Symbol()=="USDCADm" || Symbol()=="USDCAD") {MagicNumber=200019;}
   if (MagicNumber==0) {MagicNumber = 200999;}  
*/

//   MagicNumber = func_Symbol2Val(Symbol()) + 200000;
	MagicNumber = 200000 + func_Symbol2Val(Symbol())*100 + func_TimeFrame_Const2Val(Period()); 
   setup=Expert_Name + Symbol() + "_" + func_TimeFrame_Val2String(func_TimeFrame_Const2Val(Period()));
   if (UseDefaultRSI_Period)   myRSI_Period = RSI_Period; else myRSI_Period = AssignRSI_Period(Symbol());
    
 return(0);
}

int deinit()
{
 return(0);
}



int AssignRSI_Period(string symbol)
{

   int RSI = 0;
   int which = func_Symbol2Val(symbol);
   
   switch (which)
   {
        case AUDCAD : RSI = 5;
                      break;
        case AUDJPY : RSI = 7;
                      break;
        case AUDNZD : RSI = 6;
                      break;
        case AUDUSD : RSI = 4;
                      break;
        case CHFJPY : RSI = 4;
                      break;
        case EURAUD : RSI = 2;
                      break;
        case EURCAD : RSI = 3;
                      break;
        case EURCHF : RSI = 3;
                      break;
        case EURGBP : RSI = 2;
                      break;
        case EURJPY : RSI = 4;  // Optimized value
                      break;
        case EURUSD : RSI = 4;
                      break;
        case GBPCHF : RSI = 6;
                      break;
        case GBPJPY : RSI = 4;
                      break;
        case GBPUSD : RSI = 3;
                      break;
        case NZDJPY : RSI = 6;
                      break;
        case NZDUSD : RSI = 7;
                      break;
        case USDCAD : RSI = 2;
                      break;
        case USDCHF : RSI = 4;
                      break;
        case USDJPY : RSI = 4;
                      break;
        case UNEXPECTED : RSI = 4;
   }
   if (RSI == 0) RSI = 4;
   return (RSI);
}

//+------------------------------------------------------------------+
//| LastTradeStoppedOut                                              |
//| Check History to see if last trade stopped out                   |
//| Return Time for next trade                                       |
//+------------------------------------------------------------------+
  
//+------------------------------------------------------------------+
//| 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);
}

//===================================================================
//                                                    EMA_Angle.mq4 
//                                                          jpkfox
//
// You can use this indicator to measure when the EMA angle is
// "near zero". AngleTreshold determines when the angle for the
// EMA is "about zero": This is when the value is between
// [-AngleTreshold, AngleTreshold] (or when the histogram is red).
//   EMAPeriod: EMA period 
//   AngleTreshold: The angle value is "about zero" when it is
//     between the values [-AngleTreshold, AngleTreshold].
//   StartEMAShift: The starting point to calculate the 
//     angle. This is a shift value to the left from the
//     observation point. Should be StartEMAShift > EndEMAShift.
//   StartEMAShift: The ending point to calculate the
//     angle. This is a shift value to the left from the
//     observation point. Should be StartEMAShift > EndEMAShift.
//
//  Return 1 for up OK
//  Return -1 for down OK
//  Return 0 for too flat
//===================================================================
double MA_Angle( int iPrevShift, int iCurShift, double fPrevMA, double fCurMA)
{
   double fAngle, mFactor;
   string Sym;
   int ShiftDif;
   
   mFactor = 100000.0;
   Sym = StringSubstr(Symbol(),3,3);
   if (Sym == "JPY") mFactor = 1000.0;
   ShiftDif = iPrevShift-iCurShift;
   mFactor /= ShiftDif; 

    fAngle = mFactor * (fCurMA - fPrevMA)/2.0;

    return(fAngle);
}

bool CheckTrend(int cmd)
{
	double maAngle;
	
   double MACurrent=iMA(Symbol(),TrendTimeFrame,MaTrend_Period, 0, MODE_SMA, PRICE_CLOSE,CurShift);
   double MAPrevious=iMA(Symbol(),TrendTimeFrame,MaTrend_Period, 0, MODE_SMA, PRICE_CLOSE,PrevShift);
	maAngle = MA_Angle(PrevShift, CurShift, MAPrevious, MACurrent);
   switch (cmd)
   {
      case OP_BUY : if (maAngle > Threshold) return(true);
                    break;
      case OP_SELL : if (maAngle < -Threshold) return(true);
   }
   return(false);
}


bool CheckRSI14(int cmd)
{

   double RSIcur, RSIprev;
   
   RSIcur = iRSI(Symbol(),Signal_TimeFrame, 14, PRICE_CLOSE, 1);
   RSIprev = iRSI(Symbol(),Signal_TimeFrame, 14, PRICE_CLOSE, 2);
   
   switch (cmd)
   {
     case OP_BUY  : if (RSIcur < 50 && RSIprev > 50) return(true);
                    break;
     case OP_SELL : if (RSIcur > 50 && RSIprev < 50) return(true);
   }
   
   return(false);
   
   
}

bool CheckCCI50(int cmd)
{
   double CCIcur, CCIprev;
   
   CCIcur = iCCI(Symbol(), Signal_TimeFrame, 50, PRICE_CLOSE, 1);
   CCIprev = iCCI(Symbol(), Signal_TimeFrame, 50, PRICE_CLOSE, 2);
   
   switch (cmd)
   {
     case OP_BUY  : if (CCIcur < 0 && CCIprev > 0) return(true);
                    break;
     case OP_SELL : if (CCIcur > 0 && CCIprev < 0) return(true);
   }
   
   return(false);
   
   
}

//+------------------------------------------------------------------+
//| CheckExitCondition                                               |
//| Uses OP_BUY as cmd to check exit sell                            |
//| Uses OP_SELL as cmd to check exit buy                            |
//| New exit strategy checks current RSI value for high or low       |
//| threshold and for current still less than overbought value       |
//| or greater than oversold value.                                  |
//+------------------------------------------------------------------+
bool CheckExitCondition(int cmd)
{
   double RSI, RSI_Cur;
  
   RSI = iRSI(Symbol(), Signal_TimeFrame, myRSI_Period, PRICE_CLOSE, 1);
   RSI_Cur = iRSI(Symbol(), Signal_TimeFrame, myRSI_Period, PRICE_CLOSE, 0);
   
   switch (cmd)
   {
   case OP_BUY : if (useRSI14_Exit == 1) return (CheckRSI14(cmd));
                 if (useCCI50_Exit == 1) return(CheckCCI50(cmd));
                 
                 // Original Exit Strategies
                 
                 if ( RSI > RSI_Overbought_Value)
                 {
                    if (useNewExitStrategy == 1)
                    {
                       if (RSI_Cur < RSI_Overbought_Value || RSI_Cur >= RSI_High_OverBought_Exit ) return(true); else return(false);
                    }
                    else
                      return(true);
                 }
                 else if (use200SMA_Exit == 1)
                 {
                     if (CheckMA(OP_SELL)) return(true);
                 }
                break;
   case OP_SELL : if (useRSI14_Exit == 1)  return (CheckRSI14(cmd));
                  if (useCCI50_Exit == 1)  return(CheckCCI50(cmd));
                  
                 // Original Exit Strategies
                 
                  if (RSI < RSI_Oversold_Value)
                  {
                    if (useNewExitStrategy == 1)
                    {
                       if (RSI_Cur > RSI_Oversold_Value || RSI_Cur <= RSI_Low_OverSold_Exit ) return(true); else return(false);
                    }
                    else
                      return(true);
                  }
                  else if (use200SMA_Exit == 1)
                  {
                     if (CheckMA(OP_BUY)) return(true);
                  }
   }
   
   return (false);
}

bool CheckMA(int cmd)
{
  SMA_Day3 = iMA(Symbol(),Signal_TimeFrame,MaTrend_Period, 0, MODE_SMA, PRICE_CLOSE, 1);
  switch (cmd)
  {
  case OP_BUY : if (iClose(Symbol(),Signal_TimeFrame,1) > SMA_Day3) return(true);
                break;
  case OP_SELL : if (iClose(Symbol(),Signal_TimeFrame,1) < SMA_Day3) return (true);
  }
  return(false);
}

// Optional check of 4th bar back above 55 for buy
//  or below 45 for sell to confirm trend
bool CheckRSI(int cmd)
{

  RSI_Day_0 = iRSI(Symbol(), Signal_TimeFrame, myRSI_Period, PRICE_CLOSE, 4);
  RSI_Day_1 = iRSI(Symbol(), Signal_TimeFrame, myRSI_Period, PRICE_CLOSE, 3);
  RSI_Day_2 = iRSI(Symbol(), Signal_TimeFrame, myRSI_Period, PRICE_CLOSE, 2);
  RSI_Day_3 = iRSI(Symbol(), Signal_TimeFrame, myRSI_Period, PRICE_CLOSE, 1);
  
  switch (cmd)
  {
  case OP_BUY : if (RSI_Day_1 < BuyWhenRsiBelow && RSI_Day_2 < RSI_Day_1 && RSI_Day_3 < RSI_Day_2)
                {
                   if (useRSI4BarsBack == 1)
                   {
                      if (RSI_Day_0 > BuyWhenAbove) return(true); else return(false);
                   }
                   else
                     return(true);
                }
                break;
                
   
  case OP_SELL : if (RSI_Day_1 > SellWhenRsiAbove && RSI_Day_2 > RSI_Day_1 && RSI_Day_3 > RSI_Day_2)
                 {
                   if (useRSI4BarsBack == 1)
                   {
                      if (RSI_Day_0 < SellWhenBelow) return(true); else return(false);
                   }
                   else
                     return(true);
                 }
  }
  
  return(false);
}


//+------------------------------------------------------------------+
//| CheckEntryCondition                                              |
//+------------------------------------------------------------------+
bool CheckEntryCondition(int cmd)
{
   bool rule1, rule2, rule3;
   

   rule1 = true;
   rule2 = true;
   rule3 = true;
   
   rule1 = CheckMA(cmd);
   if (rule1)
   {
      rule2 = CheckRSI(cmd);
      if(rule2)
      {
        if (useMaAngleFilter == 1) rule3 = CheckTrend(cmd);
        if (rule3) return(true);
      }
      
   }
   return (false);
}
  
int start()
{ 

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

   MM_OrderLotSize = GetLots();        

	if(CheckEntryCondition(OP_BUY))
	{
		   OpenBuyOrder(MM_OrderLotSize, StopLoss,TakeProfit, Slippage, setup, MagicNumber, Green);
		   return(0);
	}

   
	if(CheckEntryCondition(OP_SELL))
	{
         OpenSellOrder(MM_OrderLotSize, StopLoss,TakeProfit, Slippage, setup, MagicNumber, Red);
	}

  return(0);
}

double GetLots()
{
// variables used for money management
double         MM_MinLotSize=0;
double         MM_MaxLotSize=0;
double         MM_LotStep=0;
double         MM_Decimals=0;
int            MM_AcctLeverage=0;
int            MM_CurrencyLotSize=0;

 double OrderLotSize;
 
//----- Money Management & Lot Sizing Stuff.

  MM_AcctLeverage = AccountLeverage();
  MM_MinLotSize = MarketInfo(Symbol(),MODE_MINLOT);
  MM_MaxLotSize = MarketInfo(Symbol(),MODE_MAXLOT);
  MM_LotStep = MarketInfo(Symbol(),MODE_LOTSTEP);
  MM_CurrencyLotSize = MarketInfo(Symbol(),MODE_LOTSIZE);

  if(MM_LotStep == 0.01) {MM_Decimals = 2;}
  if(MM_LotStep == 0.1) {MM_Decimals = 1;}

  if (UseMoneyMgmt == true)
   {
    OrderLotSize = AccountEquity() * (RiskPercent * 0.01) / (MM_CurrencyLotSize / MM_AcctLeverage);
    if(BrokerPermitsFractionalLots == true)
      OrderLotSize = StrToDouble(DoubleToStr(OrderLotSize,MM_Decimals));
    else
      OrderLotSize = MathRound(MM_OrderLotSize);
   }
   else
   {
    OrderLotSize = LotSize;
   }

  if (OrderLotSize < MM_MinLotSize) {OrderLotSize = MM_MinLotSize;}
  if (OrderLotSize > MM_MaxLotSize) {OrderLotSize = MM_MaxLotSize;}
  return(OrderLotSize);
  
}

//+------------------------------------------------------------------+
//| OpenBuyOrder                                                     |
//| If Stop Loss or TakeProfit are used the values are calculated    |
//| for each trade                                                   |
//+------------------------------------------------------------------+
int OpenBuyOrder(double mLots, double mStopLoss, double mTakeProfit, int mSlippage, string mComment, int mMagic, color mColor)
{
   int err,ticket, digits;
   double myPrice, myBid, myStopLoss = 0, myTakeProfit = 0;
   
   myPrice = MarketInfo(Symbol(), MODE_ASK);
   myBid = MarketInfo(Symbol(), MODE_BID);
   myStopLoss = StopLong(myBid,mStopLoss);
   myTakeProfit = TakeLong(myBid,mTakeProfit);
 // Normalize all price / stoploss / takeprofit to the proper # of digits.
   digits = MarketInfo(Symbol( ), MODE_DIGITS) ;
   if (digits > 0) 
   {
     myPrice = NormalizeDouble( myPrice, digits);
     myStopLoss = NormalizeDouble( myStopLoss, digits);
     myTakeProfit = NormalizeDouble( myTakeProfit, digits); 
   }
   ticket=OrderSend(Symbol(),OP_BUY,mLots,myPrice,mSlippage,myStopLoss,myTakeProfit,mComment,mMagic,0,mColor); 
   if (ticket > 0)
   {
    if (OrderSelect( ticket,SELECT_BY_TICKET, MODE_TRADES) ) 
     {
      Print("BUY order opened : ", OrderOpenPrice( ));
//      ModifyOrder(ticket,OrderOpenPrice( ), OrderStopLoss(), myTakeProfit);
     }
   }
   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, double mStopLoss, double mTakeProfit, int mSlippage, string mComment, int mMagic, color mColor)
{
   int err, ticket, digits;
   double myPrice, myAsk, myStopLoss = 0, myTakeProfit = 0;
   
   myPrice = MarketInfo(Symbol( ), MODE_BID);
   myAsk = MarketInfo(Symbol( ), MODE_ASK);
   myStopLoss = StopShort(myAsk,mStopLoss);
   myTakeProfit = TakeShort(myAsk,mTakeProfit);
   
 // Normalize all price / stoploss / takeprofit to the proper # of digits.
   digits = MarketInfo(Symbol( ), MODE_DIGITS) ;
   if (digits > 0) 
   {
     myPrice = NormalizeDouble( myPrice, digits);
     myStopLoss = NormalizeDouble( myStopLoss, digits);
     myTakeProfit = NormalizeDouble( myTakeProfit, digits); 
   }
   ticket=OrderSend(Symbol(),OP_SELL,mLots,myPrice,mSlippage,myStopLoss,myTakeProfit,mComment,mMagic,0,mColor); 
   if (ticket > 0)
   {
     if (OrderSelect( ticket,SELECT_BY_TICKET, MODE_TRADES) ) 
     {
      Print("Sell order opened : ", OrderOpenPrice());
//      ModifyOrder(ticket,OrderOpenPrice( ), OrderStopLoss(), myTakeProfit);
     }
   }
   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 [" + mComment + "]: (" + err + ") " + ErrorDescription(err));
        }
      } 
   }
   
   return(ticket);
}


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

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

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

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

//+------------------------------------------------------------------+
//| 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 (UseTrailingStop)
            {
               HandleTrailingStop(OP_BUY,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
            }
          }
      }

      if(OrderType() == OP_SELL)
      {
          if (CheckExitCondition(OP_SELL))
          {
             CloseOrder(OrderTicket(),OrderLots(),OP_SELL);
          }
          else
          {
            if (UseTrailingStop)
            {
               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)
{
   int CloseCnt, 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);
   // try to close 3 Times
      
    CloseCnt = 0;
    while (CloseCnt < 3)
    {
       if (!OrderClose(ticket,numLots,myPrice,Slippage,Violet))
       {
         err=GetLastError();
         Print(CloseCnt," Error closing order : (", err , ") " + ErrorDescription(err));
         if (err > 0) CloseCnt++;
       }
       else
       {
         CloseCnt = 3;
       }
    }
}

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, pp;
   double newSL;
   
   pp = MarketInfo(Symbol(), MODE_POINT);
   minstop = MarketInfo(Symbol(),MODE_STOPLEVEL);
   newSL = SL;
   if (type == OP_BUY)
   {
		 if((price - SL) < minstop*pp) newSL = price - minstop*pp;
   }
   if (type == OP_SELL)
   {
       if((SL-price) < minstop*pp)  newSL = price + minstop*pp;  
   }

   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                             |
//+------------------------------------------------------------------+
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 : EMA_TrailingStop (type, ticket, op, os, tp);
              break;
	  case 7 : pSAR_TrailingStop (type, ticket, op, os, tp);
              break;
     case 8 : BlutoParabolicSAR (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, pp, BuyStop, SellStop;

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

  pp = MarketInfo(Symbol(), MODE_POINT);
  digits = MarketInfo(Symbol(), MODE_DIGITS) ;
  if (type==OP_BUY)
  {
    pBid = MarketInfo(Symbol(), MODE_BID);
    if ((pBid-op)>eTrailingStop*pp)
    {
      if (os<pBid-(eTrailingStop+eTrailingStep-1)*pp)
      {
        BuyStop = pBid-eTrailingStop*pp;
        if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
		  BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
        if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
        ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
        return;
      }
    }
  }
  if (type==OP_SELL)
  {
    pAsk = MarketInfo(Symbol(), MODE_ASK);
    if (op - pAsk > eTrailingStop*pp)
    {
      if (os > pAsk + (eTrailingStop + eTrailingStep-1)*pp || os==0)
      {
        SellStop = pAsk + eTrailingStop * pp;
        if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
        SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
        if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
        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 |                                      
//+------------------------------------------------------------------+
void EMA_TrailingStop(int type, int ticket, double op, double os, double tp)
{
   int digits;
   double pBid, pAsk, pp, BuyStop, SellStop, ema;

   pp = MarketInfo(Symbol(), MODE_POINT);
   digits = MarketInfo(Symbol(), MODE_DIGITS) ;
   ema = iMA(Symbol(),EMATimeFrame,EMAPeriod,0,MODE_EMA,Price,EMAShift);
   
   if (type==OP_BUY) 
   {
	   BuyStop = ema;
      pBid = MarketInfo(Symbol(),MODE_BID);
		if(os == 0 && InitialStop>0 ) BuyStop = pBid-InitialStop*pp;
		if (digits > 0) BuyStop = NormalizeDouble(SellStop, digits); 
		BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
		if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits);
		Print("MA=",ema," BuyStop=",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*pp;
		if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);
		if (digits > 0) SellStop = NormalizeDouble(SellStop, digits);
      Print("MA=",ema," SellStop=",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, pp, BuyStop, SellStop, spr;
   double sar1, sar2;
  
   pp = MarketInfo(Symbol(), MODE_POINT);
   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*pp;
        if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
	     BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
        if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
        if (os<BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
     }
   }
   if (type==OP_SELL)
   {
     if (sar2 > sar1)
     {
        SellStop = sar1 + Interval * pp + spr;
        if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
	     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
        if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
        if (os>SellStop || os==0) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
     }
   }
}

// Manage Paraolic SAR 
void BlutoParabolicSAR(int type, int ticket, double op, double os, double tp)
{
   double pSar1 = 0, pSar2 = 0;
   int digits;
   double pt, pBid, pAsk, pp, BuyStop, SellStop;

   pp = MarketInfo(Symbol(), MODE_POINT);
   digits = MarketInfo(Symbol( ), MODE_DIGITS);
   
// Added pSar1 and pSar2 for faster backtesting
  pSar1 = iSAR(NULL,Signal_TimeFrame,SarStep,SarMax,1);
  pSar2 = iSAR(NULL,Signal_TimeFrame,SarStep,SarMax,2);

  if (type == OP_BUY)
  {
     pBid = MarketInfo(Symbol(), MODE_BID);
     if ( (pSar1> os) && (pBid > pSar1) && (op < pSar1) && (pSar1 > pSar2))
     {
         if (digits > 0)pSar1 = NormalizeDouble(pSar1, digits); 
         ModifyOrder(ticket,op,pSar1,tp,Blue);
         Print("Order # ",ticket," updated at ",Hour(),":",Minute(),":",Seconds());
         return(0);
     }
   }
   if (type == OP_SELL)
   {
      pAsk = MarketInfo(Symbol(), MODE_ASK);
      if ((pSar1 < os) && (pAsk < pSar1) && (op > pSar1) && (pSar1 < pSar2))
         {
          ModifyOrder(ticket,op,pSar1,tp,Blue);
          Print("Order # ",ticket," updated at ",Hour(),":",Minute(),":",Seconds());
          return(0);
         }
   }
}

//+------------------------------------------------------------------+
//|                                      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, pp, BuyStop, SellStop;

   pp = MarketInfo(Symbol(), MODE_POINT);
   digits = MarketInfo(Symbol(), MODE_DIGITS) ;

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

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

   pp = MarketInfo(Symbol(), MODE_POINT);
   pt = TrailingStop * pp;
   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 (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
     if (pBid-op > pt && os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
	  return;
   }
   if (type==OP_SELL)
   {
     pAsk = MarketInfo(Symbol(), MODE_ASK);
     pt = TrailingStop * pp;
     SellStop = pAsk + pt;
     if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
     if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
     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);
   }
}





}¿¥ûøûñvco½ÿh8ٙ‡»4FÊfJÈ|wÞÞñ.	Øgb¾Þ>)—ú]ïapM–å)UbÃ(¼÷‹¯0è^TC‘ÿݝ”l"»9ìòf-n3ýж0ã«;?6ŸA™tð®P—ÜÞqžh܄.;8ݔZçÅèpC½€ÉïÖä´Ù2¥ç&Rq6sÜsùŸH·â‘LùrD¾)‡¡”ËvêEˆ¶$^lÙIŽsY—­ѹk©aW„é<¨rYìïhª‡¯Ë¨ÊX+cb:¶)ó!­½%¥¸bO©í
câ4¦?yβÅ:‚\¹¹wC2P;1ì›±­UŒ•í(“¸ÔáqØpAÁòö!•ÛGOÈüÃiJT`Àb õšÂ¦›ÙÙmw˲þÐ:º^cå—åÁ“ܹÅÙ)֖†Š›NyÂæüÛßÐ&hqÝÆ	b”Wv½'ý‹›	Êmè1‘Í
Ç¥š¬žJ¢tïŸü¶\cc»¦Šº”Ã9Mbsb{È!ôØJ¾\9!ÛÚøq’(™ï‹lÑÚü9†½nå@¯"ç«|îÈÍS»2eû]h‚’K–^°[¯&Ë¢WS_yjèA¦í-|B2Â	~ßnµ!«#‰iëp?¬[Ô¿âLQ›´J/†Trw6Tž
ÿrõPMUGƒ §8kKC±±XËû~®ÇÇg*ã~î÷ȤrԔÊè®ÙÇïqN—$âqr$k´ß·øځN„èSœ}âz¹ï»ÎÇq)¾øu
ř¹yôÙWKO*ÊZÐßÌ]	_w^ô—¢œyYå&rÆB
ih[’ÓîhNê×i»Á?Л¥š½Œ_À¹¾>óÜÈqᵧy¢ü™TÏx <ÄÂOí)r9´ýÒõó°±ï7hÐ
¿±Ýõ®Ïü]¶Ä­Sœt¡måkò(?7»ÅLüw~ºôoÁèB„h§¸Š1œH"±$€¨!¶dã[3¶Á2z©NL$Øv梲esŽ	öA˜‚ËGfôÞÅÖ±ª.KÑös‰Ì›œúúSѵ·ÔæùŒgïzì¸CU|lþ”øù¥V5f܍Et56"ïÁº¥—ŠC@©SÄ%€2éT‹/GŒh-®oø‚èöÚVÓ³qÏÇÞõq°%ý>ÿ²|KÝ2ðMOýPKð\ I#ÜiZÆ9qF÷‘ãø—<¹WÃñj‡›}=l·h™ÞY^¢­ñ @bjŸÚÏ´¥FX]A³ºWñ`8î|%œêKúÕ6€´Xzø¤¿ÎöŘ<Y—fcéû:ŽÀÉ]Á‘-ã_ʑW!ÁhÇLÓe¹sèm³x)4‘ñ¦~¸{kçǘ£†#¾Np{A.ìcïÝI§‚k8
à>æ|chÎN»"$+DÞ£¦öÛ 2²„)L§¸=78ôoªÈ‡îœ_ÓSÝ@ÎÇ
ÅöC2Ùe\!…dpv–‘CrcÑó(¢5Ìkap°jˆã_cœâò®j]èõŸì™„¢SøÁ¬¡’šš;fØîRŸXÓ¯kj±@‡zW]–?·T5ðúnGúNà-b©WªÛø+tªçÝö“g²|·òåíÒ/ZæQB©§6œú•ôLòÝ\ã*q¤.G0åö5~}ú)lQØzr*WáýËÉ	ž¢§7žèUvy£RzwÕ~;——qMFÜùÝÓ¾‚LlÌBÆêðeT%É?Öú'r!úÜÏ椌=
ì@œ†LäUÕÅd»Õ’kuÝâÚO‡ÆD]hŒâ/mטl¤Óz2û?üÏ°þü?³¤Ñçåjï>@
l4߶t)7„üο2â‘MÃìÎÝQèŠÌŽÊw[ý'3f‹Ǭ‘x@6[ȸ×gŠ't<ˆmα7)b²vìTZÅÉõ£Ÿb|*¹ô
|™ñdJ€°Æc@­ÿÈX„ÙýÀÍ矹­z£:eÿÁúáÌ ­Ê†ÿuyH`ÛÃÍk`½²él®<§AWÄÐO2ÏüÐZFˆÛ–׺Ç!À\	á1þÞۍ}à‘ëʒ‰Píø˜)eæהÖÉd¢
]•²·ž9$¯û[‡²1íûù“×Gï¼Ä.4’-&3;k=ÂÃ
6|-ƒ§cÍãÄqÆBÍ/ͬtC<û
g%y-¶Ëï2Ÿð‡¥reÊõ訓¹wî]‚N†V>€4T¦8bÇ|z?â¹jCº¨F.eL(A£Á݋$êrŒ¥÷8&w³eœyÓ{½b¬
{Cõ`€ÌJŸ§Þ†¥Ç;#¯—éûߓjRYhàØ£/™íó"Õpñ붕£‚ÒKé’5œèYKÏ艘¥É¬Ö)µIgØâ’'¦~CÄ)YG*dŽ–„èh–Ćª@g¼­òÀ²OBˆ’@ƒ,<¹N”ñz99ÙE½šû1ÿÃ@Wù€òQDUǪ̀PYÎ2°ñé/ØØ'Ñßú:OAÚNâïu?F£­W·–cñ~ý~/oç­ÈO–V†ñº^€ÜJ=bì…ë'“dQ*û‡y}•QšZLǬ÷#A>‘xª‡Ç&AgÔÍé5òÅûÕk¦ƒÚ‘)4%ª 4;™„‰ôì¥û’Þ19ý
MŽ“Neˆåd	˜`:]¦/ôV	~òåßâ°bÔ˜^wLô=CËF¡x…Ê« (*R˜Q>z/{á3~¡Ó"ujŸ¸…´‡{¯Ÿ
|ƒä#—|u„WΜ©F^ÒqQb}róº#Uª>(éEcá¤&` ˜Ù[qwÚs_c¯’O\nL7³²+͹ã*óIÍæ€K…²¿6ï¼$K,º|ÏpÞb£Âw|K5¹ŽŸ¶ÕñIw¿0
ï
;cSÃÃåۑÂՋ˜kµe¿~÷ýT+ös0k(ÅßÉe~xÛú'MÙ4`~þ¤×ʮǝë³¥î©Ö\„þÐÎŽÔt…\ÿ%[¹3†Ë\ßú]á¹=^ïB­Æl-ó\	¾¯º•d|–Æ.Þ¼ñø˜?C(Òóc:=ÊSðÉ¸nW¾k§Ðá|äE9z'nNnëÚb-®Ý¸¸‰gM*3Ø:M-5L/©Éõ$.÷ák…pí{#ð˜Óòˆ±lÊÁ;”Ì%ÆL¢8ۛ÷›9œï+vöÞÊx&Ò°¦@xHÜ\¨b9h—),æwÁ¦ێJQm“á×Ö.a.F8®úвnö`øìc™% 01³æ6½[ç}èëØ=r|µýfØ&'¹U”Zn+•ˆúÔ g¬òŠÂä´s÷n‰G˜•c' S÷¤~Â>8!,F¯+\Ï·mÙý힣‚§…±e2ËÖÜd°nâ®ÈauxpkØ=srö«o’S<þÆ>¥ª@yY?¶{œ'Ý.8¹È¶eL•ãÑý¿+Ù
jE›ŠxséÔOv
g‹;¼+¥ö‘#¡^òm¼üÃ)Èøò¦«õ_¾üUhe,ã2<ÌoœgøžýdÙ"žT?”æa¿);cô¡`”äÅ7©[¤«øeWä"نÈe]üSºÜÛêÁ÷ùRÖ߯•$zW¨xŠÔlSQß©¿ñˆ%GÊý흗#O±9˥芿ÈJ©YÄBð|”`k6mòUG]¯«îÉöᧀ) Æódmõ¹Ž«„–ÛsþI)åèðÂ{Ygÿ¼=롒Cl,®óÅ3îÓBþÏù ‡ªD>½\¨ûþzªÖ`(¼«+)ÞœTó´¡Ô±Êîe4ÆD4x¬¥ŽÉþ#y|)åÛ½m½òð€€§u-Îi¾NÙMVkˆ·þïÇ }š¢©"G+u蹈¦•}SýSÒØâpP–É€++Éր®^ölˆŸâp
­çTf(lY…X+Æ_™
Eÿ°Œ¥šÇê\ÄÒø²ÍրN°½«ç½“ÛWîœQp"CÕw8fÙ^h®“Kl?P	é¢5ÔvÛË5—¯å1Õ[–[ZoneTransfer]
ZoneId=4
yÕýŠ6„³.pÇÉÿ·³%i’뙢SŒë܀¿_áÒ㝂¾Ä=Ÿêª@^’›¿cJÕðOû%<)¸Aë›"´ÔcìɆ‚çýîúÇØÔn¼xÕ¢n¿«ÁKY›KŽ8;Yô+…^Õ@kšj¤lên­kõF꼕¹\éØn2Ë&b)zïùʇðƒªsþœª.?yKÈc¿Õ™;Ù®s¡Àì‘H_—‹Ð}ž׏™µÿÞ|çϐëúã#CÿŠß¯E:Fð­ß¨˜pÕD’<"ª|¼Çôë˲y\¸è\«Z0¯RyE£`Ý´Äåâs×`#ÀÊ;Ûê?¶Fƽ€—¨­™¯ÕòwÆ»Ö9îØz‰Ì?wkö3û$¥ŠҔÁ ]qµˆQ›dç‹@îbÛÅ»¾l!O±ÝSUHsUµƒÝåòCçlŠö7¤ åd¥‡6íJOY6›ÂjH“˜ð
v£Uºìȟ¹¹rÐlVnhߓ¹«_|Ú¨rQ%AÄõl6ÙèñTuâ”}7;ðv®cZ¦fUJ*‡„ôÖ­9Á<Àeé^½
;-¬ðá°×ó‘cñ¿q,úE½s¬>Xé.,¼¼ñ”ð,êïm1þ˜Õ?¶'sÐãÎ•(û¾–%×±â—4ÛÓ®WçžÍh+hœïâ2ù	î,Jø|¼g[›g´ZnšƒR ªTìä>ïÕXûKÉxþÄùùkŠû.nÂtN¼«Pi*âUÀS¥ZáèùC•<Ý9–'rŽåÒVb?„?$ÂDß<r¨~žAÏôð%wҌ}7I˜ÍŒv8"›¶y)V€byúü¿£'oâÈy75YŽe†?}²]ðZ–¶Ê>S^]ð·d–õ:ü~éïÇïàèŠâ÷K„¢A·¯ü¿3ëø
Vï`Nìý­ËLÆéÍú¾{þ¯ñ{ƒ'Ê¥§ÿôR\y`»ÃÓDÜ::†þýÅ›Ã+„sߢ4Žpt¡=žÇñ`ÁvÉùKóû*Ä¥îëà°³îqÄñJ¤ƒØÇ1•K /é³áIއ©•¹NFQDK95𝳇*ÿÊr.î#¯ãoùsøKø\9pjÀð•ã	äëk^Z{+Pš k¤iUs¿<»»SüÞ¸7kS÷Šm¸qÄOÆ÷¾ü'ِé£2UzkÌäßTìQ¶éåEöà=개ʻ½Ekg¬†Tñ‘)"ð‘1p
@çš!oG";ì—½½§“¨8ÇNEò4IÎË+Ó£?d“Î+:
uûcÞãs’ßHV8Ðvߛ w_9$rä´§'ïŸéü‹ºƒ¤ÿŸ¨»KѯÆäüÉægϳñ©žOx*3›»1w¼T1Î"þy:½RÉâlãI53
Ö²³C˜*’Ûã?æ®öö‚Xl?_L~s¦j™ÄÿHXliMI6ü`ýîê@ðÜàOç´ÓÁQ)¹yUOŒˆ÷sü&¨o–8cQæX¶ˆæ͒›T±ªR¤	œúÇòé}-Ù¾¡öõV¦R¦äjqovViî
<¬$—t,çT<0sH·‡	×ýœšÎ4醃Ò}ØB"x¹
¡—"î7Jå{{…å}n|IzžžÆ·­¤ìpDAEÉ
ä×Ò‡›;6ف
X0ÞÁ5µºeŠG*”`ò„4‘±z	o8u,m2oÌ©>sŸ×ìñú¿@ø±G¼áÒS„¤ÛoFúX3&HDý¬³q*q`ÆíæL­äý+U*„ü¦LâÔqÎÂy|O?Íÿe^D䣟©–)é†	’zt»¹Ü–ðëe9Ü.6	Þ|p•8 B8y§´âKE4&H[ì:®ƒØ•úíÂVZŸ“·×õ‹l­µ"5‚ÉýLD3ûîӗ|*ñù湌º?’€£ö]åõMhÉÞq:Qð{7NÂI>¹)þ½Éu$O
¼J`Éoëàç}1o!cUàÛ¢4ÿä>q_ã‡Ë[Åïa:‚2÷Ö©$²qDð¥nMԎั™ö;ÔG–4½41çò·3¾†ß(z=ã›ÍÅ46Fʯ³Ç%ÏDŒ ºg¸œªEÙøéI!ò	öT?댵û+®o÷~ñ
½dç‹á¹çége@>ÏË =Ë·o~ùBý¿Ÿ¼u»
yS3ZºôÜ1ïùøë*ô­®L­LýOئ”¬Êl¯Ä×ȶÓÕ*Qƒñ^iÈÖ´'"úæïÎaü?Qq${~uzP–I­x<Í×ÉÚ>.WT0?0‰âÈ'fŒ×'Š¼Ce™[ÀlٞmÀ〪ת•Ÿ°ÖMÞ
¹ËÕù¯LòÅÎ>˓0µ³vފb™†½
ÐâÒ1¼2V<_ô SÙ4#Â¥cû/ÖÚ÷ÁaůýޜþßQóUߦìCñü)”!tx8Yòc”KWC%š°foš–jlkþ£ÿÖÿåÿ‰ý½Ç		{.jÓÁ¡ ÊYB)Bhz«£b`ˆ,Ê5×}n5µüü@÷—¿«,ÐcîïM0^"úÊψ³ý†g35Ì=7íÒì©¢?6û‘ö
N£Ñ³„/ž™8ý/ž…Cã?i2™¸¦Agl•ŠÚÕʜcÞÜfÊç.-¨R¿`ŽI£8ǝ“p¾™8
ßvY9ã·G^üîGù3’›ðÌ7Ì|(
Ôþ²²`h̬“Zr@íø4ŸÞ.õ8õ%cÓòPæ}0é<@€;ϋÈNw•JB‚zód‚Œ¦¥š—£t¯è‚1÷“^9ñ²ÔXÊfrEG
eË¡$셫 ‚ˆ”±Îò%LΣ]¾¬¤=LŸâ9>œ1rø#V„-´ý9ôd6“äÛÕÉG—V0‹ÉÇ$sŠÈÃ$Z|ñ³ëõ˜€3yrF
çÏÊҾ3›ì–S•È=Lî·Øª#ûä2_e.i¡»yûeòß·“Ë›vZÍd	¦m¸^ۚ„T«‡ËÖb=sÜþÎŒšyð§Ö¾;úãýb&ã×£M\ú^ƒ´¦4kü óþà¨þséôË{ùsÆ6w²ë1Î8•Öó?#L˜…5×dƒšU
ü;½Ú+½ú#ÔmwÁ[êàŒac@e•#³ïƒåª”œQ[Œ6ÙÍÍ-7hÖ¬´ƒl}5ü!ÁPYzºò†Å¢¼]ãÆ?Ú؀7ñmˆ{=Îq»Eς5…¢xLx@ãdK{ń˜È2¾HþÊpf'zDA¸ç@FÛ(ÃÊÅT35
:wB˜Š—5òކµm·{-ÇûÞ¦±N!ªuþ’±‰ûËÛ+·Æ—û[Þ!ƒ>Z×k†ÚöùÄ؈*lå†æ?*i¤M2	Äqöáè\„Tf¦qX0y€'‰‡-R¤ ù²ÁC–¹‡>̛˜“æ,¥\Ši LJ>å?¬c}Íês–ŽíÏý–7>)m}š”„„	˜X“i²ï`*AIðw©hoëÓoŒ{òÎ!ÝTÞ®À—O$3÷˜ÜÇxƒíUN-XWf9pöŸI÷Ïñ2mǬ‰
vÑ}¤qþ†<ˆ [¾¹PR‘¶úfþ̔n3Œ¹
Ö}ŸîëY#ø§îjýÈVáæòL|TkyöÒ¦í«¾…c”nm _mhâJ„OŸY7tZ=`™ŽÑ78d+¡0UâŸï–¸ì_O¬È<
|5ÎNöſϗvœü"Óa>˟½©Ø€=AÃL¥=
Ê,îºW%ÙTݽ:öÿ¦]U¨ÂãÍ1
q”sքwüµgòšR[±ñÞãïiô?ÉÈ+­¨ºê,ê²_ͤZ%zúY"Î3UŸ›6qKð¾«ñ»zÎ5»?Œ£"p'üA€ÒeïZâ0ցKoŸ.ªÀҜÅsïC(4åá=WÁ´7{˜““ú
¨L0‚“ðæ®-:ÝQ]ÕåÆ·Gô‚„fJhj±ñ¾¯é•Ý¼Hk%‰¢w‹ÞŸ5)‰<Žu5‚Z+@¿/%	øÑ`Fò6-¾ÿmûY¦Jì:»çE‹m}¸RJ©nýNâ÷a¯ýÕ¸a¾œMԗh>„¹lÖrÛ_]ï"UøíyGÝ[Œ«’¨ä×Lΐ¼5èxÒÄû›}0ýzº?Ǒ`5šgeäý…©Òbûa{Zûsó~T˜V9æ}mœš×4PZñ,Íú´¬w­JtÕ¤Hœ×9itóìŒþt¿`
Š¯ÓûÓ1ïjbÔàø<F“Ø‹ä¯5´÷ãÁ§,͗èܣϧQ|\,O¦}Ó6| FÆìQ%%ªð5½Od?“î~Êl­¯’/Z0â~|ÑíԀqVf©Cy×Jâê3·ˆç`°'­Ð^ë4ÿ=BwK«>âŒ¶…#:+UåÂøUÎè§%êÇÂ
ºpuGRáìf¡òMà
ƒi~î涘~ÆÔâĪ “œ±`8
Çš Bé±dIq·p]h´ÅêåºF”˱°:v„UüøŽ~эÜbLÑ+‹œ¢Å¿‰vŽñ/¬Úãíø{ë€@ŒJ`êiº'ŠnR-Ö|¤V ¢úϼ¦vú†šLIþ­'˜3ÁÁÑÕ¢ÞNbŽè=½fu.Þ/̀æ4²D/÷L¿iÊ6Ù­Hæ­Z©Lí^'q
bÏÚɤFÚ/»7ŠÃ–ç<^„)\
[‚ý²Åéüy:àáŠ~ð”K



Sample





Analysis



Market Information Used:

Series array that contains close prices for each bar


Indicator Curves created:


Indicators Used:

Moving average indicator
Relative strength index
Commodity channel index
Parabolic Stop and Reverse system


Custom Indicators Used:

Order Management characteristics:

It automatically opens orders when conditions are reached
Checks for the total of open orders
It Closes Orders by itself
It can change open orders parameters, due to possible stepping strategy

Other Features: