Simple Coding Help - No Promise.

Nehal_s143

Well-Known Member
hi friends
here is an afl called isfandi intraday trading system.

I like to modify the targets part of the code.

present code uses a percentage. These are not comfortable.

I need a ATR based targets.
can anybody modify the targets please!
thanks.

my long side targets are
//note Ltar1 =longtarget1
//ltar1 = Longentry + 2*ATR(20);
//ltar2 = Longentry + 4*ATR(20);
//ltar3 = Longentry + 6*ATR(20);

my short side targets are
//star1 = Shortentry - 2*ATR(20);
//star2 = Shortentry - 4*ATR(20);
//star3 = Shortentry - 6*ATR(20);

code is as below

HTML:
//isfandi trading system
//targets are too close  keep them far
_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, High %g, Low %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();

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

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

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

Buy = exitshort;
Sell = exitlong;
//Short = Sell;
//Cover = Buy;
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
//Short = ExRem(Short, Cover);
//Cover = ExRem(Cover, Short);
AlertIf( Buy, "", "Buy @ " + C, 1 );
AlertIf( Sell, "", "Sell @ " + C, 2 );

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



//to make changes below targets
//tar1 = entry + 2*ATR(20);
//tar2 = entry + 4*ATR(20);
//tar3 = entry + 6*ATR(20);





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

//tar1 = entry - (entry * 0.050);
//tar2 = entry - (entry * 0.112);
//tar3 = entry - (entry * 0.212);




//tar1 = entry -2*ATR(20);
//tar2 = entry -4*ATR(20);
//tar3 = entry - 6*ATR(20);


bars = i;
i = 0;
}
}
Offset = 20;
Clr = IIf(sig == "Buy", colorLime, colorRed);
ssl = IIf(bars == BarCount-1, s5d[BarCount-1], Ref(s5d, -1));
sl = ssl[BarCount-1];
//Plot(LineArray(bars-Offset, tar1, BarCount, tar1,1), "", Clr, styleLine|styleDots, Null, Null, Offset);

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

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

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

}

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

if ( sig =="Buy")
{
GfxSelectSolidBrush( colorBlue ); // this is the box background color
}
else
{
GfxSelectSolidBrush( colorRed ); // this is the box background color
}
pxHeight = Status( "pxchartheight" ) ;
xx = Status( "pxchartwidth");
Left = 1100;
width = 310;
x = 5;
x2 = 310;

y = pxHeight;

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

}
_SECTION_END();



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



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


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


_SECTION_BEGIN("Isfandi Technical Viewer");
//Plot(C,"",ParamColor( "Color", colorBlue ),ParamStyle("Style") );
//---- pivot points
GfxSetBkColor(colorBlue);
GfxSetTextColor( colorLime );
GfxSelectFont("Times New Roman", 20, 1,500, True );
GfxTextOut(" Intraday Trading System ", 20 , 40 );
_SECTION_END();


_SECTION_BEGIN(" Buy Sell Signal Confirm ");
BarColors =
IIf(BarsSince(Buy) < BarsSince(Sell)
AND BarsSince(Buy)!=0, colorGreen,
IIf(BarsSince(Sell) < BarsSince(Buy)
AND BarsSince(Sell)!=0, colorRed, colorBlue));
//Plot the Candlestick charts
Plot(C, "Close", BarColors, styleNoTitle | ParamStyle("Style") | GetPriceStyle() ) ;
_SECTION_END();

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

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


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

_SECTION_END();
try this

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

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

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

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

Buy = exitshort;
Sell = exitlong;
//Short = Sell;
//Cover = Buy;
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
//Short = ExRem(Short, Cover);
//Cover = ExRem(Cover, Short);
AlertIf( Buy, "", "Buy @ " + C, 1 );
AlertIf( Sell, "", "Sell @ " + C, 2 );

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



//to make changes below targets
tar1 = entry + 2*ATR(20);
tar2 = entry + 4*ATR(20);
tar3 = entry + 6*ATR(20);





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

//tar1 = entry - (entry * 0.050);
//tar2 = entry - (entry * 0.112);
//tar3 = entry - (entry * 0.212);




tar1 = entry -2*ATR(20);
tar2 = entry -4*ATR(20);
tar3 = entry - 6*ATR(20);


bars = i;
i = 0;
}
}
Offset = 20;
Clr = IIf(sig == "Buy", colorLime, colorRed);
ssl = IIf(bars == BarCount-1, s5d[BarCount-1], Ref(s5d, -1));
sl = ssl[BarCount-1];
//Plot(LineArray(bars-Offset, tar1, BarCount, tar1,1), "", Clr, styleLine|styleDots, Null, Null, Offset);

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

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

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

}

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

if ( sig =="Buy")
{
GfxSelectSolidBrush( colorBlue ); // this is the box background color
}
else
{
GfxSelectSolidBrush( colorRed ); // this is the box background color
}
pxHeight = Status( "pxchartheight" ) ;
xx = Status( "pxchartwidth");
Left = 1100;
width = 310;
x = 5;
x2 = 310;

y = pxHeight;

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

}
_SECTION_END();



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



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


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


_SECTION_BEGIN("Isfandi Technical Viewer");
//Plot(C,"",ParamColor( "Color", colorBlue ),ParamStyle("Style") );
//---- pivot points
GfxSetBkColor(colorBlue);
GfxSetTextColor( colorLime );
GfxSelectFont("Times New Roman", 20, 1,500, True );
GfxTextOut(" Intraday Trading System ", 20 , 40 );
_SECTION_END();


