Double Supertrend Entry with ADX Filter and ATR Exits/Entries
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AlphaOne28
//DISOBAE
//@version=5
indicator("SuperRWI Strategy", shorttitle="SuperRWI", overlay=true)

// Input Parameters
Periods = input.int(title="Supertrend 1 ATR Period", defval=14)
src = input(close, title="Source")
showsignals = input.bool(title="Show Buy/Sell Signals?", defval=true)
Multiplier = input.float(title="ATR Multiplier", defval=2.0)
changeATR = input.bool(title="Change ATR Calculation Method?", defval=true)
//highlighting = input.bool(title="Highlighter On/Off?", defval=false)
//Periods2 = input.int(title="Supertrend 2 ATR Period 2", defval=21)
//Multiplier2 = input.float(title="ATR Multiplier 2", defval=1.9)
//changeATR2 = input.bool(title="Change ATR 2 Calculation Method?", defval=true)
//highlighting2 = input.bool(title="Highlighter 2 On/Off?", defval=false)

//Set trading window
trading_window_start = input(9,"Trading Window Start")
trading_window_end = input(13,"Trading Window End")
t1 = timestamp(syminfo.timezone, year, month, dayofmonth, trading_window_start, 00, 00)
t2 = timestamp(syminfo.timezone, year, month, dayofmonth, trading_window_end, 00, 00)

// Input Parameters for DMI/ADX
dmiLength = input.int(14, title="DMI Length", minval=1)
adxLevel = input.int(0, title="ADX Threshold", minval=0)
adxSmoothing = input.int(14, title="ADX Smoothing", minval=1)

//Input Parameters for the Random Walk calc
RWlength = input.int(title="Random Walk Lookback", defval=5)
RWTrigger = input.float(title="RWI Trigger Threshold", defval=1)
//RWIDifferenceThreshold = input.float(title="Min RWI Expansion Allowed", defval=0.5)

// Input Parameters for profit target and stop loss
showSLTPLines = input.bool(title="Show Stop Loss & Take Profit Lines?", defval=true)
Periods3 = input.int(title="Profit Target ATR Period", defval=14)
Periods4 = input.int(title="Stop Loss ATR Period", defval=14)
profitTargetMultiplier = input.float(title="Profit Target Multiplier", defval=1.4)
stopLossMultiplier = input.float(title="Stop Loss Multiplier", defval=0.4)

// Adding an EMA filter to the trades
EMALen = input.int(50, minval=1, title="EMA Filter Length")
EMASrc = input(close, title="EMA Source")
EMAFilter = ta.ema(EMASrc, EMALen)

// Plot the EMA
plot(EMAFilter, "EMA Filter", color=color.white)

// Check if price is above or below the EMA
price_above_ema = close > EMAFilter
price_below_ema = close < EMAFilter

// Supertrend Function
supertrend(src, factor, length, changeATR = true) =>
    atr2 = ta.sma(ta.atr(length), length)
    atr = changeATR ? ta.atr(length) : atr2
    up = src - (factor * atr)
    up1 = nz(up[1], up)
    up := close[1] > up1 ? math.max(up, up1) : up
    dn = src + (factor * atr)
    dn1 = nz(dn[1], dn)
    dn := close[1] < dn1 ? math.min(dn, dn1) : dn
    trend = 1
    trend := nz(trend[1], trend)
    trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
    [up, dn, trend]

// Calculate Supertrends
[up1, dn1, supertrend1] = supertrend(src, Multiplier, Periods, changeATR)
//[up2, dn2, supertrend2] = supertrend(src, Multiplier2, Periods2, changeATR2)

// Calculate ATR for Profit target and Stop Losses
Profit_ATR = ta.atr(Periods3)
Stop_ATR = ta.atr(Periods4)

// Calculate DMI and ADX for the trade filtering
[diplus, diminus, adx] = ta.dmi(dmiLength, adxSmoothing)

//Calculate the random walk index
rwiHigh = (high - nz(low[RWlength])) / (ta.atr(RWlength) * math.sqrt(RWlength))
rwiLow = (nz(high[RWlength]) - low) / (ta.atr(RWlength) * math.sqrt(RWlength))
//rwiDifference1 = rwiHigh - rwiLow
//rwiDifference2 = rwiLow - rwiHigh

// Plotting Supertrend lines
upPlot1 = plot(supertrend1 == 1 ? up1 : na, title="Up Trend 1", style=plot.style_linebr, linewidth=2, color=color.green)
dnPlot1 = plot(supertrend1 == -1 ? dn1 : na, title="Down Trend 1", style=plot.style_linebr, linewidth=2, color=color.red)

