SPY Auction Intelligence v4 - Hierarchical Quant

salrafiq1 · study · 1050 行 · 点赞 3 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
import TradingView/ta/14 as tvta
 
indicator("SPY Auction Intelligence v4 - Hierarchical Quant", shorttitle="SPY Auction Quant v4", overlay=true, max_lines_count=20, max_labels_count=100)
 
//=============================================================================
// 01. FUNCTIONS
//=============================================================================
 
f_clamp(float value, float lower, float upper) =>
    math.max(lower, math.min(upper, value))
 
f_price(float value) =>
    na(value) ? "n/a" : str.tostring(value, format.mintick)
 
f_volume(float value) =>
    na(value) ? "n/a" : str.tostring(value, format.volume)
 
f_decimal(float value) =>
    na(value) ? "n/a" : str.tostring(value, "#.000")
 
f_percent(float value) =>
    na(value) ? "n/a" : str.tostring(value * 100.0, "#.0") + "%"
 
f_signed_percent(float value) =>
    na(value) ? "n/a" : (value > 0 ? "+" : "") + str.tostring(value, "#.0") + "%"
 
f_range_pair(float upper, float lower) =>
    na(upper) or na(lower) ? "n/a" : f_price(upper) + " / " + f_price(lower)
 
f_range_state(float price, float upper, float lower, string aboveText, string belowText, string insideText) =>
    na(upper) or na(lower) ? "WAITING" : price > upper ? aboveText : price < lower ? belowText : insideText
 
f_grid_slot(int gridId, array<int> ids, array<float> volumes, array<int> interactions, array<int> aboveCounts, array<int> belowCounts, array<int> lastInteractionBars) =>
    int slot = array.indexof(ids, gridId)
    if slot == -1
        array.push(ids, gridId)
        array.push(volumes, 0.0)
        array.push(interactions, 0)
        array.push(aboveCounts, 0)
        array.push(belowCounts, 0)
        array.push(lastInteractionBars, -2)
        slot := array.size(ids) - 1
    slot
 
f_grid_float(int gridId, array<int> ids, array<float> values) =>
    int slot = array.indexof(ids, gridId)
    slot == -1 ? 0.0 : array.get(values, slot)
 
f_grid_int(int gridId, array<int> ids, array<int> values) =>
    int slot = array.indexof(ids, gridId)
    slot == -1 ? 0 : array.get(values, slot)
 
