Overlayed Secondary-ZigZag : Need Help

Hello Edward Pottasch (empottasch).

I need your help.

Below is your code for ZigZag. It is a mixture of two codes written by you.
I have carefully selected these two codes and mixed them, as per my need. I have modified a few little things only, but in a way, the basic codes are still untouched.
Avoided short-forms for words, in the code, because it helps me to understand the code. I don't know any kind of programming language.
Started learning the AFL since three weeks only. Already tried really hard to code what I need, otherwise would not have bothered you.

Here is what I need:

I want to draw/plot a second-ZigZag over the Base-ZigZag.

The second-ZigZag should be drawn over the Base-ZigZag, when the Base-ZigZag is done with making Higher-High & Higher-Low series and Lower-Low & Lower-High Series.

In other words, the second-ZigZag's upward Zig-Line should be continued upside until a condition reaches where the swings of Base-ZigZag happen to make a Lower-High & Lower-Low. And the second-ZigZag's downward Zig-Line should be continued upside until a condition comes where the swings of Base-ZigZag happen to make a Higher-High & Higher-Low.

That is, this second-ZigZag should be completely based on our Base-ZigZag.

It will be really great, if you would also code a trailing-line for this second-ZigZag.

I know that any ZigZag looks into future, but that's okay for me. I guess that you like ATR based swings, but here I would like to prefer this ZigZag only.

// Author of Code:  Edward Pottasch (empottasch) //
// Little Modifications by = LotusHeart //
// Note: The Core of Code is left Untouched.
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

_SECTION_BEGIN( "Essentials" );

SetChartOptions( 0, chartShowArrows | chartShowDates );
TimeFrame = in1Minute * Interval() / 60 * 1;
_N( Title = StrFormat( "{{NAME}} - {{DATE}} Open %g, High %g, Low %g, Close %g (%.1f%%) " + 
"TimeFrame: " + TimeFrame / 60 + " Minutes or " + TimeFrame / 3600 + " Hours or " + TimeFrame / ( 3600 * 24 ) + " Days " +  "TIME: " + Now( 2 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
setbarsrequired( sbrall, sbrall );
nBarIndex = BarIndex();
nCum = Cum( 1 );

First_Visible_Bar = FirstVisibleValue( nBarIndex );
Last_Visible_Bar = LastVisibleValue( nBarIndex );

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "Chart Background Colors" );

SetChartBkColor( ParamColor( "Outer Panel Color ", colorBlack ) ); // color of outer border
SetChartBkGradientFill( ParamColor( "Inner Panel Color Upper-Half", colorBlack ), ParamColor( "Inner Panel Color Lower-Half", colorBlack ) ); // color of inner panel
SetChartBkColor( ParamColor( "background", colorBlack ) );

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "Price-Chart" );

Plot( C, "C", colorWhite, styleCandle, Null, Null, 0, 0, 0 );

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "Price-ZigZag Parameters" );

