MTF Swing Range Volume Profile

SpinTrades · study · 801 行 · 点赞 180 · TradingView 原页

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

Pine Script

//@version=6
// MTF Swing Range Volume Profile
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Volume profile of the latest swing leg, with the swing found by an ATR reversal on a timeframe you pick (D by
// default). Draws the swing high and low, POC, 70% value area, a histogram and up to six low-volume nodes (LVNs),
// each with a shelf line and a fill state.
//
// Features:
//   - Slow swing layer (D) and an optional fast one (60m), each built from source bars set by its own timeframe,
//     so its levels match on every chart from 1m up to that timeframe
//   - Switches to the swing in progress (LEG H / LEG L) at swing-timeframe closes, before the next swing confirms
//   - LVNs marked by depth, with a shelf line on the steeper side; filled LVNs fade
//   - Reads only completed source bars, so a reload and the live chart agree (exceptions in the description)
//
// How it works, settings and limits: see the script's description.
 
indicator("MTF Swing Range Volume Profile", shorttitle = "MTF Swing Range VP", overlay = true, max_lines_count = 100, max_boxes_count = 150, max_labels_count = 30)
 
grpA    = "Swing"
showS   = input.bool(true, "Slow swing", group = grpA, inline = "s")
swingTf = input.timeframe("D", "", group = grpA, inline = "s", tooltip = "Built from source bars of 5m for a 5m to 1H swing, 15m above 1H and below D, 60m from D to below W, 4H from W to below M, and D from M up, on every chart, so its levels match across chart timeframes with the same session and adjustment settings (on stocks, set intraday charts to regular hours to match the D chart). Off when the chart timeframe is higher than the swing, and on swings under 5m. Chart = the chart's own timeframe (its levels then change with the chart).")
showF   = input.bool(false, "Fast swing", group = grpA, inline = "f")
fastTf  = input.timeframe("60", "", group = grpA, inline = "f", tooltip = "Same source rule as the slow swing: source bars of 5m for a 5m to 1H swing, 15m above 1H and below D, 60m from D to below W, 4H from W to below M, and D from M up, on every chart, so its levels match across chart timeframes with the same session and adjustment settings. Off when the chart timeframe is higher than the swing, and on swings under 5m. Where the two layers share a price, the slow layer's line and label color win, so keep the fast swing on a lower timeframe than the slow one.", display = display.none)
kAtr    = input.float(3.0, "Slow swing reversal (ATRs)", minval = 0.5, step = 0.25, group = grpA, tooltip = "A swing high is confirmed on the first source bar after the high whose low is at least this many ATRs below it (a swing low the same way up). ATR = simple average of the true ranges of the last 14 completed periods of the swing timeframe like TradingView's ATR with Smoothing set to SMA (its default, RMA, is Wilder's smoothing).", display = display.none)
kFast   = input.float(4.0, "Fast swing reversal (ATRs)", minval = 0.5, step = 0.25, group = grpA, tooltip = "Same rule as the slow swing, on the fast swing's timeframe.", display = display.none)
swapMode = input.string("Price leaves the leg", "Switch to the swing in progress", options = ["Price leaves the leg", "One leg height beyond", "Never"], group = grpA, tooltip = "The profile covers the last completed swing (SWING H / SWING L) until the next swing confirms, which can take a while when price runs away without a big enough pullback. This sets when it switches early to the swing in progress: from the last confirmed swing point to the highest high or lowest low so far, labeled LEG H / LEG L. It switches, and the LEG end moves, only when a period of the swing timeframe closes (for a D swing, the daily close), so a move during the day doesn't redraw anything until the day closes.\n\nPrice leaves the leg (default): switches on the first swing-timeframe close beyond where the completed leg started, so the levels follow price soon after it leaves the old range. When the swing later confirms, only the label changes.\n\nOne leg height beyond: waits until a swing-timeframe close is a full leg height past that point. The old range stays drawn longer, and if price never gets that far, the profile jumps all at once when the next swing confirms.\n\nNever: always shows the last completed swing.", display = display.none)
bool  autoSw = swapMode != "Never"
float swapK  = swapMode == "One leg height beyond" ? 1.0 : 0.0
grpP    = "Profile"
showHist = input.bool(true, "Draw the slow histogram", group = grpP)
showHistF = input.bool(false, "Draw the fast histogram", group = grpP)
showVA  = input.bool(true, "Draw POC and value area", group = grpP)
showShelf = input.bool(true, "Shelf line on the steeper side of each LVN", group = grpP, tooltip = "The biggest one-row jump in volume between an LVN's edge and the nearest peak on that side (where volume stops rising), on the steeper side. Not drawn when it sits on the LVN's edge. Display aid.")
fillMode = input.string("Fade, no label", "Filled LVNs", options = ["Fade, no label", "Fade with label", "Hide", "Off"], group = grpP, tooltip = "An LVN counts as filled once volume equal to one average row per row of its height has traded inside it since the swing confirmed (not tracked on LEG profiles).\n\nFade, no label (default): fainter box and shelf line, and its label is removed.\n\nFade with label: the same, plus a faint label that adds 'filled' ('D LVN filled', 'D SHELF (LVN filled)').\n\nHide: removes the LVN's box, shelf line and label.\n\nOff: fill is ignored and filled LVNs draw like the others.\n\nDisplay aid.", display = display.none)
grpLabels = "Display - Labels"
showLab = input.bool(true, "Show Labels", group = grpLabels)
floatingLabelOffset = input.int(1, "Offset (bars)", minval = -20, maxval = 50, group = grpLabels, tooltip = "Bars right of the current bar (negative = left)", display = display.none)
showPriceInLabel = input.bool(false, "Show Price in Label", group = grpLabels)
labelTextSize = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal", "Large"], group = grpLabels, display = display.none)
labelBackgroundColor = input.color(#2e2e2e, "Background Color", group = grpLabels)
labelBackgroundTransparency = input.int(20, "Transparency", minval = 0, maxval = 100, group = grpLabels, display = display.none)
 
// label helpers
getSize(sizeStr) =>
    switch sizeStr
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
// other minute timeframes: "45" -> "45m", "180" -> "3H"; anything else as typed ("2D", "3M")
f_tfMinutes(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec > 0 and sec < 86400 and sec % 60 == 0 ? (sec % 3600 == 0 ? str.tostring(int(sec / 3600)) + "H" : str.tostring(int(sec / 60)) + "m") : tf
getTimeframeLabel(tf) =>
    switch tf
        "1" => "1m"
        "3" => "3m"
        "5" => "5m"
        "15" => "15m"
        "30" => "30m"
        "60" => "1H"
        "120" => "2H"
        "240" => "4H"
        "480" => "8H"
        "720" => "12H"
        "1D" => "D"
        "D" => "D"
        "1W" => "W"
        "W" => "W"
        "1M" => "M"
        "M" => "M"
        => f_tfMinutes(tf)
// readable chips: chip text keeps its line's color unless that color reads below 3:1 on the chip background;
// then it is walked toward white (black on a light background) until it reaches 3.5:1. Line colors are untouched.
srgbLin(float v) =>
    v <= 0.03928 ? v / 12.92 : math.pow((v + 0.055) / 1.055, 2.4)
relLum(color c) =>
    0.2126 * srgbLin(color.r(c) / 255.0) + 0.7152 * srgbLin(color.g(c) / 255.0) + 0.0722 * srgbLin(color.b(c) / 255.0)
contrastOn(color fg, color bg) =>
    lf = relLum(fg)
    lb = relLum(bg)
    (math.max(lf, lb) + 0.05) / (math.min(lf, lb) + 0.05)
readableOn(color fg, color bg) =>
    color out = fg
    if contrastOn(fg, bg) < 3.0
        float tr = relLum(bg) < 0.18 ? 255.0 : 0.0
        float srcR = color.r(fg)
        float srcG = color.g(fg)
        float srcB = color.b(fg)
        for i = 1 to 12
            k = i / 12.0
            cand = color.rgb(srcR + (tr - srcR) * k, srcG + (tr - srcG) * k, srcB + (tr - srcB) * k, 0)
            out := cand
            if contrastOn(cand, bg) >= 3.5
                break
    out
 
grpStH = "Style - Slow swing"
cSwH   = input.color(#2962FF, "Swing H/L", group = grpStH, inline = "h")
cVaH   = input.color(#4FC3F7, "POC / VA", group = grpStH, inline = "h")
cLvH   = input.color(#FFD54F, "LVN", group = grpStH, inline = "h")
cHsH   = input.color(#787b86, "Histogram", group = grpStH, inline = "h2")
wSlowIn = input.string("By timeframe", "Line width", options = ["By timeframe", "1", "2", "3", "4", "5"], group = grpStH, inline = "h2", tooltip = "By timeframe: 1 px under 4H, 2 px from 4H to under W, 3 px from W up.", display = display.none)
grpStL = "Style - Fast swing"
cSwL   = input.color(#7E57C2, "Swing H/L", group = grpStL, inline = "l")
cVaL   = input.color(#CE93D8, "POC / VA", group = grpStL, inline = "l")
cLvL   = input.color(#FFA726, "LVN", group = grpStL, inline = "l")
cHsL   = input.color(#7E57C2, "Histogram", group = grpStL, inline = "l2")
wFastIn = input.string("By timeframe", "Line width", options = ["By timeframe", "1", "2", "3", "4", "5"], group = grpStL, inline = "l2", tooltip = "By timeframe: 1 px under 4H, 2 px from 4H to under W, 3 px from W up.", display = display.none)
grpStX = "Style - Lines"
stSwIn  = input.string("Solid", "Swing H/L", options = ["Solid", "Dashed", "Dotted"], group = grpStX, inline = "x1", display = display.none)
stPocIn = input.string("Dotted", "POC", options = ["Solid", "Dashed", "Dotted"], group = grpStX, inline = "x1", display = display.none)
stVaIn  = input.string("Dashed", "VAH / VAL", options = ["Solid", "Dashed", "Dotted"], group = grpStX, inline = "x2", display = display.none)
stShIn  = input.string("Solid", "Shelf", options = ["Solid", "Dashed", "Dotted"], group = grpStX, inline = "x2", display = display.none)
histPct = input.int(30, "Histogram width (% of the leg's bars)", minval = 5, maxval = 100, group = grpStX, tooltip = "Width of the widest histogram row, as a share of the chart bars in the leg (at least 5 bars, never wider than the leg).", display = display.none)
grpAdv  = "Advanced"
nRows   = input.int(24, "Number of rows", minval = 10, maxval = 28, group = grpAdv, tooltip = "Rows of the histogram and of the LVN search. POC, value area and LVN edges use rows 4 times finer.", display = display.none)
promIn  = input.float(0.10, "LVN minimum depth (share of the POC row)", minval = 0.02, maxval = 0.9, step = 0.01, group = grpAdv, tooltip = "How far a valley must sit below the lower of the two peaks around it (the highest row on each side before the profile drops below the valley), as a share of the POC row's volume (0.10 = 10%).", display = display.none)
strict  = input.bool(false, "Stricter LVNs (deepest only, 20%)", group = grpAdv, tooltip = "Raises the minimum depth to 0.20 (20%) of the POC row's volume. No effect when the setting above is already 0.20 or more.")
promMin = strict ? math.max(promIn, 0.20) : promIn
lvEdgeIn = input.string("Narrow", "LVN edges", options = ["Narrow", "Wide"], group = grpAdv, tooltip = "Where an LVN box's top and bottom sit, measured from the valley's thinnest row up toward the lower of the two peaks around it.\n\nNarrow (default): at 25% of that depth, so the box marks the thin core of the valley.\n\nWide: at half the depth, so the box also covers the slopes where volume is still building back up, so boxes are taller.\n\nThe same valleys qualify either way; only the box edges move.", display = display.none)
float lvEdge = lvEdgeIn == "Wide" ? 0.5 : 0.25
cHistA = color.new(cHsH, 80)
cHistV = color.new(cHsH, 55)
f_lineStyle(string s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
stSw = f_lineStyle(stSwIn)
stPoc = f_lineStyle(stPocIn)
stVa = f_lineStyle(stVaIn)
stSh = f_lineStyle(stShIn)
f_tfWidth(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec >= 604800 ? 3 : sec >= 14400 ? 2 : 1
// prices drawn by the slow swing (the fast swing skips these lines and merges its chip)
var array<float> hiPx = array.new_float()
f_key(float p) => math.round(p / syminfo.mintick) * syminfo.mintick
 
// ---------- source bars: set by each layer's swing timeframe only, never by the chart
// "Chart" (an empty timeframe) means the chart's own timeframe
string sTf = swingTf == "" ? timeframe.period : swingTf
string fTf = fastTf == "" ? timeframe.period : fastTf
// 5m bars for a 5m to 1H swing, 15m above 1H and below D, 60m from D to below W, 4H from W to below M, D from M up;
// "simple" keeps the result simple, as request.security's lookahead argument requires
f_srcTf(simple string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec <= timeframe.in_seconds("60") ? "5" : sec < timeframe.in_seconds("1D") ? "15" : sec < timeframe.in_seconds("1W") ? "60" : sec < timeframe.in_seconds("1M") ? "240" : "D"
string srcTf = f_srcTf(sTf)
string srcF = f_srcTf(fTf)
// a chart coarser than the source: lower-timeframe request, read the last source bar inside each chart bar
bool sLtf = timeframe.in_seconds() > timeframe.in_seconds(srcTf)
bool fLtf = timeframe.in_seconds() > timeframe.in_seconds(srcF)
MAXB = 5000
// fine rows per histogram row (POC, value area and area edges)
FINE = 4
// source bars each request calculates on, counted back from the latest bar. Without it a request takes the plan's
// bar count for that timeframe (5,000 to 40,000; a lower-timeframe request up to its intrabar limit), so the history
// length would depend on the plan and on the request type
CBC = 20000
// a low-volume area taller than this many rows draws as an outline only
WIDE = 4
 
// levels from a built profile: [poc, vah, val, zone1 lo, zone1 hi, zone1 shelf, zone2 lo, ...]
f_levels(array<float> rv, array<float> rvF, float lo, float hi) =>
    array<float> out = array.new_float()
    float step = (hi - lo) / nRows
    float stF = step / FINE
    int nF = nRows * FINE
    int ip = 0
    for r = 0 to nRows - 1
        if rv.get(r) > rv.get(ip)
            ip := r
    float mx = rv.get(ip)
    if mx > 0
        // POC: the fine row with the most volume inside the widest histogram row, so the POC line crosses the widest
        // bar; the 70% value area grows from it on the fine rows
        int ipF = ip * FINE
        for r = ip * FINE + 1 to ip * FINE + FINE - 1
            if rvF.get(r) > rvF.get(ipF)
                ipF := r
        float totF = rvF.sum()
        int aF = ipF
        int bF = ipF
        float accF = rvF.get(ipF)
        while accF < 0.70 * totF and (aF > 0 or bF < nF - 1)
            float upF = bF < nF - 1 ? rvF.get(bF + 1) : -1.0
            float dnF = aF > 0 ? rvF.get(aF - 1) : -1.0
            if upF >= dnF
                bF += 1
                accF += rvF.get(bF)
            else
                aF -= 1
                accF += rvF.get(aF)
        out.push(math.round_to_mintick(lo + (ipF + 0.5) * stF))
        out.push(math.round_to_mintick(lo + (bF + 1) * stF))
        out.push(math.round_to_mintick(lo + aF * stF))
        // low-volume areas: valleys found on the coarse rows (one row, or a run of equal rows such as an empty gap),
        // edges on the fine rows
        array<float> cLo = array.new_float()
        array<float> cHi = array.new_float()
        array<float> cSh = array.new_float()
        array<float> cPr = array.new_float()
        int rr = 1
        while rr <= nRows - 2
            float x = rv.get(rr)
            int r2 = rr
            while r2 < nRows - 1 and rv.get(r2 + 1) == x
                r2 += 1
            if x < rv.get(rr - 1) and r2 < nRows - 1 and x < rv.get(r2 + 1)
                float lPk = x
                int q = rr - 1
                while q >= 0 and rv.get(q) >= x
                    lPk := math.max(lPk, rv.get(q))
                    q -= 1
                float rPk = x
                q := r2 + 1
                while q < nRows and rv.get(q) >= x
                    rPk := math.max(rPk, rv.get(q))
                    q += 1
                float prom = math.min(lPk, rPk) - x
                if prom >= promMin * mx
                    int za = rr
                    int zb = r2
                    while za > 0 and rv.get(za - 1) <= x + prom * lvEdge
                        za -= 1
                    while zb < nRows - 1 and rv.get(zb + 1) <= x + prom * lvEdge
                        zb += 1
                    float thrF = (x + prom * lvEdge) / FINE
                    // the walk starts at the thinnest fine row inside the valley's own rows, so the box can't land on a
                    // shallower valley elsewhere in the edge window
                    int fm = rr * FINE
                    for q2 = rr * FINE to (r2 + 1) * FINE - 1
                        if rvF.get(q2) < rvF.get(fm)
                            fm := q2
                    int fa = fm
                    int fb = fm
                    int faMin = math.max(0, za * FINE - 2)
                    int fbMax = math.min(nF - 1, (zb + 1) * FINE + 1)
                    while fa > faMin and rvF.get(fa - 1) <= thrF
                        fa -= 1
                    while fb < fbMax and rvF.get(fb + 1) <= thrF
                        fb += 1
                    // shelf: biggest one-row volume jump between each edge and its neighboring peak; keep the steeper
                    int rp = zb + 1
                    while rp < nRows - 1 and rv.get(rp + 1) >= rv.get(rp)
                        rp += 1
                    float bestU = 0.0
                    float pxU = na
                    int jU = fb
                    while jU < math.min(nF - 1, (rp + 1) * FINE - 1)
                        float inc = rvF.get(jU + 1) - rvF.get(jU)
                        if inc > bestU
                            bestU := inc
                            pxU := lo + (jU + 1) * stF
                        jU += 1
                    int rq = za - 1
                    while rq > 0 and rv.get(rq - 1) >= rv.get(rq)
                        rq -= 1
                    float bestD = 0.0
                    float pxD = na
                    int jD = fa
                    while jD > math.max(0, rq * FINE)
                        float inc = rvF.get(jD - 1) - rvF.get(jD)
                        if inc > bestD
                            bestD := inc
                            pxD := lo + jD * stF
                        jD -= 1
                    float shelf = bestU >= bestD ? pxU : pxD
                    float zLoR = math.round_to_mintick(lo + fa * stF)
                    float zHiR = math.round_to_mintick(lo + (fb + 1) * stF)
                    // an area that rounds to less than a tick is dropped; one identical to an area already found keeps
                    // a single slot, with the more prominent valley's shelf
                    int dup = -1
                    if cLo.size() > 0
                        for q3 = 0 to cLo.size() - 1
                            if cLo.get(q3) == zLoR and cHi.get(q3) == zHiR
                                dup := q3
                    if dup >= 0
                        if prom > cPr.get(dup)
                            cSh.set(dup, na(shelf) ? na : math.round_to_mintick(shelf))
                            cPr.set(dup, prom)
                    else if zHiR > zLoR
                        cLo.push(zLoR)
                        cHi.push(zHiR)
                        cSh.push(na(shelf) ? na : math.round_to_mintick(shelf))
                        cPr.push(prom)
            rr := r2 + 1
        // only 6 area slots per layer: keep the 6 most prominent, in price order
        while cPr.size() > 6
            int iMin = cPr.indexof(cPr.min())
            cLo.remove(iMin)
            cHi.remove(iMin)
            cSh.remove(iMin)
            cPr.remove(iMin)
        if cLo.size() > 0
            for j = 0 to cLo.size() - 1
                out.push(cLo.get(j))
                out.push(cHi.get(j))
                out.push(cSh.get(j))
    out
 
// returns [range high, range low, earlier and later source bar time of the range, status (+10 / +20 while showing the
// swing in progress up / down), POC, VAH, VAL, 4 packed histogram numbers, fill bits, 6 area triplets (lo, hi, shelf)]
// status: 0 no completed swing yet, 1 ok, 2 the range starts before the stored source bars, 3 no volume data
// Every input is the previous source bar ([1]), final on live and historical bars alike. A request at or above the
// chart's timeframe is read with lookahead on, a lower-timeframe request with lookahead off (last source bar inside
// the chart bar), so a recalculated chart and a live one show the same thing, one source bar behind.
f_calc(string stf, float k, bool on) =>
    var array<int>   bt = array.new_int()
    var array<float> bh = array.new_float()
    var array<float> bl = array.new_float()
    var array<float> bv = array.new_float()
    var array<float> trs = array.new_float()
    var array<float> rv = array.new_float()
    var array<float> rvF = array.new_float()
    var array<float> lv = array.new_float()
    var float dH = na
    var float dL = na
    var int   dHT = na
    var int   dLT = na
    var float dC = na
    var float prevC = na
    var int   zDir = 0
    var float zExt = na
    var int   zExtT = na
    var float sp0 = na
    var int   st0 = na
    var float sp1 = na
    var int   st1 = na
    var int   key = na
    var int   swapFor = na
    var float oppX = na
    var int   oppT = na
    var float zExtC = na
    var int   zExtTC = na
    var int   formDir = 0
    var float rHi = na
    var float rLo = na
    var int   tA = na
    var int   tB = na
    var int   status = 0
    var float poc = na
    var float vah = na
    var float val = na
    var float h0 = na
    var float h1 = na
    var float h2 = na
    var float h3 = na
    var array<float> zz = array.new_float(18, na)
    var array<float> zf = array.new_float(6, 0.0)
    var float rowAvg = na
    var float fillBits = 0.0
    float pH = high[1]
    float pL = low[1]
    float pC = close[1]
    float pV = nz(volume[1])
    int   pT = time[1]
    // this bar opens a new period, so bar [1] closed the old one
    bool  perEnd = timeframe.change(stf)
    if not on
        status := 0
    bool live = on and not na(pH) and not na(pT)
    // store bar [1]
    if live and (bt.size() == 0 or pT > bt.last())
        bt.push(pT)
        bh.push(pH)
        bl.push(pL)
        bv.push(pV)
        if bt.size() > MAXB
            bt.shift()
            bh.shift()
            bl.shift()
            bv.shift()
    // the period so far
    if live
        if na(dH)
            dH := pH
            dL := pL
            dHT := pT
            dLT := pT
        else
            if pH > dH
                dH := pH
                dHT := pT
            if pL < dL
                dL := pL
                dLT := pT
        dC := pC
    // track the extreme and confirm a swing on bar [1], against the ATR of the periods completed before its own
    if live and zDir != 0 and pT > nz(zExtT)
        float a14 = trs.size() == 14 ? trs.avg() : na
        // nothing confirms while the ATR is zero (flat data would flip the swing on every bar)
        float atrI = a14 > 0 ? a14 : na
        if zDir == 1
            if pH > zExt
                zExt := pH
                zExtT := pT
                oppX := na
            else
                if na(oppX) or pL < oppX
                    oppX := pL
                    oppT := pT
                // the confirming bar itself must reach k ATR below the high, so an old pullback can't qualify later
                if not na(atrI) and zExt - pL >= k * atrI
                    sp0 := sp1
                    st0 := st1
                    sp1 := zExt
                    st1 := zExtT
                    zDir := -1
                    zExt := oppX
                    zExtT := oppT
                    // highest high after the new low, up to this bar
                    oppX := na
                    oppT := na
                    int jj = bt.size() - 1
                    while jj >= 0 and bt.get(jj) > zExtT
                        if na(oppX) or bh.get(jj) >= oppX
                            oppX := bh.get(jj)
                            oppT := bt.get(jj)
                        jj -= 1
        else
            if pL < zExt
                zExt := pL
                zExtT := pT
                oppX := na
            else
                if na(oppX) or pH > oppX
                    oppX := pH
                    oppT := pT
                if not na(atrI) and pH - zExt >= k * atrI
                    sp0 := sp1
                    st0 := st1
                    sp1 := zExt
                    st1 := zExtT
                    zDir := 1
                    zExt := oppX
                    zExtT := oppT
                    // lowest low after the new high, up to this bar
                    oppX := na
                    oppT := na
                    int jj = bt.size() - 1
                    while jj >= 0 and bt.get(jj) > zExtT
                        if na(oppX) or bl.get(jj) <= oppX
                            oppX := bl.get(jj)
                            oppT := bt.get(jj)
                        jj -= 1
    // close out the period that bar [1] ended
    if live and perEnd and not na(dH)
        float tr = na(prevC) ? dH - dL : math.max(dH - dL, math.abs(dH - prevC), math.abs(dL - prevC))
        trs.push(tr)
        if trs.size() > 14
            trs.shift()
        prevC := dC
        if zDir == 0
            zDir := 1
            zExt := dH
            zExtT := dHT
        dH := na
        // the swing in progress is redrawn once per period, from the extreme as of this close (and once at the swap)
        zExtC := zExt
        zExtTC := zExtT
    // switch to the swing in progress: checked only when bar [1] closed a swing period, on that period's close, beyond
    // the completed leg's start (by swapK of its height); an intraperiod excursion that comes back never switches
    if live and perEnd and autoSw and not na(sp0) and not na(sp1) and not na(zExt) and nz(swapFor) != st1
        float cLen = math.abs(sp1 - sp0) * swapK
        if (zDir == 1 and pC > math.max(sp0, sp1) + cLen) or (zDir == -1 and pC < math.min(sp0, sp1) - cLen)
            swapFor := st1
            // the LEG runs to the extreme as of this close (already set by the period close above)
            zExtC := zExt
            zExtTC := zExtT
    // build the profile once per new leg
    bool forming = autoSw and not na(sp1) and nz(swapFor) == st1 and not na(zExtC) and not na(zExtTC) and zExtTC > st1
    int wantKey = forming ? (st1 + zExtTC) * 2 + 1 : (nz(st0) + nz(st1)) * 2
    bool built = false
    if not na(sp0) and not na(sp1) and wantKey != nz(key)
        key := wantKey
        built := true
        formDir := forming ? (zExtC > sp1 ? 1 : -1) : 0
        float q0 = forming ? sp1 : sp0
        float q1 = forming ? zExtC : sp1
        int   u0 = forming ? st1 : st0
        int   u1 = forming ? zExtTC : st1
        rHi := math.max(q0, q1)
        rLo := math.min(q0, q1)
        tA := math.min(u0, u1)
        tB := math.max(u0, u1)
        rv.clear()
        rvF.clear()
        lv.clear()
        if bt.size() == 0 or bt.first() > tA
            status := 2
        else
            status := 1
            for r = 0 to nRows - 1
                rv.push(0.0)
            int nF = nRows * FINE
            for r = 0 to nF - 1
                rvF.push(0.0)
            float step = (rHi - rLo) / nRows
            float stepF = step / FINE
            int ib = bt.size() - 1
            while ib >= 0 and bt.get(ib) >= tA
                if bt.get(ib) <= tB
                    float fullR = bh.get(ib) - bl.get(ib)
                    float bH = math.min(bh.get(ib), rHi)
                    float bL = math.max(bl.get(ib), rLo)
                    // a bar partly outside the leg adds only its inside share
                    float vol = fullR > 0 and (bh.get(ib) > rHi or bl.get(ib) < rLo) ? bv.get(ib) * math.max(0.0, bH - bL) / fullR : bv.get(ib)
                    // a one-price bar covers its own tick, half a tick each side, so it can't comb rows finer than a tick
                    if fullR == 0
                        bH := math.min(bH + syminfo.mintick / 2, rHi)
                        bL := math.max(bL - syminfo.mintick / 2, rLo)
                    if bH > bL and vol > 0
                        // clamped both ways: a Pine loop with from > to runs backward, onto a row past the end
                        int f0 = math.min(nF - 1, math.max(0, math.floor((bL - rLo) / stepF)))
                        int f1 = math.max(f0, math.min(nF - 1, math.floor((bH - rLo) / stepF)))
                        for r = f0 to f1
                            float ovF = math.min(bH, rLo + (r + 1) * stepF) - math.max(bL, rLo + r * stepF)
                            if ovF > 0
                                rvF.set(r, rvF.get(r) + vol * ovF / (bH - bL))
                        int r0 = math.min(nRows - 1, math.max(0, math.floor((bL - rLo) / step)))
                        int r1 = math.max(r0, math.min(nRows - 1, math.floor((bH - rLo) / step)))
                        for r = r0 to r1
                            float ov = math.min(bH, rLo + (r + 1) * step) - math.max(bL, rLo + r * step)
                            if ov > 0
                                rv.set(r, rv.get(r) + vol * ov / (bH - bL))
                ib -= 1
            // no volume on this symbol (an index, for example): swing high and low only
            if rv.max() == 0
                status := 3
                poc := na
    if status == 1 and lv.size() == 0 and rv.size() == nRows and rvF.size() == nRows * FINE
        lv := f_levels(rv, rvF, rLo, rHi)
        rvF.clear()
        // pack into plain numbers
        float mxv = rv.max()
        h0 := 0.0
        h1 := 0.0
        h2 := 0.0
        h3 := 0.0
        for r = 0 to math.min(nRows, 28) - 1
            float qv = mxv > 0 ? math.round(99 * rv.get(r) / mxv) : 0.0
            float pv = qv * math.pow(100, r % 7)
            int g = int(math.floor(r / 7))
            if g == 0
                h0 += pv
            else if g == 1
                h1 += pv
            else if g == 2
                h2 += pv
            else
                h3 += pv
        poc := lv.size() >= 3 ? lv.get(0) : na
        vah := lv.size() >= 3 ? lv.get(1) : na
        val := lv.size() >= 3 ? lv.get(2) : na
        for j = 0 to 17
            zz.set(j, 3 + j < lv.size() ? lv.get(3 + j) : na)
        rowAvg := rv.sum() / nRows
        for j = 0 to 5
            zf.set(j, 0.0)
        fillBits := 0.0
    // volume traded inside each low-volume area since the swing was confirmed (bar [1]; completed legs only)
    if live and status == 1 and not built and formDir == 0 and lv.size() > 0 and rowAvg > 0
        float stepZ = (rHi - rLo) / nRows
        float bits = 0.0
        for j = 0 to 5
            float zlo = zz.get(3 * j)
            float zhi = zz.get(3 * j + 1)
            if not na(zlo) and not na(zhi)
                float ovz = math.max(0.0, math.min(pH, zhi) - math.max(pL, zlo))
                float add = pH > pL ? pV * ovz / (pH - pL) : (pH >= zlo and pH <= zhi ? pV : 0.0)
                zf.set(j, zf.get(j) + add)
                if zf.get(j) >= rowAvg * (zhi - zlo) / stepZ
                    bits += math.pow(2, j)
        fillBits := bits
    [rHi, rLo, tA, tB, status + (formDir == 1 ? 10 : formDir == -1 ? 20 : 0), poc, vah, val, h0, h1, h2, h3, fillBits, zz.get(0), zz.get(1), zz.get(2), zz.get(3), zz.get(4), zz.get(5), zz.get(6), zz.get(7), zz.get(8), zz.get(9), zz.get(10), zz.get(11), zz.get(12), zz.get(13), zz.get(14), zz.get(15), zz.get(16), zz.get(17)]
 
// a swing finer than its source bars or than the chart is skipped (e.g. the 60m swing on a daily chart), and so is
// every layer on a non-standard chart (Heikin Ashi, Renko and the like), whose synthetic bars would change the levels
wantS = showS and timeframe.in_seconds(sTf) >= timeframe.in_seconds(srcTf) and timeframe.in_seconds(sTf) >= timeframe.in_seconds()
wantF = showF and timeframe.in_seconds(fTf) >= timeframe.in_seconds(srcF) and timeframe.in_seconds(fTf) >= timeframe.in_seconds()
onS = wantS and chart.is_standard
onF = wantF and chart.is_standard
// a layer that is off requests the chart's own series, so it loads no extra data
// lookahead on is safe because f_calc reads only the previous source bar (high[1], low[1], close[1], volume[1],
// time[1]) and whether the current bar opens a new swing period; on a coarser chart lookahead off returns the last
// source bar inside each chart bar (lookahead on would return the first)
[sHi, sLo, sT0, sT1, sSt, sPoc, sVah, sVal, sH0, sH1, sH2, sH3, sFb, sZ0, sZ1, sZ2, sZ3, sZ4, sZ5, sZ6, sZ7, sZ8, sZ9, sZ10, sZ11, sZ12, sZ13, sZ14, sZ15, sZ16, sZ17] = request.security(syminfo.tickerid, onS ? srcTf : timeframe.period, f_calc(sTf, kAtr, onS), lookahead = onS and sLtf ? barmerge.lookahead_off : barmerge.lookahead_on, calc_bars_count = CBC)
[fHi, fLo, fT0, fT1, fSt, fPoc, fVah, fVal, fH0, fH1, fH2, fH3, fFb, fZ0, fZ1, fZ2, fZ3, fZ4, fZ5, fZ6, fZ7, fZ8, fZ9, fZ10, fZ11, fZ12, fZ13, fZ14, fZ15, fZ16, fZ17] = request.security(syminfo.tickerid, onF ? srcF : timeframe.period, f_calc(fTf, kFast, onF), lookahead = onF and fLtf ? barmerge.lookahead_off : barmerge.lookahead_on, calc_bars_count = CBC)
 
// rebuild the row list and level list on the chart (last bar only)
f_rows(float a0, float a1, float a2, float a3) =>
    array<float> out = array.new_float()
    for r = 0 to nRows - 1
        int g = int(math.floor(r / 7))
        float hv = g == 0 ? a0 : g == 1 ? a1 : g == 2 ? a2 : a3
        out.push(math.floor(nz(hv) / math.pow(100, r % 7)) % 100)
    out
f_lvList(float p, float h, float l, array<float> z) =>
    array<float> out = array.new_float()
    if not na(p)
        out.push(p)
        out.push(h)
        out.push(l)
        for j = 0 to 5
            if not na(z.get(3 * j)) and not na(z.get(3 * j + 1))
                out.push(z.get(3 * j))
                out.push(z.get(3 * j + 1))
                out.push(z.get(3 * j + 2))
    out
 
// ---------- chart bar times, to place the histogram, the level and shelf lines and the low-volume boxes on chart bars
// (drawing by time reads no bar history)
var array<int> cbt = array.new_int()
cbt.push(time)
if cbt.size() > 90000
    cbt.shift()
// position in cbt of the first chart bar at or after t (0 when t is before the chart, the last bar when after it)
f_ai(int t) =>
    int n = cbt.size()
    int res = n - 1
    if n > 0 and t <= cbt.last()
        int a = 0
        int b = n - 1
        while a < b
            int m = math.floor((a + b) / 2)
            if cbt.get(m) < t
                a := m + 1
            else
                b := m
        res := a
    res
// position in cbt of the chart bar that contains t (on a chart coarser than the source t falls inside a bar); the
// next bar when no bar covers t (a gap), 0 when t is before the chart
f_ci(int t) =>
    int i = f_ai(t)
    i > 0 and cbt.get(i) > t and cbt.get(i - 1) + timeframe.in_seconds() * 1000 > t ? i - 1 : i
// time of position i in cbt, continued past the last bar at the chart's bar length
f_at(int i) =>
    int n = cbt.size()
    i <= n - 1 ? cbt.get(i) : cbt.last() + (i - (n - 1)) * timeframe.in_seconds() * 1000
 
// ---------- drawing
var array<line>  dl = array.new<line>()
var array<box>   db = array.new<box>()
var array<label> dlb = array.new<label>()
 
var array<float>  lP = array.new_float()
var array<string> lT = array.new_string()
var array<color>  lC = array.new_color()
f_lab(float p, string txt, color c, int tr = 0) =>
    lP.push(p)
    lT.push(txt)
    lC.push(color.new(readableOn(c, labelBackgroundColor), tr))
// merge labels at the same price and draw them
f_flushLabels() =>
    if showLab and lP.size() > 0
        array<float>  cp = array.new_float()
        array<string> ct = array.new_string()
        array<color>  cc = array.new_color()
        for i = 0 to lP.size() - 1
            float pr = math.round(lP.get(i) / syminfo.mintick) * syminfo.mintick
            int idx = cp.indexof(pr)
            if idx >= 0
                ct.set(idx, ct.get(idx) + " + " + lT.get(i))
            else
                cp.push(pr)
                ct.push(lT.get(i))
                cc.push(lC.get(i))
        color bg = color.new(labelBackgroundColor, labelBackgroundTransparency)
        for i = 0 to cp.size() - 1
            string txt = showPriceInLabel ? ct.get(i) + " " + str.tostring(cp.get(i), format.mintick) : ct.get(i)
            dlb.push(label.new(bar_index + floatingLabelOffset, cp.get(i), txt, xloc.bar_index, color = bg, textcolor = cc.get(i), style = label.style_label_left, size = getSize(labelTextSize)))
    lP.clear()
    lT.clear()
    lC.clear()
 
// a level line extended right from chart bar position cA through cB (cB > cA). Both ends are chart bar times, so
// they can't share a bar; a line that starts on the last bar uses bar indexes, because its far end would be a time
// past the last bar, which TradingView could put on the last bar after a session break
f_ray(int cA, int cB, float p, color c, string st, int w) =>
    line ln = na
    if cA >= cbt.size() - 1
        ln := line.new(bar_index, p, bar_index + 1, p, xloc.bar_index, extend.right, c, st, w)
    else
        ln := line.new(f_at(cA), p, f_at(cB), p, xloc.bar_time, extend.right, c, st, w)
    ln
 
// one level line; the lower swing skips a line the higher swing already drew at that price, and its chip merges
// into the higher swing's chip ("D VAH + 1H POC")
f_level(int cA, int cB, float p, color c, string st, int w, string txt, bool isHigher) =>
    float k = f_key(p)
    if isHigher
        hiPx.push(k)
    if isHigher or hiPx.indexof(k) < 0
        dl.push(f_ray(cA, cB, p, c, st, w))
    f_lab(p, txt, c)
 
f_draw(float rHi, float rLo, int t0, int t1, int st, array<float> rv, array<float> lv, string tfRaw, bool isHigher, bool hist, float fb, float kk, string src) =>
    string tfName = getTimeframeLabel(tfRaw)
    string wIn = isHigher ? wSlowIn : wFastIn
    int w = wIn == "By timeframe" ? f_tfWidth(tfRaw) : int(str.tonumber(wIn))
    color cSw = isHigher ? cSwH : cSwL
    color cVa = isHigher ? cVaH : cVaL
    color cLv = isHigher ? cLvH : cLvL
    int s = st % 10
    // status notes: the slow layer's above the last bar, the fast layer's below it, so they never overprint
    string who = "MTF Swing Range Volume Profile, " + tfName + " swing: "
    string sty = isHigher ? label.style_label_lower_left : label.style_label_upper_left
    if s == 0
        dlb.push(label.new(time, close, who + "no completed swing of " + str.tostring(kk) + " ATR yet in the " + getTimeframeLabel(src) + " bars this layer reads", xloc.bar_time, color = color.new(color.white, 100), textcolor = color.gray, style = sty, size = size.small))
    else if s == 2
        dlb.push(label.new(time, close, who + "no profile because the leg starts before the last 5,000 " + getTimeframeLabel(src) + " bars this layer keeps", xloc.bar_time, color = color.new(color.white, 100), textcolor = color.gray, style = sty, size = size.small))
    else if s == 3
        dlb.push(label.new(time, close, who + "no volume data on this symbol, so swing high and low only", xloc.bar_time, color = color.new(color.white, 100), textcolor = color.gray, style = sty, size = size.small))
    bool ok = s == 1 and rv.size() == nRows and lv.size() >= 3
    // drawings start at the chart bar that contains the swing time and end at least one bar later. A time that is not
    // a chart bar's open (a chart coarser than the source, or one whose bars don't nest in it) lands on the next chart
    // bar, and an extended line whose two ends share a bar draws vertical
    int c0 = f_ci(t0)
    int cZ = f_ci(t1)
    int c1 = math.max(cZ, c0 + 1)
    float lo = rLo
    float hi = rHi
    float step = (hi - lo) / nRows
    if ok
        float mx = rv.max()
        // no histogram when the whole leg ends before the chart's first bar
        if hist and mx > 0 and t1 >= cbt.first()
            // at the left of the range, placed by bar time; widths counted in chart bars
            int a0 = c0
            int a1 = cZ
            int legBars = a1 - a0
            // widest row 30% of the leg's chart bars, at least 5, never wider than the leg
            int wMax = math.max(math.min(5, math.max(1, legBars)), int(legBars * histPct / 100.0))
            int xL = cbt.get(a0)
            color cA = isHigher ? cHistA : color.new(cHsL, 82)
            color cV = isHigher ? cHistV : color.new(cHsL, 62)
            float vaTop = lv.get(1)
            float vaBot = lv.get(2)
            for r = 0 to nRows - 1
                int hw = int(math.round(wMax * rv.get(r) / mx))
                if hw > 0
                    // value-area rows: rows whose middle lies between the drawn VAL and VAH
                    float mid = lo + (r + 0.5) * step
                    bool inVA = mid <= vaTop and mid >= vaBot
                    db.push(box.new(xL, lo + (r + 1) * step, f_at(a0 + hw), lo + r * step, xloc = xloc.bar_time, border_color = color.new(color.black, 100), bgcolor = inVA ? cV : cA))
    // swing H/L whenever a leg exists, also when its profile can't be built (status 2 and 3)
    if s != 0
        f_level(c0, c1, hi, cSw, stSw, w, tfName + (st >= 10 and st < 20 ? " LEG H" : " SWING H"), isHigher)
        f_level(c0, c1, lo, cSw, stSw, w, tfName + (st >= 20 ? " LEG L" : " SWING L"), isHigher)
    if ok
        if showVA
            f_level(c0, c1, lv.get(0), cVa, stPoc, w, tfName + " POC", isHigher)
            f_level(c0, c1, lv.get(1), cVa, stVa, w, tfName + " VAH", isHigher)
            f_level(c0, c1, lv.get(2), cVa, stVa, w, tfName + " VAL", isHigher)
        int nZones = int((lv.size() - 3) / 3)
        if nZones > 0
            for j = 0 to nZones - 1
                float zLo = lv.get(3 + 3 * j)
                float zHi = lv.get(4 + 3 * j)
                float zSh = lv.get(5 + 3 * j)
                bool filled = fillMode != "Off" and math.floor(nz(fb) / math.pow(2, j)) % 2 == 1
                if not (filled and fillMode == "Hide")
                    bool sh = showShelf and not na(zSh) and math.abs(zSh - zHi) > step / FINE / 2 and math.abs(zSh - zLo) > step / FINE / 2
                    // a tall area draws as an outline: its edges carry the meaning, a filled band would cover the chart
                    bool wide = zHi - zLo > WIDE * step
                    // the shade depends only on fill, so turning shelf lines off doesn't restyle the boxes
                    int bgT = wide ? 100 : filled ? 96 : 92
                    db.push(box.new(f_at(cZ), zHi, f_at(cZ + 1), zLo, xloc = xloc.bar_time, extend = extend.right, border_color = color.new(cLv, filled ? 85 : 75), border_width = 1, bgcolor = color.new(cLv, bgT)))
                    // a filled area keeps its faded box and shelf line; its chip shows only with "Fade with label"
                    bool chip = not filled or fillMode == "Fade with label"
                    if sh
                        dl.push(f_ray(cZ, cZ + 1, zSh, color.new(cLv, filled ? 60 : 0), stSh, w))
                        if chip
                            f_lab(zSh, tfName + (filled ? " SHELF (LVN filled)" : " SHELF"), cLv, filled ? 60 : 0)
                    else if chip
                        f_lab((zLo + zHi) / 2, tfName + (filled ? " LVN filled" : " LVN"), cLv, filled ? 60 : 0)
 
if barstate.islast
    for x in dl
        line.delete(x)
    for x in db
        box.delete(x)
    for x in dlb
        label.delete(x)
    dl.clear()
    db.clear()
    dlb.clear()
    hiPx.clear()
    if not chart.is_standard and (wantS or wantF)
        dlb.push(label.new(time, close, "MTF Swing Range Volume Profile: off on this chart type, its synthetic bars would change the levels; use bars or candles", xloc.bar_time, color = color.new(color.white, 100), textcolor = color.gray, style = label.style_label_lower_left, size = size.small))
    if onS
        f_draw(sHi, sLo, sT0, sT1, sSt, f_rows(sH0, sH1, sH2, sH3), f_lvList(sPoc, sVah, sVal, array.from(sZ0, sZ1, sZ2, sZ3, sZ4, sZ5, sZ6, sZ7, sZ8, sZ9, sZ10, sZ11, sZ12, sZ13, sZ14, sZ15, sZ16, sZ17)), sTf, true, showHist, sFb, kAtr, srcTf)
    if onF
        f_draw(fHi, fLo, fT0, fT1, fSt, f_rows(fH0, fH1, fH2, fH3), f_lvList(fPoc, fVah, fVal, array.from(fZ0, fZ1, fZ2, fZ3, fZ4, fZ5, fZ6, fZ7, fZ8, fZ9, fZ10, fZ11, fZ12, fZ13, fZ14, fZ15, fZ16, fZ17)), fTf, false, showHistF, fFb, kFast, srcF)
    f_flushLabels()

← 返回列表