//+-------------------------------------------------------------------+
//|                                            KK_TrendLines_Ind.mq5  |
//|  Automatic trendlines on fractal pivots:                          |
//|   - rising LOWs   -> support line (UP trend)                      |
//|   - falling HIGHs -> resistance line (DOWN trend)                 |
//|   - optionally the other side of the trend (rising HIGH / falling |
//|     LOW)                                                          |
//|  A pivot is confirmed N bars later on a CLOSED bar -> the line is |
//|  active from the next bar until it breaks (close beyond the line).|
//|  Also drawn historically (within the Max bars window) with the    |
//|  pullback touches marked. No repaint.                             |
//+-------------------------------------------------------------------+
#property copyright   "KK"
#property link "http://www.Forex-Station.com/"
#property version     "1.00"
#property description "Automatic trendlines (support / resistance) + pullback touches, no repaint"
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots   0

input group "■■■■■■■■  PIVOTS  ■■■■■■■■"
input int            PivotDepth      = 5;           // Pivot (fractal) depth: N bars left and right (confirmed N bars later)
input int            AtrPeriod       = 14;          // ATR period (break / touch tolerance)
input int            InpMaxBars      = 3000;        // Number of bars drawn back in history

input group "■■■■■■■■  LINES  ■■■■■■■■"
input bool           ShowSupport     = true;        // Support: rising LOWs (UP trend)
input bool           ShowResistance  = true;        // Resistance: falling HIGHs (DOWN trend)
input bool           ShowUpperUp     = false;       // UP trend upper line: rising HIGHs (channel top)
input bool           ShowLowerDn     = false;       // DOWN trend lower line: falling LOWs (channel bottom)
input double         BreakAtr        = 0.0;         // Break: close beyond the line by this * ATR (0 = any amount)
input int            MaxLineBars     = 500;         // Max. line length (bars from the 1st point; 0 = no limit)

input group "■■■■■■■■  PULLBACK TOUCHES  ■■■■■■■■"
input bool           ShowTouches     = true;        // Mark the touches (support: BUY arrow below, resistance: SELL arrow above)
input double         TouchAtr        = 0.10;        // Touch tolerance: LOW / HIGH within this * ATR of the line
input int            ArrowTypeBuy    = 233;         // Buy arrow code
input int            ArrowTypeSell   = 234;         // Sell arrow code
input color          InpBuyColor     = clrAqua;     // Buy color
input color          InpSellColor    = clrYellow;   // Sell color

input group "■■■■■■■■  COLORS  ■■■■■■■■"
input color          SupColor        = clrLime;     // Support color
input color          ResColor        = clrRed;      // Resistance color
input color          UpperColor      = clrLime;     // UP trend upper line color (dotted)
input color          LowerColor      = clrRed;      // DOWN trend lower line color (dotted)
input int            LineWidth       = 2;           // Main line width
input bool           ShowPivots      = false;       // Mark the pivots (dot)

input group "■■■■■■■■  ALERTS  ■■■■■■■■"
input bool           InpAlert        = false;       // Alert on touch
input bool           InpPush         = false;       // Push on touch

#define PFX "KKTL_"
//--- line types: 0 = support (rising LOW), 1 = resistance (falling HIGH), 2 = UP upper (rising HIGH), 3 = DOWN lower (falling LOW)
struct TLine
  {
   bool   on;
   int    i1, i2, from;
   double p1, p2;
   bool   lastTouch;              // did the previous bar touch (one pullback = one signal)
  };
TLine    g_ln[4];
double   g_atr[];
int      g_lastLowI = -1, g_lastHighI = -1;
double   g_lastLowP = 0.0, g_lastHighP = 0.0;
int      g_total = 0, g_nLine = 0;
datetime g_lastAlert = 0;

double LineVal(const TLine &t,const int i) { return t.p1+(t.p2-t.p1)*(double)(i-t.i1)/(double)(t.i2-t.i1); }
bool   IsLowType(const int k)  { return (k==0 || k==3); }
bool   Shown(const int k)      { return (k==0) ? ShowSupport : (k==1) ? ShowResistance : (k==2) ? ShowUpperUp : ShowLowerDn; }

