//+------------------------------------------------------------------+
//|                                       atstraderRecentCandles.mq4 |
//+------------------------------------------------------------------+
/*
Current Author: http://www.forexfactory.com/atstrader
Current Version: 1.17, uploaded November 9, 2013

Original Name: "Recent Candles" indicator 
Original Author: http://www.forexfactory.com/hanover
Original Thread: http://www.forexfactory.com/showthread.php?t=159644
Original Version: 1.15, uploaded February 14, 2011
_____________________

TERMS AND CONDITIONS

Please note that all code is supplied FREE of charge. 
Therefore the following conditions apply:

1. You agree that, if you download and use the code, it is ENTIRELY AT YOUR OWN RISK. 
   I accept NO LIABILITY for any financial losses or computer related damage, caused by 
   either the correct or incorrect use of the code.
2. Feel welcome to share the code freely, and modify any MQ4 source. However, you may NOT sell, 
   or otherwise distribute, any part of the code commercially, without my prior written consent.
3. The code may not run correctly on Windows 7, Windows 8 or Vista, 
   probably for the reasons given http://4xtrader.net/how-to-run-metatrader-on-windows-7-or-vista/
_____________________

Disclaimer: The attached indicator is supplied 'as is', free of charge. 
            No warranty or obligation of support is implied. Download and use it at your own risk. 
_____________________

INSTRUCTIONS

This indicator will show the most recent X candles in any pair/timeframes on your current chart. 
It can update itself every tick (warning: could slow computer performance), or once per candle on any 
timeframe that you specify. It allows you to see trend/momentum/patterns in all timeframes simultaneously, 
without having to move between charts, as shown in the attached screenshot. Trade with the thrust 
provided by the longer term trends; and/or use as a kind of 'currency strength meter' to trade with 
the strongest and cleanest trending pairs.

Or, if you prefer, edit the indicator and go to the 'Levels' tab. You could add levels at (for example) 
25 and 75, just like with an oscillator, and then place countertrend trades when price is oversold or 
overbought on multiple timeframes, and/or across correlated pairs. Note that the 'indicator' values 
always range between 0 and 100 (just like RSI or stochastic), across all timeframes. Adjust the NumCandles 
parameter to plot quartile (or whatever) lines for any given number of candles.

If you set the NumCandles parameter to 0, and compress the window size vertically, you effectively get a 
'traffic light' indicator, that simply shows a green or red symbol, highlighting whether price is currently 
bullish or bearish in each timeframe.

To display different pairs all on the one chart, simply attach the indicator multiple times.

To invert the process (i.e. pairs in the one sub-window, a separate sub-window for each timeframe), 
attach multiple occurrences of the indicator, each for a single timeframe and the same group of currency 
pairs. Or attach one occurrence of the indicator, with multiple pairs, but 
leave the timeframe blank; then switch timeframes on the chart to show the candles for all pairs, for 
the selected timeframe.

You can set the parameters either by using MT4's built-in dialog, when you attach the indicator; or by overriding 
these settings using the Presets---Recent Candles.TXT file (into the ...../experts/files folder). 
Using the file allows you to save preset values, retaining them for each future time you attach the indicator. 
To disable an entry in the file, start the line with two slashes (//). To re-enable it, remove the slashes. 
You may use any number of embedded spaces or underscores, and/or any combo of upper or lower case, to aid 
readability, however you wish. Every line MUST end with a semi-colon (; ). To save typing and improve accuracy, 
copy/paste the sample lines in the file. To disable the entire file, rename it, or delete its content; if the 
file doesn't exist, the Parameter Dialog entries (when you attach/edit the indicator) will be used. To have any 
changes take immediate effect, either (1) re-attach the indicator to your chart; (2) edit the indicator 
(press Ctrl-I); or (3) toggle between timeframes.

To expand/compress the plot(s) horizontally, zoom in/out using the +/ keys.
To expand/compress the plot(s) vertically, drag the window separator upward/downward.
_____________________

PARAMETERS

    CurrencyPairs       - leave blank to default to the current chart's pair. Otherwise type in up to 30 pairs 
                          (e.g. GBPUSD or simply GU), separated by commas. Pairs will display in the left-to-right order 
                          in which you type them. Spaces are optional, and may be included for clarity. Upper/lowercase may 
                          be used interchangeably (e.g. USDCHF or usdchf). Permissible abbreviations are:
                          A=AUD; C=CAD; E=EUR; F=CHF; G=GBP; J=JPY; N=NZD; U=USD; H=HKD; S=SGD; Z=ZAR. So you could type gj 
                          instead of GBPJPY, for example. If the pair name typed is not exactly 2 characters, the abbreviation 
                          will not be recognized. You can type a valid pair symbol followed by an asterisk (*), to have its 
                          inverted pair's candles plotted, e.g. typing AU* will plot USDAUD instead of AUDUSD candles.
    RisingVolumeBars    - if set to TRUE, this will plot High / Low Bars with high-lighted Rising Volume
    HeikinAshiCandles   - if set to TRUE, this will plot Heikin Ashi candles, instead of conventional ones.
    TimeFrames          - select the timeframes you wish to see, separated by commas. If displaying only one timeframe, a trailing 
                          comma is not required. Leaving this parameter blank defaults to the timeframe of the chart to which the 
                          indicator is attached. The spaces are optional, and are included merely for clarity. Upper/lowercase may be 
                          used interchangeably (e.g. H1 or h1). Time frames will display in the left-to-right order in which you type them
    NumCandles          - how many candles back from the currently forming one, that you want to see. For example, to see the 
                          currently forming candle, and also the last 3 candles, type 3. Typing 0 (or leave blank) causes only the 
                          currently forming candle to display, creating a 'traffic light' indicator. Typing a single value will display 
                          that number of candles for all timeframes. Typing multiple values, separated by commas, allows a different 
                          number of candles for each timeframe (by matching the NumCandles entry with the corresponding TimeFrames entry)
    HistoricalShift      enter 0 to display the current plot. Enter a positive number to display the plot as it would have looked 
                          X candles ago. Typing a single value will display that HistoricalShift for all timeframes. Typing multiple 
                          values, separated by commas, allows a different HistoricalShift for each timeframe (by matching the 
                          HistoricalShift entry with the corresponding TimeFrames entry). This will likely be necessary, e.g. to see 
                          the candles as they were 4 hours ago, you'd need to type 1,4,8,16,48 for the H4,H1,M30,M15,M5 timeframes, respectively
    RefreshEveryXMins   - if set to 0, this will cause the window to update itself immediately a new tick occurs. 
                          If set to 1, 5, 15, 30, 60, or 240, this will cause the window to update itself every time a new candle 
                          appears on the M1, M5, M15, M30, H1 or H4 chart, respectively

  Multi_Indi_Settings
    MultipleCurrencyPairs        - if multiple indis are used on one chart type in the pairs (e.g. GBPUSD or simply GU), separated by commas.
    MultipleIndicatorsOnChart    - enter the pair on which the multiple indis are attached.
    MultipleIndicatorsNumCandles - number of bars used per chart. NumCandles parameter will be ignored in this case.

  Display_Settings
    DisplayInfo       - if set to TRUE, this will display the symbol name and last Bid/Ask price
    DisplaySwap       - if set to TRUE, this will display the Long/short swap rates
    DisplaySpread     - if set to TRUE, this will display the Spread (and spread as a % of average 10 day move)
    DisplayPipValue   - if set to TRUE, this will display the Pip Value (dollar value your acount will change per pip, for each full lot traded)
    DisplayLastTick   - if set to TRUE, this will display the time of the last tick
    DisplayRange      - if set to TRUE, this will display the daily range (and range as a % of average 10 day move)
    DisplayDragons    - if set to TRUE, this will display multiple dragons and distance to dragon border in percent (dragon range 100 percent)
    DragonTimeFrames  - select the timeframes you wish to see as dragons, separated by commas. e.g. "H1, M15, M1"
    DisplayRecentBarHighLowAlertBox - if set to TRUE, this will display an colored alert box for higher/lower price compared to all other bars in same time frame
    RecentBarHighLowNumCandles      - number of bars used to check the highest and lowest price
    DisplayCcyName    - if set to TRUE, <pair> will be included in the labels displayed along the bottom of the window
    DisplayTF         - if set to TRUE, <timeframe> will be included in the labels displayed along the bottom of the window

  PVA_Settings (Price Volume Analysis) - Candle Bars for Candles With Volume Rising Above Average
    PVA_Rising_Period    - number of bars used to calculate the average volume
    PVA_Rising_FactorMin - first of three rising volume levels. Min Factor determines if bar volume is greater than the average volume multiplied by this factor.
    PVA_Rising_FactorMed - second of three rising volume levels. Med Factor determines if bar volume is greater than the average volume multiplied by this factor.
    PVA_Rising_FactorMax - third of three rising volume levels. Max Factor determines if bar volume is greater than the average volume multiplied by this factor.

  Fast_Volume_Settings
    DisplayFastVolumeOnLastBar - if set to TRUE, this will calculate the last bar volume color based on percent time past.
                                 (if 50% of time pased, then 50% of average volume used to compare)
                                 So its possible to get a starting high volume bar and at the end just have a normal volume for the complete time frame bar.
    DisplayFastVolumeAlertBox  - if set to TRUE, this will display an colored alert box along the bottom of the window
    FastVolumeStartPercent     - ignores the first starting percent of a time frame e.g. 10% of M1 ignores first 6 seconds
    FastVolumeMaxTimeFrame     - since it makes on sence starting D1 levels the default for max is H1.

  Levels_Settings
    Display_Levels               - if set to TRUE, places level lines on your chart at key levels between whole numbers (00, 25, 50, 75 and 00 again)
    Display_Level_Numbers        - if set to TRUE, places the level value below the level line
    Display_Half_Lines           - if set to TRUE, enables half numbers (50)
    Display_Quarter_Lines        - if set to TRUE, enables quarter numbers (25 and 75)
    Display_Levels_TimeFrames    - select the timeframes you wish to see levels displayed, separated by commas. If blank, all timeframes are used.
    Level_Line_Length_NumCandles - if set different from 0, reduces the line length to specified number of candles
    Level_Bid_Line_On            - if set to TRUE, places a bid line on each timeframe
    Level_Ask_M1_Line_On         - if set to TRUE, places an ask line on the M1 timeframe

  Style_Settings
    CandleBodyWidth       - set to a value between 2 and 5. Default is 3. A higher value means wider candle bodies. 
    CandleShadowWidth     - set to a value between 1 and 3. Default is 1. A higher value means wider candle shadow.
                            Experiment until you find a value that suits
    SpacingBetweenCandles - set to 1, 2 or 3. Higher number means wider spacing between candles, and is preferable when the main chart 
                            is 'zoomed out' to smaller candles. Experiment until you find a value that suits
    Colors, Font and Size - should be self-explanatory
    
_____________________
Acknowlegements:
TAH - for his Levels code used from the "SonicR Control Panel" indicator and his PVA code used from the "SonicR PVA Candles" indicator
Hanover - for publishing this great indicator
_____________________

*/


