Range Panel + Rainbow Heatmap AFMA + VIX & Non-Flow [ATK/DEF]

ATTDEFS · study · 343 行 · 点赞 11 · TradingView 原页

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

Pine Script

//@version=6
indicator("Range Panel + Rainbow Heatmap AFMA + VIX & Non-Flow [ATK/DEF]", overlay = true, max_lines_count = 30, max_labels_count = 20)
 
// ==========================================
// 1. Range Panel Inputs
// ==========================================
int   rangeLen       = input.int(20, "Range Lookback Bars", minval = 5, group = "Range Panel")
int   atrLen         = input.int(14, "ATR Length", minval = 3, group = "Range Panel")
float rangeAtrMult   = input.float(3.5, "Range Volatility Threshold (ATR Mult)", minval = 0.5, step = 0.1, group = "Range Panel")
int   graceBars      = input.int(2, "Grace Bars Before Reset", minval = 0, maxval = 10, tooltip = "Allows brief excursions before resetting range duration counters", group = "Range Panel")
int   pressLen       = input.int(14, "Buy/Sell Pressure Length", minval = 3, group = "Range Panel")
bool  useVolInPress  = input.bool(true, "Weight Pressure by Volume", group = "Range Panel")
float srBufferAtr    = input.float(0.25, "Rolling S/R ATR Buffer", minval = 0.0, step = 0.05, group = "Range Panel")
bool  showSrLines    = input.bool(true, "Show Rolling Support & Resistance", group = "Range Panel")
bool  showSrLabels   = input.bool(true, "Show S/R Price Labels", group = "Range Panel")
 
// ==========================================
// 2. VIX Market Behavior & Filter Inputs
// ==========================================
bool   showVix       = input.bool(true, "Show VIX Market Behavior", group = "VIX Behavior")
string vixSymbol     = input.string("TVC:VIX", "VIX Symbol", group = "VIX Behavior")
float  vixCalmThresh = input.float(15.0, "VIX Calm Threshold", minval = 5.0, maxval = 100.0, step = 0.5, group = "VIX Behavior")
float  vixHighThresh = input.float(25.0, "VIX High Volatility Threshold", minval = 10.0, maxval = 150.0, step = 0.5, group = "VIX Behavior")
bool   filterByVix   = input.bool(false, "Filter Range by VIX", tooltip = "Treats high-VIX regimes as elevated volatility rather than quiet range", group = "VIX Behavior")
 
// ==========================================
// 3. Non-Flow Activity Inputs
// ==========================================
bool  showNonFlow     = input.bool(true, "Show Non-Flow Activity", group = "Non-Flow Activity")
int   flowVolLen      = input.int(20, "Activity Volume MA Length", minval = 5, group = "Non-Flow Activity")
float surgeVolMult    = input.float(1.35, "Surge Volume Multiplier", minval = 1.0, maxval = 5.0, step = 0.05, group = "Non-Flow Activity")
float quietVolMult    = input.float(0.75, "Quiet Volume Multiplier", minval = 0.1, maxval = 1.0, step = 0.05, group = "Non-Flow Activity")
float clashBodyMax    = input.float(0.45, "Max Body Ratio for Hedge / Clash", minval = 0.1, maxval = 0.9, step = 0.05, tooltip = "Smaller candle bodies relative to range with elevated volume indicate two-way hedging or absorption/clash", group = "Non-Flow Activity")
 
// ==========================================
// 4. Adaptive Forecast MA & Range Length Inputs
// ==========================================
bool  showAfma       = input.bool(true, "Show Adaptive Forecast MA", group = "Adaptive Forecast MA")
int   erLen          = input.int(14, "Efficiency Ratio (ER) Length", minval = 3, group = "Adaptive Forecast MA")
int   fastLen        = input.int(3, "Fast Smoothing Length", minval = 2, group = "Adaptive Forecast MA")
int   slowLen        = input.int(30, "Slow Smoothing Length", minval = 5, group = "Adaptive Forecast MA")
float forecastGain   = input.float(0.65, "Forecast Projection Gain", minval = 0.0, maxval = 1.5, step = 0.05, group = "Adaptive Forecast MA")
int   projBars       = input.int(5, "Projection Bars Ahead", minval = 1, maxval = 15, group = "Adaptive Forecast MA")
int   heatLen        = input.int(20, "Heatmap Normalization Length", minval = 5, group = "Adaptive Forecast MA")
int   maWidth        = input.int(3, "AFMA Line Width", minval = 1, maxval = 5, group = "Adaptive Forecast MA")
float flatSlopeAtr   = input.float(0.35, "AFMA Flat Slope Threshold (ATR)", minval = 0.02, maxval = 1.5, step = 0.02, group = "AFMA Range Duration")
float flatErMax      = input.float(0.55, "AFMA Max ER for Range", minval = 0.1, maxval = 0.95, step = 0.02, group = "AFMA Range Duration")
 