_SECTION_BEGIN(" Buy Sell Signal Confirm ");
BarColors =
IIf(BarsSince(Buy) < BarsSince(Sell)
AND BarsSince(Buy)!=0, colorGreen,
IIf(BarsSince(Sell) < BarsSince(Buy)
AND BarsSince(Sell)!=0, colorRed, colorBlue));
//Plot the Candlestick charts
Plot(C, "Close", BarColors, styleNoTitle | ParamStyle("Style") | GetPriceStyle() ) ;
_SECTION_END();

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

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


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

_SECTION_END();
 

Nehal_s143

Well-Known Member
But on some charts, it was just too cluttered. On one hand more lines at a certain level could point to its strength but it really is ugly. I was looking at if we could find a way to reduce the grid lines - there is no point in having 3 lines at 720.15, 720.05 & 719.80. It should actually be 720. I would continue my research on this and am open to ideas.

I have just started off on Amibroker and I chose that as I think afl is easier than mql4. Anyway, it doesnt hurt to have a look at the code. Please do share it - I could probably learn something from it.
TechQuant Sir, can we use Gann Swing in some way to get better Historical support and resistance level or turning points ?

Gann Swing AFL

_SECTION_BEGIN("Gann Swing Chart");
/* Gann Swing chart v4 */
/* Last modified 24 Feb 2001 */
/* AFL implementation by */
/* (C)2001 Tomasz Janeczko */
/* one and two - bar reversal version */

/* Change this to 1 for two-bar mode */
twobarmode = 0;

outsidebar = Outside();
insidebar = H <= Ref( H, -1 ) AND L >= Ref( L, -1 ); // built-in inside() works with < > instead of <= >=

upbar = H > Ref( H, -1 ) AND L >= Ref( L, -1 );
downbar = L < Ref( L, -1 ) AND H <= Ref( H, -1 );

upbar2 = upbar OR ( outsidebar AND Ref( downbar, 1 ) ) ;
downbar2 = downbar OR ( outsidebar AND Ref( upbar, 1 ) );

Poi = outsidebar AND Ref( insidebar, 1 );
Poo = outsidebar AND Ref( outsidebar, 1 );
Pooi = Poo AND Ref( insidebar, 2 );
Poio = Poi AND Ref( outsidebar, 2 );
Poii = Poi AND Ref( insidebar, 2 );
Pooo = Poo AND Ref( outsidebar, 2 );
Poooi = Pooo AND Ref( insidebar, 3 );
Pooio = Pooi AND Ref( outsidebar, 3 );
Poioo = Poio AND Ref( outsidebar, 3 );

upbar3 = upbar2 OR ( Poi AND Ref( downbar, 2 ) );
downbar3 = downbar2 OR ( Poi AND Ref( upbar, 2 ) );

upbar4 = upbar3 OR ( Poo AND Ref( upbar, 2 ) );
downbar4 = downbar3 OR ( Poo AND Ref( downbar, 2 ) );

upbar5 = upbar4 OR ( Pooi AND Ref( upbar, 3 ) );
downbar5 = downbar4 OR ( Pooi AND Ref( downbar, 3 ) );

upbar6 = upbar5 OR ( Poio AND Ref( upbar, 3 ) );
downbar6 = downbar5 OR ( Poio AND Ref( downbar, 3 ) );

upbar7 = upbar6 OR ( Poii AND Ref( downbar, 3 ) );
downbar7 = downbar6 OR ( Poii AND Ref( upbar, 3 ) );

upbar8 = upbar7 OR ( Pooo AND Ref( downbar, 3 ) );
downbar8 = downbar7 OR ( Pooo AND Ref( upbar, 3 ) );

upbar9 = upbar8 OR ( Poooi AND Ref( downbar, 4 ) );
downbar9 = downbar8 OR (Poooi AND Ref( upbar, 4 ) );

upbar10 = upbar9 OR ( Pooio AND Ref( downbar, 4 ) );
downbar10 = downbar9 OR ( Pooio AND Ref( upbar, 4 ) );

upbar11 = upbar10 OR ( Poioo AND Ref( downbar, 4 ) );
downbar11 = downbar10 OR ( Poioo AND Ref( upbar, 4 ) );

fupbar = upbar11;
fdownbar = downbar11;

// Two-bar mode handling
fupbar = IIf( twobarmode, fupbar AND Ref( fupbar, 1 ), fupbar );
fdownbar = IIf( twobarmode, fdownbar AND Ref( fdownbar, 1 ), fdownbar );

/* Barcount since most recent up and down swings */
Us = BarsSince( fupbar );
Ds = BarsSince( fdownbar ) ;

Sd1 =IIf( Us==0, 1, IIf( Ds==0, -1, 0) );

Sd2 = IIf( Sd1 == 1, IIf( Ref( BarsSince(Sd1==1), -1) > Ref( BarsSince( Sd1 == -1), -1), 1, 0),
IIf( Sd1 == -1, IIf( Ref( BarsSince(Sd1==1),-1) < Ref( BarsSince( Sd1 == -1),-1), -1, 0), 0 ) );

g0 = ValueWhen( Sd2, Sd2 ); /* sample and hold non-zero values */

/* shift back one bar, add one dummy swing at the end and shift forward */
/* to ensure proper handling of the last swing */
lastbar = Cum(1) == LastValue( Cum(1) );
swinglevel = IIf( g0 == -1, HighestSince( Sd2 == 1, H ), LowestSince( Sd2 == -1, L ) );
swinglevel = IIf( lastbar, IIf( g0 == -1, LowestSince( Sd2 == -1, L ), HighestSince( Sd2 == 1, H )), Ref( swinglevel, 1 ) );

/* Gann Swing chart drawn here */
Graph1 = Ref( ValueWhen( Ref( Sd2 != 0, 1 ) OR lastbar, swinglevel , 0 ), -1 );
Graph1Style = 512+1024;
GraphXSpace = 5;

