Simple Coding Help - No Promise.

Plz guide me:

Hi Guys..

IM using below code to see how much time left to complete one candle.

But now problem is when i selected time frame as ticks .. it not showing how many ticks left?

can any one add one more line to find " how many ticks left" or how many ticks done in current candle?

_SECTION_BEGIN("Time Left");
function GetSecondNum()
{
Time = Now( 4 );
Seconds = int( Time % 100 );
Minutes = int( Time / 100 % 100 );
Hours = int( Time / 10000 % 100 );
SecondNum = int( Hours * 60 * 60 + Minutes * 60 + Seconds );
return SecondNum;
}
RequestTimedRefresh( 1 );
TimeFrame = Interval();
SecNumber = GetSecondNum();
Newperiod = SecNumber % TimeFrame == 0;
SecsLeft = SecNumber - int( SecNumber / TimeFrame ) * TimeFrame;
SecsToGo = TimeFrame - SecsLeft;

x=Param("xposn",434,0,1000,1);
y=Param("yposn",40,0,1000,1);

GfxSelectSolidBrush( ColorRGB( 230, 230, 230 ) );
GfxSelectPen( ColorRGB( 230, 230, 230 ), 2 );
if ( NewPeriod )
{
GfxSelectSolidBrush( colorYellow );
GfxSelectPen( colorYellow, 2 );
Say( "" );
}
if ( SecsToGo == 302)
Say(" IOIOIOIOIO ");
cx = Param( "cxposn", 1080, 0, 1250, 1 );
cy = Param( "cyposn", 5, 0, 500, 1 );
GfxSelectFont( "Arial", 14, 98, False );
//gfxcup = SelectedValue(C > Ref(C,-1));
//gfxpcolor = IIf(gfxcup,colorBrightGreen,colorRed);
//GfxSetTextColor(colorBlue);
GfxSetTextColor( colorBlack );
GfxTextOut( "Time Left: " + SecsToGo + " ", cx, cy );
_SECTION_END();


Im using TICK chart. Im using 100 Ticks to complete One candle. But not understanding how many ticks till now completed.. and hoe many ticks need to complete that candle.

Can u help me with that code.

By looking ticks left i can guees approx timing to comple that candle.

Plz write code for that.

I need like this:
If i select chart as 100 ticks
Ticks completed:40 ticks Left:60

Plz help me.
Thanks in advance.
 
Hi

I am using Open Range Breakout.afl for MCX which marks high low of 10.00 am to 10.15 am and plots signal on either side breakout

I want this signal to be plotted only for next 30 min i.e till 10.45 am, if price crosses opening range after 10.45 am anytime during the day signal should not come, but afl should show range yellow lines till close of market, as opening range lines acts good support and resistance

Please help

_SECTION_BEGIN("Open Range Breakout");
// Open Range Breakout AFL
// Current ORB level time is set as 10.15 a.m. which can be easily changed
SetBarsRequired(1000,0);
ORBtype=ParamList("ORB Single or Two levels?","Two|Single");
Style=ParamList("Plot Bars or Candle","Candle|Bars");
BarColor = IIf(Close > Open, colorGreen, colorRed);
SetBarFillColor(BarColor);
if(style=="Bars")Cstyle=styleBar;
else Cstyle=styleCandle;
Plot(C,"",colorWhite,Cstyle);
timesetting=102000;
tn=TimeNum();
Datey=DateNum();
fastprice=lev=0;
avp=(O+C)/2;
r2=s2=ar1=ar2=ar3=bs1=bs2=bs3=0;
fastbuy=fastsell=0;
gapzz=10;
Lastsig=Buycond=Shortcond=dayopen=dayclose=dayhigh=daylow=0;
for (i=2;i<BarCount;i++)
{

//PlotText(WriteVal(1,1.0),i,H+15,colorWhite);

//day high low logic
if (Datey!=Datey[i-1])
{
Dayopen=O;
Dayclose=C;
Buycond=Shortcond=lastsig=0;
ar1=ar2=ar3=bs1=bs2=bs3=0;
fastprice=lev=0;
}
if (Datey==Datey[i-1])
{
Dayopen=Dayopen[i-1];
Dayclose=Dayclose[i-1];
Dayhigh=Dayhigh[i-1];
Daylow=Daylow[i-1];
}
if (H>Dayhigh)Dayhigh=H;
if (Daylow==0)Daylow=L;
if (L<Daylow)Daylow=L;
// day high low logic end
//PlotText(WriteVal(i,1.0),i,H+10,colorWhite);

if (tn<timesetting )
{
//PlotText(WriteVal(1,1.0),i,H+10,colorWhite);

r2=Dayhigh;
s2=Daylow;
if (ORbtype=="Single")fastprice=r2=s2=(Dayhigh+Daylow)/2;
}
else
{
//PlotText(WriteVal(1,1.0),i,H+10,colorWhite);

r2=r2[i-1];
s2=s2[i-1];
}
Lev=0;
if (ORbtype=="Single")
{
fastprice=r2;
if (avp>r2)Lev=1;
if (avp<s2)Lev=8;

}
else
{
if (avp>r2){fastprice=r2;Lev=1;}
if (avp<s2){fastprice=s2;Lev=8;}
if (avp<r2 AND avp>s2 AND avp>(r2+s2)/2){fastprice=r2;}
if (avp<r2 AND avp>s2 AND avp<(r2+s2)/2){fastprice=s2;}
}

if (Lev==1)
{
ar1=avp-r2;ar2=avp[i-1]-r2;ar3=avp[i-2]-r2;
//passthrough
if (avp>r2 AND avp[i-1]<r2)Buycond=1;
//kiss and go above
if (ar2<gapzz AND ar1>ar2 AND ar3>ar2) Buycond=1;
}
if (Lev==8)
{
bs1=s2-avp;bs2=s2-avp[i-1];bs3=s2-avp[i-2];
//pass through
if (avp[i-1]>s2 AND avp<s2)Shortcond=1;
//kiss and go
if (bs2<gapzz AND bs1>bs2 AND bs3>bs2) Shortcond=1;
}
if (Lev==1 AND Buycond==1 AND Lastsig!=1)
{
fastbuy=1;
Lastsig=1;
Buycond=shortcond=0;
}
if (Lev==8 AND Shortcond==1 AND Lastsig!=-1)
{
fastsell=1;
Lastsig=-1;
Buycond=shortcond=0;
}
}
shape = fastBuy * shapeUpArrow + fastSell * shapeDownArrow;
//PlotShapes( shape, IIf( fastBuy, colorBlue, colorRed ), 0, IIf( fastBuy, Low, High));
if (ORbtype=="Single")
{
Plot(r2,"R2",colorGreen,styleLine);
}
else
{
Plot(r2,"R2",colorYellow,styleLine);
Plot(s2,"S2",colorYellow,styleLine);
}

_SECTION_END();

Buy= fastbuy;
Sell=C<O;
Short = fastsell;
Cover=C>O;

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

PlotShapes(Buy*shapeUpArrow,colorGreen,0,L,-35);
PlotShapes(Short*shapeDownArrow,colorRed,0,H,-35);

_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", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();
 

Attachments

Last edited:

labdhi

Active Member
wow !! , a very good thread , a great learning base for afl coding ,
thanks happy ji for starting this awesome thread ........also for pratap ji for continuning it ,

sir i finalisied my system , now i want to backtest it on ami ,
trade with 2 lots always , initial equity 200,000 rs ,script only banknifty-1 , commissions shd be deducted,
what backtest code is to be added in my afl ,
also in setting window in amibroker in analysis window ,
there r options
future mode = ?
round lot size = ?
commissions=?
account margins = ?

what values r to be done in this window ?
also is there any other option , which we need to consider while backtesting ?
sorry if questions r too many or funny , but i am totally novice in terms of backtesting ,
plz sir write a code or sir simply state a process to backtest my trading idea ..........
 

ethan hunt

Well-Known Member
Hi,

Below is an AFL.

I would like to incoporate following conditions/options into the AFL.

1) BUY CONDITION: Green Arrow when MA (Close,50) crosses MA (Close,100) from below & goes up.

2) SHORT CONDITION: Red Arrow when MA (Close,100) crosses MA (Close,50) from below & goes up.


3) BUY EXECUTION: Buy at open of next candle after point 1 candle ; TARGET: 50 points; SL: 25 points

4) SHORT EXECUTION: Short at open of next candle after point 2 candle; TARGET: 50 points; SL 25 points

5) Draws automatically HORIZONTAL LINES for TARGET & SL with respective values as soon as BUY /SHORT is triggered.

6) Shows BUY@ PRICE ; SHORT@ PRICE on chart above candles of points 3 & 4.

7) VOICE ALERTS as soon as point 1 & 2 are met.

8) VOICE ALERTS as soon as TARGET or SL is hit.

9) POP-UPS as soon as point 1 & 2 are met.

10) POP-UPS as soon as point TARGET / SL is hit.

11) Back testing facility.

12) Scanning facility.

Thanks a lot.

AFL:


_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", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();

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

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

A=MA(Close,50);
B=MA(Close,100);
Buy=Cross(A,B);
Sell=Cross(B,A);
PlotShapes(IIf(Sell==1, shapeDownArrow, shapeNone), colorRed, 0,High, Offset=-50);
PlotShapes(IIf(Buy==1, shapeUpArrow , shapeNone), colorGreen, 0,Low, Offset=-50);
Bump ... anyone ?
 
Code:
//--------------------------------------------------------------//
//  Kenzie SR System - 09/2010
//  Modified By Kenzie Sebastian ([email protected])
//  Modified By [email protected]
//
// - fixed the % change to display correctly
// - modified buy/sell signals display above/below candles
// - added Market trend S&P 500
// - change color of characters to display with black background.
//--------------------------------------------------------------
SetBarsRequired( 800, 0 );
 
