Friday 27 March 2015

GUPPY MULTIMOVING AVERAGES AFL For AMibroker



 // asfatul.alam@yahoo.com

_SECTION_BEGIN("GUPPY MULTIMOVING AVERAGES AS SHOWN ON GUPPYs BOOK");
SetChartOptions(0, chartShowArrows | chartShowDates);
FastMAColor = ParamColor("Fast Group MA Color", colorRed);
SlowMAColor = ParamColor("Slow Group MA Color", colorGreen);


Plot(WMA(C, 3), _DEFAULT_NAME(), IIf(C > WMA( Close,3),colorGreen, colorRed), styleLine);
Plot(WMA(C,4), _DEFAULT_NAME(), IIf(C > WMA( Close,4),colorGreen, colorRed) ,styleLine);
Plot(WMA(C, 5), _DEFAULT_NAME(), IIf(C > WMA( Close,4),colorGreen, colorRed), styleLine);
Plot(WMA(C, 6), _DEFAULT_NAME(), IIf(C > WMA( Close,6),colorGreen, colorRed), styleLine);
Plot(WMA(C, 7), _DEFAULT_NAME(), IIf(C > WMA( Close,7),colorGreen, colorRed), styleLine);
Plot(WMA(C, 8), _DEFAULT_NAME(), IIf(C > WMA( Close,8),colorGreen, colorRed), styleLine);
Plot(WMA(C, 9), _DEFAULT_NAME(), IIf(C > WMA( Close,9),colorGreen, colorRed), styleLine);
Plot(WMA(C, 10), _DEFAULT_NAME(), IIf(C > WMA( Close,10),colorGreen, colorRed), styleLine);
Plot(WMA(C, 11), _DEFAULT_NAME(), IIf(C > WMA( Close,11),colorGreen, colorRed), styleLine);
Plot(WMA(C, 12), _DEFAULT_NAME(), IIf(C > WMA( Close,12),colorGreen, colorRed), styleLine);
Plot(WMA(C, 13), _DEFAULT_NAME(), IIf(C > WMA( Close,13),colorGreen, colorRed), styleLine);
Plot(WMA(C, 14), _DEFAULT_NAME(), IIf(C > WMA( Close,14),colorGreen, colorRed), styleLine);
Plot(WMA(C,15), _DEFAULT_NAME(), IIf(C > WMA( Close,15),colorGreen, colorRed), styleLine);
Plot(WMA(C, 16), _DEFAULT_NAME(), IIf(C > WMA( Close,16),colorGreen, colorRed), styleLine);
Plot(WMA(C, 17), _DEFAULT_NAME(), IIf(C > WMA( Close,17),colorGreen, colorRed), styleLine);
Plot(WMA(C, 18), _DEFAULT_NAME(), IIf(C > WMA( Close,18),colorGreen, colorRed), styleLine);
Plot(WMA(C, 19), _DEFAULT_NAME(), IIf(C > WMA( Close,19),colorGreen, colorRed), styleLine);
Plot(WMA(C, 20), _DEFAULT_NAME(), IIf(C > WMA( Close,20),colorGreen, colorRed), styleLine);
Plot(WMA(C, 21), _DEFAULT_NAME(), IIf(C > WMA( Close,21),colorGreen, colorRed), styleLine);
Plot(WMA(C,22), _DEFAULT_NAME(), IIf(C > WMA( Close,22),colorGreen, colorRed), styleLine);
Plot(WMA(C, 23), _DEFAULT_NAME(), IIf(C > WMA( Close,23),colorGreen, colorRed), styleLine);
Plot(WMA(C,24), _DEFAULT_NAME(), IIf(C > WMA( Close,24),colorGreen, colorRed), styleLine);
Plot(WMA(C, 25), _DEFAULT_NAME(), IIf(C > WMA( Close,25),colorGreen, colorRed), styleLine);
Plot(WMA(C, 26), _DEFAULT_NAME(), IIf(C > WMA( Close,26),colorGreen, colorRed), styleLine);
Plot(WMA(C, 27), _DEFAULT_NAME(), IIf(C > WMA( Close,27),colorGreen, colorRed), styleLine);
Plot(WMA(C, 28), _DEFAULT_NAME(), IIf(C > WMA( Close,28),colorGreen, colorRed), styleLine);
Plot(WMA(C,29), _DEFAULT_NAME(), IIf(C > WMA( Close,29),colorGreen, colorRed), styleLine);
Plot(WMA(C, 30), _DEFAULT_NAME(), IIf(C > WMA( Close,30),colorGreen, colorRed), styleLine);
Plot(WMA(C, 31), _DEFAULT_NAME(), IIf(C > WMA( Close,31),colorGreen, colorRed), styleLine);
Plot(WMA(C, 32), _DEFAULT_NAME(), IIf(C > WMA( Close,32),colorGreen, colorRed), styleLine);
Plot(WMA(C, 33), _DEFAULT_NAME(), IIf(C > WMA( Close,33),colorGreen, colorRed), styleLine);
Plot(WMA(C, 34), _DEFAULT_NAME(), IIf(C > WMA( Close,34),colorGreen, colorRed), styleLine);
Plot(WMA(C, 35), _DEFAULT_NAME(), IIf(C > WMA( Close,35),colorGreen, colorRed), styleLine);
Plot(WMA(C,36), _DEFAULT_NAME(), IIf(C > WMA( Close,36),colorGreen, colorRed), styleLine);
Plot(WMA(C, 37), _DEFAULT_NAME(), IIf(C > WMA( Close,37),colorGreen, colorRed), styleLine);
Plot(WMA(C, 38), _DEFAULT_NAME(), IIf(C > WMA( Close,38),colorGreen, colorRed), styleLine);
Plot(WMA(C, 39), _DEFAULT_NAME(), IIf(C > WMA( Close,39),colorGreen, colorRed), styleLine);
Plot(WMA(C, 40), _DEFAULT_NAME(), IIf(C > WMA( Close,40),colorGreen, colorRed), styleLine);
Plot(WMA(C, 41), _DEFAULT_NAME(), IIf(C > WMA( Close,41),colorGreen, colorRed), styleLine);
Plot(WMA(C, 42), _DEFAULT_NAME(), IIf(C > WMA( Close,42),colorGreen, colorRed), styleLine);
Plot(WMA(C, 43), _DEFAULT_NAME(), IIf(C > WMA( Close,43),colorGreen, colorRed), styleLine);
Plot(WMA(C, 44), _DEFAULT_NAME(), IIf(C > WMA( Close,44),colorGreen, colorRed), styleLine);
Plot(WMA(C, 45), _DEFAULT_NAME(), IIf(C > WMA( Close,45),colorGreen, colorRed), styleLine);
Plot(WMA(C, 46), _DEFAULT_NAME(), IIf(C > WMA( Close,46),colorGreen, colorRed), styleLine);
Plot(WMA(C, 47), _DEFAULT_NAME(), IIf(C > WMA( Close,47),colorGreen, colorRed), styleLine);
Plot(WMA(C, 48), _DEFAULT_NAME(), IIf(C > WMA( Close,48),colorGreen, colorRed), styleLine);
Plot(WMA(C, 49), _DEFAULT_NAME(), IIf(C > WMA( Close,49),colorGreen, colorRed), styleLine);
Plot(WMA(C, 50), _DEFAULT_NAME(), IIf(C > WMA( Close,50),colorGreen, colorRed), styleLine);
Plot(WMA(C, 51), _DEFAULT_NAME(), IIf(C > WMA( Close,51),colorGreen, colorRed), styleLine);
Plot(WMA(C, 52), _DEFAULT_NAME(), IIf(C > WMA( Close,52),colorGreen, colorRed), styleLine);
Plot(WMA(C, 53), _DEFAULT_NAME(), IIf(C > WMA( Close,53),colorGreen, colorRed), styleLine);
Plot(WMA(C, 54), _DEFAULT_NAME(), IIf(C > WMA( Close,54),colorGreen, colorRed), styleLine);
Plot(WMA(C, 55), _DEFAULT_NAME(), IIf(C > WMA( Close,55),colorGreen, colorRed), styleLine);
Plot(WMA(C, 56), _DEFAULT_NAME(), IIf(C > WMA( Close,56),colorGreen, colorRed), styleLine);
Plot(WMA(C, 57), _DEFAULT_NAME(), IIf(C > WMA( Close,57),colorGreen, colorRed), styleLine);
Plot(WMA(C, 58), _DEFAULT_NAME(), IIf(C > WMA( Close,58),colorGreen, colorRed), styleLine);
Plot(WMA(C, 59), _DEFAULT_NAME(), IIf(C > WMA( Close,59),colorGreen, colorRed), styleLine);
Plot(WMA(C, 60), _DEFAULT_NAME(), IIf(C > WMA( Close,60),colorGreen, colorRed), styleLine);

_SECTION_END();

SetChartOptions(0,chartShowArrows|chartShowDates);
GraphXSpace=5;
Plot(C,"",colorYellow,styleBar);

Friday 6 March 2015

Forex Trading P & F Chart AFL

Amibroker AFL: Amibroker AFL: Market Profile - V1.71 for Amibroker (AFL)







if(MarketID()==3)
{
GraphXSpace = 5;
SetChartBkColor(ParamColor("BackGroundColor",  colorCustom1));

gridColor = ParamColor("GridColor", ColorRGB( 37,64,90));
SetBarsRequired(100000,100000);


symbol = Name();
ccy2= StrRight(symbol,3);
Ccy1= StrLeft(symbol,3);

decimals=IIf(ccy2 == "JPY" OR Ccy1 =="XAG",100, IIf( Ccy1 == "XAU" , 10, 10000));
format = IIf (ccy2 == "JPY"|| Ccy1 == "XAU", 8.2, 8.4);

Box = Param("Box", 10, 1, 100, 1)/decimals;

Reverse = Param("Reverse",3, 1, 5, 1);

j = 0;

Lo[0] = Box * ceil(L[0]/Box) ;
Hi[0] = Lo[0] + box;
direction = 0;

for( i = 1; i < BarCount; i++ )
{  
    if(direction[j] == 0)
    {
        if(L[i] <= Lo[j] - Box)
        {
            Chg = Lo[j] - L[i];
            n= floor(Chg/box);
            Lo[j] = Lo[j] - n* box;
        }
        else
        {
            if(H[i] >= Lo[j] + Reverse*Box)
            {
                Chg = H[i] - Lo[j];
                n = floor(Chg/box);
                j++;
                direction[j] = 1;
                Hi[j] = Lo[j-1] + n* Box;
                Lo[j] = Lo[j-1] + Box;
            }
        }
    }
    else
    {
        if(H[i] >= Hi[j] + Box)
        {
            Chg = H[i] - Hi[j];
            n= floor(Chg/box);
            Hi[j] = Hi[j] + n*box;
        }
        else
        {
            if(L[i] <= Hi[j] - Reverse * Box )
            {
                Chg = Hi[j] - L[i];
                n= floor(Chg/box);
                j++;
                direction[j] = 0;
                Lo[j] = Hi[j-1] - n*box;
                Hi[j] = Hi[j-1] - Box;
              
            }
        }
    }
  
}
delta = BarCount - j -1;
direction = Ref(direction, - delta);



Hi = Ref(Hi, -delta) + Box/2;
Lo = Ref(Lo, -delta)- Box/2;
Cl = IIf(direction == 1, Hi, Lo);
Op = IIf(direction == 1, Cl - Box, Cl + Box);
PlotOHLC(Op, Hi, Lo, Cl,"", colorLightYellow , stylePointAndFigure|styleNoLabel);

Lastc = LastValue( C);
Last = Ref(Lastc, -(BarCount-1));
Plot( Last,"", colorRed,styleNoLine|styleDots, 0 , 0, 1);


/* Grid Construction*/
PlotGridLines = ParamToggle("PlotdGrid", "No|Yes");
if (PlotGridLines)
{
    SetChartOptions(1,0, 0);       

    end = BarCount-1;
    bar = BarIndex();
    begin =  Status("firstvisiblebar");
  
  
  
        ScreenHigh =LastValue( HHV(Hi, end - begin)) + box;
        ScreenLow =LastValue( LLV(Lo, end - begin))-box;
        shift = 5;
        gLine= LineArray( begin-shift, screenlow, end, screenLow, 0, 1);
        GridMin = screenLow;
        GridMax = screenhigh;
        step = round((GridMax - GridMin )/ box);
  
     Plot(LineArray( begin-shift, screenhigh, end, screenhigh, 0, 1),
"", gridColor, styleLine|styleNoLabel|styleNoRescale, 0, 0 ,shift);

        for (n =0; n <step ; n++)
        {
            Plot(  gLine + n*Box, "", gridColor, styleLine|styleNoLabel|styleNoRescale, 0, 0 ,shift);
            text = NumToStr( GridMin + n*Box+ 0.5*box, format);
            PlotText(text, end+2, GridMin + n*Box+ 0.25*box, colorLightYellow);
        }  
        VerticalGrid = IIf ( bar >= begin-1, IIf(frac(bar/2) ==0, screenHigh, screenLow), Null);
        Plot (VerticalGrid, "", gridColor, styleStaircase|styleNoLabel|styleNoRescale, 0,0, 1);
  
}
else
SetChartOptions(1,chartShowArrows|0);

Title  =
"Interval:   " + Interval(2) + "\n" +
"Box  :      " +  Box*decimals + "  pip \n" +
"ATR :      " +NumToStr(LastValue(ATR(20) *decimals), 1.0) + "  pip";
}

else
Title = "PF with Forex Settings is not Suitable for this market";

Thursday 5 March 2015

Amibroker AFL: Market Profile - V1.71 for Amibroker (AFL)

Amibroker AFL: Market Profile - V1.71 for Amibroker (AFL)

Amibroker AFL: Vier Box for Amibroker (AFL)

Amibroker AFL: Vier Box for Amibroker (AFL)

Amibroker AFL: MACD and Histogram with Good Understanding afl for amibroker

Amibroker AFL: MACD and Histogram with Good Understanding afl for amibroker

Amibroker AFL: Woodie's CCI Panel Full Stats for Amibroker

Amibroker AFL: Woodie's CCI Panel Full Stats for Amibroker

Amibroker AFL: DSE .................LAFSURCEML

Amibroker AFL: DSE .................LAFSURCEML

Amibroker AFL: DSE .................NTLTUBES

Amibroker AFL: DSE .................LAFSURCE

ML

DSE .................LAFSURCEML

DSE .................LAFSURCEML



Woodie's CCI Panel Full Stats for Amibroker







