//+------------------------------------------------------------------+
//|                                                    The Beast.mq4 |
//|                                  Copyright © 2010, Steve Hopwood |
//|                              http://www.hopwood3.freeserve.co.uk |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, Steve Hopwood"
#property link      "http://www.hopwood3.freeserve.co.uk"
#property copyright "Copyright © 2009, Steve Hopwood"
#property link      "http://www.hopwood3.freeserve.co.uk"
#include <WinUser32.mqh>
#include <stdlib.mqh>
#define  NL    "\n"
#define  GvPrefix "macman "
#define  breakevenlinename "Break even line"
#define  reentrylinename "Re entry line"
#define  takeprofitlinename "Take profit line"
#define  up "Market is trending up"
#define  down "Market is trending down"
#define  ranging "Market is ranging"

//From iExposure
#define SYMBOLS_MAX 1024
#define DEALS          0
#define BUY_LOTS       1
#define BUY_PRICE      2
#define SELL_LOTS      3
#define SELL_PRICE     4
#define NET_LOTS       5
#define PROFIT         6

/*
ChicagoRob's pairs: eurusd - usdjpy - gbpusd - audusd - eurjpy - usdcad - nzdusd - audjpy

void DisplayUserFeedback()
void GetSixths()
void CalculateTrades()
bool IsTradingAllowed()
bool DoesTradeExist(double price)
bool SendSingleTrade(int type, string comment, double lotsize, double price, double stop, double take, int magic)
double CalculateStop(double price, int type)
void LookForTradeClosure()
void CloseAllTrades()
void CountPendingTrades()
void DrawTakeProfitLine(int type)

----Re-entry line----
void AddReEntryLine(double price)
void CalculateReEntryLinePips()

----Recovery----
void RecoveryModule()
void CountOpenTrades()
void CheckRecoveryTakeProfit()
int Analyze()
int SymbolsIndex(string SymbolName)


----Trade management module----
void TradeManagementModule()
void BreakEvenStopLoss()
bool CheckForHiddenStopLossHit(int type, int iPipsAboveVisual, double stop )
void JumpingStopLoss() 
void HiddenTakeProfit()
void HiddenStopLoss()
void TrailingStopLoss()
bool CleanUp()

----Hedging----
void HedgingModule()
bool IsTradeAlreadyHedged(int ticket)
double GetRsi(int tf, int period, int shift)

*/
extern string  bce="----BarCount experiments----";
extern bool    UseDailyCandles=true;
extern int     NoOfDays=7;
extern bool    UseWeeklyCandles=false;
extern int     NoOfWeeks=2;
extern bool    UseMonthlyCandles=false;
extern int     NoOfMonths=1;
//extern int     BarCount=0;
extern string  gen="----General inputs----";
extern bool    StopTrading=false;
extern bool    TradeLong=true;
extern bool    TradeShort=true;
extern int     MaxTradesAllowed=5;
extern bool    Primary_trades=true;
extern bool    Secondary_trades=true;
//extern int   Max_secondary_trades=1;
//extern int   Delay_between_trades=10;
extern double  Primary_trade_Lot_size=0.03;
extern double  Secondary_trade_Lot_size=0.01;
extern string  Primary_trade_comment="";
extern string  Secondary_trade_comment="";
extern int     MinPipsFromLastEntry=50;
extern int     PipsBufferFromTradeLine=10;
extern string  tpi="----Take profit----";
extern bool    UseTplTp=false;
extern color   TakeProfitLineColour=Blue;
extern string  rec="----Recovery----";
extern bool    UseRecovery=true;
extern int     Start_Recovery_at_trades=2;  //DC
extern bool    Use1.1.3.3Recovery=false;
extern bool    Use1.1.2.4Recovery=true;
extern color   ReEntryLineColour=Yellow;
extern color   BreakEvenLineColour=Aqua;
extern int     ReEntryLinePips=0;
extern int     RecoveryBreakEvenProfitPips=10;
extern string  sli="----Stop loss----";
extern bool    UseStopLoss=false;
extern int     StopLoss=0;
extern string  tmm="----Trade management module----";
extern bool    DoNotOverload5DigitCriminals=false;
extern string  BE="Break even settings";
extern bool    BreakEven=true;
extern int     BreakEvenPips=40;
extern int     BreakEvenProfit=30;
extern bool    HideBreakEvenStop=false;
extern int     PipsAwayFromVisualBE=5;
extern string  JSL="Jumping stop loss settings";
extern bool    JumpingStop=true;
extern int     JumpingStopPips=30;
extern bool    AddBEP=false;
extern bool    JumpAfterBreakevenOnly=true;
extern bool    HideJumpingStop=false;
extern int     PipsAwayFromVisualJS=10;
extern string  TSL="Trailing stop loss settings";
extern bool    TrailingStop=false;
extern int     TrailingStopPips=50;
extern bool    HideTrailingStop=false;
extern int     PipsAwayFromVisualTS=10;
extern bool    TrailAfterBreakevenOnly=false;
extern bool    StopTrailAtPipsProfit=false;
extern int     StopTrailPips=0;
extern string  hsl1="Hidden stop loss settings";
extern bool    HideStopLossEnabled=false;
extern int     HiddenStopLossPips=20;
extern string  htp="Hidden take profit settings";
extern bool    HideTakeProfitEnabled=false;
extern int     HiddenTakeProfitPips=20;
extern string  hed="----Hedging----";
extern bool    UseHedging=true;
extern int     HedgeAtLossPips=500;
extern double  HedgeLotsMiltiplier=2;
extern string  tt="----Trading hours----";
extern string  Trade_Hours= "Set Morning & Evening Hours";
extern string  Trade_Hoursi= "Use 24 hour, local time clock";
extern string  Trade_Hours_M= "Morning Hours 0-12";
extern  int    start_hourm = 0;
extern  int    end_hourm = 12;
extern string  Trade_Hours_E= "Evening Hours 12-24";
extern  int    start_houre = 12;
extern  int    end_houre = 24;
extern string  mis="----Odds and ends----";
extern bool    ShowManagementAlerts=true;
extern int     DisplayGapSize=30;

//6ths variable.
double         BottomGoldLine;//Bottom, gold line
double         BottomGreenLine;//Bottom, green line
double         MiddleWhiteLine;//Middle, white line
double         TopGreenLine;//Top, green line
double         TopGoldLine;//Top, gold line

bool           ForcePendingTradeDeletion, ForceAllTradeDeletion;
int            OldBars, OpenTrades, PrevOpenTrades, PendingTradesTotal, PrimaryTrades, SecondaryTrades,
               PendingPrimary, PendingSecondary, Old5Bars;
string         GvName, Gap, ScreenMessage;
double         TpLinePrice1;
int            TpLinePipsFromWhite=10;

double         TradeNumber;  //DC to use with recovery module
double         BasketUpl;//Fopr keeping track of the upl of whether a group of trades should be in Recovery
double         MostRecentTradePrice;//For making sure new trades are sent a min pips distance from an existing open trade
double         RsiVal;
string         trend;
bool           HedgingInProgress;

//Recovery
bool           RecoveryInProgress, TpMoved;
string ExtSymbols[SYMBOLS_MAX];
int    ExtSymbolsTotal=0;
double ExtSymbolsSummaries[SYMBOLS_MAX][7];
int    ExtLines=-1;
string ExtCols[8]={"Symbol",
                   "Deals",
                   "Buy lots",
                   "Buy price",
                   "Sell lots",
                   "Sell price",
                   "Net lots",
                   "Profit"};
int    ExtShifts[8]={ 10, 80, 130, 180, 260, 310, 390, 460 };
int    ExtVertShift=14;
double buy_price=0.0;
double sell_price=0.0;

void DisplayUserFeedback()
{
   
   if (IsTesting() && !IsVisualMode()) return;

   ScreenMessage = "";
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
   //Code for time to bar-end display from Candle Time by Nick Bilak
   double i;
   int m,s,k;
   m=Time[0]+Period()*60-CurTime();
   i=m/60.0;
   s=m%60;
   m=(m-m%60)/60;
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, m + " minutes " + s + " seconds left to bar end", NL);

      
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);      
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Primary_trade_Lot_size: ", Primary_trade_Lot_size, NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Secondary_trade_Lot_size: ", Secondary_trade_Lot_size, NL);
   if (TradeLong == true) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading long ", NL);
   if (TradeShort == true) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading short ", NL);
   //ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Magic number: ", MagicNumber, NL);
   //ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trade comment: ", TradeComment, NL);
   //if (CriminalIsECN) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "CriminalIsECN = true", NL);
   //else ScreenMessage = StringConcatenate(ScreenMessage,Gap, "CriminalIsECN = false", NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Criminal's minimum lot size: ", MarketInfo(Symbol(), MODE_MINLOT), NL, NL );
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading hours", NL);
   if (start_hourm == 0 && end_hourm == 12 && start_houre && end_houre == 24) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "            24H trading", NL);
   else
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "            start_hourm: ", DoubleToStr(start_hourm, 2), 
                      ": end_hourm: ", DoubleToStr(end_hourm, 2), NL);
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "            end_houre: ", DoubleToStr(start_hourm, 2), 
                      ": end_houre: ", DoubleToStr(end_hourm, 2), NL);
                      
   }//else

   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
   //ScreenMessage = StringConcatenate(ScreenMessage,Gap, "BarCount = ", BarCount, NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Recovery starts at ", Start_Recovery_at_trades, " filled Primary trades", NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "ReEntryLinePips = ", ReEntryLinePips, NL);
   if (StopTrading) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trading suspended", NL);

   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
   if (BreakEven)
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Breakeven is set to ", BreakEvenPips, " with BreakEvenProfit = ", BreakEvenProfit, NL);
   }//if (BreakEven)
   
   if (JumpingStop)
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Jumping stop is set to ", JumpingStopPips);
      if (AddBEP) ScreenMessage = StringConcatenate(ScreenMessage,": BreakEvenProfit = ", BreakEvenProfit);
      if (JumpAfterBreakevenOnly) ScreenMessage = StringConcatenate(ScreenMessage, ": JumpAfterBreakevenOnly = true");
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);   
   }//if (JumpingStop)
   
   if (BreakEven)
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trailing stop is set to ", TrailingStopPips, " pips", NL);
   }//if (BreakEven)

   if (UseHedging)
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Hedging is enabled ", " with HedgeAtLossPips = ", HedgeAtLossPips, ": HedgeLotsMiltiplier = ", HedgeLotsMiltiplier, NL);
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Rsi D1 trend: ", trend, ": Val = ", RsiVal, NL);
   }//if (UseHedging)

