/*

search for "charvo add" for what i edited.

*/


#property copyright "Don Isbell"
#property link      "disbellj@gmail.com"

#define FLAT 0
#define LONG 1
#define SHORT 2




// The following is needed to save as global variable
#define NONE 0
#define BUY_ALL 1
#define SELL_ALL 2


extern string t = "---Select Trend Indicator---";
extern string t1 = " 1. Trend Magic";
extern string t2 = " 2. SuperTrend";
extern string t3 = " 3. LSMA Direction";
extern int TrendIndicator = 1;
extern string ls6 = "LSMA Direction";
extern int LSMA_Period = 25;

extern bool UseIBFXPairs = True;
extern bool ShowComments = True;
extern bool UseRealAccountBalance = True;
extern double FauxAccountBalance = 10000.00;
extern double noMMLots = 0.02;
extern bool UseDonsMM = false;
extern bool UseDonsMMLeastLot = False;
extern double DonsMM_BasketRiskPercent = 10.0;
extern int DonsMM_StopLossPerPair = 50;
extern bool MarginCall_NOTAccepted = True;
extern bool EnableLocking = True;
extern bool AlertOn = TRUE;
extern bool SignalMail = false;
extern int Magicnumber=20100617;
extern string MyOrderComment="T101 Kos";
extern bool Trade_GBPCHF_Opposite = False;
extern bool Trade_EURCHF_Opposite = False;
extern bool Trade_EURGBP_Opposite = false;
extern bool Trade_USDCHF_Opposite = True;
extern bool Trade_USDCAD_Opposite = True;
extern bool UseTFforTrendConfirmation = false;
extern bool UseSpread = True;
extern bool UseCurrencyValue = True;

extern string  sm0="--Trading Hours Filter--";
extern bool    UseTradingHours = false;
extern string  sm4="TradeAsian - Enter 0 for false, 1 for true";
extern bool    TradeAsianMarket = true;
extern int     AsianStart = 15;       // Start trades after time
extern int     AsianStop = 300;      // Stop trading after time
extern string  sm5="Trade Europe - Enter 0 for false, 1 for true";
extern bool    TradeEuropeanMarket = true;
extern int     EurStart = 900;       // Start trades after time
extern int     EurStop = 1100;      // Stop trading after time
extern string  sm6="Trade NY - Enter 0 for false, 1 for true";
extern bool    TradeNewYorkMarket = true;
extern int     NYStart = 1300;       // Start trades after time
extern int     NYStop = 1500;      // Stop trading after time



//++++++++++++++charvo add++++++++++++++++++

int     ok2entertime;

//++++++++++++++charvo add++++++++++++++++++


bool     YesStop;

double MyAccountBalance,LotsRoundTo,MyAccountProfit = 0.00,ProfitStopLoss,TakeProfit,OneMicroLot,Lots,Multiplier,LockedProfit = -999999.00,ProfitLock = -999999.00,TotalMarginRequirement,TotalLoss;
string Pair_Suffix,MARGIN_CALL,MicroLotInfo,LotsOverrideInfo;
//int TotalOrders,ProfitLocked,Buys=0,Sells=0;
int ProfitLocked,Buys=0,Sells=0;

datetime W1_OpenTime,W1_StartBarTime,D1_OpenTime,D1_StartBarTime;    
double MACD_Main_2,MACD_Signal_2,MACD_Main_1,MACD_Signal_1,TrendMagic_Blue_1,TrendMagic_Red_1,LastCandleClose,MACD_Main,MACD_Signal,BI_Red,BI_Blue,LotsForTF,sum_blue,sum_red;
int W1_StartBar,D1_StartBar;
// Modified Trade to int for use as Global Variable
//string Trade,myPair;
int Trade;
string myPair;
bool RoundTo,BuyCondition1,SellCondition1,BuyCondition2,SellCondition2,BuyCondition3,SellCondition3,BuyCondition4,SellCondition4,BuyAlertDone,SellAlertDone,TFAlertDone,ExitAlertDone;

// Added to display spread
double TotalSpread, TotalSpreadActual;      
string Pair[14];
double PairPip[14];
double PairPoint[14];
double PairPipValuePerLot[14];
double PairMarginRequirement[14];
double PairLoss[14];
double Pair_Spread[14];
double Pair_SpreadActual[14]; // Added to show actual spread
double ThisPairWeekOpen[14];
double ThisPairDayOpen[14];
double Pair_Close[14];
double blue_Week[14];
double red_Week[14];
double blue_Day[14];
double red_Day[14];

// Added for timeframe of SuperTrend
string TimeFrame;

// Added by Robert to aid in testing different trend indicators 
int TradeDirection;
double myPoint;

// Global Variables

string      gTradeName;
string      gLockedProfitName;

int init() {
   
   myPair=StringSubstr(Symbol(),0,6);
   Pair_Suffix=StringSubstr(Symbol(),6,StringLen(Symbol())-6);
   if(myPair != "GBPJPY") Alert("Place indicator on GBPJPY"+Pair_Suffix+" chart");
   
   ChooseT101PairSet();
   DefinePipForEachPair();
   DefineOneMicroLot();
   DefineLotsRoundTo();
   DefineMicroLotInfo();
   DefineRoundTo();
   myPoint = SetPoint();
   
// Added as possible future trend confirm
//   Output_EMA_ForPairs(); 

   TimeFrame = TimeFrameToString(Period()); // Get timeframe for SuperTrend
   GetGlobalVars();
   return(0);
}

int deinit() {
   
   ObjectsDeleteAll();
   Comment("");
   
   return(0);
}

int start() {
   int myTotalOrders;
   
   ChooseAccountBalance();
      
   DefinePipValuePerLotForEachPair();
   
   CalculateLots();
   
   CalculateMarginRequirement();
   
   if(MarginCall_NOTAccepted == True && MARGIN_CALL == "YES") FixLots();
   else if(MarginCall_NOTAccepted == False) {
      if(UseDonsMM == True) LotsOverrideInfo = " (Lots have been defined by DonsMM)";
      else if(UseDonsMM == False) LotsOverrideInfo = " (Lots have been defined by User)";
   }
   
   DefineStrategyVariables();
   GetBuySellConditions();
   
// Modified to only get orders placed by this EA
   myTotalOrders = GetOrdersTotal();
   if(myTotalOrders > 0) {
// CheckTradeType code added to GetOrdersTotal function
//      CheckTradeType();
      CheckProfit();
      StrategyExitRules();
   } else if(myTotalOrders == 0) {
      Trade = NONE;
      SaveTrade(Trade);
      Reset();
      YesStop = CheckTradingTimes();
      if (YesStop == false) StrategyEntryRules();
   }
   
   if(ShowComments == True) ShowCommentsThen();
   
   return (0);
   
}
//--------------+

// Function for later possible check for trend confirm on individual pairs.
// I had it print to the journal as a check.
// Can be changed to use lsma
/*
void Output_EMA_ForPairs()
{
  double mEMA1, mEMA2;
  string TradeType;
  
  for (int i = 0; i < 14; i++)
  {
    mEMA1 = iMA(Pair[i], 0, 14, 0, MODE_EMA, PRICE_CLOSE, 1);
    mEMA2 = iMA(Pair[i], 0, 14, 0, MODE_EMA, PRICE_CLOSE, 2);
    TradeType = "NONE";
    if (mEMA1 > mEMA2) TradeType = "BUY";
    if (mEMA1 < mEMA2) TradeType = "SELL";
    
    Print (Pair[i] + " : " + TradeType);
  }
  
}

*/


