//+------------------------------------------------------------------+
//|  RK-RenkoLiveChart_v3-script-adj  Old RenkoLiveChart_v1.6.mq4
//|          Inspired from Renco script by "e4" (renko_live_scr.mq4) |
//|                                         Copyleft 2009 LastViking |
//| Jan 18, 2014-RK
//| 1.converted to 3-5 digit 
//| 2.converted to ajustable renko candle size & start location by %
//| Jan 25, 2014-RK
//| 1. added strange symbol option for 6+ brokers
//| Feb 10, 2014 -RK
//| 1. added new mt4 language to compile and work with Strategy tester 5M
//| Mar 23, 2014 Converted BoxShiftAdjust to % 
//+------------------------------------------------------------------+
#property copyright "" 
#property show_inputs
//+------------------------------------------------------------------+
#include <WinUser32.mqh>
//+------------------------------------------------------------------+
extern int     BoxSize                 = 10;
extern int     RenkoTimeFrame          = 6;      // What time frame to use for the offline renko chart
extern double  BoxShiftAdjust          = 10;  // 50.0 =meanlive, 100.0 = old 3.2
extern bool    RescaleFor5DigitsBroker = TRUE;
extern bool    VolumeInHistory         = true;
extern int     RefreshRate             = 0;		// Minimum nr of seconds between chart updates
extern bool StrangeSymbolName          = False;
extern int  SymbolNamenumber           = 8;
//double SymbolName;
//+------------------------------------------------------------------+
int start() {
   	int i, LastFPos = 0, HstHandle = -1;
   	
   	string SymbolName = StringSubstr(Symbol(), 0, 6);
   	if(StrangeSymbolName) SymbolName = StringSubstr(Symbol(), 0, SymbolNamenumber);
		else SymbolName = Symbol();
	   	
      double CurHigh,CurLow;
		double CurOpen, CurClose;				
   	
  	//---- History header
   	int HstVersion = 400;
   	string HstCopyright = "";
   	string HstSymbol = SymbolName;
   	int HstPeriod = RenkoTimeFrame; 
   	int HstDigits = Digits;
   	int HstUnused[13];
	   //MqlRates rate;
	   
   	HstHandle = FileOpenHistory(HstSymbol + HstPeriod + ".hst",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_ANSI);
   	if(HstHandle < 0) 
   	   return(-1);
   	
   	//ArrayInitialize(HstUnused,0);
	//---- write history file header
   	FileWriteInteger(HstHandle, HstVersion, LONG_VALUE);
   	FileWriteString(HstHandle, HstCopyright, 64);
   	FileWriteString(HstHandle, HstSymbol, 12);
   	FileWriteInteger(HstHandle, HstPeriod, LONG_VALUE);
   	FileWriteInteger(HstHandle, HstDigits, LONG_VALUE);
   	FileWriteInteger(HstHandle, 0, LONG_VALUE);
   	FileWriteInteger(HstHandle, 0, LONG_VALUE);
   	FileWriteArray(HstHandle, HstUnused, 0, 13);
   	
  	Comment("RK-RenkoLiveChart_v6-script_adj-nf:  BoxSize ( ",DoubleToStr( BoxSize,0) ," Pip ) BoxShiftAdjust ( ",DoubleToStr( BoxShiftAdjust,1),"%)","\n"
        "   	 Open Offline ", HstSymbol,"   M", HstPeriod, " to view chart");
  	//Comment("RK-RenkoLiveChart_v6-script_adj-nf: Open Offline ", HstSymbol," BoxSize ( ",DoubleToStr( BoxSize,0) ," Pip ) BoxShiftAdjust ( ",DoubleToStr( BoxShiftAdjust,1),"%)  M", HstPeriod, " to view chart");
	//---- write history file   	
  	//int BoxPoints = 1;
   double BoxPoints;
   if (Digits == 3 || Digits > 4) 
   {
      if (RescaleFor5DigitsBroker) 
      {
        // BoxPoints = 10 * BoxSize;  //CHANGED 9-20-2010
        BoxPoints = NormalizeDouble(10 * BoxSize*Point, Digits);
      }
   }
   	
   	      // BoxPoints = NormalizeDouble(BoxSize*Point, Digits);
   	 double close = Close[1]; //me
   	double digits = Digits; //me
   	
   	double PrevLow = NormalizeDouble(MathFloor(Close[Bars-1]/BoxPoints)*BoxPoints, Digits);
Print("PrevLow  ",PrevLow,"  Close " ,close," Boxpoints ",BoxPoints," digits ",digits,"  line 83   new prevlow"); //all print me
   	 	
   	double PrevHigh = PrevLow + BoxPoints;
   	double PrevOpen = PrevLow;
   	double PrevClose = PrevHigh;
      double CurVolume = 1;
      datetime PrevTime = Time[Bars-1];  	

 	//---- begin historical data  
  	i = Bars-2;
  	while(i >= 0) {
  		//get price based on High / Low of bar
		PrevTime = Time[i]; 
		CurVolume = CurVolume + Volume[i];
		
		if(LastFPos != 0 && VolumeInHistory) {
			FileSeek(HstHandle, LastFPos, SEEK_SET);
			FileWriteDouble(HstHandle, CurVolume, DOUBLE_VALUE);	
		}
		
		bool UpTrend = High[i]+Low[i] > PrevHigh+PrevLow;
Print("uptrend (", UpTrend,") PrevHigh  ",PrevHigh, "  PrevLow " ,PrevLow,"    line 104     UT or DT");
		// update low before high or the revers depending on is closest to prev. renko bar
		
		while(UpTrend && Low[i] <= PrevLow-(BoxShiftAdjust/100) *BoxPoints) { 
Print("uptrend ", UpTrend,"  Prevlow ",PrevLow,"  PrevHigh  ",PrevHigh, "   Line 108  Low");
  			PrevHigh = PrevHigh - (BoxShiftAdjust/100) *BoxPoints;
  		   PrevLow = PrevLow - (BoxShiftAdjust/100) *BoxPoints;
  		//Print("PrevHigh  ",PrevHigh, "  PrevLow " ,PrevLow,"    line 106 final");
  			PrevOpen = PrevHigh;
  			PrevClose = PrevLow;
  			CurVolume = 1;
  			
			FileWriteInteger(HstHandle, PrevTime, LONG_VALUE);
			FileWriteDouble(HstHandle, PrevOpen, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevLow, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevHigh, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevClose, DOUBLE_VALUE);
  			LastFPos = FileTell(HstHandle);   // Remeber Last pos in file			
			FileWriteDouble(HstHandle, CurVolume, DOUBLE_VALUE);
			PrevTime++;
		}
		
		while(High[i] >= PrevHigh+(BoxShiftAdjust/100) *BoxPoints) {
Print("PrevHigh  ",PrevHigh, "  PrevLow " ,PrevLow,"    line 127     High");
  			PrevHigh = PrevHigh + (BoxShiftAdjust/100) *BoxPoints;
  			PrevLow = PrevLow + (BoxShiftAdjust/100) *BoxPoints;
  			PrevOpen = PrevLow;
  			PrevClose = PrevHigh;
  			CurVolume = 1;
  			
			FileWriteInteger(HstHandle, PrevTime, LONG_VALUE);
			FileWriteDouble(HstHandle, PrevOpen, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevLow, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevHigh, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevClose, DOUBLE_VALUE);
  			LastFPos = FileTell(HstHandle);   // Remeber Last pos in file			
			FileWriteDouble(HstHandle, CurVolume, DOUBLE_VALUE);
			PrevTime++;
		}
		
  		while(!UpTrend && Low[i] <= PrevLow-(BoxShiftAdjust/100) *BoxPoints) {
Print("uptrend (", UpTrend,")PrevHigh  ",PrevHigh, "  PrevLow " ,PrevLow,"    line 145    ! UT");
  			PrevHigh = PrevHigh -(BoxShiftAdjust/100) * BoxPoints;
  			PrevLow = PrevLow - (BoxShiftAdjust/100) *BoxPoints;
  			PrevOpen = PrevHigh;
  			PrevClose = PrevLow;
  			CurVolume = 1;
  			
			FileWriteInteger(HstHandle, PrevTime, LONG_VALUE);
			FileWriteDouble(HstHandle, PrevOpen, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevLow, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevHigh, DOUBLE_VALUE);
			FileWriteDouble(HstHandle, PrevClose, DOUBLE_VALUE);
  			LastFPos = FileTell(HstHandle);   // Remeber Last pos in file			
			FileWriteDouble(HstHandle, CurVolume, DOUBLE_VALUE);
			PrevTime++;
		}		
		i--;
	} 
	FileFlush(HstHandle);	
 	//----- end historical data
 	
 	//------ begin live data feed
	int hwnd = 0; 
	
   RefreshRates();
   CurHigh = PrevHigh; 
   CurLow = PrevLow;
   CurOpen = Bid;
   CurClose = Bid;

	datetime CurOpenTime = 0;
		
   	CurVolume = 0;
   	datetime LastUpdate = TimeLocal()-RefreshRate;
   	while(!IsStopped()) {
   	
   		if(RefreshRates()) {
   		
			if(hwnd == 0) { 
				hwnd = WindowHandle(SymbolName, HstPeriod); 
				if(hwnd != 0) Print("Chart window detected");
			}
   		// up box	
   			if(Bid >= PrevHigh+(BoxShiftAdjust/100) *BoxPoints) {
Print("PrevHigh  ",PrevHigh, "  PrevLow " ,PrevLow,"    line 189     Bid>");
				CurVolume++;   			
				FileSeek(HstHandle, LastFPos, SEEK_SET);
				FileWriteDouble(HstHandle, CurVolume, DOUBLE_VALUE);   			
   			
     	  		PrevHigh = PrevHigh + (BoxShiftAdjust/100) *BoxPoints;
	  			PrevLow = PrevLow + (BoxShiftAdjust/100) *BoxPoints;
  				PrevOpen = PrevLow;
  				PrevClose = PrevHigh;
  				PrevTime = TimeCurrent();            		  				
  				  			
				FileWriteInteger(HstHandle, PrevTime, LONG_VALUE);
				FileWriteDouble(HstHandle, PrevOpen, DOUBLE_VALUE);
				FileWriteDouble(HstHandle, PrevLow, DOUBLE_VALUE);
				FileWriteDouble(HstHandle, PrevHigh, DOUBLE_VALUE);
				FileWriteDouble(HstHandle, PrevClose, DOUBLE_VALUE);
  			  	LastFPos = FileTell(HstHandle);   // Remeber Last pos in file				  							
				FileWriteDouble(HstHandle, 1, DOUBLE_VALUE);
            		FileFlush(HstHandle);
            		
            CurOpenTime = 0;
  				CurVolume = 0;
				CurHigh = Bid;
				CurLow = Bid;  				            		
  				
            if(hwnd != 0) if(PostMessageA(hwnd, WM_COMMAND, 0x822c, 0) == 0) hwnd = 0;
//				if(hwnd != 0) PostMessageA(hwnd, WM_COMMAND, 0x822c, 0);											
			}
			else if(Bid <= PrevLow-(BoxShiftAdjust/100) * BoxPoints) {
Print("PrevHigh  ",PrevHigh, "  PrevLow " ,PrevLow,"    line 218     Bid <=");
				CurVolume++;			
				FileSeek(HstHandle, LastFPos, SEEK_SET);
				FileWriteDouble(HstHandle, CurVolume, DOUBLE_VALUE);			
			
  				PrevHigh = PrevHigh -(BoxShiftAdjust/100) *  BoxPoints;
  				PrevLow = PrevLow -(BoxShiftAdjust/100) *  BoxPoints;
  				PrevOpen = PrevHigh;
  				PrevClose = PrevLow;
  				PrevTime = TimeCurrent();            		  				
  				  			
				FileWriteInteger(HstHandle, PrevTime, LONG_VALUE);
				FileWriteDouble(HstHandle, PrevOpen, DOUBLE_VALUE);
				FileWriteDouble(HstHandle, PrevLow, DOUBLE_VALUE);
				FileWriteDouble(HstHandle, PrevHigh, DOUBLE_VALUE);
				FileWriteDouble(HstHandle, PrevClose, DOUBLE_VALUE);
  			  	LastFPos = FileTell(HstHandle);   // Remeber Last pos in file				  							
				FileWriteDouble(HstHandle, 1, DOUBLE_VALUE);
            		FileFlush(HstHandle);
            		
            		CurOpenTime = 0;
  				CurVolume = 0;
				CurHigh = Bid;
				CurLow = Bid;  				
            		  				
            if(hwnd != 0) if(PostMessageA(hwnd, WM_COMMAND, 0x822c, 0) == 0) hwnd = 0;
//				if(hwnd != 0) PostMessageA(hwnd, WM_COMMAND, 0x822c, 0);
			} 
			else {
				
				if(CurHigh < Bid) CurHigh = Bid;
				if(CurLow > Bid) CurLow = Bid;
				CurVolume++;
				
				if((TimeLocal()-LastUpdate) >= RefreshRate) {
				
					LastUpdate = TimeLocal();
				
					FileSeek(HstHandle, LastFPos, SEEK_SET); 
					FileWriteDouble(HstHandle, CurVolume, DOUBLE_VALUE);
								
					if(PrevHigh <= Bid) CurOpen = PrevHigh;
					else if(PrevLow >= Bid) CurOpen = PrevLow;
					else CurOpen = Bid;
					CurClose = Bid;
					
					if(CurOpenTime == 0) CurOpenTime = TimeCurrent();
				
					FileWriteInteger(HstHandle, CurOpenTime, LONG_VALUE);		// Time
					FileWriteDouble(HstHandle, CurOpen, DOUBLE_VALUE);         	// Open
					FileWriteDouble(HstHandle, CurLow, DOUBLE_VALUE);		// Low
					FileWriteDouble(HstHandle, CurHigh, DOUBLE_VALUE);		// High
					FileWriteDouble(HstHandle, CurClose, DOUBLE_VALUE);		// Close
					FileWriteDouble(HstHandle, 1, DOUBLE_VALUE);			// Volume				
            			FileFlush(HstHandle);
            			
                     if(hwnd != 0) if(PostMessageA(hwnd, WM_COMMAND, 0x822c, 0) == 0) hwnd = 0;
//            			if(hwnd != 0) PostMessageA(hwnd, WM_COMMAND, 0x822c, 0);
            		}
			}
		}
		else {
			Sleep(50); 
		}
	}
	
	FileClose(HstHandle);
   	Comment(""); // remove comment from main chart
	return(0);
}
//+------------------------------------------------------------------+
   