/* Colourized price bars drawn here */
/* graph0 = close; */
/* graph0style = 128; */
/* barcolor = IIF( outsidebar, 1, IIF( downbar, 4, IIF( upbar, 5, 0 ) ) ); */
/* graph0barcolor = ValueWhen( barcolor != 0, barcolor ); */


_SECTION_END();
 

rvlv

Active Member
Hi Nehal


Error comes up at line shown below.

line 93 column 50 error 5
argument #4 has incorrect type-the function expects different argument type here


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

is it possible t fix the error please

thanks
 

amitrandive

Well-Known Member
Try this.

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

_SECTION_BEGIN("ZigZag");
P = Param("ZigZag_Percent",0.1,0.01,2,0.01);
ZigH  = Zig(H,P);		ZigL = Zig(L,P);
ZigHi = ZigH > Ref(ZigH,-1) AND ZigH > Ref(ZigH,1);		
ZigLo = ZigL < Ref(ZigL,-1) AND ZigL < Ref(ZigL,1);
j=0;	k=0;	PH[0] = PL[0] = 0;
for( i = 1; i < BarCount-1; i++ ) { 
 if (ZigLo[i])	{
	if (PL[k] > ZigL[i]) {
	 	PlotText("LL",i, L[i]-5, colorRed);
		LL[i] = ZigL[i];
	}
	else {
		PlotText("HL",i, L[i]-5, colorBlue);
		HL[i] = ZigL[i];
	}
	k = k + 1;		PL[k] = ZigL[i]; }
 if (ZigHi[i]) {
	if (PH[j] < ZigH[i]) {
	  	PlotText("HH", i, H[i]+5, colorBlue);
		HH[i] = ZigH[i];
	}
	else {
		PlotText("LH", i, H[i]+5, colorRed);
		LH[i] = ZigH[i];
	}
	j = j + 1;
	PH[j] = ZigH[i]; }
}
_SECTION_END();

Filter = ZigHi OR ZigLo;

AddColumn(High,"High");
AddColumn(Low,"Low");
AddColumn(HH,"HH");
AddColumn(LH,"LH");
AddColumn(HL,"HL");
AddColumn(LL,"LL");
TechQuant

Again thanks for the prompt reply :clap:
 
Dear All,

I mean scan should give the stocks which are crossing above 70 in 5 minutes and in 60 minutes SIMULTANEOUSLY.
Something like this:

Code:
//Set the base timeframe to the lower TF - in this case 5min.
RSI5 = RSI(14);

TimeFrameSet(inHourly);
RSI60 = RSI(14);
TimeFrameRestore();

RSI60e=TimeFrameExpand(RSI60,inHourly,expandLast);

Plot(RSI5,"RSI 5m",colorRed);
Plot(RSI60e,"RSI 60m",colorBlue);

Filter =  Cross(RSI5,70) AND Cross(RSI60e,70);
AddColumn(RSI5,"RSI 5");
AddColumn(RSI60e,"RSI 60");
 
can we use Gann Swing in some way to get better Historical support and resistance level or turning points ?
Nehal,

To be frank, I am just few months old in these areas and even I wouldnt bet money on my opinions.

I have seen that there are any number of methods to get the historical support/resistance. Now, which is better - I have no idea. Today I am just trying to see if the strength of a support/resistance level can be established. If a particular level is reported by these multiple methods, that could indicate strength. Or if that price level acted as a turning point more than once, that could also indicate strength.

Second part of the problem is automating this evaluation and effectively displaying this information in a chart. I dont see any immediate conclusion to this. But when I do get to a point that I believe is worthwhile your time, I will share it here.

btw, thanks for starting me on this thought.
 
Nehalji,

Please can you convert this to AFL.I got this indicator from mudra.com.It is SAR indicator.

//+------------------------------------------------------------------+
//| MT4-LevelStop-Reverse |
//| Version 2.0 |
//| Copyright © 2007-2008, Bruce Hellstrom (brucehvn) |
//| [email protected] |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

/////////////////////////////////////////////////////////////////////
// Version 2.0
//
// This is a port of the VTTrader VT-LevelStop-Reverse trading system.
// This is ported as an MT4 indicator only and perhaps can be evolved
// into an EA later.
//
/////////////////////////////////////////////////////////////////////

