//+-----------------------------------------------------------------------------------+
//|                                                  PLUM_CRAZY6_function_version.mq4 |
//|                                                 Copyright © 2008, David E. Fulton |
//|                                                            www.defulton.com/forex |
//|                                                       Copyright © 2009, spike2009 |
//|                                                 http://bulldogge1232000@yahoo.com |
//|                                                                                   |
//| 4/26/2009                                                                         |
//| Modified by Robert Hill                                                           |
//|    5 digit price handling                                                         |
//|    Market Orders for ECN Brokers                                                  |
//| 5/5/2009                                                                          |
//|    Broke code into functions for easier changes                                   |
//|    Modified to use internal stoploss and takeprofit                               |
//|     for better control of trades                                                  |
//|     and for log file messages                                                     |
//|    Added Log files                                                                |
//|    Added defines for easier reading of myOrderType 1-SHORT, 2-LONG, 3-NONE        |
//+-----------------------------------------------------------------------------------+

///Please, do not sell this EA because its FREE

#property copyright "Copyright © 2009, spike2009"
#property link      " bulldogge1232000@yahoo.com "

// Added by Robert for better error messages
#include <stdlib.mqh>
#include <stderror.mqh>

// myOrderType for easier read of code
#define SHORT 1
#define LONG 2
#define NONE 3

extern string    INFO="PLUM_CRAZY6_function_version";
extern string    OWN="Copyright © 2009, spike2009";
extern string    magicnumber="--MAgic No--";
extern int       MagicNumberBase=220000;               // Magic number for the orders placed
//extern int       MagicNumber=222777;               // Magic number for the orders placed
extern string    sq="--STOCH SETTING--";
extern double    step = 0.7;                          // order spacing                  // setting change
extern int       K_Period = 29;                                                         // setting change  
extern int       D_Period = 4;                                                          // setting change 
extern int       Slow_Period = 16;                                                      // setting change
extern int       Stoch_TF1 = 1;                      // Primary stoch time frame
extern int       Stoch_TF2 = 1;                      // Secondary stoch time frame
extern int       shift=1;
extern int       H_level =78;
extern int       L_level =22;
extern int       H_level_1 =60;
extern int       L_level_1 =40;
extern string    ChooseLineMode="Choose 1=mode main, 2=mode signal";
extern int       stochlinemode = 1;
extern string    ChooseeMAMode="Choose 1=mode SMA, 2=mode LWMA, 3=mode EMA, 4=mode SMMA";            // setting change
extern int       stochMAmode = 2;
extern bool      ExitWithSTOCH=False;
extern string    se="--ENVELOPE SETTINGS--";
extern int       ENVELOPE_Slow_Period = 13;                                                         // setting change   
extern int       ENVELOPE_TF = 1440;
extern string    ma="--MOVING AVERAGE SETTINGS--";                                                  // setting change
extern int       MA_Period = 50;                                                                    // setting change
extern int       MA_Slow_Period = 200;                                                              // setting change
extern int       MA_TF_1 = 1;                                                                       // setting change    
extern int       MA_TF_2 = 5;                                                                       // setting change    
extern string    rs="--RSI SETTINGS--";
extern int       RSI_Period = 14;
extern int       RSI_Period_2 = 4;
extern int       RSI_TF_1 = 1;
extern int       RSI_HL = 70;
extern int       RSI_LL = 30;
extern int       RSI_HL_2 = 90;
extern int       RSI_LL_2 = 10;
extern string    rv="--RVI SETTINGS--";
extern int       RVI_Period = 18;
extern int       RVI_TF = 1;
extern string    sb="--TRADE SETTING--";
extern double    Lots = 0.01;                       // We start with this lots number
extern int       TakeProfit = 33;                   // Profit Goal for the latest order opened
extern double    SafetyTakeProfitMultiplier = 1.5;
int              InternalTakeProfit;
extern bool      MyMoneyProfitTarget=False;
extern double    My_Money_Profit_Target=45;
extern double    multiply=2.0; 
extern int       MaxTrades=4;                      // Maximum number of orders to open
extern int       Pips=14;                           // Distance in Pips from one order to another
extern int       StopLoss = 0;                     // StopLoss
extern double    SafetyStopLossMultiplier = 1.5;
int              InternalStopLoss;
extern int       TrailingStop = 0;                 // Pips to trail the StopLoss
extern string    MM="--MOney Management--";        // (from order 2, not from first order
extern string    MMSwicth="if one the lots size will increase based on account size";
extern int       mm=1;                             // if one the lots size will increase based on account size
extern string    riskset="risk to calculate the lots size (only if mm is enabled)";
extern int       risk=10;                           // risk to calculate the lots size (only if mm is enabled)    // setting change 
extern string    accounttypes="0 if Normal Lots, 1 for mini lots, 2 for micro lots";
extern int       AccountType=2;                    // 0 if Normal Lots, 1 for mini lots, 2 for micro lots
extern string    so="--CUTLOSS SETTING--";
extern bool      SecureProfitProtection=False;
extern string    SP="If profit made is bigger than SecureProfit we close the orders";
extern int       SecureProfit=22;                 // If profit made is bigger than SecureProfit we close the orders
extern string    OTP="Number of orders to enable the account protection";
extern int       OrderstoProtect=3;               // Number of orders to enable the account protection
extern string    ASP="if one will check profit from all symbols, if cero only this symbol";
extern bool      AllSymbolsProtect=False;         // if one will check profit from all symbols, if cero only this symbol
extern string    EP="if true, then the expert will protect the account equity to the percent specified";
extern bool      EquityProtection=False;          // if true, then the expert will protect the account equity to the percent specified
extern string    AEP="percent of the account to protect on a set of trades";
extern int       AccountEquityPercentProtection=90; // percent of the account to protect on a set of trades
extern string    AMP="if true, then the expert will use money protection to the USD specified";
extern bool      AccountMoneyProtection=False;
extern double    AccountMoneyProtectionValue=3000.00;
string           s1="--seting berapa jam dia nak open order--";
bool             UseHourTrade = False;
int              FromHourTrade = 0;
int              ToHourTrade = 1;

extern string    TradingTime="--trading time setting--";
extern bool      UseTradingHours = True;
extern bool      TradeAsianMarket = true;
extern int       StartHour1 = 11;              // Start trades after time
extern int       StopHour1 = 23;               // Stop trading after time
extern bool      TradeEuropeanMarket = true;
extern int       StartHour2 = 6;               // Start trades after time                                 // setting change    
extern int       StopHour2 = 11;               // Stop trading after time
extern bool      TradeNewYorkMarket = false;
extern int       StartHour3 = 15;              // Start trades after time
extern int       StopHour3 = 17;               // Stop trading after time
extern bool      TradeOnFriday=True;
extern string    OtherSetting="--Others Setting--";
extern int       OrdersTimeAlive=0;            // in seconds
extern string    reverse="if one the desition to go long/short will be reversed";
extern bool      ReverseCondition=False;       // if one the desition to go long/short will be reversed
extern string    limitorder="if true, instead open market orders it will open limit orders ";
extern bool      SetLimitOrders=False;         // if true, instead open market orders it will open limit orders 
extern int       Manual=0;                     // If set to one then it will not open trades automatically

// Create a trade log to determine if EA is trading correctly

extern string  db="--- Debug file settings---";
extern bool    Debug = false;
//extern bool    Debug_Expert = false;
extern bool    Debug_LiveTrade = false;                    // Change to true to allow debug Trade log file to be created
extern string  Trade_Log = "_PC6_TradeLog";
extern bool    Debug_BackTestTrade = false;                   // Change to true to allow Backtest debug Trade log file to be created
extern string  BT_Trade_Log = "_PC6_BTTradeLog";   // Backtest trade log. Writes when backtest is complete.

