//+------------------------------------------------------------------+
//|                             Nanningbob V5 auto trading robot.mq4 |
//|                                  Copyright © 2009, Steve Hopwood |
//|                              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  up          "Up"
#define  down        "Down"
#define  buy         "Buy"
#define  sell        "Sell"
#define  none        "None"
#define  ranging     "Ranging"
#define  confused    "Confused, and so cannot trade"
#define  trending    "Trending"
#define  irrelevant  "Irrelevant - there is no trade direction yet"
#define  mode0       "Not looking for a trade trigger"
#define  mode1buy    "#1 Buy"
#define  mode1sell   "#1 Sell"
#define  mode2buy    "#2 Buy"
#define  mode2sell   "#2 Sell"
#define  mode3buy    "#3 Buy BUlge"
#define  mode3sell   "#3 Sell Bulge"
#define  mode4buy    "#4 Buy"
#define  mode4sell   "#4 Sell"
#define  mode7buy    "#7 Buy divergence"
#define  mode7sell   "#7 Sell divergence"
#define  mode9buy    "#9 Buy OS"
#define  mode9sell   "#9 Sell OB"
#define  opentrade   "There is a trade open"
#define  stopped     "Trading is stopped"
#define  Manual_stopped             "Manual_stopped"
#define  stopped_by_Recovery_Max      "stopped_by_Recovery_Max"
#define  stopped_by_HighSpread      "stopped_by_HighSpread"
#define  stopped_by_HighVolatility     "stopped_by_HighVolatility"
#define  MaxExposure_for_this_Currency "MaxExposure_for_this_Currency"  
#define  reentrylinename "Re entry line"
#define  breakevenlinename "Break even line"

#define  oldtrendlinename "Traded trend line"
#define  ReEntryLine4HTname "Re entry line"

//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



/*
this version is from Steve 19.8.2010 8.20 AM version
Revision history :
000   :  Auto RentryLinePips
001   :  Cosmetic enhancements
002   :  high volatility protection (VolatilityStopTrading)
003   :  high spread protection (SpreadStopTrading)
004   :  change way for selecting Tp mode ect...
005   :  Add MacdBB for trend dectection (not yet tested)
006   :  Add Allow1, Allow2 ect
         Simple Recovery system, each level have it's own multiplier
007   :  Bug correction
         RentryLine Pips is a multiplier of DailyATR
008   :  Add a Maximum Exposure by Currency (not yet tested)
009   :  Add a KG module in order to check le strongest currency VS le weakest currency
         If the pair is in this case we can increase the lots size !!! (not yet tested)!!!
010   :  OB OS display
011   :  prohobit enter long if the pair is Overbought (OB) short if OS
012   :  removed Hiden TP, HidenSL ect...
013   :  attempt to Add mode 9 that is KG extreme
014   :  finish mode #9
         included some of last Steve changes
015   :  _DATRMult
016   :  3 stage recovery module, very flexible
017   :  display 
018   :  Steve LAst mods
018b  :  use or not use Steve LAst mods
019   :  easy mode for Kg
020   :  steve mod if (OrderSymbol() == Symbol() && OrderTakeProfit() != NewTake)
021   :  better code for Magic number, can use with metals, ect...
022   :  steve mod SendSingleTrade
023   :  Global profit
024   :  Mode9 use MiddleWhiteLine
025   :  Mode9 stock modif (H1) & add RsiFast, mode #9 not priority any more
      :  Spread protection value is user input : SpreadProtection__DATRMult
025b  :  new pairs for romano
026   :  Last Steve Mod for rentryline DRAW
         Do not use H1 for mode #9 mode actual TF,= Rsi3, Stoch (4.2.2 ema)
027   :  Bug correction ModifyTakeProfit
         Add code in order to redraw RentryLinePips if deleted
028   :  Use CptTick and Cpt2Tick to boost the speed, when code is not needed at everytick
029   :  Steve mod for RentryLine
030   :  Smart calculation for RentrylinePips with complex calculation for standartDeviation
         AutoSwitchZone
031   :  trademanagement module also if trades >1 (recovery)
032   :  deleted rentryline in buy()
032b2 :  corrected many bugs
049   :  in case recovery is needed, we trade zone green
050   :  if opentrades>1, no trademanagement 
051   :  Use scoob mod
053   : correct display (recovery
054   : recreate breakevenline if deleted
055   : add trend mode
*/
extern bool    Use4HTrendline                = true;
extern string  den="----Time Management-------";
extern bool    UseScoobMod                   = true;
extern bool    UseTimeManagement             = true;
extern int     MondayStartHour               =7;
extern int     FridayStopHour                =17;
extern bool    AvoidNewsHours                = true;
extern string  gen="----General inputs-------";
extern int     UseStochWhiteInDirStillValid  =1;
extern bool    UseSpreadProtection           =false;
extern double  SpreadProtection__DATRMult    =0.1;
extern bool    UseVolatilityProtection       =false;
extern double  Lot                           =0.1;
extern string  cu1="Stop trading currency exposure";
extern string  cu2="use 999 if disable";
extern double  MaxLotsPerCurr                =999; 
extern string  atms="----Trading methods----";
extern bool    Allow1                        =true;
extern bool    Allow2                        =true;
extern bool    Allow3                        =true;
extern bool    Allow4                        =true;
extern bool    Allow7                        =true;
extern bool    Allow9                        =true;
extern bool    AllowTrendMode                =true;
extern bool    CriminalIsECN                 =false;
extern bool    StopTrading                   =false;
extern string  tpk ="----Recovery------------ ";
extern bool    UseRecovery                   =true;
extern double  RecoveryRentry1Mult           =1;
extern double  RecoveryRentry2Mult           =2;
extern double  RecoveryRentry3Mult           =4;
extern string  tpv ="ReEntryPips = DailyATR * mult ";
//extern double  ReEntryPips_DATRMult          =1;
extern double  ReEntryPips_DeviationMult     =1.5;
extern double  ReEntryPipsMin_DATRMult       =0.5;
extern string  tpi ="----TPMode 1=UseSixths--- ";
extern string  tpi2="--- 2=UseBol 3=UseAtr----";
extern int     TPMode                        =3;
extern int     TakeProfit                    =0;
extern double  AtrTpMultiplier               =3;
extern double  MinimumTarget_DATRMult        =0.3;
extern string  tpi3="--Closing by Global Profit--";
extern bool    ClosingByGlobalProfit         =false;
extern int     ProfitTarget                  =500;
extern string  sli="----SL for catastrophic events";
extern int     EmergencyStopLoss             =999;
extern string  six="----Sixths inputs-------------";
extern int     BarCount                      =120;
extern bool    TradeZoneGold                 =false;
extern bool    TradeZoneGreen                =true;
extern bool    AutoSwitchZone                =true;
extern string  tcm="----Trade closure module----";
extern bool    UseWhiteLineClosure           =true;
extern int     MinSeparationFromBlue         =15;
extern string  tmm="----Trade management module----";
extern bool    DoNotOverload5DigitCriminals  =true;
extern bool    BreakEven                     =true;
extern double  BEPips_DATRMult               =0.4;
extern double  BEProfit_DATRMult             =0.03;
extern bool    UseEaToManageRecoveryOnly     =false;
extern string  JSL="----Jumping SL settings-------";
extern bool    JumpingStop                   =false;
extern double  JSPips_DATRMult               =0.4;
extern bool    AddBEP                        =true;
extern bool    JumpAfterBreakevenOnly        =false;
extern string  TSL="----Trailing SL settings------";
extern bool    TrailingStop                  =true;
extern double  TSPips_DATRMult               =0.4;
extern bool    TrailAfterBreakevenOnly       =false;
extern bool    StopTrailAtPipsProfit         =false;
extern int     StopTrailPips                 =0;
extern string  mas="----MA inputs----";
extern double  MinSepFromBB                  =0.1;
extern string  sdfcd="----Use KG Status----";
extern bool    AvoidTradingIfObOs            =false;
double         UpTrig                        =80;
double         LoTrig                        =20;
extern string  mis="----Odds and ends----";
extern int     DisplayGapSize                =00;
extern bool    ShowAlerts                    =true;
extern color   ReEntryLineColour             =Turquoise;
extern color   BreakEvenLineColour           =Red;
extern string  stri="----Atr inputs----";
extern int     FastTrendAtr                  =5;
extern int     SlowTrendAtr                  =200;
extern int     TrendTakeProfit               =0;
extern int     TrendStopLoss                 =999;
extern string  rsii="----Rsi----";
extern int     RsiPeriod                     =21;
extern int     RsiTimeFrame                  =0;
extern int     RsiOverbought                 =85;
extern int     RsiOversold                   =15;
string         hgf="---------4H Trenline ---------------";
extern bool    SendMarketTrades=false;
extern bool    SendPendingTrades=true;
extern int     PendingOrderPipsDistance=15;
extern int     PendingExpiryMinutes=60;
extern int     ReEntryLine4HTPips=200;
extern color   ReEntryLine4HTColour=Blue;
extern string  TrendLineName="Trading robot trend line";
extern color   TrendLineColour=Yellow;
extern color   TrendLineRecordColour=White;
extern string  lsdi="----Take profit and stop loss inputs----";
extern int     TakeProfit4HT=0;
extern bool    UseAtrTp=true;
extern string  lnk="Stop loss for catastrophic events";
extern int     EmergencyStopLoss4H=50;
extern string  tm="----Trend detection module----";
extern string  mts="Manual trend-setting";
extern bool    TrendIsUp=false;
extern bool    TrendIsDown=false;
extern string  ats="Automatic trend detection";
extern bool    AutoDetectTrend=true;
extern string  rsin="----Rsi----";
extern bool    UseRsi=true;
extern int     RsiTf4H=1440;
extern string  atri="----Atr----";
extern bool    UseAtr=false;
extern int     AtrTf=0;
extern int     AtrPeriod=21;
extern int     DaysToLookBack=10;
extern string  adxin="----Adx----";
extern bool    UseAdx=false;
extern int     AdxTf=0;
extern int     AdxPeriod=21;
extern string  ls="----LSMA----";
extern bool    UseLSMA=false;
extern int     LSMAPeriod=21;
extern int     LSMATf=0;
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 = 7;
extern  int    end_hourm = 12;
extern string  Trade_Hours_E= "Evening Hours 12-24";
extern  int    start_houre = 12;
extern  int    end_houre = 18;


string         bl1="-------------------------------------------------------------";
string         vbn="----Rsi for Trend ----";
int            RsiTf                         =0;
string         bl2="-------------------------------------------------------------";
string         smacd="----StochasticMacdSqualou inputs----";
int            FastEMA                       =12;
int            SlowEMA                       =26;
int            SignalSMA                     =9;
int            StochasticPeriod              =120; //4 weeks of H4 bars = 4*5*24/4 = 120
int            OverBought                    =75;
int            OverSold                      =25;
//Corresponding trade comments
string         no1_Buy25                     = "#1 BUY_25";
string         no1_Sel25                     = "#1 SELL_25";
string         no2_Buy1MA                    = "#2 BUY_1MA";
string         no2_Sel1MA                    = "#2 SELL_1MA";
string         no3_BuyBulge                  = "#3 BUY_Bulge";
string         no3_SelBulge                  = "#3 SELL_Bulge";
string         no4_BuyBB13                   = "#4 BUY_BB13";
string         no4_SelBB13                   = "#4 SELL_BB13";
string         no7_BuyDivergence             = "#7 BUY_Div";
string         no7_SelDivergence             = "#7 SELL_Div";
string         no9_BuyOS                     = "#9 BUY_OS";
string         no9_SelOB                     = "#9 SELL_OB";

int            Mode4DistanceToBB       =5;
int            TicketNo, OpenTrades, SendMagicNumber,OldBars;
double         BbUpper, BbLower,LotSize,SendLots,TrendRsiVal, TrendAtrVal;
double         BottomGoldLine,BottomGreenLine,MiddleWhiteLine,TopGreenLine,TopGoldLine;
double         StochWhite,StochFast,StochFastOld,StochBlue,MacdVal,Ma1;
string         TradeDirection=none, TradingStatus=none;
double         AdxVal, AdxPlusDI, AdxMinusDI;
string         RsiTrend, AtrTrend, AdxTrend, LsmaTrend, trend;
bool           RecoveryInProgress, TpMoved;
string         ExtSymbols[SYMBOLS_MAX];
int            ExtSymbolsTotal=0,ExtLines=-1,ExtVertShift=14;
double         ExtSymbolsSummaries[SYMBOLS_MAX][7];
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 };
double         buy_price=0.0,sell_price=0.0;
//OOOOOOOOOOOOOOOOOOOOOOOOOOO  Maxou Modif
int            AtrTpPeriod             =14;
int            AtrTpTimeFrame          =0;
double         DailyATR                =0;         
double         v_ActualSpread          =0;
bool           RecoveryStopTrading     =false;
bool           SpreadStopTrading       =false;
bool           VolatilityStopTrading   =false;
int            MacdBBTrend             =0;
bool           MaxExposure             =false;
int            BreakEvenPips           =25;
int            BreakEvenProfit         =10;
int            JumpingStopPips         =50;
int            TrailingStopPips        =50;
int            MinimumTargetinPips     =50;
int            ReEntryLinePips         =200;
double         intermedaire1,intermedaire2,intermedaire3,intermedaire4,intermedaire5,intermedaire6,MinKG,MaxKG;
double         JpyKgRS,UsdKgRS,GbpKgRS,EurKgRS,ChfKgRS,AudKgRS,NzdKgRS,CadKgRS;
double         EURTotLots,GBPTotLots,CADTotLots,JPYTotLots,CHFTotLots,USDTotLots,AUDTotLots,NZDTotLots;
int            KGstatus, MaxADr, multiplier;
string         Gap, ScreenMessage, GvName;
bool           SuspendTrading;
color          v_color;
int            MagicNumber=0;
double         Deviation, Deviationfast,Deviationslow, RsiFast,v_OrderProfit;
int            CptTick=0, Cpt2Tick=0;
bool           ThisIsFirstTick=true;
double         disptarget,NewTake;
double         recovery_profit;
string         txtzone="";
double         v_OrderTakeProfit=0,v_NewTake=0;
int            v_OrderType,  old_OpenTrades;
int            FastAtrP   =5;
int            SlowAtrP   =200;
double         FastAtr,SlowAtr;
double         fTrendAtr, sTrendAtr;
double         TrendRsi, D1Rsi;


//  4H
int            TicketNo4HT, OpenTrades4HT;
double         TargetPrice4HT,RsiTrend4h;

//Trade direction
string         TradingStatus4HT,trend4HT;
//Trend
//Trend line
double         Leg2, Leg1;
string         RsiTrend4H;
int            Leg2Time, Leg1Time;
bool TpMoved4HT, RecoveryInProgress4HT;
string TradeComment="Trend 4H";
double buy_price4HT,sell_price4HT;
int magic4HT=222555;        
int magicR  =333000;        