/*

This is a combination of two VT Trader trading systems. The first is the default
VT-LevelStop-Reverse and the second is one that was modified to allow customizing
the ATR settings for calculating the stop line. I've tried to combine these 2
versions into a single MT4 indicator.

The default VT version allows you to use two modes, optimized, and manual.
Optimized mode calculates the stop line by using a 14 period EMA smoothed
ATR(14) multiplied by a fixed multiplier of 2.824. In manual mode, you set a
fixed number of pips you want the stop line to be drawn. In my MT4 version,
there are two modes:

1. ATR mode (customizable ATR period, multiplier, and smoothing)
2. Fixed stop mode (customizable fixed stop)

The input parameters are as follows:

* UseATRMode - This calculates the stop line based on ATR using customizable period, multiplier and smoothing.
* NonATRStopPips - If "UseATRMode" is false, then this value is the number of fixed pips to place the stop line.
* ATRPeriod - If "UseATRMode" is true, then this sets the ATR period.
* ATRMultiplier - If "UseATRMode" is true, then the ATR value will be multiplied by this value when calculating the stop line.
* ATRSmoothing - If "UseATRMode" is true, then this will smooth the selected ATR with an EMA of this smoothing period.
* UpArrowColor - The color the Up arrows will display in.
* DnArrowColor - The color the Down arrows will display in.
* ArrowDistance - This can adjust the distance away from the stop line that the arrows appear. By default, the arrows appear directly above or below the stop line. A positive number here will move the arrows further away from the price. A negative number will move it closer to the price.
* AlertSound - If true, this will sound an alert when the reverse condition has been triggered.
* AlertMail - If true, will send email to the email address registered with MT4.
* ShowComment - This will turn on/off the comment on the chart. Turn off if you have other indicators that put data there and you don't want it overwritten.

For the default VT-LevelStop-Reverse behavior, set the following:
UseATRMode = true
ATRPeriod = 14
ATRMultiplier = 2.824
ATRSmoothing = 14

To use this indicator, copy it to your <MetaTrader Folder>\experts\indicators folder. Then restart MT4. It will appear in the custom indicators list.

Revision History

Version Beta 0.2
* Minor bug fixes.
* Remove extra "UseVTDefault" option.
* Add smoothing option for compatibility with default VT version.

Version Beta 0.3
* Delete objects at startup.
* Use a more unique object name prefix.
* Change ATRBuffer and SmoothBuffer to be non-indicator buffers.
* No need for UpSignal and DnSignal to be buffers.
* Change arrows to display at the stop line.
* Fix bug on current bar drawing that would cause multiple arrows to appear.

Version Beta 0.4
* Fix bug in non-indicator buffers that was causing erroneous data in the ATR buffer and smoothing buffer.

Version 1.0
* Fix some problems with the original VT formula that caused arrows to be drawn incorrectly if the price closed at the exact same level as the stop line.Fix bug in non-indicator buffers that was causing erroneous data in the ATR buffer and smoothing buffer.
* Add some print statements for arrow tracking.
* Always smooth, just use 1 for a value if no smoothing is indicated.
* Add ShowComment option

Version 2.0
* Fix multiple arrows being drawn in the same place.
* Try to fix an issue where arrows sometimes disappear.
* Add alerts.
* Name arrow objects incrementally rather than via random number.
*/

#property copyright "Copyright © 2007-2008, Bruce Hellstrom (brucehvn)"
#property link "http: //www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Magenta
#property indicator_style1 STYLE_DOT

#define INDICATOR_VERSION "v2.0"
#define VTS_OBJECT_PREFIX "vtsbh2483-"


//---- input parameters

extern bool UseATRMode = true;
extern int NonATRStopPips = 40;
extern int ATRPeriod = 9;
extern double ATRMultiplier = 3.0;
extern int ATRSmoothing = 0;
extern color UpArrowColor = DodgerBlue;
extern color DnArrowColor = OrangeRed;
extern int ArrowDistance = 0;
extern bool AlertSound = true;
extern bool AlertMail = false;
extern bool ShowComment = true;


//---- buffers
double TrStopLevel[];

//---- variables
double ATRBuffer[];
double SmoothBuffer[];
string ShortName;
int ArrowObjects = 0;
int ArrowNumber;
int PrevArrows = 0;
datetime LastArrowTime = 0;
bool LastArrowSignal = 0;
datetime LastAlertBar = 0;
datetime CurrentBarTime = 0;



//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init() {

int DrawBegin = 0;
if ( UseATRMode ) {
DrawBegin = ATRPeriod;
}

// Set the smoothing to 1 if it is zero or less
if ( ATRSmoothing <= 0 ) {
ATRSmoothing = 1;
}

IndicatorBuffers( 1 );
SetIndexStyle( 0, DRAW_LINE, STYLE_DOT, 1 );
SetIndexBuffer( 0, TrStopLevel );
SetIndexDrawBegin( 0, DrawBegin );

ShortName = "MT4-LevelStop-Reverse-" + INDICATOR_VERSION + "(";

if ( UseATRMode ) {
ShortName = StringConcatenate( ShortName, "ATRMode ", ATRPeriod, ", ",
ATRMultiplier, ", ", ATRSmoothing, " )" );
}
else {
ShortName = StringConcatenate( ShortName, "Manual Mode Stop = ", NonATRStopPips, " )" );
}

IndicatorShortName( ShortName );
SetIndexLabel( 0, ShortName );

Print( ShortName );
Print( "Copyright (c) 2007 - Bruce Hellstrom, [email protected]" );

MathSrand( TimeLocal() );

// Cleanup any leftover objects from previous runs
DeleteAllArrowObjects();
ArrowNumber = 0;
ArrowObjects = 0;

return( 0 );
}

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit() {
DeleteAllArrowObjects();
return( 0 );
}