ZigZag_Switch = ParamToggle( "Show ZigZag ", "No|Yes", 1 );
ZZ_Pivot_Dots_Switch = ParamToggle( "Show ZZ Pivot-Dots", "No|Yes", 0 );
zBox_Switch = ParamToggle( "Show zBox", "No|Yes", 0 );
ZZ_Pivot_Labels_Switch = ParamToggle( "Show ZZ-Pivot Labels", "No|Yes", 1 );
ZZ_DT_DB_Labels_Switch = ParamToggle( "Show ZZ's DT-&-DB Labels", "No|Yes", 1 );
ZZ_Trailing_Line_Switch = ParamToggle( "Show ZZ Trailing-Line", "No|Yes", 0 );
ZZ_Trail_Signals_Switch = ParamToggle( "Show ZZ Trail-Signals", "No|Yes", 0 );
ZZ_Trail_Text_Switch = ParamToggle( "Show ZZ-Trail's Text", "No|Yes", 0 );
ZZ_Zorder = Param( "ZZ's Zorder", 1, -12, 12, 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ZZ_Price_Array_Switch = ParamToggle( "Use Close or High-&-Low price", "Use Close|Use High-&-Low", 1 );
ZZ_Upward_Percentage_Change_Threshold = Param( "ZZ-Upward % Change Threshold", 1, 0.01, 25, 0.01 );  
ZZ_Downward_Percentage_Change_Threshold = Param( "ZZ-Downward % Change Threshold", 1, 0.01, 25, 0.01 );
//ZZ_Percentage_Change_Threshold = Param( "% Change Threshold ", 0.35, 0.001, 100, 0.001 );
PriceTicks = Param( "Price Change In Ticks", 4, 1, 100, 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ZZ_Label_Background_Color = ParamColor( "ZZ Label's Background-Color", colorBlack );
ZZ_Shift_Swing_Labels = Param( "Shift ZZ-Labels", 10, -20, 100, 1 );
ZZ_Label_Font_Size = Param( "ZZ Label's Font-Size", 7, 1, 25, 1 );
ZZ_Upper_Label_Color = ParamColor( "ZZ's Upper-Label Color", colorYellow );
ZZ_Lower_Label_Color = ParamColor( "ZZ's Lower-Lable Color", colorCustom11 );
ZZ_Label_Color = ParamColor( "ZZ's Lable Color", colorDefault );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ZZ_Font = "Helvetica";
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ZZUPCT = ZZ_Upward_Percentage_Change_Threshold;
ZZDPCT = ZZ_Downward_Percentage_Change_Threshold;
ZZLBC = ZZ_Label_Background_Color;
ZZSSL = ZZ_Shift_Swing_Labels;
ZZLFS = ZZ_Label_Font_Size;
ZZULC = ZZ_Upper_Label_Color;
ZZLLC = ZZ_Lower_Label_Color;
ZZLC = ZZ_Label_Color;

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag Price Array Switch" );

if( ZZ_Price_Array_Switch )
{
    ZZ_Array_High = High;
    ZZ_Array_Low = Low;
}
else
{
    ZZ_Array_High = Close;
    ZZ_Array_Low = Close;
}

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag's Pivot-Calculation" );

nPeak = nTrough = Buy = Sell = BuyPrice = SellPrice = 0;
nZigZag = nLine1 = nLine2 = Null;
ZZ_Trail_Array_Up = Null;
ZZ_Trail_Array_Down = Null;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// if ticksize is not set in code or information window use 0.01
if( TickSize == 0 )
{
    TickSize = 0.01;
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function PercentageFluctuation( PriceChange, PercentageChange )
{
    Ret_Price = round( ( PriceChange * PercentageChange / 100 ) / TickSize ) * TickSize;
    return Ret_Price;
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function CalculatePivots()
{
    // initial condition trend is up (but -1 works also)
    ZZ_Trend = 1;
    ZZ_PriceChange_Top = ZZ_Array_High[0];
    ZZ_Index_Top = 0;
    ZZ_PriceChange_Bottom = ZZ_Array_Low[0];
    ZZ_Index_Bottom = 0;
    Buy = Sell = BuyPrice = SellPrice = 0;
    ZZ_Trail_Array_Up[0] = ZZ_PriceChange_Top - PercentageFluctuation( ZZ_PriceChange_Top, ZZDPCT );
    ZZ_Trail_Array_Down[0] = ZZ_PriceChange_Bottom + PercentageFluctuation( ZZ_PriceChange_Bottom, ZZUPCT );

    for( i = 1; i < BarCount; i++ )
    {
        if( ZZ_Trend > 0 )
        {
            // trend turning down, avoid same bar as the peak
            if( ZZ_Array_Low[i] <= ZZ_Trail_Array_Up[i - 1] AND ZZ_Array_High[i] < ZZ_PriceChange_Top AND ZZ_Array_Low[i] <= ZZ_Array_Low[i - 1] AND ZZ_Array_Low[i] <= Open[i - 1] )
            {
                nPeak[ZZ_Index_Top] = 1;
                ZZ_PriceChange_Bottom = ZZ_Array_Low[i];
                ZZ_Index_Bottom = i;
                ZZ_Trend = -1;
                Sell[i] = 1;
                ZZ_Trail_Array_Down[i] = ZZ_PriceChange_Bottom + PercentageFluctuation( ZZ_PriceChange_Bottom, ZZUPCT );
                ZZ_Trail_Array_Up[i] = ZZ_Trail_Array_Up[i - 1];

                if( ZZ_Price_Array_Switch )
                    SellPrice[i] = Min( Open[i], ZZ_Trail_Array_Up[i] );
                else
                    SellPrice[i] = Close[i];

            }
            else

                // still in uptrend and new top reached
                if( ZZ_Array_High[i] >= ZZ_PriceChange_Top )
                {
                    ZZ_PriceChange_Top = ZZ_Array_High[i];
                    ZZ_Index_Top = i;
                    ZZ_Trail_Array_Up[i] = Max( ZZ_Trail_Array_Up[i - 1], ZZ_Array_High[i] - PercentageFluctuation( ZZ_PriceChange_Top, ZZDPCT ) );
                }
                // continuation inside uptrend
                else
                {
                    ZZ_Trail_Array_Up[i] = Max( ZZ_Trail_Array_Up[i - 1], ZZ_Array_High[i] - PercentageFluctuation( ZZ_Array_High[i], ZZDPCT ) );
                }
        }
        
        else
            if( ZZ_Trend < 0 )
            {
                // trend turning up, avoid same bar as the trough
                if( ZZ_Array_High[i] >= ZZ_Trail_Array_Down[i - 1] AND ZZ_Array_Low[i] > ZZ_PriceChange_Bottom AND ZZ_Array_High[i] >= ZZ_Array_High[i - 1] AND ZZ_Array_High[i] >= O[i - 1] )
                {
                    nTrough[ZZ_Index_Bottom] = 1;
                    ZZ_PriceChange_Top = ZZ_Array_High[i];
                    ZZ_Index_Top = i;
                    ZZ_Trend = 1;
                    Buy[i] = 1;
                    ZZ_Trail_Array_Up[i] = ZZ_PriceChange_Top - PercentageFluctuation( ZZ_PriceChange_Top, ZZDPCT );
                    ZZ_Trail_Array_Down[i] = ZZ_Trail_Array_Down[i - 1];

                    if( ZZ_Price_Array_Switch )
                        BuyPrice[i] = Max( Open[i], ZZ_Trail_Array_Down[i] );
                    else
                        BuyPrice[i] = Close[i];
                }
                else

                    // still in downtrend and new trough reached
                    if( ZZ_Array_Low[i] <= ZZ_PriceChange_Bottom )
                    {
                        ZZ_PriceChange_Bottom = ZZ_Array_Low[i];
                        ZZ_Index_Bottom = i;
                        ZZ_Trail_Array_Down[i] = Min( ZZ_Trail_Array_Down[i - 1], ZZ_Array_Low[i] + PercentageFluctuation( ZZ_PriceChange_Bottom, ZZUPCT ) );
                    }
                    // continuation inside downtrend
                    else
                    {
                        ZZ_Trail_Array_Down[i] = Min( ZZ_Trail_Array_Down[i - 1], ZZ_Array_Low[i] + PercentageFluctuation( ZZ_Array_Low[i], ZZUPCT ) );
                    }
            }
    }
}
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag-Calculation" );

function CalculateZigZag()
{
    // create ZIGZAG array line
    ZigUp = Flip( nTrough, nPeak );
    ZigUpLow = ValueWhen( nTrough, ZZ_Array_Low, 1 );
    ZigUpHigh = ValueWhen( nPeak, ZZ_Array_High, 0 );
    ZigUpLowIndex = ValueWhen( nTrough, nBarIndex, 1 );
    ZigUpHighIndex = ValueWhen( nPeak, nBarIndex, 0 );
    ZZ_SlopeUp = IIf( ZigUp, ( ZigUpHigh - ZigUpLow ) / ( ZigUpHighIndex - ZigUpLowIndex ) , Null );
    ZigUpLine = IIf( ZigUp, ZigUpLow + ZZ_SlopeUp * BarsSince( nTrough ), Null );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ZigDown = Flip( nPeak, nTrough );
    ZigDownLow = ValueWhen( nTrough, ZZ_Array_Low, 0 );
    ZigDownHigh = ValueWhen( nPeak, ZZ_Array_High, 1 );
    ZigDownLowIndex = ValueWhen( nTrough, nBarIndex, 0 );
    ZigDownHighIndex = ValueWhen( nPeak, nBarIndex, 1 );
    ZZ_SlopeDown = IIf( ZigDown, ( ZigDownLow - ZigDownHigh ) / ( ZigDownLowIndex - ZigDownHighIndex ) , Null );
    ZigDownLine = IIf( ZigDown, ZigDownHigh + ZZ_SlopeDown * BarsSince( nPeak ), Null );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    nZigZag = IIf( ZigUp, ZigUpLine, IIf( ZigDown, ZigDownLine, Null ) );
    nZigZag = IIf( nBarIndex > Max( LastValue( ValueWhen( nTrough, nBarIndex ) ), LastValue( ValueWhen( nPeak, nBarIndex ) ) ), Null, nZigZag );
}


function CalculateLastSegments( )
{
    //line1 = line2 = Null;
    Last_Index_Peak = LastValue( ValueWhen( nPeak, nBarIndex ) );
    Last_Index_Trough = LastValue( ValueWhen( nTrough, nBarIndex ) );
    Last_Value_Peak = LastValue( ValueWhen( nPeak, ZZ_Array_High ) );
    Last_Value_Trough = LastValue( ValueWhen( nTrough, ZZ_Array_Low ) );
    Last_Index_Buy = LastValue( ValueWhen( Buy, nBarIndex ) );
    Last_Index_Sell = LastValue( ValueWhen( Sell, nBarIndex ) );
    Value_Peak = LastValue( HighestSince( Ref( nTrough, -1 ), ZZ_Array_High , 1 ) );
    Index_Peak = LastValue( ValueWhen( ZZ_Array_High == Value_Peak, nBarIndex ) );
    Value_Trough = LastValue( LowestSince( Ref( nPeak, -1 ), ZZ_Array_Low, 1 ) );
    Index_Trough = LastValue( ValueWhen( ZZ_Array_Low == Value_Trough, nBarIndex ) );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    if( Last_Index_Sell > Last_Index_Buy AND Last_Index_Sell > Last_Index_Peak AND Last_Index_Peak > Last_Index_Trough )
    {
        x0 = Last_Index_Peak;
        y0 = Last_Value_Peak;
        x1 = Index_Trough;
        y1 = Value_Trough;
        nLine1 = nLineDown = LineArray( x0, y0, x1, y1 );
        nTrough[Index_Trough] = 1;
        Value_Peak = LastValue( HighestSince( Ref( nTrough, -1 ), ZZ_Array_High, 1 ) );
        Index_Peak = LastValue( ValueWhen( ZZ_Array_High == Value_Peak, nBarIndex ) );
    }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    if( Last_Index_Sell < Last_Index_Buy AND Last_Index_Buy > Last_Index_Trough AND Last_Index_Peak < Last_Index_Trough )
    {
        x0 = Last_Index_Trough;
        y0 = Last_Value_Trough;
        x1 = Index_Peak;
        y1 = Value_Peak;
        nLine1 = nLineUp = LineArray( x0, y0, x1, y1 );
        nPeak[Index_Peak] = 1;
        Value_Trough = LastValue( LowestSince( Ref( nPeak, -1 ), ZZ_Array_Low, 1 ) );
        Index_Trough = LastValue( ValueWhen( ZZ_Array_Low == Value_Trough, nBarIndex ) );
    }

    nZigZag = IIf( !IsEmpty( nLine1 ), nLine1, nZigZag );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
CalculatePivots();
CalculateZigZag();
CalculateLastSegments();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SetTradeDelays( 0, 0, 0, 0 );
SetOption( "FuturesMode", True );
SetOption( "PriceBoundChecking", False );
SetOption( "AllowSameBarExit", True );
SetOption( "CommissionMode", 3 );
SetOption( "CommissionAmount", 2.5 );
NumContracts = 1;
PositionSize = NumContracts * MarginDeposit;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Slip = 0;//TickSize * 2;
BuyPrice = BuyPrice + Slip;
SellPrice = SellPrice - Slip;
Short = Sell;
ShortPrice = SellPrice;
Cover = Buy;
CoverPrice = BuyPrice;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ZZ_UpTrend1 = Flip( Buy, Sell );
ZZ_DownTrend1 = Flip( Sell, Buy );
ZZ_UpTrend = Ref( Flip( nTrough, nPeak ), -1 );
ZZ_DownTrend = Ref( Flip( nPeak, nTrough ), -1 );

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag" );

ZZ_Line_Width = Param( "ZZ-Line's Width", 2, 1, 5, 1 );
ZZ_Style = ParamStyle( "ZZ Style", styleLine | styleDashed | styleNoRescale | styleNoLabel );
ZZ_Up_Color = ParamColor( "ZZ Up-Color", ColorRGB( 0, 0, 255 ) );  // ColorYellow );
ZZ_Down_Color = ParamColor( "ZZ Down-Color", ColorRGB( 255, 0, 0 ) );  // ColorYellow );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZigZag_Switch )
{
Plot( nZigZag, "", IIf( ZZ_UpTrend1, ZZ_Up_Color, ZZ_Down_Color ), ZZ_Style, Null, Null, 0, ZZ_Zorder, ZZ_Line_Width );
Plot( IIf( !IsEmpty( nLine1 ), nLine1, Null ), "", ColorRGB( 255, 255, 0 ), ZZ_Style, Null, Null, 0, ZZ_Zorder, ZZ_Line_Width );
}
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag's Pivot-Dots" );

ZZ_Up_Dot_Color = ParamColor( "ZZ Up-Dot Color", colorCustom12 );
ZZ_Down_Dot_Color = ParamColor( "ZZ Down-Dot Color", colorBlue );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZZ_Pivot_Dots_Switch )
{
    PlotShapes( shapeSmallCircle * nTrough, ZZ_Down_Dot_Color, 0, Low, -10 );
    PlotShapes( shapeSmallCircle * nPeak, ZZ_Up_Dot_Color, 0, High, 10 );
}
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag-Pivots" );

for( i = 0; i < 3; i++ )
{
    VarSet( "Peak_x" + i, ValueWhen( nPeak, nBarIndex, i ) );                // px = Peak_x
    VarSet( "Trough_x" + i, ValueWhen( nTrough, nBarIndex, i ) );            // tx = Trough_x
    VarSet( "PeakHigh_" + i, ValueWhen( nPeak, ZZ_Array_High, i ) );                  // ph = PeakHigh
    VarSet( "TroughLow_" + i, ValueWhen( nTrough, ZZ_Array_Low, i ) );                // tl = TroughLow
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
LowerLow = nTrough AND TroughLow_1 < TroughLow_2;           // ll = LowerLow
HigherLow = nTrough AND TroughLow_1 > TroughLow_2;          // hl = HigherLow
HigherHigh = nPeak AND PeakHigh_1 > PeakHigh_2;             // hh = HigherHigh
LowerHigh = nPeak AND PeakHigh_1 < PeakHigh_2;              // lh = LowerHigh
DoubleTop = nPeak AND PeakHigh_1 == PeakHigh_2;             // dt = DoubleTop
DoubleBottom = nTrough AND TroughLow_1 == TroughLow_2;      // db = DoubleBottom

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag's Box" );

if( ZZ_Price_Array_Switch )
{
zBox_Down_Low_Array = IIf( nTrough AND ZZ_DownTrend, Min( High, Low ), null );
zBox_Down_Low_Array = IIf( ZZ_DownTrend AND !nTrough, ValueWhen( nTrough, Min( High, Low ), 0 ), zBox_Down_Low_Array );
zBox_Down_High_Array = IIf( ZZ_DownTrend, HighestSince( Ref( nPeak, -1 ), Max( High, Low ) ), null );
zBox_Up_High_Array = IIf( nPeak AND ZZ_UpTrend, Max( High, Low ), null );
zBox_Up_High_Array = IIf( ZZ_UpTrend AND !nPeak, ValueWhen( nPeak, Max( High, Low ), 0 ), zBox_Up_High_Array );
zBox_Up_Low_Array = IIf( ZZ_UpTrend, LowestSince( Ref( nTrough, -1 ), Min( High, Low ) ), null );
}
else
{
zBox_Down_Low_Array = IIf( nTrough AND ZZ_DownTrend, Min( Open, Close ), null );
zBox_Down_Low_Array = IIf( ZZ_DownTrend AND !nTrough, ValueWhen( nTrough, Min( Open, Close ), 0 ), zBox_Down_Low_Array );
zBox_Down_High_Array = IIf( ZZ_DownTrend, HighestSince( Ref( nPeak, -1 ), Max( Open, Close ) ), null );
zBox_Up_High_Array = IIf( nPeak AND ZZ_UpTrend, Max( Open, Close ), null );
zBox_Up_High_Array = IIf( ZZ_UpTrend AND !nPeak, ValueWhen( nPeak, Max( Open, Close ), 0 ), zBox_Up_High_Array );
zBox_Up_Low_Array = IIf( ZZ_UpTrend, LowestSince( Ref( nTrough, -1 ), Min( Open, Close ) ), null );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
zBox_Bull_RGB1 = Param( "zBox Bull-RGB1", 0, 0, 255, 1 );
zBox_Bull_RGB2 = Param( "zBox Bull-RGB2", 0, 0, 255, 1 );
zBox_Bull_RGB3 = Param( "zBox Bull-RGB3", 80, 0, 255, 1 );

zBox_Bear_RGB1 = Param( "zBox Bear-RGB1", 80, 0, 255, 1 );
zBox_Bear_RGB2 = Param( "zBox Bear-RGB2", 0, 0, 255, 1 );
zBox_Bear_RGB3 = Param( "zBox Bear-RGB3", 0, 0, 255, 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GfxSetZOrder( -1 );
GfxSetCoordsMode( 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( zBox_Switch )
{
    ft = "Arial Black";
    clr = colorDefault;

    for( i = 0; i <= BarCount - 1; i++ )
    {
        if( nPeak[i] )
        {
            c1 = zBox_Bull_RGB1;
            c2 = zBox_Bull_RGB2;
            c3 = zBox_Bull_RGB3;
            x0 = Nz( Trough_x1[i] + 0.5 );
            x1 = Nz( Peak_x1[i] + 0.5 );
            yh = Nz( zBox_Up_High_Array[i] );
            yl = Nz( zBox_Up_Low_Array[i] );
            //GfxSelectPen( ColorRGB( c1, c2, c3 * 3 ), 2 );
            GfxSelectSolidBrush( ColorRGB( c1, c2, c3 ) );
            GfxRoundRect( x0, yh, x1, yl, 0, 0 );
        }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        if( nTrough[i] )
        {
            c1 = zBox_Bear_RGB1;
            c2 = zBox_Bear_RGB2;
            c3 = zBox_Bear_RGB3;
            x0 = Nz( Peak_x1[i] + 0.5 );
            x1 = Nz( Trough_x1[i] + 0.5 );
            yh = Nz( zBox_Down_High_Array[i] );
            yl = Nz( zBox_Down_Low_Array[i] );
            //GfxSelectPen( ColorRGB( 3 * c1, c2, c3 ), 2 );
            GfxSelectSolidBrush( ColorRGB( c1, c2, c3 ) );
            GfxRoundRect( x0, yh, x1, yl, 0, 0 );
        }
    }
}
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag's Trail" );

GfxSetZOrder( 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ZZ_Trail_Line_Width = Param( "ZZ's Trial-Line's Width", 2, 1, 5, 1 );
ZZ_Trail_Line_Style = ParamStyle( "ZZ's Trial-Line's Style", styleStaircase | styleDots | styleNoRescale | styleNoLabel );
ZZ_Trail_Up_Color = ParamColor( "ZZ Trial-Up Color", colorLightBlue );
ZZ_Trail_Down_Color = ParamColor( "ZZ Trial-Down Color", colorOrange );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZZ_Trailing_Line_Switch )
{
    Plot( ZZ_Trail_Array_Up, "Trailing-Up", ZZ_Trail_Up_Color, ZZ_Trail_Line_Style, Null, Null, 0, ZZ_Zorder, ZZ_Trail_Line_Width );
    if( !IsEmpty( ZZ_Trail_Array_Up[BarCount - 1] ) )
        {
            PlotTextSetFont( "" + ZZ_Trail_Array_Up[BarCount - 1 ], ZZ_Font, ZZLFS, BarCount + 1, ZZ_Trail_Array_Up[BarCount - 1], ZZ_Trail_Up_Color, ZZLBC, 0 );
        }
        
    Plot( ZZ_Trail_Array_Down, "Trailing-Down", ZZ_Trail_Down_Color, ZZ_Trail_Line_Style, Null, Null, 0, ZZ_Zorder, ZZ_Trail_Line_Width );
    if( !IsEmpty( ZZ_Trail_Array_Down[BarCount - 1] ) )
        {
            PlotTextSetFont( "" + ZZ_Trail_Array_Down[BarCount - 1], ZZ_Font, ZZLFS, BarCount + 1, ZZ_Trail_Array_Down[BarCount - 1], ZZ_Trail_Down_Color, ZZLBC, 0 );
        }
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZZ_Trail_Signals_Switch )
{
    PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ), colorLightBlue, 0, Low, -20 );
    PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ), colorOrange, 0, High, -20 );
    PlotShapes( IIf( Buy, shapeSmallSquare, shapeNone ), colorYellow, 0, BuyPrice, 0 );
    PlotShapes( IIf( Sell, shapeSmallSquare, shapeNone ), colorYellow, 0, SellPrice, 0 );
}

_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag-Trail's Text" );

GfxSetZOrder( 2 );
GfxSetCoordsMode( 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
BuyPrice = ValueWhen( Buy, BuyPrice );
ShortPrice = ValueWhen( Short, ShortPrice );
CoverPrice = ValueWhen( Cover, CoverPrice );
SellPrice = ValueWhen( Sell, SellPrice );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ZZ_Long_Result = Nz( Prec( IIf( Sell, SellPrice - ValueWhen( Buy, BuyPrice ), 0 ), 2 ) );
ZZ_Short_Result = Nz( Prec( IIf( Cover, ValueWhen( Short, ShortPrice ) - CoverPrice, 0 ), 2 ) );
ZZ_Total_Result = LastValue( Cum( ZZ_Long_Result ) + Cum( ZZ_Short_Result ) );
//_TRACE( "ZZ-Total: " + ZZ_Total_Result ); 
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZZ_Trail_Text_Switch )
{
    for( i = 0; i < BarCount - 1; i++ )
    {
        if( Buy[i] && Cover[i] )
        {
            String = "Buy: " + BuyPrice[i] + " (" + ZZ_Short_Result[i] + ")";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, Low[i], ZZLLC, ZZLBC, -50 - ZZSSL );
            //String = "Cover: " + CoverPrice[i] + " (" + ZZ_Short_Result[i] + ")";
            //PlotTextSetFont( String, ZZ_Font, ZZLFS, i, L[i], ZZLLC, ZZLBC, -65 - ZZSSL );
        }

        if( !Buy[i] && Cover[i] )
        {
            String = "Cover: " + CoverPrice[i] + " (" + ZZ_Short_Result[i] + ")";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, Low[i], ZZLLC, ZZLBC, -50 - ZZSSL );
        }

        if( Buy[i] && !Cover[i] )
        {
            String = "Buy: " + BuyPrice[i];
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, Low[i], ZZLLC, ZZLBC, -50 - ZZSSL );
        }

        if( Short[i] && Sell[i] )
        {
            String = "Short: " + ShortPrice[i] + " (" + ZZ_Long_Result[i] + ")";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, High[i], ZZULC, ZZLBC, 30 + ZZSSL );
            //String = "Sell: " + SellPrice[i] + " (" + ZZ_Long_Result[i] + ")";
            //PlotTextSetFont( String, ZZ_Font, ZZLFS, i, H[i], ZZULC, ZZLBC, 45 + ZZSSL );
        }

        if( !Short[i] && Sell[i] )
        {
            String = "Sell: " + SellPrice[i] + " (" + ZZ_Long_Result[i] + ")";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, High[i], ZZULC, ZZLBC, 30 + ZZSSL );
        }

        if( Short[i] && !Sell[i] )
        {
            String = "Short: " + ShortPrice[i];
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, High[i], ZZULC, ZZLBC, 30 + ZZSSL );
        }

    }
}    
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
_SECTION_BEGIN( "ZigZag Pivot's Lables" );