Woodie's CCI Panel Full Stats

/// asfatul.alam@yahoo.com


_SECTION_BEGIN("Woodie's CCI Panel Full Stats");

function StaticName( VarName )
{
return Name() + VarName;
}

procedure StaticSet( VarName, VarValue )
{
StaticVarSet(Name() + VarName, VarValue);
}

function StaticGet( VarName )
{
return Nz(StaticVarGet(Name() + VarName));
}

procedure StaticSetText( VarName, VarValue )
{
StaticVarSetText(Name() + VarName, VarValue);
}

function StaticGetText( VarName )
{
return StaticVarGetText(Name() + VarName);
}


EnableTextOutput(False);


Revision = "$Revision: 39 $";

SetChartOptions(0, chartShowDates);
SetChartOptions(3, chartLogarithmic, chartGridMiddle | chartGridPercent | chartGridMargins);


ToolTipDebug = "";


LastBarIndex = BarCount-1;
CurBarIndex = SelectedValue(BarIndex());
if (CurBarIndex > LastBarIndex)
CurBarIndex = LastBarIndex;

if (Status("action") == 1) //indicator
{
MinY = Status("axisminy");
MaxY = Status("axismaxy");
TotalY = MaxY - MinY;

LastVisibleIndex = Status("lastvisiblebarindex");
FirstVisibleIndex = Status("firstvisiblebarindex");
TotalVisibleBars = LastVisibleIndex - FirstVisibleIndex;

PixelWidth = Status("pxwidth");
PixelHeight = Status("pxheight");
ScaleY = PixelHeight / TotalY;
}
else
{
MinY = -300;
MaxY = 300;
TotalY = MaxY - MinY;

LastVisibleIndex = BarCount -1;
FirstVisibleIndex = 0;
TotalVisibleBars = LastVisibleIndex - FirstVisibleIndex;

PixelWidth = 1;
PixelHeight = 1;
ScaleY = PixelHeight / TotalY;
}

FontNameSmall = "Ariel";
FontSizeSmall = 8;
FontWeightSmall = 300;

FontNameNormal = "MS Sans Serif";
FontSizeNormal = 8;
FontWeightNormal = 300;

FontNameBig = "MS Sans Serif";
FontSizeBig = 10;
FontWeightBig=700;

GfxSetOverlayMode(0); //low level graph over chart...
GfxSetBkMode(1); //transparent
GfxSelectPen( StaticGet("ChartBkColor"), 1, 0); //to clear value area
GfxSelectSolidBrush( StaticGet("ChartBkColor") );
GfxSetTextColor( StaticGet("ChartTextColor") );

GfxSetTextAlign(10); //right, buttom
GfxSelectFont(FontNameSmall, FontSizeSmall, FontWeightSmall, True, False, 0);
GfxTextOut("by Yofa", PixelWidth-2, PixelHeight-12 );
GfxTextOut(Revision, PixelWidth-2, PixelHeight );

GfxSetTextAlign(26); //right, baseline
GfxSelectFont(FontNameNormal, FontSizeNormal, FontWeightNormal, False, False, 0);

function GfxMapYtoPixelY(Y)
{
return ( TotalY / 2 - Y ) * ScaleY;
}

_SECTION_END(); //Woodie CCI - Indicators

// Timer

TTMperiod = 6;
Low_ma = EMA(L, TTMperiod);
High_ma = EMA(H, TTMperiod);
Low_third = (High_ma - Low_ma) / 3 + Low_ma;
High_third = 2 * (High_ma - Low_ma) / 3 + Low_ma;
tempnum = Now( 4 ) - TimeNum();
TimeRem = Interval() - ((int(tempnum[BarCount - 1] / 100) * 60) + (tempnum[BarCount - 1] - int(tempnum[BarCount - 1] / 100) * 100));
if (TimeRem[BarCount - 1] < 0) TimeRem = 0;
MinuteVar = int(TimeRem / 60);
SecondsVar = int(frac(TimeRem / 60) * 60);
if (TimeRem[BarCount - 1] > 60)
{
TitleTimeRem = EncodeColor(colorWhite) + MinuteVar + ":" + WriteIf(SecondsVar > 9, "", "0") + SecondsVar;
}
else if (TimeRem[BarCount - 1] > 20)
{
TitleTimeRem = EncodeColor(colorYellow) + MinuteVar + ":" + WriteIf(SecondsVar > 9, "", "0") + SecondsVar;
}
else
{
TitleTimeRem = EncodeColor(colorRed) + MinuteVar + ":" + WriteIf(SecondsVar > 9, "", "0") + SecondsVar;
}

// Background color

SetChartBkColor(ParamColor("Panel color ",colorCustom1));

// CCI colors

zcolor= ParamColor("WCCI color",colorBlack);
z9color= ParamColor("NCCI color",colorWhite);
z6color= ParamColor("TCCI color",colorBrightGreen);
patterncolor= ParamColor("Pattern trace color",colorWhite);

// CCI periods

zperiod=Param("WCCI period",14,0,100);
z = CCI(zperiod);
z9period=Param("NCCI period",9,0,1000);
z9 = CCI(z9period);
z6period=Param("TCCI period",6,0,1000);
z6 = CCI(z6period);

// Tic/PIP value

TicMult= Param("Tic multiplier(ER2=10,YM=1,ES=4,FOREX=1)",1,0,1000000);
TicDiv= Param("Tic or PIP value(ER2=0.1,YM=1,FOREX=1)",1,0,1000000);

// Rangebar interval

rbint= Param("Rangebar interval:(YM=25.0,AB=1.5,NQ=3.75,ES=3.0)",1.0,0.25,1000000);

// Rangebar counter

rbcounter= round(((rbint-(H-L))) * ticmult);
rbcounterpercent= round((rbcounter/(rbint * ticmult))*100);

// Timer/counter title

timercode= Param("Timer:(minutes=1,rangebar=2)",1,1,2);
timetitle= WriteIf(timercode==1,TitleTimeRem, EncodeColor(colorWhite) + "Countdown " + rbcounter + " (" + rbcounterpercent + "%)");

// Spread

spread= Param("Spread (included in stop)",0,0,1000000);

// Stop value

stopval= Param("Stop above/below entry bar",2,0,1000000);

// Plot grids

PlotTheGrids = ParamToggle("Plot grids","No|Yes",0);
if (PlotTheGrids ==1)
{
PlotGrid(0);
PlotGrid(-100);
PlotGrid(100);
PlotGrid(-200);
PlotGrid(200);
}

// Angle variables

PI = atan(1.00) * 4;
periods = 30;
HighHigh = HHV(H, periods);
LowLow = LLV(L, periods);
range = 25 / (HighHigh - LowLow) * LowLow;

// EMA34 Angle

EMA34 = EMA(C,34);
x1_EMA34 = 0;
x2_EMA34 = 1;
y1_EMA34 = 0;
y2_EMA34 = (Ref(EMA34, -1) - EMA34) / Avg * range;
c_EMA34 = sqrt((x2_EMA34 - x1_EMA34)*(x2_EMA34 - x1_EMA34) + (y2_EMA34 - y1_EMA34)*(y2_EMA34 - y1_EMA34));
angle_EMA34 = round(180 * acos((x2_EMA34 - x1_EMA34)/c_EMA34) / PI);
angle_EMA34 = IIf(y2_EMA34 > 0, - angle_EMA34, angle_EMA34);

// LSMA25 Angle

LSMA25 = LinearReg(C, 25 );
x1_LSMA25 = 0;
x2_LSMA25 = 1;
y1_LSMA25 = 0;
y2_LSMA25 = (Ref(LSMA25, -1) - LSMA25) / Avg * range;
c_LSMA25 = sqrt((x2_LSMA25 - x1_LSMA25)*(x2_LSMA25 - x1_LSMA25) + (y2_LSMA25 - y1_LSMA25)*(y2_LSMA25 - y1_LSMA25));
angle_LSMA25 = round(180 * acos((x2_LSMA25 - x1_LSMA25)/c_LSMA25) / PI);
angle_LSMA25 = IIf(y2_LSMA25 > 0, - angle_LSMA25, angle_LSMA25);

// Color the bars for Woodies Trend Following

function Consecutive( array )
{
return BarsSince( NOT( array ) );
}
function Occurrences( array , period )
{
return Sum( array, period );
}
array = z;
HighBars = Consecutive( array > 0 );
LowBars = Consecutive( array < 0 );
UpCondition = BarsSince( HighBars >= 6 AND Occurrences( array > 100 , 5 ) > 0 );
DnCondition = BarsSince( LowBars >= 6 AND Occurrences( array < -100 , 5 ) > 0 );
UpTrend = ( array > 0 ) AND ( UpCondition < DnCondition );
DnTrend = ( array < 0 ) AND ( UpCondition > DnCondition );
TrTrend = ( HighBars >= 5 AND NOT UpTrend ) OR ( LowBars >= 5 AND NOT DnTrend );
Color = IIf( UpTrend, colorBlue, IIf( DnTrend, colorRed, IIf( TrTrend, colorYellow, colorGrey40 ) ) );

// Plot the Mock CZI on the 100s

ColorANGLE_EMA = IIf(angle_EMA34 >=5,colorTurquoise,
IIf(angle_EMA34 <5 AND angle_EMA34 >=3.57,colorDarkGreen,
IIf(angle_EMA34 <3.57 AND angle_EMA34 >=2.14,colorPaleGreen,
IIf(angle_EMA34 <2.14 AND angle_EMA34 >=.71,colorLime,
IIf(angle_EMA34 <=-1*5,colorDarkRed,
IIf(angle_EMA34 >-1*5 AND angle_EMA34 <=-1*3.57,colorRed,
IIf(angle_EMA34 >-1*3.57 AND angle_EMA34 <=-1*2.14,colorOrange,
IIf(angle_EMA34 >-1*2.14 AND angle_EMA34 <=-1*.71,colorLightOrange,colorYellow))))))));
Plot(100,"", ColorANGLE_EMA , styleLine | styleThick | styleNoLabel);
Plot(-100,"", ColorANGLE_EMA , styleLine | styleThick | styleNoLabel);

// Plot the Mock Sidewinder on the 200s

SW = IIf((abs(angle_EMA34) >= 15) AND (abs(angle_EMA34 + angle_LSMA25) >= 50), IIf(angle_LSMA25 > 0, 2, -2),
IIf((abs(angle_EMA34) >= 0) AND (((angle_EMA34 >= 0) AND (angle_LSMA25 >= 0)) OR ((angle_EMA34 <= 0) AND (angle_LSMA25 <= 0))) AND (abs(angle_EMA34 + angle_LSMA25) >= 5), IIf(angle_LSMA25 > 0, 1, -1), 0));
ColorSW = IIf(abs(SW) == 2, colorBrightGreen,
IIf(abs(SW) == 1, colorYellow, colorRed));
Plot(200,"", ColorSW, styleLine | styleThick | styleNoLabel);
Plot(-200,"", ColorSW, styleLine | styleThick | styleNoLabel);

// Zero line 25lsma

Plot(0,"", IIf(C > LSMA25,colorBrightGreen,IIf(C < LSMA25,colorRed,colorTeal)), styleLine | styleThick | styleNoLabel);

// CCI Points

diffCode=ParamToggle("Plot CCI diff ","No|Yes",1);
CCipointmove= z-Ref(z,-1);
CCIpointmovetitle= WriteIf(diffcode==1 AND abs(CCipointmove)<15,EncodeColor(colorRed) + "\n" + "DIFF " +
abs(round(CCipointmove)) + "\n",WriteIf(diffcode==1 AND abs(CCipointmove)>=15 AND abs(CCipointmove)<20,EncodeColor(colorYellow) + "\n" + "DIFF " +
abs(round(CCipointmove)) + "\n",WriteIf(diffcode==1 AND abs(CCIpointmove)>=20,EncodeColor(colorBrightGreen) + "\n" + "DIFF " +
abs(round(CCipointmove))+ "\n","")));

// Price Panel

Lastpricetitlehi= WriteIf(H>Ref(H,-1),EncodeColor(colorBrightGreen) + Ref(H,-1) + " " + H , EncodeColor(colorWhite)+ Ref(H,-1) + " " + H);
Lastpricetitlelo= WriteIf(L<Ref(L,-1),EncodeColor(colorRed) + Ref(L,-1) + " " + L , EncodeColor(colorWhite) + Ref(L,-1) + " " + L);
Closecolor=WriteIf(C==H AND H>Ref(H,-1),EncodeColor(colorBrightGreen),WriteIf(C==L AND L<Ref(L,-1),EncodeColor(colorRed),EncodeColor(colorWhite)));

//Pivot Points Calculations

pivCode=ParamToggle("Plot pivots ","No|Yes",1);
DayH = TimeFrameGetPrice("H", inDaily, -1);
DayL = TimeFrameGetPrice("L", inDaily, -1);
DayC = TimeFrameGetPrice("C", inDaily, -1);
DayO = TimeFrameGetPrice("O", inDaily);
HiDay = TimeFrameGetPrice("H", inDaily);
LoDay = TimeFrameGetPrice("L", inDaily);
PP = (DayH + DayL + DayO + DayO) / 4 ;
R1 = (2 * PP) - DayL;
S1 = (2 * PP) - DayH;
R2 = PP + R1 - S1;
S2 = PP + S1 - R1;
R3 = R2 + (R1 - PP);
S3 = S2 - (PP - S1);
ppvalue= round(abs((C-pp)/ticdiv));
r1value= round(abs((C-r1)/ticdiv));
s1value= round(abs((C-s1)/ticdiv));
r2value= round(abs((C-r2)/ticdiv));
s2value= round(abs((C-s2)/ticdiv));
r3value= round(abs((C-r3)/ticdiv));
s3value= round(abs((C-s3)/ticdiv));
wptitle= WriteIf(pivCode==1 AND C>=R3, "\n" + EncodeColor(colorYellow)+"R3 " + "-" + (R3value) + "\n" + "\n",
WriteIf(pivCode==1 AND C<=R3 AND C>=R2, "\n" + EncodeColor(colorYellow)+"R3 " + "+" + (R3value) + "\n" + EncodeColor(colorYellow) + "R2 " + "-" + (R2value) + "\n" + "\n",
WriteIf(pivCode==1 AND C<=R2 AND C>=R1, "\n" + EncodeColor(colorYellow)+"R2 " + "+" + (R2value) + "\n" + EncodeColor(colorYellow) + "R1 " + "-" + (R1value) + "\n" + "\n",
WriteIf(pivCode==1 AND C<=R1 AND C>=PP, "\n" + EncodeColor(colorYellow)+"R1 " + "+" + (R1value) + "\n" + EncodeColor(colorYellow) + "PP " + "-" + (PPvalue) + "\n" + "\n",
WriteIf(pivCode==1 AND C<=PP AND C>=S1, "\n" + EncodeColor(colorYellow)+"PP " + "+" + (PPvalue) + "\n" + EncodeColor(colorYellow) + "S1 " + "-" + (S1value) + "\n" + "\n",
WriteIf(pivCode==1 AND C<=S1 AND C>=S2, "\n" + EncodeColor(colorYellow)+"S1 " + "+" + (S1value) + "\n" + EncodeColor(colorYellow) + "S2 " + "-" + (S2value) + "\n" + "\n",
WriteIf(pivCode==1 AND C<=S2 AND C>=S3, "\n" + EncodeColor(colorYellow)+"S2 " + "+" + (S2value) + "\n" + EncodeColor(colorYellow) + "S3 " + "-" + (S3value) + "\n" + "\n",
WriteIf(pivCode==1 AND C<=S3, "\n" + EncodeColor(colorYellow)+"S3 " + "+" + (S3value) + "\n"+ "\n",""))))))));

