//+------------------------------------------------------------------+
//| Name          : Dashboard_Thrdscr_v1   
//| Modified by   : Alex
//| Date          : 24MAY2013
//|
//| Needs : 
//| Data Refreshment once per candle change
//| 
//| Another version of this program for another application was originally found on 
//| Steve Hopwood's site. Many thanks , Steve ! 
//+------------------------------------------------------------------+
#property indicator_chart_window

extern bool		ShowCurrentPairOnly  = false; //	Display only chart Pair
//extern string	PairsTT1             = "AUDCAD,AUDCHF,AUDJPY,AUDUSD,CADCHF,CADJPY,CHFJPY,EURAUD,EURCAD,EURCHF,EURGBP,EURJPY";
extern string	PairsTT1             = "AUDCHF,AUDCAD,AUDJPY,AUDUSD,CADCHF,CADJPY,CHFJPY,EURAUD,EURCAD,EURGBP,EURJPY";
extern string	PairsTT2             = "EURUSD,GBPAUD,GBPCAD,GBPCHF,GBPJPY,GBPUSD,NZDJPY,NZDUSD,USDCAD,USDCHF,USDJPY";
//extern string	PairsTT2             = "EURUSD,GBPAUD,GBPCAD,GBPCHF,GBPJPY,GBPUSD,NZDJPY,NZDUSD,USDCAD,USDCHF,USDJPY,XAUUSD";
//extern string	PeriodsToTrade    = "H1,H4,D1"; // Time Frames to display are user defined
extern string	PeriodsToTrade       = "D2,D1,D0,W%"; // Time Frames to display are user defined
extern int     Nr_bars              = 120;
extern bool    EveryTickMode        = false;//Tells the bot to read the indis at every tick
extern int     IndiReadTimeFrame    = 1;
//extern string  lb="----Look back inputs----";
//extern double  MinimumValueChange=1;
//extern bool    TrendRequiresAllThree=true;
//extern bool    TrendRequiresOnlyHtf=false;
//extern bool    AlertByEmail=false;
extern string	pdi                   ="----Pair display inputs----";
extern int		FontSize              =10;
extern color	FontColour            =DodgerBlue;
extern string	Font_Font             = "Lucida Sans Unicode";
extern double	DisplayStarts_X       =50;	//we positioning the object from the top right corner of window
extern double	DisplayStarts_Y       =15;
extern bool		IndicatorInRSIWindow  = false;	// Dispaly the indicator in the RSI Window
extern string	RSI_WindowName        = "RSI(3)";			// RSI Window ShortName

string	PairsToTrade;
double	ValueChange_1=0.4,
		   ValueChange_2=0.8;

int	symbolCodeSUP=233,
		symbolCodeSDN=234,
		symbolCodeWUP=236,
		symbolCodeWDN=238,
		symbolCodeNoSignal=162; //232;
color	colorCodeSUP=Blue,
		colorCodeSDN=Red,
		colorCodeWUP=DeepSkyBlue,
		colorCodeWDN=Magenta,
		colorCodeNoSignal=Green;

//Pair extraction
int		NoOfPairs;				// Holds the number of pairs passed by the user via the inputs screen
int		NoOfPeriods;			// Holds the number of periods passed by the user via the inputs screen
string	TradePair[];			//Array to hold the pairs traded by the user
string	TradePeriod[];			//Array to hold the periods traded by the user
int		TradePeriodTF[];		//Array to hold the periods traded by the user
int		TradeTrendSymbol[][5];	//Array to hold the pairs trend symbol
color 	TradeTrendColor[][5];	//Array to hold the pairs trend color
bool  	AlertSent[];
////////////////////////////////////////////////////////////////////////////////////////////////////
//SH addition
double   Slope[][8];//Array to hold the slope values
////////////////////////////////////////////////////////////////////////////////////////////////////
string	trend;
int		OldBars;
int WindowNo = 0;
//+------------------------------------------------------------------+
string objPrefix ;	// all objects drawn by this indicator will be prefixed with this
string buff_str ;	// all objects drawn by this indicator will be prefixed with this

double   Upbuf;
double   Dnbuf;

int      q2;  
double   prc; // current price 
int      shift;