//extern bool    UseHedging=false;
//extern int     HedgeAtLossPips=500;
//extern double  HedgeLotsMiltiplier=2;

   Comment(ScreenMessage);


}//void DisplayUserFeedback()




//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
//----

   
   //ReEntryLinePips is calculated using Atr during GetSixths(). I keep this code in case we change our minds
   if (ReEntryLinePips == 0)
   {
      //Reset ReEntryLinePips according to pair volatility. My thanks to Max for this
      if (StringSubstr(Symbol(), 0, 6) == "AUDCAD") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "AUDCHF") { ReEntryLinePips =180;}
      if (StringSubstr(Symbol(), 0, 6) == "AUDJPY") { ReEntryLinePips =180;}
      if (StringSubstr(Symbol(), 0, 6) == "AUDNZD") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "AUDUSD") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "CADCHF") { ReEntryLinePips =180;}
      if (StringSubstr(Symbol(), 0, 6) == "CADJPY") { ReEntryLinePips =200;}
      if (StringSubstr(Symbol(), 0, 6) == "CHFJPY") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "EURAUD") { ReEntryLinePips =200;}
      if (StringSubstr(Symbol(), 0, 6) == "EURCAD") { ReEntryLinePips =200;}
      if (StringSubstr(Symbol(), 0, 6) == "EURCHF") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "EURGBP") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "EURJPY") { ReEntryLinePips =200;}
      if (StringSubstr(Symbol(), 0, 6) == "EURNZD") { ReEntryLinePips =250;}
      if (StringSubstr(Symbol(), 0, 6) == "EURUSD") { ReEntryLinePips =180;}
      if (StringSubstr(Symbol(), 0, 6) == "GBPCHF") { ReEntryLinePips =200;}
      if (StringSubstr(Symbol(), 0, 6) == "GBPJPY") { ReEntryLinePips =250;}
      if (StringSubstr(Symbol(), 0, 6) == "GBPUSD") { ReEntryLinePips =200;}
      if (StringSubstr(Symbol(), 0, 6) == "NZDJPY") { ReEntryLinePips =180;}
      if (StringSubstr(Symbol(), 0, 6) == "NZDUSD") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "SGDJPY") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "USDCHF") { ReEntryLinePips =180;}
      if (StringSubstr(Symbol(), 0, 6) == "USDCAD") { ReEntryLinePips =150;}
      if (StringSubstr(Symbol(), 0, 6) == "USDJPY") { ReEntryLinePips =180;}
      if (StringSubstr(Symbol(), 0, 6) == "USDNOK") { ReEntryLinePips =1500;}
      if (StringSubstr(Symbol(), 0, 6) == "USDSEK") { ReEntryLinePips =1500;}
   }//if (ReEntryLinePips == 0)
   
   //In case this is a symbol not in the list
   if (ReEntryLinePips == 0) ReEntryLinePips = 200;
   
   
   double multiplier;
   if(Digits == 2 || Digits == 4) multiplier = 1;
   if(Digits == 3 || Digits == 5) multiplier = 10;
   if(Digits == 6) multiplier = 100;   
   if(Digits == 7) multiplier = 1000;   
 
   TpLinePipsFromWhite*= multiplier;
   StopLoss*= multiplier;
   RecoveryBreakEvenProfitPips*= multiplier;
   ReEntryLinePips*= multiplier;
   PipsBufferFromTradeLine*= multiplier;
   MinPipsFromLastEntry*= multiplier;
   BreakEvenPips*= multiplier;
   BreakEvenProfit*= multiplier;
   PipsAwayFromVisualBE*= multiplier;
   JumpingStopPips*= multiplier;
   PipsAwayFromVisualJS*= multiplier;
   TrailingStopPips*= multiplier;
   PipsAwayFromVisualTS*= multiplier;
   StopTrailPips*= multiplier;
   HiddenStopLossPips*= multiplier;
   HiddenTakeProfitPips*= multiplier;
   HedgeAtLossPips*= multiplier;
   
   /*
   if (BarCount == 0)
   {
      //Set up the BarCount. H1 TF first. Default barcount set at 170
      //From scoobs
      //BarCount = NormalizeDouble((iATR(NULL,1440 ,200,0)/MarketInfo(Symbol(),MODE_POINT))/10,0);

      
      if (StringSubstr(Symbol(), 0, 6) == "AUDCAD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "AUDCHF") { BarCount = 210; }
      if (StringSubstr(Symbol(), 0, 6) == "AUDJPY") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "AUDNZD") { BarCount = 20; }
      if (StringSubstr(Symbol(), 0, 6) == "AUDSGD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "AUDUSD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "CADCHF") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "CADJPY") { BarCount = 180; }
      if (StringSubstr(Symbol(), 0, 6) == "CHFJPY") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "CHFSGD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "EURAUD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "EURCAD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "EURCHF") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "EURGBP") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "EURJPY") { BarCount = 180; }
      if (StringSubstr(Symbol(), 0, 6) == "EURNZD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "EURSGD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "EURUSD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "GBPAUD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "GBPCAD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "GBPCHF") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "GBPJPY") { BarCount = 180; }
      if (StringSubstr(Symbol(), 0, 6) == "GBPUSD") { BarCount = 155; }
      if (StringSubstr(Symbol(), 0, 6) == "NZDCAD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "NZDCHF") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "NZDJPY") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "NZDUSD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "SGDJPY") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "USDCAD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "USDCHF") { BarCount = 180; }
      if (StringSubstr(Symbol(), 0, 6) == "USDHKD") { BarCount = 170; }
      if (StringSubstr(Symbol(), 0, 6) == "USDJPY") { BarCount = 180; }
      if (StringSubstr(Symbol(), 0, 6) == "USDSGD") { BarCount = 170; }
      
      
      //Now accommodate different time frames
      multiplier = 1;
      if (Period() == PERIOD_M1) multiplier = 60;
      if (Period() == PERIOD_M5) multiplier = 12;
      if (Period() == PERIOD_M15) multiplier = 4;
      if (Period() == PERIOD_M30) multiplier = 2;
      if (Period() == PERIOD_H1) multiplier = 1;
      if (Period() == PERIOD_H4) multiplier = 0.25;
      if (Period() == PERIOD_D1) multiplier = 0.25 / 6;
   
      double dBarCount = BarCount;
      //dBarCount*= multiplier;
      //BarCount = dBarCount;   
      
      //Andy's formula
      BarCount = MathRound(dBarCount/Period()*60);
      
    }//if (BarCount == 0)
    */ 

   Gap="";
   if (DisplayGapSize >0)
   {
      for (int cc=0; cc< DisplayGapSize; cc++)
      {
         Gap = StringConcatenate(Gap, " ");
      }   
   }//if (DisplayGapSize >0)
   

   
   
   Comment("..................Waiting for the first tick");
   
   OldBars = Bars;
   Old5Bars = iBars(NULL, PERIOD_M5);//For 'mopping up' operations

   GvName = GvPrefix + Symbol();
   PrevOpenTrades = GlobalVariableGet(GvName);
   if (ObjectFind(takeprofitlinename) == 0 && ObjectGet(takeprofitlinename, OBJPROP_COLOR) == Gray) TpLinePrice1 = ObjectGet(takeprofitlinename, OBJPROP_PRICE1);
      
   start();
   
//----
   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
{
//----
   Comment("");
//----
   return(0);
}