#property indicator_separate_window
#property indicator_minimum -35
#property indicator_maximum 120

#property indicator_buffers 8
#property indicator_color1 Lime
#property indicator_color2 Tomato
#property indicator_color3 Blue
#property indicator_color4 Green
#property indicator_color5 Magenta
#property indicator_color6 Black
#property indicator_color7 White
#property indicator_color8 White

#property indicator_width1 3
#property indicator_width2 3
#property indicator_width3 3
#property indicator_width4 3
#property indicator_width5 3
#property indicator_width7 3

extern string     CurrencyPairs          = "";
extern bool       RisingVolumeBars       = true;
extern bool       HeikinAshiCandles      = false;
extern string     _select_TimeFrames     = "MN, W1, D1, H4, H1, M30, M15, M5, M1";
extern string     TimeFrames             = "D1, H1, M15, M1";
extern string     NumCandles             = "70";
extern string     HistoricalShift        = "0";
extern int        RefreshEveryXMins      = 0;

extern string     _______                      = "";
extern string     Multi_Indi_Settings          = "Multi Indi Settings:"; 
extern string     MultipleCurrencyPairs        = "EURUSD,GBPUSD,EURJPY,USDJPY";
extern string     MultipleIndicatorsOnChart    = "EURCHF";
extern string     MultipleIndicatorsNumCandles = "70";

extern string     ______                 = "";
extern string     Display_Settings       = "Display Settings:"; 
extern bool       DisplayInfo            = true;
extern bool       DisplayLastTick        = false;
extern bool       DisplaySwap            = false;
extern bool       DisplaySpread          = true;
extern bool       DisplayRange           = true;
extern bool       DisplayPipValue        = false;
extern bool       DisplayDragons         = true;
extern string     DragonTimeFrames       = "H1, M15, M1";
extern bool       DisplayRecentBarHighLowAlertBox = true;
extern int        RecentBarHighLowNumCandles      = 5;
extern bool       DisplayCcyName         = false;
extern bool       DisplayTF              = true;

extern string     ________               = "";
extern string     PVA_Settings           = "Price Volume Analysis Settings:"; 
extern int        PVA_Rising_Period      = 10;
extern double     PVA_Rising_FactorMin   = 1.5;
extern double     PVA_Rising_FactorMed   = 2.0;
extern double     PVA_Rising_FactorMax   = 3.0;

extern string     ____________               = "";
extern string     Fast_Volume_Settings       = "Fast Volume Settings:"; 
extern bool       DisplayFastVolumeOnLastBar = true;
extern bool       DisplayFastVolumeAlertBox  = false;
extern int        FastVolumeStartPercent     = 10;
extern string     FastVolumeMaxTimeFrame     = "H1";

extern string ___________                     = "";
extern string Levels_Settings                 = "Levels Settings:"; 
extern bool   Display_Levels                  = true;
extern bool   Display_Level_Numbers           = true;
extern bool   Display_Half_Lines              = true;
extern bool   Display_Quarter_Lines           = true;
extern string Display_Levels_TimeFrames       = "";
extern int    Level_Line_Length_NumCandles    = 0;
extern bool   Level_Bid_Line_On               = true;
extern color  Level_Bid_Color                 = OrangeRed;//Indigo;   
extern int    Level_Bid_Style_01234           = 0;
extern int    Level_Bid_Width_12345           = 3;
extern bool   Level_Ask_M1_Line_On            = true;
extern color  Level_Ask_Color                 = Red;   
extern int    Level_Ask_Style_01234           = 0;
extern int    Level_Ask_Width_12345           = 1;
extern color  Level_Whole_Color               = Blue; //C'235,235,252';   
extern int    Level_Whole_Style_01234         = 0;
extern int    Level_Whole_Width_12345         = 1;
extern color  Level_Half_Color                = Green; //C'210,251,210'; 
extern int    Level_Half_Style_01234          = 0;
extern int    Level_Half_Width_12345          = 1;
extern color  Level_Quarter_Color             = Purple; //C'239,235,222';  
extern int    Level_Quarter_Style_01234       = 0;
extern int    Level_Quarter_Width_12345       = 1;
extern int    Level_Numbers_Text_Size         = 8;

extern string     __________             = "";
extern string     Style_Settings         = "Style Settings:"; 
extern int        CandleBodyWidth        = 3;
extern int        CandleShadowWidth      = 1;
extern int        SpacingBetweenCandles  = 1;
extern color      CandleUpMinColor       = Lime;
extern color      CandleDownMinColor     = Tomato;
extern color      CandleUpMedColor       = C'000,166,100';  //Green;
extern color      CandleDownMedColor     = C'208,017,074';  //Magenta;
extern color      CandleMaxiumColor      = Blue;
extern color      CandleShadowColor      = Black;
extern color      TextColor              = Black;
extern string     TextFont               = "Arial"; //"Verdana";
extern int        TextSize               = 14;
extern int        DisplayTextSize        = 12;
extern int        SymbolTextSize         = 28;
extern color      BackgroundColor        = White;
extern color      DragonInsideColor          = LightGray;
extern color      DragonTextInsideAboveColor = ForestGreen;
extern color      DragonTextInsideBelowColor = Red;
extern color      DragonAboveColor           = Lime;
extern color      DragonBelowColor           = Tomato;
extern color      DragonTextColor            = Black;
extern color      DragonHighAboveColor       = DarkGreen;
extern color      DragonHighBelowColor       = FireBrick;
extern color      DragonTextHighColor        = White;
extern color      FastVolumeAlertColor       = Yellow;
extern color      RecentBarHighAlertColor    = Lime;
extern color      RecentBarLowAlertColor     = Tomato;

double av=0;

//---- buffers ------------------------------------------------------+
static double UpBodyBuffer[];
static double DnBodyBuffer[];
static double EqBodyBuffer[];
static double BgBodyBuffer[];
static double UpShadowBuffer[];
static double DnShadowBuffer[];
static double EqShadowBuffer[];
static double BgShadowBuffer[];