GraphXSpace = 7;
SetChartOptions( 0, chartShowArrows | chartShowDates );
 
// set criteria to scan for big stock only;
BigStock = MA( V, 10 ) * MA( C, 10 ) > 1000000;
 
//---------------Color------------------------
per1 = 6;
per2 = 2;
Om = MA( O, per1 );
hm = MA( H, per1 );
lm = MA( L, per1 );
Cm = MA( C, per1 );
 
// 1. Heiken Ashi
HACLOSE = ( Om + Hm + Lm + Cm ) / 4;
HaOpen = AMA( Ref( HaClose,  -1 ),  0.5 );
HaHigh = Max( Hm,  Max( HaClose,  HaOpen ) );
HaLow = Min( Lm,  Min( HaClose,  HaOpen ) );
 
 
Of = MA( Haopen, per2 );
Cf = MA( Haclose, per2 );
Lf = IIf( haOpen < haClose, MA( Halow, per2 ), MA( Hahigh, per2 ) );
Hf = IIf( haOpen < haClose, MA( Hahigh, per2 ), MA( Halow, per2 ) );
//Color = IIf( Cf > Of, colorGreen, colorRed );
 
 
//----------------------------------------------------
 
TrailStop = HHV( C - 2 * ATR( 10 ), 15 );
ProfitTaker = EMA( H, 13 ) + 2 * ATR( 10 );
 
/* **********************************
Code to automatically identify pivots
********************************** */
 
// -- what will be our lookback range for the hh and ll?
farback = 140; //How Far back to go
nBars = 12; //Number of bars
 
// -- Create 0-initialized arrays the size of barcount
aHPivs = H - H;
aLPivs = L - L;
 
// -- More for future use, not necessary for basic plotting
aHPivHighs = H - H;
aLPivLows = L - L;
aHPivIdxs = H - H;
aLPivIdxs = L - L;
nHPivs = 0;
nLPivs = 0;
lastHPIdx = 0;
lastLPIdx = 0;
lastHPH = 0;
lastLPL = 0;
curPivBarIdx = 0;
 
// -- looking back from the current bar, how many bars
// back were the hhv and llv values of the previous
// n bars, etc.?
aHHVBars = HHVBars( H, nBars );
aLLVBars = LLVBars( L, nBars );
aHHV = HHV( H, nBars );
aLLV = LLV( L, nBars );
 
// -- Would like to set this up so pivots are calculated back from
// last visible bar to make it easy to "go back" and see the pivots
// this code would find. However, the first instance of
// _Trace output will show a value of 0
aVisBars = Status( "barvisible" );
nLastVisBar = LastValue( Highest( IIf( aVisBars, BarIndex(), 0 ) ) );
_TRACE( "Last visible bar: " + nLastVisBar );
 
// -- Initialize value of curTrend
curBar = ( BarCount - 1 );
curTrend = "";
 
if ( aLLVBars[curBar] < aHHVBars[curBar] )
{
    curTrend = "D";
}
else
{
    curTrend = "U";
}
 
// -- Loop through bars. Search for
// entirely array-based approach
// in future version
for ( i = 0; i < BarCount; i++ )
{
    curBar = ( BarCount - 1 ) - i;
// -- Have we identified a pivot? If trend is down...
 
    if ( aLLVBars[curBar] < aHHVBars[curBar] )
    {
// ... and had been up, this is a trend change
        if ( curTrend == "U" )
        {
            curTrend = "D";
// -- Capture pivot information
            curPivBarIdx = curBar - aLLVBars[curBar];
            aLPivs[curPivBarIdx] = 1;
            aLPivLows[nLPivs] = L[curPivBarIdx];
            aLPivIdxs[nLPivs] = curPivBarIdx;
            nLPivs++;
        }
 
// -- or current trend is up
    }
    else
    {
        if ( curTrend == "D" )
        {
            curTrend = "U";
            curPivBarIdx = curBar - aHHVBars[curBar];
            aHPivs[curPivBarIdx] = 1;
            aHPivHighs[nHPivs] = H[curPivBarIdx];
            aHPivIdxs[nHPivs] = curPivBarIdx;
            nHPivs++;
        }
 
// -- If curTrend is up...else...
    }
 
// -- loop through bars
}
 
// -- Basic attempt to add a pivot this logic may have missed
// -- OK, now I want to look at last two pivots. If the most
// recent low pivot is after the last high, I could
// still have a high pivot that I didn't catch
// -- Start at last bar
curBar = ( BarCount - 1 );
 
candIdx = 0;
 
candPrc = 0;
 
lastLPIdx = aLPivIdxs[0];
 
lastLPL = aLPivLows[0];
 
lastHPIdx = aHPivIdxs[0];
 
lastHPH = aHPivHighs[0];
 
if ( lastLPIdx > lastHPIdx )
{
// -- Bar and price info for candidate pivot
    candIdx = curBar - aHHVBars[curBar];
    candPrc = aHHV[curBar];
 
    if (
        lastHPH < candPrc AND
        candIdx > lastLPIdx AND
        candIdx < curBar )
    {
// -- OK, we'll add this as a pivot...
        aHPivs[candIdx] = 1;
// ...and then rearrange elements in the
// pivot information arrays
 
        for ( j = 0; j < nHPivs; j++ )
        {
            aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs- ( j+1 )];
            aHPivIdxs[nHPivs-j] = aHPivIdxs[nHPivs-( j+1 )];
        }
 
        aHPivHighs[0] = candPrc ;
 
        aHPivIdxs[0] = candIdx;
        nHPivs++;
    }
}
else
{
// -- Bar and price info for candidate pivot
    candIdx = curBar - aLLVBars[curBar];
    candPrc = aLLV[curBar];
 
    if (
        lastLPL > candPrc AND
        candIdx > lastHPIdx AND
        candIdx < curBar )
    {
// -- OK, we'll add this as a pivot...
        aLPivs[candIdx] = 1;
// ...and then rearrange elements in the
// pivot information arrays
 
        for ( j = 0; j < nLPivs; j++ )
        {
            aLPivLows[nLPivs-j] = aLPivLows[nLPivs-( j+1 )];
            aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-( j+1 )];
        }
 
        aLPivLows[0] = candPrc;
 
        aLPivIdxs[0] = candIdx;
        nLPivs++;
    }
}
 
//============== EXPLORATION ==============
Buy = Cover = BigStock AND aLPivs == 1;
 
Sell = Short = BigStock AND aHPivs == 1;
 
SellPrice = ValueWhen( Sell, C, 1 );
 
BuyPrice = ValueWhen( Buy, C, 1 );
 
Long = Flip( Buy, Sell );
 
Shrt = Flip( Sell, Buy );
 
//============== Plot price ==============
n = 15;
 
a =  C > ( MA( H, n ) + MA( L, n ) ) / 2;// then Buy next bar at market;
 
b = C < ( MA( H, n ) + MA( L, n ) ) / 2;// then Sell Short next bar at market;
 
state = IIf( BarsSince( a ) < BarsSince( b ), 1, 0 );
 
Longs = state == 1;
 
shorts = state == 0;
 
//Chart
Colorbar = IIf( Longs, colorGreen, IIf( Shorts, colorRed, colorGrey40 ) );
 
Plot( C, "Close", colorbar, styleCandle = 64 | styleNoTitle );
 
//============== Plot Shape ==============
PlotShapes( IIf( aHPivs == 1, shapeDownArrow, shapeNone ), colorOrange, 0, High, Offset = -45 );
 
PlotShapes( IIf( aLPivs == 1, shapeUpArrow , shapeNone ), colorLime, 0, Low, Offset = -20 );
PlotShapes( IIf(Buy, shapeSmallCircle, shapeNone),colorDarkGreen, 0, BuyPrice, Offset = -15 );
PlotShapes( IIf(Sell, shapeSmallCircle, shapeNone),colorRed, 0 ,SellPrice,  Offset = 45  );
FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status("LastVisibleBar");
for( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++)
{
if( Buy[b] ) PlotText("\n\n\n\n Buy\n "+NumToStr(BuyPrice[b],1.2),b,BuyPrice[b],colorDarkGreen);
else if( Sell[b] ) PlotText("Sell  "+NumToStr(SellPrice[b], 1.2),b,SellPrice[b],colorRed);
}
 
//============== EMA(13) ==============
Plot( EMA( C, 13 ), "" , colorSkyblue + styleLine + styleNoRescale );
 
//============== TRENDING ==============
DTL = 150; // DTL = Define Trend Long
 
DTM = 70;   // DTM = Define Trend Medium
 
DTS = 14;  // DTS = Define Trend Short
 
TL = LinRegSlope( MA( C, DTL ), 2 );     // TL = Trend Long
 
TM = LinRegSlope( MA( C, DTM ), 2 );  // TM = Trend Medium
 
TS = LinRegSlope( MA( C, DTS ), 2 );  // TS = Trend Short
 
TLL = IIf( LinRegSlope( MA( C, DTL ), 2 ) > 0, True, False );
 
TMM = IIf( LinRegSlope( MA( C, DTM ), 2 ) > 0, True, False );
 
TSS = IIf( LinRegSlope( MA( C, DTS ), 2 ) > 0, True, False );
 
//============== VOLUME ==============
Vlp = 30; //Volume lookback period
 
Vrg = MA( V, Vlp );
 
St = StDev( Vrg, Vlp );
 
Vp3 = Vrg + 3 * st;
 
Vp2 = Vrg + 2 * st;
 
Vp1 = Vrg + 1 * st;
 
Vn1 = Vrg - 1 * st;
 
Vn2 = Vrg - 2 * st;
 