color            ArrowsColor=Black;            // color for the orders arrows


int              OpenOrdersBasedOn=120;         // Method to decide if we start long or short
bool             ContinueOpening=True;

int              OpenOrders=0, cnt=0;
int              MarketOpenOrders=0,           LimitOpenOrders=0;
int              slippage=5;
double           sl=0,                         tp=0;
double           BuyPrice=0,                   SellPrice=0;
double           lotsi=0,                      mylotsi=0;
int              mode=0,                       myOrderType=0,                    myOrderTypetmp=0;

double           LastPrice=0;
int              PreviousOpenOrders=0;
double           Profit=0;
int              LastTicket=0,                 LastType=0;
double           LastClosePrice=0,             LastLots=0;
double           Pivot=0;
double           PipValue=0;
bool             Reversed=False;
double           tmp=0;
double           iTmpH=0;
double           iTmpL=0;
datetime         NonTradingTime[][2];
bool             FileReaded=false;
string           dateLimit = "2030.01.12 23:00";
int              CurTimeOpeningFlag=0;
datetime         LastOrderOpenTime=0;
bool             YesStop;

// Added by Robert

string version="Spikes_Martingale_From_Hell"; // Moved from Start
string text;
double           myPoint;
int              err;

string   filenameTradeLog,filenameBTTradeLog;
int MagicID, MagicNumber[10];

string      gHighBidName[10];
string      gLowBidName[10];
string      gHighAskName[10];
string      gLowAskName[10];

double      HighBid[10], LowBid[10], HighAsk[10], LowAsk[10];

string      gIntTPpriceName[10];
string      gIntSTpriceName[10];

double      IntSTprice[10];
double      IntTPprice[10];
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//---- 
   myPoint = SetPoint(); // Added by Robert
   
// Moved from Start

   PipValue=MarketInfo(Symbol(),MODE_TICKVALUE); 
   
   if (PipValue==0) { PipValue=5; }


  if (IsTesting() == true)// Do not do account number check in test mode
  {
    if (Debug_LiveTrade == true) Debug_LiveTrade = false;
  }
  if ((IsTesting() == false) && (Debug_BackTestTrade == true)) Debug_BackTestTrade = false;

	  MagicID = MagicNumberBase + func_Symbol2Val(Symbol())*100 + func_TimeFrame_Const2Val(Period());
	  for (int i = 0; i < 10;i++) MagicNumber[i] = MagicID + i;

     if (Debug == true) SetupLogFiles();
     GetGlobalVars();
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//---- 
   if (Debug == true) CloseLogFiles();
   DeleteAllObjects();
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//**************ADDED FOR ACCOUNT SENTRY ***************
  
      if (GlobalVariableGet("GV_CloseAllAndHalt") > 0){
      return (0);
      } else
      
//**************END ACCOUNT SENTRY HOOK ****************
   

   //--- Set Margin counter ---------------------------- WJ Begin --//
   //--- Init Code ---//
   string GlobValMargin = AccountNumber()+"_Stoch-Power-EA-5h_Margin";
   if(!GlobalVariableCheck(GlobValMargin)) GlobalVariableSet(GlobValMargin,0);
   double AcctMargin = GlobalVariableGet(GlobValMargin);

   //--- Start Code ---//
   double AcctMarginCurr = AccountMargin();
   if(AcctMargin < AcctMarginCurr){
      AcctMargin = AcctMarginCurr;
      GlobalVariableSet(GlobValMargin,AcctMargin);
   }
   //--------------------------------------------------- WJ End ----//

  
//---- 
   text="";

   lotsi= GetLots();
   
   TrackPrices();
   CheckForCloseTrades();   
   GetOpenOrders();
   
   if (OpenOrders<1) 
   {
	  if (!TradeOnFriday && DayOfWeek()==5) 
	  {
	    Comment("TradeOnfriday is False");
	    return(0);
	  }
   }
   
   PreviousOpenOrders=OpenOrders;
      
   if (OpenOrders>=MaxTrades) 
   {
	  ContinueOpening=False;
   } else {
	  ContinueOpening=True;
   }

   if (LastPrice==0) GetLastPrice();

  myOrderTypetmp=NONE;
  switch (OpenOrdersBasedOn)
  {  
     case 16:
       myOrderTypetmp=OpenOrdersBasedOnSTOCH();
       break; 	
     default: 
        myOrderTypetmp=OpenOrdersBasedOnSTOCH();
        break;
  }
  
   if (OpenOrders<1 && Manual==0) 
   {
     myOrderType=myOrderTypetmp;
	  if (ReverseCondition)
	  {
	  	  if (myOrderType==SHORT) { myOrderType=LONG; }
		  else { if (myOrderType==LONG) { myOrderType=SHORT; } }
	  }
   }   
   if (ReverseCondition)
   {
    if (myOrderTypetmp==SHORT) { myOrderTypetmp=LONG; }
    else { if (myOrderTypetmp==LONG) { myOrderTypetmp=SHORT; } }
   }
   

   YesStop = CheckTradingHours();
     if (YesStop)
     {
//      Comment ("Trading has been stopped as requested - wrong time of day");
       return (0);
     }
     
   // skrip masa trading

      if (!IsTesting()) 
      {
	     if (myOrderType==NONE && OpenOrders<1) { text=text + "\nWaiting for a position"; }
	     //else { text= text + "\n                         "; }
	     Comment(version,"\nLast price=",LastPrice," Previous open orders=",PreviousOpenOrders,"\nContinue opening=",BoolToStr(ContinueOpening)," My order type=",OrdTypeToStr(myOrderType),"\nLot size=",lotsi,text);
      }

      if (ContinueOpening)
      {
        if (OpenOrders<1)
          OpenMarketOrders();
        else
         if (SetLimitOrders) OpenLimitOrders();
         else OpenMarketOrders();
      }

//----
   return(0);
  }
//+------------------------------------------------------------------+


