// Downloaded From https://www.WiseStockTrader.com
_SECTION_BEGIN("Oz Trail Stop Long v6");
// E.M.Pottasch, Feb 2014
// based on http://www.tradernexus.com/advancedstop/advancedstop.html

_N(PersistentPath="C:\\Program Files\\AmiBroker64\\PersistentVariables\\");  // **** You need to create a directory to store the persistent variable ****

selectDate=ParamDate("Start Date","08/01/2013",0);
selectTime=ParamTime("Start Time","09:30:00",0); 
per1=Param("Length ATR",20,1,150,1); //ATR length
fac1=Param("ATR Multiple (Initial)",1,0.1,10,0.1); //Initial ATR multiple, first bar
fac2=Param("ATR Multiple (Trail)",2,0.1,10,0.1); //Trail ATR multiple
tog1=ParamToggle("Trail value","Close|High&Low",1); //trail calculated with respect to the High or the Close price
tog2=ParamToggle("Display Exit Levels","No|Yes",1); //
tog3=ParamToggle("Trail Method","Ed's|Geoff's",1); // trail method, slight difference between my code and Geoff Mulhall's code
nlev=Param("Number of target Levels",2,0,12,1);
levMultiple=Param("Target Level Multiple",2,0,12,1);
entryPrice=Param("Entry Price Trade",0,0,150000,0.01); //entry price, use 0 for Close price
trg1=ParamTrigger("Save Changes", "Click Here"); //press to save changes every time you change parameter settings
trg2=ParamTrigger("Remove Persistent Variable", "Click Here"); //remove persistant trail for active symbol

idx1=idx2=0;bi=BarIndex();//trailArray=0;

// if selecting date and time with mouse use 
// 1) select bar with cursor and click on chart
// 2) press F12 => now a marker line appears (or double click with mouse)
// 3) then press the save changes button
// 4) remove the marker line with CTRL-F12 
if(BeginValue(bi)>0)
{
	selectDate=BeginValue(DateNum());
	selectTime=BeginValue(TimeNum());
}
if(entryPrice==0)
{
	if (Interval()>=86400)
	{
		ttt=IIf(DateNum()==selectDate,1,0);
		entryPrice=LastValue(ValueWhen(ttt,C));
	}
	else
	{
		ttt=IIf(DateNum()==selectDate AND TimeNum()==selectTime,1,0);
		entryPrice=LastValue(ValueWhen(ttt,C));	
	}
}
function conDate(nDate)
{
	string=StrFormat("%0.9g",nDate);
	aa=StrLeft(string,3);mm=StrMid(string,3,2);dd=StrRight(string,2);
	aa1=StrToNum(aa)+1900; // ONLY CORRECT AFTER 2000
	result= mm + "/" + dd + "/" + NumToStr(aa1,1,False);
	return result;
}
function PersistentArraySet(VarName,infoArray)
{
	fh=fopen( PersistentPath+VarName+".pva","w" );
	if(fh)
	{
		cnt=0;
		while(!IsEmpty(infoArray[cnt]))
		{
			String=NumToStr(infoArray[cnt])+"\n";
			fputs( String,fh);
			cnt=cnt+1;
		}
		fclose(fh);
	}
}
function PersistentArrayGet(VarName)
{
	infoArray=0;
	fh = fopen( PersistentPath+VarName+".pva","r" );
	if(fh)
	{
		cnt=0;
		while(!feof(fh)) 
		{ 
			infoArray[cnt]=StrToNum(fgets( fh ));
			cnt=cnt+1;
		} 
		fclose(fh);
	}
	return infoArray;
}
function PersistentVarRemove(VarName)
{
	Fn=PersistentPath+VarName+".pva";
	fh=fdelete(Fn) ;
}

infoArrayLONG=Null;
infoArrayLONG[0]=selectDate;
infoArrayLONG[1]=selectTime;
infoArrayLONG[2]=per1;
infoArrayLONG[3]=fac1;
infoArrayLONG[4]=fac2;
infoArrayLONG[5]=tog1;
infoArrayLONG[6]=tog3;
infoArrayLONG[7]=LastValue(entryPrice);
infoArrayLONG[8]=nlev;
infoArrayLONG[9]=levMultiple;

infoLONG=PersistentArrayGet("LONG"+Name());
lvspLONG=LastValue(Cum(infoLONG));