//============== WILLIAM'S %R ==============
WR = ( ( HHV( H, 14 ) - C ) / ( HHV ( H, 14 ) - LLV ( L, 14 ) ) ) * -100;
 
//============== A/D ==============
TRH = IIf( Ref( C, -1 ) > H, Ref( C, -1 ), H );
 
TRL = IIf( Ref( C, -1 ) < L, Ref( C, -1 ), L );
 
ad = IIf( C > Ref( C, -1 ), C - TRL, IIf( C < Ref( C, -1 ), C - TRH, 0 ) );
 
WAD = Cum( ad );
 
wu = wad > Ref( wad, -1 );
 
wd = wad < Ref( wad, -1 );
 
//============== MACD ==============
MB = Cross ( MACD(), Signal() );
 
MS = Cross( Signal(), MACD() );
 
MB = ExRem( MB, MS );
 
MS = ExRem( MS, MB );
 
MB1 = MACD() > Signal();
 
MS1 = MACD() < Signal();
 
//============== STOCH ==============
StochKval = StochK( 10, 5 );
 
StochDval = StochD( 10, 5, 5 );
 
StochBuy = Cross( StochK( 10, 5 ), StochD( 10, 5, 5 ) );
 
StochSell = Cross ( StochD( 10, 5, 5 ), StochK( 10, 5 ) );
 
StBuy = StochK( 10, 5 ) > StochD( 10, 5, 5 );
 
StSell = StochK( 10, 5 ) < StochD( 10, 5, 5 );
 
//============== ADX ==============
adxBuy =  Cross( PDI( 14 ), MDI( 14 ) );
 
adxSell = Cross( MDI( 14 ), PDI( 14 ) );
 
adxBuy = ExRem( adxBuy, adxSell );
 
adxSell = ExRem( adxSell, adxBuy );
 
adxbuy1 = PDI( 14 ) > MDI( 14 );
 
adxsell1 = MDI( 14 ) > PDI( 14 );
 
//==============Zero Lag TMA ==============
function ZeroLagTEMA( array, period )
{
    TMA1 = TEMA( array, period );
    TMA2 = TEMA( TMA1, period );
    Diff = TMA1 - TMA2;
    return TMA1 + Diff ;
}
 
haClose = ( haClose + haOpen + haHigh + haLow ) / 4;
 
periodtm = 55;
ZLHa = ZeroLagTEMA( haClose, periodtm );
ZLTyp = ZeroLagTEMA( Avg, periodtm );
TMBuy = Cross( ZLTyp, ZLHa );
TMSell = Cross( ZLHa, ZLTyp );
TMBuy1 = ZLTyp > ZLHa ;
TMSell1 = ZLHa > ZLTyp ;
 
//============== ZLW ==============
R = ( ( HHV( H, 14 ) - C ) / ( HHV ( H, 14 ) - LLV ( L, 14 ) ) ) * -100;
MaxGraph = 10;
PeriodZ = 10;
EMA1 = EMA( R, PeriodZ );
EMA2 = EMA( EMA1, 5 );
Difference = EMA1 - EMA2;
ZeroLagEMA = EMA1 + Difference;
PR = 100 - abs( ZeroLagEMA );
MoveAvg = MA( PR, 5 );
ZBuy = Cross( PR, moveAvg ) AND PR < 30;
ZSell = Cross( moveAvg, PR ) AND PR > 70;
ZBuy1 = PR >= MoveAvg AND PR >= Ref( PR, -1 ) ;
ZSell1 = ( PR < MoveAvg ) OR PR >= MoveAvg AND PR < Ref( PR, -1 ) ;
 
//============== RS ==============
p = ( H + L + C ) / 3;
r1 = ( 2 * p ) - L;
s1 = ( 2 * p ) - H;
r2 = p + ( r1 - s1 );
s2 = p - ( r2 - s1 );
R3 = P + ( R2 - S2 );
S3 = P - ( R3 - S2 );
 
//============== IBUY ==============
Ibuy =  Cross( RSI( 14 ), EMA( RSI( 14 ), 9 ) );
Isell = Cross( EMA( RSI( 14 ), 9 ), RSI( 14 ) );
Ibuy = ExRem( Ibuy, ISell );
Isell = ExRem( ISell, Ibuy );
BlRSI = RSI( 14 ) > EMA( RSI( 14 ), 9 );
BrRSI = RSI( 14 ) < EMA( RSI( 14 ), 9 );
 
 
//=================Trend & Signals & Market Index ===============================
/// Please replace "00DSEGEN" with your market index ticker and activate the codes
 
/// Market Bull Bear
 
Cg = Foreign("^GSPC", "C");
Cgo= Ref(Cg,-1);
 
//Longterm Bullish or Bearish
Bullg = Cg > WMA(Cg,200);
Bearg= Cg <WMA(Cg,200);
 
//Midterm Bullish or Bearish
mBullg = Cg >WMA(Cg,50);
mBearg= Cg <WMA(Cg,50);
 
//Shortterm Bullish or Bearish
sBullg = Cg >WMA(Cg,15);
sBearg= Cg <WMA(Cg,15);
////////////////////////////////
 
 
 
xChange1=Cg - Ref(Cg,-1);
Change1 = StrFormat("%1.2f% ",xChange1);    
barche1= xChange1>=0;  
Comche1= xChange1<0;   
xperchange1 = xChange1/100;
perchange1 = StrFormat("%1.2f% ",xperchange1);   
positivechange1 = xperchange1>0;  
negativechange1 = xperchange1<0;
 
//=================Trend & Signals & Market Index END===============================
 
 
 
//============== TITLE ==============

_SECTION_BEGIN("Volatility 2");
// Just Re-share
// E.M.Pottasch, Jul 2010
// from Metastock formula, link: http://stocata.org/metastock/stop_trail_atr.html
// added separate parameters for upward and downward market environment

function vstop_func(trBull,trBear)
{
	trailArray[ 0 ] = C[ 0 ]; // initialize
	for( i = 1; i < BarCount; i++ )
	{
		prev = trailArray[ i - 1 ];
 
		if (C[ i ] > prev AND C[ i - 1 ] > prev)
		{
			trailArray[ i ] = Max(prev,C[ i ] - trBull[ i ]);
		}
		else if (C[ i ] < prev AND C[ i - 1 ] < prev)
		{
			trailArray[ i ] = Min(prev,C[ i ] + trBear[ i ]);
		}
		else if (C[ i ] > prev)
		{
			trailArray[ i ] = C[ i ] - trBull[ i ];
		}
		else
		{
			trailArray[ i ] = C[ i ] + trBear[ i ];	
		}
	}
	return trailArray;
}

per = Param("per",20, 1, 150, 1);
multBull = Param("multBull",2, 1, 4, 0.05);
multBear = Param("multBear",2, 1, 4, 0.05);

trBull = multBull * ATR(per);
trBear = multBear * ATR(per);

trailArray = vstop_func(trBull,trBear);

SetChartBkColor( ParamColor("ColorBG", ColorRGB( 0, 0, 0 ) ) );
GraphXSpace = 5;
SetChartOptions(0, chartShowDates);
Plot(IIf(trailArray > C,trailArray,Null),"\ntrailShort",ParamColor("ColorTrailShort",ColorRGB(255,0,0)),styleStaircase);
Plot(IIf(trailArray < C,trailArray,Null),"\ntrailLong",ParamColor("ColorTrailLong",ColorRGB(0,255,0)),styleStaircase);
Plot( C, "\nCandle",colorWhite, styleCandle );
_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("KPL Swing with N&M Swing");
SetBarsRequired(200,0);
 
GraphXSpace = 5;
SetChartOptions(0,chartShowArrows|chartShowDates);
k =  Optimize("K",Param("K",3,0.25,5,0.25),0.25,5,0.25);
Per= Optimize("atr",Param("atr",10,3,20,1),3,20,1);
HACLOSE=(O+H+L+C)/4;
HaOpen = AMA( Ref( HaClose,  -1 ),  0.5 );
HaHigh = Max( H,  Max( HaClose,  HaOpen ) );
HaLow = Min( L,  Min( HaClose,  HaOpen ) );
PlotOHLC( HaOpen, HaHigh, HaLow, HaClose, "" + Name(), colorBlack, styleCandle | styleNoLabel );
j=Haclose;
 
//=======================================================================================================================
//=========================Indicator==============================================================================================
f=ATR(15);
 
rfsctor = WMA(H-L, Per);
 
revers = k * rfsctor;
 
Trend = 1; 
NW[0] = 0; 
NW[BarCount-1] = Null; 
 
 
for(i = 1; i < BarCount-1; i++)
{
 if(Trend[i-1] == 1)               
 {
  if(j[i] < NW[i-1])                
  {
   Trend[i] = -1;                  
   NW[i] = j[i] + Revers[i];       
  }
  else                             
  {
   Trend[i] = 1;
   if((j[i] - Revers[i]) > NW[i-1])
   {
    NW[i] = j[i] - Revers[i];
   }
   else
   {
    NW[i] = NW[i-1];
   }
  }
 }
 if(Trend[i-1] == -1)              
 {
  if(j[i] > NW[i-1])               
  {
   Trend[i] = 1;                   
   NW[i] = j[i] - Revers[i];       
  }
  else                             
  {
   Trend[i] = -1;
   if((j[i] + Revers[i]) < NW[i-1])
   {
    NW[i] = j[i] + Revers[i];
   }
   else
   {
    NW[i] = NW[i-1];
   }
  }
 }
}
 
//===============system================
 
Plot(NW, "", IIf(Trend == 1, 27, 4), 4);
Buy=NW<HACLOSE;
Sell=NW>HACLOSE;
SellPrice=ValueWhen(Sell,C,1);
BuyPrice=ValueWhen(Buy,C,1);
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy );
 