void OpenMarketOrders()
{         
// ---------------------------------   
// Added by Robert for Market Orders 
   bool result;
   int ticket, err;
   double TPprice,STprice;
// ---------------------------------   
   int cnt=0;      
   SaveHighLow(OpenOrders);
      if (myOrderType==SHORT) 
      {	      
	     if ((Bid-LastPrice)>=ÂñåãîÎðäåðîâSell()*step*Pips*myPoint || OpenOrders<1) 
	     {	     		
          Write_Stars();
		    SellPrice=Bid;				
		    LastPrice=0;
		    mylotsi = GetCorrectLots(OpenOrders, lotsi);
		    ticket = OrderSend(Symbol(),OP_SELL,mylotsi,SellPrice,slippage,0,0,"MyMEFx EA"+MagicNumber[OpenOrders],MagicNumber[OpenOrders],0,ArrowsColor);		    		    

// ---------------------------------   
// Added by Robert for Market Orders 

       if (ticket > 0)
       {
         if (OrderSelect( ticket,SELECT_BY_TICKET, MODE_TRADES) ) 
         {
           Print("Sell order opened : ", OrderOpenPrice());
           if (StopLoss != 0 || TakeProfit != 0)
	        {
             TPprice = 0;
             if (TakeProfit > 0)
             {
                TPprice= OrderOpenPrice() - TakeProfit* SafetyTakeProfitMultiplier * myPoint;
                IntTPprice[OpenOrders] = OrderOpenPrice() - TakeProfit * myPoint;
             }
             STprice = 0;
             if (StopLoss > 0)
             {
               STprice=OrderOpenPrice() + StopLoss * SafetyStopLossMultiplier * myPoint;
		         STprice = ValidStopLoss(OP_SELL,Ask, STprice); 
               IntSTprice[OpenOrders]=OrderOpenPrice() + StopLoss * myPoint;
		       }
 // Normalize stoploss / takeprofit to the proper # of digits.
             if (Digits > 0) 
             {
               STprice = NormalizeDouble( STprice, Digits);
               TPprice = NormalizeDouble( TPprice, Digits); 
             }
		       result = OrderModify(ticket, OrderOpenPrice(), STprice, TPprice, 0, LightGreen);
				 if(result!=TRUE)
				 {
// Added by Robert, I like a description
					 err = GetLastError();
					 Print("Modify error (", err, ")", ErrorDescription(err)  );
				 }
         
             if (Debug == true)
             {
               Write_OpenTrade (" "+ Symbol() +" #"+ ticket + " OPEN SELL ORDER "+ DoubleToStr(mylotsi,2) +" LOTS AT " + DoubleToStr(Bid,Digits)+" sl: "+ DoubleToStr(STprice,Digits) + "  tp : " + DoubleToStr(TPprice, Digits)  + " itp : " + DoubleToStr(IntTPprice[OpenOrders],Digits) + "(" + DoubleToStr(TakeProfit,0) + ")");
             }
		     }
         }
       }
       else
       {
          err = GetLastError();
          if(err==0)
          { 
             return;
          }
          else
          {
            if(err==4 || err==137 ||err==146 || err==136) //Busy errors
            {
               Sleep(5000);
            }
            else //normal error
            {
              Print("Error opening Sell order (" + err + ") " + ErrorDescription(err));
            }
          } 
       }
// ---------------------------------   
		    return(0);
	     }
	     
	  //   Sleep(6000);   ////aku letak
        //      RefreshRates(); 
      }
      
      if (myOrderType==LONG) 
      {
	     if ((LastPrice-Ask)>=ÂñåãîÎðäåðîâBuy()*step*Pips*myPoint || OpenOrders<1) 
	     {			      
          Write_Stars();
		    BuyPrice=Ask;
		    LastPrice=0;
		    mylotsi = GetCorrectLots(OpenOrders, lotsi);
		    ticket = OrderSend(Symbol(),OP_BUY,mylotsi,BuyPrice,slippage,0,0,"MyMEFx EA"+MagicNumber[OpenOrders],MagicNumber[OpenOrders],0,ArrowsColor);		    

// ---------------------------------   
// Added by Robert for Market Orders
 
       if (ticket > 0)
       {
        if (OrderSelect( ticket,SELECT_BY_TICKET, MODE_TRADES) ) 
        {
          Print("BUY order opened : ", OrderOpenPrice( ));
          if (StopLoss != 0 || TakeProfit != 0)
	       {
            TPprice = 0;
            if (TakeProfit > 0)
            {
               TPprice = OrderOpenPrice() + TakeProfit * SafetyTakeProfitMultiplier*myPoint;
               IntTPprice[OpenOrders] = OrderOpenPrice() + TakeProfit * myPoint;
            }
            STprice = 0;
            if (StopLoss > 0)
            {
              STprice = OrderOpenPrice() - StopLoss * SafetyStopLossMultiplier*myPoint;
		        STprice = ValidStopLoss(OP_BUY,Bid, STprice);
              IntSTprice[OpenOrders] = OrderOpenPrice() - StopLoss * myPoint;
		      }   
            
 // Normalize stoploss / takeprofit to the proper # of digits.
            if (Digits > 0) 
            {
              STprice = NormalizeDouble( STprice, Digits);
              TPprice = NormalizeDouble( TPprice, Digits); 
              IntSTprice[OpenOrders] = NormalizeDouble( IntSTprice[OpenOrders], Digits);
              IntTPprice[OpenOrders] = NormalizeDouble( IntTPprice[OpenOrders], Digits);
            }
		      result = OrderModify(ticket, OrderOpenPrice(), STprice, TPprice, 0,  LightGreen);
              SaveIntSTprice (OpenOrders,IntSTprice[OpenOrders]);
              SaveIntTPprice (OpenOrders,IntTPprice[OpenOrders]);
				if(result!=TRUE)
				{
// Added by Robert, I like a description
					 err = GetLastError();
					 Print("Modify error (", err, ")", ErrorDescription(err)  );
				}
            if (Debug == true)
            {
               Write_OpenTrade (" "+ Symbol() +" #"+ ticket +  " OPEN BUY ORDER "+ DoubleToStr(mylotsi, 2) +" LOTS AT " + DoubleToStr(Ask,4)+" sl: "+ DoubleToStr(STprice,Digits) + "  tp : " + DoubleToStr(TPprice,Digits)  + " itp : " + DoubleToStr(IntTPprice[OpenOrders],Digits) + "(" + DoubleToStr(TakeProfit,0) + ")");
            }
		    }
        }
      }
      else
      {
        err = GetLastError();
        if(err==0)
        { 
         return;
        }
        else
        {
         if(err==4 || err==137 ||err==146 || err==136) //Busy errors
         {
            Sleep(5000);
         }
         else //normal error
         {
           Print("Error opening BUY order (" + err + ") " + ErrorDescription(err));
           if (Debug == true) Write_OpenError("Error opening BUY order (" + err + ") " + ErrorDescription(err)); 
         }  
        }
      }
// ---------------------------------   
		    return(0);
	     }
      }   
}

void OpenLimitOrders()
{
   int cnt=0;
               
      if (myOrderType==SHORT) 
      {	
	     //if ((Bid-LastPrice)>=Pips*Point || OpenOrders<1) 
	     //{		
		    //SellPrice=Bid;				
		    SellPrice = LastPrice+ÂñåãîÎðäåðîâSell()*step*Pips*myPoint;
		    LastPrice=0;
		    if (TakeProfit==0) { tp=0; }
		    else { tp=SellPrice-TakeProfit*myPoint; }	
		    if (StopLoss==0) { sl=0; }
		    else { sl=SellPrice+StopLoss*myPoint;  }
		    mylotsi = GetCorrectLots(OpenOrders, lotsi);
		    OrderSend(Symbol(),OP_SELLLIMIT,mylotsi,SellPrice,slippage,sl,tp,"MyMEFx EA"+MagicNumber[OpenOrders],MagicNumber[OpenOrders],0,ArrowsColor);		    		    
		    return(0);
	     //}
      }
      
      if (myOrderType==LONG) 
      {
	     //if ((LastPrice-Ask)>=Pips*Point || OpenOrders<1) 
	     //{		
		    //BuyPrice=Ask;
		    BuyPrice=LastPrice-ÂñåãîÎðäåðîâBuy()*step*Pips*myPoint;
		    LastPrice=0;
		    if (TakeProfit==0) { tp=0; }
		    else { tp=BuyPrice+TakeProfit*myPoint; }	
		    if (StopLoss==0)  { sl=0; }
		    else { sl=BuyPrice-StopLoss*myPoint; }
		    mylotsi = GetCorrectLots(OpenOrders, lotsi);
		    OrderSend(Symbol(),OP_BUYLIMIT,mylotsi,BuyPrice,slippage,sl,tp,"MyMEFx EA"+MagicNumber[OpenOrders],MagicNumber[OpenOrders],0,ArrowsColor);		    
		    return(0);
	     //}
      }   

}

void DeleteAllObjects()
{
 int    obj_total=ObjectsTotal();
 string name;
 for(int i=0;i<obj_total;i++)
 {
  name=ObjectName(i);
  if (name!="")
   ObjectDelete(name);
 }
 ObjectDelete("FLP_txt");
 ObjectDelete("P_txt");
}

