Wednesday, 23 October 2019

POLYNOMIAL for Amibroker (AFL)









_SECTION_BEGIN("nth ( 1 - 8)");


// *********************************************************
// *
// * VBS Function for Gaussian Elimination
// *
// *     Called by PolyFit ( AFL )
// *
// *********************************************************

EnableScript("VBScript");

<%
function Gaussian_Elimination (GE_Order, GE_N, GE_SumXn, GE_SumYXn)
    Dim b(10, 10)
    Dim w(10)
    Dim Coeff(10)

    for i = 1 To 10
        Coeff(i) = 0
    next

    n = GE_Order + 1

    for i = 1 to n
        for j = 1 to  n
            if i = 1 AND j = 1 then
                b(i, j) = cDBL(GE_N)
            else
                b(i, j) = cDbl(GE_SumXn(i + j - 2))
            end if
        next     
        w(i) = cDbl(GE_SumYXn(i))
    next

    n1 = n - 1
    for i = 1 to n1
        big = cDbl(abs(b(i, i)))
        q = i
        i1 = i + 1

        for j = i1 to n
            ab = cDbl(abs(b(j, i)))
            if (ab >= big) then
                big = ab
                q = j
            end if
        next

        if (big <> 0.0) then
            if (q <> i) then
                for j = 1 to n
                    Temp = cDbl(b(q, j))
                    b(q, j) = b(i, j)
                    b(i, j) = Temp
                next
                Temp = w(i)
                w(i) = w(q)
                w(q) = Temp
            end if
        end if

        for j = i1 to n
            t = cDbl(b(j, i) / b(i, i))
            for k = i1 to n
                b(j, k) = b(j, k) - t * b(i, k)
            next        
            w(j) = w(j) - t * w(i)
        next     
    next

    if (b(n, n) <> 0.0) then

        Coeff(n) = w(n) / b(n, n)
        i = n - 1

        while i > 0
            SumY = cDbl(0)
            i1 = i + 1
            for j = i1 to n
                SumY = SumY + b(i, j) * Coeff(j)
            next
            Coeff(i) = (w(i) - SumY) / b(i, i)
            i = i - 1
        wend  

        Gaussian_Elimination = Coeff

    end if
end function
%>

// *********************************************************
// *
// * AFL Function for nth Order Polynomial Fit
// *     Calls Gaussian_Elimination ( VBS )
// *
// *     Y      = The array to Fit
// *     BegBar = Beg Bar in range to fit
// *     EndBar = End Bar in range to fit
// *     Order  = 1 - 8 = Order of Poly Fit (Integer)
// *     ExtraB = Number of Bars to Extrapolate (Backward)
// *     ExtraF = Number of Bars to Extrapolate (Forward)
// *
// *********************************************************

function PolyFit(GE_Y, GE_BegBar, GE_EndBar, GE_Order, GE_ExtraB, GE_ExtraF)
{
    BI        = BarIndex();

    GE_N      = GE_EndBar - GE_BegBar + 1;
    GE_XBegin = -(GE_N - 1) / 2;
    GE_X      = IIf(BI < GE_BegBar, 0, IIf(BI > GE_EndBar, 0, (GE_XBegin + BI - GE_BegBar)));

    GE_X_Max  = LastValue(Highest(GE_X));

    GE_X      = GE_X / GE_X_Max;

    X1 = GE_X;
    AddColumn(X1, "X1", 1.9);

    GE_Y      = IIf(BI < GE_BegBar, 0, IIf(BI > GE_EndBar, 0, GE_Y));

    GE_SumXn  = Cum(0);
                                 GE_SumXn[1]   = LastValue(Cum(GE_X));
    GE_X2     = GE_X * GE_X;     GE_SumXn[2]   = LastValue(Cum(GE_X2));
    GE_X3     = GE_X * GE_X2;    GE_SumXn[3]   = LastValue(Cum(GE_X3));
    GE_X4     = GE_X * GE_X3;    GE_SumXn[4]   = LastValue(Cum(GE_X4));
    GE_X5     = GE_X * GE_X4;    GE_SumXn[5]   = LastValue(Cum(GE_X5));
    GE_X6     = GE_X * GE_X5;    GE_SumXn[6]   = LastValue(Cum(GE_X6));
    GE_X7     = GE_X * GE_X6;    GE_SumXn[7]   = LastValue(Cum(GE_X7));
    GE_X8     = GE_X * GE_X7;    GE_SumXn[8]   = LastValue(Cum(GE_X8));
    GE_X9     = GE_X * GE_X8;    GE_SumXn[9]   = LastValue(Cum(GE_X9));
    GE_X10    = GE_X * GE_X9;    GE_SumXn[10]  = LastValue(Cum(GE_X10));
    GE_X11    = GE_X * GE_X10;   GE_SumXn[11]  = LastValue(Cum(GE_X11));
    GE_X12    = GE_X * GE_X11;   GE_SumXn[12]  = LastValue(Cum(GE_X12));
    GE_X13    = GE_X * GE_X12;   GE_SumXn[13]  = LastValue(Cum(GE_X13));
    GE_X14    = GE_X * GE_X13;   GE_SumXn[14]  = LastValue(Cum(GE_X14));
    GE_X15    = GE_X * GE_X14;   GE_SumXn[15]  = LastValue(Cum(GE_X15));
    GE_X16    = GE_X * GE_X15;   GE_SumXn[16]  = LastValue(Cum(GE_X16));

    GE_SumYXn = Cum(0);
                                 GE_SumYXn[1]  = LastValue(Cum(GE_Y));
    GE_YX     = GE_Y    * GE_X;  GE_SumYXn[2]  = LastValue(Cum(GE_YX));
    GE_YX2    = GE_YX   * GE_X;  GE_SumYXn[3]  = LastValue(Cum(GE_YX2));
    GE_YX3    = GE_YX2  * GE_X;  GE_SumYXn[4]  = LastValue(Cum(GE_YX3));
    GE_YX4    = GE_YX3  * GE_X;  GE_SumYXn[5]  = LastValue(Cum(GE_YX4));
    GE_YX5    = GE_YX4  * GE_X;  GE_SumYXn[6]  = LastValue(Cum(GE_YX5));
    GE_YX6    = GE_YX5  * GE_X;  GE_SumYXn[7]  = LastValue(Cum(GE_YX6));
    GE_YX7    = GE_YX6  * GE_X;  GE_SumYXn[8]  = LastValue(Cum(GE_YX7));
    GE_YX8    = GE_YX7  * GE_X;  GE_SumYXn[9]  = LastValue(Cum(GE_YX8));

    GE_Coeff  = Cum(0);

    GE_VBS    = GetScriptObject();
    GE_Coeff  = GE_VBS.Gaussian_Elimination(GE_Order, GE_N, GE_SumXn, GE_SumYXn);

    for (i = 1; i <= GE_Order + 1; i++)
        printf(NumToStr(i, 1.0) + " = " + NumToStr(GE_Coeff[i], 1.9) + "\n");

    GE_X   = IIf(BI < GE_BegBar - GE_ExtraB - GE_ExtraF, 0, IIf(BI > GE_EndBar, 0, (GE_XBegin + BI - GE_BegBar + GE_ExtraF) / GE_X_Max));

    GE_X2  = GE_X   * GE_X; GE_X3  = GE_X2  * GE_X; GE_X4  = GE_X3  * GE_X; GE_X5  = GE_X4  * GE_X; GE_X6  = GE_X5  * GE_X;
    GE_X7  = GE_X6  * GE_X; GE_X8  = GE_X7  * GE_X; GE_X9  = GE_X8  * GE_X; GE_X10 = GE_X9  * GE_X; GE_X11 = GE_X10 * GE_X;
    GE_X12 = GE_X11 * GE_X; GE_X13 = GE_X12 * GE_X; GE_X14 = GE_X13 * GE_X; GE_X15 = GE_X14 * GE_X; GE_X16 = GE_X15 * GE_X;

    GE_Yn = IIf(BI < GE_BegBar - GE_ExtraB - GE_ExtraF, -1e10, IIf(BI > GE_EndBar, -1e10,
            GE_Coeff[1]  +
            GE_Coeff[2]  * GE_X   + GE_Coeff[3]  * GE_X2  + GE_Coeff[4]  * GE_X3  + GE_Coeff[5]  * GE_X4  + GE_Coeff[6]  * GE_X5  +
            GE_Coeff[7]  * GE_X6  + GE_Coeff[8]  * GE_X7  + GE_Coeff[9]  * GE_X8));

    return GE_Yn;
}

// *********************************************************
// *
// * Demo AFL to use PolyFit
// *
// *********************************************************

Filter = 1;

BI        = BarIndex();
PF_BegBar = BeginValue(BI);
PF_EndBar = EndValue(BI);
PF_Y      = (H + L) / 2;
PF_Order  = Param("nth Order",             3, 0,  8, 1);
PF_ExtraB = Param("Extrapolate Backwards", 0, 0, 50, 1);
PF_ExtraF = Param("Extrapolate Forwards",  0, 0, 50, 1);

Yn = PolyFit(PF_Y, PF_BegBar, PF_EndBar, PF_Order, PF_ExtraB, PF_ExtraF);

GraphXSpace = 10;

Plot(Yn, "nth Order Polynomial Fit - " + NumToStr(PF_Order, 1.0), IIf(BI > PF_EndBar - PF_ExtraF, colorWhite, IIf(BI < PF_BegBar - PF_ExtraF, colorWhite, colorBrightGreen)), styleThick, Null, Null, PF_ExtraF);
PlotOHLC(O, H, L, C, "Close", colorLightGrey, styleCandle);

_SECTION_END();


VierBox.afl for Amibroker for Amibroker (AFL)

VierBox.afl for Amibroker for Amibroker (AFL)