f_market_direction(string symbol) =>
    request.security(symbol, timeframe.period, not na(close) and not na(close[1]) ? close > close[1] ? 1.0 : close < close[1] ? -1.0 : 0.0 : na, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
 
//=============================================================================
// 02. SESSION SETTINGS
//=============================================================================
 
const string TZ = "America/New_York"
 
string premarketSession = input.session("0400-0930", "Premarket", group="01 - Sessions")
string regularSession = input.session("0930-1600", "Regular session", group="01 - Sessions")
string afterHoursSession = input.session("1600-2000", "After hours", group="01 - Sessions")
string openingRangeSession = input.session("0930-0945", "Opening range", group="01 - Sessions")
 
//=============================================================================
// 03. PRICE GRID SETTINGS
//=============================================================================
 
float gridStep = input.float(0.50, "Grid increment ($)", minval=0.01, step=0.01, group="02 - Price Grid")
float gridTouchTolerance = input.float(0.08, "Grid interaction tolerance ($)", minval=0.01, step=0.01, group="02 - Price Grid")
bool showGridLines = input.bool(true, "Show grid lines", group="02 - Price Grid")
bool showSignalMarkers = input.bool(true, "Show response and divergence markers", group="02 - Price Grid")
 
//=============================================================================
// 04. ORDER-FLOW SETTINGS
//=============================================================================
 
string cvdAnchorInput = input.timeframe("1D", "CVD anchor period", group="03 - Order Flow")
bool useCustomLowerTimeframe = input.bool(false, "Use custom lower timeframe", group="03 - Order Flow")
string customLowerTimeframe = input.timeframe("1", "Lower timeframe", group="03 - Order Flow")
float strongDeltaPercent = input.float(18.0, "Strong delta threshold (%)", minval=1.0, maxval=100.0, step=1.0, group="03 - Order Flow")
int divergenceLookback = input.int(12, "Divergence lookback", minval=3, maxval=100, group="03 - Order Flow")
 
//=============================================================================
// 05. QUANTITATIVE MODEL SETTINGS
//=============================================================================
 
int probabilityHorizon = input.int(3, "Forecast horizon (chart bars)", minval=1, maxval=30, group="04 - Probability Engine")
int minimumSamples = input.int(25, "Minimum global and score-bin samples", minval=5, maxval=500, group="04 - Probability Engine")
int scorePriorStrength = input.int(30, "Score-level prior strength", minval=1, maxval=300, group="04 - Probability Engine")
int regimePriorStrength = input.int(15, "Regime-cell prior strength", minval=1, maxval=300, group="04 - Probability Engine")
int maxTrainingSamples = input.int(1200, "Rolling resolved observations", minval=100, maxval=5000, group="04 - Probability Engine")
float probabilityAlertThreshold = input.float(0.65, "Probability alert threshold", minval=0.50, maxval=0.95, step=0.05, group="04 - Probability Engine")
 
//=============================================================================
// 06. REGIME AND CHANGE-DETECTION SETTINGS
//=============================================================================
 
int trendLookback = input.int(5, "Trend-efficiency lookback", minval=5, maxval=50, group="05 - Statistical Models")
float trendEfficiencyThreshold = input.float(0.30, "Directional regime threshold", minval=0.05, maxval=0.90, step=0.05, group="05 - Statistical Models")
float cusumDrift = input.float(0.10, "CUSUM drift", minval=0.01, maxval=1.0, step=0.01, group="05 - Statistical Models")
float cusumThreshold = input.float(2.50, "CUSUM threshold", minval=0.50, maxval=10.0, step=0.25, group="05 - Statistical Models")
float volatilityExpansionFactor = input.float(1.20, "Volatility expansion factor", minval=1.01, maxval=3.0, step=0.05, group="05 - Statistical Models")
 
//=============================================================================
// 07. CROSS-MARKET SYMBOLS
//=============================================================================
 
bool useCrossMarket = input.bool(true, "Include cross-market confirmation in score", group="06 - Cross-Market Context")
 
string symXLK = input.symbol("AMEX:XLK", "Technology - XLK", group="06 - Cross-Market Context")
string symXLF = input.symbol("AMEX:XLF", "Financials - XLF", group="06 - Cross-Market Context")
string symXLY = input.symbol("AMEX:XLY", "Consumer discretionary - XLY", group="06 - Cross-Market Context")
string symXLP = input.symbol("AMEX:XLP", "Consumer staples - XLP", group="06 - Cross-Market Context")
string symXLE = input.symbol("AMEX:XLE", "Energy - XLE", group="06 - Cross-Market Context")
string symXLI = input.symbol("AMEX:XLI", "Industrials - XLI", group="06 - Cross-Market Context")
string symXLB = input.symbol("AMEX:XLB", "Materials - XLB", group="06 - Cross-Market Context")
string symXLV = input.symbol("AMEX:XLV", "Health care - XLV", group="06 - Cross-Market Context")
string symXLU = input.symbol("AMEX:XLU", "Utilities - XLU", group="06 - Cross-Market Context")
string symXLRE = input.symbol("AMEX:XLRE", "Real estate - XLRE", group="06 - Cross-Market Context")
string symXLC = input.symbol("AMEX:XLC", "Communication services - XLC", group="06 - Cross-Market Context")
string symQQQ = input.symbol("NASDAQ:QQQ", "Nasdaq 100 ETF - QQQ", group="06 - Cross-Market Context")
string symDIA = input.symbol("AMEX:DIA", "Dow ETF - DIA", group="06 - Cross-Market Context")
string symIWM = input.symbol("AMEX:IWM", "Russell 2000 ETF - IWM", group="06 - Cross-Market Context")
string symES = input.symbol("CME_MINI:ES1!", "S&P futures - ES", group="06 - Cross-Market Context")
string symNQ = input.symbol("CME_MINI:NQ1!", "Nasdaq futures - NQ", group="06 - Cross-Market Context")
string symYM = input.symbol("CBOT_MINI:YM1!", "Dow futures - YM", group="06 - Cross-Market Context")
 
//=============================================================================
// 08. TIMEFRAME VALIDATION
//=============================================================================
 
string lowerTimeframe = switch
    useCustomLowerTimeframe => customLowerTimeframe
    timeframe.isseconds => "1S"
    timeframe.isintraday => "1"
    timeframe.isdaily => "5"
    => "60"
 
if not timeframe.isintraday
    runtime.error("Use this dashboard on an intraday chart.")
 
if timeframe.in_seconds() > 900
    runtime.error("Use a chart timeframe of 15 minutes or lower.")
 
if timeframe.in_seconds(lowerTimeframe) > timeframe.in_seconds()
    runtime.error("CVD lower timeframe must be equal to or lower than the chart timeframe.")
 
//=============================================================================
// 09. SESSION DETECTION
//=============================================================================
 
bool inPremarket = not na(time(timeframe.period, premarketSession, TZ))
bool inRegular = not na(time(timeframe.period, regularSession, TZ))
bool inAfterHours = not na(time(timeframe.period, afterHoursSession, TZ))
bool inOpeningRange = not na(time(timeframe.period, openingRangeSession, TZ))
 
bool newPremarket = inPremarket and not inPremarket[1]
bool newRegular = inRegular and not inRegular[1]
 
int barsSinceRthOpen = ta.barssince(newRegular)
 
//=============================================================================
// 10. DEVELOPING SESSION LEVELS AND VWAP
//=============================================================================
 
var float premarketHigh = na
var float premarketLow = na
var bool premarketSeenToday = false
 
var float openingRangeHigh = na
var float openingRangeLow = na
 
var float regularHigh = na
var float regularLow = na
 
var float rthPriceVolume = 0.0
var float rthVolume = 0.0
 
if newPremarket
    premarketHigh := high
    premarketLow := low
    premarketSeenToday := true
    openingRangeHigh := na
    openingRangeLow := na
    regularHigh := na
    regularLow := na
    rthPriceVolume := 0.0
    rthVolume := 0.0
else if inPremarket
    premarketHigh := na(premarketHigh) ? high : math.max(premarketHigh, high)
    premarketLow := na(premarketLow) ? low : math.min(premarketLow, low)
 
if newRegular
    if not premarketSeenToday
        premarketHigh := na
        premarketLow := na
 
    premarketSeenToday := false
    openingRangeHigh := na
    openingRangeLow := na
    regularHigh := high
    regularLow := low
    rthPriceVolume := 0.0
    rthVolume := 0.0
 
if inRegular
    regularHigh := na(regularHigh) ? high : math.max(regularHigh, high)
    regularLow := na(regularLow) ? low : math.min(regularLow, low)
 
    if inOpeningRange
        openingRangeHigh := na(openingRangeHigh) ? high : math.max(openingRangeHigh, high)
        openingRangeLow := na(openingRangeLow) ? low : math.min(openingRangeLow, low)
 
    if not na(volume) and volume > 0
        rthPriceVolume += hlc3 * volume
        rthVolume += volume
 
float rthVwap = rthVolume > 0 ? rthPriceVolume / rthVolume : na
 
//=============================================================================
// 11. PREVIOUS COMPLETED DAILY LEVELS
//=============================================================================
 
float priorDayHigh = request.security(syminfo.tickerid, "D", high[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
float priorDayLow = request.security(syminfo.tickerid, "D", low[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
 
//=============================================================================
// 12. CUMULATIVE VOLUME DELTA
//=============================================================================
 
[cvdOpen, cvdHigh, cvdLow, cvdClose] = tvta.requestVolumeDelta(lowerTimeframe, cvdAnchorInput)
 
bool cvdDataAvailable = not na(cvdOpen) and not na(cvdClose)
float barDelta = cvdDataAvailable ? cvdClose - cvdOpen : na
float barDeltaPercent = not na(barDelta) and not na(volume) and volume > 0 ? 100.0 * barDelta / volume : na
 
var float rthCvd = na
var bool rthCvdAvailable = false
 
if newPremarket
    rthCvd := na
    rthCvdAvailable := false
 
if newRegular
    rthCvd := nz(barDelta, 0.0)
    rthCvdAvailable := cvdDataAvailable
else if inRegular
    rthCvd := nz(rthCvd[1], 0.0) + nz(barDelta, 0.0)
    if cvdDataAvailable
        rthCvdAvailable := true
 
//=============================================================================
// 13. CROSS-MARKET AND ELEVEN-SECTOR CONFIRMATION
//=============================================================================
 
float dirXLK = f_market_direction(symXLK)
float dirXLF = f_market_direction(symXLF)
float dirXLY = f_market_direction(symXLY)
float dirXLP = f_market_direction(symXLP)
float dirXLE = f_market_direction(symXLE)
float dirXLI = f_market_direction(symXLI)
float dirXLB = f_market_direction(symXLB)
float dirXLV = f_market_direction(symXLV)
float dirXLU = f_market_direction(symXLU)
float dirXLRE = f_market_direction(symXLRE)
float dirXLC = f_market_direction(symXLC)
 
float dirQQQ = f_market_direction(symQQQ)
float dirDIA = f_market_direction(symDIA)
float dirIWM = f_market_direction(symIWM)
float dirES = f_market_direction(symES)
float dirNQ = f_market_direction(symNQ)
float dirYM = f_market_direction(symYM)
 
int sectorBullishCount = 0
int sectorBearishCount = 0
int sectorValidCount = 0
 
if not na(dirXLK)
    sectorValidCount += 1
    sectorBullishCount += dirXLK > 0 ? 1 : 0
    sectorBearishCount += dirXLK < 0 ? 1 : 0
if not na(dirXLF)
    sectorValidCount += 1
    sectorBullishCount += dirXLF > 0 ? 1 : 0
    sectorBearishCount += dirXLF < 0 ? 1 : 0
if not na(dirXLY)
    sectorValidCount += 1
    sectorBullishCount += dirXLY > 0 ? 1 : 0
    sectorBearishCount += dirXLY < 0 ? 1 : 0
if not na(dirXLP)
    sectorValidCount += 1
    sectorBullishCount += dirXLP > 0 ? 1 : 0
    sectorBearishCount += dirXLP < 0 ? 1 : 0
if not na(dirXLE)
    sectorValidCount += 1
    sectorBullishCount += dirXLE > 0 ? 1 : 0
    sectorBearishCount += dirXLE < 0 ? 1 : 0
if not na(dirXLI)
    sectorValidCount += 1
    sectorBullishCount += dirXLI > 0 ? 1 : 0
    sectorBearishCount += dirXLI < 0 ? 1 : 0
if not na(dirXLB)
    sectorValidCount += 1
    sectorBullishCount += dirXLB > 0 ? 1 : 0
    sectorBearishCount += dirXLB < 0 ? 1 : 0
if not na(dirXLV)
    sectorValidCount += 1
    sectorBullishCount += dirXLV > 0 ? 1 : 0
    sectorBearishCount += dirXLV < 0 ? 1 : 0
if not na(dirXLU)
    sectorValidCount += 1
    sectorBullishCount += dirXLU > 0 ? 1 : 0
    sectorBearishCount += dirXLU < 0 ? 1 : 0
if not na(dirXLRE)
    sectorValidCount += 1
    sectorBullishCount += dirXLRE > 0 ? 1 : 0
    sectorBearishCount += dirXLRE < 0 ? 1 : 0
if not na(dirXLC)
    sectorValidCount += 1
    sectorBullishCount += dirXLC > 0 ? 1 : 0
    sectorBearishCount += dirXLC < 0 ? 1 : 0
 
float sectorBreadthScore = sectorValidCount > 0 ? (sectorBullishCount - sectorBearishCount) / sectorValidCount : na
 
int indexBullishCount = 0
int indexBearishCount = 0
int indexValidCount = 0
 
if not na(dirQQQ)
    indexValidCount += 1
    indexBullishCount += dirQQQ > 0 ? 1 : 0
    indexBearishCount += dirQQQ < 0 ? 1 : 0
if not na(dirDIA)
    indexValidCount += 1
    indexBullishCount += dirDIA > 0 ? 1 : 0
    indexBearishCount += dirDIA < 0 ? 1 : 0
if not na(dirIWM)
    indexValidCount += 1
    indexBullishCount += dirIWM > 0 ? 1 : 0
    indexBearishCount += dirIWM < 0 ? 1 : 0
if not na(dirES)
    indexValidCount += 1
    indexBullishCount += dirES > 0 ? 1 : 0
    indexBearishCount += dirES < 0 ? 1 : 0
if not na(dirNQ)
    indexValidCount += 1
    indexBullishCount += dirNQ > 0 ? 1 : 0
    indexBearishCount += dirNQ < 0 ? 1 : 0
if not na(dirYM)
    indexValidCount += 1
    indexBullishCount += dirYM > 0 ? 1 : 0
    indexBearishCount += dirYM < 0 ? 1 : 0
 
float indexBreadthScore = indexValidCount > 0 ? (indexBullishCount - indexBearishCount) / indexValidCount : na
 
float crossNumerator = 0.0
float crossDenominator = 0.0
 
if not na(sectorBreadthScore)
    crossNumerator += sectorBreadthScore * 0.55
    crossDenominator += 0.55
if not na(indexBreadthScore)
    crossNumerator += indexBreadthScore * 0.45
    crossDenominator += 0.45
 
float crossMarketRaw = crossDenominator > 0 ? crossNumerator / crossDenominator : 0.0
float crossMarketFeature = useCrossMarket ? f_clamp(crossMarketRaw, -1.0, 1.0) : 0.0
 
//=============================================================================
// 14. PRICE GRID CALCULATIONS
//=============================================================================
 
float gridLower = math.floor(close / gridStep) * gridStep
float gridUpper = gridLower + gridStep
 
float nearestGridToClose = math.round(close / gridStep) * gridStep
float nearestGridToHigh = math.round(high / gridStep) * gridStep
float nearestGridToLow = math.round(low / gridStep) * gridStep
 
float distanceToNearestGrid = math.abs(close - nearestGridToClose)
 
bool highNearGrid = math.abs(high - nearestGridToHigh) <= gridTouchTolerance
bool lowNearGrid = math.abs(low - nearestGridToLow) <= gridTouchTolerance
bool exactlyOnGrid = math.abs(close - gridLower) <= syminfo.mintick * 0.5
 
int floorGridId = int(math.floor(close / gridStep))
int nextUpGridId = floorGridId + 1
int nextDownGridId = exactlyOnGrid ? floorGridId - 1 : floorGridId
 
float nextUpPrice = nextUpGridId * gridStep
float nextDownPrice = nextDownGridId * gridStep
 
//=============================================================================
// 15. RTH GRID PROFILE PROXY AND DISTINCT INTERACTION EVENTS
//=============================================================================
 
// Volume is assigned to the nearest HLC3 grid level. This is a bar-volume proxy,
// not transaction-level volume-at-price. Consecutive touching bars count as one
// continuous interaction event rather than many separate touches.
 
var array<int> gridIds = array.new_int()
var array<float> gridVolumes = array.new_float()
var array<int> gridInteractions = array.new_int()
var array<int> gridClosesAbove = array.new_int()
var array<int> gridClosesBelow = array.new_int()
var array<int> gridLastInteractionBars = array.new_int()
 
if newRegular
    array.clear(gridIds)
    array.clear(gridVolumes)
    array.clear(gridInteractions)
    array.clear(gridClosesAbove)
    array.clear(gridClosesBelow)
    array.clear(gridLastInteractionBars)
 
if inRegular and barstate.isconfirmed
    int volumeGridId = int(math.round(hlc3 / gridStep))
    int volumeSlot = f_grid_slot(volumeGridId, gridIds, gridVolumes, gridInteractions, gridClosesAbove, gridClosesBelow, gridLastInteractionBars)
    array.set(gridVolumes, volumeSlot, array.get(gridVolumes, volumeSlot) + nz(volume, 0.0))
 
    int minGridId = int(math.floor((low - gridTouchTolerance) / gridStep))
    int maxGridId = int(math.ceil((high + gridTouchTolerance) / gridStep))
 
    if maxGridId - minGridId <= 40
        for levelId = minGridId to maxGridId
            float levelPrice = levelId * gridStep
            bool levelTouched = high >= levelPrice - gridTouchTolerance and low <= levelPrice + gridTouchTolerance
 
            if levelTouched
                int touchSlot = f_grid_slot(levelId, gridIds, gridVolumes, gridInteractions, gridClosesAbove, gridClosesBelow, gridLastInteractionBars)
                int lastInteractionBar = array.get(gridLastInteractionBars, touchSlot)
                bool newInteractionEvent = bar_index > lastInteractionBar + 1
 
                if newInteractionEvent
                    array.set(gridLastInteractionBars, touchSlot, bar_index)
                    array.set(gridInteractions, touchSlot, array.get(gridInteractions, touchSlot) + 1)
 
                    if close > levelPrice + gridTouchTolerance
                        array.set(gridClosesAbove, touchSlot, array.get(gridClosesAbove, touchSlot) + 1)
                    else if close < levelPrice - gridTouchTolerance
                        array.set(gridClosesBelow, touchSlot, array.get(gridClosesBelow, touchSlot) + 1)
 
float nearestGridVolume = f_grid_float(int(math.round(nearestGridToClose / gridStep)), gridIds, gridVolumes)
int nearestGridInteractions = f_grid_int(int(math.round(nearestGridToClose / gridStep)), gridIds, gridInteractions)
int nearestGridAboveCloses = f_grid_int(int(math.round(nearestGridToClose / gridStep)), gridIds, gridClosesAbove)
int nearestGridBelowCloses = f_grid_int(int(math.round(nearestGridToClose / gridStep)), gridIds, gridClosesBelow)
 
int directionalGridCloses = nearestGridAboveCloses + nearestGridBelowCloses
float gridUpClosePercent = directionalGridCloses > 0 ? 100.0 * nearestGridAboveCloses / directionalGridCloses : na
 
string gridResponseStatus = na(gridUpClosePercent) ? "INSUFFICIENT DATA" : gridUpClosePercent >= 60.0 ? "MORE CLOSES ABOVE" : gridUpClosePercent <= 40.0 ? "MORE CLOSES BELOW" : "MIXED RESPONSE"
 
//=============================================================================
// 16. CVD RESPONSE AND DIVERGENCE CANDIDATES
//=============================================================================
 
float barRange = math.max(high - low, syminfo.mintick)
float closeLocation = (close - low) / barRange
 
bool buyResponseCandidate = inRegular and barstate.isconfirmed and not na(barDeltaPercent) and barDeltaPercent <= -strongDeltaPercent and closeLocation >= 0.65 and lowNearGrid
bool sellResponseCandidate = inRegular and barstate.isconfirmed and not na(barDeltaPercent) and barDeltaPercent >= strongDeltaPercent and closeLocation <= 0.35 and highNearGrid
 
float priorPriceHigh = ta.highest(high, divergenceLookback)[1]
float priorPriceLow = ta.lowest(low, divergenceLookback)[1]
float priorCvdHigh = ta.highest(rthCvd, divergenceLookback)[1]
float priorCvdLow = ta.lowest(rthCvd, divergenceLookback)[1]
 
bool enoughRthBarsForDivergence = inRegular and not na(barsSinceRthOpen) and barsSinceRthOpen >= divergenceLookback
 
bool bearishDeltaDivergence = enoughRthBarsForDivergence and barstate.isconfirmed and not na(priorPriceHigh) and not na(priorCvdHigh) and high > priorPriceHigh and rthCvd < priorCvdHigh
bool bullishDeltaDivergence = enoughRthBarsForDivergence and barstate.isconfirmed and not na(priorPriceLow) and not na(priorCvdLow) and low < priorPriceLow and rthCvd > priorCvdLow
 
//=============================================================================
// 17. SESSION-AWARE STATISTICAL FEATURES
//=============================================================================
 
float atrValue = ta.atr(14)
float atrBaseline = ta.sma(atrValue, 50)
float volatilityRatio = not na(atrBaseline) and atrBaseline > 0 ? atrValue / atrBaseline : na
 
float rthVolumeSource = inRegular ? volume : na
float averageRthVolume = ta.sma(rthVolumeSource, 20)
float relativeVolume = inRegular and not na(averageRthVolume) and averageRthVolume > 0 ? volume / averageRthVolume : na
 
float oneBarChange = close - close[1]
float rthChangeSource = inRegular ? oneBarChange : na
float rthChangeMean = ta.sma(rthChangeSource, 20)
float rthChangeStd = ta.stdev(rthChangeSource, 20)
float returnZScore = inRegular and not na(rthChangeStd) and rthChangeStd > 0 ? (oneBarChange - rthChangeMean) / rthChangeStd : na
 
bool volatilityExpansion = not na(volatilityRatio) and volatilityRatio > volatilityExpansionFactor
bool volatilityContraction = not na(volatilityRatio) and volatilityRatio < 0.80
string volatilityLabel = volatilityExpansion ? "VOL EXPANSION" : volatilityContraction ? "VOL CONTRACTION" : "NORMAL VOL"
 
//=============================================================================
// 18. DIRECTIONAL FEATURE ENGINE
//=============================================================================
 
// Momentum and CVD changes require enough bars from the current RTH open.
// This prevents the opening feature values from referencing the prior session.
 
bool enoughSameSessionBars = inRegular and not na(barsSinceRthOpen) and barsSinceRthOpen >= 3
 
float momentumFeature = enoughSameSessionBars and atrValue > 0 ? f_clamp((close - close[3]) / (atrValue * 0.80), -1.0, 1.0) : 0.0
float vwapFeature = inRegular and not na(rthVwap) and atrValue > 0 ? f_clamp((close - rthVwap) / (atrValue * 0.50), -1.0, 1.0) : 0.0
float closePressureFeature = f_clamp(closeLocation * 2.0 - 1.0, -1.0, 1.0)
float deltaFeature = not na(barDeltaPercent) ? f_clamp(barDeltaPercent / 60.0, -1.0, 1.0) : 0.0
float cvdFeature = enoughSameSessionBars and rthCvdAvailable and not na(rthCvd[3]) and not na(averageRthVolume) and averageRthVolume > 0 ? f_clamp((rthCvd - rthCvd[3]) / (averageRthVolume * 3.0), -1.0, 1.0) : 0.0
 
// Below-average volume now contributes zero directional confirmation instead
// of incorrectly producing a signal in the opposite direction.
float candleDirection = close > open ? 1.0 : close < open ? -1.0 : 0.0
float rvolParticipation = not na(relativeVolume) ? f_clamp((relativeVolume - 1.0) / 1.5, 0.0, 1.0) : 0.0
float directionalRvol = candleDirection * rvolParticipation
 
float gridPositionFeature = f_clamp(((close - gridLower) / gridStep - 0.5) * 2.0, -1.0, 1.0)
 
// One combined breadth feature avoids treating 11 correlated sectors and
// multiple index/futures products as 17 independent votes.
float modelScore = f_clamp(0.18 * momentumFeature + 0.14 * vwapFeature + 0.12 * closePressureFeature + 0.14 * deltaFeature + 0.12 * cvdFeature + 0.09 * directionalRvol + 0.08 * gridPositionFeature + 0.13 * crossMarketFeature, -1.0, 1.0)
 
int scoreBin = int(math.max(0.0, math.min(8.0, math.floor((modelScore + 1.0) * 4.5))))
bool baseFeatureReady = inRegular and enoughSameSessionBars and not na(atrValue) and atrValue > 0 and not na(averageRthVolume) and averageRthVolume > 0
 
//=============================================================================
// 19. INDEPENDENT TREND-EFFICIENCY REGIME
//=============================================================================
 
float rthAbsoluteChange = inRegular ? math.abs(oneBarChange) : na
float averageAbsoluteRthChange = ta.sma(rthAbsoluteChange, trendLookback)
float trendPath = not na(averageAbsoluteRthChange) ? averageAbsoluteRthChange * trendLookback : na
float trendDisplacement = not na(barsSinceRthOpen) and barsSinceRthOpen >= trendLookback ? close - close[trendLookback] : na
float trendEfficiency = not na(trendPath) and trendPath > 0 and not na(trendDisplacement) ? math.abs(trendDisplacement) / trendPath : na
 
int regimeState = not na(trendEfficiency) and trendEfficiency >= trendEfficiencyThreshold and trendDisplacement > 0 ? 1 : not na(trendEfficiency) and trendEfficiency >= trendEfficiencyThreshold and trendDisplacement < 0 ? -1 : 0
 
string regimeLabel = regimeState == 1 ? "UP TREND" : regimeState == -1 ? "DOWN TREND" : "BALANCED"
int regimeIndex = regimeState + 1
bool featureReady = baseFeatureReady and not na(trendEfficiency)
 
//=============================================================================
// 20. SMOOTHED MARKOV REGIME TRANSITIONS
//=============================================================================
 
var array<int> regimeTransitions = array.new_int(9, 0)
var array<int> regimeTransitionTotals = array.new_int(3, 0)
 
if inRegular and inRegular[1] and barstate.isconfirmed
    int previousStateIndex = regimeState[1] + 1
    int currentStateForMarkov = regimeState + 1
    int transitionIndex = previousStateIndex * 3 + currentStateForMarkov
    array.set(regimeTransitions, transitionIndex, array.get(regimeTransitions, transitionIndex) + 1)
    array.set(regimeTransitionTotals, previousStateIndex, array.get(regimeTransitionTotals, previousStateIndex) + 1)
 
int currentStateIndex = regimeState + 1
int persistenceIndex = currentStateIndex * 3 + currentStateIndex
int currentStateTransitionCount = array.get(regimeTransitionTotals, currentStateIndex)
int currentStatePersistenceCount = array.get(regimeTransitions, persistenceIndex)
float markovPersistence = (currentStatePersistenceCount + 1.0) / (currentStateTransitionCount + 3.0)
 
//=============================================================================
// 21. CUSUM CHANGE-POINT DETECTION
//=============================================================================
 
var float cusumPositive = 0.0
var float cusumNegative = 0.0
 
float normalizedReturn = not na(atrValue) and atrValue > 0 ? oneBarChange / atrValue : 0.0
 
if newRegular
    cusumPositive := 0.0
    cusumNegative := 0.0
else if inRegular and barstate.isconfirmed
    cusumPositive := math.max(0.0, nz(cusumPositive[1], 0.0) + normalizedReturn - cusumDrift)
    cusumNegative := math.min(0.0, nz(cusumNegative[1], 0.0) + normalizedReturn + cusumDrift)
 
bool bullishCusumSignal = inRegular and barstate.isconfirmed and cusumPositive >= cusumThreshold and nz(cusumPositive[1], 0.0) < cusumThreshold
bool bearishCusumSignal = inRegular and barstate.isconfirmed and cusumNegative <= -cusumThreshold and nz(cusumNegative[1], 0.0) > -cusumThreshold
string cusumStatus = bullishCusumSignal ? "POSITIVE SHIFT" : bearishCusumSignal ? "NEGATIVE SHIFT" : "NO NEW SHIFT"
 
//=============================================================================
// 22. HIERARCHICAL BAYESIAN OUTCOME MODEL
//=============================================================================
 
// Outcome classes:
// +1 = upper adjacent grid level reached first.
// -1 = lower adjacent grid level reached first.
//  0 = neither adjacent level reached within the forecast horizon.
// Same-bar dual touches are ambiguous and excluded because OHLC bars do not
// reveal which level traded first.
// Only one forecast may be pending at a time, preventing overlapping samples.
 
var array<int> scoreUpCounts = array.new_int(9, 0)
var array<int> scoreDownCounts = array.new_int(9, 0)
var array<int> scoreNoneCounts = array.new_int(9, 0)
 
var array<int> cellUpCounts = array.new_int(27, 0)
var array<int> cellDownCounts = array.new_int(27, 0)
var array<int> cellNoneCounts = array.new_int(27, 0)
 
var array<int> pendingBars = array.new_int()
var array<int> pendingBins = array.new_int()
var array<int> pendingRegimes = array.new_int()
var array<float> pendingUpTargets = array.new_float()
var array<float> pendingDownTargets = array.new_float()
var array<float> pendingModelUp = array.new_float()
var array<float> pendingModelDown = array.new_float()
var array<float> pendingModelNone = array.new_float()
var array<float> pendingBaseUp = array.new_float()
var array<float> pendingBaseDown = array.new_float()
var array<float> pendingBaseNone = array.new_float()
 
var array<int> resolvedBins = array.new_int()
var array<int> resolvedRegimes = array.new_int()
var array<int> resolvedOutcomes = array.new_int()
var array<float> resolvedBrier = array.new_float()
var array<float> resolvedBaselineBrier = array.new_float()
 
var int globalUpCount = 0
var int globalDownCount = 0
var int globalNoneCount = 0
var int ambiguousObservations = 0
 
var float modelBrierSum = 0.0
var float baselineBrierSum = 0.0
 
// Outstanding forecasts are censored at the new regular session rather than
// incorrectly becoming no-touch outcomes across the overnight gap.
if newRegular
    array.clear(pendingBars)
    array.clear(pendingBins)
    array.clear(pendingRegimes)
    array.clear(pendingUpTargets)
    array.clear(pendingDownTargets)
    array.clear(pendingModelUp)
    array.clear(pendingModelDown)
    array.clear(pendingModelNone)
    array.clear(pendingBaseUp)
    array.clear(pendingBaseDown)
    array.clear(pendingBaseNone)
 
// Resolve the pending observation before creating a new one on this bar.
if inRegular and barstate.isconfirmed
    int pendingIndex = 0
    while pendingIndex < array.size(pendingBars)
        int sampleBar = array.get(pendingBars, pendingIndex)
        int sampleAge = bar_index - sampleBar
        float targetUp = array.get(pendingUpTargets, pendingIndex)
        float targetDown = array.get(pendingDownTargets, pendingIndex)
 
        bool hitUp = high >= targetUp
        bool hitDown = low <= targetDown
        bool expired = sampleAge >= probabilityHorizon
        bool completed = hitUp or hitDown or expired
 
        if completed
            if hitUp and hitDown
                ambiguousObservations += 1
            else
                int sampleBin = array.get(pendingBins, pendingIndex)
                int sampleRegime = array.get(pendingRegimes, pendingIndex)
                int sampleCell = sampleRegime * 9 + sampleBin
                int outcome = hitUp ? 1 : hitDown ? -1 : 0
                int outcomeIndex = outcome == 1 ? 0 : outcome == -1 ? 1 : 2
 
                float predictedUp = array.get(pendingModelUp, pendingIndex)
                float predictedDown = array.get(pendingModelDown, pendingIndex)
                float predictedNone = array.get(pendingModelNone, pendingIndex)
                float baselineUp = array.get(pendingBaseUp, pendingIndex)
                float baselineDown = array.get(pendingBaseDown, pendingIndex)
                float baselineNone = array.get(pendingBaseNone, pendingIndex)
 
                float actualUp = outcome == 1 ? 1.0 : 0.0
                float actualDown = outcome == -1 ? 1.0 : 0.0
                float actualNone = outcome == 0 ? 1.0 : 0.0
 
                float modelError = ((predictedUp - actualUp) * (predictedUp - actualUp) + (predictedDown - actualDown) * (predictedDown - actualDown) + (predictedNone - actualNone) * (predictedNone - actualNone)) / 3.0
                float baselineError = ((baselineUp - actualUp) * (baselineUp - actualUp) + (baselineDown - actualDown) * (baselineDown - actualDown) + (baselineNone - actualNone) * (baselineNone - actualNone)) / 3.0
 
                // Remove the oldest resolved event from every level of the hierarchy.
                if array.size(resolvedBins) >= maxTrainingSamples
                    int oldBin = array.shift(resolvedBins)
                    int oldRegime = array.shift(resolvedRegimes)
                    int oldOutcome = array.shift(resolvedOutcomes)
                    float oldBrier = array.shift(resolvedBrier)
                    float oldBaselineBrier = array.shift(resolvedBaselineBrier)
                    int oldCell = oldRegime * 9 + oldBin
 
                    modelBrierSum := modelBrierSum - oldBrier
                    baselineBrierSum := baselineBrierSum - oldBaselineBrier
 
                    if oldOutcome == 1
                        array.set(scoreUpCounts, oldBin, math.max(0, array.get(scoreUpCounts, oldBin) - 1))
                        array.set(cellUpCounts, oldCell, math.max(0, array.get(cellUpCounts, oldCell) - 1))
                        globalUpCount := math.max(0, globalUpCount - 1)
                    else if oldOutcome == -1
                        array.set(scoreDownCounts, oldBin, math.max(0, array.get(scoreDownCounts, oldBin) - 1))
                        array.set(cellDownCounts, oldCell, math.max(0, array.get(cellDownCounts, oldCell) - 1))
                        globalDownCount := math.max(0, globalDownCount - 1)
                    else
                        array.set(scoreNoneCounts, oldBin, math.max(0, array.get(scoreNoneCounts, oldBin) - 1))
                        array.set(cellNoneCounts, oldCell, math.max(0, array.get(cellNoneCounts, oldCell) - 1))
                        globalNoneCount := math.max(0, globalNoneCount - 1)
 
                // Add the newly resolved observation to score, regime-cell and global counts.
                array.push(resolvedBins, sampleBin)
                array.push(resolvedRegimes, sampleRegime)
                array.push(resolvedOutcomes, outcome)
                array.push(resolvedBrier, modelError)
                array.push(resolvedBaselineBrier, baselineError)
 
                modelBrierSum += modelError
                baselineBrierSum += baselineError
 
                if outcome == 1
                    array.set(scoreUpCounts, sampleBin, array.get(scoreUpCounts, sampleBin) + 1)
                    array.set(cellUpCounts, sampleCell, array.get(cellUpCounts, sampleCell) + 1)
                    globalUpCount += 1
                else if outcome == -1
                    array.set(scoreDownCounts, sampleBin, array.get(scoreDownCounts, sampleBin) + 1)
                    array.set(cellDownCounts, sampleCell, array.get(cellDownCounts, sampleCell) + 1)
                    globalDownCount += 1
                else
                    array.set(scoreNoneCounts, sampleBin, array.get(scoreNoneCounts, sampleBin) + 1)
                    array.set(cellNoneCounts, sampleCell, array.get(cellNoneCounts, sampleCell) + 1)
                    globalNoneCount += 1
 
            // Remove the completed or ambiguous forecast.
            array.remove(pendingBars, pendingIndex)
            array.remove(pendingBins, pendingIndex)
            array.remove(pendingRegimes, pendingIndex)
            array.remove(pendingUpTargets, pendingIndex)
            array.remove(pendingDownTargets, pendingIndex)
            array.remove(pendingModelUp, pendingIndex)
            array.remove(pendingModelDown, pendingIndex)
            array.remove(pendingModelNone, pendingIndex)
            array.remove(pendingBaseUp, pendingIndex)
            array.remove(pendingBaseDown, pendingIndex)
            array.remove(pendingBaseNone, pendingIndex)
        else
            pendingIndex += 1
 
//=============================================================================
// 23. HIERARCHICAL POSTERIOR CALCULATIONS
//=============================================================================
 
int cellId = regimeIndex * 9 + scoreBin
 
int scoreUpCount = array.get(scoreUpCounts, scoreBin)
int scoreDownCount = array.get(scoreDownCounts, scoreBin)
int scoreNoneCount = array.get(scoreNoneCounts, scoreBin)
int scoreSampleCount = scoreUpCount + scoreDownCount + scoreNoneCount
 
int cellUpCount = array.get(cellUpCounts, cellId)
int cellDownCount = array.get(cellDownCounts, cellId)
int cellNoneCount = array.get(cellNoneCounts, cellId)
int cellSampleCount = cellUpCount + cellDownCount + cellNoneCount
 
int globalSampleCount = globalUpCount + globalDownCount + globalNoneCount
 
// First level: empirical prior from all score bins other than the current bin.
int globalOtherUp = math.max(0, globalUpCount - scoreUpCount)
int globalOtherDown = math.max(0, globalDownCount - scoreDownCount)
int globalOtherNone = math.max(0, globalNoneCount - scoreNoneCount)
int globalOtherSampleCount = globalOtherUp + globalOtherDown + globalOtherNone
float globalPriorDenominator = globalOtherSampleCount + 3.0
float globalPriorUp = (globalOtherUp + 1.0) / globalPriorDenominator
float globalPriorDown = (globalOtherDown + 1.0) / globalPriorDenominator
float globalPriorNone = (globalOtherNone + 1.0) / globalPriorDenominator
 
// Second level: score-bin distribution excluding the current regime cell.
int scoreOtherUp = math.max(0, scoreUpCount - cellUpCount)
int scoreOtherDown = math.max(0, scoreDownCount - cellDownCount)
int scoreOtherNone = math.max(0, scoreNoneCount - cellNoneCount)
int scoreOtherSampleCount = scoreOtherUp + scoreOtherDown + scoreOtherNone
float scorePriorDenominator = scoreOtherSampleCount + scorePriorStrength
float scorePriorUp = (scoreOtherUp + scorePriorStrength * globalPriorUp) / scorePriorDenominator
float scorePriorDown = (scoreOtherDown + scorePriorStrength * globalPriorDown) / scorePriorDenominator
float scorePriorNone = (scoreOtherNone + scorePriorStrength * globalPriorNone) / scorePriorDenominator
 
// Third level: local regime-and-score posterior shrunk toward the score-level prior.
float cellPosteriorDenominator = cellSampleCount + regimePriorStrength
float probabilityUp = (cellUpCount + regimePriorStrength * scorePriorUp) / cellPosteriorDenominator
float probabilityDown = (cellDownCount + regimePriorStrength * scorePriorDown) / cellPosteriorDenominator
float probabilityNone = (cellNoneCount + regimePriorStrength * scorePriorNone) / cellPosteriorDenominator
 
// Unconditional benchmark is stored with each forecast for a fair sequential comparison.
float baselineDenominator = globalSampleCount + 3.0
float baselineProbabilityUp = (globalUpCount + 1.0) / baselineDenominator
float baselineProbabilityDown = (globalDownCount + 1.0) / baselineDenominator
float baselineProbabilityNone = (globalNoneCount + 1.0) / baselineDenominator
 
bool modelReady = globalSampleCount >= minimumSamples and scoreSampleCount >= minimumSamples
int cellSupportMinimum = math.max(5, int(math.round(minimumSamples * 0.25)))
string modelReadiness = not inRegular ? "RTH ONLY" : not modelReady ? "WARMING UP" : cellSampleCount >= cellSupportMinimum ? "CELL SUPPORTED" : "SCORE BACKOFF"
 
float averageModelBrier = array.size(resolvedBrier) > 0 ? modelBrierSum / array.size(resolvedBrier) : na
float averageBaselineBrier = array.size(resolvedBaselineBrier) > 0 ? baselineBrierSum / array.size(resolvedBaselineBrier) : na
float brierSkill = not na(averageBaselineBrier) and averageBaselineBrier > 0 and not na(averageModelBrier) ? 1.0 - averageModelBrier / averageBaselineBrier : na
int totalResolvedObservations = array.size(resolvedBins)
 
//=============================================================================
// 24. CREATE NON-OVERLAPPING FORECAST OBSERVATION
//=============================================================================
 
if inRegular and barstate.isconfirmed and featureReady and array.size(pendingBars) == 0
    array.push(pendingBars, bar_index)
    array.push(pendingBins, scoreBin)
    array.push(pendingRegimes, regimeIndex)
    array.push(pendingUpTargets, nextUpPrice)
    array.push(pendingDownTargets, nextDownPrice)
    array.push(pendingModelUp, probabilityUp)
    array.push(pendingModelDown, probabilityDown)
    array.push(pendingModelNone, probabilityNone)
    array.push(pendingBaseUp, baselineProbabilityUp)
    array.push(pendingBaseDown, baselineProbabilityDown)
    array.push(pendingBaseNone, baselineProbabilityNone)
 
//=============================================================================
// 25. DASHBOARD INTERPRETATION
//=============================================================================
 
string vwapStatus = na(rthVwap) ? "WAITING" : close > rthVwap ? "ABOVE VWAP" : close < rthVwap ? "BELOW VWAP" : "AT VWAP"
string vwapDetail = na(rthVwap) ? "n/a" : f_price(rthVwap) + " | " + (close >= rthVwap ? "+" : "") + str.tostring(close - rthVwap, format.mintick)
 
string cvdStatus = not rthCvdAvailable ? "NO CVD DATA" : rthCvd > 0 ? "NET BUY DELTA" : rthCvd < 0 ? "NET SELL DELTA" : "BALANCED"
string cvdDirection = not rthCvdAvailable or na(rthCvd[3]) or not enoughSameSessionBars ? "n/a" : rthCvd > rthCvd[3] ? "RISING" : rthCvd < rthCvd[3] ? "FALLING" : "FLAT"
string cvdDetail = not rthCvdAvailable ? "n/a" : f_volume(rthCvd) + " | " + cvdDirection
 
string deltaStatus = na(barDeltaPercent) ? "NO DELTA DATA" : barDeltaPercent >= strongDeltaPercent ? "STRONG BUY DELTA" : barDeltaPercent <= -strongDeltaPercent ? "STRONG SELL DELTA" : "MIXED DELTA"
string deltaDetail = na(barDelta) ? "n/a" : f_volume(barDelta) + " | " + f_signed_percent(barDeltaPercent)
 
 
string openingRangeStatus = f_range_state(close, openingRangeHigh, openingRangeLow, "ABOVE OR HIGH", "BELOW OR LOW", "INSIDE OR")
string premarketStatus = f_range_state(close, premarketHigh, premarketLow, "ABOVE PM HIGH", "BELOW PM LOW", "INSIDE PM RANGE")
string priorDayStatus = f_range_state(close, priorDayHigh, priorDayLow, "ABOVE PD HIGH", "BELOW PD LOW", "INSIDE PRIOR RANGE")
 
 
string probabilityText = "UP " + f_percent(probabilityUp) + " | DN " + f_percent(probabilityDown)
string probabilityDetail = "NONE " + f_percent(probabilityNone) + " | " + str.tostring(probabilityHorizon) + " bars"
string sampleText = str.tostring(globalSampleCount) + " TOTAL"
string trainingText = "CELL " + str.tostring(cellSampleCount) + " | SCORE " + str.tostring(scoreSampleCount) + " | " + modelReadiness
string brierText = "M " + f_decimal(averageModelBrier) + " | B " + f_decimal(averageBaselineBrier) + " | SK " + f_signed_percent(brierSkill * 100.0)
 
string scoreText = (modelScore > 0 ? "+" : "") + f_decimal(modelScore)
string markovText = f_percent(markovPersistence)
string markovDetail = str.tostring(currentStateTransitionCount) + " prior-state transitions"
string cusumDetail = "UP " + f_decimal(cusumPositive) + " | DN " + f_decimal(cusumNegative)
string gridVolumeDetail = f_price(nearestGridToClose) + " | HLC3 proxy"
string gridTouchDetail = "UP CLOSE " + f_signed_percent(gridUpClosePercent) + " | " + gridResponseStatus
 
string sectorBreadthText = sectorValidCount > 0 ? str.tostring(sectorBullishCount) + "/" + str.tostring(sectorValidCount) + " UP" : "NO SECTOR DATA"
string marketBreadthDetail = "IDX " + (indexValidCount > 0 ? str.tostring(indexBullishCount) + "/" + str.tostring(indexValidCount) + " UP" : "n/a") + " | X " + f_decimal(crossMarketFeature)
 
string timeframeLabel = timeframe.isminutes ? timeframe.period + "m" : timeframe.period
string marketSession = inRegular ? "REGULAR HOURS" : inPremarket ? "PREMARKET" : inAfterHours ? "AFTER HOURS" : "CLOSED"
 
//=============================================================================
// 26. DASHBOARD COLORS
//=============================================================================
 
color panelBackground = color.rgb(19, 24, 33)
color headerBackground = color.rgb(35, 43, 56)
color neutralBackground = color.new(color.gray, 83)
color bullishBackground = color.new(color.green, 78)
color bearishBackground = color.new(color.red, 78)
color warningBackground = color.new(color.orange, 76)
color whiteText = color.white
 
color probabilityBackground = not modelReady ? warningBackground : probabilityUp > probabilityDown + 0.10 ? bullishBackground : probabilityDown > probabilityUp + 0.10 ? bearishBackground : neutralBackground
color regimeBackground = regimeState == 1 ? bullishBackground : regimeState == -1 ? bearishBackground : neutralBackground
color vwapBackground = na(rthVwap) ? neutralBackground : close > rthVwap ? bullishBackground : close < rthVwap ? bearishBackground : neutralBackground
color cvdBackground = not rthCvdAvailable ? neutralBackground : rthCvd > 0 ? bullishBackground : rthCvd < 0 ? bearishBackground : neutralBackground
color deltaBackground = na(barDeltaPercent) ? neutralBackground : barDeltaPercent >= strongDeltaPercent ? bullishBackground : barDeltaPercent <= -strongDeltaPercent ? bearishBackground : neutralBackground
color cusumBackground = bullishCusumSignal ? bullishBackground : bearishCusumSignal ? bearishBackground : neutralBackground
color openingRangeBackground = na(openingRangeHigh) ? neutralBackground : close > openingRangeHigh ? bullishBackground : close < openingRangeLow ? bearishBackground : neutralBackground
color premarketBackground = na(premarketHigh) ? neutralBackground : close > premarketHigh ? bullishBackground : close < premarketLow ? bearishBackground : neutralBackground
color priorDayBackground = na(priorDayHigh) or na(priorDayLow) ? neutralBackground : close > priorDayHigh ? bullishBackground : close < priorDayLow ? bearishBackground : neutralBackground
color gridBackground = distanceToNearestGrid <= gridTouchTolerance ? warningBackground : neutralBackground
color gridProfileBackground = na(gridUpClosePercent) ? neutralBackground : gridUpClosePercent >= 60.0 ? bullishBackground : gridUpClosePercent <= 40.0 ? bearishBackground : neutralBackground
color breadthBackground = crossMarketFeature > 0.20 ? bullishBackground : crossMarketFeature < -0.20 ? bearishBackground : neutralBackground
 
//=============================================================================
// 27. $0.50 GRID LINES
//=============================================================================
 
var array<line> gridLines = array.new<line>()
 
if barstate.isfirst
    for index = 0 to 8
        line newGridLine = line.new(bar_index, close, bar_index + 1, close, xloc=xloc.bar_index, extend=extend.right, color=color.new(color.gray, 82), style=line.style_dotted, width=1)
        array.push(gridLines, newGridLine)
 
if barstate.islast and showGridLines
    for index = 0 to 8
        float gridLevel = gridLower + (index - 4) * gridStep
        bool wholeDollarLevel = math.abs(gridLevel - math.round(gridLevel)) < 0.001
        line activeGridLine = array.get(gridLines, index)
        line.set_xy1(activeGridLine, bar_index, gridLevel)
        line.set_xy2(activeGridLine, bar_index + 1, gridLevel)
        line.set_color(activeGridLine, wholeDollarLevel ? color.new(color.orange, 48) : color.new(color.gray, 76))
        line.set_style(activeGridLine, wholeDollarLevel ? line.style_dashed : line.style_dotted)
        line.set_width(activeGridLine, wholeDollarLevel ? 2 : 1)
 
if barstate.islast and not showGridLines
    for index = 0 to 8
        line activeGridLine = array.get(gridLines, index)
        line.set_color(activeGridLine, color.new(color.gray, 100))
 
//=============================================================================
// 28. CHART PLOTS AND DATA-WINDOW OUTPUTS
//=============================================================================
 
plot(rthVwap, "RTH VWAP", color=color.yellow, linewidth=2)
plot(openingRangeHigh, "15m Opening Range High", color=color.aqua, linewidth=1, style=plot.style_linebr)
plot(openingRangeLow, "15m Opening Range Low", color=color.fuchsia, linewidth=1, style=plot.style_linebr)
plot(premarketHigh, "Premarket High", color=color.new(color.blue, 5), linewidth=1, style=plot.style_linebr)
plot(premarketLow, "Premarket Low", color=color.new(color.blue, 5), linewidth=1, style=plot.style_linebr)
plot(priorDayHigh, "Prior Day High", color=color.new(color.gray, 15), linewidth=1, style=plot.style_linebr)
plot(priorDayLow, "Prior Day Low", color=color.new(color.gray, 15), linewidth=1, style=plot.style_linebr)
 
plot(rthCvd, "RTH CVD", display=display.data_window)
plot(barDelta, "Current bar delta", display=display.data_window)
plot(barDeltaPercent, "Current bar delta percent", display=display.data_window)
plot(modelScore, "Auction feature score - not probability", display=display.data_window)
plot(probabilityUp * 100.0, "Posterior probability upper grid first (%)", display=display.data_window)
plot(probabilityDown * 100.0, "Posterior probability lower grid first (%)", display=display.data_window)
plot(probabilityNone * 100.0, "Posterior probability neither grid (%)", display=display.data_window)
plot(relativeVolume, "RTH relative volume", display=display.data_window)
plot(returnZScore, "RTH return Z-score", display=display.data_window)
plot(markovPersistence * 100.0, "Smoothed Markov regime persistence (%)", display=display.data_window)
plot(averageModelBrier, "Non-overlapping model Brier score", display=display.data_window)
plot(averageBaselineBrier, "Non-overlapping baseline Brier score", display=display.data_window)
plot(sectorBreadthScore, "Eleven-sector breadth score", display=display.data_window)
plot(indexBreadthScore, "Index and futures confirmation score", display=display.data_window)
plot(crossMarketFeature, "Combined cross-market feature", display=display.data_window)
plot(trendEfficiency, "RTH trend efficiency ratio", display=display.data_window)
 
//=============================================================================
// 29. RESPONSE AND DIVERGENCE MARKERS
//=============================================================================
 
plotshape(showSignalMarkers and buyResponseCandidate, title="Potential buy response at grid", style=shape.triangleup, location=location.belowbar, color=color.lime, text="BUY", textcolor=color.white, size=size.tiny)
plotshape(showSignalMarkers and sellResponseCandidate, title="Potential sell response at grid", style=shape.triangledown, location=location.abovebar, color=color.red, text="SELL", textcolor=color.white, size=size.tiny)
plotshape(showSignalMarkers and bullishDeltaDivergence, title="Bullish CVD divergence candidate", style=shape.circle, location=location.belowbar, color=color.aqua, text="CVD+", textcolor=color.black, size=size.tiny)
plotshape(showSignalMarkers and bearishDeltaDivergence, title="Bearish CVD divergence candidate", style=shape.circle, location=location.abovebar, color=color.orange, text="CVD-", textcolor=color.black, size=size.tiny)
plotshape(showSignalMarkers and bullishCusumSignal, title="Bullish statistical change", style=shape.diamond, location=location.belowbar, color=color.lime, text="SHIFT", textcolor=color.black, size=size.tiny)
plotshape(showSignalMarkers and bearishCusumSignal, title="Bearish statistical change", style=shape.diamond, location=location.abovebar, color=color.red, text="SHIFT", textcolor=color.white, size=size.tiny)
 
//=============================================================================
// 30. QUANTITATIVE DASHBOARD
//=============================================================================
 
var table dashboard = table.new(position.top_right, 3, 19, bgcolor=panelBackground, frame_color=color.rgb(85, 93, 106), frame_width=1, border_color=color.rgb(65, 73, 86), border_width=1)
 
if barstate.isfirst
    table.merge_cells(dashboard, 0, 0, 2, 0)
 
if barstate.islast
    table.cell(dashboard, 0, 0, "SPY AUCTION QUANT v4  |  " + syminfo.ticker + "  |  " + f_price(close), text_color=whiteText, bgcolor=headerBackground, text_size=size.small, text_halign=text.align_left)
 
    table.cell(dashboard, 0, 1, "MODEL", text_color=whiteText, bgcolor=headerBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 1, "STATE", text_color=whiteText, bgcolor=headerBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 1, "DETAIL", text_color=whiteText, bgcolor=headerBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 2, "NEXT $0.50 LEVELS", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 2, f_price(nextUpPrice) + " / " + f_price(nextDownPrice), text_color=whiteText, bgcolor=gridBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 2, "UP / DOWN", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 3, "HIERARCHICAL PROBABILITY", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 3, probabilityText, text_color=whiteText, bgcolor=probabilityBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 3, probabilityDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 4, "TRAINING SUPPORT", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 4, sampleText, text_color=whiteText, bgcolor=modelReady ? bullishBackground : warningBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 4, trainingText, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 5, "BRIER / BASELINE / SKILL", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 5, brierText, text_color=whiteText, bgcolor=not na(brierSkill) and brierSkill > 0 ? bullishBackground : neutralBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 5, "LOWER BRIER IS BETTER", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 6, "TREND / VOLATILITY REGIME", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 6, regimeLabel, text_color=whiteText, bgcolor=regimeBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 6, scoreText + " | " + volatilityLabel, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 7, "MARKOV PERSISTENCE", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 7, markovText, text_color=whiteText, bgcolor=neutralBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 7, markovDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 8, "SECTOR / INDEX BREADTH", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 8, sectorBreadthText, text_color=whiteText, bgcolor=breadthBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 8, marketBreadthDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 9, "CUSUM CHANGE DETECTION", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 9, cusumStatus, text_color=whiteText, bgcolor=cusumBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 9, cusumDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 10, "RTH VWAP", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 10, vwapStatus, text_color=whiteText, bgcolor=vwapBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 10, vwapDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 11, "RTH CVD", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 11, cvdStatus, text_color=whiteText, bgcolor=cvdBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 11, cvdDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 12, "LAST BAR DELTA", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 12, deltaStatus, text_color=whiteText, bgcolor=deltaBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 12, deltaDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 13, "GRID VOLUME PROXY", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 13, f_volume(nearestGridVolume), text_color=whiteText, bgcolor=neutralBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 13, gridVolumeDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 14, "GRID INTERACTION EVENTS", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 14, str.tostring(nearestGridInteractions) + " EVENTS", text_color=whiteText, bgcolor=gridProfileBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 14, gridTouchDetail, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 15, "15M OPENING RANGE", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 15, openingRangeStatus, text_color=whiteText, bgcolor=openingRangeBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 15, f_range_pair(openingRangeHigh, openingRangeLow), text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 16, "PREMARKET RANGE", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 16, premarketStatus, text_color=whiteText, bgcolor=premarketBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 16, f_range_pair(premarketHigh, premarketLow), text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 17, "PRIOR DAY RANGE", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 17, priorDayStatus, text_color=whiteText, bgcolor=priorDayBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 17, f_range_pair(priorDayHigh, priorDayLow), text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
    table.cell(dashboard, 0, 18, "SESSION / CHART / CVD LTF", text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
    table.cell(dashboard, 1, 18, marketSession, text_color=whiteText, bgcolor=neutralBackground, text_size=size.tiny)
    table.cell(dashboard, 2, 18, timeframeLabel + " / " + lowerTimeframe, text_color=whiteText, bgcolor=panelBackground, text_size=size.tiny)
 
//=============================================================================
// 31. ALERTS
//=============================================================================
 
alertcondition(buyResponseCandidate, "Potential buy response at 50-cent grid", "Potential buy response: negative delta, strong close and low near grid.")
alertcondition(sellResponseCandidate, "Potential sell response at 50-cent grid", "Potential sell response: positive delta, weak close and high near grid.")
alertcondition(bullishDeltaDivergence, "Bullish CVD divergence candidate", "Price made a lookback low while RTH CVD held above its lookback low.")
alertcondition(bearishDeltaDivergence, "Bearish CVD divergence candidate", "Price made a lookback high while RTH CVD remained below its lookback high.")
alertcondition(bullishCusumSignal, "Bullish CUSUM change detection", "Positive statistical change threshold crossed.")
alertcondition(bearishCusumSignal, "Bearish CUSUM change detection", "Negative statistical change threshold crossed.")
alertcondition(inRegular and barstate.isconfirmed and modelReady and probabilityUp >= probabilityAlertThreshold, "High conditional probability: upper grid", "Historical hierarchical estimate of reaching the upper adjacent $0.50 grid first exceeded the configured threshold.")
alertcondition(inRegular and barstate.isconfirmed and modelReady and probabilityDown >= probabilityAlertThreshold, "High conditional probability: lower grid", "Historical hierarchical estimate of reaching the lower adjacent $0.50 grid first exceeded the configured threshold.")

← 返回列表