// 16
int OpenOrdersBasedOnSTOCH()
{
 int myOrderType=3;
 double modest;
  switch (stochlinemode)
  {  
     case 1:
       modest=MODE_MAIN;
       break; 	
     case 2:
       modest=MODE_SIGNAL;
       break; 
     default: 
        modest=MODE_MAIN;
        break;
  }
  
 double mamode;
  switch (stochMAmode)
  {  
     case 1:
       modest=MODE_SMA;
       break; 	
     case 2:
       modest=MODE_LWMA;
       break; 
     case 3:
       modest=MODE_EMA;
       break;
     case 4:                                                   // setting change
       modest=MODE_SMMA;                                          // setting change
       break;                                                     // setting change
     default: 
        modest=MODE_LWMA;
        break;
  }

 //---- lot setting and modifications
 
   double stom1=iStochastic(NULL,Stoch_TF1,K_Period,D_Period,Slow_Period,mamode,0,MODE_MAIN, shift);
   double stom2=iStochastic(NULL,Stoch_TF1,K_Period,D_Period,Slow_Period,mamode,0,MODE_MAIN, shift+3);
     double stom3=iStochastic(NULL,Stoch_TF2,K_Period,D_Period,Slow_Period,mamode,0,MODE_MAIN, shift);
     double stom4=iStochastic(NULL,Stoch_TF2,K_Period,D_Period,Slow_Period,mamode,0,MODE_MAIN, shift+3);
   double stos1=iStochastic(NULL,Stoch_TF1,K_Period,D_Period,Slow_Period,mamode,0,MODE_SIGNAL, shift);
   double stos2=iStochastic(NULL,Stoch_TF1,K_Period,D_Period,Slow_Period,mamode,0,MODE_SIGNAL, shift+3);
     double stos3=iStochastic(NULL,Stoch_TF2,K_Period,D_Period,Slow_Period,mamode,0,MODE_SIGNAL, shift);
     double stos4=iStochastic(NULL,Stoch_TF2,K_Period,D_Period,Slow_Period,mamode,0,MODE_SIGNAL, shift+3);
   double E_upper=iEnvelopes(NULL,ENVELOPE_TF ,ENVELOPE_Slow_Period,MODE_SMA,0,PRICE_CLOSE,0.9,1,1);
   double E_lower=iEnvelopes(NULL,ENVELOPE_TF ,ENVELOPE_Slow_Period,MODE_SMA,0,PRICE_CLOSE,0.9,2,1);
     double ma1=iMA(NULL,MA_TF_1 ,MA_Period,MODE_SMA,0,PRICE_CLOSE,0);                                        // setting change
     double ma2=iMA(NULL,MA_TF_1 ,MA_Slow_Period,MODE_SMA,0,PRICE_CLOSE,0);                                   // setting change
   double ma3=iMA(NULL,MA_TF_2 ,MA_Period,MODE_SMA,0,PRICE_CLOSE,0);                                          // setting change
   double ma4=iMA(NULL,MA_TF_2 ,MA_Slow_Period,MODE_SMA,0,PRICE_CLOSE,0);                                      // setting change

// Added RSI
   double rsi1=iRSI(NULL,RSI_TF_1,RSI_Period, MODE_MAIN,0);
   double rsi2=iRSI(NULL,RSI_TF_1,RSI_Period_2, MODE_MAIN,0);

// Added RVI
    double rvi1=iRVI(NULL,RVI_TF,RVI_Period, MODE_MAIN,0);
   double rvi2=iRVI(NULL,RVI_TF,RVI_Period, MODE_SIGNAL,0);
    double rvi3=iRVI(NULL,RVI_TF,RVI_Period, MODE_MAIN,3);
   double rvi4=iRVI(NULL,RVI_TF,RVI_Period, MODE_SIGNAL,3);

//Sell order
        //  if(previousstoch>H_level && currentstoch<H_level)
         //if(previousstoch>currentstoch && currentstoch > H_level) 
         //if(previousstoch>H_level && previousstoch>currentstoch && currentstoch<H_level)
      if ((stom1<stos1 && stom2>=stos2 && stom2>H_level_1 && rsi1 > RSI_HL && (Low[0] > E_lower && High[0] < E_upper))||
      (stom1<stos1 && stom2>=stos2 && stom2>H_level_1 && rsi2 > RSI_HL_2 && (Low[0] > E_lower && High[0] < E_upper))||
      ( stom3<stos3 && stom4>=stos4 && stom4>H_level_1 && ma1 < ma2 && ma3 < ma4 && rsi1 > 70 &&((Low[0]<E_lower)||(High[0]>E_upper)))||
      (stom1<stos1 && stom2>=stos2 && stom2>H_level && ma3 < ma4 && (Low[0] > E_lower && High[0] < E_upper))||
      (ma2>ma1 && ma4>ma3 && rvi1<rvi2 && rvi4<rvi3 && stom2> H_level && (Low[0] > E_lower && High[0] < E_upper))||
      (stom3<stos3 && stom4>=stos4 && stom4>H_level && ma1 < ma2 && ma3 < ma4 &&((Low[0]<E_lower)||(High[0]>E_upper))))
         //if(previousstoch>H_level && signalstoch > currentstoch)
 {
  myOrderType=SHORT;
 }
 
//buy order
       // if(previousstoch<L_level && currentstoch>L_level)
       //if(previousstoch<currentstoch && currentstoch < L_level)
       //if(previousstoch<L_level && previousstoch<currentstoch && currentstoch>L_level)
     if (( stom1>stos1 && stom2<=stos2 && stom2<L_level_1 && rsi1 < RSI_LL &&(Low[0] > E_lower && High[0] < E_upper))||
     ( stom1>stos1 && stom2<=stos2 && stom2<L_level_1 && rsi2 < RSI_LL_2 &&(Low[0] > E_lower && High[0] < E_upper))||
     ( stom3>stos3 && stom4<=stos4 && stom4<L_level_1 && ma1 > ma2 && ma3 > ma4 && rsi1 < 30 &&((Low[0] < E_lower)||(High[0] > E_upper)))||
     (stom1>stos1 && stom2<=stos2 && stom2<L_level && ma3 > ma4 &&(Low[0] > E_lower && High[0] < E_upper))||
     (ma2<ma1 && ma4<ma3 && rvi1>rvi2 && rvi4>rvi3 &&stom2<L_level && (Low[0] > E_lower && High[0] < E_upper))||
     (stom3>stos3 && stom4<=stos4 && stom4<L_level && ma1 > ma2 && ma3 > ma4 &&((Low[0] < E_lower)||(High[0] > E_upper))))
       // if(previousstoch<L_level && signalstoch < currentstoch)
   
 {
  myOrderType=LONG;
 }

 return(myOrderType);
}



int ÂñåãîÎðäåðîâBuy() {
 
  int res = 0;
  int cnt = OrdersTotal();
  for (int i=0; i < cnt; i++) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    if (OrderSymbol() != Symbol()) continue;

    if(OrderType()==OP_BUY||OrderType()==OP_BUYSTOP) res++;
   }
  return(res);
}
int ÂñåãîÎðäåðîâSell() {
 
  int res = 0;
  int cnt = OrdersTotal();
  for (int i=0; i < cnt; i++) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    if (OrderSymbol() != Symbol()) continue;

    if(OrderType()==OP_SELL||OrderType()==OP_SELLSTOP) res++;
   }
  return(res);
}

// Functions added by Robert