/*
VierBox ver 0.1. Messy programming, rough plotting, barely usable :D
         ver 0.2. * Parameter VierBox per saham bisa di save. Tidak perlu lagi memakai
                        Draw Rectangle. Big time saver :D
                    * Plot yang lebih halus
                    * fitur untuk menampilkan/menyembunyikan VierBox
                    * fitur untuk menampilkan/menyembunyikan garis vertikal
                    * fitur untuk menampilkan dan merubah warna VierBox (masih sangat sederhana)
                    * fitur untuk merubah warna garis
                    * Bagian Title akan memberikan informasi jika ada parameter yang berubah sejak
                        disave dan memberi rekomendasi apa yang hrs dilakukan.
        ver 0.3.    * Warna box sesuai rules pak Vier. Maap pak Vier, baru kelar sekarang . Ternyata susah juga buatnya :D
                    * text di box untuk menandakan box uptrend, downtrend, stackingBox, etc.
                    * Warna Outline candlestick bisa dirubah di parameter
        ver 0.3.1   * text di box untuk ExplosiveBox


Cara penggunaan: Dari Menu Parameters, Klik "RESET ALL" untuk menampilkan parameter yang telah disave
                    atau
                    Dari Menu Parameters, Klik "SAVE" untuk menyimpan parameter yang telah dirubah

Catatan teknis: parameter setiap saham disimpan di directory C:\amibroker\vierbox\namasaham.txt

Saran, usul dan komentar dipersilahkan.

*/





function startWarna( y1, y2, range )
{

    result = colorWhite;

    if ( AlmostEqual( y1,  y2 + range* 1 / 2  ) )
        result = colorRose; //downTrend

    if ( AlmostEqual( y1,  y2 + range*3 / 2  ) )
        result = colorPink;//reversal

    if ( AlmostEqual( y1,  y2 + range*5 / 2  ) )
        result = colorRed;//Crash

    if ( AlmostEqual( y1,  y2 + range*7 / 2  ) )
        result = colorDarkRed;//Crash2

    if ( AlmostEqual( y1,  y2 + range*9 / 2  ) )
        result = colorDarkRed;//Crash3

    if ( AlmostEqual( y1,  y2 - range* 1 / 2  ) )
        result = colorAqua;//upTrend

    if ( AlmostEqual( y1,  y2 - range* 3 / 2  ) )
        result = colorTurquoise;//stackingBox

    if ( AlmostEqual( y1,  y2 - range* 5 / 2  ) )
        result = colorTeal;//ExplosiveBox

    if ( AlmostEqual( y1,  y2 - range* 7 / 2  ) )
        result = colorDarkGreen;//ExplosiveBox2

    if ( AlmostEqual( y1,  y2 - range* 9 / 2  ) )
        result = colorDarkOliveGreen;//ExplosiveBox3

    return result;
} //end function ColorWhite

function textTrend( y1, y2, range )
{

    result = "?";

    if ( AlmostEqual( y1,  y2 + range* 1 / 2  ) )
        result = "DownTrend";

    if ( AlmostEqual( y1,  y2 + range* 3 / 2  ) )
        result = "Reversal";

    if ( AlmostEqual( y1,  y2 + range* 5 / 2  ) )
        result = "Crash";

    if ( AlmostEqual( y1,  y2 + range* 7 / 2  ) )
        result = "Crash2";

    if ( AlmostEqual( y1,  y2 + range* 9 / 2  ) )
        result = "Crash3";

    if ( AlmostEqual( y1,  y2 - range* 1 / 2  ) )
        result = "UpTrend";

    if ( AlmostEqual( y1,  y2 - range* 3 / 2  ) )
        result = "StackingBox";

    if ( AlmostEqual( y1,  y2 - range* 5 / 2  ) )
        result = "ExplosiveBox";

    if ( AlmostEqual( y1,  y2 - range* 7 / 2  ) )
        result = "ExplosiveBox2";

    if ( AlmostEqual( y1,  y2 - range* 9 / 2  ) )
        result = "ExplosiveBox3";

    return result;
} //end function textTrend


_SECTION_BEGIN( "Save" );
save = ParamTrigger( "Save Parameter VierBox?", "KLIK DISINI UNTUK SAVE" ) ;
_SECTION_END(); //end section "Save"

_SECTION_BEGIN( "Price" );
SetChartOptions( 0, chartShowArrows | chartShowDates );
Plot( C, "Close", ParamColor( "Warna Outline Candlestick", colorBlack ), styleNoTitle | GetPriceStyle() );
_SECTION_END(); //end section "Price"

_SECTION_BEGIN( "Tampilkan VierBox" );
DisplayVierBox = ParamToggle( "Tampilkan VierBox?", "Tidak|Ya", 1 );
_SECTION_END(); //end section "Tampilkan VierBox"

_SECTION_BEGIN( "VierBox by DF" );

//tampilanVierBox=ParamToggle("VierBox yang Ditampilkan","Permanen|Setup",0);
//jumlahBarDiBox = Param("Jumlah Bar di Box", 15, 5, 20);
//Offset= Param("Start mundur berapa bar",75,1,200);
//LineColor =   ParamColor("Warna Garis Outline", colorGreen);
//ColorStartBox = ParamColor("Warna Box Start",colorLightYellow);
//ColorBox2 = ParamColor("Warna Box 2",colorAqua);
//DisplayBoxColor=ParamToggle("Display Box Color","Yes|No",0);
//displayBoxLine=ParamToggle("Tampilkan Garis Outline Box","Ya|Tidak",0);

SetChartOptions( 0, chartShowArrows | chartShowDates );
SetBarsRequired( 100000, 100000 ); //use all bars
//EnableTextOutput( False );

