本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//29th July 2025
//Author: Stefano Masiero - Nebbia Trading
//Commissioner: Alpha4All Italia
//Indicator: Nebbia Ranges PastDays + SpecDays integrated
//Version: v8 - black empty CHG % cell on Δ% row
//Works on a 5 minutes chart
//@version=6
indicator("Nebbia Ranges", shorttitle="Nebbia_Ranges", overlay=true)
// ────────────── BLOCCO TIMEFRAME ──────────────
if timeframe.period != "5"
label.new(bar_index, high, "⚠️ This indicator only works on a 5 minutes chart", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.large)
runtime.error("Invalid timeframe: use 5 minutes")
// ─────────────────────────────────────────────────────────────────────────────
// 0. Display mode
// ─────────────────────────────────────────────────────────────────────────────
displayMode = input.string("PastDays", "Modalità visualizzazione", options=["PastDays", "SpecDays"])
showClassic = displayMode == "PastDays"
showDow = displayMode == "SpecDays"
// ─────────────────────────────────────────────────────────────────────────────
// 1. Market timezone and trading-day handling
// ─────────────────────────────────────────────────────────────────────────────
// Tutti gli orari sono ancorati a New York, così TradingView gestisce
// automaticamente il cambio ora USA. Non servono più finestre manuali di
// discrepancy Italia/USA.
string currentTimezone = "America/New_York"
int oneDayMs = 24 * 60 * 60 * 1000
// Il giorno operativo futures viene assegnato alla data della cash session:
// dalle 18:00 NY in poi le barre appartengono al trading day successivo.
marketHourForTradeDate = hour(time, currentTimezone)
tradeTime = time + (marketHourForTradeDate >= 18 ? oneDayMs : 0)
// ─────────────────────────────────────────────────────────────────────────────
// 2. Inputs
// ─────────────────────────────────────────────────────────────────────────────
avgPeriod = input.int(5, title="Average Periods - Classic", minval=2, maxval=9)
targetDayChoice = input.string("Auto", "Target Day - SpecDays", options=["Auto", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"])
dowLookbackWeekdays = input.int(9, "SpecDays weekday rows", minval=2, maxval=9)
maxHistoryDays = input.int(260, "SpecDays History Depth - calendar days", minval=80, maxval=500)
diffThreshold = input.int(15, "Soglia Δ% per colorazione", minval=1)
ibAdrThreshold = input.int(80, "Soglia r16:30/ADR per colorazione", minval=1)
showRealTimePM = input.bool(false, "Real-Time PRE-MARKET", inline="pm")
showRealTimeOR = input.bool(false, "Real-Time OPENING RANGE", inline="or")
showRealTimeIB = input.bool(false, "Real-Time INITIAL BALANCE", inline="ib")
showRealTimeFH = input.bool(false, "Real-Time 00:00 - 16:30", inline="fh")
showRealTimeDR = input.bool(false, "Real-Time DAILY RANGE", inline="dr")
enableDRAlert = input.bool(false, "Alert quando DR ≥ Media", inline="dr")
showDailyRangeAsPct = input.bool(false, "Visualizza DAILY RANGE in % assoluta")
dailyChangeBasis = input.string("Previous Close", "Base DAILY CHG %", options=["Previous Close", "Daily Open"])
// ─────────────────────────────────────────────────────────────────────────────
// 3. Date utilities
// ─────────────────────────────────────────────────────────────────────────────
currentYear = year(tradeTime, currentTimezone)
currentMonth = month(tradeTime, currentTimezone)
currentDay = dayofmonth(tradeTime, currentTimezone)
getDowLabelFromInt(_dow) =>
string dayStr = "sun"
if _dow == dayofweek.monday
dayStr := "mon"
else if _dow == dayofweek.tuesday
dayStr := "tue"
else if _dow == dayofweek.wednesday
dayStr := "wed"
else if _dow == dayofweek.thursday
dayStr := "thu"
else if _dow == dayofweek.friday
dayStr := "fri"
else if _dow == dayofweek.saturday
dayStr := "sat"
dayStr
getDayLabel(_y, _m, _d, _tz) =>
ts = timestamp(_tz, _y, _m, _d, 12, 0)
getDowLabelFromInt(dayofweek(ts)) + " " + str.tostring(_d) + "/" + str.tostring(_m)
getDowFromDate(_y, _m, _d, _tz) =>
ts = timestamp(_tz, _y, _m, _d, 12, 0)
dayofweek(ts)
getDowFromChoice(_choice, _autoDow) =>
int selectedDow = _autoDow
if _choice == "Monday"
selectedDow := dayofweek.monday
else if _choice == "Tuesday"
selectedDow := dayofweek.tuesday
else if _choice == "Wednesday"
selectedDow := dayofweek.wednesday
else if _choice == "Thursday"
selectedDow := dayofweek.thursday
else if _choice == "Friday"
selectedDow := dayofweek.friday
selectedDow
currentDowRaw = getDowFromDate(currentYear, currentMonth, currentDay, currentTimezone)
currentDow = currentDowRaw
if currentDowRaw == dayofweek.saturday or currentDowRaw == dayofweek.sunday
currentDow := dayofweek.friday
targetDow = getDowFromChoice(targetDayChoice, currentDow)
targetDowLabel = getDowLabelFromInt(targetDow)
currentDateKey = currentYear * 10000 + currentMonth * 100 + currentDay
fmt(_v) =>
na(_v) ? "NaN" : str.tostring(_v, "#.##")
fmtPct(_v) =>
na(_v) ? "NaN" : str.tostring(_v, "#.##") + "%"
fmtChangePct(_v) =>
na(_v) ? "NaN" : (_v > 0 ? "+" : "") + str.tostring(_v, "#.##") + "%"
calcRangePct(_high, _low) =>
not na(_high) and not na(_low) and _low != 0 ? (_high - _low) / _low * 100 : na
calcChangePct(_base, _close) =>
not na(_base) and not na(_close) and _base != 0 ? (_close - _base) / _base * 100 : na
calcChangePctFromBasis(_dailyOpen, _previousClose, _close, _basis) =>
float base = na
if _basis == "Previous Close"
base := _previousClose
else
base := _dailyOpen
calcChangePct(base, _close)
getDailyChangeHeader(_basis) =>
_basis == "Previous Close" ? "CHG % PREV" : "CHG % OPEN"
formatDR(_range, _rangePct) =>
showDailyRangeAsPct ? fmtPct(_rangePct) : fmt(_range)
getChangeColor(_pct) =>
// Pastel solid colors: more readable than transparent colors on dark chart backgrounds.
na(_pct) ? color.white : _pct > 0 ? color.rgb(220, 245, 220) : _pct < 0 ? color.rgb(255, 225, 225) : color.white
getChangeTextColor(_pct) =>
na(_pct) ? color.rgb(35, 35, 35) : _pct > 0 ? color.rgb(0, 95, 0) : _pct < 0 ? color.rgb(150, 0, 0) : color.rgb(35, 35, 35)
percentDiff(_current, _avg) =>
not na(_current) and not na(_avg) and _avg != 0 ? math.round((_current - _avg) / _avg * 100) : na
getColorFromDiff(_pct) =>
_pct >= diffThreshold ? color.red : _pct <= -diffThreshold ? color.green : color.yellow
// ─────────────────────────────────────────────────────────────────────────────
// 4. Session Times - New York trading day
// ─────────────────────────────────────────────────────────────────────────────
// Giorno operativo NQ/ES:
// - DR / Pre-market: 18:00 NY del giorno precedente → 16:55 NY
// - Cash open: 09:30 NY
// - Opening Range: 09:30 → 09:35 NY
// - Initial Balance: 09:30 → 10:30 NY
// - FH/r16:30 label: 18:00 NY del giorno precedente → 10:30 NY
tradeDayMidnight = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 0, 0)
PREMARKETSTART = tradeDayMidnight - 6 * 60 * 60 * 1000
PREMARKETEND = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 9, 30)
ORSTART = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 9, 30)
OREND = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 9, 35)
IBSTART = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 9, 30)
IBEND = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 10, 30)
FHSTART = PREMARKETSTART
FHEND = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 10, 30)
DRSTART = PREMARKETSTART
DREND = timestamp(currentTimezone, currentYear, currentMonth, currentDay, 16, 55)
// Session-end triggers: più robusti di time == sessionEnd se manca una candela.
pmEnded = not na(time[1]) and time >= PREMARKETEND and time[1] < PREMARKETEND
orEnded = not na(time[1]) and time >= OREND and time[1] < OREND
ibEnded = not na(time[1]) and time >= IBEND and time[1] < IBEND
fhEnded = not na(time[1]) and time >= FHEND and time[1] < FHEND
drEnded = not na(time[1]) and time >= DREND and time[1] < DREND
// ─────────────────────────────────────────────────────────────────────────────
// 5. Classic arrays: last 10 trading days
// ─────────────────────────────────────────────────────────────────────────────
var float[] highArrPM = array.new_float(10, na)
var float[] lowArrPM = array.new_float(10, na)
var float[] rangeArrPM = array.new_float(10, na)
var string[] dateArrPM = array.new_string(10, "")
var float[] highArrOR = array.new_float(10, na)
var float[] lowArrOR = array.new_float(10, na)
var float[] rangeArrOR = array.new_float(10, na)
var string[] dateArrOR = array.new_string(10, "")
var float[] highArrIB = array.new_float(10, na)
var float[] lowArrIB = array.new_float(10, na)
var float[] rangeArrIB = array.new_float(10, na)
var string[] dateArrIB = array.new_string(10, "")
var float[] highArrFH = array.new_float(10, na)
var float[] lowArrFH = array.new_float(10, na)
var float[] rangeArrFH = array.new_float(10, na)
var string[] dateArrFH = array.new_string(10, "")
var float[] highArrDR = array.new_float(10, na)
var float[] lowArrDR = array.new_float(10, na)
var float[] rangeArrDR = array.new_float(10, na)
var float[] rangePctArrDR = array.new_float(10, na)
var float[] changePctArrDR = array.new_float(10, na)
var string[] dateArrDR = array.new_string(10, "")
// ─────────────────────────────────────────────────────────────────────────────
// 6. DOW arrays: deeper history by weekday
// ─────────────────────────────────────────────────────────────────────────────
var string[] histDate = array.new_string(0)
var int[] histDow = array.new_int(0)
var float[] histPM = array.new_float(0)
var float[] histOR = array.new_float(0)
var float[] histIB = array.new_float(0)
var float[] histFH = array.new_float(0)
var float[] histDR = array.new_float(0)
var float[] histDRPct = array.new_float(0)
var float[] histChangePct = array.new_float(0)
// ─────────────────────────────────────────────────────────────────────────────
// 7. Current day tracking variables
// ─────────────────────────────────────────────────────────────────────────────
var float PMHigh = na
var float PMLow = na
var float ORHigh = na
var float ORLow = na
var float IBHigh = na
var float IBLow = na
var float FHHigh = na
var float FHLow = na
var float DRHigh = na
var float DRLow = na
var float PMRange = na
var float ORRange = na
var float IBRange = na
var float FHRange = na
var float DRRange = na
var float DRRangePct = na
var float DailyOpen = na
var float DailyClose = na
var float PrevDailyCloseForCurrentDay = na
var float DailyChangePct = na
// ─────────────────────────────────────────────────────────────────────────────
// 8. New day initialization
// ─────────────────────────────────────────────────────────────────────────────
var int lastDateKey = na
newDay = na(lastDateKey) or currentDateKey != lastDateKey
if newDay
lastDateKey := currentDateKey
// Classic: shift out oldest and append current day placeholder at index 9.
array.shift(highArrPM)
array.shift(lowArrPM)
array.shift(rangeArrPM)
array.shift(dateArrPM)
array.shift(highArrOR)
array.shift(lowArrOR)
array.shift(rangeArrOR)
array.shift(dateArrOR)
array.shift(highArrIB)
array.shift(lowArrIB)
array.shift(rangeArrIB)
array.shift(dateArrIB)
array.shift(highArrFH)
array.shift(lowArrFH)
array.shift(rangeArrFH)
array.shift(dateArrFH)
array.shift(highArrDR)
array.shift(lowArrDR)
array.shift(rangeArrDR)
array.shift(rangePctArrDR)
array.shift(changePctArrDR)
array.shift(dateArrDR)
newLabel = getDayLabel(currentYear, currentMonth, currentDay, currentTimezone)
array.push(highArrPM, na)
array.push(lowArrPM, na)
array.push(rangeArrPM, na)
array.push(dateArrPM, newLabel)
array.push(highArrOR, na)
array.push(lowArrOR, na)
array.push(rangeArrOR, na)
array.push(dateArrOR, newLabel)
array.push(highArrIB, na)
array.push(lowArrIB, na)
array.push(rangeArrIB, na)
array.push(dateArrIB, newLabel)
array.push(highArrFH, na)
array.push(lowArrFH, na)
array.push(rangeArrFH, na)
array.push(dateArrFH, newLabel)
array.push(highArrDR, na)
array.push(lowArrDR, na)
array.push(rangeArrDR, na)
array.push(rangePctArrDR, na)
array.push(changePctArrDR, na)
array.push(dateArrDR, newLabel)
// DOW: append current day placeholder.
array.push(histDate, newLabel)
array.push(histDow, currentDowRaw)
array.push(histPM, na)
array.push(histOR, na)
array.push(histIB, na)
array.push(histFH, na)
array.push(histDR, na)
array.push(histDRPct, na)
array.push(histChangePct, na)
while array.size(histDate) > maxHistoryDays
array.shift(histDate)
array.shift(histDow)
array.shift(histPM)
array.shift(histOR)
array.shift(histIB)
array.shift(histFH)
array.shift(histDR)
array.shift(histDRPct)
array.shift(histChangePct)
// La base "Previous Close" usa la chiusura della sessione DR precedente.
PrevDailyCloseForCurrentDay := DailyClose
PMHigh := na
PMLow := na
ORHigh := na
ORLow := na
IBHigh := na
IBLow := na
FHHigh := na
FHLow := na
DRHigh := na
DRLow := na
PMRange := na
ORRange := na
IBRange := na
FHRange := na
DRRange := na
DRRangePct := na
DailyOpen := na
DailyClose := na
DailyChangePct := na
// ─────────────────────────────────────────────────────────────────────────────
// 9. Update highs/lows during sessions
// ─────────────────────────────────────────────────────────────────────────────
if time >= PREMARKETSTART and time < PREMARKETEND
PMHigh := na(PMHigh) ? high : math.max(PMHigh, high)
PMLow := na(PMLow) ? low : math.min(PMLow, low)
if time >= ORSTART and time < OREND
ORHigh := na(ORHigh) ? high : math.max(ORHigh, high)
ORLow := na(ORLow) ? low : math.min(ORLow, low)
if time >= IBSTART and time < IBEND
IBHigh := na(IBHigh) ? high : math.max(IBHigh, high)
IBLow := na(IBLow) ? low : math.min(IBLow, low)
if time >= FHSTART and time < FHEND
FHHigh := na(FHHigh) ? high : math.max(FHHigh, high)
FHLow := na(FHLow) ? low : math.min(FHLow, low)
if time >= DRSTART and time < DREND
DRHigh := na(DRHigh) ? high : math.max(DRHigh, high)
DRLow := na(DRLow) ? low : math.min(DRLow, low)
DailyOpen := na(DailyOpen) ? open : DailyOpen
DailyClose := close
// ─────────────────────────────────────────────────────────────────────────────
// 10. Store session ranges when each session ends
// ─────────────────────────────────────────────────────────────────────────────
lastDowIdx = array.size(histDate) - 1
if pmEnded
PMRange := not na(PMHigh) and not na(PMLow) ? PMHigh - PMLow : na
array.set(highArrPM, 9, PMHigh)
array.set(lowArrPM, 9, PMLow)
array.set(rangeArrPM, 9, PMRange)
if lastDowIdx >= 0
array.set(histPM, lastDowIdx, PMRange)
PMHigh := na
PMLow := na
if orEnded
ORRange := not na(ORHigh) and not na(ORLow) ? ORHigh - ORLow : na
array.set(highArrOR, 9, ORHigh)
array.set(lowArrOR, 9, ORLow)
array.set(rangeArrOR, 9, ORRange)
if lastDowIdx >= 0
array.set(histOR, lastDowIdx, ORRange)
ORHigh := na
ORLow := na
if ibEnded
IBRange := not na(IBHigh) and not na(IBLow) ? IBHigh - IBLow : na
array.set(highArrIB, 9, IBHigh)
array.set(lowArrIB, 9, IBLow)
array.set(rangeArrIB, 9, IBRange)
if lastDowIdx >= 0
array.set(histIB, lastDowIdx, IBRange)
IBHigh := na
IBLow := na
if fhEnded
FHRange := not na(FHHigh) and not na(FHLow) ? FHHigh - FHLow : na
array.set(highArrFH, 9, FHHigh)
array.set(lowArrFH, 9, FHLow)
array.set(rangeArrFH, 9, FHRange)
if lastDowIdx >= 0
array.set(histFH, lastDowIdx, FHRange)
FHHigh := na
FHLow := na
if drEnded
DRRange := not na(DRHigh) and not na(DRLow) ? DRHigh - DRLow : na
DRRangePct := calcRangePct(DRHigh, DRLow)
DailyChangePct := calcChangePctFromBasis(DailyOpen, PrevDailyCloseForCurrentDay, DailyClose, dailyChangeBasis)
array.set(highArrDR, 9, DRHigh)
array.set(lowArrDR, 9, DRLow)
array.set(rangeArrDR, 9, DRRange)
array.set(rangePctArrDR, 9, DRRangePct)
array.set(changePctArrDR, 9, DailyChangePct)
if lastDowIdx >= 0
array.set(histDR, lastDowIdx, DRRange)
array.set(histDRPct, lastDowIdx, DRRangePct)
array.set(histChangePct, lastDowIdx, DailyChangePct)
// Se DR non è valido, invalida tutta la giornata.
if na(DRRange)
array.set(rangeArrPM, 9, na)
array.set(rangeArrOR, 9, na)
array.set(rangeArrIB, 9, na)
array.set(rangeArrFH, 9, na)
array.set(rangeArrDR, 9, na)
array.set(rangePctArrDR, 9, na)
array.set(changePctArrDR, 9, na)
if lastDowIdx >= 0
array.set(histPM, lastDowIdx, na)
array.set(histOR, lastDowIdx, na)
array.set(histIB, lastDowIdx, na)
array.set(histFH, lastDowIdx, na)
array.set(histDR, lastDowIdx, na)
array.set(histDRPct, lastDowIdx, na)
array.set(histChangePct, lastDowIdx, na)
DRHigh := na
DRLow := na
// ─────────────────────────────────────────────────────────────────────────────
// 11. Classic averages and score
// ─────────────────────────────────────────────────────────────────────────────
isValidRowClassic(_idx) =>
bool ok = false
if _idx >= 0 and _idx < 10
ok := not na(array.get(rangeArrPM, _idx))
ok := ok and not na(array.get(rangeArrOR, _idx))
ok := ok and not na(array.get(rangeArrIB, _idx))
ok := ok and not na(array.get(rangeArrFH, _idx))
ok := ok and not na(array.get(rangeArrDR, _idx))
ok
getClassicValueBySession(_idx, _sessionType) =>
float value = na
if _idx >= 0 and _idx < 10
if _sessionType == "PREMARKET"
value := array.get(rangeArrPM, _idx)
else if _sessionType == "OPENING_RANGE"
value := array.get(rangeArrOR, _idx)
else if _sessionType == "INITIAL_BALANCE"
value := array.get(rangeArrIB, _idx)
else if _sessionType == "18:00_10:30"
value := array.get(rangeArrFH, _idx)
else if _sessionType == "DAILY_RANGE"
value := array.get(rangeArrDR, _idx)
else if _sessionType == "DAILY_RANGE_PCT"
value := array.get(rangePctArrDR, _idx)
else if _sessionType == "DAILY_CHANGE_PCT"
value := array.get(changePctArrDR, _idx)
value
calc_avg_classic(_periods, _sessionType) =>
float sum = 0.0
int validRows = 0
int idx = 8
while validRows < _periods and idx >= 0
if isValidRowClassic(idx)
float value = getClassicValueBySession(idx, _sessionType)
if not na(value)
sum += value
validRows += 1
idx -= 1
validRows > 0 ? sum / validRows : na
avgPMValueClassic = calc_avg_classic(avgPeriod, "PREMARKET")
avgORValueClassic = calc_avg_classic(avgPeriod, "OPENING_RANGE")
avgIBValueClassic = calc_avg_classic(avgPeriod, "INITIAL_BALANCE")
avgFHValueClassic = calc_avg_classic(avgPeriod, "18:00_10:30")
avgDRValueClassic = calc_avg_classic(avgPeriod, "DAILY_RANGE")
avgDRPctValueClassic = calc_avg_classic(avgPeriod, "DAILY_RANGE_PCT")
get_avgDR_prior_classic(_idx) =>
float somma = 0.0
int conta = 0
int lookup = _idx - 1
while lookup >= 0 and conta < 5
if isValidRowClassic(lookup)
float val = array.get(rangeArrDR, lookup)
if not na(val)
somma += val
conta += 1
lookup -= 1
conta >= 3 ? somma / conta : na
calc_scoreDR_classic() =>
int consecBelow = 0
int consecAbove = 0
int validCount = 0
int idxLoop = 8
while idxLoop >= 0 and validCount < 4
if isValidRowClassic(idxLoop)
float val = array.get(rangeArrDR, idxLoop)
float avg = get_avgDR_prior_classic(idxLoop)
if not na(val) and not na(avg)
if val < avg
if consecAbove > 0
break
consecBelow += 1
else
if consecBelow > 0
break
consecAbove += 1
validCount += 1
idxLoop -= 1
int result = 0
if consecBelow == 4
result := 50
else if consecBelow == 3
result := 40
else if consecBelow == 2
result := 30
else if consecBelow == 1
result := 20
else if consecAbove == 1
result := 50
else if consecAbove == 2
result := 40
else if consecAbove == 3
result := 30
else if consecAbove == 4
result := 20
result
scoreDRClassic = calc_scoreDR_classic()
// Score fascia oraria in New York time.
// Equivalenti NY delle vecchie fasce Chicago:
// 09:30-10:55 → 50 | 10:56-13:55 → 20 | 13:56-15:30 → 30
marketHour = hour(time, currentTimezone)
marketMinute = minute(time, currentTimezone)
ORmins = marketHour * 60 + marketMinute
scoreFascia = 0
if ORmins >= 570 and ORmins <= 655
scoreFascia := 50
else if ORmins >= 656 and ORmins <= 835
scoreFascia := 20
else if ORmins >= 836 and ORmins <= 930
scoreFascia := 30
scorePMClassic = 0
if not na(PMRange) and not na(avgPMValueClassic) and avgPMValueClassic != 0
percDiffPMClassic = (PMRange - avgPMValueClassic) / avgPMValueClassic
if percDiffPMClassic <= -0.15
scorePMClassic := 30
else if percDiffPMClassic >= 0.15
scorePMClassic := 50
else
scorePMClassic := 40
scoreORClassic = 0
if not na(ORRange) and not na(avgORValueClassic) and avgORValueClassic != 0
percDiffORClassic = (ORRange - avgORValueClassic) / avgORValueClassic
if percDiffORClassic <= -0.15
scoreORClassic := 25
else if percDiffORClassic >= 0.15
scoreORClassic := 50
else
scoreORClassic := 35
scoreTotaleClassic = scoreDRClassic + scoreFascia + scorePMClassic + scoreORClassic
// ─────────────────────────────────────────────────────────────────────────────
// 12. DOW reference day, history and averages by selected weekday
// ─────────────────────────────────────────────────────────────────────────────
isValidRowDow(_idx) =>
bool ok = false
if _idx >= 0 and _idx < array.size(histDate)
ok := not na(array.get(histPM, _idx))
ok := ok and not na(array.get(histOR, _idx))
ok := ok and not na(array.get(histIB, _idx))
ok := ok and not na(array.get(histFH, _idx))
ok := ok and not na(array.get(histDR, _idx))
ok
getValueBySessionDow(_idx, _sessionType) =>
float value = na
if _idx >= 0 and _idx < array.size(histDate)
if _sessionType == "PREMARKET"
value := array.get(histPM, _idx)
else if _sessionType == "OPENING_RANGE"
value := array.get(histOR, _idx)
else if _sessionType == "INITIAL_BALANCE"
value := array.get(histIB, _idx)
else if _sessionType == "18:00_10:30"
value := array.get(histFH, _idx)
else if _sessionType == "DAILY_RANGE"
value := array.get(histDR, _idx)
else if _sessionType == "DAILY_RANGE_PCT"
value := array.get(histDRPct, _idx)
else if _sessionType == "DAILY_CHANGE_PCT"
value := array.get(histChangePct, _idx)
value
findNthTargetBeforeDow(_targetDow, _nthFromNewest, _beforeIdx) =>
int found = 0
int result = na
int idx = _beforeIdx - 1
int maxIdx = array.size(histDate) - 1
if idx > maxIdx
idx := maxIdx
while idx >= 0 and na(result)
if array.get(histDow, idx) == _targetDow
if found == _nthFromNewest
result := idx
found += 1
idx -= 1
result
findLatestTargetBeforeDow(_targetDow, _beforeIdx) =>
findNthTargetBeforeDow(_targetDow, 0, _beforeIdx)
getReferenceIdxDow(_targetDow) =>
int result = na
int last = array.size(histDate) - 1
if last >= 0
if array.get(histDow, last) == _targetDow
result := last
else
result := findLatestTargetBeforeDow(_targetDow, last)
result
count_target_before_dow(_periods, _targetDow, _beforeIdx) =>
int rows = 0
int idx = _beforeIdx - 1
int maxIdx = array.size(histDate) - 1
if idx > maxIdx
idx := maxIdx
while rows < _periods and idx >= 0
if array.get(histDow, idx) == _targetDow
rows += 1
idx -= 1
rows
count_valid_target_before_dow(_periods, _targetDow, _beforeIdx) =>
int targetRows = 0
int validRows = 0
int idx = _beforeIdx - 1
int maxIdx = array.size(histDate) - 1
if idx > maxIdx
idx := maxIdx
while targetRows < _periods and idx >= 0
if array.get(histDow, idx) == _targetDow
targetRows += 1
if isValidRowDow(idx)
validRows += 1
idx -= 1
validRows
calc_avg_target_before_dow(_periods, _sessionType, _targetDow, _beforeIdx) =>
float sum = 0.0
int targetRows = 0
int validRows = 0
int idx = _beforeIdx - 1
int maxIdx = array.size(histDate) - 1
if idx > maxIdx
idx := maxIdx
while targetRows < _periods and idx >= 0
if array.get(histDow, idx) == _targetDow
targetRows += 1
if isValidRowDow(idx)
float value = getValueBySessionDow(idx, _sessionType)
if not na(value)
sum += value
validRows += 1
idx -= 1
validRows > 0 ? sum / validRows : na
referenceIdxDow = getReferenceIdxDow(targetDow)
referenceIsCurrentDow = not na(referenceIdxDow) and referenceIdxDow == array.size(histDate) - 1 and currentDowRaw == targetDow
avgBeforeIdxDow = na(referenceIdxDow) ? array.size(histDate) : referenceIdxDow
avgPMValueDow = calc_avg_target_before_dow(dowLookbackWeekdays, "PREMARKET", targetDow, avgBeforeIdxDow)
avgORValueDow = calc_avg_target_before_dow(dowLookbackWeekdays, "OPENING_RANGE", targetDow, avgBeforeIdxDow)
avgIBValueDow = calc_avg_target_before_dow(dowLookbackWeekdays, "INITIAL_BALANCE", targetDow, avgBeforeIdxDow)
avgFHValueDow = calc_avg_target_before_dow(dowLookbackWeekdays, "18:00_10:30", targetDow, avgBeforeIdxDow)
avgDRValueDow = calc_avg_target_before_dow(dowLookbackWeekdays, "DAILY_RANGE", targetDow, avgBeforeIdxDow)
avgDRPctValueDow = calc_avg_target_before_dow(dowLookbackWeekdays, "DAILY_RANGE_PCT", targetDow, avgBeforeIdxDow)
avgValidCountDow = count_valid_target_before_dow(dowLookbackWeekdays, targetDow, avgBeforeIdxDow)
get_avgDR_prior_target_dow(_idx, _targetDow) =>
float somma = 0.0
int conta = 0
int lookup = _idx - 1
while lookup >= 0 and conta < 5
if array.get(histDow, lookup) == _targetDow and isValidRowDow(lookup)
float val = array.get(histDR, lookup)
if not na(val)
somma += val
conta += 1
lookup -= 1
conta >= 3 ? somma / conta : na
calc_scoreDR_target_dow(_targetDow) =>
int consecBelow = 0
int consecAbove = 0
int validCount = 0
int idxLoop = array.size(histDate) - 2
while idxLoop >= 0 and validCount < 4
if array.get(histDow, idxLoop) == _targetDow and isValidRowDow(idxLoop)
float val = array.get(histDR, idxLoop)
float avg = get_avgDR_prior_target_dow(idxLoop, _targetDow)
if not na(val) and not na(avg)
if val < avg
if consecAbove > 0
break
consecBelow += 1
else
if consecBelow > 0
break
consecAbove += 1
validCount += 1
idxLoop -= 1
int result = 0
if consecBelow == 4
result := 50
else if consecBelow == 3
result := 40
else if consecBelow == 2
result := 30
else if consecBelow == 1
result := 20
else if consecAbove == 1
result := 50
else if consecAbove == 2
result := 40
else if consecAbove == 3
result := 30
else if consecAbove == 4
result := 20
result
scoreDRDow = calc_scoreDR_target_dow(targetDow)
scorePMDow = 0
if not na(PMRange) and not na(avgPMValueDow) and avgPMValueDow != 0
percDiffPMDow = (PMRange - avgPMValueDow) / avgPMValueDow
if percDiffPMDow <= -0.15
scorePMDow := 30
else if percDiffPMDow >= 0.15
scorePMDow := 50
else
scorePMDow := 40
scoreORDow = 0
if not na(ORRange) and not na(avgORValueDow) and avgORValueDow != 0
percDiffORDow = (ORRange - avgORValueDow) / avgORValueDow
if percDiffORDow <= -0.15
scoreORDow := 25
else if percDiffORDow >= 0.15
scoreORDow := 50
else
scoreORDow := 35
scoreTotaleDow = scoreDRDow + scoreFascia + scorePMDow + scoreORDow
// ─────────────────────────────────────────────────────────────────────────────
// 13. Alert DR live >= selected average DR
// ─────────────────────────────────────────────────────────────────────────────
DRLiveRange = not na(DRHigh) and not na(DRLow) ? DRHigh - DRLow : na
DRLiveRangePct = calcRangePct(DRHigh, DRLow)
DailyChangePctLive = calcChangePctFromBasis(DailyOpen, PrevDailyCloseForCurrentDay, close, dailyChangeBasis)
selectedAvgDR = showDow ? avgDRValueDow : avgDRValueClassic
alertEnabledForMode = showClassic or referenceIsCurrentDow
drBreaksAboveMedia = enableDRAlert and showRealTimeDR and alertEnabledForMode and not na(DRLiveRange) and not na(selectedAvgDR) and DRLiveRange >= selectedAvgDR
alertcondition(drBreaksAboveMedia, title="🚨 Daily Range ≥ Media", message="🚨 Il Daily Range in tempo reale ha superato la media della modalità selezionata!")
var bool drAlertFired = false
shouldTriggerAlert = drBreaksAboveMedia and not drAlertFired
if shouldTriggerAlert
alert("🚨 DR ≥ Media " + displayMode + " (" + str.tostring(DRLiveRange, "#.##") + ")", alert.freq_once_per_bar_close)
drAlertFired := true
if not drBreaksAboveMedia
drAlertFired := false
// ─────────────────────────────────────────────────────────────────────────────
// 14. Table rendering: Classic default or DOW alternative
// ─────────────────────────────────────────────────────────────────────────────
var table myTable = na
var int lastTableRows = na
var int lastTableCols = na
var string lastDisplayMode = ""
var string lastDailyChangeBasis = ""
if barstate.islast
int neededRows = showDow ? math.max(count_target_before_dow(dowLookbackWeekdays, targetDow, avgBeforeIdxDow), 0) + 4 : 13
int neededCols = 7
if na(myTable) or lastTableRows != neededRows or lastTableCols != neededCols or lastDisplayMode != displayMode or lastDailyChangeBasis != dailyChangeBasis
if not na(myTable)
table.delete(myTable)
myTable := table.new(position.middle_center, neededCols, neededRows, border_width=1, frame_color=color.blue, bgcolor=color.black)
lastTableRows := neededRows
lastTableCols := neededCols
lastDisplayMode := displayMode
lastDailyChangeBasis := dailyChangeBasis
// Header comune
table.cell(myTable, 0, 0, "Date", text_color=color.white, bgcolor=color.rgb(0, 7, 144))
table.cell(myTable, 1, 0, "PRE-MARKET", bgcolor=color.rgb(249, 138, 2))
table.cell(myTable, 2, 0, "OPENING RANGE", bgcolor=color.rgb(255, 3, 238))
table.cell(myTable, 3, 0, "INITIAL BALANCE", bgcolor=color.rgb(167, 199, 53))
table.cell(myTable, 4, 0, "00:00-16:30", bgcolor=color.rgb(3, 251, 255))
table.cell(myTable, 5, 0, showDailyRangeAsPct ? "DAILY RANGE %" : "DAILY RANGE", text_color=color.white, bgcolor=color.rgb(136, 50, 255))
table.cell(myTable, 6, 0, getDailyChangeHeader(dailyChangeBasis), text_color=color.white, bgcolor=color.rgb(80, 80, 80))
if showClassic
// ────────────── Classic: ultime 10 giornate + media + oggi + Δ% ──────────────
for i = 0 to 9
float valuePM = array.get(rangeArrPM, i)
float valueOR = array.get(rangeArrOR, i)
float valueIB = array.get(rangeArrIB, i)
float valueFH = array.get(rangeArrFH, i)
float valueDR = array.get(rangeArrDR, i)
float valueDRPct = array.get(rangePctArrDR, i)
float valueChangePct = array.get(changePctArrDR, i)
isCurrentDay = i == 9
displayPM = isCurrentDay and time < PREMARKETEND ? "---" : fmt(valuePM)
displayOR = isCurrentDay and time < OREND ? "---" : fmt(valueOR)
displayIB = isCurrentDay and time < IBEND ? "---" : fmt(valueIB)
displayFH = isCurrentDay and time < FHEND ? "---" : fmt(valueFH)
displayDR = isCurrentDay and time < DREND ? "---" : formatDR(valueDR, valueDRPct)
displayChange = isCurrentDay and time < DREND ? "---" : fmtChangePct(valueChangePct)
bgcolorRow = isValidRowClassic(i) ? color.white : #c8c8c8ec
table.cell(myTable, 0, i + 1, array.get(dateArrPM, i), bgcolor=bgcolorRow)
table.cell(myTable, 1, i + 1, displayPM, bgcolor=bgcolorRow)
table.cell(myTable, 2, i + 1, displayOR, bgcolor=bgcolorRow)
table.cell(myTable, 3, i + 1, displayIB, bgcolor=bgcolorRow)
table.cell(myTable, 4, i + 1, displayFH, bgcolor=bgcolorRow)
table.cell(myTable, 5, i + 1, displayDR, bgcolor=bgcolorRow)
table.cell(myTable, 6, i + 1, displayChange, text_color=getChangeTextColor(valueChangePct), bgcolor=isCurrentDay and time < DREND ? bgcolorRow : getChangeColor(valueChangePct))
avgPMValueRounded = na(avgPMValueClassic) ? na : math.round(avgPMValueClassic * 100) / 100
avgORValueRounded = na(avgORValueClassic) ? na : math.round(avgORValueClassic * 100) / 100
avgIBValueRounded = na(avgIBValueClassic) ? na : math.round(avgIBValueClassic * 100) / 100
avgFHValueRounded = na(avgFHValueClassic) ? na : math.round(avgFHValueClassic * 100) / 100
avgDRValueRounded = na(avgDRValueClassic) ? na : math.round(avgDRValueClassic * 100) / 100
avgDRPctValueRounded = na(avgDRPctValueClassic) ? na : math.round(avgDRPctValueClassic * 100) / 100
table.cell(myTable, 0, 10, "AVG(" + str.tostring(avgPeriod) + ")", bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 1, 10, fmt(avgPMValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 2, 10, fmt(avgORValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 3, 10, fmt(avgIBValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 4, 10, fmt(avgFHValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 5, 10, formatDR(avgDRValueRounded, avgDRPctValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 6, 10, "---", text_color=color.rgb(35, 35, 35), bgcolor=color.rgb(154, 189, 207))
showScoreClassic = time >= OREND and ORmins <= 930
dayLabelWithScore = showScoreClassic and scoreTotaleClassic != 0 ? getDayLabel(currentYear, currentMonth, currentDay, currentTimezone) + " (" + str.tostring(scoreTotaleClassic) + ")" : getDayLabel(currentYear, currentMonth, currentDay, currentTimezone)
bgScoreColor = showScoreClassic ? (scoreTotaleClassic >= 170 ? color.red : scoreTotaleClassic <= 130 ? color.green : color.yellow) : color.white
table.cell(myTable, 0, 11, dayLabelWithScore, bgcolor=bgScoreColor)
table.cell(myTable, 1, 11, time < PREMARKETEND ? (showRealTimePM and not na(PMHigh) and not na(PMLow) ? fmt(PMHigh - PMLow) : "---") : fmt(PMRange), bgcolor=color.white)
table.cell(myTable, 2, 11, time < OREND ? (showRealTimeOR and not na(ORHigh) and not na(ORLow) ? fmt(ORHigh - ORLow) : "---") : fmt(ORRange), bgcolor=color.white)
table.cell(myTable, 3, 11, time < IBEND ? (showRealTimeIB and not na(IBHigh) and not na(IBLow) ? fmt(IBHigh - IBLow) : "---") : fmt(IBRange), bgcolor=color.white)
table.cell(myTable, 4, 11, time < FHEND ? (showRealTimeFH and not na(FHHigh) and not na(FHLow) ? fmt(FHHigh - FHLow) : "---") : fmt(FHRange), bgcolor=color.white)
currentDRDisplayClassic = time < DREND ? (showRealTimeDR and not na(DRHigh) and not na(DRLow) ? formatDR(DRHigh - DRLow, DRLiveRangePct) : "---") : formatDR(DRRange, DRRangePct)
currentChangeDisplayClassic = time < DREND ? fmtChangePct(DailyChangePctLive) : fmtChangePct(DailyChangePct)
currentChangeValueClassic = time < DREND ? DailyChangePctLive : DailyChangePct
table.cell(myTable, 5, 11, currentDRDisplayClassic, bgcolor=color.white)
table.cell(myTable, 6, 11, currentChangeDisplayClassic, text_color=getChangeTextColor(currentChangeValueClassic), bgcolor=getChangeColor(currentChangeValueClassic))
diffPM = percentDiff(PMRange, avgPMValueClassic)
diffOR = percentDiff(ORRange, avgORValueClassic)
diffIB = percentDiff(IBRange, avgIBValueClassic)
labelDiffPM = na(diffPM) or time < PREMARKETEND ? "---" : (diffPM > 0 ? "+" : "") + str.tostring(diffPM) + "%"
labelDiffOR = na(diffOR) or time < OREND ? "---" : (diffOR > 0 ? "+" : "") + str.tostring(diffOR) + "%"
labelDiffIB = na(diffIB) or time < IBEND ? "---" : (diffIB > 0 ? "+" : "") + str.tostring(diffIB) + "%"
bgPM = na(diffPM) or time < PREMARKETEND ? color.white : getColorFromDiff(diffPM)
bgOR = na(diffOR) or time < OREND ? color.white : getColorFromDiff(diffOR)
bgIB = na(diffIB) or time < IBEND ? color.white : getColorFromDiff(diffIB)
table.cell(myTable, 0, 12, "Δ%", bgcolor=color.rgb(0, 0, 0), text_color=color.white)
table.cell(myTable, 1, 12, labelDiffPM, bgcolor=bgPM)
table.cell(myTable, 2, 12, labelDiffOR, bgcolor=bgOR)
table.cell(myTable, 3, 12, labelDiffIB, bgcolor=bgIB)
ratioFhAdr = not na(FHRange) and not na(avgDRValueClassic) and avgDRValueClassic != 0 ? math.round(FHRange / avgDRValueClassic * 100) : na
labelFhAdr = na(ratioFhAdr) or time < FHEND ? "---" : str.tostring(ratioFhAdr) + "%"
colorFhAdr = na(ratioFhAdr) or time < FHEND ? color.white : ratioFhAdr <= ibAdrThreshold ? color.green : color.red
table.cell(myTable, 4, 12, "r16:30 / ADR ->", bgcolor=color.rgb(0, 0, 0), text_color=color.white)
table.cell(myTable, 5, 12, labelFhAdr, bgcolor=colorFhAdr)
table.cell(myTable, 6, 12, "", bgcolor=color.rgb(0, 0, 0), text_color=color.white)
else
// ────────────── DOW: weekday selezionato + media + riferimento + Δ% ──────────────
availableRowsRaw = count_target_before_dow(dowLookbackWeekdays, targetDow, avgBeforeIdxDow)
availableRows = math.min(availableRowsRaw, dowLookbackWeekdays)
for i = 0 to dowLookbackWeekdays - 1
if i < availableRows
row = i + 1
nthFromNewest = availableRows - 1 - i
histIdx = findNthTargetBeforeDow(targetDow, nthFromNewest, avgBeforeIdxDow)
if not na(histIdx)
valuePM = array.get(histPM, histIdx)
valueOR = array.get(histOR, histIdx)
valueIB = array.get(histIB, histIdx)
valueFH = array.get(histFH, histIdx)
valueDR = array.get(histDR, histIdx)
valueDRPct = array.get(histDRPct, histIdx)
valueChangePct = array.get(histChangePct, histIdx)
bgcolorRow = isValidRowDow(histIdx) ? color.white : #c8c8c8ec
table.cell(myTable, 0, row, array.get(histDate, histIdx), bgcolor=bgcolorRow)
table.cell(myTable, 1, row, fmt(valuePM), bgcolor=bgcolorRow)
table.cell(myTable, 2, row, fmt(valueOR), bgcolor=bgcolorRow)
table.cell(myTable, 3, row, fmt(valueIB), bgcolor=bgcolorRow)
table.cell(myTable, 4, row, fmt(valueFH), bgcolor=bgcolorRow)
table.cell(myTable, 5, row, formatDR(valueDR, valueDRPct), bgcolor=bgcolorRow)
table.cell(myTable, 6, row, fmtChangePct(valueChangePct), text_color=getChangeTextColor(valueChangePct), bgcolor=getChangeColor(valueChangePct))
avgRow = availableRows + 1
referenceRow = availableRows + 2
deltaRow = availableRows + 3
avgPMValueRounded = na(avgPMValueDow) ? na : math.round(avgPMValueDow * 100) / 100
avgORValueRounded = na(avgORValueDow) ? na : math.round(avgORValueDow * 100) / 100
avgIBValueRounded = na(avgIBValueDow) ? na : math.round(avgIBValueDow * 100) / 100
avgFHValueRounded = na(avgFHValueDow) ? na : math.round(avgFHValueDow * 100) / 100
avgDRValueRounded = na(avgDRValueDow) ? na : math.round(avgDRValueDow * 100) / 100
avgDRPctValueRounded = na(avgDRPctValueDow) ? na : math.round(avgDRPctValueDow * 100) / 100
avgLabel = avgValidCountDow == availableRows ? "AVG(" + str.tostring(avgValidCountDow) + " " + targetDowLabel + ")" : "AVG(" + str.tostring(avgValidCountDow) + "/" + str.tostring(availableRows) + " " + targetDowLabel + ")"
table.cell(myTable, 0, avgRow, avgLabel, bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 1, avgRow, fmt(avgPMValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 2, avgRow, fmt(avgORValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 3, avgRow, fmt(avgIBValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 4, avgRow, fmt(avgFHValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 5, avgRow, formatDR(avgDRValueRounded, avgDRPctValueRounded), bgcolor=color.rgb(154, 189, 207))
table.cell(myTable, 6, avgRow, "---", text_color=color.rgb(35, 35, 35), bgcolor=color.rgb(154, 189, 207))
refPMValue = not na(referenceIdxDow) ? array.get(histPM, referenceIdxDow) : na
refORValue = not na(referenceIdxDow) ? array.get(histOR, referenceIdxDow) : na
refIBValue = not na(referenceIdxDow) ? array.get(histIB, referenceIdxDow) : na
refFHValue = not na(referenceIdxDow) ? array.get(histFH, referenceIdxDow) : na
refDRValue = not na(referenceIdxDow) ? array.get(histDR, referenceIdxDow) : na
refDRPctValue = not na(referenceIdxDow) ? array.get(histDRPct, referenceIdxDow) : na
refChangePctValue = not na(referenceIdxDow) ? array.get(histChangePct, referenceIdxDow) : na
showScoreDow = referenceIsCurrentDow and time >= OREND and ORmins <= 930
refLabelBase = not na(referenceIdxDow) ? array.get(histDate, referenceIdxDow) : "last " + targetDowLabel
refLabel = showScoreDow and scoreTotaleDow != 0 ? refLabelBase + " (" + str.tostring(scoreTotaleDow) + ")" : refLabelBase
refBgColor = not na(referenceIdxDow) and isValidRowDow(referenceIdxDow) ? color.white : #c8c8c8ec
if showScoreDow
if scoreTotaleDow >= 170
refBgColor := color.red
else if scoreTotaleDow <= 130
refBgColor := color.green
else
refBgColor := color.yellow
table.cell(myTable, 0, referenceRow, refLabel, bgcolor=refBgColor)
displayPMRef = referenceIsCurrentDow ? (time < PREMARKETEND ? (showRealTimePM and not na(PMHigh) and not na(PMLow) ? fmt(PMHigh - PMLow) : "---") : fmt(PMRange)) : fmt(refPMValue)
displayORRef = referenceIsCurrentDow ? (time < OREND ? (showRealTimeOR and not na(ORHigh) and not na(ORLow) ? fmt(ORHigh - ORLow) : "---") : fmt(ORRange)) : fmt(refORValue)
displayIBRef = referenceIsCurrentDow ? (time < IBEND ? (showRealTimeIB and not na(IBHigh) and not na(IBLow) ? fmt(IBHigh - IBLow) : "---") : fmt(IBRange)) : fmt(refIBValue)
displayFHRef = referenceIsCurrentDow ? (time < FHEND ? (showRealTimeFH and not na(FHHigh) and not na(FHLow) ? fmt(FHHigh - FHLow) : "---") : fmt(FHRange)) : fmt(refFHValue)
displayDRRef = referenceIsCurrentDow ? (time < DREND ? (showRealTimeDR and not na(DRHigh) and not na(DRLow) ? formatDR(DRHigh - DRLow, DRLiveRangePct) : "---") : formatDR(DRRange, DRRangePct)) : formatDR(refDRValue, refDRPctValue)
displayChangeRef = referenceIsCurrentDow ? (time < DREND ? fmtChangePct(DailyChangePctLive) : fmtChangePct(DailyChangePct)) : fmtChangePct(refChangePctValue)
changeValueRef = referenceIsCurrentDow ? (time < DREND ? DailyChangePctLive : DailyChangePct) : refChangePctValue
dataBgColor = referenceIsCurrentDow ? color.white : refBgColor
table.cell(myTable, 1, referenceRow, displayPMRef, bgcolor=dataBgColor)
table.cell(myTable, 2, referenceRow, displayORRef, bgcolor=dataBgColor)
table.cell(myTable, 3, referenceRow, displayIBRef, bgcolor=dataBgColor)
table.cell(myTable, 4, referenceRow, displayFHRef, bgcolor=dataBgColor)
table.cell(myTable, 5, referenceRow, displayDRRef, bgcolor=dataBgColor)
table.cell(myTable, 6, referenceRow, displayChangeRef, text_color=getChangeTextColor(changeValueRef), bgcolor=getChangeColor(changeValueRef))
refPMForDiff = referenceIsCurrentDow ? PMRange : refPMValue
refORForDiff = referenceIsCurrentDow ? ORRange : refORValue
refIBForDiff = referenceIsCurrentDow ? IBRange : refIBValue
refFHForRatio = referenceIsCurrentDow ? FHRange : refFHValue
diffPM = percentDiff(refPMForDiff, avgPMValueDow)
diffOR = percentDiff(refORForDiff, avgORValueDow)
diffIB = percentDiff(refIBForDiff, avgIBValueDow)
hidePMDiff = referenceIsCurrentDow and time < PREMARKETEND
hideORDiff = referenceIsCurrentDow and time < OREND
hideIBDiff = referenceIsCurrentDow and time < IBEND
labelDiffPM = na(diffPM) or hidePMDiff ? "---" : (diffPM > 0 ? "+" : "") + str.tostring(diffPM) + "%"
labelDiffOR = na(diffOR) or hideORDiff ? "---" : (diffOR > 0 ? "+" : "") + str.tostring(diffOR) + "%"
labelDiffIB = na(diffIB) or hideIBDiff ? "---" : (diffIB > 0 ? "+" : "") + str.tostring(diffIB) + "%"
bgPM = na(diffPM) or hidePMDiff ? color.white : getColorFromDiff(diffPM)
bgOR = na(diffOR) or hideORDiff ? color.white : getColorFromDiff(diffOR)
bgIB = na(diffIB) or hideIBDiff ? color.white : getColorFromDiff(diffIB)
table.cell(myTable, 0, deltaRow, "Δ%", bgcolor=color.rgb(0, 0, 0), text_color=color.white)
table.cell(myTable, 1, deltaRow, labelDiffPM, bgcolor=bgPM)
table.cell(myTable, 2, deltaRow, labelDiffOR, bgcolor=bgOR)
table.cell(myTable, 3, deltaRow, labelDiffIB, bgcolor=bgIB)
ratioFhAdr = not na(refFHForRatio) and not na(avgDRValueDow) and avgDRValueDow != 0 ? math.round(refFHForRatio / avgDRValueDow * 100) : na
hideFhAdr = referenceIsCurrentDow and time < FHEND
labelFhAdr = na(ratioFhAdr) or hideFhAdr ? "---" : str.tostring(ratioFhAdr) + "%"
colorFhAdr = na(ratioFhAdr) or hideFhAdr ? color.white : ratioFhAdr <= ibAdrThreshold ? color.green : color.red
table.cell(myTable, 4, deltaRow, "r16:30 / ADR ->", bgcolor=color.rgb(0, 0, 0), text_color=color.white)
table.cell(myTable, 5, deltaRow, labelFhAdr, bgcolor=colorFhAdr)
table.cell(myTable, 6, deltaRow, "", bgcolor=color.rgb(0, 0, 0), text_color=color.white)