
//-------------------------------------------------------------------+
/*

Copyright (c) 2010, Ronald Raygun
All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are required provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright 
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright 
      notice, this list of conditions and the following disclaimer in 
      the documentation and/or other materials provided with the distribution.
    * Neither the name of Ronald Raygun nor the names of any contributors 
      may be used to endorse or promote products derived from this software 
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.

To signify your acceptance of this agreement, change LicenseCheck2 to "I agree"

For those wishing to purchase a commercial license for this code, please contact
user Ronald Raygun on www.ForexFactory.com. 
*/














//+------------------------------------------------------------------+
#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Ronald Raygun"
#property link      "http://www.RonaldRaygunForex.com/Support"

#import "wininet.dll"

#define INTERNET_FLAG_PRAGMA_NOCACHE    0x00000100 // Forces the request to be resolved by the origin server, even if a cached copy exists on the proxy.
#define INTERNET_FLAG_NO_CACHE_WRITE    0x04000000 // Does not add the returned entity to the cache. 
#define INTERNET_FLAG_RELOAD            0x80000000 // Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
#define INTERNET_FLAG_NO_COOKIES        0x00080000 // Does not automatically add cookie headers to requests, and does not automatically add returned cookies to the cookie database. This flag can be used by 


int InternetOpenA(
	string 	sAgent,
	int		lAccessType,
	string 	sProxyName="",
	string 	sProxyBypass="",
	int 	lFlags=0
);

int InternetOpenUrlA(
	int 	hInternetSession,
	string 	sUrl, 
	string 	sHeaders="",
	int 	lHeadersLength=0,
	int 	lFlags=0,
	int 	lContext=0 
);

int InternetReadFile(
	int 	hFile,
	string 	sBuffer,
	int 	lNumBytesToRead,
	int& 	lNumberOfBytesRead[]
);

int InternetCloseHandle(
	int 	hInet
);
#import


extern string Remark1 = "== Main Settings ==";
extern int MagicNumber = 0;
extern bool SignalsOnly = False;
extern bool Alerts = False;
extern bool SignalMail = False;
extern bool PlaySounds = False;
bool TickDatabase = True;
extern bool ShowLines = False;
extern bool ECNBroker = False;
extern bool EachTickMode = True;
extern bool CloseOnOppositeSignal = False;
extern int MaxSimultaneousTrades = 1;
extern double Lots = 0;
extern bool MoneyManagement = False;
extern int Risk = 0;
extern int Slippage = 5;
extern bool UseStopLoss = True;
extern int StopLoss = 100;
extern bool UseTakeProfit = True;
extern int TakeProfit = 100;

extern bool UseTrailingStop = False;
extern int TrailingStop = 30;
extern bool MoveStopOnce = False;
extern int MoveStopWhenPrice = 50;
extern int MoveStopTo = 1;
extern string Remark2 = "";
extern string Remark3 = "== HiLo Settings ==";
extern int BarStart = 0;
extern int InitialRange = 10;
extern double WinPercent = 0;
extern double MinimumWinDifference = 0;
extern double MinimumSuccessScore = 0;
extern double MinimumSSDifference = 0;
extern int MinimumConfidence = 90;

extern string LicenseTerms = "Do you agree to the license agreement in the source code?";
extern string LicenseCheck1 = "I do not agree";
extern string LicenseCheck2 = "I do not agree";
extern string LicenseCheck3 = "I do not agree";
extern string LicenseCheck4 = "I do not agree";
extern string LicenseCheck5 = "I do not agree";

string SymbolUsed;
int TickCount = 0;
int RecordDay = -1;
string UserName = "Hilo Trader 2";
bool ShowDiagnostics = False;


int Internet_Open_Type_Direct = 1;


   string URL;
   int URLHandle = 0;                                                              
   int SessionHandle = 0;
   int MaxTries = 0;

   
   string FinalStr ;
   int bytesreturned[1];
   int readresult;

   int GMTBar;
   string GMTTime;
   string BrokerTime;
   int GMTShift;

   datetime CurGMTTime;
   datetime CurBrokerTime;
   datetime CurrentGMTTime;



 
   string TempStr ="000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
#define  maxreadlen 200

string CalcTime = "";

datetime RecentHigh = 0;
datetime RecentLow = 0;

double BreakoutWin = 0;
double BreakoutLoss = 0;
double BreakoutTotal = 0;
double BreakoutTie = 0;

double CounterWin = 0;
double CounterLoss = 0;
double CounterTotal = 0;
double CounterTie = 0;

int BarsCounted;

int DayCheck = 0;