void GetSixths()
{

   double ctgl = TopGoldLine;
   double cbgl = BottomGoldLine;
   
   

   /*
   extern bool    UseDailyCandles=true;
   extern int     NoOfDays=5;
   extern bool    UseWeeklyCandles=false;
   extern int     NoOfWeeks=2;
   extern bool    UseMonthlyCandles=false;
   extern int     NoOfMonths=1;

   int            DailyBarCount, Weekly4BarCount, MonthHiLo;
   */   

   int period, count;
   if (UseDailyCandles)
   {
      period = PERIOD_D1;
      count = NoOfDays;      
   }//if (UseDailyCandles)
   
   if (UseWeeklyCandles)
   {
      period = PERIOD_W1;
      count = NoOfWeeks;      
   }//if (UseWeeklyCandles)
   
   if (UseMonthlyCandles)
   {
      period = PERIOD_MN1;
      count = NoOfMonths;      
   }//if (UseWeeklyCandles)
   

   
   
   double low = 1000000, high = 0;
   for (int cc = 1; cc <= count; cc++)
   {
      if (iHigh(NULL, period, cc) > high) high = iHigh(NULL, period, cc);
      if (iLow(NULL, period, cc) < low) low = iLow(NULL, period, cc);
   }//for (int cc = 1: cc <= count; cc++)
   
   double value = high - low;
     
   
   double sixth = value/6;
   double valueS = (value*(MathPow(10,Digits)));
   double sixthS = (sixth*(MathPow(10,Digits)));
   
   BottomGoldLine = NormalizeDouble(low+sixth, Digits);
   BottomGreenLine = NormalizeDouble(low+sixth+sixth, Digits);
   MiddleWhiteLine = NormalizeDouble(low+sixth+sixth+sixth, Digits);
   TopGreenLine = NormalizeDouble(low+sixth+sixth+sixth+sixth, Digits);
   TopGoldLine = NormalizeDouble(low+sixth+sixth+sixth+sixth+sixth, Digits);

   if(ctgl != TopGoldLine || cbgl != BottomGoldLine) ForcePendingTradeDeletion = true;

   //Calculate ReEntryLinePips
   //if (ReEntryLinePips == 0) CalculateReEntryLinePips();


   
   if (!IsTesting() && !IsVisualMode() ) 
   {
      //Draw the lines
      double tl = ObjectGet("fivesixth", OBJPROP_PRICE1);
      double bl = ObjectGet("onesixth", OBJPROP_PRICE1);
      
      if(tl != TopGoldLine || bl != BottomGoldLine) 
      {
         if (ObjectFind("onesixth") == -1)
         {
            ObjectCreate("onesixth",1,0,TimeCurrent(),BottomGoldLine);
            ObjectSet("onesixth",OBJPROP_COLOR,Gold);
            ObjectSet("onesixth",OBJPROP_STYLE,STYLE_SOLID);
            ObjectSet("onesixth",OBJPROP_WIDTH,2);     
         }//if (ObjectFind("onesixth") == -1)
         else ObjectMove("onesixth",0,TimeCurrent(),BottomGoldLine);
      
         if (ObjectFind("twosixth") == -1)
         {
            ObjectCreate("twosixth",1,0,TimeCurrent(),BottomGreenLine);
            ObjectSet("twosixth",OBJPROP_COLOR,Green);
            ObjectSet("twosixth",OBJPROP_STYLE,STYLE_SOLID);
            ObjectSet("twosixth",OBJPROP_WIDTH,2);    
         }//if (ObjectFind(
         else ObjectMove("twosixth",0,TimeCurrent(),BottomGreenLine);

         if (ObjectFind("threesixth") == -1)
         {
            ObjectCreate("threesixth",1,0,TimeCurrent(),MiddleWhiteLine);
            ObjectSet("threesixth",OBJPROP_COLOR,White);
            ObjectSet("threesixth",OBJPROP_STYLE,STYLE_SOLID);
            ObjectSet("threesixth",OBJPROP_WIDTH,2);
         }//if (ObjectFind(
         else ObjectMove("threesixth",0,TimeCurrent(),MiddleWhiteLine);
      
         if (ObjectFind("foursixth") == -1)
         {
            ObjectCreate("foursixth",1,0,TimeCurrent(),TopGreenLine);
            ObjectSet("foursixth",OBJPROP_COLOR,Green);
            ObjectSet("foursixth",OBJPROP_STYLE,STYLE_SOLID);
            ObjectSet("foursixth",OBJPROP_WIDTH,2);
         }//if (ObjectFind(
         else ObjectMove("foursixth",0,TimeCurrent(),TopGreenLine);
      
         if (ObjectFind("fivesixth") == -1)
         {
            ObjectCreate("fivesixth",1,0,TimeCurrent(),TopGoldLine);
            ObjectSet("fivesixth",OBJPROP_COLOR,Gold);
            ObjectSet("fivesixth",OBJPROP_STYLE,STYLE_SOLID);
            ObjectSet("fivesixth",OBJPROP_WIDTH,2);
         }//if (ObjectFind(
         else ObjectMove("fivesixth",0,TimeCurrent(),TopGoldLine);

      }//if(ctgl != TopGoldLine || cbgl != BottomGoldLine) 
      
   }//if (!IsTesting() && !IsVisualMode() ) 
          
}//void GetSixths()

////////////////////////////////////////////////////////////////////////////////////////////////
//TRADE MANAGEMENT MODULE
/*
bool CleanUp()
{

   bool success = true, result = true;
   int cc;

   //Alert(PendingSecondary);

   //Close orphaned secondaries
   if (PendingSecondary > 0 && PendingPrimary == 0 && PrimaryTrades == 0)
   {
      for (cc = OrdersTotal() - 1; cc >= 0; cc--)
      {
         if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
         if (OrderSymbol() == Symbol() )
         {
            result = OrderDelete(OrderTicket() );
            Sleep(1000);
            if (result) cc++;
            if (!result) return(false);
         }//if (OrderSymbol() == Symbol() )         
      }//for (cc = orderstotal() - 1; cc >= 0; cc--)
   }//if (PendingSecondary > 0 && PendingPrimary == 0 && PrimaryTrades == 0)
   
   //Delete duplicate primary trades
   if (PendingPrimary > 1)
   {
      bool PrimaryFound;
      for (cc = OrdersTotal() - 1; cc >= 0; cc--)
      {
         if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
         if (OrderSymbol() == Symbol()  && OrderLots() == Primary_trade_Lot_size)
         {
            if (!PrimaryFound)
            {
               PrimaryFound = true;
               cc--;
               if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
            }//if (!PrimaryFound)
            if (PrimaryFound)
            {
               result = OrderDelete(OrderTicket() );
               Sleep(1000);
               if (result) 
               {
                  cc++; 
                  PendingPrimary--;
                  if (PendingPrimary == 1) break;
               }//if (result) 
               if (!result) return(false);
            }//if (PrimaryFound)
               
         }//if (OrderSymbol() == Symbol() )         
      }//for (cc = orderstotal() - 1; cc >= 0; cc--)   
   }//if (PendingPrimary > 1)
   
   //Delete duplicate secondary trades
   if (PendingSecondary > 1)
   {
      bool SecondaryFound;
      for (cc = OrdersTotal() - 1; cc >= 0; cc--)
      {
         if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
         if (OrderSymbol() == Symbol()  && OrderLots() == Secondary_trade_Lot_size)
         {
            if (!SecondaryFound)
            {
               SecondaryFound = true;
               cc--;
               if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
            }//if (!SecondaryFound)
            if (SecondaryFound)
            {
               result = OrderDelete(OrderTicket() );
               Sleep(1000);
               if (result) 
               {
                  cc++; 
                  PendingSecondary--;
                  if (PendingSecondary == 1) break;
               }//if (result) 
               if (!result) return(false);
            }//if (SecondaryFound)
               
         }//if (OrderSymbol() == Symbol() )         
      }//for (cc = orderstotal() - 1; cc >= 0; cc--)   
   }//if (PendingSecondary > 1)
   
   
   return(success);

}//bool CleanUp()
*/
bool CleanUp()
{

   bool success = true, result = true;
   int cc;

   //Alert(PendingSecondary);

   //Close orphaned secondaries
   if (PendingSecondary > 0 && PendingPrimary == 0 && PrimaryTrades == 0)
   {
      for (cc = OrdersTotal() - 1; cc >= 0; cc--)
      {
         if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
         if (OrderSymbol() == Symbol() && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP))
         {
            result = OrderDelete(OrderTicket() );
            Sleep(1000);
            if (result) cc++;
            if (!result) return(false);
         }//if (OrderSymbol() == Symbol() )         
      }//for (cc = orderstotal() - 1; cc >= 0; cc--)
   }//if (PendingSecondary > 0 && PendingPrimary == 0 && PrimaryTrades == 0)
   
   //Delete duplicate primary trades
   if (PendingPrimary > 1)
   {
      bool PrimaryFound;
      for (cc = OrdersTotal() - 1; cc >= 0; cc--)
      {
         if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
         if (OrderSymbol() == Symbol()  && OrderLots() == Primary_trade_Lot_size && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP))
         {
            if (!PrimaryFound)
            {
               PrimaryFound = true;
               cc--;
               if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
            }//if (!PrimaryFound)
            if (PrimaryFound)
            {
               result = OrderDelete(OrderTicket() );
               Sleep(1000);
               if (result) 
               {
                  cc++; 
                  PendingPrimary--;
                  if (PendingPrimary == 1) break;
               }//if (result) 
               if (!result) return(false);
            }//if (PrimaryFound)
               
         }//if (OrderSymbol() == Symbol() )         
      }//for (cc = orderstotal() - 1; cc >= 0; cc--)   
   }//if (PendingPrimary > 1)
   
   //Delete duplicate secondary trades
   if (PendingSecondary > 1)
   {
      bool SecondaryFound;
      for (cc = OrdersTotal() - 1; cc >= 0; cc--)
      {
         if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
         if (OrderSymbol() == Symbol()  && OrderLots() == Secondary_trade_Lot_size && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP))
         {
            if (!SecondaryFound)
            {
               SecondaryFound = true;
               cc--;
               if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
            }//if (!SecondaryFound)
            if (SecondaryFound)
            {
               result = OrderDelete(OrderTicket() );
               Sleep(1000);
               if (result) 
               {
                  cc++; 
                  PendingSecondary--;
                  if (PendingSecondary == 1) break;
               }//if (result) 
               if (!result) return(false);
            }//if (SecondaryFound)
               
         }//if (OrderSymbol() == Symbol() )         
      }//for (cc = orderstotal() - 1; cc >= 0; cc--)   
   }//if (PendingSecondary > 1)
   
   
   return(success);

}//End bool CleanUp()



bool CheckForHiddenStopLossHit(int type, int iPipsAboveVisual, double stop )
{
   //Reusable code that can be called by any of the stop loss manipulation routines except HiddenStopLoss().
   //Checks to see if the market has hit the hidden sl and attempts to close the trade if so. 
   //Returns true if trade closure is successful, else returns false
   
   
   //Check buy trade
   if (type == OP_BUY)
   {
      double sl = NormalizeDouble(stop + (iPipsAboveVisual * Point), Digits);
      if (Bid <= sl)
      {
         bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5000, CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());      
         }//if (result)
         else
         {
            int err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//else
      }//if (Bid <= sl)  
   }//if (type = OP_BUY)
   
   //Check buy trade
   if (type == OP_SELL)
   {
      sl = NormalizeDouble(stop - (iPipsAboveVisual * Point), Digits);
      if (Ask >= sl)
      {
         result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5000, CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());      
         }//if (result)
         else
         {
            err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//else
      }//if (Ask >= sl)  
   }//if (type = OP_SELL)
   

}//End bool CheckForHiddenStopLossHit(int type, int iPipsAboveVisual, double stop )


