Williams Fractals [Tutorial/Template]

I noticed there weren't any code templates for Williams Fractals, therefore I have written this script to be a template and tutorial for those learning Pine Script. Each line is commented to show what it does.

If you don't know what Williams Fractals are, here is a brief explanation.

Bill Williams Fractals is a lagging indicator used to plot trend reversals on a chart. These appear over a candle at the point of reversal 2 candles after it has occurred. Often times this indicator is used in strategies such as Mumbai Scalping and paired with trend direction indicators and trailing stop indicators such as Parabolic SAR and SuperTrend.

本著真正的TradingView精神,該腳本的作者將其開源發布,以便交易者可以理解和驗證它。為作者喝彩吧!您可以免費使用它,但在出版物中重複使用此代碼受網站規則的約束。 您可以收藏它以在圖表上使用。

// Bill Williams Fractal Template
// Coded By: Matthew Spencer
// If you like this script or use it's code in one of yours, please donate.
// PayPal: ma.spencer@gmx.com Bitcoin: 1foxypuyuoNp5n1LNCCCCmjZ4RAXntQ8X

// Define our title and that this script will overlay the candles.
study("Williams Fractals",shorttitle="Fractals", overlay=true)

// Define "n" as the number of periods and keep a minimum value of 2 for error handling.
n = input(title="Periods", defval=2, minval=2, type=integer)

// Williams Fractals are a 5 point lagging indicator that will draw 2 candles behind.
// The purpose of the indicator is to plot points of trend reversals.
// Often these are paired with trailing stop indicators such as Parabolic SAR, Volatility Stop, and SuperTrend.

// Down pointing fractals occur over candles when:
//   High(n-2) < High(n)
//   High(n-1) < High(n)
//   High(n + 1) < High(n)
//   High(n + 2) < High(n)
dnFractal = (high[n-2] < high[n]) and (high[n-1] < high[n]) and (high[n+1] < high[n]) and (high[n+2] < high[n])

// Up pointing fractals occur under candles when:
//   Low(n-2) > Low(n) 
//   Low(n-1) > Low(n)
//   Low(n + 1) > Low(n) 
//   Low(n + 2) > Low(n)
upFractal = (low[n-2] > low[n]) and (low[n-1] > low[n]) and (low[n+1] > low[n]) and (low[n+2] > low[n])

// Plot the fractals as shapes on the chart.
plotshape(dnFractal, style=shape.arrowdown, location=location.abovebar, offset=-2, color=olive, transp=0) // Down Arrow above candles
plotshape(upFractal, style=shape.arrowup, location=location.belowbar, offset=-2, color=maroon, transp=0)  // Up Arrow below candles