```
#
# TD Ameritrade IP Company, Inc. (c) 2014-2019
#
script VariableMinOffset {
input price = close;
input length = 0;
plot VMin;
if !IsNaN(price) and !IsNaN(length) {
VMin = fold i = 0 to length with o do if GetValue(price, i) < GetValue(price, o) then i else o;
} else {
VMin = Double.NaN;
}
}
script VariableLRS {
input price = close;
input length = 0;
plot VLRS;
if !IsNaN(price) and length != 1 {
VLRS = 6 * ( ( fold i1 = 0 to length with s1 do s1 + (length - i1) * GetValue(price, i1) ) / ( (1 + length) / 2 * length ) - ( fold i2 = 0 to length with s2 do s2 + GetValue(price, i2) ) / length ) / (length - 1);
} else if length == 1 {
VLRS = 0;
} else {
VLRS = Double.NaN;
}
}
input maxFlagLength = 15;
input maxFlagHeight = 2.5;
input maxPoleLength = 23;
input minPoleHeight = 5.5;
input upTrendLength = 70;
input minAtrPercentChange = 5.0;
Assert(maxPoleLength > 0, "'maxPoleLength' must be positive: " + maxPoleLength);
def x1 = GetMaxValueOffset(close, maxFlagLength)[2] + 2;
def x2 = x1 + 1;
def lfOffset = VariableMinOffset(close, x2);
def lf = GetValue(close, lfOffset);
def top = Max(GetValue(close, x1), GetValue(close, x1 + 1));
def atr = Average(TrueRange(high, close, low), 40);
def LRSX = VariableLRS(close[1], x1);
def LRSX1 = VariableLRS(close, x1);
def LRSX2;
if x1 == 2 {
LRSX2 = LRSX2[1];
} else if x1 > 2 {
LRSX2 = VariableLRS(close[2], x1 - 1);
} else {
LRSX2 = Double.NaN;
}
def condition1 = top - lf < maxFlagHeight * atr and x2 > 2 and x2 <= maxFlagLength;
def condition2 = if IsNaN(LRSX) or IsNaN(LRSX1) or IsNaN(LRSX2) then no else LRSX < 0 and (LRSX1 < 0 or LRSX2 < 0);
def y23 = VariableMinOffset(close, maxPoleLength + x2);
def bottom = GetValue(close, y23);
def pole = top - bottom;
def condition3 = pole > minPoleHeight * atr and y23 > x2;
def condition4 = bottom - Lowest(low, upTrendLength) > 0;
def condition5 = (atr / GetValue(atr, y23) - 1) * 100 > minAtrPercentChange;
plot Flag = condition1 and condition2 and condition3 and condition4 and condition5;
Flag.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Flag.SetLineWeight(3);
```