string   ccy, sym, CP[30], ccyp, IndiName, DisplayIndiName, PrefixIndiName;
int      IndiNumber, HHshift, LLshift, dig, tf, tmf, ccCP, ccTF, ccNC, ccHS, DTF[9], TF[9], NC[9], HS[9], IC[30];
double   spr, pnt, tickval, bidp, askp, Lswap, Sswap, HH, LL, O, H, L, C;
datetime prev_time, lastick;
double   HAhigh[],HAlow[],HAopen[],HAclose[],HAvolume[]; //,HAavgVolume[];
int      Wnum=-1;
double   Old_Price=0;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()  {

  CheckPresets();
  PrefixIndiName="Recent Candles ";
  
  if (Symbol() == MultipleIndicatorsOnChart)
  {
      CurrencyPairs = MultipleCurrencyPairs;
      
      if(!GlobalVariableCheck("RecentCandlesSem"))
        GlobalVariableSet( "RecentCandlesSem", 0);
  
      Sleep(500);
      while(!IsStopped()) {
         if(GlobalVariableSetOnCondition("RecentCandlesSem",1,0)==true)  break;
         Sleep(500);
      }

      int windowNum = WindowHandle( Symbol(), 0);
      string varName= "RecentCandles_"+windowNum;
  
      if(!GlobalVariableCheck(varName)) {
        GlobalVariableSet( varName, 1);
      } else {
        GlobalVariableSet( varName, GlobalVariableGet(varName)+1);
      }

      IndiNumber = GlobalVariableGet(varName);
      GlobalVariableSet( "RecentCandlesSem", 0);
      DisplayIndiName = PrefixIndiName + IndiNumber;
      
      NumCandles=MultipleIndicatorsNumCandles;
  }
  else {
    if (MultipleIndicatorsOnChart == "")
      DisplayIndiName = PrefixIndiName + CurrencyPairs;
    else
      DisplayIndiName = PrefixIndiName + Symbol();
  }

  IndicatorShortName(DisplayIndiName);
  IndiName=DisplayIndiName;

  if (RefreshEveryXMins > 240)                             RefreshEveryXMins = 240;
  if (RefreshEveryXMins > 60 && RefreshEveryXMins < 240)   RefreshEveryXMins = 60;
  if (RefreshEveryXMins > 30 && RefreshEveryXMins < 60)    RefreshEveryXMins = 30;
  if (RefreshEveryXMins > 15 && RefreshEveryXMins < 30)    RefreshEveryXMins = 15;
  if (RefreshEveryXMins > 5  && RefreshEveryXMins < 15)    RefreshEveryXMins = 5;
  if (RefreshEveryXMins > 1  && RefreshEveryXMins < 5)     RefreshEveryXMins = 1;

  sym     = Symbol();
  ccy     = Symbol();
  if (CurrencyPairs > "")  ccy = CurrencyPairs;
  tmf     = Period();
  bidp    = MarketInfo(ccy,MODE_BID);
  askp    = MarketInfo(ccy,MODE_ASK);
  pnt     = MarketInfo(ccy,MODE_POINT);
  dig     = MarketInfo(ccy,MODE_DIGITS);
  spr     = MarketInfo(ccy,MODE_SPREAD);
  tickval = MarketInfo(ccy,MODE_TICKVALUE);
  if (dig == 3 || dig == 5) {
    pnt     *= 10;
    spr     /= 10;
    tickval *= 10;
  }  

  prev_time = -9999;

  //---- set a accuracy of values of the indicator -----------------+
  IndicatorDigits(dig);
  //---- set a style for line --------------------------------------+
    SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleUpMinColor);
    SetIndexStyle(1,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleDownMinColor);
    SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleMaxiumColor);
    SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleUpMedColor);
    SetIndexStyle(4,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleDownMedColor);
    SetIndexStyle(5,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,CandleShadowColor);
    SetIndexStyle(6,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,BackgroundColor);
    SetIndexStyle(7,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,BackgroundColor);
  //---- set a arrays for line -------------------------------------+
  
  if (HeikinAshiCandles)
  {
    RisingVolumeBars = false;
    PVA_Rising_Period = 45;
  }
  
  if (RisingVolumeBars)
  {
    SetIndexBuffer(0,UpBodyBuffer);
    SetIndexBuffer(1,DnBodyBuffer);
    SetIndexBuffer(2,EqBodyBuffer);
    SetIndexBuffer(3,UpShadowBuffer);
    SetIndexBuffer(4,DnShadowBuffer);
    SetIndexBuffer(5,EqShadowBuffer);
    SetIndexBuffer(6,BgBodyBuffer);
    SetIndexBuffer(7,BgShadowBuffer);
  } else {
    SetIndexBuffer(0,UpShadowBuffer);
    SetIndexBuffer(1,EqShadowBuffer);
    SetIndexBuffer(2,UpBodyBuffer);
    SetIndexBuffer(3,DnBodyBuffer);
    SetIndexBuffer(4,EqBodyBuffer);
    SetIndexBuffer(5,BgBodyBuffer);
    SetIndexBuffer(6,DnShadowBuffer);
    SetIndexBuffer(7,BgShadowBuffer);
  }
  
  del_obj();
  plot_obj();    
  
  return(0);
}

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()  {
  del_obj();
  return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start() {   

   if (RefreshEveryXMins == 0) {
      del_obj();
      plot_obj();    
   }
   else {
     if(prev_time != iTime(sym,RefreshEveryXMins,0))  {
       del_obj();
       plot_obj();
       prev_time = iTime(sym,RefreshEveryXMins,0);
     } 
   }      
  return(0);
}

//+------------------------------------------------------------------+
//| del_obj                                                          |
//+------------------------------------------------------------------+
void del_obj()
{
  int k=0;
  string name=PrefixIndiName;
  if (Symbol() == MultipleIndicatorsOnChart)
   name=IndiName;

  while (k<ObjectsTotal())   {
    string objname = ObjectName(k);
    if (StringSubstr(objname,0,StringLen(name)) == name)  
      ObjectDelete(objname);
    else
      k++;
  }    
  return;
}

string getNextSymbol(int c)
{
  string ccyp;
  
  if (Symbol() != MultipleIndicatorsOnChart)
  {  
    if (MultipleIndicatorsOnChart == "") { 
      ccyp = CP[c];
    } else
    if (c != 0) {  
      ccyp = "";
    } else {  
      ccyp = Symbol();
    }  
  }
  else {  
    if (c != 0) {  
      ccyp = "";
    } else {  
      ccyp = CP[Wnum-1];
    }  
  }
  return (ccyp);
}

//+------------------------------------------------------------------+
void plot_obj()   {
//+------------------------------------------------------------------+
string ObjNameA;
string ObjNameI;

  CheckPresets();

  if (RisingVolumeBars)
  {
    SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleUpMinColor);
    SetIndexStyle(1,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleDownMinColor);
    SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleMaxiumColor);
    SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleUpMedColor);
    SetIndexStyle(4,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleDownMedColor);
    SetIndexStyle(5,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,CandleShadowColor);
    SetIndexStyle(6,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,BackgroundColor);
    SetIndexStyle(7,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,BackgroundColor);
  } else {
    SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,CandleShadowColor);
    SetIndexStyle(1,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,CandleShadowColor);
    SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleUpMinColor);
    SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleDownMinColor);
    SetIndexStyle(4,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,CandleShadowColor);
    SetIndexStyle(5,DRAW_HISTOGRAM,STYLE_SOLID,CandleBodyWidth,BackgroundColor);
    SetIndexStyle(6,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,CandleShadowColor);
    SetIndexStyle(7,DRAW_HISTOGRAM,STYLE_SOLID,CandleShadowWidth,BackgroundColor);
  }

  for (int i=0; i<Bars; i++)   {
    UpBodyBuffer[i]   = EMPTY_VALUE;
    DnBodyBuffer[i]   = EMPTY_VALUE;
    EqBodyBuffer[i]   = EMPTY_VALUE;
    BgBodyBuffer[i]   = EMPTY_VALUE;
    UpShadowBuffer[i] = EMPTY_VALUE;
    DnShadowBuffer[i] = EMPTY_VALUE;
    EqShadowBuffer[i] = EMPTY_VALUE;
    BgShadowBuffer[i] = EMPTY_VALUE;
  }

  //if (Wnum < 0)
  //{
      // can change if other indicators are removed
      Wnum = WindowFind(DisplayIndiName);
      if (Wnum < 0)   return;

      if (Symbol() == MultipleIndicatorsOnChart)
      {
         DisplayIndiName = PrefixIndiName + CP[Wnum-1];
         IndicatorShortName(DisplayIndiName);
         IndiName=DisplayIndiName;
         
         while(!IsStopped()) {
            if(GlobalVariableSetOnCondition("RecentCandlesSem",1,0)==true)  break;
            Sleep(500);
         }
         int windowNum = WindowHandle( Symbol(), 0);
         string varName= "RecentCandles_"+windowNum;
         double value=GlobalVariableGet(varName)-1;
         if (value > 0) {
           GlobalVariableSet( varName, value);
         } else {
           GlobalVariableDel( varName);
         }
         GlobalVariableSet( "RecentCandlesSem", 0);
      }
  //}
  
  int    j = 0;
  int rightChart = 0;
  for (int c=29; c>=0; c--)   {  
    ccyp = getNextSymbol(c);
    if (ccyp == "")   continue;
    if (rightChart==0)rightChart=1;
    else rightChart=2;
    Lswap   = MarketInfo(ccyp,MODE_SWAPLONG);
    Sswap   = MarketInfo(ccyp,MODE_SWAPSHORT);
    lastick = MarketInfo(ccyp,MODE_TIME);
    bidp    = MarketInfo(ccyp,MODE_BID);
    askp    = MarketInfo(ccyp,MODE_ASK);
    spr     = MarketInfo(ccyp,MODE_SPREAD);
    pnt     = MarketInfo(ccyp,MODE_POINT);
    dig     = MarketInfo(ccyp,MODE_DIGITS);
    tickval = MarketInfo(ccyp,MODE_TICKVALUE);
    if (dig == 3 || dig == 5) {
      spr     /= 10;
      tickval *= 10;
    }  

    string tft;
    for(int z=8; z>=0; z--) {
      tf = TF[z];
      if (tf == 0)    continue;
      tft = TFToStr(tf);
      string ccyt = ccyp;
      if (IC[c] == 1)   ccyt = "(" + StringSubstr(ccyp,3,3) + StringSubstr(ccyp,0,3) + ")";
      string tct = ccyt + "," + tft;

      int minval = HS[z];
      int maxval = MathMin(iBars(ccyp,tf)-2,NC[z]+HS[z]+PVA_Rising_Period+5);
      if (maxval != ArraySize(HAclose)) {
         ArrayResize(HAclose,maxval);
         ArrayResize(HAopen,maxval);
         ArrayResize(HAhigh,maxval);
         ArrayResize(HAlow,maxval);
         ArrayResize(HAvolume,maxval);
      }
      for (int q=maxval; q>=minval; q--)  {
        if (q == maxval || !HeikinAshiCandles)   {
          HAopen[q]  = iOpen(ccyp,tf,q);
          HAhigh[q]  = iHigh(ccyp,tf,q);
          HAlow[q]   = iLow(ccyp,tf,q);
          HAclose[q] = iClose(ccyp,tf,q);
        } else {
          HAopen[q]  = (HAopen[q+1]+HAclose[q+1])/2;
          HAhigh[q]  = MathMax(HAopen[q],iHigh(ccyp,tf,q));
          HAlow[q]   = MathMin(HAopen[q],iLow(ccyp,tf,q));
          HAclose[q] = (iOpen(ccyp,tf,q)+iHigh(ccyp,tf,q)+iLow(ccyp,tf,q)+iClose(ccyp,tf,q))/4;
        } 
        HAvolume[q]= iVolume(ccyp,tf,q);
      }

      HH = 0;             // highest high across last NumCandles candles, used for scaling
      LL = 999999;        // lowest low across last NumCandles candles, used for scaling
      HHshift=0;
      LLshift=0;
      for(i=HS[z]; i<=NC[z]+HS[z]; i++)  {
        if (IC[c] == 1)  {
          HH = MathMax(HH,DivZero(1,HAlow[i]));
          if (HH == DivZero(1,HAlow[i])) HHshift=i;
          LL = MathMin(LL,DivZero(1,HAhigh[i]));
          if (LL == DivZero(1,HAhigh[i])) LLshift=i;
        } else  {
          HH = MathMax(HH,HAhigh[i]);
          if (HH == HAhigh[i]) HHshift=i;
          LL = MathMin(LL,HAlow[i]);
          if (LL == HAlow[i]) LLshift=i;
        }
      }

      bool FastVolumeAlert=false;
      for(i=HS[z]; i<=NC[z]+HS[z]; i++)  {
  //      Print ("***" + tct + "  " + i + "  " + j);
        if (IC[c] == 1)  {
          O = DivZero(1,HAopen[i]);     // candle open
          H = DivZero(1,HAlow[i]);      // candle high
          L = DivZero(1,HAhigh[i]);     // candle low
          C = DivZero(1,HAclose[i]);    // candle close
        } else  {
          O = HAopen[i];     // candle open
          H = HAhigh[i];     // candle high
          L = HAlow[i];      // candle low
          C = HAclose[i];    // candle close
        }
        double open  = DivZero(100*(O-LL),(HH-LL));
        double high  = DivZero(100*(H-LL),(HH-LL));
        double low   = DivZero(100*(L-LL),(HH-LL));
        double close = DivZero(100*(C-LL),(HH-LL));
        double volume = HAvolume[i];

        if (RisingVolumeBars) {
          UpBodyBuffer[j] = EMPTY_VALUE;
          DnBodyBuffer[j] = EMPTY_VALUE;
          EqBodyBuffer[j] = EMPTY_VALUE;
          BgBodyBuffer[j] = EMPTY_VALUE;
          UpShadowBuffer[j] = EMPTY_VALUE;
          DnShadowBuffer[j] = EMPTY_VALUE;
          EqShadowBuffer[j] = high;
          BgShadowBuffer[j] = low;
        } else
        {
         if (open < close)
         {
           UpBodyBuffer[j] = close;
           DnBodyBuffer[j] = EMPTY_VALUE;
           EqBodyBuffer[j] = EMPTY_VALUE;
           BgBodyBuffer[j] = open;
           UpShadowBuffer[j] = high;
           DnShadowBuffer[j] = open+1;
           EqShadowBuffer[j] = EMPTY_VALUE;
           BgShadowBuffer[j] = low;
         }
         else
         {
           if (open > close)
           {
              UpBodyBuffer[j] = EMPTY_VALUE;
              DnBodyBuffer[j] = open;
              EqBodyBuffer[j] = EMPTY_VALUE;
              BgBodyBuffer[j] = close;
              UpShadowBuffer[j] = high;
              DnShadowBuffer[j] = close+1;
              EqShadowBuffer[j] = EMPTY_VALUE;
              BgShadowBuffer[j] = low;
           }
           else
           {
              UpBodyBuffer[j] = EMPTY_VALUE;
              DnBodyBuffer[j] = EMPTY_VALUE;
              EqBodyBuffer[j] = open;
              BgBodyBuffer[j] = open - 1;
              UpShadowBuffer[j] = high;
              DnShadowBuffer[j] = EMPTY_VALUE;
              if (high == low)
              {
                 EqShadowBuffer[j] = EMPTY_VALUE;
                 BgShadowBuffer[j] = EMPTY_VALUE;
              }
              else
              {
                 EqShadowBuffer[j] = high;
                 BgShadowBuffer[j] = low;
              }
           }
         }
        }
        
         //Rising Volume
        if (RisingVolumeBars)
        {
          av=0;
          for (int m = i+1; m <= (i+PVA_Rising_Period); m++) {av = av + HAvolume[m];}
          av = av / PVA_Rising_Period;
          double avOrg = av;
          if (DisplayFastVolumeOnLastBar && (i==0)) {
             double secondsUntilNextCandle = (iTime(ccyp,tf,4)-iTime(ccyp,tf,5))-MathMod(TimeCurrent(),iTime(ccyp,tf,4)-iTime(ccyp,tf,5));
             double timeUntilNextCandlePercent = secondsUntilNextCandle/(tf*60);
             if ((tf <= StrToTF(FastVolumeMaxTimeFrame)) && 
                 (timeUntilNextCandlePercent < (1-(FastVolumeStartPercent/100)))) { // > 5% time of current bar 
               av = av * (1-timeUntilNextCandlePercent);
             }
             //Print("SYM: "+ccyp+" Time: "+tft+" secondsUntilNextCandle: "+secondsUntilNextCandle+" timeUntilNextCandlePercent: "+timeUntilNextCandlePercent);
          }
          
          if(volume >= av * PVA_Rising_FactorMax)
          {
            //Print("SYM: "+ccyp+" Time: "+tft+" Volume: "+HAvolume[j]+" Volume2: "+volume+" av: "+av+" high: "+HAhigh[j]+" high2: "+high);
            EqBodyBuffer[j] = high;
            BgBodyBuffer[j] = low;
            EqShadowBuffer[j] = EMPTY_VALUE;
            if (DisplayFastVolumeAlertBox && avOrg != av) {
              FastVolumeAlert=true;
            }
          } else
          if(volume >= av * PVA_Rising_FactorMed)
          {
            //Print("SYM: "+ccyp+" Time: "+tft+" Volume: "+HAvolume[j]+" Volume2: "+volume+" av: "+av+" high: "+HAhigh[j]+" high2: "+high);
            if(close > open) {
              UpShadowBuffer[j] = high;
              BgBodyBuffer[j] = low;
            }
            if(close <= open) {
              DnShadowBuffer[j] = high;
              BgBodyBuffer[j] = low;
            }
            EqShadowBuffer[j] = EMPTY_VALUE;
            if (DisplayFastVolumeAlertBox && avOrg != av) {
              FastVolumeAlert=true;
            }
          } else
          if(volume >= av * PVA_Rising_FactorMin)
          {
            //Print("SYM: "+ccyp+" Time: "+tft+" Volume: "+HAvolume[j]+" Volume2: "+volume+" av: "+av+" high: "+HAhigh[j]+" high2: "+high);
            if(close > open) {
              UpBodyBuffer[j] = high;
              BgBodyBuffer[j] = low;
            }
            if(close <= open) {
              DnBodyBuffer[j] = high;
              BgBodyBuffer[j] = low;
            }
            EqShadowBuffer[j] = EMPTY_VALUE;
            if (DisplayFastVolumeAlertBox && avOrg != av) {
              FastVolumeAlert=true;
            }
          }
        }

        j += SpacingBetweenCandles;
      }

  // Levels
      if (Level_Line_Length_NumCandles>NC[z]) Level_Line_Length_NumCandles=NC[z];
      if (Level_Line_Length_NumCandles<1) Level_Line_Length_NumCandles=NC[z];
      Levels(c, z, bidp, askp, pnt, iTime(sym,tmf,j-1), iTime(sym,tmf,j-SpacingBetweenCandles*(NC[z]+1)+(NC[z]-Level_Line_Length_NumCandles)), iTime(sym,tmf,j-SpacingBetweenCandles*(NC[z]+1)));

  // Alert Box
      if (DisplayRecentBarHighLowAlertBox &&
          ((LLshift < RecentBarHighLowNumCandles) || 
           (HHshift < RecentBarHighLowNumCandles))) {
         ObjNameA = IndiName + "-" + tct + "-alert";
         int boxStart=-5;
         if (DisplayFastVolumeAlertBox&&FastVolumeAlert) boxStart=-15;
         ObjectCreate(ObjNameA,OBJ_RECTANGLE,Wnum,iTime(sym,tmf,j),boxStart,iTime(sym,tmf,j-SpacingBetweenCandles*(NC[z]+1)),-30);
         if (LLshift < RecentBarHighLowNumCandles && HHshift > LLshift)
           ObjectSet(ObjNameA,OBJPROP_COLOR,RecentBarLowAlertColor);
         else
           ObjectSet(ObjNameA,OBJPROP_COLOR,RecentBarHighAlertColor);
         ObjectSet(ObjNameA,OBJPROP_BACK,true);
      }
      if (DisplayFastVolumeAlertBox) {
        ObjNameA = IndiName + "-" + tct + "-volalert";
        if (FastVolumeAlert) {
          FastVolumeAlert=false;
          int boxEnd=-30;
          if (DisplayRecentBarHighLowAlertBox &&
          ((LLshift < RecentBarHighLowNumCandles) || 
           (HHshift < RecentBarHighLowNumCandles))) boxEnd=-15;
          ObjectCreate(ObjNameA,OBJ_RECTANGLE,Wnum,iTime(sym,tmf,j),-5,iTime(sym,tmf,j-SpacingBetweenCandles*(NC[z]+1)),boxEnd);
          ObjectSet(ObjNameA,OBJPROP_COLOR,FastVolumeAlertColor);
          ObjectSet(ObjNameA,OBJPROP_BACK,true);
        } else {
          ObjectDelete(ObjNameA);
          //ObjectSet(ObjNameA,OBJPROP_COLOR,White);
        }
      }
      
  // separator line (between time frames)
      string ObjNameS = IndiName + "-" + tct + "-s";
      ObjectCreate(ObjNameS,OBJ_TREND,Wnum,iTime(sym,tmf,j),120,iTime(sym,tmf,j),-35);
      ObjectSet(ObjNameS,OBJPROP_COLOR,TextColor);
      ObjectSet(ObjNameS,OBJPROP_WIDTH,2);
      ObjectSet(ObjNameS,OBJPROP_RAY,false);

  // separator line (between indicators)
      if (MultipleIndicatorsOnChart == Symbol()) {
         string ObjNameIndi = IndiName + "-" + tct + "-indi";
         ObjectCreate(ObjNameIndi,OBJ_TREND,Wnum,iTime(sym,tmf,j),-32,iTime(sym,tmf,j-SpacingBetweenCandles*(NC[z]+1)),-32);
         ObjectSet(ObjNameIndi,OBJPROP_COLOR,TextColor);
         ObjectSet(ObjNameIndi,OBJPROP_WIDTH,3);
         ObjectSet(ObjNameIndi,OBJPROP_RAY,false);
      }
      
  // text, e.g. "USDJPY,H1"
      string ObjNameT = IndiName + "-" + tct + "-t";
      string dispstr = "";
      ObjectCreate(ObjNameT,OBJ_TEXT,Wnum,iTime(sym,tmf,j-SpacingBetweenCandles*(NC[z]+2)/2),-10);
      ObjectSetText(ObjNameT, " ", TextSize, TextFont, TextColor);
      if (DisplayCcyName && DisplayTF)  dispstr = tct;      else
      if (DisplayCcyName             )  dispstr = ccyt;     else
      if (DisplayTF                  )  dispstr = tft;
      if (HeikinAshiCandles && DisplayCcyName) dispstr = dispstr + "-HA";
      ObjectSetText(ObjNameT, dispstr, TextSize, TextFont, TextColor);

      j += SpacingBetweenCandles;
    }

    if (DisplayInfo && 
        (((MultipleIndicatorsOnChart == Symbol()) && (rightChart==1)) ||
         ((MultipleIndicatorsOnChart != Symbol()) && (Symbol() == ccyp))))
    {
      int xOffset=5;
      int yOffset=0;
      string info;
      
      // Symbol
      color symColor=TextColor;
      if (bidp > iHigh(ccyp,PERIOD_M1,1)) {
         symColor=CandleUpMinColor;
      } else
      if (bidp < iLow(ccyp,PERIOD_M1,1)) {
         symColor=CandleDownMinColor;
      }
      ObjNameI = IndiName + "-" + ccyp + "-i0";
      Write(ObjNameI, 1, xOffset, yOffset, ccyt, SymbolTextSize, TextFont, TextColor);      
      if (symColor!=TextColor) {
         ObjNameA = IndiName + "-" + ccyp + "-i0a";
         WriteColorBar(ObjNameA, 1, xOffset-2, yOffset-2, "лллллллл", SymbolTextSize, symColor);
      }
      yOffset+=40;
      
      if (IC[c] == 0)
        info = DoubleToStr(bidp,dig) + " / " + DoubleToStr(askp,dig);
      else
        info = DoubleToStr(DivZero(1,(bidp+askp)/2),dig);
      ObjNameI = IndiName + "-" + ccyp + "-i1";
      Write(ObjNameI, 1, xOffset, yOffset, info, TextSize, TextFont, TextColor);
      yOffset+=25;

      if (DisplayLastTick && MultipleIndicatorsOnChart == Symbol()) {
         int diff=TimeLocal()-lastick;
         if (diff<0) diff=0;
         info = "  Last Tick:  " + diff + " s";
         ObjNameI = IndiName + "-" + ccyp + "-i2";
         Write(ObjNameI, 1, xOffset, yOffset, info, DisplayTextSize, TextFont, TextColor);
         symColor=TextColor;
         if (diff >= 10) {
            symColor=Orange;
         } else
         if (diff >= 5) {
            symColor=Yellow;
         }
         if (symColor!=TextColor) {
            ObjNameA = IndiName + "-" + ccyp + "-i2a";
            WriteColorBar(ObjNameA, 1, xOffset-2, yOffset-4, "ллл", DisplayTextSize+2, symColor);         
         }
         yOffset+=20;
      }
      
      if (IC[c] == 0)   {
        if (DisplaySwap)
        {
            info = "  Swap = " + DoubleToStr(Lswap,2) + " / " + DoubleToStr(Sswap,2);
            ObjNameI = IndiName + "-" + ccyp + "-i3";
            Write(ObjNameI, 1, xOffset, yOffset, info, DisplayTextSize, TextFont, TextColor);
            yOffset+=20;
        }

        int    k         = 0;
        double DailyMove = 0;
        double range =     0;
        if (DisplaySpread || DisplayRange)
        {
            for (i=1; i<=10; i++)  {
              if (TimeDayOfWeek(iTime(ccyp,PERIOD_D1,i)) > 0)  {
                k++;
                DailyMove += (iHigh(ccyp,PERIOD_D1,i) - iLow(ccyp,PERIOD_D1,i)) / pnt;
            } }  
            DailyMove = DivZero(DailyMove,k);   
            range = (iHigh(ccyp,PERIOD_D1,0) - iLow(ccyp,PERIOD_D1,0)) / pnt;
            if (dig == 3 || dig == 5) {
              DailyMove /= 10;
              range /= 10;
            }
        }
        if (DisplaySpread)
        {
            info = "  Spread: " + DoubleToStr(spr,1) + "  (" + DoubleToStr(spr * 100 / DailyMove, 2) + "%)";
            ObjNameI = IndiName + "-" + ccyp + "-i4";
            Write(ObjNameI, 1, xOffset, yOffset, info, DisplayTextSize, TextFont, TextColor);
            yOffset+=20;
        }
        if (DisplayRange)
        {
            info = "  Range: " + DoubleToStr(range,1) + "  (" + DoubleToStr(DailyMove, 1) + ")";
            ObjNameI = IndiName + "-" + ccyp + "-i5";
            Write(ObjNameI, 1, xOffset, yOffset, info, DisplayTextSize, TextFont, TextColor);
            yOffset+=20;
        }
        if (DisplayPipValue)
        {
            info = "  Pip Value = " + DoubleToStr(tickval,3);
            ObjNameI = IndiName + "-" + ccyp + "-i6";
            Write(ObjNameI, 1, xOffset, yOffset, info, DisplayTextSize, TextFont, TextColor);
            yOffset+=20;
        }
      }  
      
      if (DisplayDragons)
      for(int o=0; o<=8; o++) {
        int dtf = DTF[o];
        if (dtf == 0)    continue;
        string dtft = TFToStr(dtf);
      
        Dragon(dtf, dtft, xOffset, yOffset);
        yOffset+=20;
      }
      
      //j += 20*SpacingBetweenCandles;
    }
  }  
  return;
} 