// Used for timeframe of SuperTrend custom indicator 
string TimeFrameToString(int tf)
{
   string tfs="";
   switch(tf) {
      case PERIOD_M1:  tfs="M1"  ; break;
      case PERIOD_M5:  tfs="M5"  ; break;
      case PERIOD_M15: tfs="M15" ; break;
      case PERIOD_M30: tfs="M30" ; break;
      case PERIOD_H1:  tfs="H1"  ; break;
      case PERIOD_H4:  tfs="H4"  ; break;
      case PERIOD_D1:  tfs="D1"  ; break;
      case PERIOD_W1:  tfs="W1"  ; break;
      case PERIOD_MN1: tfs="MN1";
   }
   return(tfs);
}


void ChooseT101PairSet() {
   if(UseIBFXPairs == False) { // The usual suspects.. NOTE: PLACEMENT OF JPY PAIRS ARE CRITICAL, BECAUSE OF REST OF CODE BELOW
      Pair[0] = "CADJPY"+Pair_Suffix; 
      Pair[1] = "AUDUSD"+Pair_Suffix; 
      Pair[2] = "USDJPY"+Pair_Suffix; 
      Pair[3] = "EURUSD"+Pair_Suffix; 
      Pair[4] = "EURCHF"+Pair_Suffix;
      Pair[5] = "GBPJPY"+Pair_Suffix; 
      Pair[6]= "USDCAD"+Pair_Suffix; 
      Pair[7] = "GBPUSD"+Pair_Suffix; 
      Pair[8] = "EURGBP"+Pair_Suffix; 
      Pair[9] = "GBPCHF"+Pair_Suffix;
      Pair[10] = "CHFJPY"+Pair_Suffix; 
      Pair[11] = "AUDJPY"+Pair_Suffix; 
      Pair[12] = "EURJPY"+Pair_Suffix; 
      Pair[13] = "USDCHF"+Pair_Suffix;
   } else if (UseIBFXPairs == True) { //But these are the IBFX pairs, because IBFX does not have CADJPY
      Pair[0] = "GBPUSD"+Pair_Suffix; 
      Pair[1] = "EURGBP"+Pair_Suffix; 
      Pair[2] = "GBPJPY"+Pair_Suffix; 
      Pair[3] = "USDCHF"+Pair_Suffix; 
      Pair[4] = "NZDUSD"+Pair_Suffix;
      Pair[5] = "AUDJPY"+Pair_Suffix; 
      Pair[6] = "EURJPY"+Pair_Suffix; 
      Pair[7] = "EURUSD"+Pair_Suffix; 
      Pair[8] = "USDJPY"+Pair_Suffix; 
      Pair[9] = "AUDUSD"+Pair_Suffix;
      Pair[10] = "NZDJPY"+Pair_Suffix; 
      Pair[11] = "GBPCHF"+Pair_Suffix; 
      Pair[12] = "CHFJPY"+Pair_Suffix; 
      Pair[13] = "EURCHF"+Pair_Suffix;
   }
   
   return;
}

void DefinePipForEachPair() {
   for(int j=0;j<14;j++) {
      if(Point == 0.0001 || Point == 0.01) {
         PairPip[j] = MarketInfo(Pair[j],MODE_POINT);
      } else if(Point == 0.00001 || Point == 0.001) {
         PairPip[j] = MarketInfo(Pair[j],MODE_POINT)*10;
      }
   }
   
   return;
}

void DefineOneMicroLot() {
   if(MarketInfo(Symbol(),MODE_LOTSIZE) == 100000) {
      OneMicroLot = 0.01;
   } else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 10000) {
      OneMicroLot = 0.1;
   } else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 1000) {
      OneMicroLot = 1;
   }
   
   return;
}

void DefineLotsRoundTo() {
   if(MarketInfo(Symbol(),MODE_LOTSIZE) == 100000) {
      LotsRoundTo = 2;
   } else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 10000) {
      LotsRoundTo = 1;
   } else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 1000) {
      LotsRoundTo = 0;
   }
   
   return;
}

void DefineMicroLotInfo() {
   if(MarketInfo(Symbol(),MODE_LOTSIZE) == 100000) {
      MicroLotInfo = " (One micro lot = 0.01)";
   } else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 10000) {
      MicroLotInfo = " (One micro lot = 0.1)";
   } else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 1000) {
      MicroLotInfo = " (One micro lot = 1)";
   }
   
   return;
}

void DefineRoundTo() {  
   if(Point == 0.0001 || Point == 0.01) {
      RoundTo = 0;
   } else if(Point == 0.00001 || Point == 0.001) {
      RoundTo = 1;
   }
   
   return;
}

void Reset() {
   MyAccountProfit = 0.00;
   LockedProfit = -999999;
   SaveLockedProfit(LockedProfit);
   ProfitLock = -999999;
   
   return;
}

void ChooseAccountBalance() {
   if(UseRealAccountBalance == False) {
      MyAccountBalance = FauxAccountBalance;
   } else if(UseRealAccountBalance == True) {
      MyAccountBalance = AccountBalance();
   }
   
   return;
}

void CheckProfit() {
   int myTotalOrders;
   myTotalOrders = OrdersTotal();
   
   Multiplier = Lots/OneMicroLot;
   ProfitStopLoss = -56.00*Multiplier;
   TakeProfit = 600.00*Multiplier;
   
   
   MyAccountProfit=0;
   for(int cnt=0;cnt<myTotalOrders;cnt++) {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderMagicNumber() == Magicnumber) {
         MyAccountProfit += OrderProfit();
      }
   }

   if(MyAccountProfit <= ProfitStopLoss && ExitAlertDone == False) {
      T101_CloseAll();
      if(AlertOn) Alert("Kos CLOSEALL BY STOP LOSS. "," MyAccountProfit: "+MyAccountProfit);
      if (SignalMail) SendMail("T101 CLOSEALL BY STOP LOSS. "," MyAccountProfit: "+MyAccountProfit); 
      ExitAlertDone = True;
   }
   if(MyAccountProfit >= TakeProfit && ExitAlertDone == False) {
      T101_CloseAll();
      if(AlertOn) Alert("Kos CLOSEALL BY TAKE PROFIT. "," MyAccountProfit: "+MyAccountProfit);
      if (SignalMail) SendMail("T101 CLOSEALL BY TAKE PROFIT. "," MyAccountProfit: "+MyAccountProfit); 
      ExitAlertDone = True;
   }
   if(EnableLocking) LockInProfit();
   
   return;
}

