//@version=5
strategy("Enhanced BTCUSDT Strategy with Supertrend and CCI", 
     overlay=true, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=5, 
     initial_capital=10000, 
     currency=currency.USD,
     calc_on_order_fills=true,
     calc_on_every_tick=true)

// ------------------- Parameters -------------------
groupSupertrend = "Supertrend Settings"
supertrendFactor = input.float(3.0, minval=1.0, title="Supertrend Factor", group=groupSupertrend)
supertrendATRPeriod = input.int(10, minval=1, title="Supertrend ATR Period", group=groupSupertrend)

groupCCI = "CCI Settings"
cciLength = input.int(20, minval=1, title="CCI Length", group=groupCCI)
cciUpper = input.int(100, title="CCI Overbought Level", group=groupCCI)
cciLower = input.int(-100, title="CCI Oversold Level", group=groupCCI)

groupATR = "ATR Settings"
atrPeriod = input.int(14, minval=1, title="ATR Period", group=groupATR)
atrMultiplierSL = input.float(1.5, minval=0.1, title="ATR Stop Loss Multiplier", step=0.1, group=groupATR)
atrMultiplierTP = input.float(3.0, minval=0.1, title="ATR Take Profit Multiplier", step=0.1, group=groupATR)

groupBB = "Bollinger Bands Settings"
bbLength = input.int(20, minval=1, title="BB Length", group=groupBB)
bbStdDev = input.float(2.0, minval=0.1, title="BB Standard Deviation", group=groupBB)
volatilityThreshold = input.float(0.05, minval=0.001, title="Volatility Threshold", group=groupBB)

groupRisk = "Risk Management"
riskPerTrade = input.float(1.0, minval=0.1, maxval=5.0, title="Risk per Trade (%)", group=groupRisk)
maxDrawdownPercent = input.float(20.0, minval=1.0, maxval=100.0, title="Max Drawdown Limit (%)", group=groupRisk)

groupTime = "Time Filter Settings"
tradeSessionStart = input.string(defval="0000", title="Trade Session Start Time (HHMM)", group=groupTime)
tradeSessionEnd = input.string(defval="2359", title="Trade Session End Time (HHMM)", group=groupTime)

// Convert input strings to timestamps
tradeYear = year(timenow)
tradeMonth = month(timenow)
tradeDay = dayofmonth(timenow)
startHour = str.tonumber(str.substring(tradeSessionStart, 0, 2))
startMinute = str.tonumber(str.substring(tradeSessionStart, 2, 4))
endHour = str.tonumber(str.substring(tradeSessionEnd, 0, 2))
endMinute = str.tonumber(str.substring(tradeSessionEnd, 2, 4))

sessionStartTime = timestamp("GMT+0", tradeYear, tradeMonth, tradeDay, startHour, startMinute)
sessionEndTime = timestamp("GMT+0", tradeYear, tradeMonth, tradeDay, endHour, endMinute)

// ------------------- Indicators -------------------
[supertrend, supertrendDirection] = ta.supertrend(supertrendFactor, supertrendATRPeriod)
cci = ta.cci(hlc3, cciLength)
atr = ta.atr(atrPeriod)

basis = ta.sma(close, bbLength)
dev = bbStdDev * ta.stdev(close, bbLength)
upperBB = basis + dev
lowerBB = basis - dev

bbWidth = (upperBB - lowerBB) / basis
highVolatility = bbWidth > volatilityThreshold

inTradeSession = (time >= sessionStartTime) and (time <= sessionEndTime)

// ------------------- Strategy Logic -------------------
var float highestEquity = strategy.initial_capital
highestEquity := math.max(highestEquity, strategy.equity)

drawdown = 100 * (highestEquity - strategy.equity) / highestEquity
allowTrading = drawdown < maxDrawdownPercent

longCondition = allowTrading and inTradeSession and highVolatility and (supertrendDirection == 1) and ta.crossover(cci, cciLower)
shortCondition = allowTrading and inTradeSession and highVolatility and (supertrendDirection == -1) and ta.crossunder(cci, cciUpper)

riskAmount = strategy.equity * (riskPerTrade / 100)
positionSize = riskAmount / (atr * atrMultiplierSL)
positionSize := math.max(positionSize, 0)

// ------------------- Enter and Exit Positions -------------------
if (strategy.position_size == 0)
    if (longCondition)
        strategy.entry("Long", strategy.long, qty=positionSize)
    if (shortCondition)
        strategy.entry("Short", strategy.short, qty=positionSize)

trailPoints = atr * atrMultiplierSL

if (strategy.position_size > 0)
    longStopPrice = strategy.position_avg_price - (atr * atrMultiplierSL)
    longTakeProfitPrice = strategy.position_avg_price + (atr * atrMultiplierTP)
    strategy.exit("Long Exit", "Long", stop=longStopPrice, limit=longTakeProfitPrice, trail_points=trailPoints, trail_offset=trailPoints)

if (strategy.position_size < 0)
    shortStopPrice = strategy.position_avg_price + (atr * atrMultiplierSL)
    shortTakeProfitPrice = strategy.position_avg_price - (atr * atrMultiplierTP)
    strategy.exit("Short Exit", "Short", stop=shortStopPrice, limit=shortTakeProfitPrice, trail_points=trailPoints, trail_offset=trailPoints)

// ------------------- Plotting -------------------
plot(supertrend, title="Supertrend", color=(supertrendDirection == 1 ? color.green : color.red), linewidth=2)
hline(cciUpper, title="CCI Overbought Level", color=color.red, linestyle=hline.style_dotted)
hline(cciLower, title="CCI Oversold Level", color=color.green, linestyle=hline.style_dotted)
plot(cci, title="CCI", color=color.blue, linewidth=1)

// Optionally, plot Bollinger Bands and highlight volatility
plot(upperBB, title="Upper BB", color=color.orange, linewidth=1, style=plot.style_linebr)
plot(lowerBB, title="Lower BB", color=color.orange, linewidth=1, style=plot.style_linebr)
bgcolor(highVolatility ? color.new(color.yellow, 90) : na, title="High Volatility Background")

// ------------------- Alerts -------------------
alertcondition(longCondition, title="Long Entry", message="Long Entry Signal")
alertcondition(shortCondition, title="Short Entry", message="Short Entry Signal")