//upPlot2 = plot(supertrend2 == 1 ? up2 : na, title="Up Trend 2", style=plot.style_linebr, linewidth=2, color=color.green)
//dnPlot2 = plot(supertrend2 == -1 ? dn2 : na, title="Down Trend 2", style=plot.style_linebr, linewidth=2, color=color.red)

// Plotting the highlighters
//mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
//longFillColor = highlighting ? (supertrend1 == 1 ? color.green : color.white) : color.white
//shortFillColor = highlighting ? (supertrend1 == -1 ? color.red : color.white) : color.white
//fill(mPlot, upPlot1, title="UpTrend Highligter", color=longFillColor)
//fill(mPlot, dnPlot1, title="DownTrend Highligter", color=shortFillColor)

//mPlot2 = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
//longFillColor2 = highlighting2 ? (supertrend2 == 1 ? color.green : color.white) : color.white
//shortFillColor2 = highlighting2 ? (supertrend2 == -1 ? color.red : color.white) : color.white
//fill(mPlot2, upPlot2, title="UpTrend Highligter", color=longFillColor2)
//fill(mPlot2, dnPlot2, title="DownTrend Highligter", color=shortFillColor2)

//Take profit and Stop loss levels
var float long_tp_level = na
var float long_sl_level = na
var float short_tp_level = na
var float short_sl_level = na

//Are we in a trade?
var bool in_long_trade = false
var bool in_short_trade = false

// At what price did we enter?
var float long_entry_price = na
var float short_entry_price = na

//define entries
long_entry = (ta.barssince(ta.crossover(close, dn1)) <= 1 and close > dn1) and not in_long_trade and not in_short_trade and (time > t1 and time < t2) and (rwiHigh >= RWTrigger) and (adxLevel == 0 or adx >= adxLevel) and price_above_ema
if long_entry
    long_tp_level := close + (Profit_ATR * profitTargetMultiplier)
    long_sl_level := close - (Stop_ATR * stopLossMultiplier)
    in_long_trade := true
    long_entry_price := close

else
    long_entry := false

short_entry =  (ta.barssince(ta.crossunder(close, up1)) <= 1 and close < up1) and not in_long_trade and not in_short_trade and (time > t1 and time < t2) and (rwiLow >= RWTrigger) and (adxLevel == 0 or adx >= adxLevel) and price_below_ema
if short_entry
    short_tp_level := close - (Profit_ATR * profitTargetMultiplier)
    short_sl_level := close + (Stop_ATR * stopLossMultiplier)
    in_short_trade := true
    short_entry_price := close
else
    short_entry := false

//Define the exits
long_tp_reached = in_long_trade and ta.crossover(close, long_tp_level)
long_sl_reached = in_long_trade and ta.crossunder(close, long_sl_level)
short_tp_reached = in_short_trade and ta.crossunder(close, short_tp_level)
short_sl_reached = in_short_trade and ta.crossover(close, short_sl_level) 

long_exit = long_tp_reached or long_sl_reached
if long_exit
    in_long_trade := false

short_exit = short_tp_reached or short_sl_reached
if short_exit
    in_short_trade := false

// Backtesting
// The following can be used to stream signals to a backtest adapter
backTestStream = switch 
    long_entry => 1
    long_exit => 2
    short_entry => -1
    short_exit => -2
plot(backTestStream, "Backtest Stream", display=display.none)


// Plotting Entry and Exit Signals
plotshape(long_entry and showsignals ? close : na, title="Buy", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white)
plotshape(short_entry and showsignals ? close : na, title="Sell", text="Sell", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white)

plotshape(long_exit and showsignals and long_tp_reached ? close : na, title="Exit", text="TP", location=location.abovebar, style=shape.circle, size=size.tiny, color=color.green, textcolor=color.white)
plotshape(long_exit and showsignals and long_sl_reached ? close : na, title="Exit", text="SL", location=location.abovebar, style=shape.xcross, size=size.tiny, color=color.red, textcolor=color.white)
plotshape(short_exit and showsignals and short_tp_reached ? close : na, title="Exit", text="TP", location=location.belowbar, style=shape.circle, size=size.tiny, color=color.red, textcolor=color.white)
plotshape(short_exit and showsignals and short_sl_reached ? close : na, title="Exit", text="SL", location=location.belowbar, style=shape.xcross, size=size.tiny, color=color.green, textcolor=color.white)

