Buy and Sell Signal was generated but only zero backtest results I got

Hi everyone

I tried "Fractal Pivots" from E.M.Pottasch and modified it to eliminate future leak from the code as following


Plot( C, "", IIf( C > O, ColorRGB( 0, 255, 0 ), IIf( C <= O, ColorRGB( 255, 0, 0 ), colorLightGrey ) ), 64, Null, Null, 0, 0, 1 );

// Fractal Pivots, E.M.Pottasch 2/2018
bi = BarIndex();
fvb = FirstVisibleValue( bi );
lvb = LastVisibleValue( bi );

rightstrength = Param( "Right Strength", 5, 1, 50, 1 );
leftstrength = Param( "Left Strength", 5, 1, 50, 1 );
fact = Param( "Chart Time Frame Factor", 1, 1, 10, 1 );

rightStrength = rightStrength * fact;
leftStrength = leftStrength * fact;

pk = 0;
tr = 0;
pkl = 0;
trl = 0;
for( i = lvb; i > fvb; i-- )
{
	j = i  - leftStrength + 1;
	j = IIf(j<0, 0, j);
	LeftHighest = 0;
	LeftLowest =L[j];
	while(j <= i) {
		if (LeftHighest < H[j]) {
			LeftHighest = H[j];
		}
		if (LeftLowest > L[j]) {
			LeftLowest = L[j];
		}
		j = j + 1;
	}
	
	DistantUntilLastBar = (BarCount - 1) - i;
	
	SafeRightStrength = IIf(DistantUntilLastBar >= rightStrength, rightStrength, DistantUntilLastBar);
	k = i + SafeRightStrength;
	RightHighest = 0;
	RightLowest = L[k];
	while(k > i) {
		if (RightHighest < H[k]) {
			RightHighest = H[k];
		}
		if (RightLowest > L[k]) {
			RightLowest = L[k];
		}
		k = k - 1;
	}
	pk[i] = H[i] == LeftHighest AND RightHighest < H[i];
	tr[i] = L[i] == LeftLowest AND RightLowest > L[i];
	pkl[i] = H[i] == LeftHighest;
	trl[i] = L[i] == LeftLowest;
}

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

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

Buy = BarsSince(hh) == 1;
Sell = BarsSince(Buy) >= 10;
Sell = ExRem(Sell, Buy);

PlotShapes(Buy * shapeUpArrow, colorGreen, 0, L, -25);
PlotShapes(Sell * shapeDownArrow, colorRed, 0, H, -25);

doubleTopThreshold = 0.75 * Ref( ATR( 20 ), -1 );
doubleTop = pk && abs( ph1 - ph2 ) < doubleTopThreshold;

doubleBottomThreshold = 0.75 * Ref( ATR( 20 ), -1 );
doubleBottom = tr && abs( tl1 - tl2 ) < doubleBottomThreshold;

for( i = lvb; i > fvb; i-- )
{
    sz = 8;

    // troughs
    if( ll[i] )
    {
        str = "LL";
        PlotTextSetFont( str, "Arial Black", sz, i, L[i], ColorRGB( 0, 250, 0 ), colorDefault, -30 );
    }

    if( hl[i] )
    {
        str = "HL";
        PlotTextSetFont( str, "Arial Black", sz, i, L[i], ColorRGB( 0, 250, 0 ), colorDefault, -30 );
    }

    if( db[i] )
    {
        str = "DB";
        PlotTextSetFont( str, "Arial Black", sz, i, L[i], ColorRGB( 0, 250, 0 ), colorDefault, -30 );
    }

    //peaks
    if( hh[i] )
    {
        str = "HH";
        PlotTextSetFont( str, "Arial Black", sz, i, H[i], ColorRGB( 250, 0, 0 ), colorDefault, 20 );
    }

    if( lh[i] )
    {
        str = "LH";
        PlotTextSetFont( str, "Arial Black", sz, i, H[i], ColorRGB( 250, 0, 0 ), colorDefault, 20 );
    }

    if( dt[i] )
    {
        str = "DT";
        PlotTextSetFont( str, "Arial Black", sz, i, H[i], ColorRGB( 250, 0, 0 ), colorDefault, 20 );
    }

    if( doubleTop[i] )
    {
        str = "Double Top";
        PlotTextSetFont( str, "Arial Black", sz, i, H[i], ColorRGB( 250, 125, 0 ), colorDefault, 40 );
    }
    
     if( doubleBottom[i] )
    {
        str = "Double Bottom";
        PlotTextSetFont( str, "Arial Black", sz, i, L[i], ColorRGB( 250, 125, 0 ), colorDefault, -40 );
    }
    
}