GfxSetZOrder( 2 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZZ_Pivot_Labels_Switch )
{
    for( i = 0; i < BarCount - 1; i++ )
    {
        if( LowerLow[i] )
        {
            String = "LL";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, Low[i], ZZLLC, ZZLBC, -30 );
        }
        
        if( HigherLow[i] )
        {
            String = "HL";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, Low[i], ZZLLC, ZZLBC, -30 );
        }

        if( DoubleBottom[i] )
        {
            String = "DB";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, Low[i], ZZLLC, ZZLBC, -30 );
        }

        if( HigherHigh[i] )
        {
            String = "HH";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, High[i], ZZULC, ZZLBC, 30 );
        }

        if( LowerHigh[i] )
        {
            String = "LH";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, High[i], ZZULC, ZZLBC, 30 );
        }

        if( DoubleTop[i] )
        {
            String = "DT";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, High[i], ZZULC, ZZLBC, 30 );
        }

    }
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZZ_DT_DB_Labels_Switch )
{
    for( i = 0; i < BarCount - 1; i++ )
    {

        if( DoubleBottom[i] )
        {
            String = "DB";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, Low[i], ZZLLC, ZZLBC, -30 );
        }


        if( DoubleTop[i] )
        {
            String = "DT";
            PlotTextSetFont( String, ZZ_Font, ZZLFS, i, High[i], ZZULC, ZZLBC, 30 );
        }

    }
}
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