void Dragon(int timeframe, string timestr,int xOffset, int yOffset) 
{
  double dragonDistance=0;
  double dragonHigh=iMA(ccyp,timeframe,34,0,MODE_EMA,PRICE_HIGH,1);
  double dragonLow=iMA(ccyp,timeframe,34,0,MODE_EMA,PRICE_LOW,1);
  double dragonRange=dragonHigh-dragonLow;
  double dragonPercent=0;
  color symColor=DragonInsideColor;
  color txtColor=DragonTextColor;
  if (bidp > dragonHigh) {
     symColor=DragonAboveColor;
     dragonDistance=bidp - dragonHigh;
  } else
  if (bidp < dragonLow) {
     symColor=DragonBelowColor;
     dragonDistance=dragonLow - bidp;
  } else {
     dragonDistance=MathMin(dragonHigh - bidp, bidp - dragonLow);
     if (dragonDistance == (dragonHigh - bidp)) {
       txtColor=DragonHighAboveColor;
     } else {
       txtColor=DragonTextInsideBelowColor;
     }
  }
  dragonPercent=(dragonDistance*100)/dragonRange;
  if (dragonPercent > 100 && bidp > dragonHigh) {
     symColor=DragonTextInsideAboveColor;
     txtColor=DragonTextHighColor;
  } else
  if (dragonPercent > 100 && bidp < dragonLow) {
     symColor=DragonHighBelowColor;
     txtColor=DragonTextHighColor;
  }  
  string percentStr=DoubleToStr(dragonPercent,0);
  string info = percentStr + "%";
  string ObjNameI = IndiName + "-" + ccyp + "-i7" + timestr;
  Write(ObjNameI, 1, xOffset, yOffset, info, DisplayTextSize, TextFont, txtColor);
  info = "  Dragon " + timestr + ":";
  ObjNameI = IndiName + "-" + ccyp + "-i7a" + timestr;
  Write(ObjNameI, 1, xOffset+50, yOffset, info, DisplayTextSize, TextFont, TextColor);
  ObjNameI = IndiName + "-" + ccyp + "-i7b" + timestr;
  WriteColorBar(ObjNameI, 1, xOffset-2, yOffset-4, "ллллл", DisplayTextSize+2, symColor);
}

