#Stop
'**************************************************************
'*   Rectangle Profit Target (RectangleProfit.txt)
'*     by Jeremy Williams
'*	   April 13,2007
'*
'*	Adapted from Technical Analysis of Stocks and Commodities
'*     June 2007
'*
'*  Summary: 
'*
'*      This stop detemines profit targets for trading rectangle breakouts.  
'*  The targets are calculated with the formula given by Markos Katsanos' 
'*  regression analysis. For more information see "How Effective are Rectangles?"
'*  in the June 2007 edition of Technical Analysis of Stocks and  
'*  Commodities.
'*
'*	NOTE: This stop does not identify rectangles, though if a rectangle has already
'*  been found this stop will calculate the proper level.
'*
'*  Parameters:
'*
'*  Lookback    =  Specifies the length of time in bars of the rectangle formation
'*
'************************************************************** 

#Param "Lookback",500

Dim fUpper		As Single
Dim fLower		As Single
Dim fHeight		As Single
Dim fExponent	As Single
Dim fOffset		As Single
Dim fTarget		As Single
Dim Y1			As Single
Dim Y2			As Single
Dim X1			As Integer
Dim X2			As Integer

' Calculate the height of the rectange and the level of the stop using the formula
' Offset = 2.3 * Height ^ 0.8 
fUpper = HHV(Lookback)[2]
fLower = LLV(Lookback)[2]
fHeight = fUpper - fLower
fExponent = Power(fHeight,.8)
fOffset = 2.3*fExponent

' Initialize the stop by taking the proper offset from the rectangle boundary
If fTarget[1] <= 0 And Signal = LongSignal Then
	fTarget = fUpper + fOffSet
	' Plot the rectangle
	X2 = bar
	X1 = bar-Lookback
	Y1= fUpper
	Y2= fUpper
	PlotPriceTrendline("Upper",X1,Y1,X2,Y2,Blue,1)
	Y1= fLower
	Y2= fLower
	PlotPriceTrendline("Lower",X1,Y1,X2,Y2,Blue,1)
Else If fTarget[1] <= 0 And Signal = ShortSignal Then
	fTarget = fLower - fOffset
	' Plot The Rectangle
	X2 = bar
	X1 = bar-Lookback
	Y1= fUpper
	Y2= fUpper
	PlotPriceTrendline("Upper",X1,Y1,X2,Y2,Blue,1)
	Y1= fLower
	Y2= fLower
	PlotPriceTrendline("Lower",X1,Y1,X2,Y2,Blue,1)
Else 
	fTarget = fTarget[1]
End If

' Set the level for the order
ExitLevel = fTarget

'If level is penetrated generate exit signal
If Signal = LongSignal And H > fTarget Then
	Signal = ExitSignal
Else If Signal = ShortSignal And L < fTarget Then
	Signal = ExitSignal
End If

' Plot profit level.
PlotPrice("Exit",fTarget)