// Add alert conditions for long and short entries
alertcondition(long_entry, title="Long Entry", message="Long Entry Signal: Price has crossed both Supertrends.")
alertcondition(short_entry, title="Short Entry", message="Short Entry Signal: Price has crossed both Supertrends.")

//Plotting take profit and stop loss levels
plot(showSLTPLines and in_long_trade ? long_sl_level : na, title="Long Stop Loss", style=plot.style_linebr, linewidth=1, color=color.red)
plot(showSLTPLines and in_long_trade ? long_tp_level : na, title="Long Take Profit", style=plot.style_linebr, linewidth=1, color=color.green)
plot(showSLTPLines and in_short_trade ? short_sl_level : na, title="Short Stop Loss", style=plot.style_linebr, linewidth=1, color=color.red)
plot(showSLTPLines and in_short_trade ? short_tp_level : na, title="Short Take Profit", style=plot.style_linebr, linewidth=1, color=color.green)


// BUILDING A TRADING STATISTICS TABLE BELOW
//
//
// Initialize trade counters and running profit/loss
var int total_wins = 0
var int total_losses = 0
var float running_profit = 0.0
var float running_loss = 0.0

// Update trade counters and running profit/loss
if (long_exit and showsignals)
    if (long_tp_reached)
        total_wins := total_wins + 1
        running_profit := running_profit + (close - long_entry_price)
    else if (long_sl_reached)
        total_losses := total_losses + 1
        running_loss := running_loss + (long_entry_price - close)

if (short_exit and showsignals)
    if (short_tp_reached)
        total_wins := total_wins + 1
        running_profit := running_profit + (short_entry_price - close)
    else if (short_sl_reached)
        total_losses := total_losses + 1
        running_loss := running_loss + (close - short_entry_price)

// Calculate win/loss percentage and average profit/loss
float win_percentage = total_wins + total_losses > 0 ? total_wins * 100 / (total_wins + total_losses) : na
float avg_profit = total_wins > 0 ? running_profit / total_wins : na
float avg_loss = total_losses > 0 ? running_loss / total_losses : na
float pnl = running_profit + running_loss


// Table initialization and update functions
init_table() =>
    c_transparent = color.new(color.black, 100)
    table.new(position.top_right, columns=2, rows=7, frame_color=color.new(color.black, 100), frame_width=1, border_width=1, border_color=c_transparent)

update_table(tbl, totalWins, totalLosses, winPercentage, avgProfit, avgLoss, pnl) =>
    table.cell(tbl, 0, 0, "Winning Trades", bgcolor=color.gray, text_color=color.white)
    table.cell(tbl, 1, 0, str.tostring(totalWins), bgcolor=color.green, text_color=color.white)

    table.cell(tbl, 0, 1, "Losing Trades", bgcolor=color.gray, text_color=color.white)
    table.cell(tbl, 1, 1, str.tostring(totalLosses), bgcolor=color.red, text_color=color.white)

    table.cell(tbl, 0, 2, "% Profitable", bgcolor=color.gray, text_color=color.white)
    table.cell(tbl, 1, 2, not na(winPercentage) ? str.tostring(winPercentage, "0") + "%" : "N/A", bgcolor=color.gray, text_color=color.white)

    table.cell(tbl, 0, 3, "Avg Profit", bgcolor=color.gray, text_color=color.white)
    table.cell(tbl, 1, 3, not na(avgProfit) ? str.tostring(avgProfit, "0 points") : "N/A", bgcolor=color.green, text_color=color.white)

    table.cell(tbl, 0, 4, "Avg Loss", bgcolor=color.gray, text_color=color.white)
    table.cell(tbl, 1, 4, not na(avgLoss) ? str.tostring(avgLoss, "0 points") : "N/A", bgcolor=color.red, text_color=color.white)

    table.cell(tbl, 0, 5, "Current ATR", bgcolor=color.gray, text_color=color.white)
    table.cell(tbl, 1, 5, str.tostring(Profit_ATR, "0 points"), bgcolor=color.gray, text_color=color.white)

    table.cell(tbl, 0, 6, "Current ADX", bgcolor=color.gray, text_color=color.white)
    table.cell(tbl, 1, 6, str.tostring(adx, "0"), bgcolor=color.gray, text_color=color.white)

//   table.cell(tbl, 4, 1, "P&L", bgcolor=color.gray, text_color=color.white)
//   table.cell(tbl, 5, 1, str.tostring(pnl, "0 points"), bgcolor=color.gray, text_color=color.white)

mytable = init_table()
update_table(mytable, total_wins, total_losses, win_percentage, avg_profit, avg_loss, pnl)
