TradingView Alerts to MT4 MT5 + dynamic variables NON-REPAINTING
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Peter_O

//@version=5
strategy(title='TradingView Alerts to MT4 MT5 Strategy example', commission_type=strategy.commission.cash_per_order, commission_value=0.00003, overlay=false, default_qty_value=100000, initial_capital=1000)
//study(title="TradingView Alerts to MT4 MT5 Strategy example")  //uncomment this line and comment previous one to make it a study producing alerts
//
// This script was created for educational purposes only.
// It is showing how to use dynamic variables in TradingView alerts.
// And how to execute them in Forex, indices and commodities markets

TakeProfitDistance = input(400)
TakePartialProfitDistance = input(150)

// **** Entries logic **** {
periodK = input.int(13, title='K', minval=1)
periodD = input.int(3, title='D', minval=1)
smoothK = input.int(4, title='Smooth', minval=1)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
plot(k, title='%K', color=color.new(color.blue, 0))
plot(d, title='%D', color=color.new(color.orange, 0))
h0 = hline(80)
h1 = hline(20)
fill(h0, h1, color=color.new(color.purple, 75))

GoLong = ta.crossover(k, d) and k < 80
GoShort = ta.crossunder(k, d) and k > 20
// } End of entries logic

// **** Pivot-points and stop-loss logic **** {
piv_high = ta.pivothigh(high, 1, 1)
piv_low = ta.pivotlow(low, 1, 1)
var float stoploss_long = low
var float stoploss_short = high

pl = ta.valuewhen(piv_low, piv_low, 0)
ph = ta.valuewhen(piv_high, piv_high, 0)

if GoLong
    stoploss_long := low < pl ? low : pl
    stoploss_long
if GoShort
    stoploss_short := high > ph ? high : ph
    stoploss_short
// } End of Pivot-points and stop-loss logic

strategy.entry('Long', strategy.long, when=GoLong)
strategy.exit('XPartLong', from_entry='Long', qty_percent=50, profit=TakePartialProfitDistance)
strategy.exit('XLong', from_entry='Long', stop=stoploss_long, profit=TakeProfitDistance)
strategy.entry('Short', strategy.short, when=GoShort)
strategy.exit('XPartShort', from_entry='Short', qty_percent=50, profit=TakePartialProfitDistance)
strategy.exit('XShort', from_entry='Short', stop=stoploss_short, profit=TakeProfitDistance)

if GoLong
    alertsyntax_golong = 'long slprice=' + str.tostring(stoploss_long) + ' tp1=' + str.tostring(TakePartialProfitDistance) + ' part1=0.5 tp=' + str.tostring(TakeProfitDistance)
    alert(message=alertsyntax_golong, freq=alert.freq_once_per_bar_close)
if GoShort
    alertsyntax_goshort = 'short slprice=' + str.tostring(stoploss_short) + ' tp1=' + str.tostring(TakePartialProfitDistance) + ' part1=0.5 tp=' + str.tostring(TakeProfitDistance)
    alert(message=alertsyntax_goshort, freq=alert.freq_once_per_bar_close)