//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
//+------------------------------------------------------------------+ 
//----
	int i, j;
	objPrefix = WindowExpertName();
	
	if(IndicatorInRSIWindow)
	{
		WindowNo = WindowFind(RSI_WindowName);
		if(WindowNo < 0)
		{
			Alert("RSI_WindowName is Wrong");
			return(0);
		}
		DisplayStarts_X = 5;
		DisplayStarts_Y = 5;
	}

	if(!ShowCurrentPairOnly)
	{
		PairsToTrade=PairsTT1+","+PairsTT2;
		//Extract the pairs traded by the user
		NoOfPairs = StringFindCount(PairsToTrade,",")+1;
		ArrayResize(TradePair, NoOfPairs);
		string AddChar = StringSubstr(Symbol(),6,4);
		StrPairToStringArray(PairsToTrade, TradePair, AddChar);
	}
	else
	{
		//Fill the array with only chart pair
		NoOfPairs = 1;
		ArrayResize(TradePair, NoOfPairs);
		TradePair[0] = Symbol();
	}
	
	NoOfPeriods = StringFindCount(PeriodsToTrade, ",")+1;
	ArrayResize(TradePeriod, NoOfPeriods);
	ArrayResize(TradePeriodTF, NoOfPeriods);
	StrToStringArray(PeriodsToTrade, TradePeriod);
   
	for(j=0; j<NoOfPeriods; j++)
	{
		TradePeriodTF[j] = StrToTF(TradePeriod[j]);	//this is for display Periods from topleft corner
		//TradePeriodTF[NoOfPeriods-j] = StrToTF(TradePeriod[j]);	//this is for display Periods from topright corner
	}
//----	
	ArrayResize(TradeTrendSymbol, NoOfPairs);
	ArrayInitialize(TradeTrendSymbol, symbolCodeNoSignal);		// Inizialize the array with symbolCodeNoSignal
	ArrayResize(TradeTrendColor, NoOfPairs);
	ArrayInitialize(TradeTrendColor, colorCodeNoSignal);		// Inizialize the array with colorCodeNoSignal
////////////////////////////////////////////////////////////////////////////////////////////////////
   ArrayResize(Slope, NoOfPairs);//SH addition
////////////////////////////////////////////////////////////////////////////////////////////////////

//      GetPairTrends(TradeTrendSymbol, TradeTrendColor);
//      PrintPairTrends();


	//----
	return(0);
}// End init()

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
{
//----
//+------------------------------------------------------------------+ 
	RemoveObjects(objPrefix);
//----
	return(0);
}// End deinit()

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
//extern bool    EveryTickMode=false;//Tells the bot to read the indis at every tick
//extern int     IndiReadTimeFrame=1;

   static datetime BarsTime;
   if (EveryTickMode) BarsTime = 0;
   
   if (BarsTime != Time[0])
   {
      BarsTime = Time[0];
      GetPairTrends(TradeTrendSymbol, TradeTrendColor);
      PrintPairTrends();
   }//if (BarsTime != Time[0])
   
}//End start()
//+------------------------------------------------------------------+

//-------------------------------------------------------------------+
// RemoveObjects                                                     |
//-------------------------------------------------------------------+
void RemoveObjects(string Pref)
{   
	int i;
	string objname = "";

	for (i = ObjectsTotal(); i >= 0; i--)
	{
		objname = ObjectName(i);
		if (StringFind(objname, Pref, 0) > -1) ObjectDelete(objname);
	}
	return(0);
} // End void RemoveObjects(string Pref)

//+------------------------------------------------------------------+
// StringFindCount                                                   |
//+------------------------------------------------------------------+
int StringFindCount(string str, string str2)
// Returns the number of occurrences of STR2 in STR
// Usage:   int x = StringFindCount("ABCDEFGHIJKABACABB","AB")   returns x = 3
{
  int c = 0;
  for (int i=0; i<StringLen(str); i++)
    if (StringSubstr(str,i,StringLen(str2)) == str2)  c++;
  return(c);
} // End int StringFindCount(string str, string str2)

//+------------------------------------------------------------------+
// StrPairToStringArray                                                  |
//+------------------------------------------------------------------+
void StrPairToStringArray(string str, string &a[], string p_suffix, string delim=",")
{
	int z1=-1, z2=0;
	for (int i=0; i<ArraySize(a); i++)
	{
		z2 = StringFind(str,delim,z1+1);
		a[i] = StringSubstr(str,z1+1,z2-z1-1) + p_suffix;
		if (z2 >= StringLen(str)-1)   break;
		z1 = z2;
	}
	return(0);
} // End void StrPairToStringArray(string str, string &a[], string p_suffix, string delim=",") 