int TradeBar;
int TradesThisBar;

int OpenBarCount;
int CloseBarCount;

string BrokerType = "4-Digit Broker";
double BrokerMultiplier = 1;

int Current;
bool TickCheck = False;

bool LicenseStatus = True;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {

   if(LicenseCheck2 != "I agree" || LicenseCheck1 != "I do not agree" || LicenseCheck3 != "I do not agree" || LicenseCheck4 != "I do not agree" || LicenseCheck5 != "I do not agree" )
      {  
      Alert("Please read the license agreement included in the source code.");
      LicenseStatus = false;
      return(0);
      }
      
   OpenBarCount = Bars;
   CloseBarCount = Bars;
   
   
   TickCount = 0;
   
   SymbolUsed = StringSubstr(Symbol(), 0, 6);   
   RecordDay = TimeDayOfYear(TimeCurrent());
   
   if(!IsDllsAllowed())
      {
      Alert("ERROR: Please enable DLL calls.");
      Comment("Enable DLL Calls");
      return(0);
      }  

   
   if(Digits == 3 || Digits == 5)
      {
      BrokerType = "5-Digit Broker";
      BrokerMultiplier = 10;
      }
   Comment("Calculating...");
   if(BarStart == 0) BarStart = Bars;
   BarsCounted = GenerateStatistics(BarStart);
   
   if (EachTickMode) Current = 0; else Current = 1;

   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {

int TotalObjects = ObjectsTotal();

for(int O = TotalObjects; O > 0; O--)
   {
   if(StringFind(ObjectName(O), "HiLoTrader", 0) == 0)
      {
      ObjectDelete(ObjectName(O));
      } 
   }

   URL = LoadURL("http://www.ronaldraygunforex.com/TickDB/UserLog.php?UN="+UserName+"&P="+SymbolUsed+"&TL="+TickCount);
   //if(!IsTesting() && !IsOptimization()) /*Print("Thank you for contributing "+TickCount+" ticks. "+URL*/;
   InternetCloseHandle(SessionHandle);   

   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() 
{
if(!LicenseStatus) return(0);

{
   int Order = SIGNAL_NONE;
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;
   double PotentialStopLoss;
   double BEven; 
   double TrailStop;



   if (EachTickMode && Bars != CloseBarCount) TickCheck = False;
   Total = OrdersTotal();
   Order = SIGNAL_NONE;

//Limit Trades Per Bar
if(TradeBar != Bars)
   {
   TradeBar = Bars;
   TradesThisBar = 0;
   }


//Money Management sequence
 if (MoneyManagement)
   {
      if (Risk<1 || Risk>100)
      {
         Comment("Invalid Risk Value.");
         return(0);
      }
      else
      {
         Lots=MathFloor((AccountFreeMargin()*AccountLeverage()*Risk*Point*BrokerMultiplier*100)/(Ask*MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT)))*MarketInfo(Symbol(),MODE_MINLOT);
      }
   }

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+
   
double DailyHigh = iHigh(NULL, PERIOD_D1, 0);
double DailyLow = iLow(NULL, PERIOD_D1, 0);

double CurrentHigh = iHigh(NULL, 0, Current + 0);
double CurrentLow = iLow(NULL, 0, Current + 0);

//Recalculate stats for a new bar
int DayBarShift = iBarShift(NULL, 0, iTime(NULL, PERIOD_D1, 0), True);

if(DayBarShift >= 0 && DayBarShift < InitialRange && DayCheck != TimeDayOfYear(TimeCurrent()))
   {
   DayCheck = TimeDayOfYear(TimeCurrent());
   if(BarStart == 0) BarStart = Bars;
   GenerateStatistics(BarStart);
   }

//Calculate Current HiLo
double DayHigh = iHigh(NULL, 0, iHighest(NULL, 0, MODE_HIGH, DayBarShift, 0));
double DayLow = iLow(NULL, 0, iLowest(NULL, 0, MODE_LOW, DayBarShift, 0));

//Calculate Stats
double BOWinRate = (BreakoutWin / BreakoutTotal) * 100;
double CTWinRate = (CounterWin / CounterTotal) * 100;
double ErrorRate = ((BreakoutTie + CounterTie) / (BreakoutTotal + CounterTotal)) * 100;

double BOSuccessScore = BOWinRate * TakeProfit / StopLoss;
double CTSuccessScore = CTWinRate * TakeProfit / StopLoss;

string TSWin = "Stand Aside";
if(BOWinRate > WinPercent && CTWinRate < WinPercent && WinPercent != 0) TSWin = "Breakout"; 
if(CTWinRate > WinPercent && BOWinRate < WinPercent && WinPercent != 0) TSWin = "Counter Trend";
if(WinPercent == 0) TSWin = "Not Used";

string TSWinDiff = "Stand Aside";
if(BOWinRate - CTWinRate > MinimumWinDifference && MinimumWinDifference != 0) TSWinDiff = "Breakout";
if(CTWinRate - BOWinRate > MinimumWinDifference && MinimumWinDifference != 0) TSWinDiff = "Counter Trend";
if(MinimumWinDifference == 0) TSWinDiff = "Not Used";

string TSSS = "Stand Aside";
if(BOSuccessScore > MinimumSuccessScore && CTSuccessScore < MinimumSuccessScore && MinimumSuccessScore != 0) TSSS = "Breakout";
if(CTSuccessScore > MinimumSuccessScore && BOSuccessScore < MinimumSuccessScore && MinimumSuccessScore != 0) TSSS = "Counter Trend";
if(MinimumSuccessScore == 0) TSSS = "Not Used";

string TSSSDiff = "Stand Aside";
if(BOSuccessScore - CTSuccessScore > MinimumSSDifference && MinimumSSDifference != 0) TSSSDiff = "Breakout";
if(CTSuccessScore - BOSuccessScore > MinimumSSDifference && MinimumSSDifference != 0) TSSSDiff = "Counter Trend";
if(MinimumSuccessScore == 0) TSSSDiff = "Not Used";

string TradingStyle = "Calculating";
if(TSWin != "Counter Trend" && TSWinDiff != "Counter Trend" && TSSS != "Counter Trend" && TSSSDiff != "Counter Trend" && TSWin != "Stand Aside" && TSWinDiff != "Stand Aside" && TSSS != "Stand Aside" && TSSSDiff != "Stand Aside") TradingStyle = "Breakout";
if(TSWin != "Breakout" && TSWinDiff != "Breakout" && TSSS != "Breakout" && TSSSDiff != "Breakout" && TSWin != "Stand Aside" && TSWinDiff != "Stand Aside" && TSSS != "Stand Aside" && TSSSDiff != "Stand Aside") TradingStyle = "Counter Trend";
//if(TSWin == "Stand Aside" && TSWinDiff == "Stand Aside" && TSSS == "Stand Aside" && TSSSDiff == "Stand Aside") TradingStyle = "Stand Aside";
if(TSWin == "Not Used" && TSWinDiff == "Not Used" && TSSS == "Not Used" && TSSSDiff == "Not Used") TradingStyle = "Please set any combination of WinPercent, MinimumWinDifference, MinimumSuccessScore, MininumSSDifference";


//Count Open Trades
int TotalTrades = 0;
int TradesTotal = OrdersTotal();
for (int T = TradesTotal; T > 0; T--)
   {
   OrderSelect(T, SELECT_BY_POS, MODE_TRADES);
   if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
      {
      TotalTrades++;
      }
   }

string TradeTrigger = "None";
if(LicenseStatus && (TotalTrades < MaxSimultaneousTrades || MaxSimultaneousTrades == 0) && DayBarShift >= InitialRange && MinimumConfidence <= 100 - ErrorRate && ((DailyHigh == CurrentHigh && TradingStyle == "Breakout") || (DailyLow == CurrentLow && TradingStyle == "Counter Trend"))) TradeTrigger = "Open Long";
if(LicenseStatus && (TotalTrades < MaxSimultaneousTrades || MaxSimultaneousTrades == 0) && DayBarShift >= InitialRange && MinimumConfidence <= 100 - ErrorRate && ((DailyLow == CurrentLow && TradingStyle == "Breakout") || (DailyHigh == CurrentHigh && TradingStyle == "Counter Trend"))) TradeTrigger = "Open Short";



Comment("Broker Type: ", BrokerType, "\n",
        "Calculating Finished at: ", CalcTime, "\n",
        "Breakout Win: ", BreakoutWin, "\n",
        "Breakout Loss: ", BreakoutLoss, "\n",
        "Breakout Unsure: ", BreakoutTie, "\n",
        "Breakout Total: ", BreakoutTotal, "\n",
        "Counter Win: ", CounterWin, "\n",
        "Counter Loss: ", CounterLoss, "\n",
        "Counter Unsure: ", CounterTie, "\n",
        "Counter Total: ", CounterTotal, "\n",
        "Breakout Percent: ", BOWinRate, "%\n",
        "Breakout Success Score: ", BOSuccessScore, "\n",
        "Counter Percent: ", CTWinRate, "%\n",
        "Counter Success Score: ", CTSuccessScore, "\n",
        "Tester Quality: ", 100-ErrorRate, "\n",
        "Current High: ", DoubleToStr(NormalizeDouble(CurrentHigh,Digits),Digits), "\n",
        "High Value: ", DoubleToStr(NormalizeDouble(DailyHigh,Digits),Digits), "\n",
        "Current Low: ", DoubleToStr(NormalizeDouble(CurrentLow,Digits),Digits), "\n",
        "Low Value: ", DoubleToStr(NormalizeDouble(DailyLow,Digits),Digits), "\n",
        "Trading Style: ", TradingStyle, "\n",
        "Trade Trigger: ", TradeTrigger);
        
color HighColor = Yellow;
color LowColor = Yellow;

if(TradingStyle == "Breakout")
   {
   HighColor = Lime;
   LowColor = Red;
   }
if(TradingStyle == "Counter Trend")
   {
   HighColor = Red;
   LowColor = Lime;
   }
       
ObjectMaker("HiLoTrader High", OBJ_HLINE, 0, 0, DailyHigh, HighColor, True, STYLE_DOT);
ObjectMaker("HiloTrader Low", OBJ_HLINE, 0, 0, DailyLow, LowColor, True, STYLE_DOT);       

   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+

   //Check position
   bool IsTrade = False;

   for (int i = 0; i < Total; i ++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL &&  OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) {
         IsTrade = True;
         if(OrderType() == OP_BUY) {
         
            
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+

if(CloseOnOppositeSignal && TradeTrigger == "Open Short") Order = SIGNAL_CLOSEBUY;

            //+------------------------------------------------------------------+
            //| Signal End(Exit Buy)                                             |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != CloseBarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
               if (!EachTickMode) CloseBarCount = Bars;
               IsTrade = False;
               continue;
            }
            
            PotentialStopLoss = OrderStopLoss();
            BEven = BreakEvenValue(MoveStopOnce, OrderTicket(), MoveStopTo, MoveStopWhenPrice);
            TrailStop = TrailingStopValue(UseTrailingStop, OrderTicket(), TrailingStop);
            
            if(BEven > PotentialStopLoss && BEven != 0) PotentialStopLoss = BEven;
            if(TrailStop > PotentialStopLoss && TrailStop != 0) PotentialStopLoss = TrailStop;
             
            if(PotentialStopLoss != OrderStopLoss()) OrderModify(OrderTicket(),OrderOpenPrice(), PotentialStopLoss, OrderTakeProfit(), 0, MediumSeaGreen); 
         
         } else {
        
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Sell)                                          |
            //+------------------------------------------------------------------+

if(CloseOnOppositeSignal && TradeTrigger == "Open Long") Order = SIGNAL_CLOSESELL;

            //+------------------------------------------------------------------+
            //| Signal End(Exit Sell)                                            |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != CloseBarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
               if (!EachTickMode) CloseBarCount = Bars;
               IsTrade = False;
               continue;
            }
            
            PotentialStopLoss = OrderStopLoss();
            BEven = BreakEvenValue(MoveStopOnce, OrderTicket(), MoveStopTo, MoveStopWhenPrice);
            TrailStop = TrailingStopValue(UseTrailingStop, OrderTicket(), TrailingStop);
            
            if((BEven < PotentialStopLoss && BEven != 0) || (PotentialStopLoss == 0)) PotentialStopLoss = BEven;
            if((TrailStop < PotentialStopLoss && TrailStop != 0) || (PotentialStopLoss == 0)) PotentialStopLoss = TrailStop;
            
            if(PotentialStopLoss != OrderStopLoss() || OrderStopLoss() == 0) OrderModify(OrderTicket(),OrderOpenPrice(), PotentialStopLoss, OrderTakeProfit(), 0, DarkOrange);
              
         }
      }
   }

   //+------------------------------------------------------------------+
   //| Signal Begin(Entry)                                              |
   //+------------------------------------------------------------------+