// Levels-------------------------------------------------------------------------------------
int Levels(int c, int z, double bidp, double askp, double pnt, datetime endTime, datetime startTime, datetime startTimeBidAsk)
{
   double     Poin=0;
   double     linelevel, BL, v2;
   int        digit;
   int        u1=00, u2=50, u3=25, u4=75;        
   int        v1, ssp, ssp1;
   string     line;
   int        Full_Lines_No=0;
   int        Half_Lines_No=0;
   int        Quarter_Lines_No=0;
   bool       Show_Full_Ten_Lines=false;
   bool       Show_Full_Lines=true;
   bool       Show_Half_Lines=Display_Half_Lines;
   bool       Show_Quarter_Lines=Display_Quarter_Lines;
   
   //Panel and Levels - Check for unconventional Point digits number. 
   //Used for display of market price and Levels.
   if (pnt == 0.00001) {Poin = 0.0001;digit=5;} //5 digits     
   else {if (pnt == 0.001) {Poin = 0.01;digit=3;} //3 digits
   else {Poin = pnt;digit=4;}} //Normal 4 digits    
   if (bidp>9999) {Poin = 0.1;digit=1;}   
   if (StringSubstr(CP[c],0,6) == "XAUUSD") {Poin = 1;digit=1;}   

   ssp1= bidp/Poin;  //bid w/o the decimal 
   v1=ssp1%100; //last two significant digits
   BL=v1; //last two significant digits of starting/reference bid line  

   if ((Display_Levels) && (Display_Levels_TimeFrames == "" || StringFindCount(Display_Levels_TimeFrames,TFToStr(TF[z])) > 0))
   {
      //calculate line levels bottom to top
      for(ssp=(LL/Poin)-20; ssp<= (HH/Poin)+20; ssp++) 
      {
         v1=ssp%100;
         if(v1==u1) {
           Full_Lines_No++;
         } else
         if(v1==u2) {
           Half_Lines_No++;
         } else
         if((v1==u3) || (v1==u4)) {
           Quarter_Lines_No++;
         } 
      }
      if ((Full_Lines_No > 2) || (Half_Lines_No > 2)) 
        Show_Half_Lines=false;
      if ((Full_Lines_No+Half_Lines_No > 2) || (Quarter_Lines_No > 2))
        Show_Quarter_Lines=false;
   
      for(ssp=(LL/Poin)-20; ssp<= (HH/Poin)+20; ssp++)
      {
         v1=ssp%100;
         linelevel = ssp*Poin;
         linelevel  = DivZero(100*(linelevel-LL),(HH-LL));
         line = IndiName + TFToStr(TF[z]) + "_Line_" + DoubleToStr(linelevel,digit);

         if((Full_Lines_No > 100) && (v1==u1)) {
           if((ssp%10000)==u1) {
             DrawLines(line, endTime, startTime, (ssp*Poin), linelevel, Level_Whole_Color, 
             Level_Whole_Style_01234, Level_Whole_Width_12345);
           }
         } else
         if((Full_Lines_No > 50) && (v1==u1)) {
           if((ssp%2000)==u1) {
             DrawLines(line, endTime, startTime, (ssp*Poin), linelevel, Level_Whole_Color, 
             Level_Whole_Style_01234, Level_Whole_Width_12345);
           }
         } else
         if((Full_Lines_No > 10) && (v1==u1)) {
           if((ssp%1000)==u1) {
             DrawLines(line, endTime, startTime, (ssp*Poin), linelevel, Level_Whole_Color, 
             Level_Whole_Style_01234, Level_Whole_Width_12345);
           }
         } else
         if((Full_Lines_No > 5) && (v1==u1 || v1==u2)) {
           if((ssp%200)==u1) {
             DrawLines(line, endTime, startTime, (ssp*Poin), linelevel, Level_Whole_Color, 
             Level_Whole_Style_01234, Level_Whole_Width_12345);
           }
         } else
         if((Show_Full_Lines) && (v1==u1)) {
           DrawLines(line, endTime, startTime, (ssp*Poin), linelevel, Level_Whole_Color, 
           Level_Whole_Style_01234, Level_Whole_Width_12345);
         } else
         if((Show_Half_Lines) && (v1==u2)) {
           v2=v1*0.001;
           DrawLines(line, endTime, startTime, v2, linelevel, Level_Half_Color, 
           Level_Half_Style_01234, Level_Half_Width_12345);
         } else
         if((Show_Quarter_Lines) && ((v1==u3) || (v1==u4))) {
           v2=v1*0.001;
           DrawLines(line, endTime, startTime, v2, linelevel, Level_Quarter_Color, 
           Level_Quarter_Style_01234, Level_Quarter_Width_12345);
         } 
      }
   }

   // Draw Bid line
   if (Level_Bid_Line_On) {
      linelevel  = DivZero(100*(bidp-LL),(HH-LL));
      line = IndiName + TFToStr(TF[z]) + "_Bid_" + DoubleToStr(linelevel,digit);
      DrawLines(line, endTime, startTimeBidAsk, -1, linelevel, Level_Bid_Color, 
        Level_Bid_Style_01234, Level_Bid_Width_12345);
        
      // Bid dot
      if (TF[z] == 1) {
         color symColor=TextColor;
         if (bidp > Old_Price) {
            symColor=CandleUpMinColor;
         } else
         if (bidp < Old_Price) {
            symColor=CandleDownMinColor;
         }
         Old_Price = bidp;
         line = IndiName + TFToStr(TF[z]) + "_BidDot_" + DoubleToStr(linelevel,digit);
         DrawLines(line, startTimeBidAsk, startTimeBidAsk, -1, linelevel, symColor, 0, 9);
      }
   }
   if (Level_Ask_M1_Line_On && (TF[z] == 1)) {
      linelevel  = DivZero(100*(askp-LL),(HH-LL));
      line = IndiName + TFToStr(TF[z]) + "_Ask_" + DoubleToStr(linelevel,digit);
      DrawLines(line, endTime, startTimeBidAsk, -1, linelevel, Level_Ask_Color, 
        Level_Ask_Style_01234, Level_Ask_Width_12345);
   }
   
}
//End Levels         

