J_MO Power Structure Indicator

moolahman93 · study · 784 行 · 点赞 20 · TradingView 原页

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

Pine Script

//@version=6
indicator("Power Structure Engine v5.1 | Structure & Flow Academy", shorttitle="Power Structure v5.1", overlay=true, max_lines_count=300, max_labels_count=250, max_boxes_count=250, dynamic_requests=true)
 
// ============================================================================
// THE POWER STRUCTURE METHOD — VERSION 5.1 (zone lines redrawn per chart TF)
// ============================================================================
 
// ── 01. CORE SUPPLY / DEMAND ────────────────────────────────────────────────
string G_SD = "01 | Unused Supply & Demand (YOUR original engine)"
int   atrLen     = input.int(14, "ATR Length", minval=1, group=G_SD)
float impMult    = input.float(2.0, "Push size (x ATR, total same-color candles)", minval=0.5, step=0.1, group=G_SD)
int   maxRun     = input.int(5, "Max candles in a push", minval=1, maxval=10, group=G_SD)
int   maxZones   = input.int(8, "Max active zones per side", minval=1, maxval=50, group=G_SD)
bool  needReject = input.bool(false, "Require rejection close for first-touch signal", group=G_SD)
bool  showUsed   = input.bool(false, "Keep used zones (grayed, boxes only)", group=G_SD)
bool  showSig    = input.bool(true, "Show first-touch triangles", group=G_SD)
color demandCol  = input.color(color.new(color.green, 80), "Demand BOX color", group=G_SD)
color supplyCol  = input.color(color.new(color.red, 80), "Supply BOX color", group=G_SD)
string displayMode = input.string("Lines", "1-minute display mode", options=["Lines", "Boxes", "Both", "Off"], group=G_SD)
bool strictHorizontalOnly = input.bool(true, "Hide vertical zone edges (HORIZONTAL LINES ONLY)", group=G_SD, tooltip="Recommended ON. Disables zone rectangles and forces the horizontal level line.")
bool showLevelLabels = input.bool(true, "Label 1-minute levels", group=G_SD)
color lineDemandCol = input.color(color.new(color.blue, 0), "1m demand LINE color", group=G_SD)
color lineSupplyCol = input.color(color.new(color.blue, 0), "1m supply LINE color", group=G_SD)
 
// ── 02. EMA STRUCTURE ───────────────────────────────────────────────────────
string G_EMA = "02 | 5 / 10 / 20 EMA Structure"
int fastLen = input.int(5, "Fast EMA", minval=1, group=G_EMA)
int midLen  = input.int(10, "Middle EMA", minval=1, group=G_EMA)
int slowLen = input.int(20, "Slow EMA", minval=1, group=G_EMA)
bool showEMAs = input.bool(true, "Show chart EMAs", group=G_EMA)
color fastCol = input.color(color.red, "Fast EMA color", group=G_EMA)
color midCol = input.color(color.white, "Middle EMA color", group=G_EMA)
color slowCol = input.color(color.blue, "Slow EMA color", group=G_EMA)
float emaF = ta.ema(close, fastLen)
float emaM = ta.ema(close, midLen)
float emaS = ta.ema(close, slowLen)
plot(showEMAs ? emaF : na, "5 EMA (default)", fastCol, 2)
plot(showEMAs ? emaM : na, "10 EMA (default)", midCol, 2)
plot(showEMAs ? emaS : na, "20 EMA (default)", slowCol, 2)
 