if(TradeTrigger == "Open Long") Order = SIGNAL_BUY;
if(TradeTrigger == "Open Short") Order = SIGNAL_SELL;

   //+------------------------------------------------------------------+
   //| Signal End                                                       |
   //+------------------------------------------------------------------+

IsTrade = False;
   //Buy
   if (LicenseStatus && Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != OpenBarCount)))) {
      if(SignalsOnly) {
         if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
         if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
         if (PlaySounds) PlaySound("alert.wav");
     
      }
      
      if(!IsTrade && !SignalsOnly && TradesThisBar < 1) {
         //Check free margin
         if (AccountFreeMarginCheck(Symbol(), OP_BUY, Lots) < 0) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Ask - StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;
         if(LicenseStatus && ECNBroker) Ticket = OrderModify(OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue), OrderOpenPrice(), StopLossLevel, TakeProfitLevel, 0, CLR_NONE);
         if(LicenseStatus && !ECNBroker) Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
            if(Ticket > 0) {
               if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				  Print("BUY order opened : ", OrderOpenPrice());
                  if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
			         if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + "Buy Signal");
                  if (PlaySounds) PlaySound("alert.wav");
                  TradesThisBar++;
			   } else {
   				Print("Error opening BUY order : ", GetLastError());
			   }
            }
            
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) OpenBarCount = Bars;
         return(0);
      }
   }

   //Sell
   if (LicenseStatus && Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != OpenBarCount)))) {
      if(SignalsOnly) {
          if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
          if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
          if (PlaySounds) PlaySound("alert.wav");
         }
      if(!IsTrade && !SignalsOnly && TradesThisBar < 1) {
         //Check free margin
         if (AccountFreeMarginCheck(Symbol(), OP_SELL, Lots) < 0) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

         if(ECNBroker && LicenseStatus) Ticket = OrderModify(OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink), OrderOpenPrice(), StopLossLevel, TakeProfitLevel, 0, CLR_NONE);
         if(LicenseStatus && !ECNBroker) Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				Print("SELL order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
			       if (Alerts) Alert("[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + "Sell Signal");
                if (PlaySounds) PlaySound("alert.wav");
                TradesThisBar++;
			} else {
				Print("Error opening SELL order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) OpenBarCount = Bars;
         return(0);
      }
   }

   if (!EachTickMode) CloseBarCount = Bars;

   if(TickDatabase && !IsOptimization() && !IsTesting() && IsDllsAllowed()) TickData();

   return(0);
}
}