void DisplayUserFeedback()//-------------------------------- 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;
   if (ClosingByGlobalProfit)
   {
     ScreenMessage = StringConcatenate(ScreenMessage,Gap, "GlobalProfit: ",DoubleToStr(Globalprofit(), 1), " [",DoubleToStr(ProfitTarget, 0),"]", NL);
   }
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "TicketNo: ",DoubleToStr(TicketNo, 0), NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "DailyATR: ",DoubleToStr(DailyATR/multiplier, 0), " [",DoubleToStr(DailyATR, 0),"]", NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "BE : ", DoubleToStr(BreakEvenPips/multiplier,0)," [",DoubleToStr(BreakEvenPips,0),"]", " BEP : ", DoubleToStr(BreakEvenProfit/multiplier,0)," [",DoubleToStr(BreakEvenProfit,0),"]", " TS : ", DoubleToStr(TrailingStopPips/multiplier,0)," [",DoubleToStr(TrailingStopPips,0),"]", NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "MinimumTargetinPips: ",DoubleToStr(MinimumTargetinPips/multiplier,0), " [",DoubleToStr(MinimumTargetinPips,0),"]", NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "ReEntryLinePips: ", DoubleToStr(ReEntryLinePips/multiplier,0)," [",DoubleToStr(ReEntryLinePips,0),"]", NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "OrderProfit(): ", DoubleToStr(v_OrderProfit,1), NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "target: ", DoubleToStr(disptarget,4), NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Deviation: ", DoubleToStr(Deviation,0), NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "#4 trend: ", trend, NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);      
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Lot size: ", Lot, NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trend4H: ", trend4HT, NL);
   if (trend4HT == up && TargetPrice4HT != 0) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "I will BUY at: ", DoubleToStr(TargetPrice4HT, Digits), NL);
   if (trend4HT == down && TargetPrice4HT != 0) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "I will SELL at: ", DoubleToStr(TargetPrice4HT, Digits), NL);
   if (trend4HT == ranging) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Not trading a ranging market", NL);
   if (AutoDetectTrend) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Automatic trend detection is turned on", NL);
   if (!AutoDetectTrend) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Automatic trend detection is turned off", NL);
   if (SendMarketTrades) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Sending immediate market orders", NL);
   if (SendPendingTrades) ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Sending pending orders", NL);
   Comment(ScreenMessage);
}//void DisplayUserFeedback()


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
DeleteObj();
//----
   MaxADr=9999;
   
   if (StringSubstr(Symbol(), 0, 6) == "AUDCAD") { MaxADr=130;}// thats 1.3x normal daily ATR
   if (StringSubstr(Symbol(), 0, 6) == "AUDCHF") { MaxADr=190;}// the value is for 4 digit criminal
   if (StringSubstr(Symbol(), 0, 6) == "AUDJPY") { MaxADr=180;}
   if (StringSubstr(Symbol(), 0, 6) == "AUDNZD") { MaxADr=130;}
   if (StringSubstr(Symbol(), 0, 6) == "AUDUSD") { MaxADr=140;}
   if (StringSubstr(Symbol(), 0, 6) == "CADCHF") { MaxADr=190;}
   if (StringSubstr(Symbol(), 0, 6) == "CADJPY") { MaxADr=200;}
   if (StringSubstr(Symbol(), 0, 6) == "CHFJPY") { MaxADr=150;}
   if (StringSubstr(Symbol(), 0, 6) == "EURAUD") { MaxADr=200;}
   if (StringSubstr(Symbol(), 0, 6) == "EURCAD") { MaxADr=180;}
   if (StringSubstr(Symbol(), 0, 6) == "EURCHF") { MaxADr=170;}//??
   if (StringSubstr(Symbol(), 0, 6) == "EURGBP") { MaxADr=100;}
   if (StringSubstr(Symbol(), 0, 6) == "EURJPY") { MaxADr=200;} 
   if (StringSubstr(Symbol(), 0, 6) == "EURNZD") { MaxADr=270;}
   if (StringSubstr(Symbol(), 0, 6) == "EURUSD") { MaxADr=160;}
   if (StringSubstr(Symbol(), 0, 6) == "GBPCHF") { MaxADr=260;}
   if (StringSubstr(Symbol(), 0, 6) == "GBPJPY") { MaxADr=220;}
   if (StringSubstr(Symbol(), 0, 6) == "GBPUSD") { MaxADr=170;}
   if (StringSubstr(Symbol(), 0, 6) == "NZDJPY") { MaxADr=150;}
   if (StringSubstr(Symbol(), 0, 6) == "NZDUSD") { MaxADr=130;}
   if (StringSubstr(Symbol(), 0, 6) == "SGDJPY") { MaxADr=100;}
   if (StringSubstr(Symbol(), 0, 6) == "USDCAD") { MaxADr=140;}
   if (StringSubstr(Symbol(), 0, 6) == "USDCHF") { MaxADr=150;}
   if (StringSubstr(Symbol(), 0, 6) == "USDDKK") { MaxADr=800;}
   if (StringSubstr(Symbol(), 0, 6) == "USDJPY") { MaxADr=120;}
   if (StringSubstr(Symbol(), 0, 6) == "USDNOK") { MaxADr=1100;}
   if (StringSubstr(Symbol(), 0, 6) == "USDSEK") { MaxADr=1200;}
   if (StringSubstr(Symbol(), 0, 6) == "USDSGD") { MaxADr=80;}
   if (StringSubstr(Symbol(), 0, 6) == "_B")     { MaxADr=220;}
   if (StringSubstr(Symbol(), 0, 6) == "XAUUSD") { MaxADr=1700;}
   if (StringSubstr(Symbol(), 0, 6) == "XAGUSD") { MaxADr=50;}

   Gap="";
   if (DisplayGapSize >0)
   {  for (int cc=0; cc< DisplayGapSize; cc++)  {  Gap = StringConcatenate(Gap, " ");}  }
   
   if(Digits == 2 || Digits == 4)   multiplier = 1;
   if(Digits == 3 || Digits == 5)   multiplier = 10;
   if(Digits == 6)                  multiplier = 100;   
   if(Digits == 7)                  multiplier = 1000;   
   MaxADr               *= multiplier;
   TakeProfit           *= multiplier;
   EmergencyStopLoss    *= multiplier;
   EmergencyStopLoss4H  *= multiplier;
   Mode4DistanceToBB    *= multiplier;
   TrendTakeProfit*= multiplier;
   TrendStopLoss*= multiplier;
   PendingOrderPipsDistance*=  multiplier;
   
   double MinDist=MarketInfo(Symbol(),MODE_STOPLEVEL);
   if (PendingOrderPipsDistance<MinDist) PendingOrderPipsDistance=MinDist; 
   
   GvName = "Nanningbob V5 " + Symbol();
   
   //Pick up looking for trade setups after a crash
   if (GlobalVariableCheck(GvName) ) int dir = GlobalVariableGet(GvName);
   TradeDirection = none;  TradingStatus  = mode0;
   
   if (dir == 1)  {  TradeDirection = up;    TradingStatus = mode1buy; }
   if (dir == 11) {  TradeDirection = down;  TradingStatus = mode1sell;}
   if (dir == 2)  {  TradeDirection = up;    TradingStatus = mode2buy; }
   if (dir == 22) {  TradeDirection = down;  TradingStatus = mode2sell;}
   if (dir == 3)  {  TradeDirection = up;    TradingStatus = mode3buy; }
   if (dir == 33) {  TradeDirection = down;  TradingStatus = mode3sell;}
   if (dir == 4)  {  TradeDirection = up;    TradingStatus = mode4buy; }
   if (dir == 44) {  TradeDirection = down;  TradingStatus = mode4sell;}
   if (dir == 7)  {  TradeDirection = up;    TradingStatus = mode7buy; }
   if (dir == 77) {  TradeDirection = down;  TradingStatus = mode7sell;}
   if (dir == 9)  {  TradeDirection = up;    TradingStatus = mode9buy; }
   if (dir == 99) {  TradeDirection = down;  TradingStatus = mode9sell;}
  
   //Recovery
   CountOpenTrades();
   OrderSelect(TicketNo, SELECT_BY_TICKET);

   if (OpenTrades > 1){RecoveryInProgress = true; TpMoved = false; }

   SendLots = Lot;
   ThisIsFirstTick=true;
   if (Period()==PERIOD_H1)
   {
      AtrTpMultiplier               =2;
      BEPips_DATRMult               =0.25;
      BEProfit_DATRMult             =0.02;
      TSPips_DATRMult               =0.25;
      ReEntryPips_DeviationMult     =1.2;}
   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
{  DeleteObj();
   Comment("");
   return(0);
}

//############################################         SendSingleTrade       #################################################
bool SendSingleTrade(int type, string comment, double lotsize, double price, double stop, double take, int magicR)
{  if (OpenTrades == 1 && !RecoveryInProgress) return(true);
   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 (!CriminalIsECN) int ticket = OrderSend(Symbol(),type, lotsize, price, slippage, stop, take, comment, magicR, expiry, col);
   //Is a 2 stage criminal
   if (CriminalIsECN)
   {  ticket = OrderSend(Symbol(),type, lotsize, price, slippage, 0, 0, comment, magicR, expiry, col);
	   if (stop != 0)
	   {  if (ticket > 0)
		   bool result = OrderModify(ticket, OrderOpenPrice(), stop, take, 0, CLR_NONE);
		   if (!result)
		   {   int err=GetLastError();
             Print(Symbol(), " ", type," SL  order modify failed with error(",err,"): ",ErrorDescription(err));               
		   }//if (!result)			  
	   }//if (Sl != 0)
   }//if (CriminalIsECN)
   
   //Error trapping for both
   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";
      err=GetLastError();
      Alert(Symbol(), " ", stype," Nv5 orderSend failed error(",err,"): ",ErrorDescription(err));
      Print(Symbol(), " ", stype," Nv5 orderSend failed error(",err,"): ",ErrorDescription(err));
      return(false);
   }//if (ticket < 0)  
   
   //Got this far, so trade send succeeded
   Sleep(50000);
   //Recovery
   OpenTrades++;
   if (OpenTrades > 1)
   {  TpMoved = false;
      RecoveryInProgress = true;
   }//if (OpenTrades > 1)
   return(true);
}
//############################################           SetTarget           #################################################
double SetTarget(string tradedirection) 
{  double target = 0;

   double MinDist=MarketInfo(Symbol(),MODE_STOPLEVEL);

   if (tradedirection == sell) // SELL
   {
      if (TPMode==1) // use Sixths
      {  if ( MathAbs(Bid-TopGreenLine) < (Point*MinimumTargetinPips) ) { target = BottomGreenLine;  }
         else { target = TopGreenLine; }
      }
      if (TPMode==3) // use Atr
      {  double AtrVal = iATR(Symbol(), AtrTpTimeFrame, AtrTpPeriod, 0) * AtrTpMultiplier;
         if (AtrVal<MinDist) AtrVal=MinDist;
         target = NormalizeDouble(Bid - AtrVal,Digits);
      } 
      if (TPMode==2) // use BollingerBands middle band
      {  double MiddleBB = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_MAIN, 0);
         if ( MathAbs(Bid-MiddleBB) < (Point*MinimumTargetinPips) ) 
         { target = Bid - (MinimumTargetinPips * Point); }
         else { target = MiddleBB; } 
      }
   }
   else if (tradedirection == buy) // BUY
   {
      if (TPMode==1) // use Sixths
      {  if ( MathAbs(Ask-TopGreenLine) < (Point*MinimumTargetinPips) ) { target = TopGreenLine;  }
         else { target = TopGreenLine; }
      }
      if (TPMode==3) // use Atr
      {  AtrVal = iATR(Symbol(), AtrTpTimeFrame, AtrTpPeriod, 0) * AtrTpMultiplier;
         if (AtrVal<MinDist) AtrVal=MinDist;
         target = NormalizeDouble(Ask + AtrVal,Digits);
      } 
      if (TPMode==2) // use BollingerBands middle band
      {  MiddleBB = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_MAIN, 0);
         if ( MathAbs(Ask-MiddleBB) < (Point*MinimumTargetinPips) ) 
         { target = Ask + (MinimumTargetinPips * Point); }
         else { target = MiddleBB; }
      }
   }
   return (NormalizeDouble(target,Digits));
}

//############################################              Buy             #################################################
void Buy(string comment)
{
   //if (DoesTradeExist()) return;
   //if (ObjectFind("Re entry line") > -1) ObjectDelete("Re entry line");
   double stop = NormalizeDouble(Ask - (EmergencyStopLoss * Point),Digits);
   if (EmergencyStopLoss == 0) stop = 0;
   double take = NormalizeDouble(Ask + (TakeProfit * Point),Digits);
   if (TakeProfit == 0) take = 0;
   if (take == 0) { take = SetTarget(buy);}// if no fixed take profit, check use options for calculating take profit
   bool result = SendSingleTrade(OP_BUY, comment, SendLots, Ask, stop, take, magicR);
   if (result) 
   {  GlobalVariableSet(GvName, 0);
      TradingStatus = opentrade;
      AddReEntryLine(NormalizeDouble(Ask - (ReEntryLinePips * Point), Digits) );
   }//if (result)
}

//############################################              Sell            #################################################
void Sell(string comment)
{
   //if (DoesTradeExist()) return;
   //if (ObjectFind("Re entry line") > -1) ObjectDelete("Re entry line");
   double stop = NormalizeDouble(Bid + (EmergencyStopLoss * Point),Digits);
   if (EmergencyStopLoss == 0) stop = 0;
   double take = NormalizeDouble(Bid - (TakeProfit * Point),Digits);
   if (TakeProfit == 0) take = 0;
   if (take == 0) { take = SetTarget(sell);} // if no fixed take profit, check use options for calculating take profit
   bool result = SendSingleTrade(OP_SELL, comment, SendLots, Bid, stop, take, magicR);
   if (result) 
   {  GlobalVariableSet(GvName, 0);
      TradingStatus = opentrade;
      AddReEntryLine(NormalizeDouble(Bid + (ReEntryLinePips * Point), Digits) );
   }//if (result)
}

//############################################       GetTradeDirection      #################################################
void GetTradeDirection()
{
   double target;
   trend = irrelevant;
   //Is market in the killing zone
   if (KGstatus == 1 && Allow9)
      {target = MiddleWhiteLine;
      disptarget=target;}
   else
   {
      if (Ask <= TopGreenLine && Ask >= BottomGreenLine && Bid <= TopGreenLine && Bid >= BottomGreenLine)
      {  TradeDirection = none;
         TradingStatus = none;
         GlobalVariableDel(GvName);
         return;
      }//if (Ask <= TopGreenLine..
      if (TradeZoneGold ) target = TopGoldLine;
      if (TradeZoneGreen) target = TopGreenLine;
      disptarget=target;

   }
   /*
   Bollinger Bands %b measures the market distance from BB Upperline, so a value of 1 means the
   market is equal the top line; 0 = bottom line; 0.5 = middle line etc. This indi can be used
   to show if there is a decent separation between BB and market
   */
   double BbSeparation = iCustom(NULL, 0, "Bollinger Bands %b", 25, 2, 0, 0, 0);
   double BbBandwidth  = iCustom(NULL, 0, "Bandwidth Indicator", 0, 25, 2, 0, 0, 0, 0);
   
    //Simon's #3 Bulge variable  Steve Mod 03-09-2010
   double screentop = WindowPriceMax(0);   
   double screenbottom = WindowPriceMin(0);   
   double value = screentop - screenbottom;      //value top of the chart - value bottom
   double sixth = value/6;
   double valueS = (value*(MathPow(10,Digits)));
   double sixthS = (sixth*(MathPow(10,Digits)));

   //================= Check for short direction trade setup===================
   if (Ask > target)
   {  
      TradeDirection = down;
      if (StochBlue < 85)                       TradeDirection = none;
      if (UseScoobMod && (FastAtr > SlowAtr))   TradeDirection = none;
      else {      if (MacdVal < OverBought)     TradeDirection = none;}

      //if (MacdVal < OverBought)                 TradeDirection = none;
      if (BbUpper < TopGreenLine)               TradeDirection = none;
      //if (MathAbs(BbUpper - Ma1) < MinSepFromBB * Point) TradeDirection = none;
      if ((1-BbSeparation) < MinSepFromBB)      TradeDirection = none;
      if (AvoidTradingIfObOs && KGstatus == -1) TradeDirection = none; //OS

      if (KGstatus == 1 && Allow9) {TradeDirection = down; TradingStatus = mode9sell; GlobalVariableSet(GvName, 99);   }////non prioritaire mod v25 supprimé return

      if (TradeDirection == down)
      {
         //#1
         if (Ask < BbUpper)  {TradingStatus = mode1sell; GlobalVariableSet(GvName, 11);   }
         //#2
         if (Ask >= BbUpper) {TradingStatus = mode2sell; GlobalVariableSet(GvName, 22);   }
         //#3
         double BulgeTop = NormalizeDouble(screentop-sixth/2, Digits);
         if (BbUpper >= BulgeTop) {TradingStatus = mode3sell; GlobalVariableSet(GvName, 33);  }
         //#4
         if (Ask >= BbUpper - (Mode4DistanceToBB * Point) && Ask <= BbUpper)  //Steve mod 03/09/2010
         {TradingStatus = mode4sell;  GlobalVariableSet(GvName, 44);   }
         //#7
         if (Ask > target && OldBars != Bars)
         {  OldBars = Bars;
            double BearVal = iCustom(NULL, 0, "FX5 MACD DIVERGENCE V1.0", " ", 12, 26, 9, " ", false, false, false, 1, 1);
            if (BearVal != EMPTY_VALUE)  {TradingStatus = mode7sell; GlobalVariableSet(GvName, 77);   }  
         }//if (Ask > Target)
      }//if (TradeDirection == down)
   }//if (Ask > target)

 
   if (KGstatus == -1 && Allow9)
      target = MiddleWhiteLine;
   else
   {
      if (TradeZoneGold ) target = BottomGoldLine;
      if (TradeZoneGreen) target = BottomGreenLine;
   }

   //============  Check for long direction trade setup =================
   if (Bid < target)
   {
      TradeDirection = up;
      if (StochBlue > 15 )                      TradeDirection = none;
      if (UseScoobMod && (FastAtr < SlowAtr))   TradeDirection = none;
      else {      if (MacdVal > OverSold)       TradeDirection = none;}

      
      //if (MacdVal > OverSold)                   TradeDirection = none;
      if (BbLower > BottomGreenLine)            TradeDirection = none;
      //if (MathAbs(BbLower - Ma1) < MinSepFromBB * Point) TradeDirection = none;
      if (BbSeparation < MinSepFromBB)          TradeDirection = none;
      if (AvoidTradingIfObOs &&KGstatus == 1)   TradeDirection = none; //OB

      if (KGstatus == -1 && Allow9) {TradeDirection = up; TradingStatus = mode9buy; GlobalVariableSet(GvName, 9);   }////non prioritaire mod v25     

      if (TradeDirection == up)
      {
         //#1
         if (Bid > BbLower)  {TradingStatus = mode1buy;  GlobalVariableSet(GvName, 1);  }
         //#2
         if (Bid <= BbLower) {TradingStatus = mode2buy;  GlobalVariableSet(GvName, 2);  }
         //#3
         double BulgeBottom = NormalizeDouble(screenbottom+sixth/2, Digits);
         if (BbLower <= BulgeBottom)   {TradingStatus = mode3buy; GlobalVariableSet(GvName, 3);  }
         //#4
         if (Bid <= BbLower + (Mode4DistanceToBB * Point) && Bid >= BbLower)//Steve mod 03/09/2010
         {  TradingStatus = mode4buy;  GlobalVariableSet(GvName, 4);  }
         //#7
         if (Bid < target && OldBars != Bars)
         {  OldBars = Bars;
            double BullVal = iCustom(NULL, 0, "FX5 MACD DIVERGENCE V1.0", " ", 12, 26, 9, " ", false, false, false, 0, 1);
            if (BullVal != EMPTY_VALUE)   {TradingStatus = mode7buy;  GlobalVariableSet(GvName, 7);  }  
         }
      }//if (TradeDirection == up)
   }//if (Bid < target)
}

