FVG Map [JOAT]

officialjackofalltrades · study · 1164 行 · 点赞 375 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © officialjackofalltrades
//@version=6
indicator("FVG Map [JOAT]", "FVG Map", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 0. SAFETY
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
max_bars_back(time, 5000)
// Scale anchor: a script that only draws boxes / lines / labels can land on its own price scale on a customer's
// chart. One invisible plot pins it to the price scale. display.pane keeps it out of the status line and data window.
plot(close, "Scale anchor (invisible)", color = color.new(#000000, 100), display = display.pane, editable = false)
 
float atrK = ta.atr(14)          // shared ATR for gap sizes, glow padding, lane gaps and distances
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7. GAP INPUTS (declared first so they lead the Settings dialog; the kit blocks follow)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G7 = "Gaps"
float  minGapAtr  = input.float(0.25, "Min gap size (ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = G7,
     tooltip = "A gap between candle 1 and candle 3 must be at least this many ATR tall to be drawn. 0 = every gap.")
bool   bestOnly   = input.bool(true, "Best gaps only, score at least", group = G7, inline = "b0",
     tooltip = "Only gaps whose score (0-10) reaches this value are drawn. Score = gap size in ATR 35 % + drive of the middle candle (range in ATR and body share) 30 % + its volume rank 20 % + close tilt toward the gap's side 15 %. Without volume the first two are rescaled to 10. Keeps a 1-minute chart from filling up with small gaps.")
float  minScore   = input.float(5.0, "", minval = 0.0, maxval = 10.0, step = 0.5, group = G7, inline = "b0")
int    maxPerSide = input.int(4, "Max live gaps per side", minval = 1, maxval = 8, group = G7,
     tooltip = "Live (unfilled) gaps kept per side; the oldest leaves first. 4 keeps a 1-minute chart readable. Raise it on 1H and above.")
int    maxAge     = input.int(1500, "Gap age-out (bars)", minval = 100, maxval = 4900, step = 100, group = G7,
     tooltip = "A live gap or an inversion older than this is removed.")
int    volLen     = input.int(50, "Volume rank length", minval = 10, maxval = 300, group = G7,
     tooltip = "The middle candle's volume is ranked against this many candles (percent rank) for the score.")
int    extBars    = input.int(4, "Extend right (bars)", minval = 2, maxval = 30, group = G7,
     tooltip = "How far past the last candle a live gap reaches; its tag sits at that right end.")
 
string G8 = "Fill and inversion"
bool   showGhost  = input.bool(true, "Filled part as a ghost", group = G8,
     tooltip = "When price trades into a gap, the box shrinks from the touched edge. The part already filled stays as a faint dotted ghost.")
bool   showDead   = input.bool(true, "Grey history of filled gaps, keep", group = G8, inline = "d0",
     tooltip = "A fully filled gap turns grey, stops at the filling candle and loses its text. This many are kept; the oldest leaves first.")
int    keepDead   = input.int(3, "", minval = 1, maxval = 20, group = G8, inline = "d0")
bool   showInv    = input.bool(true, "Inversions (IFVG), keep", group = G8, inline = "i0",
     tooltip = "A candle that CLOSES through the far side of a gap inverts it: the box becomes a dashed outline in the other side's colour, tagged 'IFVG' with its range and the inversion time. Only this many of the newest are kept. A close back through the other side ends it (grey).")
int    keepInv    = input.int(3, "", minval = 1, maxval = 6, group = G8, inline = "i0")
int    invWindow  = input.int(10, "Inversion window after a full fill (bars)", minval = 0, maxval = 100, group = G8,
     tooltip = "A gap that was filled by a wick can still invert if a candle closes through its far side within this many bars.")
 
string G9 = "Gap look"
int    slabsN     = input.int(4, "Gradient steps", minval = 2, maxval = 6, group = G9,
     tooltip = "Each share of the box (bought / sold) is cut into this many nested slabs, strongest at the origin and fading toward the right edge. Each slab is one box toward the drawing limit.")
int    fillT      = input.int(66, "Fill at the origin (transparency)", minval = 40, maxval = 95, group = G9,
     tooltip = "Transparency of the stack at the origin for the share in the gap's own colour, before Brightness is applied. The other share is drawn 8 fainter. Touched gaps are 10 fainter.")
bool   showCE     = input.bool(true, "CE line (50 %)", group = G9,
     tooltip = "Consequent encroachment: a dotted line at the middle of the original gap. It dims once a fill reaches it.")
float  glowMin    = input.float(7.0, "Glow when score is at least", minval = 0.0, maxval = 10.0, step = 0.5, group = G9,
     tooltip = "Gaps with a score at or above this get a soft halo around the box.")
int    glowLayers = input.int(2, "Glow layers", minval = 1, maxval = 4, group = G9,
     tooltip = "Boxes in the halo, the frame included. 1 = no halo.")
 
string G10 = "Tags"
bool   showTags   = input.bool(true, "Gap tags", group = G10, inline = "t0",
     tooltip = "The tag at the right end of every live gap, inversion and higher-timeframe gap, and its text size. Hover a tag for score, size in ATR, fill %, CE and age.")
string tagSize    = input.string("Small", "", options = ["Small", "Normal"], group = G10, inline = "t0")
bool   tagRange   = input.bool(true, "Tag: price range", group = G10, tooltip = "The low and high of the part of the gap that is still open.")
bool   tagBuy     = input.bool(true, "Tag: bought share", group = G10, tooltip = "'Buy 63 %': the share of the three candles' volume counted as bought (by where each candle closed in its range). Needs volume data.")
bool   tagNear    = input.bool(true, "Tag: distance on the nearest gap", group = G10,
     tooltip = "The nearest live gap gets a second line: 'nearest · 0.8 ATR' or 'price inside · 40 % filled'. The dashboard reads the same number.")
float  laneGap    = input.float(0.6, "Label lane gap (ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = G10,
     tooltip = "Minimum vertical distance between right-edge tags. The gap used is the larger of this many ATR and 1/38 of the price span the chart will show (every tag plus the high / low of the last 300 bars). Tags that would touch are pushed apart in price order.")
 
string G11 = "Higher-timeframe gaps"
bool   htfOn      = input.bool(false, "Show higher-timeframe gaps", group = G11,
     tooltip = "Gaps from up to two higher timeframes, drawn as thick outlines tagged '15m FVG' / '1H FVG'. Off by default. Costs one request per timeframe, read one closed bar back so nothing repaints; a timeframe at or below the chart's is skipped.")
bool   htf1On     = input.bool(true, "Timeframe 1", group = G11, inline = "h1")
string htf1       = input.timeframe("15", "", group = G11, inline = "h1")
bool   htf2On     = input.bool(true, "Timeframe 2", group = G11, inline = "h2")
string htf2       = input.timeframe("60", "", group = G11, inline = "h2")
int    htfKeep    = input.int(2, "Gaps per side per timeframe", minval = 1, maxval = 3, group = G11,
     tooltip = "Live higher-timeframe gaps kept per side for each timeframe; the oldest leaves first. A fully filled one is removed.")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 1. THEME
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G1 = "Theme"
string theme  = input.string("JOAT Signature", "Theme", group = G1,
     options = ["JOAT Signature", "Midnight Blue / Red", "Aurora Night", "Delta Cyan / Pink", "Paper & Ink", "Lime Ember", "Custom"],
     tooltip = "Named presets. JOAT Signature is the brand pair. Paper & Ink is the clean black / white preset: direction is carried by line style, not colour. Custom uses the colour pickers below.")
int    bright = input.int(3, "Brightness", minval = 1, maxval = 5, group = G1,
     tooltip = "1 = faint, 3 = as designed, 5 = vivid. Scales every fill and glow transparency; solid lines stay solid.")
string bgMode = input.string("Auto", "Chart background", options = ["Auto", "Dark", "Light"], group = G1,
     tooltip = "Auto reads the luminance of the chart background and swaps every role so it stays readable on a white chart.")
color  inBull  = input.color(#5CF0D7, "Custom bull / bear",     group = G1, inline = "c1")
color  inBear  = input.color(#B32AC3, "",                       group = G1, inline = "c1")
color  inAcc   = input.color(#FFFFFF, "Custom accent / neutral", group = G1, inline = "c2")
color  inNeu   = input.color(#787B86, "",                       group = G1, inline = "c2")
color  inTxt   = input.color(#D1D4DC, "Custom text / panel",    group = G1, inline = "c3")
color  inPanel = input.color(#0E1116, "",                       group = G1, inline = "c3")
color  inGlow  = input.color(#5CF0D7, "Custom glow",            group = G1, inline = "c4")
 
// f_lum: relative luminance 0..1 of any colour (Rec. 601 weights). Used for light / dark awareness and plate ink.
f_lum(color c) =>
    (0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) / 255.0
 
bool isLight = bgMode == "Light" ? true : bgMode == "Dark" ? false : f_lum(chart.bg_color) > 0.5
bool isMono  = theme == "Paper & Ink"
 
// Roles, resolved once. Defaults = JOAT Signature. Each preset overrides every role, with the white-chart swap.
color cBull   = isLight ? #12B5A0 : #5CF0D7
color cBear   = isLight ? #8E1FA0 : #B32AC3
color cAcc    = isLight ? #131722 : #FFFFFF
color cNeu    = #787B86
color cTxt    = isLight ? #131722 : #D1D4DC
color cPanel  = isLight ? #FFFFFF : #0E1116
color cGlow   = isLight ? #12B5A0 : #5CF0D7
color cCandle = cAcc                       // colour for the "Mono" candle paint (white bodies on black, ink on white)
if theme == "Midnight Blue / Red"
    cBull   := #2962FF
    cBear   := #F23645
    cAcc    := isLight ? #131722 : #FFFFFF
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #D1D4DC
    cPanel  := isLight ? #FFFFFF : #0B0F13
    cGlow   := #2962FF
    cCandle := cAcc
else if theme == "Aurora Night"
    cBull   := isLight ? #00A86B : #00E676
    cBear   := isLight ? #C2185B : #E040FB
    cAcc    := isLight ? #B59A00 : #FDD835
    cNeu    := #5C6BC0
    cTxt    := isLight ? #1A1F2E : #E6F1FF
    cPanel  := isLight ? #F4F6FB : #0A0E17
    cGlow   := isLight ? #0097A7 : #00BCD4   // the outer aurora hue (cyan); bear outer is #7C4DFF
    cCandle := cNeu
else if theme == "Delta Cyan / Pink"
    cBull   := isLight ? #0097A7 : #00E5FF
    cBear   := isLight ? #D81B60 : #FF2E88
    cAcc    := isLight ? #B59A00 : #FFD600
    cNeu    := #6B7280
    cTxt    := isLight ? #111827 : #F8FAFC
    cPanel  := isLight ? #FFFFFF : #111827
    cGlow   := isLight ? #0097A7 : #00E5FF
    cCandle := cNeu
else if theme == "Paper & Ink"
    color ink = isLight ? #111827 : #F0F3FA
    cBull   := ink
    cBear   := ink                            // same ink; bear objects carry direction by DASHED style (kBearStyle)
    cAcc    := #2962FF                        // the one accent: the bought share; #F23645 is reserved for "broken"
    cNeu    := #B2B5BE
    cTxt    := ink
    cPanel  := isLight ? #FFFFFF : #131722
    cGlow   := #2962FF
    cCandle := ink
else if theme == "Lime Ember"
    cBull   := isLight ? #64DD17 : #B2FF59
    cBear   := isLight ? #2962FF : #448AFF
    cAcc    := #FF9800
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #E0E0E0
    cPanel  := isLight ? #FFFFFF : #161A25
    cGlow   := #FF9800
    cCandle := cNeu
else if theme == "Custom"
    cBull   := inBull
    cBear   := inBear
    cAcc    := inAcc
    cNeu    := inNeu
    cTxt    := inTxt
    cPanel  := inPanel
    cGlow   := inGlow
    cCandle := inAcc
 
string kBearStyle = isMono ? line.style_dashed : line.style_solid    // Paper & Ink: direction by style, not hue
string kInvStyle  = isMono ? line.style_dotted : line.style_dashed   // inversions: dashed (dotted in Paper & Ink)
int    kPanelT    = isLight ? 8 : 15                                  // panel alpha: 92 % on white, 85 % on dark
color  cBuyShare  = isMono ? cAcc : cBull                             // bought share of a gap (bottom part)
color  cSellShare = isMono ? cNeu : cBear                             // sold share of a gap (top part)
 
// f_t: brightness-aware transparency. Scales the OPACITY (100 - t) by 0.5x .. 1.5x so faint things stay faint
// and solid things stay solid; fills (t >= 40) get +4 on a white chart and are floored at 92 in Paper & Ink.
f_t(int t) =>
    float op = 100.0 - t
    float k  = 1.0 + (bright - 3) * 0.25
    float tt = 100.0 - op * k
    if t >= 40
        if isMono
            tt := math.max(tt, 92.0)
        if isLight
            tt += 4.0
    math.min(100, math.max(0, math.round(tt)))
 
// f_grad: 3-stop gradient c1 (t = 0) -> c2 (t = 0.5) -> c3 (t = 1).
f_grad(color c1, color c2, color c3, float t) =>
    float tt = math.min(1.0, math.max(0.0, nz(t, 0.5)))
    tt < 0.5 ? color.from_gradient(tt, 0.0, 0.5, c1, c2) : color.from_gradient(tt, 0.5, 1.0, c2, c3)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4a. LAYOUT — clamps (defined early because the text helpers use them)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_xo: a drawing anchored further back than ~5,000 bars kills the script on a LIVE bar (RE10143) and a Basic
// account only has 5,000 bars anyway. f_xr: nothing may be drawn more than 500 bars ahead.
f_xo(int b) =>
    math.max(b, bar_index - 4990)
f_xr(int b) =>
    math.min(b, bar_index + 490)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 3. TEXT
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_tag: plateless text (transparent background, coloured text). Evolves f_tag of [JOAT] Fibonacci Vault.
f_tag(int x, float y, string txt, color c, string sty, string sz) =>
    label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#000000, 100),
         style = sty, textcolor = c, size = sz)
 
// f_px: price with thousands separators at mintick precision: 24,550.25  /  1.08432  /  —
f_px(float p) =>
    string out = "—"
    if not na(p)
        string s = str.tostring(math.abs(p), format.mintick)
        array<string> parts = str.split(s, ".")
        string ip = array.get(parts, 0)
        string fp = ""
        if array.size(parts) > 1
            fp := "." + array.get(parts, 1)
        string g = ""
        int n = str.length(ip)
        if n > 0
            for i = 0 to n - 1
                g += str.substring(ip, i, i + 1)
                int rem = n - 1 - i
                if rem > 0 and rem % 3 == 0
                    g += ","
        out := (p < 0 ? "-" : "") + g + fp
    out
 
// f_wrap: breaks a sentence into lines of at most w characters (dashboard Read line).
f_wrap(string s, int w) =>
    array<string> words = str.split(s, " ")
    string out = ""
    int    len = 0
    for wd in words
        int l = str.length(wd)
        if len > 0 and len + 1 + l > w
            out += "\n" + wd
            len := l
        else
            out += (len > 0 ? " " : "") + wd
            len += (len > 0 ? 1 : 0) + l
    out
 
// f_tfLbl: "15m" / "1H" / "4H" / "1D" / "1W" for a timeframe string.
f_tfLbl(string tf) =>
    int    s   = timeframe.in_seconds(tf)
    string out = str.tostring(math.round(s / 60.0)) + "m"
    if s >= 604800 and s % 604800 == 0
        out := str.tostring(math.round(s / 604800.0)) + "W"
    else if s >= 86400 and s % 86400 == 0
        out := str.tostring(math.round(s / 86400.0)) + "D"
    else if s >= 3600 and s % 3600 == 0
        out := str.tostring(math.round(s / 3600.0)) + "H"
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 5. DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G2 = "Dashboard"
bool   showDash    = input.bool(true, "Show dashboard", group = G2)
string dashPos     = input.string("Top Right", "Dashboard position", group = G2,
     options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])
string dashSize    = input.string("Small", "Dashboard size", options = ["Small", "Normal", "Large"], group = G2)
bool   dashCompact = input.bool(false, "Compact dashboard", group = G2, tooltip = "Fewer rows for phones: header, the Nearest gap row and the Read line.")
bool   dashTint    = input.bool(true, "Tinted value cells", group = G2, tooltip = "Value cells carry a faint tint of their own colour.")
 
f_pos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.bottom_right
 
f_size(string s) =>
    switch s
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
// f_dashNew: panel in cPanel at the theme alpha, 1-px neutral frame. Rows = header + data rows + Read line.
f_dashNew(string pos, int cols, int rows) =>
    table.new(f_pos(pos), cols, rows, bgcolor = color.new(cPanel, kPanelT), frame_color = color.new(cNeu, 40),
         frame_width = 1, border_color = color.new(cNeu, 78), border_width = 1)
 
int dashRows = dashCompact ? 3 : 7
var table dash = f_dashNew(dashPos, 2, dashRows)
var array<int> dCur    = array.from(0)     // row cursor (arrays are the only globals a function may mutate)
var array<int> dMerged = array.from(-1)    // row already merged for the Read line
 
// f_dBegin: clear and rewind; call once per last-bar redraw before f_dHead.
f_dBegin() =>
    table.clear(dash, 0, 0, 1, dashRows - 1)
    array.set(dCur, 0, 0)
 
// f_dHead: title band (bold, glow tint) with symbol · timeframe on the right.
f_dHead(string title) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + title + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             bgcolor = color.new(cGlow, isLight ? 80 : 70), text_formatting = text.format_bold)
        table.cell(dash, 1, r, syminfo.ticker + " · " + timeframe.period + " ", text_color = cTxt, text_halign = text.align_right,
             text_size = f_size(dashSize), bgcolor = color.new(cGlow, isLight ? 88 : 80))
        array.set(dCur, 0, r + 1)
 
// f_dRow: name | value, value text in valueColor with an optional tint cell (evolves the 51-series f_row / f_pill).
f_dRow(string name, string value, color valueColor, string tip) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + name, text_color = color.new(cTxt, 25), text_halign = text.align_left,
             text_size = f_size(dashSize), tooltip = tip)
        table.cell(dash, 1, r, value + " ", text_color = valueColor, text_halign = text.align_right, text_size = f_size(dashSize),
             bgcolor = dashTint ? color.new(valueColor, isLight ? 90 : 86) : color.new(cPanel, 100), tooltip = tip)
        array.set(dCur, 0, r + 1)
 
// f_dRead: the "Read" sentence (already wrapped), merged across both columns, italic. Always the last row.
f_dRead(string txt) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        if array.get(dMerged, 0) != r
            table.merge_cells(dash, 0, r, 1, r)
            array.set(dMerged, 0, r)
        table.cell(dash, 0, r, txt, text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             text_formatting = text.format_italic)
        array.set(dCur, 0, r + 1)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 6. CANDLES
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G4 = "Candles"
string paintMode = input.string("Off", "Candle paint", options = ["Off", "Score", "Mono"], group = G4,
     tooltip = "Off = chart candles. Score = candles inside a live bull gap take the bull colour, inside a bear gap the bear colour; between the nearest bull gap below and the nearest bear gap above they blend by position, neutral when one side is missing. Mono = one colour so the gaps carry all the colour.")
 
// f_candlePaint: na (Off), f_grad(cBear, cNeu, cBull, score) (Score) or cCandle (Mono). Feed it to barcolor().
f_candlePaint(string mode, float score) =>
    color out = na
    if mode == "Score"
        out := f_grad(cBear, cNeu, cBull, score)
    else if mode == "Mono"
        out := cCandle
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 8. GAP ENGINE — type, state, series
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// One Gap = one fair value gap with its drawings. bull = the side it was born on (a bull gap sits under price).
// cur = the edge that is still open on the touched side (bull: the current top, bear: the current bottom).
// state: 0 live, 1 inverted (IFVG), 2 grey (filled, or an inversion that was closed back through).
type Gap
    float  top
    float  bot
    float  cur
    bool   bull
    int    x0
    int    t0
    float  score
    float  sizeAtr
    float  buy
    float  pad
    int    state
    bool   touched
    bool   ceHit
    int    endBar
    int    invTime
    bool   fromInv
    bool   htf
    string tfLbl
    array<box> halo
    array<box> slabA
    array<box> slabB
    box    frame
    box    ghost
    line   ce
    label  tag
 
var array<Gap>   bullG  = array.new<Gap>()      // live chart-timeframe gaps
var array<Gap>   bearG  = array.new<Gap>()
var array<Gap>   invG   = array.new<Gap>()      // inversions (IFVG), newest last
var array<Gap>   deadG  = array.new<Gap>()      // grey history, newest last
var array<Gap>   hBull1 = array.new<Gap>()      // higher-timeframe gaps, timeframe 1 / 2
var array<Gap>   hBear1 = array.new<Gap>()
var array<Gap>   hBull2 = array.new<Gap>()
var array<Gap>   hBear2 = array.new<Gap>()
var array<int>   cnt    = array.from(0, 0, 0, 0)                      // filled today bull, bear, inversions today, last inversion time
var array<bool>  evt    = array.from(false, false, false, false, false) // new bull, new bear, entered, filled, inverted
var array<float> tY     = array.new<float>()    // right-edge tag lanes, rebuilt every last-bar redraw
var array<float> tH     = array.new<float>()
var array<label> tL     = array.new<label>()
 
// Series read by the engine, computed at global scope every bar.
float posIn   = high > low ? (close - low) / (high - low) : 0.5
float boughtV = nz(volume) * posIn                  // a candle's volume counted as bought by where it closed in its range
float vol3    = math.sum(nz(volume), 3)
float bgt3    = math.sum(boughtV, 3)
float buy3    = vol3 > 0 ? bgt3 / vol3 * 100.0 : na
float vRank   = ta.percentrank(nz(volume), volLen)
float hi300   = ta.highest(high, 300)
float lo300   = ta.lowest(low, 300)
bool  newDay  = timeframe.change("1D")
int   tfMs    = timeframe.in_seconds() * 1000
 
if newDay
    array.set(cnt, 0, 0)
    array.set(cnt, 1, 0)
    array.set(cnt, 2, 0)
 
// Higher-timeframe data: one request per timeframe, every value one closed bar back (lookahead on + [1] offsets),
// so a gap appears only after its third candle has closed and never changes afterwards. A timeframe at or below
// the chart's is replaced by the chart's own timeframe (no lower-timeframe request is ever made).
int    chartSec = timeframe.in_seconds()
bool   h1On     = htfOn and htf1On and timeframe.in_seconds(htf1) > chartSec
bool   h2On     = htfOn and htf2On and timeframe.in_seconds(htf2) > chartSec and htf2 != htf1
string tfReq1   = h1On ? htf1 : timeframe.period
string tfReq2   = h2On ? htf2 : timeframe.period
string lbl1     = f_tfLbl(htf1)
string lbl2     = f_tfLbl(htf2)
 
f_htfData() =>
    [high[3], low[3], high[1], low[1], time[2], time[1], ta.atr(14)[1]]
 
// The requests sit inside `if` blocks (Pine v6 dynamic requests), so with the layer off no request runs at all.
float aH3  = na
float aL3  = na
float aH1  = na
float aL1  = na
int   aT2  = na
int   aT1  = na
float aAtr = na
float bH3  = na
float bL3  = na
float bH1  = na
float bL1  = na
int   bT2  = na
int   bT1  = na
float bAtr = na
if h1On
    [x3H, x3L, x1H, x1L, xT2, xT1, xAtr] = request.security(syminfo.tickerid, tfReq1, f_htfData(), lookahead = barmerge.lookahead_on)
    aH3  := x3H
    aL3  := x3L
    aH1  := x1H
    aL1  := x1L
    aT2  := xT2
    aT1  := xT1
    aAtr := xAtr
if h2On
    [y3H, y3L, y1H, y1L, yT2, yT1, yAtr] = request.security(syminfo.tickerid, tfReq2, f_htfData(), lookahead = barmerge.lookahead_on)
    bH3  := y3H
    bL3  := y3L
    bH1  := y1H
    bL1  := y1L
    bT2  := yT2
    bT1  := yT1
    bAtr := yAtr
bool h1New = h1On and not na(aT1) and (na(aT1[1]) or aT1 != aT1[1])
bool h2New = h2On and not na(bT1) and (na(bT1[1]) or bT1 != bT1[1])
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 9. GAP ENGINE — helpers
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_score: 0-10. Gap size in ATR 35 % (1 ATR = full marks) + drive of the middle candle 30 % (range in ATR, 2.5 =
// full, and body share, half each) + its volume rank 20 % + close tilt toward the gap's side 15 % (80 % bought
// for a bull gap = full). Without volume the first two parts are rescaled to 10. Evolves the grade of FVG Sniper.
f_score(bool bull, float sizeAtr, float rngAtr, float bodyShare, float vRk, float buyPct) =>
    float sSize  = math.min(1.0, math.max(0.0, nz(sizeAtr)))
    float sDrive = math.min(1.0, nz(rngAtr) / 2.5) * 0.5 + math.min(1.0, math.max(0.0, nz(bodyShare))) * 0.5
    float sc     = 0.0
    if na(buyPct)
        sc := (sSize * 0.35 + sDrive * 0.30) / 0.65
    else
        float tilt = bull ? (buyPct - 50.0) / 30.0 : (50.0 - buyPct) / 30.0
        sc := sSize * 0.35 + sDrive * 0.30 + nz(vRk, 50.0) / 100.0 * 0.20 + math.min(1.0, math.max(0.0, tilt)) * 0.15
    math.round(sc * 10.0, 1)
 
// f_range: [top, bottom] of the part still drawn. Live and HTF gaps: the open part; inversions / grey: the whole gap.
f_range(Gap g) =>
    float t = g.top
    float b = g.bot
    if g.state == 0
        t := g.bull ? g.cur : g.top
        b := g.bull ? g.bot : g.cur
    [t, b]
 
// f_fillPct: share of the gap already traded through from the touched edge, 0-100.
f_fillPct(Gap g) =>
    float h = math.max(g.top - g.bot, syminfo.mintick)
    math.min(100.0, math.max(0.0, (g.bull ? g.top - g.cur : g.cur - g.bot) / h * 100.0))
 
// f_roleBull: the side a gap acts for now. An inverted bull gap acts for the bear side and the reverse.
f_roleBull(Gap g) =>
    g.state == 1 ? not g.bull : g.bull
 
// f_dist: [distance from the close in points, status 0 away / 1 inside / 2 closed beyond on the live bar].
f_dist(Gap g) =>
    [rT, rB] = f_range(g)
    bool  rb = f_roleBull(g)
    int   st = close <= rT and close >= rB ? 1 : (rb ? close < rB : close > rT) ? 2 : 0
    float d  = st == 0 ? (rb ? close - rT : rB - close) : 0.0
    [math.max(0.0, d), st]
 
// f_slabT: per-slab transparency so that n nested slabs stack up to t0 at the origin.
f_slabT(int n, int t0) =>
    float a = 1.0 - math.pow(1.0 - (100 - math.min(99, t0)) / 100.0, 1.0 / math.max(1, n))
    f_t(int(math.max(0, math.min(99, math.round(100 - 100 * a)))))
 
// f_strip: delete the live-only drawings (halo, slabs, ghost); the frame, CE and tag stay.
f_strip(Gap g) =>
    for b in g.halo
        box.delete(b)
    array.clear(g.halo)
    for b in g.slabA
        box.delete(b)
    array.clear(g.slabA)
    for b in g.slabB
        box.delete(b)
    array.clear(g.slabB)
    box.delete(g.ghost)
    g.ghost := na
 
// f_kill: delete every drawing of a gap.
f_kill(Gap g) =>
    f_strip(g)
    box.delete(g.frame)
    g.frame := na
    line.delete(g.ce)
    g.ce := na
    label.delete(g.tag)
    g.tag := na
 
// f_layout: a live chart gap. Two nested gradients (bought share at the bottom, sold share at the top, split at the
// bought share of the OPEN part), halo, frame, ghost of the filled part and the CE line, origin -> right edge xr.
f_layout(Gap g, int xr) =>
    int   x0   = f_xo(g.x0)
    float mid  = (g.top + g.bot) / 2.0
    float span = math.max(1.0, float(xr - x0))
    [rT, rB] = f_range(g)
    float ySp = na(g.buy) ? (g.bull ? rT : rB) : rB + (rT - rB) * g.buy / 100.0
    int n = array.size(g.slabA)
    if n > 0
        for k = 0 to n - 1
            int xk = x0 + math.round(span * (n - k) / n)
            box a = array.get(g.slabA, k)
            box b = array.get(g.slabB, k)
            box.set_lefttop(a, x0, ySp)
            box.set_rightbottom(a, xk, rB)
            box.set_lefttop(b, x0, rT)
            box.set_rightbottom(b, xk, ySp)
    int nh = array.size(g.halo)
    if nh > 0
        for i = 0 to nh - 1
            int h = nh - i
            box hb = array.get(g.halo, i)
            box.set_lefttop(hb, x0, rT + g.pad * h)
            box.set_rightbottom(hb, xr, rB - g.pad * h)
    if not na(g.frame)
        box.set_lefttop(g.frame, x0, rT)
        box.set_rightbottom(g.frame, xr, rB)
    if not na(g.ghost)
        box.set_lefttop(g.ghost, x0, g.bull ? g.top : rB)
        box.set_rightbottom(g.ghost, xr, g.bull ? rT : g.bot)
    if not na(g.ce)
        line.set_xy1(g.ce, x0, mid)
        line.set_xy2(g.ce, xr, mid)
 
// f_layoutInv: an inversion keeps its whole range and reaches the right edge.
f_layoutInv(Gap g, int xr) =>
    float mid = (g.top + g.bot) / 2.0
    if not na(g.frame)
        box.set_lefttop(g.frame, f_xo(g.x0), g.top)
        box.set_rightbottom(g.frame, xr, g.bot)
    if not na(g.ce)
        line.set_xy1(g.ce, f_xo(g.x0), mid)
        line.set_xy2(g.ce, xr, mid)
 
// f_layoutHtf: a higher-timeframe gap lives on bar_time (its origin is the HTF middle candle's open time).
f_layoutHtf(Gap g, int xrT) =>
    float mid = (g.top + g.bot) / 2.0
    [rT, rB] = f_range(g)
    if not na(g.frame)
        box.set_lefttop(g.frame, g.t0, rT)
        box.set_rightbottom(g.frame, xrT, rB)
    if not na(g.ce)
        line.set_xy1(g.ce, g.t0, mid)
        line.set_xy2(g.ce, xrT, mid)
 
// f_dim: first touch. Both gradients 10 fainter, frame dimmer.
f_dim(Gap g) =>
    color c = g.bull ? cBull : cBear
    int n = array.size(g.slabA)
    if n > 0
        for k = 0 to n - 1
            box.set_bgcolor(array.get(g.slabA, k), color.new(cBuyShare, f_slabT(n, (g.bull ? fillT : fillT + 8) + 10)))
            box.set_bgcolor(array.get(g.slabB, k), color.new(cSellShare, f_slabT(n, (g.bull ? fillT + 8 : fillT) + 10)))
    if not na(g.frame)
        box.set_border_color(g.frame, color.new(c, f_t(35)))
 
// f_make: draw a new live chart gap (origin = the middle candle) and return it.
f_make(bool bull, float top, float bot, float sc, float sz, float buy) =>
    color c   = bull ? cBull : cBear
    int   x0  = f_xo(bar_index - 1)
    float mid = (top + bot) / 2.0
    float pd  = nz(atrK, top - bot) * 0.04
    array<box> ha = array.new<box>()
    int nh = sc >= glowMin ? glowLayers - 1 : 0
    if nh > 0
        for i = 1 to nh
            int h = nh - i + 1                                       // outermost first so the core draws on top
            array.push(ha, box.new(x0, top, x0, bot, border_color = color.new(c, 100), border_width = 1,
                 bgcolor = color.new(c, f_t(math.min(99, 86 + math.round(10.0 * h / (nh + 1)))))))
    array<box> sa = array.new<box>()
    array<box> sb = array.new<box>()
    for k = 0 to slabsN - 1
        array.push(sa, box.new(x0, top, x0, bot, border_color = color.new(c, 100), border_width = 1,
             bgcolor = color.new(cBuyShare, f_slabT(slabsN, bull ? fillT : fillT + 8))))
        array.push(sb, box.new(x0, top, x0, bot, border_color = color.new(c, 100), border_width = 1,
             bgcolor = color.new(cSellShare, f_slabT(slabsN, bull ? fillT + 8 : fillT))))
    box fr = box.new(x0, top, x0, bot, border_color = color.new(c, f_t(10)), border_width = 1,
         border_style = bull ? line.style_solid : kBearStyle, bgcolor = color.new(c, 100))
    line cl = na
    if showCE
        cl := line.new(x0, mid, x0, mid, color = color.new(c, f_t(15)), style = line.style_dotted, width = 1)
    label tg = na
    if showTags
        tg := f_tag(x0, mid, "", c, label.style_label_left, f_size(tagSize))
    Gap g = Gap.new(top = top, bot = bot, cur = bull ? top : bot, bull = bull, x0 = x0, t0 = time[1], score = sc,
         sizeAtr = sz, buy = buy, pad = pd, state = 0, touched = false, ceHit = false, endBar = na, invTime = na,
         fromInv = false, htf = false, tfLbl = "", halo = ha, slabA = sa, slabB = sb, frame = fr, ghost = na, ce = cl, tag = tg)
    f_layout(g, f_xr(bar_index + extBars))
    g
 
// f_create: a stronger overlapping live gap of the same side blocks the new one; otherwise the weaker overlapping
// gaps leave and the new one is drawn. The oldest leaves past the per-side cap. Returns true when a gap was made.
f_create(array<Gap> gs, bool bull, float top, float bot, float sc, float sz, float buy) =>
    bool blocked = false
    for o in gs
        if top >= o.bot and bot <= o.top and o.score >= sc
            blocked := true
    if not blocked
        int n = array.size(gs)
        if n > 0
            for i = n - 1 to 0
                Gap o = array.get(gs, i)
                if top >= o.bot and bot <= o.top
                    f_kill(o)
                    array.remove(gs, i)
        array.push(gs, f_make(bull, top, bot, sc, sz, buy))
        while array.size(gs) > maxPerSide
            f_kill(array.shift(gs))
    not blocked
 
// f_toDead: grey history. Live drawings go, the frame stays as a grey dotted box ending at this candle, no text.
// With the history hidden the record is still kept (invisible) so a late inversion can be seen.
f_toDead(Gap g, bool fromInv) =>
    f_strip(g)
    line.delete(g.ce)
    g.ce := na
    label.delete(g.tag)
    g.tag := na
    g.state   := 2
    g.fromInv := fromInv
    g.endBar  := bar_index
    if not na(g.frame)
        box.set_lefttop(g.frame, f_xo(g.x0), g.top)
        box.set_rightbottom(g.frame, bar_index, g.bot)
        box.set_border_color(g.frame, color.new(cNeu, showDead ? f_t(65) : 100))
        box.set_border_style(g.frame, line.style_dotted)
        box.set_border_width(g.frame, 1)
        box.set_bgcolor(g.frame, color.new(cNeu, showDead ? f_t(96) : 100))
    array.push(deadG, g)
    int cap = showDead ? keepDead : 4
    while array.size(deadG) > cap
        f_kill(array.shift(deadG))
 
// f_invert: a close through the far side. The gap becomes an IFVG in the OTHER side's colour: dashed outline with
// a faint fill, CE kept, tag "IFVG · range · time". Only the newest keepInv stay. With inversions off it goes grey.
f_invert(Gap g) =>
    array.set(cnt, 2, array.get(cnt, 2) + 1)
    array.set(cnt, 3, time)
    array.set(evt, 4, true)
    if showInv
        color c   = g.bull ? cBear : cBull
        float mid = (g.top + g.bot) / 2.0
        int   x0  = f_xo(g.x0)
        int   xr  = f_xr(bar_index + extBars)
        f_strip(g)
        g.state   := 1
        g.invTime := time
        g.endBar  := bar_index
        if na(g.frame)
            g.frame := box.new(x0, g.top, xr, g.bot)
        box.set_lefttop(g.frame, x0, g.top)
        box.set_rightbottom(g.frame, xr, g.bot)
        box.set_border_color(g.frame, color.new(c, f_t(10)))
        box.set_border_style(g.frame, kInvStyle)
        box.set_border_width(g.frame, 1)
        box.set_bgcolor(g.frame, color.new(c, f_t(90)))
        if showCE
            if na(g.ce)
                g.ce := line.new(x0, mid, xr, mid, style = line.style_dotted, width = 1)
            line.set_xy1(g.ce, x0, mid)
            line.set_xy2(g.ce, xr, mid)
            line.set_color(g.ce, color.new(c, f_t(30)))
            line.set_style(g.ce, line.style_dotted)
        if showTags and na(g.tag)
            g.tag := f_tag(xr + 1, mid, "", c, label.style_label_left, f_size(tagSize))
        array.push(invG, g)
        while array.size(invG) > keepInv
            f_kill(array.shift(invG))
    else
        f_toDead(g, true)
 
// f_updLive: one side, one confirmed bar. Age-out, inversion (close through the far side), full fill (wick to
// the far side), partial fill (the box shrinks from the touched edge, the filled part becomes a ghost).
f_updLive(array<Gap> gs) =>
    int n = array.size(gs)
    if n > 0
        for i = n - 1 to 0
            Gap  g       = array.get(gs, i)
            bool through = g.bull ? close < g.bot : close > g.top
            bool full    = g.bull ? low <= g.bot : high >= g.top
            bool deeper  = g.bull ? low < g.cur : high > g.cur
            if bar_index - g.x0 > maxAge
                f_kill(g)
                array.remove(gs, i)
            else if through or full
                array.remove(gs, i)
                array.set(cnt, g.bull ? 0 : 1, array.get(cnt, g.bull ? 0 : 1) + 1)
                array.set(evt, 3, true)
                if not g.touched
                    array.set(evt, 2, true)
                g.touched := true
                g.ceHit   := true
                g.cur     := g.bull ? g.bot : g.top
                if through
                    f_invert(g)
                else
                    f_toDead(g, false)
            else if deeper
                color c = g.bull ? cBull : cBear
                if not g.touched
                    g.touched := true
                    array.set(evt, 2, true)
                    f_dim(g)
                g.cur := g.bull ? low : high
                float mid = (g.top + g.bot) / 2.0
                if not g.ceHit and (g.bull ? g.cur <= mid : g.cur >= mid)
                    g.ceHit := true
                    if not na(g.ce)
                        line.set_color(g.ce, color.new(c, f_t(60)))
                if showGhost and na(g.ghost)
                    g.ghost := box.new(f_xo(g.x0), g.top, f_xo(g.x0), g.top, border_color = color.new(c, f_t(55)),
                         border_width = 1, border_style = line.style_dotted, bgcolor = color.new(c, f_t(96)))
                f_layout(g, f_xr(bar_index + extBars))
    n
 
// f_updInv: an inversion ends (grey) when a candle closes back through its other side, or when it ages out.
f_updInv() =>
    int n = array.size(invG)
    if n > 0
        for i = n - 1 to 0
            Gap  g    = array.get(invG, i)
            bool fail = g.bull ? close > g.top : close < g.bot
            if bar_index - g.x0 > maxAge
                f_kill(g)
                array.remove(invG, i)
            else if fail
                array.remove(invG, i)
                f_toDead(g, true)
    n
 
// f_updDead: grey records leave before they reach the 4,990-bar anchor limit; a gap filled by a wick inverts late
// when a candle closes through its far side within the inversion window.
f_updDead() =>
    array<Gap> late = array.new<Gap>()
    int n = array.size(deadG)
    if n > 0
        for i = n - 1 to 0
            Gap g = array.get(deadG, i)
            if bar_index - g.x0 > 4900
                f_kill(g)
                array.remove(deadG, i)
            else if not g.fromInv and bar_index > g.endBar and bar_index - g.endBar <= invWindow and (g.bull ? close < g.bot : close > g.top)
                array.remove(deadG, i)
                array.push(late, g)
    for g in late
        f_invert(g)
    n
 
// f_updHtf: higher-timeframe gaps shrink with chart candles and leave when fully filled (no grey history).
f_updHtf(array<Gap> gs) =>
    int n = array.size(gs)
    if n > 0
        for i = n - 1 to 0
            Gap g = array.get(gs, i)
            if (g.bull ? low <= g.bot : high >= g.top) or bar_index - g.x0 > 4900
                f_kill(g)
                array.remove(gs, i)
            else if g.bull ? low < g.cur : high > g.cur
                g.touched := true
                g.cur     := g.bull ? low : high
                float mid = (g.top + g.bot) / 2.0
                if not g.ceHit and (g.bull ? g.cur <= mid : g.cur >= mid)
                    g.ceHit := true
                    if not na(g.ce)
                        line.set_color(g.ce, color.new(g.bull ? cBull : cBear, f_t(60)))
                f_layoutHtf(g, time)
    n
 
// f_makeHtf: a new higher-timeframe gap as a thick outline (2 px, faint fill) with a dotted CE, on bar_time.
f_makeHtf(array<Gap> gs, bool bull, float top, float bot, int t0, float hAtr, string lbl) =>
    bool dup = false
    for o in gs
        if top >= o.bot and bot <= o.top
            dup := true
    bool filled = bull ? low <= bot : high >= top
    if not dup and not filled and top > bot
        color c   = bull ? cBull : cBear
        float mid = (top + bot) / 2.0
        box fr = box.new(t0, top, time, bot, xloc = xloc.bar_time, border_color = color.new(c, f_t(15)), border_width = 2,
             border_style = bull ? line.style_solid : kBearStyle, bgcolor = color.new(c, f_t(95)))
        line cl = na
        if showCE
            cl := line.new(t0, mid, time, mid, xloc = xloc.bar_time, color = color.new(c, f_t(25)), style = line.style_dotted, width = 1)
        label tg = na
        if showTags
            tg := f_tag(bar_index, mid, "", c, label.style_label_left, f_size(tagSize))
        float cur0 = bull ? math.min(top, low) : math.max(bot, high)
        Gap g = Gap.new(top = top, bot = bot, cur = cur0, bull = bull, x0 = bar_index, t0 = t0, score = na,
             sizeAtr = hAtr > 0 ? (top - bot) / hAtr : na, buy = na, pad = 0.0, state = 0, touched = cur0 != (bull ? top : bot),
             ceHit = false, endBar = na, invTime = na, fromInv = false, htf = true, tfLbl = lbl, halo = array.new<box>(),
             slabA = array.new<box>(), slabB = array.new<box>(), frame = fr, ghost = na, ce = cl, tag = tg)
        f_layoutHtf(g, time)
        array.push(gs, g)
        while array.size(gs) > htfKeep
            f_kill(array.shift(gs))
 
// f_htfStep: update one timeframe's gaps, then read a new HTF gap when a new HTF bar has closed.
f_htfStep(array<Gap> gB, array<Gap> gR, bool isNew, float h3, float l3, float h1, float l1, int t2, float hAtr, string lbl) =>
    f_updHtf(gB)
    f_updHtf(gR)
    if isNew and not na(h3) and not na(l1)
        float a = nz(hAtr, nz(atrK, syminfo.mintick))
        if l1 > h3 and l1 - h3 >= minGapAtr * a
            f_makeHtf(gB, true, l1, h3, t2, a, lbl)
        if h1 < l3 and l3 - h1 >= minGapAtr * a
            f_makeHtf(gR, false, l3, h1, t2, a, lbl)
 
// f_near: [index, distance in points, status] of the live gap of one side nearest to the close. [-1, na, 0] if none.
f_near(array<Gap> gs) =>
    int   best  = -1
    float bestD = na
    int   bestS = 0
    for [i, g] in gs
        [d, st] = f_dist(g)
        if na(bestD) or d < bestD
            best  := i
            bestD := d
            bestS := st
    [best, bestD, bestS]
 
// f_tagText: "Bull FVG · 26,912.50–26,940.25 · Buy 63 %" / "IFVG · 26,912.50–26,940.25 · 10:14" / "1H FVG · range",
// with a second line on the nearest live gap: "nearest · 0.8 ATR" or "price inside · 40 % filled".
f_tagText(Gap g, bool isNear, float dAtr, int st) =>
    [rT, rB] = f_range(g)
    string rng = f_px(rB) + "–" + f_px(rT)
    string s   = ""
    if g.state == 1
        s := "IFVG" + (tagRange ? " · " + rng : "") + " · " + str.format_time(g.invTime, "HH:mm", syminfo.timezone)
    else if g.htf
        s := g.tfLbl + " FVG" + (tagRange ? " · " + rng : "")
    else
        s := (g.bull ? "Bull FVG" : "Bear FVG") + (tagRange ? " · " + rng : "") +
             (tagBuy and not na(g.buy) ? " · Buy " + str.tostring(math.round(g.buy)) + " %" : "")
    if isNear and tagNear
        s += st == 1 ? "\nprice inside · " + str.tostring(math.round(f_fillPct(g))) + " % filled" :
             st == 2 ? "\nclosing through" : "\nnearest · " + str.tostring(dAtr, "0.0") + " ATR"
    s
 
// f_tagTip: the full record in the tag's tooltip.
f_tagTip(Gap g, float dAtr, int st) =>
    float  mid  = (g.top + g.bot) / 2.0
    string name = g.state == 1 ? "Inverted " + (g.bull ? "bull" : "bear") + " FVG (IFVG), now on the " + (g.bull ? "bear" : "bull") + " side" :
                  (g.htf ? g.tfLbl + " " : "") + (g.bull ? "Bull" : "Bear") + " FVG"
    string s = name + "\nGap " + f_px(g.bot) + " – " + f_px(g.top) + " · " + f_px(g.top - g.bot) + " pts" +
         (na(g.sizeAtr) ? "" : " · " + str.tostring(g.sizeAtr, "0.00") + " ATR" + (g.htf ? " (" + g.tfLbl + " ATR)" : "")) +
         "\nBorn " + str.format_time(g.t0, "yyyy-MM-dd HH:mm", syminfo.timezone)
    if not na(g.score)
        s += "\nScore " + str.tostring(g.score, "0.0") + " / 10 (gap size 35 %, middle candle drive 30 %, its volume rank 20 %, close tilt 15 %)"
    if not na(g.buy)
        s += "\nBought " + str.tostring(math.round(g.buy)) + " % · sold " + str.tostring(100 - math.round(g.buy)) + " % (close-position estimate over the three candles)"
    if g.state == 1
        s += "\nInverted " + str.format_time(g.invTime, "yyyy-MM-dd HH:mm", syminfo.timezone) + ": a candle closed through the far side. It ends when a candle closes back through the other side."
    else
        s += "\nFilled " + str.tostring(math.round(f_fillPct(g))) + " % · CE " + f_px(mid) + (g.ceHit ? " reached" : " not reached")
    s += "\nAge " + str.tostring(bar_index - g.x0) + " bars"
    if not na(dAtr)
        s += st == 1 ? " · price inside" : st == 2 ? " · the live candle is beyond its far side" : " · " + str.tostring(dAtr, "0.0") + " ATR from price"
    s
 
// f_tagPush: refresh one tag (text, colour, tooltip, x) and register it for the lane pass.
f_tagPush(Gap g, bool isNear, int xr) =>
    if not na(g.tag)
        [d, st] = f_dist(g)
        float a   = nz(atrK, syminfo.mintick)
        float dA  = d / a
        bool  rb  = f_roleBull(g)
        color c   = rb ? cBull : cBear
        [rT, rB]  = f_range(g)
        label.set_x(g.tag, xr + 1)
        label.set_text(g.tag, f_tagText(g, isNear, dA, st))
        label.set_tooltip(g.tag, f_tagTip(g, dA, st))
        label.set_textcolor(g.tag, g.state == 0 and g.touched and not g.htf ? color.new(c, 20) : c)
        label.set_size(g.tag, f_size(tagSize))
        array.push(tL, g.tag)
        array.push(tY, (rT + rB) / 2.0)
        array.push(tH, isNear and tagNear ? 1.8 : 1.0)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 10. GAP ENGINE — per bar (confirmed bars only, so gaps, fills and inversions never repaint)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
array.fill(evt, false)
 
if barstate.isconfirmed
    f_updDead()
    f_updInv()
    f_updLive(bullG)
    f_updLive(bearG)
    f_htfStep(hBull1, hBear1, h1New, aH3, aL3, aH1, aL1, aT2, aAtr, lbl1)
    f_htfStep(hBull2, hBear2, h2New, bH3, bL3, bH1, bL1, bT2, bAtr, lbl2)
 
    float aNow = nz(atrK, syminfo.mintick)
    float rng1 = high[1] - low[1]
    float bShr = rng1 > 0 ? math.abs(close[1] - open[1]) / rng1 : 0.0
 
    // BULL FVG: candle 3's low above candle 1's high
    if not na(high[2]) and low > high[2]
        float sz = (low - high[2]) / aNow
        if sz >= minGapAtr
            float sc = f_score(true, sz, rng1 / aNow, bShr, vRank[1], buy3)
            if not bestOnly or sc >= minScore
                if f_create(bullG, true, low, high[2], sc, sz, buy3)
                    array.set(evt, 0, true)
 
    // BEAR FVG: candle 3's high below candle 1's low
    if not na(low[2]) and high < low[2]
        float sz = (low[2] - high) / aNow
        if sz >= minGapAtr
            float sc = f_score(false, sz, rng1 / aNow, bShr, vRank[1], buy3)
            if not bestOnly or sc >= minScore
                if f_create(bearG, false, low[2], high, sc, sz, buy3)
                    array.set(evt, 1, true)
 
// nearest live gaps every bar (feeds the candle paint, the nearest tag and the dashboard)
[iB, dB, sB] = f_near(bullG)
[iR, dR, sR] = f_near(bearG)
float atrNow   = nz(atrK, syminfo.mintick)
int   nearSide = iB >= 0 and (iR < 0 or dB <= dR) ? 1 : iR >= 0 ? -1 : 0
 
// Score: 1 inside a bull gap, 0 inside a bear gap, between them by position, 0.5 otherwise
float cScore = 0.5
if iB >= 0 and sB == 1
    cScore := 1.0
else if iR >= 0 and sR == 1
    cScore := 0.0
else if iB >= 0 and iR >= 0
    [bT, bBot] = f_range(array.get(bullG, iB))
    [rTop, rBt] = f_range(array.get(bearG, iR))
    if rBt > bT
        cScore := math.min(1.0, math.max(0.0, (rBt - close) / (rBt - bT)))
barcolor(f_candlePaint(paintMode, cScore))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 11. LAST-BAR REDRAW — right edges, tags through the lane pass, dashboard
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
if barstate.islast
    int xr  = f_xr(bar_index + extBars)
    int xrT = time + extBars * tfMs
    for g in bullG
        f_layout(g, xr)
    for g in bearG
        f_layout(g, xr)
    for g in invG
        f_layoutInv(g, xr)
    for g in hBull1
        f_layoutHtf(g, xrT)
    for g in hBear1
        f_layoutHtf(g, xrT)
    for g in hBull2
        f_layoutHtf(g, xrT)
    for g in hBear2
        f_layoutHtf(g, xrT)
 
    // tags: every live gap, inversion and HTF gap; the nearest live gap carries its distance on a second line
    array.clear(tY)
    array.clear(tH)
    array.clear(tL)
    if showTags
        for [i, g] in bullG
            f_tagPush(g, nearSide == 1 and i == iB, xr)
        for [i, g] in bearG
            f_tagPush(g, nearSide == -1 and i == iR, xr)
        for g in invG
            f_tagPush(g, false, xr)
        for g in hBull1
            f_tagPush(g, false, xr)
        for g in hBear1
            f_tagPush(g, false, xr)
        for g in hBull2
            f_tagPush(g, false, xr)
        for g in hBear2
            f_tagPush(g, false, xr)
 
    // lane pass: gap = max(lane input x ATR, span / 38), span = every tag + the last 300 bars' high / low.
    // Tags are sorted top to bottom and pushed apart symmetrically (price order kept, each tag stays by its gap);
    // a final top-down pass guarantees the gap. A tag in the band a Top Right dashboard covers loses its text.
    int m = array.size(tY)
    if m > 0
        float spHi = math.max(math.max(nz(hi300, high), close), array.max(tY))
        float spLo = math.min(math.min(nz(lo300, low), close), array.min(tY))
        float spn  = math.max(spHi - spLo, syminfo.mintick)
        float gap  = math.max(math.max(nz(atrK) * laneGap, spn / 38.0), syminfo.mintick * 2)
        array<int>   ord = array.sort_indices(tY, order.descending)
        array<float> ys  = array.new<float>()
        array<float> hs  = array.new<float>()
        for k in ord
            array.push(ys, array.get(tY, k))
            array.push(hs, array.get(tH, k))
        if m > 1
            for it = 0 to 40
                bool moved = false
                for j = 1 to m - 1
                    float need = gap * (array.get(hs, j - 1) + array.get(hs, j)) / 2.0
                    float d    = array.get(ys, j - 1) - array.get(ys, j)
                    if d < need * 0.999
                        float p = (need - d) / 2.0
                        array.set(ys, j - 1, array.get(ys, j - 1) + p)
                        array.set(ys, j, array.get(ys, j) - p)
                        moved := true
                if not moved
                    break
            for j = 1 to m - 1
                float need = gap * (array.get(hs, j - 1) + array.get(hs, j)) / 2.0
                if array.get(ys, j - 1) - array.get(ys, j) < need
                    array.set(ys, j, array.get(ys, j - 1) - need)
        bool  dashTop = showDash and dashPos == "Top Right"
        float sizeK   = dashSize == "Normal" ? 1.25 : dashSize == "Large" ? 1.6 : 1.0
        float band    = (dashCompact ? 0.06 : 0.12) * sizeK * spn
        for j = 0 to m - 1
            label lb = array.get(tL, array.get(ord, j))
            float y  = array.get(ys, j)
            label.set_y(lb, y)
            // the nearest gap's tag (height 1.8) is never skipped: the dashboard row it mirrors must stay on the chart
            if dashTop and y > spHi - band and array.get(hs, j) <= 1.0
                label.set_text(lb, "")
 
    // dashboard
    if showDash
        int nBull = array.size(bullG)
        int nBear = array.size(bearG)
        int nInv  = array.size(invG)
        int nHtf  = array.size(hBull1) + array.size(hBear1) + array.size(hBull2) + array.size(hBear2)
        string actTxt = str.tostring(nBull) + " bull · " + str.tostring(nBear) + " bear" + (nInv > 0 ? " · " + str.tostring(nInv) + " IFVG" : "") +
             (nHtf > 0 ? " · " + str.tostring(nHtf) + " HTF" : "")
        color  actC   = nBull > nBear ? cBull : nBear > nBull ? cBear : cTxt
 
        // nearest live gap: near-edge price · ATR · score
        string nearTxt = "none live"
        color  nearC   = cNeu
        Gap    gN      = na
        float  dN      = na
        int    sN      = 0
        if nearSide == 1
            gN := array.get(bullG, iB)
            dN := dB
            sN := sB
        else if nearSide == -1
            gN := array.get(bearG, iR)
            dN := dR
            sN := sR
        if not na(gN)
            [nT, nB] = f_range(gN)
            nearC   := gN.bull ? cBull : cBear
            nearTxt := (gN.bull ? "bull " + f_px(nT) : "bear " + f_px(nB)) + " · " + (sN == 1 ? "inside" : str.tostring(dN / atrNow, "0.0") + " ATR") +
                 " · " + str.tostring(gN.score, "0.0")
 
        // inside a gap? live chart gaps first, then inversions, then HTF gaps
        string insTxt = "no"
        color  insC   = cNeu
        if iB >= 0 and sB == 1
            insTxt := "bull · " + str.tostring(math.round(f_fillPct(array.get(bullG, iB)))) + " % filled"
            insC   := cBull
        else if iR >= 0 and sR == 1
            insTxt := "bear · " + str.tostring(math.round(f_fillPct(array.get(bearG, iR)))) + " % filled"
            insC   := cBear
        else
            for g in invG
                if insTxt == "no" and close <= g.top and close >= g.bot
                    insTxt := "IFVG · " + (g.bull ? "bear" : "bull") + " side"
                    insC   := g.bull ? cBear : cBull
            array<Gap> hAll = array.concat(array.concat(array.copy(hBull1), hBear1), array.concat(array.copy(hBull2), hBear2))
            for g in hAll
                [hT, hB] = f_range(g)
                if insTxt == "no" and close <= hT and close >= hB
                    insTxt := g.tfLbl + " " + (g.bull ? "bull" : "bear") + " · " + str.tostring(math.round(f_fillPct(g))) + " %"
                    insC   := g.bull ? cBull : cBear
 
        int    fB     = array.get(cnt, 0)
        int    fR     = array.get(cnt, 1)
        int    nI     = array.get(cnt, 2)
        string fillTx = str.tostring(fB) + " bull · " + str.tostring(fR) + " bear"
        string invTx  = nI > 0 ? str.tostring(nI) + " · last " + str.format_time(array.get(cnt, 3), "HH:mm", syminfo.timezone) : "0"
 
        // Read
        string readTxt = "No live gap passes the filter on this chart"
        if not na(gN)
            float ceP = (gN.top + gN.bot) / 2.0
            if sN == 1
                readTxt := "Price inside a " + str.tostring(gN.sizeAtr, "0.0") + " ATR " + (gN.bull ? "bull" : "bear") + " gap, " +
                     str.tostring(math.round(f_fillPct(gN))) + " % filled; CE " + f_px(ceP) + (gN.ceHit ? " reached" : close > ceP ? " below" : " above")
            else
                readTxt := "Nearest: " + (gN.bull ? "bull" : "bear") + " gap " + str.tostring(dN / atrNow, "0.0") + " ATR " + (gN.bull ? "below" : "above") +
                     ", score " + str.tostring(gN.score, "0.0")
                if nearSide == 1 and iR >= 0
                    readTxt += "; bear gap " + str.tostring(dR / atrNow, "0.0") + " ATR above"
                else if nearSide == -1 and iB >= 0
                    readTxt += "; bull gap " + str.tostring(dB / atrNow, "0.0") + " ATR below"
        if nInv > 0
            readTxt += ". " + str.tostring(nInv) + " inversion" + (nInv > 1 ? "s" : "") + " on the chart"
 
        string tipNear = "The live gap closest to the close: its near edge (the top of a bull gap, the bottom of a bear gap, the edge price meets first), the distance from the close in ATR, and its score out of 10. FVG readers watch how price behaves when it returns to a gap: a gap that is filled fast was not defended, a gap that holds at its CE is still being respected. On the chart: the tag with the second line 'nearest · x ATR'."
        f_dBegin()
        f_dHead("FVG MAP")
        if dashCompact
            f_dRow("Nearest gap", nearTxt, nearC, tipNear)
        else
            f_dRow("Active gaps", actTxt, actC, "Live (unfilled) fair value gaps on the chart that pass the score filter, per side, plus live inversions (IFVG) and higher-timeframe gaps when they are on. Bull gaps sit under price, bear gaps over it. Many unfilled gaps on one side describe a move that left inefficiency behind it. On the chart: every live gap has a tag at its right end.")
            f_dRow("Nearest gap", nearTxt, nearC, tipNear)
            f_dRow("Inside a gap?", insTxt, insC, "Whether the close sits inside a live gap and how much of it has been filled from the touched edge. Inside an inversion or a higher-timeframe gap is shown when no live chart gap holds price. The CE (50 %) is where many FVG readers expect a gap to be judged. On the chart: the box shrinks from the touched edge, the filled part stays as a ghost.")
            f_dRow("Filled today", fillTx, cTxt, "Gaps of this chart filled completely since the start of the day (a wick reached the far side, inversions included), per side. Only gaps that passed the score filter count. On the chart: filled gaps turn grey and lose their text.")
            f_dRow("Inversions today", invTx, nI > 0 ? cAcc : cNeu, "Gaps a candle CLOSED through since the start of the day, and the time of the last one. An inverted gap is a change of structure state: the area that was support is now drawn for the other side. It is not an entry. On the chart: dashed outlines tagged 'IFVG' with the inversion time.")
        f_dRead(f_wrap(readTxt, 48))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 12. ALERTS — gap events only (no direction calls, no entries). Set them to "Once per bar close".
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
bool evNewB  = array.get(evt, 0)
bool evNewR  = array.get(evt, 1)
bool evEnter = array.get(evt, 2)
bool evFill  = array.get(evt, 3)
bool evInv   = array.get(evt, 4)
alertcondition(evNewB,  "New bull FVG",        "FVG Map: new bull fair value gap on {{ticker}} {{interval}}")
alertcondition(evNewR,  "New bear FVG",        "FVG Map: new bear fair value gap on {{ticker}} {{interval}}")
alertcondition(evEnter, "Price entered a gap", "FVG Map: price traded into a live gap on {{ticker}} {{interval}}")
alertcondition(evFill,  "Gap filled",          "FVG Map: a gap was filled completely on {{ticker}} {{interval}}")
alertcondition(evInv,   "Gap inverted (IFVG)", "FVG Map: a candle closed through a gap's far side on {{ticker}} {{interval}}")

← 返回列表