if(trg1)PersistentArraySet("LONG"+Name(),infoArrayLONG);
if(trg2)PersistentVarRemove("LONG"+Name());

procedure displayTargetLevels(trailArray,entryPriceArr,idx1,idx2,unitStop,nlevArr,levMultipleArr)
{
	lgth=5;
	validWindow=Flip(idx1==bi,Ref(idx2==bi,-1));
	for(i=1;i<=nlevArr;i++)
	{
		ll=IIf(trailArray,entryPriceArr+unitStop*i*levMultipleArr,0);
		if(LastValue(Cum(ll))>0)
		{
			sig=Cross(H,ll) AND validWindow;sig=ExRem(sig,idx2==bi);
			//Plot(ll,"",ColorRGB(60,60,60),styleLine,Null,Null,0,-1,1);
			//PlotText(""+ll[idx1],BarCount,ll[idx1],ColorRGB(100,100,100));
			line=LineArray(BarCount-lgth,ll[idx1],BarCount,ll[idx1]);
			Plot(line,"",ColorRGB(100,100,100),styleLine,Null,Null,lgth,0,1);
			PlotShapes(IIf(sig,shapeSmallCircle,shapeNone),colorOrange,0,Max(O,ll),0);
			PlotShapes(IIf(sig,shapeDownArrow,shapeNone),colorOrange,0,H,-15);
		}
	}
	// entry signal
	PlotShapes(IIf(idx1==bi,shapeSmallCircle,shapeNone),colorLightBlue,0,EntryPriceArr,0);
	PlotShapes(IIf(idx1==bi,shapeUpArrow,shapeNone),colorGreen,0,L,-15);		
	// exit signal
	PlotShapes(IIf(idx2==bi,shapeSmallCircle,shapeNone),colorOrange,0,C,0);
	PlotShapes(IIf(idx2==bi,shapeDownArrow,shapeNone),colorRed,0,H,-15);	
	// entry level
	th=IIf(trailArray,entryPriceArr,Null);//+unitStop;
	th=LineArray(BarCount-lgth,th[idx1],BarCount,th[idx1]);
	Plot(th,"",ColorRGB(0,0,160),styleLine,Null,Null,lgth,0,1);	
	// background color trade
	Plot(validWindow,"",ColorRGB(10,10,10),styleArea|styleOwnScale|styleNoLabel,0,1,0,-5);
}

///////////// Chandelier code by Geoff Mulhall
function aChandelierCl(AtrARRAY,fac1,AtrMult,entryPrice) 
{
	result=0;
	result[idx1]=entryPrice-fac1*AtrARRAY[idx1];iTrade = "LT";
	HHC[idx1]=C[idx1];LLC[idx1]=C[idx1];cnt=0;
	
	if((idx1+1)<BarCount AND idx1>0)
	{	
		for( i = idx1+1; i < BarCount; i++ ) 
		{
			cnt=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
					idx2=i;
					break;
				}
			}
		}
		if(idx2>0)
		{
			for(i=cnt;i<BarCount;i++)
			{
				result[i]=result[i-1];
			}
		}			
	}
	return result;
}
function aChandelierHL(AtrARRAY,fac1,AtrMult,entryPrice) 
{
	result=0;
	result[idx1]=entryPrice-fac1*AtrARRAY[idx1];iTrade = "LT";
	HHC[idx1]=H[idx1];LLC[idx1]=L[idx1];cnt=0;
	if((idx1+1)<BarCount AND idx1>0)
	{
		for( i = idx1+1; i < BarCount; i++ ) 
		{
			cnt=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
					idx2=i;
					break;
				}
			}
		}
		if(idx2>0)
		{
			for(i=cnt;i<BarCount;i++)
			{
				result[i]=result[i-1];
			}
		}		
	}
	return result;
}
function vstopLong_func(ATRBull,fac1,fac2,tog1,per,entryPrice)
{
	trailArray=Null;
	if(tog1)
	{
		hh=H;
	}
	else
	{
		hh=C;
	}

	trailArray[idx1]=entryPrice-fac1*ATRBull[idx1];

	// calculate trail
	if((idx1+1)<BarCount AND idx1>0)
	{
		cnt=0;	
		for(i=idx1+1;i<BarCount;i++)
		{
			prev=trailArray[i-1];cnt=i;
 
			if (C[i]>=prev AND C[i-1]>=prev)//long continuation
			{
				trailArray[i]=Max(prev,hh[i]-fac2*ATRBull[i]);
			}
			else if (C[i]<prev AND C[i-1]>=prev)//short trigger
			{
				idx2=i;
				break;
			}
		}
		if(idx2>0)
		{
			for(i=cnt;i<BarCount;i++)
			{
				trailArray[i]=trailArray[i-1];
			}
		}
	}
	return trailArray;	
}
selectDateArr=infoLONG[0];
selectTimeArr=infoLONG[1];
per1Arr=infoLONG[2];
fac1Arr=infoLONG[3];
fac2Arr=infoLONG[4];
tog1Arr=infoLONG[5];
tog3Arr=infoLONG[6];
entryPriceArr=infoLONG[7];
nlevArr=infoLONG[8];
levMultipleArr=infoLONG[9];