void BreakEvenStopLoss() // Move stop loss to breakeven
{

   //Check hidden BE for trade closure
   if (HideBreakEvenStop)
   {
      bool TradeClosed = CheckForHiddenStopLossHit(OrderType(), PipsAwayFromVisualBE, OrderStopLoss() );
      if (TradeClosed) return;//Trade has closed, so nothing else to do
   }//if (HideBreakEvenStop)


   bool result;

   if (OrderType()==OP_BUY)
   {
      if (Ask >= OrderOpenPrice() + (Point*BreakEvenPips) && 
          OrderStopLoss()<OrderOpenPrice())
      {
         result = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()+(BreakEvenProfit*Point), Digits),OrderTakeProfit(),0,CLR_NONE);
         if (result && ShowManagementAlerts==true) Alert("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
         Print("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
         if (!result)
         {
            int err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//if !result && ShowManagementAlerts)      
         //if (PartCloseEnabled && OrderLots() > Preserve_Lots)// Only try to do this if the jump stop worked
         //{
         //   bool PartCloseSuccess = PartCloseTradeFunction();
         //   if (!PartCloseSuccess) SetAGlobalTicketVariable();
         //}//if (PartCloseEnabled && OrderLots() > Preserve_Lots)
      }//if (Ask >= OrderOpenPrice() 
   } //if (OrderType()==OP_BUY)              			         
    
   if (OrderType()==OP_SELL)
   {
     if (Bid <= OrderOpenPrice() - (Point*BreakEvenPips) &&
        (OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0)) 
      {
         result = OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(OrderOpenPrice()-(BreakEvenProfit*Point), Digits),OrderTakeProfit(),0,CLR_NONE);
         if (result && ShowManagementAlerts==true) Alert("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
         Print("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
         if (!result && ShowManagementAlerts)
         {
            err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Setting of breakeven SL ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//if !result && ShowManagementAlerts)      
        //if (PartCloseEnabled && OrderLots() > Preserve_Lots)// Only try to do this if the jump stop worked
        // {
        //    PartCloseSuccess = PartCloseTradeFunction();
        //    if (!PartCloseSuccess) SetAGlobalTicketVariable();
        // }//if (PartCloseEnabled && OrderLots() > Preserve_Lots)
      }//if (Bid <= OrderOpenPrice() 
   }//if (OrderType()==OP_SELL)
      

} // End BreakevenStopLoss sub

void JumpingStopLoss() 
{
   // Jump sl by pips and at intervals chosen by user .
   // Also carry out partial closure if the user requires this

   // Abort the routine if JumpAfterBreakevenOnly is set to true and be sl is not yet set
   if (JumpAfterBreakevenOnly && OrderType()==OP_BUY)
   {
      if(OrderStopLoss()<OrderOpenPrice()) return(0);
   }
  
   if (JumpAfterBreakevenOnly && OrderType()==OP_SELL)
   {
      if(OrderStopLoss()>OrderOpenPrice() || OrderStopLoss() == 0) return(0);
   }
  
   double sl=OrderStopLoss(); //Stop loss

   if (OrderType()==OP_BUY)
   {
      //Check hidden js for trade closure
      if (HideJumpingStop)
      {
         bool TradeClosed = CheckForHiddenStopLossHit(OP_BUY, PipsAwayFromVisualJS, OrderStopLoss() );
         if (TradeClosed) return;//Trade has closed, so nothing else to do
      }//if (HideJumpingStop)
      
      // First check if sl needs setting to breakeven
      if (sl==0 || sl<OrderOpenPrice())
      {
         if (Ask >= OrderOpenPrice() + (JumpingStopPips*Point))
         {
            sl=OrderOpenPrice();
            if (AddBEP==true) sl=sl+(BreakEvenProfit*Point); // If user wants to add a profit to the break even
            bool result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
            if (result)
            {
               if (ShowManagementAlerts==true) Alert("Jumping stop set at breakeven ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
               Print("Jumping stop set at breakeven: ", OrderSymbol(), ": SL ", sl, ": Ask ", Bid);
               //if (PartCloseEnabled && OrderLots() > Preserve_Lots)// Only try to do this if the jump stop worked
               //{
                  //bool PartCloseSuccess = PartCloseTradeFunction();
                  //if (!PartCloseSuccess) SetAGlobalTicketVariable();
               //}//if (PartCloseEnabled && OrderLots() > Preserve_Lots)
            }//if (result)
            if (!result)
            {
               int err=GetLastError();
               if (ShowManagementAlerts) Alert(OrderSymbol(), "Ticket ", OrderTicket(), " buy trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
               Print(OrderSymbol(), " buy trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
            }//if (!result)
             
            return(0);
         }//if (Ask >= OrderOpenPrice() + (JumpingStopPips*Point))
      } //close if (sl==0 || sl<OrderOpenPrice()

  
      // Increment sl by sl + JumpingStopPips.
      // This will happen when market price >= (sl + JumpingStopPips)
      if (Bid>= sl + ((JumpingStopPips*2)*Point) && sl>= OrderOpenPrice())      
      {
         sl=sl+(JumpingStopPips*Point);
         result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Jumping stop set at ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
            Print("Jumping stop set: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
            //if (PartCloseEnabled && OrderLots() > Preserve_Lots)// Only try to do this if the jump stop worked
            //{
               //PartCloseSuccess = PartCloseTradeFunction();
               //if (!PartCloseSuccess) SetAGlobalTicketVariable();
            //}//if (PartCloseEnabled && OrderLots() > Preserve_Lots)
         }//if (result)
         if (!result)
         {
            err=GetLastError();
            if (ShowManagementAlerts) Alert(OrderSymbol(), " buy trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
            Print(OrderSymbol(), " buy trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
         }//if (!result)
             
      }// if (Bid>= sl + (JumpingStopPips*Point) && sl>= OrderOpenPrice())      
   }//if (OrderType()==OP_BUY)
   
   if (OrderType()==OP_SELL)
   {
      //Check hidden js for trade closure
      if (HideJumpingStop)
      {
         TradeClosed = CheckForHiddenStopLossHit(OP_SELL, PipsAwayFromVisualJS, OrderStopLoss() );
         if (TradeClosed) return;//Trade has closed, so nothing else to do
      }//if (HideJumpingStop)
            
      // First check if sl needs setting to breakeven
      if (sl==0 || sl>OrderOpenPrice())
      {
         if (Ask <= OrderOpenPrice() - (JumpingStopPips*Point))
         {
            sl = OrderOpenPrice();
            if (AddBEP==true) sl=sl-(BreakEvenProfit*Point); // If user wants to add a profit to the break even
            result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
            if (result)
            {
               //if (PartCloseEnabled && OrderLots() > Preserve_Lots)// Only try to do this if the jump stop worked
               //{
                 // PartCloseSuccess = PartCloseTradeFunction();
                  //if (!PartCloseSuccess) SetAGlobalTicketVariable();
               //}//if (PartCloseEnabled && OrderLots() > Preserve_Lots)
            }//if (result)
            if (!result)
            {
               err=GetLastError();
               if (ShowManagementAlerts) Alert(OrderSymbol(), " sell trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
               Print(OrderSymbol(), " sell trade. Jumping stop function failed to set SL at breakeven, with error(",err,"): ",ErrorDescription(err));
            }//if (!result)
             
            return(0);
         }//if (Ask <= OrderOpenPrice() - (JumpingStopPips*Point))
      } // if (sl==0 || sl>OrderOpenPrice()
   
      // Decrement sl by sl - JumpingStopPips.
      // This will happen when market price <= (sl - JumpingStopPips)
      if (Bid<= sl - ((JumpingStopPips*2)*Point) && sl<= OrderOpenPrice())      
      {
         sl=sl-(JumpingStopPips*Point);
         result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Jumping stop set at ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
            Print("Jumping stop set: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
            //if (PartCloseEnabled && OrderLots() > Preserve_Lots)// Only try to do this if the jump stop worked
            //{
              // PartCloseSuccess = PartCloseTradeFunction();
               //if (!PartCloseSuccess) SetAGlobalTicketVariable();
            //}//if (PartCloseEnabled && OrderLots() > Preserve_Lots)
         }//if (result)          
         if (!result)
         {
            err=GetLastError();
            if (ShowManagementAlerts) Alert(OrderSymbol(), " sell trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
            Print(OrderSymbol(), " sell trade. Jumping stop function failed with error(",err,"): ",ErrorDescription(err));
         }//if (!result)

      }// close if (Bid>= sl + (JumpingStopPips*Point) && sl>= OrderOpenPrice())         
   }//if (OrderType()==OP_SELL)

} //End of JumpingStopLoss sub

void HiddenStopLoss()
{
   //Called from ManageTrade if HideStopLossEnabled = true


   //Should the order close because the stop has been passed?
   //Buy trade
   if (OrderType() == OP_BUY)
   {
      double sl = NormalizeDouble(OrderOpenPrice() - (HiddenStopLossPips * Point), Digits);
      if (Bid <= sl)
      {
         bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());      
         }//if (result)
         else
         {
            int err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//else
      }//if (Bid <= sl)      
   }//if (OrderType() == OP_BUY)
   
   //Sell trade
   if (OrderType() == OP_SELL)
   {
      sl = NormalizeDouble(OrderOpenPrice() + (HiddenStopLossPips * Point), Digits);
      if (Ask >= sl)
      {
         result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());      
         }//if (result)
         else
         {
            err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Stop loss hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//else
      }//if (Ask >= sl)   
   }//if (OrderType() == OP_SELL)
   

}//End void HiddenStopLoss()

void HiddenTakeProfit()
{
   //Called from ManageTrade if HideStopLossEnabled = true


   //Should the order close because the stop has been passed?
   //Buy trade
   if (OrderType() == OP_BUY)
   {
      double tp = NormalizeDouble(OrderOpenPrice() + (HiddenTakeProfitPips * Point), Digits);
      if (Bid >= tp)
      {
         bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());      
         }//if (result)
         else
         {
            int err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//else
      }//if (Ask >= tp)      
   }//if (OrderType() == OP_BUY)
   
   //Sell trade
   if (OrderType() == OP_SELL)
   {
      tp = NormalizeDouble(OrderOpenPrice() - (HiddenTakeProfitPips * Point), Digits);
      if (Ask <= tp)
      {
         result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5, CLR_NONE);
         if (result)
         {
            if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket());      
         }//if (result)
         else
         {
            err=GetLastError();
            if (ShowManagementAlerts==true) Alert("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
            Print("Take profit hit. Close of ", OrderSymbol(), " ticket no ", OrderTicket()," failed with error (",err,"): ",ErrorDescription(err));
         }//else
      }//if (Bid <= tp)   
   }//if (OrderType() == OP_SELL)
   

}//End void HiddenTakeProfit()

void TrailingStopLoss()
{
      if (TrailAfterBreakevenOnly && OrderType()==OP_BUY)
      {
         if(OrderStopLoss()<OrderOpenPrice()) return(0);
      }
     
      if (TrailAfterBreakevenOnly && OrderType()==OP_SELL)
      {
         if(OrderStopLoss()>OrderOpenPrice()) return(0);
      }
     
   
   
   bool result;
   double sl=OrderStopLoss(); //Stop loss
   double BuyStop=0, SellStop=0;
   
   if (OrderType()==OP_BUY) 
      {
         if (HideTrailingStop)
         {
            bool TradeClosed = CheckForHiddenStopLossHit(OP_BUY, PipsAwayFromVisualTS, OrderStopLoss() );
            if (TradeClosed) return;//Trade has closed, so nothing else to do
         }//if (HideJumpingStop)
		   
		   if (Bid >= OrderOpenPrice() + (TrailingStopPips*Point))
		   {
		       if (OrderStopLoss() == 0) sl = OrderOpenPrice();
		       if (Bid > sl +  (TrailingStopPips*Point))
		       {
		          sl= Bid - (TrailingStopPips*Point);
		          // Exit routine if user has chosen StopTrailAtPipsProfit and
		          // sl is past the profit Point already
		          if (StopTrailAtPipsProfit && sl>= OrderOpenPrice() + (StopTrailPips*Point)) return;
		          result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
               if (result)
               {
                  Print("Trailing stop updated: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
               }//if (result) 
               else
               {
                  int err=GetLastError();
                  Print(OrderSymbol(), " order modify failed with error(",err,"): ",ErrorDescription(err));
               }//else
   
		       }//if (Bid > sl +  (TrailingStopPips*Point))
		   }//if (Bid >= OrderOpenPrice() + (TrailingStopPips*Point))
      }//if (OrderType()==OP_BUY) 

      if (OrderType()==OP_SELL) 
      {
		   if (Ask <= OrderOpenPrice() - (TrailingStopPips*Point))
		   {
             if (HideTrailingStop)
             {
                TradeClosed = CheckForHiddenStopLossHit(OP_SELL, PipsAwayFromVisualTS, OrderStopLoss() );
                if (TradeClosed) return;//Trade has closed, so nothing else to do
             }//if (HideJumpingStop)
		   
		       if (OrderStopLoss() == 0) sl = OrderOpenPrice();
		       if (Ask < sl -  (TrailingStopPips*Point))
		       {
	               sl= Ask + (TrailingStopPips*Point);
  	               // Exit routine if user has chosen StopTrailAtPipsProfit and
		            // sl is past the profit Point already
		            if (StopTrailAtPipsProfit && sl<= OrderOpenPrice() - (StopTrailPips*Point)) return;
		            result = OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
                  if (result)
                  {
                     Print("Trailing stop updated: ", OrderSymbol(), ": SL ", sl, ": Bid ", Bid);
                  }//if (result)
                  else
                  {
                     err=GetLastError();
                     Print(OrderSymbol(), " order modify failed with error(",err,"): ",ErrorDescription(err));
                  }//else
    
		       }//if (Ask < sl -  (TrailingStopPips*Point))
		   }//if (Ask <= OrderOpenPrice() - (TrailingStopPips*Point))
      }//if (OrderType()==OP_SELL) 

      
} // End of TrailingStopLoss sub


void TradeManagementModule()
{

   // Call the working subroutines one by one. 

   //Cut down 5 digit order modify calls for 5 digit crims, if required
   static int NoOfTicks = 9;
   int ndigits = MarketInfo(Symbol(), MODE_DIGITS);
   if (DoNotOverload5DigitCriminals && ( ndigits == 3 || ndigits == 5) )
   {
      NoOfTicks++;
   }//if (DoNotOverload5DigitCriminals && ( digits == 3 || digits == 5) )
   
   if (!DoNotOverload5DigitCriminals || ndigits == 2 || ndigits == 4)
   {
      NoOfTicks = 10;
   }//if (!DoNotOverload5DigitCriminals || digits == 2 || digits == 4)
   
   
   // Global variable to pick up on failed part-closes
   //if (GlobalVariablesTotal()>0) GlobalVariablesExist=true;
   //if (GlobalVariablesExist && GlobalVariablesTotal()>0) TryPartCloseAgain();
   //if (GlobalVariablesExist && GlobalVariablesTotal()==0) GlobalVariablesExist=false;
   
   if (NoOfTicks >= 10)
   {
      NoOfTicks = 0;//Reset the counter
      
      // Hidden stop loss
      if (HideStopLossEnabled) HiddenStopLoss();
   
      // Hidden take profit
      if (HideTakeProfitEnabled) HiddenTakeProfit();
   
      // Breakeven
      if(BreakEven) BreakEvenStopLoss();
   
      // JumpingStop
      if(JumpingStop) JumpingStopLoss();
   
      //TrailingStop
      if(TrailingStop) TrailingStopLoss();

   }//if (NoOfTicks >= 10)
   

}//void TradeManagementModule()
//END TRADE MANAGEMENT MODULE
////////////////////////////////////////////////////////////////////////////////////////////////



bool DoesTradeExist(double price)
{

   if (OrdersTotal() == 0) return(false);
   string sPrice = DoubleToStr(price, Digits);
         
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;

      string sOpen = DoubleToStr(OrderOpenPrice(), Digits);

      if (sPrice == sOpen)
      {
         return(true);
      }//if (OrderOpenPrice() == price && OrderSymbol() == Symbol() )
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)

   return(false);

}//End bool DoesTradeExist(double price)

bool SendSingleTrade(int type, string comment, double lotsize, double price, double stop, double take, int magic)
{  

   int slippage = 10;
   if (Digits == 3 || Digits == 5) slippage = 100;
   
   color col = Red;
   if (type == OP_BUY || type == OP_BUYSTOP) col = Green;
   
   int expiry = 0;
   //if (SendPendingTrades) expiry = TimeCurrent() + (PendingExpiryMinutes * 60);
   
   
   int ticket = OrderSend(Symbol(),type, lotsize, price, slippage, stop, take, comment, magic, expiry, col);
   if (ticket < 0)
   {
      string stype;
      if (type == OP_BUY) stype = "OP_BUY";
      if (type == OP_BUYSTOP) stype = "OP_BUYSTOP";
      if (type == OP_SELL) stype = "OP_SELL";
      if (type == OP_SELLSTOP) stype = "OP_SELLSTOP";
      int err=GetLastError();
      //Alert(Symbol(), " ", stype,"  order send failed with error(",err,"): ",ErrorDescription(err));
      Print(Symbol(), " ", stype,"  order send failed with error(",err,"): ",ErrorDescription(err));
      return(false);
   }//if (ticket < 0)  
   
   //Got this far, so trade send succeeded
   Sleep(120000);
   
   
   return(true);
   
}//End bool SendSingleTrade(int type, string comment, double lotsize, double price, double stop, double take)

bool IsTradingAllowed()
{
   
   
   //Trades count
   if (OpenTrades + PendingTradesTotal >= MaxTradesAllowed) return(false);
   
   //This is possibly redundant, gut I include it as a check anyhow
   if (Bid <= TopGoldLine && Ask >= BottomGoldLine) return(false);
   
   
   //Min distance from most recently filled trade
   if (MostRecentTradePrice != 0)
   {
      double MinDistance = MinPipsFromLastEntry * Point;
      
      //Possible short trade
      if (Bid > TopGoldLine)
      {
         if (TopGoldLine - MostRecentTradePrice < MinDistance) return(false);
      }//if (Bid > TopGldLine)
      
      
      //Possible long trade
      if (Ask < BottomGoldLine)
      {
         if (MostRecentTradePrice - BottomGoldLine < MinDistance) return(false);
      }//if (Ask < BottomGoldLine)
      
   }//if (MostRecentTradePrice != 0)
   

   return(true);


}//End bool IsTradingAllowed()
/*
void CalculateReEntryLinePips()
{
   //From THV ATR Pips and adapted here
   //double stopLoss = MathCeil(pipMult * multiplier * (iATR(NULL,0,periods,i)));
   ReEntryLinePips = MathCeil(iATR(NULL, 0, BarCount, 0) * 9 * 10000);
   
   //Adapt to x digit crims
   int multiplier;
   if(Digits == 2 || Digits == 4) multiplier = 1;
   if(Digits == 3 || Digits == 5) multiplier = 10;
   if(Digits == 6) multiplier = 100;   
   if(Digits == 7) multiplier = 1000;   
 
   ReEntryLinePips*= multiplier;
   
}//void CalculateReEntryLinePips()
*/

void DrawTakeProfitLine(int type)
{
   double price;
   
   if (type == OP_BUY) price = NormalizeDouble(MiddleWhiteLine + (TpLinePipsFromWhite * Point), Digits);
   if (type == OP_SELL) price = NormalizeDouble(MiddleWhiteLine - (TpLinePipsFromWhite * Point), Digits);
   
   ObjectCreate(takeprofitlinename,OBJ_HLINE,0,TimeCurrent(), price );
   ObjectSet(takeprofitlinename,OBJPROP_COLOR,Gray);
   ObjectSet(takeprofitlinename,OBJPROP_STYLE,STYLE_SOLID);
   ObjectSet(takeprofitlinename,OBJPROP_WIDTH,2);
   
   TpLinePrice1 = price;

}//End void DrawTakeProfitLine(int type)


double CalculateStop(double price, int type)
{

   double sl;
   double AtrVal = iATR(NULL, 0, 20, 0) * 3;
   
   if (type == OP_BUY)
   {
      if (StopLoss > 0) sl = NormalizeDouble(price - (StopLoss * Point), Digits);
      if (StopLoss == 0) sl = NormalizeDouble(price - AtrVal, Digits);
   }//if (type == OP_BUY)
   

   if (type == OP_SELL)
   {
      if (StopLoss > 0) sl = NormalizeDouble(price + (StopLoss * Point), Digits);
      if (StopLoss == 0) sl = NormalizeDouble(price + AtrVal, Digits);
   }//if (type == OP_SELL)
   
   return(sl);
   
}//End double CalculateStop(double price, int type)

void CalculateTrades()
{
   double target;

   bool TradingAllowed = IsTradingAllowed();
   if (!TradingAllowed) return;

//extern bool    Use1.1.3.3Recovery=false;
//extern bool    Use1.1.2.4Recovery=true;

  
   double SendLots = Primary_trade_Lot_size;
   //Using 1.1.2.4 recovery
   if (RecoveryInProgress)
   {
      if (PrimaryTrades == 2) 
      {
         SendLots = Primary_trade_Lot_size * 2;         
         if (Use1.1.3.3Recovery) SendLots = Primary_trade_Lot_size * 3;
      }//if (PrimaryTrades == 2) 
      
      if (PrimaryTrades == 3) 
      {
         SendLots = Primary_trade_Lot_size * 4;
         if (Use1.1.3.3Recovery) SendLots = Primary_trade_Lot_size * 3;
      }//if (PrimaryTrades == 3) 
      
      if (PrimaryTrades == 4) return;//No further trading is possible
      
      double RecoveryLineVal = ObjectGet(reentrylinename, OBJPROP_PRICE1);
   }//if (RecoveryInProgress)
   
   double stop;
               
   //Primary sell
   target = NormalizeDouble(TopGoldLine + (PipsBufferFromTradeLine * Point), Digits);
   if (Bid >= target && Primary_trades && TradeShort)
   {
      if (RecoveryInProgress && TopGoldLine < RecoveryLineVal) return;
      if (!DoesTradeExist(TopGoldLine) ) 
      {
         if (UseStopLoss) stop = CalculateStop(TopGoldLine, OP_SELL);
         bool result = SendSingleTrade(OP_SELLSTOP, Primary_trade_comment, SendLots, TopGoldLine, stop, 0, 0);
         if (result && !RecoveryInProgress && UseTplTp) DrawTakeProfitLine(OP_SELL);
      }//if (!DoesTradeExist(TopGoldLine) ) 
      
      if (result) AddReEntryLine(NormalizeDouble(Bid + (ReEntryLinePips * Point), Digits) );      
      if (DoesTradeExist(TopGreenLine) ) return;
      if (!DoesTradeExist(TopGreenLine) && Secondary_trades && !RecoveryInProgress) 
      {
         if (UseStopLoss) stop = CalculateStop(TopGreenLine, OP_SELL);         
         SendSingleTrade(OP_SELLSTOP, Secondary_trade_comment, Secondary_trade_Lot_size, TopGreenLine, stop, 0, 0);
      }//if (!DoesTradeExist(TopGreenLine) && Secondary_trades && !RecoveryInProgress) 
      
   }//if (Bid > TopGoldLine && Primary_trades)
   
   //Secondary sell
   target = NormalizeDouble(TopGreenLine + (PipsBufferFromTradeLine * Point), Digits);
   if (Bid <= TopGoldLine && Bid > target && Secondary_trades && TradeShort)
   {
      if (!DoesTradeExist(TopGreenLine)  && !RecoveryInProgress) 
      {
         if (UseStopLoss) stop = CalculateStop(TopGreenLine, OP_SELL);
         SendSingleTrade(OP_SELLSTOP, Secondary_trade_comment, Secondary_trade_Lot_size, TopGreenLine, stop, 0, 0);
      }//if (!DoesTradeExist(TopGreenLine)  && !RecoveryInProgress) 
      
   }//if (Bid <= TopGoldLine && Bid > TopGreenLine && Secondary_trades)
   

   //Primary buy
   target = NormalizeDouble(BottomGoldLine - (PipsBufferFromTradeLine * Point), Digits);
   if (Ask <= target && Primary_trades && TradeLong)
   {
      if (RecoveryInProgress && BottomGoldLine > RecoveryLineVal) return;
      if (!DoesTradeExist(BottomGoldLine) ) 
      {
         if (UseStopLoss) stop = CalculateStop(BottomGoldLine, OP_BUY);         
         result = SendSingleTrade(OP_BUYSTOP, Primary_trade_comment, SendLots, BottomGoldLine, stop, 0, 0);
         if (result && !RecoveryInProgress && UseTplTp) DrawTakeProfitLine(OP_BUY);
      }//if (!DoesTradeExist(BottomGoldLine) ) 
      
      if (result) AddReEntryLine(NormalizeDouble(Ask - (ReEntryLinePips * Point), Digits) );
      if (DoesTradeExist(BottomGreenLine) ) return;
      if (!DoesTradeExist(BottomGreenLine)  && Secondary_trades && !RecoveryInProgress) 
      {
         if (UseStopLoss) stop = CalculateStop(BottomGreenLine, OP_BUY);         
         SendSingleTrade(OP_BUYSTOP, Secondary_trade_comment, Secondary_trade_Lot_size, BottomGreenLine, stop, 0, 0);
      }//if (!DoesTradeExist(BottomGreenLine)  && Secondary_trades && !RecoveryInProgress) 
   }//if (Bid > TopGoldLine && Primary_trades)
   
   //Secondary buy
   target = NormalizeDouble(BottomGreenLine - (PipsBufferFromTradeLine * Point), Digits);
   if (Ask <= target && Ask >= BottomGoldLine && Secondary_trades && TradeLong)
   {
      if (!DoesTradeExist(BottomGreenLine)  && !RecoveryInProgress) 
      {
         if (UseStopLoss) stop = CalculateStop(BottomGreenLine, OP_BUY);         
         SendSingleTrade(OP_BUYSTOP, Secondary_trade_comment, Secondary_trade_Lot_size, BottomGreenLine, stop, 0, 0);
      }//if (!DoesTradeExist(BottomGreenLine)  && !RecoveryInProgress) 
   }//if (Bid <= TopGoldLine && Bid > TopGreenLine && Secondary_trades)
   

}//End void CalculateTrades()

void DeletePendingTrades()
{
   ForcePendingTradeDeletion = false;
   
   if (OrdersTotal() == 0) return;
   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() && (OrderComment() == Primary_trade_comment || OrderComment() == Secondary_trade_comment) 
          && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP) )
      {
         bool result = OrderDelete(OrderTicket() );
         if (result) {cc++; ObjectDelete(reentrylinename); }
         if (!result) ForcePendingTradeDeletion = true;
      }//if (OrderSymbol() == Symbol() && (OrderComment() == Primary_trade_comment || OrderComment() == Secondary_trade_comment) 
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)


}//void DeletePendingTrades()

void CloseAllTrades()
{
   ForceAllTradeDeletion = false;
   
   if (OrdersTotal() == 0) return;
   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() )
      {
         if (OrderType() == OP_BUY || OrderType() == OP_SELL) bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 1000, CLR_NONE);
         if (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP) result = OrderDelete(OrderTicket() );
         if (result) cc++;
         if (!result) ForceAllTradeDeletion = true;
      }//if (OrderSymbol() == Symbol() )
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)


}//End void CloseAllTrades()


