//+------------------------------------------------------------------+
//|                        .........................Scoop_V01.mq4    |
//|                        Copyright 2019, candyman752 and merlin    |
//|                             http://www.forexfactory.com          |
//+------------------------------------------------------------------+

#define  version " Scoop Version 01 "
//
#property copyright "Copyright 2020, candyman752 and merlin"
#property link      "http://www.forexfactory.com"
#include <WinUser32.mqh>
#include <stdlib.mqh>
#define  NL    "\n"


#define  AllTrades 10 //Tells CloseAllTrades() to close/delete everything
#define  million 1000000;

//Define the FifoBuy/SellTicket fields for offsetting
#define  TradeTicket 1


//Pending trade price line
#define  pendingpriceline "Pending price line"
//Hidden sl and tp lines. If used, the bot will close trades on a touch/break of these lines.
//Each line is named with its appropriate prefix and the ticket number of the relevant trade
#define  TpPrefix "Tp"
#define  SlPrefix "Sl"
#define  ESlPrefix "ESl"

//Error reporting
#define  slm " stop loss modification failed with error "
#define  tpm " take profit modification failed with error "
#define  ocm " order close failed with error "
#define  odm " order delete failed with error "
#define  pcm " part close failed with error "
#define  spm " shirt-protection close failed with error "
#define  slim " stop loss insertion failed with error "
#define  tpim " take profit insertion failed with error "
#define  tpsl " take profit or stop loss insertion failed with error "
#define  oop " pending order price modification failed with error "



extern string  gen="----General inputs----";
/*
Note to coders about TradingTimeFrame. Be consistent in your calls to indicators etc and always use TradingTimeFrame i.e.
double v = iClose(Symbol(), TradingTimeFrame, shift) instead of Close[shift].
This allows the user to change time frames without disturbing the ea. There is a line of code in OnInit(), just above the call
to DisplayUserFeedback() that forces the EA to wait until the open of a new TradingTimeFrame candle; you might want to comment
this out during your EA development.
*/
extern ENUM_TIMEFRAMES  TradingTimeFrame=PERIOD_M15;// 15min
extern bool             EveryTickMode=False;
extern bool             UseTickClosure=True;
extern double           Lot=0.01;
extern double           RiskPercent=0;//Set to zero to disable and use Lot
extern double           LotsPerDollopOfCash=0;//Over rides Lot. Zero input to cancel.
extern int              SizeOfDollop=400;
extern bool             UseBalance=false;
extern bool             UseEquity=true;
extern bool             StopTrading=false;
extern int              DeletePendingAfterThisManyMinutes =1200;
//extern bool             TradeLong=true;
//extern bool             TradeShort=true;
//extern bool             PositiveSwapTradesOnly=false;
bool                    PositiveSwapOnly;
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
extern string  rkmi="---- Risk Mitigation  ----";
extern double           MaxAllowableCashLoss=29;//Only close all trades when the negative cash upl is less than this.
                                       //Converted into a negative value in OnInit()   
extern string  ltcbs="---- Only Kicks In If Both Buys and Sells Are Open ----";
extern double           LossToCloseBuyOrSellTrades=27;
//extern double           ProfitUpl=10;//
//xtern double           ProfitBuffer=1.0;
//extern int              TrailLock=4;
//extern int              TrailGap=5;
//extern int              TradesOpen=1;

 double pcrisk                                     =0.30;
 double MoneyRisk                                  =0.8; // Offset Factor
 int    Signal                                     =1;   // Display signals mode: 1-Signals & Stops; 0-only Stops; 2-only Signals;
 int    Line                                       =1;   // Display line mode: 0-no,1-yes  
 int    Nbars                                      =40;
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
extern string  asep3="------------------------------------------------";
extern int     MagicNumber=0;
extern double  MaxSlippagePips=5;
//We need more safety to combat the cretins at Crapperquotes managing to break Matt's OR code occasionally.
//EA will make no further attempt to trade for PostTradeAttemptWaitMinutes minutes, whether OR detects a receipt return or not.
extern int     PostTradeAttemptWaitSeconds=10;//Defaults to 10 minutes
////////////////////////////////////////////////////////////////////////////////////////
datetime       TimeToStartTrading=0;//Re-start calling LookForTradingOpportunities() at this time.
double         TakeProfit, StopLoss;
datetime       OldBarsTime;
double         dPriceFloor = 0, dPriceCeiling = 0;//Next x0 numbers
double         PriceCeiling100 = 0, PriceFloor100 = 0;// Next 'big' numbers
double         Level1Pips,Level2Pips;
double         ND(double vax) {return (NormalizeDouble( vax , Digits));}
 
string         GvName="Under management flag";//The name of the GV that tells the EA not to send trades whilst the manager is closing them.
//'Close all trades this pair only script' sets a GV to tell EA's not to attempt a trade during closure
string         LocalGvName = "Local closure in operation " + Symbol();
//'Nuclear option script' sets a GV to tell EA's not to attempt a trade during closure
string         NuclearGvName = "Nuclear option closure in operation " + Symbol();

string         TradingTimeFrameDisplay="";
//For FIFO
int            FifoTicket[];//Array to store trade ticket numbers in FIFO mode, to cater for
                            //US citizens and to make iterating through the trade closure loop 
                            //quicker.
//An array to store ticket numbers of trades that need closing, should an offsetting OrderClose fail
double         ForceCloseTickets[];
bool           RemoveExpert=false;
////////////////////////////////////////////////////////////////////////////////////////
extern string  xses="----Pips Between Market And Pending Orders----";
 int           TradesMiniBufferPips=4;
double         TradeMiniBuffer=0;
/////////xxxxxxxxxxxxxxxxxxxxxxx#############################################
bool           BrokerHasSundayCandle;
bool           BrokerHasSundayCandles=false;
/////////xxxxxxxxxxxxxxxxxxxxxxx#############################################
extern string  sep1zx="================================================================";
extern string  StopsOrLimits="---- Send Stops Or Limits inputs ----";
//Variables to tell the ea that it has a trading signal
 int     PeakyCandles= 820;
////////////////////////////////////////////////////////////////////////////////////////
extern string  trailt="----TrailTrades----";
extern bool     UseTrailStop=false; 
extern int      JumpStep=14;
extern int      BEProfit=3;
extern int      SLMinDistanceToPriceBE=6;
extern int      SLMinDistanceToPriceJS=17;
////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////

extern string  sep1a="================================================================";
extern string  sfs="----SafetyFeature----";
//Safety feature. Sometimes an unexpected concatenation of inputs choice and logic error can cause rapid opening-closing of trades. Use the next input 
//in combination with TooClose() to abort the trade if the previous one closed within the time limit.
 int     MinMinutesBetweenTradeOpenClose=0;//For spotting possible rogue trades
 int     MinMinutesBetweenTrades=0;//Minimum time to pass after a trade closes, until the ea can open another.
////////////////////////////////////////////////////////////////////////////////////////
bool           SafetyViolation;//For chart display
bool           RobotSuspended=false;
////////////////////////////////////////////////////////////////////////////////////////

extern string  sep3="================================================================";
//Hidden tp/sl inputs.
extern string  hts="----Stealth stop loss and take profit inputs----";
extern int     PipsHiddenFromCriminal=0;//Added to the 'hard' sl and tp and used for closure calculations
                                         ////////////////////////////////////////////////////////////////////////////////////////
double         HiddenStopLoss,HiddenTakeProfit;
double         HiddenPips=0;//Added to the 'hard' sl and tp and used for closure calculations
                             ////////////////////////////////////////////////////////////////////////////////////////

extern string  sep7="================================================================";
//CheckTradingTimes. Baluda has provided all the code for this. Mny thanks Paul; you are a star.
extern string  trh            = "----Trading hours----";
extern string  tr1            = "tradingHours is a comma delimited list";
extern string  tr1a="of start and stop times.";
extern string  tr2="Prefix start with '+', stop with '-'";
extern string  tr2a="Use 24H format, local time.";
extern string  tr3="Example: '+07.00,-10.30,+14.15,-16.00'";
extern string  tr3a="Do not leave spaces";
extern string  tr4="Blank input means 24 hour trading.";
extern string  tradingHours="";
////////////////////////////////////////////////////////////////////////////////////////
double         TradeTimeOn[];
double         TradeTimeOff[];
// trading hours variables
int            tradeHours[];
string         tradingHoursDisplay;//tradingHours is reduced to "" on initTradingHours, so this variable saves it for screen display.
bool           TradeTimeOk;
////////////////////////////////////////////////////////////////////////////////////////

extern string  sep1de="================================================================";
extern string  fssmt="---- Inputs applied to individual days ----";
//extern int     FridayStopTradingHour=24;//Ignore signals at and after this time on Friday.
                                        //Local time input. >23 to disable.
//extern int     MondayCloseAllHour=24;//Friday time to close all open trades/delete stop orders for the weekend.
                                     //Local time input. >23 to disable.
//extern int     TuesdayCloseAllHour=24;//Friday time to close all open trades/delete stop orders for the weekend.
                                     //Local time input. >23 to disable.
//extern int     WednesdayCloseAllHour=24;//Friday time to close all open trades/delete stop orders for the weekend.
                                     //Local time input. >23 to disable.
//extern int     ThursdayCloseAllHour=24;//Friday time to close all open trades/delete stop orders for the weekend.
                                     //Local time input. >23 to disable.
//extern int     FridayCloseAllHour=24;//Friday time to close all open trades/delete stop orders for the weekend.
                                     //Local time input. >23 to disable.
//extern int     SaturdayStopTradingHour=24;//For those in Upside Down Land.  
//extern int     SaturdayCloseAllHour=24;//For those in Upside Down Land.  
                                       //Local time input. >23 to disable.
//extern int     MaxAllowableCashLoss=-30;//Only close all trades when the negative cash upl is less than this.
//                                       //Converted into a negative value in OnInit()   
//extern bool    TradeSundayCandle=false;
//extern int     MondayStartHour=0;//24h local time          
//extern double  EndHourStopsSent=23.30;

// bool    TradeThursdayCandle=true;//Thursday tends to be a reversal day, so avoid it.                               

//This code by tomele. Thank you Thomas. Wonderful stuff.
extern string  sep7b="================================================================";
extern string  roll="---- Rollover time ----";
extern bool    DisableEaDuringRollover=false;
extern string  ro1 = "Use 24H format, SERVER time.";
extern string  ro2 = "Example: '23.55'";
extern string  RollOverStarts="23.55";
extern string  RollOverEnds="00.05";
////////////////////////////////////////////////////////////////////////////////////////
bool           RolloverInProgress=false;//Tells DisplayUserFeedback() to display the rollover message
////////////////////////////////////////////////////////////////////////////////////////


extern string  sep10="================================================================";
extern string  amc="----Available Margin checks----";
extern string  sco="Scoobs";
extern bool    UseScoobsMarginCheck=false;
extern string  fk="ForexKiwi";
extern bool    UseForexKiwi=false;
extern int     FkMinimumMarginPercent=300;
////////////////////////////////////////////////////////////////////////////////////////
bool           EnoughMargin;
string         MarginMessage;
////////////////////////////////////////////////////////////////////////////////////////

extern string  sep11="================================================================";
extern string  asi="----Average spread inputs----";
bool    RunInSpreadDetectionMode=false;
extern int     TicksToCount=5;//The ticks to count whilst canculating the av spread
extern double  MultiplierToDetectStopHunt=10;
////////////////////////////////////////////////////////////////////////////////////////
double         AverageSpread=0;
string         SpreadGvName;//A GV will hold the calculated average spread
int            CountedTicks=0;//For status display whilst calculating the spread
double         BiggestSpread=0;//Holds a record of the widest spread since the EA was loaded
////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////////

//Enhanced screen feedback display code provided by Paul Batchelor (lifesys). Thanks Paul; this is fantastic.
extern string  se52  ="================================================================";
extern string  oad               ="----Odds and ends----";
extern int     ChartRefreshDelaySeconds=3;
extern int     DisplayGapSize    = 30; // if using Comments
// ****************************** added to make screen Text more readable
extern bool    DisplayAsText     = true;  // replaces Comment() with OBJ_LABEL text
extern bool    KeepTextOnTop     = true;//Disable the chart in foreground CrapTx setting so the candles do not obscure the text
extern int     DisplayX          = 100;
extern int     DisplayY          = 0;
extern int     fontSise          = 10;
extern string  fontName          = "Arial";
extern color   colour            = White;
extern int      Piip01             =1;
extern int      Piip02             =2;
extern int      Piip05             =5;
extern int      Piip10             =10;
extern int      Piip20             =20;
int Pip01;int Pip02;int Pip05;int Pip10;int Pip20;
////////////////////////////////////////////////////////////////////////////////////////
int            DisplayCount;
string         Gap,ScreenMessage;
bool           dummyResult;
////////////////////////////////////////////////////////////////////////////////////////
double         longSwap=0, shortSwap=0;
//##################################################################################
//##################################################################################
//-----
//-----
string EquityCloseProfit          = "Equity Close Profit";
string BuyCloseProfit             = "Buy Close Profit";
string SellCloseProfit            = "Sell CLose Profit";
///////////////##################################################################################
      double entryLevel1 = 0;      double entryLevel2 = 0;      datetime Time1 = 0;      datetime Time2 = 0;      int T1 =0;      int T2 =0;
///  *****************************
      double entryLevel3 = 0;      double entryLevel4 = 0;      datetime Time3 = 0;      datetime Time4 = 0;
/////###
      double entryLevel5 = 0;      double entryLevel6 = 0;      datetime Time5 = 0;      datetime Time6 = 0;
/////###
      double entryLevel7 = 0;      double entryLevel8 = 0;      datetime Time7 = 0;      datetime Time8 = 0;
/////////xxxxxxxxxxxxxxxxxxxxxxx#############################################
double digiter;

int             eDigits;
/////////xxxxxxxxxxxxxxxxxxxxxxx#############################################
extern string  sep1g="================================================================";
//---- buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];
double ExtMapBuffer5[];
double ExtMapBuffer6[];
double ExtMapBuffer7[];
double ExtMapBuffer8[];
double ExtMapBufferHT1[];
double ExtMapBufferHT2[];
double ExtMapBufferHT3[];
double ExtMapBufferHT4[];
double ExtMapBufferHT5[];
double ExtMapBufferHT6[];
double ExtMapBufferHT7[];
double ExtMapBufferHT8[];

//Calculating the factor needed to turn pip values into their correct points value to accommodate different Digit size.
//Thanks to Lifesys for providing this code. Coders, you need to briefly turn of Wrap and turn on a mono-spaced font to view this properly and see how easy it is to make changes.
//string         pipFactor[]  = {"JPY","XAG","SILVER","BRENT","WTI","XAU","GOLD","SP500","S&P","UK100","WS30","DAX30","DJ30","NAS100","CAC400"};
//double         pipFactors[] = { 100,  100,  100,     100,    100,  10,   10,    10,     10,   1,      1,     1,      1,     1,       1};
//And by Steve. I have pinched Tomasso's APTM function for returning the value of factor. Thanks Tommaso
double         factor;//For pips/points stuff. Set up in int init()
////////////////////////////////////////////////////////////////////////////////////////

//Matt's O-R stuff
int            O_R_Setting_max_retries=10;
double         O_R_Setting_sleep_time=4.0; /* seconds */
double         O_R_Setting_sleep_max=15.0; /* seconds */
int            RetryCount=10;//Will make this number of attempts to get around the trade context busy error.


//Running total of trades
int            LossTrades,WinTrades;
double         OverallProfit;

//Misc
int            OldBars;
string         PipDescription=" pips";
bool           ForceTradeClosure;
int            TurnOff=0;//For turning off functions without removing their code

//Variables for building a picture of the open position
int            MarketTradesTotal=0;//Total of open market trades
//Market Buy trades
bool           BuyOpen=false;
int            MarketBuysCount=0;
double         LatestBuyPrice=0, EarliestBuyPrice=0, HighestBuyPrice=0, LowestBuyPrice=0;
int            BuyTicketNo=-1, HighestBuyTicketNo=-1, LowestBuyTicketNo=-1, LatestBuyTicketNo=-1, EarliestBuyTicketNo=-1;
double         BuyPipsUpl=0;
double         BuyCashUpl=0;
datetime       LatestBuyTradeTime=0;
datetime       EarliestBuyTradeTime=0;

//Market Sell trades
bool           SellOpen=false;
int            MarketSellsCount=0;
double         LatestSellPrice=0, EarliestSellPrice=0, HighestSellPrice=0, LowestSellPrice=0;
int            SellTicketNo=-1, HighestSellTicketNo=-1, LowestSellTicketNo=-1, LatestSellTicketNo=-1, EarliestSellTicketNo=-1;;
double         SellPipsUpl=0;
double         SellCashUpl=0;
datetime       LatestSellTradeTime=0;
datetime       EarliestSellTradeTime=0;

//BuyStop trades
bool           BuyStopOpen=false;
int            BuyStopsCount=0;
double         LatestBuyStopPrice=0, EarliestBuyStopPrice=0, HighestBuyStopPrice=0, LowestBuyStopPrice=0;
int            BuyStopTicketNo=-1, HighestBuyStopTicketNo=-1, LowestBuyStopTicketNo=-1, LatestBuyStopTicketNo=-1, EarliestBuyStopTicketNo=-1;;
datetime       LatestBuyStopTradeTime=0;
datetime       EarliestBuyStopTradeTime=0;

//BuyLimit trades
bool           BuyLimitOpen=false;
int            BuyLimitsCount=0;
double         LatestBuyLimitPrice=0, EarliestBuyLimitPrice=0, HighestBuyLimitPrice=0, LowestBuyLimitPrice=0;
int            BuyLimitTicketNo=-1, HighestBuyLimitTicketNo=-1, LowestBuyLimitTicketNo=-1, LatestBuyLimitTicketNo=-1, EarliestBuyLimitTicketNo=-1;;
datetime       LatestBuyLimitTradeTime=0;
datetime       EarliestBuyLimitTradeTime=0;

/////SellStop trades
bool           SellStopOpen=false;
int            SellStopsCount=0;
double         LatestSellStopPrice=0, EarliestSellStopPrice=0, HighestSellStopPrice=0, LowestSellStopPrice=0;
int            SellStopTicketNo=-1, HighestSellStopTicketNo=-1, LowestSellStopTicketNo=-1, LatestSellStopTicketNo=-1, EarliestSellStopTicketNo=-1;;
datetime       LatestSellStopTradeTime=0;
datetime       EarliestSellStopTradeTime=0;

//SellLimit trades
bool           SellLimitOpen=false;
int            SellLimitsCount=0;
double         LatestSellLimitPrice=0, EarliestSellLimitPrice=0, HighestSellLimitPrice=0, LowestSellLimitPrice=0;
int            SellLimitTicketNo=-1, HighestSellLimitTicketNo=-1, LowestSellLimitTicketNo=-1, LatestSellLimitTicketNo=-1, EarliestSellLimitTicketNo=-1;;
datetime       LatestSellLimitTradeTime=0;
datetime       EarliestSellLimitTradeTime=0;

//Not related to specific order types
int            TicketNo=-1,OpenTrades,OldOpenTrades;
//Variables to tell the ea that it has a trading signal
bool           BuySignal=false, SellSignal=false;
//Variables to tell the ea that it has a trading closure signal
bool           BuyCloseSignal=false, SellCloseSignal=false;
//Variables for storing market trade ticket numbers
datetime       LatestTradeTime=0, EarliestTradeTime=0;//More specific times are in each individual section
int            LatestTradeTicketNo=-1, EarliestTradeTicketNo=-1;
double         PipsUpl;//For keeping track of the pips PipsUpl of multi-trade/hedged positions
double         CashUpl;//For keeping track of the cash PipsUpl of multi-trade/hedged positions
//Variable for the hedging code to tell if there are tp's and sl's set
bool           TpSet=false, SlSet=false;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DisplayUserFeedback()
{

   if(IsTesting() && !IsVisualMode()) return;

   string text = "";

   //cpu saving
   static datetime CurrentTime = 0;
   static datetime DisplayNow = 0;
   if (TimeCurrent() < DisplayNow )
      return;
   CurrentTime = TimeCurrent();
   DisplayNow = CurrentTime + ChartRefreshDelaySeconds;

 
 
//   ************************* added for OBJ_LABEL
   DisplayCount = 1;
   removeAllObjects();
//   *************************

   ScreenMessage="";
   //ScreenMessage = StringConcatenate(ScreenMessage,Gap + NL);
   SM(NL);
   if(SafetyViolation) SM("*************** CANNOT TRADE YET. TOO SOON AFTER CLOSE OF PREVIOUS TRADE***************"+NL);

   SM("Updates for this EA are to be found at http://www.forexfactory.com"+NL);
   SM("Feeling generous? Help keep the coder going with a small Paypal donation to pianodoodler@hotmail.com"+NL);
   SM("Broker time = "+TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS)+": Local time = "+TimeToStr(TimeLocal(),TIME_DATE|TIME_SECONDS)+NL);
   SM(version+NL);
/*
   //Code for time to bar-end display donated by Baluda. Cheers Paul.
   SM( TimeToString( iTime(Symbol(), TradingTimeFrame, 0) + TradingTimeFrame * 60 - CurTime(), TIME_MINUTES|TIME_SECONDS ) 
   + " left to bar end" + NL );
   */
   if(!TradeTimeOk)
   {
      SM(NL);
      SM("---------- OUTSIDE TRADING HOURS. Will continue to monitor opent trades. ----------"+NL+NL);
   }//if (!TradeTimeOk)

   if(RolloverInProgress)
   {
      SM(NL);
      SM("---------- ROLLOVER IN PROGRESS. I am taking no action until "+RollOverEnds+" ----------"+NL+NL);
      return;
   }//if (RolloverInProgress)
 
   SM(NL);
   /////////////////////////////////////////////////////////////////////////////////////
///------------------------------------
   double spread = (Ask - Bid) * factor;
//#############################################
// SM("TimeCurrent: "+ IntegerToString(TimeCurrent())+NL);
// SM("Time Of S00: "+ IntegerToString(TimeOfOrderWithThisComment("S00"))+NL);
// SM("TimeCurrent: "+ IntegerToString((TimeCurrent() - TimeOfOrderWithThisComment("S00") ) / 60 / 60)+NL);
 
/*   (SM("B36: "+ DoubleToStr(B36(),5)+NL);      SM("B38: "+ DoubleToStr(B38(),5)+NL);   SM("B39: "+ DoubleToStr(B39(),5)+NL);   SM("B40: "+ DoubleToStr(B40(),5)+NL);   SM("B41: "+ DoubleToStr(B41(),5)+NL);   SM("B42: "+ DoubleToStr(B42(),5)+NL);*/
//   SM("HighestClosePrice(PERIOD_H4,3, Bar(PERIOD_H4,PERIOD_D1,0) - 2): "+ DoubleToStr( iOpen(Symbol(), PERIOD_H4,HighestHighBar(PERIOD_H4,3,2) ) ,5)+NL);  
//   SM("  Bar(PERIOD_H4,PERIOD_D1,0)  " + StringToInteger(  b01   )
//   +NL);
/*  
   if(TidaneGreeni(Symbol(),Period(),20,2) )
   SM("Tidane Green : " +NL);
   if(TidaneRedi(Symbol(),Period(),20,2) )
   SM("Tidane Red : " +NL);
      SM("Tidane Green Price: "+ DoubleToStr( TidaneGreenPricei(Symbol(),Period(),20,2),5)
         + NL);
      SM("Tidane Red Price: "+ DoubleToStr( TidaneRedPricei(Symbol(),Period(),20,2),5)
         + NL);*/
   string bc28  = "Bc28 ";   string sc02  = "Sc02 " ;
//   if(TypeSellComment(sc01))
//   SM("Type Sell"+NL);
   
   SM("  ( ( TimeCurrent() - LiveTime(bc28) ) / 60 "+ IntegerToString( ( TimeCurrent() - LiveTime(bc28) ) / 60 )  
         + NL);
//   SM("  ( TimeCurrent() - LiveTime(sc01) ) / 60 "+ IntegerToString( ( TimeCurrent() - LiveTimei(sc01) ) / 60 )  
//         + NL);
// SM("HighestPriceOfOrderWithThisComment(sc01) : "+ DoubleToStr( HighestPriceOfOrderWithThisComment(sc01) ,5)+NL);
// SM("UplOfEarliestOrderWithThisComment(bc02) : "+ DoubleToStr( UplOfEarliestOrderWithThisComment(bc02) ,2)+NL);
  double SendLot = CalculateLotSize(1, NormalizeDouble(0 + (HiddenPips / factor), Digits) );       
// SM("MaxAllowableCashLoss * SendLot * 10 : "+ DoubleToStr( MaxAllowableCashLoss * SendLot * 100 ,2)+NL);
// SM("LowestClosePrice : "+ DoubleToStr( LowestClosePrice(PERIOD_M15,5, 1) ,5)+NL);
 //SM("HighestClosePrice(PERIOD_H1,5,DayXBar(PERIOD_H1,0)+ 1): "+ DoubleToStr(HighestClosePrice(PERIOD_H1,5,DayXBar(PERIOD_H1,0) + 1),5)+NL);
//SM("DayXBar(PERIOD_H1,0)+ 1: "+ IntegerToString(DayXBar(PERIOD_H1,0) + 1)+NL);
//SM("HighestCloseBar(PERIOD_H1,5,DayXBar(PERIOD_H1,0)+ 1): "+ IntegerToString(HighestCloseBar(PERIOD_H1,5,DayXBar(PERIOD_H1,0) + 1))+NL);
  
  
////XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 
   text = "Market trades open = ";
   SM(text + IntegerToString(MarketTradesTotal) + ": Pips UPL = " + DoubleToStr(PipsUpl, 0)
   +  ": Cash UPL = " + DoubleToStr(CashUpl, 2) + NL);      
   SM(NL);     
//////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
  if(BuyCashUpl < -LossToCloseBuyOrSellTrades)
     SM( ": LossToCloseBuyOrSell = " + DoubleToStr(-LossToCloseBuyOrSellTrades,2)
         + NL);
  if(SellCashUpl < -LossToCloseBuyOrSellTrades)
     SM( ": LossToCloseBuyOrSell = " + DoubleToStr(-LossToCloseBuyOrSellTrades,2)
         + NL);

   SM("  AllBuyTypeOrders  = "  + IntegerToString(AllBuyTypeOrders())
    + NL);
   if (BuyOpen)
      SM("Buy trades = " + IntegerToString(MarketBuysCount)
         + ": Pips upl = " + IntegerToString(BuyPipsUpl)
         + ": Buy Cash upl = " + DoubleToStr(BuyCashUpl, 2)
         + NL);
   SM("  AllSellTypeOrders  = "  + IntegerToString(AllSellTypeOrders())
   + NL);
   if (SellOpen)
      SM("Sell trades = " + IntegerToString(MarketSellsCount)
         + ": Pips upl = " + IntegerToString(SellPipsUpl)
         + NL);
///----
   SM(NL);
   SM("Trading time frame: " + TradingTimeFrameDisplay + NL);
//   if(TradeLong) SM("Taking long trades"+NL);
//   if(TradeShort) SM("Taking short trades"+NL);
//   if(!TradeLong && !TradeShort) SM("Both TradeLong and TradeShort are set to false"+NL);
   SM("Lot size: "+DoubleToStr(Lot,2)+" (Criminal's minimum lot size: "+DoubleToStr(MarketInfo(Symbol(),MODE_MINLOT),2)+")"+NL);
   if(!CloseEnough(TakeProfit,0)) SM("Take profit: "+DoubleToStr(TakeProfit,0)+PipDescription+NL);
   if(!CloseEnough(StopLoss,0)) SM("Stop loss: "+DoubleToStr(StopLoss,0)+PipDescription+NL);
   SM("Magic number: "+MagicNumber+NL);
  /* int Num_Orders = OrdersTotal();
   string boo = "B00";
   for(int i=0;i<Num_Orders;i++)
   { if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
      { break;}
      if(OrderComment() == boo) 
      }*/

   SM("Average Spread = "+DoubleToStr(AverageSpread,1)+": Spread = "+DoubleToStr(spread,1)+": Widest since loading = "+DoubleToStr(BiggestSpread,1)+NL);
   SM(NL);

   //Trading hours
   if(tradingHoursDisplay!="") SM("Trading hours: "+tradingHoursDisplay+NL);
   else SM("24 hour trading: "+NL);

   if(MarginMessage!="") SM(MarginMessage+NL);

   //Running total of trades
   SM(Gap+NL);
   SM("Results today. Wins: "+WinTrades+": Losses "+LossTrades+": P/L "+DoubleToStr(OverallProfit,2)+NL);

   SM(NL);


   Comment(ScreenMessage);

}//void DisplayUserFeedback()
  
//+--------------------------------------------------------------------+
//| Paul Bachelor's (lifesys) text display module to replace Comment()|
//+--------------------------------------------------------------------+
void SM(string message)
{
   if (DisplayAsText) 
   {
      DisplayCount++;
      Display(message);
   }
   else
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, message);
      
}//End void SM()

//   ************************* added for OBJ_LABEL
void removeAllObjects()
{
   for(int i = ObjectsTotal() - 1; i >= 0; i--)
   if (StringFind(ObjectName(i),"OAM-",0) > -1) 
      ObjectDelete(ObjectName(i));
}//End void removeAllObjects()
//   ************************* added for OBJ_LABEL

void Display(string text)
{
  string lab_str = "OAM-" + IntegerToString(DisplayCount);  
  double ofset = 0;
  string textpart[5];
  uint w,h;
  
  for (int cc = 0; cc < 5; cc++)
  {
     textpart[cc] = StringSubstr(text,cc*63,64);
     if (StringLen(textpart[cc]) ==0) continue;
     lab_str = lab_str + IntegerToString(cc);
    
     ObjectCreate(lab_str, OBJ_LABEL, 0, 0, 0);
     ObjectSet(lab_str, OBJPROP_CORNER, 0);
     ObjectSet(lab_str, OBJPROP_XDISTANCE, DisplayX + ofset);
     ObjectSet(lab_str, OBJPROP_YDISTANCE, DisplayY+DisplayCount*(fontSise+4));
     ObjectSet(lab_str, OBJPROP_BACK, false);
     ObjectSetText(lab_str, textpart[cc], fontSise, fontName, colour);
    
     /////////////////////////////////////////////////
     //Calculate label size
     //Tomele supplied this code to eliminate the gaps in the text.
     //Thanks Thomas.
     TextSetFont(fontName,-fontSise*10,0,0);
     TextGetSize(textpart[cc],w,h);
    
     //Trim trailing space
     if (StringSubstr(textpart[cc],63,1)==" ")
        ofset+=(int)(w-fontSise*0.25);
     else
        ofset+=(int)(w-fontSise*0.65);
     /////////////////////////////////////////////////
        
  }//for (int cc = 0; cc < 5; cc++)
}
         

bool ChartForegroundSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
   ResetLastError();
//--- set property value
   if(!ChartSetInteger(chart_ID,CHART_FOREGROUND,0,value))
   {
      //--- display the error message in Experts journal
      Print(__FUNCTION__+", Error Code = ",GetLastError());
      return(false);
   }//if(!ChartSetInteger(chart_ID,CHART_FOREGROUND,0,value))
//--- successful execution
   return(true);
}//End bool ChartForegroundSet(const bool value,const long chart_ID=0)
//+--------------------------------------------------------------------+
//| End of Paul's text display module to replace Comment()             |
//+--------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
//----


   //Missing indi check
   /*
   if (!indiExists( "IndiName" ))
   {
      Alert("");
      Alert("Download the indi from the thread or from http://www.stevehopwoodforex.com/phpBB3/viewtopic.php?f=15&t=79&p=803#p803");
      Alert("The required indicator " + "IndiName" + " does not exist on your platform. I am removing myself from your chart.");
      RemoveExpert = true;
      ExpertRemove();
      return(0);
   }//if (! indiExists( "IndiName" ))
   */
  
   

//~ Set up the pips factor. tp and sl etc.
//~ The EA uses doubles and assume the value of the integer user inputs. This: 
//~    1) minimises the danger of the inputs becoming corrupted by restarts; 
//~    2) the integer inputs cannot be divided by factor - doing so results in zero.

   factor=GetPipFactor(Symbol());
   HiddenPips=PipsHiddenFromCriminal;
   TradeMiniBuffer = TradesMiniBufferPips;
//   PositiveSwapOnly=PositiveSwapTradesOnly;
   longSwap = MarketInfo(Symbol(), MODE_SWAPLONG);
   shortSwap = MarketInfo(Symbol(), MODE_SWAPSHORT);  
   Pip01 = Piip01;
   Pip02 = Piip02;
   Pip05 = Piip05;
   Pip10 = Piip10;
   Pip20 = Piip20;
   while(IsConnected()==false)
   {
      Comment("Waiting for MT4 connection...");
      Comment("");

      Sleep(1000);
   }//while (IsConnected()==false)


   //Lot size and part-close idiot check for the cretins. Code provided by phil_trade. Many thanks, Philippe.
   //adjust Min_lot
   if (CloseEnough(RiskPercent, 0) )
      if(Lot<MarketInfo(Symbol(),MODE_MINLOT))
      {
         Alert(Symbol()+" Lot was adjusted to Minlot = "+DoubleToStr(MarketInfo(Symbol(),MODE_MINLOT),Digits));
         Lot=MarketInfo(Symbol(),MODE_MINLOT);
      }//if (Lot < MarketInfo(Symbol(), MODE_MINLOT)) 

//   Turn MaxAllowableCashLoss begative if the user has forgotten.
//   if (MaxAllowableCashLoss > 0)
//      MaxAllowableCashLoss*= -1;
   
//   if (LossToCloseBuyOrSellTrades > 0)
//      LossToCloseBuyOrSellTrades*= -1;
   
   
   Gap="";
   if (DisplayGapSize >0)
   {
      for (int cc=0; cc< DisplayGapSize; cc++)
      {
         Gap = StringConcatenate(Gap, " ");
      }   
   }//if (DisplayGapSize >0)
   
   //Reset CriminIsECN if crim is IBFX and the punter does not know or, like me, keeps on forgetting
   string name= TerminalCompany();
   int ispart = StringFind(name,"IBFX",0);
   if(ispart<0) ispart=StringFind(name,"Interbank FX",0);
//   if(ispart>-1) IsGlobalPrimeOrECNCriminal=true;
   ispart=StringFind(name,"Global Prime",0);
//   if(ispart>-1) IsGlobalPrimeOrECNCriminal=true;

   //Set up the trading hours
   tradingHoursDisplay=tradingHours;//For display
   initTradingHours();//Sets up the trading hours array

   
//   if(TradeComment=="") TradeComment=" ";
   OldBars=Bars;
   TicketNo=-1;
   ReadIndicatorValues();//For initial display in case user has turned of constant re-display
   TooClose();
   CountOpenTrades();
   OldOpenTrades=OpenTrades;
   TradeTimeOk=CheckTradingTimes();
   
   //The apread global variable
   if (!IsTesting() )
   {
      SpreadGvName=Symbol()+" average spread";
      AverageSpread=GlobalVariableGet(SpreadGvName);//If no gv, then the value will be left at zero.
   }//if (!IsTesting() )
   
   //Chart display
   if (DisplayAsText)
      if (KeepTextOnTop)
         ChartForegroundSet(false,0);// change chart to background
   
   //Ensure that an ea depending on Close[1] for its values does not immediately fire a trade.
   if (!EveryTickMode) OldBarsTime = iTime(Symbol(), TradingTimeFrame, 0);


   //Lot size based on account size
   if (!CloseEnough(LotsPerDollopOfCash, 0))
      CalculateLotAsAmountPerCashDollops();

   //Time frame display
   TradingTimeFrameDisplay = GetTimeFrameDisplay(TradingTimeFrame);
   //Hidden HGI code
   
   
   DisplayUserFeedback();


//Call sq's show trades indi
//iCustom(NULL, 0, "SQ_showTrades",Magic, 0,0);
    
         if(ArraySize(ExtMapBuffer1) < Bars)
     {
       ArraySetAsSeries(ExtMapBuffer1, false);
       ArraySetAsSeries(ExtMapBuffer2, false);
       ArraySetAsSeries(ExtMapBuffer3, false);
       ArraySetAsSeries(ExtMapBuffer4, false);
       ArraySetAsSeries(ExtMapBuffer5, false);
       ArraySetAsSeries(ExtMapBuffer6, false);
       ArraySetAsSeries(ExtMapBuffer7, false);
       ArraySetAsSeries(ExtMapBuffer8, false);
       
       //----  
       ArrayResize(ExtMapBuffer1, Bars); 
       ArrayResize(ExtMapBuffer2, Bars); 
       ArrayResize(ExtMapBuffer3, Bars); 
       ArrayResize(ExtMapBuffer4, Bars); 
       ArrayResize(ExtMapBuffer5, Bars); 
       ArrayResize(ExtMapBuffer6, Bars); 
       ArrayResize(ExtMapBuffer7, Bars); 
       ArrayResize(ExtMapBuffer8, Bars);  
      
       //----
       ArraySetAsSeries(ExtMapBuffer1, true);
       ArraySetAsSeries(ExtMapBuffer2, true);
       ArraySetAsSeries(ExtMapBuffer3, true); 
       ArraySetAsSeries(ExtMapBuffer4, true); 
       ArraySetAsSeries(ExtMapBuffer5, true); 
       ArraySetAsSeries(ExtMapBuffer6, true); 
       ArraySetAsSeries(ExtMapBuffer7, true); 
       ArraySetAsSeries(ExtMapBuffer8, true); 
      
     } 
     if(ArraySize(ExtMapBufferHT1) < Bars)
     {
       ArraySetAsSeries(ExtMapBufferHT1, false);
       ArraySetAsSeries(ExtMapBufferHT2, false);
       ArraySetAsSeries(ExtMapBufferHT3, false);
       ArraySetAsSeries(ExtMapBufferHT4, false);
       ArraySetAsSeries(ExtMapBufferHT5, false);
       ArraySetAsSeries(ExtMapBufferHT6, false);
       ArraySetAsSeries(ExtMapBufferHT7, false);
       ArraySetAsSeries(ExtMapBufferHT8, false);
       
       //----  
       ArrayResize(ExtMapBufferHT1, Bars); 
       ArrayResize(ExtMapBufferHT2, Bars); 
       ArrayResize(ExtMapBufferHT3, Bars); 
       ArrayResize(ExtMapBufferHT4, Bars); 
       ArrayResize(ExtMapBufferHT5, Bars); 
       ArrayResize(ExtMapBufferHT6, Bars); 
       ArrayResize(ExtMapBufferHT7, Bars); 
       ArrayResize(ExtMapBufferHT8, Bars);  
      
       //----
       ArraySetAsSeries(ExtMapBufferHT1, true);
       ArraySetAsSeries(ExtMapBufferHT2, true);
       ArraySetAsSeries(ExtMapBufferHT3, true); 
       ArraySetAsSeries(ExtMapBufferHT4, true); 
       ArraySetAsSeries(ExtMapBufferHT5, true); 
       ArraySetAsSeries(ExtMapBufferHT6, true); 
       ArraySetAsSeries(ExtMapBufferHT7, true); 
       ArraySetAsSeries(ExtMapBufferHT8, true); 
      
     } 

//----
   return(0);
} 
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//----
   Comment("");
   removeAllObjects();

//----
   return;
}

string GetTimeFrameDisplay(int tf)
{

   if (tf == 0)
      tf = Period();
      
   
   if (tf == PERIOD_M1)
      return "M1";
      
   if (tf == PERIOD_M5)
      return "M5";
      
   if (tf == PERIOD_M15)
      return "M15";
      
   if (tf == PERIOD_M30)
      return "M30";
      
   if (tf == PERIOD_H1)
      return "H1";
      
   if (tf == PERIOD_H4)
      return "H4";
      
   if (tf == PERIOD_D1)
      return "D1";
      
   if (tf == PERIOD_W1)
      return "W1";
      
   if (tf == PERIOD_MN1)
      return "Monthly";
      
   return("No recognisable time frame selected");

}//string GetTimeFrameDisplay()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
////===============
////===============
void SendBuyStopResult( int buytype, double buysendprice, double buystoploss, double buytakeprofit, string buytradecomment)
{  double SendLotsbs = Lot ;
   if (!CloseEnough(RiskPercent, 0))   SendLotsbs = CalculateLotSize(buysendprice, NormalizeDouble(0 + (HiddenPips / factor), Digits) );               
   
int  ticket = -1;   
   {ticket=OrderSend(Symbol(),buytype,SendLotsbs,buysendprice,slippage(),buystoploss,buytakeprofit,buytradecomment,MagicNumber,0,clrGreen); }  }//void SendBuyStopResult()  
////===============
void SendSellStopResult(int selltype,double sellsendprice, double sellstoploss, double selltakeprofit,  string selltradecomment)
{ double SendLotsss = Lot ;
  if (!CloseEnough(RiskPercent, 0))  SendLotsss = CalculateLotSize(sellsendprice, NormalizeDouble(0 + (HiddenPips / factor), Digits) );               
 int  ticket = -1;   
   {ticket=OrderSend(Symbol(),selltype,SendLotsss,sellsendprice,slippage(),sellstoploss,selltakeprofit,selltradecomment,MagicNumber,0,clrRed); }  }//void SendSellStopResult()  
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
///+-----------------------------------------------------+
//|                                                      +            |
//+------------------------------------------------------+
//=============================================================================
//                           O_R_CheckForHistory()
//
//  This function is to work around a very annoying and dangerous bug in MT4:
//      immediately after you send a trade, the trade may NOT show up in the
//      order history, even though it exists according to ticket number.
//      As a result, EA's which count history to check for trade entries
//      may give many multiple entries, possibly blowing your account!
//
//  This function will take a ticket number and loop until
//  it is seen in the history.
//
//  RETURN VALUE:
//     TRUE if successful, FALSE otherwise
//
//
//  FEATURES:
//     * Re-trying under some error conditions, sleeping a random
//       time defined by an exponential probability distribution.
//
//     * Displays various error messages on the log for debugging.
//
//  ORIGINAL AUTHOR AND DATE:
//     Matt Kennel, 2010
//
//=============================================================================
bool O_R_CheckForHistory(int ticket)
  {
//My thanks to Matt for this code. He also has the undying gratitude of all users of my trading robots

   int lastTicket=OrderTicket();

   int cnt =0;
   int err=GetLastError(); // so we clear the global variable.
   err=0;
   bool exit_loop=false;
   bool success=false;
   int c = 0;

   while(!exit_loop) 
     {
/* loop through open trades */
      int total=OrdersTotal();
      for(c=0; c<total; c++) 
        {
         if(BetterOrderSelect(c,SELECT_BY_POS,MODE_TRADES)==true) 
           {
            if(OrderTicket()==ticket) 
              {
               success=true;
               exit_loop=true;
              }
           }
        }
      if(cnt>3) 
        {
/* look through history too, as order may have opened and closed immediately */
         total=OrdersHistoryTotal();
         for(c=0; c<total; c++) 
           {
            if(BetterOrderSelect(c,SELECT_BY_POS,MODE_HISTORY)==true) 
              {
               if(OrderTicket()==ticket) 
                 {
                  success=true;
                  exit_loop=true;
                 }
              }
           }
        }

      cnt=cnt+1;
      if(cnt>O_R_Setting_max_retries) 
        {
         exit_loop=true;
        }
      if(!(success || exit_loop)) 
        {
         Print("Did not find #"+ticket+" in history, sleeping, then doing retry #"+cnt);
         O_R_Sleep(O_R_Setting_sleep_time,O_R_Setting_sleep_max);
        }
     }
// Select back the prior ticket num in case caller was using it.
   if(lastTicket>=0) 
     {
      bool s = BetterOrderSelect(lastTicket,SELECT_BY_TICKET,MODE_TRADES);
     }
   if(!success) 
     {
      Print("Never found #"+ticket+" in history! crap!");
     }
   return(success);
  }//End bool O_R_CheckForHistory(int ticket)
//=============================================================================
//                              O_R_Sleep()
//
//  This sleeps a random amount of time defined by an exponential
//  probability distribution. The mean time, in Seconds is given
//  in 'mean_time'.
//  This returns immediately if we are backtesting
//  and does not sleep.
//
//=============================================================================
void O_R_Sleep(double mean_time, double max_time)
{
   if (IsTesting()) 
   {
      return;   // return immediately if backtesting.
   }

   double p = (MathRand()+1) / 32768.0;
   double t = -MathLog(p)*mean_time;
   t = MathMin(t,max_time);
   int ms = t*1000;
   if (ms < 10) {
      ms=10;
   }//if (ms < 10) {
   
   Sleep(ms);
}//End void O_R_Sleep(double mean_time, double max_time)

////////////////////////////////////////////////////////////////////////////////////////

bool IsTradingAllowed()
{
   //Returns false if any of the filters should cancel trading, else returns true to allow trading
   
      
   //Maximum spread
   if (!IsTesting() )
   {
      double spread = (Ask - Bid) * factor;
      if (spread > AverageSpread * MultiplierToDetectStopHunt) return(false);
   }//if (!IsTesting() )
   
    
   
   
   return(true);


}//End bool IsTradingAllowed()

double CalculateLotSize(double price1,double price2)
{
   //Calculate the lot size by risk. Code kindly supplied by jmw1970. Nice one jmw.

   if(price1==0 || price2==0) return(Lot);//Just in case

   double FreeMargin= AccountFreeMargin();
   double TickValue = MarketInfo(Symbol(),MODE_TICKVALUE);
   double LotStep=MarketInfo(Symbol(),MODE_LOTSTEP);

   double SLPts=MathAbs(price1-price2);
   //SLPts/=Point;//No idea why *= factor does not work here, but it doesn't
   SLPts = int(SLPts * factor * 10);//Code from Radar. Thanks Radar; much appreciated

   double Exposure=SLPts*TickValue; // Exposure based on 1 full lot

   double AllowedExposure=(FreeMargin*RiskPercent)/100;

   int TotalSteps = ((AllowedExposure / Exposure) / LotStep);
   double LotSize = TotalSteps * LotStep;

   double MinLots = MarketInfo(Symbol(), MODE_MINLOT);
   double MaxLots = MarketInfo(Symbol(), MODE_MAXLOT);

   if(LotSize < MinLots) LotSize = MinLots;
   if(LotSize > MaxLots) LotSize = MaxLots;
   return(LotSize);

}//double CalculateLotSize(double price1, double price1)
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
datetime Time1x() { return( iTime(Symbol(),PERIOD_D1,0) ); }
datetime Time2x() { return( TimeCurrent() ); }

 double TmbFac() { return ( TradeMiniBuffer / factor ); }
//-------------------------------------||
 double slippage() { return ( MaxSlippagePips*MathPow(10,Digits)/factor) ; }
//-------------------------------------||
///###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####   
  int Bari(string cymbol, int tf1, int tf2, int bar)   { if (tf1 == 0) tf1 = Period();if (tf2 == 0) tf2 = Period();
  return (iBarShift(cymbol,tf1,iTime(cymbol,tf2,bar)));}
///###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####   
  int Bar(int tf1, int tf2, int bar)   { if (tf1 == 0) tf1 = Period();if (tf2 == 0) tf2 = Period();
  return (iBarShift(Symbol(),tf1,iTime(Symbol(),tf2,bar)));}
  int Hr40Bar()   { return (iBarShift(Symbol(),PERIOD_H1,iTime(Symbol(),PERIOD_H4,0)));}//How many Hour 1 candles starting from candle Hr4 Open
///###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
  int Day0Bar(int tf)    { return (iBarShift(Symbol(),tf,iTime(Symbol(),PERIOD_D1,0)));}
  int DayXBar(int tf, int shift)    { return (iBarShift(Symbol(),tf,iTime(Symbol(),PERIOD_D1,shift)));}
///###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
  int MN0BarDy()   { return (iBarShift(Symbol(),PERIOD_D1,iTime(Symbol(),PERIOD_MN1,0)));}
//###
   int AllBuyTypeOrders()   { return  (MarketBuysCount  + BuyStopsCount  + BuyLimitsCount );}
   int AllSellTypeOrders()  { return  (MarketSellsCount + SellStopsCount + SellLimitsCount );}
//###
  int Hr4HighBar() { return (iHighest(Symbol(), PERIOD_H1,MODE_HIGH,Bar(PERIOD_H1,PERIOD_H4,0) + 1,0)); }
//|||||
  int Hr4LowBar() { return (iLowest(Symbol(), PERIOD_H1,MODE_LOW,Bar(PERIOD_H1,PERIOD_H4,0) + 1,0)); }
//|||||
  int TodaysHighBar() { return (iHighest(Symbol(), PERIOD_H1,MODE_HIGH,Bar(PERIOD_H1,PERIOD_D1,0) + 1,0)); }
//|||||
  int TodaysLowBar() { return (iLowest(Symbol(), PERIOD_H1,MODE_LOW,Bar(PERIOD_H1,PERIOD_D1,0) + 1,0)); }
//|||||
  int WeeksHighBar() { return (iHighest(Symbol(), PERIOD_H1,MODE_HIGH,Bar(PERIOD_H1,PERIOD_W1,0),0)); }
//|||||
  int WeeksLowBar() { return (iLowest(Symbol(), PERIOD_H1,MODE_LOW,Bar(PERIOD_H1,PERIOD_W1,0),0)); }
//|||||
  int MonthsHighBar() { return (iHighest(Symbol(), PERIOD_H1,MODE_HIGH,Bar(PERIOD_H1,PERIOD_MN1,0),0)); }
//|||||
  int MonthsLowBar() { return (iLowest(Symbol(), PERIOD_H1,MODE_LOW,Bar(PERIOD_H1,PERIOD_MN1,0),0)); }
///###++++++++++++++++++++++++++++++++++++#####
///###++++++++++++++++++++++++++++++++++++#####
///###++++++++++++++++++++++++++++++++++++#####
  datetime EquityCloseProfitTime() { return (ObjectGet(EquityCloseProfit,OBJPROP_TIME1));}   int EquityCloseBarShift() { return (iBarShift(Symbol(),PERIOD_D1,EquityCloseProfitTime()));}
  double EquityCloseProfitPrice() { return (ObjectGet(EquityCloseProfit,OBJPROP_PRICE2));}
///###++++++++++++++++++++++++++++++++++++#####
  datetime BuyCloseProfitTime() { return (ObjectGet(BuyCloseProfit,OBJPROP_TIME1));}   int BuyCloseBarShift() { return (iBarShift(Symbol(),PERIOD_D1,BuyCloseProfitTime()));}
  double BuyCloseProfitPrice() { return (ObjectGet(BuyCloseProfit,OBJPROP_PRICE2));}
//###
  datetime SellCloseProfitTime() { return (ObjectGet(SellCloseProfit,OBJPROP_TIME1));}   int SellCloseBarShift() { return (iBarShift(Symbol(),PERIOD_D1,SellCloseProfitTime()));}
  double SellCloseProfitPrice() { return (ObjectGet(SellCloseProfit,OBJPROP_PRICE2));}
///###++++++++++++++++++++++++++++++++++++#####
////============================================================================================
//              MONTH MONTH                                                                   ||
////============================================================================================
//                                                                                            ||
  int HighestHighBar(int tfh , int shifth , int baseh) { if (tfh == 0)  tfh = Period(); return (iHighest(Symbol(), tfh,MODE_HIGH,shifth, baseh)); }
  double HighestHighPrice(int tfh , int shifth ,int baseh) { if (tfh == 0)  tfh = Period(); return (NormalizeDouble(iHigh(Symbol(), tfh, HighestHighBar(tfh ,shifth , baseh)),Digits));}
//|||||
  int LowestLowBar(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period(); return (iLowest(Symbol(),tfl,MODE_LOW,shiftl,basel)); }
  double LowestLowPrice(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period();  return (NormalizeDouble(iLow(Symbol(),tfl, LowestLowBar(tfl ,shiftl ,basel)),Digits)); }
//                                                                                            ||
  int HighestLowBar(int tfh , int shifth , int baseh) { if (tfh == 0)  tfh = Period(); return (iHighest(Symbol(), tfh,MODE_LOW,shifth, baseh)); }
  double HighestLowPrice(int tfh , int shifth ,int baseh) { if (tfh == 0)  tfh = Period(); return (NormalizeDouble(iLow(Symbol(), tfh, HighestLowBar(tfh ,shifth , baseh)),Digits));}
//|||||
  int LowestHighBar(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period(); return (iLowest(Symbol(),tfl,MODE_HIGH,shiftl,basel)); }
  double LowestHighPrice(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period();  return (NormalizeDouble(iHigh(Symbol(),tfl, LowestHighBar(tfl ,shiftl ,basel)),Digits)); }
////============================================================================================
//+++++
  double HighestHighPriceMinusLowestHighPrice(int tfh , int tfl , int shifth, int shiftl, int baseh, int basel)
   {if (tfh == 0)  tfh = Period();if (tfl == 0)  tfl = Period(); return ( HighestHighPrice(tfh ,shifth ,baseh) - LowestLowPrice(tfl ,shiftl , basel) ); }
////============================================================================================
////============================================================================================
//                                                                                            ||
  int HighestCloseBar(int tfh , int shifth , int baseh) 
  { if (tfh == 0)  tfh = Period(); return (iHighest(Symbol(), tfh,MODE_CLOSE,shifth, baseh)); }
  double HighestClosePrice(int tfh , int shifth ,int baseh) 
  { if (tfh == 0)  tfh = Period(); return (NormalizeDouble(iClose(Symbol(), tfh, HighestCloseBar(tfh ,shifth , baseh)),Digits));}
//|||||
  int LowestCloseBar(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period(); return (iLowest(Symbol(),tfl,MODE_CLOSE,shiftl,basel)); }

  double LowestClosePrice(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period();  
  return (NormalizeDouble(iClose(Symbol(),tfl, LowestCloseBar(tfl ,shiftl ,basel)),Digits)); }
////============================================================================================
//+++++
  double HighestClosePriceMinusLowestClosePrice(int tfh , int tfl , int shifth, int shiftl, int baseh, int basel)
   {if (tfh == 0)  tfh = Period();if (tfl == 0)  tfl = Period(); return ( HighestClosePrice(tfh ,shifth ,baseh) - LowestClosePrice(tfl ,shiftl , basel) ); }
////============================================================================================
///###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
////============================================================================================
//                                                                                            ||
  int HighestOpenBar(int tfh , int shifth , int baseh) { if (tfh == 0)  tfh = Period(); return (iHighest(Symbol(), tfh,MODE_OPEN,shifth, baseh)); }
  double HighestOpenPrice(int tfh , int shifth ,int baseh) { if (tfh == 0)  tfh = Period(); return (NormalizeDouble(iOpen(Symbol(), tfh, HighestOpenBar(tfh ,shifth , baseh)),Digits));}
//|||||
  int LowestOpenBar(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period(); return (iLowest(Symbol(),tfl,MODE_OPEN,shiftl,basel)); }
  double LowestOpenPrice(int tfl , int shiftl ,int basel) { if (tfl == 0)  tfl = Period();  return (NormalizeDouble(iOpen(Symbol(),tfl, LowestOpenBar(tfl ,shiftl ,basel)),Digits)); }
////============================================================================================
//+++++
  double HighestOpenPriceMinusLowestOpenPrice(int tfh , int tfl , int shifth, int shiftl, int baseh, int basel)
   {if (tfh == 0)  tfh = Period();if (tfl == 0)  tfl = Period(); return ( HighestOpenPrice(tfh ,shifth ,baseh) - LowestOpenPrice(tfl ,shiftl , basel) ); }
////============================================================================================
////============================================================================================
//                                                                                            ||
  int HighestHighBari(string cymbol, int tfh , int shifth , int baseh) 
  { if (tfh == 0)  tfh = Period(); return (iHighest(cymbol, tfh,MODE_HIGH,shifth, baseh)); }
  double HighestHighPricei(string cymbol,int tfh , int shifth ,int baseh) 
  { if (tfh == 0)  tfh = Period(); return (NormalizeDouble(iHigh(cymbol, tfh, HighestHighBari(cymbol, tfh ,shifth , baseh)),Digits));}
//|||||
  int LowestLowBari(string cymbol,int tfl , int shiftl ,int basel) 
  { if (tfl == 0)  tfl = Period(); return (iLowest(cymbol,tfl,MODE_LOW,shiftl,basel)); }
  double LowestLowPricei(string cymbol,int tfl , int shiftl ,int basel)
   { if (tfl == 0)  tfl = Period();  return (NormalizeDouble(iLow(cymbol,tfl, LowestLowBari(cymbol,tfl ,shiftl ,basel)),Digits)); }
//                                                                                            ||
  int HighestCloseBari(string cymbol,int tfh , int shifth , int baseh) 
  { if (tfh == 0)  tfh = Period(); return (iHighest(cymbol, tfh,MODE_CLOSE,shifth, baseh)); }
  double HighestClosePricei(string cymbol,int tfh , int shifth ,int baseh) 
  { if (tfh == 0)  tfh = Period(); return (NormalizeDouble(iClose(cymbol, tfh, HighestCloseBari(cymbol,tfh ,shifth , baseh)),Digits));}
//|||||
  int LowestCloseBari(string cymbol,int tfl , int shiftl ,int basel) 
  { if (tfl == 0)  tfl = Period(); return (iLowest(cymbol,tfl,MODE_CLOSE,shiftl,basel)); }
  double LowestClosePricei(string cymbol,int tfl , int shiftl ,int basel) 
  { if (tfl == 0)  tfl = Period();  return (NormalizeDouble(iClose(cymbol,tfl, LowestCloseBari(cymbol,tfl ,shiftl ,basel)),Digits)); }
//                                                                                            ||
  int HighestLowBari(string cymbol, int tfh , int shifth , int baseh)
   { if (tfh == 0)  tfh = Period(); return (iHighest(cymbol, tfh,MODE_LOW,shifth, baseh)); }
  double HighestLowPricei(string cymbol, int tfh , int shifth ,int baseh)
   { if (tfh == 0)  tfh = Period(); return (NormalizeDouble(iLow(cymbol, tfh, HighestLowBari(cymbol,tfh ,shifth , baseh)),Digits));}
//|||||
  int LowestHighBari(string cymbol, int tfl , int shiftl ,int basel) 
  { if (tfl == 0)  tfl = Period(); return (iLowest(cymbol,tfl,MODE_HIGH,shiftl,basel)); }
  double LowestHighPricei(string cymbol, int tfl , int shiftl ,int basel)
   { if (tfl == 0)  tfl = Period();  return (NormalizeDouble(iHigh(cymbol,tfl, LowestHighBari(cymbol,tfl ,shiftl ,basel)),Digits)); }
////============================================================================================
////============================================================================================
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
      double MoAv(string cymbol,int tf,int period,int method,int shift)
      {
         return(iMA(cymbol, tf, period, 0, method, PRICE_CLOSE, shift) );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
      double MaHigh(string cymbol,int tf,int period,int method,int shift)
      {
         return(iMA(cymbol, tf, period, 0, method, PRICE_HIGH, shift) );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)
//
      double MaLow(string cymbol,int tf,int period,int method,int shift)
      {
         return(iMA(cymbol, tf, period, 0, method, PRICE_LOW, shift) );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
      double HiHiLoHiDiff(int tf,int NrOfCandles, int StartCandle)
      {
      double hilo = HighestHighPrice(tf,NrOfCandles,StartCandle) - LowestHighPrice(tf,NrOfCandles,StartCandle);
         return( hilo );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)
//
      double LoLoHiLoDiff(int tf,int NrOfCandles, int StartCandle)
      {
      double hilo = HighestLowPrice(tf,NrOfCandles,StartCandle) - LowestLowPrice(tf,NrOfCandles,StartCandle);
         return( hilo );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   double   dongap()  { return (MathMax(TmbFac() * 3,DonGapDivide(PERIOD_M15,58,1,2) ) )  ; }
////###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void LookForTradingOpportunities()
{
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
   //Check filters
   if (!IsTradingAllowed() ) return;
//====
   int err = 0;
   /////////////////////////////////////////////////////////////////////////////////////
   double spread = (Ask - Bid) * factor;
  double SendLot = CalculateLotSize(1, NormalizeDouble(0 + (HiddenPips / factor), Digits) );       
   /////////////////////////////////////////////////////////////////////////////////////
 string cymbol = Symbol();
/////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string bc28  = "Bc28 "; 
   string bc28g  = "Bc28g "; 
   string bc28gv  = "Bc28gv "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(bc28,cymbol)      && TypeBuyStopComment(bc28)  )
   { CloseExpiredPendingWithThisComment(bc28,180); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(bc28g,cymbol)      && TypeBuyStopComment(bc28g)  )
   { CloseExpiredPendingWithThisComment(bc28g,300); } 
///////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc28)  >  3 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc28) > 0  )
   { BreakEvenTradeWithThisComment(bc28,PERIOD_M15,25,5); }
////////////////////////////////////////////////////////////////////////////////////////////
   if(UplOfOrderWithThisComment(bc28g)  >  4 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc28g) > 0  )
   { BreakEvenTradeWithThisComment(bc28g,PERIOD_M15,25,5); }
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc28) + UplOfOrderWithThisComment(bc28g) < - 4 * SendLot * 100 
   && UplOfOrderWithThisComment(bc28) + UplOfOrderWithThisComment(bc28g) > - ( 5 )  * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(bc28,5);
      ModifyStopLossOfOrdersWithThisComment(bc28g,5);}
////######//+------------------------------------------------------------------+
// THIS IS TRAILING OF ALL TRADES  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc28) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(bc28,15);}
///######//+
   if(UplOfOrderWithThisComment(bc28g) > ( 10 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(bc28g,52);}
///######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN TRADES IN A GRID  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(bc28g) >  2 * SendLot * 100 && NumberOfBuysWithThisComment(bc28g) > 1 )
   {  StepifyStopLossOfOrdersWithThisComment(bc28g,1,5,3);}
/////######//+----------------------------------------------------------------+
// THIS IS IF TRADES IN A GRID ARE IN PROIT BUT SOME ARE NOT MODIFY STOP LOSS OF THOSE TRADES WITH NO BREAK EVEN
////######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(bc28g) + UplOfOrderWithThisComment(bc28) >  2 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc28) + NumberOfBuysWithThisComment(bc28g) > 1 )
   {  ModifyOrdersWithNoBreakEvenComment(bc28,20); ModifyOrdersWithNoBreakEvenComment(bc28g,20);}
////######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double buyentryc28e1 = 0; double buytakeprofitc28e1 = 0; double buystoplossc28e1 = 0;
   double buyentryc28g1 = 0; double buytakeprofitc28g1 = 0; double buystoplossc28g1 = 0;
   double buyentryc28g2 = 0; double buytakeprofitc28g2 = 0; double buystoplossc28g2 = 0;
   double buyentryc28g3 = 0; double buytakeprofitc28g3 = 0; double buystoplossc28g3 = 0;
   double buyentryc28g4 = 0; double buytakeprofitc28g4 = 0; double buystoplossc28g4 = 0;
//MidTma(PERIOD_H4,bandi,1);//
  double firstbuyentryc28 = MidTma(PERIOD_M15,80,1) - (TmbFac() * 0);
  //GetHiDonn(cymbol,PERIOD_H4,2,1)  + (TmbFac() * 0.1);
  //HighestHighPrice(PERIOD_H4,bandi,1) ;
  // MidTma(PERIOD_H4,5,1) - (TmbFac() * 0);
///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+

   bool buyc28 =(  GetHiDonn(cymbol,PERIOD_H4,2,5) > UpperTma(PERIOD_H4,5,1.6,2,5)
      &&    GetHiDonn(cymbol,PERIOD_H4,2,5) > CandleHigh(PERIOD_D1,2)
      &&    CandleClose(PERIOD_H4,8) < MidTma(PERIOD_H4,12,8)
      &&    CandleLow(PERIOD_H4,1) < MidTma(PERIOD_H4,12,1)
      &&    MidTma(PERIOD_M15,80,Bar(PERIOD_M15,PERIOD_H4,5)) < MidTma(PERIOD_M15,80,1)
      &&    GetHiDonn(cymbol,PERIOD_M15,58,1) < UpperTma(PERIOD_M15,80,3.0,50,1)
      &&    GetMidDonn(cymbol,PERIOD_M15,58,1) < MidTma(PERIOD_M15,80,1)
      &&    CandleClose(PERIOD_M15,1) < MidTma(PERIOD_M15,80,1)
      &&    LowestLowPrice(PERIOD_M15,18,1) < LowerTma(PERIOD_M15,80,3.0,50,LowestLowBar(PERIOD_M15,18,1))
                                   );
//First Filter before Sending Single Order
   bool buytrigc281 = (   buyc28 
   &&  !DoesTradeCommentExistForThisPair(bc28,cymbol)  );
//Secomd Filter before Sending Single Order
   bool buytrigc282 = ( firstbuyentryc28 < Lowbuyprice(bc28) - ( dongap()* 2 ) 
     && DoesTradeCommentExistForThisPair(bc28,cymbol) 
     && !TypeBuyStopComment(bc28)
     &&( TimeCurrent() - LiveTime(bc28) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool buytrigc283 = ( DoesTradeCommentExistForThisPair(bc28,cymbol) 
     && !buyc28 && firstbuyentryc28 > Highbuyprice(bc28) + (dongap() * 0.8 )
     &&  IsCloseAboveMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetHiDonn(cymbol,PERIOD_H4,5,1 ) > GetHiDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) < GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(bc28) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(bc28,cymbol) 
   && DoesTradeCommentExistForThisPair(bc28g,cymbol) 
   &&    !TypeBuyComment(bc28g) )    
   { CloseExpiredPendingWithThisComment(bc28g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(bc28,cymbol) 
   && DoesTradeCommentExistForThisPair(bc28g,cymbol) 
   && TypeBuyComment(bc28) && !TypeBuyComment(bc28g)
   && Bid < Lowbuyprice(bc28) - ( TmbFac() * 4 ) 
   && Lowbuyprice(bc28g) >= Lowbuyprice(bc28) - ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(bc28g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstbuyentryc28 < Lowbuyprice(bc28) - ( dongap()* 1 )
   && TypeBuyStopComment(bc28) )     
   { CloseExpiredPendingWithThisComment(bc28,0) ;} 
//// Delete Stops when Price is going Up
   if( firstbuyentryc28 > Highbuyprice(bc28) + ( dongap()* 1 )
   && TypeBuyStopComment(bc28) )    
   { CloseExpiredPendingWithThisComment(bc28,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( buytrigc281 )  
     { buyentryc28e1 = firstbuyentryc28 ; 
      buytakeprofitc28e1 = buyentryc28e1 + ( TmbFac() * 11 );
      buystoplossc28e1 =   buyentryc28e1 - ( TmbFac() * 13 );   }
//////////////// Second Filter Take Profit And Stop Loss
    if( buytrigc282  ) if(( firstbuyentryc28 > Lowbuyprice(bc28) + dongap()|| firstbuyentryc28 < Lowbuyprice(bc28) - dongap())
      &&   firstbuyentryc28 < Highbuyprice(bc28) - dongap() )
     { buyentryc28e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc28e1 = buyentryc28e1 + ( dongap() * 10 );
      buystoplossc28e1 =   buyentryc28e1 - ( dongap() * 6 );   }
///////////////// Third Filter Take Profit And Stop Loss
     if( buytrigc283  ) 
     { buyentryc28e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc28e1 = buyentryc28e1 + ( dongap() * 10 );
      buystoplossc28e1 =   buyentryc28e1 - ( dongap() * 6 );   }
///////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
//////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(bc28,cymbol)
      &&    !TypeBuyStopComment(bc28g)
      &&    !TypeBuyComment(bc28g)
      &&    ( TimeCurrent() - LiveTime(bc28) ) / 60 < 255 ) 
     { 
      if(    NumberOfBuyStopsWithThisComment(bc28) == 1  &&    !TypeBuyComment(bc28) )
         buyentryc28g1 = Highbuyprice(bc28) + ( TmbFac()* 1.5 ) ;

      if(    NumberOfBuysWithThisComment(bc28) == 1 &&   Bid < Highbuyprice(bc28) + ( TmbFac() * 1.5 )
      &&   Bid > Highbuyprice(bc28)   )
         buyentryc28g1 = Bid + ( TmbFac()* 1.5 ) ;
          
      if(   Bid < Lowbuyprice(bc28) - ( TmbFac() * 4 ) && Bid <  LowerTma(PERIOD_M15,80,3.0,50, 1)  )
         buyentryc28g1 =  MidTma(PERIOD_M15,80,1) + ( TmbFac()* 1 ) ;
    
      buytakeprofitc28g1 = buyentryc28g1 + ( TmbFac() * 50 );
      buystoplossc28g1 =   buyentryc28g1 - ( TmbFac() * 5 );   

      buyentryc28g2 = buyentryc28g1 + ( TmbFac()* (0.5) ) ; 
      buytakeprofitc28g2 = buyentryc28g2 + (TmbFac() * 50);
      buystoplossc28g2 =   buyentryc28g2 - ( TmbFac() * 5 );   
         
      buyentryc28g3 = buyentryc28g2 + ( TmbFac()* (0.5) ) ; 
      buytakeprofitc28g3 = buyentryc28g3 + ( TmbFac() * 50 );
      buystoplossc28g3 =   buyentryc28g3 - ( TmbFac() * 5 );   
      
      buyentryc28g4 = buyentryc28g3 + ( TmbFac()* (1) ) ; 
      buytakeprofitc28g4 = buyentryc28g4 + ( TmbFac() * 50 );
      buystoplossc28g4 =   buyentryc28g4 - ( TmbFac() * 7 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  buytrigc283
      &&    !TypeBuyStopComment(bc28g)       ) 
 
     { buyentryc28g1 = buyentryc28e1 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc28g1 = buyentryc28g1 + ( TmbFac() * 10 );
      buystoplossc28g1 =   buyentryc28g1 - ( TmbFac() * 4 );   

      buyentryc28g2 = buyentryc28g1 + ( TmbFac()* 0.2 ) ; 
      buytakeprofitc28g2 = buyentryc28g2 + ( TmbFac() * 10 );
      buystoplossc28g2 =   buyentryc28g2 - ( TmbFac() * 4 );   

       buyentryc28g3 = buyentryc28g2 + ( TmbFac()* 0.6 ) ; 
      buytakeprofitc28g3 = buyentryc28g3 + ( TmbFac() * 15 );
      buystoplossc28g3 =   buyentryc28g3 - ( TmbFac() * 12 );   

      buyentryc28g4 = buyentryc28g3 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc28g4 = buyentryc28g4 + ( TmbFac() * 15 );
      buystoplossc28g4 =   buyentryc28g4 - ( TmbFac() * 12 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(buyentryc28e1 > Bid)
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc28e1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc28e1 , Digits )  ,//stop loss buyentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc28e1  , Digits)  ,//take profit  
   bc28);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc28 > Bid) 

   if(buyentryc28g1 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc28g1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc28g1 , Digits )  ,//stop loss buyentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc28g1  , Digits)  ,//take profit  
   bc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc28 > Bid) 

   if(buyentryc28g2 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc28g2 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc28g2 , Digits )  ,//stop loss buyentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc28g2  , Digits)  ,//take profit  
   bc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc28 > Bid) 

   if(buyentryc28g3 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc28g3 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc28g3 , Digits )  ,//stop loss buyentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc28g3  , Digits)  ,//take profit  
   bc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc28 > Bid) 

   if(buyentryc28g4 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc28g4 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc28g4 , Digits )  ,//stop loss buyentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc28g4  , Digits)  ,//take profit  
   bc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc08 > Bid) 
/////######//+------------------------------------------------------------------+
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string sc28  = "Sc28 "; 
   string sc28g  = "Sc28g "; 
   string sc28gv  = "Sc28gv "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(sc28,cymbol)      && TypeSellStopComment(sc28)  )
   { CloseExpiredPendingWithThisComment(sc28,210); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(sc28g,cymbol)      && TypeSellStopComment(sc28g)  )
   { CloseExpiredPendingWithThisComment(sc28g,300); } 
///////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc28)  >  4 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc28) > 0  )
   { BreakEvenTradeWithThisComment(sc28,PERIOD_M15,25,5); }
////////////////////////////////////////////////////////////////////////////////////////////
   if(UplOfOrderWithThisComment(sc28g)  >  4 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc28g) > 0  )
   { BreakEvenTradeWithThisComment(sc28g,PERIOD_M15,25,5); }
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc28) + UplOfOrderWithThisComment(sc28g) < - 4 * SendLot * 100 
   && UplOfOrderWithThisComment(sc28) + UplOfOrderWithThisComment(sc28g) > - 5 * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(sc28,5);
      ModifyStopLossOfOrdersWithThisComment(sc28g,5);}
///######//+------------------------------------------------------------------+
// THIS IS TRAILING OF ALL TRADES  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc28) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(sc28,15);}
///######//+
   if(UplOfOrderWithThisComment(sc28g) > ( 10 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(sc28g,52);}
///######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN TRADES IN A GRID  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(sc28g) >  2 * SendLot * 100 && NumberOfSellsWithThisComment(sc28g) > 1 )
   {  StepifyStopLossOfOrdersWithThisComment(sc28g,2,5,3);}
/////######//+----------------------------------------------------------------+
// THIS IS IF TRADES IN A GRID ARE IN PROIT BUT SOME ARE NOT MODIFY STOP LOSS OF THOSE TRADES WITH NO BREAK EVEN
////######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(sc28g) + UplOfOrderWithThisComment(sc28) >  2 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc28) + NumberOfSellsWithThisComment(sc28g) > 1 )
   {  ModifyOrdersWithNoBreakEvenComment(sc28,20); ModifyOrdersWithNoBreakEvenComment(sc28g,20);}
///######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double sellentryc28e1 = 0; double selltakeprofitc28e1 = 0; double sellstoplossc28e1 = 0;
   double sellentryc28g1 = 0; double selltakeprofitc28g1 = 0; double sellstoplossc28g1 = 0;
   double sellentryc28g2 = 0; double selltakeprofitc28g2 = 0; double sellstoplossc28g2 = 0;
   double sellentryc28g3 = 0; double selltakeprofitc28g3 = 0; double sellstoplossc28g3 = 0;
   double sellentryc28g4 = 0; double selltakeprofitc28g4 = 0; double sellstoplossc28g4 = 0;
//MidTma(PERIOD_H4,bandi,1);//
  double firstsellentryc28 = MidTma(PERIOD_M15,80,1) - (TmbFac() * 0);
  //GetHiDonn(cymbol,PERIOD_H4,2,1)  + (TmbFac() * 0.1);
  //HighestHighPrice(PERIOD_H4,bandi,1) ;
  // MidTma(PERIOD_H4,5,1) - (TmbFac() * 0);
///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+

   bool sellc28 =(  GetLoDonn(cymbol,PERIOD_H4,2,5) < LowerTma(PERIOD_H4,5,1.6,2,5)
      &&    GetLoDonn(cymbol,PERIOD_H4,2,5) < CandleLow(PERIOD_D1,2)
      &&    CandleClose(PERIOD_H4,8) > MidTma(PERIOD_H4,12,8)
      &&    CandleHigh(PERIOD_H4,1) > MidTma(PERIOD_H4,12,1)
      &&    MidTma(PERIOD_M15,80,Bar(PERIOD_M15,PERIOD_H4,5)) > MidTma(PERIOD_M15,80,1)
      &&    GetLoDonn(cymbol,PERIOD_M15,58,1) > LowerTma(PERIOD_M15,80,3.0,50,1)
      &&    GetMidDonn(cymbol,PERIOD_M15,58,1) > MidTma(PERIOD_M15,80,1)
      &&    CandleClose(PERIOD_M15,1) > MidTma(PERIOD_M15,80,1)
      &&    HighestHighPrice(PERIOD_M15,18,1) > UpperTma(PERIOD_M15,80,3.0,50,HighestHighBar(PERIOD_M15,18,1))
                                   );
//First Filter before Sending Single Order
   bool selltrigc281 = (   sellc28 
   &&  !DoesTradeCommentExistForThisPair(sc28,cymbol)  );
//Secomd Filter before Sending Single Order
   bool selltrigc282 = ( firstsellentryc28 > Highsellprice(sc28) + ( dongap()* 2 ) 
     && DoesTradeCommentExistForThisPair(sc28,cymbol) 
     && !TypeSellStopComment(sc28)
     &&( TimeCurrent() - LiveTime(sc28) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool selltrigc283 = ( DoesTradeCommentExistForThisPair(sc28,cymbol) 
     && !sellc28 && firstsellentryc28 < Lowsellprice(sc28) - (dongap() * 0.8 )
     &&  IsCloseBelowMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetLoDonn(cymbol,PERIOD_H4,5,1 ) < GetLoDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) > GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(sc28) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(sc28,cymbol) 
   && DoesTradeCommentExistForThisPair(sc28g,cymbol) 
   &&    !TypeSellComment(sc28g) )    
   { CloseExpiredPendingWithThisComment(sc28g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(sc28,cymbol) 
   && DoesTradeCommentExistForThisPair(sc28g,cymbol) 
   && TypeSellComment(sc28) && !TypeSellComment(sc28g)
   && Ask > Highsellprice(sc28) + ( TmbFac() * 4 ) 
   && Highsellprice(sc28g) <= Highsellprice(sc28) + ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(sc28g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstsellentryc28 > Highsellprice(sc28) + ( dongap()* 1 )
   && TypeSellStopComment(sc28) )     
   { CloseExpiredPendingWithThisComment(sc28,0) ;} 
//// Delete Stops when Price is going Up
   if( firstsellentryc28 < Lowsellprice(sc28) - ( dongap()* 1 )
   && TypeSellStopComment(sc28) )    
   { CloseExpiredPendingWithThisComment(sc28,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( selltrigc281 )  
     { sellentryc28e1 = firstsellentryc28 ; 
      selltakeprofitc28e1 = sellentryc28e1 - ( TmbFac() * 11 );
      sellstoplossc28e1 =   sellentryc28e1 + ( TmbFac() * 13 );   }
/////////////// Second Filter Take Profit And Stop Loss
    if( selltrigc282  ) if(( firstsellentryc28 > Lowsellprice(sc28) + dongap()|| firstsellentryc28 < Lowsellprice(sc28) - dongap())
      &&   firstsellentryc28 < Highsellprice(sc28) - dongap() )
     { sellentryc28e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc28e1 = sellentryc28e1 - ( dongap() * 10 );
      sellstoplossc28e1 =   sellentryc28e1 + ( dongap() * 6 );   }
//////////////// Third Filter Take Profit And Stop Loss
     if( selltrigc283  ) 
     { sellentryc28e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc28e1 = sellentryc28e1 - ( dongap() * 10 );
      sellstoplossc28e1 =   sellentryc28e1 + ( dongap() * 6 );   }
//////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
//////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(sc28,cymbol)
      &&    !TypeSellStopComment(sc28g)
      &&    !TypeSellComment(sc28g)
      &&    ( TimeCurrent() - LiveTime(sc28) ) / 60 < 255 ) 
     { 
      if(    NumberOfSellStopsWithThisComment(sc28) == 1  &&    !TypeSellComment(sc28) )
         sellentryc28g1 = Lowsellprice(sc28) - ( TmbFac()* 1.5 ) ;

      if(    NumberOfSellsWithThisComment(sc28) == 1 &&   Ask > Lowsellprice(sc28) - ( TmbFac() * 1.5 )
      &&   Ask < Lowsellprice(sc28)   )
         sellentryc28g1 = Ask - ( TmbFac()* 1.5 ) ;
          
      if(   Ask > Highsellprice(sc28) + ( TmbFac() * 4 ) && Ask >  UpperTma(PERIOD_M15,80,3.0,50, 1)    )
         sellentryc28g1 = MidTma(PERIOD_M15,80,1)  - ( TmbFac()* 1 ) ;
    
      selltakeprofitc28g1 = sellentryc28g1 - ( TmbFac() * 50 );
      sellstoplossc28g1 =   sellentryc28g1 + ( TmbFac() * 5 );   

      sellentryc28g2 = sellentryc28g1 - ( TmbFac()* (0.5) ) ; 
      selltakeprofitc28g2 = sellentryc28g2 - ( TmbFac() * 50 );
      sellstoplossc28g2 =   sellentryc28g2 + ( TmbFac() * 5 );   
         
      sellentryc28g3 = sellentryc28g2 - ( TmbFac()* (0.5) ) ; 
      selltakeprofitc28g3 = sellentryc28g3 - ( TmbFac() * 50 );
      sellstoplossc28g3 =   sellentryc28g3 + ( TmbFac() * 5 );   
      
      sellentryc28g4 = sellentryc28g3 - ( TmbFac()* (1) ) ; 
      selltakeprofitc28g4 = sellentryc28g4 - ( TmbFac() * 50 );
      sellstoplossc28g4 =   sellentryc28g4 + ( TmbFac() * 7 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  selltrigc283
      &&    !TypeSellStopComment(sc28g)       ) 
 
     { sellentryc28g1 = sellentryc28e1 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc28g1 = sellentryc28g1 - ( TmbFac() * 10 );
      sellstoplossc28g1 =   sellentryc28g1 + ( TmbFac() * 4 );   

      sellentryc28g2 = sellentryc28g1 - ( TmbFac()* 0.2 ) ; 
      selltakeprofitc28g2 = sellentryc28g2 - ( TmbFac() * 10 );
      sellstoplossc28g2 =   sellentryc28g2 + ( TmbFac() * 4 );   

       sellentryc28g3 = sellentryc28g2 - ( TmbFac()* 0.6 ) ; 
      selltakeprofitc28g3 = sellentryc28g3 - ( TmbFac() * 15 );
      sellstoplossc28g3 =   sellentryc28g3 + ( TmbFac() * 12 );   

      sellentryc28g4 = sellentryc28g3 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc28g4 = sellentryc28g4 - ( TmbFac() * 15 );
      sellstoplossc28g4 =   sellentryc28g4 + ( TmbFac() * 12 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(sellentryc28e1 < Ask && sellentryc28e1 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc28e1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc28e1 , Digits )  ,//stop loss sellentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc28e1  , Digits)  ,//take profit  
   sc28);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc28 > Bid) 

   if(sellentryc28g1 < Ask && sellentryc28g1 > 0) 
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc28g1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc28g1 , Digits )  ,//stop loss sellentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc28g1  , Digits)  ,//take profit  
   sc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc28 > Bid) 

   if(sellentryc28g2 < Ask && sellentryc28g2 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc28g2 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc28g2 , Digits )  ,//stop loss sellentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc28g2  , Digits)  ,//take profit  
   sc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc28 > Bid) 

   if(sellentryc28g3 < Ask && sellentryc28g3 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc28g3 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc28g3 , Digits )  ,//stop loss sellentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc28g3  , Digits)  ,//take profit  
   sc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc28 > Bid) 

   if(sellentryc28g4 < Ask && sellentryc28g4 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc28g4 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc28g4 , Digits )  ,//stop loss sellentryc28  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc28g4  , Digits)  ,//take profit  
   sc28g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc08 > Bid) 
/////######//+------------------------------------------------------------------+
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string bc29  = "Bc29 "; 
   string bc29g  = "Bc29g "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(bc29,cymbol)      && TypeBuyStopComment(bc29)  )
   { CloseExpiredPendingWithThisComment(bc29,180); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(bc29g,cymbol)      && TypeBuyStopComment(bc29g)  )
   { CloseExpiredPendingWithThisComment(bc29g,300); } 
///////////////////////////////////////////////////////////////////////////////////////
////######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
////######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc29)  >  4 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc29) > 0  )
   { BreakEvenTradeWithThisComment(bc29,PERIOD_M15,25,5); }
////######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc29) + UplOfOrderWithThisComment(bc29g) < - 5 * SendLot * 100 
   && UplOfOrderWithThisComment(bc29) + UplOfOrderWithThisComment(bc29g) > - ( 5 + 1.5 )  * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(bc29,5);
      ModifyStopLossOfOrdersWithThisComment(bc29g,5);}
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc29) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(bc29,15);}
/////######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double buyentryc29e1 = 0; double buytakeprofitc29e1 = 0; double buystoplossc29e1 = 0;
   double buyentryc29g1 = 0; double buytakeprofitc29g1 = 0; double buystoplossc29g1 = 0;
   double buyentryc29g2 = 0; double buytakeprofitc29g2 = 0; double buystoplossc29g2 = 0;
   double buyentryc29g3 = 0; double buytakeprofitc29g3 = 0; double buystoplossc29g3 = 0;
   double buyentryc29g4 = 0; double buytakeprofitc29g4 = 0; double buystoplossc29g4 = 0;

  double firstbuyentryc29 = MidTma(PERIOD_M15,80,1) - (TmbFac() * 0);
///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+

   bool buyc29 =(   IsCloseBelowMidDon(PERIOD_H4,5,2,3)
   &&  GetLoDonn(cymbol,PERIOD_H4,5,5) == GetLoDonn(cymbol,PERIOD_H4,5,3)
   && CandleLow(PERIOD_H4,1) < GetLoDonn(cymbol,PERIOD_H4,5,3)
   && CandleHigh(PERIOD_H4,2) > UpperTma(PERIOD_M15,80,3,50, Bar(PERIOD_M15,PERIOD_H4,2) - Bar(PERIOD_M15,PERIOD_H4,0) )   
   && CandleClose(PERIOD_H4,1) < GetMidDonn(cymbol,PERIOD_H4,5,1)
   && CandleLow(PERIOD_M15,1) < LowerTma(PERIOD_M15,80,3,50,1)
                                   );
//First Filter before Sending Single Order
   bool buytrigc291 = (   buyc29 
   &&  !DoesTradeCommentExistForThisPair(bc29,cymbol)  );
//Secomd Filter before Sending Single Order
   bool buytrigc292 = ( firstbuyentryc29 < Lowbuyprice(bc29) - ( dongap()* 2 ) 
     && DoesTradeCommentExistForThisPair(bc29,cymbol) 
     && !TypeBuyStopComment(bc29)
     &&( TimeCurrent() - LiveTime(bc29) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool buytrigc293 = ( DoesTradeCommentExistForThisPair(bc29,cymbol) 
     && !buyc29 && firstbuyentryc29 > Highbuyprice(bc29) + (dongap() * 0.8 )
     &&  IsCloseAboveMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetHiDonn(cymbol,PERIOD_H4,5,1 ) > GetHiDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) < GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(bc29) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(bc29,cymbol) 
   && DoesTradeCommentExistForThisPair(bc29g,cymbol) 
   &&    !TypeBuyComment(bc29g) )    
   { CloseExpiredPendingWithThisComment(bc29g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(bc29,cymbol) 
   && DoesTradeCommentExistForThisPair(bc29g,cymbol) 
   && TypeBuyComment(bc29) && !TypeBuyComment(bc29g)
   && Bid < Lowbuyprice(bc29) - ( TmbFac() * 4 ) 
   && Lowbuyprice(bc29g) >= Lowbuyprice(bc29) - ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(bc29g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstbuyentryc29 < Lowbuyprice(bc29) - ( dongap()* 1 )
   && TypeBuyStopComment(bc29) )     
   { CloseExpiredPendingWithThisComment(bc29,0) ;} 
//// Delete Stops when Price is going Up
   if( firstbuyentryc29 > Highbuyprice(bc29) + ( dongap()* 1 )
   && TypeBuyStopComment(bc29) )    
   { CloseExpiredPendingWithThisComment(bc29,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( buytrigc291 )  
     { buyentryc29e1 = firstbuyentryc29 ; 
      buytakeprofitc29e1 = buyentryc29e1 + ( TmbFac() * 11 );
      buystoplossc29e1 =   buyentryc29e1 - ( TmbFac() * 13 );   }
//////////////// Second Filter Take Profit And Stop Loss
    if( buytrigc292  ) if(( firstbuyentryc29 > Lowbuyprice(bc29) + dongap()|| firstbuyentryc29 < Lowbuyprice(bc29) - dongap())
      &&   firstbuyentryc29 < Highbuyprice(bc29) - dongap() )
     { buyentryc29e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc29e1 = buyentryc29e1 + ( dongap() * 10 );
      buystoplossc29e1 =   buyentryc29e1 - ( dongap() * 6 );   }
///////////////// Third Filter Take Profit And Stop Loss
     if( buytrigc293  ) 
     { buyentryc29e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc29e1 = buyentryc29e1 + ( dongap() * 10 );
      buystoplossc29e1 =   buyentryc29e1 - ( dongap() * 6 );   }
////////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(bc29,cymbol)
      &&    !TypeBuyStopComment(bc29g)
      &&    !TypeBuyComment(bc29g)
      &&    ( TimeCurrent() - LiveTime(bc29) ) / 60 > 0  
      &&    ( TimeCurrent() - LiveTime(bc29) ) / 60 < 60 ) 
     { 
      if(    NumberOfBuyStopsWithThisComment(bc29) == 1  &&    !TypeBuyComment(bc29) )
         buyentryc29g1 = Highbuyprice(bc29) + ( TmbFac()*2.5 ) ;

      if(    NumberOfBuysWithThisComment(bc29) == 1 &&   Bid < Highbuyprice(bc29) + ( TmbFac() * 1 )
      &&   Bid > Highbuyprice(bc29 ) -( TmbFac() * 0 )   )
         buyentryc29g1 = Bid + ( TmbFac()* 1 ) ;
          
      if(   Bid < Lowbuyprice(bc29) - ( TmbFac() * 4 ) && Bid <  LowerTma(PERIOD_M15,80,3.0,50, 1)  )
         buyentryc29g1 =  MidTma(PERIOD_M15,80,1) + ( TmbFac()* 1 ) ;
    
      buytakeprofitc29g1 = buyentryc29g1 + ( TmbFac() * 50 );
      buystoplossc29g1 =   buyentryc29g1 - ( TmbFac() * 5 );   

      buyentryc29g2 = buyentryc29g1 + ( TmbFac()* (4.0) ) ; 
      buytakeprofitc29g2 = buyentryc29g2 + (TmbFac() * 50);
      buystoplossc29g2 =   buyentryc29g2 - ( TmbFac() * 5 );   
         
      buyentryc29g3 = buyentryc29g2 + ( TmbFac()* (0.5) ) ; 
      buytakeprofitc29g3 = buyentryc29g3 + ( TmbFac() * 50 );
      buystoplossc29g3 =   buyentryc29g3 - ( TmbFac() * 5 );   
      
      buyentryc29g4 = buyentryc29g3 + ( TmbFac()* (0.5) ) ; 
      buytakeprofitc29g4 = buyentryc29g4 + ( TmbFac() * 50 );
      buystoplossc29g4 =   buyentryc29g4 - ( TmbFac() * 7 );   }
/////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  buytrigc293
      &&    !TypeBuyStopComment(bc29g)       ) 
 
     { buyentryc29g1 = buyentryc29e1 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc29g1 = buyentryc29g1 + ( TmbFac() * 10 );
      buystoplossc29g1 =   buyentryc29g1 - ( TmbFac() * 4 );   

      buyentryc29g2 = buyentryc29g1 + ( TmbFac()* 0.2 ) ; 
      buytakeprofitc29g2 = buyentryc29g2 + ( TmbFac() * 10 );
      buystoplossc29g2 =   buyentryc29g2 - ( TmbFac() * 4 );   

       buyentryc29g3 = buyentryc29g2 + ( TmbFac()* 0.6 ) ; 
      buytakeprofitc29g3 = buyentryc29g3 + ( TmbFac() * 15 );
      buystoplossc29g3 =   buyentryc29g3 - ( TmbFac() * 12 );   

      buyentryc29g4 = buyentryc29g3 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc29g4 = buyentryc29g4 + ( TmbFac() * 15 );
      buystoplossc29g4 =   buyentryc29g4 - ( TmbFac() * 12 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(buyentryc29e1 > Bid)
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc29e1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc29e1 , Digits )  ,//stop loss buyentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc29e1  , Digits)  ,//take profit  
   bc29);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc29 > Bid) 

   if(buyentryc29g1 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc29g1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc29g1 , Digits )  ,//stop loss buyentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc29g1  , Digits)  ,//take profit  
   bc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc29 > Bid) 

   if(buyentryc29g2 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc29g2 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc29g2 , Digits )  ,//stop loss buyentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc29g2  , Digits)  ,//take profit  
   bc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc29 > Bid) 

   if(buyentryc29g3 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc29g3 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc29g3 , Digits )  ,//stop loss buyentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc29g3  , Digits)  ,//take profit  
   bc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc29 > Bid) 

   if(buyentryc29g4 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc29g4 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc29g4 , Digits )  ,//stop loss buyentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc29g4  , Digits)  ,//take profit  
   bc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc08 > Bid) 
/////######//+------------------------------------------------------------------+
/////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string sc29  = "Sc29 "; 
   string sc29g  = "Sc29g "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(sc29,cymbol)      && TypeSellStopComment(sc29)  )
   { CloseExpiredPendingWithThisComment(sc29,180); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(sc29g,cymbol)      && TypeSellStopComment(sc29g)  )
   { CloseExpiredPendingWithThisComment(sc29g,300); } 
///////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc29)  >  4 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc29) > 0  )
   { BreakEvenTradeWithThisComment(sc29,PERIOD_M15,25,5); }
/////######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc29) + UplOfOrderWithThisComment(sc29g) < - 5 * SendLot * 100 
   && UplOfOrderWithThisComment(sc29) + UplOfOrderWithThisComment(sc29g) > - (5 + 1.5) * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(sc29,5);
      ModifyStopLossOfOrdersWithThisComment(sc29g,5);}
///######//+------------------------------------------------------------------+
// THIS IS TRAILING OF ALL TRADES  WITH THIS COMMENT 
////######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc29) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(sc29,15);}
////######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double sellentryc29e1 = 0; double selltakeprofitc29e1 = 0; double sellstoplossc29e1 = 0;
   double sellentryc29g1 = 0; double selltakeprofitc29g1 = 0; double sellstoplossc29g1 = 0;
   double sellentryc29g2 = 0; double selltakeprofitc29g2 = 0; double sellstoplossc29g2 = 0;
   double sellentryc29g3 = 0; double selltakeprofitc29g3 = 0; double sellstoplossc29g3 = 0;
   double sellentryc29g4 = 0; double selltakeprofitc29g4 = 0; double sellstoplossc29g4 = 0;

  double firstsellentryc29 = MidTma(PERIOD_M15,80,1) - (TmbFac() * 0);
///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+

   bool sellc29 =(   IsCloseAboveMidDon(PERIOD_H4,5,2,3)
   &&  GetHiDonn(cymbol,PERIOD_H4,5,5) == GetHiDonn(cymbol,PERIOD_H4,5,3)
   && CandleHigh(PERIOD_H4,1) > GetHiDonn(cymbol,PERIOD_H4,5,3)
   && CandleLow(PERIOD_H4,2) < LowerTma(PERIOD_M15,80,3,50, Bar(PERIOD_M15,PERIOD_H4,2) - Bar(PERIOD_M15,PERIOD_H4,0) )   
   && CandleClose(PERIOD_H4,1) > GetMidDonn(cymbol,PERIOD_H4,5,1)
   && CandleHigh(PERIOD_M15,1) > UpperTma(PERIOD_M15,80,3,50,1)
                                   );
//First Filter before Sending Single Order
   bool selltrigc291 = (   sellc29 
   &&  !DoesTradeCommentExistForThisPair(sc29,cymbol)  );
//Secomd Filter before Sending Single Order
   bool selltrigc292 = ( firstsellentryc29 > Highsellprice(sc29) + ( dongap()* 2 ) 
     && DoesTradeCommentExistForThisPair(sc29,cymbol) 
     && !TypeSellStopComment(sc29)
     &&( TimeCurrent() - LiveTime(sc29) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool selltrigc293 = ( DoesTradeCommentExistForThisPair(sc29,cymbol) 
     && !sellc29 && firstsellentryc29 < Lowsellprice(sc29) - (dongap() * 0.8 )
     &&  IsCloseBelowMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetLoDonn(cymbol,PERIOD_H4,5,1 ) < GetLoDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) > GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(sc29) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(sc29,cymbol) 
   && DoesTradeCommentExistForThisPair(sc29g,cymbol) 
   &&    !TypeSellComment(sc29g) )    
   { CloseExpiredPendingWithThisComment(sc29g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(sc29,cymbol) 
   && DoesTradeCommentExistForThisPair(sc29g,cymbol) 
   && TypeSellComment(sc29) && !TypeSellComment(sc29g)
   && Ask > Highsellprice(sc29) + ( TmbFac() * 4 ) 
   && Highsellprice(sc29g) <= Highsellprice(sc29) + ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(sc29g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstsellentryc29 > Highsellprice(sc29) + ( dongap()* 1 )
   && TypeSellStopComment(sc29) )     
   { CloseExpiredPendingWithThisComment(sc29,0) ;} 
//// Delete Stops when Price is going Up
   if( firstsellentryc29 < Lowsellprice(sc29) - ( dongap()* 1 )
   && TypeSellStopComment(sc29) )    
   { CloseExpiredPendingWithThisComment(sc29,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( selltrigc291 )  
     { sellentryc29e1 = firstsellentryc29 ; 
      selltakeprofitc29e1 = sellentryc29e1 - ( TmbFac() * 11 );
      sellstoplossc29e1 =   sellentryc29e1 + ( TmbFac() * 13 );   }
/////////////// Second Filter Take Profit And Stop Loss
    if( selltrigc292  ) if(( firstsellentryc29 > Lowsellprice(sc29) + dongap()|| firstsellentryc29 < Lowsellprice(sc29) - dongap())
      &&   firstsellentryc29 < Highsellprice(sc29) - dongap() )
     { sellentryc29e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc29e1 = sellentryc29e1 - ( dongap() * 10 );
      sellstoplossc29e1 =   sellentryc29e1 + ( dongap() * 6 );   }
//////////////// Third Filter Take Profit And Stop Loss
     if( selltrigc293  ) 
     { sellentryc29e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc29e1 = sellentryc29e1 - ( dongap() * 10 );
      sellstoplossc29e1 =   sellentryc29e1 + ( dongap() * 6 );   }
//////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
//////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(sc29,cymbol)
      &&    !TypeSellStopComment(sc29g)
      &&    !TypeSellComment(sc29g)
      &&    ( TimeCurrent() - LiveTime(sc29) ) / 60 < 60 ) 
     { 
      if(    NumberOfSellStopsWithThisComment(sc29) == 1  &&    !TypeSellComment(sc29) )
         sellentryc29g1 = Lowsellprice(sc29) - ( TmbFac()* 2.5 ) ;

      if(    NumberOfSellsWithThisComment(sc29) == 1 &&   Ask > Lowsellprice(sc29) - ( TmbFac() * 1.0 )
      &&   Ask < Lowsellprice(sc29)   )
         sellentryc29g1 = Ask - ( TmbFac()* 1.0 ) ;
          
      if(   Ask > Highsellprice(sc29) + ( TmbFac() * 4 ) && Ask >  UpperTma(PERIOD_M15,80,3.0,50, 1)    )
         sellentryc29g1 = MidTma(PERIOD_M15,80,1)  - ( TmbFac()* 1 ) ;
    
      selltakeprofitc29g1 = sellentryc29g1 - ( TmbFac() * 50 );
      sellstoplossc29g1 =   sellentryc29g1 + ( TmbFac() * 5 );   

      sellentryc29g2 = sellentryc29g1 - ( TmbFac()* (4.0) ) ; 
      selltakeprofitc29g2 = sellentryc29g2 - ( TmbFac() * 50 );
      sellstoplossc29g2 =   sellentryc29g2 + ( TmbFac() * 5 );   
         
      sellentryc29g3 = sellentryc29g2 - ( TmbFac()* (0.5) ) ; 
      selltakeprofitc29g3 = sellentryc29g3 - ( TmbFac() * 50 );
      sellstoplossc29g3 =   sellentryc29g3 + ( TmbFac() * 5 );   
      
      sellentryc29g4 = sellentryc29g3 - ( TmbFac()* (0.5) ) ; 
      selltakeprofitc29g4 = sellentryc29g4 - ( TmbFac() * 50 );
      sellstoplossc29g4 =   sellentryc29g4 + ( TmbFac() * 7 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  selltrigc293
      &&    !TypeSellStopComment(sc29g)       ) 
 
     { sellentryc29g1 = sellentryc29e1 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc29g1 = sellentryc29g1 - ( TmbFac() * 10 );
      sellstoplossc29g1 =   sellentryc29g1 + ( TmbFac() * 4 );   

      sellentryc29g2 = sellentryc29g1 - ( TmbFac()* 0.2 ) ; 
      selltakeprofitc29g2 = sellentryc29g2 - ( TmbFac() * 10 );
      sellstoplossc29g2 =   sellentryc29g2 + ( TmbFac() * 4 );   

       sellentryc29g3 = sellentryc29g2 - ( TmbFac()* 0.6 ) ; 
      selltakeprofitc29g3 = sellentryc29g3 - ( TmbFac() * 15 );
      sellstoplossc29g3 =   sellentryc29g3 + ( TmbFac() * 12 );   

      sellentryc29g4 = sellentryc29g3 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc29g4 = sellentryc29g4 - ( TmbFac() * 15 );
      sellstoplossc29g4 =   sellentryc29g4 + ( TmbFac() * 12 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(sellentryc29e1 < Ask && sellentryc29e1 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc29e1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc29e1 , Digits )  ,//stop loss sellentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc29e1  , Digits)  ,//take profit  
   sc29);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc29 > Bid) 

   if(sellentryc29g1 < Ask && sellentryc29g1 > 0) 
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc29g1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc29g1 , Digits )  ,//stop loss sellentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc29g1  , Digits)  ,//take profit  
   sc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc29 > Bid) 

   if(sellentryc29g2 < Ask && sellentryc29g2 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc29g2 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc29g2 , Digits )  ,//stop loss sellentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc29g2  , Digits)  ,//take profit  
   sc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc29 > Bid) 

   if(sellentryc29g3 < Ask && sellentryc29g3 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc29g3 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc29g3 , Digits )  ,//stop loss sellentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc29g3  , Digits)  ,//take profit  
   sc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc29 > Bid) 

   if(sellentryc29g4 < Ask && sellentryc29g4 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc29g4 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc29g4 , Digits )  ,//stop loss sellentryc29  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc29g4  , Digits)  ,//take profit  
   sc29g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc08 > Bid) 
/////######//+------------------------------------------------------------------+
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string bc30  = "Bc30 "; 
   string bc30g  = "Bc30g "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(bc30,cymbol)      && TypeBuyStopComment(bc30)  )
   { CloseExpiredPendingWithThisComment(bc30,180); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(bc30g,cymbol)      && TypeBuyStopComment(bc30g)  )
   { CloseExpiredPendingWithThisComment(bc30g,120); } 
///////////////////////////////////////////////////////////////////////////////////////
////######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
////######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc30)  >  4 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc30) > 0  )
   { BreakEvenTradeWithThisComment(bc30,PERIOD_M15,25,5); }
////////////////////////////////////////////////////////////////////////////////////////////
   if(UplOfOrderWithThisComment(bc30g)  >  4 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc30g) > 0  )
   { BreakEvenTradeWithThisComment(bc30g,PERIOD_M15,25,5); }
////######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc30) + UplOfOrderWithThisComment(bc30g) < - 5 * SendLot * 100 
   && UplOfOrderWithThisComment(bc30) + UplOfOrderWithThisComment(bc30g) > - ( 5 + 1.5 )  * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(bc30,5);
      ModifyStopLossOfOrdersWithThisComment(bc30g,5);}
//////######//+------------------------------------------------------------------+
// THIS IS TRAILING OF ALL TRADES  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc30) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(bc30,15);}
///######//+
   if(UplOfOrderWithThisComment(bc30g) > ( 10 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(bc30g,52);}
////######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN TRADES IN A GRID  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(bc30g) >  2 * SendLot * 100 && NumberOfBuysWithThisComment(bc30g) > 1 )
   {  StepifyStopLossOfOrdersWithThisComment(bc30g,1,5,3);}
//////######//+----------------------------------------------------------------+
// THIS IS IF TRADES IN A GRID ARE IN PROIT BUT SOME ARE NOT MODIFY STOP LOSS OF THOSE TRADES WITH NO BREAK EVEN
/////######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(bc30g) + UplOfOrderWithThisComment(bc30) >  6 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc30) + NumberOfBuysWithThisComment(bc30g) > 1 )
   {  ModifyOrdersWithNoBreakEvenComment(bc30,20); ModifyOrdersWithNoBreakEvenComment(bc30g,25);}
//////######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double buyentryc30e1 = 0; double buytakeprofitc30e1 = 0; double buystoplossc30e1 = 0;
   double buyentryc30g1 = 0; double buytakeprofitc30g1 = 0; double buystoplossc30g1 = 0;
   double buyentryc30g2 = 0; double buytakeprofitc30g2 = 0; double buystoplossc30g2 = 0;
   double buyentryc30g3 = 0; double buytakeprofitc30g3 = 0; double buystoplossc30g3 = 0;
   double buyentryc30g4 = 0; double buytakeprofitc30g4 = 0; double buystoplossc30g4 = 0;

  double firstbuyentryc30 = LowerTma(PERIOD_M15,80,3,50,0) - (TmbFac() * 0);

///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+

   bool buyc30 =(   CandleHigh(PERIOD_H4,2) > UpperTma(PERIOD_M15,80,3,50, Bar(PERIOD_M15,PERIOD_H4,2) - Bar(PERIOD_M15,PERIOD_H4,0) ) 
      && CandleLow(PERIOD_M15,5) > LowerTma(PERIOD_M15,80,3,50,5)//5 or 15
      && CandleClose(PERIOD_H4,6) < GetMidDonn(cymbol,PERIOD_H4,5,6)
      && CandleClose(PERIOD_H4,2) > GetMidDonn(cymbol,PERIOD_H4,5,2)
      && CandleHigh(PERIOD_M15,2) < LowerTma(PERIOD_M15,80,3,50,2)
      && CandleClose(PERIOD_M15,1) < LowerTma(PERIOD_M15,80,3,50,1)
      && CandleClose(PERIOD_M15,3) > CandleLow(PERIOD_D1,1) 
                                   );
//First Filter before Sending Single Order
   bool buytrigc301 = (   buyc30 
   &&  !DoesTradeCommentExistForThisPair(bc30,cymbol)  );
//Secomd Filter before Sending Single Order
   bool buytrigc302 = ( firstbuyentryc30 < Lowbuyprice(bc30) - ( dongap()* 2 ) 
     && DoesTradeCommentExistForThisPair(bc30,cymbol) 
     && !TypeBuyStopComment(bc30)
     &&( TimeCurrent() - LiveTime(bc30) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool buytrigc303 = ( DoesTradeCommentExistForThisPair(bc30,cymbol) 
     && !buyc30 && firstbuyentryc30 > Highbuyprice(bc30) + (dongap() * 0.8 )
     &&  IsCloseAboveMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetHiDonn(cymbol,PERIOD_H4,5,1 ) > GetHiDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) < GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(bc30) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(bc30,cymbol) 
   && DoesTradeCommentExistForThisPair(bc30g,cymbol) 
   &&    !TypeBuyComment(bc30g) )    
   { CloseExpiredPendingWithThisComment(bc30g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(bc30,cymbol) 
   && DoesTradeCommentExistForThisPair(bc30g,cymbol) 
   && TypeBuyComment(bc30) && !TypeBuyComment(bc30g)
   && Bid < Lowbuyprice(bc30) - ( TmbFac() * 4 ) 
   && Lowbuyprice(bc30g) >= Lowbuyprice(bc30) - ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(bc30g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstbuyentryc30 < Lowbuyprice(bc30) - ( dongap()* 1 )
   && TypeBuyStopComment(bc30) )     
   { CloseExpiredPendingWithThisComment(bc30,0) ;} 
//// Delete Stops when Price is going Up
   if( firstbuyentryc30 > Highbuyprice(bc30) + ( dongap()* 1 )
   && TypeBuyStopComment(bc30) )    
   { CloseExpiredPendingWithThisComment(bc30,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( buytrigc301 )  
     { buyentryc30e1 = firstbuyentryc30 ; 
      buytakeprofitc30e1 = buyentryc30e1 + ( TmbFac() * 11 );
      buystoplossc30e1 =   buyentryc30e1 - ( TmbFac() * 5 );   }
//////////////// Second Filter Take Profit And Stop Loss
    if( buytrigc302  ) if(( firstbuyentryc30 > Lowbuyprice(bc30) + dongap()|| firstbuyentryc30 < Lowbuyprice(bc30) - dongap())
      &&   firstbuyentryc30 < Highbuyprice(bc30) - dongap() )
     { buyentryc30e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc30e1 = buyentryc30e1 + ( dongap() * 10 );
      buystoplossc30e1 =   buyentryc30e1 - ( dongap() * 6 );   }
///////////////// Third Filter Take Profit And Stop Loss
     if( buytrigc303  ) 
     { buyentryc30e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc30e1 = buyentryc30e1 + ( dongap() * 10 );
      buystoplossc30e1 =   buyentryc30e1 - ( dongap() * 6 );   }
////////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(bc30,cymbol)
      &&    !TypeBuyStopComment(bc30g)
      &&    !TypeBuyComment(bc30g)
      &&    ( TimeCurrent() - LiveTime(bc30) ) / 60 < 60 ) 
     { 
      if(    NumberOfBuyStopsWithThisComment(bc30) == 1  &&    !TypeBuyComment(bc30) )
         buyentryc30g1 = Highbuyprice(bc30) + ( TmbFac()* 3.8 ) ;

      if(    NumberOfBuysWithThisComment(bc30) == 1 &&   Bid < Highbuyprice(bc30) + ( TmbFac() * 2.5 )
      &&   Bid > Highbuyprice(bc30 ) -( TmbFac() * 0 )   )
         buyentryc30g1 = Bid + ( TmbFac()* 0.5 ) ;
          
      if(   Bid < Lowbuyprice(bc30) - ( TmbFac() * 4 ) && Bid <  LowerTma(PERIOD_M15,80,3.0,50, 1)  )
         buyentryc30g1 =  MidTma(PERIOD_M15,80,1) + ( TmbFac()* 0.5 ) ;
    
      buytakeprofitc30g1 = buyentryc30g1 + ( TmbFac() * 50 );
      buystoplossc30g1 =   buyentryc30g1 - ( TmbFac() * 5 );   

      buyentryc30g2 = buyentryc30g1 + ( TmbFac()* (3.0) ) ; 
      buytakeprofitc30g2 = buyentryc30g2 + (TmbFac() * 50);
      buystoplossc30g2 =   buyentryc30g2 - ( TmbFac() * 5 );   
         
      buyentryc30g3 = buyentryc30g2 + ( TmbFac()* (2.5) ) ; 
      buytakeprofitc30g3 = buyentryc30g3 + ( TmbFac() * 50 );
      buystoplossc30g3 =   buyentryc30g3 - ( TmbFac() * 5 );   
      
      buyentryc30g4 = buyentryc30g3 + ( TmbFac()* (2.5) ) ; 
      buytakeprofitc30g4 = buyentryc30g4 + ( TmbFac() * 50 );
      buystoplossc30g4 =   buyentryc30g4 - ( TmbFac() * 7 );   }
/////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  buytrigc303
      &&    !TypeBuyStopComment(bc30g)       ) 
 
     { buyentryc30g1 = buyentryc30e1 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc30g1 = buyentryc30g1 + ( TmbFac() * 10 );
      buystoplossc30g1 =   buyentryc30g1 - ( TmbFac() * 4 );   

      buyentryc30g2 = buyentryc30g1 + ( TmbFac()* 0.2 ) ; 
      buytakeprofitc30g2 = buyentryc30g2 + ( TmbFac() * 10 );
      buystoplossc30g2 =   buyentryc30g2 - ( TmbFac() * 4 );   

       buyentryc30g3 = buyentryc30g2 + ( TmbFac()* 0.6 ) ; 
      buytakeprofitc30g3 = buyentryc30g3 + ( TmbFac() * 15 );
      buystoplossc30g3 =   buyentryc30g3 - ( TmbFac() * 12 );   

      buyentryc30g4 = buyentryc30g3 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc30g4 = buyentryc30g4 + ( TmbFac() * 15 );
      buystoplossc30g4 =   buyentryc30g4 - ( TmbFac() * 12 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(buyentryc30e1 > Bid)
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc30e1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc30e1 , Digits )  ,//stop loss buyentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc30e1  , Digits)  ,//take profit  
   bc30);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc30 > Bid) 

   if(buyentryc30g1 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc30g1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc30g1 , Digits )  ,//stop loss buyentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc30g1  , Digits)  ,//take profit  
   bc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc30 > Bid) 

   if(buyentryc30g2 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc30g2 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc30g2 , Digits )  ,//stop loss buyentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc30g2  , Digits)  ,//take profit  
   bc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc30 > Bid) 

   if(buyentryc30g3 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc30g3 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc30g3 , Digits )  ,//stop loss buyentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc30g3  , Digits)  ,//take profit  
   bc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc30 > Bid) 

   if(buyentryc30g4 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc30g4 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc30g4 , Digits )  ,//stop loss buyentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc30g4  , Digits)  ,//take profit  
   bc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc08 > Bid) 
/////######//+------------------------------------------------------------------+
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string sc30  = "Sc30 "; 
   string sc30g  = "Sc30g "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(sc30,cymbol)      && TypeSellStopComment(sc30)  )
   { CloseExpiredPendingWithThisComment(sc30,180); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(sc30g,cymbol)      && TypeSellStopComment(sc30g)  )
   { CloseExpiredPendingWithThisComment(sc30g,120); } 
///////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc30)  >  4 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc30) > 0  )
   { BreakEvenTradeWithThisComment(sc30,PERIOD_M15,25,5); }
/////////////////////////////////////////////////////////////////////////////////////////////
   if(UplOfOrderWithThisComment(sc30g)  >  4 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc30g) > 0  )
   { BreakEvenTradeWithThisComment(sc30g,PERIOD_M15,25,5); }
////######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc30) + UplOfOrderWithThisComment(sc30g) < - 5 * SendLot * 100 
   && UplOfOrderWithThisComment(sc30) + UplOfOrderWithThisComment(sc30g) > - (5 + 1.5) * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(sc30,5);
      ModifyStopLossOfOrdersWithThisComment(sc30g,5);}
///######//+------------------------------------------------------------------+
// THIS IS TRAILING OF ALL TRADES  WITH THIS COMMENT 
////######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc30) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(sc30,15);}
/////######//+
   if(UplOfOrderWithThisComment(sc30g) > ( 10 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(sc30g,52);}
/////######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN TRADES IN A GRID  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(sc30g) >  2 * SendLot * 100 && NumberOfSellsWithThisComment(sc30g) > 1 )
   {  StepifyStopLossOfOrdersWithThisComment(sc30g,2,5,3);}
///////######//+----------------------------------------------------------------+
// THIS IS IF TRADES IN A GRID ARE IN PROIT BUT SOME ARE NOT MODIFY STOP LOSS OF THOSE TRADES WITH NO BREAK EVEN
////######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(sc30g) + UplOfOrderWithThisComment(sc30) >  6 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc30) + NumberOfSellsWithThisComment(sc30g) > 1 )
   {  ModifyOrdersWithNoBreakEvenComment(sc30,20); ModifyOrdersWithNoBreakEvenComment(sc30g,25);}
/////######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double sellentryc30e1 = 0; double selltakeprofitc30e1 = 0; double sellstoplossc30e1 = 0;
   double sellentryc30g1 = 0; double selltakeprofitc30g1 = 0; double sellstoplossc30g1 = 0;
   double sellentryc30g2 = 0; double selltakeprofitc30g2 = 0; double sellstoplossc30g2 = 0;
   double sellentryc30g3 = 0; double selltakeprofitc30g3 = 0; double sellstoplossc30g3 = 0;
   double sellentryc30g4 = 0; double selltakeprofitc30g4 = 0; double sellstoplossc30g4 = 0;

  double firstsellentryc30 = UpperTma(PERIOD_M15,80,3,50,0) - (TmbFac() * 0);
///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+

   bool sellc30 =( CandleLow(PERIOD_H4,2) < LowerTma(PERIOD_M15,80,3,50, Bar(PERIOD_M15,PERIOD_H4,2) - Bar(PERIOD_M15,PERIOD_H4,0) ) 
      && CandleHigh(PERIOD_M15,5) < UpperTma(PERIOD_M15,80,3,50,5)//5 or 15
      && CandleClose(PERIOD_H4,6) > GetMidDonn(cymbol,PERIOD_H4,5,6)
      && CandleClose(PERIOD_H4,2) < GetMidDonn(cymbol,PERIOD_H4,5,2)
      && CandleLow(PERIOD_M15,2) > UpperTma(PERIOD_M15,80,3,50,2)
      && CandleClose(PERIOD_M15,1) > UpperTma(PERIOD_M15,80,3,50,1)
      && CandleClose(PERIOD_M15,3) < CandleHigh(PERIOD_D1,1) 
                                   );
//First Filter before Sending Single Order
   bool selltrigc301 = (   sellc30 
   &&  !DoesTradeCommentExistForThisPair(sc30,cymbol)  );
//Secomd Filter before Sending Single Order
   bool selltrigc302 = ( firstsellentryc30 > Highsellprice(sc30) + ( dongap()* 2 ) 
     && DoesTradeCommentExistForThisPair(sc30,cymbol) 
     && !TypeSellStopComment(sc30)
     &&( TimeCurrent() - LiveTime(sc30) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool selltrigc303 = ( DoesTradeCommentExistForThisPair(sc30,cymbol) 
     && !sellc30 && firstsellentryc30 < Lowsellprice(sc30) - (dongap() * 0.8 )
     &&  IsCloseBelowMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetLoDonn(cymbol,PERIOD_H4,5,1 ) < GetLoDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) > GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(sc30) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(sc30,cymbol) 
   && DoesTradeCommentExistForThisPair(sc30g,cymbol) 
   &&    !TypeSellComment(sc30g) )    
   { CloseExpiredPendingWithThisComment(sc30g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(sc30,cymbol) 
   && DoesTradeCommentExistForThisPair(sc30g,cymbol) 
   && TypeSellComment(sc30) && !TypeSellComment(sc30g)
   && Ask > Highsellprice(sc30) + ( TmbFac() * 4 ) 
   && Highsellprice(sc30g) <= Highsellprice(sc30) + ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(sc30g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstsellentryc30 > Highsellprice(sc30) + ( dongap()* 1 )
   && TypeSellStopComment(sc30) )     
   { CloseExpiredPendingWithThisComment(sc30,0) ;} 
//// Delete Stops when Price is going Up
   if( firstsellentryc30 < Lowsellprice(sc30) - ( dongap()* 1 )
   && TypeSellStopComment(sc30) )    
   { CloseExpiredPendingWithThisComment(sc30,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( selltrigc301 )  
     { sellentryc30e1 = firstsellentryc30 ; 
      selltakeprofitc30e1 = sellentryc30e1 - ( TmbFac() * 11 );
      sellstoplossc30e1 =   sellentryc30e1 + ( TmbFac() * 5 );   }
/////////////// Second Filter Take Profit And Stop Loss
    if( selltrigc302  ) if(( firstsellentryc30 > Lowsellprice(sc30) + dongap()|| firstsellentryc30 < Lowsellprice(sc30) - dongap())
      &&   firstsellentryc30 < Highsellprice(sc30) - dongap() )
     { sellentryc30e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc30e1 = sellentryc30e1 - ( dongap() * 10 );
      sellstoplossc30e1 =   sellentryc30e1 + ( dongap() * 6 );   }
//////////////// Third Filter Take Profit And Stop Loss
     if( selltrigc303  ) 
     { sellentryc30e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc30e1 = sellentryc30e1 - ( dongap() * 10 );
      sellstoplossc30e1 =   sellentryc30e1 + ( dongap() * 6 );   }
//////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(sc30,cymbol)
      &&    !TypeSellStopComment(sc30g)
      &&    !TypeSellComment(sc30g)
      &&    ( TimeCurrent() - LiveTime(sc30) ) / 60 < 60 ) 
     { 
      if(    NumberOfSellStopsWithThisComment(sc30) == 1  &&    !TypeSellComment(sc30) )
         sellentryc30g1 = Lowsellprice(sc30) - ( TmbFac()* 3.8 ) ;

      if(    NumberOfSellsWithThisComment(sc30) == 1 &&   Ask > Lowsellprice(sc30) - ( TmbFac() * 2.5 )
      &&   Ask < Lowsellprice(sc30)   )
         sellentryc30g1 = Ask - ( TmbFac()* 0.5 ) ;
          
      if(   Ask > Highsellprice(sc30) + ( TmbFac() * 4 ) && Ask >  UpperTma(PERIOD_M15,80,3.0,50, 1)    )
         sellentryc30g1 = MidTma(PERIOD_M15,80,1)  - ( TmbFac()* 0.5 ) ;
    
      selltakeprofitc30g1 = sellentryc30g1 - ( TmbFac() * 50 );
      sellstoplossc30g1 =   sellentryc30g1 + ( TmbFac() * 5 );   

      sellentryc30g2 = sellentryc30g1 - ( TmbFac()* (3) ) ; 
      selltakeprofitc30g2 = sellentryc30g2 - ( TmbFac() * 50 );
      sellstoplossc30g2 =   sellentryc30g2 + ( TmbFac() * 5 );   
         
      sellentryc30g3 = sellentryc30g2 - ( TmbFac()* (2.5) ) ; 
      selltakeprofitc30g3 = sellentryc30g3 - ( TmbFac() * 50 );
      sellstoplossc30g3 =   sellentryc30g3 + ( TmbFac() * 5 );   
      
      sellentryc30g4 = sellentryc30g3 - ( TmbFac()* (2.5) ) ; 
      selltakeprofitc30g4 = sellentryc30g4 - ( TmbFac() * 50 );
      sellstoplossc30g4 =   sellentryc30g4 + ( TmbFac() * 7 );   }
////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  selltrigc303
      &&    !TypeSellStopComment(sc30g)       ) 
 
     { sellentryc30g1 = sellentryc30e1 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc30g1 = sellentryc30g1 - ( TmbFac() * 10 );
      sellstoplossc30g1 =   sellentryc30g1 + ( TmbFac() * 4 );   

      sellentryc30g2 = sellentryc30g1 - ( TmbFac()* 0.2 ) ; 
      selltakeprofitc30g2 = sellentryc30g2 - ( TmbFac() * 10 );
      sellstoplossc30g2 =   sellentryc30g2 + ( TmbFac() * 4 );   

       sellentryc30g3 = sellentryc30g2 - ( TmbFac()* 0.6 ) ; 
      selltakeprofitc30g3 = sellentryc30g3 - ( TmbFac() * 15 );
      sellstoplossc30g3 =   sellentryc30g3 + ( TmbFac() * 12 );   

      sellentryc30g4 = sellentryc30g3 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc30g4 = sellentryc30g4 - ( TmbFac() * 15 );
      sellstoplossc30g4 =   sellentryc30g4 + ( TmbFac() * 12 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(sellentryc30e1 < Ask && sellentryc30e1 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc30e1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc30e1 , Digits )  ,//stop loss sellentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc30e1  , Digits)  ,//take profit  
   sc30);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc30 > Bid) 

   if(sellentryc30g1 < Ask && sellentryc30g1 > 0) 
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc30g1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc30g1 , Digits )  ,//stop loss sellentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc30g1  , Digits)  ,//take profit  
   sc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc30 > Bid) 

   if(sellentryc30g2 < Ask && sellentryc30g2 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc30g2 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc30g2 , Digits )  ,//stop loss sellentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc30g2  , Digits)  ,//take profit  
   sc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc30 > Bid) 

   if(sellentryc30g3 < Ask && sellentryc30g3 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc30g3 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc30g3 , Digits )  ,//stop loss sellentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc30g3  , Digits)  ,//take profit  
   sc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc30 > Bid) 

   if(sellentryc30g4 < Ask && sellentryc30g4 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc30g4 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc30g4 , Digits )  ,//stop loss sellentryc30  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc30g4  , Digits)  ,//take profit  
   sc30g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc08 > Bid) 
/////######//+------------------------------------------------------------------+
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string bc31  = "Bc31 "; 
   string bc31g  = "Bc31g "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(bc31,cymbol)      && TypeBuyStopComment(bc31)  )
   { CloseExpiredPendingWithThisComment(bc31,180); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(bc31g,cymbol)      && TypeBuyStopComment(bc31g)  )
   { CloseExpiredPendingWithThisComment(bc31g,120); } 
///////////////////////////////////////////////////////////////////////////////////////
////######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
////######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc31) + UplOfOrderWithThisComment(bc31g)  >  3 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc31) > 0  )
   { BreakEvenTradeWithThisComment(bc31,PERIOD_M15,15,5); }
////////////////////////////////////////////////////////////////////////////////////////////
   if(UplOfOrderWithThisComment(bc31g)  >  4 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc31g) > 0  )
   { BreakEvenTradeWithThisComment(bc31g,PERIOD_M15,25,5); }
////######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc31) + UplOfOrderWithThisComment(bc31g) < - 5 * SendLot * 100 
   && UplOfOrderWithThisComment(bc31) + UplOfOrderWithThisComment(bc31g) > - ( 5 + 1.5 )  * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(bc31,5);
      ModifyStopLossOfOrdersWithThisComment(bc31g,5);}
//////######//+------------------------------------------------------------------+
// THIS IS TRAILING OF ALL TRADES  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(bc31) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(bc31,15);}
///######//+
   if(UplOfOrderWithThisComment(bc31g) > ( 10 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(bc31g,52);}
////######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN TRADES IN A GRID  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(bc31g) >  2 * SendLot * 100 && NumberOfBuysWithThisComment(bc31g) > 1 )
   {  StepifyStopLossOfOrdersWithThisComment(bc31g,1,5,3);}
//////######//+----------------------------------------------------------------+
// THIS IS IF TRADES IN A GRID ARE IN PROIT BUT SOME ARE NOT MODIFY STOP LOSS OF THOSE TRADES WITH NO BREAK EVEN
/////######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(bc31g) + UplOfOrderWithThisComment(bc31) >  6 * SendLot * 100 
   && NumberOfBuysWithThisComment(bc31) + NumberOfBuysWithThisComment(bc31g) > 1 )
   {  ModifyOrdersWithNoBreakEvenComment(bc31,20); ModifyOrdersWithNoBreakEvenComment(bc31g,25);}
//////######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double buyentryc31e1 = 0; double buytakeprofitc31e1 = 0; double buystoplossc31e1 = 0;
   double buyentryc31g1 = 0; double buytakeprofitc31g1 = 0; double buystoplossc31g1 = 0;
   double buyentryc31g2 = 0; double buytakeprofitc31g2 = 0; double buystoplossc31g2 = 0;
   double buyentryc31g3 = 0; double buytakeprofitc31g3 = 0; double buystoplossc31g3 = 0;
   double buyentryc31g4 = 0; double buytakeprofitc31g4 = 0; double buystoplossc31g4 = 0;


///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+

   bool buyc31 =(  IsHiDonLMidDon(PERIOD_H4,5,22,3,7)
   && IsHiDonGMidDon(PERIOD_H4,5,22,7 - 3,1)
   && CandleClose(PERIOD_H4,1) < GetMidDonn(cymbol,PERIOD_H4,5,1)
   && GetLoDonn(cymbol,PERIOD_H4,5,1) > GetLoDonn(cymbol,PERIOD_H4,5,3)
                                   );

   bool buyc31a =(  IsMidDonGMidDon(PERIOD_H4,22,5,2,7)
   && GetHiDonn(cymbol,PERIOD_H4,22,1) == GetHiDonn(cymbol,PERIOD_H4,5,1)
    && GetHiDonn(cymbol,PERIOD_H4,22,5) == GetHiDonn(cymbol,PERIOD_H4,5,5)
    && GetHiDonn(cymbol,PERIOD_H4,22,1) == GetHiDonn(cymbol,PERIOD_H4,5,5)
  && CandleClose(PERIOD_H4,1) < GetMidDonn(cymbol,PERIOD_H4,5,1)
   && GetLoDonn(cymbol,PERIOD_H4,5,1) > GetLoDonn(cymbol,PERIOD_H4,5,3)
  && CandleClose(PERIOD_H4,5) > GetMidDonn(cymbol,PERIOD_H4,5,5)
  && CandleLow(PERIOD_H4,2) < GetMidDonn(cymbol,PERIOD_H4,5,2)
  && LowestHighPrice(PERIOD_M15,3,1) < MidTma(PERIOD_M15,34,3)
                                             );/// bool buyc31 =

   bool buyc31i =(   IsLoDonGMidDon(PERIOD_H4,5,22,3,8)
   && IsLoDonLLoDon(PERIOD_H4,22,5,5,1)
   && IsLoDonLMidDon(PERIOD_H4,5,22,8 - 3,1)
   && CandleClose(PERIOD_H4,2) > GetMidDonn(cymbol,PERIOD_H4,5,2)
   && GetHiDonn(cymbol,PERIOD_H4,5,1) < GetHiDonn(cymbol,PERIOD_H4,5,3)
   && CandleLow(PERIOD_H4,1) < GetMidDonn(cymbol,PERIOD_H4,22,1)
   && CandleHigh(PERIOD_M15,2) < GetMidDonn(cymbol,PERIOD_M15,58,2 -1)
   && CandleHigh(PERIOD_M15,1) > GetLoDonn(cymbol,PERIOD_H4,5,2)
                                   );//sellc31i
   bool buyc31ii =(  IsMidDonLMidDon(PERIOD_H4,22,5,2,8)
   && GetLoDonn(cymbol,PERIOD_H4,22,2) == GetLoDonn(cymbol,PERIOD_H4,5,2)
    && GetLoDonn(cymbol,PERIOD_H4,22,6) == GetLoDonn(cymbol,PERIOD_H4,5,6)
    && GetLoDonn(cymbol,PERIOD_H4,22,2) == GetLoDonn(cymbol,PERIOD_H4,5,6)
  && CandleClose(PERIOD_H4,2) > GetMidDonn(cymbol,PERIOD_H4,5,2)
   && GetHiDonn(cymbol,PERIOD_H4,5,2) < GetHiDonn(cymbol,PERIOD_H4,5,4)
  && CandleClose(PERIOD_H4,6) < GetMidDonn(cymbol,PERIOD_H4,5,6)
  && CandleHigh(PERIOD_H4,3) > GetMidDonn(cymbol,PERIOD_H4,5,3)
  && LowestLowPrice(PERIOD_M15,6,1) < GetHiDonn(cymbol,PERIOD_H4,5,2)//MidTma(PERIOD_M15,34,3)
                                             );/// bool buyc31 =

// ENTRY PRICE
  double firstbuyentryc31 = 0;
  if(buyc31) firstbuyentryc31 = GetHiDonn(cymbol,PERIOD_H4,5,1) - (TmbFac() * 0);//Mid 31 Hi
  if(buyc31a) firstbuyentryc31 = MidTma(PERIOD_M15,34,1) - (TmbFac() * 0);//5Profit 165Drawdown58
  if(buyc31i) firstbuyentryc31 = GetMidDonn(cymbol,PERIOD_M15,58,1) + (TmbFac() * 1);//5Profit 165Drawdown58
  if(buyc31ii) firstbuyentryc31 = Bid + (TmbFac() * 4);//5Profit 165Drawdown58
//First Filter before Sending Single Order
   bool buytrigc311 = (   (buyc31 || buyc31a || buyc31i || buyc31ii)
   &&  !DoesTradeCommentExistForThisPair(bc31,cymbol)  );
//Secomd Filter before Sending Single Order
   bool buytrigc312 = ( firstbuyentryc31 > 0
      && firstbuyentryc31 < Lowbuyprice(bc31) - ( TmbFac()* 4 ) 
     && DoesTradeCommentExistForThisPair(bc31,cymbol) 
     && !TypeBuyStopComment(bc31)
     &&( TimeCurrent() - LiveTime(bc31) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool buytrigc313 = ( DoesTradeCommentExistForThisPair(bc31,cymbol) 
     && !buyc31 && firstbuyentryc31 > Highbuyprice(bc31) + (dongap() * 0.8 )
     &&  IsCloseAboveMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) < GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetHiDonn(cymbol,PERIOD_H4,5,1 ) > GetHiDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) < GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(bc31) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(bc31,cymbol) 
   && DoesTradeCommentExistForThisPair(bc31g,cymbol) 
   &&    !TypeBuyComment(bc31g) )    
   { CloseExpiredPendingWithThisComment(bc31g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(bc31,cymbol) 
   && DoesTradeCommentExistForThisPair(bc31g,cymbol) 
   && TypeBuyComment(bc31) && !TypeBuyComment(bc31g)
   && Bid < Lowbuyprice(bc31) - ( TmbFac() * 4 ) 
   && Lowbuyprice(bc31g) >= Lowbuyprice(bc31) - ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(bc31g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstbuyentryc31 < Lowbuyprice(bc31) - ( dongap()* 1 )
   && TypeBuyStopComment(bc31) )     
   { CloseExpiredPendingWithThisComment(bc31,0) ;} 
//// Delete Stops when Price is going Up
   if( firstbuyentryc31 > Highbuyprice(bc31) + ( dongap()* 1 )
   && TypeBuyStopComment(bc31) )    
   { CloseExpiredPendingWithThisComment(bc31,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( buytrigc311 )  
     { buyentryc31e1 = firstbuyentryc31 ; 
      buytakeprofitc31e1 = buyentryc31e1 + ( TmbFac() * 11 );
      buystoplossc31e1 =   buyentryc31e1 - ( TmbFac() * 5 );   }
///////////////// Second Filter Take Profit And Stop Loss
    if( buytrigc312  ) if(( firstbuyentryc31 > Lowbuyprice(bc31) + dongap()|| firstbuyentryc31 < Lowbuyprice(bc31) - dongap())
      &&   firstbuyentryc31 < Highbuyprice(bc31) - dongap() )
     { buyentryc31e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc31e1 = buyentryc31e1 + ( dongap() * 10 );
      buystoplossc31e1 =   buyentryc31e1 - ( dongap() * 6 );   }
////////////////// Third Filter Take Profit And Stop Loss
     if( buytrigc313  ) 
     { buyentryc31e1 = Bid + ( dongap()* 0.1 ) ; 
      buytakeprofitc31e1 = buyentryc31e1 + ( dongap() * 10 );
      buystoplossc31e1 =   buyentryc31e1 - ( dongap() * 6 );   }
//////////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(bc31,cymbol)
      &&    !TypeBuyStopComment(bc31g)
      &&    !TypeBuyComment(bc31g)
      &&    ( TimeCurrent() - LiveTime(bc31) ) / 60 < 60 ) 
     { 
      if(    NumberOfBuyStopsWithThisComment(bc31) == 1  &&    !TypeBuyComment(bc31) )
         buyentryc31g1 = Highbuyprice(bc31) + ( TmbFac()* 1.0 ) ;

      if(    NumberOfBuysWithThisComment(bc31) == 1 &&   Bid < Highbuyprice(bc31) + ( TmbFac() * 1.5 )
      &&   Bid > Highbuyprice(bc31 ) -( TmbFac() * 0 )   )
         buyentryc31g1 = Bid + ( TmbFac()* 1.5 ) ;
          
      if(   Bid < Lowbuyprice(bc31) - ( TmbFac() * 4 ) && Bid <  LowerTma(PERIOD_M15,80,3.0,50, 1)  )
         buyentryc31g1 =  MidTma(PERIOD_M15,80,1) + ( TmbFac()* 0.5 ) ;
    
      buytakeprofitc31g1 = buyentryc31g1 + ( TmbFac() * 50 );
      buystoplossc31g1 =   buyentryc31g1 - ( TmbFac() * 5 );   

      buyentryc31g2 = buyentryc31g1 + ( TmbFac()* (2) ) ; 
      buytakeprofitc31g2 = buyentryc31g2 + (TmbFac() * 50);
      buystoplossc31g2 =   buyentryc31g2 - ( TmbFac() * 5 );   
         
      buyentryc31g3 = buyentryc31g2 + ( TmbFac()* (1) ) ; 
      buytakeprofitc31g3 = buyentryc31g3 + ( TmbFac() * 50 );
      buystoplossc31g3 =   buyentryc31g3 - ( TmbFac() * 5 );   
  /*    
      buyentryc31g4 = buyentryc31g3 + ( TmbFac()* (1) ) ; 
      buytakeprofitc31g4 = buyentryc31g4 + ( TmbFac() * 50 );
      buystoplossc31g4 =   buyentryc31g4 - ( TmbFac() * 7 );   */}
///////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  buytrigc313
      &&    !TypeBuyStopComment(bc31g)       ) 
 
     { buyentryc31g1 = buyentryc31e1 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc31g1 = buyentryc31g1 + ( TmbFac() * 10 );
      buystoplossc31g1 =   buyentryc31g1 - ( TmbFac() * 4 );   

      buyentryc31g2 = buyentryc31g1 + ( TmbFac()* 0.2 ) ; 
      buytakeprofitc31g2 = buyentryc31g2 + ( TmbFac() * 10 );
      buystoplossc31g2 =   buyentryc31g2 - ( TmbFac() * 4 );   

       buyentryc31g3 = buyentryc31g2 + ( TmbFac()* 0.6 ) ; 
      buytakeprofitc31g3 = buyentryc31g3 + ( TmbFac() * 15 );
      buystoplossc31g3 =   buyentryc31g3 - ( TmbFac() * 12 );   

      buyentryc31g4 = buyentryc31g3 + ( TmbFac()* 0.5 ) ; 
      buytakeprofitc31g4 = buyentryc31g4 + ( TmbFac() * 15 );
      buystoplossc31g4 =   buyentryc31g4 - ( TmbFac() * 12 );   }
////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(buyentryc31e1 > Bid)
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc31e1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc31e1 , Digits )  ,//stop loss buyentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc31e1  , Digits)  ,//take profit  
   bc31);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc31 > Bid) 

   if(buyentryc31g1 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc31g1 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc31g1 , Digits )  ,//stop loss buyentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc31g1  , Digits)  ,//take profit  
   bc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc31 > Bid) 

   if(buyentryc31g2 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc31g2 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc31g2 , Digits )  ,//stop loss buyentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc31g2  , Digits)  ,//take profit  
   bc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc31 > Bid) 

   if(buyentryc31g3 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc31g3 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc31g3 , Digits )  ,//stop loss buyentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc31g3  , Digits)  ,//take profit  
   bc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc31 > Bid) 

   if(buyentryc31g4 > Bid) 
      {     
   SendBuyStopResult(OP_BUYSTOP,
   NormalizeDouble( buyentryc31g4 , Digits) ,//order price MA27
   NormalizeDouble( buystoplossc31g4 , Digits )  ,//stop loss buyentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( buytakeprofitc31g4  , Digits)  ,//take profit  
   bc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(buyentryc08 > Bid) 
 ////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
   string sc31  = "Sc31 "; 
   string sc31g  = "Sc31g "; 
   /////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO CLOSE ALL UNFILLED PENDINGS WITH THIS COMMENT FOR A AMOUNT OF DETERMINEED TIME 
///######//+------------------------------------------------------------------+
   if( DoesTradeCommentExistForThisPair(sc31,cymbol)      && TypeSellStopComment(sc31)  )
   { CloseExpiredPendingWithThisComment(sc31,180); } 
   //////////////////////////////////////////////////////////////////////////////////////
   if( DoesTradeCommentExistForThisPair(sc31g,cymbol)      && TypeSellStopComment(sc31g)  )
   { CloseExpiredPendingWithThisComment(sc31g,120); } 
///////////////////////////////////////////////////////////////////////////////////////
///######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN INDIVIDUAL TRADES WITH THIS COMMENT  
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc31) + UplOfOrderWithThisComment(sc31g) >  3 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc31) > 0  )
   { BreakEvenTradeWithThisComment(sc31,PERIOD_M15,25,5); }
/////////////////////////////////////////////////////////////////////////////////////////////
   if(UplOfOrderWithThisComment(sc31g)  >  4 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc31g) > 0  )
   { BreakEvenTradeWithThisComment(sc31g,PERIOD_M15,25,5); }
////######//+------------------------------------------------------------------+
// THIS IS TO CLOSE  ALL TRADES WITH THIS COMMENT
///######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc31) + UplOfOrderWithThisComment(sc31g) < - 5 * SendLot * 100 
   && UplOfOrderWithThisComment(sc31) + UplOfOrderWithThisComment(sc31g) > - (5 + 1.5) * SendLot * 100)
   {  ModifyStopLossOfOrdersWithThisComment(sc31,5);
      ModifyStopLossOfOrdersWithThisComment(sc31g,5);}
///######//+------------------------------------------------------------------+
// THIS IS TRAILING OF ALL TRADES  WITH THIS COMMENT 
////######//+------------------------------------------------------------------+
   if(UplOfOrderWithThisComment(sc31) > ( 4 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(sc31,15);}
/////######//+
   if(UplOfOrderWithThisComment(sc31g) > ( 10 ) * SendLot * 100)
   {   ModifyStopLossOfOrdersWithThisComment(sc31g,52);}
/////######//+------------------------------------------------------------------+
// THIS IS TO BREAK EVEN TRADES IN A GRID  WITH THIS COMMENT 
///######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(sc31g) >  2 * SendLot * 100 && NumberOfSellsWithThisComment(sc31g) > 1 )
   {  StepifyStopLossOfOrdersWithThisComment(sc31g,2,5,3);}
///////######//+----------------------------------------------------------------+
// THIS IS IF TRADES IN A GRID ARE IN PROIT BUT SOME ARE NOT MODIFY STOP LOSS OF THOSE TRADES WITH NO BREAK EVEN
////######//+------------------------------------------------------------------+
   if(     UplOfOrderWithThisComment(sc31g) + UplOfOrderWithThisComment(sc31) >  6 * SendLot * 100 
   && NumberOfSellsWithThisComment(sc31) + NumberOfSellsWithThisComment(sc31g) > 1 )
   {  ModifyOrdersWithNoBreakEvenComment(sc31,20); ModifyOrdersWithNoBreakEvenComment(sc31g,25);}
/////######//+------------------------------------------------------------------+
//////////////18 Dec 2019  Setup
   double sellentryc31e1 = 0; double selltakeprofitc31e1 = 0; double sellstoplossc31e1 = 0;
   double sellentryc31g1 = 0; double selltakeprofitc31g1 = 0; double sellstoplossc31g1 = 0;
   double sellentryc31g2 = 0; double selltakeprofitc31g2 = 0; double sellstoplossc31g2 = 0;
   double sellentryc31g3 = 0; double selltakeprofitc31g3 = 0; double sellstoplossc31g3 = 0;
   double sellentryc31g4 = 0; double selltakeprofitc31g4 = 0; double sellstoplossc31g4 = 0;

///######//+------------------------------------------------------------------+
// THIS IS WHERE THE CONDITIONS FOR THE SETUP  
///######//+------------------------------------------------------------------+
   bool sellc31 =(  IsLoDonGMidDon(PERIOD_H4,5,22,3,7)
   && IsLoDonLMidDon(PERIOD_H4,5,22,7 - 3,1)
   && CandleClose(PERIOD_H4,1) > GetMidDonn(cymbol,PERIOD_H4,5,1)
   && GetHiDonn(cymbol,PERIOD_H4,5,1) < GetHiDonn(cymbol,PERIOD_H4,5,3)
                                   );

   bool sellc31a =(  IsMidDonLMidDon(PERIOD_H4,22,5,2,7)
   && GetLoDonn(cymbol,PERIOD_H4,22,1) == GetLoDonn(cymbol,PERIOD_H4,5,1)
    && GetLoDonn(cymbol,PERIOD_H4,22,5) == GetLoDonn(cymbol,PERIOD_H4,5,5)
    && GetLoDonn(cymbol,PERIOD_H4,22,1) == GetLoDonn(cymbol,PERIOD_H4,5,5)
  && CandleClose(PERIOD_H4,1) > GetMidDonn(cymbol,PERIOD_H4,5,1)
   && GetHiDonn(cymbol,PERIOD_H4,5,1) < GetHiDonn(cymbol,PERIOD_H4,5,3)
  && CandleClose(PERIOD_H4,5) < GetMidDonn(cymbol,PERIOD_H4,5,5)
  && CandleHigh(PERIOD_H4,2) > GetMidDonn(cymbol,PERIOD_H4,5,2)
  && HighestLowPrice(PERIOD_M15,3,1) > MidTma(PERIOD_M15,34,3)
                                             );/// bool sellc31a =

   bool sellc31i =(   IsHiDonLMidDon(PERIOD_H4,5,22,3,8)
   && IsHiDonGHiDon(PERIOD_H4,22,5,5,1)
   && IsHiDonGMidDon(PERIOD_H4,5,22,8 - 3,1)
   && CandleClose(PERIOD_H4,2) < GetMidDonn(cymbol,PERIOD_H4,5,2)
   && GetLoDonn(cymbol,PERIOD_H4,5,1) > GetLoDonn(cymbol,PERIOD_H4,5,3)
   && CandleHigh(PERIOD_H4,1) > GetMidDonn(cymbol,PERIOD_H4,22,1)
   && CandleLow(PERIOD_M15,2) > GetMidDonn(cymbol,PERIOD_M15,58,2 -1)
   && CandleLow(PERIOD_M15,1) < GetHiDonn(cymbol,PERIOD_H4,5,2)
                                   );//sellc31i
   bool sellc31ii =(  IsMidDonGMidDon(PERIOD_H4,22,5,2,8)
   && GetHiDonn(cymbol,PERIOD_H4,22,2) == GetHiDonn(cymbol,PERIOD_H4,5,2)
    && GetHiDonn(cymbol,PERIOD_H4,22,6) == GetHiDonn(cymbol,PERIOD_H4,5,6)
    && GetHiDonn(cymbol,PERIOD_H4,22,1) == GetHiDonn(cymbol,PERIOD_H4,5,6)
  && CandleClose(PERIOD_H4,2) < GetMidDonn(cymbol,PERIOD_H4,5,2)
   && GetLoDonn(cymbol,PERIOD_H4,5,2) > GetLoDonn(cymbol,PERIOD_H4,5,4)
  && CandleClose(PERIOD_H4,6) > GetMidDonn(cymbol,PERIOD_H4,5,6)
  && CandleLow(PERIOD_H4,3) < GetMidDonn(cymbol,PERIOD_H4,5,3)
  && HighestHighPrice(PERIOD_M15,6,1) > GetHiDonn(cymbol,PERIOD_H4,5,2)//MidTma(PERIOD_M15,34,3)
                                             );/// bool buyc31 =

// ENTRY PRICE
  double firstsellentryc31 = 0;
  if(sellc31) firstsellentryc31 = GetLoDonn(cymbol,PERIOD_H4,5,1) - (TmbFac() * 0);//Mid 31 Hi
  if(sellc31a) firstsellentryc31 = MidTma(PERIOD_M15,34,1) - (TmbFac() * 0);//5Profit 165Drawdown58
  if(sellc31i) firstsellentryc31 = GetMidDonn(cymbol,PERIOD_M15,58,1) - (TmbFac() * 1);//5Profit 165Drawdown58
  if(sellc31ii) firstsellentryc31 = Ask - (TmbFac() * 4);//5Profit 165Drawdown58
//First Filter before Sending Single Order
   bool selltrigc311 = (  (sellc31 || sellc31a || sellc31i || sellc31ii ) 
   &&  !DoesTradeCommentExistForThisPair(sc31,cymbol)  );
//Secomd Filter before Sending Single Order
   bool selltrigc312 = ( firstsellentryc31 > 0
      && firstsellentryc31 > Highsellprice(sc31) + ( dongap()* 2 ) 
     && DoesTradeCommentExistForThisPair(sc31,cymbol) 
     && !TypeSellStopComment(sc31)
     &&( TimeCurrent() - LiveTime(sc31) ) / 60 > 60 ) ;
//Third Filter before Sending Single Order
   bool selltrigc313 = ( DoesTradeCommentExistForThisPair(sc31,cymbol) 
     && !sellc31 && firstsellentryc31 < Lowsellprice(sc31) - (dongap() * 0.8 )
     &&  IsCloseBelowMidDon(PERIOD_H4,5,1,2)
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,18,1)                   
     &&  CandleClose(PERIOD_M15,1) > GetMidDonn(cymbol,PERIOD_H4,5,1)                  
     &&  GetLoDonn(cymbol,PERIOD_H4,5,1 ) < GetLoDonn(cymbol,PERIOD_H4,5,1 + 1 )
     &&  GetMidDonn(cymbol,PERIOD_H4,5,5 ) > GetMidDonn(cymbol,PERIOD_H4,22, 5 )
     &&( TimeCurrent() - LiveTime(sc31) ) / 60 > 510 
     ) ;
///////Delete Grid Stops when Trigger trade is closed
   if( !DoesTradeCommentExistForThisPair(sc31,cymbol) 
   && DoesTradeCommentExistForThisPair(sc31g,cymbol) 
   &&    !TypeSellComment(sc31g) )    
   { CloseExpiredPendingWithThisComment(sc31g,0) ;} 
/////Delete Grid Stops when Price is Going Below Trigger Trade
   if( DoesTradeCommentExistForThisPair(sc31,cymbol) 
   && DoesTradeCommentExistForThisPair(sc31g,cymbol) 
   && TypeSellComment(sc31) && !TypeSellComment(sc31g)
   && Ask > Highsellprice(sc31) + ( TmbFac() * 4 ) 
   && Highsellprice(sc31g) <= Highsellprice(sc31) + ( TmbFac()* ( 4 - 1)) 
   )    
   { CloseExpiredPendingWithThisComment(sc31g,0) ;} 
////Delete Stops when Price is Going Down
   if( firstsellentryc31 > Highsellprice(sc31) + ( dongap()* 1 )
   && TypeSellStopComment(sc31) )     
   { CloseExpiredPendingWithThisComment(sc31,0) ;} 
//// Delete Stops when Price is going Up
   if( firstsellentryc31 < Lowsellprice(sc31) - ( dongap()* 1 )
   && TypeSellStopComment(sc31) )    
   { CloseExpiredPendingWithThisComment(sc31,0) ;} 
/// First Filter Take Profit And Stop Loss
   if( selltrigc311 )  
     { sellentryc31e1 = firstsellentryc31 ; 
      selltakeprofitc31e1 = sellentryc31e1 - ( TmbFac() * 11 );
      sellstoplossc31e1 =   sellentryc31e1 + ( TmbFac() * 5 );   }
/////////////// Second Filter Take Profit And Stop Loss
    if( selltrigc312  ) if(( firstsellentryc31 > Lowsellprice(sc31) + dongap()|| firstsellentryc31 < Lowsellprice(sc31) - dongap())
      &&   firstsellentryc31 < Highsellprice(sc31) - dongap() )
     { sellentryc31e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc31e1 = sellentryc31e1 - ( dongap() * 10 );
      sellstoplossc31e1 =   sellentryc31e1 + ( dongap() * 6 );   }
//////////////// Third Filter Take Profit And Stop Loss
     if( selltrigc313  ) 
     { sellentryc31e1 = Ask - ( dongap()* 0.1 ) ; 
      selltakeprofitc31e1 = sellentryc31e1 - ( dongap() * 10 );
      sellstoplossc31e1 =   sellentryc31e1 + ( dongap() * 6 );   }
//////////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
//Grid Within 4Hours Of First Signal...............................................................Grid On First Signal
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(   DoesTradeCommentExistForThisPair(sc31,cymbol)
      &&    !TypeSellStopComment(sc31g)
      &&    !TypeSellComment(sc31g)
      &&    ( TimeCurrent() - LiveTime(sc31) ) / 60 < 60 ) 
     { 
      if(    NumberOfSellStopsWithThisComment(sc31) == 1  &&    !TypeSellComment(sc31) )
         sellentryc31g1 = Lowsellprice(sc31) - ( TmbFac()* 1.0 ) ;

      if(    NumberOfSellsWithThisComment(sc31) == 1 &&   Ask > Lowsellprice(sc31) - ( TmbFac() * 2.5 )
      &&   Ask < Lowsellprice(sc31)   )
         sellentryc31g1 = Ask - ( TmbFac()* 1.5 ) ;
          
      if(   Ask > Highsellprice(sc31) + ( TmbFac() * 4 ) && Ask >  UpperTma(PERIOD_M15,80,3.0,50, 1)    )
         sellentryc31g1 = MidTma(PERIOD_M15,80,1)  - ( TmbFac()* 0.5 ) ;
    
      selltakeprofitc31g1 = sellentryc31g1 - ( TmbFac() * 50 );
      sellstoplossc31g1 =   sellentryc31g1 + ( TmbFac() * 5 );   

      sellentryc31g2 = sellentryc31g1 - ( TmbFac()* (2) ) ; 
      selltakeprofitc31g2 = sellentryc31g2 - ( TmbFac() * 50 );
      sellstoplossc31g2 =   sellentryc31g2 + ( TmbFac() * 5 );   
         
      sellentryc31g3 = sellentryc31g2 - ( TmbFac()* (1) ) ; 
      selltakeprofitc31g3 = sellentryc31g3 - ( TmbFac() * 50 );
      sellstoplossc31g3 =   sellentryc31g3 + ( TmbFac() * 5 );   
 /*     
      sellentryc31g4 = sellentryc31g3 - ( TmbFac()* (2.5) ) ; 
      selltakeprofitc31g4 = sellentryc31g4 - ( TmbFac() * 50 );
      sellstoplossc31g4 =   sellentryc31g4 + ( TmbFac() * 7 );   */}
////////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Grid After First Signal...............................................................Grid After First Signal
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
      if(  selltrigc313
      &&    !TypeSellStopComment(sc31g)       ) 
 
     { sellentryc31g1 = sellentryc31e1 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc31g1 = sellentryc31g1 - ( TmbFac() * 10 );
      sellstoplossc31g1 =   sellentryc31g1 + ( TmbFac() * 4 );   

      sellentryc31g2 = sellentryc31g1 - ( TmbFac()* 0.2 ) ; 
      selltakeprofitc31g2 = sellentryc31g2 - ( TmbFac() * 10 );
      sellstoplossc31g2 =   sellentryc31g2 + ( TmbFac() * 4 );   

       sellentryc31g3 = sellentryc31g2 - ( TmbFac()* 0.6 ) ; 
      selltakeprofitc31g3 = sellentryc31g3 - ( TmbFac() * 15 );
      sellstoplossc31g3 =   sellentryc31g3 + ( TmbFac() * 12 );   

      sellentryc31g4 = sellentryc31g3 - ( TmbFac()* 0.5 ) ; 
      selltakeprofitc31g4 = sellentryc31g4 - ( TmbFac() * 15 );
      sellstoplossc31g4 =   sellentryc31g4 + ( TmbFac() * 12 );   }
///////////////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
// Send The Order...............................................................Send the Order
///++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++||
   if(sellentryc31e1 < Ask && sellentryc31e1 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc31e1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc31e1 , Digits )  ,//stop loss sellentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc31e1  , Digits)  ,//take profit  
   sc31);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc31 > Bid) 

   if(sellentryc31g1 < Ask && sellentryc31g1 > 0) 
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc31g1 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc31g1 , Digits )  ,//stop loss sellentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc31g1  , Digits)  ,//take profit  
   sc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc31 > Bid) 

   if(sellentryc31g2 < Ask && sellentryc31g2 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc31g2 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc31g2 , Digits )  ,//stop loss sellentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc31g2  , Digits)  ,//take profit  
   sc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc31 > Bid) 

   if(sellentryc31g3 < Ask && sellentryc31g3 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc31g3 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc31g3 , Digits )  ,//stop loss sellentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc31g3  , Digits)  ,//take profit  
   sc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc31 > Bid) 

   if(sellentryc31g4 < Ask && sellentryc31g4 > 0)
      {     
   SendSellStopResult(OP_SELLSTOP,
   NormalizeDouble( sellentryc31g4 , Digits) ,//order price MA27
   NormalizeDouble( sellstoplossc31g4 , Digits )  ,//stop loss sellentryc31  - ( TmbFac() * 14 )
   NormalizeDouble( selltakeprofitc31g4  , Digits)  ,//take profit  
   sc31g);//trade comment i)1 ii) 8 iii) 8 iv) 11 
         }//if(sellentryc08 > Bid) 
/////######//+------------------------------------------------------------------+
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
          if (CashUpl < -MaxAllowableCashLoss * SendLot * 100)//MaxAllowableCashLoss is a negative number
    { ModifyStopLossOfAllOrders(0,10);}
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
          if (BuyCashUpl < -LossToCloseBuyOrSellTrades * SendLot * 100)//MaxAllowableCashLoss is a negative number
    { ModifyStopLossOfAllOrders(1,10);    }
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
          if (SellCashUpl < -LossToCloseBuyOrSellTrades * SendLot * 100)//MaxAllowableCashLoss is a negative number
    { ModifyStopLossOfAllOrders(2,10);    }
/////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
}//void LookForTradingOpportunities()
//+------------------------------------------------------------------+
//============================ 
////###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
   void LookForBuyOrSellClosure(int true1false0, int BuyOrSellProfitToTriggerLock, int BuyOrSellProfitToLock, int BuyOrSellGapToTrail, int BuyOrSellStepToTrail)
///---
   {
//######
            if(BuyCashUpl >= BuyOrSellProfitToTriggerLock)if(BuyCloseProfitPrice() == 0 )
            if(ObjectFind(BuyCloseProfit) == -1)if(true1false0 == 1)       
          { 
            entryLevel1 = BuyOrSellProfitToLock;entryLevel2 = BuyOrSellProfitToLock;
            Time1       = iTime(Symbol(),PERIOD_D1,0);
            Time2       = TimeCurrent();
            DrawTrendLine(BuyCloseProfit,Time1,entryLevel1,Time2,entryLevel2,clrYellowGreen,2,STYLE_DASH,true);
          }
///######
            if(SellCashUpl >= BuyOrSellProfitToTriggerLock)if(SellCloseProfitPrice() == 0 )
            if(ObjectFind(SellCloseProfit) == -1)if(true1false0 == 1)       
          { 
            entryLevel1 = BuyOrSellProfitToLock ;entryLevel2 = BuyOrSellProfitToLock ;
            Time1       = iTime(Symbol(),PERIOD_D1,0);
            Time2       = TimeCurrent();
            DrawTrendLine(SellCloseProfit,Time1,entryLevel1,Time2,entryLevel2,clrYellow,2,STYLE_DASH,true);
          }
///######
            if(BuyCashUpl > BuyCloseProfitPrice() + BuyOrSellGapToTrail + BuyOrSellStepToTrail)
            if(ObjectFind(BuyCloseProfit) > -1)if(BuyCloseProfitPrice() > 0)       
          { 
            entryLevel1 = BuyCashUpl - BuyOrSellGapToTrail;
            entryLevel2 = BuyCashUpl - BuyOrSellGapToTrail;
            Time1       = iTime(Symbol(),PERIOD_D1,0);
            Time2       = TimeCurrent();
            DrawTrendLine(BuyCloseProfit,Time1,entryLevel1,Time2,entryLevel2,clrDodgerBlue,2,STYLE_DASH,true);
          }
///######
            if(SellCashUpl > SellCloseProfitPrice() + BuyOrSellGapToTrail + BuyOrSellStepToTrail)
            if(ObjectFind(SellCloseProfit) > -1)if(SellCloseProfitPrice() > 0)       
          { 
            entryLevel1 = SellCashUpl - BuyOrSellGapToTrail;
            entryLevel2 = SellCashUpl - BuyOrSellGapToTrail;
            Time1       = iTime(Symbol(),PERIOD_D1,0);
            Time2       = TimeCurrent();
            DrawTrendLine(SellCloseProfit,Time1,entryLevel1,Time2,entryLevel2,clrDodgerBlue,2,STYLE_DASH,true);}

          }//void LookForBuyOrSellClosure()
//////###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
/////###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//+------------------------------------------------------------------+
   void LookForEquityClosure(int true1false0, int EquityProfitToTriggerLock, int EquityProfitToLock, int EquityGapToTrail, int EquityStepToTrail)
///---
   {
//######
            if(CashUpl >= EquityProfitToTriggerLock)if(EquityCloseProfitPrice() == 0 )
            if(ObjectFind(EquityCloseProfit) == -1)if(true1false0 == 1)       
          { 
            entryLevel1 = EquityProfitToLock;entryLevel2 = EquityProfitToLock;
            Time1       = iTime(Symbol(),PERIOD_D1,0);
            Time2       = TimeCurrent();
            DrawTrendLine(EquityCloseProfit,Time1,entryLevel1,Time2,entryLevel2,clrYellowGreen,2,STYLE_DASH,true);
          }
///######
            if(CashUpl > EquityCloseProfitPrice() + EquityGapToTrail + EquityStepToTrail)
            if(ObjectFind(EquityCloseProfit) > -1)if(EquityCloseProfitPrice() > 0)       
          { 
            entryLevel1 = CashUpl - EquityGapToTrail;
            entryLevel2 = CashUpl - EquityGapToTrail;
            Time1       = iTime(Symbol(),PERIOD_D1,0);
            Time2       = TimeCurrent();
            DrawTrendLine(EquityCloseProfit,Time1,entryLevel1,Time2,entryLevel2,clrDodgerBlue,2,STYLE_DASH,true);
          }
}//void LookForEquityClosure()
/////###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
/////###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ExpirePendingOrders()
  {

   bool orderResult=false;
   bool orderResultPending=false;
   int  totalOrders   = OrdersTotal();
   int  orders        = 0;
   int lastError=0;
   datetime posOpen[][2];
   if(OrdersTotal() == 0) return;
  // if(showAlerts)Alert("APTM: Starting to close the entire Basket..");
   for(int i=0; i<totalOrders; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         lastError=GetLastError();
         Print("Error in OrderSelect!!");
         continue;
        }//if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
 

      orders++;
      ArrayResize(posOpen,orders);
      posOpen[orders - 1][0] = OrderOpenTime();
      posOpen[orders - 1][1] = OrderTicket();
     }

   for(int ix=0; ix<orders; ix++)
     {
      if(!OrderSelect((int) posOpen[ix][1],SELECT_BY_TICKET))
        {
         lastError=GetLastError();
         Print("Error in OrderSelect!!");
         continue;
        }

       if(OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT || OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP)
       if( ( TimeCurrent() - OrderOpenTime() ) / 60  >= DeletePendingAfterThisManyMinutes )
        {

         orderResultPending=OrderDelete(OrderTicket());
        }
     }

  }
////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####

////////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
///////++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####
////###+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#####

//######//+------------------------------------------------------------------+
//######//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Create the horizontal line                                       |
//+------------------------------------------------------------------+
bool HLineCreate( long            chart_ID,        // chart's ID
                  string          name,      // line name
                  int             sub_window,      // subwindow index
                  double          HLprice,           // line price
                  color           clr,        // line color
                  ENUM_LINE_STYLE style, // line style
                  int             width,           // line width
                  bool            back,        // in the background
                  bool            selection,    // highlight to move
                  bool            hidden,       // hidden in the object list
                  long            z_order)         // priority for mouse click
  {
//--- create a horizontal line
   if(!ObjectCreate(chart_ID,name,OBJ_HLINE,sub_window,0,HLprice))
     {
      Print(__FUNCTION__,
            ": failed to create a horizontal line! Error code = ",GetLastError());
      return(false);
     }
//--- set line color
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
   return(true);
  }
//+------------------------------------------------------------------+
//| The function deletes the trend line from the chart.              |
//+------------------------------------------------------------------+
bool TrendDelete( string name)
   {
//--- reset the error value
   ResetLastError();
//--- delete a trend line
   if(!ObjectDelete(name))
      {
      Print(__FUNCTION__,
            ": failed to delete a trend line! Error code = ",GetLastError());
       return(false);
      }
//--- successful execution
   return(true);
   }
//+------------------------------------------------------------------+
   int CountAllBuyTypesWithThisComment(string comment)
   {
   return(  NumberOfBuysWithThisComment(comment) + NumberOfBuyStopsWithThisComment(comment) );
   }
   double Highbuyprice(string comment)
   { static double highbuyprice=0;
   if( NumberOfBuyStopsWithThisComment(comment) == 0 && NumberOfBuysWithThisComment(comment) == 0 )
   highbuyprice= 0;

   if( NumberOfBuyStopsWithThisComment(comment) > 0 && NumberOfBuysWithThisComment(comment) == 0 )
   highbuyprice= HighestPriceOfPendingWithThisComment(comment) ;

   if(highbuyprice > 0 && HighestPriceOfOrderWithThisComment(comment) > 0 
   && HighestPriceOfOrderWithThisComment(comment) > highbuyprice ) 
   highbuyprice = HighestPriceOfOrderWithThisComment(comment);

   if(highbuyprice > 0 && HighestPriceOfPendingWithThisComment(comment) > 0 
   && HighestPriceOfPendingWithThisComment(comment) > highbuyprice ) 
   highbuyprice = HighestPriceOfPendingWithThisComment(comment);
   
   return(highbuyprice);
   }
   double Lowbuyprice(string comment)
   { static double lowbuyprice=0;
   if( NumberOfBuyStopsWithThisComment(comment) == 0 && NumberOfBuysWithThisComment(comment) == 0 )
   lowbuyprice= 0;

   if( NumberOfBuyStopsWithThisComment(comment) > 0 && NumberOfBuysWithThisComment(comment) == 0 )
   lowbuyprice= LowestPriceOfPendingWithThisComment(comment) ;

   if(lowbuyprice > 0 && LowestPriceOfOrderWithThisComment(comment) > 0 
   && LowestPriceOfOrderWithThisComment(comment) < lowbuyprice ) 
   lowbuyprice = LowestPriceOfOrderWithThisComment(comment);

   if(lowbuyprice > 0 && LowestPriceOfPendingWithThisComment(comment) > 0 
   && LowestPriceOfPendingWithThisComment(comment) < lowbuyprice ) 
   lowbuyprice = LowestPriceOfPendingWithThisComment(comment);
   
   return(lowbuyprice);
   }

   double Highsellprice(string comment)
   { static double highsellprice=0;
   if( NumberOfSellStopsWithThisComment(comment) == 0 && NumberOfSellsWithThisComment(comment) == 0 )
   highsellprice= 0;

   if( NumberOfSellStopsWithThisComment(comment) > 0 && NumberOfSellsWithThisComment(comment) == 0 )
   highsellprice= HighestPriceOfPendingWithThisComment(comment) ;

   if(highsellprice > 0 && HighestPriceOfOrderWithThisComment(comment) > 0 
   && HighestPriceOfOrderWithThisComment(comment) > highsellprice ) 
   highsellprice = HighestPriceOfOrderWithThisComment(comment);

   if(highsellprice > 0 && HighestPriceOfPendingWithThisComment(comment) > 0 
   && HighestPriceOfPendingWithThisComment(comment) > highsellprice ) 
   highsellprice = HighestPriceOfPendingWithThisComment(comment);   
   return(highsellprice);
   }

   double Lowsellprice(string comment)
   { static double lowsellprice=0;
   if( NumberOfSellStopsWithThisComment(comment) == 0 && NumberOfSellsWithThisComment(comment) == 0 )
   lowsellprice= 0;

   if( NumberOfSellStopsWithThisComment(comment) > 0 && NumberOfSellsWithThisComment(comment) == 0 )
   lowsellprice= LowestPriceOfPendingWithThisComment(comment) ;

   if(lowsellprice > 0 && LowestPriceOfOrderWithThisComment(comment) > 0 
   && LowestPriceOfOrderWithThisComment(comment) < lowsellprice ) 
   lowsellprice = LowestPriceOfOrderWithThisComment(comment);

   if(lowsellprice > 0 && LowestPriceOfPendingWithThisComment(comment) > 0 
   && LowestPriceOfPendingWithThisComment(comment) < lowsellprice ) 
   lowsellprice = LowestPriceOfPendingWithThisComment(comment);
   
   return(lowsellprice);
   }
//+------------------------------------------------------------------+
void CloseTradeWithThisComment(string comment)
{  int  totalOrders   = OrdersTotal();  
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for(int i=0; i<totalOrders; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))  continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         if (OrderType() < 2)
         {
            result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 1000, CLR_NONE);            
         }//if (OrderType() < 2)

        
   }//for(int i=0; i<totalOrders; i++)
}//CloseTradeWithThisComment(string comment)
//+------------------------------------------------------------------+
void CloseExpiredPendingWithThisComment(string comment , int minutesexpired)
{  int  totalOrders   = OrdersTotal();  
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for(int i=0; i<totalOrders; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))  continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);

            if (OrderType() > 1 && ( TimeCurrent() - OrderOpenTime() ) / 60 > minutesexpired) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
            }//if (OrderType() > 1)          
        
   }//for(int i=0; i<totalOrders; i++)
}//CloseTradeWithThisComment(string comment)
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
void ClosePendingsWhenLatestExpiresWithThisComment(string comment , int minutesexpired)
{   
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {
         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         
         if (pass == 1)
            if (OrderType() > 1) 
      if( ( TimeCurrent() - LatestTimeForPendingWithThisComment(comment) ) / 60 > minutesexpired )
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
            }//if (OrderType() > 1) 
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
}//End void CloseAllTradesFifo()
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
void ClosePendingsWhenEarliestExpiresWithThisComment(int type , string comment , int minutesexpired)
{

   ForceTradeClosure= false;
   
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {
         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if (OrderType() != type) 
            if (type != AllTrades)
               continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         
         if (pass == 1)
            if (OrderType() > 1) 
               if( (TimeCurrent() - EarliestTimeForPendingWithThisComment(comment)) / 60 > minutesexpired )
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
   //If full closure succeeded, then allow new trading
   if (!ForceTradeClosure) 
   {
      OpenTrades = 0;
      BuyOpen = false;
      SellOpen = false;
   }//if (!ForceTradeClosure) 


}//void ClosePendingsWhenEarliestExpiresWithThisComment(int type , string comment , int minutesexpired)
///+------------------------------------------------------------------+
///+------------------------------------------------------------------+
void BreakEvenTradeWithThisComment(string comment ,int tf, int pipstostartbreakeven, int breakevenpips )
{  int  totalOrders   = OrdersTotal();  
   if (OrdersTotal() == 0) return;
   
   int ticketb=-1;
   int tickets=-1;
   bool result = false;
   for(int i=0; i<totalOrders; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))  continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         if (OrderType() == OP_BUY  
         && iClose(Symbol(),tf,1) > OrderOpenPrice() + ( pipstostartbreakeven / factor )
         &&  OrderOpenPrice() > OrderStopLoss()
         )
         {
         double stopb = OrderOpenPrice() + ( breakevenpips / factor ) ; 
            ticketb = OrderTicket();
            result = ModifyOrderi( ticketb, stopb );            
         }//if (OrderType() < 2)


         if (OrderType() == OP_SELL  
         && iClose(Symbol(),tf,1) < OrderOpenPrice() - ( pipstostartbreakeven / factor ) 
         && ( OrderStopLoss() == 0  || OrderStopLoss() > OrderOpenPrice() )
         )
         {
         double stops = OrderOpenPrice() - ( breakevenpips / factor ) ; 
            tickets = OrderTicket();
            result = ModifyOrderi( tickets, stops );            
         }//if (OrderType() < 2)
        
   }//for(int i=0; i<totalOrders; i++)
}//CloseTradeWithThisComment(string comment)
//..............................................................................+
//..............................................................................+
void BreakEvenTrailOrdersThisComment(string comment , int beprofit , int slmindistancetopricebe , int slmindistancetopricejs , int jumpstep)
{   
   int Xdigits=Digits;
   double ask = Ask;
   double bid = Bid;
   double NewSLsi=0;
   double NewSLsii=0;
   double NewSLbi=0;
   double NewSLbii=0;
   int    ticket = OrderTicket();
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
//   if (OrdersTotal() == 0) return;
   
   //Iterating backwards through the orders list caters more easily for closed trades than iterating forwards
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      bool TradeWasClosed = false;//See 'check for possible trade closure'

      //Ensure the trade is still open
      if (!BetterOrderSelect(cc, SELECT_BY_TICKET, MODE_TRADES) ) continue;
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        // if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);

    if(OrderType()==OP_SELL && (OrderComment() == comment))
     {

      if(ask < OrderOpenPrice() - ( beprofit / factor) - ( slmindistancetopricebe / factor)
      && OrderStopLoss() > OrderOpenPrice()
      && 0 < OrderStopLoss()  )
        {
         NewSLsi=NormalizeDouble(OrderOpenPrice()-( beprofit /factor),Xdigits);

         if(NewSLsi!=OrderStopLoss() && NewSLsi!=0)
        {
            bool resultsi=OrderModify(ticket,OrderOpenPrice(),NewSLsi,OrderTakeProfit(),OrderExpiration(),clrRed);
            if (resultsi) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!resultsi) ForceTradeClosure= true;
        }}

      if(ask < OrderOpenPrice() - ( beprofit / factor) - ( slmindistancetopricebe / factor)
      && 0 == OrderStopLoss()  )
        {
         NewSLsi=NormalizeDouble(OrderOpenPrice()-( beprofit/factor),Xdigits);

         if(NewSLsi!=OrderStopLoss() && NewSLsi!=0)
        {
            bool resultsix=OrderModify(ticket,OrderOpenPrice(),NewSLsi,OrderTakeProfit(),OrderExpiration(),clrRed);
            if (resultsix) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!resultsix) ForceTradeClosure= true;
        }}


      if(ask < OrderStopLoss() - (slmindistancetopricejs/factor) - (jumpstep/factor)
      && OrderStopLoss() <= OrderOpenPrice() - (beprofit / factor)
       && 0 < OrderStopLoss())
        {
         NewSLsii=NormalizeDouble(OrderStopLoss()-(jumpstep/factor),Xdigits);
         if(NewSLsii!=OrderStopLoss() && NewSLsii!=0)
           {
            bool resultsii=OrderModify(ticket,OrderOpenPrice(),NewSLsii,OrderTakeProfit(),OrderExpiration(),clrRed);
             if (resultsii) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!resultsii) ForceTradeClosure= true;
          }        }//`

     }//OP_SELL


   if(OrderType()==OP_BUY  && (OrderComment() == comment))
     {

      if(bid > OrderOpenPrice() + (beprofit / factor) + (slmindistancetopricebe / factor)
      && OrderStopLoss() < OrderOpenPrice()
      && ( 0 < OrderStopLoss() || 0 == OrderStopLoss() )  )
        {
         NewSLbi=NormalizeDouble(OrderOpenPrice()+( beprofit/factor),Xdigits);

         if(NewSLbi!=OrderStopLoss() && NewSLbi!=0)
           {
            bool resulti=OrderModify(ticket,OrderOpenPrice(),NewSLbi,OrderTakeProfit(),OrderExpiration(),clrRed);
            if (resulti) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!resulti) ForceTradeClosure= true;
           }   }

      if(bid > OrderStopLoss() + ( slmindistancetopricejs /factor) + ( jumpstep/factor)
      && OrderStopLoss() >= OrderOpenPrice() + (beprofit / factor)
       && 0 < OrderStopLoss())
        {
         NewSLbii=NormalizeDouble(OrderStopLoss()+( jumpstep/factor),Xdigits);
         if(NewSLbii!=OrderStopLoss() && NewSLbii!=0)
           { 
            bool resultii=OrderModify(ticket,OrderOpenPrice(),NewSLbii,OrderTakeProfit(),OrderExpiration(),clrRed);
            if (resultii) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!resultii) ForceTradeClosure= true;
              }   }//
              
     }//OP_BUY
     }} }//void BreakEvenTrailOrdersThisComment
//+------------------------------------------------------------------+
void ModifyStopLossOfOrdersWithThisComment(string comment , int pipgap)
{   
   if (OrdersTotal() == 0) return;
   
  double stopb = Bid - ( pipgap / factor ) ; 
 double stops = Ask + ( pipgap / factor ) ; 
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {
         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         
         if (OrderType() == OP_BUY  )
         if (stopb > OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stopb);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)
            
         
         if (OrderType() == OP_SELL  )
         if (stops < OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stops);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)

         if (pass == 1)
            if (OrderType() > 1) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
}//End void CloseAllTradesFifo()
//+------------------------------------------------------------------+
void ModifyOrdersWithNoBreakEvenComment(string comment , int pipgap)
{   
   if (OrdersTotal() == 0) return;
   
  double stopb = Bid - ( pipgap / factor ) ; 
 double stops = Ask + ( pipgap / factor ) ; 
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {
         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         
         if (OrderType() == OP_BUY  )
         if (OrderOpenPrice() > OrderStopLoss() )
         if (stopb > OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stopb);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)
            
         
         if (OrderType() == OP_SELL  )
         if (OrderOpenPrice() < OrderStopLoss() )
         if (stops < OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stops);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)

         if (pass == 1)
            if (OrderType() > 1) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
}//End void CloseAllTradesFifo()
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
void StepifyStopLossOfOrdersWithThisComment( string comment,int buy1orsell2all0 ,int pipgap ,int marketgap)
{   bool buy = false; bool sell = false;
   if( buy1orsell2all0 == 1) buy = true;
   if( buy1orsell2all0 == 2) sell = true;
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {

         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if (OrderComment() != comment ) continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         double stopb = OrderOpenPrice() + ( pipgap / factor ) ; 
         
         if (OrderType() == OP_BUY && ( (!buy &&!sell) || buy ) )
         if ( Bid > OrderOpenPrice()  )
         if ( Bid > stopb + ( marketgap / factor ) )
         if ( OrderOpenPrice() > OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stopb);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)
            
         
         double stops = OrderOpenPrice() - ( pipgap / factor ) ; 
         if (OrderType() == OP_SELL  && ( (!buy &&!sell) || sell ))
         if ( Ask < OrderOpenPrice()  )
         if ( Ask < stops - ( marketgap / factor ) )
         if (OrderOpenPrice() < OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stops);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)

         if (pass == 1)
            if (OrderType() == OP_BUYLIMIT || OrderType() == OP_BUYSTOP )
            if ( ( (!buy &&!sell) || buy ) ) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
         if (pass == 1)
            if (OrderType() == OP_SELLLIMIT || OrderType() == OP_SELLSTOP ) 
            if ( ( (!buy &&!sell) || sell ) ) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
}//void ModifyStopLossOfOrdersWithThisComment(string comment , int pipgap)
//+------------------------------------------------------------------+
void StepifyStopLossOfAllOrders( int buy1orsell2all0 ,int pipgap)
{   bool buy = false; bool sell = false;
   if( buy1orsell2all0 == 1) buy = true;
   if( buy1orsell2all0 == 2) sell = true;
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {

         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         double stopb = OrderOpenPrice() + ( pipgap / factor ) ; 
         
         if (OrderType() == OP_BUY && ( (!buy &&!sell) || buy ) )
         if ( Bid > OrderOpenPrice()  )
         if ( OrderOpenPrice() > OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stopb);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)
            
         
         double stops = OrderOpenPrice() - ( pipgap / factor ) ; 
         if (OrderType() == OP_SELL  && ( (!buy &&!sell) || sell ))
         if ( Ask < OrderOpenPrice()  )
         if (OrderOpenPrice() < OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stops);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)

         if (pass == 1)
            if (OrderType() == OP_BUYLIMIT || OrderType() == OP_BUYSTOP )
            if ( ( (!buy &&!sell) || buy ) ) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
         if (pass == 1)
            if (OrderType() == OP_SELLLIMIT || OrderType() == OP_SELLSTOP ) 
            if ( ( (!buy &&!sell) || sell ) ) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
}//void ModifyStopLossOfOrdersWithThisComment(string comment , int pipgap)
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
void ModifyStopLossOfAllOrders( int buy1orsell2all0 ,int pipgap)
{   bool buy = false; bool sell = false;
         double stops = Ask + ( pipgap / factor ) ; 
         double stopb = Bid - ( pipgap / factor ) ; 
   if( buy1orsell2all0 == 1) buy = true;
   if( buy1orsell2all0 == 2) sell = true;
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {
         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         
         if (OrderType() == OP_BUY && ( (!buy &&!sell) || buy ) )
         if (stopb > OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stopb);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)
            
         
         if (OrderType() == OP_SELL  && ( (!buy &&!sell) || sell ))
         if (stops <OrderStopLoss() )
         {
            result = ModifyOrderi(OrderTicket(),stops);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)

         if (pass == 1)
            if (OrderType() == OP_BUYLIMIT || OrderType() == OP_BUYSTOP )
            if ( ( (!buy &&!sell) || buy ) ) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
         if (pass == 1)
            if (OrderType() == OP_SELLLIMIT || OrderType() == OP_SELLSTOP ) 
            if ( ( (!buy &&!sell) || sell ) ) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
}//void ModifyStopLossOfOrdersWithThisComment(string comment , int pipgap)
//+------------------------------------------------------------------+
bool TradeWithThisCommentHasBreakEvenStopLoss(string comment )
{   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
        
         while(IsTradeContextBusy()) Sleep(100);
         if (OrderType() == OP_BUY && OrderStopLoss() > 0 && OrderStopLoss() > OrderOpenPrice()  && OrderComment() == comment)
         return(true);
         if (OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT )       return(false);       

         if (OrderType() == OP_SELL && OrderStopLoss() > 0 && OrderStopLoss() < OrderOpenPrice()  && OrderComment() == comment)
          return(true);
         if (OrderType() == OP_SELLSTOP || OrderType() == OP_SELLLIMIT )       return(false);       
          
   }//for(int i=0; i<totalOrders; i++)
      return(false);       
}//bool TradeWithThisCommentHasBreakEvenStopLoss(string comment )
//+------------------------------------------------------------------+
int TicketNumberWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if(  (OrderType() == OP_BUY || OrderType() == OP_SELL )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(lastticket);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
int LatestTimeForOrderWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderType() > 1  )
         if( OrderOpenTime() > lastopentime          )
         { lastopentime = 0;
            lastticket = OrderTicket();
          }                     
          
         if( OrderType() < 2 && OrderComment() == comment ) 
         if( OrderOpenTime() > lastopentime          )
         { lastopentime = 0;
            lastticket = OrderTicket();
          } 
         if( OrderType() < 2 && OrderOpenTime() > lastopentime && OrderComment() == comment )
         if( OrderOpenTime() > lastopentime          )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(lastopentime);

}//int LatestTimeForOrderWithThisComment(string comment )
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
int EarliestTimeForOrderWithThisComment(string comment )
{  
   datetime lastopentime = TimeCurrent();  
   int lastticket=-1;
   if (OrdersTotal() == 0) return(lastticket);
   
   //Iterating backwards through the orders list caters more easily for closed trades than iterating forwards
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {

      //Ensure the trade is still open
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderCloseTime() > 0) continue; 
      if (OrderComment() != comment) continue; 
        
         while(IsTradeContextBusy()) Sleep(100);
      //Build up the position details of stop/limit orders
      if (OrderType() < 2)
      {
         //Buystops
         if (OrderType() == OP_BUY)
         {
            BuyOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastopentime = OrderOpenTime();
               lastticket = OrderTicket();
            }//if (OrderOpenTime() > lastopentime)
            }//if (OrderType() == OP_BUY  

         //Buystops
         if (OrderType() == OP_SELL)
         {
            SellOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastopentime = OrderOpenTime();
               lastticket = OrderTicket();
            }//if (OrderOpenTime() > lastopentime)
            }//if (OrderType() == OP_SELL  

          } //if (OrderType() > 1)
  }//for(int i=0; i<totalOrders; i++)
         return(lastopentime);
   }//int EarliestTimeForOrderWithThisComment(string comment )
//+------------------------------------------------------------------+
int LatestTimeForPendingWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderComment() != comment) continue;
        
         while(IsTradeContextBusy()) Sleep(100);

      if( OrderType() > 1 )   
         if( OrderOpenTime() > lastopentime          )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(lastopentime);
}//int LatestTimeForOrderWithThisComment(string comment )
//+------------------------------------------------------------------+
int EarliestTimeForPendingWithThisComment(string comment )
{  
   datetime lastopentime = TimeCurrent();  
   int lastticket=-1;
   if (OrdersTotal() == 0) return(lastticket);
   
   //Iterating backwards through the orders list caters more easily for closed trades than iterating forwards
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {

      //Ensure the trade is still open
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderCloseTime() > 0) continue; 
      if (OrderComment() != comment) continue; 
        
         while(IsTradeContextBusy()) Sleep(100);
      //Build up the position details of stop/limit orders
      if (OrderType() > 1)
      {
         //Buystops
         if (OrderType() == OP_BUYSTOP)
         {
            BuyStopOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastopentime = OrderOpenTime();
               lastticket = OrderTicket();
            }//if (OrderOpenTime() < lastopentime)
            }//if (OrderType() == OP_BUYSTOP)  

         //Buystops
         if (OrderType() == OP_SELLSTOP)
         {
            SellStopOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastopentime = OrderOpenTime();
               lastticket = OrderTicket();
            }//if (OrderOpenTime() < lastopentime)
            }//if (OrderType() == OP_SELLSTOP)  

          } //if (OrderType() > 1)
  }//for(int i=0; i<totalOrders; i++)
         return(lastopentime);
}//EarliestTimeForPendingWithThisComment(string comment )
//+------------------------------------------------------------------+
int LatestTicketNumberWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenTime() > lastopentime && (OrderType() == OP_BUY || OrderType() == OP_SELL )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(lastticket);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
double LatestPriceOfOrderWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   double orderprice = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenTime() > lastopentime //&& (OrderType() == OP_BUY || OrderType() == OP_SELL )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
            orderprice = OrderOpenPrice();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(orderprice);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
double HighestPriceOfOrderWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   double orderprice = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenPrice() > orderprice && (OrderType() == OP_BUY || OrderType() == OP_SELL )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
            orderprice = OrderOpenPrice();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(orderprice);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
double LowestPriceOfOrderWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   double orderprice = million;
   double orderopenprice = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenPrice() < orderprice && (OrderType() == OP_BUY || OrderType() == OP_SELL )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
            orderprice = OrderOpenPrice();
            orderopenprice = orderprice;
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(orderopenprice);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
double HighestPriceOfPendingWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   double orderprice = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenPrice() > orderprice && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
            orderprice = OrderOpenPrice();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(orderprice);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
double LowestPriceOfPendingWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   double orderprice = million;
   double orderopenprice = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenPrice() < orderprice && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
            orderprice = OrderOpenPrice();
            orderopenprice = orderprice;
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(orderopenprice);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int EarliestTicketNumberWithThisComment(string comment )
{  
   datetime lastopentime = TimeCurrent();  
   int lastticket=-1;
   if (OrdersTotal() == 0) return(lastticket);
   
   //Iterating backwards through the orders list caters more easily for closed trades than iterating forwards
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {

      //Ensure the trade is still open
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderCloseTime() > 0) continue; 
      if (OrderComment() != comment) continue; 
        
         while(IsTradeContextBusy()) Sleep(100);
      //Build up the position details of stop/limit orders
      if (OrderType() < 2)
      {
         //Buystops
         if (OrderType() == OP_BUY)
         {
            BuyOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastticket = OrderTicket();
            }//if (OrderOpenTime() > lastopentime)
            }//if (OrderType() == OP_BUY  

         //Buystops
         if (OrderType() == OP_SELL)
         {
            SellOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastticket = OrderTicket();
            }//if (OrderOpenTime() > lastopentime)
            }//if (OrderType() == OP_SELL  

          } //if (OrderType() > 1)
  }//for(int i=0; i<totalOrders; i++)
         return(lastticket);
}//int EarliestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
int EarliestPendingTicketNumberWithThisComment(string comment )
{  
   datetime lastopentime = TimeCurrent();  
   int lastticket=-1;
   if (OrdersTotal() == 0) return(lastticket);
   
   //Iterating backwards through the orders list caters more easily for closed trades than iterating forwards
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {

      //Ensure the trade is still open
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderCloseTime() > 0) continue; 
      if (OrderComment() != comment) continue; 
        
         while(IsTradeContextBusy()) Sleep(100);
      //Build up the position details of stop/limit orders
      if (OrderType() > 1)
      {
         //Buystops
         if (OrderType() == OP_BUYSTOP)
         {
            BuyStopOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastticket = OrderTicket();
            }//if (OrderOpenTime() < lastopentime)
            }//if (OrderType() == OP_BUYSTOP)  

         //Buystops
         if (OrderType() == OP_SELLSTOP)
         {
            SellStopOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastticket = OrderTicket();
            }//if (OrderOpenTime() < lastopentime)
            }//if (OrderType() == OP_SELLSTOP)  

          } //if (OrderType() > 1)
  }//for(int i=0; i<totalOrders; i++)
         return(lastticket);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
int LatestPendingTicketNumberWithThisComment(string comment )
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenTime() > lastopentime && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP )
         && OrderComment() == comment )
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(lastticket);
}//int LatestTicketNumberWithThisComment(string comment )
//+------------------------------------------------------------------+
bool LatestTradeWithThisCommentHasBreakEvenStopLoss(string comment )
{   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
    //  if ( OrderTicket() !=  LatestTicketNumberWithThisComment(comment)) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderType() == OP_BUY && OrderStopLoss() > 0 && OrderStopLoss() > OrderOpenPrice()
         &&  OrderTicket() ==  LatestTicketNumberWithThisComment(comment) )
         return(true);
   //      if (OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT )       return(false);       

         if (OrderType() == OP_SELL && OrderStopLoss() > 0 && OrderStopLoss() < OrderOpenPrice()
         && OrderTicket() ==  LatestTicketNumberWithThisComment(comment) )
          return(true);
     //    if (OrderType() == OP_SELLSTOP || OrderType() == OP_SELLLIMIT )       return(false);       
          
   }//for(int i=0; i<totalOrders; i++)
      return(false);       
}//bool LatestTradeWithThisCommentHasBreakEvenStopLoss(string comment )
//+------------------------------------------------------------------+
bool EarliestTradeWithThisCommentHasBreakEvenStopLoss(string comment )
{   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
    //  if ( OrderTicket() !=  LatestTicketNumberWithThisComment(comment)) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
        
         while(IsTradeContextBusy()) Sleep(100);
         if (OrderType() == OP_BUY && OrderStopLoss() > 0 && OrderStopLoss() > OrderOpenPrice()
         && OrderTicket() ==  EarliestTicketNumberWithThisComment(comment) )
         return(true);
 //        if (OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT )       return(false);       

         if (OrderType() == OP_SELL && OrderStopLoss() > 0 && OrderStopLoss() < OrderOpenPrice()
         && OrderTicket() ==  EarliestTicketNumberWithThisComment(comment) )
          return(true);
 //        if (OrderType() == OP_SELLSTOP || OrderType() == OP_SELLLIMIT )       return(false);       
          
   }//for(int i=0; i<totalOrders; i++)
      return(false);       
}//bool LatestTradeWithThisCommentHasBreakEvenStopLoss(string comment )
//------------------
//------------------
bool TypeLatestBuyComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_BUY && OrderTicket() ==  LatestTicketNumberWithThisComment(comment))
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeBuyComment(string comment)
//------------------
bool TypeLatestSellComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_SELL && OrderTicket() ==  LatestTicketNumberWithThisComment(comment))
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeBuyComment(string comment)
//------------------
int NrOfSecLatestPendingOrderWithThisCommentHasBeenOpened(string comment)
{  
   datetime lastopentime = 0;  
   int lastticket=-1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
        
         while(IsTradeContextBusy()) Sleep(100);
         if( OrderOpenTime() > lastopentime  && OrderComment() == comment && (OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP ))
         { lastopentime = OrderOpenTime();
            lastticket = OrderTicket();
          } 
  }//for(int i=0; i<totalOrders; i++)
         return(TimeCurrent() - lastopentime);
}//int LatestTimeForOrderWithThisComment(string comment )
//+------------------------------------------------------------------+
void CloseLatestPendingWithThisComment(string comment)
{  int  totalOrders   = OrdersTotal();  
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for(int i=0; i<totalOrders; i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))  continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if(OrderComment() != comment)continue;
         
         while(IsTradeContextBusy()) Sleep(100);

            if (OrderType() > 1 && OrderTicket() ==  LatestTicketNumberWithThisComment(comment)) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
            }//if (OrderType() > 1)          
        
   }//for(int i=0; i<totalOrders; i++)
}//CloseTradeWithThisComment(string comment)
//+------------------------------------------------------------------+
int NumberOfBuysWithThisComment(string comment )
{  
   int commentcount = 0;
 for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      if (OrderType() == OP_BUY && OrderComment() == comment)  commentcount++;
   }//for(int i=0; i<totalOrders; i++)
      return(commentcount);       
}//int NumberOfTradesWithThisComment(string comment )
//+------------------------------------------------------------------+
int NumberOfSellsWithThisComment(string comment )
{  
   int commentcount = 0;
 for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      if (OrderType() == OP_SELL && OrderComment() == comment)  commentcount++;
   }//for(int i=0; i<totalOrders; i++)
      return(commentcount);       
}//int NumberOfTradesWithThisComment(string comment )
//+------------------------------------------------------------------+
int NumberOfBuyStopsWithThisComment(string comment )
{  
   int commentcount = 0;
 for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      if (OrderType() == OP_BUYSTOP && OrderComment() == comment)  commentcount++;
   }//for(int i=0; i<totalOrders; i++)
      return(commentcount);       
}//int NumberOfTradesWithThisComment(string comment )
//+------------------------------------------------------------------+
int NumberOfSellStopsWithThisComment(string comment )
{  
   int commentcount = 0;
 for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      if (OrderType() == OP_SELLSTOP && OrderComment() == comment)  commentcount++;
   }//for(int i=0; i<totalOrders; i++)
      return(commentcount);       
}//int NumberOfTradesWithThisComment(string comment )
//+------------------------------------------------------------------+
bool StaticCountAllSellTypesWithThisComment(string comment)
{
 static int laststopcount;static int lastsellcount;static int lastbothcount;
  int stopcount, sellcount, bothcount; 
 for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if ( OrderComment()!= comment )continue;

      if (OrderType() == OP_SELLSTOP )
      stopcount++;

      if(OrderType() == OP_SELL  )  
      sellcount++;
      bothcount = sellcount + stopcount;
      RefreshRates();

    if( bothcount == lastbothcount) //2
    if( stopcount == 0 ) //if(laststopcount > 0 )
    //if( sellcount >  lastsellcount ) //if(sellcount > 0)
    return(true);  

    laststopcount = stopcount; 
    lastsellcount = sellcount; 
    lastbothcount = bothcount; 

   }//for(int i=0; i<totalOrders; i++)
//   return(bothcount);
   return(false);
}//int StaticSellStopsCountWithThisComment(comment)
//+------------------------------------------------------------------+
///######//+------------------------------------------------------------------+
    int LiveTime( string comment) 
   {
///######//+------------------------------------------------------------------+
   int ActiveTime = 0; static int LastActiveTime;
   int PendingTime = 0; static int LastPendingTime;
   int OrderTime = 0; static int LastOrderTime;
   if( LatestTimeForPendingWithThisComment(comment) > LastPendingTime ) LastPendingTime = LatestTimeForPendingWithThisComment(comment); 
   if( LatestTimeForOrderWithThisComment(comment) > LastOrderTime ) LastOrderTime = LatestTimeForOrderWithThisComment(comment); 
   if( LastPendingTime > LastOrderTime ) LastActiveTime = LastPendingTime;
   if( LastPendingTime < LastOrderTime ) LastActiveTime = LastOrderTime;   
   return(LastActiveTime);
///######//+------------------------------------------------------------------+
   }//    int LiveTime( string comment) 
//+------------------------------------------------------------------+
/////////////////////////////////////////////////////////////////////////////////////
    int LiveTimei( string comment) 
///######//+------------------------------------------------------------------+
   {
   int ActiveTimei = 0; static int LastActiveTimei;
   int PendingTimei = 0; static int LastPendingTimei;
   int OrderTimei = 0; static int LastOrderTimei;
   if( LatestTimeForPendingWithThisComment(comment) > LastPendingTimei ) LastPendingTimei = LatestTimeForPendingWithThisComment(comment); 
   if( LatestTimeForOrderWithThisComment(comment) > LastOrderTimei ) LastOrderTimei = LatestTimeForOrderWithThisComment(comment); 
   if( LastPendingTimei > LastOrderTimei ) LastActiveTimei = LastPendingTimei;
   if( LastPendingTimei < LastOrderTimei ) LastActiveTimei = LastOrderTimei;   
///######//+------------------------------------------------------------------+
   return(LastActiveTimei);
//+------------------------------------------------------------------+
   }//    int LiveTimei( string comment) 
//------------------
double UplOfEarliestOrderWithThisComment(string comment)
{  double OrderCommentUpl = 0;
   datetime lastopentime = TimeCurrent();  
   int lastticket=-1;
   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      //Build up the position picture of market trades
      if (OrderType() < 2)
      {
         //Buystops
         if (OrderType() == OP_BUY)
         {
            BuyOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastopentime = OrderOpenTime();
               lastticket = OrderTicket();
         OrderCommentUpl = (OrderProfit() + OrderSwap() + OrderCommission()); 
            }//if (OrderOpenTime() > lastopentime)
            }//if (OrderType() == OP_BUY  

         //Buystops
         if (OrderType() == OP_SELL)
         {
            SellOpen = true;
            
            //Furthest back in time
            if (OrderOpenTime() < lastopentime)
            {
               lastopentime = OrderOpenTime();
               lastticket = OrderTicket();
         OrderCommentUpl = (OrderProfit() + OrderSwap() + OrderCommission()); 
            }//if (OrderOpenTime() > lastopentime)
            }//if (OrderType() == OP_BUY  

            }//if (OrderType() < 2)
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)

   return(OrderCommentUpl);  }//bool TypeSell(int Ticket_No)
//------------------
double UplOfOrderWithThisComment(string comment)
{  double OrderCommentUpl = 0;
   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      //Build up the position picture of market trades
      if (OrderType() < 2)
      {
         OrderCommentUpl+= (OrderProfit() + OrderSwap() + OrderCommission()); 
         }
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)

   return(OrderCommentUpl);  }//bool TypeSell(int Ticket_No)
//------------------
//------------------
bool TypeBuyComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_BUY )
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeBuyComment(string comment)
//------------------
bool TypeBuyStopComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_BUYSTOP )
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeBuyComment(string comment)
//------------------
bool TypeBuyLimitComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_BUYLIMIT )
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeBuyComment(string comment)
//------------------
bool TypeSellComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_SELL )
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeSellComment(string comment)
//------------------
bool TypeSellStopComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_SELLSTOP )
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeSellComment(string comment)
//------------------
bool TypeSellLimitComment(string comment)
{   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() == OP_SELLLIMIT )
      if (StringFind( OrderComment(),comment,0) > -1 )
   return(true);
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( false ) ;      }//bool TypeSellComment(string comment)
//+------------------------------------------------------------------+
//------------------
double PriceOfOrderWithThisComment(string comment)
{  double OrderCommentPrice = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      OrderCommentPrice = OrderOpenPrice();
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   return(OrderCommentPrice);  }//bool TypeSell(int Ticket_No)
//------------------
//------------------
datetime TimeOfOrderWithThisComment(string comment)
{  datetime OrderCommentTime = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      OrderCommentTime = OrderOpenTime();
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   return(OrderCommentTime);     }//bool TypeSell(int Ticket_No)
//------------------
//------------------
int NrOfSecOrderWithThisCommentHasBeenOpened(string comment)
{  int OrderCommentTime = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      if( DoesTradeCommentExistForThisPair(comment, Symbol()) ) OrderCommentTime = TimeCurrent() - OrderOpenTime();
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
    return(OrderCommentTime); }//bool TypeSell(int Ticket_No)
//------------------
//------------------
//------------------
int TicketNoOfOrderWithThisComment(string comment)
{  int OrderCommentTicket = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (StringFind( OrderComment(),comment,0) > -1 )
      OrderCommentTicket = OrderTicket();
   
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   return(OrderCommentTicket);     }//bool TypeSell(int Ticket_No)
//------------------
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
string FindBuyTradeComment( string ordercomment)
{   string BuyTradeComment = -1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;

      if (StringFind( OrderComment(),ordercomment,0) > -1 )
         BuyTradeComment = OrderComment();
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( BuyTradeComment ) ;      }//int BuyTradeTicketNo()
//+------------------------------------------------------------------+
string FindSellTradeComment( string ordercomment)
{   string SellTradeComment = -1;
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;

      if (StringFind( OrderComment(),ordercomment,0) > -1 )
         SellTradeComment = OrderComment();
   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
  return ( SellTradeComment ) ;      }//int SellTradeTicketNo()
//+------------------------------------------------------------------+
//------------------
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsMoAvGMoAv( int tf, int period01 , int method01, int period02 , int method02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(  MoAv(Symbol(),tf,period01,method01,i) > MoAv(Symbol(),tf,period02,method02,i)   ) ;
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsMoAvLMoAv( int tf, int period01 , int method01, int period02 , int method02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount; i>=NrToStartCount; i--)
   {
   bool bear =(  MoAv(Symbol(),tf,period01,method01,i) < MoAv(Symbol(),tf,period02,method02,i)   ) ;
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsMaBow3G( int tf, int period01 , int method01, int period02 , int method02, int period03 , int method03  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(  MoAv(Symbol(),tf,period01,method01,i) > MoAv(Symbol(),tf,period02,method02,i)  
   &&   MoAv(Symbol(),tf,period02,method02,i) > MoAv(Symbol(),tf,period03,method03,i) 
      ) ;
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsMaBow3L( int tf, int period01 , int method01, int period02 , int method02, int period03 , int method03  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(  MoAv(Symbol(),tf,period01,method01,i) < MoAv(Symbol(),tf,period02,method02,i)  
   &&   MoAv(Symbol(),tf,period02,method02,i) < MoAv(Symbol(),tf,period03,method03,i)  ) ;
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsMaBow4G( int tf,int period01 ,int method01,int period02 ,int method02, int period03 , int method03  , int method04, int period04 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( MaBow04G(tf,period01,method01,period02,method02,period03,method03,period04,method04, i )       ) ;
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsMaBow4L( int tf, int period01 , int method01, int period02 , int method02, int period03 , int method03 , int method04, int period04 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( MaBow04L(tf,period01,method01,period02,method02,period03,method03,period04,method04, i )       ) ;

        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsCloseAboveMoAv( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) > MoAv(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsCloseAboveMaHi( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) > MaHigh(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsCloseAboveMaLo( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) > MaLow(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsCloseBelowMoAv( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) < MoAv(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsCloseBelowMaHi( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) < MaHigh(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsCloseBelowMaLo( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) < MaLow(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsCloseAboveMidDon( int tf, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) > GetMidDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsCloseBelowMidDon( int tf, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) < GetMidDonn(Symbol(), tf, channelperiod, i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsCloseAboveHiDon( int tf, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) > GetHiDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsCloseBelowHiDon( int tf, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) < GetHiDonn(Symbol(), tf, channelperiod, i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsCloseAboveLoDon( int tf, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) > GetLoDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsCloseBelowLoDon( int tf, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iClose(Symbol(),tf,i) < GetLoDonn(Symbol(), tf, channelperiod, i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHiDonGMoAv( int tf, int channelperiod  , int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod, i ) > MoAv(Symbol(),tf,period,method,i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }

//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHiDonLMoAv( int tf, int channelperiod  , int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod, i ) < MoAv(Symbol(),tf,period,method,i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsLoDonLMoAv( int tf, int channelperiod  , int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod, i ) < MoAv(Symbol(),tf,period,method,i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsLoDonGMoAv( int tf, int channelperiod  , int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod, i ) > MoAv(Symbol(),tf,period,method,i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHiDonGMidDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod01, i ) > GetMidDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLoDonLMidDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod01, i ) < GetMidDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsMidDonGMoAv( int tf, int channelperiod  , int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetMidDonn(Symbol(), tf, channelperiod, i ) > MoAv(Symbol(),tf,period,method,i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsMidDonLMoAv( int tf, int channelperiod  , int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetMidDonn(Symbol(), tf, channelperiod, i ) < MoAv(Symbol(),tf,period,method,i  ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool IsLowAboveHiTma( int tf, int halflength, double atrmultiplier, int atrperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleLow(tf,i) > UpperTma(tf,halflength,atrmultiplier,atrperiod, i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHighBelowLoTma( int tf, int halflength, double atrmultiplier, int atrperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleHigh(tf,i) < LowerTma(tf,halflength,atrmultiplier,atrperiod, i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHiDonGHiDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod01, i ) > GetHiDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHiDonLHiDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod01, i ) < GetHiDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLoDonGLoDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod01, i ) > GetLoDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLoDonLLoDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod01, i ) < GetLoDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsMidDonGMidDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetMidDonn(Symbol(), tf, channelperiod01, i ) > GetMidDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsMidDonLMidDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetMidDonn(Symbol(), tf, channelperiod01, i ) < GetMidDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLowAboveMidDon( int tf, int channelperiod ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iLow(Symbol(),tf,i) > GetMidDonn(Symbol(), tf, channelperiod, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHighAboveMidDon( int tf, int channelperiod ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iHigh(Symbol(),tf,i) > GetMidDonn(Symbol(), tf, channelperiod, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLowBelowMidDon( int tf, int channelperiod ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iLow(Symbol(),tf,i) < GetMidDonn(Symbol(), tf, channelperiod, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHighBelowMidDon( int tf, int channelperiod ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iHigh(Symbol(),tf,i) < GetMidDonn(Symbol(), tf, channelperiod, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLowAboveLoDon( int tf, int channelperiod ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iLow(Symbol(),tf,i) > GetLoDonn(Symbol(), tf, channelperiod, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHighBelowLoDon( int tf, int channelperiod ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iHigh(Symbol(),tf,i) < GetHiDonn(Symbol(), tf, channelperiod, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLoDonGMidDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod01, i ) > GetMidDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHiDonLMidDon( int tf, int channelperiod01  , int channelperiod02 ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod01, i ) < GetMidDonn(Symbol(), tf, channelperiod02, i ) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsStochG( int tf, int kperiod  , int dperiod ,int level, int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetStoch(tf,kperiod,dperiod,1,MODE_SMA,MODE_SIGNAL,i) > level );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsStochL( int tf, int kperiod  , int dperiod ,int level, int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetStoch(tf,kperiod,dperiod,1,MODE_SMA,MODE_SIGNAL,i) < level );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool IsStochGStoch( int tf, int kperiod01 , int dperiod01 , int kperiod02  , int dperiod02 , int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetStoch(tf,kperiod01,dperiod01,1,MODE_SMA,MODE_SIGNAL,i) > GetStoch(tf,kperiod02,dperiod02,1,MODE_SMA,MODE_SIGNAL,i) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool IsStochLStoch( int tf, int kperiod01 , int dperiod01 , int kperiod02  , int dperiod02 , int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetStoch(tf,kperiod01,dperiod01,1,MODE_SMA,MODE_SIGNAL,i) < GetStoch(tf,kperiod02,dperiod02,1,MODE_SMA,MODE_SIGNAL,i) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsHighAboveMoAv( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iHigh(Symbol(),tf,i) > MoAv(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsHighBelowMoAv( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iHigh(Symbol(),tf,i) < MoAv(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool IsLowAboveMoAv( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iLow(Symbol(),tf,i) > MoAv(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBearish                                                        |
//+------------------------------------------------------------------+
bool IsLowBelowMoAv( int tf, int period , int method ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(iLow(Symbol(),tf,i) < MoAv(Symbol(),tf,period,method,i)   );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsCloseAboveMidTma( int tf, int halflength, int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) > MidTma( tf, halflength, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsCloseBelowMidTma( int tf, int halflength, int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) < MidTma( tf, halflength, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsLoTmaAboveMidDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(LowerTma(tf,halflength,atrmultiplier,atrperiod, i) > GetMidDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsLoTmaAboveHiDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(LowerTma(tf,halflength,atrmultiplier,atrperiod, i) > GetHiDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsLoTmaAboveLoDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(LowerTma(tf,halflength,atrmultiplier,atrperiod, i) > GetLoDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsLoTmaBelowMidDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(LowerTma(tf,halflength,atrmultiplier,atrperiod, i) < GetMidDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsLoTmaBelowHiDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(LowerTma(tf,halflength,atrmultiplier,atrperiod, i) < GetHiDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsLoTmaBelowLoDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(LowerTma(tf,halflength,atrmultiplier,atrperiod, i) < GetLoDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//????????????????????????????????????
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHiTmaAboveMidDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(UpperTma(tf,halflength,atrmultiplier,atrperiod, i) > GetMidDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHiTmaAboveHiDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(UpperTma(tf,halflength,atrmultiplier,atrperiod, i) > GetHiDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHiTmaAboveLoDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(UpperTma(tf,halflength,atrmultiplier,atrperiod, i) > GetLoDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHiTmaBelowMidDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(UpperTma(tf,halflength,atrmultiplier,atrperiod, i) < GetMidDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHiTmaBelowHiDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(UpperTma(tf,halflength,atrmultiplier,atrperiod, i) < GetHiDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHiTmaBelowLoDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(UpperTma(tf,halflength,atrmultiplier,atrperiod, i) < GetLoDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
///??????????????????????????????????
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsMidTmaAboveMidDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(MidTma(tf,halflength, i)  > GetMidDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsMidTmaAboveHiDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(MidTma(tf,halflength, i)  > GetHiDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsMidTmaAboveLoDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(MidTma(tf,halflength, i)  > GetLoDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsMidTmaBelowMidDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(MidTma(tf,halflength, i)  < GetMidDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsMidTmaBelowHiDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(MidTma(tf,halflength, i)  < GetHiDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsMidTmaBelowLoDon( int tf, int halflength, double atrmultiplier, int atrperiod, int channelperiod  ,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(MidTma(tf,halflength, i) < GetLoDonn(Symbol(), tf, channelperiod, i )  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool StepHiDonGHiDon( int tf, int channelperiod   , int step,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod, i ) > GetHiDonn(Symbol(), tf, channelperiod, i + step) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool StepHiDonLHiDon( int tf, int channelperiod   , int step,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetHiDonn(Symbol(), tf, channelperiod, i ) < GetHiDonn(Symbol(), tf, channelperiod, i + step) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool StepLoDonGLoDon( int tf, int channelperiod   , int step,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod, i ) > GetLoDonn(Symbol(), tf, channelperiod, i + step) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| IsBullish                                                        |
//+------------------------------------------------------------------+
bool StepLoDonLLoDon( int tf, int channelperiod   , int step,int NrOfConsCandles , int NrToStartCount )
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =( GetLoDonn(Symbol(), tf, channelperiod, i ) < GetLoDonn(Symbol(), tf, channelperiod, i + step) );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool RangeCloseAboveLoDon( int tf, int channelperiod, int NrOfConsCandles , int NrToStartCount , int base)
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) > GetLoDonn(Symbol(), tf, channelperiod, base)  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool RangeCloseBelowLoDon( int tf, int channelperiod, int NrOfConsCandles , int NrToStartCount , int base)
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) < GetLoDonn(Symbol(), tf, channelperiod, base)  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool RangeCloseAboveHiDon( int tf, int channelperiod, int NrOfConsCandles , int NrToStartCount , int base)
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) > GetHiDonn(Symbol(), tf, channelperiod, base)  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool RangeCloseBelowHiDon( int tf, int channelperiod, int NrOfConsCandles , int NrToStartCount , int base)
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) < GetHiDonn(Symbol(), tf, channelperiod, base)  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool RangeCloseAboveMidDon( int tf, int channelperiod, int NrOfConsCandles , int NrToStartCount , int base)
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) > GetMidDonn(Symbol(), tf, channelperiod, base)  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }
//+------------------------------------------------------------------+
bool RangeCloseBelowMidDon( int tf, int channelperiod, int NrOfConsCandles , int NrToStartCount , int base)
  {
   int  count ;
         for(int i= NrOfConsCandles + NrToStartCount ; i>=NrToStartCount; i--)
   {
   bool bear =(CandleClose(tf, i) < GetMidDonn(Symbol(), tf, channelperiod, base)  );
        if(!bear)  count = 0; 
        if(bear)   count++; 
    }
   if(count >= NrOfConsCandles) return(true);
   return(false);
  }///+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool CloseOrder(int ticket)
{   
   while(IsTradeContextBusy()) Sleep(100);
   bool orderselect=BetterOrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
   if (!orderselect) return(false);

   bool result = OrderClose(ticket, OrderLots(), OrderClosePrice(), 1000, clrBlue);

   //Actions when trade send succeeds
   if (result)
   {
      return(true);
   }//if (result)
   
   //Actions when trade send fails
   if (!result)
   {
      ReportError(" CloseOrder()", ocm);
      return(false);
   }//if (!result)
   
   return(true);
}//End bool CloseOrder(ticket)


////////////////////////////////////////////////////////////////////////////////////////
//Indicator module

void CheckForSpreadWidening()
{
   if (CloseEnough(AverageSpread, 0)) return;
   //Detect a dramatic widening of the spread and pause the ea until this passes
   double TargetSpread = AverageSpread * MultiplierToDetectStopHunt;
   double spread = (Ask - Bid) * factor;
   
   if (spread >= TargetSpread)
   {
      if (OpenTrades == 0) Comment(Gap + "PAUSED DURING A MASSIVE SPREAD EVENT");
      if (OpenTrades > 0) Comment(Gap + "PAUSED DURING A MASSIVE SPREAD EVENT. STILL MONITORING TRADES.");
      while (spread >= TargetSpread)
      {
         RefreshRates();
         spread = (Ask - Bid) * factor;
         
         CountOpenTrades();
         //Safety feature. Sometimes an unexpected concatenation of inputs choice and logic error can cause rapid opening-closing of trades. Detect a closed trade and check that is was not a rogue.
         if (OldOpenTrades != OpenTrades)
         {
            if (IsClosedTradeRogue() )
            {
               RobotSuspended = true;
               return;
            }//if (IsClosedTradeRogue() )      
         }//if (OldOpenTrades != OpenTrades)
         if (ForceTradeClosure) return;//Emergency measure to force a retry at the next tick
         
         OldOpenTrades = OpenTrades;
         
         Sleep(1000);

      }//while (spread >= TargetSpread)      
   }//if (spread >= TargetSpread)
}//End void CheckForSpreadWidening()

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CalculateDailyResult()
{
   //Calculate the no of winners and losers from today's trading. These are held in the history tab.

   LossTrades = 0;
   WinTrades = 0;
   OverallProfit = 0;
   
   
   for (int cc = 0; cc <= OrdersHistoryTotal(); cc++)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_HISTORY) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderCloseTime() < iTime(Symbol(), PERIOD_D1, 0) ) continue;
      
      OverallProfit+= (OrderProfit() + OrderSwap() + OrderCommission() );
      if (OrderProfit() > 0) WinTrades++;
      if (OrderProfit() < 0) LossTrades++;
   }//for (int cc = 0; cc <= tot -1; cc++)
   
   

}//End void CalculateDailyResult()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CandlePipSize(int tf, int maxbars6, int shift)
{
//--------------
 double Bar12Pips = 0;
 if(maxbars6 >= 6 )
 if ( CandleOpen(tf,shift + 5) < CandleClose(tf,shift + 5) )// Bull Candle
 { Bar12Pips = CandleClose(tf,shift + 5) - CandleOpen(tf,shift + 5) ; }
 else
 if(maxbars6 >= 6 )
 if ( CandleOpen(tf,shift + 5) > CandleClose(tf,shift + 5) )// Bear Candle
 { Bar12Pips = CandleOpen(tf,shift + 5) - CandleClose(tf,shift + 5) ; }

  if(maxbars6 < 6 ){ Bar12Pips = 0;}
//--------------
 double Bar11Pips = 0;
 if(maxbars6 >= 5 )
 if ( CandleOpen(tf,shift + 4) < CandleClose(tf,shift + 4) )// Bull Candle
 { Bar11Pips = CandleClose(tf,shift + 4) - CandleOpen(tf,shift + 4) ; }
 else
 if(maxbars6 >= 5 )
 if ( CandleOpen(tf,shift + 4) > CandleClose(tf,shift + 4) )// Bear Candle
 { Bar11Pips = CandleOpen(tf,shift + 4) - CandleClose(tf,shift + 4) ; }

  if(maxbars6 < 5 ){ Bar11Pips = 0;}
//--------------
 double Bar10Pips = 0;
 if(maxbars6 >= 4 )
 if ( CandleOpen(tf,shift + 3) < CandleClose(tf,shift + 3) )// Bull Candle
 { Bar10Pips = CandleClose(tf,shift + 3) - CandleOpen(tf,shift + 3) ; }
 else
 if(maxbars6 >= 4 )
 if ( CandleOpen(tf,shift + 3) > CandleClose(tf,shift + 3) )// Bear Candle
 { Bar10Pips = CandleOpen(tf,shift + 3) - CandleClose(tf,shift + 3) ; }

  if(maxbars6 < 4 ){ Bar10Pips = 0;}
//--------------
//--------------
 double Bar9Pips = 0;
 if(maxbars6 >= 3 )
 if ( CandleOpen(tf,shift + 2) < CandleClose(tf,shift + 2) )// Bull Candle
 { Bar9Pips = CandleClose(tf,shift + 2) - CandleOpen(tf,shift + 2) ; }
 else
 if(maxbars6 >= 3 )
 if ( CandleOpen(tf,shift + 2) > CandleClose(tf,shift + 2) )// Bear Candle
 { Bar9Pips = CandleOpen(tf,shift + 2) - CandleClose(tf,shift + 2) ; }

  if(maxbars6 < 3 ){ Bar9Pips = 0;}
//--------------
//--------------
 double Bar8Pips = 0;
 if(maxbars6 >= 2 )
 if ( CandleOpen(tf,shift + 1) < CandleClose(tf,shift + 1) )// Bull Candle
 { Bar8Pips = CandleClose(tf,shift + 1) - CandleOpen(tf,shift + 1) ; }
 else
 if(maxbars6 >= 2 )
 if ( CandleOpen(tf,8) > CandleClose(tf,8) )// Bear Candle
 { Bar8Pips = CandleOpen(tf,shift + 1) - CandleClose(tf,shift + 1) ; }

  if(maxbars6 < 2 ){ Bar8Pips = 0;}
//--------------
 double Bar7Pips = 0;
 if(maxbars6 >= 1 )
 if ( CandleOpen(tf,shift) < CandleClose(tf,shift) )// Bull Candle
 { Bar7Pips = CandleClose(tf,shift) - CandleOpen(tf,shift) ; }
 else
 if(maxbars6 >= 1 )
 if ( CandleOpen(tf,shift) > CandleClose(tf,shift) )// Bear Candle
 { Bar7Pips = CandleOpen(tf,shift) - CandleClose(tf,shift) ; }
 
  if(maxbars6 < 1 ){ Bar7Pips = 0;}

 double result = 0;
     if(maxbars6 > 0 ) result = (Bar12Pips + Bar11Pips + Bar10Pips +Bar9Pips + Bar8Pips + Bar7Pips  ) / maxbars6 ;
   
   return ( result );
//---------
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
   double DonGap(int tf, int channelperiod, int shift) 
   {
   double bam = GetHiDonn(Symbol(),tf,channelperiod,shift) - GetLoDonn(Symbol(),tf,channelperiod,shift)   ;
   return ( bam );
//---------
   }
//+------------------------------------------------------------------+
   double DonGapDivide(int tf, int channelperiod, int shift, int divide) 
   {
   double bam = DonGap(tf,channelperiod,shift) / divide  ;
   return ( bam );
//---------
   }
//+------------------------------------------------------------------+
   double DonHiMinusDivide(int tf, int channelperiod, int shift , int divide  ) 
   {
   double bam = GetHiDonn(Symbol(),tf,channelperiod,shift) - DonGapDivide(tf,channelperiod,shift,divide) ;
   return ( bam );
//---------
   }   
//+------------------------------------------------------------------+
   double DonLoPlusDivide(int tf, int channelperiod, int shift , int divide  ) 
   {
   double bam = GetLoDonn(Symbol(),tf,channelperiod,shift) + DonGapDivide(tf,channelperiod,shift,divide) ;
   return ( bam );
//---------
   }   
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CanOp( int tf )
{ 
   if (tf == 0)      tf = Period();
//--------------
    return( ( CandleOpen(tf,0) + CandleOpen(tf,2)
    + CandleOpen(tf,4) + CandleOpen(tf,6) )/ 4
    );
 }//int BarShiftOfCandleWithBiggestPips( int tf )
//+------------------------------------------------------------------+
double CanClo( int tf )
{ 
   if (tf == 0)      tf = Period();
//--------------
    return( ( CandleClose(tf,1) + CandleClose(tf,3)
    + CandleClose(tf,5) + CandleClose(tf,7) )/ 4
    );
 }//int BarShiftOfCandleWithBiggestPips( int tf )
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool MaBow05( int tf, int period01, int method01, int shift01,
            int period02, int method02, int shift02,
            int period03, int method03, int shift03,
            int period04, int method04, int shift04,
            int period05, int method05, int shift05 )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift01)  >  MoAv(Symbol(),tf,period02,method02,shift02)   
   &&  MoAv(Symbol(),tf,period02,method02,shift02)  >  MoAv(Symbol(),tf,period03,method03,shift03)   
   &&  MoAv(Symbol(),tf,period03,method03,shift03)  >  MoAv(Symbol(),tf,period04,method04,shift04)   
   &&  MoAv(Symbol(),tf,period04,method04,shift04)  >  MoAv(Symbol(),tf,period05,method05,shift05)   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+  
bool MaBow05i( int tf, int period01, int method01,
            int period02, int method02, 
            int period03, int method03, 
            int period04, int method04, 
            int period05, int method05, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MoAv(Symbol(),tf,period02,method02,shift )   
   &&  MoAv(Symbol(),tf,period02,method02,shift)  >  MoAv(Symbol(),tf,period03,method03,shift )   
   &&  MoAv(Symbol(),tf,period03,method03,shift)  >  MoAv(Symbol(),tf,period04,method04,shift )   
   &&  MoAv(Symbol(),tf,period04,method04,shift )  >  MoAv(Symbol(),tf,period05,method05,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+  
bool MaBow05G( int tf, int period01, int method01,
            int period02, int method02, 
            int period03, int method03, 
            int period04, int method04, 
            int period05, int method05, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MoAv(Symbol(),tf,period02,method02,shift )   
   &&  MoAv(Symbol(),tf,period02,method02,shift)  >  MoAv(Symbol(),tf,period03,method03,shift )   
   &&  MoAv(Symbol(),tf,period03,method03,shift)  >  MoAv(Symbol(),tf,period04,method04,shift )   
   &&  MoAv(Symbol(),tf,period04,method04,shift )  >  MoAv(Symbol(),tf,period05,method05,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+  
bool MaBow05L( int tf, int period01, int method01,
            int period02, int method02, 
            int period03, int method03, 
            int period04, int method04, 
            int period05, int method05, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  <  MoAv(Symbol(),tf,period02,method02,shift )   
   &&  MoAv(Symbol(),tf,period02,method02,shift)  <  MoAv(Symbol(),tf,period03,method03,shift )   
   &&  MoAv(Symbol(),tf,period03,method03,shift)  <  MoAv(Symbol(),tf,period04,method04,shift )   
   &&  MoAv(Symbol(),tf,period04,method04,shift )  <  MoAv(Symbol(),tf,period05,method05,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool MaBow04( int tf, int period01, int method01, 
            int period02, int method02,
            int period03, int method03, 
            int period04, int method04, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MoAv(Symbol(),tf,period02,method02,shift)   
   &&  MoAv(Symbol(),tf,period02,method02,shift)  >  MoAv(Symbol(),tf,period03,method03,shift )   
   &&  MoAv(Symbol(),tf,period03,method03,shift)  >  MoAv(Symbol(),tf,period04,method04,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool MaBow04G( int tf, int period01, int method01, 
            int period02, int method02,
            int period03, int method03, 
            int period04, int method04, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MoAv(Symbol(),tf,period02,method02,shift)   
   &&  MoAv(Symbol(),tf,period02,method02,shift)  >  MoAv(Symbol(),tf,period03,method03,shift )   
   &&  MoAv(Symbol(),tf,period03,method03,shift)  >  MoAv(Symbol(),tf,period04,method04,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool MaBow04L( int tf, int period01, int method01, 
            int period02, int method02,
            int period03, int method03, 
            int period04, int method04, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  <  MoAv(Symbol(),tf,period02,method02,shift)   
   &&  MoAv(Symbol(),tf,period02,method02,shift)  <  MoAv(Symbol(),tf,period03,method03,shift )   
   &&  MoAv(Symbol(),tf,period03,method03,shift)  <  MoAv(Symbol(),tf,period04,method04,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool MaBow03( int tf, int period01, int method01, 
            int period02, int method02,
            int period03, int method03, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MoAv(Symbol(),tf,period02,method02,shift )   
   &&  MoAv(Symbol(),tf,period02,method02,shift )  >  MoAv(Symbol(),tf,period03,method03,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
bool MaBow03G( int tf, int period01, int method01, 
            int period02, int method02,
            int period03, int method03, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MoAv(Symbol(),tf,period02,method02,shift )   
   &&  MoAv(Symbol(),tf,period02,method02,shift )  >  MoAv(Symbol(),tf,period03,method03,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
bool MaBow03L( int tf, int period01, int method01, 
            int period02, int method02,
            int period03, int method03, int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  <  MoAv(Symbol(),tf,period02,method02,shift )   
   &&  MoAv(Symbol(),tf,period02,method02,shift ) <  MoAv(Symbol(),tf,period03,method03,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
bool MaBow02G( int tf, int period01, int method01, 
            int period02, int method02,
             int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MoAv(Symbol(),tf,period02,method02,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
bool MaBow02L( int tf, int period01, int method01, 
            int period02, int method02,
             int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  <  MoAv(Symbol(),tf,period02,method02,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
bool MoAvGMaHi( int tf, int period01, int method01, 
            int period02, int method02,
             int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MaHigh(Symbol(),tf,period02,method02,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
bool MoAvLMaHi( int tf, int period01, int method01, 
            int period02, int method02,
             int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  <  MaHigh(Symbol(),tf,period02,method02,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
bool MoAvGMaLo( int tf, int period01, int method01, 
            int period02, int method02,
             int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  >  MaLow(Symbol(),tf,period02,method02,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
bool MoAvLMaLo( int tf, int period01, int method01, 
            int period02, int method02,
             int shift )
   { 
   if( MoAv(Symbol(),tf,period01,method01,shift)  <  MaLow(Symbol(),tf,period02,method02,shift )   
   ) return( true);

   return(false); }
//+------------------------------------------------------------------+
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
                                                                                                                      //@
                                                                                                                      //@
 //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//------
bool TimeBuyStopHasBeenActive( int hours)
   { 
   if(BuyStopOpen)if( (TimeCurrent() - LatestBuyStopTradeTime) / 60 / 60 > hours ) return( true);
   if(!BuyStopOpen) return(true);
   return(false); }
//--------
bool TimeSellStopHasBeenActive( int hours)
   { 
   if(SellStopOpen)if( (TimeCurrent() - LatestSellStopTradeTime) / 60 / 60 > hours ) return( true);
   if(!SellStopOpen) return(true);
   return(false); }
//------
bool TimeBuyLimitHasBeenActive( int hours)
   { 
   if(BuyLimitOpen)if( (TimeCurrent() - LatestBuyLimitTradeTime) / 60 / 60 > hours ) return( true);
   if(!BuyLimitOpen) return(true);
   return(false); }
//--------
bool TimeSellLimitHasBeenActive( int hours)
   { 
   if(SellLimitOpen)if( (TimeCurrent() - LatestSellLimitTradeTime) / 60 / 60 > hours ) return( true);
   if(!SellLimitOpen) return(true);
   return(false); }
 //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
///###++++++++++++++++++++++++++++++++++++#####
      double Min15Open()   {return(iOpen(Symbol(),PERIOD_M5,Bar(PERIOD_M5,PERIOD_M15,0)) );  }    
      double Min15High() { return(iHigh(Symbol(),PERIOD_M5,Bar(PERIOD_M5,PERIOD_M15,0)) ); }    
      double Min15Low()  {  return(iLow(Symbol(),PERIOD_M5,Bar(PERIOD_M5,PERIOD_M15,0)) );     }    
///###++++++++++++++++++++++++++++++++++++#####
      double Hr1Open()  {  return(iOpen(Symbol(),PERIOD_H1,Bar(PERIOD_H1,PERIOD_H1,0)) ); }    
      double Hr1High() { return(iHigh(Symbol(),PERIOD_H1,Bar(PERIOD_H1,PERIOD_H1,0)) ); }    
      double Hr1Low()  { return(iLow(Symbol(),PERIOD_H1,Bar(PERIOD_H1,PERIOD_H1,0)) ); }    
///###++++++++++++++++++++++++++++++++++++#####
      double Hr4Open() {  return(iOpen(Symbol(),PERIOD_H1,Hr40Bar()) );     }    
      double Hr4High()  {  return(iHigh(Symbol(),PERIOD_H1,Hr4HighBar()) ); }    
      double Hr4Low() {  return(iLow(Symbol(),PERIOD_H1,Hr4LowBar()) ); }     
      double TodaysOpen()  {  return(iOpen(Symbol(),PERIOD_H1,Day0Bar(PERIOD_H1)) ); }    
      double TodaysHigh() {  return(iHigh(Symbol(),PERIOD_H1,TodaysHighBar()) ); }    
      double TodaysLow()  {return(iLow(Symbol(),PERIOD_H1,TodaysLowBar()) ); }    
///###++++++++++++++++++++++++++++++++++++#####
      double WeeksOpen() {   return(iHigh(Symbol(),PERIOD_H1,Bar(PERIOD_H1,PERIOD_W1,0) ));     }    
       double WeeksHigh() {  return(iHigh(Symbol(),PERIOD_H1,Bar(PERIOD_H1,PERIOD_W1,0)) );   }    
       double WeeksLow() { return(iLow(Symbol(),PERIOD_H1,WeeksLowBar()) );  }    
///###++++++++++++++++++++++++++++++++++++#####
      double MonthsOpen() {  return(iHigh(Symbol(),PERIOD_H1,Bar(PERIOD_H1,PERIOD_MN1,0)) );     }    
      double MonthsHigh() {  return(iHigh(Symbol(),PERIOD_H1,MonthsHighBar()) ); }    
      double MonthsLow()  {  return(iLow(Symbol(),PERIOD_H1,MonthsLowBar()) );  }    
//
bool   BullCandle(int tf , int shift)  {  if( CandleClose(tf,shift) > CandleOpen(tf, shift) ) return(true);  return(false); }
//
bool   BearCandle(int tf , int shift) { if( CandleClose(tf,shift) < CandleOpen(tf, shift) ) return(true);  return(false);  }
//
//
      double CandleHigh(int tf ,int shift) {    return(iHigh(Symbol(),tf ,iHighest(Symbol(),tf,MODE_HIGH,1,shift) ));  }
//
      double CandleLow(int tf ,int shift)   {    return(iLow(Symbol(),tf ,iLowest(Symbol(),tf,MODE_LOW,1,shift) )); }
//      
      double CandleOpen(int tf ,int shift)  {   return(iOpen(Symbol(),tf ,shift));    }
//      
      double CandleClose(int tf ,int shift)  {  return(iClose(Symbol(), tf, shift));    }
//
      double BollingerBandUpper(int tf, int period, double deviation, int shift)
      {        
         return(iBands(Symbol(), tf, period, deviation, 0, PRICE_CLOSE, MODE_UPPER ,shift));
      }
//
      double BollingerBandLower(int tf, int period, double deviation, int shift)
      {        
         return(iBands(Symbol(), tf, period, deviation, 0, PRICE_CLOSE, MODE_LOWER ,shift));
      }
//
      double MovingAverage(int tf,int period,int method,int shift)
      {
         return(iMA(Symbol(), tf, period, 0, method, PRICE_CLOSE, shift) );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)
//
      double MovingHighAverage(int tf,int period,int method,int shift)
      {
         return(iMA(Symbol(), tf, period, 0, method, PRICE_HIGH, shift) );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)
//
      double MovingLowAverage(int tf,int period,int method,int shift)
      {
         return(iMA(Symbol(), tf, period, 0, method, PRICE_LOW, shift) );
      }///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)
///+------------------------------------------------------------------+
//| UpperTma()                                                        |
//+------------------------------------------------------------------+
double UpperTma( int tf, int HalfLength , double atrmultiplier, int atrperiod , int shift)
   {
   return (  MidTma(  tf,  HalfLength,  shift ) + (atrmultiplier * Atrtmarange(  tf,  atrperiod,  shift) ) ) ; 
   }//double UpperTma
///+------------------------------------------------------------------+
//| UpperTma()                                                        |
//+------------------------------------------------------------------+
double LowerTma( int tf, int HalfLength , double atrmultiplier, int atrperiod , int shift)
   {
   return (  MidTma(  tf,  HalfLength,  shift ) - (atrmultiplier * Atrtmarange(  tf,  atrperiod,  shift) ) ) ; 
   }//double UpperTma
///+------------------------------------------------------------------+
//| calcRange()                                                        |
//+------------------------------------------------------------------+
double MidTma(  int tf, int HalfLength, int Shift )
{
   double dblResult, dblSum, dblSumW;
   int inx, jnx;
   
   dblSumW = HalfLength + 1;
   dblSum = dblSumW * CandleClose(tf, Shift);
   jnx = HalfLength;
   
   for ( inx = 1, jnx = HalfLength; inx <= HalfLength; inx++, jnx-- )
   {
      dblSumW += jnx;
      dblSum += ( jnx * CandleClose( tf, Shift+inx) );
   } 
   
   dblResult = dblSum / dblSumW;
   
   return( dblResult );
}//double MidTma(  int tf, int HalfLength, int Shift )

///+------------------------------------------------------------------+
//| calcRange()                                                        |
//+------------------------------------------------------------------+
double Atrtmarange( int tf, int atrperiod, int shift)
   {
   return(iATR( Symbol(), tf, atrperiod, shift+10 ) );
   }//double Atrtmarange( int tf, int atrperiod, int shift)
///+------------------------------------------------------------------+
//| calcTma()                                                        |
//+------------------------------------------------------------------+
double calcTma( int tf, int HalfLength, int Shift )
{
   double dblResult, dblSum, dblSumW;
   int inx, jnx;
   
   dblSumW = HalfLength + 1;
   dblSum = dblSumW * CandleClose(tf, Shift);
   jnx = HalfLength;
   
   for ( inx = 1, jnx = HalfLength; inx <= HalfLength; inx++, jnx-- )
   {
      dblSumW += jnx;
      dblSum += ( jnx * CandleClose( tf, Shift+inx) );
   } 
   
   dblResult = dblSum / dblSumW;
   
   return( dblResult );
}

//+------------------------------------------------------------------+
//+----------a--------------------------------------------------------+
   bool Bar3H4()
   {
/*   if( CandleLow(PERIOD_H4,3) > GetMidDonn(Symbol(),PERIOD_H4,3,3) &&
       CandleLow(PERIOD_H4,2) > GetMidDonn(Symbol(),PERIOD_H4,3,2) &&
       CandleLow(PERIOD_H4,1) < GetMidDonn(Symbol(),PERIOD_H4,3,1) &&
       CandleClose(PERIOD_H4,1) > LowestLowPrice(PERIOD_H4,2,2) )return(true);

   if( CandleHigh(PERIOD_H4,3) < GetMidDonn(Symbol(),PERIOD_H4,3,3) &&
       CandleHigh(PERIOD_H4,2) < GetMidDonn(Symbol(),PERIOD_H4,3,2) &&
       CandleHigh(PERIOD_H4,1) > GetMidDonn(Symbol(),PERIOD_H4,3,1) &&
       CandleClose(PERIOD_H4,1) < HighestHighPrice(PERIOD_H4,2,2) )return(true);
       
      if( CandleHigh(PERIOD_H4,6) == GetHiDonn(Symbol(),PERIOD_H4,3,6) &&
         CandleLow(PERIOD_H4,6) == GetLoDonn(Symbol(),PERIOD_H4,3,6) &&
         CandleHigh(PERIOD_H4,3) == GetHiDonn(Symbol(),PERIOD_H4,3,3) &&
         CandleLow(PERIOD_H4,3) == GetLoDonn(Symbol(),PERIOD_H4,3,3)  &&
         HighestClosePrice(PERIOD_H4,2,1) < GetHiDonn(Symbol(),PERIOD_H4,3,3) &&
         LowestClosePrice(PERIOD_H4,2,1) > GetLoDonn(Symbol(),PERIOD_H4,3,3)     )return(true);

   if( CandleLow(PERIOD_H4,3) < GetMidDonn(Symbol(),PERIOD_H4,3,3) &&
       CandleHigh(PERIOD_H4,3) > GetHiDonn(Symbol(),PERIOD_H4,3,4) &&
       HighestHighPrice(PERIOD_H4,2,1) < GetHiDonn(Symbol(),PERIOD_H4,3,1)&&
       HighestClosePrice(PERIOD_H4,3,1) < CandleHigh(PERIOD_H4,2)&&
       LowestClosePrice(PERIOD_H4,3,1) > GetMidDonn(Symbol(),PERIOD_H4,3,1 ))return(true);

   if( CandleHigh(PERIOD_H4,3) > GetMidDonn(Symbol(),PERIOD_H4,3,3) &&
       CandleLow(PERIOD_H4,3) < GetLoDonn(Symbol(),PERIOD_H4,3,4) &&
       LowestLowPrice(PERIOD_H4,2,1) > GetLoDonn(Symbol(),PERIOD_H4,3,1)&&
       LowestClosePrice(PERIOD_H4,3,1) > CandleLow(PERIOD_H4,2)&&
       HighestClosePrice(PERIOD_H4,3,1) < GetMidDonn(Symbol(),PERIOD_H4,3,1 ))return(true);
*/
   if(  GetHiDonn(Symbol(),PERIOD_H4,3,2) > GetHiDonn(Symbol(),PERIOD_H4,3,3) && 
   CandleClose(PERIOD_H4,1) < GetMidDonn(Symbol(),PERIOD_H4,3,1) &&
   CandleLow(PERIOD_H4,1) < GetLoDonn(Symbol(),PERIOD_H4,4,2) &&
   GetHiDonn(Symbol(),PERIOD_H4,3,1) > GetMidDonn(Symbol(),PERIOD_H4,20,1) &&
   CandleClose(PERIOD_H4,1) > GetLoDonn(Symbol(),PERIOD_H4,3,2)
   )return(true);

   return(false);
   }//bool Bar3H4()
//+----------a--------------------------------------------------------+
//+----------a--------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
int TidaneGreenCount(string cymbol,int timeframei, int Lengthi,int Deviationi)
 {
   bool tidanegreen = false;
   bool tidanered   = false;
   int  ix;
   int trend=0;
   int  counthigh =0;
   int  countlow =0;
   double smax=0;double smin=0;double bsmax=0;double bsmin=0;
   double smaxi=0;double smini=0; double bsmaxi=0; double bsmini=0;
   for(ix = Nbars-Lengthi-1; ix >=0; ix--)
      {
      
     smax=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER,ix);
	  smin=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER,ix);
     
     smaxi=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER, ix + 1);
	  smini=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER, ix + 1);

	  	  
	  bsmax =smax + 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Upper Tidane current RED
	  bsmin =smin - 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Lower Tidane current GREEN
		
	  bsmaxi =smaxi + 0.5 * (MoneyRisk-1) * (smaxi -smini );// Upper Tidane previous bar RED
	  bsmini =smini - 0.5 * (MoneyRisk-1) * (smaxi -smini );// Lower Tidane previous bar GREEN


       if ( iClose(cymbol,timeframei,ix + 1) > bsmaxi )  
       // set to "i+1" to be able to read out the counted bars till next bars open   
          counthigh = 0;     // counter set back to zero 
          
       if ( iClose(cymbol, timeframei, ix + 1 ) < bsmini )      
       // set to "i+1" to be able to read out the counted bars till next bars open
          countlow = 0;                     // counter set back to zero  
           
       if ( iClose(cymbol,timeframei,ix ) < bsmax ) // close less than red
          
          counthigh++; 
          
       if ( iClose(cymbol,timeframei,ix ) > bsmin ) // close greater than green
          
          countlow++;  
           
       }
   if(countlow > counthigh) tidanegreen = true; //green    
   if(countlow < counthigh) tidanered = true; //red    
   //if(tidanegreen) return(true);
    return(counthigh);
 }
//+----------a--------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int TidaneRedCount(string cymbol,int timeframei, int Lengthi,int Deviationi)
 {
   bool tidanegreen = false;
   bool tidanered   = false;
   int  ix;
   int trend=0;
   int  counthigh =0;
   int  countlow =0;
   double smax=0;double smin=0;double bsmax=0;double bsmin=0;
   double smaxi=0;double smini=0; double bsmaxi=0; double bsmini=0;
   for(ix = Nbars-Lengthi-1; ix >=0; ix--)
      {
      
     smax=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER,ix);
	  smin=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER,ix);
     
     smaxi=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER, ix + 1);
	  smini=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER, ix + 1);

	  	  
	  bsmax =smax + 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Upper Tidane current RED
	  bsmin =smin - 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Lower Tidane current GREEN
		
	  bsmaxi =smaxi + 0.5 * (MoneyRisk-1) * (smaxi -smini );// Upper Tidane previous bar RED
	  bsmini =smini - 0.5 * (MoneyRisk-1) * (smaxi -smini );// Lower Tidane previous bar GREEN


       if ( iClose(cymbol,timeframei,ix + 1) > bsmaxi )  
       // set to "i+1" to be able to read out the counted bars till next bars open   
          counthigh = 0;     // counter set back to zero 
          
       if ( iClose(cymbol, timeframei, ix + 1 ) < bsmini )      
       // set to "i+1" to be able to read out the counted bars till next bars open
          countlow = 0;                     // counter set back to zero  
           
       if ( iClose(cymbol,timeframei,ix ) < bsmax ) // close less than red
          
          counthigh++; 
          
       if ( iClose(cymbol,timeframei,ix ) > bsmin ) // close greater than green
          
          countlow++;  
           
       }
   if(countlow > counthigh) tidanegreen = true; //green    
   if(countlow < counthigh) tidanered = true; //red    
   //if(tidanegreen) return(true);
    return(countlow);
 }
//+----------a--------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool TidaneGreeni(string cymbol,int timeframei, int Lengthi,int Deviationi)
 {
   bool tidanegreen = false;
   bool tidanered   = false;
   int  ix;
   int trend=0;
   int  counthigh =0;
   int  countlow =0;
   double smax=0;double smin=0;double bsmax=0;double bsmin=0;
   double smaxi=0;double smini=0; double bsmaxi=0; double bsmini=0;
   for(ix = Nbars-Lengthi-1; ix >=0; ix--)
      {
      
     smax=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER,ix);
	  smin=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER,ix);
     
     smaxi=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER, ix + 1);
	  smini=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER, ix + 1);

	  	  
	  bsmax =smax + 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Upper Tidane current RED
	  bsmin =smin - 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Lower Tidane current GREEN
		
	  bsmaxi =smaxi + 0.5 * (MoneyRisk-1) * (smaxi -smini );// Upper Tidane previous bar RED
	  bsmini =smini - 0.5 * (MoneyRisk-1) * (smaxi -smini );// Lower Tidane previous bar GREEN


       if ( iClose(cymbol,timeframei,ix + 1) > bsmaxi )  
       // set to "i+1" to be able to read out the counted bars till next bars open   
          counthigh = 0;     // counter set back to zero 
          
       if ( iClose(cymbol, timeframei, ix + 1 ) < bsmini )      
       // set to "i+1" to be able to read out the counted bars till next bars open
          countlow = 0;                     // counter set back to zero  
           
       if ( iClose(cymbol,timeframei,ix ) < bsmax ) // close less than red
          
          counthigh++; 
          
       if ( iClose(cymbol,timeframei,ix ) > bsmin ) // close greater than green
          
          countlow++;  
           
       }
   if(countlow > counthigh) tidanegreen = true; //green    
   if(countlow < counthigh) tidanered = true; //red    
   if(tidanegreen) return(true);
    return(false);
 }
//+----------a--------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool TidaneRedi(string cymbol,int timeframei, int Lengthi,int Deviationi)
 {
   bool tidanegreen = false;
   bool tidanered   = false;
   int  ix;
   int trend=0;
   int  counthigh =0;
   int  countlow =0;
   double smax=0;double smin=0;double bsmax=0;double bsmin=0;
   double smaxi=0;double smini=0; double bsmaxi=0; double bsmini=0;
   for(ix = Nbars-Lengthi-1; ix >=0; ix--)
      {
      
     smax=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER,ix);
	  smin=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER,ix);
     
     smaxi=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER, ix + 1);
	  smini=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER, ix + 1);

	  	  
	  bsmax =smax + 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Upper Tidane current RED
	  bsmin =smin - 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Lower Tidane current GREEN
		
	  bsmaxi =smaxi + 0.5 * (MoneyRisk-1) * (smaxi -smini );// Upper Tidane previous bar RED
	  bsmini =smini - 0.5 * (MoneyRisk-1) * (smaxi -smini );// Lower Tidane previous bar GREEN


       if ( iClose(cymbol,timeframei,ix + 1) > bsmaxi )  
       // set to "i+1" to be able to read out the counted bars till next bars open   
          counthigh = 0;     // counter set back to zero 
          
       if ( iClose(cymbol, timeframei, ix + 1 ) < bsmini )      
       // set to "i+1" to be able to read out the counted bars till next bars open
          countlow = 0;                     // counter set back to zero  
           
       if ( iClose(cymbol,timeframei,ix ) < bsmax ) // close less than red
          
          counthigh++; 
          
       if ( iClose(cymbol,timeframei,ix ) > bsmin ) // close greater than green
          
          countlow++;  
           
       }
   if(countlow > counthigh) tidanegreen = true; //green    
   if(countlow < counthigh) tidanered = true; //red    
   if(tidanered) return(true);
    return(false);
 }
//+----------a--------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double TidaneGreenPricei(string cymbol,int timeframei, int Lengthi,int Deviationi)
 {
   int  ix;
   double smax=0;double smin=0;double bsmax=0;double bsmin=0;
   double smaxi=0;double smini=0; double bsmaxi=0; double bsmini=0;
   for(ix = Nbars-Lengthi-1; ix >=0; ix--)
      {
      
     smax=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER,ix);
	  smin=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER,ix);
     
     smaxi=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER, ix + 1);
	  smini=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER, ix + 1);

	  	  
	  bsmax =smax + 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Upper Tidane current RED
	  bsmin =smin - 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Lower Tidane current GREEN
		
	  bsmaxi =smaxi + 0.5 * (MoneyRisk-1) * (smaxi -smini );// Upper Tidane previous bar RED
	  bsmini =smini - 0.5 * (MoneyRisk-1) * (smaxi -smini );// Lower Tidane previous bar GREEN
           
       }
   return(bsmin);
 }
//+----------a--------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double TidaneRedPricei(string cymbol,int timeframei, int Lengthi,int Deviationi)
 {
   int  ix;
   double smax=0;double smin=0;double bsmax=0;double bsmin=0;
   double smaxi=0;double smini=0; double bsmaxi=0; double bsmini=0;
   for(ix = Nbars-Lengthi-1; ix >=0; ix--)
      {
      
     smax=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER,ix);
	  smin=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER,ix);
     
     smaxi=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_UPPER, ix + 1);
	  smini=iBands(cymbol,timeframei,Lengthi,Deviationi,0,PRICE_CLOSE,MODE_LOWER, ix + 1);

	  	  
	  bsmax =smax + 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Upper Tidane current RED
	  bsmin =smin - 0.5 * ( MoneyRisk - 1 ) * ( smax -smin );//Lower Tidane current GREEN
		
	  bsmaxi =smaxi + 0.5 * (MoneyRisk-1) * (smaxi -smini );// Upper Tidane previous bar RED
	  bsmini =smini - 0.5 * (MoneyRisk-1) * (smaxi -smini );// Lower Tidane previous bar GREEN
           
       }
   return(bsmax);
 }

/*double GetMa(string symbol,int tf,int period,int mashift,int method,int ap,int shift)
{
   return(iMA(symbol, tf, period, mashift, method, ap, shift) );
}*///End double GetMa(int tf, int period, int mashift, int method, int ap, int shift)

double GetHiDonn(string cymbol, int tf, int channelperiod, int shift)
{

   //Returns the value of atr

      int hii = iHighest(cymbol,tf,MODE_HIGH,channelperiod,shift);
      double hi=iHigh(cymbol,tf,hii);     

   return( hi );   

}//End double GetAtr()
double GetLoDonn(string cymbol, int tf, int channelperiod, int shift)
{

   //Returns the value of atr
      int loi = iLowest(cymbol,tf,MODE_LOW,channelperiod,shift);
      double lo=iLow(cymbol,tf,loi);    

   return( lo );   

}//End double GetAtr()

double GetMidDonn(string cymbol, int tf, int channelperiod, int shift)
{

   //Returns the value of atr
   double hi = ( GetHiDonn(cymbol,tf,channelperiod,shift) + GetLoDonn(cymbol,tf,channelperiod,shift) ) / 2 ;

   return( NormalizeDouble( hi, Digits ) );   

}//End double GetAtr()

double GetAtr(string symbol, int tf, int period, int shift)
{
   //Returns the value of atr
   
   return(iATR(symbol, tf, period, shift) );   

}//End double GetAtr()


double GetCci(int tf, int period, int ap, int shift)
{// from aurora round number eas
   return(iCCI(Symbol(), tf, period, ap, shift) );
}//double GetCci(int tf, int period, int ap, int shift)


double GetStoch(int tf, int k_period, int d_period, int slowing, int method,int mode, int shift)
{// from aurora round number eas
   return(iStochastic(Symbol(), tf, k_period, d_period, slowing, method, 0, mode, shift) );
}//double GetCci(int tf, int period, int ap, int shift)

double GetAO(int tf, int shift)
{// from dsumgums zwesome accelerator EA
   return (iAO(NULL, tf, shift));
}//End double GetAO(int tf, int period, int shift)

double GetAC(int tf, int shift)
{
   return (iAC(NULL, tf, shift));
}//End double GetAC(int tf, int period, int shift)

//+------------------------------------------------------------------+
//| GetSlope()                                                       |
//+------------------------------------------------------------------+
double GetSuperSlope(string symbol, int tf, int maperiod, int atrperiod, int pShift )
{
   double dblTma, dblPrev;
   int shiftWithoutSunday = pShift;
   if ( BrokerHasSundayCandles && PERIOD_CURRENT == PERIOD_D1 )
   {
      if ( TimeDayOfWeek( iTime( symbol, PERIOD_D1, pShift ) ) == 0  ) shiftWithoutSunday++;
   }   

   double atr = iATR( symbol, tf, atrperiod, shiftWithoutSunday + 10 ) / 10;
   double result = 0.0;
   if ( atr != 0 )
   {
      dblTma = iMA( symbol, tf, maperiod, 0, MODE_LWMA, PRICE_CLOSE, shiftWithoutSunday );
      dblPrev = ( iMA( symbol, tf, maperiod, 0, MODE_LWMA, PRICE_CLOSE, shiftWithoutSunday + 1 ) * 231 + iClose( symbol, tf, shiftWithoutSunday ) * 20 ) / 251;

      result = ( dblTma - dblPrev ) / atr;
   }
   
   return ( result );
   
}//GetSuperSlope(}
//+------------------------------------------------------------------+

void GetAverageSpread()
{

//   ************************* added for OBJ_LABEL
   DisplayCount = 1;
   removeAllObjects();
//   *************************

   static double SpreadTotal=0;
   AverageSpread=0;

   //Add spread to total and keep track of the ticks
   double Spread=(Ask-Bid)*factor;
   SpreadTotal+=Spread;
   CountedTicks++;

   //All ticks counted?
   if(CountedTicks>=TicksToCount)
   {
      AverageSpread=NormalizeDouble(SpreadTotal/TicksToCount,1);
      //Save the average for restarts.
      GlobalVariableSet(SpreadGvName,AverageSpread);
      RunInSpreadDetectionMode=false;
   }//if (CountedTicks >= TicksToCount)


}//void GetAverageSpread()

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeleteBuyPendingOrders()
 {bool result;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_BUYSTOP){
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
void DeleteSellPendingOrders()
{ bool result;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_SELLSTOP){
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
void DeleteBuyOrder( int ticketNo)
 {bool result;
    double slippage=MaxSlippagePips*MathPow(10,Digits)/factor;

 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_BUY)
      {    while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderClose(ticketNo,OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),slippage,Violet);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
 
void DeleteSellOrder( int ticketNo)
{ bool result;
   double slippage=MaxSlippagePips*MathPow(10,Digits)/factor;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_SELL){
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderClose(ticketNo,OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),slippage,Violet);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
void DeleteBuyOrders()
 {bool result;
    double slippage=MaxSlippagePips*MathPow(10,Digits)/factor;

 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_BUY)
      {    while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),slippage,Violet);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
 
void DeleteSellOrders()
{ bool result;
   double slippage=MaxSlippagePips*MathPow(10,Digits)/factor;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_SELL){
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),slippage,Violet);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
void DeleteBuyStopOrders()
 {bool result;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_BUYSTOP  ) 
      {
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
void DeleteSellStopOrders()
{ bool result;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_SELLSTOP  )
      {
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
void DeleteBuyLimitOrders()
 {bool result;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if(  OrderType () == OP_BUYLIMIT ) 
      {
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}
void DeleteSellLimitOrders()
{ bool result;
 for(int i=OrdersTotal()-1; i>=0; i--){
      if (!BetterOrderSelect(i, SELECT_BY_POS, MODE_TRADES) ) 
         {  Print("Order Select Failed!");
                     continue; }
      //Ensure the trade is still open
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if( OrderType () == OP_SELLLIMIT )
      {
         while( !IsTradeAllowed() )
            Sleep(1000);
         result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  i++;
                 // OpenTrades--;
               }//(result) 
                        }
        }}

void ReadIndicatorValues()
{

   int cc = 0;
   
   //Declare a shift for use with indicators.
   int shift = 0;
   if (!EveryTickMode)
   {
      shift = 1;
   }//if (!EveryTickMode)

   
   //Declare a datetime variable to force cca reading only at the open of a new candle.
   static datetime OldCcaReadTime = 0;
   //Accommodate every tick mode
   if (EveryTickMode)
      OldCcaReadTime = 0;
   
   //Allow easy experimentation.
   //shift = 2;
   
   /////////////////////////////////////////////////////////////////////////////////////
   //Read indicators for the system being coded and put them together into a trade signal
   if (OldCcaReadTime != iTime(Symbol(), TradingTimeFrame, 0) )
   {
      OldCcaReadTime = iTime(Symbol(), TradingTimeFrame, 0);
    
      ///////////////////////////////////////
      //Indi reading code goes here

      //Super Slope
      //HTF SS
      //Read at the open of each new TradingTimeFrame in case it has changed colour
   //Hidden HGI code
   
      //Read HGI at the open of each new HgiTimeFrame candle

   /////////////////////////////////////////////////////////////////////////////////////
      
      //Do we have a trade signal
      BuySignal = false;
      SellSignal = false;
      //Code to compare all the indi values and generate a signal if they all pass
      
                       
          //Close trades on an opposite direction signal
      BuyCloseSignal = false;
      SellCloseSignal = false;
      
     // if (BuySignal)
     //    SellCloseSignal = true;
      
     // if (SellSignal)
     //    BuyCloseSignal = true;
   
   }//if (OldCcaReadTime != iTime(Symbol(), TradingTimeFrame, 0) )   
         
   

}//void ReadIndicatorValues()
//End Indicator module
////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////
///+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseAllTrades(int type)
{

   ForceTradeClosure= false;
   
   if (OrdersTotal() == 0) return;
   
   bool result = false;
   for (int pass = 0; pass <= 1; pass++)
   {
      if (OrdersTotal() == 0 || OpenTrades == 0)
         break;
      for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
      {
         if (!BetterOrderSelect(FifoTicket[cc], SELECT_BY_TICKET, MODE_TRADES) ) continue;
         if (OrderMagicNumber() != MagicNumber) continue;
         if (OrderSymbol() != Symbol() ) continue;
         if (OrderType() != type) 
            if (type != AllTrades)
               continue;
         
         while(IsTradeContextBusy()) Sleep(100);
         if (OrderType() < 2)
         {
            result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 1000, CLR_NONE);
            if (result) 
            {
               cc++;
               OpenTrades--;
            }//(result) 
            
            if (!result) ForceTradeClosure= true;
         }//if (OrderType() < 2)
         
         if (pass == 1)
            if (OrderType() > 1) 
            {
               result = OrderDelete(OrderTicket(), clrNONE);
               if (result) 
               {
                  cc++;
                  OpenTrades--;
               }//(result) 
               if (!result) ForceTradeClosure= true;
            }//if (OrderType() > 1) 
            
      }//for (int cc = ArraySize(FifoTicket) - 1; cc >= 0; cc--)
   }//for (int pass = 0; pass <= 1; pass++)
   
   //If full closure succeeded, then allow new trading
   if (!ForceTradeClosure) 
   {
      OpenTrades = 0;
      BuyOpen = false;
      SellOpen = false;
   }//if (!ForceTradeClosure) 


}//End void CloseAllTradesFifo()
///+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool CheckTradingTimes() 
{

	// Trade 24 hours if no input is given
	if ( ArraySize( tradeHours ) == 0 ) return ( true );

	// Get local time in minutes from midnight
    int time = TimeHour( TimeLocal() ) * 60 + TimeMinute( TimeLocal() );
   
	// Don't you love this?
	int i = 0;
	while ( time >= tradeHours[i] ) 
	{	
		i++;		
		if ( i == ArraySize( tradeHours ) ) break;
	}
	if ( i % 2 == 1 ) return ( true );
	return ( false );
}//End bool CheckTradingTimes2() 
//+------------------------------------------------------------------+
//| Initialize Trading Hours Array                                   |
//+------------------------------------------------------------------+
bool initTradingHours() 
{
   // Called from init()
   
	// Assume 24 trading if no input found
	if ( tradingHours == "" )	
	{
		ArrayResize( tradeHours, 0 );
		return ( true );
	}

	int i;

	// Add 00:00 start time if first element is stop time
	if ( StringSubstrOld( tradingHours, 0, 1 ) == "-" ) 
	{
		tradingHours = StringConcatenate( "+0,", tradingHours );   
	}
	
	// Add delimiter
	if ( StringSubstrOld( tradingHours, StringLen( tradingHours ) - 1) != "," ) 
	{
		tradingHours = StringConcatenate( tradingHours, "," );   
	}
	
	string lastPrefix = "-";
	i = StringFind( tradingHours, "," );
	
	while (i != -1) 
	{

		// Resize array
		int size = ArraySize( tradeHours );
		ArrayResize( tradeHours, size + 1 );

		// Get part to process
		string part = StringSubstrOld( tradingHours, 0, i );

		// Check start or stop prefix
		string prefix = StringSubstrOld ( part, 0, 1 );
		if ( prefix != "+" && prefix != "-" ) 
		{
			Print("ERROR IN TRADINGHOURS INPUT (NO START OR CLOSE FOUND), ASSUME 24HOUR TRADING.");
			ArrayResize ( tradeHours, 0 );
			return ( true );
		}

		if ( ( prefix == "+" && lastPrefix == "+" ) || ( prefix == "-" && lastPrefix == "-" ) )	
		{
			Print("ERROR IN TRADINGHOURS INPUT (START OR CLOSE IN WRONG ORDER), ASSUME 24HOUR TRADING.");
			ArrayResize ( tradeHours, 0 );
			return ( true );
		}
		
		lastPrefix = prefix;

		// Convert to time in minutes
		part = StringSubstrOld( part, 1 );
		double time = StrToDouble( part );
		int hour = MathFloor( time );
		int minutes = MathRound( ( time - hour ) * 100 );

		// Add to array
		tradeHours[size] = 60 * hour + minutes;

		// Trim input string
		tradingHours = StringSubstrOld( tradingHours, i + 1 );
		i = StringFind( tradingHours, "," );
	}//while (i != -1) 

	return ( true );
}//End bool initTradingHours() 

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CountOpenTrades()
{
   //Not all these will be needed. Which ones are depends on the individual EA.
   //Market Buy trades
   BuyOpen=false;
   MarketBuysCount=0;
   LatestBuyPrice=0; EarliestBuyPrice=0; HighestBuyPrice=0; LowestBuyPrice=million;
   BuyTicketNo=-1; HighestBuyTicketNo=-1; LowestBuyTicketNo=-1; LatestBuyTicketNo=-1; EarliestBuyTicketNo=-1;
   BuyPipsUpl=0;
   BuyCashUpl=0;
   LatestBuyTradeTime=0;
   EarliestBuyTradeTime=TimeCurrent();
   
   //Market Sell trades
   SellOpen=false;
   MarketSellsCount=0;
   LatestSellPrice=0; EarliestSellPrice=0; HighestSellPrice=0; LowestSellPrice=million;
   SellTicketNo=-1; HighestSellTicketNo=-1; LowestSellTicketNo=-1; LatestSellTicketNo=-1; EarliestSellTicketNo=-1;;
   SellPipsUpl=0;
   SellCashUpl=0;
   LatestSellTradeTime=0;
   EarliestSellTradeTime=TimeCurrent();
   
   //BuyStop trades
   BuyStopOpen=false;
   BuyStopsCount=0;
   LatestBuyStopPrice=0; EarliestBuyStopPrice=0; HighestBuyStopPrice=0; LowestBuyStopPrice=million;
   BuyStopTicketNo=-1; HighestBuyStopTicketNo=-1; LowestBuyStopTicketNo=-1; LatestBuyStopTicketNo=-1; EarliestBuyStopTicketNo=-1;;
   LatestBuyStopTradeTime=0;
   EarliestBuyStopTradeTime=TimeCurrent();
   
   //BuyLimit trades
   BuyLimitOpen=false;
   BuyLimitsCount=0;
   LatestBuyLimitPrice=0; EarliestBuyLimitPrice=0; HighestBuyLimitPrice=0; LowestBuyLimitPrice=million;
   BuyLimitTicketNo=-1; HighestBuyLimitTicketNo=-1; LowestBuyLimitTicketNo=-1; LatestBuyLimitTicketNo=-1; EarliestBuyLimitTicketNo=-1;;
   LatestBuyLimitTradeTime=0;
   EarliestBuyLimitTradeTime=TimeCurrent();
   
   /////SellStop trades
   SellStopOpen=false;
   SellStopsCount=0;
   LatestSellStopPrice=0; EarliestSellStopPrice=0; HighestSellStopPrice=0; LowestSellStopPrice=million;
   SellStopTicketNo=-1; HighestSellStopTicketNo=-1; LowestSellStopTicketNo=-1; LatestSellStopTicketNo=-1; EarliestSellStopTicketNo=-1;;
   LatestSellStopTradeTime=0;
   EarliestSellStopTradeTime=TimeCurrent();
   
   //SellLimit trades
   SellLimitOpen=false;
   SellLimitsCount=0;
   LatestSellLimitPrice=0; EarliestSellLimitPrice=0; HighestSellLimitPrice=0; LowestSellLimitPrice=million;
   SellLimitTicketNo=-1; HighestSellLimitTicketNo=-1; LowestSellLimitTicketNo=-1; LatestSellLimitTicketNo=-1; EarliestSellLimitTicketNo=-1;;
   LatestSellLimitTradeTime=0;
   EarliestSellLimitTradeTime=TimeCurrent();
   
   //Not related to specific order types
   MarketTradesTotal = 0;
   TicketNo=-1;OpenTrades=0;
   LatestTradeTime=0; EarliestTradeTime=TimeCurrent();//More specific times are in each individual section
   LatestTradeTicketNo=-1; EarliestTradeTicketNo=-1;
   PipsUpl=0;//For keeping track of the pips PipsUpl of multi-trade/hedged positions
   CashUpl=0;//For keeping track of the cash PipsUpl of multi-trade/hedged positions

   
   //FIFO ticket resize
   ArrayResize(FifoTicket, 0);
   
      
   
   int type;//Saves the OrderType() for consulatation later in the function
   
   
   if (OrdersTotal() == 0) return;
   
   //Iterating backwards through the orders list caters more easily for closed trades than iterating forwards
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      bool TradeWasClosed = false;//See 'check for possible trade closure'

      //Ensure the trade is still open
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_TRADES) ) continue;
      //Ensure the EA 'owns' this trade
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderCloseTime() > 0) continue; 
      
      //The time of the most recent trade
      if (OrderOpenTime() > LatestTradeTime)
      {
         LatestTradeTime = OrderOpenTime();
         LatestTradeTicketNo = OrderTicket();
      }//if (OrderOpenTime() > LatestTradeTime)
      
      //The time of the earliest trade
      if (OrderOpenTime() < EarliestTradeTime)
      {
         EarliestTradeTime = OrderOpenTime();
         EarliestTradeTicketNo = OrderTicket();
      }//if (OrderOpenTime() < EarliestTradeTime)
      
      //All conditions passed, so carry on
      type = OrderType();//Store the order type
      
      if (!CloseEnough(OrderTakeProfit(), 0) )
         TpSet = true;
      if (!CloseEnough(OrderStopLoss(), 0) )
         SlSet = true;

      OpenTrades++;
      //Store the latest trade sent. Most of my EA's only need this final ticket number as either they are single trade
      //bots or the last trade in the sequence is the important one. Adapt this code for your own use.
      if (TicketNo  == -1) TicketNo = OrderTicket();
      
      //Store ticket numbers for FIFO
      ArrayResize(FifoTicket, OpenTrades + 1);
      FifoTicket[OpenTrades] = OrderTicket();
      
      
      //The next line of code calculates the pips upl of an open trade. As yet, I have done nothing with it.
      //something = CalculateTradeProfitInPips()
      
      double pips = 0;
      
      //Buile up the position picture of market trades
      if (OrderType() < 2)
      {
         CashUpl+= (OrderProfit() + OrderSwap() + OrderCommission()); 
         MarketTradesTotal++;
         pips = CalculateTradeProfitInPips(OrderType());
         PipsUpl+= pips;
         
         //Buys
         if (OrderType() == OP_BUY)
         {
            BuyOpen = true;
            BuyTicketNo = OrderTicket();
            MarketBuysCount++;
            BuyPipsUpl+= pips;
            BuyCashUpl+= (OrderProfit() + OrderSwap() + OrderCommission()); 
            
            //Latest trade
            if (OrderOpenTime() > LatestBuyTradeTime)
            {
               LatestBuyTradeTime = OrderOpenTime();
               LatestBuyPrice = OrderOpenPrice();
               LatestBuyTicketNo = OrderTicket();
            }//if (OrderOpenTime() > LatestBuyTradeTime)  
 
            //Furthest back in time
            if (OrderOpenTime() < EarliestBuyTradeTime)
            {
               EarliestBuyTradeTime = OrderOpenTime();
               EarliestBuyPrice = OrderOpenPrice();
               EarliestBuyTicketNo = OrderTicket();
            }//if (OrderOpenTime() < EarliestBuyTradeTime)
            
            //Highest trade price
            if (OrderOpenPrice() > HighestBuyPrice)
            {
               HighestBuyPrice = OrderOpenPrice();
               HighestBuyTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > HighestBuyPrice)
            
            //Lowest trade price
            if (OrderOpenPrice() < LowestBuyPrice)
            {
               LowestBuyPrice = OrderOpenPrice();
               LowestBuyTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > LowestBuyPrice)
              
         }//if (OrderType() == OP_BUY)
         
         //Sells
         if (OrderType() == OP_SELL)
         {
            SellOpen = true;
            SellTicketNo = OrderTicket();
            MarketSellsCount++;
            SellPipsUpl+= pips;
            SellCashUpl+= (OrderProfit() + OrderSwap() + OrderCommission()); 
            
            //Latest trade
            if (OrderOpenTime() > LatestSellTradeTime)
            {
               LatestSellTradeTime = OrderOpenTime();
               LatestSellPrice = OrderOpenPrice();
               LatestSellTicketNo = OrderTicket();
            }//if (OrderOpenTime() > LatestSellTradeTime)  
 
            //Furthest back in time
            if (OrderOpenTime() < EarliestSellTradeTime)
            {
               EarliestSellTradeTime = OrderOpenTime();
               EarliestSellPrice = OrderOpenPrice();
               EarliestSellTicketNo = OrderTicket();
            }//if (OrderOpenTime() < EarliestSellTradeTime)
            
            //Highest trade price
            if (OrderOpenPrice() > HighestSellPrice)
            {
               HighestSellPrice = OrderOpenPrice();
               HighestSellTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > HighestSellPrice)
            
            //Lowest trade price
            if (OrderOpenPrice() < LowestSellPrice)
            {
               LowestSellPrice = OrderOpenPrice();
               LowestSellTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > LowestSellPrice)
              
         }//if (OrderType() == OP_SELL)
         
         
      }//if (OrderType() < 2)
      
      
      //Build up the position details of stop/limit orders
      if (OrderType() > 1)
      {
         //Buystops
         if (OrderType() == OP_BUYSTOP)
         {
            BuyStopOpen = true;
            BuyStopTicketNo = OrderTicket();
            BuyStopsCount++;
            
            //Latest trade
            if (OrderOpenTime() > LatestBuyStopTradeTime)
            {
               LatestBuyStopTradeTime = OrderOpenTime();
               LatestBuyStopPrice = OrderOpenPrice();
               LatestBuyStopTicketNo = OrderTicket();
            }//if (OrderOpenTime() > LatestBuyStopTradeTime)  
 
            //Furthest back in time
            if (OrderOpenTime() < EarliestBuyStopTradeTime)
            {
               EarliestBuyStopTradeTime = OrderOpenTime();
               EarliestBuyStopPrice = OrderOpenPrice();
               EarliestBuyStopTicketNo = OrderTicket();
            }//if (OrderOpenTime() < EarliestBuyStopTradeTime)
            
            //Highest trade price
            if (OrderOpenPrice() > HighestBuyStopPrice)
            {
               HighestBuyStopPrice = OrderOpenPrice();
               HighestBuyStopTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > HighestBuyStopPrice)
            
            //Lowest trade price
            if (OrderOpenPrice() < LowestBuyStopPrice)
            {
               LowestBuyStopPrice = OrderOpenPrice();
               LowestBuyStopTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > LowestBuyStopPrice)
              
         }//if (OrderType() == OP_BUYSTOP)
         
         //Sellstops
         if (OrderType() == OP_SELLSTOP)
         {
            SellStopOpen = true;
            SellStopTicketNo = OrderTicket();
            SellStopsCount++;
            
            //Latest trade
            if (OrderOpenTime() > LatestSellStopTradeTime)
            {
               LatestSellStopTradeTime = OrderOpenTime();
               LatestSellStopPrice = OrderOpenPrice();
               LatestSellStopTicketNo = OrderTicket();
            }//if (OrderOpenTime() > LatestSellStopTradeTime)  
 
            //Furthest back in time
            if (OrderOpenTime() < EarliestSellStopTradeTime)
            {
               EarliestSellStopTradeTime = OrderOpenTime();
               EarliestSellStopPrice = OrderOpenPrice();
               EarliestSellStopTicketNo = OrderTicket();
            }//if (OrderOpenTime() < EarliestSellStopTradeTime)
            
            //Highest trade price
            if (OrderOpenPrice() > HighestSellStopPrice)
            {
               HighestSellStopPrice = OrderOpenPrice();
               HighestSellStopTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > HighestSellStopPrice)
            
            //Lowest trade price
            if (OrderOpenPrice() < LowestSellStopPrice)
            {
               LowestSellStopPrice = OrderOpenPrice();
               LowestSellStopTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > LowestSellStopPrice)
              
         }//if (OrderType() == OP_SELLSTOP)
         
         //Buy limits
         if (OrderType() == OP_BUYLIMIT)
         {
            BuyLimitOpen = true;
            BuyLimitTicketNo = OrderTicket();
            BuyLimitsCount++;
            
            //Latest trade
            if (OrderOpenTime() > LatestBuyLimitTradeTime)
            {
               LatestBuyLimitTradeTime = OrderOpenTime();
               LatestBuyLimitPrice = OrderOpenPrice();
               LatestBuyLimitTicketNo = OrderTicket();
            }//if (OrderOpenTime() > LatestBuyLimitTradeTime)  
 
            //Furthest back in time
            if (OrderOpenTime() < EarliestBuyLimitTradeTime)
            {
               EarliestBuyLimitTradeTime = OrderOpenTime();
               EarliestBuyLimitPrice = OrderOpenPrice();
               EarliestBuyLimitTicketNo = OrderTicket();
            }//if (OrderOpenTime() < EarliestBuyLimitTradeTime)
            
            //Highest trade price
            if (OrderOpenPrice() > HighestBuyLimitPrice)
            {
               HighestBuyLimitPrice = OrderOpenPrice();
               HighestBuyLimitTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > HighestBuyLimitPrice)
            
            //Lowest trade price
            if (OrderOpenPrice() < LowestBuyLimitPrice)
            {
               LowestBuyLimitPrice = OrderOpenPrice();
               LowestBuyLimitTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > LowestBuyLimitPrice)
              
         }//if (OrderType() == OP_BUYLIMIT)
         
         //Sell limits
         if (OrderType() == OP_SELLLIMIT)
         {
            SellLimitOpen = true;
            SellLimitTicketNo = OrderTicket();
            SellLimitsCount++;
            
            //Latest trade
            if (OrderOpenTime() > LatestSellLimitTradeTime)
            {
               LatestSellLimitTradeTime = OrderOpenTime();
               LatestSellLimitPrice = OrderOpenPrice();
               LatestSellLimitTicketNo = OrderTicket();
            }//if (OrderOpenTime() > LatestSellLimitTradeTime)  
 
            //Furthest back in time
            if (OrderOpenTime() < EarliestSellLimitTradeTime)
            {
               EarliestSellLimitTradeTime = OrderOpenTime();
               EarliestSellLimitPrice = OrderOpenPrice();
               EarliestSellLimitTicketNo = OrderTicket();
            }//if (OrderOpenTime() < EarliestSellLimitTradeTime)
            
            //Highest trade price
            if (OrderOpenPrice() > HighestSellLimitPrice)
            {
               HighestSellLimitPrice = OrderOpenPrice();
               HighestSellLimitTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > HighestSellLimitPrice)
            
            //Lowest trade price
            if (OrderOpenPrice() < LowestSellLimitPrice)
            {
               LowestSellLimitPrice = OrderOpenPrice();
               LowestSellLimitTicketNo = OrderTicket();
            }//if (OrderOpenPrice() > LowestSellLimitPrice)
              
         }//if (OrderType() == OP_SELLLIMIT)
         
      
      }//if (OrderType() > 1)
      
      
      
      
      //Add missing tp/sl in case rapidly moving markets prevent their addition - ECN
 
      //Replace missing tp and sl lines
      if (HiddenPips > 0) ReplaceMissingSlTpLines();
      
         
               
      
   }//for (int cc = OrdersTotal() - 1; cc <= 0; c`c--)
   
   //Sort ticket numbers for FIFO
   if (ArraySize(FifoTicket) > 0)
      ArraySort(FifoTicket, WHOLE_ARRAY, 0, MODE_DESCEND);
      
   
             if (OrderProfit() > 0 && UseTrailStop ) 
           {
            SetBEAndJump(OrderTicket());
           }
         //if (OrderStopLoss() == 0  && UseTrailStop)  InsertStopLoss(OrderTicket());

    
}//End void CountOpenTrades();
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
////////////////////////////////////////////////////////////////////////////////////////
//Pending trade price lines module.
//Doubles up by providing missing lines for the stealth stuff
void DrawPendingPriceLines()
{
   //This function will work for a full pending-trade EA.
   //The pending tp/sl can be used for hiding the stops in a market-trading ea
   
   /*
   ObjectDelete(pendingpriceline);
   ObjectCreate(pendingpriceline, OBJ_HLINE, 0, TimeCurrent(), PendingPrice);
   if (PendingBuy) ObjectSet(pendingpriceline, OBJPROP_COLOR, Green);
   if (PendingSell) ObjectSet(pendingpriceline, OBJPROP_COLOR, Red);
   ObjectSet(pendingpriceline, OBJPROP_WIDTH, 1);
   ObjectSet(pendingpriceline, OBJPROP_STYLE, STYLE_DASH);
   */
   string LineName = TpPrefix + DoubleToStr(TicketNo, 0);//TicketNo is set by the calling function - either CountOpenTrades or DoesTradeExist
   HiddenTakeProfit = 0;
   if (TicketNo > -1 && OrderTakeProfit() > 0)
   {
      if (OrderType() == OP_BUY || OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT)
      {
         HiddenTakeProfit = NormalizeDouble(OrderTakeProfit() - (HiddenPips / factor), Digits);
      }//if (OrderType() == OP_BUY)
      
      if (OrderType() == OP_SELL)
      {
         HiddenTakeProfit = NormalizeDouble(OrderTakeProfit() + (HiddenPips / factor), Digits);
      }//if (OrderType() == OP_BUY)      
   }//if (TicketNo > -1 && OrderTakeProfit() > 0)
   
   if (HiddenTakeProfit > 0 && ObjectFind(LineName) == -1)
   {
      ObjectDelete(LineName);
      ObjectCreate(LineName, OBJ_HLINE, 0, TimeCurrent(), HiddenTakeProfit);
      ObjectSet(LineName, OBJPROP_COLOR, Green);
      ObjectSet(LineName, OBJPROP_WIDTH, 1);
      ObjectSet(LineName, OBJPROP_STYLE, STYLE_DOT);
   }//if (HiddenTakeProfit > 0)
   
   
   LineName = SlPrefix + DoubleToStr(TicketNo, 0);//TicketNo is set by the calling function - either CountOpenTrades or DoesTradeExist
   HiddenStopLoss = 0;
   if (TicketNo > -1 && OrderStopLoss() > 0)
   {
      if (OrderType() == OP_BUY || OrderType() == OP_BUYSTOP || OrderType() == OP_BUYLIMIT)
      {
         HiddenStopLoss = NormalizeDouble(OrderStopLoss() + (HiddenPips / factor), Digits);
      }//if (OrderType() == OP_BUY)
      
      if (OrderType() == OP_SELL || OrderType() == OP_SELLSTOP || OrderType() == OP_SELLLIMIT)
      {
         HiddenStopLoss = NormalizeDouble(OrderStopLoss() - (HiddenPips / factor), Digits);
      }//if (OrderType() == OP_BUY)      
   }//if (TicketNo > -1 && OrderStopLoss() > 0)
   
   if (HiddenStopLoss > 0 && ObjectFind(LineName) == -1)
   {
      ObjectDelete(LineName);
      ObjectCreate(LineName, OBJ_HLINE, 0, TimeCurrent(), HiddenStopLoss);
      ObjectSet(LineName, OBJPROP_COLOR, Red);
      ObjectSet(LineName, OBJPROP_WIDTH, 1);
      ObjectSet(LineName, OBJPROP_STYLE, STYLE_DOT);
   }//if (HiddenStopLoss > 0)
   
   

}//End void DrawPendingPriceLines()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeletePendingPriceLines()
{

   //ObjectDelete(pendingpriceline);
   string LineName=TpPrefix+DoubleToStr(TicketNo,0);
   ObjectDelete(LineName);
   LineName=SlPrefix+DoubleToStr(TicketNo,0);
   ObjectDelete(LineName);

}//End void DeletePendingPriceLines()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void ReplaceMissingSlTpLines()
{

   if(OrderTakeProfit()>0 || OrderStopLoss()> 0) DrawPendingPriceLines();

}//End void ReplaceMissingSlTpLines()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeleteOrphanTpSlLines()
{

   if (ObjectsTotal() == 0) return;
   
   for (int cc = ObjectsTotal() - 1; cc >= 0; cc--)
   {
      string name = ObjectName(cc);
      
      if ((StringSubstrOld(name, 0, 2) == TpPrefix || StringSubstrOld(name, 0, 2) == SlPrefix) && ObjectType(name) == OBJ_HLINE)
      {
         int tn = StrToDouble(StringSubstrOld(name, 2));
         if (tn > 0) 
         {
            if (!BetterOrderSelect(tn, SELECT_BY_TICKET, MODE_TRADES) || OrderCloseTime() > 0)
            {
               ObjectDelete(name);
            }//if (!BetterOrderSelect(tn, SELECT_BY_TICKET, MODE_TRADES) || OrderCloseTime() > 0)
            
         }//if (tn > 0) 
         
         
      }//if (StringSubstrOld(name, 0, 1) == TpPrefix)
      
   }//for (int cc = ObjectsTotal() - 1; cc >= 0; cc--)
   
   
}//End void DeleteOrphanTpSlLines()

//END Pending trade price lines module
////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////
//TRADE MANAGEMENT MODULE

void ReportError(string function, string message)
{
   //All purpose sl mod error reporter. Called when a sl mod fails
   
   int err=GetLastError();
   if (err == 1) return;//That bloody 'error but no error' report is a nuisance
   
      
   Alert(WindowExpertName(), " ", OrderTicket(), " ", function, message, err,": ",ErrorDescription(err));
   Print(WindowExpertName(), " ", OrderTicket(), " ", function, message, err,": ",ErrorDescription(err));
   
}//void ReportError()

bool ModifyOrder(int ticket, double price, double stop, double take, datetime expiry, color col, string function, string reason)
{
   //Multi-purpose order modify function
   
   bool result = OrderModify(ticket, price ,stop , take, expiry, col);

   //Actions when trade close succeeds
   if (result)
   {
      return(true);
   }//if (result)
   
   //Actions when trade close fails
   if (!result)
      ReportError(function, reason);

   //Got this far, so modify failed
   return(false);
   
}// End bool ModifyOrder()
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+++++
//                                        +
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+++++
bool ModifyOrderi( int ticket, double stop )
{
   //Multi-purpose order modify function
   
      bool result = ModifyOrder(ticket, OrderOpenPrice(), stop, OrderTakeProfit(), OrderExpiration(), clrRed, __FUNCTION__, slim);

   //Actions when trade close succeeds
   if (result)
   {
      return(true);
   }//if (result)
   
   //Actions when trade close fails
  // if (!result)
    //  ReportError(function, reason);

   //Got this far, so modify failed
   return(false);
   
}// End bool ModifyOrder()

//|                                                                  |
//+------------------------------------------------------------------+
void TradeManagementModule(int ticket)
{
   // Call the working subroutines one by one. 
}//void TradeManagementModule()
//END TRADE MANAGEMENT MODULE
////////////////////////////////////////////////////////////////////////////////////////
////////////xxxxxxxxxxxxxxxxxxxxxxx////////////////////xxxxxxxxxxxxxxxxxxxxxxxxxxx////////////////////
////////////xxxxxxxxxxxxxxxxxxxxxxx////////////////////xxxxxxxxxxxxxxxxxxxxxxxxxxx////////////////////


double CalculateTradeProfitInUpl(int type)
{
   //This code supplied by Lifesys. Many thanks Paul.
   
   //Returns the pips Upl of the currently selected trade. Called by CountOpenTrades()
   double profit;

   if (type == OP_BUY)
   {
      profit = (OrderProfit() + OrderSwap() + OrderCommission());
   }//if (OrderType() == OP_BUY)

   if (type == OP_SELL)
   {
      profit = (OrderProfit() + OrderSwap() + OrderCommission());
   }//if (OrderType() == OP_SELL)

   return(profit); // in real pips
}//double CalculateTradeProfitInP


double CalculateTradeProfitInPips(int type)
{
   //This code supplied by Lifesys. Many thanks Paul.
   
   //Returns the pips Upl of the currently selected trade. Called by CountOpenTrades()
   double profit;
   // double point = BrokerPoint(OrderSymbol() ); // no real use
   double ask = MarketInfo(OrderSymbol(), MODE_ASK);
   double bid = MarketInfo(OrderSymbol(), MODE_BID);

   if (type == OP_BUY)
   {
      profit = bid - OrderOpenPrice();
   }//if (OrderType() == OP_BUY)

   if (type == OP_SELL)
   {
      profit = OrderOpenPrice() - ask;
   }//if (OrderType() == OP_SELL)
   //profit *= PFactor(OrderSymbol()); // use PFactor instead of point. This line for multi-pair ea's
   profit *= factor; // use PFactor instead of point.

   return(profit); // in real pips
}//double CalculateTradeProfitInPips(int type)
///###++++++++++++++++++++++++++++++++++++#####
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool CloseEnough(double num1,double num2)
{
/*
   This function addresses the problem of the way in which mql4 compares doubles. It often messes up the 8th
   decimal point.
   For example, if A = 1.5 and B = 1.5, then these numbers are clearly equal. Unseen by the coder, mql4 may
   actually be giving B the value of 1.50000001, and so the variable are not equal, even though they are.
   This nice little quirk explains some of the problems I have endured in the past when comparing doubles. This
   is common to a lot of program languages, so watch out for it if you program elsewhere.
   Gary (garyfritz) offered this solution, so our thanks to him.
   */

   if(num1==0 && num2==0) return(true); //0==0
   if(MathAbs(num1 - num2) / (MathAbs(num1) + MathAbs(num2)) < 0.00000001) return(true);

//Doubles are unequal
   return(false);

}//End bool CloseEnough(double num1, double num2)
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int GetPipFactor(string Xsymbol)
{
   //Code from Tommaso's APTM. Thanks Tommaso.
   
   static const string factor1000[]={"SEK","TRY","ZAR","MXN"};
   static const string factor100[]         = {"JPY","XAG","SILVER","BRENT","WTI"};
   static const string factor10[]          = {"XAU","GOLD","SP500","US500Cash","US500","Bund"};
   static const string factor1[]           = {"UK100","WS30","DAX30","NAS100","CAC40","FRA40","GER30","ITA40","EUSTX50","JPN225","US30Cash","US30"};

   int j = 0;
   
   int xFactor=10000;       // correct xFactor for most pairs
   if(MarketInfo(Xsymbol,MODE_DIGITS)<=1) xFactor=1;
   else if(MarketInfo(Xsymbol,MODE_DIGITS)==2) xFactor=10;
   else if(MarketInfo(Xsymbol,MODE_DIGITS)==3) xFactor=100;
   else if(MarketInfo(Xsymbol,MODE_DIGITS)==4) xFactor=1000;
   else if(MarketInfo(Xsymbol,MODE_DIGITS)==5) xFactor=10000;
   else if(MarketInfo(Xsymbol,MODE_DIGITS)==6) xFactor=100000;
   else if(MarketInfo(Xsymbol,MODE_DIGITS)==7) xFactor=1000000;
   for(j=0; j<ArraySize(factor1000); j++)
   {
      if(StringFind(Xsymbol,factor1000[j])!=-1) xFactor=1000;
   }
   for(j=0; j<ArraySize(factor100); j++)
   {
      if(StringFind(Xsymbol,factor100[j])!=-1) xFactor=100;
   }
   for(j=0; j<ArraySize(factor10); j++)
   {
      if(StringFind(Xsymbol,factor10[j])!=-1) xFactor=10;
   }
   for(j=0; j<ArraySize(factor1); j++)
   {
      if(StringFind(Xsymbol,factor1[j])!=-1) xFactor=1;
   }

   return (xFactor);
}//End int GetPipFactor(string Xsymbol)

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool TooClose()
{
   //Returns false if the previously closed trade and the proposed new trade are sufficiently far apart, else return true. Called from IsTradeAllowed().
   
   SafetyViolation = false;//For chart feedback
         
   if (OrdersHistoryTotal() == 0) return(false);
   
   for (int cc = OrdersHistoryTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS, MODE_HISTORY) ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderType() > 1) continue;
      
      
      //Examine the OrderCloseTime to see if it closed far enought back in time.
      if (TimeCurrent() - OrderCloseTime() < (MinMinutesBetweenTrades * 60))
      {
         SafetyViolation = true;
         return(true);//Too close, so disallow the trade
      }//if (OrderCloseTime() - TimeCurrent() < (MinMinutesBetweenTrades * 60))
      break;      
   }//for (int cc = OrdersHistoryTotal() - 1; cc >= 0; cc--)
   
   //Got this far, so there is no disqualifying trade in the history
   return(false);
   
}//bool TooClose()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsClosedTradeRogue()
{
   //~ Safety feature. Sometimes an unexpected concatenation of inputs choice and logic error can cause rapid opening-closing of trades. Detect a closed trade and check that is was not a rogue. Examine trades closed within the last 5 minutes.
   
   //~ If it is a rogue:
   //~ * Show a warning alert.
   //~ * Send an email alert.
   //~ * Suspend the robot
   
   if (OrdersHistoryTotal() == 0) return(false);
   
   datetime latestTime = TimeCurrent() - ( 5 * 60 );
  
   datetime duration = -1; //impossible value
  
   //We cannot guarantee that the most recent trade shown in our History tab is actually the most recent on the crim's server - CraptT4 again. pah has supplied this code to ensure that we are examining the latest trade. Many thanks, Paul.
   
   // look for trades that closed within the last 5 minutes
   // otherwise we will always find the last rogue trade
   // even when that happened some time ago and can be ignored
   
   for ( int i = OrdersHistoryTotal()-1; i >= 0; i-- )
   {
      if ( !BetterOrderSelect(i, SELECT_BY_POS, MODE_HISTORY) ) continue;
       
      if ( OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() ) continue;
      if (OrderType() > 1) continue;
        
      if ( OrderCloseTime() >= latestTime )
      {
         latestTime = OrderCloseTime();
         duration    = OrderCloseTime() - OrderOpenTime();
      }//if ( OrderCloseTime() >= latestTime )
       
   }//for ( int i = OrdersHistoryTotal()-1; i >= 0; i-- )
   
  
   bool rogue = ( duration >= 0 ) && ( duration < ( MinMinutesBetweenTradeOpenClose * 60) );
  
   if (rogue)
   {
      RobotSuspended = true;
      Alert(Symbol(), " ", WindowExpertName() , " possible rogue trade.");
      SendMail("Possible rogue trade warning ", Symbol() + " " + WindowExpertName() + " possible rogue trade.");
      Comment(NL, Gap, "****************** ROBOT SUSPENDED. POSSIBLE ROGUE TRADING ACTIVITY. REMOVE THIS EA IMMEDIATELY ****************** ");
      return(true);//Too close, so disallow the trade
   
   }//if (rogue)
   
   //Got this far, so there is no rogue trade
   return(false);
   


}//bool IsClosedTradeRogue()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DrawTrendLine(string name,datetime time1,double value1,datetime time2,double value2,color dColor,int width,int style,bool ray)
  {
//Plots a trendline with the given parameters
   ObjectDelete(name);

   ObjectCreate(name,OBJ_TREND,0,time1,value1,time2,value2);

   ObjectSet(name,OBJPROP_COLOR,dColor);
   ObjectSet(name,OBJPROP_WIDTH,width);
   ObjectSet(name,OBJPROP_STYLE,style);
   ObjectSet(name,OBJPROP_RAY,ray);
         ChartRedraw();

  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DrawHorizontalLine(string name,double price,color col,int style,int width)
{

   ObjectDelete(name);

   ObjectCreate(name,OBJ_HLINE,0,TimeCurrent(),price);
   ObjectSet(name,OBJPROP_COLOR,col);
   ObjectSet(name,OBJPROP_STYLE,style);
   ObjectSet(name,OBJPROP_WIDTH,width);

}//void DrawLine(string name, double price, color col)
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DrawVerticalLine(string name,color col,int style,int width)
{
//ObjectCreate(vline,OBJ_VLINE,0,iTime(NULL, TimeFrame, 0), 0);
   ObjectDelete(name);
   ObjectCreate(name,OBJ_VLINE,0,iTime(NULL,0,0),0);
   ObjectSet(name,OBJPROP_COLOR,col);
   ObjectSet(name,OBJPROP_STYLE,style);
   ObjectSet(name,OBJPROP_WIDTH,width);

}//void DrawVerticalLine()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool MarginCheck()
{

   EnoughMargin = true;//For user display
   MarginMessage = "";
   if (UseScoobsMarginCheck && OpenTrades > 0)
   {
      if(AccountMargin() > (AccountFreeMargin()/100)) 
      {
         MarginMessage = "There is insufficient margin to allow trading. You might want to turn off the UseScoobsMarginCheck input.";
         return(false);
      }//if(AccountMargin() > (AccountFreeMargin()/100)) 
      
   }//if (UseScoobsMarginCheck)


   if (UseForexKiwi && AccountMargin() > 0)
   {
      double ml = NormalizeDouble(AccountEquity() / AccountMargin() * 100, 2);
      if (ml < FkMinimumMarginPercent)
      {
         MarginMessage = StringConcatenate("There is insufficient margin percent to allow trading. ", DoubleToStr(ml, 2), "%");
         return(false);
      }//if (ml < FkMinimumMarginPercent)
   }//if (UseForexKiwi && AccountMargin() > 0)
   
  
   //Got this far, so there is sufficient margin for trading
   return(true);
}//End bool MarginCheck()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string PeriodText(int per)
{

	switch (per)
	{
   	case PERIOD_M1:
   		return("M1");
   	case PERIOD_M5:
   		return("M5");
   	case PERIOD_M15:
   		return("M15");
   	case PERIOD_M30:
   		return("M30");
   	case PERIOD_H1:
   		return("H1");
   	case PERIOD_H4:
   		return("H4");
   	case PERIOD_D1:
   		return("D1");
   	case PERIOD_MN1:
   		return("MN1");
   	default:
   		return("");
	}

}//End string PeriodText(int per)
//+------------------------------------------------------------------+
//  Code to check that there are at least 100 bars of history in
//  the sym / per in the passed params
//+------------------------------------------------------------------+
bool HistoryOK(string sym,int per)
  {

   double tempArray[][6];  //used for the call to ArrayCopyRates()

                           //get the number of bars
   int bars=iBars(sym,per);
//and report it in the log
   Print("Checking ",sym," for complete data.... number of ",PeriodText(per)," bars = ",bars);

   if(bars<100)
     {
      //we didn't have enough, so set the comment and try to trigger the DL another way
      Comment("Symbol ",sym," -- Waiting for "+PeriodText(per)+" data.");
      ArrayCopyRates(tempArray,sym,per);
      int error=GetLastError();
      if(error!=0) Print(sym," - requesting data from the server...");

      //return false so the caller knows we don't have the data
      return(false);
     }//if (bars < 100)

//if we got here, the data is fine, so clear the comment and return true
   Comment("");
   return(true);

  }//End bool HistoryOK(string sym,int per)
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| NormalizeLots(string symbol, double lots)                        |
//+------------------------------------------------------------------+
//function added by fxdaytrader
//Lot size must be adjusted to be a multiple of lotstep, which may not be a power of ten on some brokers
//see also the original function by WHRoeder, http://forum.mql4.com/45425#564188, fxdaytrader
double NormalizeLots(string symbol,double lots)
{
   if(MathAbs(lots)==0.0) return(0.0); //just in case ... otherwise it may happen that after rounding 0.0 the result is >0 and we have got a problem, fxdaytrader
   double ls=MarketInfo(symbol,MODE_LOTSTEP);
   lots=MathMin(MarketInfo(symbol,MODE_MAXLOT),MathMax(MarketInfo(symbol,MODE_MINLOT),lots)); //check if lots >= min. lots && <= max. lots, fxdaytrader
   return(MathRound(lots/ls)*ls);
}
////////////////////////////////////////////////////////////////////////////////////////

// for 6xx build compatibilità added by milanese

string StringSubstrOld(string x,int a,int b=-1) 
{
   if(a<0) a=0; // Stop odd behaviour
   if(b<=0) b=-1; // new MQL4 EOL flag
   return StringSubstr(x,a,b);
}


bool MopUpTradeClosureFailures()
{
   //Cycle through the ticket numbers in the ForceCloseTickets array, and attempt to close them
   
   bool Success = true;
   
   for (int cc = ArraySize(ForceCloseTickets) - 1; cc >= 0; cc--)
   {
      //Order might have closed during a previous attempt, so ensure it is still open.
      if (!BetterOrderSelect(ForceCloseTickets[cc], SELECT_BY_TICKET, MODE_TRADES) )
         continue;
   
      bool result = CloseOrder(OrderTicket() );
      if (!result)
         Success = false;
   }//for (int cc = ArraySize(ForceCloseTickets) - 1; cc >= 0; cc--)
   
   if (Success)
      ArrayResize(ForceCloseTickets, 0);
   
   return(Success);


}//END bool MopUpTradeClosureFailures()



bool DoesTradeExist(int type, double price)
{

   if (OrdersTotal() == 0)
      return(false);
   if (OpenTrades == 0)
      return(false);
   
   
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!BetterOrderSelect(cc, SELECT_BY_POS) ) continue;
      if (OrderSymbol() != Symbol() ) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
      if (OrderType() != type) continue;
      if (!CloseEnough(OrderOpenPrice(), price) ) continue;
      
      //Got to here, so we have found a trade
      return(true);

   }//for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   
   
   //Got this far, so no trade found
   return(false);   

}//End bool DoesTradeExist(int type, double price)

void CalculateLotAsAmountPerCashDollops()
{

   double lotstep = MarketInfo(Symbol(), MODE_LOTSTEP);
   int decimal = 0;
   if (CloseEnough(lotstep, 0.1) )
      decimal = 1;
   if (CloseEnough(lotstep, 0.01) )
      decimal = 2;
      
   double maxlot = MarketInfo(Symbol(), MODE_MAXLOT);
   double minlot = MarketInfo(Symbol(), MODE_MINLOT);
   double DoshDollop = AccountInfoDouble(ACCOUNT_BALANCE); 
   
   if (UseEquity)
      DoshDollop = AccountInfoDouble(ACCOUNT_EQUITY); 


   int NoOfDollops = (int) DoshDollop /  SizeOfDollop;
   
   //Initial lot size
   Lot = NormalizeDouble(NoOfDollops  * LotsPerDollopOfCash, decimal);
     
   //Min/max size check
   if (Lot > maxlot)
      Lot = maxlot;
      
   if (Lot < minlot)
      Lot = minlot;      


}//void CalculateLotAsAmountPerCashDollops()

bool SundayMondayFridayStuff()
{
/*
   //Friday/Saturday stop trading hour
   int d = TimeDayOfWeek(TimeLocal());
   int h = TimeHour(TimeLocal());
   if (d == 5)
      if (h >= FridayStopTradingHour)
         if (OpenTrades == 0)
            return(false);
         
   if (d == 4)
      if (!TradeThursdayCandle)
         return(false);
        
   
   if (d == 6)
      if (h >= SaturdayStopTradingHour)
         return(false);
  
   //Sunday candle
   if (d == 0)
      if (!TradeSundayCandle)
         return(false);
         
   //Monday start hour
   if (d == 1)
      if (h < MondayStartHour)      
         return(false);
  */       
   //Got this far, so we are in a trading period
   return(true);      
   
}//End bool  SundayMondayFridayStuff()

bool indiExists( string indiName ) 
{

   //Returns true if a custom indi exists in the user's indi folder, else false
   bool exists = false;
   
   ResetLastError();
   double value = iCustom( Symbol(), Period(), indiName, 0, 0 );
   if ( GetLastError() == 0 ) exists = true;
   
   return(exists);

}//End bool indiExists( string indiName ) 

//For BetterOrderSelect() Craptrader documentation states:
//   The pool parameter is ignored if the order is selected by the ticket number. The ticket number is a unique order identifier. 
//   To find out from what list the order has been selected, its close time must be analyzed. If the order close time equals to 0, 
//   the order is open or pending and taken from the terminal open orders list.
//This function heals this and allows use of pool parameter when selecting orders by ticket number.
//Tomele provided this code. Thanks Thomas.
bool BetterOrderSelect(int index,int select,int pool=-1)
{
   if (select==SELECT_BY_POS)
   {
      if (pool==-1) //No pool given, so take default
         pool=MODE_TRADES;
         
      return(OrderSelect(index,select,pool));
   }
   
   if (select==SELECT_BY_TICKET)
   {
      if (pool==-1) //No pool given, so submit as is
         return(OrderSelect(index,select));
         
      if (pool==MODE_TRADES) //Only return true for existing open trades
         if(OrderSelect(index,select))
            if(OrderCloseTime()==0)
               return(true);
               
      if (pool==MODE_HISTORY) //Only return true for existing closed trades
         if(OrderSelect(index,select))
            if(OrderCloseTime()>0)
               return(true);
   }
   
   return(false);
}//End bool BetterOrderSelect(int index,int select,int pool=-1)


///////////////####@@@@@@@@@@@


//This code by tomele. Thank you Thomas. Wonderful stuff.
bool AreWeAtRollover()
{

   double time;
   int hours,minutes,rstart,rend,ltime;
   
   time=StrToDouble(RollOverStarts);
   hours=(int)MathFloor(time);
   minutes=(int)MathRound((time-hours)*100);
   rstart=60*hours+minutes;
      
   time=StrToDouble(RollOverEnds);
   hours=(int)MathFloor(time);
   minutes=(int)MathRound((time-hours)*100);
   rend=60*hours+minutes;
   
   ltime=TimeHour(TimeCurrent())*60+TimeMinute(TimeCurrent());

   if (rend>rstart)
     if(ltime>rstart && ltime<rend)
       return(true);
   if (rend<rstart) //Over midnight
     if(ltime>rstart || ltime<rend)
       return(true);

   //Got here, so not at rollover
   return(false);

}//End bool AreWeAtRollover()

void ShutDownForTheWeekend()
{
/*
   //Close/delete all trades to be flat for the weekend.
   
   int day = TimeDayOfWeek(TimeLocal() );
   int hour = TimeHour(TimeLocal() );
   bool CloseDelete = false;
   
   //Monday
   if (day == 1)
   {
      if (hour >= MondayCloseAllHour)
         if (CashUpl > MaxAllowableCashLoss)//MaxAllowableCashLoss is a negative number
            CloseDelete = true;
   }//if (day == 1)
   //Tuesday
   if (day == 2)
   {
      if (hour >= TuesdayCloseAllHour)
         if (CashUpl > MaxAllowableCashLoss)//MaxAllowableCashLoss is a negative number
            CloseDelete = true;
   }//if (day == 2)
   //Wednesday
   if (day == 3)
   {
      if (hour >= WednesdayCloseAllHour)
         if (CashUpl > MaxAllowableCashLoss)//MaxAllowableCashLoss is a negative number
            CloseDelete = true;
   }//if (day == 3)
   //Thursday
   if (day == 4)
   {
      if (hour >= ThursdayCloseAllHour)
         if (CashUpl > MaxAllowableCashLoss)//MaxAllowableCashLoss is a negative number
            CloseDelete = true;
   }//if (day == 4)
   //Friday
   if (day == 5)
   {
      if (hour >= FridayCloseAllHour)
         if (CashUpl > MaxAllowableCashLoss)//MaxAllowableCashLoss is a negative number
            CloseDelete = true;
   }//if (day == 5)
 
   //Saturday
   if (day == 6)
   {
      if (hour >= SaturdayCloseAllHour)
         if (CashUpl > MaxAllowableCashLoss)//MaxAllowableCashLoss is a negative number
            CloseDelete = true;
   }//if (day == 6)
   
   if (CloseDelete)
   {
      CloseAllTrades(AllTrades);
      if (ForceTradeClosure)
         CloseAllTrades(AllTrades);
      if (ForceTradeClosure)
         CloseAllTrades(AllTrades);
   }//if (CloseDelete)
  */    

}//End void ShutDownForTheWeekend()

void ShouldTradesBeClosed(int NoOfTradesMustBeOpen)
{
   //Examine baskets of trades for possible closure
   
   if (OpenTrades == 0)
      return;//Nothing to do

        
}//void ShouldTradesBeClosed()
//+------------------------------------------------------------------+
//|                                                                  |
///+------------------------------------------------------------------+
void SetBEAndJump(int ticket)
  {
    int Xdigits=Digits;
    double ask = Ask;
   double bid = Bid;
  double NewSLsi=0;
  double NewSLsii=0;
  double NewSLbi=0;
  double NewSLbii=0;
   //Security check
   if (!BetterOrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
      return;

    if(OrderType()==OP_SELL )
     {

      if(ask < OrderOpenPrice() - (BEProfit / factor) - (SLMinDistanceToPriceBE / factor)
      && OrderStopLoss() > OrderOpenPrice()
      && 0 < OrderStopLoss()  )
        {
         NewSLsi=NormalizeDouble(OrderOpenPrice()-(BEProfit/factor),Xdigits);

         if(NewSLsi!=OrderStopLoss() && NewSLsi!=0)
        {
            bool resultsi=OrderModify(ticket,OrderOpenPrice(),NewSLsi,OrderTakeProfit(),OrderExpiration(),clrRed);
        }}

      if(ask < OrderOpenPrice() - (BEProfit / factor) - (SLMinDistanceToPriceBE / factor)
      && 0 == OrderStopLoss()  )
        {
         NewSLsi=NormalizeDouble(OrderOpenPrice()-(BEProfit/factor),Xdigits);

         if(NewSLsi!=OrderStopLoss() && NewSLsi!=0)
        {
            bool resultsix=OrderModify(ticket,OrderOpenPrice(),NewSLsi,OrderTakeProfit(),OrderExpiration(),clrRed);
        }}


      if(ask < OrderStopLoss() - (SLMinDistanceToPriceJS/factor) - (JumpStep/factor)
      && OrderStopLoss() <= OrderOpenPrice() - (BEProfit / factor)
       && 0 < OrderStopLoss())
        {
         NewSLsii=NormalizeDouble(OrderStopLoss()-(JumpStep/factor),Xdigits);
         if(NewSLsii!=OrderStopLoss() && NewSLsii!=0)
           {
            bool resultsii=OrderModify(ticket,OrderOpenPrice(),NewSLsii,OrderTakeProfit(),OrderExpiration(),clrRed);
           }        }//`

     }//OP_SELL


   if(OrderType()==OP_BUY  )
     {

      if(bid > OrderOpenPrice() + (BEProfit / factor) + (SLMinDistanceToPriceBE / factor)
      && OrderStopLoss() < OrderOpenPrice()
      && ( 0 < OrderStopLoss() || 0 == OrderStopLoss() )  )
        {
         NewSLbi=NormalizeDouble(OrderOpenPrice()+(BEProfit/factor),Xdigits);

         if(NewSLbi!=OrderStopLoss() && NewSLbi!=0)
           {
            bool resulti=OrderModify(ticket,OrderOpenPrice(),NewSLbi,OrderTakeProfit(),OrderExpiration(),clrRed);
           }   }

      if(bid > OrderStopLoss() + (SLMinDistanceToPriceJS/factor) + (JumpStep/factor)
      && OrderStopLoss() >= OrderOpenPrice() + (BEProfit / factor)
       && 0 < OrderStopLoss())
        {
         NewSLbii=NormalizeDouble(OrderStopLoss()+(JumpStep/factor),Xdigits);
         if(NewSLbii!=OrderStopLoss() && NewSLbii!=0)
           { 
            bool resultii=OrderModify(ticket,OrderOpenPrice(),NewSLbii,OrderTakeProfit(),OrderExpiration(),clrRed);
              }   }//
              
     }//OP_BUY
        
   }//void SetBEAndJump(int ticket,double Xfactor,int Xdigits)
///////+------------------+
void InsertStopLoss(int ticket)
{
   //Inserts a stop loss if the ECN crim managed to swindle the original trade out of the modification at trade send time
   //Called from CountOpenTrades() if StopLoss > 0 && OrderStopLoss() == 0.
   
   if (!BetterOrderSelect(ticket, SELECT_BY_TICKET)) return;
   if (OrderCloseTime() > 0) return;//Somehow, we are examining a closed trade
   if (OrderStopLoss() > 0) return;//Function called unnecessarily.
   
   while(IsTradeContextBusy()) Sleep(100);
   
   double stopb;
   double stops;
   
   if (OrderType() == OP_BUY)
   {
      stopb = LowestLowPricei(Symbol(),PERIOD_H4,6,1);
   }//if (OrderType() == OP_BUY)
   
   if (OrderType() == OP_SELL)
   {
      stops = HighestHighPricei(Symbol(),PERIOD_H4,6,1);
   }//if (OrderType() == OP_SELL)
   
   
   //In case some errant behaviour/code creates a sl the wrong side of the market, which would cause an instant close.
   if (OrderType() == OP_BUY && stopb > OrderOpenPrice() ) 
   {
      stopb = 0;
      ReportError(" InsertStopLoss()", " stop loss > market ");
   }//if (OrderType() == OP_BUY && take < OrderOpenPrice() ) 
   
   if (OrderType() == OP_SELL && stops < OrderOpenPrice() ) 
   {
      stops = 0;
      ReportError(" InsertStopLoss()", " stop loss > market ");
   }//if (OrderType() == OP_SELL && take > OrderOpenPrice() ) 

   
   if (OrderType() == OP_BUY && stopb < OrderOpenPrice() ) 
   {
      bool resultb = ModifyOrder(OrderTicket(), OrderOpenPrice(), stopb, OrderTakeProfit(), OrderExpiration(), clrRed, __FUNCTION__, slim);
   }//if (!CloseEnough(stop, OrderStopLoss())) 

   if (OrderType() == OP_SELL && stops > OrderOpenPrice() ) 
   {
      bool results = ModifyOrder(OrderTicket(), OrderOpenPrice(), stops, OrderTakeProfit(), OrderExpiration(), clrRed, __FUNCTION__, slim);
   }//if (!CloseEnough(stop, OrderStopLoss())) 

 }//End void InsertStopLoss(int ticket)
///////+------------------+
//////+------------------+
//////+------------------+

void NuclearOptions()
{
   //Respond to the user's choice of options when a position becomes unbalanced.
   
   //Instant closure of the position.
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////   
}//End void NuclearOptions()
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool DoesTradeCommentExistForThisPair(string comment, string pair)
 {
   int lastError=0;
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         lastError=GetLastError();
         Print("Error in OrderSelect!!");
         continue;
        }
      if (OrderSymbol() != pair ) continue;
      if (OrderComment() != comment) continue;
      //Got to here, so we have found a comment
      return(true);

   }//for(int cnt=0;cnt<OrdersTotal();cnt++)
   
   
   //Got this far, so no no comment found
   return(false);   
 }//bool DoesTradeCommentExist()


//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
void OnTick()
{
//----
   //int cc;

   //mptm sets a Global Variable when it is closing the trades.
   //This tells this ea not to send any fresh trades.
   if (GlobalVariableCheck(GvName))
      return;
   //'Close all trades this pair only script' sets a GV to tell EA's not to attempt a trade during closure
   if (GlobalVariableCheck(LocalGvName))
      return;
   //'Nuclear option script' sets a GV to tell EA's not to attempt a trade during closure
   if (GlobalVariableCheck(NuclearGvName))
      return;

   if (RemoveExpert)
   {
      ExpertRemove();
      return;
   }//if (RemoveExpert)

   //Those stupid sods at MetaCrapper have ensured that stopping an ea by diabling AutoTrading no longer works. Ye Gods alone know why.
   //This routine provided by FxCoder. Thanks Bob.
   if ( !TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) )
   {
      Comment("                          TERMINAL AUTOTRADING IS DISABLED");
      return;
      
   }//if ( !TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) )
   if (!IsTradeAllowed() )
   {
      Comment("                          THIS EXPERT HAS LIVE TRADING DISABLED");
      return;
   }//if (!IsTradeAllowed() )
      
   //In case any trade closures failed
   if (ArraySize(ForceCloseTickets) > 0)
   {
      MopUpTradeClosureFailures();
      return;
   }//if (ArraySize(ForceCloseTickets) > 0)      
      
   //Rollover
   if (DisableEaDuringRollover)
   {
      RolloverInProgress = false;
      if (AreWeAtRollover())
      {
         RolloverInProgress = true;
         DisplayUserFeedback();
         return;
      }//if (AreWeAtRollover)
   }//if (DisableEaDuringRollover)
         
   //Code to check that there are sufficient bars in the chart's history. Gaheitman provided this. Many thanks George.
   static bool NeedToCheckHistory=false;
   if (NeedToCheckHistory)
   {
        //Customize these for the EA.  You can use externs for the periods 
        //if the user can change the timeframes used.
        //In a multi-currency bot, you'd put the calls in a loop across
        //all pairs
        
        //Customise these to suit what you are doing
        bool WeHaveHistory = true;
        if (!HistoryOK(Symbol(),Period())) WeHaveHistory = false;
        if (!WeHaveHistory)
        {
            Alert("There are <100 bars on this chart so the EA cannot work. It has removed itself. Please refresh your chart.");
            ExpertRemove();
        }//if (!WeHaveHistory)
        
        //if we get here, history is OK, so stop checking
        NeedToCheckHistory=false;
   }//if (NeedToCheckHistory)

   //Spread calculation
   if (!IsTesting() )
   {   
      if(CloseEnough(AverageSpread,0) || RunInSpreadDetectionMode)
      {
         GetAverageSpread();
         ScreenMessage="";
         int left=TicksToCount-CountedTicks;
         //   ************************* added for OBJ_LABEL
         DisplayCount = 1;
         removeAllObjects();
         //   *************************
         SM("Calculating the average spread. "+DoubleToStr(left,0)+" left to count.");
         Comment(ScreenMessage);
         return;
      }//if (CloseEnough(AverageSpread, 0) || RunInSpreadDetectionMode) 
      //Keep the average spread updated
      double spread=(Ask-Bid)*factor;
      if(spread>BiggestSpread) BiggestSpread=spread;//Widest spread since the EA was loaded
      static double SpreadTotal=0;
      static int counter=0;
      SpreadTotal+=spread;
      counter++;
      if(counter>=500)
      {
         AverageSpread=NormalizeDouble(SpreadTotal/counter,1);
         //Save the average for restarts.
         GlobalVariableSet(SpreadGvName,AverageSpread);
         SpreadTotal=0;
         counter=0;
      }//if (counter >= 500)
   }//if (!IsTesting() )
   
   //Create a flashing comment if there has been a rogue trade
   if (RobotSuspended) 
   {
      while (RobotSuspended)
      {
         Comment(NL, Gap, "****************** ROBOT SUSPENDED. POSSIBLE ROGUE TRADING ACTIVITY. REMOVE THIE EA IMMEDIATELY ****************** ");
         Sleep(2000);
         Comment("");
         Sleep(1000);
         if ( !TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) )
            return;
      }//while (RobotSuspended)           
      return;
   }//if (RobotSuspended) 

   //If HG is sleeping after a trade closure, is it time to awake?
   TooClose();
   if(SafetyViolation)//TooClose() sets SafetyViolation
   {
      DisplayUserFeedback();
      return;
   }//if (SafetyViolation) 


   
   if(OrdersTotal()==0)
   {
      TicketNo=-1;
      ForceTradeClosure=false;
   }//if (OrdersTotal() == 0)

   if(ForceTradeClosure)
   {
      CloseAllTrades(AllTrades);
      if (ForceTradeClosure)
         return;
   }//if (ForceTradeClosure) 


   //Check for a massive spread widening event and pause the ea whilst it is happening
   if (!IsTesting() )
      CheckForSpreadWidening();

   
   
   //Daily results so far - they work on what in in the history tab, so users need warning that
   //what they see displayed on screen depends on that.   
   //Code courtesy of TIG yet again. Thanks, George.
   static int OldHistoryTotal;
   if(OrdersHistoryTotal()!=OldHistoryTotal)
   {
      CalculateDailyResult();//Does no harm to have a recalc from time to time
      OldHistoryTotal=OrdersHistoryTotal();
   }//if (OrdersHistoryTotal() != OldHistoryTotal)

   ForceTradeClosure = false;
   ReadIndicatorValues();//This might want moving to the trading section at the end of this function if EveryTickMode = false
   if (ForceTradeClosure)//In case a stop order deletion failed
   {
      ForceTradeClosure = false;
      ReadIndicatorValues();//Try again
      if (ForceTradeClosure)
      {
         DisplayUserFeedback();
         return;//Make sure the bot does not send pending orders that will be deleted at the next tick
      }//if (ForceTradeClosure)      
   }//if (ForceTradeClosure)
   

   //Delete orphaned tp/sl lines
   static int M15Bars;
   if(M15Bars!=iBars(NULL,PERIOD_M15))
   {
      M15Bars=iBars(NULL,PERIOD_M15);
      DeleteOrphanTpSlLines();
   }//if (M15Bars != iBars(NULL, PERIOD_M15)

///////////////////////////////////////////////////////////////////////////////////
   //Find open trades.
   CountOpenTrades();
   //Possible shut down for the weekend
   if (OpenTrades > 0)
   {
      ShutDownForTheWeekend();
      if (ForceTradeClosure)
      {
         CloseAllTrades(AllTrades);
         return;
      }//if (ForceTradeClosure)

      
      

         
   }//if (OpenTrades > 0)
   
//Safety feature. Sometimes an unexpected concatenation of inputs choice and logic error can cause rapid opening-closing of trades. Detect a closed trade and check that is was not a rogue.
   if(OldOpenTrades!=OpenTrades)
   {
      if(IsClosedTradeRogue())
      {
         RobotSuspended=true;
         return;
      }//if (IsClosedTradeRogue() )      
   }//if (OldOpenTrades != OpenTrades)

   OldOpenTrades=OpenTrades;


      
   if (ForceTradeClosure)
   {
      CloseAllTrades(AllTrades);
      if (ForceTradeClosure)
      {
         CloseAllTrades(AllTrades);
         if (ForceTradeClosure)
         {
            return;
         }//if (ForceTradeClosure)                     
      }//if (ForceTradeClosure)         
   }//if (ForceTradeClosure)      
 
   //Lot size based on account size
   if (!CloseEnough(LotsPerDollopOfCash, 0))
      CalculateLotAsAmountPerCashDollops();

///////////////////////////////////////////////////////////////////////////////////

   //Trading times
   TradeTimeOk=CheckTradingTimes();
   if(!TradeTimeOk)
   {
      DisplayUserFeedback();
      Sleep(1000);
      return;
   }//if (!TradeTimeOk)

   //Sunday trading, Monday start time, Friday stop time, Thursday trading
   TradeTimeOk = SundayMondayFridayStuff();
   if (!TradeTimeOk)
   {
      DisplayUserFeedback();
      return;
   }//if (!TradeTimeOk)

///////////////////////////////////////////////////////////////////////////////////

   //Check that there is sufficient margin for trading
   if(!MarginCheck())
   {
      DisplayUserFeedback();
      return;
   }//if (!MarginCheck() )

   
   //Trading
   if(EveryTickMode) OldBarsTime=0;
   if(OldBarsTime!=iTime(NULL,TradingTimeFrame,0))
   {
      OldBarsTime = iTime(NULL, TradingTimeFrame, 0);
      if (TimeCurrent()+ PostTradeAttemptWaitSeconds  >= TimeToStartTrading)
         if (!StopTrading)              
            {
               TimeToStartTrading = 0;//Set to TimeCurrent() + (PostTradeAttemptWaitMinutes * 60) when there is an OrderSend() attempt)
               LookForTradingOpportunities();
            }//if (!StopTrading)
   }//if(OldBarsTime!=iTime(NULL,TradingTimeFrame,0))
   //Trading
   //Trading
   if(UseTickClosure) OldBarsTime=0;
   if(OldBarsTime!=iTime(NULL,TradingTimeFrame,0))
   {
      OldBarsTime = iTime(NULL, TradingTimeFrame, 0);
      if (TimeCurrent()+ PostTradeAttemptWaitSeconds  >= TimeToStartTrading)
         if (!StopTrading)              
            {  //SetBEAndJump();
               ExpirePendingOrders();
                        }//if (!StopTrading)
   }//if(OldBarsTime!=iTime(NULL,PERIOD_H1,0))
   //Trading

///////////////////////////////////////////////////////////////////////////////////

   DisplayUserFeedback();

//----
   return;
}
//+-------------------------
