declare lower;
#=======================================================
#               ACCUMULATION LINES
#=======================================================
input length_1 = 4; 
input length_2 = 9;
input length_3 = 14;
input length_4 = 19;
input factor = 0.75;
input bullish = 1.75;
input Show_Range1 = yes;
input Show_Range2 = yes;
input Show_Range3 = yes;
input Show_Range4 = no;
input mode = {default Range, ATR};
def     vHigh        = high;
def     vLow         = low;
def     nan          = Double.NaN;
def range1;
switch (mode) {
case Range:
    range1 = Highest(vhigh, length_1) - Lowest(vlow, length_1);
case ATR:
    range1 = reference ATR();
}
def range2;
switch (mode) {
case Range:
    range2 = Highest(vhigh, length_2) - Lowest(vlow, length_2);
case ATR:
    range2 = reference ATR();
}
def range3;
switch (mode) {
case Range:
    range3 = Highest(vhigh, length_3) - Lowest(vlow, length_3);
case ATR:
    range3 = reference ATR();
}
def range4;
switch (mode) {
case Range:
    range4 = Highest(vhigh, length_4) - Lowest(vlow, length_4);
case ATR:
    range4 = reference ATR();
}
plot RangeFactor = factor;
plot RangeBullish = bullish;
plot RangeRatio1 = if Show_Range1 then range1 / range1[length_1] else nan;
RangeRatio1.SetPaintingStrategy(PaintingStrategy.line);
RangeRatio1.DefineColor("Consolidation", color.light_green);
RangeRatio1.DefineColor("Non-consolidation", GetColor(1));
RangeRatio1.AssignValueColor( if (RangeRatio1 < RangeFactor) then RangeRatio1.Color("Consolidation") else RangeRatio1.Color("Non-consolidation"));
RangeFactor.SetDefaultColor(GetColor(2));
plot RangeRatio2 = if Show_Range2 then range2 / range2[length_2] else nan;
RangeRatio2.SetPaintingStrategy(PaintingStrategy.line);
RangeRatio2.DefineColor("Consolidation", color.yellow);
RangeRatio2.DefineColor("Non-consolidation", GetColor(1));
RangeRatio2.AssignValueColor( if (RangeRatio2 < RangeFactor) then RangeRatio2.Color("Consolidation") else RangeRatio2.Color("Non-consolidation"));
RangeFactor.SetDefaultColor(GetColor(3));
plot RangeRatio3 = if Show_Range3 then  range3 / range3[length_3] else nan;
RangeRatio3.SetPaintingStrategy(PaintingStrategy.line);
RangeRatio3.DefineColor("Consolidation", color.cyan);
RangeRatio3.DefineColor("Non-consolidation", GetColor(1));
RangeRatio3.AssignValueColor( if (RangeRatio3 < RangeFactor) then RangeRatio3.Color("Consolidation") else RangeRatio3.Color("Non-consolidation"));
RangeFactor.SetDefaultColor(GetColor(4));
plot RangeRatio4 = if Show_Range4 then range4 / range1[length_4] else nan;
RangeRatio4.SetPaintingStrategy(PaintingStrategy.line);
RangeRatio4.DefineColor("Consolidation", GetColor(4));
RangeRatio4.DefineColor("Non-consolidation", color.red);
RangeRatio4.AssignValueColor( if (RangeRatio4 < RangeFactor) then RangeRatio4.Color("Consolidation") else RangeRatio4.Color("Non-consolidation"));
RangeFactor.SetDefaultColor(GetColor(5));
#=======================================================
#               pivot points code
#=======================================================
#Inputs
#input     showbubble     = no;
input     Pivot_length   = 10;
#input     Show_Pivot     = yes;
input     DisplayLabel   = no;
input     compbars       = 20;  # pull in trend for longest period.  reduce within the specific groupings below
input     Fast_Length    = 4; #hint: for accumulation
input     Med_Length     = 9;
input     Slow_length    = 14;
def       ttmtrenddwn    = reference TTM_Trend( compBars = compbars ).trenddown;
input     lowlevel       = 0.75;
input     highlevel      = 1.5;
input     fallbelow      = 1.25;
input     drop_percent   = 20;
input     override_drop_percent = 70;
def     RVSD         = RelativeVolumeStDev()."RelVol";
def     Mobo         = FW_DPO_MOBO()."DPO";
def     LowBand      = FW_DPO_MOBO()."LOWERBANDP";
def     Mobo_True    = if Mobo > Mobo[1] or Mobo > LowBand then 1 else 0;
def     vTTM         = TTM_Wave()."Wave1";
def     bn           = BarNumber();
def     PPSdwn       = !IsNaN(PPS().”SellSignal”);
def     PPSup        = !IsNaN(PPS().”buySignal”);
#disused variables
#def     VChaikin     = ChaikinOscillator().COSC / 1000;
#def     vCCI         = CCI().CCI;
#def     vLow         = low;
#def     vOpen        = open;
#def     vClose       = close;
#def     vVolume      = volume;
#def     aggperiod    = if getaggregationperiod() == aggregationperiod.day then 1 else 0;
#=================================================
#            PPS Pivot Point
#================================================
def     hh =
        fold i = 1 to  Pivot_length + 1
        with p = 1
        while p       
        do PPSdwn > GetValue(PPSdwn, -i);