double SetPoint()
{
   double mPoint;
   
   if (Digits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}

double ValidStopLoss(int type, double price, double SL)
{

   double minstop;
   double newSL;
   
   minstop = MarketInfo(Symbol(),MODE_STOPLEVEL);
   if (Digits == 3 || Digits == 5) minstop = minstop / 10;
   newSL = SL;
   if (type == OP_BUY)
   {
		 if((price - SL) < minstop*myPoint) newSL = price - minstop*myPoint;
   }
   if (type == OP_SELL)
   {
       if((SL-price) < minstop*myPoint)  newSL = price + minstop*myPoint;  
   }
   newSL = NormalizeDouble(newSL,Digits);   

   return(newSL);   
}

// Functions created from existing code
double GetLots()
{
   double mlotsi, div;
   
   div = 1;
   
   switch (AccountType)
   {
      case 0 : div = 1; // Standard
               break;
      case 1 : div = 10; // Mini
               break;
      case 2 : div = 100; // Micro
               break;
   }
   
	 if (mm!=0) { mlotsi=MathCeil(AccountBalance()*risk/10000)/div; }
	 else { mlotsi=Lots; }
   
   if (mlotsi<0.01) mlotsi=0.01;
   if (mlotsi>100) mlotsi=100; 
   return(mlotsi);
}

double GetCorrectLots(int myOpenOrders, double myLots)
{
   double mLots;
   
   if (myOpenOrders!=0) 
	{
	    mLots=myLots;			
	    for(cnt=0;cnt<OpenOrders;cnt++)
	    {
	     if (MaxTrades>12) { mLots=NormalizeDouble(mLots*multiply,2); }
	     else { mLots=NormalizeDouble(mLots*multiply,2); }
	    }
	} else { mLots=myLots; }
	if (mLots>100) { mLots=100; }
   return(mLots);
   			    
}

void GetOpenOrders()
{
   OpenOrders=0;
   MarketOpenOrders=0;
   LimitOpenOrders=0;
   for(cnt=0;cnt<OrdersTotal();cnt++)   
   {
     if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
     {
	   if (OrderSymbol()==Symbol() && MyMagicNumber(OrderMagicNumber()) >= 0)
	   {				
	  	  if (OrderType()==OP_BUY || OrderType()==OP_SELL) 
	  	  {
	  	   MarketOpenOrders++;
	  	   LastOrderOpenTime=OrderOpenTime();
	  	  }
	  	  if (OrderType()==OP_SELLLIMIT || OrderType()==OP_BUYLIMIT) LimitOpenOrders++;
	  	  OpenOrders++;
	   }
	  }
   }  
}

bool CheckTradingHours()
{
   bool myStop;
   
  // skrip masa trading
    if (!UseTradingHours) return(false);

     myStop = true;
// Check trading Asian Market
     if (TradeAsianMarket)
     {
        if (StartHour1 > 18)
        {
// Check broker that uses Asian open before 0:00

          if (Hour() >= StartHour1) myStop = false;
          if (!myStop)
          {
            if (StopHour1 < 24)
            {
              if ( Hour() <= StopHour1) myStop = false;
            }
// These cannot be combined even though the code looks the same
            if (StopHour1 >=0)
            {
              if ( Hour() <= StopHour1) myStop = false;
            }
          }
        }
        else
        {
          if (Hour() >= StartHour1 && Hour() <= StopHour1) myStop = false;
        }
     }
     if (myStop)
     {
// Check trading European Market
       if (TradeEuropeanMarket)
       {
         if (Hour() >= StartHour2 && Hour() <= StopHour2) myStop = false;
       }
     }
     if (myStop)
     {
// Check trading New York Market
       if (TradeNewYorkMarket)
       {
         if (Hour() >= StartHour3 && Hour() <= StopHour3) myStop = false;
       }
     }
     
     return(myStop);
}

bool CheckForClose()
{
   bool result;   

   if (AccountMoneyProtection && AccountBalance()-AccountEquity()>=AccountMoneyProtectionValue)
   {
    text = text + "\nClosing all orders and stop trading because account money protection activated..";
    Print("Closing all orders and stop trading because account money protection activated.. Balance: ",AccountBalance()," Equity: ",AccountEquity());
    PreviousOpenOrders=OpenOrders+1;
    ContinueOpening=False;
    return(true);
   }
   
   ////aku masukkan time
   if (UseHourTrade){
      if (!(Hour()>=FromHourTrade && Hour()<=ToHourTrade)) {
    text = text + "\nNot the designated trading hours.";
    Print("Not the designated trading hours. Profit: ",AccountProfit()," Equity: ",AccountEquity());
    PreviousOpenOrders=OpenOrders+1;
    ContinueOpening=False;
    return(true);
   }
}
   //set my profit for one Day
   if (MyMoneyProfitTarget && AccountProfit()>= My_Money_Profit_Target)
   {
    text = text + "\nClosing all orders and stop trading because mymoney profit target reached..";
    Print("Closing all orders and stop trading because mymoney profit target reached.. Profit: ",AccountProfit()," Equity: ",AccountEquity());
    PreviousOpenOrders=OpenOrders+1;
    ContinueOpening=False;
    return(true);
   }
   // Account equity protection 
   if (EquityProtection && AccountEquity()<=AccountBalance()*AccountEquityPercentProtection/100) 
	 {
	 text = text + "\nClosing all orders and stop trading because account money protection activated.";
	 Print("Closing all orders and stop trading because account money protection activated. Balance: ",AccountBalance()," Equity: ", AccountEquity());
	 //Comment("Closing orders because account equity protection was triggered. Balance: ",AccountBalance()," Equity: ", AccountEquity());
	 //OrderClose(LastTicket,LastLots,LastClosePrice,slippage,Orange);		 
	 PreviousOpenOrders=OpenOrders+1;
	 ContinueOpening=False;
	 return(true);
   }
     
   // if dont trade at fridays then we close all
   if (!TradeOnFriday && DayOfWeek()==5)
   {
    PreviousOpenOrders=OpenOrders+1;
    ContinueOpening=False;
    text = text +"\nClosing all orders and stop trading because TradeOnFriday protection.";
    Print("Closing all orders and stop trading because TradeOnFriday protection.");
    return(true);
   }
   
   // Orders Time alive protection
   if (OrdersTimeAlive>0 && CurTime() - LastOrderOpenTime>OrdersTimeAlive)
   {
    PreviousOpenOrders=OpenOrders+1;
    ContinueOpening=False;
    text = text + "\nClosing all orders because OrdersTimeAlive protection.";
    Print("Closing all orders because OrdersTimeAlive protection.");
    return(true);
   }
   
   // SecureProfit protection
  //if (SecureProfitProtection && MarketOpenOrders>=(MaxTrades-OrderstoProtect)
  // Modified to make easy to understand 
  if (SecureProfitProtection && MarketOpenOrders>=OrderstoProtect) 
   {
	  Profit=0;
     for(cnt=0;cnt<OrdersTotal();cnt++)
     {
      if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
      {
       if ((OrderSymbol()==Symbol() && MyMagicNumber(OrderMagicNumber()) >= 0) || AllSymbolsProtect)
        Profit=Profit+OrderProfit();         
      }
     }	    
	  if (Profit>=SecureProfit) 
	  {
	     text = text + "\nClosing orders because account protection with SecureProfit was triggered.";
	     Print("Closing orders because account protection with SeureProfit was triggered. Balance: ",AccountBalance()," Equity: ", AccountEquity()," Profit: ",Profit);
	     PreviousOpenOrders=OpenOrders+1;
		  ContinueOpening=False;
		  return(true);
	  }
   }
   
   return(false);
}



void CloseAllTrades(string msg)
{
   int cnt, mode, which;
   
	  for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
	  {
	     if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
	     {
         which = MyMagicNumber(OrderMagicNumber());
		   if (which >= 0)
		   {
		     if ((OrderSymbol()==Symbol()) || AllSymbolsProtect) 
		     {
	  	       mode=OrderType();
		 	    if (mode==OP_BUY || mode==OP_SELL)
		 	    { 
              if (Debug == true) WriteTradeExit(msg, OrderTicket(), OrderType(), OrderOpenPrice(), OrderLots(), which);
		 	     OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),slippage,ArrowsColor);
	 		    }
		 	    if (mode==OP_SELLLIMIT || mode==OP_BUYLIMIT || mode==OP_BUYSTOP || mode==OP_SELLSTOP)
		 	    {
			     OrderDelete(OrderTicket());
	 		    }
	 		 }
		  }
		 }
	  }

}