void TickData ()
   {
   if(GMTBar != Bars)
      {
      GMTTime = LoadURL("http://www.ronaldraygunforex.com/TickDB/Time.php");
      GMTBar = Bars;
      GMTShift = TimeCurrent() - StrToTime(GMTTime);
      } 

   if(TimeDayOfYear(TimeCurrent()) != RecordDay)
      {
      URL = LoadURL("http://www.ronaldraygunforex.com/TickDB/UserLog.php?UN="+UserName+"&P="+SymbolUsed+"&TL="+TickCount);
   
      if(StringFind(URL, "1 record added") != -1)
         {
         TickCount = 0;
         RecordDay = TimeDayOfYear(TimeCurrent());
         }
      }
   
   CurGMTTime = StrToTime(GMTTime);
  
   CurrentGMTTime = TimeCurrent() - GMTShift;
   //CurrentGMTTime = CurGMTTime + TimeCurrent - CurBrokerTime
   
   URL = LoadURL("http://www.ronaldraygunforex.com/TickDB/Load.php?TN="+SymbolUsed+"&GMT="+CurrentGMTTime+"&TT="+TimeCurrent()+"&B="+DoubleToStr(NormalizeDouble(Bid,Digits),Digits)+"&A="+DoubleToStr(NormalizeDouble(Ask,Digits),Digits)+"&BN="+AccountCompany()+"&UN="+UserName);
  
   if(StringFind(URL, "1 record added") != -1)
      {
      TickCount++;
      }
      else
      {
      Print(SymbolUsed+" Error: "+URL);
      LoadURL("http://www.ronaldraygunforex.com/TickDB/Error.php?UN="+UserName+"&Error="+URL);
      }
   }
   
   