//############################################     IsDirectionStillValid    #################################################
void IsDirectionStillValid()
{if (TradingStatus == mode9buy || TradingStatus == mode9sell) return;// mod v19

   if (Ask <= TopGreenLine && Ask >= BottomGreenLine && Bid <= TopGreenLine && Bid >= BottomGreenLine)
   {  TradeDirection = none;
      TradingStatus = none;
      GlobalVariableDel(GvName);
   }//if (Ask <= TopGreenLine && Ask >= BottomGreenLine Bid <= TopGreenLine && Bid >= BottomGreenLine)
   if(UseStochWhiteInDirStillValid==1)
   {   
      //Check white line
      if (StochWhite > 30 && StochWhite < 70)
      {  TradeDirection = none;
         TradingStatus = none;
         GlobalVariableDel(GvName);
      }//if (StochWhite > 30 && StochWhite < 70)
   }
}//void IsDirectionStillValid()

//############################################        AddReEntryLine       #################################################
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);     
}

//############################################        WhiteLineClose       #################################################
bool WhiteLineClose(int type)
{  if (OrderProfit() < 0) return(false);
   if (type == OP_BUY)  { if (StochWhite > 85 && StochWhite - StochBlue > MinSeparationFromBlue) return(true); }
   if (type == OP_SELL) { if (StochWhite < 15 && StochBlue - StochWhite > MinSeparationFromBlue) return(true); }
   return(false);
}

//############################################      TradeClosureModule     #################################################
void TradeClosureModule()
{  bool CloseRequired = false;
   if (!CloseRequired)  {  if (UseWhiteLineClosure)   {  CloseRequired = WhiteLineClose(OrderType() );  }  }
   if (CloseRequired) CloseTrade();
}

//############################################        RecoveryModule       #################################################
void RecoveryModule()
{
   //Check that recovery is necessary
   double target = ObjectGet(reentrylinename, OBJPROP_PRICE1); 
   if (OrderType() == OP_BUY) {if (Ask > target) return;}
   if (OrderType() == OP_SELL){if (Bid < target) return;}
   RecoveryStopTrading = false;
   //Count no of open trades. The final one in the sequence will be the one that needs recovery
   CountOpenTrades();
   if (OpenTrades == 0) RecoveryInProgress = false;
   //If 1 trade open, then recovery is at the it's 1rst stage
   if (OpenTrades == 1)
   {  if (RecoveryRentry1Mult==0) RecoveryStopTrading = true;
      else {  SendLots = Lot * RecoveryRentry1Mult;   }
   }
   if (OpenTrades == 2)
   {  if (RecoveryRentry2Mult==0) RecoveryStopTrading = true;
      else { SendLots = Lot * RecoveryRentry2Mult;    }
   }
   if (OpenTrades == 3)
   {  if (RecoveryRentry3Mult==0) RecoveryStopTrading = true;
      else { SendLots = Lot * RecoveryRentry3Mult;    }
   }
   if (OpenTrades == 4)
   { RecoveryStopTrading = true;}

RecoveryInProgress = true;
}