// HOD , LOD, Range

HiDayTitle = WriteIf(pivCode==1,EncodeColor(colorYellow) + "HOD ","");
HiDayTitle = WriteIf(pivCode==1,HiDayTitle + EncodeColor(colorYellow) + HiDay + " +" + round(abs((HiDay-C)/ticdiv)) + "\n","");
LoDayTitle = WriteIf(pivCode==1,EncodeColor(colorYellow) + "LOD ","");
LoDayTitle = WriteIf(pivCode==1,LoDayTitle + EncodeColor(colorYellow) + LoDay + " -" + round(abs((C-LoDay)/ticdiv)) + "\n"," ");
RangeTitle1 =WriteIf(pivCode==1,EncodeColor(colorYellow) + "Day Range " + EncodeColor(colorYellow) + StrToNum(NumToStr(round((HiDay - LoDay)/ticdiv), 4.4)) + "\n","");

// Pattern codes

Cziquallong= ((angle_EMA34>=5 OR Ref(angle_EMA34,-1)>=5) AND Ref(angle_EMA34,-2)>=5) OR (Ref(angle_EMA34,-1)>=5 AND angle_EMA34>=5);
Cziqualshort= ((angle_EMA34<=-5 OR Ref(angle_EMA34,-1)<=-5) AND Ref(angle_EMA34,-2)<=-5) OR (Ref(angle_EMA34,-1)<=-5 AND angle_EMA34<=-5);

// ZLR Long

Linex_long=Ref(z,-1)>100 AND z<100;
barsfromline_long=BarsSince(Linex_long);
CCIhook_long=z>Ref(z,-1) AND Ref(z,-1)>-100 AND Ref(z,-1)<Ref(z,-2) AND Ref(z,-2)>-100 AND z>0;
SW_trendinglong= sw==1 OR sw==2;
zlrlong1= abs(CCipointmove)>=15 AND SW_trendinglong AND z<120 AND barsfromline_long<=10 AND CCIhook_long AND UpTrend;
zlrnextl= z<120 AND barsfromline_long<10 AND CCIhook_long AND UpTrend;
zlrlong= Cziquallong AND (zlrlong1 OR ( NOT Ref(zlrlong1,-1) AND Ref(zlrnextl,-1) AND abs(CCipointmove)>=15 AND z>=Ref(z,-1) AND SW_trendinglong AND z<120 AND UpTrend));

// ZLR Short

Linex_short=Ref(z,-1)<=-100 AND z>=-100;
barsfromline_short=BarsSince(Linex_short);
CCIhook_short=z<Ref(z,-1) AND Ref(z,-1)<100 AND Ref(z,-1)>Ref(z,-2) AND Ref(z,-2)<100 AND z<0;
SW_trendingshort= sw==-1 OR sw==-2;
zlrshort1= abs(CCipointmove)>=15 AND SW_trendingshort AND z>-120 AND barsfromline_short<=10 AND CCIhook_short AND DnTrend;
zlrnexts= z>-120 AND barsfromline_short<10 AND CCIhook_short AND DnTrend;
zlrshort= Cziqualshort AND (zlrshort1 OR (NOT Ref(zlrshort1,-1) AND Ref(zlrnexts,-1) AND abs(CCipointmove)>=15 AND z<=Ref(z,-1) AND SW_trendingshort AND z>-120 AND DnTrend));

// Famir Long

FamirLinex_long=Ref(z,-1)<=-100 AND z>-100;
Famir_barsfromline_long=BarsSince(FamirLinex_long);
Famir_pivotlong= (Ref(z,-2)>Ref(z,-1)AND Ref(z,-1)>=-55 AND Ref(z,-2)>=-55) OR (Ref(z,-3)>Ref(z,-1) AND Ref(z,-1)>=-55 AND Ref(z,-2)>=-55 AND Ref(z,-3)>=-55)OR (Ref(z,-4)>Ref(z,-1) AND Ref(z,-1)>=-55 AND Ref(z,-2)>=-55 AND Ref(z,-3)>=-55);
Famirhook_long=Famir_pivotlong AND z>Ref(HHV(z,Famir_barsfromline_long),-1) AND (z>=-55 AND z<=55);
Famirlong= Famir_barsfromline_long<10 AND Famirhook_long AND ((DnTrend OR Ref(Dntrend,-BarsSince(z<0))==1) AND NOT UpTrend) AND C>LSMA25;

// Famir Short

FamirLinex_short=Ref(z,-1)>=100 AND z<100;
Famir_barsfromline_short=BarsSince(FamirLinex_short);
Famir_pivotshort= (Ref(z,-2)<Ref(z,-1)AND Ref(z,-1)<=55 AND Ref(z,-2)<=55) OR (Ref(z,-3)<Ref(z,-1)AND Ref(z,-1)<=55 AND Ref(z,-2)<=55 AND Ref(z,-3)<=55) OR (Ref(z,-4)<Ref(z,-1) AND Ref(z,-1)<=55 AND Ref(z,-2)<=55 AND Ref(z,-3)<=55);
Famirhook_short=Famir_pivotshort AND z<Ref(LLV(z,Famir_barsfromline_short),-1) AND (z>=-55 AND z<=55);
Famirshort= Famir_barsfromline_short<10 AND Famirhook_short AND ((UpTrend OR Ref(Uptrend,-BarsSince(z>0))==1) AND NOT DnTrend) AND C<LSMA25;

// HFE

HFEshort=(Ref(z,-1)>200 AND z<200);
HFElong=(Ref(z,-1)<-200 AND z>-200);
HFE= HFEshort OR HFElong;

// VT Long

vtLinex_long=Ref(z,-1)<=-200 AND z>-200;
vt_barsfromline_long=BarsSince(vtLinex_long);
vtlong_A = z<-200;
vtlong_B = Ref(z,-1)<=Ref(z,-2) OR
Ref(z,-2)<=Ref(z,-3) OR
Ref(z,-3)<=Ref(z,-4) OR
Ref(z,-4)<=Ref(z,-5) OR
Ref(z,-5)<=Ref(z,-6) OR
Ref(z,-6)<=Ref(z,-7) OR
Ref(z,-7)<=Ref(z,-8);
vtlong_bs_A = BarsSince(vtlong_A);
vtlong_bs_B = BarsSince(vtlong_b);
Vtlong_bars = vtlong_bs_A>=5 AND vtlong_bs_B<=0;
vt_pivotlong= Vtlong_bars;
swinghibars=BarsSince(z>Ref(HHV(z,vt_barsfromline_long),-1));
vthook_long= vt_pivotlong AND z>Ref(HHV(z,vt_barsfromline_long),-1);
vtlong= z<100 AND vt_barsfromline_long<=11 AND (Ref(HHV(z,vt_barsfromline_long),-1)<0 OR HHV(z,vt_barsfromline_long)<=0) AND vthook_long AND C>Lsma25 AND Ref(swinghibars>=2,-1) AND z>-100;

// VT Short

vtLinex_short=Ref(z,-1)>=200 AND z<200;
vt_barsfromline_short=BarsSince(vtLinex_short);
vtshort_A = z>200 ;
vtshort_B =Ref(z,-1)>=Ref(z,-2) OR
Ref(z,-2)>=Ref(z,-3) OR
Ref(z,-3)>=Ref(z,-4) OR
Ref(z,-4)>=Ref(z,-5) OR
Ref(z,-5)>=Ref(z,-6) OR
Ref(z,-6)>=Ref(z,-7) OR
Ref(z,-7)>=Ref(z,-8);
vtshort_bs_A = BarsSince(vtshort_A);
vtshort_bs_B = BarsSince(vtshort_b);
Vtshort_bars = vtshort_bs_A>=5 AND vtshort_bs_B<=0;
vt_pivotshort= Vtshort_bars;
swinglowbars= BarsSince(z<Ref(LLV(z,vt_barsfromline_short),-1));
vthook_short= vt_pivotshort AND z<Ref(LLV(z,vt_barsfromline_short),-1);
vtshort= z>-100 AND vt_barsfromline_short<=11 AND (Ref(LLV(z,vt_barsfromline_short),-1)>0 OR LLV(z,vt_barsfromline_short)>0) AND vthook_short AND C<Lsma25 AND Ref(swinglowbars>=2,-1) AND z<100;

// GB 100 Long

Linex_longGB=Ref(z,-1)>100 AND z<100;
barsfromline_longGB=BarsSince(Linex_longGB);
CCIhook_longGB= Ref(z,-1)<-100 AND z>-100;
GB100long= z<100 AND barsfromline_longGB<=12 AND Cziquallong AND CCIhook_longGB AND (Ref(UpTrend,-BarsSince(z>0))==1 AND NOT DnTrend);

// GB100 Short

Linex_shortGB=Ref(z,-1)<-100 AND z>-100;
barsfromline_shortGB=BarsSince(Linex_shortGB);
CCIhook_shortGB=Ref(z,-1)>100 AND z<100;
Gb100short= z>-100 AND barsfromline_shortGB<=12 AND Cziqualshort AND CCIhook_shortGB AND (Ref(DnTrend,-BarsSince(z<0))==1 AND NOT UpTrend);

// TT Long

Minuszero=BarsSince(Ref(z,-1)>0) + 1;
TTCCIhook_long= z>Ref(z,-1) AND z>0;
TTlong= Cziquallong AND z<100 AND Ref(UpTrend,-Minuszero)==1 AND LLV(Ref(z,-1),BarsSince(Ref(z,-1)>=100))>-100 AND HHV(Ref(z,-1),BarsSince(Ref(z,-1)< 0))>=100 AND TTCCIhook_long AND Ref(LowBars,-1)>=4 AND Ref(LowBars,-1)<=9;

// TT Short

Pluszero=BarsSince(Ref(z,-1)<0) + 1;
TTCCIhook_short=z<Ref(z,-1) AND z<0;
TTshort= Cziqualshort AND z>-100 AND Ref(DnTrend,-Pluszero)==1 AND HHV(Ref(z,-1),BarsSince(Ref(z,-1)<=-100))<100 AND LLV(Ref(z,-1),BarsSince(Ref(z,-1)>0))<=-100 AND TTCCIhook_short AND Ref(HighBars,-1)>=4 AND Ref(HighBars,-1)<=9;

// PT Long

Phook_long1= Ref(z,-1)>=Ref(z,-2) AND Ref(z,-2)<Ref(z,-3) AND Ref(z,-3)>0;
Phook_long2= Ref(z,-3)>-100 AND Ref(z,-1)>Ref(z,-2) AND Ref(z,-2)<Ref(z,-3) AND Ref(z,-3)<Ref(z,-4) AND Ref(z,-4)>0;
Ptlong= Cziquallong AND (Phook_long1 OR Phook_long2) AND (z>0 AND Ref(z,-1)<0 AND z<120 AND Ref(z,-1)>-100 AND Ref(z,-2)>-100 AND z>Ref(z,-1) AND UpTrend);

// PT Short

Phook_short1= Ref(z,-1)<=Ref(z,-2) AND Ref(z,-2)>Ref(z,-3) AND Ref(z,-3)<0;
Phook_short2= Ref(z,-3)<100 AND Ref(z,-1)<Ref(z,-2) AND Ref(z,-2)>Ref(z,-3) AND Ref(z,-3)> Ref(z,-4) AND Ref(z,-4)<0;
Ptshort= Cziqualshort AND (Phook_short1 OR Phook_short2) AND (z<0 AND Ref(z,-1)>0 AND z>-120 AND Ref(z,-1)<100 AND Ref(z,-2)<100 AND z<Ref(z,-1) AND DnTrend);

// Ghosts (6)
GhostBarIndex = LastBarIndex;
if (LastBarIndex != CurBarIndex)
GhostBarIndex = CurBarIndex;

C14GhostChange = Param("Ghost - Min WCCI change %", 8, 0, 50);
GhostCciShift=300;
C14GhostChange = Param("Ghost - Min WCCI change %", 8, 0, 50);
GhostCciChange=C14GhostChange / 2; //CCI values are shifted up 300 ponts (-300 - + 300 -> 0 - 600)
C14GhostSteepCompToZL=Param("Ghost - Max trend line slope to ZL(CCI/bar)", 8, 0, 30, 1);
C14GhostSteepCompFromZL=Param("Ghost - Max trend line slope from ZL(CCI/bar)", 4, 0, 30, 1);

// Ghost Long (6)
C14Shifted = -Z + GhostCciShift;
C14Shifted = IIf(C14Shifted < 0, 0, C14Shifted);
C14Shifted = IIf(C14Shifted > 600, 600, C14Shifted);