hi, I would think you will have to use a loop to do that. I do not see a smart way of doing it. Also the secondary Zig would not necessarily have to be continuous. You would have "up legs" and "down legs". An up leg will start wil a LL, the second pivot can be a HH or LH. After that only HL and HH. The leg stops after you get a LH (or even earlier when you get a LL after the HH). Or something like that. I do not see any "smart" way to do it. You will probably have to use a loop and identify the up and down legs

1 Like

Thanks for responding Mr. Edward Pottasch (empottasch).

I am aware that there is no simple and easy way to do that. That's why I started learning AFL. Still I am trying hard to learn AFL on daily basis, usually 12 to 16 hours per day since 3 weeks. But still I am a newbie in coding and unable to code that. As per my best of knowledge, you are the only person who is a master of ZigZag coding.

Yes, you are absolutely right about these points.

Is it possible that we somehow put a condition in the code that as long as there is Higher-High series in an upleg or Lower-Low series in a downleg, it creates the secondary zigzag, and rest of the time it mimics the base-zigzag so that its uplegs and downlegs remains continuous. I will be happy if it is possible even with a loop. Please help me, if you see any possible roundabout way to do that. I don't mind even if the round-about way put a load on the system or if it looks too much in the future.

Used to trade manually, that is, was in the habit of drawing zigzags by hand over the screen. But due to an accident there is a lot of shaking in my hands and now its almost impossible for me to draw these zigzags by hands. That's why now its so important for me to trade. Somehow I am unable to visualize the chart patterns in upside down view. The base-zigzag and secondary-zigzag helps me to properly visualize such trade-patterns in the charts.

i think you want to do something like this, right?

I was just learning a bit of Pinescript. Pinscript however also uses self-referencing I believe although I think that is now obsolete.

Although if I look at the charts more closely they do not always have a perfect sequence. Like the first chart the second leg up is not as you described it. So maybe what they do here is just overlay 2 Zig functions each with their own parameters. For instance the primary using 1% swing and the secondary 3% swing.

Else show me the link where you got your idea from.

Going through the link you have provided. Will respond within a few minutes after checking it.

Okay. This is exactly what I want. The only thing is that the secondary-zigzag should be totally based on base-zigzag. I don't mind if the secondary ZigZag's HH/HL/LL/LH changes dynamically.