//+------------------------------------------------------------------+
// StrToStringArray                                                  |
//+------------------------------------------------------------------+
void StrToStringArray(string str, string &a[], string delim=",")
{
	int z1=-1, z2=0;
	for (int i=0; i<ArraySize(a); i++)
	{
		z2 = StringFind(str,delim,z1+1);
		a[i] = StringSubstr(str,z1+1,z2-z1-1);
		if (z2 >= StringLen(str)-1)   break;
		z1 = z2;
	}
	return(0);
} // End void StrToStringArray(string str, string &a[], string delim=",") 

//+------------------------------------------------------------------+
// StrToTF(string str)                                               |
//+------------------------------------------------------------------+
// Converts a timeframe string to its MT4-numeric value
// Usage:   int x=StrToTF("M15")   returns x=15
int StrToTF(string str)
{
  str = StringUpper(str);
  str = StringTrimLeft(str);
  str = StringTrimRight(str);
  
  if (str == "M1")   return(1);
  if (str == "M5")   return(5);
  if (str == "M15")  return(15);
  if (str == "M30")  return(30);
  if (str == "H1")   return(60);
  if (str == "H4")   return(240);
  if (str == "D1")   return(1440);
  if (str == "W1")   return(10080);
  if (str == "MN")   return(43200);
  return(0);
}  

//+------------------------------------------------------------------+
// StringUpper(string str)                                           |
//+------------------------------------------------------------------+
// Converts any lowercase characters in a string to uppercase
// Usage:    string x=StringUpper("The Quick Brown Fox")  returns x = "THE QUICK BROWN FOX"
string StringUpper(string str)
{
  string outstr = "";
  string lower  = "abcdefghijklmnopqrstuvwxyz";
  string upper  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for(int i=0; i<StringLen(str); i++)  {
    int t1 = StringFind(lower,StringSubstr(str,i,1),0);
    if (t1 >=0)  
      outstr = outstr + StringSubstr(upper,t1,1);
    else
      outstr = outstr + StringSubstr(str,i,1);
  }
  return(outstr);
}  
//+------------------------------------------------------------------+
//| GetPairTrends                                                    |
//+------------------------------------------------------------------+
void GetPairTrends(int &trend_symbol[][], color &trend_color[][])
{
	int i, j;
	double c_val, p_val, delta_val;
	
	for(i=0; i<NoOfPairs; i++)
	{

		for(j=0; j<NoOfPeriods-1; j++)
		{
			trend_symbol[i][j] = symbolCodeNoSignal;
			trend_color[i][j] = colorCodeNoSignal;

	      shift=2-j; 
			q2 = Get_macd_adj(TradePair[i], shift);
         if (q2==1) 
         {
				trend_symbol[i][j] = symbolCodeSUP;
				trend_color[i][j] = colorCodeSUP;
         }
         if (q2==-1) 
         {
				trend_symbol[i][j] = symbolCodeSDN;
				trend_color[i][j] = colorCodeSDN;
         }
		} 
            
		trend_symbol[i][3] = symbolCodeNoSignal;
		trend_color[i][3] = colorCodeNoSignal;


		q2 = Get_Williams(TradePair[i], 0);
      if (q2==1) 
      {
			trend_symbol[i][3] = symbolCodeSUP;
			trend_color[i][3] = colorCodeSUP;
      }
      if (q2==-1) 
      {
			trend_symbol[i][3] = symbolCodeSDN;
			trend_color[i][3] = colorCodeSDN;
      }


	} 
	return(0);

}//End GetPairTrends(int &trend_symbol[][], color &trend_color[][])

