//@version=5
strategy("HARSI Strategy with Confirmations", overlay=true, 
         default_qty_type=strategy.percent_of_equity, 
         default_qty_value=10, 
         initial_capital=10000, 
         currency=currency.USD, 
         calc_on_every_tick=true)

// ----------------------------------------------------------------------------
// === INPUTS ===

// HARSI Candles Configuration
group_cand = "Config » HARSI Candles"
i_lenHARSI  = input.int(title="HARSI Length", defval=14, minval=1, group=group_cand)
i_smoothing = input.int(title="HARSI Open Smoothing", defval=1, minval=1, maxval=100, group=group_cand)
i_colUp     = input.color(title="HARSI Up Color", defval=color.teal, group=group_cand)
i_colDown   = input.color(title="HARSI Down Color", defval=color.red, group=group_cand)
i_colWick   = input.color(title="HARSI Wick Color", defval=color.gray, group=group_cand)

// RSI Plot Configuration
group_plot = "Config » RSI Plot"
my_hlc4    = (high + low + close + open) / 4
i_source   = input.source(title="RSI Source", defval=my_hlc4, group=group_plot)
i_lenRSI   = input.int(title="RSI Length", defval=7, minval=1, group=group_plot)
i_mode     = input.bool(title="Smoothed Mode RSI?", defval=true, group=group_plot)
i_showPlot = input.bool(title="Show RSI Plot?", defval=true, group=group_plot)
i_showHist = input.bool(title="Show RSI Histogram?", defval=true, group=group_plot)

// Stochastic RSI Plot Configuration
group_stoch = "Config » Stochastic RSI Plot"
i_showStoch = input.bool(title="Show Stochastic RSI?", defval=false, group=group_stoch)
i_ribbon    = input.bool(title="Stochastic Ribbon?", defval=true, group=group_stoch)
i_smoothK   = input.int(title="Stochastic K Smoothing", defval=3, minval=1, group=group_stoch)
i_smoothD   = input.int(title="Stochastic D Smoothing", defval=3, minval=1, group=group_stoch)
i_stochLen  = input.int(title="Stochastic Length", defval=14, minval=1, group=group_stoch)
i_stochFit  = input.int(title="Stochastic Scaling (%)", defval=80, minval=1, maxval=100, group=group_stoch)

// OB/OS Boundaries Configuration
group_chan = "Config » OB/OS Boundaries"
i_upper     = input.int(title="Overbought Level (OB)", defval=20, minval=1, maxval=50, group=group_chan)
i_upperx    = input.int(title="OB Extreme Level", defval=30, minval=1, maxval=50, group=group_chan)
i_lower     = input.int(title="Oversold Level (OS)", defval=-20, minval=-50, maxval=-1, group=group_chan)
i_lowerx    = input.int(title="OS Extreme Level", defval=-30, minval=-50, maxval=-1, group=group_chan)

// Confirmation Indicators Configuration
group_conf = "Config » Confirmations"
ema_enabled    = input.bool(title="Use EMA Confirmation", defval=true, group=group_conf)
ema_length     = input.int(title="EMA Length", defval=50, minval=1, group=group_conf)
vol_enabled    = input.bool(title="Use Volume Oscillator", defval=true, group=group_conf)
vol_osc_length = input.int(title="Volume Oscillator Length", defval=20, minval=1, group=group_conf)
adx_enabled    = input.bool(title="Use ADX Confirmation", defval=true, group=group_conf)
adx_length     = input.int(title="ADX Length", defval=14, minval=1, group=group_conf)
adx_threshold  = input.int(title="ADX Threshold", defval=25, minval=1, group=group_conf)
vortex_enabled = input.bool(title="Use Vortex Confirmation", defval=true, group=group_conf)
vortex_length  = input.int(title="Vortex Length", defval=14, minval=1, group=group_conf)

// Risk Management Configuration
group_risk = "Config » Risk Management"
tp_enabled    = input.bool(title="Enable Take Profit", defval=false, group=group_risk)
tp_percent    = input.float(title="Take Profit (%)", defval=2.0, minval=0.1, step=0.1, group=group_risk)
sl_enabled    = input.bool(title="Enable Stop Loss", defval=true, group=group_risk)
sl_percent    = input.float(title="Stop Loss (%)", defval=1.0, minval=0.1, step=0.1, group=group_risk)
tsl_enabled   = input.bool(title="Enable Trailing Stop Loss", defval=true, group=group_risk)
tsl_percent   = input.float(title="Trailing Stop Loss (%)", defval=1.5, minval=0.1, step=0.1, group=group_risk)
tsl_arm_level = input.float(title="TSL Arm Level (%)", defval=0.5, minval=0.1, step=0.1, group=group_risk)

// ----------------------------------------------------------------------------
// === FUNCTIONS ===

// Function to calculate HARSI Heikin Ashi values
f_rsiHeikinAshi(_length) =>
    _closeRSI = rsi(close, _length) - 50
    _openRSI  = nz(_closeRSI[1], _closeRSI)
    _highRSI_raw = rsi(high, _length) - 50
    _lowRSI_raw  = rsi(low, _length) - 50
    _highRSI = math.max(_highRSI_raw, _lowRSI_raw)
    _lowRSI  = math.min(_highRSI_raw, _lowRSI_raw)
    _close   = (_openRSI + _highRSI + _lowRSI + _closeRSI) / 4
    var float _open = na
    _open    := na(_open[1]) ? (_openRSI + _closeRSI) / 2 : ((_open[1] * i_smoothing) + _closeRSI) / (i_smoothing + 1)
    _high = math.max(_highRSI, math.max(_open, _close))
    _low  = math.min(_lowRSI, math.min(_open, _close))
    [_open, _high, _low, _close]

// ----------------------------------------------------------------------------
// === VORTEX INDICATOR FUNCTION (MANUAL IMPLEMENTATION) ===
f_vortex(_length) =>
    vm_plus = math.abs(high - low[1])
    vm_minus = math.abs(low - high[1])
    trur = tr(true)
    sum_vm_plus = sum(vm_plus, _length)
    sum_vm_minus = sum(vm_minus, _length)
    sum_tr = sum(trur, _length)
    vi_plus = sum_vm_plus / sum_tr
    vi_minus = sum_vm_minus / sum_tr
    [vi_plus, vi_minus]

// ----------------------------------------------------------------------------
// === CALCULATIONS ===

// Calculate HARSI Heikin Ashi values
[O, H, L, C] = f_rsiHeikinAshi(i_lenHARSI)

// Calculate RSI
RSI = rsi(i_source, i_lenRSI)
RSI_z = RSI - 50

// Calculate Stochastic RSI
StochK = stoch(RSI, RSI, RSI, i_stochLen) - 50
StochK_smoothed = sma(StochK, i_smoothK)
StochD = sma(StochK_smoothed, i_smoothD)

// Calculate Confirmation Indicators
// EMA
ema_val = ema(close, ema_length)

// Volume Oscillator
vol_sma_high = sma(volume, vol_osc_length)
vol_osc_val = volume - vol_sma_high

// ADX
adx_val = adx(adx_length)
diplus_val = plus_di(adx_length)
diminus_val = minus_di(adx_length)

// Vortex Indicator
[vi_plus, vi_minus] = f_vortex(vortex_length)

// ----------------------------------------------------------------------------
// === BUY AND SELL CONDITIONS ===

// Buy Condition:
// 1. HARSI Indicates Green HA Candle
// 2. Stochastic RSI crosses under Overbought (OB) line
// 3. Confirmation Indicators are met

harsi_green = C > O
stoch_cross_under_ob = crossunder(StochK_smoothed, i_upper)

buy_signal = harsi_green and stoch_cross_under_ob

// Apply Confirmation Conditions
buy_signal := buy_signal and (not ema_enabled or (close > ema_val))
buy_signal := buy_signal and (not vol_enabled or (vol_osc_val > 0))
buy_signal := buy_signal and (not adx_enabled or (diplus_val > diminus_val and adx_val > adx_threshold))
buy_signal := buy_signal and (not vortex_enabled or (vi_plus > vi_minus))

// Sell Condition:
// 1. Stochastic RSI crosses above OB Extreme line

stoch_cross_above_obx = crossover(StochK_smoothed, i_upperx)
sell_signal = stoch_cross_above_obx

// ----------------------------------------------------------------------------
// === RISK MANAGEMENT ===

// Calculate Take Profit and Stop Loss Prices
tp_price = strategy.position_avg_price * (1 + tp_percent / 100)
sl_price = strategy.position_avg_price * (1 - sl_percent / 100)

// Enter Long Position
if (buy_signal)
    strategy.entry("Long", strategy.long)

// Exit Long Position on Sell Signal
if (sell_signal)
    strategy.close("Long", comment="Stoch Cross OBX")

// Take Profit Exit
if (tp_enabled)
    strategy.exit("Take Profit", "Long", limit=tp_price)

// Stop Loss Exit
if (sl_enabled)
    strategy.exit("Stop Loss", "Long", stop=sl_price)

// Trailing Stop Loss Exit
if (tsl_enabled)
    // Arm TSL when price has moved in favor by tsl_arm_level
    trg_level = strategy.position_avg_price * (1 + tsl_arm_level / 100)
    if (close > trg_level)
        // Convert percentage to price difference
        trail_amount = strategy.position_avg_price * (tsl_percent / 100)
        strategy.exit("Trailing Stop", "Long", trail_offset=trail_amount, trail_points=trail_amount)

// ----------------------------------------------------------------------------
// === PLOTTING ===

// Plot HARSI Heikin Ashi Candles
plotcandle(O, H, L, C, title="HARSI Candles", 
           color=(C > O ? i_colUp : i_colDown), 
           wickcolor=i_colWick, bordercolor=(C > O ? i_colUp : i_colDown))

// Plot RSI and RSI Histogram
if i_showPlot
    plot(RSI, title="RSI", color=color.purple)
if i_showHist
    plot(RSI_z, title="RSI Histogram", color=color.gray, style=plot.style_histogram)

// Plot EMA
plot(ema_enabled ? ema_val : na, title="EMA", color=color.blue, linewidth=1)

// Plot Volume Oscillator
plot(vol_enabled ? vol_osc_val : na, title="Volume Oscillator", color=color.purple, style=plot.style_histogram)

// Plot ADX
plot(adx_enabled ? adx_val : na, title="ADX", color=color.orange)

// Plot Vortex Indicators
plot(vortex_enabled ? vi_plus : na, title="Vortex Plus", color=color.green)
plot(vortex_enabled ? vi_minus : na, title="Vortex Minus", color=color.red)

// Plot Buy and Sell Signals
plotshape(buy_signal, title="Buy Signal", location=location.belowbar, color=color.green, 
          style=shape.labelup, text="BUY")
plotshape(sell_signal, title="Sell Signal", location=location.abovebar, color=color.red, 
          style=shape.labeldown, text="SELL")

// ----------------------------------------------------------------------------
// === ALERTS ===

// Buy and Sell Alerts
alertcondition(buy_signal, title="Buy Alert", message="HARSI Strategy Buy Signal")
alertcondition(sell_signal, title="Sell Alert", message="HARSI Strategy Sell Signal")