//@version=5
indicator("Auto Trend Fib Signals", overlay=true)
// Trend Detection Parameters
trend_length = input.int(3, "Trend Consecutive Bars")
// Detect Trends
up_trend = ta.rising(high, trend_length) and ta.rising(low, trend_length)
dn_trend = ta.falling(high, trend_length) and ta.falling(low, trend_length)
// Track Trend Parameters
var bool in_uptrend = false
var bool in_downtrend = false
var float up_high = na
var float up_low = na
var float dn_high = na
var float dn_low = na
var line fibLineUp = na
var line fibLineDn = na
// Uptrend Management
if up_trend and not in_uptrend
in_uptrend := true
in_downtrend := false
up_high := high
up_low := low
if in_uptrend
up_high := math.max(up_high, high)
up_low := math.min(up_low, low)
// Downtrend Management
if dn_trend and not in_downtrend
in_downtrend := true
in_uptrend := false
dn_high := high
dn_low := low
if in_downtrend
dn_high := math.max(dn_high, high)
dn_low := math.min(dn_low, low)
// Clear drawings when trend ends
if not up_trend and in_uptrend
line.delete(fibLineUp)
in_uptrend := false
if not dn_trend and in_downtrend
line.delete(fibLineDn)
in_downtrend := false
// Fibonacci Calculations
fib_level = 0.618
// For Uptrend (Retracement)
up_range = up_high - up_low
up_fib = up_high - up_range * fib_level
// For Downtrend (Retracement)
dn_range = dn_high - dn_low
dn_fib = dn_low + dn_range * fib_level
// Draw Fibonacci Levels
if in_uptrend
fibLineUp := line.new(bar_index - 5, up_fib, bar_index + 5, up_fib,
color=color.new(color.blue, 0), width=1, style=line.style_dotted)
line.set_extend(fibLineUp, extend.both)
if in_downtrend
fibLineDn := line.new(bar_index - 5, dn_fib, bar_index + 5, dn_fib,
color=color.new(color.red, 0), width=1, style=line.style_dotted)
line.set_extend(fibLineDn, extend.both)
// Signal Conditions
buy_signal = ta.crossover(low, up_fib) and in_uptrend
sell_signal = ta.crossunder(high, dn_fib) and in_downtrend
// Plot Signals
plotshape(buy_signal, "BUY", shape.labelup, location.belowbar,
color=color.green, size=size.small, text="BUY")
plotshape(sell_signal, "SELL", shape.labeldown, location.abovebar,
color=color.red, size=size.small, text="SELL")
// Alerts
alertcondition(buy_signal, "Bullish Reversal at 0.618",
"Price reached Fibonacci support level")
alertcondition(sell_signal, "Bearish Reversal at 0.618",
"Price reached Fibonacci resistance level")