BTM - Volume Profile + Volatility

BeyondTheMarkets · study · 1173 行 · 点赞 151 · TradingView 原页

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

Pine Script

//@version=6
indicator("BTM - Volume Profile + Volatility",
     shorttitle="BTM - VP+VOL",
     overlay=true,
     max_boxes_count=500,
     max_lines_count=500,
     max_labels_count=500,
     max_bars_back=5000)
 
// Volume profile with a volatility read-out, built for XAUUSD intraday.
//
// Profile    : session (day / week / custom UK session) or fixed lookback, with
//              POC, value area, buy/sell split, developing + previous session
//              levels and naked POCs.
// Volatility : ATR regime (percentile rank), volatility vs the norm for this
//              time of day, expansion/contraction, annualised historical vol,
//              ADR used, relative volume and an effort-vs-result read.
//
// Signals    : the "80% rule". When a session opens outside the previous
//              session's value area and then holds back inside it, price
//              tends to cross to the far side. On 1h Nasdaq it held up on
//              futures and CFD data alike; on spot gold it was about
//              breakeven, so treat gold signals as unproven. The dashboard
//              tracks how the signals have done on whatever chart you load,
//              says whether the signal was tested on this market, sizes the
//              trade from your account risk, and can alert you early when a
//              setup starts forming.
//
// Also draws last week's POC / value area and shades heavy and thin volume
// zones inside the profile.
//
// Works on any symbol. Feeds with no volume (e.g. FOREX.com) automatically
// borrow volume from another feed and spread it over the chart's own bars:
// the same ticker on OANDA (FX, metals), OANDA's name for the index or
// commodity (NAS100 -> NAS100USD, GER40 -> DE30EUR, USOIL -> WTICOUSD, ...),
// or Coinbase (crypto). That volume is tick volume; pick a Custom Symbol such
// as COMEX:GC1! or CME_MINI:NQ1! for real futures volume.
 
//━━━━━━━━━━━━━━━━━━━
// INPUTS
//━━━━━━━━━━━━━━━━━━━
grpVP  = "Volume Profile"
grpLvl = "Session Levels"
grpVol = "Volatility"
grpSrc = "Volume Source"
grpSig = "Signals (80% Rule)"
grpRisk = "Position Size"
grpUI  = "Display"
 
profileMode   = input.string("Session", "Profile Mode", options=["Session", "Lookback"], group=grpVP)
sessionAnchor = input.string("Day", "Session Anchor", options=["Day", "Week", "Custom Session"], group=grpVP)
customSession = input.session("0700-1600", "Custom Session (UK)", group=grpVP)
lookbackBars  = input.int(300, "Lookback Bars", minval=10, maxval=5000, group=grpVP)
profileRows   = input.int(50, "Row Resolution", minval=10, maxval=150, group=grpVP, tooltip="Lookback profiles use exactly this many rows. Session profiles keep between half and this many rows, coarsening as the session range grows.")
valueAreaPct  = input.float(70, "Value Area %", minval=10, maxval=99, group=grpVP)
splitMethod   = input.string("Close Location", "Buy/Sell Split", options=["Close Location", "Bar Polarity"], group=grpVP, tooltip="Close Location: buy share = (close - low) / (high - low). Bar Polarity: up bars are all buying, down bars all selling.")
profPrecision = input.string("Intrabar", "Profile Precision", options=["Intrabar", "Candle Range"], group=grpVP, tooltip="Intrabar: places each candle's volume where price actually traded inside it, using this chart's lower-timeframe data (most useful on 15m and above). Candle Range: spreads it evenly from high to low. Older history beyond TradingView's intrabar limit, 1m charts and Lookback profiles use Candle Range.")
showZones     = input.bool(true, "Heavy / Thin Volume Zones", group=grpVP, tooltip="Shades where the profile traded heavily (price often stalls there) and the thin gaps between heavy areas (price often moves quickly through them). For reading the chart only: these zones are not part of the tested signal.")
 
showDevPOC     = input.bool(true, "Developing POC", group=grpLvl, tooltip="How the session's POC moved, bar by bar.")
showDevVA      = input.bool(false, "Developing VAH / VAL", group=grpLvl)
showPrevLevels = input.bool(true, "Previous Session POC / VAH / VAL", group=grpLvl)
showWeekLevels = input.bool(true, "Last Week POC / VAH / VAL", group=grpLvl, tooltip="Last week's busiest price and value area as dotted lines, for bigger-picture targets. Not part of the tested signal. Hidden when the Session Anchor is Week, because the previous-session levels are then last week's.")
showNakedPOC   = input.bool(true, "Naked POCs", group=grpLvl, inline="naked")
maxNakedPOC    = input.int(5, "Max", minval=1, maxval=20, group=grpLvl, inline="naked")
showHistory    = input.bool(false, "Show Level History", group=grpLvl, tooltip="Off: only the current session's levels, each labelled on the right. On: also every past session's developing POC trail and previous-session levels.")
 
showSignals  = input.bool(true, "Buy / Sell Signals", group=grpSig, tooltip="BUY when the session opened below the previous session's value area and has held back inside it for the acceptance time; target the previous VAH, stop below the session low. SELL is the mirror image. One trade per session; it exits at target, stop or session end.")
acceptMins   = input.int(60, "Acceptance Time (minutes)", minval=1, group=grpSig, tooltip="How long closes must stay back inside the previous value area. 60 (the textbook value) held up best across data sources.")
sigDirection = input.string("Both", "Direction", options=["Both", "Long only", "Short only"], group=grpSig)
stopBufATR   = input.float(0.1, "Stop Buffer (x ATR)", minval=0, step=0.05, group=grpSig)
sigCost      = input.float(0.0, "Cost per Trade (price units)", minval=0, step=0.05, group=grpSig, tooltip="Spread + commission deducted from every trade in the stats, e.g. 0.35 for gold or 1.5 for NAS100.")
earlyAlert   = input.bool(true, "'Setup Forming' Early Alert", group=grpSig, tooltip="Part of the 'Any alert() function call' alert: once a session, the moment price trades back inside the previous value area after opening outside it. The real signal comes later, if closes hold inside for the acceptance time.")
 
accountSize   = input.float(10000, "Account Size", minval=0, group=grpRisk)
riskPct       = input.float(1.0, "Risk per Trade (%)", minval=0.01, maxval=100, step=0.25, group=grpRisk)
accountCcy    = input.string("USD", "Account Currency", options=["USD", "GBP", "EUR", "AUD", "CAD", "CHF", "JPY", "NZD"], group=grpRisk)
unitsPerLotIn = input.float(0, "Units per Lot (0 = auto)", minval=0, group=grpRisk, tooltip="How much of the market one lot is. Auto: 100,000 for FX pairs, 100 oz for gold and platinum, 5,000 oz for silver, the contract size for futures, and 1 for indices, oil and crypto. Brokers differ, so check one size against your broker's order ticket and enter the right number here if it's off.")
 
atrLen      = input.int(14, "ATR Length", minval=1, group=grpVol)
regimeLen   = input.int(200, "Regime Lookback (bars)", minval=20, group=grpVol)
lowPct      = input.int(25, "Low Below Percentile", minval=1, maxval=99, group=grpVol)
highPct     = input.int(75, "High Above Percentile", minval=1, maxval=99, group=grpVol)
extremePct  = input.int(90, "Extreme Above Percentile", minval=1, maxval=99, group=grpVol)
fastATRLen  = input.int(5, "Expansion ATR Fast", minval=1, group=grpVol, inline="exp")
slowATRLen  = input.int(50, "Slow", minval=2, group=grpVol, inline="exp")
todDays     = input.int(20, "Time-of-Day Baseline (days)", minval=2, group=grpVol, tooltip="Each bar is compared with the average for the same time of day (UK) over roughly this many days, so a quiet Asian bar and a busy London open are judged against their own norm.")
todSmooth   = input.int(3, "Time-of-Day Smoothing (bars)", minval=1, group=grpVol)
hvLen       = input.int(20, "Historical Vol Length", minval=2, group=grpVol)
adrLen      = input.int(14, "ADR Length (days)", minval=1, group=grpVol)
 
volSource       = input.string("Auto", "Volume Source", options=["Auto", "Chart", "Exchange", "Custom Symbol"], group=grpSrc, tooltip="Auto tries, in order: the chart's own volume; the same ticker on the exchange below (XAUUSD -> OANDA:XAUUSD); OANDA's name for common indices and commodities (NAS100 -> OANDA:NAS100USD, GER40 -> OANDA:DE30EUR); Coinbase for crypto. Exchange: always the same ticker on that exchange. Custom Symbol: any symbol, e.g. COMEX:GC1! for real gold futures volume. Borrowed volume is spread over this chart's bars; bars missing on that symbol count as zero.")
volExchange     = input.string("OANDA", "Volume Exchange", group=grpSrc, tooltip="Prices always come from your chart's broker (e.g. FOREX.com). Only volume is borrowed, because FOREX.com publishes none on TradingView. Used by Auto and Exchange: the chart's ticker is looked up here, e.g. XAUUSD -> OANDA:XAUUSD.")
customVolSymbol = input.symbol("COMEX:GC1!", "Custom Symbol", group=grpSrc)
 