// ── 03. DASHBOARD & ALIGNMENT ───────────────────────────────────────────────
string G_MTF = "03 | Eight-Timeframe Structure"
bool showBoard = input.bool(true, "Show structure dashboard", group=G_MTF)
string boardPlace = input.string("Top Right", "Dashboard location", options=["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group=G_MTF)
int boardFade = input.int(25, "Dashboard background transparency", minval=0, maxval=95, group=G_MTF)
bool showFullMarks = input.bool(false, "Show full-alignment markers", group=G_MTF)
int alignmentMemoryMinutes = input.int(120, "Remember recent full alignment (minutes)", minval=1, maxval=10080, group=G_MTF)
 
// ── 04. NEUTRALIZATION / V-TURNS ────────────────────────────────────────────
string G_TURN = "04 | Buyers / Sellers Neutral and V-Shapes"
bool showTurns = input.bool(true, "Dashboard shows HTF neutral / V-turn", group=G_TURN)
bool showTurnMarks = input.bool(false, "Show HTF turn markers on candles", group=G_TURN)
float flatSlopeATR = input.float(0.025, "5 EMA flat threshold (x ATR per bar)", minval=0.001, maxval=0.50, step=0.005, group=G_TURN)
 
// ── 05. 5M / 15M CONTEXT ────────────────────────────────────────────────────
string G_CTX = "05 | 5-minute and 15-minute Level Confirmation"
bool showContextLines = input.bool(false, "Show nearest ACTIVE 5m / 15m context levels", group=G_CTX)
bool requireContext = input.bool(false, "Require 5m OR 15m level near 1m for confluence alerts", group=G_CTX)
float contextDistanceATR = input.float(0.75, "5m / 15m level near 1m (x 1m ATR)", minval=0.05, step=0.05, group=G_CTX)
 
// ── 06. CONFLUENCE & APPROACH ALERTS ────────────────────────────────────────
string G_ALERT = "06 | Power Move Confluence Alerts"
bool enablePowerAlerts = input.bool(true, "Enable power-move conditions", group=G_ALERT)
float approachATR = input.float(1.0, "Approaching fresh 1m level (x 1m ATR)", minval=0.05, step=0.05, group=G_ALERT)
float confluenceATR = input.float(2.0, "1m level near HTF EMA (x 1m ATR)", minval=0.05, step=0.1, group=G_ALERT)
bool requireApproachMomentum = input.bool(false, "Require 1m/5m momentum moving toward level", group=G_ALERT)
bool dynamicAlerts = input.bool(false, "Send dynamic alert() text (Create Alert > Any alert() function call)", group=G_ALERT)
bool enableEMATouch = input.bool(false, "Alert on 4H / Daily / Weekly EMA touches", group=G_ALERT)
 
// ── 07. HTF EMA APPROACH ────────────────────────────────────────────────────
string G_PROX = "07 | 4H / Daily / Weekly EMA Approach Signals"
bool enableProximity = input.bool(true, "Enable proximity signals + alerts", group=G_PROX)
bool proxWatch4H = input.bool(true, "Watch 4H EMA 5 / 10 / 20", group=G_PROX)
bool proxWatchDaily = input.bool(true, "Watch Daily EMA 5 / 10 / 20", group=G_PROX)
bool proxWatchWeekly = input.bool(true, "Watch Weekly EMA 5 / 10 / 20", group=G_PROX)
string proxUnit = input.string("Percent", "Distance measurement", options=["Percent", "Price points", "1-minute ATR"], group=G_PROX)
float proxPercent = input.float(0.10, "Price within (%) of EMA", minval=0.01, maxval=5.0, step=0.01, group=G_PROX, tooltip="0.10 means 0.10 percent. For NQ at 25,000, this is approximately 25 points.")
float proxPoints = input.float(25.0, "Distance in price points (when selected)", minval=0.0, step=0.25, group=G_PROX)
float proxATR = input.float(2.0, "Distance in 1-minute ATRs (when selected)", minval=0.05, step=0.1, group=G_PROX)
int proxCooldownMinutes = input.int(20, "Minimum minutes between approach alerts per timeframe", minval=0, maxval=10080, group=G_PROX)
bool showProxMarkers = input.bool(true, "Show small 4H / D / W markers on chart", group=G_PROX)
int proxMarkerHours = input.int(8, "Keep HTF approach tags from last N hours", minval=1, maxval=720, group=G_PROX, tooltip="Visual cleanup only: older 4H/D/W EMA approach labels are deleted. Alert detection remains active at every bar.")
int proxMaxTags = input.int(4, "Maximum HTF approach tags visible (total)", minval=1, maxval=50, group=G_PROX, tooltip="Keeps only the newest N HTF EMA approach labels in total.")
bool enableProxDynamic = input.bool(false, "Detailed dynamic alert() message (optional)", group=G_PROX)
 
// ── 08. BOLLINGER BANDS ─────────────────────────────────────────────────────
string G_BB = "08 | Bollinger Bands"
bool showBB = input.bool(true, "Show Bollinger Bands", group=G_BB)
int bbLen = input.int(20, "BB Length", minval=1, group=G_BB)
float bbMult = input.float(2.0, "BB Standard Deviations", minval=0.1, step=0.1, group=G_BB)
bool showBBMiddle = input.bool(true, "Show middle band", group=G_BB)
int bbUpperWidth = input.int(2, "Upper band line thickness (px)", minval=1, maxval=5, group=G_BB)
int bbMiddleWidth = input.int(1, "Middle band line thickness (px)", minval=1, maxval=5, group=G_BB)
int bbLowerWidth = input.int(2, "Lower band line thickness (px)", minval=1, maxval=5, group=G_BB)
bool fillBB = input.bool(false, "Shade area between bands", group=G_BB)
int bbFillTransparency = input.int(94, "Band-fill transparency", minval=0, maxval=100, group=G_BB)
color bbUpperColor = input.color(color.aqua, "Upper band color", group=G_BB)
color bbMiddleColor = input.color(color.new(color.gray, 25), "Middle band color", group=G_BB)
color bbLowerColor = input.color(color.aqua, "Lower band color", group=G_BB)
float bbMid = ta.sma(close, bbLen)
float bbDev = bbMult * ta.stdev(close, bbLen)
float bbUpper = bbMid + bbDev
float bbLower = bbMid - bbDev
bbUPlot = plot(showBB ? bbUpper : na, "BB Upper", color=bbUpperColor, linewidth=bbUpperWidth)
plot(showBB and showBBMiddle ? bbMid : na, "BB Middle", color=bbMiddleColor, linewidth=bbMiddleWidth)
bbLPlot = plot(showBB ? bbLower : na, "BB Lower", color=bbLowerColor, linewidth=bbLowerWidth)
fill(bbUPlot, bbLPlot, color=showBB and fillBB ? color.new(bbUpperColor, bbFillTransparency) : na, title="Bollinger Band Fill")
 
// ── 09. SESSION BACKGROUNDS ─────────────────────────────────────────────────
string G_TIME = "09 | Six Colored Time Areas (original J_MO palette)"
bool showSessions = input.bool(true, "SHOW session background COLORS", group=G_TIME)
string sessionTZ = input.string("GMT-4", "Time zone", options=["GMT-4", "America/New_York", "GMT-5", "Etc/UTC"], group=G_TIME, tooltip="GMT-4 is fixed UTC-4. America/New_York follows daylight saving time.")
bool sess1On = input.bool(true, "Show Session 1", group=G_TIME, inline="t1")
string sess1Time = input.session("0100-0245", "1", group=G_TIME, inline="t1")
color sess1Col = input.color(color.new(#b05fb0, 60), "1 color", group=G_TIME)
bool sess2On = input.bool(true, "Show Session 2", group=G_TIME, inline="t2")
string sess2Time = input.session("0300-0600", "2", group=G_TIME, inline="t2")
color sess2Col = input.color(color.new(#8b2c2c, 60), "2 color", group=G_TIME)
bool sess3On = input.bool(true, "Show Session 3", group=G_TIME, inline="t3")
string sess3Time = input.session("0600-0815", "3", group=G_TIME, inline="t3")
color sess3Col = input.color(color.new(#3cb043, 60), "3 color", group=G_TIME)
bool sess4On = input.bool(true, "Show Session 4", group=G_TIME, inline="t4")
string sess4Time = input.session("0900-1030", "4", group=G_TIME, inline="t4")
color sess4Col = input.color(color.new(#d4c94a, 60), "4 color", group=G_TIME)
bool sess5On = input.bool(true, "Show Session 5", group=G_TIME, inline="t5")
string sess5Time = input.session("1000-1315", "5", group=G_TIME, inline="t5")
color sess5Col = input.color(color.new(#c98a5e, 60), "5 color", group=G_TIME)
bool sess6On = input.bool(true, "Show Session 6", group=G_TIME, inline="t6")
string sess6Time = input.session("1830-2100", "6", group=G_TIME, inline="t6")
color sess6Col = input.color(color.new(#2ec4c4, 60), "6 color", group=G_TIME)
 
f_inChartSession(string hours) =>
    timeframe.isintraday and not na(time(timeframe.period, hours, sessionTZ))
color sessionShade = na
sessionShade := sess1On and f_inChartSession(sess1Time) ? sess1Col : sessionShade
sessionShade := sess2On and f_inChartSession(sess2Time) ? sess2Col : sessionShade
sessionShade := sess3On and f_inChartSession(sess3Time) ? sess3Col : sessionShade
sessionShade := sess4On and f_inChartSession(sess4Time) ? sess4Col : sessionShade
sessionShade := sess5On and f_inChartSession(sess5Time) ? sess5Col : sessionShade
sessionShade := sess6On and f_inChartSession(sess6Time) ? sess6Col : sessionShade
bgcolor(showSessions ? sessionShade : na, title="Six time-area colors")
 
// ── 10. HOD/LOD and PHOD/PLOD ───────────────────────────────────────────────
string G_HILO = "10 | Yesterday HOD/LOD + Previous HOD/LOD"
string rangeHours = input.session("0100-1514", "High/Low measurement window", group=G_HILO)
bool showPriorHilo = input.bool(true, "Show HOD / LOD — last completed range", group=G_HILO)
bool showOlderHilo = input.bool(true, "Show PHOD / PLOD — two ranges back", group=G_HILO)
bool showLiveHilo = input.bool(false, "Also show TODAY's live range", group=G_HILO)
bool showHLLabels = input.bool(true, "Show right-side labels", group=G_HILO)
bool hlShowPrices = input.bool(true, "Include prices on labels", group=G_HILO)
bool hlBadgeLabels = input.bool(true, "High-contrast colored label badges", group=G_HILO)
string hlLabelSizeInput = input.string("Normal", "HOD / LOD label font size", options=["Tiny", "Small", "Normal", "Large"], group=G_HILO)
string hlLabelSize = hlLabelSizeInput == "Large" ? size.large : hlLabelSizeInput == "Normal" ? size.normal : hlLabelSizeInput == "Small" ? size.small : size.tiny
color hiLineColor = input.color(color.rgb(215, 53, 69), "HOD / PHOD color (red)", group=G_HILO)
color loLineColor = input.color(color.rgb(0, 145, 109), "LOD / PLOD color (green)", group=G_HILO)
int hlLineWidth = input.int(3, "HOD / LOD line thickness (px)", minval=1, maxval=5, group=G_HILO)
int olderLineWidth = input.int(2, "PHOD / PLOD line thickness (px)", minval=1, maxval=5, group=G_HILO)
int liveLineWidth = input.int(1, "Live H/L line thickness (px)", minval=1, maxval=5, group=G_HILO)
int olderFade = input.int(20, "PHOD / PLOD line transparency", minval=0, maxval=90, group=G_HILO)
int hlLookbackBars = input.int(180, "Length of visible H/L lines (bars to left)", minval=10, maxval=5000, group=G_HILO)
int hlRightOffset = input.int(8, "Place H/L labels this many bars to right", minval=1, maxval=40, group=G_HILO)
string priorPattern = input.string("Solid", "HOD / LOD line style", options=["Solid", "Dashed", "Dotted"], group=G_HILO)
string olderPattern = input.string("Dashed", "PHOD / PLOD line style", options=["Solid", "Dashed", "Dotted"], group=G_HILO)
priorLineStyle = priorPattern == "Dotted" ? line.style_dotted : priorPattern == "Dashed" ? line.style_dashed : line.style_solid
olderLineStyle = olderPattern == "Dotted" ? line.style_dotted : olderPattern == "Solid" ? line.style_solid : line.style_dashed
 
var int rangeDayKey = na
var float liveRangeHi = na
var float liveRangeLo = na
var float priorRangeHi = na
var float priorRangeLo = na
var float olderRangeHi = na
var float olderRangeLo = na
 
var line pHiLine = na
var line pLoLine = na
var line ppHiLine = na
var line ppLoLine = na
var line todayHiLine = na
var line todayLoLine = na
var label pHiLabel = na
var label pLoLabel = na
var label ppHiLabel = na
var label ppLoLabel = na
var label todayHiLabel = na
var label todayLoLabel = na
 
// ============================================================================
// PART A — ORIGINAL CANDLE-RUN / ATR DISPLACEMENT DETECTION
// ============================================================================
f_origin() =>
    float atr = ta.atr(atrLen)
    bool demandFound = false
    bool supplyFound = false
    float dTop = na
    float dBot = na
    float sTop = na
    float sBot = na
    int dTime = na
    int sTime = na
    int rUp = 0
    for j = 0 to maxRun
        if close[j] > open[j]
            rUp += 1
        else
            break
    if rUp >= 1 and rUp <= maxRun and close[rUp] < open[rUp]
        float totNow = close - open[rUp - 1]
        float totPrev = rUp > 1 ? close[1] - open[rUp - 1] : 0.0
        if totNow >= impMult * atr and totPrev < impMult * atr
            demandFound := true
            dTop := high[rUp]
            dBot := low[rUp]
            dTime := time[rUp]
    int rDn = 0
    for j = 0 to maxRun
        if close[j] < open[j]
            rDn += 1
        else
            break
    if rDn >= 1 and rDn <= maxRun and close[rDn] > open[rDn]
        float totNow = open[rDn - 1] - close
        float totPrev = rDn > 1 ? open[rDn - 1] - close[1] : 0.0
        if totNow >= impMult * atr and totPrev < impMult * atr
            supplyFound := true
            sTop := high[rDn]
            sBot := low[rDn]
            sTime := time[rDn]
    [demandFound, supplyFound, dTop, dBot, dTime, sTop, sBot, sTime]
 
f_oneMinutePayload() =>
    [d, s, dt, db, dTime, st, sb, sTime] = f_origin()
    bool insideRange = not na(time("1", rangeHours, sessionTZ))
    [open, high, low, close, time, d, s, dt, db, dTime, st, sb, sTime, insideRange]
 
// ============================================================================
// PART B — UNUSED ZONE OBJECTS (lines are drawn later, on the last bar)
// ============================================================================
type Zone
    box bx
    line ln
    label tag
    bool isDemand
    bool pushActive
    float top
    float bot
    int origT
 
var array<Zone> zones = array.new<Zone>()
 
f_erase(Zone z) =>
    if not na(z.bx)
        box.delete(z.bx)
    if not na(z.ln)
        line.delete(z.ln)
    if not na(z.tag)
        label.delete(z.tag)
 
f_createZone(bool isDemand, float top, float bot, int origT, int t) =>
    box bx = na
    bool drawBox = not strictHorizontalOnly and (displayMode == "Boxes" or displayMode == "Both")
    if drawBox
        bx := box.new(left=origT, top=top, right=t+60000, bottom=bot, xloc=xloc.bar_time, extend=extend.right, border_color=isDemand ? color.green : color.red, bgcolor=isDemand ? demandCol : supplyCol)
    zones.push(Zone.new(bx, na, na, isDemand, true, top, bot, origT))
 
f_step(float o, float h, float l, float c, int t, bool madeDemand, bool madeSupply, float dt, float db, int dOrig, float st, float sb, int sOrig) =>
    bool longHit = false
    bool shortHit = false
    int n = zones.size()
    if n > 0
        for i = n - 1 to 0
            Zone z = zones.get(i)
            bool usedNow = false
            bool sameColor = z.isDemand ? c > o : c < o
            if z.pushActive and sameColor
                if not na(z.bx)
                    box.set_right(z.bx, t)
            else
                z.pushActive := false
                bool touched = z.isDemand ? l <= z.top : h >= z.bot
                if touched
                    usedNow := true
                    if z.isDemand
                        if not needReject or (c > o and c > z.bot)
                            longHit := true
                    else
                        if not needReject or (c < o and c < z.top)
                            shortHit := true
                    if showUsed and not na(z.bx)
                        box.set_extend(z.bx, extend.none)
                        box.set_right(z.bx, t)
                        box.set_bgcolor(z.bx, color.new(color.gray, 88))
                        box.set_border_color(z.bx, color.gray)
                    else
                        f_erase(z)
                    zones.remove(i)
                else
                    if not na(z.bx)
                        box.set_right(z.bx, t)
    if madeDemand and not na(dOrig)
        f_createZone(true, dt, db, dOrig, t)
    if madeSupply and not na(sOrig)
        f_createZone(false, st, sb, sOrig, t)
    int dCount = 0
    int sCount = 0
    for z in zones
        if z.isDemand
            dCount += 1
        else
            sCount += 1
    if dCount > maxZones or sCount > maxZones
        bool removeDemand = dCount > maxZones
        for i = 0 to zones.size() - 1
            Zone z = zones.get(i)
            if z.isDemand == removeDemand
                f_erase(z)
                zones.remove(i)
                break
    [longHit, shortHit]
 
if timeframe.in_seconds() < 60
    runtime.error("Use a 1-minute chart or higher. The origin engine requires real 1m candles.")
 
[aO, aH, aL, aC, aT, aDF, aSF, aDT, aDB, aDO, aST, aSB, aSO, aInHLRange] = request.security_lower_tf(syminfo.tickerid, "1", f_oneMinutePayload(), calc_bars_count=30000)
 
var int lastProcessedMinute = na
bool longTouch = false
bool shortTouch = false
int countInner = array.size(aT)
if countInner > 0
    for i = 0 to countInner - 1
        int minuteTime = array.get(aT, i)
        bool minuteClosed = barstate.ishistory or minuteTime + 60000 <= timenow
        if minuteClosed and (na(lastProcessedMinute) or minuteTime > lastProcessedMinute)
            int thisDayKey = year(minuteTime, sessionTZ) * 10000 + month(minuteTime, sessionTZ) * 100 + dayofmonth(minuteTime, sessionTZ)
            if na(rangeDayKey) or thisDayKey != rangeDayKey
                if not na(liveRangeHi) and not na(liveRangeLo)
                    olderRangeHi := priorRangeHi
                    olderRangeLo := priorRangeLo
                    priorRangeHi := liveRangeHi
                    priorRangeLo := liveRangeLo
                liveRangeHi := na
                liveRangeLo := na
                rangeDayKey := thisDayKey
            if array.get(aInHLRange, i)
                float hMinute = array.get(aH, i)
                float lMinute = array.get(aL, i)
                liveRangeHi := na(liveRangeHi) ? hMinute : math.max(liveRangeHi, hMinute)
                liveRangeLo := na(liveRangeLo) ? lMinute : math.min(liveRangeLo, lMinute)
            [hitL, hitS] = f_step(array.get(aO,i), array.get(aH,i), array.get(aL,i), array.get(aC,i), minuteTime, array.get(aDF,i), array.get(aSF,i), array.get(aDT,i), array.get(aDB,i), array.get(aDO,i), array.get(aST,i), array.get(aSB,i), array.get(aSO,i))
            longTouch := longTouch or hitL
            shortTouch := shortTouch or hitS
            lastProcessedMinute := minuteTime
 
// ── ZONE LINES: redrawn on the last bar using BAR INDEX (always horizontal) ─
var array<line> zoneLines = array.new<line>()
var array<label> zoneTags = array.new<label>()
if barstate.islast
    for ln0 in zoneLines
        line.delete(ln0)
    for tg0 in zoneTags
        label.delete(tg0)
    zoneLines.clear()
    zoneTags.clear()
    bool drawZ = displayMode != "Off" and (strictHorizontalOnly or displayMode == "Lines" or displayMode == "Both")
    if drawZ
        int barMs = timeframe.in_seconds() * 1000
        for z in zones
            float zp = z.isDemand ? z.top : z.bot
            color zc = z.isDemand ? lineDemandCol : lineSupplyCol
            int back = math.max(1, math.min(4999, int(math.round((time - z.origT) / barMs))))
            int zx1 = math.max(0, bar_index - back)
            if zx1 >= bar_index
                zx1 := math.max(0, bar_index - 1)
            zoneLines.push(line.new(zx1, zp, bar_index, zp, xloc=xloc.bar_index, extend=extend.right, color=zc, width=2))
            if showLevelLabels
                zoneTags.push(label.new(bar_index + 1, zp, z.isDemand ? "1min D" : "1min S", xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=color.new(zc, 35), size=size.tiny))
 
// ── Horizontal reference lines (HOD/LOD etc.) drawn on the last bar ─────────
if barstate.islast
    if not na(pHiLine)
        line.delete(pHiLine)
    if not na(pLoLine)
        line.delete(pLoLine)
    if not na(ppHiLine)
        line.delete(ppHiLine)
    if not na(ppLoLine)
        line.delete(ppLoLine)
    if not na(todayHiLine)
        line.delete(todayHiLine)
    if not na(todayLoLine)
        line.delete(todayLoLine)
    if not na(pHiLabel)
        label.delete(pHiLabel)
    if not na(pLoLabel)
        label.delete(pLoLabel)
    if not na(ppHiLabel)
        label.delete(ppHiLabel)
    if not na(ppLoLabel)
        label.delete(ppLoLabel)
    if not na(todayHiLabel)
        label.delete(todayHiLabel)
    if not na(todayLoLabel)
        label.delete(todayLoLabel)
    int hlStart = math.max(0, bar_index - hlLookbackBars)
    int hlEnd = bar_index + hlRightOffset
    string hiPriorText = "HOD" + (hlShowPrices and not na(priorRangeHi) ? "  " + str.tostring(priorRangeHi, format.mintick) : "")
    string loPriorText = "LOD" + (hlShowPrices and not na(priorRangeLo) ? "  " + str.tostring(priorRangeLo, format.mintick) : "")
    string hiOlderText = "PHOD" + (hlShowPrices and not na(olderRangeHi) ? "  " + str.tostring(olderRangeHi, format.mintick) : "")
    string loOlderText = "PLOD" + (hlShowPrices and not na(olderRangeLo) ? "  " + str.tostring(olderRangeLo, format.mintick) : "")
    string hiLiveText = "TODAY H" + (hlShowPrices and not na(liveRangeHi) ? "  " + str.tostring(liveRangeHi, format.mintick) : "")
    string loLiveText = "TODAY L" + (hlShowPrices and not na(liveRangeLo) ? "  " + str.tostring(liveRangeLo, format.mintick) : "")
    if showPriorHilo and not na(priorRangeHi) and not na(priorRangeLo)
        pHiLine := line.new(hlStart, priorRangeHi, hlEnd, priorRangeHi, xloc=xloc.bar_index, extend=extend.none, color=hiLineColor, width=hlLineWidth, style=priorLineStyle)
        pLoLine := line.new(hlStart, priorRangeLo, hlEnd, priorRangeLo, xloc=xloc.bar_index, extend=extend.none, color=loLineColor, width=hlLineWidth, style=priorLineStyle)
        if showHLLabels
            pHiLabel := label.new(hlEnd, priorRangeHi, hiPriorText, xloc=xloc.bar_index, style=hlBadgeLabels ? label.style_label_left : label.style_none, color=hlBadgeLabels ? hiLineColor : color.new(hiLineColor, 100), textcolor=hlBadgeLabels ? color.white : hiLineColor, size=hlLabelSize, tooltip="HOD: high of the last COMPLETED custom day range")
            pLoLabel := label.new(hlEnd, priorRangeLo, loPriorText, xloc=xloc.bar_index, style=hlBadgeLabels ? label.style_label_left : label.style_none, color=hlBadgeLabels ? loLineColor : color.new(loLineColor, 100), textcolor=hlBadgeLabels ? color.white : loLineColor, size=hlLabelSize, tooltip="LOD: low of the last COMPLETED custom day range")
    if showOlderHilo and not na(olderRangeHi) and not na(olderRangeLo)
        color dimHigh = color.new(hiLineColor, olderFade)
        color dimLow = color.new(loLineColor, olderFade)
        ppHiLine := line.new(hlStart, olderRangeHi, hlEnd, olderRangeHi, xloc=xloc.bar_index, extend=extend.none, color=dimHigh, width=olderLineWidth, style=olderLineStyle)
        ppLoLine := line.new(hlStart, olderRangeLo, hlEnd, olderRangeLo, xloc=xloc.bar_index, extend=extend.none, color=dimLow, width=olderLineWidth, style=olderLineStyle)
        if showHLLabels
            ppHiLabel := label.new(hlEnd, olderRangeHi, hiOlderText, xloc=xloc.bar_index, style=hlBadgeLabels ? label.style_label_left : label.style_none, color=hlBadgeLabels ? color.new(hiLineColor, 12) : color.new(hiLineColor, 100), textcolor=hlBadgeLabels ? color.white : hiLineColor, size=hlLabelSize, tooltip="PHOD: high of TWO completed custom day ranges ago")
            ppLoLabel := label.new(hlEnd, olderRangeLo, loOlderText, xloc=xloc.bar_index, style=hlBadgeLabels ? label.style_label_left : label.style_none, color=hlBadgeLabels ? color.new(loLineColor, 12) : color.new(loLineColor, 100), textcolor=hlBadgeLabels ? color.white : loLineColor, size=hlLabelSize, tooltip="PLOD: low of TWO completed custom day ranges ago")
    if showLiveHilo and not na(liveRangeHi) and not na(liveRangeLo)
        color liveHighCol = color.new(hiLineColor, 45)
        color liveLowCol = color.new(loLineColor, 45)
        todayHiLine := line.new(hlStart, liveRangeHi, hlEnd, liveRangeHi, xloc=xloc.bar_index, extend=extend.none, color=liveHighCol, width=liveLineWidth, style=line.style_dotted)
        todayLoLine := line.new(hlStart, liveRangeLo, hlEnd, liveRangeLo, xloc=xloc.bar_index, extend=extend.none, color=liveLowCol, width=liveLineWidth, style=line.style_dotted)
        if showHLLabels
            todayHiLabel := label.new(hlEnd, liveRangeHi, hiLiveText, xloc=xloc.bar_index, style=hlBadgeLabels ? label.style_label_left : label.style_none, color=hlBadgeLabels ? hiLineColor : color.new(hiLineColor, 100), textcolor=hlBadgeLabels ? color.white : hiLineColor, size=hlLabelSize, tooltip="LIVE range high; still changing")
            todayLoLabel := label.new(hlEnd, liveRangeLo, loLiveText, xloc=xloc.bar_index, style=hlBadgeLabels ? label.style_label_left : label.style_none, color=hlBadgeLabels ? loLineColor : color.new(loLineColor, 100), textcolor=hlBadgeLabels ? color.white : loLineColor, size=hlLabelSize, tooltip="LIVE range low; still changing")
 
float nearestDemand = na
float nearestSupply = na
for z in zones
    if z.isDemand and z.top <= close
        if na(nearestDemand) or z.top > nearestDemand
            nearestDemand := z.top
    if not z.isDemand and z.bot >= close
        if na(nearestSupply) or z.bot < nearestSupply
            nearestSupply := z.bot
 
// ============================================================================
// PART C — 5M/15M CONTEXT ZONES
// ============================================================================
type ContextZone
    bool isDemand
    bool pushActive
    float top
    float bot
 
f_contextLevels() =>
    var array<ContextZone> cx = array.new<ContextZone>()
    int n = cx.size()
    if n > 0
        for i = n - 1 to 0
            ContextZone z = cx.get(i)
            bool sameColor = z.isDemand ? close > open : close < open
            if not (z.pushActive and sameColor)
                z.pushActive := false
                bool touched = z.isDemand ? low <= z.top : high >= z.bot
                if touched
                    cx.remove(i)
    [dFound, sFound, dt, db, dOrigin, st, sb, sOrigin] = f_origin()
    if dFound
        cx.push(ContextZone.new(true, true, dt, db))
    if sFound
        cx.push(ContextZone.new(false, true, st, sb))
    int dCount = 0
    int sCount = 0
    for z in cx
        if z.isDemand
            dCount += 1
        else
            sCount += 1
    if dCount > maxZones or sCount > maxZones
        bool remD = dCount > maxZones
        for i = 0 to cx.size() - 1
            ContextZone z = cx.get(i)
            if z.isDemand == remD
                cx.remove(i)
                break
    float nearD = na
    float nearS = na
    for z in cx
        if z.isDemand and z.top <= close
            if na(nearD) or z.top > nearD
                nearD := z.top
        if not z.isDemand and z.bot >= close
            if na(nearS) or z.bot < nearS
                nearS := z.bot
    [nearD, nearS]
 
[ctx5D, ctx5S] = request.security(syminfo.tickerid, "5", f_contextLevels(), lookahead=barmerge.lookahead_off)
[ctx15D, ctx15S] = request.security(syminfo.tickerid, "15", f_contextLevels(), lookahead=barmerge.lookahead_off)
 
var line show5D = na
var line show5S = na
var line show15D = na
var line show15S = na
if barstate.islast
    if not na(show5D)
        line.delete(show5D)
        show5D := na
    if not na(show5S)
        line.delete(show5S)
        show5S := na
    if not na(show15D)
        line.delete(show15D)
        show15D := na
    if not na(show15S)
        line.delete(show15S)
        show15S := na
    if showContextLines
        if not na(ctx5D)
            show5D := line.new(bar_index-1, ctx5D, bar_index, ctx5D, extend=extend.right, color=color.new(color.green,30), style=line.style_dashed)
        if not na(ctx5S)
            show5S := line.new(bar_index-1, ctx5S, bar_index, ctx5S, extend=extend.right, color=color.new(color.red,30), style=line.style_dashed)
        if not na(ctx15D)
            show15D := line.new(bar_index-1, ctx15D, bar_index, ctx15D, extend=extend.right, color=color.new(color.lime,40), style=line.style_dotted)
        if not na(ctx15S)
            show15S := line.new(bar_index-1, ctx15S, bar_index, ctx15S, extend=extend.right, color=color.new(color.maroon,40), style=line.style_dotted)
 
// ============================================================================
// PART D — EIGHT-TIMEFRAME EMA STRUCTURE
// ============================================================================
f_state() =>
    float e1 = ta.ema(close, fastLen)
    float e2 = ta.ema(close, midLen)
    float e3 = ta.ema(close, slowLen)
    e1 > e2 and e2 > e3 ? 1 : e1 < e2 and e2 < e3 ? -1 : 0
 
f_htf() =>
    float e1 = ta.ema(close, fastLen)
    float e2 = ta.ema(close, midLen)
    float e3 = ta.ema(close, slowLen)
    float slope = e1 - e1[1]
    float oldSlope = e1[1] - e1[2]
    float atrHTF = ta.atr(14)
    [e1, e2, e3, slope, oldSlope, atrHTF]
 
int s1 = request.security(syminfo.tickerid, "1", f_state(), lookahead=barmerge.lookahead_off)
int s5 = request.security(syminfo.tickerid, "5", f_state(), lookahead=barmerge.lookahead_off)
int s15 = request.security(syminfo.tickerid, "15", f_state(), lookahead=barmerge.lookahead_off)
int s30 = request.security(syminfo.tickerid, "30", f_state(), lookahead=barmerge.lookahead_off)
int s60 = request.security(syminfo.tickerid, "60", f_state(), lookahead=barmerge.lookahead_off)
[e4, e4m, e4s, slope4, prevSlope4, atr4] = request.security(syminfo.tickerid, "240", f_htf(), lookahead=barmerge.lookahead_off)
[ed, edm, eds, slopeD, prevSlopeD, atrD] = request.security(syminfo.tickerid, "D", f_htf(), lookahead=barmerge.lookahead_off)
[ew, ewm, ews, slopeW, prevSlopeW, atrW] = request.security(syminfo.tickerid, "W", f_htf(), lookahead=barmerge.lookahead_off)
int s4 = e4 > e4m and e4m > e4s ? 1 : e4 < e4m and e4m < e4s ? -1 : 0
int sd = ed > edm and edm > eds ? 1 : ed < edm and edm < eds ? -1 : 0
int sw = ew > ewm and ewm > ews ? 1 : ew < ewm and ewm < ews ? -1 : 0
bool allBull = s1 == 1 and s5 == 1 and s15 == 1 and s30 == 1 and s60 == 1 and s4 == 1 and sd == 1 and sw == 1
bool allBear = s1 == -1 and s5 == -1 and s15 == -1 and s30 == -1 and s60 == -1 and s4 == -1 and sd == -1 and sw == -1
bool htfBull = s4 == 1 and sd == 1 and sw == 1
bool htfBear = s4 == -1 and sd == -1 and sw == -1
 
f_turnLabel(int state, float slope, float oldSlope, float at) =>
    string status = state == 1 ? "Bull" : state == -1 ? "Bear" : "Mixed"
    bool flat = not na(at) and math.abs(slope) <= flatSlopeATR * at
    bool vUp = oldSlope <= 0 and slope > 0
    bool vDown = oldSlope >= 0 and slope < 0
    if vUp
        status := "V-up"
    else if vDown
        status := "V-down"
    else if flat
        status := slope >= 0 ? "Buyers neutral" : "Sellers neutral"
    status
 
string turn4 = f_turnLabel(s4, slope4, prevSlope4, atr4)
string turnD = f_turnLabel(sd, slopeD, prevSlopeD, atrD)
string turnW = f_turnLabel(sw, slopeW, prevSlopeW, atrW)
 
bool v4Bull = slope4 > 0 and prevSlope4 <= 0
bool v4Bear = slope4 < 0 and prevSlope4 >= 0
bool vDBull = slopeD > 0 and prevSlopeD <= 0
bool vDBear = slopeD < 0 and prevSlopeD >= 0
bool vWBull = slopeW > 0 and prevSlopeW <= 0
bool vWBear = slopeW < 0 and prevSlopeW >= 0
 
plotshape(showFullMarks and allBull and not allBull[1], "Full Bull Alignment", shape.labelup, location.belowbar, color.new(color.green,15), text="8/8 UP", textcolor=color.white, size=size.tiny)
plotshape(showFullMarks and allBear and not allBear[1], "Full Bear Alignment", shape.labeldown, location.abovebar, color.new(color.red,15), text="8/8 DN", textcolor=color.white, size=size.tiny)
plotshape(showTurnMarks and (v4Bull or vDBull or vWBull), "HTF V-up developing", shape.circle, location.belowbar, color.new(color.green,0), size=size.tiny)
plotshape(showTurnMarks and (v4Bear or vDBear or vWBear), "HTF V-down developing", shape.circle, location.abovebar, color.new(color.red,0), size=size.tiny)
 
// ============================================================================
// PART E — POWER CONFLUENCE AND ALERT EVENTS
// ============================================================================
float atr1 = request.security(syminfo.tickerid, "1", ta.atr(atrLen), lookahead=barmerge.lookahead_off)
float approachDist = approachATR * nz(atr1, syminfo.mintick*10)
float emaDist = confluenceATR * nz(atr1, syminfo.mintick*10)
float ctxDist = contextDistanceATR * nz(atr1, syminfo.mintick*10)
 
bool demandCtx = not na(nearestDemand) and ((not na(ctx5D) and math.abs(ctx5D-nearestDemand)<=ctxDist) or (not na(ctx15D) and math.abs(ctx15D-nearestDemand)<=ctxDist))
bool supplyCtx = not na(nearestSupply) and ((not na(ctx5S) and math.abs(ctx5S-nearestSupply)<=ctxDist) or (not na(ctx15S) and math.abs(ctx15S-nearestSupply)<=ctxDist))
 
bool demandEMA = not na(nearestDemand) and ((s4 == 1 and (math.abs(nearestDemand-e4)<=emaDist or math.abs(nearestDemand-e4m)<=emaDist or math.abs(nearestDemand-e4s)<=emaDist)) or (sd == 1 and (math.abs(nearestDemand-ed)<=emaDist or math.abs(nearestDemand-edm)<=emaDist or math.abs(nearestDemand-eds)<=emaDist)) or (sw == 1 and (math.abs(nearestDemand-ew)<=emaDist or math.abs(nearestDemand-ewm)<=emaDist or math.abs(nearestDemand-ews)<=emaDist)))
bool supplyEMA = not na(nearestSupply) and ((s4 == -1 and (math.abs(nearestSupply-e4)<=emaDist or math.abs(nearestSupply-e4m)<=emaDist or math.abs(nearestSupply-e4s)<=emaDist)) or (sd == -1 and (math.abs(nearestSupply-ed)<=emaDist or math.abs(nearestSupply-edm)<=emaDist or math.abs(nearestSupply-eds)<=emaDist)) or (sw == -1 and (math.abs(nearestSupply-ew)<=emaDist or math.abs(nearestSupply-ewm)<=emaDist or math.abs(nearestSupply-ews)<=emaDist)))
 
bool nearD = not na(nearestDemand) and close >= nearestDemand and close-nearestDemand<=approachDist
bool nearS = not na(nearestSupply) and close <= nearestSupply and nearestSupply-close<=approachDist
bool lowerMovingDown = s1 == -1 or s5 == -1
bool lowerMovingUp = s1 == 1 or s5 == 1
bool powerLong = enablePowerAlerts and nearD and demandEMA and (not requireContext or demandCtx) and (not requireApproachMomentum or lowerMovingDown)
bool powerShort = enablePowerAlerts and nearS and supplyEMA and (not requireContext or supplyCtx) and (not requireApproachMomentum or lowerMovingUp)
bool newPowerLong = powerLong and not powerLong[1]
bool newPowerShort = powerShort and not powerShort[1]
var int lastFullBullTime = na
var int lastFullBearTime = na
if allBull
    lastFullBullTime := time
if allBear
    lastFullBearTime := time
bool recentFullBull = not na(lastFullBullTime) and time - lastFullBullTime <= alignmentMemoryMinutes * 60000
bool recentFullBear = not na(lastFullBearTime) and time - lastFullBearTime <= alignmentMemoryMinutes * 60000
bool alignPullbackLong = htfBull and recentFullBull and nearD and (not requireContext or demandCtx)
bool alignPullbackShort = htfBear and recentFullBear and nearS and (not requireContext or supplyCtx)
bool newAlignPullbackLong = alignPullbackLong and not alignPullbackLong[1]
bool newAlignPullbackShort = alignPullbackShort and not alignPullbackShort[1]
bool hit4 = enableEMATouch and ((low <= e4 and high >= e4) or (low <= e4m and high >= e4m) or (low <= e4s and high >= e4s))
bool hitD = enableEMATouch and ((low <= ed and high >= ed) or (low <= edm and high >= edm) or (low <= eds and high >= eds))
bool hitW = enableEMATouch and ((low <= ew and high >= ew) or (low <= ewm and high >= ewm) or (low <= ews and high >= ews))
bool newHit4 = hit4 and not hit4[1]
bool newHitD = hitD and not hitD[1]
bool newHitW = hitW and not hitW[1]
 
// ── HTF EMA APPROACH / PROXIMITY WATCH ──────────────────────────────────────
f_closestEMA(float price, float eFast, float eMid, float eSlow) =>
    float nearestPrice = na
    float minDistance = na
    int nearestLength = na
    if not na(eFast)
        minDistance := math.abs(price - eFast)
        nearestPrice := eFast
        nearestLength := fastLen
    if not na(eMid) and (na(minDistance) or math.abs(price - eMid) < minDistance)
        minDistance := math.abs(price - eMid)
        nearestPrice := eMid
        nearestLength := midLen
    if not na(eSlow) and (na(minDistance) or math.abs(price - eSlow) < minDistance)
        minDistance := math.abs(price - eSlow)
        nearestPrice := eSlow
        nearestLength := slowLen
    [nearestPrice, minDistance, nearestLength]
 
f_proxMaxDistance(float emaPrice) =>
    float dist = proxUnit == "Percent" ? math.abs(emaPrice) * proxPercent / 100.0 : proxUnit == "Price points" ? proxPoints : proxATR * nz(atr1, syminfo.mintick * 10)
    math.max(dist, syminfo.mintick)
 
[nearEma4, nearDist4, nearLength4] = f_closestEMA(close, e4, e4m, e4s)
[nearEmaD, nearDistD, nearLengthD] = f_closestEMA(close, ed, edm, eds)
[nearEmaW, nearDistW, nearLengthW] = f_closestEMA(close, ew, ewm, ews)
 
bool inProx4 = enableProximity and proxWatch4H and not na(nearDist4) and nearDist4 <= f_proxMaxDistance(nearEma4)
bool inProxD = enableProximity and proxWatchDaily and not na(nearDistD) and nearDistD <= f_proxMaxDistance(nearEmaD)
bool inProxW = enableProximity and proxWatchWeekly and not na(nearDistW) and nearDistW <= f_proxMaxDistance(nearEmaW)
 
var int lastProx4Time = na
var int lastProxDTime = na
var int lastProxWTime = na
int cooldownMs = proxCooldownMinutes * 60000
bool newProx4 = false
bool newProxD = false
bool newProxW = false
if barstate.isconfirmed
    if inProx4 and not inProx4[1] and (na(lastProx4Time) or time - lastProx4Time >= cooldownMs)
        newProx4 := true
        lastProx4Time := time
    if inProxD and not inProxD[1] and (na(lastProxDTime) or time - lastProxDTime >= cooldownMs)
        newProxD := true
        lastProxDTime := time
    if inProxW and not inProxW[1] and (na(lastProxWTime) or time - lastProxWTime >= cooldownMs)
        newProxW := true
        lastProxWTime := time
 
var array<label> recentProxTags = array.new<label>()
var array<int> recentProxTimes = array.new<int>()
int proxCutoffTime = last_bar_time - proxMarkerHours * 60 * 60 * 1000
if array.size(recentProxTags) > 0
    for tagIndex = array.size(recentProxTags) - 1 to 0
        if array.get(recentProxTimes, tagIndex) < proxCutoffTime
            label.delete(array.get(recentProxTags, tagIndex))
            array.remove(recentProxTags, tagIndex)
            array.remove(recentProxTimes, tagIndex)
 
float signalOffset = math.max(ta.atr(14), syminfo.mintick * 20)
bool showNewProxTag = showProxMarkers and time >= proxCutoffTime and (newProx4 or newProxD or newProxW)
if showNewProxTag
    string tagText = newProxW ? "W " + str.tostring(nearLengthW) : newProxD ? "D " + str.tostring(nearLengthD) : "4H " + str.tostring(nearLength4)
    color tagColor = newProxW ? color.new(color.purple, 5) : newProxD ? color.new(color.orange, 10) : color.new(color.blue, 15)
    color tagTextColor = newProxD and not newProxW ? color.black : color.white
    string tagTooltip = "HTF EMA approaches (watch, not entry):"
    if newProx4
        tagTooltip += "\n4H " + str.tostring(nearLength4) + " EMA @ " + str.tostring(nearEma4, format.mintick)
    if newProxD
        tagTooltip += "\nDaily " + str.tostring(nearLengthD) + " EMA @ " + str.tostring(nearEmaD, format.mintick)
    if newProxW
        tagTooltip += "\nWeekly " + str.tostring(nearLengthW) + " EMA @ " + str.tostring(nearEmaW, format.mintick)
    label newTag = label.new(bar_index, high + signalOffset * 0.55, text=tagText, style=label.style_label_down, color=tagColor, textcolor=tagTextColor, size=size.tiny, tooltip=tagTooltip)
    array.push(recentProxTags, newTag)
    array.push(recentProxTimes, time)
 
while array.size(recentProxTags) > proxMaxTags
    label.delete(array.shift(recentProxTags))
    array.shift(recentProxTimes)
 
alertcondition(newProx4, "4H EMA APPROACH", "{{ticker}}: price is close to a 4H EMA (5/10/20). Current price {{close}}; chart {{interval}}")
alertcondition(newProxD, "DAILY EMA APPROACH", "{{ticker}}: price is close to a Daily EMA (5/10/20). Current price {{close}}; chart {{interval}}")
alertcondition(newProxW, "WEEKLY EMA APPROACH", "{{ticker}}: price is close to a Weekly EMA (5/10/20). Current price {{close}}; chart {{interval}}")
alertcondition(newProx4 or newProxD or newProxW, "ANY HTF EMA APPROACH (4H/D/W)", "{{ticker}}: close to a 4H, Daily, or Weekly 5/10/20 EMA. Price {{close}}; chart {{interval}}")
 
if enableProxDynamic and barstate.isconfirmed and (newProx4 or newProxD or newProxW)
    string details = ""
    if newProx4
        details += "4H " + str.tostring(nearLength4) + " EMA @" + str.tostring(nearEma4, format.mintick) + " gap=" + str.tostring(nearDist4, format.mintick) + " (" + str.tostring(nearDist4 / math.max(math.abs(nearEma4), syminfo.mintick) * 100, "#.###") + "%); "
    if newProxD
        details += "D " + str.tostring(nearLengthD) + " EMA @" + str.tostring(nearEmaD, format.mintick) + " gap=" + str.tostring(nearDistD, format.mintick) + " (" + str.tostring(nearDistD / math.max(math.abs(nearEmaD), syminfo.mintick) * 100, "#.###") + "%); "
    if newProxW
        details += "W " + str.tostring(nearLengthW) + " EMA @" + str.tostring(nearEmaW, format.mintick) + " gap=" + str.tostring(nearDistW, format.mintick) + " (" + str.tostring(nearDistW / math.max(math.abs(nearEmaW), syminfo.mintick) * 100, "#.###") + "%); "
    alert("POWER STRUCTURE | " + syminfo.ticker + " HTF EMA APPROACH | price=" + str.tostring(close, format.mintick) + " | " + details + "(watch / not entry)", alert.freq_once_per_bar_close)
 
bool anyBullTurn = v4Bull or vDBull or vWBull
bool anyBearTurn = v4Bear or vDBear or vWBear
 
plotshape(showSig and longTouch, title="First return into unused 1m demand", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny)
plotshape(showSig and shortTouch, title="First return into unused 1m supply", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny)
alertcondition(longTouch, "1M unused demand first pullback", "{{ticker}}: first pullback into unused 1-minute demand")
alertcondition(shortTouch, "1M unused supply first pullback", "{{ticker}}: first pullback into unused 1-minute supply")
alertcondition(newPowerLong, "POWER MOVE CONFLUENCE LONG", "{{ticker}}: fresh 1m demand approaching bullish 4H/D/W EMA structure")
alertcondition(newPowerShort, "POWER MOVE CONFLUENCE SHORT", "{{ticker}}: fresh 1m supply approaching bearish 4H/D/W EMA structure")
alertcondition(newPowerLong or newPowerShort, "POWER MOVE CONFLUENCE ANY", "{{ticker}}: power-move confluence approaching a fresh 1-minute origin")
alertcondition(newAlignPullbackLong, "FULL ALIGNMENT -> NEAREST 1M DEMAND", "{{ticker}}: after bullish alignment, price approaching closest unused 1m demand")
alertcondition(newAlignPullbackShort, "FULL ALIGNMENT -> NEAREST 1M SUPPLY", "{{ticker}}: after bearish alignment, price approaching closest unused 1m supply")
alertcondition(newHit4, "4H EMA TOUCH", "{{ticker}}: price touched a 4H EMA")
alertcondition(newHitD, "DAILY EMA TOUCH", "{{ticker}}: price touched a Daily EMA")
alertcondition(newHitW, "WEEKLY EMA TOUCH", "{{ticker}}: price touched a Weekly EMA")
alertcondition(allBull and not allBull[1], "8/8 FULL BULLISH ALIGNMENT", "{{ticker}}: all eight EMA timeframes are bullish")
alertcondition(allBear and not allBear[1], "8/8 FULL BEARISH ALIGNMENT", "{{ticker}}: all eight EMA timeframes are bearish")
alertcondition(anyBullTurn and not anyBullTurn[1], "HTF bullish V-turn (developing)", "{{ticker}}: 4H, Daily, or Weekly 5 EMA turned upward; developing / can change")
alertcondition(anyBearTurn and not anyBearTurn[1], "HTF bearish inverted V-turn (developing)", "{{ticker}}: 4H, Daily, or Weekly 5 EMA turned downward; developing / can change")
if dynamicAlerts and barstate.isconfirmed and (newPowerLong or newPowerShort)
    string side = newPowerLong ? "LONG" : "SHORT"
    float level = newPowerLong ? nearestDemand : nearestSupply
    alert("POWER STRUCTURE " + side + " | " + syminfo.ticker + " | fresh 1m level=" + str.tostring(level, format.mintick) + " | price=" + str.tostring(close, format.mintick) + " | 5m/15m confluence=" + str.tostring(newPowerLong ? demandCtx : supplyCtx), alert.freq_once_per_bar_close)
 
// ============================================================================
// PART F — COMPACT EMA DASHBOARD
// ============================================================================
boardPos = boardPlace == "Top Left" ? position.top_left : boardPlace == "Bottom Right" ? position.bottom_right : boardPlace == "Bottom Left" ? position.bottom_left : position.top_right
var table panel = table.new(boardPos, 3, 11, border_width=1)
f_directionText(int st) => st == 1 ? "BULL" : st == -1 ? "BEAR" : "NEUTRAL"
f_directionColor(int st) => st == 1 ? color.new(color.green, 20) : st == -1 ? color.new(color.red, 20) : color.new(color.orange, 32)
f_row(int rowNum, string tfText, int st, string note) =>
    table.cell(panel, 0, rowNum, tfText, text_color=color.white, bgcolor=color.new(color.black, boardFade), text_size=size.tiny)
    table.cell(panel, 1, rowNum, f_directionText(st), text_color=color.white, bgcolor=f_directionColor(st), text_size=size.tiny)
    table.cell(panel, 2, rowNum, note, text_color=color.white, bgcolor=color.new(color.black, boardFade), text_size=size.tiny)
if barstate.islast
    if showBoard
        table.cell(panel, 0, 0, "TF", text_color=color.white, bgcolor=color.new(color.blue,35), text_size=size.tiny)
        table.cell(panel, 1, 0, "5/10/20", text_color=color.white, bgcolor=color.new(color.blue,35), text_size=size.tiny)
        table.cell(panel, 2, 0, "TURN / STATUS", text_color=color.white, bgcolor=color.new(color.blue,35), text_size=size.tiny)
        f_row(1, "W", sw, showTurns ? turnW : "")
        f_row(2, "D", sd, showTurns ? turnD : "")
        f_row(3, "4H", s4, showTurns ? turn4 : "")
        f_row(4, "1H", s60, "")
        f_row(5, "30m", s30, "")
        f_row(6, "15m", s15, "")
        f_row(7, "5m", s5, "")
        f_row(8, "1m", s1, "")
        string alignTxt = allBull ? "ALL BULL" : allBear ? "ALL BEAR" : htfBull ? "HTF BULL" : htfBear ? "HTF BEAR" : "MIXED"
        table.cell(panel, 0, 9, "ALIGN", text_color=color.white, bgcolor=color.new(color.black,boardFade), text_size=size.tiny)
        table.cell(panel, 1, 9, alignTxt, text_color=color.white, bgcolor=allBull or htfBull ? color.new(color.green,20) : allBear or htfBear ? color.new(color.red,20) : color.new(color.orange,20), text_size=size.tiny)
        table.cell(panel, 2, 9, "Live / developing", text_color=color.white, bgcolor=color.new(color.black,boardFade), text_size=size.tiny)
        string nearText = "D:" + (na(nearestDemand) ? "—" : str.tostring(nearestDemand,format.mintick))
        string supText = "S:" + (na(nearestSupply) ? "—" : str.tostring(nearestSupply,format.mintick))
        table.cell(panel, 0, 10, "FRESH 1m", text_color=color.white, bgcolor=color.new(color.black,boardFade), text_size=size.tiny)
        table.cell(panel, 1, 10, nearText, text_color=color.white, bgcolor=color.new(color.black,boardFade), text_size=size.tiny)
        table.cell(panel, 2, 10, supText, text_color=color.white, bgcolor=color.new(color.black,boardFade), text_size=size.tiny)
    else
        table.clear(panel, 0, 0, 2, 10)

← 返回列表