def     PH =
            if (bn >  Pivot_length
                and PPSdwn == Highest(PPSdwn,  Pivot_length)
                and hh)
            then PPSdwn
            else Double.NaN;
def     PHBar       = if !IsNaN(PH) then bn else PHBar[1];
def     PHL         = if !IsNaN(PH) then PH else PHL[1];
def     priorPHBar  = if PHL != PHL[1] then PHBar[1] else priorPHBar[1];
def     HighPivots  = bn >= HighestAll(priorPHBar);
def     DynamicLength =
            if bn - PHBar < 2 
            then bn - priorPHBar     
            else bn - PHBar;
#============================================================
#          DIVERGENCE CODE
#============================================================
#==================================================================
#         1 week - 3 bar factors (short length manipulation)
#==================================================================
def     w1_length     = Fast_Length;
def     w1_Range      = Highest(vHigh, w1_length) - Lowest(vLow, w1_length);
def     w1_Ratio      = w1_Range / w1_Range[w1_length];
#def     w1_RatioMax   = highest(w1_Ratio, 2);
#def     w1_Drop       = if
#                        ( w1_RatioMax - w1_Ratio ) >  ( drop_percent / 100 )
#                        then 1 else 0;
#def     w1_Slope      = w1_Ratio[6] - w1_Ratio[1];
#def     w1_Sign       = sign(w1_Slope);
#def     w1_trendup    = sum(ttmtrendup > 0, w1_length );  # num of upsignals in last 5
#def     w1_TrendDwn   = sum(ttmtrenddwn > 0, w1_length ); #num of downsignals in last 5
#==================================================================
#        2 week - 10 bar factors (medium length manipulation)
#==================================================================
def     w2_length = Med_Length;
def     w2_Range = Highest(vHigh, w2_length) - Lowest(vLow, w2_length);
def     w2_Ratio = w2_Range / w2_Range[w2_length];
def     w2_RatioMax = Highest(w2_Ratio, 5);
def     w2_Drop_Percent = ( w2_RatioMax - w2_Ratio ) / w2_RatioMax * 100;
def     w2_Drop = if w2_RatioMax == w2_Ratio then 0 else if
                w2_Drop_Percent >  drop_percent                   
                then 1 else 0;
def     w2_Slope = w2_Ratio[w2_length + 1] - w2_RatioMax;
def     w2_Sign =
                if w2_Drop_Percent > override_drop_percent
                and w2_Ratio <= lowlevel
                then -1
                else Sign(w2_Slope);
        #override sign if the drop% > 70 and falls below lowlevel
def     w2_TrendDwn = Sum(ttmtrenddwn > 0, w2_length );
#==================================================================
#======= 3 week - 15+ bar factors (long length manipulation)
#==================================================================
def     w3_length = Slow_length;
def     w3_Range = Highest(high, w3_length) - Lowest(low, w3_length);
def     w3_Ratio = w3_Range / w3_Range[w3_length];
def     w3_RatioMax = Highest(w3_Ratio, 3);
def     w3_Drop_Percent = ( w3_RatioMax - w3_Ratio ) / w3_RatioMax * 100;
def     w3_Drop = if
                w3_RatioMax == w3_Ratio then 0 else if
                w3_Drop_Percent > drop_percent / 2     
                then 1 else               
                0;