GhostLongLeft = -Peak(C14Shifted, GhostCciChange, 3) + GhostCciShift;
GhostLongHead = -Peak(C14Shifted, GhostCciChange, 2) + GhostCciShift;
GhostLongRight = -Peak(Ref(C14Shifted,-1), GhostCciChange, 1) + GhostCciShift;
GhostLongRightDip = -Ref(Trough(C14Shifted, GhostCciChange, 1), -1) + GhostCciShift;
GhostLongRightDipIndex = BarIndex() - Ref(TroughBars(C14Shifted, GhostCciChange, 1), -1)-1;
GhostLongLeftDip = -Ref(Trough(C14Shifted, GhostCciChange, 2), -1) + GhostCciShift;
GhostLongLeftDipIndex = BarIndex() - Ref(TroughBars(C14Shifted, GhostCciChange, 2), -1) -1;
GhostLongHeadWidth = GhostLongRightDipIndex - GhostLongLeftDipIndex;
GhostLongRightWidth = BarIndex() - GhostLongRightDipIndex;
GhostLongComp = (GhostLongRightDip - GhostLongLeftDip) / GhostLongHeadWidth;
GhostLongBar = ( (GhostLongLeft > GhostLongHead AND GhostLongRight > GhostLongHead AND GhostLongHead <= -100 ) //Ghost
OR (GhostLongLeft < GhostLongHead AND GhostLongRight < GhostLongHead AND GhostLongLeft <= -100)) //MGhost
AND GhostLongLeftDip <= 0
AND GhostLongRightDip <= 0
AND (GhostLongRightDip + GhostLongComp*GhostLongRightWidth <= Z OR Z>0)//WCCI returned above neckline
AND GhostLongHeadWidth < 25
AND GhostLongRightWidth > 1 AND GhostLongRightWidth < 12;
GhostLong = GhostLongBar AND NOT Ref(GhostLongBar,-1) AND Z < 120
AND GhostLongComp >= -C14GhostSteepCompFromZL AND GhostLongComp <= C14GhostSteepCompToZL;

GhostLongRef = BarsSince(GhostLong);

if ( GhostLongRef[GhostBarIndex] <= 5 )
{
GhostLongIndex = GhostBarIndex - GhostLongRef[GhostBarIndex];
GhostLine = LineArray( GhostLongLeftDipIndex[GhostLongIndex],
GhostLongLeftDip[GhostLongIndex],
GhostLongRightDipIndex[GhostLongIndex] + 10,
GhostLongRightDip[GhostLongIndex] + GhostLongComp[GhostLongIndex] * 10,
0, False);
Plot(GhostLine, "", colorWhite, styleThick | styleNoLabel | styleNoTitle);
}

C14Shifted = Z + GhostCciShift;
C14Shifted = IIf(C14Shifted < 0, 0, C14Shifted);
C14Shifted = IIf(C14Shifted > 600, 600, C14Shifted);

GhostShortLeft = Peak(C14Shifted, GhostCciChange, 3) - GhostCciShift;
GhostShortHead = Peak(C14Shifted, GhostCciChange, 2) - GhostCciShift;
GhostShortRight = Peak(C14Shifted, GhostCciChange, 1) - GhostCciShift;
GhostShortRightDip = Ref(Trough(C14Shifted, GhostCciChange, 1), -1) - GhostCciShift;
GhostShortRightDipIndex = BarIndex() - Ref(TroughBars(C14Shifted, GhostCciChange, 1), -1) -1;
GhostShortLeftDip = Ref(Trough(C14Shifted, GhostCciChange, 2), -1) - GhostCciShift;
GhostShortLeftDipIndex = BarIndex() - Ref(TroughBars(C14Shifted, GhostCciChange, 2), -1) -1;
GhostShortHeadWidth = GhostShortRightDipIndex - GhostShortLeftDipIndex;
GhostShortRightWidth = BarIndex() - GhostShortRightDipIndex;
GhostShortComp = (GhostShortRightDip - GhostShortLeftDip) / GhostShortHeadWidth;
GhostShortBar = ( (GhostShortLeft < GhostShortHead AND GhostShortRight < GhostShortHead AND GhostShortHead >= 100) //Ghost
OR (GhostShortLeft > GhostShortHead AND GhostShortRight > GhostShortHead AND GhostShortLeft >= 100)) //MGhost
AND GhostShortLeftDip >= 0
AND GhostShortRightDip >=0
AND (GhostShortRightDip + GhostShortComp*GhostShortRightWidth >= Z OR Z<0) //WCCI returned below neckline
AND GhostShortHeadWidth < 25
AND GhostShortRightWidth > 1 AND GhostShortRightWidth < 12;
GhostShort = GhostShortBar AND NOT Ref(GhostShortBar,-1) AND Z > -120
AND GhostShortComp <= C14GhostSteepCompFromZL AND GhostShortComp >= -C14GhostSteepCompToZL;

GhostShortRef = BarsSince(GhostShort);

if ( GhostShortRef[GhostBarIndex] <= 5 )
{
GhostShortIndex = GhostBarIndex - GhostShortRef[GhostBarIndex];
GhostLine = LineArray( GhostShortLeftDipIndex[GhostShortIndex],
GhostShortLeftDip[GhostShortIndex],
GhostShortRightDipIndex[GhostShortIndex] + 10,
GhostShortRightDip[GhostShortIndex] + GhostShortComp[GhostShortIndex] * 10,
0, False);
Plot(GhostLine, "", colorWhite, styleThick | styleNoLabel | styleNoTitle);
}


PatCode1=ParamToggle("Plot ZLR (1)","No|Yes",1);
PatCode2=ParamToggle("Plot FAMIR (2)","No|Yes",1);
PatCode3=ParamToggle("Plot VT (3)","No|Yes",1);
PatCode4=ParamToggle("Plot GB100 (4)","No|Yes",1);
PatCode5=ParamToggle("Plot TT (5)","No|Yes",1);
PatCode6=ParamToggle("Plot GHOST (6)","No|Yes",1);
PatCode7=ParamToggle("Plot HFE","No|Yes",1);

Signaltitle= WriteIf(PatCode1==1 AND zlrlong,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- ZLR ***" + "\n",
WriteIf(PatCode1==1 AND zlrshort,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- ZLR ***" + "\n",
WriteIf(PatCode2==1 AND Famirshort,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- FAMIR ***" + "\n",
WriteIf(PatCode2==1 AND Famirlong,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- FAMIR ***" + "\n",
WriteIf(PatCode3==1 AND VTlong AND NOT famirlong,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- VT ***" + "\n",
WriteIf(PatCode3==1 AND VTshort AND NOT famirshort,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- VT ***" + "\n",
WriteIf(PatCode4==1 AND GB100long,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- GB100 ***" + "\n",
WriteIf(PatCode4==1 AND Gb100short,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- GB100 ***" + "\n",
WriteIf(PatCode5==1 AND TTLong,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- TT ***" + "\n",
WriteIf(PatCode5==1 AND TTShort,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- TT ***" + "\n",
WriteIf(PatCode6==1 AND GhostLong,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- GHOST ***" + "\n",
WriteIf(PatCode6==1 AND GhostShort,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- GHOST ***" + "\n",
WriteIf(PatCode7==1 AND HFE,EncodeColor(colorDarkRed) + "\n" + "*** ALERT -- HFE ***" + "\n","")))))))))))));

// Pattern signal codes

PlotShapes(IIf(PatCode1==1 AND zlrlong,shapeDigit1,shapeNone),colorBlue,0,Min(z,0),-15);
PlotShapes(IIf(PatCode1==1 AND zlrshort,shapeDigit1+ shapePositionAbove,shapeNone),colorRed,0,Max(z,0),-15);
PlotShapes(IIf(PatCode2==1 AND famirlong,shapeDigit2,shapeNone),colorBlue,0,Min(z,0),-15);
PlotShapes(IIf(PatCode2==1 AND famirShort ,shapeDigit2+ shapePositionAbove,shapeNone),colorRed,0,Max(z,0),-15) ;
PlotShapes(IIf(PatCode3==1 AND vtlong AND NOT famirlong,shapeDigit3,shapeNone),colorBlue,0,Min(z,0),-47);
PlotShapes(IIf(PatCode3==1 AND vtshort AND NOT famirshort,shapeDigit3+ shapePositionAbove,shapeNone),colorRed,0,Max(z,0),-47);
PlotShapes(IIf(PatCode4==1 AND GB100long,shapeDigit4,shapeNone),colorBlue,0,Min(z,0),-60);
PlotShapes(IIf(PatCode4==1 AND GB100short,shapeDigit4+ shapePositionAbove,shapeNone),colorRed,0,Max(z,0),-60);
PlotShapes(IIf(PatCode5==1 AND ttlong,shapeDigit5,shapeNone),colorBlue,0,Min(z,0),-50);
PlotShapes(IIf(PatCode5==1 AND ttshort,shapeDigit5+ shapePositionAbove,shapeNone),colorRed,0,Max(z,0),-50);
PlotShapes(IIf(PatCode6==1 AND GhostLong,shapeDigit6,shapeNone),colorBlue,0,Min(z,0),-50);
PlotShapes(IIf(PatCode6==1 AND GhostShort,shapeDigit6+ shapePositionAbove,shapeNone),colorRed,0,Max(z,0),-50);
PlotShapes(IIf(PatCode7==1 AND HFEshort,shapeCircle,shapeNone),IIf(PatCode7==1 AND HFEshort,colorYellow,shapeNone),0,200,10);
PlotShapes(IIf(PatCode7==1 AND HFElong,shapeCircle,shapeNone),IIf(PatCode7==1 AND HFElong,colorYellow,shapeNone),0,-200,-10) ;

// CCI hook Exit
HookExitLong= z<=Ref(z,-1);
HookExitShort= z>=Ref(z,-1);

// 100 Line Cross Exit Conservative
Cross100longC= z<=Ref(z,-1) AND z<100;
Cross100shortC= z>=Ref(z,-1) AND z>-100;

// 100 Line Cross Exit Aggressive
Cross100longA= Ref(z,-1)>100 AND z<100;
Cross100shortA= Ref(z,-1)<-100 AND z>-100;

// Mplay Exit

MplayExitLong= z<Ref(z,-1) AND Ref(z,-1)<Ref(z,-2) AND C<O;
MplayExitShort= z>Ref(z,-1) AND Ref(z,-1)>Ref(z,-2) AND C>O;

// Heikin-Ashi Exit

HaClose =EMA((O+H+L+C)/4,3);
HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );
HaHigh = Max( H, Max( HaClose, HaOpen ) );
HaLow = Min( L, Min( HaClose, HaOpen ) );
HExitConLong= HaLow < HaOpen;
HExitConShort= HaHigh > HaOpen;

// Exit code
ExitCode= Param("Exits:Hook=1,100xConservative=2,100xAggressive=3,Mplay=4,H-Ashi=5",1,1,5);
ExitCodeTitleLong= IIf(ExitCode==1,HookExitLong,IIf(Exitcode==2,Cross100longC,IIf(Exitcode==3,Cross100longA,IIf(Exitcode==4,MplayExitLong,IIf(Exitcode==5,HExitConLong,0)))));
ExitCodeTitleShort= IIf(ExitCode==1,HookExitShort,IIf(Exitcode==2,Cross100shortC,IIf(Exitcode==3,Cross100shortA,IIf(Exitcode==4,MplayExitShort,IIf(Exitcode==5,HExitConShort,0)))));
AllPatterns =(zlrlong AND patcode1==1) OR (famirlong AND patcode2==1) OR (Vtlong AND patcode3==1) OR (gb100long AND patcode4==1) OR (ttlong AND patcode5==1) OR (GhostLong AND patcode6==1) OR (Hfelong AND patcode7==1)
OR (zlrshort AND patcode1==1) OR (famirshort AND patcode2==1) OR (Vtshort AND patcode3==1) OR (gb100short AND patcode4==1) OR (ttshort AND patcode5==1) OR (GhostShort AND patcode6==1) OR (Hfeshort AND patcode7==1);
BuyPattern = (zlrlong AND patcode1==1) OR (famirlong AND patcode2==1) OR (Vtlong AND patcode3==1) OR (gb100long AND patcode4==1) OR (ttlong AND patcode5==1) OR (GhostLong AND patcode6==1) OR (Hfelong AND patcode7==1);
SellPattern= ExitCodeTitleLong;
ShortPattern = (zlrshort AND patcode1==1) OR (famirshort AND patcode2==1) OR (Vtshort AND patcode3==1) OR (gb100short AND patcode4==1) OR (ttshort AND patcode5==1) OR (GhostShort AND patcode6==1) OR (Hfeshort AND patcode7==1);
CoverPattern = ExitCodeTitleShort;

//Plot Sell/Cover Arrows

Sell1=ExRem(SellPattern,BuyPattern);
Cover1=ExRem(CoverPattern,ShortPattern);
SellCode=ParamToggle("Plot sell/cover arrows ","No|Yes",0);
PlotShapes(IIf(Sell1 AND SellCode==1,shapeHollowDownArrow,shapeNone),colorBlue,0,200,10);
PlotShapes(IIf(Cover1 AND SellCode==1,shapeHollowDownArrow,shapeNone),colorRed,0,200,10);

// Calculate pattern hilites

// Long

AsellL= BuyPattern;
BsellL= Sell1;
bs_AsellL= BarsSince(AsellL);
bs_BsellL= BarsSince(BsellL);
bars_sellL= IIf(bs_ASellL<= bs_BsellL,bs_AsellL,0);

//Short
AsellS= ShortPattern;
BsellS= Cover1;
bs_AsellS= BarsSince(AsellS);
bs_BsellS= BarsSince(BsellS);
bars_sellS= IIf(bs_ASellS<= bs_BsellS,bs_AsellS,0);
hilitecode=ParamToggle("Hi-lite patterns","No|Yes",0);

// CCI Line

CCIcolor= IIf(((bars_sellL OR bars_sellS) OR AllPAtterns) AND hilitecode==1,patterncolor,zcolor);
Plot(round(z),"WCCI", CCIcolor , styleLine | styleThick);

Plot(round(z9),"NCCI", z9color, styleLine);

// Turbo CCI

Plot(round(z6),"TCCI", z6color, styleLine);

// CCI Histogram

Plot( array, "", colorDefault, styleLine | styleThick | styleNoLabel);
Plot( array, "", Color, styleHistogram | styleThick| styleNoLabel);

// BackTest Long