//+------------------------------------------------------------------+
//| Function run on every tick |
//+------------------------------------------------------------------+
int start() {
Comment( ShortName );

int ictr;
int counted_bars = IndicatorCounted();

// Check for errors
if ( counted_bars < 0 ) {
return( -1 );
}

// Last bar will be recounted
if ( counted_bars > 0 ) {
counted_bars--;
}

int limit = Bars - counted_bars;
ictr = limit - 1;

if ( UseATRMode && Bars < ATRPeriod ) {
return( 0 );
}

// Make sure buffers are sized correctly
int buff_size = ArraySize( TrStopLevel );
if ( ArraySize( ATRBuffer ) != buff_size ) {
ArraySetAsSeries( ATRBuffer, false );
ArrayResize( ATRBuffer, buff_size );
ArraySetAsSeries( ATRBuffer, true );

ArraySetAsSeries( SmoothBuffer, false );
ArrayResize( SmoothBuffer, buff_size );
ArraySetAsSeries( SmoothBuffer, true );
}

int xctr;

if ( UseATRMode ) {
// First calculate the ATR
for ( xctr = 0; xctr < limit; xctr++ ) {
ATRBuffer[xctr] = iATR( NULL, 0, ATRPeriod, xctr );
}

// Smooth the ATR
for ( xctr = 0; xctr < limit; xctr++ ) {
SmoothBuffer[xctr] = Wilders( ATRBuffer, ATRSmoothing, xctr );
}
}


for ( xctr = ictr; xctr >= 0; xctr-- ) {
// Calculate the stop amount
double DeltaStop = NonATRStopPips * Point;

// Calculate our stop value based on ATR if required
if ( UseATRMode ) {
DeltaStop = NormalizeDouble( SmoothBuffer[xctr] * ATRMultiplier, 4 );
}

// Figure out where the current bar's stop level should be
double NewStopLevel;
double PrevStop = TrStopLevel[xctr + 1];
bool Up = false;
bool Dn = false;

if ( Close[xctr] == PrevStop ) {
NewStopLevel = PrevStop;
}
else {
if ( Close[xctr + 1] <= PrevStop && Close[xctr] < PrevStop ) {
NewStopLevel = MathMin( PrevStop, ( Close[xctr] + DeltaStop ) );
}
else {
if ( Close[xctr + 1] >= PrevStop && Close[xctr] > PrevStop ) {
NewStopLevel = MathMax( PrevStop, ( Close[xctr] - DeltaStop ) );
}
else {
if ( Close[xctr] > PrevStop ) {
NewStopLevel = Close[xctr] - DeltaStop;
Up = true;
}
else {
NewStopLevel = Close[xctr] + DeltaStop;
Dn = true;
}
}
}
}


TrStopLevel[xctr] = NewStopLevel;

// Can't do the arrows until the bar closes
if ( xctr > 0 ) {
if ( Up ) {
if ( Time[xctr] > LastArrowTime ) {
double UpSignal = TrStopLevel[xctr] - ( ArrowDistance * Point );
string ObjName = GetNextObjectName();
ObjectCreate( ObjName, OBJ_ARROW, 0, Time[xctr], UpSignal );
ObjectSet( ObjName, OBJPROP_COLOR, UpArrowColor );
ObjectSet( ObjName, OBJPROP_ARROWCODE, 233 );
ArrowObjects++;
LastArrowTime = Time[xctr];
LastArrowSignal = true;
}
}

if ( Dn ) {
if ( Time[xctr] > LastArrowTime ) {
double DnSignal = TrStopLevel[xctr] + ( 2 * Point ) + ( ArrowDistance * Point );
ObjName = GetNextObjectName();
ObjectCreate( ObjName, OBJ_ARROW, 0, Time[xctr], DnSignal );
ObjectSet( ObjName, OBJPROP_COLOR, DnArrowColor );
ObjectSet( ObjName, OBJPROP_ARROWCODE, 234 );
ArrowObjects++;
LastArrowTime = Time[xctr];
LastArrowSignal = false;
}
}
}

// Do the alerting
if ( xctr == 1 ) {
if ( LastArrowTime == Time[xctr] ) {
DoAlerts();
}
}

// Check to see if we've closed a bar and redraw the objects
if ( xctr == 0 ) {
if ( Time[xctr] != CurrentBarTime ) {
ObjectsRedraw();
CurrentBarTime = Time[xctr];
}
}

}

if ( ArrowObjects != PrevArrows ) {
Print( "Total Arrow Objects: ", ArrowObjects );
PrevArrows = ArrowObjects;
}

return( 0 );
}


//+------------------------------------------------------------------+
//| Gets the next object index so they can be deleted later |
//+------------------------------------------------------------------+
string GetNextObjectName() {
//int rand_val = MathRand() + 1;
ArrowNumber++;
//string retval = VTS_OBJECT_PREFIX + rand_val;
string retval = VTS_OBJECT_PREFIX + ArrowNumber;
return( retval );
}

//+------------------------------------------------------------------+
//| Wilders Calculation |
//+------------------------------------------------------------------+
double Wilders( double& indBuffer[], int Periods, int shift ) {
double retval = 0.0;
retval = iMAOnArray( indBuffer, 0, ( Periods * 2 ) - 1, 0, MODE_EMA, shift );
return( retval );
}

//+------------------------------------------------------------------+
//| Delete all the arrow objects |
//+------------------------------------------------------------------+
void DeleteAllArrowObjects() {
int delcnt = 0;
for ( int ictr = 1; ictr <= ArrowNumber; ictr++ ) {
string ObjName = VTS_OBJECT_PREFIX + ( ictr + 1 );
if ( ObjectDelete( ObjName ) ) {
delcnt++;
}
}
Print( "Objects deleted: ", delcnt );
return;
}

//+------------------------------------------------------------------+
//| Handles alerting via sound/email |
//+------------------------------------------------------------------+
void DoAlerts() {
if ( LastArrowTime > LastAlertBar ) {
if ( AlertSound ) {
PlaySound( "alert.wav" );
}

if ( AlertMail ) {
int per = Period();
string perstr = "";

switch( per ) {
case PERIOD_M1:
perstr = "M1";
break;

case PERIOD_M5:
perstr = "M5";
break;

case PERIOD_M15:
perstr = "M15";
break;

case PERIOD_M30:
perstr = "M30";
break;

case PERIOD_H1:
perstr = "H1";
break;

case PERIOD_H4:
perstr = "H4";
break;

case PERIOD_D1:
perstr = "D1";
break;

case PERIOD_W1:
perstr = "W1";
break;

case PERIOD_MN1:
perstr = "MN1";
break;

default:
perstr = "" + per + " Min";
break;
}

datetime curtime = TimeCurrent();
string strSignal = "LONG";
if ( !LastArrowSignal ) {
strSignal = "SHORT";
}
string str_subject = "MT4-SLReverse Alert " + TimeToStr( curtime, TIME_DATE | TIME_SECONDS );
SendMail( str_subject,
"The StopLevelReverse has given a " +
strSignal +
" signal for pair " +
Symbol() +
" " + perstr + "." );
}

LastAlertBar = LastArrowTime;
}
}