if ( displayVierBox == 1 ) 
{

    //Buka file
    input_file = Name() + ".txt";
    input_folder = "vierbox";
    fh = fopen( input_folder + "\\" + input_file, "r" );

    if ( fh )
    {
        strFile = fgets( fh );
        fclose( fh );

        strStartBar = StrExtract( strfile, 0 );
        strJumlahBarDiBox = StrExtract( strFile, 1 );
        strdisplayBoxLine = StrExtract( strFile, 2 );
        strDisplayBoxColor = StrExtract( strFile, 3 );
        strlineColor = StrExtract( strFile, 4 );
        strColorStartBox = StrExtract( strFile, 5 );
        //strColorBox2 = StrExtract( strFile, 6 );

        startBar = StrToNum( strStartBar );
        lastBar = LastValue( BarIndex() ); //value jumlah total bar . Base 0
        Offset = Lastbar - startBar; //box mulai di sini. Nilai offset keluar cuma sekali di sini!
        Offset = Param( "Start Mundur Berapa Bar?", Offset, 1, 200 );
        startBar = LastBar - Offset;
        jumlahBarDiBox = StrToNum( strJumlahBarDiBox );

        jumlahBarDiBox = Param( "Jumlah Bar di Box", StrToNum( strJumlahBarDiBox ), 5, 20 );
        displayBoxLine = ParamToggle( "Tampilkan Garis Outline Box", "Tidak|Ya", StrToNum( strdisplayBoxLine ) );
        lineColor   =   ParamColor( "Warna Garis Outline Box", StrToNum( strLineColor ) );
        DisplayBoxColor = ParamToggle( "Tampilkan Warna Box", "Tidak|Ya", StrToNum( strDisplayBoxColor ) );
        ColorStartBox   = ParamColor( "Warna Start Box", StrToNum( strColorStartBox ) );
        //ColorBox2 = ParamColor( "Warna Box 2", StrToNum( strColorBox2 ) );

    }
    else //jika file yang mau dibuka gak ada, bikin jadi default dan save
    {
        printf( "error open file" );
        Offset = Param( "Start Mundur Berapa Bar?", 75, 1, 200 );
        lastBar = LastValue( BarIndex() );
        startBar = Lastbar - Offset;

        jumlahBarDiBox = Param( "Jumlah Bar di Box", 15, 5, 20 );
        displayBoxLine = ParamToggle( "Tampilkan Garis Outline Box", "Tidak|Ya", 0 );
        LineColor   =   ParamColor( "Warna Garis Outline", colorGreen );
        DisplayBoxColor = ParamToggle( "Display Box Color", "Tidak|Ya", 1 );
        ColorStartBox   = ParamColor( "Warna Start Box", colorLightYellow );
        //ColorBox2 = ParamColor( "Warna Box 2", colorAqua );


        //save
        Output_file = Name() + ".txt";
        Output_folder = "vierbox";
        fmkdir( Output_folder );
        fh = fopen( Output_folder + "\\" + Output_file, "w" );
        fputs( NumToStr( startBar, 1.0, False ) + "," + NumToStr( jumlahBarDiBox, 1.0, False ) + "," +
               NumToStr( displayBoxLine, 1.0, False ) + "," + NumToStr( displayBoxColor, 1.0, False ) + "," +
               NumToStr( Linecolor, 1.0, False ) + "," + NumToStr( ColorStartBox, 1.0, False ) + ",", fh );
        fclose( fh );
        fclose( fh );
    }

    ; //end if fh

    lastBar = LastValue( BarIndex() ); //value jumlah total bar

    lArray = LLV( Low, jumlahBardiBox ); //cari Low terendah di box awal

    hArray = HHV( High, jumlahBardiBox ); //cari High tertinggi di box awal

    VierL = Larray[startBar-1];//convert lArray jadi value

    VierH = Harray[startBar-1];//convert hArray jadi value

    range = VierH - VierL;//hitung tinggi box awal


    //cari baseline box, sedekat mungkin dengan harga 0
    //berguna agar box-box di depan selalu berada dekat bar-bar harga
    baselineBoxGenap = VierL - int( VierL / range ) * range;

    baselineBoxGanjil = VierL - int( VierL / range ) * range - range / 2;

    //start Buat box awal
    x0 = -jumlahBarDiBox + startBar;

    x1 = startBar ;

    garisBawah = LineArray( x0, VierL, x1 - 1, VierL, 0 );

    garisAtas = LineArray( x0, VierH, x1 - 1, VierH, 0 );

    if ( displayBoxLine == 1 )
    {
        garisKiriBawah = LineArray( x0 - 1, VierL  + range / 2, x0, VierL , 0 );
        garisKiriAtas = LineArray( x0 - 1, VierL  + range / 2, x0, VierL  + range, 0 );
        garisKananBawah = LineArray( x1 - 1, VierL  , x1, VierL  + range / 2, 0 );
        garisKananAtas = LineArray( x1 - 1, VierL  + range, x1, VierL  + range / 2, 0 );


        Plot( garisBawah, "", LineColor, styleNoLabel );
        Plot( garisatas, "", LineColor );
        Plot( garisKiriBawah, "", LineColor, styleNoLabel  );
        Plot( garisKiriAtas, "", LineColor, styleNoLabel  );
        Plot( garisKananBawah, "", LineColor, styleNoLabel  );
        Plot( garisKananAtas, "", LineColor, styleNoLabel  );
    }

    //selesai buat box awal

    //hitung harus buat berapa box ke depan(horisontal dan vertikal)
    jumlahBoxH = int( ( LastBar - startBar ) / jumlahBarDiBox ) + 1;//jumlah box ke depan yang akan dibuat


    /*unused. replaced with new code.

    //Plot Vertical Line
        if ( displayBoxLine == 1 )
        {
            for ( k = 0;k < jumlahBoxH + 1;k++ )
            {
                x0 = -jumlahBarDiBox + startBar + k * jumlahBarDiBox;
                Plot( BarIndex() == x0, "", LineColor,  styleOwnScale + styleHistogram + styleNoLabel );
            } //end for
        }

    */

    if ( displayBoxColor == 1 )
    {
        PlotOHLC( Null, garisAtas, garisBawah, Null, "", ColorStartBox, styleCloud + styleNoLabel );
        PlotText( "Start", startBar - jumlahBarDiBox*2 / 3, VierL + Range / 2 , colorBlack, colorYellow );
    } //end if displayBoxColor

    baselineBox[0] = VierL; //akan dipakai untuk nilai y1 di box horisontal ke 1

    //buat baselineBox[boxNo] dari box horisontal pertama sampai terakhir
    for ( boxNo = 1;boxNo <= jumlahBoxH;boxNo++ )
    {
        testGanjil = frac( boxNo / 2 ) != 0;//genap jika nilainya 0

        if ( testGanjil == 0 )
        {
            baselineBox[boxNo] = BaselineBoxGenap;
        }
        else
        {
            baselineBox[boxNo] = BaselineBoxGanjil;
        } //end testGanjil
    } //end for buat baselineBox[boxNo]

    for ( boxNo = 1;boxNo < jumlahBoxH;boxNo++ ) //mulai buat box didepan sebanyak jumlahBoxH
    {

        boxL = lArray[startBar-1 + boxNo*jumlahBarDiBox];//nilai minimum harga di box no k
        boxH = hArray[startBar-1 + boxNo*jumlahBarDiBox];//nilai maksimum harga di box no k

        //hitung jumlahBoxV

        for ( i = 0;baselineBox[boxNo] + i*Range <= boxH;i++ )
        {
            jumlahBoxV = i + 1;
        }

        ClosingPriceBoxSebelumnya = C[startBar-1 + ( boxNo-1 )*jumlahBarDiBox];//harga penutupan di ujung kanan box sebelumnya.

        //Cari garis bawah terdekat dengan ClosingPriceBoxSebelumnya

        for ( i = 0;( baselineBox[boxNo-1] + i*range ) <= ClosingPriceBoxSebelumnya ;i++ )
        {
            y1 = baselineBox[BoxNo-1] + i * range;
        }

        //hitung garis bawah terdekat dengan boxL
        for ( i = 0;( baselineBox[boxNo] + i*range ) <= boxL;i++ )
        {
            y2 = baselineBox[boxNo] + i * range;
        }


        //printf( "\nClosingPriceBoxSebelumnya=" + ClosingPriceBoxSebelumnya );

        //printf( "\ny1=" + y1 );

        //printf( "\ny2=" + y2 );

        //buat Plot di box-box di depan

        for ( j = 1;j <= jumlahBoxV;j++ )
        {
            if ( ( baselineBox[boxNo] + j*range ) > boxL ) //buat plot hanya kalau dekat dengan bar
            {
                x0 = -jumlahBarDiBox + startBar + boxNo * jumlahBarDiBox;
                x1 =                      startBar + boxNo * jumlahBarDiBox;
                y = baselineBox[boxNo] + ( j - 1 ) * range;

                garisBawah = LineArray( x0, y, x1 - 1 , y, 0 );
                garisAtas = LineArray( x0, y + range, x1 - 1 , y + range, 0 );

                if ( displayBoxLine == 1 )
                {
                    garisKiriBawah = LineArray( x0 - 1, y + range / 2, x0, y, 0 );
                    garisKiriAtas = LineArray( x0 - 1, y + range / 2, x0, y + range, 0 );
                    garisKananBawah = LineArray( x1 - 1, y , x1, y + range / 2, 0 );
                    garisKananAtas = LineArray( x1 - 1, y + range, x1, y + range / 2, 0 );


                    Plot( garisBawah, "", LineColor, styleNoLabel );
                    Plot( garisatas, "", LineColor );
                    Plot( garisKiriBawah, "", LineColor, styleNoLabel  );
                    Plot( garisKiriAtas, "", LineColor, styleNoLabel  );
                    Plot( garisKananBawah, "", LineColor, styleNoLabel  );
                    Plot( garisKananAtas, "", LineColor, styleNoLabel  );
                } //end if displayBoxLine


                if ( displayBoxColor == 1 )
                {
                    ColorBoxBawah = startWarna( y1, y2, range );
                    PlotOHLC( Null, garisAtas, garisBawah, Null, "", ColorBoxBawah, styleCloud );
                    PlotText( textTrend( y1, y2, range ), x0 + jumlahBarDiBox / 3, y + Range / 2, colorBlack, colorYellow );
                    y2 = y2 + range; //rubah warna untuk box diatas box sekarang
                } //end if displayBoxColor
            } //end if dekat dengan bar
        } //end for
    } //end for


    //sekarang plot khusus di box paling kanan. Like I said, messy :(
    boxNo = jumlahBoxH; //no box yang paling kanan

    //BoxL dan BoxH di box terakhir. Very-very messy. Try and error.
    boxL = LastValue( LLV( Low, ( 1 + Offset - jumlahBarDiBox * ( jumlahBoxH - 1 ) ) ) ); //nilai minimum harga di box terakhir

    boxH = LastValue( HHV( High, ( 1 + Offset - jumlahBarDiBox * ( jumlahBoxH - 1 ) ) ) );//nilai maksimum harga di box terakhir

    //printf( "\nmundur berapa periode di bar terakhir=" + ( 1 + ( Offset - jumlahBarDiBox*( ( jumlahBoxH - 1 ) ) ) ) );

    //printf( "\nboxL=" + boxL );

    //printf( "\nboxH=" + boxH );

    //hitung jumlahBoxV
    for ( i = 0;baselineBox[boxNo] + i*Range <= boxH;i++ )
    {
        jumlahBoxV = i + 1;
    }

    ClosingPriceBoxSebelumnya = C[startBar-1 + ( boxNo-1 )*jumlahBarDiBox];//harga penutupan di ujung kanan box sebelumnya.

    //Cari garis bawah terdekat dengan ClosingPriceBoxSebelumnya

    for ( i = 0;( baselineBox[boxNo-1] + i*range ) <= ClosingPriceBoxSebelumnya ;i++ )
    {
        y1 = baselineBox[BoxNo-1] + i * range;
    }

    //hitung garis bawah terdekat dengan boxL
    for ( i = 0;( baselineBox[boxNo] + i*range ) <= boxL;i++ )
    {
        y2 = baselineBox[boxNo] + i * range;
    }


    for ( j = 1;j <= jumlahBoxV;j++ )
    {
        if ( ( baselineBox[boxNo] + j*range ) > boxL ) //buat plot hanya kalau dekat dengan bar
        {
            x0 = -jumlahBarDiBox + startBar + boxNo * jumlahBarDiBox;
            x1 =                      startBar + boxNo * jumlahBarDiBox;
            y = baselineBox[boxNo] + ( j - 1 ) * range;
            garisBawah = LineArray( x0, y, x1 - 1, y, 0 );
            garisAtas = LineArray( x0, y + range, x1 - 1, y + range, 0 );
            displace = jumlahBarDiBox - ( LastBar - x0 ) - 1;
            //printf( "\ndisplace=" + displace );

            if ( displayBoxLine == 1 )
            {
                garisKiriBawah = LineArray( x0 - 1, y + range / 2, x0, y, 0 );
                garisKiriAtas = LineArray( x0 - 1, y + range / 2, x0, y + range, 0 );
                garisKananBawah = LineArray( x1 - 1 , y , x1, y + range / 2, 0 );
                garisKananAtas = LineArray( x1 - 1 , y + range, x1, y + range / 2, 0 );
                Plot( Ref( garisbawah, displace ), "", LineColor, styleLine + styleNoLabel ,  0, 0, displace );//garis bawah box
                Plot( Ref( garisAtas, displace ), "", LineColor, styleLine , 0, 0, displace );//garis atas box
                Plot( garisKiriBawah, "", LineColor, styleNoLabel );
                Plot( garisKiriAtas, "", LineColor, styleNoLabel );
                Plot( garisKananBawah, "", LineColor, styleNoLabel ,  0, 0, displace );
                Plot( garisKananAtas, "", LineColor, styleNoLabel ,  0, 0, displace  );
            }

            if ( displayBoxColor == 1 )
            {
                ColorBoxBawah = startWarna( y1, y2, range );//
                PlotOHLC( Null, Ref( garisbawah, displace ), Ref( garisAtas, displace ), Null, "", ColorBoxBawah, styleCloud + styleNoLabel, 0, 0, displace );
                PlotText( textTrend( y1, y2, range ), x0 + jumlahBarDiBox / 3, y + Range / 2, colorBlack, colorYellow );
                y2 = y2 + range; //rubah warna untuk box diatas box sekarang
            }
        }//end if
    }//end for


    stringTitleOri = StrFormat( "{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) Vol " +
                                WriteVal( V, 1.0 ) + " {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) ;

    stringVierBox = WriteIf( jumlahBarDiBox != StrToNum( strJumlahBarDiBox ) OR
                             startBar != StrToNum( strStartBar ) OR
                             displayBoxLine != StrToNum( strdisplayBoxLine ) OR
                             displayBoxColor != StrToNum( strDisplayBoxColor ) OR
                             Linecolor != StrToNum( strLineColor ) OR
                             ColorStartBox != StrToNum( strColorStartBox ),
                             EncodeColor( colorRed ) + "VierBox " + Name() + " belum disimpan." +
                             "\nUntuk menyimpan VierBox ini, masuk ke menu Parameters dan klik SAVE." +
                             "\nUntuk memanggil VierBox yang telah disimpan, masuk ke menu Parameters dan klik RESET ALL.",
                             EncodeColor( colorBlue ) + "VierBox " + Name() + " sudah disimpan" );


    Title = stringVierBox + "\n\n" + EncodeColor( colorBlack ) + stringTitleOri;

    if ( save == 1 )
    {
        Output_file = Name() + ".txt";
        Output_folder = "vierbox";
        fmkdir( Output_folder );
        fh = fopen( Output_folder + "\\" + Output_file, "w" );
        fputs( NumToStr( startBar, 1.0, False ) + "," + NumToStr( jumlahBarDiBox, 1.0, False ) + "," +
               NumToStr( displayBoxLine, 1.0, False ) + "," + NumToStr( displayBoxColor, 1.0, False ) + "," +
               NumToStr( Linecolor, 1.0, False ) + "," + NumToStr( ColorStartBox, 1.0, False ) + "," , fh );
        fclose( fh );
    } //end if

} //end if displayVierBox
 

Bullish, Bearish Head and Shoulder pattern AFL AMIBROKER

Bullish + Bearish Head and Shoulder pattern







// Bullish + Bearish Head and Shoulder pattern
SetOption("MaxOpenPositions",10);
PositionSize=-5;
SetTradeDelays(0,0,0,0);
procedure exitLoop_proc(Buy,BuyPrice,buDeltaProfitTarget,buStopLossLevel,buNeckline,Short,ShortPrice,beDeltaProfitTarget,beStopLossLevel,beNeckline,Maxbars)
{
global BuyAdjusted;
global BuyPriceAdjusted;
global ShortAdjusted;
global ShortPriceAdjusted;
global SellAdjusted;
global SellPriceAdjusted;
global CoverAdjusted;
global CoverPriceAdjusted;
global LongStopTrail;
global ShortStopTrail;
global LongTarget;
global ShortTarget;

BuyAdjusted=0;
BuyPriceAdjusted=0;
ShortAdjusted=0;
ShortPriceAdjusted=0;
SellAdjusted=0;
SellPriceAdjusted=0;
CoverAdjusted=0;
CoverPriceAdjusted=0;
LongStopTrail=Null;
ShortStopTrail=Null;
LongTarget=Null;
ShortTarget=Null;

for(i=1;i<BarCount;i++)
{
    if(Buy[i])
    {
        BuyAdjusted[i]=1;
        BuyPriceAdjusted[i]=BuyPrice[i];   
        LongStopTrail[i]=buStopLossLevel[i];
        LongTarget[i]=buNeckline[i]+buDeltaProfitTarget[i];
        cnt=0;
        for(j=i+1;j<BarCount;j++)
        {
            LongStopTrail[j]=LongStopTrail[i];
            LongTarget[j]=LongTarget[i];
            if(cnt>Maxbars)
            {
                SellAdjusted[j]=1;
                SellPriceAdjusted[j]=O[j];
                i=j;
                break;           
            }
            else if(C[j-1]<LongStopTrail[j-1])
            {
                SellAdjusted[j]=1;
                SellPriceAdjusted[j]=O[j];
                i=j;
                break;
            }   
            else if(Short[j])
            {
                SellAdjusted[j]=1;
                SellPriceAdjusted[j]=O[j];
                i=j-1;
                break;
            }           
            else if(C[j-1]>LongTarget[j-1])
            {
                SellAdjusted[j]=1;
                SellPriceAdjusted[j]=O[j];
                i=j;
                break;
            }   
            else if(j==BarCount-1)
            {   
                i=BarCount;
                break;
            }
            cnt=cnt+1;           
        }
    }
    else if(Short[i])
    {
        ShortAdjusted[i]=1;
        ShortPriceAdjusted[i]=ShortPrice[i];   
        ShortStopTrail[i]=beStopLossLevel[i];
        ShortTarget[i]=beNeckline[i]-beDeltaProfitTarget[i];
        cnt=0;
        for(j=i+1;j<BarCount;j++)
        {
            ShortStopTrail[j]=ShortStopTrail[i];
            ShortTarget[j]=ShortTarget[i];
            if(cnt>Maxbars)
            {
                CoverAdjusted[j]=1;
                CoverPriceAdjusted[j]=O[j];
                i=j;
                break;           
            }           
            else if(C[j-1]>ShortStopTrail[j-1])
            {
                CoverAdjusted[j]=1;
                CoverPriceAdjusted[j]=O[j];
                i=j;
                break;
            }   
            else if(Buy[j])
            {
                CoverAdjusted[j]=1;
                CoverPriceAdjusted[j]=O[j];
                i=j-1;
                break;
            }                   
            else if(C[j-1]<ShortTarget[j-1])
            {
                CoverAdjusted[j]=1;
                CoverPriceAdjusted[j]=O[j];
                i=j;
                break;
            }   
            else if(j==BarCount-1)
            {   
                i=BarCount;
                break;
            }   
            cnt=cnt+1;
        }
    }
}
}
xx=BarIndex();x=xx;Lx=LastValue(x);
nbar=Param("N Pivot Bars",5,2,50,1);
tf=Param("Time Frame (min)",5,0.001,1440,0.001);tfrm=in1Minute*tf;
atrper=Param("ATR Period (bars)",20,2,100,1);
atrfac1=Param("ATR tolerance factor (Shoulders)",2.25,0,50,0.01);
atrfac2=Param("ATR tolerance factor (Head Minimum)",0.4,0,50,0.01);
atrfac3=Param("ATR tolerance factor (Head Maximum)",5,0,50,0.01);
CleanPivots=ParamToggle("Use Clean Pivots","Off|On",1);
PivotSymmetry=ParamToggle("Use Symmetric Pivots","Off|On",0);
dispbeHS=ParamToggle("Display bearish HS","Off|On",1);
dispbuHS=ParamToggle("Display bullish HS","Off|On",1);
extendN=Param("Extension neckline (bars)",100,0,500,1);
validSignalRangeCheck=ParamToggle("Signal Validity Range Check","Off|On",1);
hssym=Param("Max Deviation H&S Symmetry (%)",80,0,500,1);
includeVolumeSlope=ParamToggle("Volume Slope Constraint","Off|On",0);
Maxbars=Param("Maximum bars of trade",50,2,200,1);

TimeFrameSet(tfrm);
atra=ATR(atrper);
if(PivotSymmetry)
{
    fc=1;
    pk=H>Ref(HHV(H,nbar*fc),-1) AND Ref(HHV(H,nbar),nbar)<=H;
    tr=L<Ref(LLV(L,nbar*fc),-1) AND Ref(LLV(L,nbar),nbar)>=L;
}
else
{
    fc=2;
    pk=H>Ref(HHV(H,nbar*fc),-1) AND Ref(HHV(H,nbar),nbar)<=H;
    tr=L<Ref(LLV(L,nbar*fc),-1) AND Ref(LLV(L,nbar),nbar)>=L;
}

px0=ValueWhen(pk,x,0); tx0=ValueWhen(tr,x,0);
px1=ValueWhen(pk,x,1); tx1=ValueWhen(tr,x,1);
px2=ValueWhen(pk,x,2); tx2=ValueWhen(tr,x,2);
px3=ValueWhen(pk,x,3); tx3=ValueWhen(tr,x,3);
ph0=ValueWhen(pk,H,0); tl0=ValueWhen(tr,L,0);
ph1=ValueWhen(pk,H,1); tl1=ValueWhen(tr,L,1);
ph2=ValueWhen(pk,H,2); tl2=ValueWhen(tr,L,2);
ph3=ValueWhen(pk,H,3); tl3=ValueWhen(tr,L,3);

if(CleanPivots)
{
    tr=IIf((tr==1 AND pk==1) AND px2<tx2,False,tr);
    pk=IIf((tr==1 AND pk==1) AND px2>tx2,False,pk);

    px0=ValueWhen(pk,x,0); tx0=ValueWhen(tr,x,0);
    px1=ValueWhen(pk,x,1); tx1=ValueWhen(tr,x,1);
    px2=ValueWhen(pk,x,2); tx2=ValueWhen(tr,x,2);
    px3=ValueWhen(pk,x,3); tx3=ValueWhen(tr,x,3);   
    ph0=ValueWhen(pk,H,0); tl0=ValueWhen(tr,L,0);
    ph1=ValueWhen(pk,H,1); tl1=ValueWhen(tr,L,1);
    ph2=ValueWhen(pk,H,2); tl2=ValueWhen(tr,L,2);
    ph3=ValueWhen(pk,H,3); tl3=ValueWhen(tr,L,3);   
   
    tr=IIf(tr AND ((tx0<px0 AND tl1>tl0) OR (tx2>px1 AND tl1>=tl2) OR (px0==px1 AND tl1>tl0)),False,tr);
    pk=IIf(pk AND ((px0<tx0 AND ph1<ph0) OR (px2>tx1 AND ph1<=ph2) OR (tx0==tx1 AND ph1<ph0)),False,pk);

    px0=ValueWhen(pk,x,0); tx0=ValueWhen(tr,x,0);
    px1=ValueWhen(pk,x,1); tx1=ValueWhen(tr,x,1);
    px2=ValueWhen(pk,x,2); tx2=ValueWhen(tr,x,2);
    px3=ValueWhen(pk,x,3); tx3=ValueWhen(tr,x,3);
    ph0=ValueWhen(pk,H,0); tl0=ValueWhen(tr,L,0);
    ph1=ValueWhen(pk,H,1); tl1=ValueWhen(tr,L,1);
    ph2=ValueWhen(pk,H,2); tl2=ValueWhen(tr,L,2);
    ph3=ValueWhen(pk,H,3); tl3=ValueWhen(tr,L,3);   

    tr=IIf(tr AND ((tx0<px0 AND tl1>tl0) OR (tx2>px1 AND tl1>=tl2) OR (px0==px1 AND tl1>tl0)),False,tr);
    pk=IIf(pk AND ((px0<tx0 AND ph1<ph0) OR (px2>tx1 AND ph1<=ph2) OR (tx0==tx1 AND ph1<ph0)),False,pk);

    px0=ValueWhen(pk,x,0); tx0=ValueWhen(tr,x,0);
    px1=ValueWhen(pk,x,1); tx1=ValueWhen(tr,x,1);
    px2=ValueWhen(pk,x,2); tx2=ValueWhen(tr,x,2);
    px3=ValueWhen(pk,x,3); tx3=ValueWhen(tr,x,3);
    ph0=ValueWhen(pk,H,0); tl0=ValueWhen(tr,L,0);
    ph1=ValueWhen(pk,H,1); tl1=ValueWhen(tr,L,1);
    ph2=ValueWhen(pk,H,2); tl2=ValueWhen(tr,L,2);
    ph3=ValueWhen(pk,H,3); tl3=ValueWhen(tr,L,3);   
}
pkh=IIf(pk,H,Null);
trl=IIf(tr,L,Null);
TimeFrameRestore();
fact=Nz(Max(tfrm/60,Interval()/60)/(Interval()/60));
if(fact==0)fact=1;
Lkbk=tfrm/Interval();
if(Lkbk>1 AND !IsNan(Lkbk))
{
    pk=TimeFrameExpand(pk,tfrm,expandFirst);
    pkh=TimeFrameExpand(pkh,tfrm,expandFirst);
    pkhs=IIf(!IsEmpty(pkh),1,0);pkhs=pkhs-Ref(pkhs,-1);
    pk=pk AND H==pkh;
    cond1=Sum(pk,BarsSince(pkhs==1)+1)==1 AND pk;
    pk=pk AND cond1;
   
    tr=TimeFrameExpand(tr,tfrm,expandFirst);   
    trl=TimeFrameExpand(trl,tfrm,expandFirst);
    trls=IIf(!IsEmpty(trl),1,0);trls=trls-Ref(trls,-1);
    tr=tr AND L==trl;
    cond1=Sum(tr,BarsSince(trls==1)+1)==1 AND tr;
    tr=tr AND cond1;
   
    px0=ValueWhen(pk,x,0); tx0=ValueWhen(tr,x,0);
    px1=ValueWhen(pk,x,1); tx1=ValueWhen(tr,x,1);
    px2=ValueWhen(pk,x,2); tx2=ValueWhen(tr,x,2);
    px3=ValueWhen(pk,x,3); tx3=ValueWhen(tr,x,3);
    ph0=ValueWhen(pk,H,0); tl0=ValueWhen(tr,L,0);
    ph1=ValueWhen(pk,H,1); tl1=ValueWhen(tr,L,1);
    ph2=ValueWhen(pk,H,2); tl2=ValueWhen(tr,L,2);
    ph3=ValueWhen(pk,H,3); tl3=ValueWhen(tr,L,3);
   
    atra=TimeFrameExpand(atra,tfrm,expandFirst);
}
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;

ll_h=IIf(ll,1,0);
hl_h=IIf(hl,2,0);
hh_h=IIf(hh,3,0);
lh_h=IIf(lh,4,0);
dt_h=IIf(dt,5,0);
db_h=IIf(db,6,0);

combi=ll_h+hl_h+lh_h+hh_h+dt_h+db_h;

t0=ValueWhen(combi,combi,0);
t1=ValueWhen(combi,combi,1);
t2=ValueWhen(combi,combi,2);
t3=ValueWhen(combi,combi,3);
t4=ValueWhen(combi,combi,4);
t5=ValueWhen(combi,combi,5);

// bearisch pattern
beHS=pk AND t1==4 AND (t2==1 OR t2==2) AND t3==3 AND t4==2 AND (t5==3 OR t5==4)
AND abs(tl1-tl2)<atra*atrfac1 AND abs(ph1-ph3)<atra*atrfac1 AND ph2>(Max(ph1,ph3)+atra*atrfac2) AND ph2<(Max(ph1,ph3)+atra*atrfac3);
beAx=ValueWhen(beHS,px3);beAy=ValueWhen(beHS,ph3);
beBx=ValueWhen(beHS,tx2);beBy=ValueWhen(beHS,tl2);
beCx=ValueWhen(beHS,px2);beCy=ValueWhen(beHS,ph2);
beDx=ValueWhen(beHS,tx1);beDy=ValueWhen(beHS,tl1);
beEx=ValueWhen(beHS,px1);beEy=ValueWhen(beHS,ph1);
beFx=ValueWhen(beHS,px1);aa=(beDy-beBy)/(beDx-beBx);bb=beDy;ii=px1-beDx;beFy=aa*ii+bb;
beHS=beHS AND 100*abs((beCx-beAx)-(beEx-beCx))/(Min(beCx-beAx,beEx-beCx)+1)<hssym;
if(includeVolumeSlope) beHS=IIf(beHS AND LinRegSlope(V,beEx-beAx)<0,beHS,0);
rr=BarsSince(beHS)>=0 AND BarsSince(beHS)<extendN;
idx=IIf(rr,xx-ValueWhen(beHS,beDx),Null);
aa=ValueWhen(beHS,aa);bb=ValueWhen(beHS,bb);
beNeckline=IIf(idx,aa*idx+bb,Null);
beValidSignalArea=Ref(Flip(Ref(beHS,-1),pk),1);
if(validSignalRangeCheck) beNeckline=IIf(beValidSignalArea,beNeckline,Null);
beGx=beCx;beGy=beBy+(beDy-beBy)/(beDx-beBx)*(beCx-beBx);
Short=Cross(beNeckline,C) AND !IsEmpty(beNeckline);Short=Ref(Short,-1);ShortPrice=O;
Short=ExRem(Short,beHS);beDeltaProfitTarget=beCy-beGy;beStopLossLevel=beEy;

// bullish pattern
buHS=tr AND t1==2 AND (t2==3 OR t2==4) AND t3==1 AND t4==4 AND (t5==1 OR t5==2)
AND abs(ph1-ph2)<atra*atrfac1 AND abs(tl1-tl3)<atra*atrfac1 AND tl2<(Max(tl1,tl3)-atra*atrfac2) AND tl2>(Max(tl1,tl3)-atra*atrfac3);
buAx=ValueWhen(buHS,tx3);buAy=ValueWhen(buHS,tl3);
buBx=ValueWhen(buHS,px2);buBy=ValueWhen(buHS,ph2);
buCx=ValueWhen(buHS,tx2);buCy=ValueWhen(buHS,tl2);
buDx=ValueWhen(buHS,px1);buDy=ValueWhen(buHS,ph1);
buEx=ValueWhen(buHS,tx1);buEy=ValueWhen(buHS,tl1);
buFx=ValueWhen(buHS,tx1);aa=(buDy-buBy)/(buDx-buBx);bb=buDy;ii=tx1-buDx;buFy=aa*ii+bb;
buHS=buHS AND 100*abs((buCx-buAx)-(buEx-buCx))/(Min(buCx-buAx,buEx-buCx)+1)<hssym;
if(includeVolumeSlope) buHS=IIf(buHS AND LinRegSlope(V,buEx-buAx)<0,buHS,0);
rr=BarsSince(buHS)>=0 AND BarsSince(buHS)<extendN;
idx=IIf(rr,xx-ValueWhen(buHS,buDx),Null);
aa=ValueWhen(buHS,aa);bb=ValueWhen(buHS,bb);
buNeckline=IIf(idx,aa*idx+bb,Null);
buValidSignalArea=Ref(Flip(Ref(buHS,-1),tr),1);
if(validSignalRangeCheck) buNeckline=IIf(buValidSignalArea,buNeckline,Null);
buGx=buCx;buGy=buBy+(buDy-buBy)/(buDx-buBx)*(buCx-buBx);
Buy=Cross(C,buNeckline) AND !IsEmpty(buNeckline);Buy=Ref(Buy,-1);BuyPrice=O;
Buy=ExRem(Buy,buHS);buDeltaProfitTarget=buGy-buCy;buStopLossLevel=buEy;

exitLoop_proc(Buy,BuyPrice,buDeltaProfitTarget,buStopLossLevel,buNeckline,Short,ShortPrice,beDeltaProfitTarget,beStopLossLevel,beNeckline,Maxbars);
Buy=BuyAdjusted;BuyPrice=BuyPriceAdjusted;
Short=ShortAdjusted;ShortPrice=ShortPriceAdjusted;
Sell=SellAdjusted;SellPrice=SellPriceAdjusted;
Cover=CoverAdjusted;CoverPrice=CoverPriceAdjusted;

SetChartBkColor(ColorRGB(0,0,0));SetChartOptions(0,chartShowDates);
SetBarFillColor(IIf(C>O,colorGreen,IIf(C<=O,colorRed,colorLightGrey)));
Plot(C,"Price",IIf(C>O,colorDarkGreen,IIf(C<=O,colorDarkRed,colorLightGrey)),64,0,0,0,0);
Plot(pkh,"",colorRed,styleThick,0,0,0,-1);
Plot(trl,"",colorBrightGreen,styleThick,0,0,0,-1);
PlotShapes(shapeSmallCircle*tr,IIf(Lx-ValueWhen(tr,x)>nbar*fact,ColorRGB(0,100,0),colorWhite),0,L,-10);
PlotShapes(shapeSmallCircle*pk,IIf(Lx-ValueWhen(pk,x)>nbar*fact,ColorRGB(255,0,0),colorWhite),0,H,10);

if(dispbuHS)
{
    Plot(buNeckline,"",colorGreen,styleNoLine|styleDots,0,0,0,1);
    PlotShapes(IIf(Buy,shapeUpArrow,shapeNone),colorDarkGreen,0,L,-15);
    PlotShapes(IIf(Buy,shapeSmallCircle,shapeNone),colorWhite,0,BuyPrice,0);
    PlotShapes(IIf(Sell,shapeDownArrow,shapeNone),colorRed,0,H,-15);
    PlotShapes(IIf(Sell,shapeSmallCircle,shapeNone),colorWhite,0,SellPrice,0);
    Plot(LongStopTrail,"",colorRed,styleLine,0,0,1,1);
    Plot(LongTarget,"",colorBrightGreen,styleLine,0,0,1,1);   
}
if(dispbeHS)
{
    Plot(beNeckline,"",colorRed,styleNoLine|styleDots,0,00,0,1);
    PlotShapes(IIf(Short,shapeSmallDownTriangle,shapeNone),colorRed,0,H,IIf(Short AND Sell,-30,-15));   
    PlotShapes(IIf(Short,shapeSmallCircle,shapeNone),colorWhite,0,ShortPrice,0);
    PlotShapes(IIf(Cover,shapeSmallUpTriangle,shapeNone),colorDarkGreen,0,L,IIf(Cover AND Buy,-30,-15));
    PlotShapes(IIf(Cover,shapeSmallCircle,shapeNone),colorWhite,0,CoverPrice,0);   
    Plot(ShortStopTrail,"",colorRed,styleLine,0,00,1,1);
    Plot(ShortTarget,"",colorBrightGreen,styleLine,0,00,1,1);
}

qq=Interval()/60;
if(qq < 60){tf=" min";tt=qq;}
else if(qq >= 60 AND qq < 1440){tf=" hrs";tt=qq/60;}
else if(qq >= 1440){tf=" days";tt=(qq/60)/24;}
qq=Max(tfrm/60,Interval()/60);
if(qq < 60){tfa=" min";tta=qq;}
else if(qq >= 60 AND qq < 1440){tfa=" hrs";tta=qq/60;}
else if(qq >= 1440){tfa=" days";tta=(qq/60)/24;}

Title = Name() +
"\nNbar: " + nbar +
"\nChart TF: " + tt + tf +
"\nTrend TF: " + tta + tfa;

abcdy_up=20;
abcdy_dn=28;
function GetVisibleBarCount()
{
    lvb=Status("lastvisiblebar");
    fvb=Status("firstvisiblebar");
    return Min(lvb-fvb,BarCount-fvb);
}
function GfxConvertPixelsToBarX(Pixels)
{
    lvb=Status("lastvisiblebar");
    fvb=Status("firstvisiblebar");
    pxchartleft=Status("pxchartleft");
    pxchartwidth=Status("pxchartwidth");
    fac=pxchartwidth/Pixels;
    bar=(lvb-fvb)/fac;
    return bar;
}
function GfxConvertPixelToValueY(Pixels)
{
    local Miny,Maxy,pxchartbottom,pxchartheight;
    Miny=Status("axisminy");
    Maxy=Status("axismaxy");
    pxchartbottom=Status("pxchartbottom");
    pxchartheight=Status("pxchartheight");
    fac=pxchartheight/Pixels;
    Value=(Maxy-Miny)/fac;
    return Value;
}

AllVisibleBars=GetVisibleBarCount();
fvb=Status("firstvisiblebar");
abcdy_up=GfxConvertPixelToValueY(abcdy_up);
abcdy_dn=GfxConvertPixelToValueY(abcdy_dn);
for(i=0;i<AllVisibleBars;i++)
{
    if(beHS[i+fvb] AND dispbeHS)
    {
        clr=colorRed;
        lvix=i+fvb;
        Plot(LineArray(beAx[lvix],beAy[lvix],beBx[lvix],beBy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(beBx[lvix],beBy[lvix],beCx[lvix],beCy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(beCx[lvix],beCy[lvix],beDx[lvix],beDy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(beDx[lvix],beDy[lvix],beEx[lvix],beEy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(beDx[lvix],beDy[lvix],beFx[lvix],beFy[lvix],0,True ),"",clr,styleDashed);
        Plot(LineArray(beBx[lvix],beBy[lvix],beDx[lvix],beDy[lvix],0,True ),"",clr,styleDashed);
        PlotText("S1",beAx[lvix]-0,beAy[lvix]+abcdy_up,colorRed,colorDefault);
        PlotText("H",beCx[lvix]-0,beCy[lvix]+abcdy_up,colorRed,colorDefault);
        PlotText("S2",beEx[lvix]-0,beEy[lvix]+abcdy_up,colorRed,colorDefault);
    }
    if(buHS[i+fvb] AND dispbuHS)
    {
        clr=colorGreen;
        lvix=i+fvb;
        Plot(LineArray(buAx[lvix],buAy[lvix],buBx[lvix],buBy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(buBx[lvix],buBy[lvix],buCx[lvix],buCy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(buCx[lvix],buCy[lvix],buDx[lvix],buDy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(buDx[lvix],buDy[lvix],buEx[lvix],buEy[lvix],0,True ),"",clr,styleThick);
        Plot(LineArray(buDx[lvix],buDy[lvix],buFx[lvix],buFy[lvix],0,True ),"",clr,styleDashed);
        Plot(LineArray(buBx[lvix],buBy[lvix],buDx[lvix],buDy[lvix],0,True ),"",clr,styleDashed);
        PlotText("S1",buAx[lvix]-0,buAy[lvix]-abcdy_dn,colorGreen,colorDefault);
        PlotText("H",buCx[lvix]-0,buCy[lvix]-abcdy_dn,colorGreen,colorDefault);
        PlotText("S2",buEx[lvix]-0,buEy[lvix]-abcdy_dn,colorGreen,colorDefault);
    }   
}

Volume for Amibroker (AFL)





_SECTION_BEGIN("Simple Volume");
SetChartOptions(0,chartShowArrows|chartShowDates);
GfxSetBkMode(1);

_SECTION_BEGIN ("?????");
BarsColor = ParamList ("Bars Color", "By Price|Mono|By Volume|By Bull and Bears");
HistWidth = Param("??????? ??????????", -30, -60, 0, 10);

BullCond  = V>Ref(V,-1) AND C>Ref(C,-1) OR V<Ref(V,-1) AND C<Ref(C,-1);
BearCond  = V>Ref(V,-1) AND C<Ref(C,-1) OR V<Ref(V,-1) AND C>Ref(C,-1);
BuBeColor = IIf(BullCond, colorBrightGreen, IIf( BearCond, colorRed, colorLightYellow));

if      (BarsColor == "Mono")            { BarColors=colorSkyblue; Txt = "Mono"; }
else if (BarsColor == "By Price")        { BarColors=IIf(C==O, colorWhite, IIf(C>O, colorBrightGreen, colorRed)); Txt="By Price"; }
else if (BarsColor == "By Volume")        { BarColors=IIf(V==Ref(V,-1), colorWhite, IIf(V>Ref(V, -1), colorBrightGreen, colorRed));  Txt="By Volume"; }
else if (BarsColor == "By Bull and Bears")    { BarColors=BuBeColor; Txt = "By Bull and Bears";}

SetBarFillColor(BarColors);
Plot(V,"Volume "+ Txt, BarColors, styleHistogram, Null, Null,  1, HistWidth);
VL    = LastValue(Volume);
VLCol = LastValue(BarColors);
//Plot(EndValue(Volume), "", VLCol, styleLine|styleNoLabel, Null, Null,0,10);

VAv = MA(V, Param("MA Period", 30, 10, 400, 10));
Plot(VAv, "Average Volume", colorYellow, styleThick);
PlotOHLC(0,VAv,0,VAv, "",  colorBlack, styleCloud|styleNoLabel);
_SECTION_END();

Intraday Trading system for Amibroker (AFL)


99% accurate system for Amibroker (AFL)




_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, High %g, Low %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();

_SECTION_BEGIN("Signal Panel");
no=10;
res=HHV(H,no);
sup=LLV(L,no);
avd=IIf(C>Ref(res,-1),1,IIf(C<Ref(sup,-1),-1,0));
avn=ValueWhen(avd!=0,avd,1);
s5d=IIf(avn==1,sup,res);

showsl = ParamToggle("Stop Loss Line", "Show|Hide", 0);
if (showsl == 1)
{Plot(s5d,"Stop Loss",colorCustom14,styleDots);}

exitlong = Cross(s5d, H);
PlotShapes(exitlong * shapeNone, colorBlack,0,H,-10);
exitshort = Cross(L, s5d);
PlotShapes(exitshort * shapeNone, colorBlack,0,L,-15);

Buy = exitshort;
Sell = exitlong;

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

AlertIf( Buy, "", "Buy @ " + C, 1 );
AlertIf( Sell, "", "Sell @ " + C, 2 );

for(i=BarCount-1;i>1;i--)
{
if(Buy[i] == 1)
{
entry = C[i];
sig = "Buy";
sl = s5d[i];
tar1 = entry + (entry * .0050);
tar2 = entry + (entry * .0092);
tar3 = entry + (entry * .0179);

bars = i;
i = 0;
}
if(Sell[i] == 1)
{
sig = "Sell";
entry = C[i];
sl = s5d[i];
tar1 = entry - (entry * .0050);
tar2 = entry - (entry * .0112);
tar3 = entry - (entry * .0212);


bars = i;
i = 0;
}
}
Offset = 20;
Clr = IIf(sig == "Buy", colorLime, colorRed);
ssl = IIf(bars == BarCount-1, s5d[BarCount-1], Ref(s5d, -1));
sl = ssl[BarCount-1];

Plot(LineArray(bars-Offset, tar1, BarCount, tar1,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
Plot(LineArray(bars-Offset, tar2, BarCount, tar2,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
Plot(LineArray(bars-Offset, tar3, BarCount, tar3,1), "", Clr, styleLine|styleDots, Null, Null, Offset);

Plot(LineArray(bars-Offset, sl, BarCount, sl,1), "", colorDarkRed, styleLine|styleLine, Null, Null, Offset);
Plot(LineArray(bars-Offset, entry, BarCount, entry,1), "", colorGreen, styleLine|styleLine, Null, Null, Offset);

for (i=bars; i <BarCount;i++)
{
PlotText(""+sig+"@"+entry, BarCount-3,entry,Null,colorBlue);
PlotText("TGT-1@"+tar1,BarCount-4,tar1,Null,Clr);PlotText("TGT-2@"+tar2,BarCount-4,tar2,Null,Clr);PlotText ("TGT-3@"+tar3,BarCount-4,tar3,Null,Clr);

}

messageboard = ParamToggle("Message Board","Show|Hide",1);
if (messageboard == 1 )
{
GfxSelectFont( "Tahoma", 13, 100 );
GfxSetBkMode( 1 );
GfxSetTextColor( colorWhite );

if ( sig =="Buy")
{
GfxSelectSolidBrush( colorBlue );
}
else
{
GfxSelectSolidBrush( colorRed ); 
}
pxHeight = Status( "pxchartheight" ) ;
xx = Status( "pxchartwidth");
Left = 1100;
width = 310;
x = 5;
x2 = 310;

y = pxHeight;

GfxSelectPen( colorGreen, 5); // broader color
GfxRoundRect( x, y - 142, x2, y , 7, 7 ) ;
GfxTextOut( Name(),12,y-140);
GfxTextOut( " Last Traded Price = "+  C , 08,y- 120 );
GfxTextOut( ( "Signal Panel"),160,y-140);
GfxTextOut( (" "),27,y-160);
GfxTextOut( ("Last " + sig + " Signal came " + (BarCount-bars-1) * Interval()/60 + " mins ago"), 13, y-100) ; // The text format location
GfxTextOut( ("" + WriteIf(sig =="Buy",sig + " @ ",sig + " @") + " : " + entry), 13, y-80);
GfxTextOut( ("Trailing Stop Loss : " + sl + " (P/L:" + WriteVal(IIf(sig == "Sell",entry-sl,sl-entry), 2.2) + ")"), 13, y-60);
GfxTextOut( ("TGT:1 : " + tar1), 13, y -40);
GfxTextOut( ("Current Profit/Loss : " + WriteVal(IIf(sig == "BUY",(C-entry),(entry-C)),2.2)), 40, y-22);;

}
_SECTION_END();



_SECTION_BEGIN("Sound Alert");
AlertIf( Buy, "SOUND C:\\Windows\\Media\\Chord.wav", "Sell " + C,2,1+2,1);
AlertIf( Sell, "SOUND C:\\Windows\\Media\\tada.wav","Buy " + C,1,1+2,1);
_SECTION_END();



_SECTION_BEGIN("Magnified Market Price");
FS=Param("Font Size",15,30,100,1);
GfxSelectFont("Arial", FS, 700, italic = False, underline = False, True );
GfxSetBkMode( colorWhite );
GfxSetTextColor( ParamColor("Color",colorBlue) );
Hor=Param("Horizontal Position",750,800,800,800);
Ver=Param("Vertical Position",27,27,27,27);
GfxTextOut("L.T.P="+C,Hor , Ver );
YC=TimeFrameGetPrice("C",inDaily,-1);
DD=Prec(C-YC,2);
xx=Prec((DD/YC)*100,2);
GfxSelectFont("Arial", 12, 700, italic = False, underline = False, True );
GfxSetBkMode( colorWhite );
GfxSetTextColor(ParamColor("Color",colorYellow) );
GfxTextOut(""+DD+" ("+xx+"%)", Hor+5.45, Ver+45 );
_SECTION_END();


_SECTION_BEGIN("");
GfxSetOverlayMode(0);
GfxSelectPen( colorRed, 3 );
GfxSelectSolidBrush( colorLightYellow );
GfxRoundRect( 350, 38,665, 70, 15, 15 );
GfxSetBkMode(1);
GfxSelectFont( "Arial", 17.5, 700, False );
GfxSetTextColor( colorBrown );
GfxSetTextAlign(0);
GfxSetTextColor( colorBlack );
GfxTextOut( " Last Traded Price = "+  BuyPrice , 350, 40);
_SECTION_END();


_SECTION_BEGIN("Isfandi Technical Viewer");

GfxSetBkColor(colorBlue);
GfxSetTextColor( colorLime );
GfxSelectFont("Times New Roman", 20, 1,500, True );
GfxTextOut(" Intraday Trading System ", 20 , 40 );
_SECTION_END();


_SECTION_BEGIN(" Buy Sell Signal Confirm ");
BarColors =
IIf(BarsSince(Buy) < BarsSince(Sell)
AND BarsSince(Buy)!=0, colorGreen,
IIf(BarsSince(Sell) < BarsSince(Buy)
AND BarsSince(Sell)!=0,  colorRed, colorBlue));

Plot(C, "Close", BarColors,  styleNoTitle | ParamStyle("Style") | GetPriceStyle() ) ;
_SECTION_END();

_SECTION_BEGIN("Show Up Down Arrow & Price ");
shape = Buy * shapeUpArrow + Sell * shapeDownArrow;
AlertIf( Buy, "SOUND C:\\Windows\\Media\\Chord.wav", "Audio alert", 2 );
AlertIf( Sell, "SOUND C:\\Windows\\Media\\Ding.wav", "Audio alert", 2 );

dist = 1.8*ATR(15);
  for( i = 0; i < BarCount; i++ )
  {
  if( Buy[i] ) PlotText( "Buy@" + L[ i ], i, L[ i ]-dist[i], colorWhite, colorGreen );
  if( Sell[i] ) PlotText( "Sell@" + H[ i ], i, H[ i ]+dist[i], colorWhite, colorRed );
  }


PlotShapes( shape, IIf( Buy, colorBlue, colorRed ), 0, IIf( Buy, Low, High )
);

_SECTION_END();

Special for Amibroker (AFL)



_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
if( ParamToggle("Tooltip shows", "All Values|Only Prices" ) )
{
 ToolTip=StrFormat("Open: %g\nHigh:  %g\nLow:   %g\nClose:  %g (%.1f%%)\nVolume: "+NumToStr( V, 1 ), O, H, L, C, SelectedValue( ROC( C, 1 )));
}
_SECTION_END();

_SECTION_BEGIN("Mid MA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 45, 2, 300, 1 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") | styleNoRescale );
_SECTION_END();

_SECTION_BEGIN("Long MA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 100, 2, 400, 1 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") | styleNoRescale );
_SECTION_END();

_SECTION_BEGIN("BBands");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1 );
Width = Param("Width", 2, 0, 10, 0.05 );
Color = ParamColor("Color", colorLightGrey );
Style = ParamStyle("Style") | styleNoRescale | styleNoRescale;
Plot( BBandTop( P, Periods, Width ), "BBTop" + _PARAM_VALUES(), Color, Style );
Plot( BBandBot( P, Periods, Width ), "BBBot" + _PARAM_VALUES(), Color, Style );
_SECTION_END();

_SECTION_BEGIN("Price Interpretation");
movshort = ParamField("Short Time MA", 8 );
movmed = ParamField("Mid Time MA", 9 );
movlong = ParamField("Long Time MA", 10 );
btop = ParamField("BBTop", 11 );
bbot = ParamField("BBBottom", 12 );
if( Status("action") == actionCommentary )
{
width = btop - bbot;
lslop = LinRegSlope( C, 30 ) + 100;
lslo = LLV( lslop, 90 );
lshi = HHV( lslop, 90 );
lswidth = lshi - lslo;
trend = 100*( lslop - lslo )/lswidth;

mawidth = MA( width, 100 );
relwidth = 100*(width - mawidth)/mawidth;

_N( tname = Name()+"("+FullName()+")" );

printf("Price and moving averages:\n");
printf( tname + " has closed " + WriteIf( C > movshort, "above" , "below" ) + " its Short time moving average. ");

printf("\nShort time moving average is currently " + WriteIf( movshort > movmed, "above", "below") + " mid-time, AND " + WriteIf( movshort > movlong, "above", "below" ) + " long time moving averages.");

printf("\nThe relationship between price and moving averages is: "+
WriteIf( C > movshort AND movshort > movmed, "bullish",
WriteIf( C < movshort AND movshort < movmed, "bearish", "neutral" ) ) + " in short-term, and "+
WriteIf( movshort > movmed AND movmed > movlong , "bullish",
WriteIf( movshort < movmed AND movmed < movlong, "bearish", "neutral" ) ) + " in mid-long term. ");

printf("\n\nBollinger Bands:\n");
printf(tname+ " has closed " +
WriteIf( C < bbot, "below the lower band by " +
WriteVal( 100 *( bbot-C )/ width, 1.1 ) + "%%. " +
WriteIf( trend < 30, " This combined with the steep downtrend can suggest that the downward trend in prices has a good chance of continuing.  However, a short-term pull-back inside the bands is likely.",
WriteIf( trend > 30 AND trend < 70, "Although prices have broken the lower band and a downside breakout is possible, the most likely scenario for "+tname+" is to continue within current trading range.", "" ) ), "" ) +

WriteIf( C > btop, "above the upper band by " +
WriteVal( 100 *( C- btop )/ width, 1.1 ) + "%%. " +
WriteIf( trend > 70, " This combined with the steep uptrend suggests that the upward trend in prices has a good chance of continuing.  However, a short-term pull-back inside the bands is likely.",
WriteIf( trend > 30 AND trend < 70, "Although prices have broken the upper band and a upside breakout is possible, the most likely scenario for "+tname+" is to continue within current trading range.", "" ) ), "" ) +

WriteIf( C < btop AND ( ( btop - C ) / width ) < 0.5,
"below upper band by " +
WriteVal( 100 *( btop - C )/ width, 1.1 ) + "%%. ",
WriteIf( C < btop AND C > bbot , "above bottom band by " +
WriteVal( 100 *( C - bbot )/ width, 1.1 ) + "%%. ", "" ) ));

printf("\n"+
WriteIf( ( trend > 30 AND trend < 70 AND ( C > btop OR C < bbot ) ) AND abs(relwidth) > 40,
         "This picture becomes somewhat unclear due to the fact that Bollinger Bands are  currently",
         "Bollinger Bands are " )+     
WriteVal( abs( relwidth ), 1.1 ) + "%% " +
WriteIf( relwidth > 0, "wider" , "narrower" ) +
" than normal.");

printf("\n");

printf(
WriteIf( abs( relwidth ) < 40, "The current width of the bands (alone) does not suggest anything conclusive about the future volatility or movement of prices.","")+
WriteIf( relwidth < -40, "The narrow width of the bands suggests low volatility as compared to " + tname + "'s normal range.  Therefore, the probability of volatility increasing with a sharp price move has increased for the near-term. "+
"The bands have been in this narrow range for " + WriteVal(BarsSince(Cross(-40,relwidth)),1.0) + " bars. The probability of a significant price move increases the longer the bands remain in this narrow range." ,"")+
WriteIf( relwidth > 40, "The large width of the bands suggest high volatility as compared to " + tname + "'s normal range.  Therefore, the probability of volatility decreasing and prices entering (or remaining in) a trading range has increased for the near-term. "+
"The bands have been in this wide range for  " + WriteVal(BarsSince(Cross(relwidth,40)),1.0) + " bars.The probability of prices consolidating into a less volatile trading range increases the longer the bands remain in this wide range." ,""));

printf("\n\nThis commentary is not a recommendation to buy or sell. Use at your own risk.");
}
_SECTION_END();

_SECTION_BEGIN("EMA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1, 10 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );
_SECTION_END();

_SECTION_BEGIN("EMA1");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1, 10 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );
_SECTION_END();

_SECTION_BEGIN("Pivot Finder for Amibroker");

farback=Param("How Far back to go",100,50,5000,10);
nBars = Param("Number of bars", 12, 5, 40);

Title = Name() + " (" + StrLeft(FullName(), 15) + ") O: " + Open + ",

H: " + High + ", L: " + Low + ", C: " + Close;


PlotOHLC(Open, High, Low, Close,

"BIdx = " + BarIndex() +

"\n" + "O = " + O + "\n"+"H = "+ H + "\n"+"L = " + L

+ "\n"+"C ",

colorBlack, styleCandle);

GraphXSpace=7;



aHPivs = H - H;

aLPivs = L - L;



aHPivHighs = H - H;

aLPivLows = L - L;

aHPivIdxs = H - H;

aLPivIdxs = L - L;

nHPivs = 0;

nLPivs = 0;

lastHPIdx = 0;

lastLPIdx = 0;

lastHPH = 0;

lastLPL = 0;

curPivBarIdx = 0;



aHHVBars = HHVBars(H, nBars);

aLLVBars = LLVBars(L, nBars);

aHHV = HHV(H, nBars);

aLLV = LLV(L, nBars);



aVisBars = Status("barvisible");

nLastVisBar = LastValue(Highest(IIf(aVisBars, BarIndex(), 0)));

_TRACE("Last visible bar: " + nLastVisBar);



curBar = (BarCount-1);

curTrend = "";

if (aLLVBars[curBar] <

aHHVBars[curBar]) {

curTrend = "D";

}

else {

curTrend = "U";

}



for (i=0; i<farback; i++) {

curBar = (BarCount - 1) - i;



if (aLLVBars[curBar] < aHHVBars[curBar]) {



if (curTrend == "U") {

curTrend = "D";



curPivBarIdx = curBar - aLLVBars[curBar];

aLPivs[curPivBarIdx] = 1;

aLPivLows[nLPivs] = L[curPivBarIdx];

aLPivIdxs[nLPivs] = curPivBarIdx;

nLPivs++;

}} else {

if (curTrend == "D") {

curTrend = "U";

curPivBarIdx = curBar - aHHVBars[curBar];

aHPivs[curPivBarIdx] = 1;

aHPivHighs[nHPivs] = H[curPivBarIdx];

aHPivIdxs[nHPivs] = curPivBarIdx;

nHPivs++;

}} }

curBar = (BarCount-1);

candIdx = 0;

candPrc = 0;

lastLPIdx = aLPivIdxs[0];

lastLPL = aLPivLows[0];

lastHPIdx = aHPivIdxs[0];

lastHPH = aHPivHighs[0];

if (lastLPIdx > lastHPIdx) {

candIdx = curBar - aHHVBars[curBar];

candPrc = aHHV[curBar];

if (

lastHPH < candPrc AND

candIdx > lastLPIdx AND

candIdx < curBar) {

aHPivs[candIdx] = 1;



for (j=0; j<nHPivs; j++) {

aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-

(j+1)];

aHPivIdxs[nHPivs-j] = aHPivIdxs[nHPivs-(j+1)];

}

aHPivHighs[0] = candPrc ;

aHPivIdxs[0] = candIdx;

nHPivs++;

}

} else {




candIdx = curBar - aLLVBars[curBar];

candPrc = aLLV[curBar];

if (

lastLPL > candPrc AND

candIdx > lastHPIdx AND

candIdx < curBar) {




aLPivs[candIdx] = 1;



for (j=0; j<nLPivs; j++) {

aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)];

aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)];

}

aLPivLows[0] = candPrc;

aLPivIdxs[0] = candIdx;

nLPivs++;

}

}



PlotShapes(

IIf(aHPivs==1, shapeDownArrow, shapeNone), colorRed, 0,

High, Offset=-15);

PlotShapes(

IIf(aLPivs==1, shapeUpArrow , shapeNone), colorYellow, 0,

Low, Offset=-15);
_SECTION_END();

_SECTION_BEGIN("ZIG - Zig");
P = ParamField( "Price field" );
change = Param("% change",5,0.1,25,0.1);
Plot( Zig(P, change), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );
_SECTION_END();

Gann Level for Amibroker (AFL)



Gann level plotter for Amibroker (AFL)







_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g,
Close %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C,
SelectedValue( ROC( C, 1 )) ));
Plot( C, "Close", ParamColor("Color", colorOrange ), styleNoTitle |
ParamStyle("Style") | GetPriceStyle() );


YH=HHV(Close,365);
YEL=LLV(Close,365);
YCENTRE=(YH+YEL)/2;
yhov=IIf(Close>ycentre,yEL,yel);
g1=sqrt(yEL);
x1=Param("GANN MULTIPLIER",2,0.5,5,0.5);
L0=floor((g1-1*X1)^2);
L1=floor((g1-0*x1)^2);
L2=floor((g1+1*x1)^2);
L3=floor((g1+3*x1)^2);
L4=floor((g1+4*x1)^2);
L5=floor((g1+5*x1)^2);
L6=floor((g1+6*x1)^2);
L7=floor((g1+7*x1)^2);
L8=floor((g1+8*x1)^2);
L9=floor((g1+9*x1)^2);
L10=floor((g1+10*x1)^2);
L11=floor((g1+11*x1)^2);
L12=floor((g1+12*x1)^2);
L13=floor((g1+13*X1)^2);
L14=floor((g1+14*X1)^2);
L15=floor((g1+15*X1)^2);
L16=floor((g1+16*X1)^2);
L17=floor((g1+17*X1)^2);
L18=floor((g1+18*X1)^2);
L19=floor((g1+19*X1)^2);
L20=floor((g1+20*X1)^2);

Cx=C+0.12345;

x=IIf(Cx>L0 AND cx<L1,L0,IIf(cx>L1 AND cx<L2,L1,IIf(cx>L2 AND cx<L3,L2,IIf(cx>L3
AND cx<L4,L3,IIf(cx>L4 AND cx<L5,L4,IIf(cx>L5 AND cx<L6,L5,IIf(cx>L5 AND
cx<L7,L6,IIf(cx>L7 AND cx<L8,L7,IIf(cx>L8 AND cx<L9,L8,IIf(cx>L9 AND
cx<L10,L9,IIf(cx>L10 AND cx<L11,L10,IIf(cx>L11 AND cx<L12,L11,IIf(cx>L12 AND
cx<L13,L12,IIf(cx>L13 AND cx<L14,L13,IIf(cx>L14 AND cx<L15,L14,IIf(cx>L15 AND
cx<L16,L15,IIf(cx>L16 AND cx<L17,L16,IIf(cx>L17 AND cx<L18,L17,IIf(cx>L18 AND
cx<L19,L18,IIf(cx>L19 AND cx<L20,L19,L20))))))))))))))))))));
p=IIf(x==L0,L0,IIf(x==L1,L1,IIf(x==L2,L2,
IIf(x==L3,L3,IIf(x==L4,L4,IIf(x==L5,L5, IIf(x==L6,L6 ,IIf(x==L6,L6 ,
IIf(x==L7,L7 ,IIf(x==L8,L8 ,IIf(x==L9,l9,IIf(x==L10,L10
,IIf(x==L11,L11,IIf(x==L12,L12,IIf(x==L13,L13,IIf(x==L14,L14,IIf(x==L15,L15,IIf(x==L16,L16,IIf(x==L17,L17,IIf(x==L18,L18,IIf(x==L19,L19,IIf(x==L20,L20,L20))))))))))))))))))))));
q=IIf(x==L0,L1,IIf(x==L1,L2,IIf(x==L2,L3,
IIf(x==L3,L4,IIf(x==L4,L5,IIf(x==L5,L6, IIf(x==L6,L7 ,IIf(x==L6,L8 ,
IIf(x==L7,L8 ,IIf(x==L8,L9 ,IIf(x==L9,L10,IIf(x==L10,L11
,IIf(x==L11,L12,IIf(x==L12,L13,IIf(x==L13,L14,IIf(x==L14,L15,IIf(x==L15,L16,IIf(x==L16,L17,IIf(x==L17,L18,IIf(x==L18,L19,IIf(x==L19,L20,IIf(x==L20,L20,L20))))))))))))))))))))));
r=IIf(x==L0,L2,IIf(x==L1,L3,IIf(x==L2,L4,
IIf(x==L3,L5,IIf(x==L4,L6,IIf(x==L5,L7, IIf(x==L6,L8 ,IIf(x==L6,L9 ,
IIf(x==L7,L9 ,IIf(x==L8,L10 ,IIf(x==L9,L11,IIf(x==L10,L12
,IIf(x==L11,L13,IIf(x==L12,L14,IIf(x==L13,L15,IIf(x==L14,L16,IIf(x==L15,L17,IIf(x==L16,L18,IIf(x==L17,L19,IIf(x==L18,L20,IIf(x==L19,L20,IIf(x==L20,L20,L20))))))))))))))))))))));


Plot(p,"support if falls below",colorBlack,styleDots);
Plot(q,"crucial if crosses this",colorBlue,styleDots);
Plot(r,"target or resistance",colorRed,styleDots);
Plot((r-((r-q)/2)),"intermediatelevel",colorLightGrey,styleDots);
Plot((p+((q-p)/2)),"intermediatelevel2",colorLightGrey,styleDots);