MACD Strategy
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © maxencetajet

//@version=5
strategy("MACD Strategy", overlay=true, initial_capital=1000)

tlpc = input.string(title="Alert", defval="PineConnector", options=["PineConnector", "Telegram"], tooltip="Go to alertatron to have alerts automatically sent to Telegram")

// Setting 

ID = input("1234567890123", title="License ID (PineConnector)", group="Setting")
risk = input.float(2, title="Risk per Trade %", group="Setting", step=0.5)
typeSL = input.string(title="StopLoss", defval="Swing", options=["Swing", "ATR"], group="Setting")
typeTP = input.string(title="TakeProfit", defval="R:R", options=["R:R", "Multiple Target"], group="Setting")
_x = input.bool(false, title="do not take too small positions", group="Setting", tooltip="This parameter is used to avoid positions that have a stoploss too close to the entry point and that the broker's spreads take all the gains")
security = input.float(10, title="min of pips (00001.00)", group="Setting")

riskt = risk / 100 + 1

useDateFilter = input.bool(false, title="Filter Date Range of Backtest", group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 June 2022"), title="Start Date", group="Backtest Time Period", tooltip="This start date is in the time zone of the exchange " + "where the chart's instrument trades. It doesn't use the time " + "zone of the chart or of your computer.")
backtestEndDate = input.time(timestamp("1 July 2022"), title="End Date", group="Backtest Time Period", tooltip="This end date is in the time zone of the exchange " + "where the chart's instrument trades. It doesn't use the time " + "zone of the chart or of your computer.")

inTradeWindow = not useDateFilter or (time >= backtestStartDate and time < backtestEndDate)

//StopLoss

swingHighV = input.int(7, title="Swing High", group="Stop Loss", tooltip="Number of candles in which the parameter targets the highest")
swingLowV = input.int(7, title="Swing Low", group="Stop Loss", tooltip="Number of candles in which the parameter targets the lowest")

atr1 = input.int(14, title="ATR Period", group="Stop Loss")
atrMultiplierSL = input.int(2, title = "ATR Multiplier", group="Stop Loss")

atr = ta.atr(atr1)

swingHigh = ta.highest(high, swingHighV)
swingLow = ta.lowest(low, swingLowV)

atrSell = close + atr * atrMultiplierSL
atrBuy = close - atr * atrMultiplierSL

//TakeProfit

target_stop_ratio = input.float(title='Risk/Reward (R:R)', defval=3, minval=0.5, maxval=100, step=0.1, group="TakeProfit")
target1 = input.float(1, title='Target 1 R:R (Multiple Target)', group="TakeProfit", step=0.1, tooltip="SL moved to entry point if hit")
target2 = input.float(2, title='Target 2 R:R (Multiple Target)', group="TakeProfit", step=0.1)

//EMA

src1 = input(title="Source", defval=close, group="EMA")
emaV = input.int(200, title="Length", group="EMA")

ema = ta.ema(src1, emaV)

//Parabolic SAR

sarT = input.bool(true, title="Parabolic SAR Indicator", group="Parabolic SAR")
start = input(0.02, group="Parabolic SAR")
increment = input(0.02, group="Parabolic SAR")
maximum = input(0.2, "Max Value", group="Parabolic SAR")

SAR = ta.sar(start, increment, maximum)

myColor = SAR < low ? color.green : color.red

//MACD

src = input(title="Source", defval=close, group="MACD")
fast_length = input(title="Fast Length", defval=12, group="MACD")
slow_length = input(title="Slow Length", defval=26, group="MACD")
signal_length = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9, group="MACD")
sma_source = input.string(title="Oscillator MA Type",  defval="EMA", options=["SMA", "EMA"], group="MACD")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD")

fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal

//Alert

getpips() =>
    syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)

mess_buyT = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(swingLow) + " ⛔️ \n" + "TP  " + str.tostring(((close-swingLow)*target_stop_ratio)+close) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."
mess_sellT = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(swingHigh) + " ⛔️ \n" + "TP  " + str.tostring(close-((swingHigh-close)*target_stop_ratio)) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."