//############################################        TRADING MODULE       #################################################
void Mode1Buy()
{ //if (DoesTradeExist()) return;
   RefreshRates();
   if (Bid < BbLower) { Buy(no1_Buy25); } 
}
void Mode1Sell()
{  //if (DoesTradeExist()) return;
   RefreshRates();
   if (Ask > BbUpper) { Sell(no1_Sel25); }
}
void Mode2Buy()
{  //Equates to #1 Buy 1 MA 25 BB
   //if (DoesTradeExist()) return;
   RefreshRates();
   double  Var1, Var2;
   Var1 = iMA(NULL, 0,  1, 0, MODE_LWMA, PRICE_MEDIAN,  1);
   Var2 = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_LOWER, 1);
   BbLower = iBands(NULL, PERIOD_H4,  25, 2, 0, PRICE_CLOSE, MODE_LOWER, 0); 
   RefreshRates();
   if (Bid > BbLower && Var1 < Var2) { Buy(no2_Buy1MA); }
}
void Mode2Sell()
{  //if (DoesTradeExist()) return;
   RefreshRates();
   double  Var1, Var2;
   Var1 = iMA(NULL, 0,  1, 0, MODE_LWMA, PRICE_MEDIAN,  1);
   Var2 = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_LOWER, 1);
   BbUpper = iBands(NULL, PERIOD_H4,  25, 2, 0, PRICE_CLOSE, MODE_UPPER, 0);
   if( Bid < BbUpper && Var1 > Var2) { Sell(no2_Sel1MA); }
   RefreshRates();
}
void Mode3Buy()
{  //if (DoesTradeExist()) return;
   double  Var1, Var2;
   Var1 = iMA(NULL, 0, 1, 0, MODE_LWMA, PRICE_MEDIAN,  0);
   Var2 = iMA(NULL, 0, 4, 0, MODE_LWMA, PRICE_LOW,  0);
   BbLower = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_LOWER, 0); 
   RefreshRates();
   if(Bid < Var2 && Var1 > BbLower) { Buy(no3_BuyBulge); }    
}
void Mode3Sell()
{  //if (DoesTradeExist()) return;
   double  Var1, Var3;
   Var1 = iMA(NULL, 0, 1, 0, MODE_LWMA, PRICE_MEDIAN,  0);
   Var3 = iMA(NULL, 0, 4, 0, MODE_LWMA, PRICE_HIGH,  0);
   BbUpper = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_UPPER, 0);
   RefreshRates();
   if(Bid  > Var3 && Var1 < BbUpper) { Sell(no3_SelBulge); }
}
void Mode4Buy()
{  //if (DoesTradeExist()) return;
   BbLower = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_LOWER, 0); 
   double Var1 = iMA(NULL, 0,  1, 0, MODE_LWMA, PRICE_MEDIAN,  0);
   double Var2 = iMA(NULL, 0,  3, 1, MODE_LWMA, PRICE_MEDIAN,  0);
   RefreshRates();
   if (Bid  < BbLower || (Bid > Var2 && Var1 < Var2)) { Buy(no4_BuyBB13); }
}
void Mode4Sell()
{  //if (DoesTradeExist()) return;
   BbUpper = iBands(NULL, 0,  25, 2, 0, PRICE_CLOSE, MODE_UPPER, 0);
   double Var1 = iMA(NULL, 0,  1, 0, MODE_LWMA, PRICE_MEDIAN,  0);
   double Var2 = iMA(NULL, 0,  3, 1, MODE_LWMA, PRICE_MEDIAN,  0);
   RefreshRates();
   if(Bid  > BbUpper || (Bid < Var2 && Var1 > Var2)) { Sell(no4_SelBB13); }
}
void Mode7Buy()
{  //if (DoesTradeExist()) return;
   double  Var1, Var2;
   Var1 = iMA(NULL, 0, 1, 0, MODE_LWMA, PRICE_MEDIAN, 1);
   Var2 = iBands(NULL, 0,  25, 2, 3, PRICE_CLOSE, MODE_LOWER, 1); 
   BbLower = iBands(NULL, 0,  25, 2, 3, PRICE_CLOSE, MODE_LOWER, 0); 
   RefreshRates();
   if (Bid > BbLower && Var1 < Var2) 
   { Buy(no7_BuyDivergence);} 
}
void Mode7Sell()
{  //if (DoesTradeExist()) return;
   double  Var1, Var2;
   Var1 = iMA(NULL, 0, 1, 0, MODE_LWMA, PRICE_MEDIAN, 1);
   Var2 = iBands(NULL, 0,  25, 2, 3, PRICE_CLOSE, MODE_LOWER, 1); 
   BbUpper = iBands(NULL, 0,  25, 2, 3, PRICE_CLOSE, MODE_UPPER, 0);
   RefreshRates();
   if( Bid < BbUpper && Var1 > Var2)
   {  Sell(no7_SelDivergence);}
}
void Mode9Buy()
{  //if (DoesTradeExist()) return;
   RefreshRates();
   if (RsiFast < 30 && StochFast < 20 && StochFast>StochFastOld  )   
   { Buy(no9_BuyOS);} 
}
void Mode9Sell()
{  //if (DoesTradeExist()) return;
   RefreshRates();
   if (RsiFast > 70 && StochFast > 80 && StochFast<StochFastOld  )   
   { Buy(no9_SelOB);} 
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{  CptTick++;
   if (CptTick>5)  {CptTick=0 ;Cpt2Tick++;}
   if (Cpt2Tick>20) Cpt2Tick=0;
   string txt6="";
   if (CptTick==0)txt6="|-----";
   if (CptTick==1)txt6="-|----";
   if (CptTick==2)txt6="--|---";
   if (CptTick==3)txt6="---|--";
   if (CptTick==4)txt6="----|-";
   if (CptTick==5)txt6="-----|";
   //PrintLeftBottom(txt6, DarkOrange);
   PrintLeftBottom(txt6 ,"stringCpt",9,"Arial Black", DarkOrange,0,2); //size, font color, vertical, droite

   // ---------------------------------- Time Management
   bool TimeForOpenOK   =true;
   string txttime="TIME";
   color ColorTime=DimGray;
   if (UseTimeManagement)
   {  ColorTime=Green;
      if (DayOfWeek() >= 5 && TimeHour(TimeCurrent()) >= FridayStopHour) TimeForOpenOK = FALSE;//Friday
      if (DayOfWeek() == 1 && TimeHour(TimeCurrent()) < MondayStartHour) TimeForOpenOK = FALSE;//Monday
      if (DayOfWeek() == 0                          )  TimeForOpenOK = FALSE; //Sunday
      //if (TimeHour(TimeCurrent()) >= 18 || TimeHour(TimeCurrent()) <1 )
   }//if (UseTimeManagement)
   if (AvoidNewsHours)
   {  ColorTime=Green;
      // Europe News realease, Summer Paris Time
      if (  (TimeHour(TimeCurrent()) == 10-1 && TimeMinute(TimeCurrent())>=55)    ||    (TimeHour(TimeCurrent()) == 10 && TimeMinute(TimeCurrent())<=5)    )TimeForOpenOK = FALSE;//10h00
      if (  (TimeHour(TimeCurrent()) == 10   && TimeMinute(TimeCurrent())>=25)    &&    (TimeHour(TimeCurrent()) == 10 && TimeMinute(TimeCurrent())<=35)   )TimeForOpenOK = FALSE;//10h30
      if (  (TimeHour(TimeCurrent()) == 11-1 && TimeMinute(TimeCurrent())>=55)    ||    (TimeHour(TimeCurrent()) == 11 && TimeMinute(TimeCurrent())<=5)    )TimeForOpenOK = FALSE;//11h00
      // US News realease, Summer Paris Time
      if (  (TimeHour(TimeCurrent()) == 14-1 && TimeMinute(TimeCurrent())>=55)    ||    (TimeHour(TimeCurrent()) == 14 && TimeMinute(TimeCurrent())<=5)    )TimeForOpenOK = FALSE;//14h00
      if (  (TimeHour(TimeCurrent()) == 14   && TimeMinute(TimeCurrent())>=25)    &&    (TimeHour(TimeCurrent()) == 14 && TimeMinute(TimeCurrent())<=35)   )TimeForOpenOK = FALSE;//14h30
      if (  (TimeHour(TimeCurrent()) == 15-1 && TimeMinute(TimeCurrent())>=55)    ||    (TimeHour(TimeCurrent()) == 15 && TimeMinute(TimeCurrent())<=5)    )TimeForOpenOK = FALSE;//15h00
      if (  (TimeHour(TimeCurrent()) == 16-1 && TimeMinute(TimeCurrent())>=55)    ||    (TimeHour(TimeCurrent()) == 16 && TimeMinute(TimeCurrent())<=5)    )TimeForOpenOK = FALSE;//16h00
      if (  (TimeHour(TimeCurrent()) == 16   && TimeMinute(TimeCurrent())>=25)    &&    (TimeHour(TimeCurrent()) == 16 && TimeMinute(TimeCurrent())<=35)   )TimeForOpenOK = FALSE;//16h30
   }
   if (TimeForOpenOK == FALSE) ColorTime=Red;
   PrintLeftBottom(txttime ,"stringTime",9,"Arial Black", ColorTime,0,110); //size, font color, vertical, droite
   // ---------------------------------- autocalculation of parameters
   if (Cpt2Tick==0 ||ThisIsFirstTick)// only 1 tick on 100
   {  int multi;
      DailyATR = iATR(Symbol(), PERIOD_D1, 14, 0) ; // in 4 digits
      if(Digits == 5 ) multi = 100000;
      if(Digits == 4 ) multi = 10000;
      if(Digits == 3 ) multi = 1000;
      if(Digits == 2 ) multi = 100;
      DailyATR            = DailyATR*multi;
      BreakEvenPips      =NormalizeDouble(DailyATR*BEPips_DATRMult       ,0);  if (BreakEvenPips      <10*multiplier)  BreakEvenPips      =10*multiplier;      
      BreakEvenProfit    =NormalizeDouble(DailyATR*BEProfit_DATRMult     ,0);  if (BreakEvenProfit    <5 *multiplier)  BreakEvenProfit    =5 *multiplier;    
      JumpingStopPips    =NormalizeDouble(DailyATR*JSPips_DATRMult       ,0);  if (JumpingStopPips    <20*multiplier)  JumpingStopPips    =20*multiplier;    
      MinimumTargetinPips=NormalizeDouble(DailyATR*MinimumTarget_DATRMult,0);  if (MinimumTargetinPips<10*multiplier)  MinimumTargetinPips=10*multiplier;
      TrailingStopPips   =NormalizeDouble(DailyATR*TSPips_DATRMult       ,0);  if (TrailingStopPips   <10*multiplier)  TrailingStopPips   =10*multiplier;     

   }
  // ---------------------------------- deviation
   if (CptTick==5 ||ThisIsFirstTick)// only 1 tick on 5
   {
      Deviationfast=iStdDev(NULL,0,15,0,MODE_EMA,PRICE_CLOSE,0);
      Deviationfast=Deviationfast*1.5;
      Deviationslow=iStdDev(NULL,0,40,0,MODE_EMA,PRICE_CLOSE,0);
      if (Deviationfast>Deviationslow) Deviation=Deviationfast;
      else Deviation=Deviationslow;
      //if (Deviation<DailyATR) Deviation=DailyATR;
      if(Digits == 3 ||Digits == 2) Deviation*=100;
      if(Digits == 5 ||Digits == 4) Deviation*=10000;
      //Deviation   =NormalizeDouble(Deviation  ,0);
      ReEntryLinePips    =NormalizeDouble(Deviation*ReEntryPips_DeviationMult  ,0);
      ReEntryLinePips    *= multiplier;
      bool CalmMarket=false;
      if (ReEntryLinePips <DailyATR)  {ReEntryLinePips =DailyATR; CalmMarket=true;}     
   }
  // ---------------------------------- AutoSwitchZone
   if (AutoSwitchZone)
   string txtzone;
   { txtzone="[Zone]";
     if (CalmMarket==true)   {TradeZoneGold =false ;TradeZoneGreen=true; }
      else                    {TradeZoneGold =true ;TradeZoneGreen=false; }
   }
   else
   {txtzone="Zone";
   }
   color ColorZone;
   if (TradeZoneGreen==true) ColorZone=Green;
   if (TradeZoneGold==true) ColorZone=Goldenrod;
   
   PrintLeftBottom(txtzone ,"stringZone",9,"Arial Black", ColorZone,0,50); //size, font color, vertical, droite

  // ---------------------------------- spread protection
   if (CptTick==1 ||ThisIsFirstTick)// only 1 tick on 5
   {  v_ActualSpread = MarketInfo(Symbol(), MODE_SPREAD);
      if (v_ActualSpread>DailyATR*SpreadProtection__DATRMult && UseSpreadProtection )  {  SpreadStopTrading=true;  v_color= Crimson;      }
      else                             {  SpreadStopTrading=false; v_color= LimeGreen;    }
      if (UseSpreadProtection==false) v_color= Gray;
      Printtxt(" Spread" ,"string1",8,"Arial", v_color,0,2); //size, font color, vertical, droite
   }//if (CptTick==1)
   // ---------------------------------- volatility protection
   if (CptTick==3 ||ThisIsFirstTick)// only 1 tick on 5
   {  if (DailyATR>=MaxADr && UseVolatilityProtection )  {  VolatilityStopTrading=true;   v_color= Crimson;  }
      else                   {  VolatilityStopTrading=false;  v_color= LimeGreen;}
      if (UseVolatilityProtection==false) v_color= Gray;
      Printtxt(" Volat." ,"string2",8,"Arial", v_color,0,50); //size, font color, vertical, droite
   }//if (CptTick==2)
   //----------------------------------- MaxLotsPerCurrency                                                  =
   if (CptTick==5 ||ThisIsFirstTick)// only 1 tick on 5
   {  MaxExposure=false;
      if (IsTesting()==false && MaxLotsPerCurr !=999  )

      {
         if (  StringSubstr(Symbol(), 0, 3)=="EUR" || StringSubstr(Symbol(), 3, 3)=="EUR")
         {  EURTotLots  = TotalCurrLOT("EUR");
            if (EURTotLots>=MaxLotsPerCurr) MaxExposure=true;}
         if (  StringSubstr(Symbol(), 0, 3)=="GBP" || StringSubstr(Symbol(), 3, 3)=="GBP")
         {  GBPTotLots  = TotalCurrLOT("GBP");
            if (GBPTotLots>=MaxLotsPerCurr) MaxExposure=true;}
         if (  StringSubstr(Symbol(), 0, 3)=="CAD" || StringSubstr(Symbol(), 3, 3)=="CAD")
         {  CADTotLots  = TotalCurrLOT("CAD");
            if (CADTotLots>=MaxLotsPerCurr) MaxExposure=true;}
         if (  StringSubstr(Symbol(), 0, 3)=="JPY" || StringSubstr(Symbol(), 3, 3)=="JPY")
         {  JPYTotLots  = TotalCurrLOT("JPY");
            if (JPYTotLots>=MaxLotsPerCurr) MaxExposure=true;}
         if (  StringSubstr(Symbol(), 0, 3)=="CHF" || StringSubstr(Symbol(), 3, 3)=="CHF")
         {  CHFTotLots  = TotalCurrLOT("CHF");
            if (CHFTotLots>=MaxLotsPerCurr) MaxExposure=true;}
         if (  StringSubstr(Symbol(), 0, 3)=="USD" || StringSubstr(Symbol(), 3, 3)=="USD")
         {  USDTotLots  = TotalCurrLOT("USD");
            if (USDTotLots>=MaxLotsPerCurr) MaxExposure=true;}
         if (  StringSubstr(Symbol(), 0, 3)=="AUD" || StringSubstr(Symbol(), 3, 3)=="AUD")
         {  AUDTotLots  = TotalCurrLOT("AUD");
            if (AUDTotLots>=MaxLotsPerCurr) MaxExposure=true;}
         if (  StringSubstr(Symbol(), 0, 3)=="NZD" || StringSubstr(Symbol(), 3, 3)=="NZD")
         {  NZDTotLots  = TotalCurrLOT("NZD");
            if (NZDTotLots>=MaxLotsPerCurr) MaxExposure=true;}

         string txt3;
         txt3="Exposure: OK";
         v_color=LimeGreen;
      }//(IsTesting()==false)
   if (MaxExposure==true){txt3="Exposure: MAX"; v_color=Crimson;}
   if (MaxLotsPerCurr ==999) {txt3="Exposure: ---";v_color= Gray;}
   Printtxt(txt3,"string3",8,"Arial", v_color,0,100); //size, font color, vertical, droite
   }//if (CptTick==3)
 
   //----------------------------------- KGstatus
   if (IsTesting()==false && (CptTick==0 ||ThisIsFirstTick))// only 1 tick on 5
   {  KGstatus=0;
      KGstatus=LookingKGstatus(Symbol());
      PrintOBOS("--", DarkGray);
      if(KGstatus == 1)   PrintOBOS("OB", Red); 
      if(KGstatus == -1)  PrintOBOS("OS", Lime); 
   }
   //=======================================  Start  ================================================
   bool TradeExists;
   CountOpenTrades();
   TrendTradingStartFunction();
   if (Use4HTrendline)Trendline4HStartFunction();
//----------------------------------- Recovery
   if (OpenTrades!=old_OpenTrades) // in case manual trade
   {  ObjectDelete(breakevenlinename);
      ObjectDelete(reentrylinename);
      TpMoved = false;
   }
   if (TicketNo > 0) OrderSelect(TicketNo, SELECT_BY_TICKET);
   if (OpenTrades > 1) 
   {  RecoveryInProgress = true;
      if (OrderTakeProfit() == 0) TpMoved = false;
   }
   if (OpenTrades == 0) 
   {  TicketNo = 0;
      RecoveryStopTrading = false;
      RecoveryInProgress = false;
      TpMoved = true;
      SendLots = Lot;
      ObjectDelete(breakevenlinename);
      ObjectDelete(reentrylinename);
   }//if (OpenTrades == 0) 
   
   if (OpenTrades > 0) // in case not the 1st trade, trade green zone for ecovery
   {TradeZoneGold =false ;TradeZoneGreen=true; }
 
   if (RecoveryInProgress && !TpMoved)
   {  buy_price = 0;
      sell_price = 0;
      CheckRecoveryTakeProfit(magicR);
      double recovery_profit;
      if (buy_price > 0) 
      {  recovery_profit = buy_price;
         //if (buy_price < BottomGoldLine) recovery_profit = BottomGoldLine;
         ModifyTakeProfit(recovery_profit);
      }//if (buy_price > 0) 
      
      if (sell_price > 0) 
      {  recovery_profit = sell_price;
         //if (sell_price > TopGoldLine) recovery_profit = TopGoldLine;
         ModifyTakeProfit(recovery_profit);
      }//if (sell_price > 0) 

   }//if (RecoveryInProgress)
   
   //----------------------------------- ReadIndicatorValues
   // ReadIndicatorValues (previously was a separate function)
   GetBB();//Bollinger Bands
   GetSixths();
   GetStoch();
   MacdVal = GetStochMACD(FastEMA, SlowEMA, SignalSMA, StochasticPeriod , 0);
   GetMA();
   if (UseScoobMod)
   {
   FastAtr = iATR(NULL, 0, FastAtrP, 0);
   SlowAtr = iATR(NULL, 0, SlowAtrP, 0);
   }
   else
   MacdVal = GetStochMACD(FastEMA, SlowEMA, SignalSMA, StochasticPeriod , 0);


   if (TradeDirection == none && (OpenTrades == 0 || RecoveryInProgress) ) GetTradeDirection();
   if (TradeDirection != none   /*&&  (KGstatus == 0 || Allow9==false)*/) IsDirectionStillValid();
   
   // °°°°°°°°°°°°°°°°°°°°°°  Display °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
   string txtDir;
   color colorDir=DimGray;
   if (TradeDirection == none) {txtDir="---";}    
   if (TradeDirection == up  ) {colorDir=DarkTurquoise; txtDir="UP";}
   if (TradeDirection == down) {colorDir=RoyalBlue; txtDir="Down";}
   PrintLeftBottom(txtDir ,"stringDir",9,"Arial Black", colorDir,0,160); //size, font color, vertical, droite
   // °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°

   OrderSelect(TicketNo, SELECT_BY_TICKET);
   //OrderSelect(TicketNo, SELECT_BY_TICKET);
   if (OpenTrades > 0 && ObjectFind(reentrylinename) == -1) //recreate rentryline if deleted
   { 
      if (OrderType() == OP_BUY) AddReEntryLine(NormalizeDouble(OrderOpenPrice() - (ReEntryLinePips * Point), Digits) );
      if (OrderType() == OP_SELL)AddReEntryLine(NormalizeDouble(OrderOpenPrice() + (ReEntryLinePips * Point), Digits) );
   }//if (ObjectFind(reentrylinename) == -1) //recreate rentryline if deleted
   if (OpenTrades > 0 && ObjectFind(breakevenlinename) == -1)
      {   if (v_OrderType == OP_BUY)  BreakEvenLineColour=LimeGreen;
          if (v_OrderType == OP_SELL) BreakEvenLineColour=Red;

         ObjectCreate(breakevenlinename,OBJ_HLINE,0,TimeCurrent(), OrderTakeProfit() );
         ObjectSet(breakevenlinename,OBJPROP_COLOR,BreakEvenLineColour);
         ObjectSet(breakevenlinename,OBJPROP_STYLE,STYLE_DASHDOT);
         if (OpenTrades > 1) ObjectSet(breakevenlinename,OBJPROP_WIDTH,2); else  ObjectSet(breakevenlinename,OBJPROP_WIDTH,1);   
      }//if (ObjectFind(breakevenlinename) == -1)

   // ClosingByGlobalProfit
   if (ClosingByGlobalProfit && Globalprofit()> ProfitTarget) CloseAllTrades();   

   color colorSta;
   string txtSta;
  
   old_OpenTrades=OpenTrades; // fin avant tous les returns et avant new countopentrades

   v_OrderProfit=OrderProfit();
   if (OpenTrades > 0 && v_OrderProfit < 0 && UseRecovery)
   {  RecoveryModule();
      colorSta=DarkOrange; 
      txtSta=" WAIT RECOVERY";
      PrintLeftBottom(txtSta ,"stringSta",9,"Arial Black", colorSta,0,210);DisplayUserFeedback();
      if (RecoveryInProgress)
      {
         colorSta=Red; 
         txtSta="RECOVERY";
         PrintLeftBottom(txtSta ,"stringSta",9,"Arial Black", colorSta,0,210);DisplayUserFeedback();
      } 
   }
   if (OpenTrades == 1 && v_OrderProfit > 0)
   {  TradeManagementModule();
      TradeClosureModule();
      colorSta=HotPink; 
      txtSta="1T In Profit";
      PrintLeftBottom(txtSta ,"stringSta",9,"Arial Black", colorSta,0,210); DisplayUserFeedback();
      return;
   }
   /*if (OpenTrades > 1 && v_OrderProfit > 0)
   {
      TradeManagementModule();
      colorSta=DeepPink; 
      txtSta="Last In Profit";
      PrintLeftBottom(txtSta ,"stringSta",9,"Arial Black", colorSta,0,210);DisplayUserFeedback(); 
   }*/
   

  //Trading
   if (StopTrading || RecoveryStopTrading || SpreadStopTrading || VolatilityStopTrading || MaxExposure)
   {
      TradeDirection = none;  v_color=Gray;      
      TradingStatus = stopped; v_color=Red;      
      if (StopTrading)           {TradingStatus = Manual_stopped;                v_color=Red;}
      if (RecoveryStopTrading)   {TradingStatus = stopped_by_Recovery_Max;       v_color=Red;}
      if (SpreadStopTrading)     {TradingStatus = stopped_by_HighSpread;         v_color=Red;}
      if (VolatilityStopTrading) {TradingStatus = stopped_by_HighVolatility;     v_color=Red;}
      if (MaxExposure)           {TradingStatus = MaxExposure_for_this_Currency; v_color=Red;}
      GlobalVariableDel(GvName);
      DisplayUserFeedback();
      return;
   }//if (StopTrading)

   //*     Mod
   if (RecoveryInProgress)
   {
      double target = ObjectGet(reentrylinename, OBJPROP_PRICE1);
      if (OrderType() == OP_BUY)
      {  if (Ask > target)
         {  DisplayUserFeedback();
            return;
         }//if (Ask < target)         
      }//if (OrderType() == OP_BUY)
      
      if (OrderType() == OP_SELL)
      {  if (Bid < target)
         {  DisplayUserFeedback();
            return;
         }//if (Bid > target)
      }//if (OrderType() == OP_SELL)
      
   }//if (RecoveryInProgress)

   //Abort L1 trade if bot is being used to manage Recovery of manual trades Mod STEVE 08-09-10
   if (UseEaToManageRecoveryOnly && OpenTrades == 0)
   {
      DisplayUserFeedback();
      return;
   }//if (UseEaToManageRecoveryOnly && OpenTrades == 0)

   if (TradingStatus == mode1buy  && Allow1 && TimeForOpenOK) {Mode1Buy();   colorSta=DarkTurquoise;     txtSta="#1Buy"; }
   if (TradingStatus == mode1sell && Allow1 && TimeForOpenOK) {Mode1Sell();  colorSta=RoyalBlue;         txtSta="#1Sell";}
   if (TradingStatus == mode2buy  && Allow2 && TimeForOpenOK) {Mode2Buy();   colorSta=DarkTurquoise;     txtSta="#2Buy"; }
   if (TradingStatus == mode2sell && Allow2 && TimeForOpenOK) {Mode2Sell();  colorSta=RoyalBlue;         txtSta="#2Sell";}
   if (TradingStatus == mode3buy  && Allow3 && TimeForOpenOK) {Mode3Buy();   colorSta=DarkTurquoise;     txtSta="#3Buy"; }
   if (TradingStatus == mode3sell && Allow3 && TimeForOpenOK) {Mode3Sell();  colorSta=RoyalBlue;         txtSta="#3Sell";}
   if (TradingStatus == mode4buy  && Allow4 && TimeForOpenOK) {Mode4Buy();   colorSta=DarkTurquoise;     txtSta="#4Buy"; }
   if (TradingStatus == mode4sell && Allow4 && TimeForOpenOK) {Mode4Sell();  colorSta=RoyalBlue;         txtSta="#4Sell";}
   if (TradingStatus == mode7buy  && Allow7 && TimeForOpenOK) {Mode7Buy();   colorSta=DarkTurquoise;     txtSta="#7Buy"; }
   if (TradingStatus == mode7sell && Allow7 && TimeForOpenOK) {Mode7Sell();  colorSta=RoyalBlue;         txtSta="#7Sell";}
   if (TradingStatus == mode9buy  && Allow9 && TimeForOpenOK) {Mode9Buy();   colorSta=DarkTurquoise;     txtSta="#9Buy"; }
   if (TradingStatus == mode9sell && Allow9 && TimeForOpenOK) {Mode9Sell();  colorSta=RoyalBlue;         txtSta="#9Sell";}

   if (AllowTrendMode) TrendTradingStartFunction();

  PrintLeftBottom(txtSta ,"stringSta",9,"Arial Black", colorSta,0,210); //size, font color, vertical, droite
   DisplayUserFeedback();
//----
   return(0);
}
//+------------------------------------------------------------------+
//|    DeleteObj                                                     |
//+------------------------------------------------------------------+
void DeleteObj()
{
   ObjectDelete( "mystring6");
   ObjectDelete( "String1");
   ObjectDelete( "String2");
   ObjectDelete( "String3");
   ObjectDelete( "String4");
   ObjectDelete( "String5");
   ObjectDelete(breakevenlinename);
   ObjectDelete(reentrylinename);
   ObjectDelete( "stringCpt");
   ObjectDelete( "stringZone");
   ObjectDelete( "stringTime");
   ObjectDelete( "stringDir");
   ObjectDelete( "stringSta");
   
}


//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+                          V A R I O U S   S U B R O U T I N E S                                        +
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//############################################   TrendTradingStartFunction   #################################################
void  TrendTradingStartFunction()
{

   TrendRsi = GetTrendRsi(RsiTimeFrame, RsiPeriod);
   GetTrendAtr();
   DisplayUserFeedback();   

   //Is there already a trade open
   bool TradeExists= DoesTradeExist();
   //No need to go further it there is already a trade Open   
   if (TradeExists)
   {      return;   }
   //No trade open, so see if one is possible
   LookForTrendTrades();

}//void  TrendTradingStartFunction()

//############################################      LookForTrendTrades      #################################################
void LookForTrendTrades()
{

   bool SendTrade = false;
   int type;
   double price, take, stop;

   RefreshRates();
   
   //Look for buy opportunity
   if (TrendRsi < RsiOversold && fTrendAtr > sTrendAtr)
   {
      SendTrade = true;
      type = OP_BUY;
      price = Ask;      
      take = NormalizeDouble(Ask + (TrendTakeProfit * Point), Digits);
      stop = NormalizeDouble(Ask - (TrendStopLoss * Point), Digits);
   }//if (TrendRsi < RsiBoxTop && fTrendAtr > sTrendAtr)
   

   //Look for sell opportunity
   if (TrendRsi > RsiOverbought && fTrendAtr < sTrendAtr)
   {
      SendTrade = true;
      type = OP_SELL;
      price = Bid;      
      take = NormalizeDouble(Bid - (TrendTakeProfit * Point), Digits);
      stop = NormalizeDouble(Bid + (TrendStopLoss * Point), Digits);
   }//if (TrendRsi > RsiBoxBottom && sTrendAtr < sTrendAtr)
   
   if (TrendTakeProfit == 0) take = 0;
   if (TrendStopLoss == 0) stop = 0;
   

   //Send trade if conditions are right
   if (SendTrade)
   {
      //SendSingleTrade(type, " ", Lot, price, stop, take, 0);
      SendSingleTrade(type, "Trend", Lot*2, price, stop, take, 0);
   }//if (SendTrade)
   

}//End void LookForTrendTrades()
//############################################         GetTrendRsi          #################################################
double GetTrendRsi(int tf, int period)
{
   double val = iRSI(NULL, tf, period, PRICE_CLOSE, 0);

   return(val);
   
}//double GetTrendRsi(int tf, int period)

//############################################        CloseTrendTrade       #################################################
bool CloseTrendTrade()
{

   bool success = true;
   
   success = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 1000, CLR_NONE);
   
   return(success);
      
}//void DoesTradeNeedClosing()

