//@version=5
indicator("Spike Structure (Clean History)", overlay=true, max_lines_count=500, max_labels_count=500)

// --- تنظیمات ---
atrLen = input.int(14, "ATR Length")
spikeMult = input.float(1, "Spike Strength Multiplier")
emaLen = input.int(60, "EMA Filter Length")
bodyRatio = input.float(0.4, "Min Body-to-Range Ratio")

// --- اندیکاتورهای کمکی ---
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

// --- تشخیص اسپایک صعودی ---
bullSpike = false
if close > ema60 
    spike3 = isPowerful(0) and isPowerful(1) and isPowerful(2) and high[0] > high[1] and high[1] > high[2] and close[0] > open[0] and close[1] > open[1] and close[2] > open[2]
    bullSpike := spike3 

// --- تشخیص اسپایک نزولی ---
bearSpike = false
if close < ema60 
    spike3 = isPowerful(0) and isPowerful(1) and isPowerful(2) and low[0] < low[1] and low[1] < low[2] and close[0] < open[0] and close[1] < open[1] and close[2] < open[2]
    bearSpike := spike3 

// --- مدیریت متغیرها ---
var int barsSinceSpike = 0
var int xCount = 0
var int activeSpikeType = 0 // 1 = Bull, -1 = Bear
var bool inMomentum = false 

// --- متغیرهای ذخیره خطوط و لیبل‌ها ---
var line lastLineL = na
var line lastLineH = na
var label lastLabelL = na
var label lastLabelH = na

// --- شروع اسپایک ---
if bullSpike
    activeSpikeType := 1
    inMomentum := true 
    barsSinceSpike := 0
    xCount := 0
    
    // *** نکته کلیدی: قطع ارتباط با اسپایک قبلی ***
    // با این کار خطوط اسپایک قبلی را "رها" می‌کنیم تا روی چارت بمانند
    // و متغیرها را برای اسپایک جدید آماده می‌کنیم.
    lastLineL := na
    lastLineH := na
    lastLabelL := na
    lastLabelH := na
    
    label.new(bar_index, high + ta.atr(14), "BULL SPIKE", color=#4caf4f86, textcolor=color.white, style=label.style_label_down, size=size.small)

if bearSpike
    activeSpikeType := -1
    inMomentum := true 
    barsSinceSpike := 0
    xCount := 0
    
    // قطع ارتباط با اسپایک قبلی
    lastLineL := na
    lastLineH := na
    lastLabelL := na
    lastLabelH := na
    
    label.new(bar_index, low - ta.atr(14), "BEAR SPIKE", color=#ff52525c, textcolor=color.white, style=label.style_label_up, size=size.small)

// --- منطق بررسی مومنتوم و ترسیم ---
if activeSpikeType != 0
    
    bool triggerDraw = false
    
    // 1. بررسی فاز مومنتوم
    if inMomentum
        // صعودی
        if activeSpikeType == 1
            if high > high[1]
                barsSinceSpike := 0 
            else
                inMomentum := false 
                triggerDraw := true

        // نزولی
        else if activeSpikeType == -1
            if low < low[1]
                barsSinceSpike := 0 
            else
                inMomentum := false
                triggerDraw := true

    // 2. فاز تریلینگ (حرکت استاپ و نقطه ورود)
    else 
        barsSinceSpike := barsSinceSpike + 1
        
        if barsSinceSpike <= 10
            // صعودی: تشکیل سقف پایین‌تر -> آپدیت نقطه ورود
            if activeSpikeType == 1 and high < high[1]
                triggerDraw := true
            
            // نزولی: تشکیل کف بالاتر -> آپدیت نقطه ورود
            else if activeSpikeType == -1 and low > low[1] 
                triggerDraw := true
        else
            // انقضا
            activeSpikeType := 0
            inMomentum := false
            barsSinceSpike := 0

    // --- بخش رسم و حذف (مخصوص همین اسپایک) ---
    if triggerDraw
        xCount := xCount + 1
        
        color lColor = activeSpikeType == 1 ? color.blue : color.orange
        color hColor = activeSpikeType == 1 ? color.yellow : color.purple
        
        // رسم جدید
        lastLineL := line.new(bar_index, low, bar_index + 5, low, color=lColor, style=line.style_dotted)
        lastLineH := line.new(bar_index, high, bar_index + 5, high, color=hColor, style=line.style_dotted)
        
        lastLabelL := label.new(bar_index + 5, low, "L" + str.tostring(xCount), textcolor=lColor, style=label.style_none, size=size.small)
        lastLabelH := label.new(bar_index + 5, high, "H" + str.tostring(xCount), textcolor=hColor, style=label.style_none, size=size.small)