mess_buyP = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingLow) + ",tp=" + str.tostring(((close-swingLow)*target_stop_ratio)+close) + ",risk=" + str.tostring(risk) + ""
mess_sellP = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingHigh) + ",tp=" + str.tostring(close-((swingHigh-close)*target_stop_ratio)) + ",risk=" + str.tostring(risk) + ""

mess_buyAT = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(atrBuy) + " ⛔️ \n" + "TP  " + str.tostring(((close-atrBuy)*target_stop_ratio)+close) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."
mess_sellAT = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(atrSell) + " ⛔️ \n" + "TP  " + str.tostring(close-((atrSell-close)*target_stop_ratio)) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."

mess_buyAP = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrBuy) + ",tp=" + str.tostring(((close-atrBuy)*target_stop_ratio)+close) + ",risk=" + str.tostring(risk) + ""
mess_sellAP = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrSell) + ",tp=" + str.tostring(close-((atrSell-close)*target_stop_ratio)) + ",risk=" + str.tostring(risk) + ""

mess_buyAMT = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(atrBuy) + " ⛔️ \n" + "TP1  " + str.tostring(((close-atrBuy)*target1)+close) + " 🎯 \n" + "TP2  " + str.tostring(((close-atrBuy)*target2)+close) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"
mess_sellAMT = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(atrSell) + " ⛔️ \n" + "TP1  " + str.tostring(close-((atrSell-close)*target1)) + " 🎯 \n" + "TP2  " + str.tostring(close-((atrSell-close)*target2)) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"

mess_buyAMP1 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrBuy) + ",tp=" + str.tostring(((close-atrBuy)*target1)+close) + ",risk=" + str.tostring(risk/2) + ""
mess_buyAMP2 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrBuy) + ",tp=" + str.tostring(((close-atrBuy)*target2)+close) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring(((((close-atrBuy)*target1)+close)-close)/getpips()) + ",beoffset=0"
mess_sellAMP1 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrSell) + ",tp=" + str.tostring(close-((atrSell-close)*target1)) + ",risk=" + str.tostring(risk/2) + ""
mess_sellAMP2 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrSell) + ",tp=" + str.tostring(close-((atrSell-close)*target2)) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring((close-(close-((atrSell-close)*target1)))/getpips()) + ",beoffset=0"

mess_buyMT = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(swingLow) + " ⛔️ \n" + "TP1  " + str.tostring(((close-swingLow)*target1)+close) + " 🎯 \n" + "TP2  " + str.tostring(((close-swingLow)*target2)+close) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"                                                                                 
mess_sellMT = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée  " + str.tostring(close) + "\n" + "SL  " + str.tostring(swingHigh) + " ⛔️ \n" + "TP1  " + str.tostring(close-((swingHigh-close)*target1)) + " 🎯 \n" + "TP2  " + str.tostring(close-((swingHigh-close)*target2)) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"

mess_buyMP1 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingLow) + ",tp=" + str.tostring(((close-swingLow)*target1)+close) + ",risk=" + str.tostring(risk/2) + ""
mess_buyMP2 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingLow) + ",tp=" + str.tostring(((close-swingLow)*target2)+close) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring(((((close-swingLow)*target1)+close)-close)/getpips()) + ",beoffset=0"
mess_sellMP1 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingHigh) + ",tp=" + str.tostring(close-((swingHigh-close)*target1)) + ",risk=" + str.tostring(risk/2) + ""
mess_sellMP2 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingHigh) + ",tp=" + str.tostring(close-((swingHigh-close)*target2)) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring((close-(close-((swingHigh-close)*target1)))/getpips()) + ",beoffset=0"

// Strategy
    
float risk_long = na
float risk_short = na
float stopLoss = na
float takeProfit1 = na
float takeProfit2 = na
float entry_price = na
bool longcondition = na
bool shortcondition = na