void LookForTradeClosure()
{
   ForceAllTradeDeletion = false;
   if (UseTplTp) return;//Take profit line
   
   if (OrdersTotal() == 0) return;
   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() )
      {
         if (OrderType() == OP_SELL && Bid <= MiddleWhiteLine)
         {
            CloseAllTrades();
         }//if (OrderType == OP_SELL && Bid < MiddleWhiteLine)
         
         if (OrderType() == OP_BUY && Ask >= MiddleWhiteLine)
         {
            CloseAllTrades();
         }//if (OrderType == OP_SELL && Bid < MiddleWhiteLine)
         
      }//if (OrderSymbol() == Symbol() )     
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)


}//End void LookForTradeClosure()
   
void CountOpenTrades()
{
   OpenTrades = 0;
   BasketUpl = 0;
   PrimaryTrades = 0;
   bool BuyOpen, SellOpen;
   
   if (OrdersTotal() == 0) return;
   
   for (int cc = 0; cc <= OrdersTotal(); cc++)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() )
      {
         if (OrderProfit() > 0 && ObjectFind(breakevenlinename) == -1 && !RecoveryInProgress && !HedgingInProgress) TradeManagementModule();
         if (OrderType() == OP_BUY || OrderType() == OP_SELL) 
         {
            if (OrderType() == OP_BUY) BuyOpen = true;
            if (OrderType() == OP_SELL) SellOpen = true;
            OpenTrades++;
            BasketUpl+= (OrderProfit() + OrderSwap() + OrderCommission() );
            MostRecentTradePrice = OrderOpenPrice();
            if (OrderLots() == Primary_trade_Lot_size) PrimaryTrades++;
            if (OrderProfit() < 0 && UseHedging) HedgingModule();
         }//if (OrderType() == OP_BUY || OrderType() == OP_SELL) 
         
         if (ObjectFind(breakevenlinename) > -1 && !HedgingInProgress)
         {
            double take = ObjectGet(breakevenlinename, OBJPROP_PRICE1);
            if (OrderTakeProfit() != take && (OrderType() == OP_BUY || OrderType() == OP_SELL) )
            {
               OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), take, OrderExpiration(), CLR_NONE);
            }//if (OrderTakeProfit() != take && (OrderType() == OP_BUY || OrderType() == OP_SELL) )
         }//if (ObjectFind(breakevenlinename) > -1)
         
         if (ObjectFind(takeprofitlinename) > -1 && ObjectGet(takeprofitlinename, OBJPROP_COLOR) == TakeProfitLineColour)
         {
            take = ObjectGet(takeprofitlinename, OBJPROP_PRICE1);
            if (OrderTakeProfit() != take && (OrderType() == OP_BUY || OrderType() == OP_SELL) )
            {
               OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), take, OrderExpiration(), CLR_NONE);
            }//if (OrderTakeProfit() != take && (OrderType() == OP_BUY || OrderType() == OP_SELL) )
         }//if (ObjectFind(takeprofitlinename) > -1)
         
         
      }//if (OrderSymbol() == Symbol() )
   }//for (int cc = 0; cc <= OrdersTotal(); cc++)

   if (BuyOpen && SellOpen) HedgingInProgress = true;
   
}//End void CountOpenTrades()