string LoadURL (string URLLoad)
   {
   int Position = StringFind(URLLoad, " ");
   
   while (Position != -1)
      {
      string InitialURLA = StringTrimLeft(StringTrimRight(StringSubstr(URLLoad, 0, StringFind(URLLoad, " ", 0))));
      string InitialURLB = StringTrimLeft(StringTrimRight(StringSubstr(URLLoad, StringFind(URLLoad, " ", 0))));
      URLLoad = InitialURLA+"%20"+InitialURLB;
      Position = StringFind(URLLoad, " ");
      if(ShowDiagnostics) Print("Processing URL: "+URLLoad);
      }
      
   MaxTries =0; 
   URLHandle=0;
   while (MaxTries < 3 && URLHandle == 0)
      {
      if(SessionHandle != 0)
         {
         URLHandle = InternetOpenUrlA(SessionHandle, URLLoad, NULL, 0, INTERNET_FLAG_NO_CACHE_WRITE |
                                                                   INTERNET_FLAG_PRAGMA_NOCACHE |
                                                                   INTERNET_FLAG_RELOAD |
                                                                   INTERNET_FLAG_NO_COOKIES, 0);
         }
      if(URLHandle == 0)
         {
         InternetCloseHandle(SessionHandle);
         if(ShowDiagnostics) Print("Closing Handle");
         SessionHandle = InternetOpenA("mymt4InetSession", Internet_Open_Type_Direct, NULL, NULL, 0);
         }
         
      MaxTries++;   
      }
      
   if(ShowDiagnostics) Print("URL Handle: ", URLHandle);   
      
   //Parse file 
    
   FinalStr = "";
   bytesreturned[0]=1;
   
   while (bytesreturned[0] > 0)
      {

    
     
      // get next chunk
      InternetReadFile(URLHandle, TempStr , maxreadlen, bytesreturned);
      if(ShowDiagnostics) Print("bytes returned: "+bytesreturned[0]);
      
      

      if(bytesreturned[0] > 0)
      FinalStr = FinalStr + StringSubstr(TempStr, 0, bytesreturned[0]);
            
      }

      if(ShowDiagnostics) Print("FinalStr: "+FinalStr);

   // now we are done with the URL we can close its handle 
   InternetCloseHandle(URLHandle);
   
   return(FinalStr);    
   }
   
   
