EDIT: I made a mistake for which I apologized to @mradtke. So hopefully others can learn from my mistake and give credit where it's due when posting code.
Hello everyone,
I found a very simple Supertrend indicator on the website QuantForHire written by Matt Radke, for which I have provided the code below. I am hoping someone can guide me as to how I can backtest this indicator and run a walk forward optimization on the same assuming I take all trades (long and short). I am assuming I need to add something to this code (probably Buy and Sell flags) but am not totally sure where.
Further, I would love some guidance on how clean my code is and if it can be improved in any way. I know there are ways to encapsulate into functions such that the same code can be used in both my backtest and indicator without duplication.
Thank you for the help!
function SuperTrend(lenATR, width)
{
nATR = ATR(lenATR);
pAvg = (H+L) / 2;
upperBand = pAvg + width * nATR;
lowerBand = pAvg - width * nATR;
isUpTrend = True;
for (i=lenATR; i<BarCount; ++i)
{
if (H[i] > upperBand[i-1])
isUpTrend[i] = True;
else if (L[i] < lowerBand[i-1])
isUpTrend[i] = False;
else
isUpTrend[i] = isUpTrend[i-1];
if (isUpTrend[i])
lowerBand[i] = Max(lowerBand[i], lowerBand[i-1]);
else
upperBand[i] = Min(upperBand[i], upperBand[i-1]);
}
super = IIf(isUpTrend, lowerBand, upperBand);
return super;
}
lengthATR = Param("ATR Length", 10, 1, 100, 1);
widthBands = Param("Band Width", 3, 1, 20, 0.1);
st = Supertrend(lengthATR,widthBands);
Plot(st, "Supertrend("+lengthATR+","+widthBands+")", ParamColor( "Color", colorCycle ), ParamStyle("Style") );