void CountPendingTrades()
{
   PendingTradesTotal = 0;
   PendingPrimary = 0;
   PendingSecondary = 0;
   
   if (OrdersTotal() == 0) return;
   
   for (int cc = 0; cc <= OrdersTotal(); cc++)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() )
      {
         if (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP) 
         {
            PendingTradesTotal++;  
            if (OrderLots() == Primary_trade_Lot_size) PendingPrimary++;
            if (OrderLots() == Secondary_trade_Lot_size) PendingSecondary++;
         }//if (OrderType() == OP_BUY || OrderType() == OP_SELL) 
      }//if (OrderSymbol() == Symbol() )
   }//for (int cc = 0; cc <= OrdersTotal(); cc++)

}//End void CountPendingTrades()

void RecoveryModule()
{
   
   //Draw a breakeven line if there is not one in place already.
   //The bot will adjust the tp's during the CountOpenTrades function.
   
   if (ObjectFind(breakevenlinename) > -1) return;
   
   buy_price = 0;
   sell_price = 0;
   CheckRecoveryTakeProfit();
   double recovery_profit;
   if (buy_price > 0) 
   {
      recovery_profit = buy_price;
      recovery_profit = NormalizeDouble(buy_price + (RecoveryBreakEvenProfitPips * Point), Digits);
   }//if (buy_price > 0) 
   
   if (sell_price > 0) 
   {
      recovery_profit = sell_price;
      recovery_profit = NormalizeDouble(sell_price - (RecoveryBreakEvenProfitPips * Point), Digits);
   }//if (sell_price > 0) 
   
   ObjectCreate(breakevenlinename,OBJ_HLINE,0,TimeCurrent(), recovery_profit );
   ObjectSet(breakevenlinename,OBJPROP_COLOR,BreakEvenLineColour);
   ObjectSet(breakevenlinename,OBJPROP_STYLE,STYLE_SOLID);
   ObjectSet(breakevenlinename,OBJPROP_WIDTH,2);
   
}//End void RecoveryModule()