double BreakEvenValue (bool Decision, int OrderTicketNum, int MoveStopTo, int MoveStopwhenPrice)
   {
   //Select the appropriate order ticket
   OrderSelect(OrderTicketNum, SELECT_BY_TICKET, MODE_TRADES);
   
   //If the Order is a BUY order...
   if(OrderType() == OP_BUY)
      {
      //Check if the user wants to use the MoveStopOnce function and did it correctly
      if(Decision && MoveStopWhenPrice > 0) 
         {
         //Check if the trade is above the required profit threshold
         if(Bid - OrderOpenPrice() >= Point * MoveStopWhenPrice) 
            {
            //Return the value of the stoploss
            return(OrderOpenPrice() + Point * MoveStopTo);
            }
         }
      }
   
   //If the Order is a SELL order...   
   if(OrderType() == OP_SELL)
      {
      //Check if the user wants to use the MoveStopOnce function and did it correctly
      if(Decision && MoveStopWhenPrice > 0) 
         {
         //Check if the trade is above the required profit threshold
         if(OrderOpenPrice() - Ask >= Point * MoveStopWhenPrice) 
            {
            //Return the value of the stoploss
            return(OrderOpenPrice() - Point * MoveStopTo);
            }
         }
      }   
      
   if(OrderType() != OP_BUY || OrderType() != OP_SELL) return(0);
   }
   