//############################################          GetTrendAtr         #################################################
void GetTrendAtr()
{
   fTrendAtr = iATR(NULL, 0, FastTrendAtr, 0);
   sTrendAtr = iATR(NULL, 0, SlowTrendAtr, 0);

}//void GetTrendAtr()
//############################################        CountOpenTrades       #################################################
void CountOpenTrades()
{  OpenTrades = 0;
   TicketNo = 0;
   for (int cc = 0; cc < OrdersTotal(); cc++)
   {  if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicR)
      {  v_OrderType=OrderType();
         OpenTrades++;
         TicketNo = OrderTicket();
         //Check for a break even line move
         if (RecoveryInProgress)
         {
            if (ObjectFind(breakevenlinename) > -1)
            {
               double take = ObjectGet(breakevenlinename, OBJPROP_PRICE1);
               if (OrderTakeProfit() != take)
               {
                  OrderModify(TicketNo, OrderOpenPrice(), OrderStopLoss(), take, OrderExpiration(), CLR_NONE);
               }//if (OrderTakeProfit() != ObjectGet(breakevenlinename, OBJPROP_PRICE1) )
            }//if (ObjectFind(breakevenlinename) > -1)

            //Create BE line if one does not exist already - perhaps because of accidental deletion
            if (ObjectFind(breakevenlinename) == -1)
            {   if (v_OrderType == OP_BUY)  BreakEvenLineColour=LimeGreen;
                if (v_OrderType == OP_SELL) BreakEvenLineColour=Red;

               ObjectCreate(breakevenlinename,OBJ_HLINE,0,TimeCurrent(), OrderTakeProfit() );
               ObjectSet(breakevenlinename,OBJPROP_COLOR,BreakEvenLineColour);
               ObjectSet(breakevenlinename,OBJPROP_STYLE,STYLE_DASHDOT);
               if (OpenTrades > 1) ObjectSet(breakevenlinename,OBJPROP_WIDTH,2); else  ObjectSet(breakevenlinename,OBJPROP_WIDTH,1);
            }//if (ObjectFind(breakevenlinename) == -1)
   
         }//if (RecoveryInProgress)
      }//if (OrderSymbol() == Symbol() )
   }//for (int cc = 0; cc < OrdersTotal() - 1; cc++)
}

//############################################        ModifyTakeProfit      #################################################
void ModifyTakeProfit(double NewTake)
{  
   TpMoved = true;
   for (int cc = 0; cc < OrdersTotal(); cc++)
   {  if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() && OrderComment()!=TradeComment && OrderTakeProfit() != NewTake)
      {
         v_OrderTakeProfit=OrderTakeProfit();  
         v_NewTake=NewTake; 
         v_OrderType=OrderType();
         bool result = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), NewTake, OrderExpiration(), CLR_NONE);
		   int err=GetLastError();      
         if (!result && err>1)// mod v42
		   {   TpMoved = false;
             Alert(Symbol(), " TP  order modify failed with error(",err,"): ",ErrorDescription(err));               
		   }//if (!result)			  
      }//if (OrderTakeProfit() != NewTake)
   }//for (int cc = OrdersTotal() -1; cc >= 0; cc--)
   //if(TpMoved)
   //{
   if (v_OrderType == OP_BUY)  BreakEvenLineColour=LimeGreen;
   if (v_OrderType == OP_SELL) BreakEvenLineColour=Red;
   ObjectDelete(breakevenlinename);
   ObjectCreate(breakevenlinename,OBJ_HLINE,0,TimeCurrent(), NewTake);
   ObjectSet(breakevenlinename,OBJPROP_COLOR,BreakEvenLineColour);
   ObjectSet(breakevenlinename,OBJPROP_STYLE,STYLE_DASHDOT);
   if (OpenTrades > 1) ObjectSet(breakevenlinename,OBJPROP_WIDTH,2); else  ObjectSet(breakevenlinename,OBJPROP_WIDTH,1);      //}
}

//############################################     CheckRecoveryTakeProfit   #################################################
void CheckRecoveryTakeProfit(int Magic)
{  ExtLines = 0;
   int    i,col,line;
   ArrayInitialize(ExtSymbolsSummaries,0.0);
   int total=Analyze(Magic);
   if(total>0)
   {  line=0;
      for(i=0; i<ExtSymbolsTotal; i++)
      {  if (ExtSymbols[i] != Symbol() ) continue;
         if(ExtSymbolsSummaries[i][DEALS]<=0) continue;
         line++;
         if(line>ExtLines)//---- add line
         {  int y_dist=ExtVertShift*(line+1)+1;
            ExtLines++;
         }
         //---- set line
         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)
}
//############################################            GetSixths         #################################################
void GetSixths()
{
   double value   = High[iHighest(NULL,0,MODE_HIGH,BarCount,1)] - Low[iLowest(NULL,0,MODE_LOW,BarCount,1)];      //value top of the chart - value bottom
   double sixth   = value/6;
   double valueS  = (value*(MathPow(10,Digits)));
   double sixthS  = (sixth*(MathPow(10,Digits)));
   BottomGoldLine    = NormalizeDouble(Low[iLowest(NULL,0,MODE_LOW,BarCount,1)]+sixth, Digits);
   BottomGreenLine   = NormalizeDouble(Low[iLowest(NULL,0,MODE_LOW,BarCount,1)]+sixth+sixth, Digits);
   MiddleWhiteLine   = NormalizeDouble(Low[iLowest(NULL,0,MODE_LOW,BarCount,1)]+sixth+sixth+sixth, Digits);
   TopGreenLine      = NormalizeDouble(Low[iLowest(NULL,0,MODE_LOW,BarCount,1)]+sixth+sixth+sixth+sixth, Digits);
   TopGoldLine       = NormalizeDouble(Low[iLowest(NULL,0,MODE_LOW,BarCount,1)]+sixth+sixth+sixth+sixth+sixth, Digits);
}

//############################################            GetStoch          #################################################
void GetStoch()
{
   StochWhite    = iStochastic(NULL, 0, 7, 3, 3,  MODE_LWMA, 1, MODE_MAIN, 0);
   StochFast       = iStochastic(NULL, 0, 4, 2, 2,  MODE_EMA, 1, MODE_MAIN, 0);
   StochFastOld    = iStochastic(NULL, 0, 4, 2, 2,  MODE_EMA, 1, MODE_MAIN, 1);
   StochBlue     = iStochastic(NULL, 0, 14, 3, 5, MODE_LWMA, 1, MODE_MAIN, 0);
   RsiFast         = iRSI(NULL, 0, 3, PRICE_CLOSE, 0);
}

//############################################          GetStochMACD        #################################################
double GetStochMACD(int fast_ema_period, int slow_ema_period, int signal_period, int StochasticPeriod, int shift)
{
  double macdSignal;int j;
  // get highest/lowest of macdSignal over StochasticPeriod
  double ll = 100000, hh = -100000, dif;
  for(j=shift; j<shift+StochasticPeriod; j++)
  { macdSignal = iMACD(NULL,0,fast_ema_period, slow_ema_period, signal_period, PRICE_CLOSE,MODE_SIGNAL,j);
    hh = MathMax(hh,macdSignal);
    ll = MathMin(ll,macdSignal);
  }
  // normalize to 0..100
  dif = hh-ll;
  if (dif==0) return (0);
  else return (100 * (iMACD(NULL,0,fast_ema_period, slow_ema_period, signal_period, PRICE_CLOSE,MODE_SIGNAL,shift)-ll)/dif); 
}
//############################################             GetMA           #################################################
void GetMA()
{
   Ma1 = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_CLOSE, 0);
}
//############################################         DoesTradeExist      #################################################
bool DoesTradeExist()
{  TicketNo = 0;
   if (OrdersTotal() == 0) return(false);
   for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)
   {  if (!OrderSelect(cc,SELECT_BY_POS)) continue;
      if ( OrderMagicNumber() == magicR && OrderSymbol() == Symbol() )      
      {  TicketNo = OrderTicket();
         return(true);         
      }//if (OrderMagicNumber()==MagicNumber && OrderSymbol() == Symbol() )      
   }//for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)
   return(false);
}

//############################################           CloseTrade        #################################################
bool CloseTrade()
{  bool result = OrderClose(TicketNo, OrderLots(), OrderClosePrice(), 1000, CLR_NONE);
   if (!result)
   {   string stype;
      if (OrderType() == OP_BUY) stype = "OP_BUY";
      if (OrderType() == OP_BUYSTOP) stype = "OP_BUYSTOP";
      if (OrderType() == OP_SELL) stype = "OP_SELL";
      if (OrderType() == OP_SELLSTOP) stype = "OP_SELLSTOP";
      int err=GetLastError();
      Alert(Symbol(), " ", stype," Nannin order send failed with error(",err,"): ",ErrorDescription(err));
      Print(Symbol(), " ", stype," Nannin order send failed with error(",err,"): ",ErrorDescription(err));
      return(false);
   }//if (!result)
   return(true);
}

//############################################          GetRsiTrend        #################################################
void GetRsiTrend() 
{  //TrendRsiVal = GetRsi(0);
   trend = ranging;
   double tf = RsiTf;
   if (tf == 0) tf = Period();
   TrendRsiVal = iRSI(NULL, tf, RsiPeriod, PRICE_CLOSE, 0);
   if (TrendRsiVal > 55) RsiTrend = up;
   if (TrendRsiVal < 45) RsiTrend = down;
}//End void GetRsiTrend()

//############################################          GetTheTrend        #################################################
void GetTheTrend()
{  trend = "";
   string oldtrend = "";
      GetRsiTrend();
      trend = RsiTrend;
      oldtrend = trend;
}//End void GetTheTrend()

//############################################              GetBB          #################################################
void GetBB()
{  BbUpper = iBands(NULL, 0, 25, 2, 0, PRICE_OPEN, MODE_UPPER, 0);
   BbLower = iBands(NULL, 0, 25, 2, 0, PRICE_OPEN, MODE_LOWER, 0);
}

//############################################          SymbolsIndex       #################################################
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);
}