Unfortunately, I have no link to share such zigzag. As I am not aware of any other person who is using such secondary-zigzag. As reference to idea, all I can say is that I am just using some of nature's universal laws mentioned in ancient scriptures of Yoga & Tantra. Initially hard to understand those laws but once understood they are applicable to every phenomena. For example, just like W.D. Gann's work, it is possible to calculate the precise time and price of any stock in adavance ( but not the entire future, as everything is not already fixed, only certain things are fixed due to past events ). These laws are highly accurate and precise. But perhaps they might not be programmable. I can show you a few things in live market via screen sharing, if you kindly give a thought to help me to code those principles. You will be amazed that how accurate these principle are. I call them Yin-Yang of Chaos-&-Order.

Sorry for taking too much time for responding. My hand not functioning properly so its really tough to type.

the secondary zigzag in the code used in the TradingView example is not based on the primary zigzag. They use "highestbars" and "lowestbars" functions to calculate the pivots. These function are the same as Amibroker HHVBars and LLVBars functions. But what they do is use prd1 bars for the primary zigzag and prd2 bars for the secondary zigzag. So they are independent. This you can see in the top chart the second leg up. This second leg up of the secondary is clearly not based on the primary pivots.

To make the secondary zigzag dependent on the primary that code I do not have at the moment. Possibly will get back on the topic. If you can find example code somewhere let me know. But I think you just need to go through all bars and construct these secondary legs

Okay, will try to find some example code. Meanwhile if you happen to have some solution please share. If you are interested in my trading techniques please let me know via email. Of course, first I will demonstrate the practical application of them. And if you like them then please help me to code them. Currently, I am using all of my techniques manually. If they are even partially programmable then it would be a great help for me. My email is 'neo.lotusheart@gmail.com' Thanks and grateful for showing interest in the above problem.

you can actually avoid using loops. In the example below my reasoning is that between two LL's (lower lows) in an up-leg you have only HL's (higher lows). Using the SparseCompress and SparseExpand functions I came up with the code below for an up-leg. So with the up-leg you have only HL's (higher lows) but both HH's (Higher Highs) and LH's (lower highs) can occur.

The code needs to be integrated in the code you have. I used my shorter names for arrays. Chart shows how it looks like. I did not add the down-leg yet.

only_when = tr OR pk;

llc = SparseCompress( only_when, ll );
hlc = SparseCompress( only_when, hl );
dbc = SparseCompress( only_when, db );
hhc = SparseCompress( only_when, hh );
lhc = SparseCompress( only_when, lh );
dtc = SparseCompress( only_when, dt );

//uplegtop = ( hhc OR lhc )  AND BarsSince( llc ) > 2;
uplegtop = hhc AND BarsSince( llc ) > 2;
uplegtop = SparseExpand( only_when, uplegtop );
uplegbot = ll;

uplegtopr = Reverse( uplegtop );
uplegbotr = Reverse( uplegbot );

uplegtopr = ExRem( uplegtopr, uplegbotr );
uplegbotr = ExRem( uplegbotr, uplegtopr );
uplegtop = Reverse( uplegtopr );
uplegbot = Reverse( uplegbotr );

botx = ValueWhen( uplegbot, bi );
boty = ValueWhen( uplegbot, L );
topx = ValueWhen( uplegtop, bi );
topy = ValueWhen( uplegtop, H );

PlotShapes( IIf( uplegtop, shapeCircle, shapeNone ), colorRed, 0, H, 50 );
PlotShapes( IIf( uplegbot, shapeCircle, shapeNone ), colorGreen, 0, L, -50 );

for( i = lvb; i > fvb; i-- )
{
    if( uplegtop[i] )
    {
        line = LineArray( botx[i], boty[i], topx[i], topy[i] );
        Plot( IIf( line, line, Null ), "", colorAqua, styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 8 );
    }
}

2 Likes

added the down-leg (leg down)

only_when = tr OR pk;

llc = SparseCompress( only_when, ll );
hlc = SparseCompress( only_when, hl );
dbc = SparseCompress( only_when, db );
hhc = SparseCompress( only_when, hh );
lhc = SparseCompress( only_when, lh );
dtc = SparseCompress( only_when, dt );

// up leg
//uplegtop = ( hhc OR lhc )  AND BarsSince( llc ) > 2;
uplegtop = hhc AND BarsSince( llc ) > 2;
uplegtop = SparseExpand( only_when, uplegtop );
uplegbot = ll;

uplegtopr = Reverse( uplegtop );
uplegbotr = Reverse( uplegbot );
uplegtopr = ExRem( uplegtopr, uplegbotr );
uplegbotr = ExRem( uplegbotr, uplegtopr );
uplegtop = Reverse( uplegtopr );
uplegbot = Reverse( uplegbotr );

upbotx = ValueWhen( uplegbot, bi );
upboty = ValueWhen( uplegbot, prcl );
uptopx = ValueWhen( uplegtop, bi );
uptopy = ValueWhen( uplegtop, prch );

PlotShapes( IIf( uplegtop, shapeCircle, shapeNone ), colorRed, 0, H, 50 );
PlotShapes( IIf( uplegbot, shapeCircle, shapeNone ), colorGreen, 0, L, -50 );

// down leg
//dnlegbot = ( llc OR hlc )  AND BarsSince( hhc ) > 2;
dnlegbot = llc AND BarsSince( hhc ) > 2;
dnlegbot = SparseExpand( only_when, dnlegbot );
dnlegtop = hh;

dnlegtopr = Reverse( dnlegtop );
dnlegbotr = Reverse( dnlegbot );
dnlegbotr = ExRem( dnlegbotr, dnlegtopr );
dnlegtopr = ExRem( dnlegtopr, dnlegbotr );
dnlegtop = Reverse( dnlegtopr );
dnlegbot = Reverse( dnlegbotr );

dnbotx = ValueWhen( dnlegbot, bi );
dnboty = ValueWhen( dnlegbot, prcl );
dntopx = ValueWhen( dnlegtop, bi );
dntopy = ValueWhen( dnlegtop, prch );

PlotShapes( IIf( dnlegtop, shapeCircle, shapeNone ), colorRed, 0, H, 50 );
PlotShapes( IIf( dnlegbot, shapeCircle, shapeNone ), colorGreen, 0, L, -50 );

for( i = lvb; i > fvb; i-- )
{
    if( uplegtop[i] )
    {
        line = LineArray( upbotx[i], upboty[i], uptopx[i], uptopy[i] );
        Plot( IIf( line, line, Null ), "", colorAqua, styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 8 );
    }
    if( dnlegbot[i] )
    {
        line = LineArray( dntopx[i], dntopy[i], dnbotx[i], dnboty[i] );
        Plot( IIf( line, line, Null ), "", colorLightOrange, styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 8 );
    }    
}

3 Likes

here is some fully functioning code with the secondary Zig code added at the bottom

period = Param( "Period", 100, 5, 100, 1 );
uppercentageFactor = Param( "Upward Zig Factor", 2, 0.1, 10, 0.1 );
downpercentageFactor = Param( "Downward Zig Factor", 2, 0.1, 10, 0.1 );
priceswitch = ParamToggle( "Use Close or High and Low price", "Use Close|Use High and Low", 0 );
labelsswitchswing = ParamToggle( "Show Swing Labels", "Off|On", 0 );
labelsswitch = ParamToggle( "Show Pivot Labels", "Off|On", 1 );
showTrailline = ParamToggle( "Show Trail Line", "Off|On", 0 );

// build variable percentage array
//variablePercentage = StDev( 100 * ( H - L ) / ( ( H + L ) / 2 ), period );
variablePercentage = ATR( period ) / MA( C, period ) * 100;
uppercentage = uppercentageFactor * Ref( variablePercentage, -1 );
downpercentage = downpercentageFactor * Ref( variablePercentage, -1 );

bi = BarIndex();
fvb = FirstVisibleValue( bi );
lvb = LastVisibleValue( bi );
pk = tr = Buy = Sell = BuyPrice = SellPrice = 0;
ZigZag = line1 = line2 = Null;
trailarrayup = Null;
trailarraydn = Null;
mode = "";
SetBarsRequired( ( lvb - fvb ) * 2 );
sz = 8;
ft = "Arial Black";
clr = colorDefault;

if( priceswitch )
{
    prch = H;
    prcl = L;
    mode = "High/Low price";
}
else
{
    prch = C;
    prcl = C;
    mode = "Close price";
}

