'last red low / last green high' exit
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © carlpwilliams2

//@version=5
indicator("'Last red low / Last green high' exit", overlay=true)

/// copy from this point to add to your strat

/// ****  'Last red low / Last green high' exit indicator by @carlpwilliams2 - https://www.tradingview.com/script/B5MWwWad-last-red-low-last-green-high-exit/
stopLossTarget = input.float(0.5,title="Stop loss target %")
reqChangePerc = input.float(0.1,title="Change % required for new high/low")
showGreenHighs = input.bool(true, title="Show long Exit points", group="Exit points")
showRedLows = input.bool(true, title="Show short Exit points", group="Exit points")

var lowOfLastRed =low
var highOfLastGreen = high
var tpLongPrice = close

candleIsRed = open>close
candleIsGreen = not candleIsRed

changeOfLowPerc = lowOfLastRed>low? ((lowOfLastRed - low)/low)*100 : ((low - lowOfLastRed)/lowOfLastRed) *100
changeOfHighPerc =  highOfLastGreen>high? ((highOfLastGreen - high)/high) *100 :  ((high - highOfLastGreen)/highOfLastGreen) *100

if(candleIsRed and barstate.isconfirmed and (changeOfLowPerc>reqChangePerc or changeOfLowPerc<0))
    lowOfLastRed :=  low

if(candleIsGreen and barstate.isconfirmed and (changeOfHighPerc>reqChangePerc or changeOfHighPerc>0))
    highOfLastGreen := high

distanceToHigh = (highOfLastGreen - close)
distanceToLow  = (close - lowOfLastRed)
distanceToLongExitPercentage = (distanceToLow/close)*100
distanceToShortExitPercentage = (distanceToHigh/highOfLastGreen) * 100


plot(not ta.change(lowOfLastRed) and showGreenHighs and distanceToLongExitPercentage > stopLossTarget ? lowOfLastRed : na, title = "Low of last red", style = plot.style_stepline_diamond, color = distanceToLongExitPercentage > stopLossTarget ? color.red:color.new(color.red,60), linewidth=2)
plot(not ta.change(highOfLastGreen) and showRedLows and distanceToShortExitPercentage > stopLossTarget ? highOfLastGreen : na, title="High of last green", style=plot.style_stepline_diamond, color = distanceToShortExitPercentage > stopLossTarget ? color.green:color.new(color.green,60), linewidth=2)

// ***** end of last red/green indicator