// Lines====================================================================================== 
void DrawLines(string line, datetime stoptime, datetime starttime, double v1, double level, color Color,  int linestyle, int thickness)
{
  // Horizontal Lines Placement
  int c = 1; 
  if (linestyle==0) c=thickness;
   
  // Draw lines   
  ObjectCreate(line, OBJ_TREND, Wnum, starttime, level, stoptime, level);
  ObjectSet(line, OBJPROP_STYLE, linestyle);
  ObjectSet(line, OBJPROP_COLOR, Color);
  ObjectSet(line, OBJPROP_WIDTH, c);
  ObjectSet(line, OBJPROP_RAY,false);
  
  if ((Display_Level_Numbers) && (v1 != -1)) {
   string num;
   string ObjNameT = line + "-t";
   if (v1 < 0.1) {
     num=DoubleToStr(v1*10,2);
     num=StringSubstr(num,2);
   } else 
   if (v1 < 10000) {
     num=StringSubstr(DoubleToStr(v1,2),0,4);
   } else {
     num=StringSubstr(DoubleToStr(v1,2),0,5);
   }
   ObjectCreate(ObjNameT,OBJ_TEXT,Wnum,stoptime+(tmf*180),level);
   ObjectSetText(ObjNameT, num, Level_Numbers_Text_Size, TextFont, TextColor);
  }  
}

void Write(string LBL, double side, int pos_x, int pos_y, string text, int fontsize, string fontname, color Tcolor=CLR_NONE)
{
   ObjectCreate(LBL, OBJ_LABEL, Wnum, 0, 0);
   ObjectSetText(LBL,text, fontsize, fontname, Tcolor);
   ObjectSet(LBL, OBJPROP_CORNER, side);
   ObjectSet(LBL, OBJPROP_XDISTANCE, pos_x);
   ObjectSet(LBL, OBJPROP_YDISTANCE, pos_y);
}

void WriteColorBar(string name, double side, int pos_x, int pos_y, string text, int fontsize, color theColor)
{
   ObjectCreate(name, OBJ_LABEL, Wnum,0,0,0,0);
   ObjectSet(name, OBJPROP_CORNER, side);
   ObjectSet(name, OBJPROP_XDISTANCE, pos_x);
   ObjectSet(name, OBJPROP_YDISTANCE, pos_y+5);
   ObjectSetText(name, text,fontsize,"Terminal",theColor);
   ObjectSet(name,OBJPROP_BACK,true);
}     

//+------------------------------------------------------------------+
double DivZero(double n, double d)
//+------------------------------------------------------------------+
 {
   if (d == 0) return(0);  else return(n/d);
 }  

//+------------------------------------------------------------------+
bool StrToBool(string str)
//+------------------------------------------------------------------+
{
  str = StringLower(StringSubstr(str,0,1));
  if (str == "t" || str == "y" || str == "1")   return(true);
  return(false);
}  

//+------------------------------------------------------------------+
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);
}  

//+------------------------------------------------------------------+
string StringTrim(string str)
//+------------------------------------------------------------------+
{
  string outstr = "";
  for(int i=0; i<StringLen(str); i++)  {
    if (StringSubstr(str,i,1) != " ")
      outstr = outstr + StringSubstr(str,i,1);
  }
  return(outstr);
}
//+------------------------------------------------------------------+
string TFToStr(int tf)
//+------------------------------------------------------------------+
// Converts a MT4-numeric timeframe to its descriptor string
// Usage:   string s=TFToStr(15) returns s="M15"
{
  switch (tf)  {
    case     0 :  return(0);
    case     1 :  return("M1");
    case     5 :  return("M5");
    case    15 :  return("M15");
    case    30 :  return("M30");
    case    60 :  return("H1");
    case   240 :  return("H4");
    case  1440 :  return("D1");
    case 10080 :  return("W1");
    case 43200 :  return("MN");
    default    :  return("T"+MathAbs(tf));
  }  
  return(0);
}  