double SetPoint()
{
   double mPoint;
   
   if (Digits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}

double iLsma(int LSMAPeriod,int shift)
{
   double wt;
   
   double ma1=iMA(NULL,0,LSMAPeriod,0,MODE_SMA ,PRICE_CLOSE,shift);
   double ma2=iMA(NULL,0,LSMAPeriod,0,MODE_LWMA,PRICE_CLOSE,shift);
   wt = MathFloor((3.0*ma2-2.0*ma1)/myPoint)*myPoint;
   return(wt);
}  

int GetTradeDirectionFromTrend()
{
   int trend = FLAT;
   double lsma_cur, lsma_prev;
   
   switch(TrendIndicator)
   {
     case 1 : TrendMagic_Blue_1 = iCustom(myPair+Pair_Suffix,0,"Trend Magic",0,1);
              TrendMagic_Red_1 = iCustom(myPair+Pair_Suffix,0,"Trend Magic",1,1);
              if((TrendMagic_Blue_1 != 2147483647 && LastCandleClose > TrendMagic_Blue_1) || //last candle TM closed blue and candle closed above blue TM -OR-
                 (TrendMagic_Red_1 != 2147483647 && LastCandleClose > TrendMagic_Red_1)) { //last candle TM closed red and candle closed above red TM
                 trend = LONG;
              }
              if((TrendMagic_Blue_1 != 2147483647 && LastCandleClose < TrendMagic_Blue_1) || //last candle TM closed blue and candle closed below blue TM -OR-
                 (TrendMagic_Red_1 != 2147483647 && LastCandleClose < TrendMagic_Red_1)) { //last candle TM closed red and candle closed below red TM
                 trend = SHORT;
              }
              break;
     case 2 : TrendMagic_Blue_1 = iCustom(myPair+Pair_Suffix,0,"SuperTrend nrp mtf",TimeFrame,0,1);
              TrendMagic_Red_1 = iCustom(myPair+Pair_Suffix,0,"SuperTrend nrp mtf",TimeFrame,1,1);
              if((TrendMagic_Blue_1 != 2147483647 && LastCandleClose > TrendMagic_Blue_1) || //last candle TM closed blue and candle closed above blue TM -OR-
                 (TrendMagic_Red_1 != 2147483647 && LastCandleClose > TrendMagic_Red_1)) { //last candle TM closed red and candle closed above red TM
                 trend = LONG;
              }
              if((TrendMagic_Blue_1 != 2147483647 && LastCandleClose < TrendMagic_Blue_1) || //last candle TM closed blue and candle closed below blue TM -OR-
                 (TrendMagic_Red_1 != 2147483647 && LastCandleClose < TrendMagic_Red_1)) { //last candle TM closed red and candle closed below red TM
                 trend = SHORT;
              }
              break;
     case 3 : lsma_cur = iLsma(LSMA_Period, 1);
              lsma_prev = iLsma(LSMA_Period, 2);
   
              if (lsma_cur > lsma_prev) trend = LONG;
              if (lsma_cur < lsma_prev) trend = SHORT;
   }
   
   return(trend);

}

void DefineStrategyVariables() {
double mBid, mAsk, mPoint, mSpread;
   MACD_Main_2 = iMACD(myPair+Pair_Suffix,0,12,26,9,PRICE_CLOSE,MODE_MAIN,2);
   MACD_Signal_2 = iMACD(myPair+Pair_Suffix,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,2);
   MACD_Main_1 = iMACD(myPair+Pair_Suffix,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   MACD_Signal_1 = iMACD(myPair+Pair_Suffix,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
   
   LastCandleClose = iClose(myPair+Pair_Suffix,0,1);
   
   TradeDirection = GetTradeDirectionFromTrend();
   
   MACD_Main = iMACD(myPair+Pair_Suffix,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MACD_Signal = iMACD(myPair+Pair_Suffix,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   
   BI_Red = iCustom(myPair+Pair_Suffix,0,"BI_T101_OTR_V1_6",UseIBFXPairs,10,5,288,0.0,0.0,"Check_Candle : 0 for current , 1 for last closed candle",0,true," 0 for S_R , 1 for Fast/Slow cross",1,"Alert.wav","Alert2.wav",false,0,0);
   BI_Blue = iCustom(myPair+Pair_Suffix,0,"BI_T101_OTR_V1_6",UseIBFXPairs,10,5,288,0.0,0.0,"Check_Candle : 0 for current , 1 for last closed candle",0,true," 0 for S_R , 1 for Fast/Slow cross",1,"Alert.wav","Alert2.wav",false,1,0);
   
// Added to display spread
   TotalSpread = 0;
   TotalSpreadActual = 0;
   
   if(UseTFforTrendConfirmation == True) {
      //timeframes Weekly and Daily - for trend
      if(UseSpread == True) {
         for(int j=0;j<14;j++) {
// Calculate default spread
            if(MarketInfo(Pair[j],MODE_POINT) == 0.00001 || MarketInfo(Pair[j],MODE_POINT) == 0.001) {
               Pair_Spread[j] = MarketInfo(Pair[j],MODE_SPREAD)/10;
            } else if(MarketInfo(Pair[j],MODE_POINT) == 0.0001 || MarketInfo(Pair[j],MODE_POINT) == 0.01) {
               Pair_Spread[j] = MarketInfo(Pair[j],MODE_SPREAD);
            }
// Calculate actual spread
            mBid = MarketInfo(Pair[j], MODE_BID);
            mAsk = MarketInfo(Pair[j], MODE_ASK);
            mSpread = (mAsk - mBid) / PairPip[j];
            Pair_SpreadActual[j] = mSpread;
            TotalSpread = TotalSpread + Pair_Spread[j];
            TotalSpreadActual = TotalSpreadActual + mSpread;
         }
      } else {
         for(j=0;j<14;j++) {
            Pair_Spread[j] = 0;
            Pair_SpreadActual[j] = 0;
         }
      }
   
      for(j=0;j<14;j++) {
         Pair_Close[j] = iClose(Pair[j],0,0);
      }
   
      if(MarketInfo(Symbol(),MODE_LOTSIZE) == 100000) LotsForTF = 0.1;
      else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 10000) LotsForTF = 1.0;
      else if(MarketInfo(Symbol(),MODE_LOTSIZE) == 1000) LotsForTF = 10.0;
   
      if(Period() == 240) {//if H4 timeframe, use Weekly for trend
         W1_OpenTime =  iTime(NULL,PERIOD_W1,0);
         W1_StartBar = iBarShift(NULL,0,W1_OpenTime);
         W1_StartBarTime = iTime(NULL,0,W1_StartBar);
         for(j=0;j<14;j++) {
            if(W1_StartBarTime < W1_OpenTime) {
               ThisPairWeekOpen[j] = iOpen(Pair[j],0,iBarShift(Pair[j],0,W1_OpenTime)-1);
            } else {
               ThisPairWeekOpen[j] = iOpen(Pair[j],0,iBarShift(Pair[j],0,W1_OpenTime));
            }
         }
         for(j=0;j<7;j++) {
            if( StringFind(Pair[j],"JPY",0)!=-1) {
               blue_Week[j] = (((Pair_Close[j]-(ThisPairWeekOpen[j]+(Pair_Spread[j]*PairPip[j])))/100)*10000);
            } else {
               blue_Week[j] = ((Pair_Close[j]-(ThisPairWeekOpen[j]+(Pair_Spread[j]*PairPip[j])))*10000);
            }
         }
         for(j=7;j<14;j++) {
            if( StringFind(Pair[j],"JPY",0)!=-1) {
               red_Week[j] = (((ThisPairWeekOpen[j]-(Pair_Close[j]+(Pair_Spread[j]*PairPip[j])))/100)*10000);
            } else {
               red_Week[j] = ((ThisPairWeekOpen[j]-(Pair_Close[j]+(Pair_Spread[j]*PairPip[j])))*10000);
            }
         }
         if(UseCurrencyValue == True) {
            for(j=0;j<7;j++) {
               blue_Week[j] = blue_Week[j]*PairPipValuePerLot[j]*LotsForTF;
            }
            for(j=7;j<14;j++) {
               red_Week[j] = red_Week[j]*PairPipValuePerLot[j]*LotsForTF;
            }
         }
         sum_blue=0;
         sum_red=0;
         for(j=0;j<7;j++) {
            sum_blue = sum_blue+blue_Week[j];
         }
         for(j=7;j<14;j++) {
            sum_red = sum_red+red_Week[j];
         }
      } else if(Period() == 15 || Period() == 60) {//if M15 timeframe or H1 timeframe, use Daily for trend
         D1_OpenTime =  iTime(NULL,PERIOD_D1,0);
         D1_StartBar = iBarShift(NULL,0,D1_OpenTime);
         D1_StartBarTime = iTime(NULL,0,D1_StartBar);
         for(j=0;j<14;j++) {
            if(D1_StartBarTime < D1_OpenTime) {
               ThisPairDayOpen[j] = iOpen(Pair[j],0,iBarShift(Pair[j],0,D1_OpenTime)-1);
            } else {
               ThisPairDayOpen[j] = iOpen(Pair[j],0,iBarShift(Pair[j],0,D1_OpenTime));
            }
         }
         for(j=0;j<7;j++) {
            if( StringFind(Pair[j],"JPY",0)!=-1) {
               blue_Day[j] = (((Pair_Close[j]-(ThisPairDayOpen[j]+(Pair_Spread[j]*PairPip[j])))/100)*10000);
            } else {
               blue_Day[j] = ((Pair_Close[j]-(ThisPairDayOpen[j]+(Pair_Spread[j]*PairPip[j])))*10000);
            }
         }
         for(j=7;j<14;j++) {
            if( StringFind(Pair[j],"JPY",0)!=-1) {
               red_Day[j] = (((ThisPairDayOpen[j]-(Pair_Close[j]+(Pair_Spread[j]*PairPip[j])))/100)*10000);
            } else {
               red_Day[j] = ((ThisPairDayOpen[j]-(Pair_Close[j]+(Pair_Spread[j]*PairPip[j])))*10000);
            }
         }
         if(UseCurrencyValue == True) {
            for(j=0;j<7;j++) {
               blue_Day[j] = blue_Day[j]*PairPipValuePerLot[j]*LotsForTF;
            }
            for(j=7;j<14;j++) {
               red_Day[j] = red_Day[j]*PairPipValuePerLot[j]*LotsForTF;
            }
         }
         sum_blue=0;
         sum_red=0;
         for(j=0;j<7;j++) {
            sum_blue = sum_blue+blue_Day[j];
         }
         for(j=7;j<14;j++) {
            sum_red = sum_red+red_Day[j];
         }            
      } else if(Period() != 60 && Period() != 240 && TFAlertDone == False) {
         Alert("Change timeframe to M15, H1 or H4");
         TFAlertDone = True;
      }
   }
   
   return;
}

void StrategyExitRules() {  
  int myTotalOrders;

// First check for MACD exit
   if(Trade == BUY_ALL && MACD_Main_2 > MACD_Signal_2 && MACD_Main_1 < MACD_Signal_1 && ExitAlertDone == False) {
      if(AlertOn) Alert("Kos - CLOSEBUY BY MACD/SIGNAL CROSS. "," MyAccountProfit: "+MyAccountProfit);
      if (SignalMail) SendMail("T101 KosLineUp - CLOSEBUY BY MACD/SIGNAL CROSS. "," MyAccountProfit: "+MyAccountProfit); 
      ExitAlertDone = True;
      T101_CloseAll();
   }

   if(Trade == SELL_ALL && MACD_Main_2 < MACD_Signal_2 && MACD_Main_1 > MACD_Signal_1 && ExitAlertDone == False) {
      if(AlertOn) Alert("Kos - CLOSESELL BY MACD/SIGNAL CROSS. "," MyAccountProfit: "+MyAccountProfit);
      if (SignalMail) SendMail("T101 KosLineUp - CLOSESELL BY MACD/SIGNAL CROSS. "," MyAccountProfit: "+MyAccountProfit);  
      ExitAlertDone = True;
      T101_CloseAll();
   }
   
// Then check for reversal of rules
   if(Trade == BUY_ALL && SellCondition1 == True && SellCondition2 == True && SellCondition3 == True && SellCondition4 == True && ExitAlertDone == False) {
      if(AlertOn) Alert("Kos - CLOSEBUY BY RULE REVERSAL. "," MyAccountProfit: "+MyAccountProfit);
      if (SignalMail) SendMail("T101 KosLineUp - CLOSEBUY BY RULE REVERSAL. "," MyAccountProfit: "+MyAccountProfit); 
      ExitAlertDone = True;
      T101_CloseAll();
      myTotalOrders = GetOrdersTotal();
      if(myTotalOrders == 0) {
         Trade = NONE;
         SaveTrade(Trade);
      }
   }

   if(Trade == SELL_ALL && BuyCondition1 == True && BuyCondition2 == True && BuyCondition3 == True && BuyCondition4 == True && ExitAlertDone == False) {
      if(AlertOn) Alert("Kos - CLOSESELL BY RULE REVERSAL. "," MyAccountProfit: "+MyAccountProfit);
      if (SignalMail) SendMail("T101 KosLineUp - CLOSESELL BY RULE REVERSAL. "," MyAccountProfit: "+MyAccountProfit); 
      ExitAlertDone = True;
      T101_CloseAll();
      myTotalOrders = GetOrdersTotal();
      if(myTotalOrders == 0) {
         Trade = NONE;
         SaveTrade(Trade);
      }
   }
   
   return;
}

void GetBuySellConditions()
{
  if(TradeDirection == LONG) {
      BuyCondition1 = True;
      SellCondition1 = False;
   }
   if(TradeDirection == SHORT) {
      SellCondition1 = True;
      BuyCondition1 = False;
   }
   
   if(TradeDirection == FLAT) {
      SellCondition1 = False;
      BuyCondition1 = False;
   }

   
   if(BuyCondition1 == True) {
      if(MACD_Main > MACD_Signal) BuyCondition2 = True; else BuyCondition2 = False;    
   } else {
      BuyCondition2 = False;
   }
   
   if(SellCondition1 == True) {
      if(MACD_Main < MACD_Signal) SellCondition2 = True; else SellCondition2 = False;
   } else {
      SellCondition2 = False;
   }
   
   if(BuyCondition2 == True) {
      if(BI_Red > BI_Blue) BuyCondition3 = True; else BuyCondition3 = False;
   } else {
      BuyCondition3 = False;
   }
   
   if(SellCondition2 == True) {
      if(BI_Red < BI_Blue) SellCondition3 = True; else SellCondition3 = False;
   } else {
      SellCondition3 = False;
   }
   
   if(UseTFforTrendConfirmation == True) {
      if(BuyCondition3 == True) {
         if(sum_blue > 0 && sum_red < 0) BuyCondition4 = True; else BuyCondition4 = False;
      } else {
         BuyCondition4 = False;
      }
   
      if(SellCondition3 == True) {
         if(sum_blue < 0 && sum_red > 0) SellCondition4 = True; else SellCondition4 = False;
      } else {
         SellCondition4 = False;
      }
   } else {
      BuyCondition4 = True;
      SellCondition4 = True;

//+++++++++++charvo add++++++++++++++++
      if (BuyCondition4 && SellCondition4 && ok2entertime == 0) ok2entertime = TimeCurrent();
      
      if ( (CheckRecntCrx(1,1)!=0 || CheckRecntCrx(1,-1)!=0) && (ok2entertime!=0 && (TimeCurrent()-ok2entertime)>720) ) ok2entertime = 0;
//+++++++++++charvo add++++++++++++++++
   }
   
}

void StrategyEntryRules() { 

//+++++++++++charvo add++++++++++++++++
if ( ok2entertime!=0 && (TimeCurrent()-ok2entertime) <= 180 )
 {
//+++++++++++charvo add++++++++++++++++
   if(Trade == NONE && BuyCondition1 == True && BuyCondition2 == True && BuyCondition3 == True && BuyCondition4 == True) {
      if(AlertOn == True && BuyAlertDone == False) {
         Alert("Kos - BUYALL");
         if (SignalMail) SendMail("T101 KosLineUp - BUYALL","T101 LineUp - BUYALL");
         BuyAlertDone = True;
      }
      T101_BuyAll();
   }
   
   if(Trade == NONE && SellCondition1 == True && SellCondition2 == True && SellCondition3 == True && SellCondition4 == True) {
      if(AlertOn == True && SellAlertDone == False) {
         Alert("Kos - SELLALL","T101 LineUp - SELLALL");
         if (SignalMail) SendMail("T101 KosLineUp - SELLALL","T101 LineUp - SELLALL");
         SellAlertDone = True;
      }
      T101_SellAll();
   }

 }   
   
   return;
}

void T101_BuyAll() {   
// Safer to keep this local
   int myTotalOrders;
   myTotalOrders = GetOrdersTotal();

   if(myTotalOrders > 0) {
      Buys=0;
      Sells=0;
      for(int cnt=0;cnt<myTotalOrders;cnt++) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if(OrderMagicNumber() == Magicnumber) {
            if(OrderType()==OP_BUY) Buys=Buys+1;
            else if(OrderType()==OP_SELL) Sells=Sells+1;
         }
      }
      if(Sells > Buys) T101_CloseAll();
   } else if(myTotalOrders == 0) {
      for(int j=0;j<14;j++) {
         if(Trade_GBPCHF_Opposite == True && StringFind(Pair[j],"GBPCHF",0)!=-1) {
            OrderSend(Pair[j],OP_SELL, Lots, MarketInfo(Pair[j],MODE_BID), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_EURCHF_Opposite == True && StringFind(Pair[j],"EURCHF",0)!=-1) {
            OrderSend(Pair[j],OP_SELL, Lots, MarketInfo(Pair[j],MODE_BID), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_EURGBP_Opposite == True && StringFind(Pair[j],"EURGBP",0)!=-1) {
            OrderSend(Pair[j],OP_SELL, Lots, MarketInfo(Pair[j],MODE_BID), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_USDCHF_Opposite == True && StringFind(Pair[j],"USDCHF",0)!=-1) {
            OrderSend(Pair[j],OP_SELL, Lots, MarketInfo(Pair[j],MODE_BID), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_USDCAD_Opposite == True && StringFind(Pair[j],"USDCAD",0)!=-1) {
            OrderSend(Pair[j],OP_SELL, Lots, MarketInfo(Pair[j],MODE_BID), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else {  
            OrderSend(Pair[j],OP_BUY, Lots, MarketInfo(Pair[j],MODE_ASK), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         }
      }
   }
   Trade = BUY_ALL;
   SaveTrade(Trade);
   ExitAlertDone = False;
   
   return;
}

void T101_SellAll() {
// Safer to keep this local
   int myTotalOrders;
   myTotalOrders = GetOrdersTotal();
   
   if(myTotalOrders > 0) {
      Buys=0;
      Sells=0;
      for(int cnt=0;cnt<myTotalOrders;cnt++) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if(OrderMagicNumber() == Magicnumber) {
            if(OrderType()==OP_BUY) Buys=Buys+1;
            else if(OrderType()==OP_SELL) Sells=Sells+1;
         }
      }
      if(Buys > Sells) T101_CloseAll();
   } else if(myTotalOrders == 0) {
      for(int j=0;j<14;j++) {
         if(Trade_GBPCHF_Opposite == True && StringFind(Pair[j],"GBPCHF",0)!=-1) {
            OrderSend(Pair[j],OP_BUY, Lots, MarketInfo(Pair[j],MODE_ASK), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_EURCHF_Opposite == True && StringFind(Pair[j],"EURCHF",0)!=-1) {
            OrderSend(Pair[j],OP_BUY, Lots, MarketInfo(Pair[j],MODE_ASK), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_EURGBP_Opposite == True && StringFind(Pair[j],"EURGBP",0)!=-1) {
            OrderSend(Pair[j],OP_BUY, Lots, MarketInfo(Pair[j],MODE_ASK), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_USDCHF_Opposite == True && StringFind(Pair[j],"USDCHF",0)!=-1) {
            OrderSend(Pair[j],OP_BUY, Lots, MarketInfo(Pair[j],MODE_ASK), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else if(Trade_USDCAD_Opposite == True && StringFind(Pair[j],"USDCAD",0)!=-1) {
            OrderSend(Pair[j],OP_BUY, Lots, MarketInfo(Pair[j],MODE_ASK), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         } else {
            OrderSend(Pair[j],OP_SELL, Lots, MarketInfo(Pair[j],MODE_BID), 2, 0, 0, MyOrderComment, Magicnumber, 0, CLR_NONE);
         }
      }
   }
   Trade = SELL_ALL;
   SaveTrade(Trade);
   ExitAlertDone = False;
   
   return;
}

void DefinePipValuePerLotForEachPair() {
   for(int j=0;j<14;j++) {
      if(Point == 0.0001 || Point == 0.01) {
         PairPipValuePerLot[j] = MarketInfo(Pair[j], MODE_TICKVALUE);
      } else if(Point == 0.00001 || Point == 0.001) {
         PairPipValuePerLot[j] = MarketInfo(Pair[j], MODE_TICKVALUE)*10;  
      }
   }
   
   return;
}

void CalculateLots() {
   if(UseDonsMM == True) {
      if(UseDonsMMLeastLot == True) {
         for(int j=0;j<14;j++) { 
            if(NormalizeDouble((MyAccountBalance*((DonsMM_BasketRiskPercent/14) *0.01)) /(DonsMM_StopLossPerPair*PairPipValuePerLot[j]), LotsRoundTo) < Lots || Lots == 0.0) {
               Lots = NormalizeDouble((MyAccountBalance*((DonsMM_BasketRiskPercent/14)*0.01)) /(DonsMM_StopLossPerPair*PairPipValuePerLot[j]), LotsRoundTo);
            }
         } 
      } else if(UseDonsMMLeastLot == False) {
         Lots = NormalizeDouble((MyAccountBalance*((DonsMM_BasketRiskPercent/14)*0.01)) /(DonsMM_StopLossPerPair*PairPipValuePerLot[7]), LotsRoundTo);
      }
   } else if(UseDonsMM == False) {
      Lots = noMMLots;
   }
   for(j=0;j<14;j++) {
      if(Lots < MarketInfo(Pair[j],MODE_MINLOT)) Lots = MarketInfo(Pair[j],MODE_MINLOT);
      if(Lots > MarketInfo(Pair[j],MODE_MAXLOT)) Lots = MarketInfo(Pair[j],MODE_MAXLOT);
   }
   
   return;
}
   
void CalculateMarginRequirement() {
   //Calculate total margin requirement for all 14 trades
   for (int j=0;j<14;j++) {
      if(StringFind(Pair[j],"USD",3)!=-1) { //for pairs that end in USD
         PairMarginRequirement[j] = (MarketInfo(Pair[j],MODE_LOTSIZE)*(MarketInfo(Pair[j], MODE_ASK))/AccountLeverage())*Lots;
      } else if(StringFind(Pair[j],"USD",0)!=-1 || StringFind(Pair[j],"CHFJPY",0)!=-1 || StringFind(Pair[j],"CADJPY",0)!=-1) { //for pairs that begin in USD, or if CADJPY or CHFJPY
         PairMarginRequirement[j] = (MarketInfo(Pair[j],MODE_LOTSIZE)/AccountLeverage())*Lots; 
      } else {
         string substr=StringSubstr(Pair[j], 0, 3);
         string text=StringConcatenate(substr,"USD" );
         PairMarginRequirement[j] = (MarketInfo(Pair[j],MODE_LOTSIZE)*(MarketInfo(text, MODE_ASK))/AccountLeverage())*Lots;
      }
   }

   TotalMarginRequirement = 0.00;

   for (j=0;j<14;j++) {
      TotalMarginRequirement += PairMarginRequirement[j];
   }

   //Calculate total possible loss (all 14 trades, to make sure we don't get a margin call)
   for (j=0;j<14;j++) {
      PairLoss[j] = DonsMM_StopLossPerPair*PairPipValuePerLot[j]*Lots;
   }
   
   TotalLoss = 0.00;
   
   for (j=0;j<14;j++) {
      TotalLoss += PairLoss[j];
   }
   
   if((MyAccountBalance-TotalLoss) < TotalMarginRequirement) MARGIN_CALL = "YES"; else MARGIN_CALL = "NO";
   
   return;
}

void FixLots() {
   while(MARGIN_CALL == "YES") {
      CalculateMarginRequirement();
      if(MARGIN_CALL == "YES") {
         Lots = Lots-OneMicroLot;
      } else if(MARGIN_CALL == "NO") {
         Lots = Lots;
      }
   }
   LotsOverrideInfo = " (Margin Call is NOT Allowed)";  
   
   return;
}

void LockInProfit() {
   if(MyAccountProfit <= LockedProfit && ExitAlertDone == False) {
      if(AlertOn) Alert("Kos CLOSEALL BY PROFIT-LOCK. "," MyAccountProfit: "+MyAccountProfit+", LockedProfit: "+LockedProfit);
      if (SignalMail) SendMail("T101 CLOSEALL BY PROFIT-LOCK. "," MyAccountProfit: "+MyAccountProfit+", LockedProfit: "+LockedProfit); 
      ExitAlertDone = True;
      T101_CloseAll();
   } 
   if ((MyAccountProfit >= (500.00*Multiplier)) && (LockedProfit == NormalizeDouble(401.00*Multiplier, 2))) ProfitLock = (451.00*Multiplier);
   if ((MyAccountProfit >= (450.00*Multiplier)) && (LockedProfit == NormalizeDouble(351.00*Multiplier, 2))) ProfitLock = (401.00*Multiplier);
   if ((MyAccountProfit >= (400.00*Multiplier)) && (LockedProfit == NormalizeDouble(301.00*Multiplier, 2))) ProfitLock = (351.00*Multiplier);
   if ((MyAccountProfit >= (350.00*Multiplier)) && (LockedProfit == NormalizeDouble(251.00*Multiplier, 2))) ProfitLock = (301.00*Multiplier);
   if ((MyAccountProfit >= (300.00*Multiplier)) && (LockedProfit == NormalizeDouble(201.00*Multiplier, 2))) ProfitLock = (251.00*Multiplier);
   if ((MyAccountProfit >= (250.00*Multiplier)) && (LockedProfit == NormalizeDouble(151.00*Multiplier, 2))) ProfitLock = (201.00*Multiplier);
   if ((MyAccountProfit >= (200.00*Multiplier)) && (LockedProfit == NormalizeDouble(101.00*Multiplier, 2))) ProfitLock = (151.00*Multiplier);
   if ((MyAccountProfit >= (150.00*Multiplier)) && (LockedProfit == NormalizeDouble(71.00*Multiplier, 2))) ProfitLock = (101.00*Multiplier);
   if ((MyAccountProfit >= (100.00*Multiplier)) && (LockedProfit == NormalizeDouble(46.00*Multiplier, 2))) ProfitLock = (71.00*Multiplier);
   if ((MyAccountProfit >= (70.00*Multiplier)) && (LockedProfit == NormalizeDouble(22.00*Multiplier, 2))) ProfitLock = (46.00*Multiplier);
   if ((MyAccountProfit >= (50.00*Multiplier)) && (LockedProfit == NormalizeDouble(15.00*Multiplier, 2))) ProfitLock = (22.00*Multiplier);
   //if ((MyAccountProfit >= (40.00*Multiplier)) && (LockedProfit == NormalizeDouble(21.00*Multiplier, 2))) ProfitLock = (31.00*Multiplier);
   if ((MyAccountProfit >= (36.00*Multiplier)) && (LockedProfit == NormalizeDouble(2.00*Multiplier, 2))) ProfitLock = (15.00*Multiplier);
   //if ((MyAccountProfit >= (20.00*Multiplier)) && (LockedProfit == NormalizeDouble(5.00*Multiplier, 2))) ProfitLock = (11.00*Multiplier);
   if ((MyAccountProfit >= (25.00*Multiplier)) && (LockedProfit == -999999.00)) ProfitLock = (2.00*Multiplier);
   ProfitLock = NormalizeDouble(ProfitLock, 2);
   if (ProfitLock > LockedProfit)
   {
      LockedProfit = ProfitLock;
      SaveLockedProfit(LockedProfit);
   }
   
   //below is just used in user comments
   if (LockedProfit == -999999.00 || EnableLocking == False) {
      ProfitLocked = 0.00;
   } else {
      ProfitLocked = LockedProfit;
   }
   
   return;
}


// Added by robert to avoid endless loop when other orders are open not placed by this EA
// Combined GetOrdersTotal with CheckTradeType
int GetOrdersTotal() {
// Safer to keep this local
   int myTotalOrders;
   myTotalOrders = OrdersTotal();
   
// reset Buys and Sells to 0 to fix comments bug
   Buys=0;
   Sells=0;
   Trade = NONE;
   
   if(myTotalOrders > 0) {
//      Buys=0;
//      Sells=0;
      for(int cnt=0;cnt<myTotalOrders;cnt++) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if(OrderMagicNumber() == Magicnumber) {
            if(OrderType()==OP_BUY) Buys=Buys+1;
            else if(OrderType()==OP_SELL) Sells=Sells+1;
         }
      }
      if(Sells > Buys) Trade = SELL_ALL;
      else if(Sells < Buys) Trade = BUY_ALL;
      myTotalOrders = Buys + Sells;
   }
   SaveTrade(Trade);
   
   return(myTotalOrders);
}

void T101_CloseAll() {
   int myOrderType;
   bool CloseOrder;
   int AllPos;
   int OpenOrders = GetOrdersTotal();
   while(OpenOrders > 0) {
// AllPos - 1 because order numbers start at 0
      AllPos = OrdersTotal();
      for (int i = AllPos - 1; i >= 0; i--) {
// Put back to i because fifo rule should still be met
         OrderSelect(i, SELECT_BY_POS);
//         OrderSelect(0, SELECT_BY_POS);
         if (OrderMagicNumber()==Magicnumber) {
            myOrderType = OrderType();
            CloseOrder = FALSE;
            switch (myOrderType) {
            case OP_BUY:
               CloseOrder = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red);
// All checks are done in local functions
//               OpenOrders = OpenOrders - 1;
//               TotalOrders = TotalOrders - 1;
               break;
            case OP_SELL:
               CloseOrder = OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red);
// All checks are done in local functions
//               OpenOrders = OpenOrders - 1; 
//               TotalOrders = TotalOrders - 1;
               break;
            case OP_BUYLIMIT:
            case OP_BUYSTOP:
            case OP_SELLLIMIT:
            case OP_SELLSTOP:
               CloseOrder = OrderDelete(OrderTicket());
            }  
         }
      }
// Out of loop so check if any open orders from this EA failed to close 
      OpenOrders = GetOrdersTotal();
      
   }
   ObjectsDeleteAll();
   Trade = NONE;
   SaveTrade(Trade);
   BuyCondition1 = False;
   SellCondition1 = False;
   BuyCondition2 = False;
   SellCondition2 = False;
   BuyCondition3 = False;
   SellCondition3 = False;
   BuyCondition4 = False;
   SellCondition4 = False;
   BuyAlertDone = False;
   SellAlertDone = False;
   
// This should fix the profit lock bug

   Reset();
   
   return;
}

void ShowCommentsThen() {
   
   string value1,value2,value3,value4;
   int Cond4Round;
   
   if(sum_red > 0 && sum_blue < 0) value1 = "SHORT (Strong)"; else if(sum_red > sum_blue && (sum_red > 0 && sum_blue > 0)) value1 = "SHORT (Weak)";
   else if(sum_blue > 0 && sum_red < 0) value1 = "LONG (Strong)"; else if(sum_blue > sum_red && (sum_blue > 0 && sum_red > 0)) value1 = "LONG (Weak)"; else value1 = "NONE";
   
   if(Period() == 15 || Period() == 60) value2 = "Daily";
   else if(Period() == 240) value2 = "Weekly";
   
   if(UseCurrencyValue == True) {
      value3 = "$ ";
      Cond4Round = 2;
      value4 = " (assuming 1 mini lot per pair)";
   } else {
      value3 = "";
      Cond4Round = RoundTo;
      value4 = " (pips)";
   }

   string value8,value9;
   if ((MyAccountProfit < (500*Multiplier)) && (LockedProfit == (401.00*Multiplier))) { value8 = (500*Multiplier); value9 = (451.00*Multiplier); }
   if ((MyAccountProfit < (450.00*Multiplier)) && (LockedProfit == (351.00*Multiplier))) { value8 = (450*Multiplier); value9 = (401.00*Multiplier); }
   if ((MyAccountProfit < (400.00*Multiplier)) && (LockedProfit == (301.00*Multiplier))) { value8 = (400*Multiplier); value9 = (351.00*Multiplier); }
   if ((MyAccountProfit < (350.00*Multiplier)) && (LockedProfit == (251.00*Multiplier))) { value8 = (350*Multiplier); value9 = (301.00*Multiplier); }
   if ((MyAccountProfit < (300.00*Multiplier)) && (LockedProfit == (201.00*Multiplier))) { value8 = (300*Multiplier); value9 = (251.00*Multiplier); }
   if ((MyAccountProfit < (250.00*Multiplier)) && (LockedProfit == (151.00*Multiplier))) { value8 = (250*Multiplier); value9 = (201.00*Multiplier); }
   if ((MyAccountProfit < (200.00*Multiplier)) && (LockedProfit == (101.00*Multiplier))) { value8 = (200*Multiplier); value9 = (151.00*Multiplier); }
   if ((MyAccountProfit < (150.00*Multiplier)) && (LockedProfit == (71.00*Multiplier))) { value8 = (150*Multiplier); value9 = (101.00*Multiplier); }
   if ((MyAccountProfit < (100.00*Multiplier)) && (LockedProfit == (46.00*Multiplier))) { value8 = (100*Multiplier); value9 = (71.00*Multiplier); }
   if ((MyAccountProfit < (70.00*Multiplier)) && (LockedProfit == (22.00*Multiplier))) { value8 = (70*Multiplier); value9 = (46.00*Multiplier); }
   if ((MyAccountProfit < (50.00*Multiplier)) && (LockedProfit == (15.00*Multiplier))) { value8 = (50*Multiplier); value9 = (22.00*Multiplier); }
   if ((MyAccountProfit < (36.00*Multiplier)) && (LockedProfit == (2.00*Multiplier))) { value8 = (36*Multiplier); value9 = (15.00*Multiplier); }
   //if ((MyAccountProfit < (30.00*Multiplier)) && (LockedProfit == (11.00*Multiplier))) { value8 = (30*Multiplier); value9 = (21.00*Multiplier); }
   //if ((MyAccountProfit < (20.00*Multiplier)) && (LockedProfit == (5.00*Multiplier))) { value8 = (20*Multiplier); value9 = (11.00*Multiplier); }
   if ((MyAccountProfit < (25.00*Multiplier)) && (LockedProfit == -999999.00)) { value8 = (25.00*Multiplier); value9 = (2.00*Multiplier); }
   
   Comment(
   "-----------------------------------" + "\n" + 
   "T101ProfitProtectEnhanced" + "\n" +
   "--------------------------------------" + "\n" +
   "Account Balance = $ " + DoubleToStr(MyAccountBalance,2) + "\n" +
   "Account Leverage = " + DoubleToStr(AccountLeverage(),0) + ":1" + "\n" +
   "MARGIN CALL ?  " + MARGIN_CALL + "\n" +
   "Total Possible Loss = $ " + DoubleToStr(TotalLoss,2) + "\n" +
   "Total Margin Requirement = $ " + DoubleToStr(TotalMarginRequirement,2) + "\n" +
   "Lots = " + DoubleToStr(Lots,2) + MicroLotInfo + LotsOverrideInfo + "\n" +
   "--------------------------------------" + "\n" +
   "Basket Profit = $ " + DoubleToStr(MyAccountProfit,2) + "\n" + 
   "Profit Locked = $ " + DoubleToStr(ProfitLocked,2) + " (Must go above " + value8 + " to lock " + value9 + ")" + "\n" + 
   "Stop Loss = $ " + DoubleToStr(ProfitStopLoss,2) + "\n" +
   "Take Profit = $ " + DoubleToStr(TakeProfit,2)  + "\n" +
   "Default Spread = " + DoubleToStr(TotalSpread,1)  + "\n" +
   "Actual Spread = " + DoubleToStr(TotalSpreadActual,1)  + "\n" +
   "--------------------------------------" + "\n" +
   "If using DonsMM, User Set basket Stop Loss Percent = " + DoubleToStr(DonsMM_BasketRiskPercent,2) + " %" + "\n" +
   "Actual Basket Stop Loss Percent = " + DoubleToStr((((-ProfitStopLoss)/MyAccountBalance)*100),2) + " %" + "\n" + 
   "Total Stop Loss Percent = " + DoubleToStr(((-ProfitStopLoss)/MyAccountBalance)*100,2) + " %" + "\n" + 
   "Take Profit Percent = " + DoubleToStr((TakeProfit/MyAccountBalance)*100,2) + " %" + "\n" + 
   "--------------------------------------" + "\n" +
   "TrendMagic_Blue_1 = " + DoubleToStr(TrendMagic_Blue_1,4) + ", " + "TrendMagic_Red_1 = " + DoubleToStr(TrendMagic_Red_1,4) + "\n" +
   "LastCandleClose = " + DoubleToStr(LastCandleClose,Digits) + "\n" +
   "BuyCondition1 = " + BuyCondition1 + ", " + "SellCondition1 = " + SellCondition1 + "\n" +
   "-----------------------------------" + "\n" +
   "MACD_Main = " + DoubleToStr(MACD_Main,4) + ", " + "MACD_Signal = " + DoubleToStr(MACD_Signal,4) + "\n" +
   "BuyCondition2 = " + BuyCondition2 + ", " + "SellCondition2 = " + SellCondition2 + "\n" +
   "-----------------------------------" + "\n" +
   "BI_Red = " + DoubleToStr(BI_Red,4) + ", " + "BI_Blue = " + DoubleToStr(BI_Blue,4) + "\n" +
   "BuyCondition3 = " + BuyCondition3 + ", " + "SellCondition3 = " + SellCondition3 + "\n" +
   "-----------------------------------" + "\n" + 
   "sum_blue = " + value3 + DoubleToStr(sum_blue,Cond4Round) + ", " + "sum_red = " + value3 + DoubleToStr(sum_red,Cond4Round) + value4 + "\n" +
   value2 + " Trend = " + value1 + "\n" +
   "BuyCondition4 = " + BuyCondition4 + ", " + "SellCondition4 = " + SellCondition4 + "\n" +
   "-----------------------------------" + "\n" +
   "Trade =  " + Trade + ", #Buys:  " + Buys + ", #Sells:  " + Sells
   );
   
   return;
}


// Return true if time is not in session for trading
bool CheckOutsideSession( int StartHour, int EndHour, int ct)
{
  if(StartHour<=EndHour)
  {
    if(ct < StartHour || ct > EndHour) return(true) ;
  }
  else
  {
    if(ct > EndHour && ct < StartHour) return(true) ;
  }
  return(false) ;
}

bool CheckTradingTimes()
{
   bool StopTrading;
   int ct;
   ct = Hour() * 100 + Minute();
   
    if (UseTradingHours == false) return(false);
    
    StopTrading = true;
    
// Check trading Asian Market
     if (TradeAsianMarket == true)
     {
        StopTrading = CheckOutsideSession(AsianStart, AsianStop, ct);
     }
     if (StopTrading == true)
     {
// Check trading European Market
       if (TradeEuropeanMarket == true)
       {
         StopTrading = CheckOutsideSession(EurStart, EurStop, ct);
       }
     }
     if (StopTrading == true)
     {
// Check trading New York Market
       if (TradeNewYorkMarket == true)
       {
         StopTrading = CheckOutsideSession(NYStart, NYStop, ct);
       }
     }
     
     return(StopTrading);
}

string tf2txt(int tf)
{
   switch(tf)
   {
      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_W1: return("W1");
      case PERIOD_MN1: return("MN");
   
   }
   return("??");
}

void GetGlobalVars()
{
   NameGlobalVars();
   InitGlobalVars();
   GetGlobalVarValues();
}
  
void GetGlobalVarValues()
{
   double temp;

// Booleans stored as double so convert to boolean
// > 0 true, < 0 false

//    temp = GlobalVariableGet(gFirst_TP_LevelName);
//    if (temp > 0) First_TP_Level = true; else First_TP_Level = false;
    
    Trade = GlobalVariableGet(gTradeName);
    LockedProfit = GlobalVariableGet(gLockedProfitName);
}

void InitGlobalVars()
{

// check variable before use

//  if(!GlobalVariableCheck(gFirst_TP_LevelName))
//    GlobalVariableSet(gFirst_TP_LevelName,-10);
    
  if(!GlobalVariableCheck(gTradeName))
    GlobalVariableSet(gTradeName,NONE);
  if(!GlobalVariableCheck(gLockedProfitName))
    GlobalVariableSet(gLockedProfitName,0);

}

void NameGlobalVars()
{
   string  prefix;

   prefix = "T101_" + Symbol() +  tf2txt(Period());

   gTradeName = prefix + "_Trade";
   gLockedProfitName = prefix + "_LockedProfit";
}

//void SaveFirst_TP_Level(bool myVal)
//{
//    if (myVal == true)
//       GlobalVariableSet(gFirst_TP_LevelName,10.0);
//    else
//       GlobalVariableSet(gFirst_TP_LevelName,-10.0);
//}

void SaveTrade(int myVal)
{
    GlobalVariableSet(gTradeName,myVal);
}
    
void SaveLockedProfit(double myVal)
{
    GlobalVariableSet(gLockedProfitName,myVal);
}
    
//+------------------------------------------------------------------+

// ----------------Charvo Added Function---------------------
//                       SUBROUTINES
// ----------------Charvo Added Function---------------------
 bool CheckRecntCrx(int lookback, int updn) 
 {
   // updn: 1 to check cross up; -1 to check cross down;
   int i;
   double BuyAll_fast, BuyAll_slow, BuyAll_fast_pre, BuyAll_slow_pre;
   int cross;

   for(i=0; i<=lookback;i++)
   {
      BuyAll_fast = iCustom(NULL,0,"BI_T101_OTR_V1_5",10,5,288,0.0,0.0,"Check_Candle : 0 for current , 1 for last closed candle",0,false," 0 for S_R , 1 for Fast/Slow cross",1,"Alert.wav","Alert2.wav",false,0,i);
      BuyAll_slow = iCustom(NULL,0,"BI_T101_OTR_V1_5",10,5,288,0.0,0.0,"Check_Candle : 0 for current , 1 for last closed candle",0,false," 0 for S_R , 1 for Fast/Slow cross",1,"Alert.wav","Alert2.wav",false,1,i);
      BuyAll_fast_pre = iCustom(NULL,0,"BI_T101_OTR_V1_5",10,5,288,0.0,0.0,"Check_Candle : 0 for current , 1 for last closed candle",0,false," 0 for S_R , 1 for Fast/Slow cross",1,"Alert.wav","Alert2.wav",false,0,i+1);
      BuyAll_slow_pre = iCustom(NULL,0,"BI_T101_OTR_V1_5",10,5,288,0.0,0.0,"Check_Candle : 0 for current , 1 for last closed candle",0,false," 0 for S_R , 1 for Fast/Slow cross",1,"Alert.wav","Alert2.wav",false,1,i+1);

      if ( updn==1 && (BuyAll_fast>BuyAll_slow+0.002 && BuyAll_fast_pre<=BuyAll_slow_pre) )  cross = 1;
      if ( cross != 0 ) break;
      if ( updn==-1 && (BuyAll_fast<BuyAll_slow-0.002 && BuyAll_fast_pre>=BuyAll_slow_pre) )  cross = -1;
      if ( cross != 0 ) break;
   }     
 
   //if (cross != 0) Print("XXXXXX Cross is found for ", cross, " around ", i, "th bar!XXXXXX");
   
   return(cross);
      
 } 

