Simple Coding Help - No Promise.

vijkris

Learner and Follower
Happy Ji,can you re-code this code by Xray bhai for lower version ami-

http://www.traderji.com/advanced-tr...le-new-wave-market-picture-3.html#post1170851

I pmed Vijkris also regarding this.
Wisp bro's post:
I have no idea whether it works or not..

try this - it was shared by XRAY bro at some point

Code:
_SECTION_BEGIN("MarketProfile");
//------------------------------------------------------------------------------
//
// Formula Name: Market Profile
//
// Use with 5/15min chart
// Originial - From AFL library
// Edited by - Milind / KAKA

//Market Profile 10/12/2009


//------------------------------------------------------------------------------
// This is a modified version of afl date 09/19/2009 as listed above
// Contains a couple changes:
// 1) a more correct (but not complete) calculation of POC.
// 2) attempt to avoid the out of bound runtime error that
// sometimes occurs. See below:
//
// Here are changes to emulate the arrays x[] and total[] so
// that the array size are not limited by Barcount.
// Now one probably should not get the out of bound error even
// if the density or ticksize is smaller. Of course, there will
// be more overhead in calculation.
// johncw 20091010
// Wrapper start
_N(VarKey = NumToStr(GetChartID(), 1.0, False) + "_");
_N(VarTotal = "V_T" + VarKey);
_N(VarX = "V_x" + VarKey);

function L_StaticVarSet(L_name, L_value)
{
local L_name, L_value;
StaticVarSet(L_name + VarKey, L_value);
}

function L_StaticVarGet(L_name)
{
local L_name;
return(StaticVarGet(L_name + VarKey));
}

function x_g(L_idx)
{
local L_idx;
return VarGet(VarX + L_idx);
}

function x_s(L_idx, L_value)
{
local L_idx, L_value;
VarSet(VarX + L_idx, L_value);
}

function total_g(L_idx)
{
local L_idx;
return VarGet(VarTotal+L_idx);
}

function total_s(L_idx, L_value)
{
local L_idx, L_value, L_name;
VarSet(VarTotal+L_idx, L_value);
}
// Wrapper end
//------------------------------------------------------------------------------


PlotOHLC(O,H,L,C,"Price",IIf(C>O,colorGreen,colorRed),styleCandle);


EnMP2= ParamList("MarketProfile","Solid|Lines|Letters");
styleLines = ParamStyle("Style", styleLine, maskAll);

Type=ParamList("Type","Price Profile|Volume Profile");
Period= ParamList("Base","Hourly|Daily|Weekly|Monthly",1);

Den = Param("Density", 1, 0.25, 100, 0.25); // Resolution in terms of $
percent=Param("Value Area", 70, 1, 100, 1);
ViewTPOCount= ParamToggle("Show TPO Count", "No|Yes",1);
Viewvalues= ParamToggle("Show Values", "No|Yes",1);

ViewPREVIOUS = ParamToggle("Previous Values", "No|Yes",1);

ViewVALVAH = ParamToggle("Show VAL VAH Line", "No|Yes",1);
Viewfill = ParamToggle("Show VA Fill", "No|Yes",0);
Colorpoc=ParamColor("Color POC", colorYellow);
Colorfill=ParamColor("Color Fill", ColorRGB(20,40,60));


EnIB = ParamToggle("Show Initial Balance", "Yes|No");
IBBars = Param("Initial Balance Bars", 2, 0, 10, 1);

if(Period=="Daily"){
BarsInDay = BarsSince(Day() != Ref(Day(), -1));
Bot = TimeFrameGetPrice("L", inDaily, 0);
Top = TimeFrameGetPrice("H", inDaily, 0);
Vol = TimeFrameGetPrice("V", inDaily, 0);
}

if(Period=="Hourly"){
BarsInDay = BarsSince(Minute() != Ref(Minute(), -1));
Bot = TimeFrameGetPrice("L", in5Minute, 0);
Top = TimeFrameGetPrice("H", in5Minute, 0);
Vol = TimeFrameGetPrice("V", in5Minute, 0);
}

if(Period=="Weekly"){
BarsInDay = BarsSince(DayOfWeek() < Ref( DayOfWeek(), -1 ));
Bot = TimeFrameGetPrice("L", inWeekly, 0);
Top = TimeFrameGetPrice("H", inWeekly, 0);
Vol = TimeFrameGetPrice("V", inWeekly, 0);
}

if(Period=="Monthly" ){
BarsInDay = BarsSince(Month() != Ref(Month(), -1));
Bot = TimeFrameGetPrice("L", inMonthly, 0);
Top = TimeFrameGetPrice("H", inMonthly, 0);
Vol = TimeFrameGetPrice("V", inMonthly, 0);
}

CurTop = HHV(H,BarsInDay+1);
Curbot = LLV(L,BarsInDay+1);
Range = Highest(Top-Bot);
TodayRange = Top - Bot;

AveRange = Sum(Top-Bot,30)/30;
LAveRange = AveRange[BarCount-1];
TimeFrameSet(30*60);
// Initialization
baseX = 0;
baseY = floor(Bot[0]/Den)*Den;
relTodayRange = 0;
firstVisBar = Status("firstvisiblebar");
lastVisBar = Status("lastvisiblebar");

D=.0005;
//total=0;
totaldn=0;
totalup=0;
shiftup=0;
shiftdn=0;
startr=0;

i0 = 0;
i1 = 0;
for (i=0; i<BarCount; i++) {
x_s(i, 0); // should not need this
if (BarsInDay[i] == 0 AND i < firstVisBar) {
i0 = i;
}
if (BarsInDay[i] == 0 AND i >= lastVisBar) {
i1 = i;
}
}