Short=Sell;
Cover=Buy;
 
 
NMAB= NW<HACLOSE;
NMAS= NW>HACLOSE;
AlertIf( Buy , "SOUND C://Windows//Media//chimes.wav", "Audio alert", 2 );
AlertIf( Sell , "SOUND C://Windows//Media//alert.wav", "Audio alert", 2 );
 
NMA_status= WriteIf(NMAB, "BUY MODE", WriteIf(NMAS, "SELL MODE", "NEUTRAL"));
NMAS_Col=IIf(NMAB, colorGreen, IIf(NMAS, colorRed, colorLightGrey));
Filter=1;
AddColumn( NW[BarCount-1], "SAR", 1.2 );
AddColumn( HACLOSE, "HA Close", 1.2 );
AddColumn( C, "Close", 1.2 );
AddTextColumn(NMA_status, "MODE", 1, colorWhite, NMAS_Col);
AddColumn( DateTime(), "Date / Time", formatDateTime );
_SECTION_END();
//=================TITLE================================================================================================
_SECTION_BEGIN("Title");
if( Status("action") == actionIndicator )
(
Title = EncodeColor(colorWhite)+ "SureShot trading 3 10" + " - " +  Name() + " - " + EncodeColor(colorRed)+ Interval(2) + EncodeColor(colorWhite) +
 "  - " + Date() +" - "+"\n" +EncodeColor(colorRed) +"Op-"+O+"  "+"Hi-"+H+"  "+"Lo-"+L+"  "+
"Cl-"+C+"  "+ "Vol= "+ WriteVal(V)+"\n"+
EncodeColor(colorLime)+
WriteIf (Buy , " GO LONG / Reverse Signal at "+C+"  ","")+
WriteIf (Sell , " EXIT LONG / Reverse Signal at "+C+"  ","")+"\n"+EncodeColor(colorWhite)+
WriteIf(Sell , "Total Profit/Loss for the Last Trade Rs."+(C-BuyPrice)+"","")+
WriteIf(Buy  , "Total Profit/Loss for the Last trade Rs."+(SellPrice-C)+"",""));
//WriteIf(Long AND NOT Buy, "Trade : Long - Entry price Rs."+(BuyPrice),"")+
//WriteIf(shrt AND NOT Sell, "Trade : Short - Entry price Rs."+(SellPrice),"")+"\n"+
//WriteIf(Long AND NOT Buy, "Current Profit/Loss Rs."+(C-BuyPrice)+"","")+
//WriteIf(shrt AND NOT Sell, "Current Profit/Loss Rs."+(SellPrice-C)+"",""));
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                     
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                     
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
 
 
 
for(i=BarCount-1;i>1;i--)
{
if(Buy[i] == 1)
{
entry = H[i];
sig = "BUY";
sl = Ref(NW,-1);
tar1 = entry + (entry * .0050);
tar2 = entry + (entry * .0092);
tar3 = entry + (entry * .0179);
  
bars = i;
i = 0;
}
if(Sell[i] == 1)
{
sig = "SELL";
entry = L[i];
sl = Ref(NW,-1);
tar1 = entry - (entry * .0050);
tar2 = entry - (entry * .0112);
tar3 = entry - (entry * .0212);
  
  
bars = i;
i = 0;
}
}
Offset = 20;
Clr = IIf(sig == "BUY", colorLime, colorRed);
ssl = IIf(bars == BarCount-1, NW[BarCount-1], Ref(NW, -1));
sl = ssl[BarCount-1];
 