LastPatLong= BuyPattern;
LastPatBarLong= BarsSince(LastPatLong);
DDL=IIf((((LLV(L,LastPatBarLong)-Ref(C,-LastPatBarLong))))/ticdiv>=0,0,(((LLV(L,LastPatBarLong)-Ref(C,-LastPatBarLong))))/ticdiv);
BTExitLong= (((C-Ref(C,-LastPatBarLong))))/ticdiv;
PeakLong=IIf((((HHV(H,LastPatBarLong)-Ref(C,-LastPatBarLong))))/ticdiv<=0,0,(((HHV(H,LastPatBarLong)-Ref(C,-LastPatBarLong))))/ticdiv);
StopLong1= Ref(C,-LastPatBarLong) - (Ref(L,-LastPatBarLong) - (stopval*ticdiv) - (spread*ticdiv));
stoplong= (((StopLong1)))/ticdiv;
BackTestLongTitle= WriteIf(Sell1,EncodeColor(colorBlue) + "\n" +
"Stop " + (Ref(C,-LastPatBarLong) - (round(stoplong)*ticdiv)) + " " + round(stoplong) + "\n" +
"DD " + (Ref(C,-LastPatBarLong) + (round(DDL)*ticdiv)) + " " + round(DDL) + "\n" +
"Exit " + (Ref(C,-LastPatBarLong) + (round(BTExitLong)*ticdiv)) + " " + round(BTExitLong) + "\n" +
"Peak " + (Ref(C,-LastPatBarLong) + (round(PeakLong)*ticdiv)) + " " + round(PeakLong) + "\n",EncodeColor(colorBlue) + "\n" +
"Stop " + (Ref(C,-LastPatBarLong) - (round(stoplong)*ticdiv)) + " " + round(stoplong) + "\n" +
"DD " + (Ref(C,-LastPatBarLong) + (round(DDL)*ticdiv)) + " " + round(DDL) + "\n" +
"Exit " + (Ref(C,-LastPatBarLong) + (round(BTExitLong)*ticdiv)) + " " + round(BTExitLong) + "\n" +
"Peak " + (Ref(C,-LastPatBarLong) + (round(PeakLong)*ticdiv)) + " " + round(PeakLong) + "\n");

// BackTest Short

LastPatShort= ShortPattern;
LastPatBarShort= BarsSince(LastPatShort);
DDS= IIf((((Ref(C,-LastPatBarShort)-HHV(H,LastPatBarShort))))/ticdiv>=0,0,(((Ref(C,-LastPatBarShort)-HHV(H,LastPatBarShort))))/ticdiv);
BTExitShort= (((Ref(C,-LastPatBarShort)-C)))/ticdiv;
PeakShort= IIf((((Ref(C,-LastPatBarShort)-LLV(L,LastPatBarShort))))/ticdiv<=0,0,(((Ref(C,-LastPatBarShort)-LLV(L,LastPatBarShort))))/ticdiv);
StopShort1= (Ref(H,-LastPatBarShort) + (Stopval*ticdiv) + (spread*ticdiv)) - Ref(C,-LastPatBarShort);
StopShort= (((StopShort1)))/ticdiv;
BackTestShortTitle= WriteIf(Cover1,EncodeColor(colorRed) + "\n" +
"Stop " + (Ref(C,-LastPatBarShort) + (round(stopshort)*ticdiv)) + " " + round(stopshort) + "\n" +
"DD " + (Ref(C,-LastPatBarShort) + abs(round(DDS)*ticdiv)) + " " + round(DDS) + "\n" +
"Exit " + (Ref(C,-LastPatBarShort) - (round(BTExitShort)*ticdiv)) + " " + round(BTExitShort) + "\n" +
"Peak " + (Ref(C,-LastPatBarShort) - (round(PeakShort)*ticdiv)) + " " + round(PeakShort) + "\n",EncodeColor(colorRed)+ "\n" +
"Stop " + (Ref(C,-LastPatBarShort) + (round(stopshort)*ticdiv)) + " " + round(stopshort) + "\n" +
"DD " + (Ref(C,-LastPatBarShort) + abs(round(DDS)*ticdiv)) + " " + round(DDS) + "\n" +
"Exit " + (Ref(C,-LastPatBarShort) - (round(BTExitShort)*ticdiv)) + " " + round(BTExitShort) + "\n" +
"Peak " + (Ref(C,-LastPatBarShort) - (round(PeakShort)*ticdiv)) + " " + round(PeakShort) + "\n");

// Backtest title

BackTestCode= ParamToggle("Display Stop,DD,Peak,Exit stats","No|Yes",0);
BackTestTitle= WriteIf((bars_sellL>0 OR Sell1) AND BackTestCode==1,BackTestLongTitle ,WriteIf((bars_sellS>0 OR Cover1 )AND BackTestCode==1,BackTestShortTitle ,""));

// Stop in

Longbar= L+rbint;
Shortbar= H-rbint;
sstoptitle=WriteIf(timercode==2, EncodeColor(colorBlue) + "\n" + "Stop In Long " + Longbar + EncodeColor(colorRed) + "\n" + "Stop In Short " + Shortbar + "\n","");

// Stop out

stopCode=ParamToggle("Display stop-out ","No|Yes",0);
StopLong1= C -(L - (stopval*ticdiv) - (spread*ticdiv));
stoplong1c=C-stoplong1;
stoplong= round(StopLong1/ticdiv);
StopShort1= (H + (stopval*ticdiv) + (spread*ticdiv)) - C;
stopshortc= C+StopShort1;
StopShort= round(StopShort1/ticdiv);
stoptitle= WriteIf(stopcode==1,EncodeColor(colorBlue) + "\n" + "Stop Out Long " + stoplong1c + " " +stoplong + "\n" +
EncodeColor(colorRed) + "Stop Out Short " + stopshortc + " " + stopshort + "\n","");

// Title

Title = "\n" + "" + EncodeColor(colorWhite) + Date() + "\n" + "\n" +
timetitle + "\n" + "\n" + Lastpricetitlehi + "\n" + Closecolor + C + "\n" +
Lastpricetitlelo + "\n" + CCIpointmovetitle + wptitle + HiDayTitle + LoDayTitle + RangeTitle1 + BackTestTitle + Signaltitle + sstoptitle + stoptitle;
_SECTION_END();

MACD and Histogram with Good Understanding afl for amibroker

MACD and Histogram with Good Understanding afl for amibroker



//asfatul.alam@yahoo.com

 _SECTION_BEGIN("MACDval");
r1 = Param( "Fast avg", 12, 2, 200, 1 );
r2 = Param( "Slow avg", 26, 2, 200, 1 );
r3 = Param( "Signal avg", 9, 2, 200, 1 );

dynamic_color = IIf( MACD() > 0, colorGreen, colorRed );
Plot( MACD(), "MACD(12,26)", dynamic_color, styleHistogram | styleThick );

_SECTION_BEGIN("SIGNALval");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1, 10 );
Plot( EMA( MACD(12,26),9 ),"signal 9",colorYellow,styleHistogram |styleThick, ParamStyle("Style") );


MACDval = MACD(12,26);
EMAval = EMA(Close,9);
Signalval = Cross(EMAval,MACDval);

Buy = C > EMA(Close,200) AND Ref(MACDval,-1) < MACDval AND MACDval < 0;

Sell= Signalval;

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

Wednesday 4 March 2015

Vier Box for Amibroker (AFL)

Click a star to give your rating!
It has been observed that most of the technical anlysts are bogged down with series of indicators and hardly have time to trade. I call it “complexomenia” with “analysis & paralysis” symptom. Answer to it is viered box which gives pictoral presentatin about market direction, trend strength aon a continues basis and free us for undertaking actual trade.
Here is a screenshot of how the indicator looks:



/*
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.

*/

//bikin fungsi start warna box



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 ) //section vierbox by DF hanya akan ditampilkan kalau 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;
    }

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

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

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

    //buat plot box paling kanan

    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


_SECTION_END();

Market Profile - V1.71 for Amibroker (AFL)

Market Profile - V1.71 for Amibroker (AFL)






_N(FileName    = "Market Profile 1.71");
_N(VAP_Version = "1.71"); 

VMP_Control    = 0;   // Controls whether parameters are local or controlled from calling program
//
VMPperiods     = 0;   // Number of block of data (weeks, months etc.)
VMPDispPeriod  = "";  // Used in title
VMPNumSteps    = 150; // Number of price steps for entire range
VMPPeriod_High = 0;   // High price for a specific data block (period)
VMPPeriod_Low  = 0;   // Low price for a specific data block (period)
VMPStartBar    = 0;   // First bar in a data block
VMPEndBar      = 0;   // Last  bar in a data block
VMPNumdays     = 0;   // Number of bars in a data block
VMPPrice_Step  = 0;   // Price increment per volume bucket
VMPMin_Price   = 0;   // Min Price for visible range - not needed?? also associated code
VMPMax_Price   = 0;   // Max Price for visible range - not needed??
//
//
VMP_Group_PeakVolume   = 0; 
VMPDisplay_Block      = "";
VMPVol_Error          = "";
//
// Create root for dynamic variables
VMP_GroupPeakVol  = "";
VMP_BlockStartBar = "";
VMP_Blockvol      = "";
VMP_BlockVol1     = "";
VMP_BlockVol2     = "";        
VMP_BlockPeakVol  = "";
VMP_NumDays       = "";
VMP_MinStep       = "";
VMP_MaxStep       = "";
VMP_BlockHigh     = "";
VMP_BlockLow      = "";


//Compute Data Interval
//Variables: EOD, Weekly, Monthly, RT, DateStamp, MDYear, TimeStamp
EOD      = IIf(Interval() > 80000 AND Interval() < 100000,1,0);
Weekly   = IIf(Interval() > 100000 AND Interval() < 1000000,1,0);
Monthly  = IIf(Interval() > 2000000,1,0);
RT       = IIf(Interval() < 23401,1,0);

//Compute Date
Y1  = Year();
M1  = Month();
D1  = Day();

_N(DateStamp  = WriteVal(M1,1.0) + "/" + WriteVal(D1,1.0) + "/" + WriteVal(Y1,1.0));
_N(DateStamp2 = WriteVal(M1,1.0) + "-" + WriteVal(D1,1.0) + "-" + WriteVal(Y1,1.0));
//Compute Time
Hr  = Hour();
Mn  = Minute();
Sc  = Second();

_N(TimeStamp = WriteVal(Hr,1.0) + ":" + WriteIf(Mn<10,"0","") + WriteVal(Mn,1.0)
               + ":" + WriteIf(Sc<10,"0","") + WriteVal(Sc,1.0)
                 + WriteIf(Hr<12,"am","pm"));

//  ****************************************************************************

if (RT==0)
{
VMP_TimeFrame   = Param("1=Q, 2=M, 3=W",2,1,3,1);
}
else
{
VMP_TimeFrame   = Param("4=Day, 5=Int",4,4,4,1); 
VMP_Mini_Period = Param("Mini Period",60,20,120,10);
}

VMP_Scaling     = Param("Scaled=0,  Full=1",1,0,1,1);
VMP_Periods     = Param("Num Periods",0,0,15,1);
VMP_Vol_Plot    = Param("Vol_Plot",1,0,1,1);
Debug_          = Param("Debug",1,0,1,1);
//
VMP_Stat        = Status("action");
Debug           = Debug_ AND VMP_Stat ==1;
//
//
//Amibroker Status

//Preferences set to mark time at "06:30" and "13:10"
//Time stamp must be for start of bar
VMP_StartTime   = 63000;
VMP_EndTime     = 131000;
Minutes_perday  = 405;
//
bar_Index      = BarIndex();
Lastbar_Index  = BarCount-1;
LastBar_Number = LastValue(BarIndex());

//
//
//
//
//   ==============================       Start Functions        ================================
//Function Definitions
//
//   ========================   Start Function ComputeDataBlockParms   ==========================
//
//
function VerifyVolume()
{
// Verify that volume is available
Vol_Test   = IIf(LastValue(Sum(Volume,10)),1,0);

return Vol_Test;
}
//
//
function UpdateDynamicVars(m)
{
VMP_GroupPeakVol  = "VMP:GroupPeakVol";
VMP_BlockStartBar = "VMP:BlockStartBar_"     + NumToStr(m,1.0);
VMP_Blockvol      = "VMP:Blockvol_"          + NumToStr(m,1.0);
VMP_BlockVol1     = "VMP:BlockVol1_"         + NumToStr(m,1.0);
VMP_BlockVol2     = "VMP:BlockVol2_"         + NumToStr(m,1.0);
VMP_BlockPeakVol  = "VMP:BlockPeakVol_"      + NumToStr(m,1.0);
VMP_NumDays       = "VMP:NumDays_"           + NumToStr(m,1.0);
VMP_MinStep       = "VMP:MinStep_"           + NumToStr(m,1.0);
VMP_MaxStep       = "VMP:MaxStep_"           + NumToStr(m,1.0);
VMP_BlockHigh     = "VMP:BlockHigh_"         + NumToStr(m,1.0);
VMP_BlockLow      = "VMP:BlockLow_"          + NumToStr(m,1.0);
}
//
//
function ComputeDataBlockParms(j,Time_Block)
{
VMPNumdays          = LastValue(ValueWhen(Time_Block==2 OR Time_Block==3,BarsSince(Time_Block==1 OR Time_Block==3),j)) +1;
VMPStartBar         = LastValue(ValueWhen(Time_Block==1 OR Time_Block==3,Bar_Index,j));
//
VMPEndBar           = VMPStartBar + VMPNumdays-1;  
//
VMPPeriod_High      = LastValue(Ref(HHV(High,VMPNumdays),-(LastBar_Number - VMPEndBar))); 
VMPPeriod_Low       = LastValue(Ref(LLV(Low,VMPNumdays),-(LastBar_Number - VMPEndBar)));
//
if (VMPEndBar > LastBar_Number)
_TRACE("VMP171-DBP-0 - End Bar " + VMPEndBar + "  Last Bar " + LastBar_Number);

if (Debug==1)
{
_TRACE("VMP171-DBP-1 - j " + j + "  StartBar " + VMPStartBar + "  Numdays " + VMPNumdays + "  EndBar " + VMPEndBar
       + "  PHigh " + VMPPeriod_High + "  PLow " + VMPPeriod_Low);
}
}
//
//
//
//   ============================  end function ComputeDataBlocks   =============================
//
//
//   =================================  start function FindFirstBar    ================================
//
//Compute number of bar on screen
function FindFirstBar(TimeFrame)
{
Max_price_ = Min_price_ = Bars = 0;
BarsperInterval = 0;
//
if (VMP_Stat ==1)  
{
//

    if (TimeFrame ==5)
        {
        Bars        = LastValue(BarsSince(TimeNum()==VMP_StartTime)) + 1;
        }
    else
        {
    FirstBar       = LastBar_Number  - Status ( "firstvisiblebar") - bar_index[0];   // result is in array index domain (not barindex).
    LastBar        = LastBar_Number  - Status ( "lastvisiblebar")  - bar_index[0];
    Bars           = FirstBar - LastBar;
    Bars           = LastBar_Number - Status ( "firstvisiblebar") - bar_index[0];  // original
_TRACE("VMP171-FFB - FirstBar " + FirstBar + " LastBar " + LastBar + " Bars " + Bars + "  FVBar " + Status ( "firstvisiblebar") + "  BarCount " + BarCount);
        }
//
//    SetBarsRequired(Bars,0);
//
// Compute max number of blocks possible with number of bars available

    Max_price_      = LastValue(HHV(High,Bars));   // original
    Min_price_      = LastValue(LLV(Low,Bars));
_TRACE("VMP171-FFB-0 - min Price " + Min_price_ + "  max price " + Max_price_);
/*
    Max_price_      = LastValue(Ref(HHV(High,Bars),-LastBar));  
    Min_price_      = LastValue(Ref(LLV(Low,Bars),-LastBar));      
*/

if (debug)
_TRACE("VMP171-FFB-1 - Bars " + Bars); 
}
//
if (VMP_Periods ==0)
{
//if VMP_Periods is set to zero, compute periods dynimically
switch(TimeFrame)
{

case 1: VMP_Periods = int(Bars / 66);  break;                  // Quarter
case 2: VMP_Periods = int(Bars / 21);  break;                  // Month
case 3: VMP_Periods = int(Bars /  5);  break;                  // Week
// Below using ceil() instead in int() allows an extra bar making it possible for 60 and 120 min bars to work properly
case 4: BarsperInterval = ceil(Minutes_perday * 60 / Interval(0));       
         VMP_Periods     = ceil(Bars / BarsperInterval);  break;     // Day

//case 5: BarsperInterval = int(VMP_Mini_Period * 60 / Interval(0));
    //     VMP_Periods     = int(Bars / BarsperInterval) +0;  break;     // Intraday


} // end switch
} // end VMP_Periods ==0
/*
else xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
{
//Insure that number of periods specified are possible within the available bars. xxxxxxxxxxxxxx
switch(TimeFrame)
{
case 1: VMP_Periods = int(Bars / 66) +0;  break;                  // Quarter

}
}
*/

//


//
//
Price_Range     = Max_Price_ - Min_Price_;
//
//These 3 variables are used later on
VMPPrice_Step   = Price_Range / VMPNumSteps;
//Offset Max and Min Prices to avoid problems when Max_price = High ...etc
VMPMax_Price    = Max_Price_ + (0.01 * Price_Range);
VMPMin_Price    = Min_Price_ - (0.01 * Price_Range);
//

if (debug)
{
_TRACE("VMP171-FFB-2 - FindFirst  - Bars " + Bars + " Periods " +  VMP_Periods + " Min " + Min_Price_ + " Max " + Max_Price_);
_TRACE("VMP171-FFB-3 - PriceRange " + Price_Range + " NumSteps " + VMPNumSteps + " PriceStep " + VMPPrice_Step);
}
return Bars;
} // end function FindFirstBar
//