//+------------------------------------------------------------------+



Thanks

Rajesh
 
I am using an indicator in Metatrader which helps to avoid taking a trade when the propability of it moving in my favor are significally low. That is ATR. It calculate the ATR, informs how much the price has moved today and projects a low and a high Projection ATR for the Day. So if let's say we are near the top atr Projected the probability of giving a profit for the day are greatly diminished. I tried to implemented on amibroker but did it only on the title and I dont even jnow if it is correct.
What I would like is from the seniors in here take a look and comment and help to plot the projected lines as well as in the pictures below from MT4.

and here is what I tryed on Ami
Code:
TimeFrameSet(inDaily);
TrueRange = Max( H - L, Max( abs( H - Ref( C, -1 ) ), abs( L - Ref( C, -1 )
) ) );
myATR = MA(TrueRange, 10);
tARGETuP=L+myATR;
tARGETdWN=H-myATR;
TimeFrameRestore();

//Plot(myATR, "myATR", colorBlue, 1);
_SECTION_BEGIN("Title");
dec = (Param("Decimals",2,0,7,1)/10)+1;
Title = EncodeColor(55)+  Title = Name() + "     " + EncodeColor(32) + Date() +
"      " + EncodeColor(5) + "{{INTERVAL}}  " +
    EncodeColor(55)+ "     Open = "+ EncodeColor(52)+ WriteVal(O,dec) + 
    EncodeColor(55)+ "     High = "+ EncodeColor(5) + WriteVal(H,dec) +
    EncodeColor(55)+ "      Low = "+ EncodeColor(32)+ WriteVal(L,dec) + 
    EncodeColor(55)+ "    Close = "+ EncodeColor(7)+ WriteVal(C,dec)+
    EncodeColor(55)+ "    Volume = "+ EncodeColor(11)+ WriteVal(V,1)+ "\n" +
    EncodeColor(7)+ "      ATR(10) = "+ EncodeColor(32)+ WriteVal(TimeFrameExpand(Myatr,inDaily),dec)+
	EncodeColor(7)+ "      Today ATR = "+ EncodeColor(32)+ WriteVal(TimeFrameExpand(TrueraNGE,inDaily),dec)+"\n" +
	EncodeColor(7)+ "      TP UP = "+ EncodeColor(32)+ WriteVal(TimeFrameExpand(tARGETuP,inDaily),dec)+
	EncodeColor(7)+ "      TP Dwn = "+ EncodeColor(32)+ WriteVal(TimeFrameExpand(tARGETdwn,inDaily),dec);
_SECTION_END();
Any help greatly appreciated.

What is name of the Indicator in MT4?

As you do already know, standard ATR is simply average of High - Low. in this variation, you've done a criss-cross between previous High/Low with Close price.

What you need to do to confirm accuracy is to get Amibroker to compute over same scrip and since you cannot import data into MT4, only choice left is to get data from MT4 into Ami.
 

Nehal_s143

Well-Known Member
Nehalji,

Please can you convert this to AFL.I got this indicator from mudra.com.It is SAR indicator.

//+------------------------------------------------------------------+
//| MT4-LevelStop-Reverse |
//| Version 2.0 |
//| Copyright © 2007-2008, Bruce Hellstrom (brucehvn) |
//| [email protected] |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

/////////////////////////////////////////////////////////////////////
// Version 2.0
//
// This is a port of the VTTrader VT-LevelStop-Reverse trading system.
// This is ported as an MT4 indicator only and perhaps can be evolved
// into an EA later.
//
/////////////////////////////////////////////////////////////////////

/*

This is a combination of two VT Trader trading systems. The first is the default
VT-LevelStop-Reverse and the second is one that was modified to allow customizing
the ATR settings for calculating the stop line. I've tried to combine these 2
versions into a single MT4 indicator.

The default VT version allows you to use two modes, optimized, and manual.
Optimized mode calculates the stop line by using a 14 period EMA smoothed
ATR(14) multiplied by a fixed multiplier of 2.824. In manual mode, you set a
fixed number of pips you want the stop line to be drawn. In my MT4 version,
there are two modes:

1. ATR mode (customizable ATR period, multiplier, and smoothing)
2. Fixed stop mode (customizable fixed stop)

The input parameters are as follows:

* UseATRMode - This calculates the stop line based on ATR using customizable period, multiplier and smoothing.
* NonATRStopPips - If "UseATRMode" is false, then this value is the number of fixed pips to place the stop line.
* ATRPeriod - If "UseATRMode" is true, then this sets the ATR period.
* ATRMultiplier - If "UseATRMode" is true, then the ATR value will be multiplied by this value when calculating the stop line.
* ATRSmoothing - If "UseATRMode" is true, then this will smooth the selected ATR with an EMA of this smoothing period.
* UpArrowColor - The color the Up arrows will display in.
* DnArrowColor - The color the Down arrows will display in.
* ArrowDistance - This can adjust the distance away from the stop line that the arrows appear. By default, the arrows appear directly above or below the stop line. A positive number here will move the arrows further away from the price. A negative number will move it closer to the price.
* AlertSound - If true, this will sound an alert when the reverse condition has been triggered.
* AlertMail - If true, will send email to the email address registered with MT4.
* ShowComment - This will turn on/off the comment on the chart. Turn off if you have other indicators that put data there and you don't want it overwritten.

For the default VT-LevelStop-Reverse behavior, set the following:
UseATRMode = true
ATRPeriod = 14
ATRMultiplier = 2.824
ATRSmoothing = 14

To use this indicator, copy it to your <MetaTrader Folder>\experts\indicators folder. Then restart MT4. It will appear in the custom indicators list.

Revision History

Version Beta 0.2
* Minor bug fixes.
* Remove extra "UseVTDefault" option.
* Add smoothing option for compatibility with default VT version.

Version Beta 0.3
* Delete objects at startup.
* Use a more unique object name prefix.
* Change ATRBuffer and SmoothBuffer to be non-indicator buffers.
* No need for UpSignal and DnSignal to be buffers.
* Change arrows to display at the stop line.
* Fix bug on current bar drawing that would cause multiple arrows to appear.

Version Beta 0.4
* Fix bug in non-indicator buffers that was causing erroneous data in the ATR buffer and smoothing buffer.

Version 1.0
* Fix some problems with the original VT formula that caused arrows to be drawn incorrectly if the price closed at the exact same level as the stop line.Fix bug in non-indicator buffers that was causing erroneous data in the ATR buffer and smoothing buffer.
* Add some print statements for arrow tracking.
* Always smooth, just use 1 for a value if no smoothing is indicated.
* Add ShowComment option

Version 2.0
* Fix multiple arrows being drawn in the same place.
* Try to fix an issue where arrows sometimes disappear.
* Add alerts.
* Name arrow objects incrementally rather than via random number.
*/