Plot(LineArray(bars-Offset, tar1, BarCount, tar1,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
Plot(LineArray(bars-Offset, tar2, BarCount, tar2,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
Plot(LineArray(bars-Offset, tar3, BarCount, tar3,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
 
 
 
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 = 290;
  
y = pxHeight;
  
GfxSelectPen( colorGreen, 1); // broader color
GfxRoundRect( x, y - 98, x2, y , 7, 7 ) ;
GfxTextOut( ( "SureShot Trading System"),13,y-100);
GfxTextOut( (" "),27,y-100);
GfxTextOut( ("Last " + sig + " Signal came " + (BarCount-bars-1) * Interval()/60 + " mins ago"), 13, y-80) ; // The text format location
GfxTextOut( ("" + WriteIf(sig =="BUY",sig + " @ ",sig + " @") + " : " + entry), 13, y-60);
GfxTextOut( ("Trailing SL : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"), 13, y-40);
/*GfxTextOut( ("TGT:1 : " + tar1), 13, y -80);
GfxTextOut( ("TGT:2 : " + tar2), 13,y-60);
GfxTextOut( ("TGT:3 : " + tar3), 13,y-40);*/
GfxTextOut( ("Current P/L : " + WriteVal(IIf(sig == "BUY",(C-entry),(entry-C)),2.2)), 13, y-22);
 
}
 
_SECTION_END();

_SECTION_END();
function ChandelierCl(AtrARRAY, AtrMult) {
    // Skip empty values
    i = 0;
    do {
        result[i] = Null;
        i++;
    }
    while( i < BarCount AND (IsNull(O[i]) OR IsNull(H[i]) OR IsNull(L[i]) OR IsNull(C[i]) ) );
    First = i;
 
if (i < BarCount - 1) {
    HHC[First]    = C[First];
    LLC[First]    = C[First];
 
    if (C[First + 1] > HHC[First]) {
        HHC[First + 1] = C[First + 1];
        LLC[First + 1] = LLC[First];
        result[First] = C[First] - AtrMult * AtrARRAY[First];
        iTrade = "LT";
    }
    else {
        if (C[First + 1] < LLC[First]) {
            HHC[First = 1] = HHC[First];
            LLC[First + 1] = LLC[First + 1];
            result[First] = C[First] + AtrMult * AtrARRAY[First];
            iTrade = "ST";
        }
        else {
            HHC[First + 1] = C[First + 1];
            LLC[First + 1] = C[First + 1];
            result[First] = C[First] - AtrMult * AtrARRAY[First];
            iTrade = "LT";
        }
    }
 
    for( i = First; i < BarCount; i++ ) {
        if (iTrade == "LT") {
            if (C[i] >= result[i-1]) {        // Long Trade is continuing
                if (C[i] > C[i-1]) {
                    HHC[i] = C[i];
                }
                else {
                    HHC[i] = HHC[i-1];
                }
                result[i] = HHC[i] - AtrMult * AtrARRAY[i];
                if (result[i] < result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                            // Long trade Exit triggered
                iTrade = "ST";
                LLC[i] = C[i];
                result[i] = C[i] + AtrMult * AtrARRAY[i];
            }
        }
        else {                               // Short trade
            if (C[i] <= result[i-1]) {
                if (C[i] <= C[i-1]) {        // Short Trade is continuing
                    LLC[i] = C[i];
                }
                else {
                    LLC[i] = LLC[i-1];
                }
                result[i] = LLC[i] + AtrMult * AtrARRAY[i];
                if (result[i] > result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                           //Short Trade Exit is triggered
                iTrade = "LT";
                HHC[i]  = C[i];
                result[i] = C[i] - AtrMult * AtrARRAY[i];
            }
        }
    }
}
return result;
}
 
function ChandelierHL(AtrARRAY, AtrMult) {
    // Skip empty values
    i = 0;
    do {
        result[i] = Null;
        i++;
    }
    while( i < BarCount AND (IsNull(O[i]) OR IsNull(H[i]) OR IsNull(L[i]) OR IsNull(C[i]) ) );
    First = i;
 
if (i < BarCount - 1) {
    HHC[First]    = H[First];
    LLC[First]    = L[First];
 
    if (H[First + 1] > HHC[First]) {
        HHC[First + 1] = H[First + 1];
        LLC[First + 1] = LLC[First];
        result[First] = H[First] - AtrMult * AtrARRAY[First];
        iTrade = "LT";
    }
    else {
        if (L[First + 1] < LLC[First]) {
            HHC[First = 1] = HHC[First];
            LLC[First + 1] = LLC[First + 1];
            result[First] = L[First] + AtrMult * AtrARRAY[First];
            iTrade = "ST";
        }
        else {
            HHC[First + 1] = C[First + 1];
            LLC[First + 1] = C[First + 1];
            result[First] = H[First] - AtrMult * AtrARRAY[First];
            iTrade = "LT";
        }
    }
 
    for( i = First; i < BarCount; i++ ) {
        if (iTrade == "LT") {
            if (C[i] >= result[i-1]) {        // Long Trade is continuing
                if (H[i] > H[i-1]) {
                    HHC[i] = H[i];
                }
                else {
                    HHC[i] = HHC[i-1];
                }
                result[i] = HHC[i] - AtrMult * AtrARRAY[i];
                if (result[i] < result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                            // Long trade Exit triggered
                iTrade = "ST";
                LLC[i] = L[i];
                result[i] = L[i] + AtrMult * AtrARRAY[i];
            }
        }
        else {                               // Short trade
            if (C[i] <= result[i-1]) {
                if (L[i] <= L[i-1]) {        // Short Trade is continuing
                    LLC[i] = L[i];
                }
                else {
                    LLC[i] = LLC[i-1];
                }
                result[i] = LLC[i] + AtrMult * AtrARRAY[i];
                if (result[i] > result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                           //Short Trade Exit is triggered
                iTrade = "LT";
                HHC[i]  = H[i];
                result[i] = H[i] - AtrMult * AtrARRAY[i];
            }
        }
    }
}
return result;
}

_SECTION_BEGIN("MACD Exploration");
r1 = Param( "Fast avg", 12, 2, 200, 1 );
r2 = Param( "Slow avg", 26, 2, 200, 1 );
r3 = Param( "Signal avg", 9, 2, 200, 1 );
Z=Param("zig",1,0,10,0.1);


Cond1 = Cross(MACD(r1,r2),Signal(r1,r2,r3));

Cond3 = Zig(C,z)>Ref(Zig(C,z),-4);
Buy = Cond1 AND Cond3;

Cond4 = Cross(Signal(r1,r2,r3),MACD(r1,r2));

Cond6 = Zig(C,z)<Ref(Zig(C,z),-4);
Sell = Cond4 AND Cond6;
Trigger = WriteIf(Buy, "Buy", "") + WriteIf(Sell, "Sell", "");

_N(Title = StrFormat("{{NAME}} {{DATE}} {{INTERVAL}}: O=%1.2f, H=%1.2f, L=%1.2f, C=%1.2f, V=%1.0f\n{{VALUES}}", O, H, L, C, V));

BG = IIf(Buy, colorPaleGreen, IIf(Sell, colorRose, colorDefault));
FG = IIf(Buy, colorDarkGreen, IIf(Sell, colorDarkRed, colorDefault));

if(Status("action") == actionIndicator)
{
Plot(C, "", colorGrey50, styleBar);
PlotShapes(IIf(Buy, shapeCircle, shapeNone),colorGreen, 0,L, Offset=-40);
PlotShapes(IIf(Sell, shapeCircle, shapeNone),colorRed, 0,H, Offset=40);
PlotShapes(shapeHollowDownArrow*Sell,colorYellow,0,SellPrice,-05);
PlotShapes(shapeHollowUpArrow*Buy,colorYellow,0,BuyPrice,-05);

}

_SECTION_BEGIN("MA1");
P = ParamField("Price field",-1);
Periods = Param("Periods",100, 2, 300, 1, 100 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorBlue ), ParamStyle("Style") ); 
_SECTION_END();


havind some error....
 

Nehal_s143

Well-Known Member
there is no error, may be you are using old version, your afl is working perfectly in ver 5.30

Code:
//--------------------------------------------------------------//
//  Kenzie SR System - 09/2010
//  Modified By Kenzie Sebastian ([email protected])
//  Modified By [email protected]
//
// - fixed the % change to display correctly
// - modified buy/sell signals display above/below candles
// - added Market trend S&P 500
// - change color of characters to display with black background.
//--------------------------------------------------------------
SetBarsRequired( 800, 0 );
 
GraphXSpace = 7;
SetChartOptions( 0, chartShowArrows | chartShowDates );
 
// set criteria to scan for big stock only;
BigStock = MA( V, 10 ) * MA( C, 10 ) > 1000000;
 
//---------------Color------------------------
per1 = 6;
per2 = 2;
Om = MA( O, per1 );
hm = MA( H, per1 );
lm = MA( L, per1 );
Cm = MA( C, per1 );
 
// 1. Heiken Ashi
HACLOSE = ( Om + Hm + Lm + Cm ) / 4;
HaOpen = AMA( Ref( HaClose,  -1 ),  0.5 );
HaHigh = Max( Hm,  Max( HaClose,  HaOpen ) );
HaLow = Min( Lm,  Min( HaClose,  HaOpen ) );
 
 
Of = MA( Haopen, per2 );
Cf = MA( Haclose, per2 );
Lf = IIf( haOpen < haClose, MA( Halow, per2 ), MA( Hahigh, per2 ) );
Hf = IIf( haOpen < haClose, MA( Hahigh, per2 ), MA( Halow, per2 ) );
//Color = IIf( Cf > Of, colorGreen, colorRed );
 
 
//----------------------------------------------------
 
TrailStop = HHV( C - 2 * ATR( 10 ), 15 );
ProfitTaker = EMA( H, 13 ) + 2 * ATR( 10 );
 
/* **********************************
Code to automatically identify pivots
********************************** */
 
// -- what will be our lookback range for the hh and ll?
farback = 140; //How Far back to go
nBars = 12; //Number of bars
 
// -- Create 0-initialized arrays the size of barcount
aHPivs = H - H;
aLPivs = L - L;
 
// -- More for future use, not necessary for basic plotting
aHPivHighs = H - H;
aLPivLows = L - L;
aHPivIdxs = H - H;
aLPivIdxs = L - L;
nHPivs = 0;
nLPivs = 0;
lastHPIdx = 0;
lastLPIdx = 0;
lastHPH = 0;
lastLPL = 0;
curPivBarIdx = 0;
 
// -- looking back from the current bar, how many bars
// back were the hhv and llv values of the previous
// n bars, etc.?
aHHVBars = HHVBars( H, nBars );
aLLVBars = LLVBars( L, nBars );
aHHV = HHV( H, nBars );
aLLV = LLV( L, nBars );
 
// -- Would like to set this up so pivots are calculated back from
// last visible bar to make it easy to "go back" and see the pivots
// this code would find. However, the first instance of
// _Trace output will show a value of 0
aVisBars = Status( "barvisible" );
nLastVisBar = LastValue( Highest( IIf( aVisBars, BarIndex(), 0 ) ) );
_TRACE( "Last visible bar: " + nLastVisBar );
 
// -- Initialize value of curTrend
curBar = ( BarCount - 1 );
curTrend = "";
 
if ( aLLVBars[curBar] < aHHVBars[curBar] )
{
    curTrend = "D";
}
else
{
    curTrend = "U";
}
 
// -- Loop through bars. Search for
// entirely array-based approach
// in future version
for ( i = 0; i < BarCount; i++ )
{
    curBar = ( BarCount - 1 ) - i;
// -- Have we identified a pivot? If trend is down...
 
    if ( aLLVBars[curBar] < aHHVBars[curBar] )
    {
// ... and had been up, this is a trend change
        if ( curTrend == "U" )
        {
            curTrend = "D";
// -- Capture pivot information
            curPivBarIdx = curBar - aLLVBars[curBar];
            aLPivs[curPivBarIdx] = 1;
            aLPivLows[nLPivs] = L[curPivBarIdx];
            aLPivIdxs[nLPivs] = curPivBarIdx;
            nLPivs++;
        }
 
// -- or current trend is up
    }
    else
    {
        if ( curTrend == "D" )
        {
            curTrend = "U";
            curPivBarIdx = curBar - aHHVBars[curBar];
            aHPivs[curPivBarIdx] = 1;
            aHPivHighs[nHPivs] = H[curPivBarIdx];
            aHPivIdxs[nHPivs] = curPivBarIdx;
            nHPivs++;
        }
 
// -- If curTrend is up...else...
    }
 
// -- loop through bars
}
 
// -- Basic attempt to add a pivot this logic may have missed
// -- OK, now I want to look at last two pivots. If the most
// recent low pivot is after the last high, I could
// still have a high pivot that I didn't catch
// -- Start at last bar
curBar = ( BarCount - 1 );
 
candIdx = 0;
 
candPrc = 0;
 
lastLPIdx = aLPivIdxs[0];
 
lastLPL = aLPivLows[0];
 
lastHPIdx = aHPivIdxs[0];
 
lastHPH = aHPivHighs[0];
 
if ( lastLPIdx > lastHPIdx )
{
// -- Bar and price info for candidate pivot
    candIdx = curBar - aHHVBars[curBar];
    candPrc = aHHV[curBar];
 
    if (
        lastHPH < candPrc AND
        candIdx > lastLPIdx AND
        candIdx < curBar )
    {
// -- OK, we'll add this as a pivot...
        aHPivs[candIdx] = 1;
// ...and then rearrange elements in the
// pivot information arrays
 
        for ( j = 0; j < nHPivs; j++ )
        {
            aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs- ( j+1 )];
            aHPivIdxs[nHPivs-j] = aHPivIdxs[nHPivs-( j+1 )];
        }
 
        aHPivHighs[0] = candPrc ;
 
        aHPivIdxs[0] = candIdx;
        nHPivs++;
    }
}
else
{
// -- Bar and price info for candidate pivot
    candIdx = curBar - aLLVBars[curBar];
    candPrc = aLLV[curBar];
 
    if (
        lastLPL > candPrc AND
        candIdx > lastHPIdx AND
        candIdx < curBar )
    {
// -- OK, we'll add this as a pivot...
        aLPivs[candIdx] = 1;
// ...and then rearrange elements in the
// pivot information arrays
 
        for ( j = 0; j < nLPivs; j++ )
        {
            aLPivLows[nLPivs-j] = aLPivLows[nLPivs-( j+1 )];
            aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-( j+1 )];
        }
 
        aLPivLows[0] = candPrc;
 
        aLPivIdxs[0] = candIdx;
        nLPivs++;
    }
}
 
//============== EXPLORATION ==============
Buy = Cover = BigStock AND aLPivs == 1;
 
Sell = Short = BigStock AND aHPivs == 1;
 
SellPrice = ValueWhen( Sell, C, 1 );
 
BuyPrice = ValueWhen( Buy, C, 1 );
 
Long = Flip( Buy, Sell );
 
Shrt = Flip( Sell, Buy );
 
//============== Plot price ==============
n = 15;
 
a =  C > ( MA( H, n ) + MA( L, n ) ) / 2;// then Buy next bar at market;
 
b = C < ( MA( H, n ) + MA( L, n ) ) / 2;// then Sell Short next bar at market;
 
state = IIf( BarsSince( a ) < BarsSince( b ), 1, 0 );
 
Longs = state == 1;
 
shorts = state == 0;
 
//Chart
Colorbar = IIf( Longs, colorGreen, IIf( Shorts, colorRed, colorGrey40 ) );
 
Plot( C, "Close", colorbar, styleCandle = 64 | styleNoTitle );
 
//============== Plot Shape ==============
PlotShapes( IIf( aHPivs == 1, shapeDownArrow, shapeNone ), colorOrange, 0, High, Offset = -45 );
 
PlotShapes( IIf( aLPivs == 1, shapeUpArrow , shapeNone ), colorLime, 0, Low, Offset = -20 );
PlotShapes( IIf(Buy, shapeSmallCircle, shapeNone),colorDarkGreen, 0, BuyPrice, Offset = -15 );
PlotShapes( IIf(Sell, shapeSmallCircle, shapeNone),colorRed, 0 ,SellPrice,  Offset = 45  );
FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status("LastVisibleBar");
for( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++)
{
if( Buy[b] ) PlotText("\n\n\n\n Buy\n "+NumToStr(BuyPrice[b],1.2),b,BuyPrice[b],colorDarkGreen);
else if( Sell[b] ) PlotText("Sell  "+NumToStr(SellPrice[b], 1.2),b,SellPrice[b],colorRed);
}
 
//============== EMA(13) ==============
Plot( EMA( C, 13 ), "" , colorSkyblue + styleLine + styleNoRescale );
 
//============== TRENDING ==============
DTL = 150; // DTL = Define Trend Long
 
DTM = 70;   // DTM = Define Trend Medium
 
DTS = 14;  // DTS = Define Trend Short
 
TL = LinRegSlope( MA( C, DTL ), 2 );     // TL = Trend Long
 
TM = LinRegSlope( MA( C, DTM ), 2 );  // TM = Trend Medium
 
TS = LinRegSlope( MA( C, DTS ), 2 );  // TS = Trend Short
 
TLL = IIf( LinRegSlope( MA( C, DTL ), 2 ) > 0, True, False );
 
TMM = IIf( LinRegSlope( MA( C, DTM ), 2 ) > 0, True, False );
 
TSS = IIf( LinRegSlope( MA( C, DTS ), 2 ) > 0, True, False );
 
//============== VOLUME ==============
Vlp = 30; //Volume lookback period
 
Vrg = MA( V, Vlp );
 
St = StDev( Vrg, Vlp );
 
Vp3 = Vrg + 3 * st;
 
Vp2 = Vrg + 2 * st;
 
Vp1 = Vrg + 1 * st;
 
Vn1 = Vrg - 1 * st;
 
Vn2 = Vrg - 2 * st;
 
//============== WILLIAM'S %R ==============
WR = ( ( HHV( H, 14 ) - C ) / ( HHV ( H, 14 ) - LLV ( L, 14 ) ) ) * -100;
 
//============== A/D ==============
TRH = IIf( Ref( C, -1 ) > H, Ref( C, -1 ), H );
 
TRL = IIf( Ref( C, -1 ) < L, Ref( C, -1 ), L );
 
ad = IIf( C > Ref( C, -1 ), C - TRL, IIf( C < Ref( C, -1 ), C - TRH, 0 ) );
 
WAD = Cum( ad );
 
wu = wad > Ref( wad, -1 );
 
wd = wad < Ref( wad, -1 );
 
//============== MACD ==============
MB = Cross ( MACD(), Signal() );
 
MS = Cross( Signal(), MACD() );
 
MB = ExRem( MB, MS );
 
MS = ExRem( MS, MB );
 
MB1 = MACD() > Signal();
 
MS1 = MACD() < Signal();
 
//============== STOCH ==============
StochKval = StochK( 10, 5 );
 
StochDval = StochD( 10, 5, 5 );
 
StochBuy = Cross( StochK( 10, 5 ), StochD( 10, 5, 5 ) );
 
StochSell = Cross ( StochD( 10, 5, 5 ), StochK( 10, 5 ) );
 
StBuy = StochK( 10, 5 ) > StochD( 10, 5, 5 );
 
StSell = StochK( 10, 5 ) < StochD( 10, 5, 5 );
 
//============== ADX ==============
adxBuy =  Cross( PDI( 14 ), MDI( 14 ) );
 
adxSell = Cross( MDI( 14 ), PDI( 14 ) );
 
adxBuy = ExRem( adxBuy, adxSell );
 
adxSell = ExRem( adxSell, adxBuy );
 
adxbuy1 = PDI( 14 ) > MDI( 14 );
 
adxsell1 = MDI( 14 ) > PDI( 14 );
 
//==============Zero Lag TMA ==============
function ZeroLagTEMA( array, period )
{
    TMA1 = TEMA( array, period );
    TMA2 = TEMA( TMA1, period );
    Diff = TMA1 - TMA2;
    return TMA1 + Diff ;
}
 
haClose = ( haClose + haOpen + haHigh + haLow ) / 4;
 
periodtm = 55;
ZLHa = ZeroLagTEMA( haClose, periodtm );
ZLTyp = ZeroLagTEMA( Avg, periodtm );
TMBuy = Cross( ZLTyp, ZLHa );
TMSell = Cross( ZLHa, ZLTyp );
TMBuy1 = ZLTyp > ZLHa ;
TMSell1 = ZLHa > ZLTyp ;
 
//============== ZLW ==============
R = ( ( HHV( H, 14 ) - C ) / ( HHV ( H, 14 ) - LLV ( L, 14 ) ) ) * -100;
MaxGraph = 10;
PeriodZ = 10;
EMA1 = EMA( R, PeriodZ );
EMA2 = EMA( EMA1, 5 );
Difference = EMA1 - EMA2;
ZeroLagEMA = EMA1 + Difference;
PR = 100 - abs( ZeroLagEMA );
MoveAvg = MA( PR, 5 );
ZBuy = Cross( PR, moveAvg ) AND PR < 30;
ZSell = Cross( moveAvg, PR ) AND PR > 70;
ZBuy1 = PR >= MoveAvg AND PR >= Ref( PR, -1 ) ;
ZSell1 = ( PR < MoveAvg ) OR PR >= MoveAvg AND PR < Ref( PR, -1 ) ;
 
//============== RS ==============
p = ( H + L + C ) / 3;
r1 = ( 2 * p ) - L;
s1 = ( 2 * p ) - H;
r2 = p + ( r1 - s1 );
s2 = p - ( r2 - s1 );
R3 = P + ( R2 - S2 );
S3 = P - ( R3 - S2 );
 
//============== IBUY ==============
Ibuy =  Cross( RSI( 14 ), EMA( RSI( 14 ), 9 ) );
Isell = Cross( EMA( RSI( 14 ), 9 ), RSI( 14 ) );
Ibuy = ExRem( Ibuy, ISell );
Isell = ExRem( ISell, Ibuy );
BlRSI = RSI( 14 ) > EMA( RSI( 14 ), 9 );
BrRSI = RSI( 14 ) < EMA( RSI( 14 ), 9 );
 
 
//=================Trend & Signals & Market Index ===============================
/// Please replace "00DSEGEN" with your market index ticker and activate the codes
 
/// Market Bull Bear
 
Cg = Foreign("^GSPC", "C");
Cgo= Ref(Cg,-1);
 
//Longterm Bullish or Bearish
Bullg = Cg > WMA(Cg,200);
Bearg= Cg <WMA(Cg,200);
 
//Midterm Bullish or Bearish
mBullg = Cg >WMA(Cg,50);
mBearg= Cg <WMA(Cg,50);
 
//Shortterm Bullish or Bearish
sBullg = Cg >WMA(Cg,15);
sBearg= Cg <WMA(Cg,15);
////////////////////////////////
 
 
 
xChange1=Cg - Ref(Cg,-1);
Change1 = StrFormat("%1.2f% ",xChange1);    
barche1= xChange1>=0;  
Comche1= xChange1<0;   
xperchange1 = xChange1/100;
perchange1 = StrFormat("%1.2f% ",xperchange1);   
positivechange1 = xperchange1>0;  
negativechange1 = xperchange1<0;
 
//=================Trend & Signals & Market Index END===============================
 
 
 
//============== TITLE ==============

_SECTION_BEGIN("Volatility 2");
// Just Re-share
// E.M.Pottasch, Jul 2010
// from Metastock formula, link: http://stocata.org/metastock/stop_trail_atr.html
// added separate parameters for upward and downward market environment

function vstop_func(trBull,trBear)
{
	trailArray[ 0 ] = C[ 0 ]; // initialize
	for( i = 1; i < BarCount; i++ )
	{
		prev = trailArray[ i - 1 ];
 
		if (C[ i ] > prev AND C[ i - 1 ] > prev)
		{
			trailArray[ i ] = Max(prev,C[ i ] - trBull[ i ]);
		}
		else if (C[ i ] < prev AND C[ i - 1 ] < prev)
		{
			trailArray[ i ] = Min(prev,C[ i ] + trBear[ i ]);
		}
		else if (C[ i ] > prev)
		{
			trailArray[ i ] = C[ i ] - trBull[ i ];
		}
		else
		{
			trailArray[ i ] = C[ i ] + trBear[ i ];	
		}
	}
	return trailArray;
}

per = Param("per",20, 1, 150, 1);
multBull = Param("multBull",2, 1, 4, 0.05);
multBear = Param("multBear",2, 1, 4, 0.05);

trBull = multBull * ATR(per);
trBear = multBear * ATR(per);

trailArray = vstop_func(trBull,trBear);

SetChartBkColor( ParamColor("ColorBG", ColorRGB( 0, 0, 0 ) ) );
GraphXSpace = 5;
SetChartOptions(0, chartShowDates);
Plot(IIf(trailArray > C,trailArray,Null),"\ntrailShort",ParamColor("ColorTrailShort",ColorRGB(255,0,0)),styleStaircase);
Plot(IIf(trailArray < C,trailArray,Null),"\ntrailLong",ParamColor("ColorTrailLong",ColorRGB(0,255,0)),styleStaircase);
Plot( C, "\nCandle",colorWhite, styleCandle );
_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("KPL Swing with N&M Swing");
SetBarsRequired(200,0);
 
GraphXSpace = 5;
SetChartOptions(0,chartShowArrows|chartShowDates);
k =  Optimize("K",Param("K",3,0.25,5,0.25),0.25,5,0.25);
Per= Optimize("atr",Param("atr",10,3,20,1),3,20,1);
HACLOSE=(O+H+L+C)/4;
HaOpen = AMA( Ref( HaClose,  -1 ),  0.5 );
HaHigh = Max( H,  Max( HaClose,  HaOpen ) );
HaLow = Min( L,  Min( HaClose,  HaOpen ) );
PlotOHLC( HaOpen, HaHigh, HaLow, HaClose, "" + Name(), colorBlack, styleCandle | styleNoLabel );
j=Haclose;
 
//=======================================================================================================================
//=========================Indicator==============================================================================================
f=ATR(15);
 
rfsctor = WMA(H-L, Per);
 
revers = k * rfsctor;
 
Trend = 1; 
NW[0] = 0; 
NW[BarCount-1] = Null; 
 
 
for(i = 1; i < BarCount-1; i++)
{
 if(Trend[i-1] == 1)               
 {
  if(j[i] < NW[i-1])                
  {
   Trend[i] = -1;                  
   NW[i] = j[i] + Revers[i];       
  }
  else                             
  {
   Trend[i] = 1;
   if((j[i] - Revers[i]) > NW[i-1])
   {
    NW[i] = j[i] - Revers[i];
   }
   else
   {
    NW[i] = NW[i-1];
   }
  }
 }
 if(Trend[i-1] == -1)              
 {
  if(j[i] > NW[i-1])               
  {
   Trend[i] = 1;                   
   NW[i] = j[i] - Revers[i];       
  }
  else                             
  {
   Trend[i] = -1;
   if((j[i] + Revers[i]) < NW[i-1])
   {
    NW[i] = j[i] + Revers[i];
   }
   else
   {
    NW[i] = NW[i-1];
   }
  }
 }
}
 
//===============system================
 
Plot(NW, "", IIf(Trend == 1, 27, 4), 4);
Buy=NW<HACLOSE;
Sell=NW>HACLOSE;
SellPrice=ValueWhen(Sell,C,1);
BuyPrice=ValueWhen(Buy,C,1);
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy );
 
Short=Sell;
Cover=Buy;
 
 
NMAB= NW<HACLOSE;
NMAS= NW>HACLOSE;
AlertIf( Buy , "SOUND C://Windows//Media//chimes.wav", "Audio alert", 2 );
AlertIf( Sell , "SOUND C://Windows//Media//alert.wav", "Audio alert", 2 );
 
NMA_status= WriteIf(NMAB, "BUY MODE", WriteIf(NMAS, "SELL MODE", "NEUTRAL"));
NMAS_Col=IIf(NMAB, colorGreen, IIf(NMAS, colorRed, colorLightGrey));
Filter=1;
AddColumn( NW[BarCount-1], "SAR", 1.2 );
AddColumn( HACLOSE, "HA Close", 1.2 );
AddColumn( C, "Close", 1.2 );
AddTextColumn(NMA_status, "MODE", 1, colorWhite, NMAS_Col);
AddColumn( DateTime(), "Date / Time", formatDateTime );
_SECTION_END();
//=================TITLE================================================================================================
_SECTION_BEGIN("Title");
if( Status("action") == actionIndicator )
(
Title = EncodeColor(colorWhite)+ "SureShot trading 3 10" + " - " +  Name() + " - " + EncodeColor(colorRed)+ Interval(2) + EncodeColor(colorWhite) +
 "  - " + Date() +" - "+"\n" +EncodeColor(colorRed) +"Op-"+O+"  "+"Hi-"+H+"  "+"Lo-"+L+"  "+
"Cl-"+C+"  "+ "Vol= "+ WriteVal(V)+"\n"+
EncodeColor(colorLime)+
WriteIf (Buy , " GO LONG / Reverse Signal at "+C+"  ","")+
WriteIf (Sell , " EXIT LONG / Reverse Signal at "+C+"  ","")+"\n"+EncodeColor(colorWhite)+
WriteIf(Sell , "Total Profit/Loss for the Last Trade Rs."+(C-BuyPrice)+"","")+
WriteIf(Buy  , "Total Profit/Loss for the Last trade Rs."+(SellPrice-C)+"",""));
//WriteIf(Long AND NOT Buy, "Trade : Long - Entry price Rs."+(BuyPrice),"")+
//WriteIf(shrt AND NOT Sell, "Trade : Short - Entry price Rs."+(SellPrice),"")+"\n"+
//WriteIf(Long AND NOT Buy, "Current Profit/Loss Rs."+(C-BuyPrice)+"","")+
//WriteIf(shrt AND NOT Sell, "Current Profit/Loss Rs."+(SellPrice-C)+"",""));
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                     
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                     
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
 
 
 
for(i=BarCount-1;i>1;i--)
{
if(Buy[i] == 1)
{
entry = H[i];
sig = "BUY";
sl = Ref(NW,-1);
tar1 = entry + (entry * .0050);
tar2 = entry + (entry * .0092);
tar3 = entry + (entry * .0179);
  
bars = i;
i = 0;
}
if(Sell[i] == 1)
{
sig = "SELL";
entry = L[i];
sl = Ref(NW,-1);
tar1 = entry - (entry * .0050);
tar2 = entry - (entry * .0112);
tar3 = entry - (entry * .0212);
  
  
bars = i;
i = 0;
}
}
Offset = 20;
Clr = IIf(sig == "BUY", colorLime, colorRed);
ssl = IIf(bars == BarCount-1, NW[BarCount-1], Ref(NW, -1));
sl = ssl[BarCount-1];
 
Plot(LineArray(bars-Offset, tar1, BarCount, tar1,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
Plot(LineArray(bars-Offset, tar2, BarCount, tar2,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
Plot(LineArray(bars-Offset, tar3, BarCount, tar3,1), "", Clr, styleLine|styleDots, Null, Null, Offset);
 
 
 
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 = 290;
  
y = pxHeight;
  
GfxSelectPen( colorGreen, 1); // broader color
GfxRoundRect( x, y - 98, x2, y , 7, 7 ) ;
GfxTextOut( ( "SureShot Trading System"),13,y-100);
GfxTextOut( (" "),27,y-100);
GfxTextOut( ("Last " + sig + " Signal came " + (BarCount-bars-1) * Interval()/60 + " mins ago"), 13, y-80) ; // The text format location
GfxTextOut( ("" + WriteIf(sig =="BUY",sig + " @ ",sig + " @") + " : " + entry), 13, y-60);
GfxTextOut( ("Trailing SL : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"), 13, y-40);
/*GfxTextOut( ("TGT:1 : " + tar1), 13, y -80);
GfxTextOut( ("TGT:2 : " + tar2), 13,y-60);
GfxTextOut( ("TGT:3 : " + tar3), 13,y-40);*/
GfxTextOut( ("Current P/L : " + WriteVal(IIf(sig == "BUY",(C-entry),(entry-C)),2.2)), 13, y-22);
 
}
 
_SECTION_END();

_SECTION_END();
function ChandelierCl(AtrARRAY, AtrMult) {
    // Skip empty values
    i = 0;
    do {
        result[i] = Null;
        i++;
    }
    while( i < BarCount AND (IsNull(O[i]) OR IsNull(H[i]) OR IsNull(L[i]) OR IsNull(C[i]) ) );
    First = i;
 
if (i < BarCount - 1) {
    HHC[First]    = C[First];
    LLC[First]    = C[First];
 
    if (C[First + 1] > HHC[First]) {
        HHC[First + 1] = C[First + 1];
        LLC[First + 1] = LLC[First];
        result[First] = C[First] - AtrMult * AtrARRAY[First];
        iTrade = "LT";
    }
    else {
        if (C[First + 1] < LLC[First]) {
            HHC[First = 1] = HHC[First];
            LLC[First + 1] = LLC[First + 1];
            result[First] = C[First] + AtrMult * AtrARRAY[First];
            iTrade = "ST";
        }
        else {
            HHC[First + 1] = C[First + 1];
            LLC[First + 1] = C[First + 1];
            result[First] = C[First] - AtrMult * AtrARRAY[First];
            iTrade = "LT";
        }
    }
 
    for( i = First; i < BarCount; i++ ) {
        if (iTrade == "LT") {
            if (C[i] >= result[i-1]) {        // Long Trade is continuing
                if (C[i] > C[i-1]) {
                    HHC[i] = C[i];
                }
                else {
                    HHC[i] = HHC[i-1];
                }
                result[i] = HHC[i] - AtrMult * AtrARRAY[i];
                if (result[i] < result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                            // Long trade Exit triggered
                iTrade = "ST";
                LLC[i] = C[i];
                result[i] = C[i] + AtrMult * AtrARRAY[i];
            }
        }
        else {                               // Short trade
            if (C[i] <= result[i-1]) {
                if (C[i] <= C[i-1]) {        // Short Trade is continuing
                    LLC[i] = C[i];
                }
                else {
                    LLC[i] = LLC[i-1];
                }
                result[i] = LLC[i] + AtrMult * AtrARRAY[i];
                if (result[i] > result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                           //Short Trade Exit is triggered
                iTrade = "LT";
                HHC[i]  = C[i];
                result[i] = C[i] - AtrMult * AtrARRAY[i];
            }
        }
    }
}
return result;
}
 
function ChandelierHL(AtrARRAY, AtrMult) {
    // Skip empty values
    i = 0;
    do {
        result[i] = Null;
        i++;
    }
    while( i < BarCount AND (IsNull(O[i]) OR IsNull(H[i]) OR IsNull(L[i]) OR IsNull(C[i]) ) );
    First = i;
 
if (i < BarCount - 1) {
    HHC[First]    = H[First];
    LLC[First]    = L[First];
 
    if (H[First + 1] > HHC[First]) {
        HHC[First + 1] = H[First + 1];
        LLC[First + 1] = LLC[First];
        result[First] = H[First] - AtrMult * AtrARRAY[First];
        iTrade = "LT";
    }
    else {
        if (L[First + 1] < LLC[First]) {
            HHC[First = 1] = HHC[First];
            LLC[First + 1] = LLC[First + 1];
            result[First] = L[First] + AtrMult * AtrARRAY[First];
            iTrade = "ST";
        }
        else {
            HHC[First + 1] = C[First + 1];
            LLC[First + 1] = C[First + 1];
            result[First] = H[First] - AtrMult * AtrARRAY[First];
            iTrade = "LT";
        }
    }
 
    for( i = First; i < BarCount; i++ ) {
        if (iTrade == "LT") {
            if (C[i] >= result[i-1]) {        // Long Trade is continuing
                if (H[i] > H[i-1]) {
                    HHC[i] = H[i];
                }
                else {
                    HHC[i] = HHC[i-1];
                }
                result[i] = HHC[i] - AtrMult * AtrARRAY[i];
                if (result[i] < result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                            // Long trade Exit triggered
                iTrade = "ST";
                LLC[i] = L[i];
                result[i] = L[i] + AtrMult * AtrARRAY[i];
            }
        }
        else {                               // Short trade
            if (C[i] <= result[i-1]) {
                if (L[i] <= L[i-1]) {        // Short Trade is continuing
                    LLC[i] = L[i];
                }
                else {
                    LLC[i] = LLC[i-1];
                }
                result[i] = LLC[i] + AtrMult * AtrARRAY[i];
                if (result[i] > result[i-1]) {
                    result[i] = result[i-1];
                }
            }
            else {                           //Short Trade Exit is triggered
                iTrade = "LT";
                HHC[i]  = H[i];
                result[i] = H[i] - AtrMult * AtrARRAY[i];
            }
        }
    }
}
return result;
}

_SECTION_BEGIN("MACD Exploration");
r1 = Param( "Fast avg", 12, 2, 200, 1 );
r2 = Param( "Slow avg", 26, 2, 200, 1 );
r3 = Param( "Signal avg", 9, 2, 200, 1 );
Z=Param("zig",1,0,10,0.1);


Cond1 = Cross(MACD(r1,r2),Signal(r1,r2,r3));

Cond3 = Zig(C,z)>Ref(Zig(C,z),-4);
Buy = Cond1 AND Cond3;

Cond4 = Cross(Signal(r1,r2,r3),MACD(r1,r2));

Cond6 = Zig(C,z)<Ref(Zig(C,z),-4);
Sell = Cond4 AND Cond6;
Trigger = WriteIf(Buy, "Buy", "") + WriteIf(Sell, "Sell", "");

_N(Title = StrFormat("{{NAME}} {{DATE}} {{INTERVAL}}: O=%1.2f, H=%1.2f, L=%1.2f, C=%1.2f, V=%1.0f\n{{VALUES}}", O, H, L, C, V));

BG = IIf(Buy, colorPaleGreen, IIf(Sell, colorRose, colorDefault));
FG = IIf(Buy, colorDarkGreen, IIf(Sell, colorDarkRed, colorDefault));

if(Status("action") == actionIndicator)
{
Plot(C, "", colorGrey50, styleBar);
PlotShapes(IIf(Buy, shapeCircle, shapeNone),colorGreen, 0,L, Offset=-40);
PlotShapes(IIf(Sell, shapeCircle, shapeNone),colorRed, 0,H, Offset=40);
PlotShapes(shapeHollowDownArrow*Sell,colorYellow,0,SellPrice,-05);
PlotShapes(shapeHollowUpArrow*Buy,colorYellow,0,BuyPrice,-05);

}

_SECTION_BEGIN("MA1");
P = ParamField("Price field",-1);
Periods = Param("Periods",100, 2, 300, 1, 100 );
Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorBlue ), ParamStyle("Style") ); 
_SECTION_END();


havind some error....
 

Cubt

Algo Trader
Guys,
Is there any AFL with buy sell signal based on support and resistance? ? I need one for backtesting. Would be really helpful if someone can share it.
 
1) BUY CONDITION: Green Arrow when MA (Close,50) crosses MA (Close,100) from below & goes up.


2) SHORT CONDITION: Red Arrow when MA (Close,100) crosses MA (Close,50) from below & goes up.


3) BUY EXECUTION: Buy at open of next candle after point 1 candle ; TARGET: 50 points; SL: 25 points

4) SHORT EXECUTION: Short at open of next candle after point 2 candle; TARGET: 50 points; SL 25 points

5) Draws automatically HORIZONTAL LINES for TARGET & SL with respective values as soon as BUY /SHORT is triggered.

6) Shows BUY@ PRICE ; SHORT@ PRICE on chart above candles of points 3 & 4.

7) VOICE ALERTS as soon as point 1 & 2 are met.

8) VOICE ALERTS as soon as TARGET or SL is hit.

9) POP-UPS as soon as point 1 & 2 are met.