def     w3_Slope = w3_Ratio[w3_length + 1] - w3_RatioMax;
def     w3_Sign = Sign(w3_Slope);
def     w3_TrendDwn = Sum(ttmtrenddwn > 0, w3_length );             
#==================================================================
#                    PLOT POINTS
#==================================================================
def     w2_Diverge = if
            DynamicLength > w1_length #and dynamiclength <= w2_length + 3
            and w2_Drop
            and w2_Sign < 0
            and w2_RatioMax >= highlevel * .9
            and w2_Ratio <= fallbelow
            and w2_TrendDwn >= w2_length * .5
            and RVSD <= 1
            and w3_Ratio <= w3_Ratio[1]
            and w1_Ratio < w1_Ratio[1]
            and !PPSup
            and Mobo_True
            and vTTM > vTTM[1]
            then 1 else
            0;
def     w3_Diverge = if
            DynamicLength >= w2_length - 3
            and w3_Drop
            and w3_Sign < 0         
            and w3_RatioMax >= highlevel * .9
            and w3_Ratio <= fallbelow * 1.5     
            and w3_TrendDwn >= w3_length * .5
            and RVSD <= 2.1
            #and w1_Ratio < w1_Ratio[1]
            and !PPSup
           # and Mobo_True
            #and vTTM > vTTM[1]
            then 1 else
            0;
def     divergence = if w2_Diverge or w3_Diverge then 1 else 0;   #for scanner version
plot w2_alert = If w2_Diverge then W2_Ratio else nan;
w2_alert.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
w2_alert.SetDefaultColor(color.yellow);
w2_alert.SetLineWeight(2);
plot w_3alert = if w3_Diverge then W3_RATIO else nan;
w_3alert.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
w_3alert.SetDefaultColor(color.cyan);
w_3alert.SetLineWeight(2);
#plot Pivot = PH and Show_Pivot;#hint: to show the downarrow used for pivot point
#Pivot.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
#Pivot.SetDefaultColor(Color.plum);
#Pivot.SetLineWeight(5);
#==================================================================
#                    CHART BUBBLES (for upper study)
#==================================================================
#AddChartBubble(w2_Diverge and !w2_Diverge[1] and showbubble, close,
#                            "W2 " + close
#                             "BarNum: " + bn
#                            + "\n" + "start: " + w2_Ratio[w2_length]
#                            + "\n" + "end: " + w2_Ratio[1]
#                            + "\n" + "sign: " + w2_sign                           
#                            + "\n" + "slope: " + w2_slope
#                            + "\n" + "D%: " +  ( w2_RatioMax - w2_Ratio ) / w2_ratiomax
#                            + "\n" + "D%: min " +  drop_percent
#                            + "\n" + "drop: " +  ( w2_RatioMax - w2_Ratio )
#                            + "\n" + "max: " + w2_RatioMax
#                            + "\n" + "cur: " + w2_Ratio
#                            + "\n" + "Chkn diff: " + (vchaikin[1] - vchaikin)
#                            + "\n" + "Chaikin[1]: " + vchaikin[1] 
#                            + "\n" + "CCI diff: " + (vcci[1] -  vcci)
#                            + "\n" + "CCI[1]: " + vcci[1]
#                            , Color.CYAN, yes);
#AddChartBubble(w3_Diverge and !w3_Diverge[1] and showbubble, close,
#                            "W3 " + close
#                            + "BarNum: " + bn
#                            + "\n" + "down: " + w3_TrendDwn
#                            + "\n" + "sign: " + w3_sign                           
#                            + "\n" + "slope: " + w3_slope
#                            + "\n" + "D%: " +  (w3_Ratio / w3_RatioMax ) / W3_RatioMax
#                            + "\n" + "drop: " +  ( w3_RatioMax - w3_Ratio )
#                            + "\n" + "cur: " + w3_Ratio
#                            + "\n" + "beg: " + w3_Ratio[w3_length + 1]
#                            , Color.Plum, yes);
#def symbol = getsymbol();
#addlabel(yes, getsymbol(), color.white);