Code:

```
#
# TD Ameritrade IP Company, Inc. (c) 2020-2022
#
input length = 3;
def HAclose = (open + high + low + close) / 4;
def HAopen = CompoundValue( 1, ( HAopen[1] + HAclose[1] ) / 2, HAclose );
def HAhigh = Max( high, Max( HAopen, HAclose ) );
def HAlow = Min( low, Min( HAopen, HAclose ) );
def maHigh = Average(HAhigh, length);
def maLow = Average(HAlow, length);
def state = {default init, short, long};
if (HAclose > maHigh) {
state = state.long;
} else if (HAclose < maLow) {
state = state.short;
} else {
state = state[1];
}
plot BuyStop = if state == state.short or state != state[1] then maHigh else Double.NaN;
plot SellStop = if state == state.long or state != state[1] then maLow else Double.NaN;
BuyStop.SetDefaultColor(GetColor(0));
SellStop.SetDefaultColor(GetColor(1));
AssignPriceColor(if State == State.Long then SellStop.takevalueColor() else BuyStop.takevalueColor());
BuyStop.SetDefaultColor(GetColor(0));
SellStop.SetDefaultColor(GetColor(1));
```