i1 = BarCount-1;
for (i=i0; i<=i1; i++) {
if (BarsInDay[i] == 0) {
baseX = i;
baseY = floor(Bot[i]/Den)*Den;
maxY = floor(Top[i]/Den)*Den;
relTodayRange = (maxY-baseY)/Den;

for (j=0; j <= relTodayRange; j++) {
x_s(j, 0);

}
}

range_x=lastVisBar-firstVisBar;
spread = Param("X Space", 80, 1, 200, 1);
tpl = Param("Time Per Letter (mins)", 30, 1, 360, 1);
Intervalmin=Interval()/60;
flt =Param("First Letter (Bars)", 1, 1, 60, 1);
teb=ParamToggle("To Each Bar","No|Yes");
Color=Param("Color Threshold",20,1,50,1);
stopg=0;
stopr=0;
new=0;

Voloumeunit=Vol[i]/LastValue(BarsInDay);


if (EnMP2 == "Letters") {
for (j=0; j<= relTodayRange; j++) {
if (L[i] <= baseY+j*Den AND H[i] >= baseY+j*Den) {
PlotText(StrExtract(" A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , U , V , W , X , Y , Z, a , b , c , d , e , f , g , h , i , j , k , L , m , n ,o , p , q , r , s , t , u , v , w , x , y , z ",
IIf(BarsInDay[i]<flt,0,ceil(BarsInDay[i]/(tpl/Intervalmin))-0)), baseX+IIf(teb==1,BarsInDay[i],x_g(j)*(range_x/spread)), baseY+j*Den,
colorWhite,ColorHSB(10+((ceil(BarsInDay[i]/(tpl/Intervalmin)))*Color),160,140));
x_s(j, x_g(j)+1);

}
}
}

else if (EnMP2 == "Lines" OR EnMP2 == "Solid") {
for (j=0; j<= relTodayRange; j++) {
if (L[i] <= baseY+j*Den AND H[i] >= baseY+j*Den) {
if(Type=="Price Profile"){x_s(j, x_g(j)+1);}
else if(Type=="Volume Profile"){x_s(j, x_g(j)+round(V[i]/Voloumeunit));}

}
}
}

// Draw Initial Balance after 11am bar is complete
if (BarsInDay[i] == IBBars+1 AND EnIB == 0) {
Line1 = LineArray(i-2, curtop[i-1],i+7, curtop[i-1],0,True);
Plot(Line1,"",colorLightGrey,styleLine+styleDashed |styleNoRescale);
Line1 = LineArray(i-2, curbot[i-1],i+7, curbot[i-1],0,True);
Plot(Line1,"",colorLightGrey,styleLine+styleDashed |styleNoRescale);
}

// Examine x[j]
if ((i < BarCount - 1 AND BarsInDay[i+1] == 0) OR i == BarCount-1) {
maxXj = 0;
maxj = 0;
midrange = int(relTodayRange/2)+1;
for (j=0; j<= relTodayRange; j++) {
if (maxXj < x_g(j)) {
maxXj = x_g(j); maxj = j; L_StaticVarSet("Maxj",j); new=j;
} else if ( MaxXj == x_g(j)) {
if (abs(midrange-j) < abs(midrange-L_StaticVarGet("Maxj"))) {
maxXj = x_g(j); maxj = j; L_StaticVarSet("Maxj",j); new=j;
}
}
}
total_s(0, 0);
for ( n = 1; n <= relTodayRange; n++ ) {
total_s(n, x_g(n) + total_g(n-1));
}

Value_area=(total_g(relTodayRange)*percent)/100;

for ( a = 1; a <= relTodayRange; a++ )
{
if(Maxj-a>0 AND Maxj+a<relTodayRange)
{
if(MaxXj+total_g(Maxj+a)-total_g(Maxj)+(total_g(maxj)-MaxXj)-total_g(Maxj-(a+1))>=Value_area) {shiftup=a; shiftdn=a; break;}
}
else if(Maxj-a<1 )
{
if(MaxXj+total_g(Maxj+a)-total_g(Maxj)+(total_g(maxj)-MaxXj)>=Value_area){shiftup=a; shiftdn=maxj-1; break;}
}
else if(Maxj+a>relTodayRange )
{
if(MaxXj+total_g(relTodayRange)-total_g(Maxj)+(total_g(maxj)-MaxXj)-total_g(Maxj-(a+1)) >=Value_area){shiftup=relTodayRange-maxj; shiftdn=a; break;}
}
}
TimeFrameRestore();
Vah = LineArray(baseX, baseY+(maxj+shiftup)*Den, i, baseY+(maxj+shiftup)*Den,0,True);
Val = LineArray(baseX, baseY+(maxj-shiftdn)*Den, i, baseY+(maxj-shiftdn)*Den,0,True);
Vah1 = LineArray(i, baseY+(maxj+shiftup)*Den, i+BarsInDay[i], baseY+(maxj+shiftup)*Den,0,True);
Val1 = LineArray(i, baseY+(maxj-shiftdn)*Den, i+BarsInDay[i], baseY+(maxj-shiftdn)*Den,0,True);
poc = LineArray(baseX, baseY+maxj*Den, i, baseY+maxj*Den,0,True);
poc1 = LineArray(i, baseY+maxj*Den, i+BarsInDay[i], baseY+maxj*Den,0,True);

if(ViewVALVAH==1)
{
Plot(Vah,"",ParamColor("Color_VA", colorBlueGrey),styleLine|styleNoRescale);
Plot(Val,"",ParamColor("Color_VA", colorLightBlue),styleLine|styleNoRescale);
Plot(poc,"",Colorpoc,styleLine|styleNoRescale);
}
if(ViewPREVIOUS==1)
{
Plot(Vah1,"",ParamColor("Color_VA", colorBlueGrey),styleDashed|styleNoRescale);
Plot(Val1,"",ParamColor("Color_VA", colorLightBlue),styleDashed|styleNoRescale);
Plot(poc1,"",Colorpoc,styleDashed|styleNoRescale);
}


if(Viewvalues==1)
{
PlotText(""+(baseY+maxj*Den),i-5,baseY+maxj*Den,Colorpoc);
PlotText(""+(baseY+(maxj+shiftup)*Den),i-5,baseY+(maxj+shiftup)*Den,colorWhite);
PlotText(""+(baseY+(maxj-shiftdn)*Den),i-5,baseY+(maxj-shiftdn)*Den,colorWhite);
if(ViewTPOCount==1){PlotText(""+(total_g(maxj)-MaxXj)+" / "+(total_g(maxj-shiftdn-1)),basex,bot[i]-(Top[i]-bot[i])*0.05,ParamColor("Color_Below_VA", colorGrey40));
PlotText(""+(total_g(relTodayRange)-total_g(maxj))+" / "+(total_g(relTodayRange)-total_g(maxj+shiftup)),basex,Top[i],ParamColor("Color_Above_VA", colorGrey40));
}


}

}

if (i < BarCount - 1 AND BarsInDay[i+1] == 0 OR i == BarCount-1) {

for (p = 1; p < relTodayRange+1; p++){
line = LineArray(baseX, baseY+p*Den, baseX+x_g(p), baseY+p*Den);
line2 = LineArray(baseX, baseY+(p-1)*Den, baseX+x_g(p-1), baseY+(p-1)*Den);

if (EnMP2 == "Solid")
{
PlotOHLC( Line, Line, Line2, Line2, "",IIf(p>(maxj+shiftup),ParamColor("Color_Above_VA ", colorGrey40),IIf(p<=(maxj+shiftup)AND p>(maxj-shiftdn),ParamColor("Color_VA", colorBlueGrey),ParamColor("Color_Below_VA", colorGrey40))) ,styleCloud|styleNoRescale|styleNoLabel);
}
if (EnMP2 == "Lines")
{
Plot(line,"",IIf(p>(maxj+shiftup),ParamColor("Colo r_Above_VA", colorGrey40),IIf(p<=(maxj+shiftup)AND p>(maxj-shiftdn),ParamColor("Color_VA", colorBlueGrey),ParamColor("Color_Below_VA", colorGrey40))) , styleLines|styleNoLabel);
}

}
if(Viewfill==1){PlotOHLC(Vah,Vah,Val,Val,"",Colorfill,styleCloud|styleNoRescale|styleNoLabel);}

}
}


