Zigzag indicator with pivot trend flips

Hi Experts

I am a newbie, trying to learn AFL.I am stucked in coding and need your guidance. Please guide me to found error in my approach.
After completting the code when I run it, there is nothing drawn on my chart. Don't know what is lacking?

Below is what I am trying to achive.

I am trying to code a zigzag indicator which should be drawn between highest-high & lowest-low of Pivot-Trend.
Where pivot-trend is the trend of peaks-and-troughs.

The moment pivot-trend flips from upside to downside, then the highest-high between the range of uptrend's lifespan,
should be marked as peak for zigzag.

Similarly, the moment pivot-trend flips downside to upside, then the lowest-low between the range of downtrend's lifespan,
should be marked as trough for the zigzag.

As this zigzag needs pivots, I am using the pivots of Mr. Empottasch's zigzag and using his code as base for my zigzag. My code starts from line 236.

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Date-Time etc." );


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( -2, -2 );
bi = BarIndex();
xCum = Cum( 1 );


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Chart Background Colors" );


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


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Price-Chart's Style" );


Plot_Price_Chart = ParamToggle( "Plot Price-Chart", "Off|On", 1 );
Price_Zorder = Param( "Price-Zorder", -1, -5, 5, 1 );
Price_Line_Width = Param( "Price-Line's Width", 2, 1, 5, 1 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Price_Bull_Color = ParamColor( "Price Bull Color", colorWhite );
Price_Bear_Color =  ParamColor( "Price Bear Color", colorBlack );
Doji_Color = ParamColor( "Doji Color", colorBlue );

Price_Color = IIf( Close > Open, Price_Bull_Color, IIf( Close < Open, Price_Bear_Color, Doji_Color ) );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if (ParamToggle("Plot Price-Chart","Off|On",1))
{
Plot( Close, "Close", Price_Color, styleBar | styleThick, Null, Null, Null, Price_Zorder, Price_Line_Width );
}


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


_SECTION_BEGIN( "Empottasch-ZigZag" );


nbar = Param( "Swing number of Bars", 10, 1, 50, 1 );
priceswitch = ParamToggle( "Use Close or High and Low price", "Use Close|Use High and Low", 1 );
// this toggle is for when in H/L mode the high is above res and the low below sup. There are 2 ways to handle this.
handleBothOutside = ParamToggle( "Long AND Short signal at the SAME bar", "Change Trend|Stay with current Trend", 0 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// bi = BarIndex();
fvb = FirstVisibleValue( bi );
lvb = LastVisibleValue( bi );

pk = tr = 0;
ZigZag = line1 = Null;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

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

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function calculateZigZag()
{
    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 );
}

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function calculateLastSegments()
{
    lastidxpk = LastValue( ValueWhen( pk, bi ) );
    lastidxtr = LastValue( ValueWhen( tr, bi ) );
    lastvalpk = LastValue( ValueWhen( pk, prch ) );
    lastvaltr = LastValue( ValueWhen( tr, prcl ) );
    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( 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( 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 );
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// find trend
res = HHV( prch, nbar );
sup = LLV( prcl, nbar );
crossup = prch > Ref( res, -1 );
crossdn = prcl < Ref( sup, -1 );

if( handleBothOutside )
{
    // if in H/L mode both crossup and crossdn at the same bar may occur.
    // if handleBothOutside is true then it will stay in the current trend
    // if handleBothOutside is false it will change the trend.
    crossup = IIf( ( crossup AND crossdn ) AND( BarsSince( Ref( crossup, -1 ) ) > BarsSince( Ref( crossdn, -1 ) ) ), 0, crossup );
    crossdn = IIf( ( crossup AND crossdn ) AND( BarsSince( Ref( crossdn, -1 ) ) > BarsSince( Ref( crossup, -1 ) ) ), 0, crossdn );
}

crossup = ExRem( crossup, crossdn );
crossdn = ExRem( crossdn, crossup );
trendup = Flip( crossup, crossdn );
trenddn = Flip( crossdn, crossup );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// find pivots
rtrenddn = Reverse( trenddn );
rtrendup = Reverse( trendup );
l1 = LowestSince( trenddn AND Ref( trendup, -1 ), prcl );
rL = Reverse( prcl );
l2 = LowestSince( rtrenddn AND Ref( rtrendup, -1 ), rL );
rl2 = Reverse( l2 );
h1 = HighestSince( trendup AND Ref( trenddn, -1 ), prch );
rH = Reverse( prch );
h2 = HighestSince( rtrendup AND Ref( rtrenddn, -1 ), rH );
rh2 = Reverse( h2 );
tr = l1 == rl2 AND trenddn;
pk = h1 == rh2 AND trendup;
rpk = Reverse( pk );
rtr = Reverse( tr );
rpk = ExRem( rpk, rtr );
rtr = ExRem( rtr, rpk );
pk = Reverse( rpk );
tr = Reverse( rtr );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

calculateZigZag();
calculateLastSegments();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


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



_SECTION_END();

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


_SECTION_BEGIN( "Shivoham-ZigZag" );



mZigZag_DisplaySwitch = ParamToggle( "Display Major-ZigZag", "Off|On", 0 );
mZigZag_Pivot_Shapes_DisplaySwitch = ParamToggle( "Display Major-ZigZag's Pivot-Shapes", "Off|On", 0 );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 // Peak & Trough
 
xPeak = pk;
xTrough =tr; 

PeakHigh = ValueWhen( xPeak, High);
TroughLow = ValueWhen( xTrough, Low);

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 // Determine Trend
// Letter 'x' is added before variable 'UpTrend' & 'DownTtrend' until its not decided which trend comes before and which trend comes after.  
xDownTrend = Cross( TroughLow, Low );
xUpTrend = Cross( High, TroughLow );

xDownTrend_D = xDownTrend = ExRem( xDownTrend, xUpTrend );
xUpTrend_U = xUpTrend = ExRem( xUpTrend, xDownTrend );

xDownTrend = Flip( xDownTrend_D, xUpTrend_U );
xUpTrend = Flip( xUpTrend_U, xDownTrend_D );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Find highest-high after trend turns downside and find lowest-trough after trend turns upside.

UpTrendIndex = ValueWhen( xUpTrend, bi );
DownTrendIndex = ValueWhen( xDownTrend, bi );

UpTrend = IIf( DownTrendIndex > UpTrendIndex, xDownTrend, Null );
DownTrend = IIf( UpTrendIndex > DownTrendIndex, xUpTrend, Null );

UpTrend_Periods = UpTrendIndex -DownTrendIndex; 
DownTrend_Periods = DownTrendIndex -UpTrendIndex;

UpTtrend_HighestHigh = HHV( High, UpTrend_Periods );
DownTrend_LowestLow = LLV( Low, DownTrend_Periods );

xPeak = IIf( DownTrend, UpTtrend_HighestHigh, Null  );
xTrough = IIf( UpTrend, DownTrend_LowestLow, Null  );

xPeakIndex = ValueWhen( xPeak, bi );
xTroughIndex = ValueWhen( xTrough, bi );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Setting Zigzag's up-line's top as xPeak and upline's bottom xTrough
UpLegTop = IIf( xPeak AND xPeakIndex > xTroughIndex, xPeak, Null ) ;
UpLegBottom = IIf( xPeak AND xPeakIndex > xTroughIndex, xTrough, Null ) ; 

// Setting Zigzag's down-line's bottom as xTrough and down-line's top as xPeak  
DownLegTop = IIf( xTrough AND xTroughIndex > xPeakIndex, xTrough, Null ) ;
DownLegBottom = IIf( xTrough AND xTroughIndex > xPeakIndex, xPeak, Null ) ;
 
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Up-Leg's X-&-Y coordinates
UpBottom_x = ValueWhen( UpLegBottom, bi );
UpBottom_y = ValueWhen( UpLegBottom, Low );
UpTop_x = ValueWhen( UpLegTop, bi );
UpTop_y = ValueWhen( UpLegTop, High );


// Down-Leg's X-&-Y coordinates
DownBottom_x = ValueWhen( DownLegBottom, bi );
DownBottom_y = ValueWhen( DownLegBottom, Low );
DownTop_x = ValueWhen( DownLegTop, bi );
DownTop_y = ValueWhen( DownLegTop, High );

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  
// Empottasch's code to draw Lines
MajorZigZag = Null;
    
	for( i = EndValue(bi); i >= BeginValue(bi); i-- )
    //for( i = Last_Visible_Value; i > First_Visible_Value; i-- )
    {
        if( UpLegTop[i] )
        {
            Line = LineArray( UpBottom_x[i], UpBottom_y[i], UpTop_x[i], UpTop_y[i] );
            MajorZigZag = IIf( Line, Line, MajorZigZag );
        }

        if( DownLegBottom[i] )
        {
            Line = LineArray( DownTop_x[i], DownTop_y[i], DownBottom_x[i], DownBottom_y[i] );
            ZigZag = IIf( Line, Line, MajorZigZag );
        }
    }

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

MajorZigZag = IIf( MajorZigZag, MajorZigZag, zigzag );
    
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

if( mZigZag_DisplaySwitch )
	   {
			mZigZag_UpLine_Color = ParamColor( "Major-ZigZag's UpLine-Color", colorBlue );
			mZigZag_DownLine_Color =  ParamColor( "Major-ZigZag DownLine-Color", colorBlue );
			mZigZag_Color = IIf( (MajorZigZag > Ref( MajorZigZag, -1 )), Major_ZigZag_UpLine_Color,
							IIf( (MajorZigZag < Ref( MajorZigZag, -1 )), Major_ZigZag_DownLine_Color, Null ) );
			
			Plot( MajorZigZag, "", Major_ZigZag_Color, styleLine | styleNoLabel | styleNoRescale, Null, Null, 0, 0, 8 );
		}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    
	if( mZigZag_Pivot_Shapes_DisplaySwitch )
	   {
			PlotShapes( IIf( DownLegTop, shapeCircle, shapeNone ), colorRed, 0, H, 50 );
			PlotShapes( IIf( DownLegBottom, shapeCircle, shapeNone ), colorGreen, 0, L, -50 );
		}


_SECTION_END();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
![001|690x330](upload://1nCKBTJAuyPeF3FaNpgX4yLAwxt.png)
![002|690x330](upload://8KgfOjvOhMSdMf2re03rGf6zreo.png)


Found an error in line 261.

This should be:

xUpTrend = Cross( High, PeakHigh );

But even after that code is not succeful. Kindly guide.

Still waiting for any answer from any kind hearted soul. Please help.

@LotusHeart,I cannot help with the logic to draw additional lines (unfortunately, not my cup of tea...).
IMO, the resident guru for this kind of code is @empottasch

In any case, since it seems that the code you added is directly derived (and subsequently modified) from the previous one, I see variables whose names have not been updated and which generate errors when you turn On the "Display Major Zig-Zag".

image

I suggest starting to fix these simple errors; something like this:

if( mZigZag_DisplaySwitch )
	   {
			mZigZag_UpLine_Color = ParamColor( "Major-ZigZag's UpLine-Color", colorBlue );
			mZigZag_DownLine_Color =  ParamColor( "Major-ZigZag DownLine-Color", colorBlue );
			mZigZag_Color = IIf( (MajorZigZag > Ref( MajorZigZag, -1 )), mZigZag_UpLine_Color,
							IIf( (MajorZigZag < Ref( MajorZigZag, -1 )), mZigZag_DownLine_Color, Null ) );
			
			Plot( MajorZigZag, "", mZigZag_Color, styleLine | styleNoLabel | styleNoRescale, Null, Null, 0, 0, 8 );
		}

This does not address/solve the issue of drawing the correct "major" lines, but at least the code will run to debug it further.

1 Like

i already worked with Lotusheart last week and I just have problems understanding the rules (partially a language issue). It is all too complicated for me. Also I spent weeks (months) on Gann code last year that I never use. I just do not find it interesting anymore. Too much detail/rules, drives me nuts.

I can post the Python code if Lotusheart permits. I expanded that code that it draws the pivots. I failed to translate this to AFL. So maybe someone else can do that translation to AFL. So if Lotusheart wants me to post that Python code let me know. The output looks like this in Python:

1 Like

Yes. Mr. Empottasch you can post the python code anywhere. And those complicated rules that I discussed last week you can ignore them. Just kindly help me to solve this problem. There is no complicated rule here. It’s a very simple thing and rest anyone can understand by looking at the code.Everything is already described in the post. Thanks for responding.

this python code works for me. I run it from the Visual Studio Code editor but you can also run it just from the console

import yfinance as yf
import pandas as pd
import numpy as np
from datetime import date, timedelta, datetime
import matplotlib.pyplot as plt
import mplfinance as mpf
#from operator import itemgetter

today = date.today()
date_today = today.strftime("%Y-%m-%d")
date_start = '2024-01-01'

# Getting NASDAQ quotes
#stockname = 'HONAUT'
#symbol = 'HONAUT.NS'
stockname = 'TSLA'
symbol = 'TSLA'

stock_df = yf.download(symbol, start=date_start, end=date_today)
stock_df['Date'] = stock_df.index
stock_df['Pivots'] = stock_df['Close']
stock_df['Pivots'] = np.nan
print(stock_df)

def momentum_check(candle1_high, candle1_low, candle2_high, candle2_low):
    '''
    returns:
            trend_continuation: Bool
            candle_type: Inside, Outside, Continuation
    '''
    
    #If candles are moving in Upwards in a HH and HL formation
    if candle2_high > candle1_high and candle2_low > candle1_low:
        return True, 'Upward'
    
    # If candles are moving Downwards in a LH and LL formation 
    if candle2_high < candle1_high and candle2_low < candle1_low:
        return True, 'Downward'
    
    # Inside Candle
    # Candles forming LH and HL formation
    if candle2_high <= candle1_high and candle2_low >= candle1_low:
        return False, 'Inside'
    
    # Outside Candle
    # Candles are forming HH and LL formation
    if candle2_high > candle1_high and candle1_low > candle2_low:
        return False, 'Outside'
		

def primary_pivot_alter_check(primary_pivot_list, current_trend, candle_type, candle1_high, candle1_low):
    last_pivot = primary_pivot_list[-1][0]
    print('Entering primary_pivot_alter_check')
    # If last pivot is higher than low of outside candle
    if current_trend == 'Upward' and candle_type == 'Upward':
        if last_pivot > candle1_low:
            print(f'{current_trend}, last pivot: {last_pivot}, candle: {candle1_high}')
            primary_pivot_list[-1][0] = candle1_low
            print(f'+++++++++++++++++++Pivot changed to {primary_pivot_list[-1]}+++++++++++++++++++++++++++++')
            
    # If last pivot high is lower than the high of outside candle
    if current_trend == 'Downward' and candle_type == 'Downward':
        if candle1_high > last_pivot:
            print(f'{current_trend}, last pivot: {last_pivot}, candle: {candle1_high}')
            primary_pivot_list[-1][0] = candle1_high
            print(f'+++++++++++++++++++Pivot changed to {primary_pivot_list[-1]}+++++++++++++++++++++++++++++')
            
    return primary_pivot_list
    
    
def change_trend_update_pivots(primary_pivot_list, current_trend, candle_type, candle1_high, candle1_low, stock_df, i):
    current_trend = candle_type   # Updating current trend
    if candle_type == 'Upward':
        primary_pivot_list.append([candle1_low, stock_df["Date"].iloc[i], current_trend])
    if candle_type == 'Downward':
        primary_pivot_list.append([candle1_high, stock_df["Date"].iloc[i], current_trend])
    print(primary_pivot_list[-1],'\n')
    
    return primary_pivot_list, current_trend
        

 # Define a function 'remove_column' that extracts and removes a specified column from a nested list
def remove_column(nums, n):
   # Use a list comprehension to extract and remove the column 'n' from each sublist in 'nums'
   result = [i.pop(n) for i in nums]
   # Return the extracted values in the 'result' list
   return result 

primary_pivot_list = []
current_trend = None
outside_candle_flag = False

i = 1
while i < len(stock_df)-1:
#    print('\n')
#    print(f'i start: {i}')
    # Default outside_candle_flag to False
    outside_candle_flag = False
    candle1_high, candle1_low = stock_df['High'].iloc[i], stock_df['Low'].iloc[i]
    candle2_high, candle2_low = stock_df['High'].iloc[i+1], stock_df['Low'].iloc[i+1]
    
    trend_continuation, candle_type = momentum_check(candle1_high, candle1_low, candle2_high, candle2_low)
    print(stock_df['Date'].iloc[i+1], trend_continuation, candle_type)
    
    # Keep the prev momentum candle high and low 
    # If we get continues inside or outside candles
    range_count = 0
    while candle_type not in ['Upward','Downward']:
        candle1_high, candle1_low = candle1_high, candle1_low
        candle2_high, candle2_low = stock_df['High'].iloc[i+1+range_count], stock_df['Low'].iloc[i+1+range_count]
        
        print(f'Price: {candle1_high}, {candle1_low}, {candle2_high}, {candle2_low}')
        trend_continuation, candle_type = momentum_check(candle1_high, candle1_low, candle2_high, candle2_low)
        
        # Consider the Highest and Lowest point if the trend chagges 
        # during a consolidation (Multiple no directional candles)
        if candle_type == 'Outside':
            outside_candle_flag = True
            candle1_high = max(candle1_high, candle2_high)
            candle1_low = min(candle1_low, candle2_low)
            print(f'Price Change: {candle1_high}, {candle1_low}, {candle2_high}, {candle2_low} ############################')
            
        print(f'{stock_df["Date"].iloc[i+1+range_count]} {trend_continuation} {candle_type}------------')
        range_count = range_count + 1
        print(f'range_count: {range_count}')
        
    # If there is a change in trend and outside candle occured in range(consolidation)
    if trend_continuation and outside_candle_flag and current_trend == candle_type:
        primary_pivot_list = primary_pivot_alter_check(primary_pivot_list, current_trend, candle_type, candle1_high, candle1_low)
    
    # When Trend is changing
    if trend_continuation == True and current_trend != candle_type:
        print(f'--PIVOT-- {current_trend}, {candle_type} {stock_df["Date"].iloc[i+1]}')
        primary_pivot_list, current_trend = change_trend_update_pivots(primary_pivot_list, current_trend, candle_type, candle1_high, candle1_low, stock_df, i)
    
    if range_count:
        i = i+range_count
    else:
        i = i + 1
#    print(f'i end: {i}')
#    if trend_continuation == True:
#        continue
        
#print(primary_pivot_list[0][2])

the_price = 0
for i in range(len(primary_pivot_list)):
    # extract price
    #the_price[i] = primary_pivot_list[i][0]
    stock_df['Pivots'].loc[primary_pivot_list[i][1]] = primary_pivot_list[i][0]
    #print(stock_df['Close'].loc[primary_pivot_list[i][1]])

'''
the_price = remove_column(primary_pivot_list, 0)
the_pivot = remove_column(primary_pivot_list, 1)
#the_pivot = remove_column(primary_pivot_list, 2)

print(the_price)
print(the_pivot)
'''
print(stock_df)

#stock_df.plot(x="Date", y=["High","Low"], kind="line", figsize=(10, 10))
#stock_df.plot(x="Date", y=["High","Low","Pivots"], marker = ['_','_','x'], figsize=(10, 10))
#stock_df.plot(x="Date", y=["Pivots"],marker="x") 
# Display plot

datearray = stock_df["Date"].to_numpy()
higharray = stock_df["High"].to_numpy()
lowarray = stock_df["Low"].to_numpy()
pivotsarray = stock_df["Pivots"].to_numpy()

s1mask = np.isfinite(pivotsarray)

plt.plot(datearray,higharray)
plt.plot(datearray,lowarray)
plt.plot(datearray[s1mask],pivotsarray[s1mask],'-o')
#plt.plot(stock_df["Date"],stock_df["High"])
#plt.plot(stock_df["Date"],stock_df["Low"])
#plt.plot(stock_df["Date"],stock_df["Pivots"])
plt.legend(['High','Low','Pivots']) 

#ax = plt.subplot() 
#mpf.plot(stock_df, type="candle", ax=ax)

plt.show()
1 Like

Thanks Mr. Empottasch for improving my python code and sharing with the Amibroker community. This code is actually not mine. Just the idea behind that code is mine. One of my friend who is well versed in Python coded that for. Just before saying yes to share the code, I also asked from that friend, because it was a joint effort. I hope soon someone will find it interesting and translate this code in AFL and will share with the community.

yes the only code I added to that Python code is the yahoo data put in a dataframe and then the existing code returned a list of a list with the pivot points and I extracted these pivots and put them also in the pandas dataframe. Then I made a simple chart.

With respect to the code you posted using parts of my code I posted elsewhere. Below I show how it is intended to be used using a simple trendchange. It is up to you to add the outbars and inbars.

_SECTION_BEGIN( "Lotusheart" );

// global declarations
bi = BarIndex();
fvb = FirstVisibleValue( bi );
lvb = LastVisibleValue( bi );
pk = tr = 0;
prch = H;
prcl = L;
zigzag = line1 = Null;

// define the functions
function calculatePivots( upbar, downbar )
{
    trend = 1; // start trend at 1 or -1 doesnt matter
    topprc = 0;
    topidx = 0;
    botprc = 0;
    botidx = 0;
    pk = tr = 0;

    for( i = 0; i < BarCount; i++ )
    {
        if( trend > 0 )
        {
            // trend turning down, avoid same bar as the peak
            if( downbar[i] )
            {
                pk[topidx] = 1;
                botprc = L[i];
                botidx = i;
                trend = -1;
            }
            else

                // still in uptrend but new top reached
                if( H[i] >= topprc )
                {
                    topprc = H[i];
                    topidx = i;
                }
        }
        else
            if( trend < 0 )
            {
                // trend turning up, avoid same bar as the trough
                if( upbar[i] )
                {
                    tr[botidx] = 1;
                    topprc = H[i];
                    topidx = i;
                    trend = 1;
                }
                else

                    // still in downtrend but new trough reached
                    if( L[i] <= botprc )
                    {
                        botprc = L[i];
                        botidx = 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 );

    return zigzag;
}

function calculateLastSegment()
{
    lastidxpk = LastValue( ValueWhen( pk, bi ) );
    lastidxtr = LastValue( ValueWhen( tr, bi ) );
    lastvalpk = LastValue( ValueWhen( pk, prch ) );
    lastvaltr = LastValue( ValueWhen( tr, prcl ) );
    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( 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( 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 );
}

// define trendchange
upbar = High > Ref( High, -1 ) and Low >= Ref( Low, -1 );
downbar = High <= Ref( High, -1 ) and Low < Ref( Low, -1 );

// calculate pivots
calculatePivots( upbar, downbar );

// calculate zigzag
zigzag = calculatezigzag();

// calculate last segment of zigzag
calculateLastSegment();

// chart
SetChartOptions( 0, chartShowDates );
SetChartBkColor( ColorRGB( 0, 0, 0 ) );
_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) );
Plot( C, " | Data | ", colorDefault, styleCandle, Null, Null, 0, 0, 3 );
Plot( zigzag, " | zigzag | ", colorAqua, styleLine | styleNoRescale, Null, Null, 0, 0, 1 );
PlotShapes( IIf( tr, shapeSmallCircle, shapeNone ), colorGreen, 0, L, -20 );
PlotShapes( IIf( pk, shapeSmallCircle, shapeNone ), colorRed, 0, H, 20 );
_SECTION_END();

Hello guys, ultimately problem is solved. Here is the insight I used for the solution: I wanted to have a super zigzag which is imposed over another zigzag. For that purpose I studied @empttasch’s zigzag by using the exploration and realized that I should use the same logic with the peaks & troughs to generate new peaks & troughs for the imposed zigzag. In other words, @empottasch’s zigzag is using the up-bar and down-bar definition and in another zigzag highest-high & lowest-low definition to generate the peaks & troughs for the zigzag; similarly, I defined the relation between peaks & troughs like higher-peak & lower-peak and used that definition as an input for the zigzag function and got new peaks & troughs to generate my overlayed zigzag on the top of another zigzag. Thanks to @empttasch for his zigzag and to @beppe mentioning the debugging to understand how code is working.

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.