void CheckForCloseTrades()
{
   if (CheckForClose())
   {
      CloseAllTrades("Profit/Loss Exit");
      return;
   }
   for (int i=0; i < MaxTrades; i++) CheckForClose2(MagicNumber[i], IntSTprice[i], IntTPprice[i], i);
}
//+------------------------------------------------------------------+
//|                                          CheckExitTrades_inc.mqh |
//|                                                 Copyright © 2007 |
//|                                                                  |
//+------------------------------------------------------------------+

void CheckForClose2(int MagicID, double IntSTprice, double IntTPprice, int which)
{
   bool Done;
   int ticket, OrderTy;
   double OrderLTS, OrderOP, OrderCL;
   double OrderTP, OrderSL; 
   
   for(int i=OrdersTotal()-1;i>=0;i--)
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol()) continue;
      if(OrderMagicNumber()!=MagicID) continue;
      
      ticket = OrderTicket();
      OrderTy = OrderType();
      OrderLTS = OrderLots();
      OrderOP = OrderOpenPrice();
      OrderCL = OrderClosePrice();
      OrderTP = OrderTakeProfit();
      OrderSL = OrderStopLoss();
      
// Check for TakeProfit Exits

      Done = false;
      Done = CheckTPClose(OrderTy, IntTPprice);
      if (Done == true) return;

       
// Check for internal StopLoss

      Done = false;
      Done = CheckSLClose(OrderTy, IntSTprice);
      if (Done == true) return;
      
// Check for exit on signal

      Done = false;
      Done = CheckExit(OrderTy);
      if (Done == true) return;
      
// If we get to here the trade is still Open

      HandleTrailingStop(OrderTy, ticket, OrderOP, OrderCL, OrderSL, OrderTP);
   }
   return;
}

void HandleTrailingStop(int cmd, int myTicket, double myOpenPrice, double myClosePrice, double oSL, double oTP)
{
  int result, err;
     if (TrailingStop>0) 
	{
	  	  if (cmd==OP_SELL) 
	  	  {		
				  if ((myOpenPrice-myClosePrice)>=(TrailingStop*myPoint+Pips*myPoint)) 
				  {						
					 if (oSL>(myClosePrice+TrailingStop*myPoint))
					 {										    
					    result=OrderModify(myTicket,myOpenPrice,myClosePrice+TrailingStop*myPoint,myClosePrice-TakeProfit*myPoint-TrailingStop*myPoint,0,Purple);
					    if(result!=TRUE)
					    {
// Added by Robert, I like a description
					       err = GetLastError();
					       Print("LastError (", err, ")", ErrorDescription(err)  );
					    }
                   else OrderPrint();
	  					 return(0);	  					
	  				 }
	  			  }
	  	  }
   
	  	  if (cmd==OP_BUY)
	  	  {
			   if ((myClosePrice-myOpenPrice)>=(TrailingStop*myPoint+Pips*myPoint)) 
				{
					if (oSL<(myClosePrice-TrailingStop*myPoint)) 
					{					   
					   result=OrderModify(myTicket,myOpenPrice,myClosePrice-TrailingStop*myPoint,myClosePrice+TakeProfit*myPoint+TrailingStop*myPoint,0,ArrowsColor);		
					   if(result!=TRUE)
					   {
// Added by Robert, I like a description
					      err = GetLastError();
					      Print("LastError (", err, ")", ErrorDescription(err) ); 
					   }                 
                  else OrderPrint();
                  return(0);
					}
  				}
	  	  }
	}
}

bool CheckSLClose(int cmd , double IntSTprice)
{
   if (cmd == OP_BUY)
   {
         
       if(Bid <= IntSTprice)
       {
//          if (Debug == true) WriteTradeExit("StopLoss Exit", ticket, OP_BUY, op, ol, which);
//         CloseOrder(ticket,ol,OP_BUY);
          CloseAllTrades("StopLoss Exit");	  
          return (true);
       }
     return(false);
   }
    
   if (cmd == OP_SELL)
   {
         
     if (IntSTprice > 0.1)
     {
       if(Ask >= IntSTprice)
       {
//         if (Debug == true) WriteTradeExit("StopLoss Exit", ticket, OP_SELL, op, ol, which);
//         CloseOrder(ticket,ol,OP_SELL);
          CloseAllTrades("StopLoss Exit");	  
         return(true);
       }
     }
   }
   return(false);
}


bool CheckTPClose(int cmd, double IntTPprice)
{

   if (cmd == OP_BUY)
   {
        
      if(Bid >= IntTPprice && IntTPprice > 0.1)
      {
//           if (Debug == true) WriteTradeExit("TakeProfit Exit", ticket, OP_BUY, op, ol, which);
//           CloseOrder(ticket,ol,OP_BUY);
          CloseAllTrades("TakeProfit Exit");	  
           return(true);
      }
       return(false);
   }
   
   if (cmd == OP_SELL)
   {
      if(Ask <= IntTPprice)
      {
//           if (Debug == true) WriteTradeExit("TakeProfit Exit", ticket, OP_SELL, op, ol, which);
//           CloseOrder(ticket,ol,OP_SELL);
          CloseAllTrades("TakeProfit Exit");	  
           return(true);
         
      }
   }
    return(false);
}    

   
bool CheckExit(int cmd)
{
      if (cmd == OP_BUY)
      {
	  	     if (ExitWithSTOCH && myOrderTypetmp==SHORT)
           {
             PreviousOpenOrders=OpenOrders+1;
             ContinueOpening=False;
             text = text +"\nClosing all orders because Indicator triggered another signal.";
             Print("Closing all orders because Indicator triggered another signal."); 
//             if (Debug == true) WriteTradeExit("Buy Exit Signal", ticket, OP_BUY, op, ol, which);
//         CloseOrder(ticket,ol,OP_BUY);
            CloseAllTrades("Buy Exit Signal");	  
            return(true);
          }
      }
      if(cmd==OP_SELL)
      {
	  	     if (ExitWithSTOCH && myOrderTypetmp==LONG)
           {
             PreviousOpenOrders=OpenOrders+1;
             ContinueOpening=False;
             text = text +"\nClosing all orders because Indicator triggered another signal.";
             Print("Closing all orders because Indicator triggered another signal."); 
             //return(0);
//          if (Debug == true) WriteTradeExit("Sell Exit Signal", ticket, OP_SELL, op, ol, which);
//          CloseOrder(ticket,ol,OP_SELL);
          CloseAllTrades("Sell Exit Signal");	  
          return (true);
           }
      }
   return(false);
}