void CheckRecoveryTakeProfit()
{
   //This is adapted from the NB iExposure indicator. I do not understand how it works.
   //There will be redundant code, so anybody wishing to clear it up is most welcome to do so.
   
   ExtLines = 0;
   int    i,col,line;

   ArrayInitialize(ExtSymbolsSummaries,0.0);
   int total=Analyze();
   if(total>0)
   {
      line=0;
      for(i=0; i<ExtSymbolsTotal; i++)
      {
         if (ExtSymbols[i] != Symbol() ) continue;
         if(ExtSymbolsSummaries[i][DEALS]<=0) continue;
         line++;
         //---- add line
         if(line>ExtLines)
         {
            int y_dist=ExtVertShift*(line+1)+1;
            /*for(col=0; col<8; col++)
              {
               name="Line_"+line+"_"+col;
               if(ObjectCreate(name,OBJ_LABEL,windex,0,0))
                 {
                  ObjectSet(name,OBJPROP_XDISTANCE,ExtShifts[col]);
                  ObjectSet(name,OBJPROP_YDISTANCE,y_dist);
                 }
              }*/
            ExtLines++;
         }//if(line>ExtLines)
         //---- set line
         //color  price_colour;//Steve mod
         int    digits=MarketInfo(ExtSymbols[i],MODE_DIGITS);
         double buy_lots=ExtSymbolsSummaries[i][BUY_LOTS];
         double sell_lots=ExtSymbolsSummaries[i][SELL_LOTS];
         if(buy_lots!=0)  buy_price=NormalizeDouble(ExtSymbolsSummaries[i][BUY_PRICE]/buy_lots, Digits);
         if(sell_lots!=0) sell_price=NormalizeDouble(ExtSymbolsSummaries[i][SELL_PRICE]/sell_lots, Digits);
         
      }//for(i=0; i<ExtSymbolsTotal; i++)
   }//if(total>0)


}//End void CheckRecoveryTakeProfit()

int Analyze()
{
   double profit;
   int    i,index,type,total=OrdersTotal();
//----
   for(i=0; i<total; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS)) continue;
      type=OrderType();
      if(type!=OP_BUY && type!=OP_SELL) continue;
      index=SymbolsIndex(OrderSymbol());
      if(index<0 || index>=SYMBOLS_MAX) continue;
      //----
      ExtSymbolsSummaries[index][DEALS]++;
      profit=OrderProfit()+OrderCommission()+OrderSwap();
      ExtSymbolsSummaries[index][PROFIT]+=profit;
      if(type==OP_BUY)
        {
         ExtSymbolsSummaries[index][BUY_LOTS]+=OrderLots();
         ExtSymbolsSummaries[index][BUY_PRICE]+=OrderOpenPrice()*OrderLots();
        }
      else
        {
         ExtSymbolsSummaries[index][SELL_LOTS]+=OrderLots();
         ExtSymbolsSummaries[index][SELL_PRICE]+=OrderOpenPrice()*OrderLots();
        }
     }
//----
   total=0;
   for(i=0; i<ExtSymbolsTotal; i++)
     {
      if(ExtSymbolsSummaries[i][DEALS]>0) total++;
     }
//----
   return(total);
}//int Analyze()

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int SymbolsIndex(string SymbolName)
{
   bool found=false;
//----
   for(int i=0; i<ExtSymbolsTotal; i++)
     {
      if(SymbolName==ExtSymbols[i])
        {
         found=true;
         break;
        }
     }
//----
   if(found) return(i);
   if(ExtSymbolsTotal>=SYMBOLS_MAX) return(-1);
//----
   i=ExtSymbolsTotal;
   ExtSymbolsTotal++;
   ExtSymbols[i]=SymbolName;
   ExtSymbolsSummaries[i][DEALS]=0;
   ExtSymbolsSummaries[i][BUY_LOTS]=0;
   ExtSymbolsSummaries[i][BUY_PRICE]=0;
   ExtSymbolsSummaries[i][SELL_LOTS]=0;
   ExtSymbolsSummaries[i][SELL_PRICE]=0;
   ExtSymbolsSummaries[i][NET_LOTS]=0;
   ExtSymbolsSummaries[i][PROFIT]=0;
//----
   return(i);
}//End int SymbolsIndex(string SymbolName)

bool CheckTradingTimes()
{
   int hour = TimeHour(TimeLocal() );
   
   if (end_hourm < start_hourm)
	{
		end_hourm += 24;
	}
	

	if (end_houre < start_houre)
	{
		end_houre += 24;
	}
	
	bool ok2Trade = true;
	
	ok2Trade = (hour >= start_hourm && hour <= end_hourm) || (hour >= start_houre && hour <= end_houre);

	// adjust for past-end-of-day cases
	// eg in AUS, USDJPY trades 09-17 and 22-06
	// so, the above check failed, check if it is because of this condition
	if (!ok2Trade && hour < 12)
	{
 		hour += 24;
		ok2Trade = (hour >= start_hourm && hour <= end_hourm) || (hour >= start_houre && hour <= end_houre);		
		// so, if the trading hours are 11pm - 6am and the time is between  midnight to 11am, (say, 5am)
		// the above code will result in comparing 5+24 to see if it is between 23 (11pm) and 30(6+24), which it is...
	}


   // check for end of day by looking at *both* end-hours

   if (hour >= MathMax(end_hourm, end_houre))
   {      
      ok2Trade = false;
   }//if (hour >= MathMax(end_hourm, end_houre))

   return(ok2Trade);

}//bool CheckTradingTimes()

void AddReEntryLine(double price)
{
      if (ObjectFind(reentrylinename) > -1) ObjectDelete(reentrylinename);   
      
      
      if (!ObjectCreate(reentrylinename,OBJ_HLINE,0,TimeCurrent(),price) )
      {
         int err=GetLastError();      
         Alert("Re-entry line draw failed with error(",err,"): ",ErrorDescription(err));
         Print("Re-entry line draw failed with error(",err,"): ",ErrorDescription(err));
         return(0);

      }//if (!ObjectCreate(reentrylinename,OBJ_HLINE,0,TimeCurrent(),price) )
      
      ObjectSet(reentrylinename,OBJPROP_COLOR,ReEntryLineColour);
      ObjectSet(reentrylinename,OBJPROP_STYLE,STYLE_SOLID);
      ObjectSet(reentrylinename,OBJPROP_WIDTH,2);     


}//void AddReEntryLine(int type, double price)