// if ticksize is not set in code or information window 0.01 is used
if( TickSize == 0 )
{
    TickSize = 0.01;
}

function percfluc( prc, perc )
{
    retprice = round( ( prc * perc / 100 ) / TickSize ) * TickSize;
    return retprice;
}

function calculatePivots()
{
    // initial condition trend is up (but -1 works also)
    trend = 1;
    topprc = prch[0];
    topidx = 0;
    botprc = prcl[0];
    botidx = 0;
    trailarrayup[period] = topprc - percfluc( topprc, downpercentage[period] );
    trailarraydn[period] = botprc + percfluc( botprc, uppercentage[period] );

    for( i = period + 1; i < BarCount; i++ )
    {
        if( trend > 0 )
        {
            // trend turning down, avoid same bar as the peak
            if( prcl[i] <= trailarrayup[i - 1] AND prch[i] < topprc )
            {
                pk[topidx] = 1;
                botprc = prcl[i];
                botidx = i;
                trend = -1;
                Sell[i] = 1;
                trailarraydn[i] = botprc + percfluc( botprc, uppercentage[i] );
                trailarrayup[i] = trailarrayup[i - 1];

                if( priceswitch )
                    SellPrice[i] = Min( O[i], trailarrayup[i] );
                else
                    SellPrice[i] = C[i];
            }
            else

                // still in uptrend and new top reached
                if( prch[i] >= topprc )
                {
                    topprc = prch[i];
                    topidx = i;
                    trailarrayup[i] = Max( trailarrayup[i - 1], prch[i] - percfluc( topprc, downpercentage[i] ) );
                }
                // continuation inside uptrend
                else
                {
                    trailarrayup[i] = Max( trailarrayup[i - 1], prch[i] - percfluc( prch[i], downpercentage[i] ) );
                }
        }
        else
            if( trend < 0 )
            {
                // trend turning up, avoid same bar as the trough
                if( prch[i] >= trailarraydn[i - 1] AND prcl[i] > botprc )
                {
                    tr[botidx] = 1;
                    topprc = prch[i];
                    topidx = i;
                    trend = 1;
                    Buy[i] = 1;
                    trailarrayup[i] = topprc - percfluc( topprc, downpercentage[i] );
                    trailarraydn[i] = trailarraydn[i - 1];

                    if( priceswitch )
                        BuyPrice[i] = Max( O[i], trailarraydn[i] );
                    else
                        BuyPrice[i] = C[i];
                }
                else

                    // still in downtrend and new trough reached
                    if( prcl[i] <= botprc )
                    {
                        botprc = prcl[i];
                        botidx = i;
                        trailarraydn[i] = Min( trailarraydn[i - 1], prcl[i] + percfluc( botprc, uppercentage[i] ) );
                    }
                    // continuation inside downtrend
                    else
                    {
                        trailarraydn[i] = Min( trailarraydn[i - 1], prcl[i] + percfluc( prcl[i], uppercentage[i] ) );
                    }
            }
    }
}

function calculateZigZag()
{
    // create ZIGZAG array line
    zigup = Flip( tr, pk );
    zigupLow = ValueWhen( tr, prcl, 1 );
    zigupHigh = ValueWhen( pk, prch, 0 );
    zigupLowIndex = ValueWhen( tr, bi, 1 );
    zigupHighIndex = ValueWhen( pk, bi, 0 );
    slopeup = IIf( zigup, ( zigupHigh - zigupLow ) / ( zigupHighIndex - zigupLowIndex ) , Null );
    zigupLine = IIf( zigup, zigupLow + slopeup * BarsSince( tr ), Null );

    zigdn = Flip( pk, tr );
    zigdnLow = ValueWhen( tr, prcl, 0 );
    zigdnHigh = ValueWhen( pk, prch, 1 );
    zigdnLowIndex = ValueWhen( tr, bi, 0 );
    zigdnHighIndex = ValueWhen( pk, bi, 1 );
    slopedn = IIf( zigdn, ( zigdnLow - zigdnHigh ) / ( zigdnLowIndex - zigdnHighIndex ) , Null );
    zigdnLine = IIf( zigdn, zigdnHigh + slopedn * BarsSince( pk ), Null );

    ZigZag = IIf( zigup, zigupLine, IIf( zigdn, zigdnLine, Null ) );
    ZigZag = IIf( bi > Max( LastValue( ValueWhen( tr, bi ) ), LastValue( ValueWhen( pk, bi ) ) ), Null, ZigZag );
}

function calculateLastSegments( )
{
    line1 = line2 = Null;
    lastidxpk = LastValue( ValueWhen( pk, bi ) );
    lastidxtr = LastValue( ValueWhen( tr, bi ) );
    lastvalpk = LastValue( ValueWhen( pk, prch ) );
    lastvaltr = LastValue( ValueWhen( tr, prcl ) );
    lastidxbuy = LastValue( ValueWhen( Buy, bi ) );
    lastidxsell = LastValue( ValueWhen( Sell, bi ) );
    valpk = LastValue( HighestSince( Ref( tr, -1 ), prch , 1 ) );
    idxpk = LastValue( ValueWhen( prch == valpk, bi ) );
    valtr = LastValue( LowestSince( Ref( pk, -1 ), prcl, 1 ) );
    idxtr = LastValue( ValueWhen( prcl == valtr, bi ) );

    if( lastidxsell > lastidxbuy AND lastidxsell > lastidxpk AND lastidxpk > lastidxtr )
    {
        x0 = lastidxpk;
        y0 = lastvalpk;
        x1 = idxtr;
        y1 = valtr;
        line1 = linedn = LineArray( x0, y0, x1, y1 );
        tr[idxtr] = 1;
        valpk = LastValue( HighestSince( Ref( tr, -1 ), prch, 1 ) );
        idxpk = LastValue( ValueWhen( prch == valpk, bi ) );
    }

    if( lastidxsell < lastidxbuy AND lastidxbuy > lastidxtr AND lastidxpk < lastidxtr )
    {
        x0 = lastidxtr;
        y0 = lastvaltr;
        x1 = idxpk;
        y1 = valpk;
        line1 = lineup = LineArray( x0, y0, x1, y1 );
        pk[idxpk] = 1;
        valtr = LastValue( LowestSince( Ref( pk, -1 ), prcl, 1 ) );
        idxtr = LastValue( ValueWhen( prcl == valtr, bi ) );
    }

    ZigZag = IIf( !IsEmpty( line1 ), line1, ZigZag );
}

SetChartBkColor( ColorRGB( 0, 0, 0 ) );
SetChartOptions( 0, chartShowArrows | chartShowDates );
Plot( C, "Price", colorWhite, styleCandle, Null, Null, 0, 0, 0 );

calculatePivots();
calculateZigZag();
calculateLastSegments();

Plot( zigzag, "ZigZag", colorGold, styleLine | styleNoLabel | styleNoRescale, Null, Null, 0, 1, 1 );
PlotShapes( shapeSmallCircle * tr, colorGreen, 0, L, -10 );
PlotShapes( shapeSmallCircle * pk, colorRed, 0, H, 10 );

