//+------------------------------------------------------------------+
//|                                                        Oscar.mq4 |
//+------------------------------------------------------------------+

#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_level1 75
#property indicator_level2 25
#property indicator_levelcolor clrDarkSlateGray

#property indicator_buffers 2
#property indicator_color1  clrBlue
#property indicator_color2  clrRed

//---- input parameters
extern  int            iLookBack        = 8;
extern int             OscarAve         = 5;
extern int             highstop         = 3;
extern int             lowstop          = 2;
input bool             alertsOn         = true;               // Alerts on true/false?
input bool             alertsOnCurrent  = false;              // Alerts on current bar true/false?
input bool             alertsMessage    = true;               // Alerts pop-up message true/false?
input bool             alertsSound      = false;              // Alerts sound true/false?
input bool             alertsNotify     = false;              // Alerts push notification true/false?
input bool             alertsEmail      = false;              // Alerts email true/false?
input string           soundFile        = "alert2.wav";       // Alerts sound file
input bool             arrowsVisible    = false;              // Arrows visible true/false?
//input bool             arrowsOnNewest   = false;              // Arrows drawn on newest bar of higher time frame bar true/false?
input string           arrowsIdentifier = "osc Arrows1";      // Unique ID for arrows
input double           arrowsUpperGap   = 0.1;                // Upper arrow gap
input double           arrowsLowerGap   = 0.1;                // Lower arrow gap
input color            arrowsUpColor    = clrBlue;            // Up arrow color
input color            arrowsDnColor    = clrCrimson;         // Down arrow color
input int              arrowsUpCode     = 116;                // Up arrow code
input int              arrowsDnCode     = 116;                // Down arrow code
input int              arrowsUpSize     = 2;                  // Up arrow size
input int              arrowsDnSize     = 2;                  // Down arrow size


/* unused code
double  spr, pnt, tickval;
int     dig;
string  IndiName, ccy;
*/

string  IndiName;

//---- buffers
double Buffer1[];
double Buffer2[];
double Buffer3[];
double Buffer4[],trend[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+

int init()   {
   IndicatorBuffers(3);
   SetIndexBuffer(0, Buffer1);  SetIndexStyle(0, DRAW_LINE);  SetIndexLabel(1,"MA("+OscarAve+")");
   SetIndexBuffer(1, Buffer2);  SetIndexStyle(1, DRAW_LINE);
   SetIndexBuffer(2, trend);
  
/* useless code  
  int checksum = 0;
  string str = "1";
  for (int i=0; i<StringLen(str); i++)  
    checksum += i * StringGetChar(str,i);
  IndiName = "Oscar-" + checksum;
*/
  IndicatorShortName("Oscar("+iLookBack+")");
  

/* useless code
  ccy     = Symbol();
  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;
  }
*/

  return(0);
}
void OnDeinit(const int reason)
{ 
    string lookFor       = arrowsIdentifier+":";
    int    lookForLength = StringLen(lookFor);
    for (int i=ObjectsTotal()-1; i>=0; i--)
    {
       string objectName = ObjectName(i);
       if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
    }
}
//+------------------------------------------------------------------+
int start()  {
  double Y = 0;
  for (int i=Bars-(iLookBack+2); i>=0; i--)  {
    double X = Y;
    double A = 0;
    double B = 999999;
    for(int j=i; j<i+iLookBack; j++)   {
      A = MathMax(High[j],A);
      B = MathMin(Low[j],B);
    }
    double C = Close[i];  
    double rough  = (C-B)/(A-B)*100;
    Y = X/3*2 + rough/3;
    Buffer1[i] = Y;
    Buffer3[i] = (A + highstop/10000); 
    Buffer4[i] = (B- lowstop/10000);    
  }
  	i = Bars - (iLookBack+2);
	while(i>=0)
	{
		Buffer2[i] = iMAOnArray(Buffer1,0,OscarAve,0,MODE_LWMA,i);
		trend[i]   = (i<Bars-1) ? (Buffer1[i]>Buffer2[i])  ? 1 : (Buffer1[i]<Buffer2[i]) ? -1 : trend[i+1] : 0;
		
		//
      //
      //
      //
      //
      
      if (arrowsVisible)
      {
         string lookFor = arrowsIdentifier+":"+(string)Time[i]; ObjectDelete(lookFor);            
         if (i<(Bars-1) && trend[i] != trend[i+1])
         {
            if (trend[i] == 1) drawArrow(i,arrowsUpColor,arrowsUpCode,arrowsUpSize,false);
            if (trend[i] ==-1) drawArrow(i,arrowsDnColor,arrowsDnCode,arrowsDnSize, true);
         }
      }  
		i--;	
	}
	if (alertsOn)
   {
     int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
     if (trend[whichBar] != trend[whichBar+1])
     if (trend[whichBar] == 1)
           doAlert("crossing up");
     else  doAlert("crossing down");       
   }   
  return(0);
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

void doAlert(string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
      if (previousAlert != doWhat || previousTime != Time[0]) {
          previousAlert  = doWhat;
          previousTime   = Time[0];

          //
          //
          //
          //
          //

          message = timeFrameToString(_Period)+" "+_Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" Oscar "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(_Symbol+" Oscar ",message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void drawArrow(int i,color theColor,int theCode, int theSize, bool up)
{
   string name = arrowsIdentifier+":"+(string)Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
      //
      //
      //
      //
      //

      datetime atime = Time[i]; //if (arrowsOnNewest) atime += _Period*60-1;      
      ObjectCreate(name,OBJ_ARROW,0,atime,0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         ObjectSet(name,OBJPROP_WIDTH,theSize);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i] + arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i]  - arrowsLowerGap * gap);
}



//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}