//############################################            Analyze         #################################################
int Analyze(int Magic)
{  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;
      if(OrderMagicNumber()!=Magic) 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()

//+------------------------------------------------------------------+
//| TotalCurrLOT                                                     |
//+------------------------------------------------------------------+
double TotalCurrLOT(string cur)
{  int i=0; double TotalLots=0;
   while(i<OrdersTotal())
   { OrderSelect(i,SELECT_BY_POS,MODE_TRADES);i++;
     if(StringSubstr(OrderSymbol(), 0, 3)==cur || StringSubstr(OrderSymbol(), 3, 3)==cur )
     TotalLots=TotalLots+OrderLots();
   }
   return(TotalLots);
}
//+------------------------------------------------------------------+
//| LookingKGstatus                                                  |
//+------------------------------------------------------------------+
int   LookingKGstatus(string symbol)
{  ReadbasketRSI(0,0);
   // second stage OB OS
   intermedaire1 = MathMax(JpyKgRS,UsdKgRS);
   intermedaire2 = MathMax(GbpKgRS,EurKgRS);
   intermedaire3 = MathMax(ChfKgRS,AudKgRS);
   intermedaire4 = MathMax(NzdKgRS,CadKgRS);
   intermedaire5 = MathMax(intermedaire1,intermedaire2);
   intermedaire6 = MathMax(intermedaire3,intermedaire4);
   MaxKG         = MathMax(intermedaire5,intermedaire6);
   intermedaire1 = MathMin(JpyKgRS,UsdKgRS);
   intermedaire2 = MathMin(GbpKgRS,EurKgRS);
   intermedaire3 = MathMin(ChfKgRS,AudKgRS);
   intermedaire4 = MathMin(NzdKgRS,CadKgRS);
   intermedaire5 = MathMin(intermedaire1,intermedaire2);
   intermedaire6 = MathMin(intermedaire3,intermedaire4);
   MinKG         = MathMin(intermedaire5,intermedaire6);
   //******************************
   int ret=0;
   if (StringSubstr(symbol, 0, 6) == "AUDCAD")
      {
       if (AudKgRS>UpTrig && CadKgRS<LoTrig) ret=1 ;//OB
       if (AudKgRS<LoTrig && CadKgRS>UpTrig) ret=-1;//OS
       if (AudKgRS>=MaxKG && CadKgRS<=MinKG) ret=1 ;//OB
       if (AudKgRS<=MinKG && CadKgRS>=MaxKG) ret=-1;//OS
      }
   if (StringSubstr(symbol, 0, 6) == "AUDCHF") 
      {
       if (AudKgRS>UpTrig && ChfKgRS<LoTrig) ret=1 ;
       if (AudKgRS<LoTrig && ChfKgRS>UpTrig) ret=-1;
       if (AudKgRS>=MaxKG && ChfKgRS<=MinKG) ret=1 ;
       if (AudKgRS<=MinKG && ChfKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "AUDJPY")
      {
       if (AudKgRS>UpTrig && JpyKgRS<LoTrig) ret=1 ;
       if (AudKgRS<LoTrig && JpyKgRS>UpTrig) ret=-1;
       if (AudKgRS>=MaxKG && JpyKgRS<=MinKG) ret=1 ;
       if (AudKgRS<=MinKG && JpyKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "AUDNZD") 
      {
       if (AudKgRS>UpTrig && NzdKgRS<LoTrig) ret=1 ;
       if (AudKgRS<LoTrig && NzdKgRS>UpTrig) ret=-1;
       if (AudKgRS>=MaxKG && NzdKgRS<=MinKG) ret=1 ;
       if (AudKgRS<=MinKG && NzdKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "AUDUSD") 
      {
       if (AudKgRS>UpTrig && UsdKgRS<LoTrig) ret=1 ;
       if (AudKgRS<LoTrig && UsdKgRS>UpTrig) ret=-1;
       if (AudKgRS>=MaxKG && UsdKgRS<=MinKG) ret=1 ;
       if (AudKgRS<=MinKG && UsdKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "CADCHF") 
      {
       if (CadKgRS>UpTrig && ChfKgRS<LoTrig) ret=1 ;
       if (CadKgRS<LoTrig && ChfKgRS>UpTrig) ret=-1;
       if (CadKgRS>=MaxKG && ChfKgRS<=MinKG) ret=1 ;
       if (CadKgRS<=MinKG && ChfKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "CADJPY") 
      {
       if (CadKgRS>UpTrig && JpyKgRS<LoTrig) ret=1 ;
       if (CadKgRS<LoTrig && JpyKgRS>UpTrig) ret=-1;
       if (CadKgRS>=MaxKG && JpyKgRS<=MinKG) ret=1 ;
       if (CadKgRS<=MinKG && JpyKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "CHFJPY") 
      {
       if (ChfKgRS>UpTrig && JpyKgRS<LoTrig) ret=1 ;
       if (ChfKgRS<LoTrig && JpyKgRS>UpTrig) ret=-1;
       if (ChfKgRS>=MaxKG && JpyKgRS<=MinKG) ret=1 ;
       if (ChfKgRS<=MinKG && JpyKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "EURAUD") 
      {
       if (EurKgRS>UpTrig && AudKgRS<LoTrig) ret=1 ;
       if (EurKgRS<LoTrig && AudKgRS>UpTrig) ret=-1;
       if (EurKgRS>=MaxKG && AudKgRS<=MinKG) ret=1 ;
       if (EurKgRS<=MinKG && AudKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "EURCAD") 
      {
       if (EurKgRS>UpTrig && CadKgRS<LoTrig) ret=1 ;
       if (EurKgRS<LoTrig && CadKgRS>UpTrig) ret=-1;
       if (EurKgRS>=MaxKG && CadKgRS<=MinKG) ret=1 ;
       if (EurKgRS<=MinKG && CadKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "EURCHF") 
      {
       if (EurKgRS>UpTrig && ChfKgRS<LoTrig) ret=1 ;
       if (EurKgRS<LoTrig && ChfKgRS>UpTrig) ret=-1;
       if (EurKgRS>=MaxKG && ChfKgRS<=MinKG) ret=1 ;
       if (EurKgRS<=MinKG && ChfKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "EURGBP") 
      {
       if (EurKgRS>UpTrig && GbpKgRS<LoTrig) ret=1 ;
       if (EurKgRS<LoTrig && GbpKgRS>UpTrig) ret=-1;
       if (EurKgRS>=MaxKG && GbpKgRS<=MinKG) ret=1 ;
       if (EurKgRS<=MinKG && GbpKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "EURJPY") 
      {
       if (EurKgRS>UpTrig && JpyKgRS<LoTrig) ret=1 ;
       if (EurKgRS<LoTrig && JpyKgRS>UpTrig) ret=-1;
       if (EurKgRS>=MaxKG && JpyKgRS<=MinKG) ret=1 ;
       if (EurKgRS<=MinKG && JpyKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "EURNZD") 
      {
       if (EurKgRS>UpTrig && NzdKgRS<LoTrig) ret=1 ;
       if (EurKgRS<LoTrig && NzdKgRS>UpTrig) ret=-1;
       if (EurKgRS>=MaxKG && NzdKgRS<=MinKG) ret=1 ;
       if (EurKgRS<=MinKG && NzdKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "EURUSD") 
      {
       if (EurKgRS>UpTrig && UsdKgRS<LoTrig) ret=1 ;
       if (EurKgRS<LoTrig && UsdKgRS>UpTrig) ret=-1;
       if (EurKgRS>=MaxKG && UsdKgRS<=MinKG) ret=1 ;
       if (EurKgRS<=MinKG && UsdKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "GBPAUD") 
      {
       if (GbpKgRS>UpTrig && AudKgRS<LoTrig) ret=1 ;
       if (GbpKgRS<LoTrig && AudKgRS>UpTrig) ret=-1;
       if (GbpKgRS>=MaxKG && AudKgRS<=MinKG) ret=1 ;
       if (GbpKgRS<=MinKG && AudKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "GBPCAD") 
      {
       if (GbpKgRS>UpTrig && CadKgRS<LoTrig) ret=1 ;
       if (GbpKgRS<LoTrig && CadKgRS>UpTrig) ret=-1;
       if (GbpKgRS>=MaxKG && CadKgRS<=MinKG) ret=1 ;
       if (GbpKgRS<=MinKG && CadKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "GBPCHF") 
      {
       if (GbpKgRS>UpTrig && ChfKgRS<LoTrig) ret=1 ;
       if (GbpKgRS<LoTrig && ChfKgRS>UpTrig) ret=-1;
       if (GbpKgRS>=MaxKG && ChfKgRS<=MinKG) ret=1 ;
       if (GbpKgRS<=MinKG && ChfKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "GBPJPY") 
      {
       if (GbpKgRS>UpTrig && JpyKgRS<LoTrig) ret=1 ;
       if (GbpKgRS<LoTrig && JpyKgRS>UpTrig) ret=-1;
       if (GbpKgRS>=MaxKG && JpyKgRS<=MinKG) ret=1 ;
       if (GbpKgRS<=MinKG && JpyKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "GBPNZD") 
      {
       if (GbpKgRS>UpTrig && NzdKgRS<LoTrig) ret=1 ;
       if (GbpKgRS<LoTrig && NzdKgRS>UpTrig) ret=-1;
       if (GbpKgRS>=MaxKG && NzdKgRS<=MinKG) ret=1 ;
       if (GbpKgRS<=MinKG && NzdKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "GBPUSD") 
      {
       if (GbpKgRS>UpTrig && UsdKgRS<LoTrig) ret=1 ;
       if (GbpKgRS<LoTrig && UsdKgRS>UpTrig) ret=-1;
       if (GbpKgRS>=MaxKG && UsdKgRS<=MinKG) ret=1 ;
       if (GbpKgRS<=MinKG && UsdKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "NZDCAD") 
      {
       if (NzdKgRS>UpTrig && CadKgRS<LoTrig) ret=1 ;
       if (NzdKgRS<LoTrig && CadKgRS>UpTrig) ret=-1;
       if (NzdKgRS>=MaxKG && CadKgRS<=MinKG) ret=1 ;
       if (NzdKgRS<=MinKG && CadKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "NZDCHF") 
      {
       if (NzdKgRS>UpTrig && ChfKgRS<LoTrig) ret=1 ;
       if (NzdKgRS<LoTrig && ChfKgRS>UpTrig) ret=-1;
       if (NzdKgRS>=MaxKG && ChfKgRS<=MinKG) ret=1 ;
       if (NzdKgRS<=MinKG && ChfKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "NZDJPY") 
      {
       if (NzdKgRS>UpTrig && JpyKgRS<LoTrig) ret=1 ;
       if (NzdKgRS<LoTrig && JpyKgRS>UpTrig) ret=-1;
       if (NzdKgRS>=MaxKG && JpyKgRS<=MinKG) ret=1 ;
       if (NzdKgRS<=MinKG && JpyKgRS>=MaxKG) ret=-1;
     }
   if (StringSubstr(symbol, 0, 6) == "NZDUSD") 
      {
       if (NzdKgRS>UpTrig && UsdKgRS<LoTrig) ret=1 ;
       if (NzdKgRS<LoTrig && UsdKgRS>UpTrig) ret=-1;
       if (NzdKgRS>=MaxKG && UsdKgRS<=MinKG) ret=1 ;
       if (NzdKgRS<=MinKG && UsdKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "USDCHF") 
      {
       if (UsdKgRS>UpTrig && ChfKgRS<LoTrig) ret=1 ;
       if (UsdKgRS<LoTrig && ChfKgRS>UpTrig) ret=-1;
       if (UsdKgRS>=MaxKG && ChfKgRS<=MinKG) ret=1 ;
       if (UsdKgRS<=MinKG && ChfKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "USDCAD") 
      {
       if (UsdKgRS>UpTrig && CadKgRS<LoTrig) ret=1 ;
       if (UsdKgRS<LoTrig && CadKgRS>UpTrig) ret=-1;
       if (UsdKgRS>=MaxKG && CadKgRS<=MinKG) ret=1 ;
       if (UsdKgRS<=MinKG && CadKgRS>=MaxKG) ret=-1;
      }
   if (StringSubstr(symbol, 0, 6) == "USDJPY") 
      {
       if (UsdKgRS>UpTrig && JpyKgRS<LoTrig) ret=1 ;
       if (UsdKgRS<LoTrig && JpyKgRS>UpTrig) ret=-1;
       if (UsdKgRS>=MaxKG && JpyKgRS<=MinKG) ret=1 ;
       if (UsdKgRS<=MinKG && JpyKgRS>=MaxKG) ret=-1;
      }
return(ret);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+   ReadbasketRSI                                                  +
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
double ReadbasketRSI(int timeframe, int shift) 
{  double pair_count = 0;
   JpyKgRS = 0;
   UsdKgRS = 0;
   GbpKgRS = 0;
   EurKgRS = 0;
   ChfKgRS = 0;
   AudKgRS = 0;
   NzdKgRS = 0;
   CadKgRS = 0;
// JPY
   if (iClose("GBPJPY", timeframe, shift) != 0.0) {
      JpyKgRS = JpyKgRS + 100 - iRSI("GBPJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURJPY", timeframe, shift) != 0.0) {
      JpyKgRS = JpyKgRS + 100 - iRSI("EURJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDJPY", timeframe, shift) != 0.0) {
      JpyKgRS = JpyKgRS + 100 - iRSI("AUDJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDJPY", timeframe, shift) != 0.0) {
      JpyKgRS = JpyKgRS + 100 - iRSI("NZDJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("CHFJPY", timeframe, shift) != 0.0) {
      JpyKgRS = JpyKgRS + 100 - iRSI("CHFJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("CADJPY", timeframe, shift) != 0.0) {
      JpyKgRS = JpyKgRS + 100 - iRSI("CADJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("USDJPY", timeframe, shift) != 0.0) {
      JpyKgRS = JpyKgRS + 100 - iRSI("USDJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   JpyKgRS=JpyKgRS/pair_count;
// USD
   pair_count = 0;
   if (iClose("GBPUSD", timeframe, shift) != 0.0) {
      UsdKgRS = UsdKgRS + 100 - iRSI("GBPUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURUSD", timeframe, shift) != 0.0) {
      UsdKgRS = UsdKgRS + 100 - iRSI("EURUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDUSD", timeframe, shift) != 0.0) {
      UsdKgRS = UsdKgRS + 100 - iRSI("AUDUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDUSD", timeframe, shift) != 0.0) {
      UsdKgRS = UsdKgRS + 100 - iRSI("NZDUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("USDCHF", timeframe, shift) != 0.0) {
      UsdKgRS = UsdKgRS + iRSI("USDCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("USDCAD", timeframe, shift) != 0.0) {
      UsdKgRS = UsdKgRS + iRSI("USDCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("USDJPY", timeframe, shift) != 0.0) {
      UsdKgRS = UsdKgRS + iRSI("USDJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   UsdKgRS=UsdKgRS/pair_count;
// GBP
   pair_count = 0;
   if (iClose("EURGBP", timeframe, shift) != 0.0) {
      GbpKgRS = GbpKgRS + 100 - iRSI("EURGBP", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("GBPJPY", timeframe, shift) != 0.0) {
      GbpKgRS = GbpKgRS + iRSI("GBPJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("GBPAUD", timeframe, shift) != 0.0) {
      GbpKgRS = GbpKgRS + iRSI("GBPAUD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("GBPNZD", timeframe, shift) != 0.0) {
      GbpKgRS = GbpKgRS + iRSI("GBPNZD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("GBPCHF", timeframe, shift) != 0.0) {
      GbpKgRS = GbpKgRS + iRSI("GBPCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("GBPCAD", timeframe, shift) != 0.0) {
      GbpKgRS = GbpKgRS + iRSI("GBPCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("GBPUSD", timeframe, shift) != 0.0) {
      GbpKgRS = GbpKgRS + iRSI("GBPUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   GbpKgRS=GbpKgRS/pair_count;
// EUR
   pair_count = 0;
   if (iClose("EURGBP", timeframe, shift) != 0.0) {
      EurKgRS = EurKgRS + iRSI("EURGBP", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURJPY", timeframe, shift) != 0.0) {
      EurKgRS = EurKgRS + iRSI("EURJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURAUD", timeframe, shift) != 0.0) {
      EurKgRS = EurKgRS + iRSI("EURAUD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURNZD", timeframe, shift) != 0.0) {
      EurKgRS = EurKgRS + iRSI("EURNZD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURCHF", timeframe, shift) != 0.0) {
      EurKgRS = EurKgRS + iRSI("EURCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURCAD", timeframe, shift) != 0.0) {
      EurKgRS = EurKgRS + iRSI("EURCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURUSD", timeframe, shift) != 0.0) {
      EurKgRS = EurKgRS + iRSI("EURUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   EurKgRS=EurKgRS/pair_count;
// CHF
   pair_count = 0;
   if (iClose("GBPCHF", timeframe, shift) != 0.0) {
      ChfKgRS = ChfKgRS + 100 - iRSI("GBPCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURCHF", timeframe, shift) != 0.0) {
      ChfKgRS = ChfKgRS + 100 - iRSI("EURCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDCHF", timeframe, shift) != 0.0) {
      ChfKgRS = ChfKgRS + 100 - iRSI("AUDCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDCHF", timeframe, shift) != 0.0) {
      ChfKgRS = ChfKgRS + 100 - iRSI("NZDCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("CADCHF", timeframe, shift) != 0.0) {
      ChfKgRS = ChfKgRS + 100 - iRSI("CADCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("USDCHF", timeframe, shift) != 0.0) {
      ChfKgRS = ChfKgRS + 100 - iRSI("USDCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("CHFJPY", timeframe, shift) != 0.0) {
      ChfKgRS = ChfKgRS + iRSI("CHFJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   ChfKgRS=ChfKgRS/pair_count;
// AUD
   pair_count = 0;
   if (iClose("GBPAUD", timeframe, shift) != 0.0) {
      AudKgRS = AudKgRS + 100 - iRSI("GBPAUD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURAUD", timeframe, shift) != 0.0) {
      AudKgRS = AudKgRS + 100 - iRSI("EURAUD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDJPY", timeframe, shift) != 0.0) {
      AudKgRS = AudKgRS + iRSI("AUDJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDNZD", timeframe, shift) != 0.0) {
      AudKgRS = AudKgRS + iRSI("AUDNZD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDCHF", timeframe, shift) != 0.0) {
      AudKgRS = AudKgRS + iRSI("AUDCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDCAD", timeframe, shift) != 0.0) {
      AudKgRS = AudKgRS + iRSI("AUDCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDUSD", timeframe, shift) != 0.0) {
      AudKgRS = AudKgRS + iRSI("AUDUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   AudKgRS=AudKgRS/pair_count;
// NZD
   pair_count = 0;
   if (iClose("GBPNZD", timeframe, shift) != 0.0) {
      NzdKgRS = NzdKgRS + 100 - iRSI("GBPNZD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURNZD", timeframe, shift) != 0.0) {
      NzdKgRS = NzdKgRS + 100 - iRSI("EURNZD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDNZD", timeframe, shift) != 0.0) {
      NzdKgRS = NzdKgRS + 100 - iRSI("AUDNZD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDJPY", timeframe, shift) != 0.0) {
      NzdKgRS = NzdKgRS + iRSI("NZDJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDCHF", timeframe, shift) != 0.0) {
      NzdKgRS = NzdKgRS + iRSI("NZDCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDCAD", timeframe, shift) != 0.0) {
      NzdKgRS = NzdKgRS + iRSI("NZDCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDUSD", timeframe, shift) != 0.0) {
      NzdKgRS = NzdKgRS + iRSI("NZDUSD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   NzdKgRS=NzdKgRS/pair_count;
// CAD
   pair_count = 0;
   if (iClose("GBPCAD", timeframe, shift) != 0.0) {
      CadKgRS = CadKgRS + 100 - iRSI("GBPCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("EURCAD", timeframe, shift) != 0.0) {
      CadKgRS = CadKgRS + 100 - iRSI("EURCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("AUDCAD", timeframe, shift) != 0.0) {
      CadKgRS = CadKgRS + 100 - iRSI("AUDCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("NZDCAD", timeframe, shift) != 0.0) {
      CadKgRS = CadKgRS + 100 - iRSI("NZDCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("CADCHF", timeframe, shift) != 0.0) {
      CadKgRS = CadKgRS + iRSI("CADCHF", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("CADJPY", timeframe, shift) != 0.0) {
      CadKgRS = CadKgRS + iRSI("CADJPY", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   if (iClose("USDCAD", timeframe, shift) != 0.0) {
      CadKgRS = CadKgRS + 100 - iRSI("USDCAD", timeframe, 2, PRICE_WEIGHTED, shift);  pair_count++;}
   CadKgRS=CadKgRS/pair_count;
}
//+-------------------------------------+
//|           PrintOBOS                 +
//+-------------------------------------+
void PrintOBOS(string TextToPrint, color ColorToPrint = -1)
{
   string str = "mystring6";
   if (ObjectFind(str) != 0) {
      ObjectCreate(str, OBJ_LABEL, 0, 0, 0);
      ObjectSet(str, OBJPROP_CORNER, 3);
   }
   ObjectSetText(str, TextToPrint, 12, "Arial Black", ColorToPrint);
   ObjectSet(str, OBJPROP_XDISTANCE, 5);
   ObjectSet(str, OBJPROP_YDISTANCE, 1);
}
/*//+-------------------------------------+
//|           PrintLeftBottom           +
//+-------------------------------------+
void PrintLeftBottom(string TextToPrint, color ColorToPrint = -1) {
   string str = "stringLeftBottom";
   if (ObjectFind(str) != 0) {
      ObjectCreate(str, OBJ_LABEL, 0, 0, 0);
      ObjectSet(str, OBJPROP_CORNER, 2);
   }
   ObjectSetText(str, TextToPrint, 12, "Arial Black", ColorToPrint);
   ObjectSet(str, OBJPROP_XDISTANCE, 5);
   ObjectSet(str, OBJPROP_YDISTANCE, 1);
}*/
//+------------------------------------------------------------------+
//| Printtxt                                                         |
//+------------------------------------------------------------------+
void PrintLeftBottom(string text, string str,int size, string font, color vcolor = -1, double vertical = -1.0, int droite = 0)
{
   if (vertical <= -1.0) vertical = 0;
   if (ObjectFind(str) != 0)
   {
      ObjectCreate(str, OBJ_LABEL, 0, 0, 0);
      ObjectSet(str, OBJPROP_CORNER, 2);
   }
   ObjectSetText(str, text, size, font, vcolor);
   ObjectSet(str, OBJPROP_XDISTANCE, 5 + droite);
   ObjectSet(str, OBJPROP_YDISTANCE, 1 );
}

//+------------------------------------------------------------------+
//| Printtxt                                                         |
//+------------------------------------------------------------------+
void Printtxt(string text, string str,int size, string font, color vcolor = -1, double vertical = -1.0, int droite = 0) {
   if (vertical == -1.0) vertical = 0;
   if (ObjectFind(str) != 0)
   {
      ObjectCreate(str, OBJ_LABEL, 0, 0, 0);
      ObjectSet(str, OBJPROP_CORNER, 0);
   }
   ObjectSetText(str, text, size, font, vcolor);
   ObjectSet(str, OBJPROP_XDISTANCE, 0 + droite);
   ObjectSet(str, OBJPROP_YDISTANCE, 0 + 14.0 * vertical);
}
//############################################        BreakEvenStopLoss   #################################################
void BreakEvenStopLoss() 
{// Move stop loss to breakeven
   bool result;
   if (OrderType()==OP_BUY)
         {
            if (Bid >= OrderOpenPrice () + (Point*BreakEvenPips) && 
                OrderStopLoss()<OrderOpenPrice())
            {
               result = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(BreakEvenProfit*Point),OrderTakeProfit(),0,CLR_NONE);
               if (result && ShowAlerts==true) Alert("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
               Print("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
               if (!result)
               {
                  int err=GetLastError();
                  if (ShowAlerts==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 && ShowAlerts)      
            }
   	   }               			         
          
   if (OrderType()==OP_SELL)
         {
           if (Ask <= OrderOpenPrice() - (Point*BreakEvenPips) &&
              (OrderStopLoss()>OrderOpenPrice()|| OrderStopLoss()==0)) 
            {
               result = OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(BreakEvenProfit*Point),OrderTakeProfit(),0,CLR_NONE);
               if (result && ShowAlerts==true) Alert("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
               Print("Breakeven set on ", OrderSymbol(), " ticket no ", OrderTicket());
               if (!result && ShowAlerts)
               {
                  err=GetLastError();
                  if (ShowAlerts==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 && ShowAlerts)      
            }    
         }
}

//############################################        JumpingStopLoss      #################################################
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()) return(0);}
  
   double sl=OrderStopLoss(); //Stop loss

   if (OrderType()==OP_BUY)
   {
      // 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 (ShowAlerts==true) Alert("Jumping stop set at breakeven ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
               Print("Jumping stop set at breakeven: ", OrderSymbol(), ": SL ", sl, ": Ask ", Bid);
            }//if (result)
            if (!result)
            {
               int err=GetLastError();
               if (ShowAlerts) Alert(OrderSymbol(), " 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 (ShowAlerts==true) Alert("Jumping stop set at ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
            Print("Jumping stop set: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
         }//if (result)
         if (!result)
         {
            err=GetLastError();
            if (ShowAlerts) 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)
   {
      // 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 (result)
            if (!result)
            {
               err=GetLastError();
               if (ShowAlerts) 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 (ShowAlerts==true) Alert("Jumping stop set at ",sl, " ", OrderSymbol(), " ticket no ", OrderTicket());
            Print("Jumping stop set: ", OrderSymbol(), ": SL ", sl, ": Ask ", Ask);
         }//if (result)          
         if (!result)
         {
            err=GetLastError();
            if (ShowAlerts) 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)

}

//############################################        TrailingStopLoss      #################################################
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 (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);}
               else {int err=GetLastError(); Print(OrderSymbol(), " order modify failed with error(",err,"): ",ErrorDescription(err)); }
		       }//if (Bid > sl +  (TrailingStopPips*Point))
		   }//if (Bid >= OrderOpenPrice() + (TrailingStopPips*Point))
      }//if (OrderType()==OP_BUY) 

      if (OrderType()==OP_SELL) 
      {
		   if (Ask <= OrderOpenPrice() - (TrailingStopPips*Point))
		   {
		       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);}
                  else {err=GetLastError(); Print(OrderSymbol(), " order modify failed with error(",err,"): ",ErrorDescription(err));}
		       }//if (Ask < sl -  (TrailingStopPips*Point))
		   }//if (Ask <= OrderOpenPrice() - (TrailingStopPips*Point))
      }//if (OrderType()==OP_SELL) 
}

//############################################        TradeManagementModule      #################################################
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)
   
   //if (NoOfTicks >= 10)
   //{
   //   NoOfTicks = 0;//Reset the counter
      if(BreakEven)     BreakEvenStopLoss();
      if(JumpingStop)   JumpingStopLoss();
      if(TrailingStop)  TrailingStopLoss();
   //}//if (NoOfTicks >= 10)
}
//+------------------------------------------------------------------+
//| Globalprofit                                                     |  
//+------------------------------------------------------------------+
double Globalprofit()
{
   int i=0;double profTrade=0;
   while(i<OrdersTotal())
   { OrderSelect(i,SELECT_BY_POS,MODE_TRADES);  i++;
     profTrade+=OrderProfit();}
   return(profTrade);
}

//+------------------------------------------------------------------+
//| CloseAllTrades()                                                    |
//+------------------------------------------------------------------+
void CloseAllTrades()
{
      for(int i1=OrdersTotal()-1; i1>=0; i1--)
      { OrderSelect(i1,SELECT_BY_POS,MODE_TRADES);
         if(OrderType()==OP_BUY)  OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),MarketInfo(Symbol(),MODE_SPREAD),Yellow);
         if(OrderType()==OP_SELL) OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),MarketInfo(Symbol(),MODE_SPREAD),Yellow);
      }//for(int......
}
///////////////////////////  4h trend functions
void GetAtrTrend()
{
   double PriceNow = Bid;
   double tf = AtrTf;
   if (AtrTf == 0) tf = Period();
   double ComparePrice = iOpen(NULL, tf, DaysToLookBack);
   
   TrendAtrVal = iATR(NULL, tf, AtrPeriod, 0);

   double x2TrendAtrVal = TrendAtrVal * 2;
   
   AtrTrend = ranging;
   if (PriceNow > ComparePrice) 
   {
      double TrendLevel = NormalizeDouble(ComparePrice + x2TrendAtrVal, Digits);
      if (Ask > TrendLevel) AtrTrend = up;
   }//if (PriceNow > ComparePrice) 
   
   if (PriceNow < ComparePrice) 
   {
      TrendLevel = NormalizeDouble(ComparePrice - x2TrendAtrVal, Digits);
      if (Bid < TrendLevel) AtrTrend = down;
   }//if (PriceNow > ComparePrice) 
   

}//End void GetAtrTrend()

void GetAdxTrend()
{
   AdxTrend = ranging;
   double tf = AdxTf;
   if (AdxTf == 0) tf = Period();
   double PreviousAdxVal = iADX(NULL, tf, AdxPeriod, PRICE_CLOSE, MODE_MAIN, 1);
   

   AdxVal = iADX(NULL, tf, AdxPeriod, PRICE_CLOSE, MODE_MAIN, 0);
   AdxPlusDI = iADX(NULL, tf, AdxPeriod, PRICE_CLOSE, MODE_PLUSDI, 0);
   AdxMinusDI = iADX(NULL, tf, AdxPeriod, PRICE_CLOSE, MODE_MINUSDI, 0);
   
   if (AdxVal < PreviousAdxVal) return;//No trend so nothing to do
   
   if (AdxPlusDI > AdxMinusDI)//trend is up
   {
      AdxTrend = up;
      return;
   }//if (AdxPlusDI > AdxMinusDI) 
   
   //Trend is neither up nor ranging
   AdxTrend = down;
   
}//End void GetAdxTrend()

double iLsma(int tf,int shift)
{
   //Code to calculate LSMA value. Copied from MrPip's work. Many thanks, MrPip
   
   double wt;
   
   double ma1=iMA(NULL,LSMATf,LSMAPeriod,0,MODE_SMA ,PRICE_CLOSE,shift);
   double ma2=iMA(NULL,LSMATf,LSMAPeriod,0,MODE_LWMA,PRICE_CLOSE,shift);
   wt = MathFloor((3.0*ma2-2.0*ma1)/Point) * Point;
   return(wt);
}//double iLsma(int LSMAPeriod,int shift)  

string GetLsmaTrend(int tf, int shift)
{
   LsmaTrend = ranging;
   double lsma_cur, lsma_prev;
   
   lsma_cur = iLsma(tf, shift);
   lsma_prev = iLsma(tf, shift + 1);
   if (lsma_cur > lsma_prev) LsmaTrend = up;
   if (lsma_cur < lsma_prev) LsmaTrend = down;
   
   return(LsmaTrend);

}//End string GetLsmaTrend()

void GetRsiTrend4H()  //==================== Idem
{
   //TrendRsiVal = GetRsi(0);
   trend4HT = ranging;
   double tf = RsiTf4H;
   if (tf == 0) tf = Period();
   
   double TrendRsiVal4H = iRSI(NULL, tf, RsiPeriod, PRICE_CLOSE, 0);

   if (TrendRsiVal4H > 55) RsiTrend4H = up;
   if (TrendRsiVal4H < 45) RsiTrend4H = down;
}

void CalculateTrendLine()
{

   Leg2 = 0; Leg1 = 0;
   int PointsFound, cc;
   Leg2Time = 0; Leg1Time = 0;
   ObjectDelete(oldtrendlinename);
   
   //Find rising zigzag for downtrend
   if (trend4HT == down)
   {
      double dHigh = High[0];
      Leg1 = 0;
      Leg2 = High[0];
      Leg2Time = Time[0];
      if (High[1] > High[0])
      {
         dHigh = High[1];
         Leg2 = High[1];
         Leg2Time = Time[1];
      }//if (High[1} < High[0])
      cc = 1;
      
         
      while (Leg1 == 0)
      {
         cc++;         
         if (cc == Bars) return;
      
         double hi = High[cc];
         if (hi > Leg2 && (Leg2Time - Time[cc] > (8 * 3600)) && hi > dHigh && High[cc + 1] <= hi)
         {
            Leg1 = hi;
            Leg1Time = Time[cc];
         }//if (hi > Leg2 && (Leg2Time - Time[cc] > (8 * 3600)) && hi > dHigh)
         if (High[cc] > dHigh) dHigh = High[cc];
         
         if (Leg1 > 0)
         {
            ObjectCreate(TrendLineName, OBJ_TREND, 0, Leg1Time, Leg1, Leg2Time, Leg2);
            ObjectSet(TrendLineName, OBJPROP_COLOR, TrendLineColour);

        }//if (Leg1 > 0)
      }//while (Leg1 == 0)
   }//if (trend4HT == down)

   
   //Find falling zigzag for uptrend
   if (trend4HT == up)
   {
      Leg1 = 0;
      Leg2 = Low[0];
      Leg2Time = Time[0];
      double dLow = Low[0];
      if (Low[1] < Low[0])
      {
         dLow = Low[1];
         Leg2 = Low[1];
         Leg2Time = Time[1];
      }//if (Low[1} < Low[0])
      
      cc = 1;
         
      while (Leg1 == 0)
      {
         cc++;         
         if (cc == Bars) return;
      
         double lo = Low[cc];
         if (lo < Leg2 && (Leg2Time - Time[cc] > (8 * 3600)) && lo < dLow)
         {
            Leg1 = lo;
            Leg1Time = Time[cc];
         }//if (lo < Leg2 && (Leg2Time - Time[cc] > (8 * 3600)) && lo < dLow)
         if (Low[cc] < dLow) dLow = Low[cc];
         
         if (Leg1 > 0)
         {
            ObjectCreate(TrendLineName, OBJ_TREND, 0, Leg1Time, Leg1, Leg2Time, Leg2);
            ObjectSet(TrendLineName, OBJPROP_COLOR, TrendLineColour);
        }//if (Leg1 > 0)
      }//while (Leg1 == 0)
   }//if (trend4HT == up)
   
}//End void CalculateTrendLine()


void DrawTrendLine(color lc, string name)
{
   //lc = line colour
   ObjectCreate(name, OBJ_TREND, 0, Leg1Time, Leg1, Leg2Time, Leg2);
   ObjectSet(name, OBJPROP_COLOR, lc);
               

}//void DrawTrendLine(color lc, string name)


void GetTheTrend4HT()
{
   trend4HT = "";
   string oldtrend = "";
   
   //Rsi
   if (UseRsi)
   {
      GetRsiTrend4H();
      trend4HT = RsiTrend4H;
      oldtrend = trend4HT;
   }//if (UseRsi)
   
   //Rsi
   if (UseAtr)
   {
      GetAtrTrend();
      trend4HT = AtrTrend;
      if (trend4HT != oldtrend && oldtrend != "")
      {
         trend4HT = confused;
         return;
      }//if (trend4HT != oldtrend)
      oldtrend = trend4HT;
   }//if (UseRsi)
   
   //Axx
   if (UseAdx)
   {
      GetAdxTrend();
      trend4HT = AdxTrend;
      if (trend4HT != oldtrend && oldtrend != "")
      {
         trend4HT = confused;
         return;
      }//if (trend4HT != oldtrend)
      oldtrend = trend4HT;
   }//if (UseRsi)
   
   //LSMA - MrPips
   if (UseLSMA)
   {
      string PrevTrend = GetLsmaTrend(LSMATf, 1);
      LsmaTrend = GetLsmaTrend(LSMATf, 0);  
      if (LsmaTrend == up && (PrevTrend == ranging || PrevTrend == down) ) trend4HT = up;
      if (LsmaTrend == down && (PrevTrend == ranging || PrevTrend == up) ) trend4HT = down;   
      trend4HT = LsmaTrend;
      if (trend4HT != oldtrend && oldtrend != "")
      {
         trend4HT = confused;
         return;
      }//if (trend4HT != oldtrend)
      oldtrend = trend4HT;
   }//if (UseLSMA)
   //Alert(LsmaTrend);
  
}//End void GetTheTrend4HT()

bool SendSingleTrade4HT(int type4HT, string comment4HT, double lotsize4HT, double price4HT, double stop4HT, double take4HT, int magic4HT)
{
   int slippage = 10;
   if (Digits == 3 || Digits == 5) slippage = 100;
   
   color col = Red;
   if (type4HT == OP_BUY || type4HT == OP_BUYSTOP) col = Green;
   
   int expiry = 0;
   
   if (SendMarketTrades)
   {
      if (!CriminalIsECN) int ticket4HT = OrderSend(Symbol(),type4HT, lotsize4HT, price4HT, slippage, stop4HT, take4HT, comment4HT, magic4HT, expiry, col);
   
   
      //Is a 2 stage criminal
      if (CriminalIsECN)
      {
         ticket4HT = OrderSend(Symbol(),type4HT, lotsize4HT, price4HT, slippage, 0, 0, comment4HT, magic4HT, expiry, col);
	      if (stop4HT != 0)
	      {
		      if (ticket4HT > 0)
		      bool result = OrderModify(ticket4HT, OrderOpenPrice(), stop4HT, take4HT, 0, CLR_NONE);
		      if (!result)
		      {
		          int err=GetLastError();
                Print(Symbol(), " ", type4HT," SL  order modify failed with error(",err,"): ",ErrorDescription(err));               
		      }//if (!result)			  
	      }//if (Sl != 0)
      
      
      }//if (CriminalIsECN)
   }//if (SendMarketTrades)
   
   if (SendPendingTrades) 
   {
      expiry = TimeCurrent() + (PendingExpiryMinutes * 60);
      ticket4HT = OrderSend(Symbol(),type4HT, lotsize4HT, price4HT, slippage, stop4HT, take4HT, comment4HT, magic4HT, expiry, col);   
   }//if (SendPendingTrades) 
    
   //Error trapping for both
   if (ticket4HT < 0)
   {
      string stype;
      if (type4HT == OP_BUY) stype = "OP_BUY";
      if (type4HT == OP_BUYSTOP) stype = "OP_BUYSTOP";
      if (type4HT == OP_SELL) stype = "OP_SELL";
      if (type4HT == OP_SELLSTOP) stype = "OP_SELLSTOP";
      err=GetLastError();
      Alert(Symbol(), " ", stype," David H4 order send failed with error(",err,"): ",ErrorDescription(err));
      Print(Symbol(), " ", stype," David H4 order send failed with error(",err,"): ",ErrorDescription(err));
      return(false);
   }//if (ticket4HT < 0)  
   
   //Got this far, so trade send succeeded
   Sleep(5000);
   //Recovery
   OpenTrades4HT++;
   if (OpenTrades4HT > 1)
   {
      TpMoved4HT = false;
      RecoveryInProgress4HT = true;
   }//if (OpenTrades4HT > 1)
   
   return(true);
   
}//End bool SendSingleTrade4HT(int type4HT, string comment4HT, double lotsize4HT, double price, double stop4HT, double take4HT)

bool DoesTradeExist4HT()
{
   
   TicketNo4HT = 0;
   
   if (OrdersTotal() == 0) return(false);
   
   for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)
   {
      if (!OrderSelect(cc,SELECT_BY_POS)) continue;
      
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == magic4HT)      
      {
         TicketNo4HT = OrderTicket();
         return(true);         
      }//if (OrderMagicNumber()==MagicNumber && OrderSymbol() == Symbol() )      
   }//for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)

   return(false);

}//End bool DoesTradeExist4HT()




double SetTarget4HT(string tradedirection4HT)
{
   
   double EntryPrice;   
   double target4HT = 0;
   
   double MinDist=MarketInfo(Symbol(),MODE_STOPLEVEL);
   
   RefreshRates();
   if (tradedirection4HT == sell) // SELL
   {
      EntryPrice = Bid;
      if (SendPendingTrades)
      {
         EntryPrice = NormalizeDouble(Bid - (PendingOrderPipsDistance * Point), Digits);
      }//if (SendPendingTrades)
      
      target4HT = NormalizeDouble(EntryPrice - (TakeProfit4HT * Point),Digits);
      if (UseAtrTp) // use Atr
      {         
         double AtrVal = iATR(Symbol(), AtrTpTimeFrame, AtrTpPeriod, 0) * AtrTpMultiplier;
         if (AtrVal<MinDist) AtrVal=MinDist;
         target4HT = NormalizeDouble(EntryPrice - AtrVal,Digits);
      }//if (UseAtrTp) 
      
   }//if (tradedirection4HT == sell)
   
   if (tradedirection4HT == buy) // BUY
   {
      EntryPrice = Ask;
      if (SendPendingTrades)
      {
         EntryPrice = NormalizeDouble(Ask + (PendingOrderPipsDistance * Point), Digits);
      }//if (SendPendingTrades)
      
      target4HT = NormalizeDouble(EntryPrice + (TakeProfit4HT * Point),Digits);
      if (UseAtrTp) // use Atr
      {
         EntryPrice = Ask;
         AtrVal = iATR(Symbol(), AtrTpTimeFrame, AtrTpPeriod, 0) * AtrTpMultiplier;
         if (AtrVal<MinDist) AtrVal=MinDist;
         target4HT = NormalizeDouble(Bid + AtrVal,Digits);
      }//if (UseAtrTp) 
      
      
   }//if (tradedirection4HT == buy)
   return (NormalizeDouble(target4HT,Digits));
}//End double SetTarget4HT(string tradedirection4HT)

void Buy4HT(string comment4HT)
{
     /* if ( DoesTrendTradeExist() )
   { CloseTrendTrade(99); } */
   
   
   RefreshRates();
   double EntryPrice = Ask;
   int type4HT = OP_BUY;
   if (SendPendingTrades) 
   {
      type4HT = OP_BUYSTOP;
      EntryPrice = NormalizeDouble(Ask + (PendingOrderPipsDistance * Point), Digits);
   }//if (SendPendingTrades) 
   
   double stop4HT = NormalizeDouble(EntryPrice - (EmergencyStopLoss4H * Point),Digits);
   if (EmergencyStopLoss4H == 0) stop4HT = 0;
   double take4HT = SetTarget4HT(buy);
   
   
   bool result = false;
   int loop;
   
   while (result == false)
   {
      result = SendSingleTrade4HT(type4HT, comment4HT, SendLots, EntryPrice, stop4HT, take4HT, magic4HT);
      if (result) 
      {
         if (UseRecovery) AddReEntryLine4HT(OP_BUY);
      }//if (result)
      else
      {
         loop++;
         if (loop == 2) return;
         if (!result)Sleep(5000);
      }
   }//while (result == false)   
   
}//End void Buy4HT(string comment4HT)


void Sell4HT(string comment4HT)
{
  /* if ( DoesTrendTradeExist() )
   { CloseTrendTrade(9); } */
   
   
   RefreshRates();
   int type4HT = OP_SELL;
   double EntryPrice = Bid;   
   if (SendPendingTrades) 
   {
      type4HT = OP_SELLSTOP;
      EntryPrice = NormalizeDouble(Bid - (PendingOrderPipsDistance * Point), Digits);
   }//if (SendPendingTrades) 
   
   double stop4HT = NormalizeDouble(EntryPrice + (EmergencyStopLoss4H * Point),Digits);
   if (EmergencyStopLoss4H == 0) stop4HT = 0;
   double take4HT = SetTarget4HT(sell);
   

   bool result = false;
   int loop;

   while (result == false)
   { 
      result = SendSingleTrade4HT(type4HT, comment4HT, SendLots, EntryPrice, stop4HT, take4HT, magic4HT);
      if (result) 
      {
         TradingStatus4HT = opentrade;
         if (UseRecovery) AddReEntryLine4HT(OP_SELL);
      }//if (result)
      loop++;
      if (loop == 20) return;
      if (!result)Sleep(5000);
   }//while (result == false)
      
}//End void Sell4HT(string comment4HT)


void AddReEntryLine4HT(int type4HT)
{
      if (ObjectFind(ReEntryLine4HTname) > -1) ObjectDelete(ReEntryLine4HTname);   
      
      RefreshRates();
      
      if (type4HT == OP_BUY)
      {
         double LinePrice = NormalizeDouble(Ask - (ReEntryLine4HTPips * Point), Digits);
         ObjectCreate(ReEntryLine4HTname,OBJ_HLINE,0,TimeCurrent(),LinePrice);
         ObjectSet(ReEntryLine4HTname,OBJPROP_COLOR,ReEntryLine4HTColour);
         ObjectSet(ReEntryLine4HTname,OBJPROP_STYLE,STYLE_SOLID);
         ObjectSet(ReEntryLine4HTname,OBJPROP_WIDTH,2);     

      }//if (type4HT == OP_BUY)
      
      if (type4HT == OP_SELL)
      {
         LinePrice = NormalizeDouble(Bid + (ReEntryLine4HTPips * Point), Digits);
         ObjectCreate(ReEntryLine4HTname,OBJ_HLINE,0,TimeCurrent(),LinePrice);
         ObjectSet(ReEntryLine4HTname,OBJPROP_COLOR,ReEntryLine4HTColour);
         ObjectSet(ReEntryLine4HTname,OBJPROP_STYLE,STYLE_SOLID);
         ObjectSet(ReEntryLine4HTname,OBJPROP_WIDTH,2);     

      }//if (type4HT == OP_SELL)



}//void AddReEntryLine4HT(int type)

//1.1.3.3 RECOVERY MODULE
void RecoveryModule4H()
{
   //My thanks to sundog for coding the change to 1.1.3.3
   //Check that recovery is necessary
   TargetPrice4HT = ObjectGet(ReEntryLine4HTname, OBJPROP_PRICE1);

   if (OrderType() == OP_BUY)
   {
      if (Ask > TargetPrice4HT) return;
   }//if (OrderType() == OP_BUY)
   
   if (OrderType() == OP_SELL)
   {
      if (Bid < TargetPrice4HT) return;
   }//if (OrderType() == OP_SELL)
   
   //Count no of open trades. The final one in the sequence will be the one that needs recovery
   //CountOpenTrades4HT();
            
   
   //If 1 trade open, then recovery is at the 1 stage
   if (OpenTrades4HT == 1)
   {
      //SendMagicNumber = MagicNumber + 30;
      SendLots = Lot * 1;
   }//if (OpenTrades4HT == 1)
   
   
   //If 2 trades open, then recovery is at the 3 stage
   if (OpenTrades4HT == 2)
   {
      //SendMagicNumber = MagicNumber + 60;
      SendLots = Lot * 3;
   }//if (OpenTrades4HT == 2)
   
   //If 3 trades open, then recovery is at the sedond 3  stage
   if (OpenTrades4HT == 3)
   {
      //SendMagicNumber = MagicNumber + 90;
      SendLots = Lot * 3;
   }//if (OpenTrades4HT == 3)
   
   //Stop trading if the full 4-trade position is open
   if (OpenTrades4HT == 4)
   {
      SuspendTrading = true;
   }//if (OpenTrades4HT == 4)
   
   RecoveryInProgress4HT = true;

   if (OpenTrades4HT < 4)
   {
      int PrevOpenTrades = OpenTrades4HT;

      
      //Buy
      if (OrderType() == OP_BUY && Low[0] <= TargetPrice4HT && Ask > Open[0])
      {
         Buy4HT(TradeComment);      
      }//if (OrderType() == OP_BUY && Low[0] <= TargetPrice4HT && Ask > Open[0])
   
      //Sell4HT
      if (OrderType() == OP_SELL && High[0] >= TargetPrice4HT && Bid < Open[0])
      {
         Sell4HT(TradeComment);
      }//if (OrderType() == OP_SELL && High[0] >= TargetPrice4HT && Bid < Open[0])
   }//if (OpenTrades4HT < 4)
   
   if (OpenTrades4HT > PrevOpenTrades)
   {
      ObjectDelete(ReEntryLine4HTname);
      AddReEntryLine4HT(OrderType() );
   }//if (OpenTrades4HT > PrevOpenTrades)
   
   
}//End void RecoveryModule()

void CountOpenTrades4HT()
{
   OpenTrades4HT = 0;
   TicketNo4HT = 0;

   if (OrdersTotal() == 0) return;
   
   for (int cc = 0; cc <= OrdersTotal(); cc++)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == magic4HT)
      {
         OpenTrades4HT++;
         TicketNo4HT = OrderTicket();
      }//if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol() )
   }//for (int cc = 0; cc < OrdersTotal() - 1; cc++)   
}//End void CountOpenTrades4HT();

void ModifyTakeProfit4HT(double NewTake)
{

   TpMoved4HT = true;
   
   for (int cc = OrdersTotal() -1; cc >= 0; cc--)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) ) continue;      
      if (OrderSymbol() == Symbol() && OrderTakeProfit() != NewTake)
      {
         bool result = OrderModify(OrderTicket(), OrderOpenPrice(), OrderStopLoss(), NewTake, OrderExpiration(), CLR_NONE);
         if (!result) TpMoved4HT = false;
      }//if (OrderTakeProfit() != NewTake) 
   
   }//for (int cc = OrdersTotal() -1; cc >= 0; cc--)
   

}//End void ModifyTakeProfit(double NewTake);



//}//End void CheckRecoveryTakeProfit()


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 Trendline4HStartFunction()
{
//----

   if (TrendIsUp) trend4HT = up;
   if (TrendIsDown) trend4HT = down;
   if (AutoDetectTrend) GetTheTrend4HT();
   
   bool TradeExists4HT;
   OpenTrades4HT = 0;
   
   if (OrdersTotal() > 0) CountOpenTrades4HT();
   if (OpenTrades4HT > 1) RecoveryInProgress4HT = true;
   if (OpenTrades4HT == 0) 
   {
      RecoveryInProgress4HT = false;
      TpMoved4HT = true;
      SendLots = Lot;
      SuspendTrading = false;
      //SendMagicNumber = MagicNumber;
      if (ObjectFind(oldtrendlinename) > -1) ObjectDelete(oldtrendlinename);
      if (ObjectFind(TrendLineName) == -1) CalculateTrendLine();
      else Leg2Time = ObjectGet(TrendLineName, OBJPROP_TIME2);
   }//if (OpenTrades4HT == 0) 
   
   if (RecoveryInProgress4HT && !TpMoved4HT)
   {
      //TradeExists4HT = DoesTradeExist4HT();//Identifies and selects the most recent trade
      CheckRecoveryTakeProfit(magic4HT);
      if (buy_price4HT > 0) ModifyTakeProfit4HT(buy_price4HT);
      if (sell_price4HT > 0) ModifyTakeProfit4HT(sell_price4HT);      
   }//if (RecoveryInProgress4HT)
   ///////////////////////////////////////////////////////////////////////////////////////////////
   //Trade closure and management
   if (OrdersTotal() > 0) TradeExists4HT = DoesTradeExist4HT();
   
   if (TradeExists4HT)
   {
      if (OrderProfit() < 0 && UseRecovery) 
      {
         //1.1.3.3 recovery   
         RecoveryModule4H();
         
      }//if (OrderProfit() < 0) 
      
   }//if (TradeExists4HT)
   ///////////////////////////////////////////////////////////////////////////////////////////////
      
   /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   //Trading times
   bool TradeTimeOk = CheckTradingTimes();
   if (!TradeTimeOk)
   {
      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)
   /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

       
   ///////////////////////////////////////////////////////////////////////////////////////////////         
   //Trading
   
   if (StopTrading || SuspendTrading)
   {
      TradingStatus4HT = stopped;
      DisplayUserFeedback();
      return;
   }//if (StopTrading || SuspendTrading)
   
   if (OpenTrades4HT > 0) 
   {
      DisplayUserFeedback();
      SuspendTrading = false;
      return;
   }//if (OpenTrades4HT > 0) 
   
   int PrevOpenTrades = OpenTrades4HT;
   
   //Abort trade if conditions are wrong
   TargetPrice4HT = 0;
   TargetPrice4HT = ObjectGetValueByShift(TrendLineName, 0);
   if (TargetPrice4HT == 0 || Time[0] == Leg2Time) 
   {
      //Re-calculate trend line if Time[0] is Leg2 and the market has pierced the trend line
      if (trend4HT == down && (Bid > TargetPrice4HT || TargetPrice4HT == 0) )
      {
         ObjectDelete(TrendLineName);
         CalculateTrendLine();         
      }//if ( (trend4HT == down)
   
      if (trend4HT == up && (Ask < TargetPrice4HT || TargetPrice4HT == 0) )
      {
         ObjectDelete(TrendLineName);
         CalculateTrendLine();         
      }//if (trend4HT == up)
   
      
      DisplayUserFeedback();
      return;
   }//if (TargetPrice4HT == 0) 
   
   //////////////////////////////////////////////////////////////////////////////////////
   //Trading
   
   //Buy
   if (trend4HT == up && Low[0] <= TargetPrice4HT && Ask > Low[0])
   {
      Buy4HT(TradeComment);      
   }//if (trend4HT == up && Bid <= TargetPrice4HT)
   
   //Sell4HT
   if (trend4HT == down && High[0] >= TargetPrice4HT && Bid < High[0])
   {
      Sell4HT(TradeComment);
   }//if (trend4HT == down && Ask >= TargetPrice4HT)
   
   //Delete existing trend line and replace with a different-coloured replica.
   //This both leaves the trader with a record of where the trend line was, and prepares
   //the robot for a replacement when the trade closes
   if (OpenTrades4HT > PrevOpenTrades)
   {
      Leg1 = ObjectGet(TrendLineName, OBJPROP_PRICE1);
      Leg2 = ObjectGet(TrendLineName, OBJPROP_PRICE2);
      Leg1Time = ObjectGet(TrendLineName, OBJPROP_TIME1);
      Leg2Time = ObjectGet(TrendLineName, OBJPROP_TIME2);
      ObjectDelete(TrendLineName);
      DrawTrendLine(TrendLineRecordColour, oldtrendlinename);
   }//if (OpenTrades4HT > PrevOpenTrades)
     
   ///////////////////////////////////////////////////////////////////////////////////////////////      
   
   DisplayUserFeedback();
   
//----
   return(0);
}