//+------------------------------------------------------------------+
int StrToTF(string str)
//+------------------------------------------------------------------+
// Converts a timeframe string to its MT4-numeric value
// Usage:   int x=StrToTF("M15")   returns x=15
{
  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);
  if (StringSubstr(str,0,1) == "T") return(StrToInteger(StringSubstr(str,1))*(-1));
  return(0);
}  

//+------------------------------------------------------------------+
int CheckPresets()
//+------------------------------------------------------------------+
{
//---------------------------------------------------------------------------------------------------------------
//    Enter the file name in here
//---------------------------------------------------------------------------------------------------------------
  string FileName = "Presets---Recent Candles.TXT";
//---------------------------------------------------------------------------------------------------------------
  int handle = FileOpen(FileName, FILE_CSV|FILE_READ,';');
  if (handle > 0)  {
    while(!FileIsEnding(handle))  {
      string text  = FileReadString(handle);
      int t0 = StringFind(text,"//",0);
      if (t0 == 0)       text = "";    
      else if (t0 > 0)   text = StringSubstr(text,0,t0);
      string temp  = "";
      int    quote = 0;
      for(int i=0; i<StringLen(text); i++)   {
        string schar = StringSubstr(text,i,1);
        if (schar == "\x22")     quote = 1 - quote;  
        else if (quote == 1)    temp  = temp + schar;
        else if (schar != " " && schar != "_") temp  = temp + StringLower(schar);  
      }
      if (StringLen(temp) > 0) {
        int equal = StringFind(temp,"=",0);
        int semic = StringFind(temp,";",0);
        string pname = "";
        pname   = StringSubstr(temp,0,equal);
        string pvalue = StringSubstr(temp,equal+1,semic-equal+1);
        if (pvalue != "*")  {
//---------------------------------------------------------------------------------------------------------------
//    Parameter assignment statements go in here
//---------------------------------------------------------------------------------------------------------------
          if (pname == "currencypairs")            CurrencyPairs            = pvalue;                     else
          if (pname == "timeframes")               TimeFrames               = pvalue;                     else
          if (pname == "numcandles")               NumCandles               = pvalue;                     else
          if (pname == "historicalshift")          HistoricalShift          = pvalue;                     else
          if (pname == "candlewidth")              CandleBodyWidth          = StrToInteger(pvalue);       else
          if (pname == "candlebodywidth")          CandleBodyWidth          = StrToInteger(pvalue);       else
          if (pname == "candleshadowwidth")        CandleShadowWidth        = StrToInteger(pvalue);       else
          if (pname == "spacingbetweencandles")    SpacingBetweenCandles    = StrToInteger(pvalue);       else
          if (pname == "candleupcolor")            CandleUpMinColor         = StrToColor(pvalue);         else
          if (pname == "candledowncolor")          CandleDownMinColor       = StrToColor(pvalue);         else
          if (pname == "candleupmaxcolor")         CandleUpMedColor         = StrToColor(pvalue);         else
          if (pname == "candledownmaxcolor")       CandleDownMedColor       = StrToColor(pvalue);         else
          if (pname == "candlemaxiumcolor")        CandleMaxiumColor        = StrToColor(pvalue);         else
          if (pname == "candleshadowcolor")        CandleShadowColor        = StrToColor(pvalue);         else
          if (pname == "textcolor")                TextColor                = StrToColor(pvalue);         else
          if (pname == "textfont")                 TextFont                 = pvalue;                     else
          if (pname == "textsize")                 TextSize                 = StrToInteger(pvalue);       else
          if (pname == "backgroundcolor")          BackgroundColor          = StrToColor(pvalue);         else
          if (pname == "displayinfo")              DisplayInfo              = StrToBool(pvalue);          else
          if (pname == "displayccyname")           DisplayCcyName           = StrToBool(pvalue);          else
          if (pname == "displaytf")                DisplayTF                = StrToBool(pvalue);          else
          if (pname == "refresheveryxmins")        RefreshEveryXMins        = StrToInteger(pvalue);       else
          if (pname == "heikinashicandles")        HeikinAshiCandles        = StrToBool(pvalue);         

//---------------------------------------------------------------------------------------------------------------
        }
      }  
      temp = FileReadString(handle);
    }
    FileClose(handle);
  }  
  
  CurrencyPairs  = StringUpper(CurrencyPairs);
  if (CurrencyPairs == "")  CurrencyPairs = Symbol();
  ccy            = CurrencyPairs;
  if (StringSubstr(CurrencyPairs,StringLen(CurrencyPairs)-1,1) != ",")  CurrencyPairs = CurrencyPairs + ",";
  TimeFrames     = StringTrim(StringUpper(TimeFrames));
  if (TimeFrames == "")  TimeFrames = TFToStr(Period());
  if (StringSubstr(TimeFrames,StringLen(TimeFrames)-1,1) != ",")  TimeFrames = TimeFrames + ",";
  if (NumCandles == "")   NumCandles = "5";
  if (StringSubstr(NumCandles,StringLen(NumCandles)-1,1) != ",")  NumCandles = NumCandles + ",";
  DragonTimeFrames = StringTrim(StringUpper(DragonTimeFrames));
  if (StringSubstr(DragonTimeFrames,StringLen(DragonTimeFrames)-1,1) != ",")  DragonTimeFrames = DragonTimeFrames + ",";

  ccCP = StringFindCount(CurrencyPairs,",");
  ccTF = StringFindCount(TimeFrames,",");
  ccNC = StringFindCount(NumCandles,",");
  ccHS = StringFindCount(HistoricalShift,",");
  for (i=0; i<30; i++)
    CP[i] = "";
  ArrayInitialize(TF,0);  
  ArrayInitialize(DTF,0);  
  ArrayInitialize(NC,-1);
  ArrayInitialize(HS,0);  
  ArrayInitialize(IC,0);  
  int comma1 = -1;
  for (i=0; i<30; i++)  {
    int comma2 = StringFind(CurrencyPairs,",",comma1+1);
    temp  = StringSubstr(CurrencyPairs,comma1+1,comma2-comma1-1);
    if (StringFind(temp,"*",0) >= 0)   {
      temp = sStringReplace(temp,"*","");
      IC[i] = 1;
    }
    CP[i] = ExpandCcy(temp);
    if (StringLen(CP[i]) > 6)
      CP[i] = StringSubstr(CP[i],0,6) + StringLower(StringSubstr(CP[i],6));
    if (comma2 >= StringLen(CurrencyPairs)-1)   break;
    comma1 = comma2;
  }  
  comma1 = -1;
  for (i=0; i<9; i++)  {
    comma2 = StringFind(TimeFrames,",",comma1+1);
    temp  = StringSubstr(TimeFrames,comma1+1,comma2-comma1-1);
    TF[i] = StrToTF(temp);
    if (comma2 >= StringLen(TimeFrames)-1)   break;
    comma1 = comma2;
  }  
  comma1 = -1;
  for (i=0; i<9; i++)  {
    comma2 = StringFind(NumCandles,",",comma1+1);
    temp  = StringSubstr(NumCandles,comma1+1,comma2-comma1-1);
    NC[i] = StrToInteger(temp);
    if (comma2 >= StringLen(NumCandles)-1)   break;
    comma1 = comma2;
  }
  if (ccNC == 1)   
    for (i=0; i<ccTF; i++)  
      NC[i] = NC[0];
  comma1 = -1;
  for (i=0; i<9; i++)  {
    comma2 = StringFind(HistoricalShift,",",comma1+1);
    temp  = StringSubstr(HistoricalShift,comma1+1,comma2-comma1-1);
    HS[i] = StrToInteger(temp);
    if (comma2 >= StringLen(HistoricalShift)-1)   break;
    comma1 = comma2;
  }
  if (ccHS == 1)   
    for (i=0; i<ccHS; i++)  
      HS[i] = HS[0];

  comma1 = -1;
  for (i=0; i<9; i++)  {
    comma2 = StringFind(DragonTimeFrames,",",comma1+1);
    temp  = StringSubstr(DragonTimeFrames,comma1+1,comma2-comma1-1);
    DTF[i] = StrToTF(temp);
    if (comma2 >= StringLen(DragonTimeFrames)-1)   break;
    comma1 = comma2;
  }  

  return(0);
}

//+------------------------------------------------------------------+
string StringLower(string str)
//+------------------------------------------------------------------+
{
  string outstr = "";
  string lower  = "abcdefghijklmnopqrstuvwxyz";
  string upper  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for(int i=0; i<StringLen(str); i++)  {
    int t1 = StringFind(upper,StringSubstr(str,i,1),0);
    if (t1 >=0)  
      outstr = outstr + StringSubstr(lower,t1,1);
    else
      outstr = outstr + StringSubstr(str,i,1);
  }
  return(outstr);
}



