I checked this for errors but I have not actually run it as a scan. So you will need to test it and make sure it works. The last four lines are the scan signals for the four buy and sell order types used in the strategy. Only one of the four can be used at a time. Use the “#” symbols to turn individual scan signals on or off.
input entryLength = 40;
input exitLength = 15;
input atrLength = 20;
input atrFactor = 0.9;
input atrStopFactor = 4.0;
input atrAverageType = AverageType.SIMPLE;
def entryUpper = Highest(high, entryLength)[1];
def entryLower = Lowest(low, entryLength)[1];
def exitUpper = Highest(high, exitLength)[1];
def exitLower = Lowest(low, exitLength)[1];
def atr = reference ATR(length = atrLength, "average type" = atrAverageType);
def volatilityOk = TrueRange(high, low, close)[1] < atrFactor * atr[1]; def buyToOpen = (atrFactor == 0 or volatilityOk) and high > entryUpper;
def sellToOpen = (atrFactor == 0 or volatilityOk) and low < entryLower; def buyToClose = high > exitUpper;
def sellToClose = low < exitLower;
def position = {default none, long, short};
position = if (buyToOpen or (position[1] == position.long and !sellToClose)) then position.long
else if (sellToOpen or (position[1] == position.short and !buyToClose)) then position.short
else position.none;
plot scan = buyToOpen and !buyToOpen[1];
#plot scan = sellToOpen and !sellToOpen[1];
#plot scan = sellToClose and !sellToClose[1];
#plot scan = butToClose and !buyToClose[1];