// ==========================================
// 5. Styling Inputs
// ==========================================
color c_panelBg      = input.color(color.new(#131722, 8), "Panel Background", group = "Style")
color c_headerBg     = input.color(color.new(#1E2433, 0), "Header Background", group = "Style")
color c_border       = input.color(color.new(#363C4E, 0), "Panel Border", group = "Style")
color c_bull         = input.color(#089981, "Bullish / Buy / Support", group = "Style")
color c_bear         = input.color(#F23645, "Bearish / Sell / Resistance", group = "Style")
color c_neutral      = input.color(#FF9800, "Range / Neutral", group = "Style")
color c_hedge        = input.color(#E040FB, "Hedge / Clash Highlight", group = "Style")
 
// ==========================================
// 6. VIX Behavior & Filter
// ==========================================
float vixRaw = showVix and str.length(str.trim(vixSymbol)) > 0 ? request.security(str.trim(vixSymbol), timeframe.period, close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true) : na
 
bool   hasVix       = not na(vixRaw)
bool   isVixHigh    = hasVix and (vixRaw >= vixHighThresh)
bool   isVixCalm    = hasVix and (vixRaw <= vixCalmThresh)
string vixBehavior  = not hasVix ? "No Data" : isVixHigh ? "High Vol / Fear" : isVixCalm ? "Calm / Low Vol" : "Normal"
color  vixColor     = not hasVix ? color.gray : isVixHigh ? c_bear : isVixCalm ? c_bull : c_neutral
bool   vixAllowsRng = not filterByVix or not hasVix or not isVixHigh
 
// ==========================================
// 7. Adaptive Forecast MA & Rainbow Heatmap
// ==========================================
float atr        = ta.atr(atrLen)
float netChange  = math.abs(close - close[erLen])
float totalNoise = math.sum(math.abs(close - close[1]), erLen)
float er         = totalNoise > 0 ? (netChange / totalNoise) : 0.0
 
float fastAlpha   = 2.0 / (fastLen + 1.0)
float slowAlpha   = 2.0 / (slowLen + 1.0)
float smoothAlpha = math.pow(er * (fastAlpha - slowAlpha) + slowAlpha, 2)
 
var float adaptBase = na
adaptBase := na(adaptBase[1]) ? close : adaptBase[1] + smoothAlpha * (close - adaptBase[1])
 
float velocity    = adaptBase - nz(adaptBase[1], adaptBase)
var float smoothVel = 0.0
smoothVel := smoothVel + 0.35 * (velocity - smoothVel)
 
float afma        = adaptBase + smoothVel * forecastGain
 
float distNorm    = atr > 0 ? (close - afma) / atr : 0.0
float slopeNorm   = atr > 0 ? (smoothVel / atr) * 3.0 : 0.0
float rawHeat     = distNorm * 0.65 + slopeNorm * 0.35
 
float heatHigh    = ta.highest(rawHeat, heatLen)
float heatLow     = ta.lowest(rawHeat, heatLen)
float heatSpan    = heatHigh - heatLow
float heatScore   = heatSpan > 0 ? math.max(0.0, math.min(100.0, ((rawHeat - heatLow) / heatSpan) * 100.0)) : 50.0
 
f_rainbowHeatColor(float h) =>
    color col = color.new(#00E5FF, 0)
    if h < 25.0
        col := color.from_gradient(h, 0.0, 25.0, #2962FF, #00E5FF)
    else if h < 50.0
        col := color.from_gradient(h, 25.0, 50.0, #00E5FF, #00E676)
    else if h < 75.0
        col := color.from_gradient(h, 50.0, 75.0, #00E676, #FFEA00)
    else
        col := color.from_gradient(h, 75.0, 100.0, #FF9100, #FF1744)
    col
 
color afmaColor = f_rainbowHeatColor(heatScore)
plot(showAfma ? afma : na, title = "Adaptive Forecast MA", color = afmaColor, linewidth = maWidth, style = plot.style_line)
 
var line forecastLine = line.new(na, na, na, na, style = line.style_dotted, width = 2)
if barstate.islast
    if showAfma
        float futureVal = afma + smoothVel * projBars
        forecastLine.set_xy1(bar_index, afma)
        forecastLine.set_xy2(bar_index + projBars, futureVal)
        forecastLine.set_color(afmaColor)
    else
        forecastLine.set_xy1(na, na)
        forecastLine.set_xy2(na, na)
 
// ==========================================
// 8. Range Duration & AFMA Range Length
// ==========================================
float winHigh = ta.highest(high, rangeLen)
float winLow  = ta.lowest(low, rangeLen)
float winSpan = winHigh - winLow
 
bool isRangeBounded = atr > 0 and (winSpan <= atr * rangeAtrMult) and vixAllowsRng
 
var int sidewaysBars      = 0
var int sidewaysMisses    = 0
var int lastSidewaysBars  = 0
 
if isRangeBounded
    sidewaysBars   += 1
    sidewaysMisses := 0
    if sidewaysBars >= 3
        lastSidewaysBars := sidewaysBars
else
    sidewaysMisses += 1
    if sidewaysMisses > graceBars
        sidewaysBars   := 0
        sidewaysMisses := 0
 
float afmaStep       = math.abs(afma - nz(afma[1], afma))
bool  isAfmaRangeBar = atr > 0 and (afmaStep <= atr * flatSlopeAtr) and (er <= flatErMax) and vixAllowsRng
 
var int afmaFlatBars     = 0
var int afmaFlatMisses   = 0
var int lastAfmaFlatBars = 0
 
if isAfmaRangeBar
    afmaFlatBars   += 1
    afmaFlatMisses := 0
    if afmaFlatBars >= 3
        lastAfmaFlatBars := afmaFlatBars
else
    afmaFlatMisses += 1
    if afmaFlatMisses > graceBars
        afmaFlatBars   := 0
        afmaFlatMisses := 0
 
int   secPerBar     = math.max(1, timeframe.in_seconds())
float secondsInDay  = 86400.0
int   dispRngBars   = sidewaysBars > 0 ? sidewaysBars : lastSidewaysBars
int   dispAfmaBars  = afmaFlatBars > 0 ? afmaFlatBars : lastAfmaFlatBars
float sidewaysDays  = (dispRngBars * secPerBar) / secondsInDay
float afmaFlatDays  = (dispAfmaBars * secPerBar) / secondsInDay
 
float relSlope    = atr > 0 ? smoothVel / atr : 0.0
string regimeText = isVixHigh and filterByVix ? "High Vol Alert" : "Trending / Exp"
color  regimeCol  = isVixHigh and filterByVix ? c_bear : color.new(#787B86, 0)
 
if isRangeBounded or sidewaysBars > 0
    if relSlope > 0.06
        regimeText := "Upward Range"
        regimeCol  := c_bull
    else if relSlope < -0.06
        regimeText := "Downward Range"
        regimeCol  := c_bear
    else
        regimeText := "Sideways Range"
        regimeCol  := c_neutral
 
// ==========================================
// 9. Buy / Sell Pressure Index (0 - 100)
// ==========================================
float hlRange     = high - low
float barPosScore = hlRange > 0 ? (((close - low) / hlRange) * 2.0 - 1.0) : 0.0
 
bool  hasValidVol = useVolInPress and nz(volume) > 0
float volWeight   = hasValidVol ? volume : 1.0
 
float weightedSum = math.sum(barPosScore * volWeight, pressLen)
float weightTotal = math.sum(volWeight, pressLen)
float rawScore    = weightTotal > 0 ? (weightedSum / weightTotal) : 0.0
 
float pressureIdx = math.max(0.0, math.min(100.0, (rawScore + 1.0) * 50.0))
 
string pressState = pressureIdx >= 58.0 ? "Buy Pressure" : pressureIdx <= 42.0 ? "Sell Pressure" : "Balanced"
color  pressColor = pressureIdx >= 58.0 ? c_bull : pressureIdx <= 42.0 ? c_bear : c_neutral
 
// ==========================================
// 10. Non-Flow Activity (Buy / Sell / Hedge & Clash)
// ==========================================
float actMeasure   = nz(volume) > 0 ? volume : (atr > 0 ? hlRange / atr : 1.0)
float actAvg       = ta.sma(actMeasure, flowVolLen)
float actRatio     = actAvg > 0 ? (actMeasure / actAvg) : 1.0
 
float bodySize     = math.abs(close - open)
float bodyRatio    = hlRange > 0 ? (bodySize / hlRange) : 0.0
 
float nonFlowScore = math.max(0.0, math.min(100.0, (actRatio / math.max(0.1, surgeVolMult)) * 55.0 + (1.0 - bodyRatio) * 45.0))
 
bool   isSurge      = actRatio >= surgeVolMult
bool   isQuiet      = actRatio <= quietVolMult
bool   isHedgeClash = isSurge and (bodyRatio <= clashBodyMax or (pressureIdx > 44.0 and pressureIdx < 56.0 and math.abs(barPosScore) < 0.35))
bool   isActiveBuy  = not isHedgeClash and isSurge and (pressureIdx >= 54.0 or close > open)
bool   isActiveSell = not isHedgeClash and isSurge and (pressureIdx <= 46.0 or close < open)
 
string nonFlowLabel = "Idle / Watch"
color  nonFlowColor = color.silver
 
if isHedgeClash
    nonFlowLabel := "Hedge / Clash"
    nonFlowColor := c_hedge
else if isActiveBuy
    nonFlowLabel := "Active Buy"
    nonFlowColor := c_bull
else if isActiveSell
    nonFlowLabel := "Active Sell"
    nonFlowColor := c_bear
else if isQuiet
    nonFlowLabel := "Low Activity"
    nonFlowColor := color.gray
else if bodyRatio <= clashBodyMax
    nonFlowLabel := "Mild Hedge"
    nonFlowColor := c_neutral
else if pressureIdx >= 54.0
    nonFlowLabel := "Buy Tilt"
    nonFlowColor := c_bull
else if pressureIdx <= 46.0
    nonFlowLabel := "Sell Tilt"
    nonFlowColor := c_bear
 
// ==========================================
// 11. Rolling Support & Resistance
// ==========================================
float dynResistance = winHigh + atr * srBufferAtr
float dynSupport    = winLow  - atr * srBufferAtr
 
var line resLine  = line.new(na, na, na, na, color = c_bear, style = line.style_dashed, width = 2)
var line supLine  = line.new(na, na, na, na, color = c_bull, style = line.style_dashed, width = 2)
var label resLbl  = label.new(na, na, "", style = label.style_label_left, color = c_bear, textcolor = color.white, size = size.small)
var label supLbl  = label.new(na, na, "", style = label.style_label_left, color = c_bull, textcolor = color.white, size = size.small)
 
if barstate.islast
    int xStart = math.max(0, bar_index - rangeLen + 1)
    int xEnd   = bar_index + 5
 
    if showSrLines
        resLine.set_xy1(xStart, dynResistance)
        resLine.set_xy2(xEnd, dynResistance)
        supLine.set_xy1(xStart, dynSupport)
        supLine.set_xy2(xEnd, dynSupport)
    else
        resLine.set_xy1(na, na)
        resLine.set_xy2(na, na)
        supLine.set_xy1(na, na)
        supLine.set_xy2(na, na)
 
    if showSrLines and showSrLabels
        resLbl.set_xy(xEnd, dynResistance)
        resLbl.set_text("Res: " + str.tostring(dynResistance, format.mintick))
        supLbl.set_xy(xEnd, dynSupport)
        supLbl.set_text("Sup: " + str.tostring(dynSupport, format.mintick))
    else
        resLbl.set_xy(na, na)
        supLbl.set_xy(na, na)
 
// ==========================================
// 12. Range Panel (Top Right)
// ==========================================
var table rangePanel = table.new(position.top_right, 2, 10, bgcolor = c_panelBg, border_width = 1, border_color = c_border, frame_width = 1, frame_color = c_border)
 
if barstate.islast
    string rngPrefix  = sidewaysBars > 0 ? "" : "Last "
    string afmaPrefix = afmaFlatBars > 0 ? "" : "Last "
 
    table.cell(rangePanel, 0, 0, "Range Panel", text_color = color.white, bgcolor = c_headerBg, text_size = size.normal, text_halign = text.align_left)
    table.cell(rangePanel, 1, 0, regimeText, text_color = regimeCol, bgcolor = c_headerBg, text_size = size.small, text_halign = text.align_right)
 
    table.cell(rangePanel, 0, 1, "Range Duration", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 1, rngPrefix + str.tostring(sidewaysDays, "#.##") + "d (" + str.tostring(dispRngBars) + "b)", text_color = regimeCol, text_size = size.small, text_halign = text.align_right)
 
    table.cell(rangePanel, 0, 2, "AFMA Range Len", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 2, afmaPrefix + str.tostring(afmaFlatDays, "#.##") + "d (" + str.tostring(dispAfmaBars) + "b)", text_color = afmaColor, text_size = size.small, text_halign = text.align_right)
 
    string vixCellText = hasVix ? str.tostring(vixRaw, "#.##") + " (" + vixBehavior + ")" : "No Data"
    table.cell(rangePanel, 0, 3, "VIX Behavior", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 3, vixCellText, text_color = vixColor, text_size = size.small, text_halign = text.align_right)
 
    string nfText = showNonFlow ? nonFlowLabel + " (" + str.tostring(nonFlowScore, "#.0") + ")" : "Hidden"
    table.cell(rangePanel, 0, 4, "Non-Flow Activity", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 4, nfText, text_color = showNonFlow ? nonFlowColor : color.gray, text_size = size.small, text_halign = text.align_right)
 
    table.cell(rangePanel, 0, 5, "Buy/Sell Pressure", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 5, str.tostring(pressureIdx, "#.1") + " / 100 (" + pressState + ")", text_color = pressColor, text_size = size.small, text_halign = text.align_right)
 
    table.cell(rangePanel, 0, 6, "Rolling Resistance", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 6, str.tostring(dynResistance, format.mintick), text_color = c_bear, text_size = size.small, text_halign = text.align_right)
 
    table.cell(rangePanel, 0, 7, "Rolling Support", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 7, str.tostring(dynSupport, format.mintick), text_color = c_bull, text_size = size.small, text_halign = text.align_right)
 
    string forecastDir = smoothVel > 0 ? "Bullish ↑" : smoothVel < 0 ? "Bearish ↓" : "Flat →"
    table.cell(rangePanel, 0, 8, "Forecast MA", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 8, "Heat " + str.tostring(heatScore, "#.0") + "% | " + forecastDir, text_color = afmaColor, text_size = size.small, text_halign = text.align_right)
 
    float spanPct = close > 0 ? (winSpan / close) * 100.0 : 0.0
    float posPct  = (dynResistance - dynSupport) > 0 ? ((close - dynSupport) / (dynResistance - dynSupport)) * 100.0 : 50.0
    table.cell(rangePanel, 0, 9, "Width / Position", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(rangePanel, 1, 9, str.tostring(spanPct, "#.##") + "% | " + str.tostring(posPct, "#.0") + "%", text_color = color.white, text_size = size.small, text_halign = text.align_right)
 
// ==========================================
// 13. Alert Conditions (Non-Flow Activity)
// ==========================================
bool condHedgeClash = showNonFlow and isHedgeClash
bool condActiveBuy  = showNonFlow and isActiveBuy
bool condActiveSell = showNonFlow and isActiveSell
bool condAnyFlowSig = condHedgeClash or condActiveBuy or condActiveSell
 
alertcondition(condHedgeClash, title = "Non-Flow: Hedge / Clash Surge", message = "{{ticker}} [{{interval}}] Hedge / Clash surge detected. Pressure: {{plot_0}}")
alertcondition(condActiveBuy,  title = "Non-Flow: Active Buy Surge", message = "{{ticker}} [{{interval}}] Active Buy surge detected. Pressure: {{plot_0}}")
alertcondition(condActiveSell, title = "Non-Flow: Active Sell Surge", message = "{{ticker}} [{{interval}}] Active Sell surge detected. Pressure: {{plot_0}}")
alertcondition(condAnyFlowSig, title = "Non-Flow: Any Activity Surge", message = "{{ticker}} [{{interval}}] Non-Flow activity surge signal triggered.")

← 返回列表