#property copyright "Copyright © 2007-2008, Bruce Hellstrom (brucehvn)"
#property link "http: //www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Magenta
#property indicator_style1 STYLE_DOT

#define INDICATOR_VERSION "v2.0"
#define VTS_OBJECT_PREFIX "vtsbh2483-"


//---- input parameters

extern bool UseATRMode = true;
extern int NonATRStopPips = 40;
extern int ATRPeriod = 9;
extern double ATRMultiplier = 3.0;
extern int ATRSmoothing = 0;
extern color UpArrowColor = DodgerBlue;
extern color DnArrowColor = OrangeRed;
extern int ArrowDistance = 0;
extern bool AlertSound = true;
extern bool AlertMail = false;
extern bool ShowComment = true;


//---- buffers
double TrStopLevel[];

//---- variables
double ATRBuffer[];
double SmoothBuffer[];
string ShortName;
int ArrowObjects = 0;
int ArrowNumber;
int PrevArrows = 0;
datetime LastArrowTime = 0;
bool LastArrowSignal = 0;
datetime LastAlertBar = 0;
datetime CurrentBarTime = 0;



//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init() {

int DrawBegin = 0;
if ( UseATRMode ) {
DrawBegin = ATRPeriod;
}

// Set the smoothing to 1 if it is zero or less
if ( ATRSmoothing <= 0 ) {
ATRSmoothing = 1;
}

IndicatorBuffers( 1 );
SetIndexStyle( 0, DRAW_LINE, STYLE_DOT, 1 );
SetIndexBuffer( 0, TrStopLevel );
SetIndexDrawBegin( 0, DrawBegin );

ShortName = "MT4-LevelStop-Reverse-" + INDICATOR_VERSION + "(";

if ( UseATRMode ) {
ShortName = StringConcatenate( ShortName, "ATRMode ", ATRPeriod, ", ",
ATRMultiplier, ", ", ATRSmoothing, " )" );
}
else {
ShortName = StringConcatenate( ShortName, "Manual Mode Stop = ", NonATRStopPips, " )" );
}

IndicatorShortName( ShortName );
SetIndexLabel( 0, ShortName );

Print( ShortName );
Print( "Copyright (c) 2007 - Bruce Hellstrom, [email protected]" );

MathSrand( TimeLocal() );

// Cleanup any leftover objects from previous runs
DeleteAllArrowObjects();
ArrowNumber = 0;
ArrowObjects = 0;

return( 0 );
}

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit() {
DeleteAllArrowObjects();
return( 0 );
}

