Break even stop loss (% of instrument price)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © osmaras
// based on https://kodify.net/tradingview/orders/percentage-trail/

//@version=5
strategy("Break even stop loss (% of instrument price)", overlay=true)

// Configure trail stop level with input options (optional)
longTrailPerc = input.float(defval=3.0,step=0.1,title="Trail Long Loss (%)")* 0.01 
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))

// Determine trail stop loss prices
longStopPrice = 0.0
lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
longStopPrice := if (strategy.position_size > 0 and close > (lastEntryPrice * (1 + longTrailPerc)))
    stopValue = lastEntryPrice
    math.max(stopValue, longStopPrice[1])
else
    longStopPrice := if (strategy.position_size > 0)
        stopValue = lastEntryPrice * (1 - longTrailPerc)
        math.max(stopValue, longStopPrice[1])
    else
        0

// Plot stop loss values for confirmation
plot(series=(strategy.position_size > 0) ? longStopPrice : na,
     color=color.fuchsia, style=plot.style_cross,
     linewidth=2, title="Long Trail Stop")

// set strategy only long
strategy.risk.allow_entry_in(strategy.direction.long)

// Submit entry orders
if (longCondition)
    strategy.entry("Long", strategy.long)

shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition)
    strategy.close("Long")


// Submit exit orders for trail stop loss price
if (strategy.position_size > 0)
    strategy.exit(id="Stop Loss", stop=longStopPrice)