//    ===================================   end FindFirstBar   ==================================
//
//   ========================   Start Function Compute_RT_Intraday_1   ==========================
//
//

function Compute_RT_Intraday()
{

LB = SB = 0;
Bars_perblock = 0;
//Define function parameters
//Compute following variable for future use
//
//Items below are applicable for entire day. Need to be processed only once per day (m==1)
//
VMPDispPeriod       = "Intraday";
VMPDisplay_Block    = "Time Block " + NumToStr(VMP_Mini_Period,1.0) + " Minutes";
//
//
//Find bars on screen and copmute screen parms
//FirstBar  = FindFirstBar(VMP_TimeFrame);       // xxxxxxxxxxxxxxxxxxxxxxxxxxxx
//
//Find number of bars since start of day
//Computed for real time
Bars_past        = LastValue(BarsSince(TimeNum()==VMP_StartTime)) + 1; 
_TRACE("BarsPast - Bars " + Bars_Past);
//SetBarsRequired(Bars_Past + 20,0);  // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//Compute number of timeblocks as defined in "minitimes"
timeBlocks_1     = int(LastValue(Bars_past *Interval() / 60 / VMP_Mini_Period)); // completed timeblocks
timeBlocks_2     = LastValue(Bars_past *Interval() / 60 / VMP_Mini_Period);      // completed timeblocks + one in progress
//

//Total number of timeblocks
if (TimeBlocks_1 == TimeBlocks_2)
{
//All time blocks are completed (on last bar of block)
TimeBlocks = TimeBlocks_1;
}
else
{
//Time blocks completed plus in progress
TimeBlocks = TimeBlocks_1+1;
}

//

VMPPeriods          = Timeblocks;
//
Bars_PerBlock    = VMP_Mini_Period * 60 / Interval();  


//
//
//Define starting bar for day
Start_bar        = LastValue(ValueWhen(TimeNum()==VMP_StartTime,Bar_Index,1));
_TRACE("BarsPast - Start Bar " + Start_Bar + " Last bar " + LastBar_Number);
//    
//
//Mark array with 1=Start, 2=end of TimeBlock


if (debug==1)
{
_TRACE("VMP171-RTI-1 - Initial Vars - minitimes " + VMP_Mini_Period + " TimeNum " + TimeNum() + " STime " + VMP_StartTime
                + "  Bars Past " + Bars_Past);
_TRACE("VMP171-RTI-2 - BarsPast " + Bars_Past);  // // Total bars current day
_TRACE("VMP171-RTI-3 - TB1 " + TimeBlocks_1 + " TB2 " + TimeBlocks_2 + "  T Blocks " + TimeBlocks );
}
//
//
//
//Find starting and ending bars for each time block - Loop
x=0;
do
{
if (debug==1)
{
_TRACE("VMP171-RTI-4A - Status " + VMP_Stat /*+ "  Trade_Period " + Trade_Period*/ + "  x= " + x + " TB " + Timeblocks);
}
//Last time block
TB = TimeBlocks-1; 
if (x==TB) 
{
//if there is only one timeblock, then block may not be complete. last bar is last bar of data
SB = Start_Bar + (x*(Bars_PerBlock)) - Bar_Index[0];
LB = LastBar_Number - Bar_Index[0];
//
if (debug==1)
{
_TRACE("VMP171-RTI-4B - TB " + TB + "  SB " + SB + "  LB " + LB);
}
} // end x==TB
else
{
//Data block is complete
SB = Start_Bar + (x*(Bars_PerBlock)) - Bar_Index[0];
LB = Start_Bar + ((x+1)*(Bars_PerBlock)) - 1 - Bar_Index[0];

//
if (debug==1)
{
_TRACE("VMP171-RTI-4C - TB " + TB + "  SB " + SB + "  LB " + LB);
}
} // end if x==TB
//
//if only one bar exists in a new timeblock (SB==LB), mark it as starting bar.
if (SB==LB)
{
//First bar of time block
Time_Block[SB] = 1;
//
if (debug==1)
{
_TRACE("VMP171-RTI-4D - TB " + TB + "  SB " + SB + "  LB " + LB + " SB Mark " + Time_Block[SB] + "  LB Mark " + Time_Block[LB]);
}
} // end SB==LB
else
{
//Mark starting bar as "1" and ending bar as "2"
Time_Block[SB] = 1;
Time_Block[LB] = 2;
//

//
if (debug==1)
{
_TRACE("VMP171-RTI-4E - TB " + TB + "  SB " + SB + "  LB " + LB + " SB Mark " + Time_Block[SB] + "  LB Mark " + Time_Block[LB]);
}
} // end if (SB==LB)

//
if (debug==1)
{
_TRACE("VMP171-RTI-5A - Status " + VMP_Stat /*+ "  Trade_Period " + Trade_Period*/ + "  x= " + x + "  SB= " + SB + "  LB= " + LB
        + "  Last Bar# " + LastBar_Number + "  #Bars  " + Bars_PerBlock);
_TRACE("VMP171-RTI-5B - SB Mark " + Time_Block[SB] + "  LB Mark " + Time_Block[LB]);
}
//
x++;

} while (x < TimeBlocks AND x <30);
//
Time_Block[LB]       = IIf(Time_Block[LB]==1,3,2);  // Modify last bar if ==1
// Entire day has been marked for each intraday segment
//
return Time_Block;
} // end function RT_Intraday
//

//
//   ===============================  end function RT_Intraday_1  =================================
//
//   =============================  start function Compute_RT_Daily  ==============================
//


//Time block = 1 full day
function Compute_RT_Daily()
{
//Items below are applicable for entire day. Need to be processed only once per day (m==1)
//Should be placed in static variables
//
//m=0;                        
TimeBlocks          = VMP_Periods;
//
//Daily
VMPDispPeriod       = "Day";
VMPPeriods          = VMP_Periods;
VMPDisplay_Block    = "Time Block 1 Day";
//
// Specify number of minutes based on issue (Futures =400, Stocks=390 and change start stop times)
Bars_PerBlock    = (Minutes_perday * 60 / Interval(0)) +1; // for debug only
//

//
//Start_bar        = ValueWhen(TimeNum()==VMP_StartTime,Bar_Index,1);

//
//Mark Starting and ending bars of each timeblock.
if (VMPDispPeriod =="DayNight")  // Day and Night
{
//Need debug
Time_Block       = IIf(TimeNum() >=Start_Time AND Ref(TimeNum(),-1) <Start_Time,1,
                        IIf(TimeNum() <=End_Time AND Ref(TimeNum(),1) >End_Time,2,      // same as TimeNum()==End_Time???
                        IIf(LastBar_Number==Bar_Index AND TimeNum() < End_Time,2,0)));
}
else // Regular trading hours only
{
Time_Block          = IIf(TimeNum() >=VMP_StartTime AND DateNum() > Ref(DateNum(),-1),1,
                        IIf((TimeNum() <=VMP_EndTime AND DateNum() < Ref(DateNum(),1)) OR TimeNum() == VMP_EndTime,2,
                        IIf(LastBar_Number==Bar_Index AND TimeNum() < VMP_EndTime,2,0)));

}
Time_Block[Lastbar_Index]       = IIf(Time_Block[Lastbar_Index]==1,3,2);  // Modify last bar if ==1       
//
//
if (Debug ==1)
{
_TRACE("VMP171-RTD-1 - Inital Vars - Trade Period " + Bars_PerBlock + " T Blocks " + TimeBlocks     + "  B_Block " + Bars_PerBlock);
}

return Time_Block;
} // end function RT_Daily
//

//
//   =============================  end function Compute_RT_Daily  ==============================
//
//   =============================  start function Compute_EOD_Weekly  ==============================
Time_Block = 0;
function Compute_EOD_Weekly() //Weekly  
{
//
//
//Weekly
VMPDisplay_Block    = "Time Block 1 Week";
VMPDispPeriod       = "Week";
VMPPeriods          = VMP_Periods; 

//
/*
for (i=BarCount-10; i<BarCount; i++)
{
//
if (debug)
{
_TRACE("VMP171-TB-Week - Index " + BarCount);
}
//
*/
Time_Block       = IIf(DayOfWeek() < Ref(DayOfWeek(),-1),1,                                       // first day of week
                        IIf(DayOfWeek() > Ref(DayOfWeek(),1),2,0));                                  // last day of week

Time_Block[Lastbar_Index]       = IIf(Time_Block[Lastbar_Index]==1,3,2);  // Modify last bar if ==1   
//
//
LBI = BarCount-1;                                      
//
/*
for (i=BarCount-10; i<BarCount; i++)
{
_TRACE("VMP171-TB-Week - Periods " + VMPPeriods + " Bar_Index " + i + " Time_Block " + Time_Block[i] + " LBI " + BarCount);
}
//

} // end Barcount loop
*/


return Time_Block;
} // end function EOD_Weekly 
//

//
//   =============================   end  function Compute_EOD_Weekly   ==============================
//
//   =============================  start function Compute_EOD_Monthly  ==============================
//

function Compute_EOD_Monthly() 
{
//Export variables: Numdays, Period_High, Period_Low
//
if (Debug ==1)

_TRACE("VAP53-EOD-M1 - Enter Monthly function");
}
//


VMPDisplay_Block    = "Time Block 1 Month";
VMPPeriods          = VMP_Periods;
VMPDispPeriod       = "Month";

//
//Problem area with last bar being 1st bar of timeblock
Time_Block       = IIf(Day() < Ref(Day(),-1),1,                                       // first day of month
                        IIf(Day() > Ref(Day(),1)
                        OR (Day() > Ref(Day(),-1) AND Bar_Index==LastBar_Number),2,0));  // last day of month

Time_Block[LastBar_Index] = IIf(Time_Block[LastBar_Index]==1,3,2);  // Modify last bar if ==1

//
if (Debug ==1)
{
for (i=LastBar_Number-Bar_Index[0]-10; i<=LastBar_Number-Bar_Index[0]; i++)
{
//_TRACE("VMP171-TB-Month - Last Number "  + LastBar_Number + " Last Index " + LastBar_Index + "  B0 " + Bar_Index[0] + " BarCount " + BarCount);
//_TRACE("VMP171-TB-Month - Periods " + VMPPeriods + " Bar_Index " + i + " Time_Block " + Time_Block[i] + " LBI " + LastBar_Number);
}
}

return Time_Block;
} // end function EOD_Monthly
//
//
//   =============================  end  function Compute_EOD_Monthly  ==============================
//
function Compute_EOD_Quarterly() 
{
//Export variables: Numdays, Period_High, Period_Low
//
if (Debug ==1)

_TRACE("VAP170-EOD-Q1 - Enter Quarterly function");
}
//


VMPDisplay_Block    = "Time Block 1 Quarter";
VMPPeriods          = VMP_Periods;
VMPDispPeriod       = "Quarter";

//
//Problem area with last bar being 1st bar of timeblock
Time_Block       = IIf((Day() < Ref(Day(),-1) AND Month()==1) OR (Day() < Ref(Day(),-1) AND Month()==4)
                            OR (Day() < Ref(Day(),-1) AND Month()==7) OR (Day() < Ref(Day(),-1) AND Month()==10),1,                                      // first day of quarter
                        IIf((Day() > Ref(Day(),1) AND Month()==3) OR (Day() > Ref(Day(),1) AND Month()==6)
                            OR (Day() > Ref(Day(),1) AND Month()==9) OR (Day() > Ref(Day(),1) AND Month()==12)
                        OR (Day() > Ref(Day(),-1) AND Bar_Index==LastBar_Number),2,0));      // last day of quarter

Time_Block[LastBar_Index] = IIf(Time_Block[LastBar_Index]==1,3,2);  // Modify last bar if ==1