_SECTION_END();

_SECTION_BEGIN("Title");
Title =
EncodeColor(colorCustom12)+ Title = Name () + " | "
+EncodeColor(colorYellow) + Date() +" | " + Interval( 2 )+ " | "
+EncodeColor(colorWhite)+ "OPEN : "+ EncodeColor(colorWhite)+ O + " | "
+EncodeColor(colorWhite)+ "HIGH : "+ EncodeColor(colorBrightGreen)+ H + " | "
+EncodeColor(colorWhite)+ "LOW : "+ EncodeColor(colorDarkRed)+ L + " | "
+EncodeColor(colorWhite)+ "CLOSE : "+ WriteIf(C> Ref(C, -1),EncodeColor(colorYellow),EncodeColor(colorGold) )+ C + " | "
+EncodeColor(colorWhite)+ "Volume : " + WriteIf(V> Ref(V, -1),EncodeColor(colorGreen),EncodeColor(colorRed))+ WriteVal(V,1);
_SECTION_END(); 

SetChartBkColor(colorBlack);
 
HI DEAR Happy_Singh
WILL YOU PLZ ADD TREND LINE TO CCI LIKE THAT RSI
HTML:
_SECTION_BEGIN("CCI");
periods = Param( "Periods", 14, 2, 200, 1 );
Plot( CCI( periods ), _DEFAULT_NAME(), ParamColor( "Color",  colorCycle ), ParamStyle("Style")  );
_SECTION_END();
HTML:
// RSI TRENDLINE formula ver 1.0

SetBarsRequired(sbrAll, sbrAll);                                                        
TP = Param("Trend Per", 300,2,1000);                                                                
per_RSI= Param("RSI Per", 9, 7, 35,1);
IND =  RSI(per_RSI);                                                                                                      
Center = 50 ;

Plot( RSI(per_RSI), "", 4, 4);     
Plot(50,"",1,1) ;

// CALCULATE  UPTREND

startvalue = LastValue( LLV( IND, TP ) );                                                                          
startbar =  LastValue( ValueWhen( IND == startvalue, BarIndex(), 1) );                      
BP = BarCount - Startbar;                                                                                            

secondvalue =  LastValue( LLV( IND, BP - 5  ) );                                                       
secondbar =  LastValue( ValueWhen( IND == secondvalue, BarIndex(), 1) );            
BP2 = BarCount - secondbar;  

thirdvalue =  LastValue( LLV( IND, BP2 - 5 ) );                                                    
thirdbar =  LastValue( ValueWhen( IND == thirdvalue, BarIndex(), 1) );             
BP3 = BarCount - thirdbar;  

fourthvalue =  LastValue( LLV( IND, BP3 - 5 ) );                                                       
fourthbar =  LastValue( ValueWhen( IND ==fourthvalue, BarIndex(), 1) );         
BP4 = BarCount - fourthbar;  

fifthvalue =  LastValue( LLV( IND, BP4 - 5 ) );                                                    
fifthbar =  LastValue( ValueWhen( IND ==fifthvalue, BarIndex(), 1) );       
BP5 = BarCount - fifthbar;  

sixthvalue =  LastValue( LLV( IND, BP5 - 5 ) );                                             
sixthbar =  LastValue( ValueWhen( IND ==sixthvalue, BarIndex(), 1) );         

Low_1= IIf( BarIndex() == startbar, 80, Null);
Low_2= IIf( BarIndex() == secondbar, 80, Null);
Low_3= IIf( BarIndex() == thirdbar, 80, Null);
Low_4= IIf( BarIndex() == fourthbar, 80, Null);
Low_5= IIf( BarIndex() == fifthbar, 80, Null);
Low_6= IIf( BarIndex() == sixthbar, 80, Null);

b = startvalue ;    
FirstSlope = (secondvalue - b) / (secondbar - startbar) ;
FirstTrendline = FirstSlope * ( BarIndex() - startbar ) + b;                                                             
// Plot(  IIf(  BarIndex() >= startbar  AND FirstTrendline <= 90 , FirstTrendline, Null ) , "FirstTrendline", colorGreen, styleThick +2048 );        

SecondSlope = (thirdvalue - b) / (thirdbar - startbar) ;
SecondTrendline = SecondSlope * ( BarIndex() - startbar ) + b;                                                              

ThirdSlope = (fourthvalue - b) / (fourthbar - startbar) ;
ThirdTrendline = ThirdSlope * ( BarIndex() - startbar ) + b;  

FourthSlope = (fifthvalue - b) / (fifthbar - startbar) ;
FourthTrendline = FourthSlope * ( BarIndex() - startbar ) + b;  

FifthSlope = (sixthvalue - b) / (sixthbar - startbar) ;
FifthTrendline = FifthSlope * ( BarIndex() - startbar ) + b;  

MainSlope = IIf( FirstSlope > SecondSlope,  IIf( SecondSlope > ThirdSlope,  IIf( ThirdSlope > FourthSlope, 
 IIf( FourthSlope >  FifthSlope,  FifthSlope, FourthSlope),ThirdSlope), SecondSlope), FirstSlope) ;

MainLine = MainSlope * ( BarIndex() - startbar ) + b;    
Plot(  IIf(  BarIndex() >= startbar, MainLine, Null ) , "MainLine", colorDarkGreen, styleThick ) ;   


IND_Diff = IIf(  BarIndex() >= startbar, abs( IND - MainLine), Null) ;
MainTrendLine_Diff = Param("Difference IND from MainTrendLine", 2.5, 0.5,5,  0.5);

Cond_Buy = IIf( BarIndex() >= Thirdbar AND  IND_Diff  <= MainTrendLine_Diff, IND, 0)  AND  MainLine < 55 ;

PlotShapes( IIf( Cond_Buy, shapeUpArrow , shapeNone ), colorGreen );