writeif( highest( doubleTop ) == 1, "\nAmiBroker has detected some possible Double Top patterns for " + name() + "\n\nLook for TAG on the price chart.", "\n\nThere are no double top patterns for " + name() );
writeif( highest( doubleBottom ) == 1, "\n\nAmiBroker has detected some possible Double Bottom patterns for " + name() + "\n\nLook for TAG on the price chart.", "\nThere are no double top patterns for " + name() );

When I use it to plot buy/sell shape, it's show every signal correctly as expectly. But when I trid to backtest, it's show zero row in Result list in Analysis window. To check that my system work properly, I change the Buy signal code from

Buy = BarsSince(hh) == 1;

to

Buy = C > Ref(HHV(H, 60), -1);

Then I got the result in Result list as I expected.

What could be the source of this problem? I can't find the answer by myself because it's beyond my (limited) knowledge in afl language and environment.

Please help me.

hi,

I did not go into the details of your code but if you do a playback you will see it repaints. So it will never work.

so below is an adjusted version that can be backtested on futures and does not repaint

Plot( C, "", IIf( C > O, ColorRGB( 0, 255, 0 ), IIf( C <= O, ColorRGB( 255, 0, 0 ), colorLightGrey ) ), 64, Null, Null, 0, 0, 1 );

// Fractal Pivots, E.M.Pottasch 2/2018
bi = BarIndex();
fvb = FirstVisibleValue( bi );
lvb = LastVisibleValue( bi );

rightstrength = Param( "Right Strength", 5, 1, 50, 1 );
leftstrength = Param( "Left Strength", 5, 1, 50, 1 );
fact = Param( "Chart Time Frame Factor", 1, 1, 10, 1 );

rightStrength = rightStrength * fact;
leftStrength = leftStrength * fact;

pk = H == HHV( H, leftstrength ) AND Ref( HHV( H, rightstrength ), rightstrength ) < H;
tr = L == LLV( L, leftstrength ) AND Ref( LLV( L, rightstrength ), rightstrength ) > L;

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

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

hhlevel = Ref( ValueWhen( hh, H ), -rightstrength );
Plot( hhlevel, "", colorAqua, styleLine | styleNoRescale, Null, Null, 0, 0, 1 );

SetTradeDelays( 0, 0, 0, 0 );
SetOption( "FuturesMode", True );
SetOption( "PriceBoundChecking", False );
SetOption( "AllowSameBarExit", True );
SetOption( "CommissionMode", 3 );
SetOption( "CommissionAmount", 2.5 );
NumContracts = 1;
SetOption( "MaxOpenPositions", 6 );
PositionSize = NumContracts * MarginDeposit;

Buy = Cross( C, hhlevel );
Buy = Ref( Buy, -1 );
Sell = BarsSince( Buy ) == 10;
Buy = ExRem( Buy, Sell );
Sell = ExRem( Sell, Buy );

BuyPrice = O;
SellPrice = C;

PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ), colorLightBlue, 0, L, -15 );
PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ), colorOrange, 0, H, -15 );
PlotShapes( IIf( Buy, shapeSmallCircle, shapeNone ), colorWhite, 0, BuyPrice, 0 );
PlotShapes( IIf( Sell, shapeSmallCircle, shapeNone ), colorWhite, 0, SellPrice, 0 );

for( i = lvb; i > fvb; i-- )
{
    sz = 8;

    // troughs
    if( ll[i] )
    {
        str = "LL";
        PlotTextSetFont( str, "Arial Black", sz, i, L[i], ColorRGB( 0, 250, 0 ), colorDefault, -30 );
    }

    if( hl[i] )
    {
        str = "HL";
        PlotTextSetFont( str, "Arial Black", sz, i, L[i], ColorRGB( 0, 250, 0 ), colorDefault, -30 );
    }

    if( db[i] )
    {
        str = "DB";
        PlotTextSetFont( str, "Arial Black", sz, i, L[i], ColorRGB( 0, 250, 0 ), colorDefault, -30 );
    }

    //peaks
    if( hh[i] )
    {
        str = "HH";
        PlotTextSetFont( str, "Arial Black", sz, i, H[i], ColorRGB( 250, 0, 0 ), colorDefault, 20 );
    }

    if( lh[i] )
    {
        str = "LH";
        PlotTextSetFont( str, "Arial Black", sz, i, H[i], ColorRGB( 250, 0, 0 ), colorDefault, 20 );
    }

    if( dt[i] )
    {
        str = "DT";
        PlotTextSetFont( str, "Arial Black", sz, i, H[i], ColorRGB( 250, 0, 0 ), colorDefault, 20 );
    }
}
1 Like

Thank you so much for very responsive answer. Very appreciated.

Buy and Sell show at my machine as following:
01

When I run backtest, it's show the empty result:
02

The following images are my analysis configuration:
03
04

hi,

this has to do with the trading settings. I set it up to backtest a future contract. If you want to backtest stocks the settings should be different.

You can use all your setting but change this in the code. Then you will get some results in the backtester. But you have to study the topic a bit, go through a few examples

//SetTradeDelays( 0, 0, 0, 0 );
//SetOption( "FuturesMode", True );
//SetOption( "PriceBoundChecking", False );
//SetOption( "AllowSameBarExit", True );
//SetOption( "CommissionMode", 3 );
//SetOption( "CommissionAmount", 2.5 );
//NumContracts = 1;
//SetOption( "MaxOpenPositions", 6 );
//PositionSize = NumContracts * MarginDeposit;
SetTradeDelays( 0, 0, 0, 0 );
SetOption("MaxOpenPositions", 10 ); 
PositionSize = 5000;

Thank you so much. I tried it without success. When I try to replay chart, I found it is repaint everytime new bar was added.

So my code didn't work from the start.

hi,

maybe first go through this manual page: Back testing your trading ideas

then try out a few simple examples.

Are there anyway to create the Swing HH and LL signal without look ahead to the 'right' side?

i wish there was :slightly_smiling_face:

there are a few methods to create pivots. Fractals is 1 of them. None of the pivots will be known in real time. Below some code that uses ATR pivots. Try doing a Playback. The last pivot is only know when you see a buy or sell signal come in. That is when the trend changes and the last pivot is known.

The last pivot in the chart can always repaint if new data comes in.

per = Param( "ATR Period", 50, 1, 100, 1 ); // you need at least "per" data points to run this code
mult = Param( "ATR Multiple", 3, 0.5, 20, 0.1 );
priceswitch = ParamToggle( "Use Close or High and Low price", "Use Close|Use High and Low", 0 );
labelsswitch = ParamToggle( "Show Labels", "Off|On", 1 );
plottrailswitch = ParamToggle( "Show Trail Line", "No|Yes", 1 );
sz = Param( "Text Size", 7, 5, 20, 1 );

GraphXSpace = sz / 2;