if( labelsswitchSwing )
{
    Short = Sell;
    ShortPrice = SellPrice;
    Cover = Buy;
    CoverPrice = BuyPrice;

    BuyPrice = ValueWhen( Buy, BuyPrice );
    ShortPrice = ValueWhen( Short, ShortPrice );
    CoverPrice = ValueWhen( Cover, CoverPrice );
    SellPrice = ValueWhen( Sell, SellPrice );

    longResult = Nz( Prec( IIf( Sell, SellPrice - ValueWhen( Buy, BuyPrice ), 0 ), 2 ) );
    shortResult = Nz( Prec( IIf( Cover, ValueWhen( Short, ShortPrice ) - CoverPrice, 0 ), 2 ) );
    totalResult = LastValue( Cum( longResult ) + Cum( shortResult ) );

    GfxSetZOrder( 0 );
    GfxSetCoordsMode( 1 );
    shiftLabels = 10;//Param( "Shift Labels", 10, -20, 100, 1 );
    upColor = colorAqua;
    dnColor = colorGold;

    PlotShapes( shapeSmallUpTriangle * Buy, colorAqua, 0, L, -20 );
    PlotShapes( shapeSmallDownTriangle * Sell, colorGold, 0, H, -20 );
    PlotShapes( shapeSmallCircle * Buy, colorAqua, 0, BuyPrice, 0 );
    PlotShapes( shapeSmallCircle * Sell, colorGold, 0, SellPrice, 0 );

    for( i = fvb; i <= lvb; i++ )
    {
        if( Buy[i] && Cover[i] )
        {
            str = "Buy: " + BuyPrice[i] + " (" + shortResult[i] + ")";
            PlotTextSetFont( str, ft, sz, i, L[i], upColor, clr, -35 - shiftLabels );
            //str = "Cover: " + CoverPrice[i] + " (" + shortResult[i] + ")";
            //PlotTextSetFont( str, ft, sz, i, L[i], upColor, clr, -50 - shiftLabels );
        }

        if( !Buy[i] && Cover[i] )
        {
            str = "Cover: " + CoverPrice[i] + " (" + shortResult[i] + ")";
            PlotTextSetFont( str, ft, sz, i, L[i], upColor, clr, -35 - shiftLabels );
        }

        if( Buy[i] && !Cover[i] )
        {
            str = "Buy: " + BuyPrice[i];
            PlotTextSetFont( str, ft, sz, i, L[i], upColor, clr, -35 - shiftLabels );
        }

        if( Short[i] && Sell[i] )
        {
            str = "Short: " + ShortPrice[i] + " (" + longResult[i] + ")";
            PlotTextSetFont( str, ft, sz, i, H[i], dnColor, clr, 25 + shiftLabels );
            //str = "Sell: " + SellPrice[i] + " (" + longResult[i] + ")";
            //PlotTextSetFont( str, ft, sz, i, H[i], dnColor, clr, 40 + shiftLabels );
        }

        if( !Short[i] && Sell[i] )
        {
            str = "Sell: " + SellPrice[i] + " (" + longResult[i] + ")";
            PlotTextSetFont( str, ft, sz, i, H[i], dnColor, clr, 25 + shiftLabels );
        }

        if( Short[i] && !Sell[i] )
        {
            str = "Short: " + ShortPrice[i];
            PlotTextSetFont( str, ft, sz, i, H[i], dnColor, clr, 25 + shiftLabels );
        }
    }
}

if( showTrailline )
{
    Plot( trailarrayup, "trail up", colorLightBlue, styleDots | styleStaircase | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 1 );

    if( !IsEmpty( trailarrayup[BarCount - 1] ) )
    {
        PlotTextSetFont( "" + trailarrayup[BarCount - 1 ], ft, sz, BarCount + 1, trailarrayup[BarCount - 1], colorLightBlue, clr, 0 );
    }

    Plot( trailarraydn, "trail dn", colorOrange, styleDots | styleStaircase | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 1 );

    if( !IsEmpty( trailarraydn[BarCount - 1] ) )
    {
        PlotTextSetFont( "" + trailarraydn[BarCount - 1], ft, sz, BarCount + 1, trailarraydn[BarCount - 1], colorOrange, clr, 0 );
    }
}

Title =
    "Price: " + C
    + EncodeColor( colorGold ) + " | ZigZag: " + ZigZag
    + EncodeColor( colorBrightGreen ) + " | Up Percentage (%): " + Prec( uppercentage, 2 )
    + EncodeColor( colorRed ) + " | Down Percentage (%): " + Prec( downpercentage, 2 )
    + EncodeColor( colorLightBlue ) + " | Trail Array Up: " + trailarrayup
    + EncodeColor( colorOrange ) + " | Trail Array Down: " + trailarraydn
    + EncodeColor( colorGrey40 ) + " | Mode: " + mode;

for( i = 0; i < 3; i++ )
{
    VarSet( "px" + i, ValueWhen( pk, bi, i ) );
    VarSet( "tx" + i, ValueWhen( tr, bi, i ) );
    VarSet( "ph" + i, ValueWhen( pk, H, i ) );
    VarSet( "tl" + i, ValueWhen( tr, L, i ) );
}

ll = tr AND tl1 < tl2;
hl = tr AND tl1 > tl2;
hh = pk AND ph1 > ph2;
lh = pk AND ph1 < ph2;
dt = pk AND ph1 == ph2;
db = tr AND tl1 == tl2;

if( labelsswitch )
{
    str1 = "";

    for( i = fvb; i <= lvb; i++ )
    {
        if( pk[i] )
        {
            if( dt[i] )
                str1 = "DT";
            else
                if( hh[i] )
                    str1 = "HH";
                else
                    if( lh[i] )
                        str1 = "LH";

            PlotTextSetFont( str1, ft, sz, i, H[i], colorRed, clr, sz * 3 );
            //PlotTextSetFont( "" + prch[i], ft, sz, i, H[i], colorRed, clr, sz * 5 );
            //PlotTextSetFont( "" + CumVolumeUpMBoxChart[i], ft, sz, i, H[i], colorBlue, colorWhite, sz * 7 );
        }

        if( tr[i] )
        {
            str1 = "";

            if( db[i] )
                str1 = "DB";
            else
                if( ll[i] )
                    str1 = "LL";
                else
                    if( hl[i] )
                        str1 = "HL";

            PlotTextSetFont( str1, ft, sz, i, L[i], colorBlue, clr, -sz * 4 );
            //PlotTextSetFont( "" + prcl[i], ft, sz, i, L[i], colorGreen, clr, -sz * 6 );
            //PlotTextSetFont( "" + CumVolumeDnMBoxChart[i], ft, sz, i, L[i], colorRed, colorWhite, -sz * 8 );
        }
    }
}

// secondary Zig
only_when = tr OR pk;

llc = SparseCompress( only_when, ll );
hlc = SparseCompress( only_when, hl );
dbc = SparseCompress( only_when, db );
hhc = SparseCompress( only_when, hh );
lhc = SparseCompress( only_when, lh );
dtc = SparseCompress( only_when, dt );

// up leg
//uplegtop = ( hhc OR lhc )  AND BarsSince( llc ) > 2;
uplegtop = hhc AND BarsSince( llc ) > 2;
uplegtop = SparseExpand( only_when, uplegtop );
uplegbot = ll;

uplegtopr = Reverse( uplegtop );
uplegbotr = Reverse( uplegbot );
uplegtopr = ExRem( uplegtopr, uplegbotr );
uplegbotr = ExRem( uplegbotr, uplegtopr );
uplegtop = Reverse( uplegtopr );
uplegbot = Reverse( uplegbotr );

upbotx = ValueWhen( uplegbot, bi );
upboty = ValueWhen( uplegbot, prcl );
uptopx = ValueWhen( uplegtop, bi );
uptopy = ValueWhen( uplegtop, prch );

PlotShapes( IIf( uplegtop, shapeCircle, shapeNone ), colorRed, 0, H, 50 );
PlotShapes( IIf( uplegbot, shapeCircle, shapeNone ), colorGreen, 0, L, -50 );

// down leg
//dnlegbot = ( llc OR hlc )  AND BarsSince( hhc ) > 2;
dnlegbot = llc AND BarsSince( hhc ) > 2;
dnlegbot = SparseExpand( only_when, dnlegbot );
dnlegtop = hh;

dnlegtopr = Reverse( dnlegtop );
dnlegbotr = Reverse( dnlegbot );
dnlegbotr = ExRem( dnlegbotr, dnlegtopr );
dnlegtopr = ExRem( dnlegtopr, dnlegbotr );
dnlegtop = Reverse( dnlegtopr );
dnlegbot = Reverse( dnlegbotr );

dnbotx = ValueWhen( dnlegbot, bi );
dnboty = ValueWhen( dnlegbot, prcl );
dntopx = ValueWhen( dnlegtop, bi );
dntopy = ValueWhen( dnlegtop, prch );

PlotShapes( IIf( dnlegtop, shapeCircle, shapeNone ), colorRed, 0, H, 50 );
PlotShapes( IIf( dnlegbot, shapeCircle, shapeNone ), colorGreen, 0, L, -50 );