if sarT
    longcondition := close > ema and ta.crossover(macd, signal) and macd < 0 and high > SAR 
    shortcondition := close < ema and ta.crossunder(macd, signal) and macd > 0 and low < SAR 
if not sarT
    longcondition := close > ema and ta.crossover(macd, signal) and macd < 0 
    shortcondition := close < ema and ta.crossunder(macd, signal) and macd > 0 
    
risk_long := risk_long[1]
risk_short := risk_short[1]

lotB = (strategy.equity*riskt-strategy.equity)/(close - swingLow)
lotS = (strategy.equity*riskt-strategy.equity)/(swingHigh - close)
    
lotB1 = (strategy.equity*riskt-strategy.equity)/(close - atrBuy)
lotS1 = (strategy.equity*riskt-strategy.equity)/(atrSell - close)

if typeSL == "ATR"

    if typeTP == "Multiple Target"
    
        if strategy.position_size == 0 and longcondition and inTradeWindow 
            risk_long := (close - atrBuy) / close
            minp = close - atrBuy
            
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMT, when = minp > security)
                
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMP1, when = minp > security)
                    alert(mess_sellAMP2, alert.freq_once_per_bar_close)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMT)
                
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMP1)
                    alert(mess_sellAMP2, alert.freq_once_per_bar_close)
        
        if strategy.position_size == 0 and shortcondition and inTradeWindow 
            risk_short := (atrSell - close) / close 
            minp = atrSell - close
            
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMT, when = minp > security)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMP1, when = minp > security)
                    alert(mess_sellAMP2, alert.freq_once_per_bar_close)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMT)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMP1)
                    alert(mess_sellAMP2, alert.freq_once_per_bar_close)
    
    if typeTP == "R:R"
    
        if strategy.position_size == 0 and longcondition and inTradeWindow 
            risk_long := (close - atrBuy) / close
            minp = close - atrBuy
            
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAT, when = minp > security)
                
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAP, when = minp > security)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAT)
                
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAP)
        
        if strategy.position_size == 0 and shortcondition and inTradeWindow 
            risk_short := (atrSell - close) / close 
            minp = atrSell - close
         
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAT, when = minp > security)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAP, when = minp > security)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAT)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAP)
    
if typeSL == "Swing"

    if typeTP == "Multiple Target"
    
        if strategy.position_size == 0 and longcondition and inTradeWindow 
            risk_long := (close - swingLow) / close
            minp = close - swingLow
            
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMT, when = minp > security)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMP1, when = minp > security)
                    alert(mess_buyMP2, alert.freq_once_per_bar_close)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMT)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMP1)
                    alert(mess_buyMP2, alert.freq_once_per_bar_close)
       
        if strategy.position_size == 0 and shortcondition and inTradeWindow 
            risk_short := (swingHigh - close) / close  
            minp = swingHigh - close
            
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMT, when = minp > security)
                        
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMP1, when = minp > security)
                    alert(mess_sellMP2, alert.freq_once_per_bar_close)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMT)
                        
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMP1)
                    alert(mess_sellMP2, alert.freq_once_per_bar_close)
                    
    if typeTP == "R:R"

        if strategy.position_size == 0 and longcondition and inTradeWindow 
            risk_long := (close - swingLow) / close
            minp = close - swingLow
        
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyT, when = minp > security)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyP, when = minp > security)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyT)
                    
                if tlpc == "PineConnector" 
                    strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyP)
       
        if strategy.position_size == 0 and shortcondition and inTradeWindow 
            risk_short := (swingHigh - close) / close  
            minp = swingHigh - close
  
            if _x 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellT, when = minp > security)
                        
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellP, when = minp > security)
            else 
                if tlpc == "Telegram" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellT)
                        
                if tlpc == "PineConnector" 
                    strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellP)
    