bi = BarIndex();
fvb = FirstVisibleValue( bi );
lvb = LastVisibleValue( bi );
pk = tr = Buy = Sell = BuyPrice = SellPrice = 0;
trailarrayup = trailarraydn = Null;

if( priceswitch )
{
    prch = H;
    prcl = L;
}
else
{
    prch = C;
    prcl = C;
}

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

slip = TickSize * 0;
sup = round( ( prch - mult * ATR( per ) ) / TickSize ) * TickSize;
res = round( ( prcl + mult * ATR( per ) ) / TickSize ) * TickSize;

trend = 1; // start trend at 1 or -1 doesnt matter
topprc = 0;
topidx = 0;
botprc = 0;
botidx = 0;

for( i = per + 1; i < BarCount; i++ )
{
    if( trend > 0 )
    {

        // trend turning down, avoid same bar as the peak
        if( prcl[i] < trailarrayup[i - 1] AND prch[i] < topprc )
        {
            pk[topidx] = 1;
            botprc = prcl[i];
            botidx = i;
            trend = -1;
            Sell[i] = 1;
            SellPrice[i] = C[i] - slip;
            trailarraydn[i] = res[i];
            //trailarrayup[i] = trailarrayup[i - 1];
        }
        else

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

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

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

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

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

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

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

// 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 );
ZigZag = IIf( !IsEmpty( line1 ), line1, ZigZag );

uptrend1 = Flip( Buy, Sell );
dntrend1 = Flip( Sell, Buy );
trn = LowestSince( pk, prcl ) == prcl && dntrend1;
pkn = HighestSince( tr, prch ) == prch && uptrend1;

SetChartBkColor( ColorRGB( 0, 0, 0 ) );
SetChartOptions( 0, chartShowArrows | chartShowDates );
Plot( C, "C", colorWhite, styleCandle, Null, Null, 0, 0, 0 );
//Plot( IIf( !IsEmpty( line1 ), line1, Null ), "", ColorRGB( 255, 255, 0 ), styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, -1, 4 );
Plot( ZigZag, "", IIf( uptrend1, colorAqua, colorOrange ), styleLine | styleNoRescale | styleNoLabel, Null, Null, 0, 0, 1 );

PlotShapes( shapeSmallCircle * tr, colorGreen, 0, L, -10 );
PlotShapes( shapeSmallCircle * pk, colorRed, 0, H, 10 );

if( plottrailswitch )
{
    Plot( trailarrayup, "trail up", colorLightBlue, styleDashed | styleDots | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 1 );
    Plot( trailarraydn, "trail dn", colorOrange, styleDashed | styleDots | styleNoRescale | styleNoLabel, Null, Null, 0, 1, 1 );
    PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ), colorLightBlue, 0, L, -15 );
    PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ), colorOrange, 0, H, -15 );
    PlotShapes( IIf( Buy, shapeSmallSquare, shapeNone ), colorYellow, 0, BuyPrice, 0 );
    PlotShapes( IIf( Sell, shapeSmallSquare, shapeNone ), colorYellow, 0, SellPrice, 0 );
}

ft = "Arial Black";
clr = colorDefault;
GfxSetZOrder( -1 );
GfxSetCoordsMode( 1 );

if( labelsswitch )
{
    str1 = "";
    str2 = "";

    for( i = fvb; i <= lvb; i++ )
    {
        if( pk[i] )
        {
            if( dt[i] )
                str1 = "DT";

            if( hh[i] )
                str1 = "HH";

            if( lh[i] )
                str1 = "LH";

            PlotTextSetFont( str1, ft, sz, i, H[i], colorRed, clr, sz * 3 );
        }

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

            if( db[i] )
                str1 = "DB";

            if( ll[i] )
                str1 = "LL";

            if( hl[i] )
                str1 = "HL";

            PlotTextSetFont( str1, ft, sz, i, L[i], colorGreen, clr, -sz * 4 );
        }
    }
}
1 Like

Great thank for your great help.

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