//+------------------------------------------------------------------+
//| Function run on every tick |
//+------------------------------------------------------------------+
int start() {
Comment( ShortName );

int ictr;
int counted_bars = IndicatorCounted();

// Check for errors
if ( counted_bars < 0 ) {
return( -1 );
}

// Last bar will be recounted
if ( counted_bars > 0 ) {
counted_bars--;
}

int limit = Bars - counted_bars;
ictr = limit - 1;

if ( UseATRMode && Bars < ATRPeriod ) {
return( 0 );
}

// Make sure buffers are sized correctly
int buff_size = ArraySize( TrStopLevel );
if ( ArraySize( ATRBuffer ) != buff_size ) {
ArraySetAsSeries( ATRBuffer, false );
ArrayResize( ATRBuffer, buff_size );
ArraySetAsSeries( ATRBuffer, true );

ArraySetAsSeries( SmoothBuffer, false );
ArrayResize( SmoothBuffer, buff_size );
ArraySetAsSeries( SmoothBuffer, true );
}

int xctr;

if ( UseATRMode ) {
// First calculate the ATR
for ( xctr = 0; xctr < limit; xctr++ ) {
ATRBuffer[xctr] = iATR( NULL, 0, ATRPeriod, xctr );
}

// Smooth the ATR
for ( xctr = 0; xctr < limit; xctr++ ) {
SmoothBuffer[xctr] = Wilders( ATRBuffer, ATRSmoothing, xctr );
}
}


for ( xctr = ictr; xctr >= 0; xctr-- ) {
// Calculate the stop amount
double DeltaStop = NonATRStopPips * Point;

// Calculate our stop value based on ATR if required
if ( UseATRMode ) {
DeltaStop = NormalizeDouble( SmoothBuffer[xctr] * ATRMultiplier, 4 );
}

// Figure out where the current bar's stop level should be
double NewStopLevel;
double PrevStop = TrStopLevel[xctr + 1];
bool Up = false;
bool Dn = false;

if ( Close[xctr] == PrevStop ) {
NewStopLevel = PrevStop;
}
else {
if ( Close[xctr + 1] <= PrevStop && Close[xctr] < PrevStop ) {
NewStopLevel = MathMin( PrevStop, ( Close[xctr] + DeltaStop ) );
}
else {
if ( Close[xctr + 1] >= PrevStop && Close[xctr] > PrevStop ) {
NewStopLevel = MathMax( PrevStop, ( Close[xctr] - DeltaStop ) );
}
else {
if ( Close[xctr] > PrevStop ) {
NewStopLevel = Close[xctr] - DeltaStop;
Up = true;
}
else {
NewStopLevel = Close[xctr] + DeltaStop;
Dn = true;
}
}
}
}


TrStopLevel[xctr] = NewStopLevel;

// Can't do the arrows until the bar closes
if ( xctr > 0 ) {
if ( Up ) {
if ( Time[xctr] > LastArrowTime ) {
double UpSignal = TrStopLevel[xctr] - ( ArrowDistance * Point );
string ObjName = GetNextObjectName();
ObjectCreate( ObjName, OBJ_ARROW, 0, Time[xctr], UpSignal );
ObjectSet( ObjName, OBJPROP_COLOR, UpArrowColor );
ObjectSet( ObjName, OBJPROP_ARROWCODE, 233 );
ArrowObjects++;
LastArrowTime = Time[xctr];
LastArrowSignal = true;
}
}

if ( Dn ) {
if ( Time[xctr] > LastArrowTime ) {
double DnSignal = TrStopLevel[xctr] + ( 2 * Point ) + ( ArrowDistance * Point );
ObjName = GetNextObjectName();
ObjectCreate( ObjName, OBJ_ARROW, 0, Time[xctr], DnSignal );
ObjectSet( ObjName, OBJPROP_COLOR, DnArrowColor );
ObjectSet( ObjName, OBJPROP_ARROWCODE, 234 );
ArrowObjects++;
LastArrowTime = Time[xctr];
LastArrowSignal = false;
}
}
}

// Do the alerting
if ( xctr == 1 ) {
if ( LastArrowTime == Time[xctr] ) {
DoAlerts();
}
}

// Check to see if we've closed a bar and redraw the objects
if ( xctr == 0 ) {
if ( Time[xctr] != CurrentBarTime ) {
ObjectsRedraw();
CurrentBarTime = Time[xctr];
}
}

}

if ( ArrowObjects != PrevArrows ) {
Print( "Total Arrow Objects: ", ArrowObjects );
PrevArrows = ArrowObjects;
}

return( 0 );
}


//+------------------------------------------------------------------+
//| Gets the next object index so they can be deleted later |
//+------------------------------------------------------------------+
string GetNextObjectName() {
//int rand_val = MathRand() + 1;
ArrowNumber++;
//string retval = VTS_OBJECT_PREFIX + rand_val;
string retval = VTS_OBJECT_PREFIX + ArrowNumber;
return( retval );
}

//+------------------------------------------------------------------+
//| Wilders Calculation |
//+------------------------------------------------------------------+
double Wilders( double& indBuffer[], int Periods, int shift ) {
double retval = 0.0;
retval = iMAOnArray( indBuffer, 0, ( Periods * 2 ) - 1, 0, MODE_EMA, shift );
return( retval );
}

//+------------------------------------------------------------------+
//| Delete all the arrow objects |
//+------------------------------------------------------------------+
void DeleteAllArrowObjects() {
int delcnt = 0;
for ( int ictr = 1; ictr <= ArrowNumber; ictr++ ) {
string ObjName = VTS_OBJECT_PREFIX + ( ictr + 1 );
if ( ObjectDelete( ObjName ) ) {
delcnt++;
}
}
Print( "Objects deleted: ", delcnt );
return;
}

//+------------------------------------------------------------------+
//| Handles alerting via sound/email |
//+------------------------------------------------------------------+
void DoAlerts() {
if ( LastArrowTime > LastAlertBar ) {
if ( AlertSound ) {
PlaySound( "alert.wav" );
}

if ( AlertMail ) {
int per = Period();
string perstr = "";

switch( per ) {
case PERIOD_M1:
perstr = "M1";
break;

case PERIOD_M5:
perstr = "M5";
break;

case PERIOD_M15:
perstr = "M15";
break;

case PERIOD_M30:
perstr = "M30";
break;

case PERIOD_H1:
perstr = "H1";
break;

case PERIOD_H4:
perstr = "H4";
break;

case PERIOD_D1:
perstr = "D1";
break;

case PERIOD_W1:
perstr = "W1";
break;

case PERIOD_MN1:
perstr = "MN1";
break;

default:
perstr = "" + per + " Min";
break;
}

datetime curtime = TimeCurrent();
string strSignal = "LONG";
if ( !LastArrowSignal ) {
strSignal = "SHORT";
}
string str_subject = "MT4-SLReverse Alert " + TimeToStr( curtime, TIME_DATE | TIME_SECONDS );
SendMail( str_subject,
"The StopLevelReverse has given a " +
strSignal +
" signal for pair " +
Symbol() +
" " + perstr + "." );
}

LastAlertBar = LastArrowTime;
}
}

//+------------------------------------------------------------------+


Thanks

Rajesh

Rajeshji

I am just beginner in AFL Coding, I can do small modifications but converting mq4 to afl is still long way for me
 

Similar threads