//+------------------------------------------------------------------+
int StrToColor(string str)
//+------------------------------------------------------------------+
{
  str = StringLower(str);
  if (str == "aliceblue")              return(0xFFF8F0);
  if (str == "antiquewhite")           return(0xD7EBFA);
  if (str == "aqua")                   return(0xFFFF00);
  if (str == "aquamarine")             return(0xD4FF7F);
  if (str == "beige")                  return(0xDCF5F5);
  if (str == "bisque")                 return(0xC4E4FF);
  if (str == "black")                  return(0x000000);
  if (str == "blanchedalmond")         return(0xCDEBFF);
  if (str == "blue")                   return(0xFF0000);
  if (str == "blueviolet")             return(0xE22B8A);
  if (str == "brown")                  return(0x2A2AA5);
  if (str == "burlywood")              return(0x87B8DE);
  if (str == "cadetblue")              return(0xA09E5F);
  if (str == "chartreuse")             return(0x00FF7F);
  if (str == "chocolate")              return(0x1E69D2);
  if (str == "coral")                  return(0x507FFF);
  if (str == "cornflowerblue")         return(0xED9564);
  if (str == "cornsilk")               return(0xDCF8FF);
  if (str == "crimson")                return(0x3C14DC);
  if (str == "darkblue")               return(0x8B0000);
  if (str == "darkgoldenrod")          return(0x0B86B8);
  if (str == "darkgray")               return(0xA9A9A9);
  if (str == "darkgreen")              return(0x006400);
  if (str == "darkkhaki")              return(0x6BB7BD);
  if (str == "darkolivegreen")         return(0x2F6B55);
  if (str == "darkorange")             return(0x008CFF);
  if (str == "darkorchid")             return(0xCC3299);
  if (str == "darksalmon")             return(0x7A96E9);
  if (str == "darkseagreen")           return(0x8BBC8F);
  if (str == "darkslateblue")          return(0x8B3D48);
  if (str == "darkslategray")          return(0x4F4F2F);
  if (str == "darkturquoise")          return(0xD1CE00);
  if (str == "darkviolet")             return(0xD30094);
  if (str == "deeppink")               return(0x9314FF);
  if (str == "deepskyblue")            return(0xFFBF00);
  if (str == "dimgray")                return(0x696969);
  if (str == "dodgerblue")             return(0xFF901E);
  if (str == "firebrick")              return(0x2222B2);
  if (str == "forestgreen")            return(0x228B22);
  if (str == "gainsboro")              return(0xDCDCDC);
  if (str == "gold")                   return(0x00D7FF);
  if (str == "goldenrod")              return(0x20A5DA);
  if (str == "gray")                   return(0x808080);
  if (str == "green")                  return(0x008000);
  if (str == "greenyellow")            return(0x2FFFAD);
  if (str == "honeydew")               return(0xF0FFF0);
  if (str == "hotpink")                return(0xB469FF);
  if (str == "indianred")              return(0x5C5CCD);
  if (str == "indigo")                 return(0x82004B);
  if (str == "ivory")                  return(0xF0FFFF);
  if (str == "khaki")                  return(0x8CE6F0);
  if (str == "lavender")               return(0xFAE6E6);
  if (str == "lavenderblush")          return(0xF5F0FF);
  if (str == "lawngreen")              return(0x00FC7C);
  if (str == "lemonchiffon")           return(0xCDFAFF);
  if (str == "lightblue")              return(0xE6D8AD);
  if (str == "lightcoral")             return(0x8080F0);
  if (str == "lightcyan")              return(0xFFFFE0);
  if (str == "lightgoldenrod")         return(0xD2FAFA);
  if (str == "lightgray")              return(0xD3D3D3);
  if (str == "lightgreen")             return(0x90EE90);
  if (str == "lightpink")              return(0xC1B6FF);
  if (str == "lightsalmon")            return(0x7AA0FF);
  if (str == "lightseagreen")          return(0xAAB220);
  if (str == "lightskyblue")           return(0xFACE87);
  if (str == "lightslategray")         return(0x998877);
  if (str == "lightsteelblue")         return(0xDEC4B0);
  if (str == "lightyellow")            return(0xE0FFFF);
  if (str == "lime")                   return(0x00FF00);
  if (str == "limegreen")              return(0x32CD32);
  if (str == "linen")                  return(0xE6F0FA);
  if (str == "magenta")                return(0xFF00FF);
  if (str == "maroon")                 return(0x000080);
  if (str == "mediumaquamarine")       return(0xAACD66);
  if (str == "mediumblue")             return(0xCD0000);
  if (str == "mediumorchid")           return(0xD355BA);
  if (str == "mediumpurple")           return(0xDB7093);
  if (str == "mediumseagreen")         return(0x71B33C);
  if (str == "mediumslateblue")        return(0xEE687B);
  if (str == "mediumspringgreen")      return(0x9AFA00);
  if (str == "mediumturquoise")        return(0xCCD148);
  if (str == "mediumvioletred")        return(0x8515C7);
  if (str == "midnightblue")           return(0x701919);
  if (str == "mintcream")              return(0xFAFFF5);
  if (str == "mistyrose")              return(0xE1E4FF);
  if (str == "moccasin")               return(0xB5E4FF);
  if (str == "navajowhite")            return(0xADDEFF);
  if (str == "navy")                   return(0x800000);
  if (str == "none")                   return(C'0x00,0x00,0x00');
  if (str == "oldlace")                return(0xE6F5FD);
  if (str == "olive")                  return(0x008080);
  if (str == "olivedrab")              return(0x238E6B);
  if (str == "orange")                 return(0x00A5FF);
  if (str == "orangered")              return(0x0045FF);
  if (str == "orchid")                 return(0xD670DA);
  if (str == "palegoldenrod")          return(0xAAE8EE);
  if (str == "palegreen")              return(0x98FB98);
  if (str == "paleturquoise")          return(0xEEEEAF);
  if (str == "palevioletred")          return(0x9370DB);
  if (str == "papayawhip")             return(0xD5EFFF);
  if (str == "peachpuff")              return(0xB9DAFF);
  if (str == "peru")                   return(0x3F85CD);
  if (str == "pink")                   return(0xCBC0FF);
  if (str == "plum")                   return(0xDDA0DD);
  if (str == "powderblue")             return(0xE6E0B0);
  if (str == "purple")                 return(0x800080);
  if (str == "red")                    return(0x0000FF);
  if (str == "rosybrown")              return(0x8F8FBC);
  if (str == "royalblue")              return(0xE16941);
  if (str == "saddlebrown")            return(0x13458B);
  if (str == "salmon")                 return(0x7280FA);
  if (str == "sandybrown")             return(0x60A4F4);
  if (str == "seagreen")               return(0x578B2E);
  if (str == "seashell")               return(0xEEF5FF);
  if (str == "sienna")                 return(0x2D52A0);
  if (str == "silver")                 return(0xC0C0C0);
  if (str == "skyblue")                return(0xEBCE87);
  if (str == "slateblue")              return(0xCD5A6A);
  if (str == "slategray")              return(0x908070);
  if (str == "snow")                   return(0xFAFAFF);
  if (str == "springgreen")            return(0x7FFF00);
  if (str == "steelblue")              return(0xB48246);
  if (str == "tan")                    return(0x8CB4D2);
  if (str == "teal")                   return(0x808000);
  if (str == "thistle")                return(0xD8BFD8);
  if (str == "tomato")                 return(0x4763FF);
  if (str == "turquoise")              return(0xD0E040);
  if (str == "violet")                 return(0xEE82EE);
  if (str == "wheat")                  return(0xB3DEF5);
  if (str == "white")                  return(0xFFFFFF);
  if (str == "whitesmoke")             return(0xF5F5F5);
  if (str == "yellow")                 return(0x00FFFF);
  if (str == "yellowgreen")            return(0x32CD9A);

  int t1 = StringFind(str,",",0);
  int t2 = StringFind(str,",",t1+1);
  if (t1>0 && t2>0) {
    int red   = StrToInteger(StringSubstr(str,0,t1));
    int green = StrToInteger(StringSubstr(str,t1+1,t2-1));
    int blue  = StrToInteger(StringSubstr(str,t2+1,StringLen(str)));
    return(blue*256*256+green*256+red);
  }  

  return(0);
}  

//+------------------------------------------------------------------+
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);
}

//+------------------------------------------------------------------+
string ExpandCcy(string str)
//+------------------------------------------------------------------+
{
  str = StringTrim(StringUpper(str));
  if (StringLen(str) < 1 || StringLen(str) > 2)   return(str);
  string str2 = "";
  for (int i=0; i<StringLen(str); i++)   {
    string schar = StringSubstr(str,i,1);
    if (schar == "A")  str2 = str2 + "AUD";     else
    if (schar == "C")  str2 = str2 + "CAD";     else   
    if (schar == "E")  str2 = str2 + "EUR";     else   
    if (schar == "F")  str2 = str2 + "CHF";     else   
    if (schar == "G")  str2 = str2 + "GBP";     else   
    if (schar == "J")  str2 = str2 + "JPY";     else   
    if (schar == "N")  str2 = str2 + "NZD";     else   
    if (schar == "U")  str2 = str2 + "USD";     else   
    if (schar == "H")  str2 = str2 + "HKD";     else   
    if (schar == "S")  str2 = str2 + "SGD";     else   
    if (schar == "Z")  str2 = str2 + "ZAR";   
  }  
  return(str2);
}

//+------------------------------------------------------------------+
string sStringReplace(string str, string str1, string str2)  {
//+------------------------------------------------------------------+
// Usage: replaces every occurrence of str1 with str2 in str
  string outstr = "";
  for (int i=0; i<StringLen(str); i++)   {
    if (StringSubstr(str,i,StringLen(str1)) == str1)  {
      outstr = outstr + str2;
      i += StringLen(str1) - 1;
    }
    else
      outstr = outstr + StringSubstr(str,i,1);
  }
  return(outstr);
}