bool IsTradeAlreadyHedged(int ticket)
{

   for (int cc = OrdersTotal() - 1; cc >=0; cc--)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      string tn = DoubleToStr(ticket, 0);
      if (OrderComment() == tn) return(true);
   }//for (int cc = OrdersTotal() - 1; cc >=0; cc--)
   
   
   return(false);
   
}//End bool IsTradeAlreadyHedged(int ticket)



void HedgingModule()
{
   //Called from CountOpenTrades if the trade is loosing
   
   double loss;
   int tn = OrderTicket();
   RefreshRates();
   
   RsiVal = GetRsi(PERIOD_D1, 20, 0);
   if (RsiVal < 55 && RsiVal > 45) return;
   
   if (OrderType() == OP_BUY)
   {
      loss = OrderOpenPrice() - Ask;
      if (loss > (HedgeAtLossPips * Point) )
      {
         bool HedgeExists = IsTradeAlreadyHedged(tn);
         OrderSelect(tn, SELECT_BY_TICKET);
         if (HedgeExists) return;
         if (RsiVal > 45) return;
         bool result = SendSingleTrade(OP_SELL, DoubleToStr(tn, 0), OrderLots() * HedgeLotsMiltiplier, Bid, 0, 0, 0);
      }//if (loss > (HedgeAtLossPips * Point)      
   }//if (OrderType() == OP_BUY)
   
   if (OrderType() == OP_SELL)
   {
      loss = Bid - OrderOpenPrice();
      if (loss > (HedgeAtLossPips * Point) )
      {
         HedgeExists = IsTradeAlreadyHedged(tn);
         OrderSelect(tn, SELECT_BY_TICKET);
         if (HedgeExists) return;
         if (RsiVal < 55) return;
         result = SendSingleTrade(OP_BUY, DoubleToStr(tn, 0), OrderLots() * HedgeLotsMiltiplier, Ask, 0, 0, 0);
      }//if (loss > (HedgeAtLossPips * Point)      
   }//if (OrderType() == OP_SELL)
   
   
   
}//End void HedgingModule()

double GetRsi(int tf, int period, int shift)
{
   return(iRSI(NULL, tf, period, PRICE_CLOSE, shift) );
}//End double GetRsi(int tf, int period, int shift)


//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{


   static double OldBottomGoldLine, OldTopGoldLine;//Keep track of where the sixths were, in case they have moved
   static int OldH1Bars;
   
   if (UseHedging && OldH1Bars != iBars(NULL, PERIOD_H1) )
   {
      RsiVal = GetRsi(PERIOD_D1, 20, 0);
      trend = ranging;
      if (RsiVal > 55) trend = up;
      if (RsiVal < 45) trend = down;
      OldH1Bars = iBars(NULL, PERIOD_H1);
   }//if (UseHedging)
   
   
   if (ObjectFind(takeprofitlinename) == 0 && ObjectGet(takeprofitlinename, OBJPROP_PRICE1) != TpLinePrice1) 
   {
      ObjectSet(takeprofitlinename,OBJPROP_COLOR,TakeProfitLineColour);
   }//if (ObjectFind(takeprofitlinename) > -1 && OBJPROP_PRICE1 != TpLinePrice1) 
   
   CountOpenTrades();
   CountPendingTrades();
   
   //Mop up unwanted duplicate trades and orphaned secondaries 
   if (Old5Bars != iBars(NULL, PERIOD_M5) )
   {
      Old5Bars = iBars(NULL, PERIOD_M5);
      if (OpenTrades > 0 || PendingPrimary > 0 || PendingSecondary > 0) 
      {
         bool result = CleanUp();
         Sleep(10000);
         if (!result)
         {
            Old5Bars = 0;
         }//if (!result)
         return;   
      }//if (OpenTrades > 0 && Old5Bars != iBars(NULL, PERIOD_M5) )
   }//if (Old5Bars != iBars(NULL, PERIOD_M5) )
   

   if (OpenTrades == 0) 
   {
      ForcePendingTradeDeletion = false;
      ForceAllTradeDeletion = false;
      PrevOpenTrades = 0;
      GlobalVariableSet(GvName, 0);
      if (ObjectFind(breakevenlinename) > -1) ObjectDelete(breakevenlinename);
      if (ObjectFind(reentrylinename) > -1) ObjectDelete(reentrylinename);
      //if (ObjectFind(takeprofitlinename) > -1) ObjectDelete(takeprofitlinename);      
      MostRecentTradePrice=0;
      PrimaryTrades = 0;
      RecoveryInProgress = false;
      HedgingInProgress = false;      
   }//if (OpenTrades == 0) 
   
   if (OpenTrades == 0) RecoveryInProgress = false;
   
   //Recovery
   if (UseRecovery && !HedgingInProgress)
   {
      if (PrimaryTrades >= Start_Recovery_at_trades) RecoveryInProgress = true;
      if (RecoveryInProgress)
      {
         if (ObjectFind(takeprofitlinename) > -1) ObjectDelete(takeprofitlinename);
         RecoveryModule();
      }//if (RecoveryInProgress)

      //Replace accidentally deleted be line
      if (RecoveryInProgress && ObjectFind(breakevenlinename) == -1)
      //if (ObjectFind(breakevenlinename) == -1 && OpenTrades > TradeNumber) //DC
      {
         RecoveryModule();      
      }//if (ObjectFind(breakevenlinename) == -1 && OpenTrades > 2)
   }//if (UseRecovery)
   
   if (HedgingInProgress)
   {
      if (ObjectFind(takeprofitlinename) > -1) ObjectDelete(takeprofitlinename);
      if (BasketUpl >= 0)
      {
         ForceAllTradeDeletion = true;
         CloseAllTrades();      
      }//if (BasketUpl >= 0)
      
   }//if (HedgingInProgress)
   
   
   /*
   if (OldBars != Bars5)
   {
      OldBars = Bars;
      ForcePendingTradeDeletion = true;
      DeletePendingTrades();
      if (ForcePendingTradeDeletion) OldBars = 0;
   }//if (OldBars != Bars)
   */
   
   //Delete pending orders if a previous attempt failed
   if (ForcePendingTradeDeletion)
   {
      DeletePendingTrades();
      return;
   }//if (ForcePendingTradeDeletion)
   
   //Delete open trades if a previous attempt failed
   if (ForceAllTradeDeletion)
   {
      CloseAllTrades();
      return;
   }//if (ForcePendingTradeDeletion)
   
       /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   //Trading times
   bool TradeTimeOk = CheckTradingTimes();
   if (!TradeTimeOk)
   {
      if (PendingTradesTotal > 0)
      {
         ForcePendingTradeDeletion = true;
         DeletePendingTrades();
      }//if (PendingTradesTotal > 0)
      
      Comment("Outside trading hours\nstart_hourm-end_hourm: ", start_hourm, "-",end_hourm, "\nstart_houre-end_houre: ", start_houre, "-",end_houre);
      return;
   }//if (hour < start_hourm)
   /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

   GetSixths();
   if (ObjectFind(takeprofitlinename) == -1 && OpenTrades > 0 && UseTplTp) 
   {
      if (OrderType() == OP_SELL) DrawTakeProfitLine(OP_SELL);
      if (OrderType() == OP_BUY) DrawTakeProfitLine(OP_BUY);
   }//if (ObjectFind(takeprofitlinename) == -1 && OpenTrades > 0) 
   
   //Delete pending orders if sixths have changed
   if ((OldBottomGoldLine != BottomGoldLine || OldTopGoldLine != TopGoldLine) && (OldBottomGoldLine > 0 
   && OldTopGoldLine > 0) && PendingTradesTotal > 0)
   {
      ForcePendingTradeDeletion = true;
      DeletePendingTrades();
   }//if ((OldBottomGoldLine != BottomGoldLine || OldTopGoldLine != TopGoldLine) && (OldBottomGoldLine > 0 && OldTopGoldLine > 0) )
   OldBottomGoldLine = BottomGoldLine;
   OldTopGoldLine = TopGoldLine;
   
   //Should open trades be closed?
   if (BasketUpl >= 0) LookForTradeClosure();
   
   //Look for trading opportunities
   if (!StopTrading)
   {
      CalculateTrades();
   }//if (!StopTrading)
   
   DisplayUserFeedback();
      

}
//+------------------------------------------------------------------+
/*
//+------------------------------------------------------------------+
//| expert PivotL function |
//+------------------------------------------------------------------+
double PivotL(string symbol)
{
return(iLow(symbol,60,iLowest(symbo l,60,MODE_LOW,168,1)));
}

//+------------------------------------------------------------------+
//| expert PivotH function |
//+------------------------------------------------------------------+
double PivotH(string symbol)
{
return(iHigh(symbol,60,iHighest(sym bol,60,MODE_HIGH,168,1)));
}

E2u
I think you are right and maybe this is something to check for each pairs also.

When it moves 0-9 pips from the days opening the probability of it reversing the trend is 75%.

When it moves 10-19 pips from the days opening the probability of it reversing the trend is 55%.

When it moves 20-29 pips from the days opening the probability of it reversing the trend is 40 %.

When it moves 30-39 pips from the days opening the probability of it reversing the trend is 25%.

When it moves 40-49 pips from the days opening the probability of it reversing the trend is 13%.

When it moves 50-59 pips from the days opening the probability of it reversing the trend is 8%.

When it moves 60-69 pips from the days opening the probability of it reversing the trend is 4%.

When it moves 70 pips from the days opening the probability of it reversing the trend is less then 1%.
*/