void GetLastPrice()
{
   int cnt;
   
	  for(cnt=0;cnt<OrdersTotal();cnt++)
	  {	
	    if (OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
	    {
		  mode=OrderType();	
		  if (OrderSymbol()==Symbol() && MyMagicNumber(OrderMagicNumber()) >= 0) 
		  {
			LastPrice=OrderOpenPrice();
			if (mode==OP_BUY) { myOrderType=2; }
			if (mode==OP_SELL) { myOrderType=1;	}
		  }
		 }
	  }
}

// Return which order index from magic number
// returns -1 if not in list
int MyMagicNumber (int Magic)
{
   for (int i = 0; i < MaxTrades; i++)
   {
      if (Magic == MagicNumber[i]) return(i);
   }
   return(-1);
   
}

string BoolToStr(bool myBool)
{
   if (myBool) return("True");
   return("False");
}

string OrdTypeToStr(int myOrdType)
{
   if (myOrdType == LONG) return("BUY");
   if (myOrdType == SHORT) return ("SELL");
   return("NONE");
}

void SaveHighLow(int myOpenOrders)
{
   HighBid[myOpenOrders] = Bid;
   LowBid[myOpenOrders] = Bid;
   HighAsk[myOpenOrders] = Ask;
   LowAsk[myOpenOrders] = Ask;
   SaveHighBid (myOpenOrders, Bid);
   SaveLowBid (myOpenOrders, Bid);
   SaveHighAsk (myOpenOrders, Ask);
   SaveLowAsk (myOpenOrders, Ask);
}

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("??");
}

//+------------------------------------------------------------------+
//| Track High and Low prices                                        |
//+------------------------------------------------------------------+
void TrackPrices()
{
   for (int i = 0; i < MaxTrades; i++)
   {
      if (Bid < LowBid[i])
      {
         LowBid[i] = Bid;
         SaveLowBid (i, Bid);
      }
      if (Bid > HighBid[i])
      {
         HighBid[i] = Bid;
         SaveHighBid (i, Bid);
      }
   
     if (Ask < LowAsk[i])
     {
        LowAsk[i] = Ask;
        SaveLowAsk (i, Ask);
     }
     if (Ask > HighAsk[i])
     {
        HighAsk[i] = Ask;
        SaveHighAsk (i, Ask);
     }
   }

}

int func_Symbol2Val(string symbol)
 {
   string mySymbol = StringSubstr(symbol,0,6);
   
	if(mySymbol=="AUDCAD") return(1);
	if(mySymbol=="AUDJPY") return(2);
	if(mySymbol=="AUDNZD") return(3);
	if(mySymbol=="AUDUSD") return(4);
	if(mySymbol=="CHFJPY") return(5);
	if(mySymbol=="EURAUD") return(6);
	if(mySymbol=="EURCAD") return(7);
	if(mySymbol=="EURCHF") return(8);
	if(mySymbol=="EURGBP") return(9);
	if(mySymbol=="EURJPY") return(10);
	if(mySymbol=="EURUSD") return(11);
	if(mySymbol=="GBPCHF") return(12);
	if(mySymbol=="GBPJPY") return(13);
	if(mySymbol=="GBPUSD") return(14);
	if(mySymbol=="NZDJPY") return(15);
	if(mySymbol=="NZDUSD") return(16);
	if(mySymbol=="USDCAD") return(17);
	if(mySymbol=="USDCHF") return(18);
	if(mySymbol=="USDJPY") return(19);
   Comment("unexpected Symbol");
	return(999);
}

//+------------------------------------------------------------------+
//| Time frame interval appropriation  function                      |
//+------------------------------------------------------------------+

int func_TimeFrame_Const2Val(int Constant ) {
   switch(Constant) {
      case 1:  // M1
         return(1);
      case 5:  // M5
         return(2);
      case 15:
         return(3);
      case 30:
         return(4);
      case 60:
         return(5);
      case 240:
         return(6);
      case 1440:
         return(7);
      case 10080:
         return(8);
      case 43200:
         return(9);
   }
}

//+------------------------------------------------------------------+
//|                                                     Logs_inc.mqh |
//|                                                 Copyright © 2007 |
//|                                                                  |
//+------------------------------------------------------------------+

void CloseLogFiles()
{
   int BThandleTrade;
     
   if (Debug_BackTestTrade == true)
   {
      if (GlobalVariableCheck("BTMyHandleTrade") == true)
      {
        BThandleTrade = GlobalVariableGet("BTMyHandleTrade");
        FileFlush(BThandleTrade);
        FileClose(BThandleTrade);
        GlobalVariableDel("BTMyHandleTrade");
      }  
   }
}

void SetupLogFiles()
{
    string BTfilenameTrade_Log;
    int err,BThandleTrade;

    BTfilenameTrade_Log=Symbol()+" " + BT_Trade_Log + ".txt";
    if (Debug_BackTestTrade == true)
    {
      GlobalVariableSet("BTMyHandleTrade",0);
      if (GlobalVariableCheck("BTMyHandleTrade") == false)
      {
         err = GetLastError();
         Print("Error creating Global Variable BTMyHandleTrade: (" + err + ") " + ErrorDescription(err));
         return(0); 
      }
      BThandleTrade = FileOpen(BTfilenameTrade_Log,FILE_CSV|FILE_WRITE,"\t");
      GlobalVariableSet("BTMyHandleTrade",BThandleTrade); 
    }

    filenameTradeLog=AccountNumber() +" "+ Symbol() + Trade_Log + "_" + Month() + "-" + Day() +".txt"; 
}

/*
void WriteDash()
{
   if (Debug_BackTestTrade == true){
     BTWrite_Trade ("-----------------------------------------------------------------");
     }
   if (Debug_LiveTrade == true){
     Write_Trade ("-----------------------------------------------------------------");
   }
}

void WriteComment(string st)
{
   if (Debug_BackTestTrade == true){
     BTWrite_Trade (" " + st);
     }
   if (Debug_LiveTrade == true){
     Write_Trade (" " + st);
   }
}
*/

void Write_OpenError(string msg)
{
   if (Debug_BackTestTrade == true) BTWrite_Trade(msg);
   if (Debug_LiveTrade == true) Write_Trade(msg);
}

void Write_Stars()
{
   if (Debug_BackTestTrade == true)
   {
     BTWrite_Trade ("****************************************************************");
   }
   if (Debug_LiveTrade == true)
   {
     Write_Trade ("****************************************************************");
   }
}
void Write_OpenTrade(string msg)
{
   if (Debug_BackTestTrade == true)
   {
     BTWrite_Trade(msg);
   }
   if (Debug_LiveTrade == true)
   {
     Write_Trade(msg);
   }
}

void WriteExit(int myTicket, string msg, int cmd, double op, string Profit, int which)
{
   if (Debug_BackTestTrade == true){
     BTWrite_Trade ("-----------------------------------------------------------------");
     BTWrite_Trade (" "+ Symbol() +" #" + myTicket + " " +  msg + " : " + Profit);
     if (op > 0.1) BTWrite_Prices(cmd, op, which);
   }
   if (Debug_LiveTrade == true){
     Write_Trade ("-----------------------------------------------------------------");
     Write_Trade (" "+ Symbol() +" #" + myTicket + " " +  msg + " : " + Profit);
     if (op > 0.1) Write_Prices(cmd, op, which);
   }
}

void Write_Trade(string str)
{ 
   int handleTradeLog;
    
  if (Debug_LiveTrade == true)
   {
      handleTradeLog = FileOpen(filenameTradeLog,FILE_READ|FILE_WRITE|FILE_CSV,"/t");
      FileSeek(handleTradeLog, 0, SEEK_END);      
      FileWrite(handleTradeLog,TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS)+str);
      FileClose(handleTradeLog);
   }
}

void BTWrite_Trade(string str) 
{ 
   int BThandleTrade_Log;
   
  if (Debug_BackTestTrade == true)
   {
   if (GlobalVariableCheck("BTMyHandleTrade"))
      {
      BThandleTrade_Log = GlobalVariableGet("BTMyHandleTrade");
      FileWrite(BThandleTrade_Log,TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS)+str);
      } 
   }
}