double TrailingStopValue (bool Decision, int OrderTicketNum, int TrailingStop)
   {
   //Select the appropriate order ticket
   OrderSelect(OrderTicketNum, SELECT_BY_TICKET, MODE_TRADES);
   
   //If the Order is a BUY order...
   if(OrderType() == OP_BUY)
      {
      //Check if the user wants to use teh Trailingstop function and did it correctly
      if(Decision && TrailingStop > 0) 
         {                 
         //Check to see that the profit threshold is met
         if(Bid - OrderOpenPrice() > Point * TrailingStop) 
            {
            //Return the value of the potential stoploss
            return(Bid - Point * TrailingStop);
            }
         }
      }
   //If the Order is a SELL order...
   if(OrderType() == OP_SELL)
      {
      //Check if the user wants to use teh Trailingstop function and did it correctly
      if(Decision && TrailingStop > 0) 
         {                 
         //Check to see that the profit threshold is met
         if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) 
            {
            //Return the value of the potential stoploss
            return(Ask + Point * TrailingStop);
            }
         }
      }     
   //If the trade is not the right order type, give a stoploss of 0   
   if(OrderType() != OP_BUY || OrderType() != OP_SELL) return(0);
   }
  
 
   int GenerateStatistics(int FBarStart)
      {
      int SearchShift;
      int DayStartShift = FBarStart;
      int RangeEndShift = FBarStart;
      double HighValue = 0;
      double LowValue = 0;
      double HighValue1 = 0;
      double LowValue1 = 0;
      int HighShift = 0;
      int LowShift = 0;
      int TestHighValue = 0;
      int TestLowValue = 0;
      string TestResultBO = "None";
      string TestResultCT = "None";
      
      
      
      for (SearchShift = DayStartShift; SearchShift > 1; SearchShift--)
         {
         //Determine if the bar is the daily start
         if(TimeDayOfYear(Time[SearchShift]) != TimeDayOfYear(Time[SearchShift + 1]))
            {
            DayStartShift = SearchShift;
            }
         //Find the end of the range and establish initial high and low
         if(DayStartShift - SearchShift == InitialRange)
            {
            RangeEndShift = SearchShift;      
            HighShift = iHighest(NULL, 0, PRICE_HIGH, DayStartShift - RangeEndShift, RangeEndShift);
            HighValue = iHigh(NULL, 0, HighShift);
            LowShift = iLowest(NULL, 0, PRICE_LOW, DayStartShift - RangeEndShift, RangeEndShift);
            LowValue = iLow(NULL, 0, LowShift);
            if(ShowLines) ObjectMaker("HiLoTrader RangeStart "+SearchShift, OBJ_VLINE, 0, iTime(NULL, 0, DayStartShift), 0, Yellow, True, STYLE_SOLID);
            if(ShowLines) ObjectMaker("HiLoTrader RangeEnd "+SearchShift, OBJ_VLINE, 0, iTime(NULL, 0, RangeEndShift), 0, Yellow, True, STYLE_DASH);
            }    
         //Determine subsequent high and low
         if(DayStartShift > RangeEndShift)
            {
            if(iHigh(NULL, 0, SearchShift) > HighValue)
               {
               HighValue1 = HighValue;
               HighValue = iHigh(NULL, 0, SearchShift);
               TestResultBO = TestTrader("Long", HighValue1, SearchShift);
               if(TestResultBO == "Win")
                  {
                  BreakoutWin++;
                  BreakoutTotal++;
                  }
               if(TestResultBO == "Loss")
                  {
                  BreakoutLoss++;
                  BreakoutTotal++;
                  }
               if(TestResultBO == "Tie")
                  {
                  BreakoutTie++;
                  BreakoutTotal++;
                  }      
               TestResultCT = TestTrader("Short", HighValue1, SearchShift);
               if(TestResultCT == "Win")
                  {
                  CounterWin++;
                  CounterTotal++;
                  }
               if(TestResultCT == "Loss")
                  {
                  CounterLoss++;
                  CounterTotal++;
                  }
               if(TestResultCT == "Tie")
                  {
                  CounterTie++;
                  CounterTotal++;
                  }   
               if(TestResultBO == "Tie" && TestResultCT == "Tie" && ShowLines) ObjectMaker("HiLoTrader Aqua High "+SearchShift+" "+DoubleToStr(HighValue1, Digits)+" BO: "+TestResultBO+" CT: "+TestResultCT, OBJ_VLINE, 0, iTime(NULL, 0, SearchShift), 0, Aqua, True, STYLE_DASHDOT);    
               if((TestResultBO != "Tie" || TestResultCT != "Tie") && ShowLines) ObjectMaker("HiLoTrader Lime High "+SearchShift+" "+DoubleToStr(HighValue1, Digits)+" BO: "+TestResultBO+" CT: "+TestResultCT, OBJ_VLINE, 0, iTime(NULL, 0, SearchShift), 0, Lime, True, STYLE_DASHDOT);    
               }  
            if(iLow(NULL, 0, SearchShift) < LowValue)
               {
               LowValue1 = LowValue;
               LowValue = iLow(NULL, 0, SearchShift);
               TestResultBO = TestTrader("Short", LowValue1, SearchShift);
               if(TestResultBO == "Win")
                  {
                  BreakoutWin++;
                  BreakoutTotal++;
                  }
               if(TestResultBO == "Loss")
                  {
                  BreakoutLoss++;
                  BreakoutTotal++;
                  }
               if(TestResultBO == "Tie")
                  {
                  BreakoutTie++;
                  BreakoutTotal++;
                  }    
               TestResultCT = TestTrader("Long", LowValue1, SearchShift);
               if(TestResultCT == "Win")
                  {
                  CounterWin++;
                  CounterTotal++;
                  }
               if(TestResultCT == "Loss")
                  {
                  CounterLoss++;
                  CounterTotal++;
                  }
               if(TestResultCT == "Tie")
                  {
                  CounterTie++;
                  CounterTotal++;
                  }  
               if(TestResultBO == "Tie" && TestResultCT == "Tie" && ShowLines) ObjectMaker("HiLoTrader Aqua Low "+SearchShift+" "+DoubleToStr(LowValue1, Digits)+" BO: "+TestResultBO+" CT: "+TestResultCT, OBJ_VLINE, 0, iTime(NULL, 0, SearchShift), 0, Aqua, True, STYLE_DOT);   
               if((TestResultBO != "Tie" || TestResultCT != "Tie") && ShowLines) ObjectMaker("HiLoTrader Red Low "+SearchShift+" "+DoubleToStr(LowValue1, Digits)+" BO: "+TestResultBO+" CT: "+TestResultCT, OBJ_VLINE, 0, iTime(NULL, 0, SearchShift), 0, Red, True, STYLE_DOT);   
               
               }    
            
            Comment("Calculating...\n",
            "Broker Type: ", BrokerType, "\n",
        "Breakout Win: ", BreakoutWin, "\n",
        "Breakout Loss: ", BreakoutLoss, "\n",
        "Breakout Unsure: ", BreakoutTie, "\n",
        "Breakout Total: ", BreakoutTotal, "\n",
        "Counter Win: ", CounterWin, "\n",
        "Counter Loss: ", CounterLoss, "\n",
        "Counter Unsure: ", CounterTie, "\n",
        "Counter Total: ", CounterTotal);
            }   
        }
        
        double BOWinRate = (BreakoutWin / BreakoutTotal) * 100;
        double CTWinRate = (CounterWin / CounterTotal) * 100;
        double ErrorRate = ((BreakoutTie + CounterTie) / (BreakoutTotal + CounterTotal)) * 100;
        
       
        CalcTime = TimeToStr(TimeCurrent(), TIME_DATE|TIME_SECONDS);

        Comment("Calculating finished at: ",CalcTime, "\n",
        "Breakout Win: ", BreakoutWin, "\n",
        "Breakout Loss: ", BreakoutLoss, "\n",
        "Breakout Unsure: ", BreakoutTie, "\n",
        "Breakout Total: ", BreakoutTotal, "\n",
        "Counter Win: ", CounterWin, "\n",
        "Counter Loss: ", CounterLoss, "\n",
        "Counter Unsure: ", CounterTie, "\n",
        "Counter Total: ", CounterTotal, "\n",
        "Breakout Percent: ", BOWinRate, "%\n",
        "Counter Percent: ", CTWinRate, "%\n",
        "Tester Quality: ", 100-ErrorRate);
        
      return(SearchShift);  
      }
      
   string TestTrader(string TestDirection, double TestPrice, int TestShift)
      {
      double TestTakeProfit = 0;
      double TestStopLoss = 0;

      if(TestDirection == "Long")
         {
         TestTakeProfit = TestPrice + (TakeProfit * Point);
         TestStopLoss = TestPrice - (StopLoss * Point);
         }
      if(TestDirection == "Short")
         {
         TestTakeProfit = TestPrice - (TakeProfit * Point);
         TestStopLoss = TestPrice + (StopLoss * Point);
         }
      
      string FinalResult = "None";
      string TPResult = "None";
      string SLResult = "None";
      for (int FShift = TestShift; FShift > 0; FShift--)
         {
         if(TestDirection == "Long")
            {
            if(iHigh(NULL, 0, FShift) >= TestTakeProfit && iLow(NULL, 0, FShift) <= TestTakeProfit)
               {
               TPResult = "Hit";
               } 
            if(iHigh(NULL, 0, FShift) >= TestStopLoss && iLow(NULL, 0, FShift) <= TestStopLoss)
               {
               SLResult = "Hit";
               }
            }
         if(TestDirection == "Short")
            {
            if(iHigh(NULL, 0, FShift) >= TestTakeProfit && iLow(NULL, 0, FShift) <= TestTakeProfit)
               {
               TPResult = "Hit";
               } 
            if(iHigh(NULL, 0, FShift) >= TestStopLoss && iLow(NULL, 0, FShift) <= TestStopLoss)
               {
               SLResult = "Hit";
               }
            }
         if(FShift == TestShift && (TPResult == "Hit" || SLResult == "Hit"))
            {
            return("Tie");
            }   
         if(TPResult == "Hit" && SLResult == "Hit")
            {
            return("Tie");
            }   
         if(TPResult == "None" && SLResult == "Hit")
            {
            return("Loss");
            }   
         if(TPResult == "Hit" && SLResult == "None")
            {
            return("Win");
            }         
         } 
      }
      
void ObjectMaker(string OBJName, int OBJType, int OBJWindow, datetime OBJTime, double OBJPrice, color OBJColor, bool OBJBack, int OBJStyle)
   {
   ObjectDelete(OBJName);
   ObjectCreate(OBJName, OBJType, OBJWindow, OBJTime, OBJPrice);
   ObjectSet(OBJName, OBJPROP_COLOR, OBJColor);
   ObjectSet(OBJName, OBJPROP_STYLE, OBJStyle);
   ObjectSet(OBJName, OBJPROP_BACK, OBJBack);
   }