// Downloaded From https://www.WiseStockTrader.com
_SECTION_BEGIN("Oz Trail Stop Long");
// 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);
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); //
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();

if(entryPrice==0)
{
	ttt=IIf(DateNum()>=selectDate,1,0);
	ttt=ttt-Ref(ttt,-1);
	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]=per1;
infoArrayLONG[2]=fac1;
infoArrayLONG[3]=fac2;
infoArrayLONG[4]=tog1;
infoArrayLONG[5]=LastValue(entryPrice);
infoArrayLONG[6]=nlev;
infoArrayLONG[7]=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)
{
	validWindow=Flip(idx1==bi,idx2==bi);
	for(i=1;i<=nlevArr;i++)
	{
		ll=IIf(trailArray,entryPriceArr+unitStop*i*levMultipleArr,Null);
		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));
			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;
	Plot(th,"",ColorRGB(0,0,160),styleLine,Null,Null,0,-1,1);
	PlotText("Entry "+th[idx1],BarCount,th[idx1],ColorRGB(0,0,200));
	// background color trade
	Plot(validWindow,"",ColorRGB(10,10,10),styleArea|styleOwnScale|styleNoLabel,0,1,0,-5);
}
function vstopLong_func(ATRBull,fac1,fac2,tog1,per,idx1,entryPrice)
{
	trailArray=Null;
	if(tog1)
	{
		hh=H;
		ll=L;
	}
	else
	{
		hh=C;
		ll=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;
			}
		}
		for(i=cnt;i<BarCount;i++)
		{
			trailArray[i]=trailArray[i-1];
		}		
	}
	return trailArray;	
}

selectDateArr=infoLONG[0];
per1Arr=infoLONG[1];
fac1Arr=infoLONG[2];
fac2Arr=infoLONG[3];
tog1Arr=infoLONG[4];
entryPriceArr=infoLONG[5];
nlevArr=infoLONG[6];
levMultipleArr=infoLONG[7];

if(lvspLONG>0)
{
	tt=IIf(DateNum()>=selectDateArr,1,0);
	tt=tt-Ref(tt,-1);idx1=LastValue(ValueWhen(tt,bi));
	ATRBull=ATR(per1Arr);
	trailArray=vstopLong_func(ATRBull,fac1Arr,fac2Arr,tog1Arr,per1Arr,idx1,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,"\nPrice",IIf(C>O,ColorRGB(0,255,0),IIf(C<=O,ColorRGB(255,0,0),colorLightGrey)),64,Null,Null,0,0,1);
Plot(trailArray,"\ntrailLong",ColorRGB(0,255,0),styleStaircase,Null,Null,0,0,1);

if(lvspLONG>0)
{	
	if(tog1Arr==0)trailRef="Close";
	else trailRef="High";

	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"+
	"ATR Period: " + per1Arr +"\n"+
	"ATR Multiple (Initial): " + fac1Arr +"\n"+
	"ATR Multiple (Trail): " + fac2Arr +"\n"+
	"Trail reference: " + trailRef +"\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);
	}
}
_SECTION_END();