//
if (Debug ==1)
{
for (i=LastBar_Number-Bar_Index[0]-10; i<=LastBar_Number-Bar_Index[0]; i++)
{
//_TRACE("VMP171-TB-Month - Last Number "  + LastBar_Number + " Last Index " + LastBar_Index + "  B0 " + Bar_Index[0] + " BarCount " + BarCount);
//_TRACE("VMP171-TB-Month - Periods " + VMPPeriods + " Bar_Index " + i + " Time_Block " + Time_Block[i] + " LBI " + LastBar_Number);
}
}

return Time_Block;
} // end function EOD_Quarterly
//
//
//   =====================================  end function Quarterly  ===================================
//
//
//
//
//   =================================  end  function  FindFirstBar    ================================
//
//   =================================  start function Data Collect    ================================
//
function DataCollect(TimeFrame)
{
//
//
FirstBar  = FindFirstBar(TimeFrame);
//Vars defined: VMP_Periods, Price_Range, VMPPrice_Step, VMPMax_Price, VMPMin_Price.
//
if (Debug==1)
{
_TRACE("VMP171-DC-01 - Status " + VMP_Stat + "  Interval " + Interval() / 60 + "min" + "  T Period #" + TimeFrame);    
_TRACE("VMP171-DC-02 - Visible High / Low - Max_Price " + WriteVal(VMPMax_Price,1.2) + "  Min_Price " + WriteVal(VMPMin_Price,1.2)
                + " F Bar " + Firstbar + " LastBar " + LastBar_Number);

}

GetPerformanceCounter( bReset = True );
//
//Variables

//
//Compute Time_Block array - Mark start and end date bars
//Includes all time blocks
//Vars defined: VMPPeriods, Time_Block.  - VMP_Periods dynamically defined above is assigned to VMPPeriods
switch(TimeFrame)
{
case 1: Time_Block = Compute_EOD_Quarterly();  break;
case 2: Time_Block = Compute_EOD_Monthly();    break;
case 3: Time_Block = Compute_EOD_Weekly();     break;
case 4: Time_Block = Compute_RT_Daily();       break;
case 5: Time_Block = Compute_RT_Intraday();    break;
}
//
//create data sets (set is a month, week, day etc)
//m represents the period number
m=0;
//
do
{
//loop on period - month / week
m++;
 
//Define time frame period
//Get StartBar, EndBar and Numdays
//Process Block Parms
j = VMPPeriods - m + 1;

//Variables Returned below as Globals
//VMPNumdays, VMPStartBar, VMPEndBar, VMPPeriod_High, VMPPeriod_Low        
ComputeDataBlockParms(j,Time_Block);
//

//
Block_MaxStep   = VMPNumSteps - int((VMPMax_Price - VMPPeriod_High) / VMPPrice_Step);
Block_MinStep   = int((VMPPeriod_Low - VMPMin_Price) / VMPPrice_Step);
//
if (Debug==1)
{
_TRACE("VMP171-DC-031 - j " + j + "  Status " + VMP_Stat + " m " + m + "  Numdays " + VMPNumdays + " Start Bar " + VMPStartBar + " End Bar " + VMPEndBar);
           
_TRACE("VMP171-DC-032 - j " + j + " Block MinStep " + Block_MinStep + " Block MaxStep " + Block_MaxStep);
_TRACE("VMP171-DC-033 - MaxPrice " + VMPMax_Price + " PeriodHigh " + VMPPeriod_High + " Priceperstep " + VMPPrice_Step);
}
//    
//   
//LOOP THRU DAILY DATA
//Loop through each day of period
//need to estalish max vol for each segment, then scale appropriately for charting.
//Total Volume for period                  
//
//Variables for entire data block
Sum_Volume_d1 = LastValue(Ref(Sum(Volume,VMPNumdays),-((LastBar_Number - VMPEndBar))));  // Sum of daily volume for data block
Sum_Volume_d2 = 0;  // alternate to above
Block_MaxVol  = 0;  // max volume step for data block
//
//Variables for single bar only
Bar_Steps     = 0;  // Number of price steps
Bar_MaxStep   = 0;  // Highest number step
Bar_MinStep   = 0;  // Lowest number step
DayVolume     = 0;  // Total volume for bar
Bar_Volume    = 0;  // Total volume for bar - (alternate for above)
//
if (debug)
{
_TRACE("VMP171-DC-03A - VMPstartbar " + VMPstartbar + " VMPEndBar " +VMPEndBar);
}
//
//initialize dynamic variables to zero in order to keep correct values
//These variables will keep data for entire block. One variable for each step of each block
//Variables are the equivalent of an array in the form of Var[m,i]
//
mm = NumToStr(m,1.0);
for (i=1; i<=VMPNumSteps; i++) 

VMP_Vol    = "VMP_Vol_" + mm + "_" + NumToStr(i,1.0);   
VarSet(VMP_Vol,0);
}
//
//  
//
Block_Volume  = 0;
Peak_BlockVol = 0;
for (dd=VMPstartbar; dd<=VMPEndBar; dd++)   
{
if (debug)
_TRACE("VMP171-DC-04-0 - dd "  + dd + " BI0 " + Bar_Index[0] + " VMP_Start bar " + VMPstartbar);
//Calculate volume attributable to each step with price bar
Bar_Volume       = Volume[dd-Bar_Index[0]];   // Volume for the day
Bar_High         = High[dd-Bar_Index[0]];     
Bar_Low          = Low[dd-Bar_Index[0]];
//
Bar_MaxStep      = VMPNumSteps - int((VMPMax_Price - Bar_High) / VMPPrice_Step);  // Highest step number (fisrt step with no volume above bar)
Bar_MinStep      = int((Bar_Low - VMPMin_Price)  / VMPPrice_Step);                // Lowest  step number (fisrt step with no volume below bar)
Bar_Steps        = Bar_MaxStep - Bar_MinStep +1;
Vol_perstep      = Bar_Volume / Bar_Steps;                    
//
Sum_Volume_d2    = IIf(1,Sum_Volume_d2 + Volume[dd-Bar_Index[0]],0);              // Sum of daily volume for timeblock - compare value with d1
//
//
if (Debug==1)
{
_TRACE("VMP171-DC-04 - daily loop2 - Status " + VMP_Stat + " Start Bar " + VMPStartBar + "  dd= " + dd + " EndBar " + VMPEndBar + " BarCount " + LastBar_Number);
_TRACE("VMP171-DC-05 - daily loop2 - Status " + VMP_Stat + "  Bar High " + WriteVal(Bar_High,1.2) + "  Bar Low "
                                         + WriteVal(Bar_Low,1.2) + "  Bar Volume " + WriteVal(Bar_Volume/1000,1.0) + "K");
_TRACE("VMP171-DC-06 - daily loop2 - Status " + VMP_Stat + " Min Step " + Bar_MinStep + " max Step " + Bar_MaxStep + " Vol PerStep " + WriteVal(Vol_perstep,1.0) + "  Steps " + Bar_Steps);
}
//
//
//Distribute daily volume equally to all applicable price steps
Bar_Volume2  = 0;
Max_Volume   = 0;
for (Step=Bar_MinStep; Step<=Bar_MaxStep; Step++)
{
//Max_Group_Volume stores value of largest volume at price for ALL periods.
//Used to scale VMP relative to largest volume.
VMP_Vol      = "VMP_Vol_" + mm + "_" + NumToStr(Step,1.0);
VarSet(VMP_Vol,VarGet(VMP_Vol) + (Vol_perStep));                                                         // Volume per price step
//

Bar_Volume2         = IIf(1,Bar_Volume2+Vol_perStep,0);                                                 // Alternate to Volume[dd] *
Block_Volume        = IIf(1,Block_Volume+Vol_perStep,0);                                               // Volume for entire block

//

if (Debug==1) 
{
_TRACE("VMP171-DC-08 - Max Vol_d Summary - m " + m + " dd " + dd + "  Step " + Step + "  Volume " + WriteVal(VarGet(VMP_Vol)/1000,1.0) + "K"
            + "   Bar Vol-2 " + Bar_Volume2/1000 + "K");
}

} // end Step for loop
//

Peak_BlockVol        = IIf(Peak_BlockVol < VarGet(VMP_Vol),VarGet(VMP_Vol),Peak_BlockVol);                // Peak volume for block
VMP_Group_PeakVolume = IIf(VarGet(VMP_Vol) >VMP_Group_PeakVolume, VarGet(VMP_Vol),VMP_Group_PeakVolume);  // Peak volume for all groups
//
if (Debug==1)
{
_TRACE("VMP171-DC-09 - Day Volume_d Summary - m " + m + " Bar Volume " + Bar_Volume/1000 + "K  Bar Vol-2 " + Bar_Volume2/1000 + "K");
}
//
} // end dd   for loop
//
// Create Dynamic Variables for all parameters
//
UpdateDynamicVars(m);  // Set proper subscripts
//
VarSet(VMP_GroupPeakVol,VMP_Group_PeakVolume);                  // Peak volume step for all groups    - used for scaling chart
VarSet(VMP_BlockStartBar,VMPStartBar);                          // Block Start Bar
VarSet(VMP_BlockVol,Block_Volume);                              // Total Volume for data block        - used for diagnostic
VarSet(VMP_BlockVol1,Sum_Volume_d1);                            // Total Volume for data block        - used for diagnostic - alternate
VarSet(VMP_BlockVol2,Sum_Volume_d2);                            // Total Volume for data block        - used for diagnostic - alternate#2
VarSet(VMP_BlockPeakVol,Peak_BlockVol);                         // Peak volume for data block         - used for scaling chart
VarSet(VMP_NumDays,VMPNumDays);                                 // number of bars in data block      
VarSet(VMP_MinStep,Block_MinStep+1);                            // Smallest price Block step number
VarSet(VMP_MaxStep,Block_MaxStep);                              // Largest  price Block step number
VarSet(VMP_BlockHigh,VMPPeriod_High);                           // Highest price in block            
VarSet(VMP_BlockLow,VMPPeriod_Low);                             // Lowest price in block              - Compute UVA, LVA, POC
//
if (Debug==1)
{
_TRACE("VMP171-DC-10 - Block1 - m " + m + " Block Volume_d Summary - m " + " Numdays " + VMPNumdays + " Sumvol_d 1:2 " + Sum_Volume_d1/1000 + "K / " + Sum_Volume_d2/1000 + "K");
_TRACE("VMP171-DC-11 - Block2 - m " + m + " Dyn Vars: - Start Bar " + VarGet(VMP_BlockStartBar) + " Block Vol-1 " + VarGet(VMP_Blockvol)/1000
            + "K  Block Vol-2 " + VarGet(VMP_BlockVol1)/1000 + "K  Block Vol-3 " + VarGet(VMP_BlockVol2)/1000 + "K");
_TRACE("VMP171-DC-12 - Block3 - m " + m + " Block Vol " + Block_Volume/1000 +"K  Block MaxPeakVol " + VarGet(VMP_BlockPeakVol)/1000 + "K" + " Group Peak Vol " + VarGet(VMP_GroupPeakVol)/1000 + "K");
_TRACE("VMP171-DC-13 - Block4 - m " + m + " NumDays " + VarGet(VMP_NumDays) + " Min Step " + VarGet(VMP_MinStep) + " Max Step " + VarGet(VMP_MaxStep));
}
} while (m<VMPPeriods);
//

} // end function DataCollect
//   ========================================   end of data collection   =====================================
//
//   =======================================   start of data reconstruction   ================================
//