if typeTP == "Multiple Target"

    if tlpc == "Telegram" 
    
        if strategy.position_size > 0
    
            stopLoss := strategy.position_avg_price * (1 - risk_long)
            takeProfit1 := strategy.position_avg_price * (1 + target1 * risk_long)
            takeProfit2 := strategy.position_avg_price * (1 + target2 * risk_long)
            entry_price := strategy.position_avg_price
            mess_profit1 = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n" + "TP1 Touché ✅ +" + str.tostring(risk*target1) + "% " 
            strategy.exit("Exit 1", "long", limit = takeProfit1, qty_percent=50, comment_profit = "TP1 ✅", alert_profit = mess_profit1)
            
            if ta.crossover(high, takeProfit1)
                mess_profit2 = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n" + "TP2 Touché ✅ +" + str.tostring(risk*target2) + "% " 
                mess_be = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n" + "BE ❎"
                strategy.exit("Exit 2", "long", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎", alert_profit = mess_profit2)
            else 
                mess_loss = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% " 
                strategy.exit("Exit 1", "long", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌", alert_loss = mess_loss)
        
        if strategy.position_size < 0
    
            stopLoss := strategy.position_avg_price * (1 + risk_short)
            takeProfit1 := strategy.position_avg_price * (1 - target1 * risk_short)
            takeProfit2 := strategy.position_avg_price * (1 - target2 * risk_short)
            entry_price := strategy.position_avg_price
            mess_profit1 = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n" + "TP1 Touché ✅ +" + str.tostring(risk*target1) + "% " 
            strategy.exit("Exit 1", "short", limit = takeProfit1, qty_percent = 50, comment_profit = "TP1 ✅", alert_profit = mess_profit1)
            
            if ta.crossunder(low, takeProfit1)
                mess_profit2 = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n" + "TP2 Touché ✅ +" + str.tostring(risk*target2) + "% " 
                mess_be = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n" + "BE ❎"
                strategy.exit("Exit 2", "short", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎", alert_profit = mess_profit2)
            else 
                mess_loss = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% " 
                strategy.exit("Exit 1", "short", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌", alert_loss = mess_loss)
                
    if tlpc == "PineConnector" 
        
        if strategy.position_size > 0

            stopLoss := strategy.position_avg_price * (1 - risk_long)
            takeProfit1 := strategy.position_avg_price * (1 + target1 * risk_long)
            takeProfit2 := strategy.position_avg_price * (1 + target2 * risk_long)
            entry_price := strategy.position_avg_price
            strategy.exit("Exit 1", "long", limit = takeProfit1, qty_percent=50, comment_profit = "TP1 ✅")
            
            if ta.crossover(high, takeProfit1)
                strategy.exit("Exit 2", "long", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎")
            else 
                strategy.exit("Exit 1", "long", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌")
    
        if strategy.position_size < 0
    
            stopLoss := strategy.position_avg_price * (1 + risk_short)
            takeProfit1 := strategy.position_avg_price * (1 - target1 * risk_short)
            takeProfit2 := strategy.position_avg_price * (1 - target2 * risk_short)
            entry_price := strategy.position_avg_price
            strategy.exit("Exit 1", "short", limit = takeProfit1, qty_percent = 50, comment_profit = "TP1 ✅")
            
            if ta.crossunder(low, takeProfit1)
                strategy.exit("Exit 2", "short", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎")
            else 
                strategy.exit("Exit 1", "short", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌")
            
if typeTP == "R:R"

    if strategy.position_size > 0

        stopLoss := strategy.position_avg_price * (1 - risk_long)
        takeProfit1 := strategy.position_avg_price * (1 + target_stop_ratio * risk_long)
        entry_price := strategy.position_avg_price
        
        if tlpc == "Telegram" 
            mess_profit = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n" + "TP Touché ✅ +" + str.tostring(risk*target_stop_ratio) + "% " 
            mess_loss = "📈  𝗔𝗖𝗛𝗔𝗧  🔵  " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% " 
            strategy.exit("Exit long", "long", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅", comment_loss="SL ❌", alert_profit = mess_profit, alert_loss = mess_loss)
        
        if tlpc == "PineConnector" 
            strategy.exit("Exit long", "long", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅", comment_loss="SL ❌")
            
    if strategy.position_size < 0

        stopLoss := strategy.position_avg_price * (1 + risk_short) 
        takeProfit1 := strategy.position_avg_price * (1 - target_stop_ratio * risk_short) 
        entry_price := strategy.position_avg_price
        
        if tlpc == "Telegram" 
            mess_profit = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n" + "TP Touché ✅ +" + str.tostring(risk*target_stop_ratio) + "% " 
            mess_loss = "📉  𝗩𝗘𝗡𝗧𝗘  🔴  " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% " 
            strategy.exit("Exit short", "short", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅" , comment_loss="SL ❌", alert_profit = mess_profit, alert_loss = mess_loss)           
            
        if tlpc == "PineConnector" 
            strategy.exit("Exit short", "short", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅" , comment_loss="SL ❌")         
        
//Plot 

exsar = sarT ? SAR : na
plot(exsar, "ParabolicSAR", style=plot.style_circles, color=myColor, linewidth=1) 

plot(ema, color=color.white, linewidth=2, title="EMA")

exswingH = typeSL == "Swing" ? swingHigh : na
exswingL = typeSL == "Swing" ? swingLow : na
plot(exswingH, color=color.new(color.white, 60), style=plot.style_cross, title='Swing High')
plot(exswingL, color=color.new(color.white, 60), style=plot.style_cross, title='Swing Low')

exatrS = typeSL == "ATR" ? atrSell : na
exatrB = typeSL == "ATR" ? atrBuy : na
plot(exatrS, color=color.new(color.white, 60), title='ATR')
plot(exatrB, color=color.new(color.white, 60), title='ATR')

p_ep = plot(entry_price, color=color.new(color.white, 0), linewidth=2, style=plot.style_linebr, title='entry price')
p_sl = plot(stopLoss, color=color.new(color.red, 0), linewidth=2, style=plot.style_linebr, title='stopLoss')
p_tp2 = plot(takeProfit2, color=color.new(color.green, 0), linewidth=2, style=plot.style_linebr, title='takeProfit1')
p_tp1 = plot(takeProfit1, color=color.new(#52F071, 0), linewidth=1, style=plot.style_linebr, title='takeProfit2')
fill(p_sl, p_ep, color.new(color.red, transp=85))
fill(p_tp2, p_ep, color.new(color.green, transp=85))
fill(p_tp1, p_ep, color.new(#52F071, transp=85))

colorresult = strategy.netprofit > 0 ? color.green : color.red	
profitprc = strategy.netprofit / strategy.initial_capital * 100
periodzone = (backtestEndDate - backtestStartDate) / 3600 / 24 / 1000

var tbl = table.new(position.top_right, 4, 2, border_width=3)

table.cell(tbl, 0, 0, "Symbole",  bgcolor = #9B9B9B, width = 6, height = 6)
table.cell(tbl, 1, 0, "Net Profit", bgcolor = #9B9B9B, width = 6, height = 6)
table.cell(tbl, 2, 0, "Trades", bgcolor = #9B9B9B, width = 6, height = 6)
table.cell(tbl, 3, 0, "Period",  bgcolor = #9B9B9B, width = 6, height = 6)
    
table.cell(tbl, 0, 1, str.tostring(syminfo.ticker),  bgcolor = #E8E8E8, width = 6, height = 6)
table.cell(tbl, 1, 1, str.tostring(profitprc, format.mintick) + " %", bgcolor = colorresult,   width = 6, height = 6)
table.cell(tbl, 2, 1, str.tostring(strategy.closedtrades), bgcolor = colorresult,   width = 6, height = 6)
table.cell(tbl, 3, 1, str.tostring(periodzone) + " day", bgcolor = colorresult,   width = 6, height = 6)