'**************************************************************
'*   Self Adjusting RSI
'*     by Jeremy Williams
'*	   February 3,2006
'*
'*	Adapted from Technical Analysis of Stocks and Commodities
'*     February 2006
'*
'*  Summary: 
'*
'*      This indicator plots bands around the RSI to allow 
'*  corrections to overbought/oversold conditions for
'*  non-standard period RSI calculations. For more information
'*  see "The Self-Adjusting RSI" in the February 2006 edition
'*  of Technical Analysis of Stocks and Commodities.
'*
'*  Parameters:
'*
'*  Adjustment_Type= Determines which methodology to use for the
'*                    correction. 
'*                    1: Standard Deviation 2: Moving Average
'*
'*  Periods= Specifies the number of Periods used for the RSI
'*             calculation
'*
'*  K= Specifies the number of deviations used to indicate 
'*      overbought/oversold conditions
'*
'************************************************************** 

#Indicator

#Param "Adjustment_Type",1      		' 1: Use Standard Deviation  2: Use Moving Average
#Param "Periods",14     				' Set number of periods used for calculation of RSI
#Param "K", 2.0							' Specifies the number of deviations used to indicate overbought/oversold levels

Dim myRSI 		As Single
Dim mySD 		As Single
Dim mySMA		As Single
Dim myAverage 	As Single
Dim Overbought	As Single
Dim Oversold 	As Single
Dim Difference 	As Single
Dim N 			As Integer



myRSI=RSI(Periods)

If Adjustment_Type = 1 then				' Use Std. Deviation to calculate bands

mySD = STD(myRSI,Periods)	
Overbought = 50 + K*mySD				'Calculate the bands
Oversold = 50 - K*mySD

Else 									' Use moving average to calculate the bands

mySMA=SMA(myRSI,Periods)

For N=0 to Periods-1					' This loop calculates the average
Difference = myRSI[N] - mySMA			' deviation of RSI from its moving
myAverage = Abs(Difference) + myAverage	' Average.
Next N
myAverage = myAverage / Periods

Overbought = 50 + K*myAverage			' Calculate the bands
Oversold = 50 - K*myAverage
    
End if

Setscales(0,100)						' Plot the RSI and the bands
Plot("RSI",myRSI,black,2)
Plot("Overbought",Overbought,blue)
Plot("Oversold",Oversold,blue)
Plotlabel(50)
Plotlabel(30)
Plotlabel(70)

Return myRSI							' Returns the value of the RSI