for( i = lvb; i > fvb; i-- )
{
    if( uplegtop[i] )
    {
        line = LineArray( upbotx[i], upboty[i], uptopx[i], uptopy[i] );
        Plot( IIf( line, line, Null ), "", colorAqua, styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 8 );
    }

    if( dnlegbot[i] )
    {
        line = LineArray( dntopx[i], dntopy[i], dnbotx[i], dnboty[i] );
        Plot( IIf( line, line, Null ), "", colorLightOrange, styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 8 );
    }
}
4 Likes

Hi Mr. Empottasch. First of all sorry for the late response. I was hopeless and didn’t checked the forum. I am very grateful to you for your code and your hard work behind it. Code is wonderful. Can’t pay back what you have done for me. But as a gift I am documenting my one of techniques in word file to share with you. Its not a holy grail but its works pretty well and enough to have a pretty good financial life. It will take a few days to fully document it, as due to injury its difficult to type for me. But I am going do that and after completion will share to you. Eventually will share more techniques I frequently use to make a living. Once again, I am very grateful and obliged for your help. You make a dream come true for me. If possible please share your email in my email address. I will send you the word file. My English is not good. Pease forgive for that.

Thanks to Tomasz also. You have created amazing software and always working hard to improve it more and more with every passing year. I am in love with AmiBroker. I just can’t imagine to work in any other technical-analysis software. Thanks to whole AmiBroker community also, who are day & night supporting and helping other members selflessly.

ok thanks, i will be looking forward to your method. Will send you a message in the PM (Messages) section.

I think my code does not really need the sparse functions. Initially I wanted to solve it differently. Then with the sparse functions already in place I changed my strategy. I will probably change the code a bit later. I have seen some things in the chart that I want to change. Also I can make a continuous ZigZag function by replacing the gaps in the secondary with the primary zig function. So I will update the code later.

on a closer look the sparse functions indeed are needed.

1 Like

sometimes the secondary legs do not look right as you can see in the chart. However, they follow the definition I used and that is that an up-leg has as a start a LL and in the end a HH and in between only HL. So when using this definition I think the code is correct.

1 Like

you can make the secondary ZigZag a continuous function by replacing the bottom part of the code with this:

secondaryZigZag = Null;

for( i = lvb; i > fvb; i-- )
{
    if( uplegtop[i] )
    {
        line = LineArray( upbotx[i], upboty[i], uptopx[i], uptopy[i] );
        Plot( IIf( line, line, Null ), "", colorAqua, styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 8 );
        secondaryZigZag = IIf( line, line, secondaryZigZag );
    }

    if( dnlegbot[i] )
    {
        line = LineArray( dntopx[i], dntopy[i], dnbotx[i], dnboty[i] );
        Plot( IIf( line, line, Null ), "", colorLightOrange, styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 8 );
        secondaryZigZag = IIf( line, line, secondaryZigZag );
    }
}

secondaryZigZag = IIf( secondaryZigZag, secondaryZigZag, zigzag );
Plot( secondaryZigZag, "", colorGold, styleLine | styleNoLabel | styleNoRescale, Null, Null, 0, 0, 8 );

also lines 309-315 need prch and prcl instead of H and L

for( i = 0; i < 3; i++ )
{
    VarSet( "px" + i, ValueWhen( pk, bi, i ) );
    VarSet( "tx" + i, ValueWhen( tr, bi, i ) );
    VarSet( "ph" + i, ValueWhen( pk, prch, i ) );
    VarSet( "tl" + i, ValueWhen( tr, prcl, i ) );
}
5 Likes

Hello Mr. Edward Pottasch

First of all, Thanks for making the zigzag continious.
After applying the your last update my chart was was'nt showing any golden line's of zigzag between HigherHigher to LowerLow move in downleg of secondary zigzag nor the LowerLow to HigherHigh move in upleg of secondary move.
Moreover when I was setting any percentage below 1%, the chart was showing the error "Warning 502. You are calling Plot()/PlotOHLC() function over 500 times, it is highly inefficient. Reduce number of calls".
So in order to get rid of this error I tried to modify your code and then strangely it started plotting those missing legs also. I was very happy for that. But the problem is that I am still getting the same 'Warning 502'. Any suggestion ? Please help. Below is the modified code.

_SECTION_BEGIN( "Secondary-ZigZag" );

Secondary_ZZ_Line_Width = Param( "Secondary ZZ-Line's Width", 8, 1, 5, 1 );
Secondary_ZZ_Style = ParamStyle( "Secondary ZZ-Style", styleLine | styleNoRescale | styleNoLabel );
Secondary_ZZ_Up_Color = ParamColor( "Secondary-ZZ Up-Color", colorBlue );
Secondary_ZZ_Down_Color = ParamColor( "Secondary-ZZ Down-Color", colorCustom11 );
Secondary_ZigZag_Color = ParamColor( "Secondary-ZigZag Color", colorGold );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Secondary_ZigZag_Up = Null;
Secondary_ZigZag_Down = Null;
Combined_Secondary_ZZ_Line_Up = Null;
Combined_Secondary_ZZ_Line_Down = Null;


if( Secondary_ZigZag_Switch )
{
    for( i = 0; i < BarCount - 1; i++ )
    {
        if( ZZ_UpLegTop[i] )
        {
            Secondary_ZZ_Line_Up = LineArray( ZZ_UpBottom_x[i], ZZ_UpBottom_y[i], ZZ_UpTop_x[i], ZZ_UpTop_y[i] );
            Combined_Secondary_ZZ_Line_Up = IIf( IsNull( Secondary_ZZ_Line_Up ), Combined_Secondary_ZZ_Line_Up, Secondary_ZZ_Line_Up ); // combine lines
            Plot( IIf( Combined_Secondary_ZZ_Line_Up, Combined_Secondary_ZZ_Line_Up, Null ), "", Secondary_ZZ_Up_Color, Secondary_ZZ_Style, Null, Null, 0, ZZ_Zorder, Secondary_ZZ_Line_Width );
            Secondary_ZigZag_Up = IIf( Combined_Secondary_ZZ_Line_Up,  Combined_Secondary_ZZ_Line_Up, Secondary_ZigZag_Up );
        }

        if( ZZ_DownLegBottom[i] )
        {
            Secondary_ZZ_Line_Down = LineArray( ZZ_DownTop_x[i], ZZ_DownTop_y[i], ZZ_DownBottom_x[i], ZZ_DownBottom_y[i] );
            Combined_Secondary_ZZ_Line_Down = IIf( IsNull( Secondary_ZZ_Line_Down ), Combined_Secondary_ZZ_Line_Up, Secondary_ZZ_Line_Down ); // combine lines
            Plot( IIf( Combined_Secondary_ZZ_Line_Down, Combined_Secondary_ZZ_Line_Down, Null ), "", Secondary_ZZ_Down_Color, Secondary_ZZ_Style, Null, Null, 0, ZZ_Zorder, Secondary_ZZ_Line_Width );
            Secondary_ZigZag_Down = IIf( Combined_Secondary_ZZ_Line_Down, Combined_Secondary_ZZ_Line_Down, Secondary_ZigZag_Down );
        }
    }


}


Secondary_ZigZag = IIf( Secondary_ZigZag_Up, Secondary_ZigZag_Up, IIf( Secondary_ZigZag_Down, Secondary_ZigZag_Down, nZigZag ) );
Plot( Secondary_ZigZag, "", Secondary_ZigZag_Color, Secondary_ZZ_Style, Null, Null, 0, ZZ_Zorder, Secondary_ZZ_Line_Width );


_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Secondary-ZigZag's Pivot-Dots" );

GfxSetZOrder( 12 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Secondary_ZZ_Upper_Shape_Color = ParamColor( "Secondary-ZZ Upper-Shape Color", colorRed );
Secondary_ZZ_Lower_Shape_Color = ParamColor( "Secondary-ZZ Lower-Shape Color", colorBrightGreen );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


if( Secondary_ZZ_Pivot_Shape_Switch )
{
    PlotShapes( IIf( ZZ_UpLegTop, shapeCircle, shapeNone ), Secondary_ZZ_Upper_Shape_Color, 0, High, 10 );
    PlotShapes( IIf( ZZ_UpLegBottom, shapeCircle, shapeNone ), Secondary_ZZ_Lower_Shape_Color, 0, Low, -10 );
}


_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx