input length1 = 40;
input length2 = 15;
def buystop = Highest(high, length1)[1];
def sellstop = Lowest(low, length2)[1];
def shortstop = Lowest(low, length1)[1];
def coverstop = Highest(high, length2)[1];
def buy = high > buystop;
def short = low < shortstop;
def sell = low < sellstop;
def cover = high > coverstop;
def position = {default none, long, short};
position = if (buy or (position[1] == position.long and !sell)) then position.long else if (short or (position[1] == position.short and !cover)) then position.short else position.none;
plot BandUp = if position[1] == position.short then coverstop else buystop;
plot BandDown = if position[1] == position.long then sellstop else shortstop;
BandUp.SetDefaultColor(GetColor(1));
BandDown.SetDefaultColor(GetColor(1));
AddOrder(OrderType.BUY_AUTO, buy, tickColor = GetColor(1), arrowColor = GetColor(1), name = "DonchianBuy");
AddOrder(OrderType.SELL_AUTO, short, tickColor = GetColor(1), arrowColor = GetColor(1), name = "DonchianShort");
AddOrder(OrderType.SELL_TO_CLOSE, sell, tickColor = GetColor(1), arrowColor = GetColor(1), name = "DonchianSell");
AddOrder(OrderType.BUY_TO_CLOSE, cover, tickColor = GetColor(1), arrowColor = GetColor(1), name = "DonchianCover");