// line segment from the 1st point to bar e
void DrawLine(const int k,const TLine &t,const int e,const datetime &time[],const string nm)
  {
   if(!Shown(k)) return;
   if(ObjectFind(0,nm)<0) ObjectCreate(0,nm,OBJ_TREND,0,time[t.i1],t.p1,time[e],LineVal(t,e));
   else { ObjectMove(0,nm,0,time[t.i1],t.p1); ObjectMove(0,nm,1,time[e],LineVal(t,e)); }
   color c = (k==0) ? SupColor : (k==1) ? ResColor : (k==2) ? UpperColor : LowerColor;
   ObjectSetInteger(0,nm,OBJPROP_COLOR,c);
   ObjectSetInteger(0,nm,OBJPROP_STYLE,(k<2) ? STYLE_SOLID : STYLE_DOT);
   ObjectSetInteger(0,nm,OBJPROP_WIDTH,(k<2) ? LineWidth : 1);
   ObjectSetInteger(0,nm,OBJPROP_RAY_RIGHT,false);
   ObjectSetInteger(0,nm,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,nm,OBJPROP_HIDDEN,true);
   string tp = (k==0) ? "Support (rising LOW)" : (k==1) ? "Resistance (falling HIGH)" : (k==2) ? "UP trend upper (rising HIGH)" : "DOWN trend lower (falling LOW)";
   ObjectSetString(0,nm,OBJPROP_TOOLTIP,StringFormat("%s  %s -> %s",tp,TimeToString(time[t.i1],TIME_DATE|TIME_MINUTES),TimeToString(time[e],TIME_DATE|TIME_MINUTES)));
  }

void Mark(const string nm,const int code,const color clr,const datetime t,const double p,const bool below)
  {
   if(ObjectFind(0,nm)<0) ObjectCreate(0,nm,OBJ_ARROW,0,t,p);
   else ObjectMove(0,nm,0,t,p);
   ObjectSetInteger(0,nm,OBJPROP_ARROWCODE,code);
   ObjectSetInteger(0,nm,OBJPROP_COLOR,clr);
   ObjectSetInteger(0,nm,OBJPROP_ANCHOR,below ? ANCHOR_TOP : ANCHOR_BOTTOM);
   ObjectSetInteger(0,nm,OBJPROP_WIDTH,1);
   ObjectSetInteger(0,nm,OBJPROP_SELECTABLE,false);
   ObjectSetInteger(0,nm,OBJPROP_HIDDEN,true);
  }

// end line k at bar e (drawn)
void EndLine(const int k,const int e,const datetime &time[])
  {
   if(!g_ln[k].on) return;
   DrawLine(k,g_ln[k],e,time,PFX+"L"+(string)k+"_"+(string)(long)time[g_ln[k].i1]+"_"+(string)(g_nLine++));
   g_ln[k].on = false;
  }

void StartLine(const int k,const int i1,const double p1,const int i2,const double p2,const int confirm,const datetime &time[])
  {
   EndLine(k,confirm,time);                                      // one active line per type: the new one ends the old one
   g_ln[k].on = true;
   g_ln[k].i1 = i1; g_ln[k].p1 = p1; g_ln[k].i2 = i2; g_ln[k].p2 = p2;
   g_ln[k].from = confirm+1;
   g_ln[k].lastTouch = false;
  }

//--- bar i on line k: break (close) and touch (live HIGH / LOW). Returns 1 = touch
int BarOnLine(const int k,const int i,const bool closed,const datetime &time[],const double &h[],const double &l[],const double &c[])
  {
   TLine t = g_ln[k];
   if(!t.on || i<t.from) return 0;
   double v = LineVal(t,i);
   double atr = (i>0) ? g_atr[i-1] : 0.0;
   int res = 0;
   //--- touch: LOW reaches the support, HIGH reaches the resistance (with tolerance), line not broken yet
   bool touch = IsLowType(k) ? (l[i]<=v+TouchAtr*atr) : (h[i]>=v-TouchAtr*atr);
   if(touch && !t.lastTouch) res = 1;
   //--- break on a CLOSED bar: close beyond the line (+ ATR buffer); max. length
   if(closed)
     {
      g_ln[k].lastTouch = touch;
      bool brk = IsLowType(k) ? (c[i]<v-BreakAtr*atr) : (c[i]>v+BreakAtr*atr);
      if(brk || (MaxLineBars>0 && i-t.i1>MaxLineBars)) EndLine(k,i,time);
     }
   return res;
  }

//--- pivot on CLOSED bar i (bar c = i-N): new lines
void CheckPivots(const int i,const datetime &time[],const double &h[],const double &l[])
  {
   int N = PivotDepth, c = i-N;
   if(c-N<0) return;
   bool isH = true, isL = true;
   for(int k=1;k<=N && (isH || isL);k++)
     {
      if(!(h[c]>h[c-k] && h[c]>=h[c+k])) isH = false;
      if(!(l[c]<l[c-k] && l[c]<=l[c+k])) isL = false;
     }
   if(isL)
     {
      if(ShowPivots) Mark(PFX+"PL"+(string)(long)time[c],159,LowerColor,time[c],l[c],true);
      if(g_lastLowI>=0)
        {
         if(l[c]>g_lastLowP)      StartLine(0,g_lastLowI,g_lastLowP,c,l[c],i,time);   // rising LOW -> support
         else if(l[c]<g_lastLowP) StartLine(3,g_lastLowI,g_lastLowP,c,l[c],i,time);   // falling LOW -> DOWN lower
        }
      g_lastLowI = c; g_lastLowP = l[c];
     }
   if(isH)
     {
      if(ShowPivots) Mark(PFX+"PH"+(string)(long)time[c],159,UpperColor,time[c],h[c],false);
      if(g_lastHighI>=0)
        {
         if(h[c]<g_lastHighP)      StartLine(1,g_lastHighI,g_lastHighP,c,h[c],i,time); // falling HIGH -> resistance
         else if(h[c]>g_lastHighP) StartLine(2,g_lastHighI,g_lastHighP,c,h[c],i,time); // rising HIGH -> UP upper
        }
      g_lastHighI = c; g_lastHighP = h[c];
     }
  }