//Process Data reconstruction for Value area and POC values
function DataReconstruct()
{
//Analyze saved data for display.
//
FirstBar  = FindFirstBar(VMP_TimeFrame);
//Read data from prior section and reconstruct to show volume per price
//Process one data block per pass (n) 
n = 0;
do
{
n++;
nn = NumToStr(n,1.0);
//
UpdateDynamicVars(n);
//
/*
//These are redundant vars for diagnostics
VarGet(VMP_BlockVol1);                            // Total Volume for data block
VarGet(VMP_BlockVol2);                            // Total Volume for data block
    
*/
//
//
//Assign value to local variables to speed execution
//Scale variables for plotting
//
if (VMP_scaling ==0)
{
//Scaled as a group
SelVolume   = VarGet(VMP_GroupPeakVol)*1.4;

}
else 
{
//scale each period as 100%
SelVolume   = VarGet(VMP_BlockPeakVol) *1.4;
}
//
Scale_Factor = VarGet(VMP_NumDays);
//
Group_PeakValue   = VarGet(VMP_GroupPeakVol);     // Peak volume step for all groups    - used for scaling chart
Block_Numdays     = VarGet(VMP_NumDays);          // number of bars in data block
Block_PeakValue   = VarGet(VMP_BlockPeakVol);     // Peak volume for data block
Block_Volume      = VarGet(VMP_BlockVol);         // Total Volume for data block       
Block_MinStep     = VarGet(VMP_MinStep);          // Smallest price Block step number
Block_MaxStep     = VarGet(VMP_MaxStep);          // Largest  price Block step number  
Block_StartBar    = VarGet(VMP_BlockStartBar);    // Block Start Bar                   
Block_MaxValue    = VarGet(VMP_BlockHigh);        // Largest price Block Value          - Diagnostics only
Block_MinValue    = VarGet(VMP_BlockLow);         // Snallest price Block Value         - Diagnostics only
//
UVA_Var     = "UVA_" + nn;
LVA_Var     = "LVA_" + nn;
//
//Compute UVA, LVA levels
//Compute Value Area upper limit
//
//
if (Debug==1)
{
_TRACE("VMP171-DR-01  Days - n= " + n + "  Numdays " + VMPNumdays);

_TRACE("VMP171-DR-02 - Reconstruct - Status " + VMP_Stat + "  n " + n + "  PLow " + Block_MinValue + "  PHigh " + Block_MaxValue
        + "  PMax " + VMPMax_Price + " PMin " + VMPMin_Price);
_TRACE("VMP171-DR-03 - Reconstruct - Status " + VMP_Stat + "  MinStep " + Block_MinStep + "  MaxStep " + Block_MaxStep);
}
//
if (debug)
{
_TRACE("VMP171-DR-06 - Value Area - Max Step " + Block_MaxStep + " Min Step " + Block_MinStep
        + " Block Vol " + Block_Volume/1000 + "K  BPeak Value " + Block_PeakValue/1000 +"K  Group PeakVol " + Group_PeakValue/1000 + "K");
}
//
//Compute step number for POC - (Max Block Volume)
POC_Volume  = 0;
POC_StepNum = 0;
for (i=Block_MinStep-1; i<Block_MaxStep+1; i++)
{
Vol_i        = "VMP_Vol_" + nn + "_" + NumToStr(i,1.0);
VMP_Vol      = VarGet(Vol_i );
POC_StepNum  = IIf(VMP_Vol >POC_Volume,i,POC_StepNum);
POC_Volume   = IIf(VMP_Vol >POC_Volume,VMP_Vol,POC_Volume);

//_TRACE("VMP171-DR-07*** - i " + i +" Voli " + Vol_i + " VMP_Vol " + VMP_Vol + " POC Vol " + POC_Volume + " POC SNum " + POC_StepNum);
}
//
//Compute UVA/LVA. Value area volume should be 70% of toal Block Volume
//_TRACE("VMP171-DR-07** - POC Step " + POC_StepNum + " Min Step " + Block_MinStep + " Max Step " + Block_MaxStep);
Stepvalue    = POC_StepNum;
VA_Volume    = POC_Volume;
kk           = Stepvalue +1;
jj           = Stepvalue -1;
Loopcount    = 0;
do
{
Loopcount++;
Volk     = "VMP_Vol_" + nn + "_" + NumToStr(kk,1.0);
Volj     = "VMP_Vol_" + nn + "_" + NumToStr(jj,1.0);
VMP_Volk = VarGet(Volk);
VMP_Volj = VarGet(Volj);
//


VA_Volume    = IIf(VMP_Volk >=VMP_Volj,VA_Volume +VMP_Volk,VA_Volume);
VA_Volume    = IIf(VMP_Volk <= VMP_Volj,VA_Volume +VMP_Volj,VA_Volume);
//
//
//_TRACE("VMP171-DR-07*  - lcnt " + loopcount + " kk " + kk + " Max Step " + Block_MaxStep + " Min Step " + Block_MinStep + " jj " + jj + " VAvol " + VA_Volume
            //        + " kvol " + VMP_Volk + " jvol " + VMP_Volj + " BLvol " + Block_Volume);

if (VMP_Volk >=VMP_Volj AND kk <=Block_MaxStep) kk++;
if (VMP_Volk <= VMP_Volj AND jj >=Block_MinStep) jj--;

} while (VA_Volume < 0.7 * Block_Volume AND Loopcount <VMPNumSteps);
//
upvalstep = kk;
dnvalstep = jj;
//

//

UVA_Value = VMPMin_Price +(upvalstep*VMPPrice_Step);  // should be block min price + ...
//UVA_Value = Block_MinValue +(upvalstep*VMPPrice_Step);  // should be block min price + ...

VarSet(UVA_Var,UVA_Value);
//
LVA_Value = VMPMin_Price +(dnvalstep*VMPPrice_Step);
//LVA_Value = Block_MinValue +(dnvalstep*VMPPrice_Step);
VarSet(LVA_Var,LVA_Value);
//
//
//Find POC step number
Max_Volume = i_CPOC = i_PPOC = 0;
for (i=Block_MinStep; i<=Block_MaxStep+1; i++)
{
VMP_Vol    = "VMP_Vol_" + nn + "_" + NumToStr(i,1.0);
if (VarGet(VMP_Vol) > Max_Volume)
{
Max_Volume = VarGet(VMP_Vol);
//
if (n==VMPPeriods-1)  i_PPOC     = i;
if (n==VMPPeriods)    i_CPOC     = i;
//
if (debug ==1)
{
_TRACE("VMP171-DR-09 - n " + n + " Min " + Block_MinStep + " Max " + Block_MaxStep
        + " Block_PeakValuePval " + Block_PeakValue/1000 + "K  Max Val " + Max_Volume/1000 + "K  i_PPOC " + i_PPOC + " i_CPOC " + i_CPOC);
}
} // end VarGet()
}
//
//
if (n==VMPPeriods-1)
{
StaticVarSet("VMP171_RT_P_UVA",VarGet(UVA_Var));
//
StaticVarSet("VMP171_RT_P_LVA",VarGet(LVA_Var));
}
//
if (n==VMPPeriods)
{
StaticVarSet("VMP171_RT_C_UVA",VarGet(UVA_Var));
//
StaticVarSet("VMP171_RT_C_LVA",VarGet(LVA_Var));
}
//
P_POC_Value = C_POC_Value =0; //initialize
if (n==VMPPeriods-1)
{
P_POC_Value = VMPMin_Price+(i_PPOC*VMPPrice_Step);
//P_POC_Value = Block_MinValue+(i_PPOC*VMPPrice_Step);
StaticVarSet("VMP171_RT_P_POC",P_POC_Value);
}
if (n==VMPPeriods)
{
C_POC_Value = VMPMin_Price+(i_CPOC*VMPPrice_Step);
//C_POC_Value = Block_MinValue+(i_CPOC*VMPPrice_Step);
StaticVarSet("VMP171_RT_C_POC",C_POC_Value);
}
//
//
if (debug)
{
_TRACE("VMP171 - SVars-1 - n " + n + " UVA " + VarGet(UVA_Var) + " LVA " + VarGet(LVA_Var));
_TRACE("VMP171 - SVars-2 - n " + n + " UVA " + StaticVarGet("VMP171_RT_P_UVA") + " LVA " + StaticVarGet("VMP171_RT_P_LVA"));
//
_TRACE("VMP171 - SVars-3 - n " + n + " UVA " + VarGet(UVA_Var) + " LVA " + VarGet(LVA_Var));
_TRACE("VMP171 - SVars-4 - n " + n + " UVA " + StaticVarGet("VMP171_RT_C_UVA") + " LVA " + StaticVarGet("VMP171_RT_C_LVA"));
//
_TRACE("VMP171 - SVars-5 - n " + n + " P_POC " + P_POC_Value + " C_POC " + C_POC_Value);
_TRACE("VMP171 - SVars-6 - n " + n + " P_POC " + StaticVarGet("VMP171_RT_P_POC") + " C_POC " + StaticVarGet("VMP171_RT_C_POC"));
}
if (VMP_Stat==1)
{
//Compute lines to plot - UVA, LVA
for (i=Block_MinStep; i<=Block_MaxStep; i++)
{
//
//Compute Volume Lines
VMP_Vol     = "VMP_Vol_" + NumToStr(n,1.0) + "_" + NumToStr(i,1.0);  
x0          = Block_StartBar;
x1_         = Nz((VarGet(VMP_Vol) / LastValue(SelVolume) * (Scale_Factor))); 
xx1_        = IIf(x1_<1,0,x1_);
x1          = x0 + xx1_;
y0          = y1 = VMPMin_Price + (i*VMPPrice_Step);
//
if (Debug ==1)
{
_TRACE("VMP171-PL-01 - n " + n + " i " + i + "  x0 " + x0 + "  x1 " + x1 + "  y0 " + y0 + "  x1_ " + x1_);
_TRACE("VMP171-PL-02 - n " + n + "  Vol " + VarGet(VMP_Vol) + "  Numdays " + VMPNumdays + "  SelVol " + SelVolume);
_TRACE("VMP171-PL-02 - n " + n + "  Block Min Step " + Block_MinStep + "  Block_MaxStep " + Block_MaxStep);
}
//
Line_Vol    = LineArray(x0,y0,x1,y1,0,1);
//
//
if (x0 > LastBar_Number - FirstBar)                 // Needed to truncate plotting outside of chart
{
Plot(Line_Vol,"",colorOrange,styleLine|styleNoLabel);
}
//
} // end for Block_MinStep
//
//Compute and plot UVA, LVA lines
x0          = Block_startBar;
x1_UpVal    = x1_DnVal = x0 + Block_Numdays-1;
//
y0_UpVal    = y1_UpVal = UVA_Value;
y0_DnVal    = y1_DnVal = LVA_Value;
Line_UVA    = LineArray(x0,y0_UpVal,x1_UpVal,y1_UpVal,0,1);
Line_DVA    = LineArray(x0,y0_DnVal,x1_DnVal,y1_DnVal,0,1);
//
//Plot Start and end points
PlotShapes(IIf((Time_Block==1 OR Time_Block==3) AND Bar_Index>=Block_StartBar,shapeCircle,shapeNone),colorYellow,0,Open,0);
PlotShapes(IIf((Time_Block==2 OR Time_Block==3) AND Bar_Index>=Block_StartBar,shapeCircle,shapeNone),colorBlue,0,Close,0);
//Plot - UVA, LVA
Plot(Line_UVA,"",colorWhite,styleDots|styleThick|styleNoLabel);
Plot(Line_DVA,"",colorWhite,styleDots|styleThick|styleNoLabel);

//
//
//
}
//
} while (n < VMPPeriods);
//
//
//Plot prices
PlotOHLC(O,H,L,C,"",colorBlack,styleCandle);
//
if (Debug ==1)
{
_TRACE("VMP171 - =============================   end of data reconstruct   ================================");
}
} // end function Data Reconstruct

//
//
function Plot_POC_UVA_LVA() 
{
if (debug)
_TRACE("VMP171-UVA-LVA-01 - BarCount " + BarCount + " POC " + StaticVarGet("VMP171_RT_P_POC") + " UVA " + StaticVarGet("VMP171_RT_P_UVA") + " LVA " + StaticVarGet("VMP171_RT_P_LVA"));
//
//Plot current day Value lines and POCs
POC_Value = StaticVarGet("VMP171_RT_C_POC");
POC_Line  = LineArray(BarCount-5,POC_Value,BarCount-1,POC_Value,0,0);
Plot(POC_Line,"",colorRed,styleThick|styleDots|styleNoRescale,0,0,5);
UVA_Value = StaticVarGet("VMP171_RT_C_UVA");
UVA_Line = LineArray(BarCount-5,UVA_Value,BarCount-1,UVA_Value,0,0);
Plot(UVA_Line,"",colorYellow,styleThick|styleDots|styleNoRescale,0,0,5);
LVA_Value = StaticVarGet("VMP171_RT_C_LVA");
LVA_Line = LineArray(BarCount-5,LVA_Value,BarCount-1,LVA_Value,0,0);
Plot(LVA_Line,"",colorYellow,styleThick|styleDots|styleNoRescale,0,0,5);
//
if (debug)
_TRACE("VMP171 - UVA / LVA - Enter Section");
//Plot prior day Value lines and POCs
POC_Value = StaticVarGet("VMP171_RT_P_POC");
POC_Line  = LineArray(BarCount-7,POC_Value,BarCount-1,POC_Value,0,0);
Plot(POC_Line,"",colorBlue,styleThick|styleNoRescale,0,0,5);
UVA_Value = StaticVarGet("VMP171_RT_P_UVA");
UVA_Line = LineArray(BarCount-7,UVA_Value,BarCount-1,UVA_Value,0,0);
Plot(UVA_Line,"",colorWhite,styleThick|styleNoRescale,0,0,5);
LVA_Value = StaticVarGet("VMP171_RT_P_LVA");
LVA_Line = LineArray(BarCount-7,LVA_Value,BarCount-1,LVA_Value,0,0);
Plot(LVA_Line,"",colorWhite,styleThick|styleNoRescale,0,0,5);
//

//
}
//
//   ==================================    end  Plot_POC_UVA_LVA()      =====================================
//
function PlotVolumeStats()
{
//
global PercVolume;
//Find number of bars since beginning of time block
Bars_inPeriod = BarsSince(Time_Block==1) +1;
//
if (VMP_Vol_Plot==1)
{
Vol_Accumulate = Sum(Volume,Bars_InPeriod);
Time_Num    = TimeNum();
PriorVolume = ValueWhen(TimeNum() ==Time_Num,Vol_Accumulate,2);   //   xxxxxxxxxxx  does not work accurately
PercVolume  = LastValue(Vol_Accumulate / PriorVolume) * 100;
//Plot Accumulated volume scale
FirstBar = FindFirstBar(VMP_TimeFrame);
VolAcc_High  = 5*LastValue(HHV(Vol_Accumulate,FirstBar));
Volume_High  = 5*LastValue(HHV(Volume,FirstBar));
//
//Mark time for prior period where volume equals current volume
Time_Num = LastValue(TimeNum());
BarNum   = ValueWhen(Time_Num ==TimeNum(),BarIndex(),2);
//Plot(IIf(BarNum==BarIndex(),1,0),"",colorYellow,styleArea|styleOwnScale,0,10);

//
if (RT AND Now(4) > LastValue(TimeNum()))
{
Plottime = 1;
Plot(Plottime,"",colorPaleGreen,styleArea|styleOwnScale|styleNoLabel,0,20);
}
Plot(Volume,"",colorWhite,styleDots|styleThick|styleNoLabel|styleNoRescale|styleOwnScale,0,Volume_High);
Plot(Vol_Accumulate,"",colorBlue,styleDots|styleThick|styleNoLabel|styleNoRescale|styleOwnScale,0,VolAcc_High);
}
} // end Plot Volume Stats
//
//   ==================================      end Volume Stats      =====================================
//   ==================================       PROGRAM START        =====================================
if (Debug==1)
{
_TRACE("VMP171-0  =============================  PROGRAM START =====================================");
_TRACE("VMP171-00 ===                                                                              ====");                           
}
//
//
VMPVol_Error  = "";
Vol_Test   = VerifyVolume();
//
// Add VMP_Control parameter for calls from other programs
//
//
//
if (Vol_Test ==1 AND VMP_Stat ==1)
{
//Proceed with program
//GetPerformanceCounter(True);
DataCollect(VMP_TimeFrame);
//GetPerformanceCounter( bReset = True );
//
//Time1 = GetPerformanceCounter(True);
DataReconstruct();
//
//
//Plot_Chart  = GetPerformanceCounter( bReset = False );
//
//Time2 = GetPerformanceCounter(True);
if (VMP_Stat ==1)
{
Plot_POC_UVA_LVA();

}
}

if (VMP_Vol_Plot==1)
{
PlotVolumeStats();
//
}
else
{
//There is no volume
VolumeTest = VerifyVolume();
if (VolumeTest ==0)
VMPVol_Error  = "ERROR - No Volume";
}
//
GraphXSpace = 10;
GraphZOrder=1;
//

_N(Time_Interval = Interval(2));
//
_N(Title = Name() + "  " + FileName + "    " + Time_Interval + "   " +  "   Period " + VMPDispPeriod + "    " + DateStamp + "  " + TimeStamp
            + "  High " + High + "  Low " + Low + " Close " + Close + "  Vol " + Volume + " bar# " + Bar_Index
            + "\nVersion: " + VAP_Version + "\n\nPrior Volume " + PercVolume
            + "\n\n" + EncodeColor(colorRed) + VMPVol_Error
            + "\n" + VMPDisplay_Block);