

//@version=5
// تعریف به عنوان استراتژی تا قابلیت بک‌تست داشته باشد
strategy("Spike Structure (Hybrid Mode)", overlay=true, initial_capital=10000, default_qty_type=strategy.fixed, default_qty_value=1, currency=currency.USD, max_lines_count=500, max_labels_count=500)

// --- تنظیمات ورودی ---
// *** سوییچ حالت ***
runStrategy = input.bool(false, "🔴 Run Backtest Strategy?", tooltip="If checked, it executes trades. If unchecked, it acts as an Indicator.", group="MODE SETTINGS")

// تنظیمات فنی
atrLen = input.int(14, "ATR Length", group="Strategy Settings")
spikeMult = input.float(1.0, "Spike Strength Multiplier", group="Strategy Settings") 
emaLen = input.int(60, "EMA Filter Length", group="Strategy Settings")
bodyRatio = input.float(0.6, "Min Body-to-Range Ratio", group="Strategy Settings")
rrRatio = input.float(2.0, "Risk/Reward Ratio (TP)", group="Strategy Settings")

// فیلتر زمانی (فقط برای حالت بک‌تست موثر است)
useDateFilter = input.bool(true, "Filter Date Range", group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2023"), "Start Date", group="Backtest Time Period")
backtestEndDate = input.time(timestamp("1 Jan 2030"), "End Date", group="Backtest Time Period")
inTradeWindow = not useDateFilter or (time >= backtestStartDate and time <= backtestEndDate)

// --- اندیکاتورهای کمکی ---
ema60 = ta.ema(close, emaLen)
plot(ema60, color=color.gray, title="EMA 60")

// --- توابع تشخیص قدرت کندل ---
isPowerful(idx) => 
    cRange = high[idx] - low[idx]
    cBody = math.abs(close[idx] - open[idx])
    cBody >= cRange * bodyRatio and cBody > ta.atr(atrLen)[idx] * spikeMult

// --- تشخیص اسپایک (2 کندلی - حساس) ---
bullSpike = false
if close > ema60 
    spike2 = isPowerful(0) and isPowerful(1) and close[0] > open[0] and close[1] > open[1] and low[0] > low[1]
    bullSpike := spike2 

bearSpike = false
if close < ema60 
    spike2 = isPowerful(0) and isPowerful(1) and close[0] < open[0] and close[1] < open[1] and high[0] < high[1]
    bearSpike := spike2 

// --- متغیرهای وضعیت (State Machine) ---
// 0=هیچ، 1=شتاب، 2=اصلاح، 3=معامله باز (Virtual or Real)، 4=تمام شده
var int phase = 0 
var int spikeDirection = 0 // 1=Bull, -1=Bear

// متغیرهای حیاتی اسپایک
var float spikeOrigin = na 

// متغیرهای تریلینگ (Pending)
var float pendingH = na
var float pendingL = na
var int pendingIdx = na

// متغیرهای مدیریت معامله (برای هر دو حالت لازم است)
var float entryPrice = na
var float stopPrice = na
var float targetPrice = na

// خطوط گرافیکی موقت
var line floatLineH = na
var line floatLineL = na
var label floatLabelH = na
var label floatLabelL = na

// --- رویداد: اسپایک جدید ---
// اگر در فاز معامله نیستیم، اسپایک جدید اولویت دارد
isNewBull = bullSpike and phase != 3
isNewBear = bearSpike and phase != 3

if isNewBull
    phase := 1 
    spikeDirection := 1
    spikeOrigin := low[1] 
    
    line.delete(floatLineH)
    line.delete(floatLineL)
    label.delete(floatLabelH)
    label.delete(floatLabelL)
    
    // نمایش لیبل اسپایک (در هر دو حالت)
    //label.new(bar_index, high + ta.atr(14), "BULL SPIKE", color=color.green, textcolor=color.white, style=label.style_label_down, size=size.small)

if isNewBear
    phase := 1 
    spikeDirection := -1
    spikeOrigin := high[1] 
    
    line.delete(floatLineH)
    line.delete(floatLineL)
    label.delete(floatLabelH)
    label.delete(floatLabelL)
    
    //label.new(bar_index, low - ta.atr(14), "BEAR SPIKE", color=color.red, textcolor=color.white, style=label.style_label_up, size=size.small)

// --- لاجیک ابطال (Kill Switch) ---
if phase == 1 or phase == 2 or phase == 3
    if spikeDirection == 1 and low <= spikeOrigin
        phase := 4 
        //label.new(bar_index, spikeOrigin, "INVALID", textcolor=color.gray, style=label.style_label_up, size=size.small)
        // اگر استراتژی فعال بود، پوزیشن را ببند
        if runStrategy
            strategy.close("Long Spk", comment="Invalidated")
        
        line.delete(floatLineH)
        line.delete(floatLineL)
        label.delete(floatLabelH)
        label.delete(floatLabelL)
        
    else if spikeDirection == -1 and high >= spikeOrigin
        phase := 4 
        //label.new(bar_index, spikeOrigin, "INVALID", textcolor=color.gray, style=label.style_label_down, size=size.small)
        if runStrategy
            strategy.close("Short Spk", comment="Invalidated")
            
        line.delete(floatLineH)
        line.delete(floatLineL)
        label.delete(floatLabelH)
        label.delete(floatLabelL)

// --- منطق اصلی ---
if phase != 4 and phase != 0

    // 1. فاز شتاب (Impulse)
    if phase == 1
        if spikeDirection == 1
            if high <= high[1] // شروع اصلاح
                phase := 2 
                pendingH := high
                pendingL := low
                pendingIdx := bar_index
                floatLineH := line.new(bar_index, high, bar_index + 3, high, color=color.yellow, style=line.style_dotted)
                floatLineL := line.new(bar_index, low, bar_index + 3, low, color=color.blue, style=line.style_dotted)
                floatLabelH := label.new(bar_index + 3, high, "H", textcolor=color.yellow, style=label.style_none, size=size.small)
                floatLabelL := label.new(bar_index + 3, low, "L", textcolor=color.blue, style=label.style_none, size=size.small)

        else if spikeDirection == -1
            if low >= low[1] // شروع اصلاح
                phase := 2
                pendingH := high
                pendingL := low
                pendingIdx := bar_index
                floatLineH := line.new(bar_index, high, bar_index + 3, high, color=color.purple, style=line.style_dotted)
                floatLineL := line.new(bar_index, low, bar_index + 3, low, color=color.orange, style=line.style_dotted)
                floatLabelH := label.new(bar_index + 3, high, "S", textcolor=color.purple, style=label.style_none, size=size.small , color = #2195f390)
                floatLabelL := label.new(bar_index + 3, low, "E", textcolor=color.orange, style=label.style_none, size=size.small , color = #2195f390)

    // 2. فاز اصلاح (Correction) - جستجوی نقطه ورود
    else if phase == 2
        
        // === صعودی ===
        if spikeDirection == 1
            if high > pendingH // Trigger Entry
                phase := 3
                entryPrice := pendingH
                stopPrice := math.min(pendingL,low)
                float dist = entryPrice - stopPrice
                targetPrice := entryPrice + (dist * rrRatio)
                
                // پاک کردن خطوط شناور
                line.delete(floatLineH)
                line.delete(floatLineL)
                label.delete(floatLabelH)
                label.delete(floatLabelL)
                
                // رسم خطوط ثابت (E, S, T) - هم در استراتژی هم اندیکاتور
                line.new(pendingIdx, entryPrice, bar_index + 5, entryPrice, color=color.white, style=line.style_solid, width=1)
                label.new(pendingIdx, entryPrice, "E", textcolor=color.white, style=label.style_label_down, size=size.small, color = #2195f351)
                line.new(pendingIdx, stopPrice, bar_index + 5, stopPrice, color=color.red, style=line.style_solid, width=1)
                label.new(pendingIdx, stopPrice, "S", textcolor=color.red, style=label.style_label_up, size=size.small , color = #2195f351)
                line.new(bar_index, targetPrice, bar_index + 10, targetPrice, color=color.green, style=line.style_dashed, width=1)
                label.new(bar_index + 10, targetPrice, "T", textcolor=color.green, style=label.style_label_left, size=size.small , color = #2195f351)
                
                // *** بخش استراتژی (فقط اگر تیک خورده باشد) ***
                if runStrategy and inTradeWindow
                    strategy.entry("Long Spk", strategy.long, stop=entryPrice)
                    strategy.exit("Exit Long", "Long Spk", stop=stopPrice, limit=targetPrice)
                
            else // تریلینگ
                line.delete(floatLineH)
                line.delete(floatLineL)
                label.delete(floatLabelH)
                label.delete(floatLabelL)
                
                pendingH := high
                pendingL := low
                pendingIdx := bar_index
                
                floatLineH := line.new(bar_index, high, bar_index + 3, high, color=color.yellow, style=line.style_dotted)
                floatLineL := line.new(bar_index, low, bar_index + 3, low, color=color.blue, style=line.style_dotted)
                floatLabelH := label.new(bar_index + 3, high, "H", textcolor=color.yellow, style=label.style_none, size=size.small , color = #2195f351)
                floatLabelL := label.new(bar_index + 3, low, "L", textcolor=color.blue, style=label.style_none, size=size.small , color = color.rgb(243, 233, 33, 68))

        // === نزولی ===
        else if spikeDirection == -1
            if low < pendingL // Trigger Entry
                phase := 3
                entryPrice := pendingL
                stopPrice := math.max(pendingH,high)
                float dist = stopPrice - entryPrice
                targetPrice := entryPrice - (dist * rrRatio)
                
                line.delete(floatLineH)
                line.delete(floatLineL)
                label.delete(floatLabelH)
                label.delete(floatLabelL)
                
                line.new(pendingIdx, entryPrice, bar_index + 5, entryPrice, color=color.white, style=line.style_solid, width=1)
                label.new(pendingIdx, entryPrice, "E", textcolor=color.white, style=label.style_label_up, size=size.small , color = #2195f351)
                line.new(pendingIdx, stopPrice, bar_index + 5, stopPrice, color=color.red, style=line.style_solid, width=1)
                label.new(pendingIdx, stopPrice, "S", textcolor=color.red, style=label.style_label_down, size=size.small , color = #2195f351)
                line.new(bar_index, targetPrice, bar_index + 10, targetPrice, color=color.green, style=line.style_dashed, width=1)
                label.new(bar_index + 10, targetPrice, "T", textcolor=color.green, style=label.style_label_left, size=size.small , color = #2195f351)
                
                // *** بخش استراتژی ***
                if runStrategy and inTradeWindow
                    strategy.entry("Short Spk", strategy.short, stop=entryPrice)
                    strategy.exit("Exit Short", "Short Spk", stop=stopPrice, limit=targetPrice)
                
            else // تریلینگ
                line.delete(floatLineH)
                line.delete(floatLineL)
                label.delete(floatLabelH)
                label.delete(floatLabelL)
                
                pendingH := high
                pendingL := low
                pendingIdx := bar_index
                
                floatLineH := line.new(bar_index, high, bar_index + 3, high, color=color.purple, style=line.style_dotted)
                floatLineL := line.new(bar_index, low, bar_index + 3, low, color=color.orange, style=line.style_dotted)
                floatLabelH := label.new(bar_index + 3, high, "S", textcolor=color.purple, style=label.style_none, size=size.small , color = #2195f351)
                floatLabelL := label.new(bar_index + 3, low, "E", textcolor=color.orange, style=label.style_none, size=size.small , color = #2195f351)

    // 3. فاز معامله باز (Active Trade - Manual check for Indicator Mode)
    // ما باید خودمان دستی TP/SL را چک کنیم تا در حالت اندیکاتور هم فازها درست کار کنند
    else if phase == 3
        if spikeDirection == 1
            if high >= targetPrice
                // WIN
                //label.new(bar_index, targetPrice, "WIN", textcolor=color.green, style=label.style_label_down, size=size.small)
                phase := 4 
                
            else if low <= stopPrice
                // LOSS
                //label.new(bar_index, stopPrice, "LOSS", textcolor=color.red, style=label.style_label_up, size=size.small)
                // بازگشت به فاز اصلاح (Re-Entry)
                phase := 2 
                pendingH := high
                pendingL := low
                pendingIdx := bar_index
                floatLineH := line.new(bar_index, high, bar_index + 3, high, color=color.yellow, style=line.style_dotted)
                floatLineL := line.new(bar_index, low, bar_index + 3, low, color=color.blue, style=line.style_dotted)
                floatLabelH := label.new(bar_index + 3, high, "H", textcolor=color.yellow, style=label.style_none, size=size.small , color = #2195f351)
                floatLabelL := label.new(bar_index + 3, low, "L", textcolor=color.blue, style=label.style_none, size=size.small , color = color.rgb(243, 233, 33, 68))
                
        else if spikeDirection == -1
            if low <= targetPrice
                // WIN
                label.new(bar_index, targetPrice, "WIN", textcolor=color.green, style=label.style_label_up, size=size.small , color = #2195f351)
                phase := 4
                
            else if high >= stopPrice
                // LOSS -> Re-Entry
                label.new(bar_index, stopPrice, "LOSS", textcolor=color.red, style=label.style_label_down, size=size.small , color = #2195f351)
                phase := 2 
                pendingH := high
                pendingL := low
                pendingIdx := bar_index
                floatLineH := line.new(bar_index, high, bar_index + 3, high, color=color.purple, style=line.style_dotted)
                floatLineL := line.new(bar_index, low, bar_index + 3, low, color=color.orange, style=line.style_dotted)
                floatLabelH := label.new(bar_index + 3, high, "S", textcolor=color.purple, style=label.style_none, size=size.small , color = #2195f351)
                floatLabelL := label.new(bar_index + 3, low, "E", textcolor=color.orange, style=label.style_none, size=size.small , color = #2195f351)