if(lvspLONG>0)
{
	if (Interval()>=86400)
	{
		tt=IIf(DateNum()==selectDateArr,1,0);
		idx1=LastValue(ValueWhen(tt,bi));
	}
	else
	{
		tt=IIf(DateNum()==selectDateArr AND TimeNum()==selectTimeArr,1,0);
		idx1=LastValue(ValueWhen(tt,bi));	
	}
	
	if(tog3Arr)
	{
		AtrARRAY=ATR(per1Arr);
		if(tog1Arr)
		{
			trailArray=aChandelierHL(AtrARRAY,fac1Arr,fac2Arr,entryPriceArr);trailArray=IIf(trailArray==0,Null,trailArray);
		}
		else
		{
			trailArray=aChandelierCl(AtrARRAY,fac1Arr,fac2Arr,entryPriceArr);trailArray=IIf(trailArray==0,Null,trailArray);
		}
	}
	else
	{
		ATRBull=ATR(per1Arr);
		trailArray=vstopLong_func(ATRBull,fac1Arr,fac2Arr,tog1Arr,per1Arr,entryPriceArr);trailArray=IIf(trailArray==0,Null,trailArray);	
	}
}
else
{
	trailArray=Null;
}

GraphXSpace=5;SetChartBkColor(colorBlack);SetChartOptions(0,chartShowDates);
SetBarFillColor(IIf(C>O,ColorRGB(0,75,0),IIf(C<=O,ColorRGB(75,0,0),colorLightGrey)));
Plot(C,"",IIf(C>O,ColorRGB(0,255,0),IIf(C<=O,ColorRGB(255,0,0),colorLightGrey)),64,Null,Null,0,0,1);
Plot(trailArray,"",ColorRGB(0,255,0),styleStaircase,Null,Null,0,0,1);

if(lvspLONG>0)
{	
	if(tog1Arr==0)trailRef="Close";
	else trailRef="High";
	if(tog3Arr==0)trailMeth="Ed's";
	else trailMeth="Geoff's";
	
	unitStop=(entryPriceArr-trailArray[idx1]);
	barsInTrade=0;
	if(idx1>0 AND idx2==0)
	{
		barsInTrade=BarsSince(idx1==bi)+1;
	} 
	else if(idx1>0 AND idx2>0)
	{
		barsIntrade=(idx2-idx1)+1;
	}

	Title= EncodeColor(colorBrightGreen) +
	"POSITION LONG\n" +
	EncodeColor(colorWhite) + 
	"Entry Date: " + conDate(selectDateArr) +"\n"+
	"Entry Time: " + selectTimeArr +"\n"+
	"ATR Period: " + per1Arr +"\n"+
	"ATR Multiple (Initial): " + fac1Arr +"\n"+
	"ATR Multiple (Trail): " + fac2Arr +"\n"+
	"Trail reference: " + trailRef +"\n"+
	"Trail method: " + trailMeth +"\n"+
	"Entry Price: " + entryPriceArr +"\n"+
	"Number of Levels: " + nlevArr +"\n"+
	"Multiple of Unitstop: " + levMultiple +"\n"+	
	EncodeColor(colorYellow) + 
	"UnitStop: " + unitStop +"\n"+
	"Bars in Trade: " + barsInTrade;	
	
	if(tog2 AND nlevArr>0 AND levMultipleArr>0)
	{
		displayTargetLevels(trailArray,entryPriceArr,idx1,idx2,unitStop,nlevArr,levMultipleArr);
	}
}
else 
{
	Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) );
}
_SECTION_END();