/////////////////////////////////////////////

// CALCULATE  DOWNTREND

starthigh = LastValue( HHV( IND, TP ) );                                                                         
starthighbar =  LastValue( ValueWhen( IND == starthigh, BarIndex(), 1) );                
HBP = BarCount - starthighbar;                                                                                   

secondhigh =  LastValue( HHV( IND, HBP - 5  ) );                                                    
secondhighbar =  LastValue( ValueWhen( IND == secondhigh, BarIndex(), 1) );      
HBP2 = BarCount - secondhighbar;  

thirdhigh =  LastValue( HHV( IND, HBP2 - 5 ) );                                                    
thirdhighbar =  LastValue( ValueWhen( IND == thirdhigh, BarIndex(), 1) );            
HBP3 = BarCount - thirdhighbar;  

fourthhigh =  LastValue( HHV( IND, HBP3 - 5 ) );                                                         
fourthhighbar =  LastValue( ValueWhen( IND ==fourthhigh, BarIndex(), 1) );           
HBP4 = BarCount - fourthhighbar;  

fifthhigh =  LastValue( HHV( IND, HBP4 - 5 ) );                                                   
fifthhighbar =  LastValue( ValueWhen( IND ==fifthhigh, BarIndex(), 1) );         
HBP5 = BarCount - fifthhighbar;  

sixthhigh =  LastValue( HHV( IND, HBP5 - 5 ) );                                                
sixthhighbar =  LastValue( ValueWhen( IND ==sixthhigh, BarIndex(), 1) );           

High_1= IIf( BarIndex() == starthighbar, 90, Null);
High_2= IIf( BarIndex() == secondhighbar, 90, Null);
High_3= IIf( BarIndex() == thirdhighbar, 90, Null);
High_4= IIf( BarIndex() == fourthhighbar, 90, Null);
High_5= IIf( BarIndex() == fifthhighbar, 90, Null);
High_6= IIf( BarIndex() == sixthhighbar, 90, Null);

MainTrendLine_Diff = Param("Difference IND from MainTrendLine", 2.5, 0.5,7,  0.5);

d = starthigh ;    
FirstDownSlope = (secondhigh - d) / (secondhighbar - starthighbar) ;
FirstDownTrendline = FirstDownSlope * ( BarIndex() - starthighbar ) + d;                                                               

SecondDownSlope = (thirdhigh - d) / (thirdhighbar - starthighbar) ;
SecondDownTrendline = SecondDownSlope * ( BarIndex() -  starthighbar ) + d;                                                          

ThirdDownSlope = (fourthhigh - d) / (fourthhighbar - starthighbar) ;
ThirdDownTrendline = ThirdDownSlope * ( BarIndex() - starthighbar ) + d;  

FourthDownSlope = (fifthhigh - d) / (fifthhighbar - starthighbar) ;
FourthDownTrendline = FourthDownSlope * ( BarIndex() - starthighbar ) + d;  

FifthDownSlope = (sixthhigh - d) / (sixthhighbar - starthighbar) ;
FifthDownTrendline = FifthDownSlope * ( BarIndex() - starthighbar ) + d;  

MainDownSlope = IIf( FirstDownSlope < SecondDownSlope,  IIf( SecondDownSlope < ThirdDownSlope,  
IIf( ThirdDownSlope < FourthDownSlope,  IIf( FourthDownSlope <  FifthDownSlope, FifthDownSlope, FourthDownSlope),ThirdDownSlope), SecondDownSlope), FirstDownSlope) ;

MainDownLine =  IIf( MainDownSlope == 0, Null, MainDownSlope * ( BarIndex() - starthighbar ) + d ) ;    
Plot(  IIf(  BarIndex() >=  starthighbar, MainDownLine, Null ) , "Main_DOWN_Line", colorViolet, styleThick ) ;    

IND_Diff = IIf(  BarIndex() >=  starthighbar, abs( IND - MainDownLine), Null) ;

Cond_Sell = IIf( BarIndex() >= Thirdbar AND  IND_Diff  <= MainTrendLine_Diff, IND, 0)  AND  MainDownLine > 45 ;

PlotShapes( IIf( Cond_Sell, shapeDownArrow , shapeNone ), colorRed );


Title =  Name() + "\\c17" +   "  " +"\\c12" + "RSI" +  " " + per_RSI   ;
THANKS
 
Dear Happy Singh JI
Please help

printf("Last " + sig + " Signal came " + (BarCount-bars) + " bars ago");