//+------------------------------------------------------------------+
//| PrintPairTrends                                                    |
//+------------------------------------------------------------------+
void PrintPairTrends()
{
	RemoveObjects(objPrefix);
	
	int i, j;
	int ColStart = DisplayStarts_X;
	
//	buff_str = objPrefix+" PREV_DAY";  // Programname ; Dashboard_nld
	buff_str = objPrefix;  // Programname ; Dashboard_ceograv
	
	ObjectDelete(buff_str);
	ObjectCreate(buff_str,OBJ_LABEL,WindowNo,0,0,0,0);
	ObjectSet(buff_str,OBJPROP_CORNER,1);
	ObjectSet(buff_str,OBJPROP_XDISTANCE,DisplayStarts_X -60+ FontSize*(NoOfPeriods*2));
   ObjectSet(buff_str,OBJPROP_YDISTANCE,DisplayStarts_Y - (FontSize+FontSize/2));
	ObjectSetText(buff_str,buff_str,FontSize-2,Font_Font,FontColour);

//	Comment("  xxx",TradePeriod[0]," objprefix:  ",objPrefix,"  bufstr:  ",buff_str);


	//Set Trade Pair
	for(i=0; i<NoOfPairs; i++)
	{
		buff_str = StringConcatenate(objPrefix, TradePair[i]);
		ObjectDelete(buff_str);
		ObjectCreate(buff_str,OBJ_LABEL,WindowNo,0,0,0,0);
		ObjectSet(buff_str,OBJPROP_CORNER,1);
		ObjectSet(buff_str,OBJPROP_XDISTANCE,DisplayStarts_X + FontSize*(NoOfPeriods*2));
		ObjectSet(buff_str,OBJPROP_YDISTANCE,DisplayStarts_Y + (i+1)*(FontSize+FontSize/2));
		ObjectSetText(buff_str,TradePair[i],FontSize-2,Font_Font,FontColour);
	}
	//Set Trade Period




	for(j=0; j<NoOfPeriods; j++)
	{
		buff_str = StringConcatenate(objPrefix, TradePeriod[j]);
		ObjectDelete(buff_str);
		ObjectCreate(buff_str,OBJ_LABEL,WindowNo,0,0,0,0);
		ObjectSet(buff_str,OBJPROP_CORNER,1);
		ObjectSet(buff_str,OBJPROP_XDISTANCE,DisplayStarts_X + (NoOfPeriods-1-j)*(FontSize*2));
		ObjectSet(buff_str,OBJPROP_YDISTANCE,DisplayStarts_Y);
		ObjectSetText(buff_str,TradePeriod[j],FontSize-2,Font_Font,FontColour);      
	}

	//Set Trade Trend
	for(i=0; i<NoOfPairs; i++)
	{
      for(j=0; j<NoOfPeriods; j++)
		{
			buff_str = StringConcatenate(objPrefix, TradePair[i], TradePeriod[j]);
			ObjectDelete(buff_str);
			ObjectCreate(buff_str,OBJ_LABEL,WindowNo,0,0,0,0);
 			ObjectSet(buff_str,OBJPROP_CORNER,1);
			ObjectSet(buff_str,OBJPROP_XDISTANCE,DisplayStarts_X + (NoOfPeriods-1-j)*(FontSize*2));
			ObjectSet(buff_str,OBJPROP_YDISTANCE,DisplayStarts_Y + (i+1)*(FontSize+FontSize/2));
			ObjectSetText(buff_str,CharToStr(TradeTrendSymbol[i][j]),FontSize,"Wingdings",TradeTrendColor[i][j]);
		}//for(j=0; j<NoOfPeriods; j++)

////////////////////////////////////////////////////////////////////////////////////////////////////
//SH addition
   
   //Set Slope values. Not a clue how.
////////////////////////////////////////////////////////////////////////////////////////////////////
      
	}//for(i=0; i<NoOfPairs; i++)
//----
	return(0);

}//End PrintPairTrends()


double Get_macd_adj(string smbl, int shft)
{
   double   macd_main;
   double   macd_sgnl;
   
   double   prc;
   double   y1,y2,y3,y4;
   int      Result;  // 1 = go long, -1 = go short 

   prc  = iClose(smbl,PERIOD_D1,shft);  //MarketInfo(smbl,MODE_BID);

   macd_main =  iMACD(smbl,PERIOD_D1,12,24,9,PRICE_CLOSE,MODE_MAIN,shft);
   macd_sgnl =  iMACD(smbl,PERIOD_D1,12,24,9,PRICE_CLOSE,MODE_SIGNAL,shft);



   y1 = macd_main - macd_sgnl;
   
   if (y1>0  ) Result=1;
   if (y1<=0 ) Result=-1;

//   Comment("shft: ",shft,"  smbl:",smbl,"  prc: ",prc,"  macd_main: ",macd_main,"  macd_sgnl:",macd_sgnl," y1: ",y1);

   return(Result);  
}


double Get_Williams(string smbl, int shft)
{
   double   y1,y2;
   int      Result;
   
   y1 =  iWPR(smbl,PERIOD_H1,14,shft); 

   if (y1 <= -80) Result = 1;
   if (y1 >= -20) Result = -1; 

   return(Result);
}

