Kindly Guide: regarding a loop generated problem

I always wanted to have a zigzag where I can have peak-trough on same-bar.
With my little knowledge of AFL I somehow succeded in creating a zigzag using low-level graphics.
This zigzag fulfills my trading needs. On a visual basis everything is fine.
But due to particular section now I am unable to use the peak-trough for another applications.
The code is simple, well-organized and self-explainatory.

My problem is with a section named " _SECTION_BEGIN( "Find Missed Peaks-Troughs" ) ".
The three line comments at the beginning of this section explains my problem.

After applying the code of this section it became impossible for me to make any further use of peak-trough values and their indexes.

I am stucked. Kindly guide me for the solution of this problem.
Especially looking forward to experts: @fxshrat, @beppe, @Panos @Milosz

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Date-Time etc." );

RequestTimedRefresh( 1 );

TTDC = ParamColor( "Title-Text's Default-Color", colorWhite );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

MT_Start = BeginValue( BarIndex() );
MT_End = EndValue( BarIndex() );
MT_Periods = MT_End - MT_Start;
MT_ValueStart = BeginValue( C );
MT_ValueEnd = EndValue( C );
MT_Difference = MT_ValueEnd - MT_ValueStart;
MT_Percentage = NumToStr( ( ( MT_Difference / MT_ValueStart ) * 100 ), 1.2 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function GetSecondNum()
{
    Time = Now( 4 );
    Seconds = int( Time % 100 );
    Minutes = int( Time / 100 % 100 );
    Hours = int( Time / 10000 % 100 );
    SecondNum = int( Hours * 60 * 60 + Minutes * 60 + Seconds );
    return SecondNum;
}

TimeFrame = Interval();
SecNumber = GetSecondNum();
NewPeriod = SecNumber % TimeFrame == 0;
SecsLeft = SecNumber - int( SecNumber / TimeFrame ) * TimeFrame;
SecsToGo = TimeFrame - SecsLeft;

if( NewPeriod )
{
    Say( "New period" );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

LastBar_Price = EndValue( Close );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

SetChartOptions( 0, chartShowArrows | chartShowDates );
//TimeFrame = in1Minute * Param( "Time Frame (min)", 5, 1, 1440 * 10, 1 ); // 1440 minutes is 1 day
TimeFrame = in1Minute * Interval() / 60 * 1;  // Param( "Chart Time Frame Factor", 1, 1, 10, 1 ); // factor 1 uses timeframe of chart
_N( Title = EncodeColor( TTDC ) + /* GfxSetTextColor(Text_Background_Color) + */ StrFormat( "Symbol-Name  =  {{NAME}}  ||  Visible-Chart-Area's  Date-&-Time  =  {{DATE}}  ||  Open %g  |  High %g  |  Low %g  |  Close %g  |  ROC (%.1f%%)  || " +
            "                                                                                  Last-Price  =  " + LastBar_Price + "\n TimeFrame: " + TimeFrame / 60 + " Minutes | " + TimeFrame / 3600 + " Hours | " + TimeFrame / ( 3600 * 24 ) + " Days  || " +
            " Total-Bars  =  " + MT_Periods + "  ||  Total %%Change  =  " + MT_Percentage + "  ||  My Machine-Time  =  " + Now( 2 ) + "  ||  CountDown to Bar-Close  =  " + SecsToGo +
            "{{VALUES}} ", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// SetBarsRequired( -2, -2 );
Bi = BarIndex();
BC = BarCount - 1;

xCum = Cum( 1 );

FvB = FirstVisibleValue( Bi );
LvB = LastVisibleValue( Bi );

StartBar = BeginValue( Bi );
EndBar = EndValue( Bi );

SelectedBar = SelectedValue( Bi );
LastBar = LastValue( Bi );

SetBarsRequired( ( LVB - FVB ) * 4 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

GraphXSpace = Param( "GraphXSpace", 10, 0, 100, 1 );
GraphLabelDecimals = Param( "Graph-Label's Decimals", 3, 0, 100, 1 );
Decimals = ( Param( "Decimals", 3, 0, 7, 1 ) / 10 ) + 1;

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Font_Name = ParamList( "Font", "Tahoma|Helvetica|Arial Black|Verdana|Courier New|Times New Roman|Open Sans|Compact|Segoe UI|DejaVu Sans", 1 );
Text_Size = Param( "Text-Size", 8, 5, 20, 1 );
Text_Color = ParamColor( "Gfx Background-Color", colorWhite );
//Text_Background_Color = ParamColor( "Text Background-Color", colorBlack );
Separation_of_Letters = Param( "Separation of Letters", 3, 1, 10, 1 );
Dashed_Line_Number = Param( "Dashed Line Number", 2, 1, 4, 1 );
Gfx_Background_Color = ParamColor( "Gfx Background Default-Color", colorBlack );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
/*
function ParamOptimize( Pname, DefaultValue, MinValue, MaxValue, Step )
{
    return Optimize( Pname,
                     Param( pname, DefaultValue, MinValue, MaxValue, Step ),
                     MinValue, MaxValue, Step );
}
*/
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Session Seprator Vertical-Lines
/*
Start_Time = 093000;
End_Time = 153000;

Day_Separator = Day() != Ref( Day(), -1 );
In_Session =  timenum() >= Start_Time && timenum() <= End_Time;
End_Session = timenum() >= End_Time;
End_Session = ( End_Session - Ref( End_Session, -1 ) ) == 1 OR Ref( Day_Separator, 1 );;
Start_Session = timenum() >= Start_Time;
Start_Session = ( Start_Session - Ref( Start_Session, -1 ) ) == 1;
*/


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Chart's Background-Colors" );


Outer_Panel_Color = ParamColor( "Outer Panel Color", colorDarkGrey );

InnerPanel_UpperHalf_Color = ParamColor( "Inner-Panel Upper-Half's Color", colorDarkGrey );
InnerPanel_LowerHalf_Color = ParamColor( "Inner-Panel Lower-Half's Color", colorDarkGrey );

Chart_Background_Color = ParamColor( "Chart Background Color", colorDarkGrey );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

SetChartBkColor( Outer_Panel_Color ); // color of outer border
SetChartBkGradientFill( InnerPanel_UpperHalf_Color, InnerPanel_LowerHalf_Color ); // color of inner panel
SetChartBkColor( Chart_Background_Color );


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Style of Price" );


Price_Chart_DisplaySwitch = ParamToggle( "Display Price-Chart", "Off|On", 1 );
Price_Chart_Style = ParamList( "Price-Chart's Style", "Neo-Candle|Meta-Candle|Bar|Line", 0 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Price_Zorder = Param( "Price-Zorder", 1, -5, 5, 1 );
Price_Line_Width = Param( "Price-Line's Width", 2, 1, 5, 1 );
Price_Style = ParamStyle( "Price_Style", styleCandle );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Doji_Color = ParamColor( "Doji Color", colorWhite );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Bar-Color Options
Price_Bull_Color = ParamColor( "Price Bull Color", colorTeal );
Price_Bear_Color =  ParamColor( "Price Bear Color", colorOrange );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Meta-Candle Color-Options
Price_Bull_MetaColor = ParamColor( "Price Bull MetaColor", colorWhite );
Price_Bear_MetaColor =  ParamColor( "Price Bear MetaColor", colorOrange );
Price_Internal_MetaColor = ParamColor( "Price Internal MetaColor", colorTeal );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Neo-Candle Color-Options
Doji_Bar_Color = ParamColor( "Doji-Bar Color", colorWhite );

BullBar_Color_A =  ParamColor( "Bull-Bar Color-A", colorTeal );
BearBar_Color_A = 	ParamColor( "Bear-Bar Color-A", colorOrange );

BullBar_Color_B = ParamColor( "Bull-Bar Color-B", colorWhite );
BearBar_Color_B = ParamColor( "Bear-Bar Color-B", colorOrange );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Price_Title = "";

// Bar Color-Conditions
Price_Color = IIf( Close > Open, Price_Bull_Color, IIf( Close < Open, Price_Bear_Color, Doji_Color ) );

// Meta-Candle Color-Conditions
Price_MetaColor = IIf( Close > Open, Price_Bull_MetaColor, IIf( Close < Open, Price_Bear_MetaColor, Doji_Color ) );
Price_Inside_MetaColor = IIf( Close < Open, Price_MetaColor, Price_Internal_MetaColor );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( Price_Chart_DisplaySwitch )
{
    switch( Price_Chart_Style )
    {
        case "Meta-Candle":
            SetBarFillColor( Price_Inside_MetaColor );
            PlotOHLC( Open, High, Low, Close, Price_Title, Price_MetaColor, Price_Style, 0, -5, 0, Price_Zorder );
            break;

        case "Bar":
            PriceStyle = styleBar;
            PlotOHLC( Open, High, Low, Close, Price_Title, Price_Color, PriceStyle | styleThick, 0, -5, 0, Price_Zorder, Price_Line_Width );
            break;

        case "Line":
            PriceStyle = styleLine;
            Price_Color = IIf( Close >= Open, Price_Bull_Color, Price_Bear_Color );
            SetBarFillColor( Price_Color );
            PlotOHLC( Open, High, Low, Close, Price_Title, Price_Color, PriceStyle | styleDots | styleThick, 0, -5, 0, Price_Zorder, Price_Line_Width );
            break;

        case "Neo-Candle":
            SetBarFillColor( IIf( Close > Open, BullBar_Color_A, IIf( Close < Open, BearBar_Color_A, Doji_Bar_Color ) ) );
            PlotOHLC( Open, High, Low, Close, Price_Title, IIf( Close > O, BullBar_Color_B, IIf( Close < Open, BearBar_Color_B, Doji_Bar_Color ) ),
                      Price_Style, Null, Null, 0, Price_Zorder, Price_Line_Width );
            break;

        default:
            SetBarFillColor( Price_Color );
            Price_Color = cLine;
            break;
    }
}


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Price-Mode" );


PriceArrayMode_Switch = ParamToggle( "Use Close or High and Low price", "Use Close|Use High and Low", 1 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( PriceArrayMode_Switch == 1 )
{
    PaH = High;
    PaL = Low;
}
else
    if( PriceArrayMode_Switch == 0 )
    {
        PaH = C;
        PaL = C;
    }



_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx



_SECTION_BEGIN( "Bars & Swings" );


Missed_High_Low_HandleSwitch = ParamToggle( "Include Missed Highs-&-Lows ?", "No | Yes", 0 );
Number_of_Bars_for_UpSwing = Param( "Number-of-Bars for ZigZag-Swing", 1, 1, 10, 1 );
Number_of_Bars_for_DownSwing = Number_of_Bars_for_UpSwing; // Param( "Number-of-Bars for DownSwing", 1, 1, 5, 1 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

UpBar = PaH > Ref( PaH, -1 ) and PaL >= Ref( PaL, -1 );
DownBar = PaH <= Ref( PaH, -1 ) and PaL < Ref( PaL, -1 );
OutBar = PaH > Ref( PaH, -1 ) AND PaL < Ref( PaL, -1 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

UpSwing = Sum( UpBar, Number_of_Bars_for_UpSwing ) == Number_of_Bars_for_UpSwing;
DownSwing = Sum( DownBar, Number_of_Bars_for_DownSwing ) == Number_of_Bars_for_DownSwing;


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


// This section's code is not mine. A online friend shared a code and I extracted it from his code.
// Already seeked his permission before sharing it here online. Many thanks to him for his kindness.
// Breakout-section is placed below the 'UpSwing-start' AND 'DownSwing-start' sections because then this code is generating better peaks & troughs.
// Changes due to this suffle are very subtle and are observable only when one notices all the fine details of zigzag.

_SECTION_BEGIN( "Calculate Peak-Trough" );


xPeak = xTrough = 0;
xPeak_High = 0;
xTrough_Low = 1e5;
Ups = Downs = 0;
IdxHigh = IdxLow = 0;
High_PriceArray = Low_PriceArray = 0;
Breakout_High = Breakout_Low = 0;
UpSwing_Start = DownSwing_Start = 0;

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx




for( i = 0; i < BarCount; i++ )
{
    // UpSwing start
    if( UpSwing[i] AND Ups == 0 )
    {
        IdxHigh = i;
        High_PriceArray = PaH[i];
        Ups = 1;
        Downs = 0;
        UpSwing_Start[i] = 1;

        xTrough[IdxLow] = 1;
        xTrough_Low[IdxLow] = PaL[IdxLow];
    }

    else

        // UpSwing continuation
        if( Ups == 1 AND PaH[i] >= High_PriceArray )
        {
            IdxHigh = i;
            High_PriceArray = PaH[i];
        }

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    // DownSwing start
    if( DownSwing[i] AND Downs == 0 )
    {
        IdxLow = i;
        Low_PriceArray = PaL[i];
        Ups = 0;
        Downs = 1;
        DownSwing_Start[i] = 1;

        xPeak[IdxHigh] = 1;
        xPeak_High[IdxHigh] = PaH[IdxHigh];
    }
    else

        // DownSwing continuation
        if( Downs == 1 AND PaL[i] <= Low_PriceArray )
        {
            IdxLow = i;
            Low_PriceArray = PaL[i];
        }

    // breakout lower without swinglow
    if( Ups == 1 AND PaL[i] < Low_PriceArray AND !UpSwing[i] )
    {
        Breakout_Low[i] = 1;
        DownSwing[i] = 1;
        DownSwing_Start[i] = 1;

        IdxLow = i;
        Low_PriceArray = PaL[i];
        Ups = 0;
        Downs = 1;

        xPeak[IdxHigh] = 1;
        xPeak_High[IdxHigh] = High_PriceArray;
    }

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    // breakout higher without swinghigh
    if( Downs == 1 AND PaH[i] > High_PriceArray AND !DownSwing[i] )
    {
        Breakout_High[i] = 1;
        UpSwing[i] = 1;
        UpSwing_Start[i] = 1;

        IdxHigh = i;
        High_PriceArray = PaH[i];
        Ups = 1;
        Downs = 0;

        xTrough[IdxLow] = 1;
        xTrough_Low[IdxLow] = Low_PriceArray;
    }
}


_SECTION_END();


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


// I coded this display is to help myself to understand the outbar-points because Most of the zigzag's problems are found at outside-bars.
// Here, I have invented new terms to expand the concept of outside-bars, for ease of handling.
// As per best of my information, a few of these concepts about outbars might not be in available techinical-analysis theories.

_SECTION_BEGIN( "Outside-Bar Display" );


OutBar_DisplaySwitch = ParamToggle( "Display Shapes 'When OutBar' ?", "No|Yes", 0 );
OutBar_Shape_Color = ParamColor( "OutBar Shape-Color", colorWhite );
xAbsolute_OutBar_DisplaySwitch = ParamToggle( "Display Shapes 'When xAbsolute-OutBar' ?", "No|Yes", 0 );
xAbsolute_OutBar_Shape_Color = ParamColor( "xAbsolute-OutBar Shape-Color", colorGold );
xPeakBar_Absolute_OutBar_DisplaySwitch = ParamToggle( "Display Shapes 'When xPeak-Bar is also xAbsolute-OutBar' ?", "No|Yes", 0 );
xPeakBar_Absolute_OutBar_Shape_Color = ParamColor( "'xPeakBar-Absolute-OutBar' Shape-Color", colorBrightGreen );
xTroughBar_Absolute_OutBar_DisplaySwitch = ParamToggle( "Display Shapes 'When xTrough-Bar is also xAbsolute-OutBar' ?", "No|Yes", 0 );
xTroughBar_Absolute_OutBar_Shape_Color = ParamColor( "'xTroughBar-Absolute-OutBar' Shape-Color", colorOrange );
xPeakTrough_SameBar_Absolute_OutBar_DisplaySwitch = ParamToggle( "Display Shapes 'When xPeakTrough-@-SameBar is also xAbsolute-OutBar' ?", "No|Yes", 0 );
xPeakTrough_SameBar_Absolute_OutBar_Shape_Color = ParamColor( "'xPeakTrough-SameBar is Absolute-OutBar' Shape-Color", colorBlue );
xPeakTrough_SameBar_DisplaySwitch = ParamToggle( "Display Shapes 'When xPeakTrough-@-SameBar' ?", "No|Yes", 0 );
xPeakTrough_SameBar_Shape_Color = ParamColor( "'xPeakTrough_SameBar' Shape-Color", colorAqua );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xRecent_Pivot_Peak =  ValueWhen( xPeak, Bi, 1 ) > ValueWhen( xTrough, Bi, 1 );
xRecent_Pivot_Trough = ValueWhen( xTrough, Bi, 1 ) > ValueWhen( xPeak, Bi, 1 );

xRecent_PreviousPivot_Peak = ValueWhen( xPeak, Bi, 2 ) > ValueWhen( xTrough, Bi, 2 ) AND ValueWhen( xTrough, Bi, 1 ) > ValueWhen( xPeak, Bi, 2 ) AND ValueWhen( xPeak, Bi, 1 ) > ValueWhen( xTrough, Bi, 1 );
xRecent_PreviousPivot_Trough = ValueWhen( xTrough, Bi, 2 ) > ValueWhen( xPeak, Bi, 2 ) AND ValueWhen( xPeak, Bi, 1 ) > ValueWhen( xTrough, Bi, 2 ) AND ValueWhen( xTrough, Bi, 1 ) > ValueWhen( xPeak, Bi, 1 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

OutBar = PaH > Ref( PaH, -1 ) AND PaL < Ref( PaL, -1 );
OutBar_High = ValueWhen( OutBar, PaH );
OutBar_Low = ValueWhen( OutBar, PaL );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


xAbsolute_OutBar = OutBar AND( ValueWhen( xPeak, PaH, 1 ) < ValueWhen( OutBar, PaH ) AND ValueWhen( xTrough, PaL, 1 ) > ValueWhen( OutBar, PaL ) );


xPeakBar_Absolute_OutBar = OutBar AND( ValueWhen( xPeak, PaH, 1 ) == ValueWhen( OutBar, PaH ) AND ValueWhen( xTrough, PaL, 1 ) != ValueWhen( OutBar, PaL ) ) AND
                           ( ValueWhen( xPeak, PaH, 2 ) < ValueWhen( OutBar, PaH ) AND ValueWhen( xTrough, PaL, 1 ) > ValueWhen( OutBar, PaL ) );

xTroughBar_Absolute_OutBar = OutBar AND( ValueWhen( xPeak, PaH, 1 ) != ValueWhen( OutBar, PaH ) AND ValueWhen( xTrough, PaL, 1 ) == ValueWhen( OutBar, PaL ) ) AND
                             ( ValueWhen( xPeak, PaH, 1 ) < ValueWhen( OutBar, PaH ) AND ValueWhen( xTrough, PaL, 2 ) > ValueWhen( OutBar, PaL ) );

xPT_SameBar_Absolute_OutBar = OutBar AND( ValueWhen( xPeak, PaH, 1 ) == ValueWhen( OutBar, PaH ) AND ValueWhen( xTrough, PaL, 1 ) == ValueWhen( OutBar, PaL ) ) AND
                              ( ValueWhen( xPeak, PaH, 2 ) < ValueWhen( OutBar, PaH ) AND ValueWhen( xTrough, PaL, 2 ) > ValueWhen( OutBar, PaL ) );

xPeakTrough_SameBar = xPeak AND xTrough;

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( OutBar_DisplaySwitch == 1 )
{
    PlotShapes( shapeSquare * OutBar, OutBar_Shape_Color, 0, High, 70 );
    PlotShapes( shapeSquare * OutBar, OutBar_Shape_Color, 0, Low, -70 );
}

if( xAbsolute_OutBar_DisplaySwitch == 1 )
{
    PlotShapes( shapeSquare * xAbsolute_OutBar, xAbsolute_OutBar_Shape_Color, 0, High, 60 );
    PlotShapes( shapeSquare * xAbsolute_OutBar, xAbsolute_OutBar_Shape_Color, 0, Low, -60 );
}

if( xPeakTrough_SameBar_Absolute_OutBar_DisplaySwitch == 1 )
{
    PlotShapes( shapeSquare * xPT_SameBar_Absolute_OutBar, xPeakTrough_SameBar_Absolute_OutBar_Shape_Color, 0, High, 50 );
    PlotShapes( shapeSquare * xPT_SameBar_Absolute_OutBar, xPeakTrough_SameBar_Absolute_OutBar_Shape_Color, 0, Low, -50 );
}

if( xPeakBar_Absolute_OutBar_DisplaySwitch == 1 )
{
    PlotShapes( shapeSquare * xPeakBar_Absolute_OutBar, xPeakBar_Absolute_OutBar_Shape_Color, 0, High, 40 );
    PlotShapes( shapeSquare * xPeakBar_Absolute_OutBar, xPeakBar_Absolute_OutBar_Shape_Color, 0, Low, -40 );
}

if( xTroughBar_Absolute_OutBar_DisplaySwitch == 1 )
{
    PlotShapes( shapeSquare * xTroughBar_Absolute_OutBar, xTroughBar_Absolute_OutBar_Shape_Color, 0, High, 30 );
    PlotShapes( shapeSquare * xTroughBar_Absolute_OutBar, xTroughBar_Absolute_OutBar_Shape_Color, 0, Low, -30 );
}

if( xPeakTrough_SameBar_DisplaySwitch == 1 )
{
    PlotShapes( shapeSquare * xPeakTrough_SameBar, xPeakTrough_SameBar_Shape_Color, 0, High, 20 );
    PlotShapes( shapeSquare * xPeakTrough_SameBar, xPeakTrough_SameBar_Shape_Color, 0, Low, -20 );
}



_SECTION_END();


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Find Missed Peaks-Troughs" );


// The idea I have used in this section is workable but visually only.
// It has gnerated a problem which makes difficlut to use Troughs for any applications which reqire peaks and trough.
// This problem can be visually seen if one tries to display the peaks and troughs via ploting shapes.

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xTrough_Bar_01 = ValueWhen( xTrough, Bi, 1 );
xPeak_Bar_01 = ValueWhen( xPeak, Bi, 1 );
xTrough_Bar_Low_01 = xTrough;
xPeak_Bar_High_01 = xPeak;

xRecentPivot_Trough = IIf( xTrough_Bar_01 > xPeak_Bar_01, 1, 0 );

PT_Bar_Count = IIf( xRecentPivot_Trough == 1, abs( xPeak_Bar_01 - xTrough_Bar_01 ), Null );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


function LookBack_LowestLow( Tr )
{
    iLL_Value = Null;

    for( i = 0; i < BarCount - 1; i++ )
    {
        if( xTrough[i] )
        {
            ii = i;
            iL = 1e7;  // I put this value to avoid any possible encounter with faulty zero-value operations.

            //Loop-back the bars to find the lowest-low
            for( j = 0; j < PT_Bar_Count[i]; j++ )
            {
                if( L[i - j] < iL )
                {
                    ii = i - j;
                    iL = L[ii];

                }
            }

            iLL_Value[ii] = iL;  // set the array of the lowest-low
        }
    }

    return iLL_Value;
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( Missed_High_Low_HandleSwitch == 1 )
{
    Looped_LowestLow = LookBack_LowestLow( xTrough );

    Missed_LowestLow = IIf( ( xRecentPivot_Trough == 1 ) AND( Looped_LowestLow <= xTrough ), 1, 0 );

    xTrough = IIf( Missed_LowestLow == 1, 0, Looped_LowestLow );
}


_SECTION_END();


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "xPivot-Camparison" );


for( i = 0; i < 3; i++ )
{
    VarSet( "xPeak_x" + i, ValueWhen( xPeak, Bi, i ) );
    VarSet( "xTrough_x" + i, ValueWhen( xTrough, Bi, i ) );
    VarSet( "xPeakHigh_" + i, ValueWhen( xPeak, PaH, i ) );
    VarSet( "xTroughLow_" + i, ValueWhen( xTrough, PaL, i ) );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xLL = xTrough AND xTroughLow_1 < xTroughLow_2;           // LL = LowerLow
xHL = xTrough AND xTroughLow_1 > xTroughLow_2;         // HL = HigherLow
xHH = xPeak AND xPeakHigh_1 > xPeakHigh_2;             // HH = HigherHigh
xLH = xPeak AND xPeakHigh_1 < xPeakHigh_2;              // LH = LowerHigh
xDT = xPeak AND xPeakHigh_1 == xPeakHigh_2;             // DT = DoubleTop
xDB = xTrough AND xTroughLow_1 == xTroughLow_2;      // DB = DoubleBottom

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xHH_Bar_01 = ValueWhen( xHH, Bi, 1 );
xLH_Bar_01 = ValueWhen( xLH, Bi, 1 );
xLL_Bar_01 = ValueWhen( xLL, Bi, 1 );
xHL_Bar_01 = ValueWhen( xHL, Bi, 1 );
xDT_Bar_01 = ValueWhen( xDT, Bi, 1 );
xDB_Bar_01 = ValueWhen( xDB, Bi, 1 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xHH_Bar_High_01 = ValueWhen( xHH, PaH );
xLH_Bar_High_01 = ValueWhen( xLH, PaH );
xLL_Bar_Low_01 = ValueWhen( xLL, PaL );
xHL_Bar_Low_01 = ValueWhen( xHL, PaL );
xDT_Bar_High_01 = ValueWhen( xDT, PaH );
xDB_Bar_Low_01 = ValueWhen( xDB, PaL );


_SECTION_END();


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "xPivot Comparison-Lables" );


xPivotLabels_DisplaySwitch = ParamToggle( "Display xPivot-Labels", "No|Yes", 0 );
xPivotLabels_Zorder = Param( "xPivot-Label's Zorder", 5, -5, 5, 1 );
xLabel_Background_Color = ParamColor( "xPivot-Label's Background-Color", colorBlack );
xUpper_Label_Color = ParamColor( "xPivot's Upper-Label Color", colorYellow );
xLower_Label_Color = ParamColor( "xPivot's Lower-Lable Color", colorCustom11 );


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( xPivotLabels_DisplaySwitch )
{

    GfxSetZOrder( xPivotLabels_Zorder );

    for( i = 0; i < BarCount; i++ )
    {
        if( xLL[i] )
        {
            xString = "LL";
            PlotTextSetFont( xString, Font_Name, Text_Size, i, Low[i], xLower_Label_Color, xLabel_Background_Color, -30 );
        }

        if( xHL[i] )
        {
            xString = "HL";
            PlotTextSetFont( xString, Font_Name, Text_Size, i, Low[i], xLower_Label_Color, xLabel_Background_Color, -30 );
        }

        if( xDB[i] )
        {
            xString = "DB";
            PlotTextSetFont( xString, Font_Name, Text_Size, i, Low[i], xLower_Label_Color, xLabel_Background_Color, -30 );
        }

        if( xHH[i] )
        {
            xString = "HH";
            PlotTextSetFont( xString, Font_Name, Text_Size, i, High[i], xUpper_Label_Color, xLabel_Background_Color, 30 );
        }

        if( xLH[i] )
        {
            xString = "LH";
            PlotTextSetFont( xString, Font_Name, Text_Size, i, High[i], xUpper_Label_Color, xLabel_Background_Color, 30 );
        }

        if( xDT[i] )
        {
            xString = "DT";
            PlotTextSetFont( xString, Font_Name, Text_Size, i, High[i], xUpper_Label_Color, xLabel_Background_Color, 30 );
        }

    }
}


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


// This entire section is also coded by me and therby some errors might be there. Because I am just a beginner in AFL coding.
// However after checking the output quite extensively and thoroughly, no errors have been found yet. But still I have doubt.

_SECTION_BEGIN( "Gfx-ZigZag" );


nZigZag_DisplaySwitch = ParamToggle( "Display nZigZag ", "No|Yes", 1 );
nPeakTrough_Shapes_DisplaySwitch = ParamToggle( "Display nPeak-Trough Shapes", "No|Yes", 0 );
nPeakTrough_SameBar_HandleSwitch = ParamToggle( "Handle nPeakTrough-@-SameBar", "No|Yes", 1 );

nZigZag_Line_Zorder = Param( "nZigZag's Line-Zorder", 5, -5, 5, 1 );
nZigZag_Line_Width = Param( "nZigZag's Line-Width", 2, 0, 5, 1 ); // If this value is 0, the width in device units is always 1 pixel, regardless of the mapping mode (this is useful for drawing hairline lines on printer outputs).
nZigZag_Line_Style = Param( "nZigZag's Line-Style", 0, 0, 5, 1 ); // Solid=0, Dash=1, Dot=2, Null=5 (Invisible-Pen).
nZigZag_Line_Color = ParamColor( "nZigZag's Line-Color", colorWhite );


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

nPeak = xPeak;
nTrough = xTrough;

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


function Draw_UpLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_01, TroughBarLow_01, PeakBar_01, PeakBarHigh_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( TroughBar_01, TroughBarLow_01 );
    GfxLineTo( PeakBar_01, PeakBarHigh_01 );
}

function Draw_DownLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_01, PeakBarHigh_01, TroughBar_01, TroughBarLow_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( PeakBar_01, PeakBarHigh_01 );
    GfxLineTo( TroughBar_01, TroughBarLow_01 );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function Draw_UpLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02, TroughBarLow_02, PeakBar_01, PeakBarHigh_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( TroughBar_02, TroughBarLow_02 );
    GfxLineTo( PeakBar_01, PeakBarHigh_01 );
}

function Draw_DownLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_02, PeakBarHigh_02, TroughBar_01, TroughBarLow_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( PeakBar_02, PeakBarHigh_02 );
    GfxLineTo( TroughBar_01, TroughBarLow_01 );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


function Draw_Line_PT_SameBar_to_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02, TroughBarLow_02, PeakBar_01, PeakBarHigh_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( TroughBar_02, TroughBarLow_02 );
    GfxLineTo( PeakBar_01, PeakBarHigh_01 );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx



if( nZigZag_DisplaySwitch )
{

    GfxCoordsMode = 1;
    Line_Zorder = nZigZag_Line_Zorder;

    Line_Color = nZigZag_Line_Color;
    Line_Width = nZigZag_Line_Width;
    Line_Style = nZigZag_Line_Style;

    PeakBar_01 =  ValueWhen( nPeak, Bi, 1 );
    PeakBar_02 =  ValueWhen( nPeak, Bi, 2 );
    TroughBar_01 = ValueWhen( nTrough, Bi, 1 );
    TroughBar_02 = ValueWhen( nTrough, Bi, 2 );

    PeakBarHigh_01 =  ValueWhen( nPeak, PaH, 1 );
    PeakBarHigh_02 =  ValueWhen( nPeak, PaH, 2 );
    TroughBarLow_01 = ValueWhen( nTrough, PaL, 1 );
    TroughBarLow_02 = ValueWhen( nTrough, PaL, 2 );

    PeakTrough_SameBar_01 = ValueWhen( nPeak, Bi, 1 ) == ValueWhen( nTrough, Bi, 1 );
    PeakTrough_SameBar_02 = ValueWhen( nPeak, Bi, 2 ) == ValueWhen( nTrough, Bi, 2 );

    Recent_Previous_Pivot_Peak = ValueWhen( nPeak, Bi, 2 ) > ValueWhen( nTrough, Bi, 2 ) AND ValueWhen( nTrough, Bi, 1 ) > ValueWhen( nPeak, Bi, 2 );
    Recent_Previous_Pivot_Trough = ValueWhen( nTrough, Bi, 2 ) > ValueWhen( nPeak, Bi, 2 ) AND ValueWhen( nPeak, Bi, 1 ) > ValueWhen( nTrough, Bi, 2 );


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    for( i = 0; i < BarCount - 1; i++ )
    {
        Draw_UpLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_01[i], TroughBarLow_01[i], PeakBar_01[i], PeakBarHigh_01[i] );
        Draw_DownLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_01[i], PeakBarHigh_01[i], TroughBar_01[i], TroughBarLow_01[i] );

        //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        if( nPeakTrough_SameBar_HandleSwitch == 1 )
        {
            if( PeakTrough_SameBar_01[i] AND Recent_Previous_Pivot_Trough[i] )
            {
                Draw_UpLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02[i], TroughBarLow_02[i], PeakBar_01[i], PeakBarHigh_01[i] );
            }

            if( PeakTrough_SameBar_01[i] AND Recent_Previous_Pivot_Peak[i] )
            {
                Draw_DownLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_02[i], PeakBarHigh_02[i], TroughBar_01[i], TroughBarLow_01[i] );
            }

            //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

            if( PeakTrough_SameBar_01[i] AND PeakTrough_SameBar_02[i] )
            {
                Draw_Line_PT_SameBar_to_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02[i], TroughBarLow_02[i], PeakBar_01[i], PeakBarHigh_01[i] );
            }
        }
    }
}


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


if( nPeakTrough_Shapes_DisplaySwitch )
{
    nPeak_Shape_Color = ParamColor( "nPeak Shape-Color", colorCustom12 );
    nTrough_Shape_Color = ParamColor( "nTrough Shape-Color", colorYellow );

    nPeak_Shape_Type = Param( "nPeak Shape-Type", 13, 0, 50, 1 );
    nTrough_Shape_Type = Param( "nTrough Shape-Type", 13, 0, 50, 1 );


    PlotShapes( nPeak_Shape_Type * nPeak, nPeak_Shape_Color, 0, High, 10 );
    PlotShapes( nTrough_Shape_Type * nTrough, nTrough_Shape_Color, 0, Low, -10 );
}


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

As per my understanding.

Loop is working perfectly, but it is moving over and creating low-to-low comparisions.
And even after finding out the lowest-value it is retaining all the previous comparisions.
The loop is returning multiple lows with their comparitive values, as new lower lows are found throughout the range.
What the loop is tracing is just the lowest value until the range is over.
On a visual basis, every thing seems okay when noticing zigzag. However, it is not letting to assign and refer to a single bar as trough for any future use.

Reason behind this can be seen when we choose to display the peak-trough shapes from the parameters.

Now, all the light-bulbs inside my brain are completely switched-off. Kindly guide me for any possible solution if you have in your mind.


Any expert ! kindly respond. At least let me know whether it’s not possible or what alternative approach should be used. Thanks.

Typically the reason for getting no responses, is that nobody really understands what you are after. Your code is 900 lines long and no it is not "self explanatory".
Nobody is keen to spend whole day looking at it.
Please follow this advice: How to ask a good question

To get better understanding of what is happening in your code and how functions work, use advice given here: How do I debug my formula? You have better chances to understand your own code that somebody else.

ok.. I get it. I posted whole code because most of the time experts demands to share the whole code to check the context of problematic code’s working. Another point that you mentioned is due to language problem. It’s difficult for me to express in English. Being monk, my focus was more on Sanskrit texts and thereby I always lack in expressing my thoughts in english. But I am practicing English and AFL more and more. Then perhaps in future I will be able to avoid these problems.
I apologize to you and everyone in the forum community for bothering with my poor expression of the problem.
I will not bother the forum community again.
Thanks @Tomasz for responding and pointing. :pray:

It is not about "bothering" the forum. It is about expectations that you have.
You expect others to read your mind. We can't do that.
Reading and understanding somebody's else code is difficult.
People differ very much in their "coding style". I would rather write formula from scratch than trying to understand what somebody wanted to write. Really. It takes 10 times LESS time to write from start than trying to fix somebody's else code.

Yes general advice is to post the code, but you can't expect people to fix 900 lines of your coding. When printed it is 20+ pages of text.

To have better chances for help you need to provide smallest viable code example that shows the problem you are having.

Also make sure your post is clear for the reader.

In your original post you wrote:

"The three line comments at the beginning of this section explains my problem."

Then in the code we have

// The idea I have used in this section is workable but visually only.
// It has gnerated a problem which makes difficlut to use Troughs for any applications which reqire peaks and trough.
// This problem can be visually seen if one tries to display the peaks and troughs via ploting shapes.

Frankly, I don't know what you mean at all. "makes difficult to use"? In what way? What it does and what do you expect instead?

You should be writing like this:

"When I uncomment line 123 I am getting a green dot at date XXX and I expect to get a red arrow."

That is precise description of the problem.

"Difficult to use" means nothing.

3 Likes

ok @Tomaz. I get it. Will write back with better explanation. Thanks.

Below is what I am trying to achieve.

Outside bars are the bars which sometimes have the peak & trough on their both sides.
And such outside-bars are important for my trading strategy.
To solve this problem I have coded this Gfx-Zigzag and it is letting me to have peak & trough on the same bar.

After that comes the second problem which is common to every type of zigzag.
Sometimes between the peak & trough an important low-pivot or high-pivot is not captured by the zigzag.

This phenomena is unavoidable and bound to happen: no matter in what way we chooses to define the peaks and troughs.
This is something which is inherent to the very structure of a zigzag, but can be handled after defining the zigzag.
I mean such problem can be handled in a later stage: after defining the peaks and troughs.

In order to handle this problem in a scenario where price movement was from PEAK-to-TROUGH:
First we need to look-back the bars from Trough upto Peak, and evaluate whether there is low in this range, which is lower than the trough-low.
If such a low exists then we disable that trough and mark this missed low as the trough.
If such a low don't exists then we need not to do anyhing with the trough because this trough is already a good enough trough.

In order to handle this problem in a scenario where price movement was from TROUGH-to-PEAK:
First we need to look-back the bars from Peak upto Trough, and evaluate whether there is a high between a TROUGH-to-Peak price movement, which is higherthan the peak-high.
If such a high exists then we disable that peak and mark this missed high as the peak.
If such a high don't exists then we need not to do anyhing with the peak because this peak is already a good enough peak.

To solve the above problem I am using a loop approach but its generating the problem which is difficult for me express in words therefore I have demonstrated it in the imgaes. Please have a look at the images.

Below is the code for looking backwards to find the missed low-pivot.


_SECTION_BEGIN( "Find Missed Troughs" );


 Missed_Pivot_HandleSwitch = ParamToggle( "Include Missed Pivots ?", "No | Yes", 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Trough_Bar_01 = ValueWhen( nTrough, Bi, 1 );
Peak_Bar_01 = ValueWhen( nPeak, Bi, 1 );

Peak_Bar_High_01 = nPeak;
Trough_Bar_Low_01 = nTrough;

Last_Pivot_Peak =  ValueWhen( nPeak, Bi, 1 ) > ValueWhen( nTrough, Bi, 1 );
Last_Pivot_Trough = ValueWhen( nTrough, Bi, 1 ) > ValueWhen( nPeak, Bi, 1 );

PT_Bar_Count = IIf( Last_Pivot_Trough == 1, abs( Peak_Bar_01 - Trough_Bar_01 ), Null ); // Here, 'PT' stands for 'Peak-&-Trough
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function LookBack_LowestLow( Tr )
{

    iLL_Value = Null;

    for( i = 0; i < BarCount - 1; i++ )
    {
        if( nTrough[i] )
        {
            ii = i;
            iL = 1e7;  // I put this value to avoid any possible encounter with faulty zero-value operations. 

            //Loop-back the bars to find the lowest-low
            for( j = 0; j < PT_Bar_Count[i]; j++ )
            {
                if( L[i - j] < iL )
                {
                    ii = i - j;
                    iL = L[ii];

                }
            }

            iLL_Value[ii] = iL;  // set the array of the lowest-low
        }
    }

    return iLL_Value;
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( Missed_Pivot_HandleSwitch == 1 )
{
Low_Pivot_between_PT = LookBack_LowestLow( nTrough ); // Here, 'PT' stands for 'Peak-&-Trough

Missed_Low_Pivot = IIf( (Last_Pivot_Trough == 1) AND ( Low_Pivot_between_PT <= nTrough ), 1, 0 );

nTrough = IIf( Missed_Low_Pivot == 1, 0, Low_Pivot_between_PT );
}

_SECTION_END();



If you require the whole code to help me out, then below is the whole code.

// For testing purposes, I am not limiting the loops to work in visible chart area.

_SECTION_BEGIN( "General" );

RequestTimedRefresh( 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SetChartOptions( 0, chartShowArrows | chartShowDates );
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Bi = BarIndex();

FvB = FirstVisibleValue( Bi );
LvB = LastVisibleValue( Bi );

SetBarsRequired( ( LVB - FVB ) * 4 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GraphXSpace = Param( "GraphXSpace", 10, 0, 100, 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SetChartBkColor( colorDarkGrey ); // color of outer border
SetChartBkGradientFill( colorDarkGrey, colorDarkGrey ); // color of inner panel
SetChartBkColor( colorDarkGrey );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Candle_Zorder = Param( "Candle-Zorder", 1, -5, 5, 1 );
Candle_BodyLine_Width = Param( "Candle's Body-Line Width", 2, 1, 5, 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SetBarFillColor( IIf( Close > Open, colorTeal, IIf( Close < Open, colorOrange, colorWhite ) ) );
PlotOHLC( Open, High, Low, Close, "", IIf( Close > O, colorWhite, IIf( Close < Open, colorOrange, colorWhite ) ),
          styleCandle, Null, Null, 0, Candle_Zorder, Candle_BodyLine_Width );
                    
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

_SECTION_BEGIN( "BarTypes & Swings" );

Number_of_Bars_for_UpSwing = Param( "Number-of-Bars for ZigZag-Swing", 1, 1, 10, 1 );
Number_of_Bars_for_DownSwing = Number_of_Bars_for_UpSwing; // Param( "Number-of-Bars for DownSwing", 1, 1, 5, 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
UpBar = High > Ref( High, -1 ) AND Low >= Ref( Low, -1 );
DownBar = High <= Ref( High, -1 ) AND Low < Ref( Low, -1 );
OutBar = High > Ref( High, -1 ) AND Low < Ref( Low, -1 );
InBar = High <= Ref( High, -1 ) AND Low >= Ref( Low, -1 ); 
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
UpSwing = Sum( UpBar, Number_of_Bars_for_UpSwing ) == Number_of_Bars_for_UpSwing;
DownSwing = Sum( DownBar, Number_of_Bars_for_DownSwing ) == Number_of_Bars_for_DownSwing;

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

_SECTION_BEGIN( "Calculate Peak-Trough" );

nPeak = nTrough = 0;
Peak_High = 0;
Peak_Low = 0;
Trough_Low = 1e5;
Ups = Downs = 0;
IdxHigh = IdxLow = 0;
Array_High = ArrayLow = 0;
Breakout_High = Breakout_Low = 0;
UpSwing_Start = DownSwing_Start = 0;

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

for( i = 0; i < BarCount; i++ )
{
    // UpSwing start
    if( UpSwing[i] AND Ups == 0 )
    {
        IdxHigh = i;
        Array_High = High[i];
        Ups = 1;
        Downs = 0;
        UpSwing_Start[i] = 1;

        nTrough[IdxLow] = 1;
        Trough_Low[IdxLow] = Low[IdxLow];
    }

    else

        // UpSwing continuation
        if( Ups == 1 AND High[i] > Array_High )
        {
            IdxHigh = i;
           Array_High = High[i];
        }

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    // DownSwing start
    if( DownSwing[i] AND Downs == 0 )
    {
        IdxLow = i;
        ArrayLow = Low[i];
        Ups = 0;
        Downs = 1;
        DownSwing_Start[i] = 1;

        nPeak[IdxHigh] = 1;
        Peak_High[IdxHigh] = High[IdxHigh];
    }
    else

        // DownSwing continuation
        if( Downs == 1 AND Low[i] < ArrayLow )
        {
            IdxLow = i;
            ArrayLow = Low[i];
        }
        
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    // breakout lower without swinglow
    if( Ups == 1 AND Low[i] < ArrayLow AND !UpSwing[i] )
    {
        Breakout_Low[i] = 1;
        DownSwing[i] = 1;
        DownSwing_Start[i] = 1;

        IdxLow = i;
        ArrayLow = Low[i];
        Ups = 0;
        Downs = 1;

        nPeak[IdxHigh] = 1;
        Peak_High[IdxHigh] = Array_High;
    }

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    // breakout higher without swinghigh
    if( Downs == 1 AND High[i] > Array_High AND !DownSwing[i] )
    {
        Breakout_High[i] = 1;
        UpSwing[i] = 1;
        UpSwing_Start[i] = 1;

        IdxHigh = i;
        Array_High = High[i];
        Ups = 1;
        Downs = 0;

        nTrough[IdxLow] = 1;
        Trough_Low[IdxLow] = ArrayLow;
    }
}
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

_SECTION_BEGIN( "Find Missed Troughs" );

 Missed_Pivot_HandleSwitch = ParamToggle( "Include Missed Pivots ?", "No | Yes", 1 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Trough_Bar_01 = ValueWhen( nTrough, Bi, 1 );
Peak_Bar_01 = ValueWhen( nPeak, Bi, 1 );

Peak_Bar_High_01 = nPeak;
Trough_Bar_Low_01 = nTrough;

Last_Pivot_Peak =  ValueWhen( nPeak, Bi, 1 ) > ValueWhen( nTrough, Bi, 1 );
Last_Pivot_Trough = ValueWhen( nTrough, Bi, 1 ) > ValueWhen( nPeak, Bi, 1 );

PT_Bar_Count = IIf( Last_Pivot_Trough == 1, abs( Peak_Bar_01 - Trough_Bar_01 ), Null ); // Here, 'PT' stands for 'Peak-&-Trough
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function LookBack_LowestLow( Tr )
{

    iLL_Value = Null;

    for( i = 0; i < BarCount - 1; i++ )
    {
        if( nTrough[i] )
        {
            ii = i;
            iL = 1e7;  // I put this value to avoid any possible encounter with faulty zero-value operations. 

            //Loop-back the bars to find the lowest-low
            for( j = 0; j < PT_Bar_Count[i]; j++ )
            {
                if( L[i - j] < iL )
                {
                    ii = i - j;
                    iL = L[ii];

                }
            }

            iLL_Value[ii] = iL;  // set the array of the lowest-low
        }
    }

    return iLL_Value;
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( Missed_Pivot_HandleSwitch == 1 )
{
Low_Pivot_between_PT = LookBack_LowestLow( nTrough ); // Here, 'PT' stands for 'Peak-&-Trough

Missed_Low_Pivot = IIf( (Last_Pivot_Trough == 1) AND ( Low_Pivot_between_PT <= nTrough ), 1, 0 );

nTrough = IIf( Missed_Low_Pivot == 1, 0, Low_Pivot_between_PT );
}

_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 
_SECTION_BEGIN( "Gfx-ZigZag" );

ZigZag_DisplaySwitch = ParamToggle( "Display nZigZag ", "No|Yes", 1 );
PeakTrough_Shapes_DisplaySwitch = ParamToggle( "Display nPeak-Trough Shapes", "No|Yes", 1 );
PeakTrough_SameBar_HandleSwitch = ParamToggle( "Handle nPeakTrough-@-SameBar", "No|Yes", 1 );

ZigZag_Line_Zorder = Param( "nZigZag's Line-Zorder", 5, -5, 5, 1 );
ZigZag_Line_Width = Param( "nZigZag's Line-Width", 3, 0, 5, 1 ); // If this value is 0, the width in device units is always 1 pixel, regardless of the mapping mode (this is useful for drawing hairline lines on printer outputs).
ZigZag_Line_Style = Param( "nZigZag's Line-Style", 2, 0, 5, 1 ); // Solid=0, Dash=1, Dot=2, Null=5 (Invisible-Pen).
ZigZag_Line_Color = ParamColor( "nZigZag's Line-Color", colorAqua );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function Draw_UpLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_01, TroughBarLow_01, PeakBar_01, PeakBarHigh_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( TroughBar_01, TroughBarLow_01 );
    GfxLineTo( PeakBar_01, PeakBarHigh_01 );
}

function Draw_DownLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_01, PeakBarHigh_01, TroughBar_01, TroughBarLow_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( PeakBar_01, PeakBarHigh_01 );
    GfxLineTo( TroughBar_01, TroughBarLow_01 );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function Draw_UpLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02, TroughBarLow_02, PeakBar_01, PeakBarHigh_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( TroughBar_02, TroughBarLow_02 );
    GfxLineTo( PeakBar_01, PeakBarHigh_01 );
}

function Draw_DownLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_02, PeakBarHigh_02, TroughBar_01, TroughBarLow_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( PeakBar_02, PeakBarHigh_02 );
    GfxLineTo( TroughBar_01, TroughBarLow_01 );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function Draw_Line_PT_SameBar_to_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02, TroughBarLow_02, PeakBar_01, PeakBarHigh_01 )
{
    GfxSetCoordsMode( GfxCoordsMode );
    GfxSetZOrder( Line_Zorder );

    GfxSelectPen( Line_Color, Line_Width, Line_Style );
    GfxMoveTo( TroughBar_02, TroughBarLow_02 );
    GfxLineTo( PeakBar_01, PeakBarHigh_01 );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( ZigZag_DisplaySwitch )
{
    GfxCoordsMode = 1;
    Line_Zorder = ZigZag_Line_Zorder;

    Line_Color = ZigZag_Line_Color;
    Line_Width = ZigZag_Line_Width;
    Line_Style = ZigZag_Line_Style;

    PeakBar_01 =  ValueWhen( nPeak, Bi, 1 );
    PeakBar_02 =  ValueWhen( nPeak, Bi, 2 );
    TroughBar_01 = ValueWhen( nTrough, Bi, 1 );
    TroughBar_02 = ValueWhen( nTrough, Bi, 2 );

    PeakBarHigh_01 =  ValueWhen( nPeak, High, 1 );
    PeakBarHigh_02 =  ValueWhen( nPeak, High, 2 );
    TroughBarLow_01 = ValueWhen( nTrough, Low, 1 );
    TroughBarLow_02 = ValueWhen( nTrough, Low, 2 );

    PeakTrough_SameBar_01 = ValueWhen( nPeak, Bi, 1 ) == ValueWhen( nTrough, Bi, 1 );
    PeakTrough_SameBar_02 = ValueWhen( nPeak, Bi, 2 ) == ValueWhen( nTrough, Bi, 2 );

    Previous_Pivot_Peak = ValueWhen( nPeak, Bi, 2 ) > ValueWhen( nTrough, Bi, 2 ) AND ValueWhen( nTrough, Bi, 1 ) > ValueWhen( nPeak, Bi, 2 );    
    Previous_Pivot_Trough = ValueWhen( nTrough, Bi, 2 ) > ValueWhen( nPeak, Bi, 2 ) AND ValueWhen( nPeak, Bi, 1 ) > ValueWhen( nTrough, Bi, 2 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    for( i = 0; i < BarCount - 1; i++ )
    {
        Draw_UpLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_01[i], TroughBarLow_01[i], PeakBar_01[i], PeakBarHigh_01[i] );
        Draw_DownLine( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_01[i], PeakBarHigh_01[i], TroughBar_01[i], TroughBarLow_01[i] );
        //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        if( PeakTrough_SameBar_HandleSwitch == 1 )
        {
            if( PeakTrough_SameBar_01[i] AND Previous_Pivot_Trough[i] )
            {
                Draw_UpLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02[i], TroughBarLow_02[i], PeakBar_01[i], PeakBarHigh_01[i] );
            }
            
            if( PeakTrough_SameBar_01[i] AND Previous_Pivot_Peak[i] )
            {
                Draw_DownLine_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, PeakBar_02[i], PeakBarHigh_02[i], TroughBar_01[i], TroughBarLow_01[i] );
            }
            //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
            if( PeakTrough_SameBar_01[i] AND PeakTrough_SameBar_02[i] )
            {
                Draw_Line_PT_SameBar_to_PT_SameBar( GfxCoordsMode, Line_Zorder, Line_Color, Line_Width, Line_Style, TroughBar_02[i], TroughBarLow_02[i], PeakBar_01[i], PeakBarHigh_01[i] );
            }
        }
    }
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( PeakTrough_Shapes_DisplaySwitch )
{
    Peak_Shape_Color = ParamColor( "Peak Shape-Color", colorCustom12 );
    Trough_Shape_Color = ParamColor( "Trough Shape-Color", colorYellow );

    Peak_Shape_Type = Param( "Peak Shape-Type", 13, 0, 50, 1 );
    Trough_Shape_Type = Param( "Trough Shape-Type", 13, 0, 50, 1 );


    PlotShapes( Peak_Shape_Type * nPeak, Peak_Shape_Color, 0, High, 20 );
    PlotShapes( Trough_Shape_Type * nTrough, Trough_Shape_Color, 0, Low, -20 );
}
_SECTION_END();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

_SECTION_BEGIN( "Pivot-Camparison" );

for( i = 0; i < 3; i++ )
{
    VarSet( "Peak_x" + i, ValueWhen( nPeak, Bi, i ) );
    VarSet( "Trough_x" + i, ValueWhen( nTrough, Bi, i ) );
    VarSet( "PeakHigh_" + i, ValueWhen( nPeak, High, i ) );
    VarSet( "TroughLow_" + i, ValueWhen( nTrough, Low, i ) );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
LL = nTrough AND TroughLow_1 < TroughLow_2;           // LL = LowerLow
HL = nTrough AND TroughLow_1 > TroughLow_2;         // HL = HigherLow
HH = nPeak AND PeakHigh_1 > PeakHigh_2;             // HH = HigherHigh
LH = nPeak AND PeakHigh_1 < PeakHigh_2;              // LH = LowerHigh
DT = nPeak AND PeakHigh_1 == PeakHigh_2;             // DT = DoubleTop
DB = nTrough AND TroughLow_1 == TroughLow_2;      // DB = DoubleBottom

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

_SECTION_BEGIN( "Pivot Comparison-Lables" );

PivotLabels_DisplaySwitch = ParamToggle( "Display Pivot-Labels", "No|Yes", 1 );
PivotLabels_Zorder = Param( "Pivot-Label's Zorder", 5, -5, 5, 1 );

Font_Name = ParamList( "Font", "Tahoma|Helvetica|Arial Black|Verdana|Courier New|Times New Roman|Open Sans|Compact|Segoe UI|DejaVu Sans", 1 );
Text_Size = Param( "Text-Size", 8, 5, 20, 1 );

Label_Background_Color = ParamColor( "Pivot-Label's Background-Color", colorBlack );
Upper_Label_Color = ParamColor( "Pivot's Upper-Label Color", colorYellow );
Lower_Label_Color = ParamColor( "Pivot's Lower-Lable Color", colorCustom11 );
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
if( PivotLabels_DisplaySwitch )
{

    GfxSetZOrder( PivotLabels_Zorder );

    for( i = 0; i < BarCount; i++ )
    {
        if( LL[i] )
        {
            String = "LL";
            PlotTextSetFont( String, Font_Name, Text_Size, i, Low[i], Lower_Label_Color, Label_Background_Color, -30 );
        }

        if( HL[i] )
        {
            String = "HL";
            PlotTextSetFont( String, Font_Name, Text_Size, i, Low[i], Lower_Label_Color, Label_Background_Color, -30 );
        }

        if( DB[i] )
        {
            String = "DB";
            PlotTextSetFont( String, Font_Name, Text_Size, i, Low[i], Lower_Label_Color, Label_Background_Color, -30 );
        }

        if( HH[i] )
        {
            String = "HH";
            PlotTextSetFont( String, Font_Name, Text_Size, i, High[i], Upper_Label_Color, Label_Background_Color, 30 );
        }

        if( LH[i] )
        {
            String = "LH";
            PlotTextSetFont( String, Font_Name, Text_Size, i, High[i], Upper_Label_Color, Label_Background_Color, 30 );
        }

        if( DT[i] )
        {
            String = "DT";
            PlotTextSetFont( String, Font_Name, Text_Size, i, High[i], Upper_Label_Color, Label_Background_Color, 30 );
        }

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

Mr. @Tomasz , I hope that this is clear enough to provide the general idea of things ? I have put best of my effort to express. If not, then I am afraid that I have to leave this problem aside and wait for such a day to come when my AFL learning journey comes to a point where I am confidently able to decide whether this problem's solution is achievable or not. But I don't know how long I have to wait.

Thanks to Mr. @Tomasz for paying attention and putting effort to point out the what was necessary. I highly appriciate your response, because I understand that your eyes must be bleeding out by sitting whole day in front to screen in order to read all the forum posts and be ready to response when necessary. :pray:

And thanks to all the experts who also helps Mr. @Tomasz to bear the burden and sacrifice their precious time and energy to help all the forum members like me. :pray:

Mr. @Tomasz and other experts, I understand that your time is also as precious as everyone else is. Therefore, if you find that I am still not clear, or in future any post is the same, then there is no need to put extra effort and waste your time & energy over me. Just the lack of any response will be enough for me to understand. Actually, all these problems are due to the fact that I have to take help of google translator to translate my words from Sanskrit to English. And then make further adjustments also. And all of this is limiting my ability to express properly. Thanks.

@LotusHeart, unfortunately, I'm unable to help you with this kind of code (as I mentioned before, it's not my area of expertise).

However, regarding your difficulty in expressing yourself in English, in the future, I suggest you try translating your messages from Sanskrit to English using Chat-GPT (or other large language model engines).
I have done some translations from less widely used languages, and in my experience, the quality was significantly better than that of Google Translate.
Since I don't know your language I don't know if it will work: anyway, it’s worth a try!

1 Like

Thanks @beppe. I will try that.

Ok, let me put my question in a different way, by not discussing the context of application. That way we can forget about the jargon of peaks, troughs and the zigzag. That way question could be put in a more simple way.

Within a Period-Range ( suppose 7 bars range ), while looking backward from the 7th bar,
I want to get precisely the bar, whose low is lowest within the Period-Range, not just to the 7th-bar but also to all the bars that are within the Period-Range.

For example, suppose there is a 7 bars-range ( including the 7th-bar ), and 7th bar is the bar we start looking backward.
Now if the 3rd bar's low is lowest to all the bars then the code should be able to detect and retun the low-value and index of this bar. And this index number of the bar should be the same as the the chart's original default index.

If within this 7-bar Period-Range only the 7th bar itself is having the lowest-low, then it should return the low-value and index of that 7th bar.

Same goes for reveresed scenario, where we look backwards from the 7th-bar for highest-high value.

My code I is not letting me to run both codes ( code for lowest-low and the code for highest-high ) simultaneously.

I just want to know some possible solution for that. Thanks.

I just want to try some other possible codes to check if anyone's code could run sucessfully for both scenarios without any conflict arising in between them, when run simultaneously.

Hi

Did you ever think to place more than one zig() in one AFL ?

And yes, i know there are so many zigzag afl codes,
here in one afl code very-very easy to understand and to visualize.
I hope you will understand what happen with the "percentages" in your loop

_SECTION_BEGIN( "Zig Hi Lo triple" );
// Zig triple
// ZIG hilo original version by Joris Schuller
// mod reinsley

function Zag( Change )
{
    pk = PeakBars( H, Change ) == 0;
    tr = TroughBars( L, Change ) == 0;
    pkbars = PeakBars( H, Change );
    trbars = TroughBars( L, Change );
    zHi = Zig( H, Change );
    zLo = Zig( L, Change );
    HLAvg = ( zHi + zLo ) / 2;
    zp2 = IIf( pk, zHi, IIf( tr, zLo, IIf( pkbars <= trbars, L, H ) ) );
    return za = Zig( zp2, Change );
}

Plot( C, "", colorDefault, styleBar );


plt = ParamToggle( "Plot ZigHL ", "Off|On", 1 );
Changeslo = Param( "Zig-HL slow % colorBlue", 2, 0.01, 15, 0.01 );
Changemed = Param( "Zig-HL medium % colorYellow", 1, 0.01, 9, 0.01 );
Changefas = Param( "Zig-HL fast % colorAqua", 0.2, 0.01, 7, 0.01 );

za3 = Zag( Changeslo );
za2 = Zag( Changemed );
za1 = Zag( Changefas );

if ( plt == 1 )
{
    Title = EncodeColor( 5 ) + _DEFAULT_NAME() + "; " + EncodeColor( colorAqua) + StrFormat( "{{NAME}} - {{INTERVAL}}; {{DATE}}; \nO =%g, \nH =%g,\nL =%g, \nC =%g (%.1f%%){{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) );
    Plot( za3, "\nZig slow", colorBlue, 5 | styleNoLabel );
    Plot( za2, "\nZig med", colorYellow, 5 | styleNoLabel );
    Plot( za1, "\nZig fas", colorAqua, 5 | styleNoLabel );
}

_SECTION_END();

1 Like

Mr. PanoS, First of all thanks for paying attention and responding.

Mr. PanoS, I always use at least three zigzags. Where, second zigzag is based on the HH-LL pivots of first zigzag and the third zigzag is based on the HH-LL pivots of the second zigzag.

Here, I am sharing a snapshot of not three but two zigzags only for better clarity.
You can clearly see in the image that the prime-zigzag is missing an imprtant pivot.

Such a thing happens very less times but it does happens to every type of zigzag.

I am copy-pasting a few of my lines from one of my posts, already posted on this same page.

"...Sometimes between the peak & trough an important low-pivot or high-pivot is not captured by the zigzag.

This phenomena is unavoidable and bound to happen: no matter in what way we chooses to define the peaks and troughs.
This is something which is inherent to the very structure of a zigzag, but can be handled after defining the zigzag.
I mean such problem can be handled in a later stage: after defining the peaks and troughs..."

For more details check ( Kindly Guide: regarding a loop generated problem - #8 by LotusHeart )

1 Like

Here references are to the most recent 'full' code posted. Please note I can not replicate your chart examples because I do not have Indian stock data. I am only using Norgate daily data.

I have been watching this thread evolve and thought I was getting closer to understanding what you are trying to achieve so I will jump in with some (hopefully useful) comments.

Initially you were talking about a loop problem that was creating multiple troughs and I eventually concluded that you were referring to the loop in the "Find Missed Troughs" section, not to the large loop in the "Calculate Peak-Trough" section.

First a comment about the multiple yellow arrows. You have concentrated on the missed pivots issue recently so you may have solved this, but in case you have not here are my thoughts:
The multiple arrows are probably caused by invalid shape values passed to PlotShapes. In section "Find Missed Troughs" change
nTrough = IIf( Missed_Low_Pivot == 1, 0, Low_Pivot_between_PT );
to
nTrough = IIf( Missed_Low_Pivot == 1, 1, nTrough );
The code in this section adds extra trough 'signals' so I put in
nTrough = ExRem( nTrough, nPeak );
next to clean out all but the first trough 'signal'.

At this stage I have not looked at the code further at the code in this section to try and determine all the rules by which you decide there is a missed trough.
Your description and charts at first seem to be clear but when I decided to stretch my old brain and write some code to do what I thought you meant it came up with different 'missed' pivots than your code. So my code might not match your rules exactly, or even your code may not be fully debugged, or both.

If I was building this code I would look at better understanding the "Calculate Peak-Trough" section and build all the rules into it and not do 'post-processing' of the peak & trough arrays to match some rules that don't fit the UpSwing/DownSwing criteria. Just a thought.

At this stage my code is a mess but I'll clean it up if it helps. Its written using array functions only so it may not be very understandable to a new AFL coder. The pictures are a random stock where bar 'A' is the trough your code picks (with or without "Include Missed Pivots" set to 'Yes') and bar 'B' is where my code finds a 'missed' trough.

As a final observation - in this code:

{
    Peak_Shape_Color = ParamColor( "Peak Shape-Color", colorCustom12 );
    Trough_Shape_Color = ParamColor( "Trough Shape-Color", colorYellow );

    Peak_Shape_Type = Param( "Peak Shape-Type", 13, 0, 50, 1 );
    Trough_Shape_Type = Param( "Trough Shape-Type", 13, 0, 50, 1 );

    PlotShapes( Peak_Shape_Type * nPeak, Peak_Shape_Color, 0, High, 20 );
    PlotShapes( Trough_Shape_Type * nTrough, Trough_Shape_Color, 0, Low, -20 );
}

you have parameter functions inside an if() block.
My understanding is that conditionally executing these is not recommended. Only execute the plot statements inside the if().

John.

Forum38544-18_01

Forum38544-18_02

1 Like

Mr. @JohnHT, from the bottom of my heart very many thanks to you for paying attention and putting efforts to such an extent. I was hopeless. I am not good at looping, moreover I don’t like to use very many loops.

Thanks for reviving my hope and broaden the horizon of my understanding. Now I understand what the plot of shapes was doing. And what things I should avoid in my future coding efforts.

I am extremely good at trading using even the plain charts, so much so that I love to teach my trading techniques to my friends-cum-students, but simultaneously on the other hand I am very poor in knowledge and experience of AFL coding.

If you feel comfortable, I would love to know how you approached the problem in order to solve it.
Further, you mentioned that your code is not complete yet, if it’s ok for you, then kindly share the code even if it is not finished yet. I want to see how you solved this problem.

Again I very grateful to you for taking the pain by going in such great extent of details, just to make me understand things right. May you have light and happiness in your life. :pray:

Mr. @JohnHT, since you are working on such a code let me share a very important thing with you.

After finding the missed-low-pivots and accordingly letting the code to update the troughs when we work on the reverse scenario ( finding the missed-high-pivots ) and letting the code to update the peaks accordingly then the very next moment the code for missed-low-pivots jumps in and starts working to find and update to new missed-troughs and once it has done its work then again the code for missed-high-pivots will jump in to find and update the troughs according to new info fresh troughs.

All of this will create an infinite-regression of never ending cycle. And can be demonstrated via a GIF image or video, not by a static picture.

And this infinite-regression to never ending cycle is due to the loop approch. Due to this reason its better to avoid the loop approach to find and update troughs.

Another way is that after finding the missed-low-pivots and accordingly updating the troughs we put an instruction in the code to permanently fix all those troughs and only then we find the missed-high-pivots and update peaks accordingly.

Its possible to handle this situation because two years before I was successful to solve the problrem. But unforunately the hard-disk of my laptop crashed and l lost that code. At present I don't remember how I did it. Thats why I am facing the problems in coding the zigzag.

Now the last point : Even the application of finding missed-low-pivot and accordingly updating the troughs is more than enough. The reason is that automatically peaks are also adjusted upto a great accuracy. So much so that I have notice that less than 0.5 % of cases are found where a high-pivot missed. Furthor, I found that those missed high-pivots are so much insignificant that they do not imapct the overall structure of the zigzag ( mapping of the market fluctuation). But this much accuracy in peaks is automatically achieved only by finding the missed-low pivot and updating the troughs accordingly.

And if you compare such a zigzag with other types of zigzags then you you will be surprised to found out that this zigzag is the most perfect market structure mapping zigzag one may have ever seen.