10) POP-UPS as soon as point TARGET / SL is hit.

11) Back testing facility.

12) Scanning facility.

Thanks a lot.
Hello Ethan

Maybe not many are interested in spending time on it as it is a very basic system and if one searches can be freely found on internet.

I am posting a basic implementation of it . . . have not coded for alerts and popups . . .

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", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

_SECTION_BEGIN("MA Xross Sys");
//Optimization parameters for MA
P1 = Optimize("Period 1",Param("Period 1", 20, 2, 300, 1), 10, 300, 10);
P2 = Optimize("Period 2",Param("Period 2", 60, 2, 300, 1), 20, 300, 10);
A=MA(Close,P1);		B=MA(Close,P2);

//Plot MAs
Plot(A,"\nMA1",ParamColor("Color1", colorGreen),ParamStyle("Style1") ); 
Plot(B,"MA2", ParamColor("Color2", colorYellow), ParamStyle("Style2") ); 

//MA-Cross System for Backtest 
Buy = Cross(A,B); 		Sell = Cross(B,A);
Buy = ExRem(Buy,Sell);	Sell = ExRem(Sell,Buy);
Short = Sell; 			Cover = Buy;
UP = Flip(Buy,Sell);		DN = Flip(Sell,Buy);
//Arrows
PlotShapes(Buy+2*Sell, IIf(Buy,colorGreen,colorRed), 0,IIf(Buy,L,H));