placement     = input.string("Right", "Profile Placement", options=["Right", "Left"], group=grpUI, tooltip="Right: drawn past the last bar. Left: drawn from the start of the profile range over the candles.")
profileWidth  = input.int(40, "Profile Width (bars)", minval=5, maxval=300, group=grpUI)
profileOffset = input.int(5, "Right Offset (bars)", minval=0, maxval=100, group=grpUI)
showSplit     = input.bool(true, "Show Buy/Sell Split", group=grpUI)
showProfLvls  = input.bool(true, "Show POC / VA Lines", group=grpUI)
levelLabelGap = input.int(15, "Level Label Offset (bars)", minval=0, maxval=50, group=grpUI, tooltip="Gap between the profile's POC / VAH / VAL labels and the Prev / Naked POC labels further right.")
buyColor      = input.color(#26a69a, "Buy / Up", group=grpUI, inline="c1")
sellColor     = input.color(#e0f2f1, "Sell / Down", group=grpUI, inline="c1")
pocColor      = input.color(#ffffff, "POC", group=grpUI, inline="c2")
vaColor       = input.color(#80cbc4, "Value Area", group=grpUI, inline="c2")
colorCandles  = input.bool(true, "Colour Candles (Buy / Up and Sell / Down colours)", group=grpUI)
showDash      = input.bool(true, "Show Dashboard", group=grpUI)
dashMode      = input.string("Simple", "Dashboard Mode", options=["Simple", "Pro", "Mini"], group=grpUI, tooltip="Simple: a short plain-English summary for beginners. Pro: every reading. Mini: signal, speed and price only, for phones. Hover over any row for an explanation.")
dashPosInput  = input.string("Top Right", "Dashboard Position", options=["Top Right", "Top Left", "Middle Right", "Bottom Right", "Bottom Left"], group=grpUI)
dashSizeInput = input.string("Normal", "Dashboard Text", options=["Small", "Normal", "Large"], group=grpUI)
showVolBg     = input.bool(false, "Tint Background on High Volatility", group=grpUI)
 
//━━━━━━━━━━━━━━━━━━━
// VOLUME SOURCE
//━━━━━━━━━━━━━━━━━━━
// OANDA's name for common index / commodity CFDs, whatever the chart's broker
// calls them. Exact matches keep the result a "simple" string, which
// request.security needs for its symbol.
tk = syminfo.ticker
aliasName = switch
    tk == "NAS100" or tk == "US100" or tk == "USTEC" or tk == "USTECH" or tk == "NSXUSD" or tk == "NDX" or tk == "US100USD" or tk == "NASDAQ100" => "NAS100USD"
    tk == "US30" or tk == "DJ30" or tk == "WS30" or tk == "DJI" or tk == "WALLST30" or tk == "US30USD" => "US30USD"
    tk == "SP500" or tk == "SPX500" or tk == "US500" or tk == "SPX" or tk == "SPXUSD" or tk == "US500USD" => "SPX500USD"
    tk == "US2000" or tk == "RUSSELL2000" or tk == "RTY" or tk == "US2000USD" => "US2000USD"
    tk == "GER40" or tk == "GER30" or tk == "DE40" or tk == "DE30" or tk == "DAX" or tk == "DAX40" or tk == "GRXEUR" or tk == "DE40EUR" => "DE30EUR"
    tk == "UK100" or tk == "FTSE100" or tk == "FTSE" or tk == "UKX" or tk == "UKXGBP" => "UK100GBP"
    tk == "JPN225" or tk == "JP225" or tk == "NIKKEI225" or tk == "NIKKEI" or tk == "N225" or tk == "NI225" or tk == "JPXJPY" => "JP225USD"
    tk == "FRA40" or tk == "FR40" or tk == "CAC40" or tk == "CAC" or tk == "FRXEUR" => "FR40EUR"
    tk == "EU50" or tk == "EUSTX50" or tk == "STOXX50" or tk == "STOXX50E" or tk == "ETXEUR" => "EU50EUR"
    tk == "AUS200" or tk == "AU200" or tk == "ASX200" or tk == "AUXAUD" => "AU200AUD"
    tk == "HK50" or tk == "HK33" or tk == "HSI" or tk == "HKXHKD" => "HK33HKD"
    tk == "UKOIL" or tk == "BRENT" or tk == "XBRUSD" or tk == "UKOUSD" or tk == "BRENTUSD" => "BCOUSD"
    tk == "USOIL" or tk == "WTI" or tk == "XTIUSD" or tk == "USOUSD" or tk == "WTIUSD" or tk == "CRUDEOIL" => "WTICOUSD"
    tk == "NATGAS" or tk == "NGAS" or tk == "XNGUSD" => "NATGASUSD"
    tk == "COPPER" or tk == "XCUUSD" => "XCUUSD"
    tk == "GOLD" => "XAUUSD"
    tk == "SILVER" => "XAGUSD"
    => ""
 
isAuto = volSource == "Auto"
brokerName = syminfo.prefix == "FOREXCOM" ? "FOREX.com" : syminfo.prefix
 
// Candidates not needed by the chosen mode request the chart itself, which costs nothing extra.
directSymbol = isAuto or volSource == "Exchange" ? volExchange + ":" + syminfo.ticker : syminfo.tickerid
aliasSymbol  = isAuto and aliasName != "" ? "OANDA:" + aliasName : syminfo.tickerid
cryptoSymbol = isAuto ? "COINBASE:" + syminfo.ticker : syminfo.tickerid
customSymbol = volSource == "Custom Symbol" ? customVolSymbol : syminfo.tickerid
 
directVol = request.security(directSymbol, timeframe.period, volume, gaps=barmerge.gaps_on, ignore_invalid_symbol=true)
aliasVol  = request.security(aliasSymbol, timeframe.period, volume, gaps=barmerge.gaps_on, ignore_invalid_symbol=true)
cryptoVol = request.security(cryptoSymbol, timeframe.period, volume, gaps=barmerge.gaps_on, ignore_invalid_symbol=true)
customVol = request.security(customSymbol, timeframe.period, volume, gaps=barmerge.gaps_on, ignore_invalid_symbol=true)
 
chartHas  = ta.cum(nz(volume)) > 0
directHas = ta.cum(nz(directVol)) > 0
aliasHas  = ta.cum(nz(aliasVol)) > 0
cryptoHas = ta.cum(nz(cryptoVol)) > 0
 
// 0 = chart, 1 = exchange, 2 = index/commodity alias, 3 = crypto, 4 = custom
volPick =
     volSource == "Chart" ? 0 :
     volSource == "Exchange" ? 1 :
     volSource == "Custom Symbol" ? 4 :
     chartHas ? 0 : directHas ? 1 : aliasHas ? 2 : cryptoHas ? 3 : 0
 
vol = nz(volPick == 0 ? volume : volPick == 1 ? directVol : volPick == 2 ? aliasVol : volPick == 3 ? cryptoVol : customVol)
volSourceName = volPick == 0 ? syminfo.ticker : volPick == 1 ? directSymbol : volPick == 2 ? aliasSymbol : volPick == 3 ? cryptoSymbol : customVolSymbol
volEverSeen = ta.cum(vol) > 0
 
// Lower timeframe for intrabar profiles: roughly 15-60 intrabars per candle.
tfMins = timeframe.in_seconds() / 60.0
ltf = tfMins <= 1 ? "" : tfMins <= 30 ? "1" : tfMins <= 60 ? "3" : tfMins <= 240 ? "15" : tfMins <= 1440 ? "60" : "240"
useIntrabar = profPrecision == "Intrabar" and ltf != ""
 
array<float> ibO = na
array<float> ibH = na
array<float> ibL = na
array<float> ibC = na
array<float> ibV = na
if useIntrabar
    [o_, h_, l_, c_, v_] = request.security_lower_tf(syminfo.tickerid, ltf, [open, high, low, close, volume], ignore_invalid_symbol=true)
    ibO := o_
    ibH := h_
    ibL := l_
    ibC := c_
    ibV := v_
 
nIb = useIntrabar and not na(ibH) ? ibH.size() : 0
ibVolSum = nIb > 0 ? nz(ibV.sum()) : 0.0
 
barRange = high - low
buyShare = splitMethod == "Bar Polarity" ? (close > open ? 1.0 : close < open ? 0.0 : 0.5) : barRange > 0 ? (close - low) / barRange : 0.5
buyVol = vol * buyShare
 
//━━━━━━━━━━━━━━━━━━━
// PROFILE ENGINE
//━━━━━━━━━━━━━━━━━━━
// Row i spans [bottom + i * step, bottom + (i + 1) * step).
type Profile
    array<float> vol
    array<float> buy
    float        bottom
    float        step
 
method rowBottom(Profile p, int i) =>
    p.bottom + i * p.step
 
method rowTop(Profile p, int i) =>
    p.bottom + (i + 1) * p.step
 
method rowMid(Profile p, int i) =>
    p.bottom + (i + 0.5) * p.step
 
method reset(Profile p, float price, float step) =>
    p.vol.clear()
    p.buy.clear()
    p.step := step
    p.bottom := math.floor(price / step) * step
 
// Merge row pairs and double the row height. The bottom edge stays put.
method compress(Profile p) =>
    int n = p.vol.size()
    float[] newVol = array.new_float()
    float[] newBuy = array.new_float()
    for i = 0 to n - 1 by 2
        bool hasPair = i + 1 < n
        newVol.push(p.vol.get(i) + (hasPair ? p.vol.get(i + 1) : 0.0))
        newBuy.push(p.buy.get(i) + (hasPair ? p.buy.get(i + 1) : 0.0))
    p.vol := newVol
    p.buy := newBuy
    p.step := p.step * 2
 
// Grow the grid to cover [lo, hi], halving resolution whenever it passes maxRows.
method cover(Profile p, float hi, float lo, int maxRows) =>
    while lo < p.bottom
        p.vol.unshift(0.0)
        p.buy.unshift(0.0)
        p.bottom := p.bottom - p.step
        if p.vol.size() > maxRows
            p.compress()
    while hi >= p.bottom + p.step * p.vol.size()
        p.vol.push(0.0)
        p.buy.push(0.0)
        if p.vol.size() > maxRows
            p.compress()
 
// Spread a bar's volume over the rows it touches, in proportion to overlap.
method addBar(Profile p, float hi, float lo, float v, float bv) =>
    int n = p.vol.size()
    if v > 0 and n > 0
        int r0 = math.max(0, math.min(n - 1, math.floor((lo - p.bottom) / p.step)))
        int r1 = math.max(0, math.min(n - 1, math.floor((hi - p.bottom) / p.step)))
        for i = r0 to r1
            float share = 1.0
            if r1 > r0
                share := (math.min(hi, p.rowTop(i)) - math.max(lo, p.rowBottom(i))) / (hi - lo)
            p.vol.set(i, p.vol.get(i) + v * share)
            p.buy.set(i, p.buy.get(i) + bv * share)
 
// Add this candle. Its volume is split across its intrabars: by their own volume
// when the chart has it, otherwise by time spent at each price (equal shares).
method addCandle(Profile p) =>
    if nIb > 0
        for j = 0 to nIb - 1
            float h = ibH.get(j)
            float l = ibL.get(j)
            float c = ibC.get(j)
            float o = ibO.get(j)
            float w = ibVolSum > 0 ? nz(ibV.get(j)) / ibVolSum : 1.0 / nIb
            float bs = splitMethod == "Bar Polarity" ? (c > o ? 1.0 : c < o ? 0.0 : 0.5) : h > l ? (c - l) / (h - l) : 0.5
            p.addBar(h, l, vol * w, vol * w * bs)
    else
        p.addBar(high, low, vol, buyVol)
 
// Highest-volume row, or -1 if the profile holds no volume.
// Ties go to the row nearest the middle of the profile.
method pocIndex(Profile p) =>
    int best = -1
    float bestVol = 0.0
    float mid = (p.vol.size() - 1) / 2.0
    for [i, v] in p.vol
        if v > bestVol or (v == bestVol and best >= 0 and math.abs(i - mid) < math.abs(best - mid))
            best := i
            bestVol := v
    best
 
// Expand from the POC towards the heavier neighbouring row until pct of volume is inside.
method valueArea(Profile p, int poc, float pct) =>
    int n = p.vol.size()
    int lo = poc
    int hi = poc
    if poc >= 0
        float target = p.vol.sum() * pct / 100
        float acc = p.vol.get(poc)
        while acc < target and (lo > 0 or hi < n - 1)
            float up = hi < n - 1 ? p.vol.get(hi + 1) : -1.0
            float dn = lo > 0 ? p.vol.get(lo - 1) : -1.0
            if up >= dn
                hi += 1
                acc += up
            else
                lo -= 1
                acc += dn
    [lo, hi]
 
//━━━━━━━━━━━━━━━━━━━
// SESSION PROFILE
//━━━━━━━━━━━━━━━━━━━
atrVal = ta.atr(atrLen)
 
newDay  = timeframe.change("D")
newWeek = timeframe.change("W")
 
inCustom    = not na(time(timeframe.period, customSession, "Europe/London"))
customStart = inCustom and not inCustom[1]
customEnd   = not inCustom and inCustom[1]
 
isCustom     = sessionAnchor == "Custom Session"
inSession    = not isCustom or inCustom
sessionStart = sessionAnchor == "Day" ? newDay : sessionAnchor == "Week" ? newWeek : customStart
sessionClose = isCustom ? customEnd : sessionStart
 
var Profile sess = Profile.new(array.new_float(), array.new_float(), na, na)
var int sessStartBar = na
 
var float devPOC = na
var float devVAH = na
var float devVAL = na
 
var float prevPOC = na
var float prevVAH = na
var float prevVAL = na
 
var int prevSetBar = na
 
// Last completed session's profile, shown while a new session has no volume yet.
var Profile lastSess = na
var int lastSessStart = na
 
var line[] nakedLines = array.new_line()
var int[]  nakedTimes = array.new_int()
 
// Current session's developing levels, drawn as trails when history is off.
var array<chart.point> devPocPts = array.new<chart.point>()
var array<chart.point> devVahPts = array.new<chart.point>()
var array<chart.point> devValPts = array.new<chart.point>()
 
// Lock in the finished session as "previous" and leave its POC as a naked level.
if sessionClose and not na(devPOC)
    prevPOC := devPOC
    prevVAH := devVAH
    prevVAL := devVAL
    prevSetBar := bar_index
    lastSess := Profile.new(sess.vol.copy(), sess.buy.copy(), sess.bottom, sess.step)
    lastSessStart := sessStartBar
 
    if showNakedPOC
        nakedLines.push(line.new(sessStartBar, devPOC, bar_index, devPOC, color=pocColor, style=line.style_dotted))
        nakedTimes.push(time[1])
 
        if nakedLines.size() > maxNakedPOC
            nakedLines.shift().delete()
            nakedTimes.shift()
 
startNow = inSession and (sessionStart or na(sess.bottom))
 
if startNow
    sess.reset(low, math.max(syminfo.mintick, nz(atrVal, barRange) / 4))
    sessStartBar := bar_index
    devPocPts.clear()
    devVahPts.clear()
    devValPts.clear()
 
if inSession and not na(sess.bottom)
    sess.cover(high, low, profileRows)
    sess.addCandle()
 
    int sPOC = sess.pocIndex()
    [sVaLo, sVaHi] = sess.valueArea(sPOC, valueAreaPct)
 
    // No volume means no levels, rather than a fake POC at mid-range.
    devPOC := sPOC >= 0 ? sess.rowMid(sPOC) : na
    devVAH := sPOC >= 0 ? sess.rowTop(sVaHi) : na
    devVAL := sPOC >= 0 ? sess.rowBottom(sVaLo) : na
 
    if sPOC >= 0
        devPocPts.push(chart.point.from_index(bar_index, devPOC))
        devVahPts.push(chart.point.from_index(bar_index, devVAH))
        devValPts.push(chart.point.from_index(bar_index, devVAL))
 
// Last week's levels, from every bar of the week whatever the session anchor.
// The chart's first, partial week is skipped.
showWeek = showWeekLevels and sessionAnchor != "Week"
 
var Profile wk = Profile.new(array.new_float(), array.new_float(), na, na)
var bool  wkFull = false
var float pwPOC = na
var float pwVAH = na
var float pwVAL = na
var int   pwSetBar = na
 
if showWeek
    if newWeek and wkFull
        int wPOC = wk.pocIndex()
        if wPOC >= 0
            [wVaLo, wVaHi] = wk.valueArea(wPOC, valueAreaPct)
            pwPOC := wk.rowMid(wPOC)
            pwVAH := wk.rowTop(wVaHi)
            pwVAL := wk.rowBottom(wVaLo)
            pwSetBar := bar_index
    if newWeek or na(wk.bottom)
        wkFull := not na(wk.bottom)
        wk.reset(low, math.max(syminfo.mintick, nz(atrVal, barRange) / 4))
    wk.cover(high, low, profileRows)
    wk.addCandle()
 
// A naked POC is gone once price trades back through it.
if nakedLines.size() > 0
    for i = nakedLines.size() - 1 to 0
        line ln = nakedLines.get(i)
        float y = ln.get_y1()
 
        if high >= y and low <= y
            ln.delete()
            nakedLines.remove(i)
            nakedTimes.remove(i)
 
hideDev  = startNow or not inSession
hidePrev = sessionClose
 
// Level history. When off, nothing is painted and the price scale gets no
// unlabelled tags, but values stay readable in the data window (and by other scripts).
histDisplay = showHistory ? display.all : display.data_window
 
plot(showDevPOC and not hideDev ? devPOC : na, "Developing POC", color=pocColor, linewidth=2, style=plot.style_linebr, display=histDisplay)
plot(showDevVA and not hideDev ? devVAH : na, "Developing VAH", color=vaColor, style=plot.style_linebr, display=histDisplay)
plot(showDevVA and not hideDev ? devVAL : na, "Developing VAL", color=vaColor, style=plot.style_linebr, display=histDisplay)
 
plot(showPrevLevels and not hidePrev ? prevPOC : na, "Previous POC", color=color.new(pocColor, 40), style=plot.style_linebr, display=histDisplay)
plot(showPrevLevels and not hidePrev ? prevVAH : na, "Previous VAH", color=color.new(vaColor, 40), style=plot.style_linebr, display=histDisplay)
plot(showPrevLevels and not hidePrev ? prevVAL : na, "Previous VAL", color=color.new(vaColor, 40), style=plot.style_linebr, display=histDisplay)
 
plot(showWeek and not newWeek ? pwPOC : na, "Last Week POC", color=color.new(pocColor, 60), style=plot.style_linebr, display=histDisplay)
plot(showWeek and not newWeek ? pwVAH : na, "Last Week VAH", color=color.new(vaColor, 60), style=plot.style_linebr, display=histDisplay)
plot(showWeek and not newWeek ? pwVAL : na, "Last Week VAL", color=color.new(vaColor, 60), style=plot.style_linebr, display=histDisplay)
 
//━━━━━━━━━━━━━━━━━━━
// VOLATILITY ENGINE
//━━━━━━━━━━━━━━━━━━━
atrPctOfPrice = atrVal / close * 100
atrRank = ta.percentrank(atrVal, regimeLen)
 
// 0 = LOW, 1 = NORMAL, 2 = HIGH, 3 = EXTREME
int regime = na(atrRank) ? na : atrRank >= extremePct ? 3 : atrRank >= highPct ? 2 : atrRank < lowPct ? 0 : 1
 
expRatio = ta.atr(fastATRLen) / ta.atr(slowATRLen)
volTrend = na(expRatio) ? "—" : expRatio > 1.15 ? "EXPANDING" : expRatio < 0.85 ? "CONTRACTING" : "STABLE"
 
// Time-of-day baselines: EMA of true range and volume per UK clock slot.
var map<int, float> todTRBase  = map.new<int, float>()
var map<int, float> todVolBase = map.new<int, float>()
 
var int daysSeen = 0
if newDay
    daysSeen += 1
 
todSlot   = hour(time, "Europe/London") * 60 + minute(time, "Europe/London")
trueRange = ta.tr(true)
todAlpha  = 2.0 / (todDays + 1)
 
baseTR  = todTRBase.get(todSlot)
baseVol = todVolBase.get(todSlot)
 
todTRBase.put(todSlot, na(baseTR) ? trueRange : baseTR + todAlpha * (trueRange - baseTR))
todVolBase.put(todSlot, na(baseVol) ? vol : baseVol + todAlpha * (vol - baseVol))
 
// 1.0 = normal for this time of day.
todVolRaw  = math.sum(trueRange, todSmooth) / math.sum(baseTR, todSmooth)
todRVOLRaw = math.sum(vol, todSmooth) / math.sum(baseVol, todSmooth)
 
todVolatility = daysSeen >= 3 ? todVolRaw : na
todRVOL       = daysSeen >= 3 ? todRVOLRaw : na
 
// Bars per calendar year measured from the chart itself, so annualising is right
// for 24/7 crypto, 23h gold and 6.5h stocks alike.
hvSpan = math.min(bar_index, 1000)
barsPerYear = hvSpan > 0 ? hvSpan * 365.25 * 86400000 / (time - time[hvSpan]) : na
 
histVol = ta.stdev(math.log(close / close[1]), hvLen) * math.sqrt(barsPerYear) * 100
 
adr = request.security(syminfo.tickerid, "D", ta.sma(high - low, adrLen)[1], lookahead=barmerge.lookahead_on)
 
var float dayHigh = na
var float dayLow  = na
 
if newDay or na(dayHigh)
    dayHigh := high
    dayLow  := low
else
    dayHigh := math.max(dayHigh, high)
    dayLow  := math.min(dayLow, low)
 
adrUsed = (dayHigh - dayLow) / adr * 100
 
// Effort (volume) vs result (range), both relative to this time of day.
effortRead =
     na(todRVOL) or na(todVolatility) ? "—" :
     todRVOL >= 1.5 and todVolatility < 0.9 ? "ABSORPTION" :
     todVolatility >= 1.5 and todRVOL < 0.9 ? "THIN MOVE" :
     todRVOL >= 1.3 and todVolatility >= 1.3 ? "EXPANSION" :
     todRVOL < 0.7 and todVolatility < 0.7 ? "QUIET" :
     "BALANCED"
 
bgcolor(showVolBg and regime == 3 ? color.new(sellColor, 88) : showVolBg and regime == 2 ? color.new(buyColor, 92) : na)
barcolor(colorCandles ? (close >= open ? buyColor : sellColor) : na)
 
// Hidden outputs so other scripts (e.g. the strategy) can read them via input.source.
plot(regime, "Volatility Regime (0-3)", display=display.data_window)
plot(atrRank, "ATR Percentile", display=display.data_window)
plot(todVolatility, "Volatility vs Time of Day", display=display.data_window)
plot(todRVOL, "RVOL vs Time of Day", display=display.data_window)
plot(adrUsed, "ADR Used %", display=display.data_window)
 
//━━━━━━━━━━━━━━━━━━━
// POSITION SIZE
//━━━━━━━━━━━━━━━━━━━
// Lots such that hitting the stop loses riskPct of the account. One lot moves
// unitsPerLot x the price change, in the symbol's currency, converted to the
// account's currency at the daily rate.
autoUnits =
     str.startswith(tk, "XAU") or str.startswith(tk, "XPT") or str.startswith(tk, "XPD") or tk == "GOLD" ? 100.0 :
     str.startswith(tk, "XAG") or tk == "SILVER" ? 5000.0 :
     syminfo.type == "futures" ? syminfo.pointvalue :
     syminfo.type == "forex" ? 100000.0 :
     syminfo.pointvalue
unitsPerLot = unitsPerLotIn > 0 ? unitsPerLotIn : autoUnits
lotWord = syminfo.type == "futures" ? "contracts" : "lots"
 
float fxRate = 1.0
if accountCcy != syminfo.currency
    fxRate := request.currency_rate(syminfo.currency, accountCcy, ignore_invalid_currency=true)
 
valuePerMove = unitsPerLot * fxRate
riskMoney = accountSize * riskPct / 100
 
ccySym = switch accountCcy
    "USD" => "$"
    "GBP" => "£"
    "EUR" => "€"
    "JPY" => "¥"
    => accountCcy + " "
 
lotsFor(float dist) =>
    dist > 0 and valuePerMove > 0 ? riskMoney / (dist * valuePerMove) : na
 
// Rounded down, so the real risk is never more than the amount shown.
fmtLots(float x) =>
    na(x) ? "—" : x >= 0.01 ? str.tostring(math.floor(x * 100) / 100, "0.00") : str.tostring(x, "0.0000")
 
fmtMoney(float x) =>
    na(x) ? "—" : ccySym + str.tostring(x, "#,##0.##")
 
//━━━━━━━━━━━━━━━━━━━
// TESTED MARKETS
//━━━━━━━━━━━━━━━━━━━
// What the backtests (research/README.md) say about the signal on this chart.
// 2 = held up, 1 = held up on another timeframe, 0 = not tested, -1 = unproven.
isNasdaq = aliasName == "NAS100USD" or tk == "NAS100USD" or syminfo.root == "NQ" or syminfo.root == "MNQ"
isGold   = tk == "XAUUSD" or aliasName == "XAUUSD" or syminfo.root == "GC" or syminfo.root == "MGC"
lightTF  = tfMins >= 5 and tfMins <= 30
 
int testedLevel = isNasdaq ? (tfMins == 60 ? 2 : 1) : isGold ? -1 : 0
testedText =
     isNasdaq and tfMins == 60 ? "✔ Nasdaq 1h: held up" :
     isNasdaq and lightTF ? "✔ Nasdaq 1h: held up\nthis timeframe: lightly" :
     isNasdaq ? "✔ Nasdaq 1h: held up\nthis timeframe: not tested" :
     isGold ? "⚠ Gold: unproven\n(about breakeven on spot)" :
     "Not tested on this market"
testedLine = str.replace_all(testedText, "\n", ", ")
 
//━━━━━━━━━━━━━━━━━━━
// SIGNALS (80% RULE)
//━━━━━━━━━━━━━━━━━━━
var float sessOpenPx = na
var float sessHi = na
var float sessLo = na
var int   insideRun = 0
var bool  sigTaken = false
var bool  headsUp = false
 
if startNow
    sessOpenPx := open
    sessHi := high
    sessLo := low
    insideRun := 0
    sigTaken := false
    headsUp := false
else if inSession
    sessHi := math.max(sessHi, high)
    sessLo := math.min(sessLo, low)
 
if inSession and not na(prevVAH)
    insideRun := close > prevVAL and close < prevVAH ? insideRun + 1 : 0
 
// Trade state: 0 flat, +/-1 in a long/short, +/-2 waiting to enter on the next open.
var int   tState = 0
var float tEntry = na
var float tStop = na
var float tTarget = na
var int   tEntryBar = na
var line  tStopLn = na
var line  tTgtLn = na
 
var int   sTrades = 0
var int   sWins = 0
var float sGrossWin = 0.0
var float sGrossLoss = 0.0
var float sSumR = 0.0
 
float exitPx = na
string exitWhy = ""
 
// A trade never outlives its session: cancel a pending entry, or exit at the last close.
if tState != 0 and sessionClose
    if math.abs(tState) == 2
        tState := 0
    else
        exitPx := close[1]
        exitWhy := "session ended"
 
if math.abs(tState) == 2
    int side = tState > 0 ? 1 : -1
    if (open - tStop) * side > 0 and (tTarget - open) * side > 0
        tState := side
        tEntry := open
        tEntryBar := bar_index
        if showSignals
            tStopLn := line.new(bar_index, tStop, bar_index, tStop, color=sellColor, style=line.style_dashed)
            tTgtLn := line.new(bar_index, tTarget, bar_index, tTarget, color=buyColor, style=line.style_dashed)
    else
        tState := 0
        sigTaken := false
 
// Stop is assumed hit first when one bar touches both; gaps fill at the open.
if math.abs(tState) == 1 and na(exitPx)
    bool firstBar = bar_index == tEntryBar
    if tState == 1
        if low <= tStop
            exitPx := firstBar ? tStop : math.min(open, tStop)
            exitWhy := "stop hit"
        else if high >= tTarget
            exitPx := firstBar ? tTarget : math.max(open, tTarget)
            exitWhy := "target hit"
    else
        if high >= tStop
            exitPx := firstBar ? tStop : math.max(open, tStop)
            exitWhy := "stop hit"
        else if low <= tTarget
            exitPx := firstBar ? tTarget : math.min(open, tTarget)
            exitWhy := "target hit"
 
if not na(exitPx) and math.abs(tState) == 1
    float pnl = (exitPx - tEntry) * tState - sigCost
    float r = pnl / ((tEntry - tStop) * tState)
    sTrades += 1
    sWins += pnl > 0 ? 1 : 0
    sGrossWin += math.max(pnl, 0)
    sGrossLoss += math.max(-pnl, 0)
    sSumR += r
    int exitBar = sessionClose ? bar_index - 1 : bar_index
    line.set_x2(tStopLn, exitBar)
    line.set_x2(tTgtLn, exitBar)
    alert((tState == 1 ? "BUY " : "SELL ") + syminfo.ticker + " closed: " + exitWhy + " at " + str.tostring(exitPx, format.mintick) + ", " + (r >= 0 ? "+" : "") + str.tostring(r, "0.0") + "R", alert.freq_once_per_bar)
    if showSignals
        label.new(exitBar, exitPx, (r >= 0 ? "+" : "") + str.tostring(r, "0.0") + "R", style=label.style_label_left, color=color.new(color.black, 100), textcolor=r >= 0 ? buyColor : sellColor, size=size.small, text_formatting=text.format_bold)
    tState := 0
 
if math.abs(tState) == 1
    line.set_x2(tStopLn, bar_index)
    line.set_x2(tTgtLn, bar_index)
 
needBars    = math.max(1, math.ceil(acceptMins * 60.0 / timeframe.in_seconds()))
openedBelow = sessOpenPx < prevVAL
openedAbove = sessOpenPx > prevVAH
accText     = acceptMins % 60 == 0 ? str.tostring(acceptMins / 60, "0") + "h" : str.tostring(acceptMins) + " min"
 
canSignal = showSignals and barstate.isconfirmed and inSession and not sigTaken and tState == 0 and not na(prevVAH) and insideRun >= needBars
buySig    = canSignal and openedBelow and sigDirection != "Short only"
sellSig   = canSignal and openedAbove and sigDirection != "Long only"
 
if buySig or sellSig
    tState := buySig ? 2 : -2
    tStop := buySig ? sessLo - stopBufATR * atrVal : sessHi + stopBufATR * atrVal
    tTarget := buySig ? prevVAH : prevVAL
    sigTaken := true
    float riskPts = math.abs(close - tStop)
    float rewardPts = math.abs(tTarget - close)
    alert((buySig ? "BUY " : "SELL ") + syminfo.ticker + " (" + brokerName + ", 80% rule)" +
         "\nEntry: next candle open, now " + str.tostring(close, format.mintick) +
         "\nStop: " + str.tostring(tStop, format.mintick) + "  (risk " + str.tostring(riskPts, format.mintick) + ")" +
         "\nTarget: " + str.tostring(tTarget, format.mintick) + "  (reward " + str.tostring(rewardPts, format.mintick) + (riskPts > 0 ? ", " + str.tostring(rewardPts / riskPts, "0.0") + "R" : "") + ")" +
         "\nSize: " + fmtLots(lotsFor(riskPts)) + " " + lotWord + " to risk " + fmtMoney(riskMoney) + " (check against your broker)" +
         "\nTested: " + testedLine +
         "\nExits at target, stop or session end.", alert.freq_once_per_bar_close)
    label.new(bar_index, buySig ? low : high, buySig ? "BUY" : "SELL", style=buySig ? label.style_label_up : label.style_label_down, color=buySig ? buyColor : sellColor, textcolor=buySig ? color.white : #00332e, size=size.small, text_formatting=text.format_bold, tooltip="80% rule: opened " + (buySig ? "below" : "above") + " the previous value area and held back inside it.\nTarget " + str.tostring(tTarget, format.mintick) + " · Stop " + str.tostring(tStop, format.mintick))
 
plot(buySig ? 1 : sellSig ? -1 : 0, "80% Rule Signal (1 buy / -1 sell)", display=display.data_window)
 
// A setup this session could still produce, and where its stop would sit now.
watchBuy  = openedBelow and sigDirection != "Short only"
watchSell = openedAbove and sigDirection != "Long only"
setupLive = showSignals and inSession and not sigTaken and tState == 0 and not na(prevVAH) and (watchBuy or watchSell)
wouldStop = watchBuy ? sessLo - stopBufATR * atrVal : sessHi + stopBufATR * atrVal
// It can only fire back inside the value area, so expect entry no better than its edge.
setupEntry = watchBuy ? math.max(close, prevVAL) : math.min(close, prevVAH)
 
// Early warning: price trades back inside the previous value area. Fires on the
// live tick, not the close, so it comes before the signal on every timeframe.
formingNow = setupLive and not headsUp and (watchBuy ? high > prevVAL : low < prevVAH)
 
if formingNow
    headsUp := true
    if earlyAlert
        string sideWord = watchBuy ? "BUY" : "SELL"
        alert(sideWord + " setup forming on " + syminfo.ticker + " (" + brokerName + ", 80% rule)" +
             "\nPrice is back " + (watchBuy ? "above " + str.tostring(prevVAL, format.mintick) : "below " + str.tostring(prevVAH, format.mintick)) + ", inside the previous session's value area." +
             "\nA " + sideWord + " signal follows if closes hold inside for " + accText + "." +
             "\nIf it fires: target " + str.tostring(watchBuy ? prevVAH : prevVAL, format.mintick) + ", stop about " + str.tostring(wouldStop, format.mintick) +
             "\nTested: " + testedLine, alert.freq_once_per_bar)
 
//━━━━━━━━━━━━━━━━━━━
// ALERTS
//━━━━━━━━━━━━━━━━━━━
liveLevels = inSession and not startNow
 
crossPOC = ta.cross(close, devPOC)
breakVAH = ta.crossover(close, devVAH)
breakVAL = ta.crossunder(close, devVAL)
volSpike = ta.crossover(todVolatility, 1.5)
rvolSpike = ta.crossover(todRVOL, 2.0)
 
alertcondition(liveLevels and crossPOC, "Price crossed POC", "{{ticker}} crossed the developing POC at {{close}}")
alertcondition(liveLevels and breakVAH, "Price broke above VAH", "{{ticker}} broke above the developing VAH at {{close}}")
alertcondition(liveLevels and breakVAL, "Price broke below VAL", "{{ticker}} broke below the developing VAL at {{close}}")
alertcondition(regime >= 2 and nz(regime[1]) < 2, "Volatility turned HIGH", "{{ticker}} volatility regime turned HIGH")
alertcondition(regime == 3 and nz(regime[1]) < 3, "Volatility turned EXTREME", "{{ticker}} volatility regime turned EXTREME")
alertcondition(volSpike, "Volatility expansion vs time of day", "{{ticker}} range is running 1.5x+ its normal for this time of day")
alertcondition(rvolSpike, "Volume spike vs time of day", "{{ticker}} volume is running 2x+ its normal for this time of day")
alertcondition(buySig, "80% rule BUY", "{{ticker}} 80% rule BUY: back inside the previous value area from below at {{close}}")
alertcondition(sellSig, "80% rule SELL", "{{ticker}} 80% rule SELL: back inside the previous value area from above at {{close}}")
alertcondition(formingNow, "80% rule setup forming", "{{ticker}} 80% rule setup forming: price is back inside the previous value area at {{close}}")
 
//━━━━━━━━━━━━━━━━━━━
// PROFILE DRAWING
//━━━━━━━━━━━━━━━━━━━
var box[]   profBoxes  = array.new_box()
var line[]  profLines  = array.new_line()
var label[] profLabels = array.new_label()
var array<polyline> profTrails = array.new<polyline>()
 
clearProfile() =>
    while profBoxes.size() > 0
        profBoxes.pop().delete()
    while profLines.size() > 0
        profLines.pop().delete()
    while profLabels.size() > 0
        profLabels.pop().delete()
    while profTrails.size() > 0
        profTrails.pop().delete()
 
// A horizontal level with its name and price printed at the right-hand end.
drawLevel(int x1, int x2, float price, string name, color c, string style, int width) =>
    profLines.push(line.new(x1, price, x2, price, color=c, style=style, width=width))
    profLabels.push(label.new(x2, price, name + " " + str.tostring(price, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=c, size=size.small, text_formatting=text.format_bold))
 
drawTrail(array<chart.point> pts, color c, int width) =>
    if pts.size() >= 2 and pts.size() <= 10000
        profTrails.push(polyline.new(pts, line_color=c, line_width=width))
 
drawProfile(Profile p, int startBar, int x0, int lineEnd, int pocI, int vaLo, int vaHi) =>
    int n = p.vol.size()
    float maxVol = n > 0 ? p.vol.max() : 0.0
 
    if maxVol > 0
        float pad = p.step * 0.1
 
        for i = 0 to n - 1
            float v = p.vol.get(i)
 
            if v > 0
                int w = math.max(1, math.round(v / maxVol * profileWidth))
                float top = p.rowTop(i) - pad
                float bot = p.rowBottom(i) + pad
                bool isPOC = i == pocI
                int transp = isPOC ? 0 : i >= vaLo and i <= vaHi ? 35 : 75
                color edge = isPOC ? pocColor : na
 
                if showSplit
                    int wb = math.round(p.buy.get(i) / v * w)
 
                    if wb > 0
                        profBoxes.push(box.new(x0, top, x0 + wb, bot, border_color=edge, bgcolor=color.new(buyColor, transp)))
                    if w - wb > 0
                        profBoxes.push(box.new(x0 + wb, top, x0 + w, bot, border_color=edge, bgcolor=color.new(sellColor, transp)))
                else
                    color rowColor = isPOC ? pocColor : vaColor
                    profBoxes.push(box.new(x0, top, x0 + w, bot, border_color=edge, bgcolor=color.new(rowColor, transp)))
 
        if showProfLvls
            drawLevel(startBar, lineEnd, p.rowMid(pocI), "POC", pocColor, line.style_solid, 2)
            drawLevel(startBar, lineEnd, p.rowTop(vaHi), "VAH", vaColor, line.style_dashed, 1)
            drawLevel(startBar, lineEnd, p.rowBottom(vaLo), "VAL", vaColor, line.style_dashed, 1)
 
// Heavy zones: smoothed row volume at 70%+ of the peak, where price tends to
// stall. Thin zones: 25% or less, between heavier rows, where it tends to move
// fast. Thin rows at the very top or bottom are the profile's tails, not gaps.
drawZones(Profile p, int x1, int x2) =>
    int n = p.vol.size()
    if n >= 5
        float[] s = array.new_float(n, 0.0)
        for i = 0 to n - 1
            int a = math.max(0, i - 1)
            int b = math.min(n - 1, i + 1)
            float acc = 0.0
            for j = a to b
                acc += p.vol.get(j)
            s.set(i, acc / (b - a + 1))
        float peak = s.max()
        int[] kind = array.new_int(n, 0)
        for i = 0 to n - 1
            kind.set(i, s.get(i) >= 0.7 * peak ? 1 : s.get(i) <= 0.25 * peak ? -1 : 0)
        int runStart = 0
        int drawn = 0
        for i = 0 to n - 1
            int k = kind.get(i)
            if i == n - 1 or kind.get(i + 1) != k
                bool heavy = k == 1
                if drawn < 8 and (heavy or (k == -1 and runStart > 0 and i < n - 1))
                    profBoxes.push(box.new(x1, p.rowTop(i), x2, p.rowBottom(runStart), border_color=na, bgcolor=heavy ? color.new(buyColor, 85) : color.new(sellColor, 92), text=heavy ? "heavy volume" : "thin volume", text_size=size.tiny, text_color=heavy ? color.new(buyColor, 25) : color.new(sellColor, 35), text_halign=text.align_left, text_valign=text.align_center))
                    drawn += 1
                runStart := i + 1
 
//━━━━━━━━━━━━━━━━━━━
// DASHBOARD
//━━━━━━━━━━━━━━━━━━━
dashPos = switch dashPosInput
    "Top Left"     => position.top_left
    "Middle Right" => position.middle_right
    "Bottom Right" => position.bottom_right
    "Bottom Left"  => position.bottom_left
    => position.top_right
 
dashSize = switch dashSizeInput
    "Small" => size.small
    "Large" => size.large
    => size.normal
 
// Bright teal panel with bold white text. Emphasis comes from brightness: aqua
// for bullish / elevated, muted teal for quiet, and a lit-up cell for readings
// that need attention.
cPanel    = #00695c
cPanelAlt = #005b50
cSection  = #00796b
cTitle    = #1de9b6
cKey      = #b2dfdb
cText     = #ffffff
cUp       = #64ffda
cMuted    = #a7d8d2
cInk      = #00332e
 
isSimple = dashMode == "Simple"
isMini   = dashMode == "Mini"
 
var table dash = table.new(dashPos, 2, isMini ? 4 : isSimple ? 13 : 25, bgcolor=cPanel, frame_color=cTitle, frame_width=2, border_color=#004d40, border_width=1)
 
// Full-width rows: titles, section headers, the summary and the footer.
if barstate.isfirst and showDash
    array<int> wideRows = isMini ? array.from(0) : isSimple ? array.from(0, 1, 8, 12) : array.from(0, 8, 15, 18, 24)
    for r in wideRows
        table.merge_cells(dash, 0, r, 1, r)
 
fmt(float x, string f, string suffix) =>
    na(x) ? "—" : str.tostring(x, f) + suffix
 
fmtPrice(float x) =>
    na(x) ? "—" : str.tostring(x, format.mintick)
 
// Rounded for reading at a glance: fewer decimals on big prices.
fmtNum(float x) =>
    na(x) ? "—" : close >= 1000 ? str.tostring(x, "0.0") : close >= 10 ? str.tostring(x, "0.00") : str.tostring(x, format.mintick)
 
// ●●○○ for a 0-3 level, ████░░░░ for a percentage.
meterDots(int lvl) =>
    na(lvl) ? "○○○○" : str.repeat("●", lvl + 1) + str.repeat("○", 3 - lvl)
 
meterBar(float pct) =>
    int filled = na(pct) ? 0 : math.max(0, math.min(8, math.round(pct / 100 * 8)))
    str.repeat("█", filled) + str.repeat("░", 8 - filled)
 
ratioColor(float x) =>
    na(x) ? cMuted : x >= 1.5 ? cUp : x <= 0.7 ? cMuted : cText
 
// valueBg lights the value cell up (bright background, dark text); tip shows on hover.
dashRow(int row, string key, string value, color valueColor, color valueBg = na, string tip = "") =>
    color rowBg = row % 2 == 0 ? cPanel : cPanelAlt
    table.cell(dash, 0, row, key, text_color=cKey, text_halign=text.align_left, text_size=dashSize, bgcolor=rowBg, text_formatting=text.format_bold, tooltip=tip)
    table.cell(dash, 1, row, value, text_color=na(valueBg) ? valueColor : cInk, text_halign=text.align_right, text_size=dashSize, bgcolor=na(valueBg) ? rowBg : valueBg, text_formatting=text.format_bold, tooltip=tip)
 
// A full-width line of text across both columns.
dashNote(int row, string txt, color txtColor, color bg, string tip = "") =>
    table.cell(dash, 0, row, txt, text_color=txtColor, text_halign=text.align_left, text_size=dashSize, bgcolor=bg, text_formatting=text.format_bold, tooltip=tip)
 
// Hover explanations, shared by all modes.
tipSummary = "A plain-English read of the rows below."
tipSpeed   = "How fast price is moving compared with the last " + str.tostring(regimeLen) + " candles (ATR percentile). ●○○○ quiet to ●●●● very fast. Faster markets swing further, so stops need more room."
tipVolume  = "Trading activity compared with the usual amount at this time of day (UK). Above 1.5x is busy; below 0.7x is quiet."
tipRange   = "How much of the average day's high-to-low range has already been covered today. Near 100%, big new moves are less likely."
tipValue   = "Fair value zone (value area): where " + str.tostring(valueAreaPct, "0") + "% of this session's volume traded. Price tends to come back to it; leaving it on strong volume can start a trend."
tipPOC     = "Busiest price (POC): the single price with the most volume this session. It often acts like a magnet."
tipPrevPOC = "Yesterday's busiest price. Until price trades back through it, it stays 'naked' and often gets revisited."
tipWeekPOC = "Last week's busiest price, a bigger-picture level that price often returns to. Its value area is drawn on the chart as dotted lines."
tipDelta   = "Estimated buying minus selling volume this session, from where each candle closed in its range."
tipATR     = "Average True Range: the typical candle size over the last " + str.tostring(atrLen) + " candles, in price and as % of price."
tipToD     = "Candle size compared with the usual for this time of day (UK). 1.00x = normal."
tipTrend   = "Whether volatility is rising (EXPANDING) or falling (CONTRACTING): fast ATR vs slow ATR."
tipHV      = "Historical volatility: how much price moves, scaled to a yearly %."
tipEffort  = "Volume vs movement. ABSORPTION: heavy volume, little movement (orders being soaked up). THIN MOVE: big move on light volume (fragile). EXPANSION: both high."
tipProfile = "Which candles the volume profile is built from."
tipSignal  = "80% rule. BUY: the day opened below yesterday's fair value, got back inside and held for " + str.tostring(acceptMins) + " minutes; target the top of that zone. SELL is the opposite. At most one a day. Held up in testing on Nasdaq; unproven on gold."
tipRecord  = "How the signals have done on this chart and timeframe, history included. Past results don't guarantee future ones."
tipTested  = "What the backtests (2024-2026, after costs, 1h) found for this market. Nasdaq: profitable on futures and CFD data and in both halves of the period. Gold: strong on futures but about breakeven on spot gold. Other markets weren't tested." + (acceptMins == 60 ? "" : " The tests used 60-minute acceptance; yours is set to " + str.tostring(acceptMins) + ".")
tipSize    = "Lots to trade so that hitting the stop loses " + str.tostring(riskPct) + "% of a " + fmtMoney(accountSize) + " account (set yours in Position Size). Uses the open trade's stop. While a setup is building, it uses the distance from where the signal would trigger (back inside the value area) to where its stop is now; that stop moves if the session makes a new extreme, so recheck when the signal fires. Here 1 lot = " + str.tostring(unitsPerLot, "#,##0.##") + " units of " + syminfo.ticker + ". Brokers differ, so check one size against your broker's order ticket before relying on it."
tipSource  = "Every price, level, stop and target comes from your chart's broker. Volume is borrowed only when the broker publishes none (FOREX.com doesn't on TradingView); spot FX, gold and CFD volume is tick volume, which tracks real volume reasonably well."
 
dashTitle(int row, string title, bool isMain = false) =>
    table.cell(dash, 0, row, title, text_color=isMain ? cInk : cText, text_halign=text.align_center, text_size=dashSize, bgcolor=isMain ? cTitle : cSection, text_formatting=text.format_bold)
 
//━━━━━━━━━━━━━━━━━━━
// RENDER (LAST BAR)
//━━━━━━━━━━━━━━━━━━━
if barstate.islast
    clearProfile()
 
    Profile shown = sess
    int shownStart = sessStartBar
    string modeText = "Session · " + (isCustom ? customSession : sessionAnchor)
    bool showingLast = false
 
    if profileMode == "Lookback"
        int n = math.min(lookbackBars, bar_index + 1)
        float pHi = high
        float pLo = low
 
        for i = 0 to n - 1
            pHi := math.max(pHi, high[i])
            pLo := math.min(pLo, low[i])
 
        float pStep = math.max((pHi - pLo) / profileRows, syminfo.mintick)
        Profile lb = Profile.new(array.new_float(profileRows, 0.0), array.new_float(profileRows, 0.0), pLo, pStep)
 
        for i = 0 to n - 1
            lb.addBar(high[i], low[i], vol[i], buyVol[i])
 
        shown := lb
        shownStart := bar_index - n + 1
        modeText := "Lookback · " + str.tostring(n) + " bars"
    else if sess.pocIndex() < 0 and not na(lastSess)
        // Nothing traded yet this session (e.g. the volume feed is in its daily break).
        shown := lastSess
        shownStart := lastSessStart
        showingLast := true
        modeText := modeText + " (last)"
 
    int pocI = shown.pocIndex()
    [pVaLo, pVaHi] = shown.valueArea(pocI, valueAreaPct)
 
    float pocPrice = pocI >= 0 ? shown.rowMid(pocI) : na
    float vahPrice = pocI >= 0 ? shown.rowTop(pVaHi) : na
    float valPrice = pocI >= 0 ? shown.rowBottom(pVaLo) : na
 
    int profX0 = placement == "Right" or na(shownStart) ? bar_index + profileOffset : shownStart
    int profRight = math.max(profX0 + profileWidth, bar_index)
    int levelX = profRight + levelLabelGap
 
    if pocI >= 0
        if showZones
            drawZones(shown, na(shownStart) ? profX0 : shownStart, profRight)
        drawProfile(shown, shownStart, profX0, profRight, pocI, pVaLo, pVaHi)
 
    // Current session only, labelled one column right of the profile's own levels.
    if not showHistory
        if showDevPOC
            drawTrail(devPocPts, pocColor, 2)
        if showDevVA
            drawTrail(devVahPts, vaColor, 1)
            drawTrail(devValPts, vaColor, 1)
 
    bool showPrev = showPrevLevels and not na(prevPOC) and not showingLast
    bool prevIsNaked = false
 
    for [i, ln] in nakedLines
        float y = ln.get_y1()
        ln.set_x2(levelX)
 
        // Yesterday's POC stays naked until revisited; fold it into the Prev POC label.
        if showPrev and y == prevPOC
            prevIsNaked := true
        else
            int t = nakedTimes.get(i)
            string dateText = str.tostring(dayofmonth(t, "Europe/London")) + "/" + str.tostring(month(t, "Europe/London"))
            profLabels.push(label.new(levelX, y, "Naked POC " + str.tostring(y, format.mintick) + " (" + dateText + ")", style=label.style_label_left, color=color.new(color.black, 100), textcolor=pocColor, size=size.small, text_formatting=text.format_bold))
 
    if showPrev
        drawLevel(prevSetBar, levelX, prevPOC, prevIsNaked ? "Prev POC (naked)" : "Prev POC", color.new(pocColor, 40), line.style_solid, 1)
        drawLevel(prevSetBar, levelX, prevVAH, "Prev VAH", color.new(vaColor, 40), line.style_dashed, 1)
        drawLevel(prevSetBar, levelX, prevVAL, "Prev VAL", color.new(vaColor, 40), line.style_dashed, 1)
 
    if showWeek and not na(pwPOC)
        drawLevel(pwSetBar, levelX, pwPOC, "Last Week POC", color.new(pocColor, 40), line.style_dotted, 1)
        drawLevel(pwSetBar, levelX, pwVAH, "Last Week VAH", color.new(vaColor, 40), line.style_dotted, 1)
        drawLevel(pwSetBar, levelX, pwVAL, "Last Week VAL", color.new(vaColor, 40), line.style_dotted, 1)
 
    if showDash
        float totVol = shown.vol.size() > 0 ? shown.vol.sum() : 0.0
        float totBuy = shown.buy.size() > 0 ? shown.buy.sum() : 0.0
        float deltaPct = totVol > 0 ? (2 * totBuy - totVol) / totVol * 100 : na
 
        string pvText = na(vahPrice) ? "—" : close > vahPrice ? "ABOVE VALUE" : close < valPrice ? "BELOW VALUE" : "IN VALUE"
        string pvArrow = pvText == "ABOVE VALUE" ? "▲ " : pvText == "BELOW VALUE" ? "▼ " : pvText == "IN VALUE" ? "● " : ""
        color pvColor = pvText == "ABOVE VALUE" ? cUp : pvText == "BELOW VALUE" ? cText : cMuted
 
        string regimeText = switch regime
            0 => "LOW"
            1 => "NORMAL"
            2 => "HIGH"
            3 => "EXTREME"
            => "—"
        color regimeColor = regime == 2 ? cUp : regime == 0 ? cMuted : cText
        color regimeBg = regime == 3 ? cText : na
 
        color trendColor = volTrend == "EXPANDING" ? cUp : volTrend == "CONTRACTING" ? cMuted : cText
        color adrColor = adrUsed >= 75 ? cUp : cText
        color adrBg = adrUsed >= 100 ? cText : na
        color effortColor = effortRead == "EXPANSION" ? cUp : effortRead == "QUIET" or effortRead == "—" ? cMuted : cText
        color effortBg = effortRead == "ABSORPTION" or effortRead == "THIN MOVE" ? cText : na
 
        color sigColor = not showSignals or sigTaken or na(prevVAH) ? cMuted : cText
        color sigBg = tState > 0 ? cUp : tState < 0 ? cText : na
        float pf = sGrossLoss > 0 ? sGrossWin / sGrossLoss : na
        color recColor = sTrades == 0 ? cMuted : sSumR >= 0 ? cUp : cText
 
        string speedWord = switch regime
            0 => "Quiet"
            1 => "Normal"
            2 => "Fast"
            3 => "Very fast"
            => "Warming up"
        string priceIs = na(vahPrice) ? "—" : close > vahPrice ? "▲ " + fmtNum(close - vahPrice) + " above fair value" : close < valPrice ? "▼ " + fmtNum(valPrice - close) + " below fair value" : "● inside fair value"
        string progress = insideRun > 0 ? " (" + str.tostring(insideRun) + "/" + str.tostring(needBars) + ")" : ""
 
        // Size for the open trade, or for the setup from where it would trigger.
        float sizeDist = tState != 0 ? math.abs((math.abs(tState) == 1 ? tEntry : close) - tStop) : setupLive ? math.abs(setupEntry - wouldStop) : na
        float lots = lotsFor(sizeDist)
        string lotsText = fmtLots(lots) + " " + lotWord
        string noSize = na(fxRate) ? "— (no " + accountCcy + " rate)" : "— (set Units per Lot)"
 
        color testedColor = testedLevel == 2 ? cUp : testedLevel == 1 ? cText : cMuted
        color testedBg = testedLevel == -1 ? cText : na
 
        string srcText = not volEverSeen ? "⚠ No volume found for " + syminfo.ticker + " — set a Custom Symbol" : "Prices: " + brokerName + " · Volume: " + volSourceName + (totVol > 0 ? "" : " · none yet this session")
        int footRow = isSimple ? 12 : 24
 
        if isMini
            string miniSig =
                 not showSignals ? "Signals off" :
                 tState == 1 ? "BUY → " + fmtNum(tTarget) :
                 tState == -1 ? "SELL → " + fmtNum(tTarget) :
                 math.abs(tState) == 2 ? "Entering next candle" :
                 sigTaken ? "Done for today" :
                 na(prevVAH) ? "Waiting for data" :
                 watchBuy ? (headsUp ? "BUY forming" : "Watching BUY") + progress :
                 watchSell ? (headsUp ? "SELL forming" : "Watching SELL") + progress :
                 "No setup today"
 
            // No room for a footer, so a missing volume feed takes over the title.
            if volEverSeen
                dashTitle(0, "VP+VOL · " + syminfo.ticker, true)
            else
                dashNote(0, "⚠ No volume: set a Custom Symbol", cInk, cText, tipSource)
            dashRow(1, "Signal", miniSig, sigColor, sigBg, tip=tipSignal)
            dashRow(2, "Speed", meterDots(regime) + "  " + speedWord, regimeColor, regimeBg, tip=tipSpeed)
            dashRow(3, "Price", priceIs, pvColor, tip=tipValue)
        else if isSimple
            string locWord = na(vahPrice) ? "no fair value yet" : close > vahPrice ? "above fair value" : close < valPrice ? "below fair value" : "inside fair value"
            string rangeWord = na(adrUsed) ? "" : adrUsed >= 100 ? "Daily range used up: moves may stall." : adrUsed >= 75 ? "Most of today's range is used." : "Plenty of range left today."
            string summary = speedWord + (na(regime) ? "" : " market") + ", price " + locWord + "." + (rangeWord == "" ? "" : "\n" + rangeWord)
 
            string volText = na(todRVOL) ? "— (needs 3 days)" : (todRVOL >= 1.5 ? "Busier than usual" : todRVOL <= 0.7 ? "Quieter than usual" : "About usual") + " (" + str.tostring(todRVOL, "0.0") + "x)"
            string pocText = na(pocPrice) ? "—" : fmtNum(pocPrice) + (pocPrice >= close ? "  (▲ " : "  (▼ ") + fmtNum(math.abs(pocPrice - close)) + " away)"
 
            string sigText =
                 not showSignals ? "Signals off" :
                 tState == 1 ? "BUY active\ntarget " + fmtNum(tTarget) + " · stop " + fmtNum(tStop) :
                 tState == -1 ? "SELL active\ntarget " + fmtNum(tTarget) + " · stop " + fmtNum(tStop) :
                 math.abs(tState) == 2 ? "Signal fired\nentering next candle" :
                 sigTaken ? "Done for today" :
                 na(prevVAH) ? "Waiting for a full\nday of data" :
                 watchBuy ? (headsUp ? "BUY setup forming" : "Watching for a BUY") + "\nneeds " + accText + " back above " + fmtNum(prevVAL) + progress :
                 watchSell ? (headsUp ? "SELL setup forming" : "Watching for a SELL") + "\nneeds " + accText + " back below " + fmtNum(prevVAH) + progress :
                 openedBelow or openedAbove ? "No setup today\n(that direction is off)" :
                 "No setup today\n(opened in yesterday's fair value)"
            string sizeText =
                 na(sizeDist) ? "No trade to size" :
                 na(lots) ? noSize :
                 lotsText + (tState != 0 ? "" : " if it fires") + "\nrisking " + fmtMoney(riskMoney) + " · stop " + fmtNum(sizeDist) + " away"
 
            dashTitle(0, "MARKET SUMMARY · " + syminfo.ticker, true)
            dashNote(1, summary, cText, cPanelAlt, tipSummary)
            dashRow(2, "Speed", meterDots(regime) + "  " + speedWord, regimeColor, regimeBg, tip=tipSpeed)
            dashRow(3, "Volume", volText, ratioColor(todRVOL), tip=tipVolume)
            dashRow(4, "Daily range used", meterBar(adrUsed) + "  " + fmt(adrUsed, "0", "%"), adrColor, adrBg, tip=tipRange)
            dashRow(5, "Fair value zone", fmtNum(valPrice) + " – " + fmtNum(vahPrice), cText, tip=tipValue)
            dashRow(6, "Price is", priceIs, pvColor, tip=tipValue)
            dashRow(7, "Busiest price", pocText, cText, tip=tipPOC)
            dashTitle(8, "SIGNAL")
            dashRow(9, "Signal", sigText, sigColor, sigBg, tip=tipSignal)
            dashRow(10, "Backtested", testedText, testedColor, testedBg, tip=tipTested)
            dashRow(11, "Position size", sizeText, na(sizeDist) ? cMuted : cText, tip=tipSize)
        else
            string sigStatus =
                 not showSignals ? "Off" :
                 tState == 1 ? "LONG → " + fmtPrice(tTarget) :
                 tState == -1 ? "SHORT → " + fmtPrice(tTarget) :
                 math.abs(tState) == 2 ? "Entering next bar" :
                 sigTaken ? "Done this session" :
                 na(prevVAH) ? "—" :
                 watchBuy ? (headsUp ? "BUY forming · " : "Below value · ") + str.tostring(insideRun) + "/" + str.tostring(needBars) + " bars in" :
                 watchSell ? (headsUp ? "SELL forming · " : "Above value · ") + str.tostring(insideRun) + "/" + str.tostring(needBars) + " bars in" :
                 openedBelow or openedAbove ? "No setup (direction off)" :
                 "No setup (opened in value)"
            string wkText = sessionAnchor == "Week" ? "= Prev POC" : not showWeekLevels ? "Off" : fmtPrice(pwPOC)
            string proSize = na(sizeDist) ? "—" : na(lots) ? noSize : lotsText + " · " + fmtMoney(riskMoney) + (tState != 0 ? "" : " if it fires")
 
            dashTitle(0, "VOLUME PROFILE + VOLATILITY", true)
            dashRow(1, "Profile", modeText, cText, tip=tipProfile)
            dashRow(2, "POC", fmtPrice(pocPrice), cText, tip=tipPOC)
            dashRow(3, "Value Area", fmtPrice(valPrice) + " – " + fmtPrice(vahPrice), cText, tip=tipValue)
            dashRow(4, "Price vs Value", pvArrow + pvText, pvColor, tip=tipValue)
            dashRow(5, "Profile Delta", (deltaPct > 0 ? "+" : "") + fmt(deltaPct, "0.0", "%"), na(deltaPct) ? cMuted : deltaPct >= 0 ? cUp : cText, tip=tipDelta)
            dashRow(6, "Prev POC", fmtPrice(prevPOC), cText, tip=tipPrevPOC)
            dashRow(7, "Last Week POC", wkText, cText, tip=tipWeekPOC)
 
            dashTitle(8, "VOLATILITY")
            dashRow(9, "Regime", meterDots(regime) + "  " + regimeText + (na(atrRank) ? "" : " (" + str.tostring(atrRank, "0") + "%ile)"), regimeColor, regimeBg, tip=tipSpeed)
            dashRow(10, "ATR " + str.tostring(atrLen), fmtPrice(atrVal) + "  (" + fmt(atrPctOfPrice, "0.00", "%") + ")", cText, tip=tipATR)
            dashRow(11, "vs Time of Day", fmt(todVolatility, "0.00", "x"), ratioColor(todVolatility), tip=tipToD)
            dashRow(12, "Trend", volTrend, trendColor, tip=tipTrend)
            dashRow(13, "Hist Vol (ann.)", fmt(histVol, "0.0", "%"), cText, tip=tipHV)
            dashRow(14, "ADR Used", meterBar(adrUsed) + "  " + fmt(adrUsed, "0", "%") + " of " + fmtPrice(adr), adrColor, adrBg, tip=tipRange)
 
            dashTitle(15, "VOLUME")
            dashRow(16, "RVOL vs Time of Day", fmt(todRVOL, "0.00", "x"), ratioColor(todRVOL), tip=tipVolume)
            dashRow(17, "Effort vs Result", effortRead, effortColor, effortBg, tip=tipEffort)
 
            dashTitle(18, "SIGNALS · 80% RULE")
            dashRow(19, "Status", sigStatus, sigColor, sigBg, tip=tipSignal)
            dashRow(20, "Backtest", testedLine, testedColor, testedBg, tip=tipTested)
            dashRow(21, "Trades (this chart)", sTrades == 0 ? "none yet" : str.tostring(sTrades) + " · " + str.tostring(100.0 * sWins / sTrades, "0") + "% win", sTrades == 0 ? cMuted : cText, tip=tipRecord)
            dashRow(22, "Profit Factor · Avg", sTrades == 0 ? "—" : fmt(pf, "0.00", "") + " · " + (sSumR >= 0 ? "+" : "") + str.tostring(sSumR / sTrades, "0.00") + "R", recColor, tip=tipRecord)
            dashRow(23, "Position Size", proSize, na(sizeDist) ? cMuted : cText, tip=tipSize)
 
        if not isMini
            table.cell(dash, 0, footRow, srcText, text_color=volEverSeen ? cKey : cInk, bgcolor=volEverSeen ? cPanel : cText, text_size=size.small, text_formatting=text.format_bold, tooltip=tipSource)

← 返回列表