printf("\n" + sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-
-----------------------------------------------------------------------------------------------------^

Error 29.
Variable 'entry' used without having been initialized.

printf("Last " + sig + " Signal came " + (BarCount-bars) + " bars ago");

printf("\n" + sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry)
-----------------------------------------------------------------------------------------------------------------^

Error 29.
Variable 'entry' used without having been initialized.

printf("Last " + sig + " Signal came " + (BarCount-bars) + " bars ago");

printf("\n" + sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"+ "\nTarget_1 : " + tar1 +
-------------------------------------------------------------------------------------------------------------------------------------------------------^

Error 29.
Variable 'tar1' used without having been initialized.

printf("Last " + sig + " Signal came " + (BarCount-bars) + " bars ago");

printf("\n" + sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"+ "\nTarget_1 : " + tar1 + "\nTarget_2 : " + tar2 +
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------^

Error 29.
Variable 'tar2' used without having been initialized.

g + " Signal came " + (BarCount-bars) + " bars ago");

printf("\n" + sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"+ "\nTarget_1 : " + tar1 + "\nTarget_2 : " + tar2 + "\nTarget_3 : " + tar3)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------^

Error 29.
Variable 'tar3' used without having been initialized.

;

printf("\n" + sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"+ "\nTarget_1 : " + tar1 + "\nTarget_2 : " + tar2 + "\nTarget_3 : " + tar3);

printf("\nCurrent P/L : " + WriteVal(IIf(sig == "
------------------------------------------------^

Error 1.
Operation not allowed. Operator/operand type mismatch.

+ sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"+ "\nTarget_1 : " + tar1 + "\nTarget_2 : " + tar2 + "\nTarget_3 : " + tar3);

printf("\nCurrent P/L : " + WriteVal(IIf(sig == "BUY",(C-entry)
--------------------------------------------------------------^

Error 29.
Variable 'entry' used without having been initialized.
 
please help me correct this formula


PctVlt=(ATR(14)/C)*100;//PercentVolatility

PK=IIf(PctVlt<0.5,Peak(Close,0.5,1),
IIf( PctVlt>=0.5 AND PctVlt< 1.0 ,Peak(Close,0.70,1),
IIf( PctVlt>=1.0 AND PctVlt< 1.5 ,Peak(Close,0.90,1),
IIf( PctVlt>=1.5 AND PctVlt< 2.0 ,Peak(Close,1.10,1),
IIf( PctVlt>=2.0 AND PctVlt< 2.5 ,Peak(Close,1.30,1),
IIf( PctVlt>=2.5 AND PctVlt< 3.0 ,Peak(Close,1.50,1),
IIf( PctVlt>=3.0 AND PctVlt< 3.5 ,Peak(Close,1.70,1),
IIf( PctVlt>=3.5 AND PctVlt< 4.0 ,Peak(Close,2.00,1),
Peak(Close,2.20,1) ))))))));

TGH=IIf(PctVlt<0.5,Trough(Close,0.5,1),
IIf( PctVlt>=0.5 AND PctVlt< 1.0 ,Trough(Close,0.75,1),
IIf( PctVlt>=1.0 AND PctVlt< 1.5 ,Trough(Close,1.00,1),
IIf( PctVlt>=1.5 AND PctVlt< 2.0 ,Trough(Close,1.25,1),
IIf( PctVlt>=2.0 AND PctVlt< 2.5 ,Trough(Close,1.50,1),
IIf( PctVlt>=2.5 AND PctVlt< 3.0 ,Trough(Close,1.75,1),
IIf( PctVlt>=3.0 AND PctVlt< 3.5 ,Trough(Close,2.00,1),
IIf( PctVlt>=3.5 AND PctVlt< 4.0 ,Trough(Close,2.25,1),
Trough(Close,2.50,1) ))))))));

Sens=IIf(PctVlt<0.5,0.5,
IIf( PctVlt>=0.5 AND PctVlt< 1.0 ,0.75,
IIf( PctVlt>=1.0 AND PctVlt< 1.5 ,1.00,
IIf( PctVlt>=1.5 AND PctVlt< 2.0 ,1.25,
IIf( PctVlt>=2.0 AND PctVlt< 2.5 ,1.50,
IIf( PctVlt>=2.5 AND PctVlt< 3.0 ,1.75,
IIf( PctVlt>=3.0 AND PctVlt< 3.5 ,2.00,
IIf( PctVlt>=3.5 AND PctVlt< 4.0 ,2.25,
2.50 ))))))));


Color=IIf(BarsSince(Cross(C,Ref(PK,-1)))<BarsSince(Cross(Ref(TGH,-1),C)),colorBrightGreen,colorRed);
Plot(C,"Chaloke.com Peak-Trough",Color,styleCandle);

///////////////////////////////////////////////////////////////////////////////////////////////////////////
_SECTION_BEGIN("RI Auto Trading System");

acc = Param("Acceleration", 0.1, 0, 1, 0.001 );
accm = Param("Max. acceleration", 0.06, 0, 1, 0.001 );

Buy = Cross(Open, SAR(acc,accm));
Sell = Cross(SAR(acc,accm), Open );

PlotShapes(IIf(Buy,shapeUpArrow,shapeNone), colorYellow, 0, Low, Offset=-15);
PlotShapes(IIf(Buy,shapeSmallCircle,shapeNone), colorYellow, 0, Low, Offset=-28);

PlotShapes(IIf(Sell, shapeDownArrow,shapeNone), colorWhite, 0, High, Offset=-15);
PlotShapes(IIf(Sell, shapeSmallCircle,shapeNone), colorWhite, 0, High, Offset= 28);

_SECTION_END();

///////////////////////////////////////////////////////////////////////////////////////////////////////////


DayH = TimeFrameGetPrice("H", inDaily, -1); DayHI = LastValue (DayH,1);// yesterdays high
DayL = TimeFrameGetPrice("L", inDaily, -1); DayLI = LastValue (DayL,1); // yesterdays low
DayC = TimeFrameGetPrice("C", inDaily, -1); // yesterdays close
DayO = TimeFrameGetPrice("O", inDaily); // current day open
DayH2= TimeFrameGetPrice("H", inDaily, -2); DayH2I = LastValue (DayH2,1); // Two days before high
DayL2= TimeFrameGetPrice("L", inDaily, -2); DayL2I = LastValue (DayL2,1); // Two days before low
DayH3= TimeFrameGetPrice("H", inDaily, -3); DayH3I = LastValue (DayH3,1); // Three days before high
DayL3= TimeFrameGetPrice("L", inDaily, -3); DayL3I = LastValue (DayL3,1); // Three days before low

numbars = LastValue(Cum(Status("barvisible")));
hts = -33.5;

YHL = ParamToggle("Yesterday HI LO","Show|Hide",1);
if(YHL==1) {
//Plot(DayL,"YL",colorTurquoise,styleDots|styleNoLin e|styleNoRescale|styleNoTitle);
//Plot(DayH,"YH",colorTurquoise,styleDots|styleNoLin e|styleNoRescale|styleNoTitle);
PlotText(" YH " , LastValue(BarIndex())-(numbars/Hts), DayHI, colorTurquoise);
PlotText(" YL " , LastValue(BarIndex())-(numbars/Hts), DayLI, colorTurquoise);
}

TDBHL = ParamToggle("2/3Days before HI LO","Show|Hide",0);
if(TDBHL==1) {
//Plot(DayL2,"2DBL",colorTurquoise,styleDots|styleNo Line|styleNoRescale|styleNoTitle);
//Plot(DayH2,"2DBH",colorTurquoise,styleDots|styleNo Line|styleNoRescale|styleNoTitle);
//Plot(DayL3,"3DBL",colorTurquoise,styleDots|styleNo Line|styleNoRescale|styleNoTitle);
//Plot(DayH3,"3DBH",colorTurquoise,styleDots|styleNo Line|styleNoRescale|styleNoTitle);
PlotText(" 2DBH " , LastValue(BarIndex())-(numbars/Hts), DayH2I, colorTurquoise);
PlotText(" 2DBL " , LastValue(BarIndex())-(numbars/Hts), DayL2I, colorTurquoise);
PlotText(" 3DBH " , LastValue(BarIndex())-(numbars/Hts), DayH3I, colorTurquoise);
PlotText(" 3DBL " , LastValue(BarIndex())-(numbars/Hts), DayL3I, colorTurquoise);
}

// Pivot Levels //
PP = (DayL + DayH + DayC)/3; PPI = LastValue (PP,1); // Pivot
R1 = (PP * 2) - DayL; R1I = LastValue (R1,1); // Resistance 1
S1 = (PP * 2) - DayH; S1I = LastValue (S1,1); // Support 1
R2 = PP + R1 - S1; R2I = LastValue (R2,1); // Resistance 2
S2 = PP - R1 + S1; S2I = LastValue (S2,1); // Support 2
R3 = PP + R2 - S1; R3I = LastValue (R3,1); // Resistance 3
S3 = PP - R2 + S1; S3I = LastValue (S3,1); // Support 3

ppl = ParamToggle("Pivot Levels","Show|Hide",1);
if(ppl==1) {
//Plot(PP, "PP",colorYellow,styleDots|styleNoLine|styleNoResc ale|styleNoTitle);
//Plot(R1, "R1",colorViolet,styleDots|styleNoLine|styleNoResc ale|styleNoTitle);
//Plot(S1, "S1",colorViolet,styleDots|styleNoLine|styleNoResc ale|styleNoTitle);
//Plot(R2, "R2",colorViolet,styleDots|styleNoLine|styleNoResc ale|styleNoTitle);
//Plot(S2, "S2",colorViolet,styleDots|styleNoLine|styleNoResc ale|styleNoTitle);
//Plot(R3, "R3",colorViolet,styleDots|styleNoLine|styleNoResc ale|styleNoTitle);
//Plot(S3, "S3",colorViolet,styleDots|styleNoLine|styleNoResc ale|styleNoTitle);

PlotText(" Pivot ", LastValue(BarIndex())-(numbars/Hts), PPI, colorYellow);
PlotText(" R1 " , LastValue(BarIndex())-(numbars/Hts), R1I, colorViolet);
PlotText(" S1 " , LastValue(BarIndex())-(numbars/Hts), S1I, colorViolet);
PlotText(" R2 " , LastValue(BarIndex())-(numbars/Hts), R2I, colorViolet);
PlotText(" S2 " , LastValue(BarIndex())-(numbars/Hts), S2I, colorViolet);
PlotText(" R3 " , LastValue(BarIndex())-(numbars/Hts), R3I, colorViolet);
PlotText(" S3 " , LastValue(BarIndex())-(numbars/Hts), S3I, colorViolet);
}
// Camerilla Levels //

rg = (DayH - DayL);

H5=DayC+1.1*rg; H5I = LastValue (H5,1);
H4=DayC+1.1*rg/2; H4I = LastValue (H4,1);
H3=DayC+1.1*rg/4; H3I = LastValue (H3,1);
H2=DayC+1.1*rg/6; H2I = LastValue (H2,1);
H1=DayC+1.1*rg/12; H1I = LastValue (H1,1);
L1=DayC-1.1*rg/12; L1I = LastValue (L1,1);
L2=DayC-1.1*rg/6; L2I = LastValue (L2,1);
L3=DayC-1.1*rg/4; L3I = LastValue (L3,1);
L4=DayC-1.1*rg/2; L4I = LastValue (L4,1);
L5=DayC-1.1*rg; L5I = LastValue (L5,1);

pcl = ParamToggle("Camerilla Levels","Show|Hide",0);
if(pcl==1) {
//Plot(H5,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(H4,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(H3,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(H2,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(H1,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(L1,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(L2,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(L3,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(L4,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
//Plot(L5,"",colorRose,styleDots|styleNoLine|styleNo Rescale|styleNoTitle);
PlotText(" H5 = " , LastValue(BarIndex())-(numbars/Hts), H5I +0.05, colorRose);
PlotText(" H4 = " , LastValue(BarIndex())-(numbars/Hts), H4I +0.05, colorRose);
PlotText(" H3 = " , LastValue(BarIndex())-(numbars/Hts), H3I +0.05, colorRose);
PlotText(" H2 = " , LastValue(BarIndex())-(numbars/Hts), H2I +0.05, colorRose);
PlotText(" H1 = " , LastValue(BarIndex())-(numbars/Hts), H1I +0.05, colorRose);
PlotText(" L1 = " , LastValue(BarIndex())-(numbars/Hts), L1I +0.05, colorRose);
PlotText(" L2 = " , LastValue(BarIndex())-(numbars/Hts), L2I +0.05, colorRose);
PlotText(" L3 = " , LastValue(BarIndex())-(numbars/Hts), L3I +0.05, colorRose);
PlotText(" L4 = " , LastValue(BarIndex())-(numbars/Hts), L4I +0.05, colorRose);
PlotText(" L5 = " , LastValue(BarIndex())-(numbars/Hts), L5I +0.05, colorRose);
}

// Current Days Hi Lo //
THL = ParamToggle("Todays Hi Lo","Show|Hide",1);
if(THL==1) {
isRth = TimeNum() >= 084500 & TimeNum() <= 085959;
isdRth = TimeNum() >= 084500 & TimeNum() <= 160000;
aRthL = IIf(isRth, L, 1000000);
aRthH = IIf(isdRth, H, Null);
aRthLd = IIf(isdRth, L, 1000000);
DayH = TimeFrameCompress( aRthH, inDaily, compressHigh );
DayH = TimeFrameExpand( DayH, inDaily, expandFirst );
DayL = TimeFrameCompress( aRthLd, inDaily, compressLow );
DayL = TimeFrameExpand( DayL, inDaily, expandFirst );
Bars = BarsSince(TimeNum() >= 94500 AND TimeNum() < 095959);//,BarIndex(),1); // AND DateNum()==LastValue(DateNum());
x0 = BarCount-LastValue(Bars);
x1 = BarCount-1;
DayHline=LineArray(x0,LastValue(DayH),x1,LastValue (DayH),0);
DayLline=LineArray(x0,LastValue(DayL),x1,LastValue (DayL),0);
DayHlineI = LastValue (DayHline,1);
DayLlineI = LastValue (DayLline,1);
//Plot(DayHline,"DayH",colorYellow,styleBar|styleNoR escale|styleNoTitle);
//Plot(DayLline,"DayL",colorYellow,styleBar|styleNoR escale|styleNoTitle);
PlotText(" Day Hi " , LastValue(BarIndex())-(numbars/Hts), DayHlineI +0.05, colorYellow);
PlotText(" Day Lo " , LastValue(BarIndex())-(numbars/Hts), DayLlineI +0.05, colorYellow);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////



//Support and resistance levels using RSI.
//graham Kavanagh May 2003
//Load into Indicator Builder
//Sensitivity of the levels can be changed with the variables
//Can test different numbers live with the Param function ctrl-R with open pane
RSIperiod = 5; // Param("RSI p",3,14,30,1);
Percent = 5; // Param("ZIG %",8,9,15,1);
EMAperiod = 5; //Param("EMA p",4,5,10,1);
HHVperiod = 5; //Param("HHV p",3,5,10,1);
NumLine = 1; //Param("Num Lines",3,1,20,1);

Base = DEMA(RSI(RSIperiod),EMAperiod);

for( i = 1; i <= numline; i++ )
{
ResBase = LastValue(Peak(Base,Percent,i));
SupBase = LastValue(Trough(Base,Percent,i));
Plot(ValueWhen( ResBase==Base, HHV(H,HHVperiod) ), "Resist Level", colorRed,
styleDashed);
Plot(ValueWhen( supbase==Base, LLV(L,HHVperiod) ), "Support Level", colorGreen,
styleDashed);
}
Title = Name() + "; " + Date() + ": Support & Resistance Levels using RSI: " +
/*EncodeColor(colorGreen)+ "Support Levels are Green; "+EncodeColor(colorRed)+
"Resistance Levels are Red: "+EncodeColor(colorBlack)+*/ "Num lines
="+WriteVal(numline,1) ;

/////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////////
///// Trailing Stop Module /////

P6=Param("Trailing Stop Risk",2.5,2,3.5,0.1);
P7=Param("Trailing Stop LookBack",14,5,25,1);
P8=Param("Trailing Stop PrevLow Switch",0,0,1,1);
PrevLow=IIf(P8==1, Ref(C,-TroughBars(C,5,1)) ,Null);
Plot(PrevLow,"",colorRed);

//Position sizing//
MyTotalPort = Param("MyTotalPort",1000000,10000,10000000,100000) ;
AcceptableRisk = Param("AcceptableRisk",0.5,0.1,3,0.1);
BarsFromStart = BarsSince(Cross(C,Ref(PK,-1))AND Ref(Color,-1)==colorRed) ;
InitialStopLoss =Ref( H - P6*ATR(P7),-BarsFromStart);
PositionSizing = 0.01*AcceptableRisk*MyTotalPort/( C - InitialStopLoss );

Plot(IIf( HHV(H - P6*ATR(P7),BarsFromStart+1) <C ,HHV(H - P6*ATR(P7),BarsFromStart+1),Null) ,"",colorCustom12,1);

PlotShapes(shapeDownArrow*Cross(Ref(HHV(H - P6*ATR(P7),BarsFromStart+1),-1),C),colorBlack,0,H,Offset=-43);

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////////////////

_SECTION_BEGIN("Price");

SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} - {{DATE}} "+ EncodeColor(colorYellow)+"Open = "+ EncodeColor(colorYellow) +"%g "+ EncodeColor(colorBrightGreen)+"High = "+ EncodeColor(colorBrightGreen) +"%g "+ EncodeColor(colorRed)+"Low = "+ EncodeColor(colorRed) +"%g "+ EncodeColor(colorYellow) +"Close = "+ EncodeColor(colorYellow) +" %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) ));

////////////////////////////////////////////////////////////////////////////////////////////////

Odd=13;//enter Odd numbers only
CoefOdd=round(Odd/2);

Even=12;//enter Even numbers only
Coefeven=Even/2;
Coefeven2=Coefeven+1;

CongestionPercent=2.8;/*Set % above/below Moving average for congestion / sideways market*/

TriangularOdd=MA(MA(C,CoefOdd),CoefOdd);
TriangularEven=MA(MA(C,Coefeven),Coefeven2);

finalMov_avg=IIf(Odd > even,triangularOdd,TriangularEven);

Color=colorBrightGreen;//select Moving average line color
tickercolor=colorBlack;//select price color

Plot(finalMov_avg,"",IIf(C < finalmov_avg,colorRed,Color),styleDots|styleThick) ;

////////////////////////////////////////////////////////////////////////////////////////////////



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

Code to automatically identify pivots TRIANGLE

********************************** */
// -- what will be our lookback range for the hh and ll?
farback=Param("How Far back to go",200,12,30,1);
nBars = Param("Number of bars", 12, 1, 30, 1);
// -- 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<farback; 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++;
}
}
// -- Dump inventory of high pivots for debugging
/*
for (k=0; k<nHPivs; k++) {
_TRACE("High pivot no. " + k
+ " at barindex: " + aHPivIdxs[k] + ", "
+ WriteVal(ValueWhen(BarIndex()==aHPivIdxs[k],
DateTime(), 1), formatDateTime)
+ ", " + aHPivHighs[k]);
}
*/
// -- OK, let's plot the pivots using arrows

PlotShapes(IIf(aHPivs==1, shapeSmallDownTriangle, shapeNone), colorCustom12, 0, High, Offset=-5);
PlotShapes(IIf(aLPivs==1, shapeSmallUpTriangle , shapeNone), colorCustom11, 0, Low, Offset=-5);

Sell = aHPivs == 1 ;
Buy = aLPivs == 1 ;
Filter=Buy OR Sell;
Sell=ExRem(Sell,Buy);
Buy=ExRem(Buy,Sell);

////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////////////

_SECTION_BEGIN("Pivot_Finder");
/* **********************************

Code to automatically identify pivots for STAR

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

// -- what will be our lookback range for the hh and ll?
farback=Param("How Far back to go",200,0,5000,10);
nBars = Param("Number of bars", 12, 5, 40);


// -- 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<farback; 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++;

}

}

// -- Dump inventory of high pivots for debugging



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

_TRACE("High pivot no. " + k

+ " at barindex: " + aHPivIdxs[k] + ", "

+ WriteVal(ValueWhen(BarIndex()==aHPivIdxs[k],

DateTime(), 1), formatDateTime)

+ ", " + aHPivHighs[k]);

}

//////////////////////////////////////////////////////////////////////////////

// -- OK, let's plot the pivots using arrows

PlotShapes(

IIf(aHPivs==1, shapeStar, shapeNone), colorBrightGreen, 0, H, 15);

PlotShapes(

IIf(aLPivs==1, shapeStar , shapeNone), colorCustom12, 0, L, -20);


//////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////

messageboard = ParamToggle("Message Board","Show|Hide",0);
showsl = ParamToggle("Stop Loss Line", "Show|Hide", 0);
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);

if (showsl == 0)
//{Plot(s5d,"Stop Loss",colorCustom14,styleDots);}
exitlong = Cross(s5d, H);
PlotShapes(exitlong * shapeDownArrow, colorBlack,0,H,-10);
exitshort = Cross(L, s5d);
PlotShapes(exitshort * shapeUpArrow, 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 * .0056);
tar2 = entry + (entry * .0116);
tar3 = entry + (entry * .0216);

bars = i;
i = 0;
}
if(Sell == 1)
{
sig = "SELL";
entry = C;
sl = s5d;
tar1 = entry - (entry * .0056);
tar2 = entry - (entry * .0116);
tar3 = entry - (entry * .0216);


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

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

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

for (i=bars; i <BarCount;i++)
{
PlotText(""+sig+"@"+entry, BarCount+1,entry,Null,colorBlue);
//PlotText("T1@"+tar1,BarCount+3,tar1,Null,Clr);Plot Text("T2@"+tar2,BarCount+3,tar2,Null,Clr);PlotText ("T3@"+tar3,BarCount+3,tar3,Null,Clr);

}


printf("Last " + sig + " Signal came " + (BarCount-bars) + " bars ago");
printf("\n" + sig + " @ : " + entry + "\nStop Loss : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"+ "\nTarget_1 : " + tar1 + "\nTarget_2 : " + tar2 + "\nTarget_3 : " + tar3);
printf("\nCurrent P/L : " + WriteVal(IIf(sig == "BUY",(C-entry),(entry-C)),2.2));

if (messageboard == 0 )
{
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 - 163, x2, y , 7, 7 ) ;
GfxTextOut( ( " GAIN TRADE "),88,y-165);
GfxTextOut( (" "),27,y-160);
GfxTextOut( ("Last " + sig + " Signal came " + (BarCount-bars-1) * Interval()/60 + " mins ago"), 13, y-140) ; // The text format location
GfxTextOut( ("" + WriteIf(sig =="BUY",sig + " @ ",sig + " @") + " : " + entry), 13, y-120);
GfxTextOut( ("Trailing SL : " + sl + " (" + WriteVal(IIf(sig == "SELL",entry-sl,sl-entry), 2.2) + ")"), 13, y-100);
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)), 88, y-22);;

}
//////////////////////////////////////////////////////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////////////////////////////////////////////////////

_SECTION_BEGIN("Magnified Market Price");
//by Vidyasagar, [email protected]//
FS=Param("Font Size",30,30,100,1);
GfxSelectFont("Arial", FS, 900, italic = False, underline = False, True );
GfxSetBkMode( colorWhite );
GfxSetTextColor( ParamColor("Color",colorYellow) );
Hor=Param("Horizontal Position",800,800,800,800);
Ver=Param("Vertical Position",27,27,27,27);
GfxTextOut(""+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, Ver+45 );
_SECTION_END();

////////////////////////////////////////////////////////////////////////////////

_SECTION_BEGIN("trending ribbon");
uptrend=PDI()>MDI()AND Signal()<MACD();
downtrend=MDI()>PDI()AND Signal()>MACD();
Plot( 2, /* defines the height of the ribbon in percent of pane width */"ribbon",
IIf( uptrend, colorGreen, IIf( downtrend, colorRed, colorBlack )), /* choose color */
styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );
_SECTION_END();
GraphXSpace=5;

//////////////////////////////////////////////////////////////////////////////ENJOYYYYYYYYYYYYYYY...............
 
i think only this is left

for (i=0; i<farback; 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




ERROR MSG - Array subscript out of range. you must not access array elements outside 0..(BarCount-1) range. you attempted to access non-existing - 1st element of array(ln:532, Col: 39)
 
AFL for positive, negative and hidden divergences, Request seniors to help me writing the AFL.
For finding divergence, I watch Price, Indicators (Fast MACD 5,10,9, Slow MACD 12,26,9, Stochastic 14,3,3 and RSI 14,9) and Trendlines on Price. Breaking TL on Price it will confirm the divergence.
Below is the strategy:
NEGATIVEDIVERGENCE
1-Price is making higher highs while the indicator is making lower highs: Bearish
POSITIVEDIVERGENCE
2-Price is making lower lows while the indicator is making higher lows: Bullish
HIDDEN NEGATIVEDIVERGENCE
3- Price is making lower highs while the indicator is making higher highs: Bearish
HIDDEN POSITIVEDIVERGENCE
4- Price is making higher lows while the indicator is making lower lows: Bullish
 
Lots of Errors in this Can any body please correct


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 ) PlotText("\n\n\n\n Buy\n "+NumToStr(BuyPrice,1.2),b,BuyPrice,colorDarkGreen);
else if( Sell ) PlotText("Sell "+NumToStr(SellPrice, 1.2),b,SellPrice,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 < NW[i-1])
{
Trend = -1;
NW = j + Revers;
}
else
{
Trend = 1;
if((j - Revers) > NW[i-1])
{
NW = j - Revers;
}
else
{
NW = NW[i-1];
}
}
}
if(Trend[i-1] == -1)
{
if(j > NW[i-1])
{
Trend = 1;
NW = j - Revers;
}
else
{
Trend = -1;
if((j + Revers) < NW[i-1])
{
NW = j + Revers;
}
else
{
NW = 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 == 1)
{
entry = H;
sig = "BUY";
sl = Ref(NW,-1);
tar1 = entry + (entry * .0050);
tar2 = entry + (entry * .0092);
tar3 = entry + (entry * .0179);

bars = i;
i = 0;
}
if(Sell == 1)
{
sig = "SELL";
entry = L;
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 = Null;
i++;
}
while( i < BarCount AND (IsNull(O) OR IsNull(H) OR IsNull(L) OR IsNull(C) ) );
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 >= result[i-1]) { // Long Trade is continuing
if (C > C[i-1]) {
HHC = C;
}
else {
HHC = HHC[i-1];
}
result = HHC - AtrMult * AtrARRAY;
if (result < result[i-1]) {
result = result[i-1];
}
}
else { // Long trade Exit triggered
iTrade = "ST";
LLC = C;
result = C + AtrMult * AtrARRAY;
}
}
else { // Short trade
if (C <= result[i-1]) {
if (C <= C[i-1]) { // Short Trade is continuing
LLC = C;
}
else {
LLC = LLC[i-1];
}
result = LLC + AtrMult * AtrARRAY;
if (result > result[i-1]) {
result = result[i-1];
}
}
else { //Short Trade Exit is triggered
iTrade = "LT";
HHC = C;
result = C - AtrMult * AtrARRAY;
}
}
}
}
return result;
}

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




regards
 
Code:
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("Colo rTrailShort",ColorRGB(255,0,0)),styleStaircase);
Plot(IIf(trailArray < C,trailArray,Null),"\ntrailLong",ParamColor("Color TrailLong",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();
///////////// Chandelier code by Geoff Mulhall
function aChandelierCl(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 aChandelierHL(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;
}
///////////// end Chandelier code by Geoff Mulhall


_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();
:thumb::thumb::thumb:
 

Similar threads