void BTWrite_Prices(int cmd, double op, int which)
{
   double profit, drawdown;
   
   if (Debug_BackTestTrade == true){
     BTWrite_Trade ("  PRICES Trade " + which);
     BTWrite_Trade ("  Low Ask : " + DoubleToStr(LowAsk[which],Digits) + "  High Ask : " + DoubleToStr(HighAsk[which],Digits));
     BTWrite_Trade ("  Low Bid : " + DoubleToStr(LowBid[which],Digits) + "  High Bid : " + DoubleToStr(HighBid[which],Digits));
     if (cmd == OP_BUY)
     {
       profit = (HighBid[which] - op) / myPoint;
       drawdown = (op - LowBid[which]) / myPoint;
     }
     if (cmd == OP_SELL)
     {
       profit = ( op - LowAsk[which]) / myPoint;
       drawdown = (HighAsk[which] - op) / myPoint;
     }
     BTWrite_Trade ("  High Profit : " + DoubleToStr(profit,0));
     BTWrite_Trade ("  DrawDown : " + DoubleToStr(drawdown,0));
   }
}

void Write_Prices(int cmd, double op, int which)
{
   double profit, drawdown;
   
   if (Debug_LiveTrade == true){
     Write_Trade ("  PRICES Trade " + which);
     Write_Trade ("  Low Ask : " + DoubleToStr(LowAsk[which],Digits) + "  High Ask : " + DoubleToStr(HighAsk[which],Digits));
     Write_Trade ("  Low Bid : " + DoubleToStr(LowBid[which],Digits) + "  High Bid : " + DoubleToStr(HighBid[which],Digits));
     if (cmd == OP_BUY)
     {
        profit = (HighBid[which] - op) / myPoint;
        drawdown = (op - LowBid[which]) / myPoint;
     }
     if (cmd == OP_SELL)
     {
        profit = ( op - LowAsk[which]) / myPoint;
        drawdown = (HighAsk[which] - op) / myPoint;
     }
     Write_Trade ("  High Profit : " + DoubleToStr(profit,0));
     Write_Trade ("  DrawDown    : " + DoubleToStr(drawdown,0));
   }
}

void WriteTradeExit ( string why, int mTicket, int cmd, double op, double ol, int which)
{ 
   string olStr, bidStr, askStr;
   int Pips;
   
   olStr = DoubleToStr(ol,2);
   bidStr = DoubleToStr(Bid, Digits);
   askStr = DoubleToStr(Ask, Digits);
   
   if (cmd == OP_BUY)
   {
     Pips = (Bid - op) / myPoint;
     if (Pips >= 0)
       WriteExit(mTicket, why, OP_BUY, op, "Profit of " + Pips, which);
     else
       WriteExit(mTicket, why, OP_BUY, op, "Loss of " + Pips, which);
     if (Debug_LiveTrade == true){
         Write_Trade(" "+ Symbol() +" #"+ mTicket +" CLOSE BUY ORDER "+ olStr +" LOTS AT "+ bidStr +".");}
     if (Debug_BackTestTrade == true){
         BTWrite_Trade(" "+ Symbol() +" #"+ mTicket +" CLOSE BUY ORDER "+ olStr +" LOTS AT "+ bidStr +".");}
   }
   if (cmd == OP_SELL)
   {
     Pips = (op - Ask) / myPoint;
     if (Pips >= 0)
       WriteExit(mTicket, why, OP_SELL, op, "Profit of " + Pips, which);
     else
       WriteExit(mTicket, why, OP_SELL, op, "Loss of " + Pips, which);
     if (Debug_LiveTrade == true){
         Write_Trade(" "+ Symbol() +" #"+ mTicket +" CLOSE SELL ORDER "+ olStr +" LOTS AT "+ askStr +".");}
     if (Debug_BackTestTrade == true){
         BTWrite_Trade(" "+ Symbol() +" #"+ mTicket +" CLOSE SELL ORDER "+ olStr +" LOTS AT "+ askStr +".");}
   }
}

//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//|                                               GlobalVars_inc.mqh |
//|                                                 Copyright © 2007 |
//|                                                                  |
//| List of Global variables to refresh after dis-connect            |
//| * means code completed for global variable usage                 |
//|                                                                  |
//| * bool     First_TP_Level                                        |
//| * bool     ClosedPartial                                         |
//| * bool     First_Trigger_Level                                   |
//| * int      InternalTakeProfit                                    |
//| * int      TP_Level1                                             |
//| * int      InternalStopLoss                                      |
//| * int      StopLoss                                              |
//| * double   HighBid                                               |
//| * double   LowBid                                                |
//| * double   HighAsk                                               |
//| * double   LowAsk                                                |
//| * double   IntSTprice                                            |
//| * double   IntTPprice                                            |
//|                                                                  |
//+------------------------------------------------------------------+

void GetGlobalVars()
{
   NameGlobalVars();
   InitGlobalVars();
   GetGlobalVarValues();
}
  
void GetGlobalVarValues()
{
   double temp;
   int i;

// 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;
    
    for (i = 0; i < MaxTrades; i++)
    {
      HighBid[i] = GlobalVariableGet(gHighBidName[i]);
      LowBid[i] = GlobalVariableGet(gLowBidName[i]);
      HighAsk[i] = GlobalVariableGet(gHighAskName[i]);
      LowAsk[i] = GlobalVariableGet(gLowAskName[i]);
    
      IntTPprice[i] = GlobalVariableGet (gIntTPpriceName[i]);
      IntSTprice[i] = GlobalVariableGet (gIntSTpriceName[i]);
    }
}

void InitGlobalVars()
{

// check variable before use

  for (int i = 0; i < MaxTrades; i++)
  {  
  if(!GlobalVariableCheck(gHighBidName[i]))
    GlobalVariableSet(gHighBidName[i],0);
    
  if(!GlobalVariableCheck(gLowBidName[i]))
    GlobalVariableSet(gLowBidName[i],0);
    
  if(!GlobalVariableCheck(gHighAskName[i]))
    GlobalVariableSet(gHighAskName[i],0);
    
  if(!GlobalVariableCheck(gLowAskName[i]))
    GlobalVariableSet(gLowAskName[i],0);
    

  if(!GlobalVariableCheck(gIntTPpriceName[i]))
    GlobalVariableSet(gIntTPpriceName[i],0);
    
    
  if(!GlobalVariableCheck(gIntSTpriceName[i]))
    GlobalVariableSet(gIntSTpriceName[i],0);
  }

}

void NameGlobalVars()
{
   string  prefix;

   prefix = "SMFH_" + Symbol() +  tf2txt(Period());
   for (int i = 0; i < MaxTrades; i++)
   {
     gHighBidName[i] = prefix + "_HighBid" + i;
     gLowBidName[i] = prefix + "_LowBid" + i;
     gHighAskName[i] = prefix + "_HighAsk" + i;
     gLowAskName[i] = prefix + "_LowAsk" + i;
     gIntTPpriceName[i] = prefix + "_IntTPprice" + i;
     gIntSTpriceName[i] = prefix + "_IntSTprice" + i;
   }
}

void SaveHighBid(int which, double myVal)
{
    GlobalVariableSet(gHighBidName[which],myVal);
}
    
void SaveLowBid(int which, double myVal)
{
    GlobalVariableSet(gLowBidName[which],myVal);
}
    
void SaveHighAsk(int which, double myVal)
{
    GlobalVariableSet(gHighAskName[which],myVal);
}
    
void SaveLowAsk(int which, double myVal)
{
    GlobalVariableSet(gLowAskName[which],myVal);
}
    

void SaveIntSTprice (int which, double myVal)
{
    GlobalVariableSet(gIntSTpriceName[which],myVal);
}

void SaveIntTPprice (int which, double myVal)
{
    GlobalVariableSet(gIntTPpriceName[which],myVal);
}
    
//+------------------------------------------------------------------+


