Daily/Weekly Extremes
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Zeal_Trading
//
////////// DAILY/WEEKLY EXTREMES //////////
//
// This indicator calculates the daily and weekly +-1 standard deviation of the S&P 500 based on 2 methodologies:
// 1. VIX - Using the market's expectation of forward volatility, one can calculate the daily expectation by dividing the VIX by the square root of 252 (the number of trading days in a year).
// Similarly, dividing by the square root of 50 will give you the weekly expected range based on the VIX.
// 2. ATR - We also provided expected weekly and daily ranges based on 5 day/week ATR.
//
///////////////////////////////////////////
//@version=5
indicator("Daily/Weekly Extremes", overlay=true)

rangeType = input.string(title="Range Type", defval="ATR", options=["VIX","ATR"])

vix_daily = request.security('VIX','D',close[1], lookahead=barmerge.lookahead_on)
vix_weekly = request.security('VIX','W',close[1], lookahead=barmerge.lookahead_on)
es_daily_open = syminfo.ticker == 'SPX' ? request.security('SPX','D', open, lookahead=barmerge.lookahead_on) : request.security('ES1!','D', open, lookahead=barmerge.lookahead_on)
es_weekly_open = syminfo.ticker == 'SPX' ? request.security('SPX','W', open, lookahead=barmerge.lookahead_on) : request.security('ES1!','W', open, lookahead=barmerge.lookahead_on)
daily_atr_5 = syminfo.ticker == 'SPX' ? request.security('SPX','D',ta.atr(5)) : request.security('ES1!','D',ta.atr(5))
weekly_atr_5 = syminfo.ticker == 'SPX' ? request.security('SPX','W',ta.atr(5)) : request.security('ES1!','W',ta.atr(5))

top_daily_range = float(na)
bottom_daily_range = float(na)
top_weekly_range = float(na)
bottom_weekly_range = float(na)

if rangeType == "VIX"

    daily_range = ((vix_daily/math.sqrt(252)))/100*es_daily_open
    weekly_range = ((vix_weekly/math.sqrt(50)))/100*es_weekly_open
    
    top_daily_range := es_daily_open + daily_range
    bottom_daily_range := es_daily_open - daily_range
    top_weekly_range := es_weekly_open + weekly_range
    bottom_weekly_range := es_weekly_open - weekly_range

else
    
    top_daily_range := es_daily_open + daily_atr_5/2
    bottom_daily_range := es_daily_open - daily_atr_5/2
    top_weekly_range := es_weekly_open + weekly_atr_5/2
    bottom_weekly_range := es_weekly_open - weekly_atr_5/2
    
plot(syminfo.ticker == 'ES1!' or syminfo.ticker == 'SPX' ? top_daily_range : na, color=color.orange, title = "Daily High")
plot(syminfo.ticker == 'ES1!' or syminfo.ticker == 'SPX' ? bottom_daily_range : na, color=color.orange, title = "Daily Low")
plot(syminfo.ticker == 'ES1!' or syminfo.ticker == 'SPX' ? top_weekly_range : na, color=color.fuchsia, title = "Weekly High")
plot(syminfo.ticker == 'ES1!' or syminfo.ticker == 'SPX' ? bottom_weekly_range : na, color=color.fuchsia, title = "Weekly Low")


 