//Trade Action on next bar open after MA-Cross
SetTradeDelays(1, 1, 1, 1); 
BuyPrice   = Open;	SellPrice  = Open;
CoverPrice = Open;	ShortPrice = Open;

//Position sizing
SetPositionSize(1,4);

//Stops
ApplyStop(0,2,25); // Stop Loss
ApplyStop(1,2,50); //Profit Stop

//Plots for TGT & Stops
Long  = ValueWhen(Ref(Buy,-1),O);
Shrt = ValueWhen(Ref(Sell,-1),O);

Plot(IIf(UP,Long,Shrt),"ENTRY_PRICE",colorLightGrey,styleStaircase|styleNoRescale|styleDashed);

Plot(IIf(UP,Long+50,Null),"\nLong_TGT",colorBlueGrey,styleStaircase|styleNoRescale);
Plot(IIf(UP,Long-25,Null),"Long_SL",   colorLime,    styleStaircase|styleNoRescale);

Plot(IIf(DN,Shrt-50,Null),"\nShort_TGT",colorRed, styleStaircase|styleNoRescale);
Plot(IIf(DN,Shrt+25,Null),"Short_SL",   colorBlue,styleStaircase|styleNoRescale|styleDashed);

/*
Plot(SelectedValue(IIf(UP,Long-25,Null)),"Long_SL",colorRed,styleStaircase|styleNoRescale,0,0,10);
Plot(SelectedValue(IIf(UP,Long+50,Null)),"Long_TGT",colorBlue,styleStaircase|styleNoRescale,0,0,10);
Plot(SelectedValue(IIf(DN,Shrt+25,Null)),"Short_SL",colorBlue,styleStaircase,0,0,10);
Plot(SelectedValue(IIf(DN,Shrt-50,Null)),"Short_TGT",colorRed,styleStaircase,0,0,10);
*/

//exploration
Filter = Buy OR Sell;
_SECTION_END();
I have implemented the basic functionality and commented the code, as the spirit of this thread is learning to do your own code . . .
now one can easily modify this template and use it for other entry / exit strategies.


:) Happy
 

Nehal_s143

Well-Known Member
hi

you can try this

_SECTION_BEGIN("EMA CROSSOVER CHART");
LongPer = Param("Long Period", 50, 30, 100, 5);
ShortPer = Param("Short Period", 100, 30, 100, 5);
LongMA = EMA(C, LongPer);
ShortMA = EMA(C, ShortPer);
LastHigh = HHV(H, LongPer);
Plot(LongMA, " EMA(C, " + WriteVal(LongPer, 1) + ")", colorBrightGreen, styleLine);
Plot(ShortMA, " EMA(C, " + WriteVal(ShortPer, 1) + ")", colorRed, styleLine);
Buy = Cross(LongMA, ShortMA);
Sell = Cross(ShortMA, LongMA);
PlotShapes(shapeUpArrow * Buy, colorBrightGreen, 0, L, - 10);
PlotShapes(shapeDownArrow * Sell, colorRed, 0, H, - 10);
_SECTION_END();


 

Similar threads