void TouchMark(const int k,const int i,const datetime &time[],const double &h[],const double &l[],const string tag)
  {
   if(!ShowTouches || !Shown(k) || k>1) return;               // only with-trend touches: support = BUY, resistance = SELL
   if(k==0) Mark(PFX+tag+"B"+(string)(long)time[i],ArrowTypeBuy, InpBuyColor, time[i],l[i],true);
   else     Mark(PFX+tag+"S"+(string)(long)time[i],ArrowTypeSell,InpSellColor,time[i],h[i],false);
  }

//+------------------------------------------------------------------+
//| Full calculation (on a new bar): the closed bars                  |
//+------------------------------------------------------------------+
void FullCalc(const int total,const datetime &time[],const double &h[],const double &l[],const double &c[])
  {
   ObjectsDeleteAll(0,PFX);
   ArrayResize(g_atr,total);
   double s = 0.0;
   for(int i=0;i<total;i++)
     {
      double tr = (i<1) ? h[i]-l[i] : MathMax(h[i],c[i-1])-MathMin(l[i],c[i-1]);
      s += tr;
      if(i>=AtrPeriod) s -= (i-AtrPeriod<1) ? h[i-AtrPeriod]-l[i-AtrPeriod] : MathMax(h[i-AtrPeriod],c[i-AtrPeriod-1])-MathMin(l[i-AtrPeriod],c[i-AtrPeriod-1]);
      g_atr[i] = (i>=AtrPeriod-1) ? s/AtrPeriod : 0.0;
     }
   for(int k=0;k<4;k++) g_ln[k].on = false;
   g_lastLowI = -1; g_lastHighI = -1; g_nLine = 0;
   int b0 = (InpMaxBars>0) ? MathMax(2*PivotDepth+1,total-InpMaxBars) : 2*PivotDepth+1;
   for(int i=b0;i<=total-2;i++)
     {
      for(int k=0;k<4;k++)
         if(BarOnLine(k,i,true,time,h,l,c)==1) TouchMark(k,i,time,h,l,"T");
      CheckPivots(i,time,h,l);
     }
  }

// forming bar: active lines up to the current bar, touch on live HIGH / LOW
void LiveBar(const int total,const datetime &time[],const double &h[],const double &l[],const double &c[])
  {
   int i = total-1;
   ObjectsDeleteAll(0,PFX+"X");
   string msg = "";
   for(int k=0;k<4;k++)
     {
      if(!g_ln[k].on) continue;
      DrawLine(k,g_ln[k],i,time,PFX+"XL"+(string)k);
      if(BarOnLine(k,i,false,time,h,l,c)==1 && k<2 && Shown(k))
        {
         TouchMark(k,i,time,h,l,"X");
         msg += (k==0) ? "Support touch (BUY) " : "Resistance touch (SELL) ";
        }
     }
   if(msg!="" && (InpAlert || InpPush) && g_lastAlert!=time[i])
     {
      g_lastAlert = time[i];
      string fm = StringFormat("KK TrendLines | %s %s | %s",_Symbol,EnumToString(_Period),msg);
      if(InpAlert) Alert(fm);
      if(InpPush)  SendNotification(fm);
     }
  }

int OnInit()
  {
   if(PivotDepth<1 || AtrPeriod<1 || BreakAtr<0.0 || TouchAtr<0.0)
     {
      Print("KK_TrendLines_Ind: invalid parameter");
      return INIT_PARAMETERS_INCORRECT;
     }
   IndicatorSetString(INDICATOR_SHORTNAME,StringFormat("KK TrendLines (pivot %d)",PivotDepth));
   g_total = 0;
   return INIT_SUCCEEDED;
  }

void OnDeinit(const int reason)
  {
   ObjectsDeleteAll(0,PFX);
   ChartRedraw();
  }

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   if(rates_total<4*PivotDepth+AtrPeriod+10) return 0;
   ArraySetAsSeries(time,false);
   ArraySetAsSeries(high,false);
   ArraySetAsSeries(low,false);
   ArraySetAsSeries(close,false);
   if(prev_calculated<=0 || rates_total!=g_total)
     {
      FullCalc(rates_total,time,high,low,close);
      g_total = rates_total;
     }
   LiveBar(rates_total,time,high,low,close);
   ChartRedraw();
   return rates_total;
  }
//+------------------------------------------------------------------+