本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Titpaud
// This work is licensed under Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
// © Titpaud (varreyfrederic) — derivative work of « Price Action Smart Money Concepts [BigBeluga] » © BigBeluga
//@version=6
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Titpaud SMC All TFs [OB + FVG grid]
// Overlays, as boxes, the order blocks and fair value gaps of a whole list of timeframes
// (Wide 1m → 1M = 22 TFs, Fine 1m → 3M = 36 TFs, or a custom list), plus the chart TF.
//
// Base: order block / structure / FVG logic of « Price Action Smart Money Concepts [BigBeluga] »
// by BigBeluga (open-source script published on TradingView)
// (BOS / CHoCH structure, volumetric OBs with % weight, Close / Wick / Avg invalidation,
// overlap hiding). This logic is copied as is, without the drawings, then computed
// separately in each requested timeframe. One request per TF returns both its OBs and its FVGs.
//
// No repaint: each TF is only taken into account once its candle has closed.
// Credit for the original SMC logic goes to BigBeluga. Added by Titpaud: multi-timeframe grid,
// strength stars (V I R F S), volume weight, overlap and declutter filters, FVG options, end of zones.
// FVG strength stars: the T criterion (gap size relative to the largest gap of the last 1000 candles)
// and the idea of a buy / sell volume split come from « Volumatic Fair Value Gaps [BigBeluga] » © BigBeluga.
// Released under the same licence as the originals (CC BY-NC-SA 4.0): non-commercial, share alike.
// ═══════════════════════════════════════════════════════════════════════════════════════════
indicator("Titpaud SMC All TFs", "Titpaud SMC All TFs", overlay = true, max_bars_back = 5000, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
// ───────────────────────────────────── SETTINGS ─────────────────────────────────────
G_TF = "TIMEFRAMES"
G_CUS = "CUSTOM LIST (used when List = Custom list)"
G_COL = "COLOURS AND BORDERS"
G_OB = "ORDER BLOCKS (same settings as the original SMC)"
G_AFF = "DISPLAY"
G_IMB = "NESTED OB"
obShow = input.bool(true, "Show order blocks", group = G_TF, tooltip = "Master switch of the order blocks: untick it to hide every OB (boxes and labels) and keep only the FVGs. The OBs are still computed, so the FVG option « Only FVGs touching an OB » keeps working.")
tfList = input.string("Wide 1m → 1M (22 TFs)", "List", options = ["Wide 1m → 1M (22 TFs)", "Fine 1m → 3M (36 TFs)", "Custom list"], group = G_TF, tooltip = "Timeframes whose OBs and FVGs are computed. One request per TF (Pine allows 40).\nWide 1m → 1M: 1m, 3m, 5m, 10m, 15m, 30m, 45m, 1h, 1h30, 2h, 3h, 4h, 6h, 8h, 12h, 1D, 2D, 3D, 1W, 2W, 3W, 1M.\nFine 1m → 3M: 1m, 2m, 3m, 4m, 5m, 6m, 8m, 10m, 12m, 15m, 20m, 25m, 30m, 40m, 45m, 1h, 1h15, 1h30, 1h45, 2h, 2h30, 3h, 4h, 6h, 8h, 12h, 1D, 2D, 3D, 4D, 5D, 1W, 2W, 3W, 1M, 3M. Much heavier: lower the history per TF if the script is too slow.\nCustom list: the 16 slots of the « CUSTOM LIST » group.")
obLoR = input.int(64, "OB TFs from chart TF ÷", minval = 1, maxval = 10000, inline = "obr", group = G_TF)
obHiR = input.int(1000, "to chart TF ×", minval = 1, maxval = 10000, inline = "obr", group = G_TF, tooltip = "Only the TFs of the list between these two limits show their OBs. Example: 1h chart, ÷64 and ×1000 → every TF from 1m to 1M. ÷1 → no TF lower than the chart.")
fvLoR = input.int(4, "FVG TFs from chart TF ÷", minval = 1, maxval = 10000, inline = "fvr", group = G_TF)
fvHiR = input.int(4, "to chart TF ×", minval = 1, maxval = 10000, inline = "fvr", group = G_TF, tooltip = "Same for the FVGs of the other TFs. Example: 1h chart, ÷4 and ×4 → FVGs from 15m to 4h. The chart-TF FVGs are set in « FAIR VALUE GAP ».")
incChart = input.bool(true, "Always include the chart TF", inline = "ch", group = G_TF)
nChart = input.int(4, "OBs per side", minval = 0, maxval = 10, inline = "ch", group = G_TF, tooltip = "The chart TF is always computed, even if it is not in the list, with its own number of OBs per side (bullish and bearish).")
nTF = input.int(4, "OBs per side, other TFs", minval = 0, maxval = 10, group = G_TF, tooltip = "Number of OBs per side (bullish and bearish) for each TF of the list. The % weight is computed on these OBs. 22 TFs × 2 sides × 4 OBs = 176 boxes at most, before the overlap filter.")
win = input.int(5000, "History: chart TF (bars)", minval = 500, maxval = 20000, inline = "win", group = G_TF)
winTF = input.int(1500, "other TFs (bars)", minval = 300, maxval = 5000, inline = "win", group = G_TF, tooltip = "Like « Window » in the original SMC: number of candles of each timeframe used for the calculation. On a 1h chart, 1500 candles of 1m = about 25 hours: older 1m OBs are not found. Lower it if the script is slow or shows a memory error.")
cTf1 = input.timeframe("1", "", inline = "cu1", group = G_CUS)
cOn1 = input.bool(true, "", inline = "cu1", group = G_CUS)
cTf2 = input.timeframe("3", "", inline = "cu1", group = G_CUS)
cOn2 = input.bool(true, "", inline = "cu1", group = G_CUS)
cTf3 = input.timeframe("5", "", inline = "cu2", group = G_CUS)
cOn3 = input.bool(true, "", inline = "cu2", group = G_CUS)
cTf4 = input.timeframe("15", "", inline = "cu2", group = G_CUS)
cOn4 = input.bool(true, "", inline = "cu2", group = G_CUS)
cTf5 = input.timeframe("30", "", inline = "cu3", group = G_CUS)
cOn5 = input.bool(true, "", inline = "cu3", group = G_CUS)
cTf6 = input.timeframe("60", "", inline = "cu3", group = G_CUS)
cOn6 = input.bool(true, "", inline = "cu3", group = G_CUS)
cTf7 = input.timeframe("120", "", inline = "cu4", group = G_CUS)
cOn7 = input.bool(true, "", inline = "cu4", group = G_CUS)
cTf8 = input.timeframe("240", "", inline = "cu4", group = G_CUS)
cOn8 = input.bool(true, "", inline = "cu4", group = G_CUS)
cTf9 = input.timeframe("480", "", inline = "cu5", group = G_CUS)
cOn9 = input.bool(true, "", inline = "cu5", group = G_CUS)
cTf10 = input.timeframe("720", "", inline = "cu5", group = G_CUS)
cOn10 = input.bool(true, "", inline = "cu5", group = G_CUS)
cTf11 = input.timeframe("D", "", inline = "cu6", group = G_CUS)
cOn11 = input.bool(true, "", inline = "cu6", group = G_CUS)
cTf12 = input.timeframe("3D", "", inline = "cu6", group = G_CUS)
cOn12 = input.bool(true, "", inline = "cu6", group = G_CUS)
cTf13 = input.timeframe("W", "", inline = "cu7", group = G_CUS)
cOn13 = input.bool(true, "", inline = "cu7", group = G_CUS)
cTf14 = input.timeframe("M", "", inline = "cu7", group = G_CUS)
cOn14 = input.bool(true, "", inline = "cu7", group = G_CUS)
cTf15 = input.timeframe("2", "", inline = "cu8", group = G_CUS)
cOn15 = input.bool(false, "", inline = "cu8", group = G_CUS)
cTf16 = input.timeframe("10", "", inline = "cu8", group = G_CUS, tooltip = "16 slots: pick a TF and tick it to use it. A TF listed twice, or equal to the chart TF when « Always include the chart TF » is ticked, is only computed once.")
cOn16 = input.bool(false, "", inline = "cu8", group = G_CUS)
// colours of the OBs (all TFs) and border per TF class: 1 = below 15m, 2 = 15m to 1h, 3 = 1h to 4h, 4 = 4h to 1D, 5 = 1D and above
cUp = input.color(color.new(#089981, 97), "OB colours: bullish", inline = "k0", group = G_COL)
cDn = input.color(color.new(#f23645, 97), "bearish", inline = "k0", group = G_COL, tooltip = "Fill colours of the OBs of every TF. Overlapping OBs of several TFs look darker because their boxes stack up.")
T_CL = "Border of the OBs of this class of timeframes. The border is also used for the FVGs of these TFs."
bs1 = input.string("None", "Border: below 15m", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL, tooltip = T_CL)
bs2 = input.string("None", "Border: 15m to 1h", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)
bs3 = input.string("None", "Border: 1h to 4h", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)
bs4 = input.string("None", "Border: 4h to 1D", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)
bs5 = input.string("None", "Border: 1D and above", options = ["None", "Solid", "Dashed", "Dotted"], group = G_COL)
msmode = input.string("Adjusted Points", "Structure logic", options = ["Extreme Points", "Adjusted Points"], inline = "node", group = G_OB, tooltip = "Same as « Algorithmic Logic » in the original SMC. The number = pivot length.")
mslen = input.int(5, "", minval = 2, inline = "node", group = G_OB)
buildsweep = input.bool(true, "Sweeps (x)", group = G_OB, tooltip = "Same as « Build Sweep (x) »: a wick beyond a structure level without a close beyond it moves that level.")
obmode = input.string("Length", "Construction", options = ["Length", "Full"], inline = "atr", group = G_OB, tooltip = "[Length] OB height limited to ATR(200) × number / 5\n[Full] whole candle")
len = input.int(5, "", minval = 1, inline = "atr", group = G_OB)
obmiti = input.string("Close", "Invalidation", options = ["Close", "Wick", "Avg"], group = G_OB, tooltip = "[Close] the body of a candle of the OB's timeframe closes beyond it\n[Wick] the wick goes beyond it\n[Avg] the wick reaches the middle of the OB")
showmetric = input.bool(true, "Volume and weight (%)", group = G_AFF)
showline = input.bool(false, "Mid-line", group = G_AFF)
showLeg = input.bool(true, "Legend", inline = "leg", group = G_AFF)
legPos = input.string("Bottom left", "", options = ["Bottom left", "Bottom right", "Top right", "Top left"], inline = "leg", group = G_AFF, tooltip = "Legend: range of TFs computed for the OBs and the FVGs. Bottom left by default so it stays clear of the TradingView buttons and of the OB labels on the right.")
obtxt = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "txt", group = G_AFF)
txtCol = input.color(color.new(color.white, 50), "Color", inline = "txt", group = G_AFF, tooltip = "Text color of the labels (OB and FVG) and of the legend.")
labOff = input.int(0, "Labels: offset", minval = 0, maxval = 200, inline = "lab", group = G_AFF)
labMode = input.string("One label per overlap zone", "Labels", options = ["One label per overlap zone", "One label per OB", "No OB labels"], group = G_AFF, tooltip = "[One label per overlap zone] the OBs of all TFs that overlap (same direction) share one label: TF list, number of TFs, best stars. Volume and V/I/R details are not shown.\n[One label per OB] one label per OB with all the details, shifted per TF class (can pile up).\n[No OB labels] boxes only.")
labRange = input.bool(false, "Price range in the overlap-zone labels", group = G_AFF, tooltip = "Adds the bottom and top prices of the whole group of overlapping OBs to its label. The label itself sits on the band where the most OBs of the group overlap.")
labStep = input.int(11, "spacing between TF classes", minval = 0, maxval = 100, inline = "lab", group = G_AFF, tooltip = "Horizontal offset (in bars) of the labels to the right of price, and spacing between the labels of each TF class (below 15m, 15m-1h, 1h-4h, 4h-1D, 1D and above) so they don't overlap.")
obBWidth = input.int(1, "OB border: width", minval = 1, maxval = 5, inline = "obb", group = G_AFF)
obBOpac = input.int(70, "opacity (%)", minval = 0, maxval = 100, inline = "obb", group = G_AFF, tooltip = "Width and opacity of the OB borders, for TF classes whose border is not None. 100 = fully opaque.")
maxDist = input.float(0.0, "Max distance from price (%)", minval = 0, step = 0.5, group = G_AFF, tooltip = "Hides the OBs and FVGs farther from the current price than this percentage. 0 = no limit.")
// ── FAIR VALUE GAPS (from the original SMC, on the chart TF)
fvg_enable = input.bool(true, "", inline="1", group="FAIR VALUE GAP", tooltip="Master switch: shows or hides ALL fair value gaps, on every timeframe. The TFs of the list showing FVGs are set in « TIMEFRAMES ».")
fvg_num = input.int(4, "Show Last", inline="1a", group="FAIR VALUE GAP", tooltip="Number of fvg to show", minval=0)
fvg_upcss = input.color(color.new(#067a67, 96), "", inline="1", group="FAIR VALUE GAP", tooltip="Bullish / bearish FVG colours: by default a slightly darker shade of the OB green and red, so FVGs and OBs can be told apart.")
fvg_dncss = input.color(color.new(#c12b37, 95), "", inline="1", group="FAIR VALUE GAP")
fvg_src = input.string("Close", "Mitigation",
inline="3",
group="FAIR VALUE GAP",
tooltip="[Close] Use the close of the body as trigger\n\n[Wick] Use the extreme point of the body as trigger",
options=["Close", "Wick", "Avg"])
fvgthresh = input.float(0, "Threshold", tooltip="Filter out non significative FVG", group="FAIR VALUE GAP",
inline="asd", minval=0, maxval=2, step=0.1)
fvgoverlap = input.bool(true, "Hide Overlap", "Hide overlapping FVG", group="FAIR VALUE GAP")
fvgChart = input.bool(false, "FVGs of the chart TF", group="FAIR VALUE GAP")
fvgMtfN = input.int(4, "FVGs per side, other TFs", minval = 1, maxval = 10, group="FAIR VALUE GAP", tooltip = "Number of FVGs shown per side for each TF of the list. The chart TF uses « Show Last » above.")
fvgOvStep = input.int(5, "Overlapping FVGs: opacity added per overlapping TF (%)", minval = 0, maxval = 10, inline = "fvo", group="FAIR VALUE GAP")
fvgOvCap = input.int(5, "max (%)", minval = 0, maxval = 50, inline = "fvo", group="FAIR VALUE GAP", tooltip = "An FVG gets this many % less transparent for each other TF with a same-direction FVG overlapping it, up to the max. 0 = no effect.")
fvgMtfLab = input.bool(false, "TF label on other-TF FVGs", group="FAIR VALUE GAP")
fvgMtfOut = input.bool(false, "Dashed outline on other-TF FVGs", group="FAIR VALUE GAP", tooltip = "When the TF class border is None, draws a thin dashed outline around the FVGs of the other timeframes so they stand out from the chart-TF FVGs. Untick: no outline at all.")
G_SUP = "OVERLAP FILTER"
obOnlyOv = input.bool(true, "Only show OBs overlapping OBs of other TFs", inline = "oo", group = G_SUP)
obMinOv = input.int(2, "minimum number of TFs", minval = 1, maxval = 35, inline = "oo", group = G_SUP, tooltip = "An OB stays visible only if it overlaps (at least partly) same-direction OBs of at least this number of OTHER timeframes. 1 = one other TF is enough. Raise it to keep only the strongest confluences.")
obKeepLast = input.bool(true, " … except the most recent OB", group = G_SUP, tooltip = "When the filter above is on, the most recent OB (all timeframes and both directions) stays visible even if it overlaps nothing.")
obKeepCh = input.bool(true, " … except the OBs of the chart TF", group = G_SUP, tooltip = "When the filter above is on, all OBs of the chart TF stay visible, overlapping or not. The other timeframes are still filtered.")
fvgOnlyOv = input.bool(true, "Only show FVGs overlapping an FVG of another TF", group = G_SUP, tooltip = "An FVG stays visible only if it overlaps (at least partly) a same-direction FVG of another timeframe.")
showOvN = input.bool(true, "Show the number of overlapping TFs in the OB label", group = G_SUP, tooltip = "Adds « +N TF » to the label: number of other timeframes whose same-direction OBs overlap this OB.")
minTr = input.int(93, "Minimum transparency of one OB (%)", minval = 0, maxval = 100, group = G_SUP, tooltip = "No single OB is drawn more opaque than this, whatever its stars, ◆ or overlaps. The confluence zones still look darker because the boxes of several TFs stack up. 100 = invisible, 90 = quite visible.")
G_FOR = "OB STRENGTH"
showStr = input.bool(true, "Rate OB strength (★ to ★★★★★)", group = G_FOR, tooltip = "1 star per criterion met (5 at most): V volume of the OB candle, I strength of the initial impulse, R best bounce on retests, F the impulse left a fair value gap, S the OB swept liquidity (took out the previous swing high / low, then price closed back inside). More stars = more opaque zone.")
showDetV = input.bool(true, "Details: V", inline = "det", group = G_FOR)
showDetI = input.bool(false, "I", inline = "det", group = G_FOR)
showDetR = input.bool(false, "R", inline = "det", group = G_FOR)
showDetF = input.bool(false, "F", inline = "det", group = G_FOR)
showDetS = input.bool(false, "S", inline = "det", group = G_FOR, tooltip = "Tick each detail to show it in the OB label (« One label per OB » mode):\nV = volume of the OB candle / 20-period average\nI = impulse: distance between the OB and the close that broke structure, in ATR(14)\nR = number of retests / best bounce in ATR(14)\nF = shown when the impulse leaving the OB left a fair value gap\nS = shown when the OB swept liquidity")
thrV = input.float(1.5, "Strong volume if ≥ × average", minval = 0.1, step = 0.1, group = G_FOR)
thrI = input.float(3.0, "Strong impulse if ≥ (ATR)", minval = 0.1, step = 0.5, group = G_FOR)
thrR = input.float(2.0, "Strong bounce if ≥ (ATR)", minval = 0.1, step = 0.5, group = G_FOR)
swBars = input.int(3, "Sweep: close back within (candles)", minval = 0, maxval = 20, group = G_FOR, tooltip = "Star S: the OB candle went beyond the last swing low (bullish OB) or swing high (bearish OB) confirmed before it, and a close came back on the other side of that level within this many candles. 0 = the OB candle itself must close back.")
opStep = input.int(1, "Opacity added per star", minval = 0, maxval = 40, group = G_FOR)
wOn = input.bool(true, "Heavy OBs: solid border", group = G_FOR, tooltip = "Weight = volume of the OB / average volume of the last OBs of the same TF and same side. From the threshold below, the OB keeps its normal fill but gets a solid border in its own colour, so heavy OBs stand out without darkening the chart. The labels show its volume multiple and rank (vol ×2.4 top 3%).")
wMin = input.float(2.0, "Heavy from (× average)", minval = 1.0, step = 0.5, group = G_FOR)
volHist = input.int(50, "Volume reference: last N OBs of the TF", minval = 5, maxval = 200, group = G_FOR, tooltip = "The volume of each OB is compared with the average volume of the last N OBs of the same TF and same side, formed before it. ×3 = three times the usual OB volume on that TF.")
vxMin = input.float(1.5, "Show the volume multiple from (× average)", minval = 0.0, step = 0.5, group = G_FOR, tooltip = "The labels show « vol ×3.2 » (the heaviest OB of an overlap zone, or each OB in « One label per OB » mode) only for OBs at least this many times the average volume. 0 = every OB.")
vxRank = input.bool(true, "Add the rank (top N %)", group = G_FOR, tooltip = "Adds the rank of the OB volume among the last N OBs of the same TF and side: « top 5 % » = only 5 % of them had a higher volume. More reliable than the multiple when a few huge OBs inflate the average.")
markNest = input.bool(true, "Mark ◆ OBs contained in a higher-TF OB", group = G_IMB, tooltip = "An OB is marked ◆ if it lies within a same-direction, still active OB of a higher timeframe.")
nestMode = input.string("Inside", "Condition", options = ["Inside", "Overlap"], group = G_IMB, tooltip = "[Inside] the OB is fully contained in the higher-TF OB\n[Overlap] the two zones overlap at least partly")
nestBStyle = input.string("Same as TF", "Nested OB border", options = ["Same as TF", "Solid", "Dashed", "Dotted", "None"], inline = "nb", group = G_IMB, tooltip = "Border of OBs marked ◆.\n[Same as TF] same border as the other OBs of that TF class\n[Solid / Dashed / Dotted] custom border, with the width and opacity set here\n[None] no border; the ◆ stays in the label")
nestBWidth = input.int(2, "width", minval = 1, maxval = 5, inline = "nb", group = G_IMB)
nestBOpac = input.int(100, "Nested OB border opacity (%)", minval = 0, maxval = 100, group = G_IMB, tooltip = "Opacity of the custom border of nested OBs. 100 = fully opaque, 0 = invisible.")
nestFill = input.int(1, "Extra fill opacity for nested OBs (%)", minval = 0, maxval = 50, group = G_IMB, tooltip = "Opacity added to the fill of OBs marked ◆, on top of their colour and their stars, so nested OBs stand out. 0 = same fill as the other OBs.")
// ── END OF ZONES
G_END = "END OF ZONES"
endOn = input.bool(true, "End OBs and FVGs when a chart-TF candle closes through them", group = G_END, tooltip = "An OB of a higher TF normally stays active until a candle of ITS OWN TF closes through it, so its band can cross many chart candles. With this option, the zone stops at the first chart-TF candle that closes through it (same rule as « Invalidation » for the OBs and « Mitigation » for the FVGs). Display only: the OB is still computed in its own TF.")
endMode = input.string("Stop the box at the break", "Broken zones", options = ["Stop the box at the break", "Hide broken zones"], group = G_END, tooltip = "[Stop the box at the break] the zone is drawn from its start to the candle that broke it, without label\n[Hide broken zones] the zone disappears completely")
// ── FVG FILTERS AND LOOK (all optional, off by default)
G_FVO = "FVG FILTERS AND LOOK (optional)"
fv1 = input.bool(false, "1. Minimum size", inline = "fv1", group = G_FVO)
fv1Atr = input.float(0.5, "(× ATR14 of its TF)", minval = 0.0, step = 0.1, inline = "fv1", group = G_FVO, tooltip = "Keeps only the FVGs at least this many ATR(14) high, ATR of their own TF at the time they formed. Removes the tiny gaps.")
fv2 = input.bool(false, "2. Strong middle candle", inline = "fv2", group = G_FVO)
fv2Min = input.float(1.5, "(body or volume ≥ × average)", minval = 0.0, step = 0.1, inline = "fv2", group = G_FVO, tooltip = "Keeps only the FVGs whose middle candle has a body OR a volume at least this many times its 20-candle average: gaps created by a real displacement.")
fv3 = input.bool(true, "3. Show only the unfilled part", group = G_FVO, tooltip = "When price enters an FVG, the box shrinks to the part still unfilled (wicks included). A half-filled FVG only shows its remaining half.")
fv4 = input.bool(false, "4. Only the nearest FVGs", inline = "fv4", group = G_FVO)
fv4N = input.int(2, "(per side of price)", minval = 1, maxval = 20, inline = "fv4", group = G_FVO, tooltip = "Keeps only the N FVGs closest to price above it and the N closest below it, all TFs together. FVGs containing the price are always kept.")
fv5 = input.bool(false, "5. Only FVGs touching an OB", group = G_FVO, tooltip = "Keeps only the FVGs overlapping a same-direction OB kept by the OB filters (even if the OBs are hidden).")
fv6 = input.bool(false, "6. Outline only, with a 50 % line", group = G_FVO, tooltip = "No fill: a thin dotted outline and a dotted line at the middle of the FVG (50 %, « consequent encroachment »). The OBs stay filled bands, the FVGs become frames.")
fv7 = input.bool(false, "7. Short boxes", inline = "fv7", group = G_FVO)
fv7Bars = input.int(20, "(chart candles after the FVG)", minval = 3, maxval = 500, inline = "fv7", group = G_FVO, tooltip = "The FVG box stops this many chart candles after its start instead of extending to the right edge.")
fv8 = input.bool(true, "8. Own colours", inline = "fv8", group = G_FVO)
fv8Up = input.color(color.new(#3949ab, 90), "", inline = "fv8", group = G_FVO)
fv8Dn = input.color(color.new(#7b1fa2, 90), "", inline = "fv8", group = G_FVO, tooltip = "Bullish / bearish FVG colours used instead of the green / red ones, so FVGs cannot be confused with OBs.")
// ── FVG STRENGTH (stars, like the OBs)
G_FST = "FVG STRENGTH (optional)"
fsOn = input.bool(false, "Rate FVG strength (★ to ★★★★★)", group = G_FST, tooltip = "1 star per criterion met (5 at most), measured in the FVG's own TF:\nV = volume of the middle candle vs its 20-candle average\nD = share of the middle candle volume in the FVG direction (buy share for a bullish FVG, sell share for a bearish one), estimated from where the candle closed in its range\nT = size of the gap vs the largest gap of the last 1000 candles (filter of Volumatic Fair Value Gaps [BigBeluga])\nO = the FVG touches a same-direction OB kept by the OB filters\nI = the FVG is still mostly intact (filled less than the % below)\nMore stars = more opaque FVG.")
fsV = input.float(1.5, "V: volume ≥ × average", minval = 0.1, step = 0.1, group = G_FST)
fsD = input.float(65, "D: volume in the FVG direction ≥ (%)", minval = 50, maxval = 100, step = 5, group = G_FST)
fsT = input.float(10, "T: size ≥ % of the largest FVG (1000 candles)", minval = 0, maxval = 100, step = 5, group = G_FST)
fsI = input.float(50, "I: filled less than (%)", minval = 1, maxval = 100, step = 5, group = G_FST)
fsStep = input.int(1, "Opacity added per star (%)", minval = 0, maxval = 20, group = G_FST)
fsMin = input.int(0, "Hide FVGs below (stars)", minval = 0, maxval = 5, group = G_FST, tooltip = "0 = all FVGs are shown. 3 = only the FVGs with at least 3 stars.")
fsLab = input.bool(true, "Show the stars on each FVG", group = G_FST, tooltip = "Small ★ text at the start of each active FVG (nothing when it has no star).")
bool fsh1 = fvg_enable and fvgChart
// with one of the FVG options, the chart-TF FVGs are taken from the chart-TF request (same engine as the other TFs)
// the chart-TF FVGs always come from the chart-TF request (same engine as the other TFs)
bool fvUseReq = incChart
bool obshowbb = false // breakers not shown (default of the original SMC): an invalidated OB disappears
plot(na, "", display = display.none, editable = false) // mandatory output (like the plot(na) of the original SMC)
// ───────────────────────────────────── TYPES (from the original SMC) ─────────────────────────────────────
type FVG
float top = na
float btm = na
int loc = na
bool isbb = false
int bbloc = na
bool israid = false
float raidy = na
int raidloc = na
int raidx2 = na
bool active = false
color raidcs = na
float ftop = na
float fbtm = na
float sz = na
float imp = na
float vr = na
float dom = na
float rel = na
type store
line [] ln
label [] lb
box [] bx
linefill[] lf
type structure
int zn
float zz
float bos
float choch
int loc
int temp
int trend
int start
float main
int xloc
bool upsweep
bool dnsweep
string txt = na
type ob
bool bull
float top
float btm
float avg
int loc
color css
float vol
int dir
int move
int blPOS
int brPOS
int xlocbl
int xlocbr
bool isbb = false
int bbloc
float vr = na
float disp = na
int nret = 0
float retX = na
float bestRet = 0.0
float wr = na
float rk = na
int fg = 0
int sw = 0
// ───────────────────────────────────── METHODS (from the original SMC) ─────────────────────────────────────
method txSz(string s) =>
out = switch s
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
out
method find(structure ms, bool use_max, bool sweep, bool useob) =>
min = 99999999.0
max = 0.0
idx = 0
if not sweep
if ((bar_index - ms.loc) - 1) > 0
if use_max
for i = 0 to (bar_index - ms.loc) - 1
max := math.max(high[i], max)
min := max == high[i] ? low[i] : min
idx := max == high[i] ? i : idx
if useob
if high[idx + 1] > high[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
else
for i = 0 to (bar_index - ms.loc) - 1
min := math.min(low[i], min)
max := min == low[i] ? high[i] : max
idx := min == low[i] ? i : idx
if useob
if low[idx + 1] < low[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
else
if use_max
for i = 0 to (bar_index - ms.loc)
max := math.max(high[i], max)
min := max == high[i] ? low[i] : min
idx := max == high[i] ? i : idx
if useob
if high[idx + 1] > high[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
else
for i = 0 to (bar_index - ms.loc)
min := math.min(low[i], min)
max := min == low[i] ? high[i] : max
idx := min == low[i] ? i : idx
if useob
if low[idx + 1] < low[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
else
if ((bar_index - ms.xloc) - 1) > 0
if use_max
for i = 0 to (bar_index - ms.xloc) - 1
max := math.max(high[i], max)
min := max == high[i] ? low[i] : min
idx := max == high[i] ? i : idx
if useob
if high[idx + 1] > high[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
else
for i = 0 to (bar_index - ms.xloc) - 1
min := math.min(low[i], min)
max := min == low[i] ? high[i] : max
idx := min == low[i] ? i : idx
if useob
if low[idx + 1] < low[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
else
if use_max
for i = 0 to (bar_index - ms.xloc)
max := math.max(high[i], max)
min := max == high[i] ? low[i] : min
idx := max == high[i] ? i : idx
if useob
if high[idx + 1] > high[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
else
for i = 0 to (bar_index - ms.xloc)
min := math.min(low[i], min)
max := min == low[i] ? high[i] : max
idx := min == low[i] ? i : idx
if useob
if low[idx + 1] < low[idx]
max := high[idx + 1]
min := low [idx + 1]
idx := idx + 1
idx
method fnOB(ob[] block, bool bull, float cords, int idx) =>
switch bull
true =>
block.unshift(ob.new(true, cords, low[idx], math.avg(cords, low[idx]), time[idx], color.teal, volume[idx], close[idx] > open[idx] ? 1 : -1, 1, 1, 1, time[idx]))
false =>
block.unshift(ob.new(false, high[idx], cords, math.avg(cords, high[idx]), time[idx], color.red, volume[idx], close[idx] > open[idx] ? 1 : -1, 1, 1, 1, time[idx]))
method mitigated(ob[] block) =>
if barstate.isconfirmed
for [i, stuff] in block
if not stuff.isbb
switch stuff.bull
true =>
if obmiti == "Close" ? math.min(close, open) < stuff.btm : obmiti == "Wick" ? low < stuff.btm : obmiti == "Avg" ? low < stuff.avg : false
stuff.isbb := true
stuff.bbloc := time
if not obshowbb
block.remove(i)
false =>
if obmiti == "Close" ? math.max(close, open) > stuff.top : obmiti == "Wick" ? high > stuff.top : obmiti == "Avg" ? high > stuff.avg : false
stuff.isbb := true
stuff.bbloc := time
if not obshowbb
block.remove(i)
else
switch stuff.bull
true =>
if obmiti == "Close" ? math.max(close, open) > stuff.top : obmiti == "Wick" ? high > stuff.top : obmiti == "Avg" ? high > stuff.avg : false
block.remove(i)
false =>
if obmiti == "Close" ? math.min(close, open) < stuff.btm : obmiti == "Wick" ? low < stuff.btm : obmiti == "Avg" ? low < stuff.avg : false
block.remove(i)
// ───────────────────────────────────── OB ENGINE (one instance per TF) ─────────────────────────────────────
// Same as the structure() function of the original SMC without the drawings (BOS/CHoCH, creation,
// invalidation and overlap of the OBs), then returns the active OBs as text:
// "dir,top,bottom,time,volume,vol ratio,impulse,retests,best bounce,weight,rank,fvg,sweep;" (1 = bullish, -1 = bearish)
// volume of a new OB compared with the last OBs of the same TF and side (history h, before adding it):
// ratio = volume / average volume, rank = % of those OBs with a lower volume
f_volRank(float[] h, float v) =>
float ratio = na
float rank = na
int n = h.size()
if n > 0 and not na(v)
float avg = h.avg()
ratio := avg > 0 ? v / avg : na
int below = 0
for x in h
if x < v
below += 1
rank := below * 100.0 / n
h.unshift(nz(v))
if h.size() > volHist
h.pop()
[ratio, rank]
// star F: a 3-candle gap in the impulse direction between the OB candle (idx bars ago) and the current bar
f_impFvg(bool bull, int idx) =>
int res = 0
int lim = math.min(idx, 300)
if lim >= 2
for k = 0 to lim - 2
if bull ? low[k] > high[k + 2] : high[k] < low[k + 2]
res := 1
break
res
// star S: the OB candle took out the last swing confirmed before it, and a close came back within swBars candles
f_sweep(bool bull, int idx, float[] pP, int[] pB) =>
int res = 0
float lvl = na
if pP.size() > 0
for j = 0 to pP.size() - 1
if pB.get(j) < bar_index - idx
lvl := pP.get(j)
break
if not na(lvl) and idx <= 4900
bool beyond = bull ? low[idx] < lvl : high[idx] > lvl
if beyond
int kMin = math.max(0, idx - swBars)
for k = idx to kMin
if bull ? close[k] > lvl : close[k] < lvl
res := 1
break
res
f_obState(bool act, int nShow) =>
var structure ms = structure.new(start = 0)
var ob[] blob = array.new<ob>()
var ob[] brob = array.new<ob>()
var float up = na
var float dn = na
var int[] phn = array.new<int>(1, na)
var int[] pln = array.new<int>(1, na)
var float[] php = array.new<float>(1, na)
var float[] plp = array.new<float>(1, na)
var string cache = ""
var int sigB = -1
var int sigR = -1
var int locB = -1
var int locR = -1
float atrL = ta.atr(200) / (5.0 / len)
float ph = ta.pivothigh(high, mslen, mslen)
float pl = ta.pivotlow (low , mslen, mslen)
float vma = ta.sma(volume, 20)
float a14 = ta.atr(14)
var float lastChk = -1.0
var float[] hvB = array.new<float>()
var float[] hvR = array.new<float>()
var float[] swHP = array.new<float>()
var int[] swHB = array.new<int>()
var float[] swLP = array.new<float>()
var int[] swLB = array.new<int>()
bool crossup = false
bool crossdn = false
// the structure starts once ATR(200) is available (200 warm-up bars on top of the window)
if act and not na(atrL)
int nb0 = blob.size()
int nr0 = brob.size()
idbull = na(ms.loc) ? 0 : ms.find(false, false, true)
idbear = na(ms.loc) ? 0 : ms.find(true , false, true)
btmP = obmode == "Length" ? (high[idbear] - 1 * atrL[idbear]) < low [idbear] ? low [idbear] : (high[idbear] - 1 * atrL[idbear]) : low [idbear]
topP = obmode == "Length" ? (low [idbull] + 1 * atrL[idbull]) > high[idbull] ? high[idbull] : (low [idbull] + 1 * atrL[idbull]) : high[idbull]
if not na(ph)
phn.unshift(bar_index[mslen])
php.unshift(high[mslen])
swHP.unshift(high[mslen]), swHB.unshift(bar_index)
if swHP.size() > 30
swHP.pop(), swHB.pop()
if not na(pl)
pln.unshift(bar_index[mslen])
plp.unshift(low[mslen])
swLP.unshift(low[mslen]), swLB.unshift(bar_index)
if swLP.size() > 30
swLP.pop(), swLB.pop()
if php.size() > 0
if high > php.get(0)
php.clear()
phn.clear()
if plp.size() > 0
if low < plp.get(0)
plp.clear()
pln.clear()
if na(up)
up := high
if na(dn)
dn := low
if high > up
up := high
dn := low
crossup := true
if low < dn
up := high
dn := low
crossdn := true
if ms.start == 0
ms := structure.new(bar_index, na, high, low, bar_index, bar_index, 0, 1, na, bar_index)
ms.upsweep := false
ms.dnsweep := false
if ms.start == 1
switch
low <= ms.choch and close >= ms.choch and buildsweep =>
ms.dnsweep := true
ms.choch := low
ms.xloc := bar_index
high >= ms.bos and close <= ms.bos and buildsweep =>
ms.upsweep := true
ms.bos := high
ms.xloc := bar_index
close <= ms.choch =>
ms.txt := "choch"
blob.fnOB(true, topP, idbull)
ms.trend := -1
ms.choch := ms.bos
ms.bos := na
ms.start := 2
ms.loc := bar_index
ms.main := low
ms.temp := ms.loc
ms.xloc := bar_index
close >= ms.bos =>
ms.txt := "choch"
brob.fnOB(false, btmP, idbear)
ms.trend := 1
ms.choch := ms.choch
ms.bos := na
ms.start := 2
ms.loc := bar_index
ms.main := high
ms.temp := ms.loc
ms.xloc := bar_index
if ms.start == 2
switch ms.trend
-1 =>
if low <= ms.main
ms.main := low
ms.temp := bar_index
if bar_index % mslen * 2 == 0
if not na(ms.bos) and msmode == "Adjusted Points" and php.size() > 0
if php.get(0) < ms.choch
ms.choch := php.get(0)
ms.loc := phn.get(0)
ms.xloc := phn.get(0)
ms.temp := phn.get(0)
if na(ms.bos)
if crossup and close > open and close[1] > open[1]
ms.bos := ms.main
ms.loc := ms.temp
ms.xloc := ms.loc
switch
low <= ms.bos and close >= ms.bos and not na(ms.bos) and buildsweep =>
ms.dnsweep := true
ms.bos := low
ms.xloc := bar_index
close <= ms.bos and not na(ms.bos) =>
ms.txt := "bos"
ms.zz := ms.bos
ms.zn := bar_index
brob.fnOB(false, btmP, idbear)
id = ms.find(true, false, false)
ms.xloc := bar_index
ms.bos := na
ms.choch := high[id]
ms.loc := bar_index[id]
switch
high >= ms.choch and close <= ms.choch and buildsweep =>
ms.upsweep := true
ms.choch := high
ms.xloc := bar_index
close >= ms.choch =>
ms.txt := "choch"
ms.zz := ms.choch
ms.zn := bar_index
blob.fnOB(true, topP, idbull)
id = ms.find(false, false, false)
switch
na(ms.bos) =>
ms.choch := low[id]
=>
ms.choch := ms.bos
ms.bos := na
ms.main := high
ms.trend := 1
ms.loc := bar_index
ms.xloc := bar_index
ms.temp := ms.loc
ms.xloc := bar_index
1 =>
if high >= ms.main
ms.main := high
ms.temp := bar_index
if na(ms.bos)
if crossdn and close < open and close[1] < open[1]
ms.bos := ms.main
ms.loc := ms.temp
ms.xloc := ms.loc
if bar_index % mslen * 2 == 0
if not na(ms.bos) and msmode == "Adjusted Points" and plp.size() > 0
if plp.get(0) > ms.choch
ms.choch := plp.get(0)
ms.loc := pln.get(0)
ms.xloc := pln.get(0)
ms.temp := pln.get(0)
switch
high >= ms.bos and close <= ms.bos and not na(ms.bos) and buildsweep =>
ms.upsweep := true
ms.bos := high
ms.xloc := bar_index
close >= ms.bos and not na(ms.bos) =>
ms.txt := "bos"
ms.zz := ms.bos
ms.zn := bar_index
blob.fnOB(true, topP, idbull)
id = ms.find(false, false, false)
ms.xloc := bar_index
ms.bos := na
ms.choch := low[id]
ms.loc := bar_index[id]
switch
low <= ms.choch and close >= ms.choch and buildsweep =>
ms.dnsweep := true
ms.choch := low
ms.xloc := bar_index
close <= ms.choch =>
ms.txt := "choch"
ms.zz := ms.choch
ms.zn := bar_index
brob.fnOB(false, btmP, idbear)
id = ms.find(true, false, false)
switch
na(ms.bos) =>
ms.choch := high[id]
=>
ms.choch := ms.bos
ms.bos := na
ms.main := low
ms.trend := -1
ms.loc := bar_index
ms.temp := ms.loc
ms.xloc := bar_index
// strength: volume of the OB candle and initial impulse
if blob.size() > nb0
o0 = blob.get(0)
o0.vr := nz(vma[idbull]) > 0 ? volume[idbull] / vma[idbull] : na
o0.disp := a14 > 0 ? (close - o0.btm) / a14 : na
[wr0, rk0] = f_volRank(hvB, o0.vol)
o0.wr := wr0
o0.rk := rk0
o0.fg := f_impFvg(true, idbull)
o0.sw := f_sweep(true, idbull, swLP, swLB)
if brob.size() > nr0
o0 = brob.get(0)
o0.vr := nz(vma[idbear]) > 0 ? volume[idbear] / vma[idbear] : na
o0.disp := a14 > 0 ? (o0.top - close) / a14 : na
[wr1, rk1] = f_volRank(hvR, o0.vol)
o0.wr := wr1
o0.rk := rk1
o0.fg := f_impFvg(false, idbear)
o0.sw := f_sweep(false, idbear, swHP, swHB)
// strength: retests (new entry into the zone) and best bounce from the zone
if blob.size() > 0
for o in blob
if low <= o.top and low[1] > o.top
o.nret += 1
o.retX := high
else if o.nret > 0
o.retX := math.max(nz(o.retX, high), high)
if a14 > 0
o.bestRet := math.max(o.bestRet, (o.retX - o.top) / a14)
if brob.size() > 0
for o in brob
if high >= o.btm and high[1] < o.btm
o.nret += 1
o.retX := low
else if o.nret > 0
o.retX := math.min(nz(o.retX, low), low)
if a14 > 0
o.bestRet := math.max(o.bestRet, (o.btm - o.retX) / a14)
// invalidation and overlaps (same as the SMC: only on a closed candle)
if barstate.isconfirmed
blob.mitigated()
brob.mitigated()
// text export of the active OBs (rebuilt only when the list changes)
int fb = blob.size() > 0 ? blob.get(0).loc : 0
int fr = brob.size() > 0 ? brob.get(0).loc : 0
float chk = 0.0
for o in blob
chk += o.nret * 1000 + o.bestRet
for o in brob
chk += o.nret * 1000 + o.bestRet
if blob.size() != sigB or brob.size() != sigR or fb != locB or fr != locR or chk != lastChk
lastChk := chk
sigB := blob.size()
sigR := brob.size()
locB := fb
locR := fr
string s = ""
int nb = math.min(nShow, blob.size())
if nb > 0
for i = 0 to nb - 1
o = blob.get(i)
s := s + "1," + str.tostring(o.top, "#.##########") + "," + str.tostring(o.btm, "#.##########") + "," + str.tostring(o.loc, "#") + "," + str.tostring(nz(o.vol), "#.####") + "," + str.tostring(nz(o.vr), "#.##") + "," + str.tostring(nz(o.disp), "#.##") + "," + str.tostring(o.nret) + "," + str.tostring(o.bestRet, "#.##") + "," + str.tostring(nz(o.wr, -1), "#.##") + "," + str.tostring(nz(o.rk, -1), "#") + "," + str.tostring(o.fg) + "," + str.tostring(o.sw) + ";"
int nr = math.min(nShow, brob.size())
if nr > 0
for i = 0 to nr - 1
o = brob.get(i)
s := s + "-1," + str.tostring(o.top, "#.##########") + "," + str.tostring(o.btm, "#.##########") + "," + str.tostring(o.loc, "#") + "," + str.tostring(nz(o.vol), "#.####") + "," + str.tostring(nz(o.vr), "#.##") + "," + str.tostring(nz(o.disp), "#.##") + "," + str.tostring(o.nret) + "," + str.tostring(o.bestRet, "#.##") + "," + str.tostring(nz(o.wr, -1), "#.##") + "," + str.tostring(nz(o.rk, -1), "#") + "," + str.tostring(o.fg) + "," + str.tostring(o.sw) + ";"
cache := s
cache
// ───────────────────────────── FVG OVERLAP (code of the original SMC, used by the FVG engine) ─────────────────────────────
overlapFVG(FVG[] blFVG, FVG[] brFVG) =>
if blFVG.size() > 1
for i = blFVG.size() - 1 to 1
stuff = blFVG.get(i)
current = blFVG.get(0)
switch
stuff.btm > current.btm and stuff.btm < current.top => blFVG.remove(i)
stuff.top < current.top and stuff.btm > current.btm => blFVG.remove(i)
stuff.top > current.top and stuff.btm < current.btm => blFVG.remove(i)
stuff.top < current.top and stuff.top > current.btm => blFVG.remove(i)
if brFVG.size() > 1
for i = brFVG.size() - 1 to 1
stuff = brFVG.get(i)
current = brFVG.get(0)
switch
stuff.btm > current.btm and stuff.btm < current.top => brFVG.remove(i)
stuff.top < current.top and stuff.btm > current.btm => brFVG.remove(i)
stuff.top > current.top and stuff.btm < current.btm => brFVG.remove(i)
stuff.top < current.top and stuff.top > current.btm => brFVG.remove(i)
if blFVG.size() > 0 and brFVG.size() > 0
for i = blFVG.size() - 1 to 0
stuff = blFVG.get(i)
current = brFVG.get(0)
switch
stuff.btm > current.btm and stuff.btm < current.top => blFVG.remove(i)
stuff.top < current.top and stuff.btm > current.btm => blFVG.remove(i)
stuff.top > current.top and stuff.btm < current.btm => blFVG.remove(i)
stuff.top < current.top and stuff.top > current.btm => blFVG.remove(i)
if blFVG.size() > 0 and brFVG.size() > 0
for i = brFVG.size() - 1 to 0
stuff = brFVG.get(i)
current = blFVG.get(0)
switch
stuff.btm > current.btm and stuff.btm < current.top => brFVG.remove(i)
stuff.top < current.top and stuff.btm > current.btm => brFVG.remove(i)
stuff.top > current.top and stuff.btm < current.btm => brFVG.remove(i)
stuff.top < current.top and stuff.top > current.btm => brFVG.remove(i)
f_fvgState(bool act, int nShow) =>
var FVG[] bl = array.new<FVG>()
var FVG[] br = array.new<FVG>()
var string fc = ""
var int sgB = -1
var int sgR = -1
var int lcB = -1
var int lcR = -1
var float fck = -1.0
float fa = ta.atr(200)
float f14 = ta.atr(14)
float bAv = ta.sma(math.abs(close - open), 20)
float vAv = ta.sma(volume, 20)
// star T: gap size in % of price, compared with the largest gap of the last 1000 candles (Volumatic FVG [BigBeluga])
float gpB = low > high[2] ? (low - high[2]) / low * 100 : 0.0
float gpR = low[2] > high ? (low[2] - high) / high * 100 : 0.0
float gp = math.max(gpB, gpR)
float gMx = nz(ta.highest(gp, 1000), ta.max(gp))
if act
// stars V and D: volume of the middle candle and its share in the FVG direction (close position in the range)
float vrN = nz(vAv[1]) > 0 ? volume[1] / vAv[1] : na
float rg1 = high[1] - low[1]
float buyF = rg1 > 0 ? (close[1] - low[1]) / rg1 : 0.5
float relN = nz(gMx) > 0 ? gp / gMx * 100 : na
// size (in ATR14) and strength of the middle candle (body or volume / 20-candle average)
float szN = f14 > 0 ? 1.0 / f14 : na
float impN = math.max(nz(bAv[1]) > 0 ? math.abs(close[1] - open[1]) / bAv[1] : 0.0, nz(vAv[1]) > 0 ? volume[1] / vAv[1] : 0.0)
if low > high[2] and close[1] > low[1] + nz(fa[1]) * fvgthresh
bl.unshift(FVG.new(low, high[2], time[2], false, na, sz = (low - high[2]) * nz(szN), imp = impN, vr = vrN, dom = buyF * 100, rel = relN))
if low[2] > high and close[1] < high[1] - nz(fa[1]) * fvgthresh
br.unshift(FVG.new(low[2], high, time[2], false, na, sz = (low[2] - high) * nz(szN), imp = impN, vr = vrN, dom = (1 - buyF) * 100, rel = relN))
// unfilled part: lowest low inside a bullish FVG / highest high inside a bearish FVG
for g in bl
g.ftop := math.max(g.btm, math.min(nz(g.ftop, g.top), low))
for g in br
g.fbtm := math.min(g.top, math.max(nz(g.fbtm, g.btm), high))
if bl.size() > 0
for i = bl.size() - 1 to 0
FVG g = bl.get(i)
bool hit = fvg_src == "Close" ? math.min(close, open) < g.btm : fvg_src == "Wick" ? low < g.btm : low < math.avg(g.top, g.btm)
if hit
bl.remove(i)
if br.size() > 0
for i = br.size() - 1 to 0
FVG g = br.get(i)
bool hit = fvg_src == "Close" ? math.max(close, open) > g.top : fvg_src == "Wick" ? high > g.top : high > math.avg(g.top, g.btm)
if hit
br.remove(i)
if fvgoverlap
overlapFVG(bl, br)
if bl.size() > 60
bl.pop()
if br.size() > 60
br.pop()
int fb = bl.size() > 0 ? bl.get(0).loc : 0
int fr = br.size() > 0 ? br.get(0).loc : 0
float ck = 0.0
int nkb = math.min(nShow, bl.size())
int nkr = math.min(nShow, br.size())
if nkb > 0
for i = 0 to nkb - 1
ck += nz(bl.get(i).ftop)
if nkr > 0
for i = 0 to nkr - 1
ck += nz(br.get(i).fbtm)
if bl.size() != sgB or br.size() != sgR or fb != lcB or fr != lcR or ck != fck
fck := ck
sgB := bl.size()
sgR := br.size()
lcB := fb
lcR := fr
string s = ""
int nb = math.min(nShow, bl.size())
if nb > 0
for i = 0 to nb - 1
FVG g = bl.get(i)
s := s + "1," + str.tostring(g.top, "#.##########") + "," + str.tostring(g.btm, "#.##########") + "," + str.tostring(g.loc, "#") + "," + str.tostring(nz(g.ftop, g.top), "#.##########") + "," + str.tostring(g.btm, "#.##########") + "," + str.tostring(nz(g.sz), "#.##") + "," + str.tostring(nz(g.imp), "#.##") + "," + str.tostring(nz(g.vr), "#.##") + "," + str.tostring(nz(g.dom), "#") + "," + str.tostring(nz(g.rel), "#.#") + ";"
int nr = math.min(nShow, br.size())
if nr > 0
for i = 0 to nr - 1
FVG g = br.get(i)
s := s + "-1," + str.tostring(g.top, "#.##########") + "," + str.tostring(g.btm, "#.##########") + "," + str.tostring(g.loc, "#") + "," + str.tostring(g.top, "#.##########") + "," + str.tostring(nz(g.fbtm, g.btm), "#.##########") + "," + str.tostring(nz(g.sz), "#.##") + "," + str.tostring(nz(g.imp), "#.##") + "," + str.tostring(nz(g.vr), "#.##") + "," + str.tostring(nz(g.dom), "#") + "," + str.tostring(nz(g.rel), "#.#") + ";"
fc := s
fc
// ───────────────────────────────────── ONE REQUEST PER TF: OBs + FVGs ─────────────────────────────────────
// value of the last CLOSED candle of the requested TF (no repaint): "OB list|FVG list"
f_req(int nOB, int nFV) =>
string s = f_obState(true, nOB) + "|" + f_fvgState(true, nFV)
s[1]
// ───────────────────────────────────── TOOLS ─────────────────────────────────────
f_tfName(string t) =>
int sec = timeframe.in_seconds(t)
int mn = int(math.round(sec / 60))
string r = ""
if sec >= 2419200 and str.endswith(t, "M")
r := (t == "M" ? "1" : str.replace(t, "M", "")) + "M"
else if sec < 60
r := str.tostring(sec) + "s"
else if mn < 60
r := str.tostring(mn) + "m"
else if mn < 1440
r := str.tostring(int(mn / 60)) + "h" + (mn % 60 > 0 ? (mn % 60 < 10 ? "0" : "") + str.tostring(mn % 60) : "")
else if mn % 10080 == 0
r := str.tostring(int(mn / 10080)) + "W"
else
r := str.tostring(int(mn / 1440)) + "D"
r
f_bstyle(string s) =>
s == "Dotted" ? line.style_dotted : s == "Dashed" ? line.style_dashed : line.style_solid
// TF class: 1 = below 15m, 2 = 15m to 1h, 3 = 1h to 4h, 4 = 4h to 1D, 5 = 1D and above
f_tier(int sec) =>
sec < 900 ? 1 : sec < 3600 ? 2 : sec < 14400 ? 3 : sec < 86400 ? 4 : 5
f_cu(int t) =>
cUp
f_cd(int t) =>
cDn
f_bs(int t) =>
t == 1 ? bs1 : t == 2 ? bs2 : t == 3 ? bs3 : t == 4 ? bs4 : bs5
// distance (%) between the current price and a zone (0 = price inside the zone)
f_dist(float zt, float zb) =>
close > zt ? (close - zt) / close * 100 : close < zb ? (zb - close) / close * 100 : 0.0
f_parse(string s, int slot, float[] aT, float[] aB, int[] aL, float[] aV, int[] aD, int[] aS, float[] aVR, float[] aDP, int[] aNR, float[] aBR, float[] aWR, float[] aRK, int[] aFG, int[] aSW) =>
if not na(s)
if str.length(s) > 0
string[] items = str.split(s, ";")
for it in items
if str.length(it) > 0
string[] f = str.split(it, ",")
if f.size() >= 9
aD.push(int(str.tonumber(f.get(0))))
aT.push(str.tonumber(f.get(1)))
aB.push(str.tonumber(f.get(2)))
aL.push(int(str.tonumber(f.get(3))))
aV.push(nz(str.tonumber(f.get(4))))
aS.push(slot)
aVR.push(nz(str.tonumber(f.get(5))))
aDP.push(nz(str.tonumber(f.get(6))))
aNR.push(int(nz(str.tonumber(f.get(7)))))
aBR.push(nz(str.tonumber(f.get(8))))
float wrx = f.size() >= 11 ? str.tonumber(f.get(9)) : na
float rkx = f.size() >= 11 ? str.tonumber(f.get(10)) : na
aWR.push(nz(wrx, -1) < 0 ? na : wrx)
aRK.push(nz(rkx, -1) < 0 ? na : rkx)
aFG.push(f.size() >= 13 ? int(nz(str.tonumber(f.get(11)))) : 0)
aSW.push(f.size() >= 13 ? int(nz(str.tonumber(f.get(12)))) : 0)
true
// ───────────────────────────────────── TF LISTS ─────────────────────────────────────
f_tfW(int k) =>
switch k
1 => "1"
2 => "3"
3 => "5"
4 => "10"
5 => "15"
6 => "30"
7 => "45"
8 => "60"
9 => "90"
10 => "120"
11 => "180"
12 => "240"
13 => "360"
14 => "480"
15 => "720"
16 => "D"
17 => "2D"
18 => "3D"
19 => "W"
20 => "2W"
21 => "3W"
22 => "M"
=> ""
f_tfF(int k) =>
switch k
1 => "1"
2 => "2"
3 => "3"
4 => "4"
5 => "5"
6 => "6"
7 => "8"
8 => "10"
9 => "12"
10 => "15"
11 => "20"
12 => "25"
13 => "30"
14 => "40"
15 => "45"
16 => "60"
17 => "75"
18 => "90"
19 => "105"
20 => "120"
21 => "150"
22 => "180"
23 => "240"
24 => "360"
25 => "480"
26 => "720"
27 => "D"
28 => "2D"
29 => "3D"
30 => "4D"
31 => "5D"
32 => "W"
33 => "2W"
34 => "3W"
35 => "M"
36 => "3M"
=> ""
f_tfC(int k) =>
switch k
1 => cOn1 ? cTf1 : ""
2 => cOn2 ? cTf2 : ""
3 => cOn3 ? cTf3 : ""
4 => cOn4 ? cTf4 : ""
5 => cOn5 ? cTf5 : ""
6 => cOn6 ? cTf6 : ""
7 => cOn7 ? cTf7 : ""
8 => cOn8 ? cTf8 : ""
9 => cOn9 ? cTf9 : ""
10 => cOn10 ? cTf10 : ""
11 => cOn11 ? cTf11 : ""
12 => cOn12 ? cTf12 : ""
13 => cOn13 ? cTf13 : ""
14 => cOn14 ? cTf14 : ""
15 => cOn15 ? cTf15 : ""
16 => cOn16 ? cTf16 : ""
=> ""
f_tf(int k) =>
tfList == "Custom list" ? f_tfC(k) : tfList == "Fine 1m → 3M (36 TFs)" ? f_tfF(k) : f_tfW(k)
int NS = tfList == "Custom list" ? 16 : tfList == "Fine 1m → 3M (36 TFs)" ? 36 : 22
// ───────────────────────────────────── REQUESTS ─────────────────────────────────────
// one slot per requested TF: slot 0 = chart TF (if ticked), then the TFs of the list.
// A TF outside both ranges (OB and FVG), or already requested, is not requested at all.
int secChart = timeframe.in_seconds()
string[] gTf = array.new<string>()
int[] gSec = array.new<int>()
bool[] gOb = array.new<bool>()
bool[] gFv = array.new<bool>()
string[] gRes = array.new<string>()
if incChart
string r0 = request.security(syminfo.tickerid, timeframe.period, f_req(nChart, fvgMtfN), calc_bars_count = win + 200)
gTf.push(timeframe.period)
gSec.push(secChart)
gOb.push(nChart > 0)
gFv.push(false) // the chart-TF FVGs are drawn by the original SMC code below
gRes.push(r0)
for k = 1 to NS
string tf = f_tf(k)
if tf != ""
int sc = timeframe.in_seconds(tf)
bool obk = nTF > 0 and float(sc) * obLoR >= secChart and sc <= float(secChart) * obHiR
bool fvk = fvg_enable and sc != secChart and float(sc) * fvLoR >= secChart and sc <= float(secChart) * fvHiR
if (obk or fvk) and not gSec.includes(sc)
string r = request.security(syminfo.tickerid, tf, f_req(nTF, fvgMtfN), calc_bars_count = winTF + 200)
gTf.push(tf)
gSec.push(sc)
gOb.push(obk)
gFv.push(fvk)
gRes.push(r)
int nSlot = gTf.size()
// ───────────────────────────────────── END OF ZONES ─────────────────────────────────────
// time of the first chart-TF candle (after the zone start) that closes through the zone, na if none.
// rule: "Close" = body beyond, "Wick" = wick beyond, "Avg" = wick beyond the middle (same as the OB / FVG settings)
f_breakTime(int loc, float top, float btm, int d, string rule) =>
int res = na
// first guess from the bar duration (exact on 24/7 markets), then a few steps to adjust
int tfMs = timeframe.in_seconds() * 1000
int n = math.max(0, math.min(math.min(4990, bar_index), int((time - loc) / tfMs)))
while n > 0 and time[n] <= loc
n -= 1
while n < math.min(4990, bar_index) and time[n] > loc
n += 1
if n > 0
float mid = math.avg(top, btm)
for j = n - 1 to 0
if j > 0 or barstate.isconfirmed
bool hit = d == 1 ? (rule == "Close" ? math.min(close[j], open[j]) < btm : rule == "Wick" ? low[j] < btm : low[j] < mid) : (rule == "Close" ? math.max(close[j], open[j]) > top : rule == "Wick" ? high[j] > top : high[j] > mid)
if hit
res := time[j]
break
res
// OBs kept by the filters (used by the FVG option « Only FVGs touching an OB »)
var float[] obCT = array.new<float>()
var float[] obCB = array.new<float>()
var int[] obCD = array.new<int>()
// ───────────────────────────────────── OB DRAWING (last bar) ─────────────────────────────────────
var box[] gBx = array.new<box>()
var line[] gLn = array.new<line>()
var label[] gLb = array.new<label>()
var table leg = table.new(legPos == "Top right" ? position.top_right : legPos == "Top left" ? position.top_left : legPos == "Bottom left" ? position.bottom_left : position.bottom_right, 1, 3)
var bool boxFull = false
if barstate.islast
for bx in gBx
bx.delete()
for ln in gLn
ln.delete()
for lb in gLb
lb.delete()
gBx.clear()
gLn.clear()
gLb.clear()
boxFull := false
obCT.clear()
obCB.clear()
obCD.clear()
// drawing order: the highest TF first (underneath), the lowest on top
int[] ordre = nSlot > 0 ? gSec.sort_indices(order.descending) : array.new<int>()
float[] zT = array.new<float>()
float[] zB = array.new<float>()
int[] zL = array.new<int>()
float[] zV = array.new<float>()
int[] zD = array.new<int>()
int[] zS = array.new<int>()
float[] zVR = array.new<float>()
float[] zDP = array.new<float>()
int[] zNR = array.new<int>()
float[] zBR = array.new<float>()
float[] zWR = array.new<float>()
float[] zRK = array.new<float>()
int[] zFG = array.new<int>()
int[] zSW = array.new<int>()
for slk in ordre
if gOb.get(slk)
string rs = gRes.get(slk)
if not na(rs)
string[] parts = str.split(rs, "|")
if parts.size() > 0
// the chart TF keeps nChart OBs per side, the other TFs nTF (already cut in the request)
f_parse(parts.get(0), slk, zT, zB, zL, zV, zD, zS, zVR, zDP, zNR, zBR, zWR, zRK, zFG, zSW)
// OBs already broken by a chart-TF close: drawn up to the break (or hidden), and left out of the rest
if endOn and zT.size() > 0
for i = zT.size() - 1 to 0
int brk = f_breakTime(zL.get(i), zT.get(i), zB.get(i), zD.get(i), obmiti)
if not na(brk)
if obShow and endMode == "Stop the box at the break" and gBx.size() < 495 and (maxDist <= 0 or f_dist(zT.get(i), zB.get(i)) <= maxDist)
color cb0 = zD.get(i) == 1 ? f_cu(f_tier(gSec.get(zS.get(i)))) : f_cd(f_tier(gSec.get(zS.get(i))))
gBx.push(box.new(left = zL.get(i), top = zT.get(i), right = brk, bottom = zB.get(i), xloc = xloc.bar_time, border_color = na, bgcolor = color.new(cb0, math.min(100, math.max(minTr, color.t(cb0))))))
zT.remove(i), zB.remove(i), zL.remove(i), zV.remove(i), zD.remove(i), zS.remove(i)
zVR.remove(i), zDP.remove(i), zNR.remove(i), zBR.remove(i), zWR.remove(i), zRK.remove(i), zFG.remove(i), zSW.remove(i)
int nzn = zT.size()
if nzn > 0
// sum of the volumes per TF and per side (for the % weight)
float[] sums = array.new<float>(nSlot * 2, 0.0)
int[] cnts = array.new<int>(nSlot * 2, 0)
for i = 0 to nzn - 1
int key = zS.get(i) * 2 + (zD.get(i) == 1 ? 0 : 1)
sums.set(key, sums.get(key) + zV.get(i))
cnts.set(key, cnts.get(key) + 1)
// most recent OB (all TFs, both sides): kept visible by the overlap filter if requested
int lastIdx = -1
if obOnlyOv and obKeepLast
for i = 0 to nzn - 1
if lastIdx == -1 or zL.get(i) > zL.get(lastIdx)
lastIdx := i
// visible OBs (kept for the merged labels)
int[] vI = array.new<int>()
int[] vSt = array.new<int>()
float[] vW = array.new<float>()
float[] vR = array.new<float>()
int[] vOv = array.new<int>()
bool[] vNe = array.new<bool>()
for i = 0 to nzn - 1
int sl = zS.get(i)
int d = zD.get(i)
float zt = zT.get(i)
float zb = zB.get(i)
float mid = math.avg(zt, zb)
int sec = gSec.get(sl)
int tier = f_tier(sec)
bool nested = false
if markNest
for j = 0 to nzn - 1
if j != i and zD.get(j) == d and gSec.get(zS.get(j)) > sec
bool hit = nestMode == "Inside" ? (zB.get(j) <= zb and zT.get(j) >= zt) : (zB.get(j) <= zt and zT.get(j) >= zb)
if hit
nested := true
// number of OTHER TFs with a same-direction OB overlapping this one
// (the zones of one TF are consecutive in the arrays, so a change of slot = a new TF)
int ovN = 0
int lastS = -1
for j = 0 to nzn - 1
if j != i and zS.get(j) != sl and zD.get(j) == d and zB.get(j) <= zt and zT.get(j) >= zb and zS.get(j) != lastS
ovN += 1
lastS := zS.get(j)
int stars = (zVR.get(i) >= thrV ? 1 : 0) + (zDP.get(i) >= thrI ? 1 : 0) + (zBR.get(i) >= thrR ? 1 : 0) + zFG.get(i) + zSW.get(i)
// weight: volume / average volume of the other OBs of the same TF and side
// weight: volume / average volume of the last OBs of the same TF and side (computed in the TF)
float wR = nz(zWR.get(i))
float wRk = zRK.get(i)
bool heavy = wOn and wR >= wMin
bool isChrt = incChart and sl == 0
bool keep = not obOnlyOv or ovN >= obMinOv or i == lastIdx or (obKeepCh and isChrt)
bool near = maxDist <= 0 or f_dist(zt, zb) <= maxDist
if keep and near
obCT.push(zt), obCB.push(zb), obCD.push(d)
if keep and near and obShow
if gBx.size() >= 495
boxFull := true
else
// the overlaps darken by themselves (stacked boxes); one OB never goes below the minimum transparency
color col0 = d == 1 ? f_cu(tier) : f_cd(tier)
float tr0 = (showStr ? color.t(col0) - stars * opStep : color.t(col0))
color col = color.new(col0, math.min(100, math.max(0, math.max(minTr, nested ? tr0 - nestFill : tr0))))
color colS = color.new(col, 0)
string bst = f_bs(tier)
bool custN = nested and nestBStyle != "Same as TF"
bool heavyB = heavy
color bcol = heavyB ? color.new(col0, 30) : custN ? (nestBStyle == "None" ? na : color.new(col, 100 - nestBOpac)) : (bst == "None" ? na : color.new(col, 100 - obBOpac))
int bw = heavyB ? 1 : custN ? nestBWidth : obBWidth
string bsty = heavyB ? line.style_solid : custN ? f_bstyle(nestBStyle) : f_bstyle(bst)
gBx.push(box.new(left = zL.get(i), top = zt, right = time, bottom = zb, border_color = bcol, border_width = bw, border_style = bsty, extend = extend.right, xloc = xloc.bar_time, bgcolor = col))
if showline
gLn.push(line.new(x1 = zL.get(i), y1 = mid, x2 = time, y2 = mid, xloc = xloc.bar_time, color = colS, style = line.style_dashed))
vI.push(i), vSt.push(stars), vOv.push(ovN), vNe.push(nested), vW.push(wR >= vxMin ? wR : 0.0), vR.push(wRk)
if labMode == "One label per OB"
string txt = (nested ? "◆ " : "") + f_tfName(gTf.get(sl))
if showOvN and ovN > 0
txt := txt + " +" + str.tostring(ovN) + " TF"
if wR > 0 and wR >= vxMin
txt := txt + " ×" + str.tostring(wR, "#.#") + (vxRank and not na(wRk) ? " top " + str.tostring(math.max(1, math.round(100 - wRk))) + "%" : "")
if showmetric
float sm = sums.get(sl * 2 + (d == 1 ? 0 : 1))
int pct = sm > 0 ? math.floor(zV.get(i) / sm * 100) : 0
txt := txt + " " + str.tostring(math.round(zV.get(i), 3), format.volume) + " (" + str.tostring(pct) + "%)"
if showStr
txt := txt + " " + (stars > 0 ? str.repeat("★", stars) : "·")
if showDetV
txt := txt + " V" + str.tostring(zVR.get(i), "#.#") + "×"
if showDetI
txt := txt + " I" + str.tostring(zDP.get(i), "#.#")
if showDetR
txt := txt + " R" + str.tostring(zNR.get(i)) + "/" + str.tostring(zBR.get(i), "#.#")
if showDetF and zFG.get(i) == 1
txt := txt + " F"
if showDetS and zSW.get(i) == 1
txt := txt + " S"
gLb.push(label.new(x = bar_index + labOff + (tier - 1) * labStep, y = mid, text = txt, style = label.style_label_left, color = #ffffff00, textcolor = txtCol, size = obtxt.txSz()))
// merged labels: one label per group of overlapping same-direction OBs (all TFs together)
int nv = vI.size()
if labMode == "One label per overlap zone" and nv > 0 and obShow
// union-find: two visible OBs of the same direction that overlap go into the same group
int[] par = array.new<int>(nv, 0)
for a = 0 to nv - 1
par.set(a, a)
if nv > 1
for a = 0 to nv - 2
int ia = vI.get(a)
for b = a + 1 to nv - 1
int ib = vI.get(b)
if zD.get(ia) == zD.get(ib) and zB.get(ib) <= zT.get(ia) and zT.get(ib) >= zB.get(ia)
int ra = a
while par.get(ra) != ra
ra := par.get(ra)
int rb = b
while par.get(rb) != rb
rb := par.get(rb)
if ra != rb
par.set(rb, ra)
int[] grp = array.new<int>(nv, -1)
int[] rootG = array.new<int>(nv, -1)
int ng = 0
for a = 0 to nv - 1
int r = a
while par.get(r) != r
r := par.get(r)
if rootG.get(r) == -1
rootG.set(r, ng)
ng += 1
grp.set(a, rootG.get(r))
for g = 0 to ng - 1
float gT = na
float gB = na
int mSt = 0
float mW = 0.0
float mRk = na
bool anyN = false
int cnt = 0
string nms = ""
string lastNm = ""
// the zones are sorted from the highest TF to the lowest: TF names in decreasing order
for a = 0 to nv - 1
if grp.get(a) == g
int ia = vI.get(a)
gT := na(gT) ? zT.get(ia) : math.max(gT, zT.get(ia))
gB := na(gB) ? zB.get(ia) : math.min(gB, zB.get(ia))
mSt := math.max(mSt, vSt.get(a))
if vW.get(a) > mW
mW := vW.get(a)
mRk := vR.get(a)
anyN := anyN or vNe.get(a)
string nm = f_tfName(gTf.get(zS.get(ia)))
if nm != lastNm
nms := nms + (cnt > 0 ? " " : "") + nm
lastNm := nm
cnt += 1
// label position: the band where the most OBs of the group overlap (closest to price on a tie)
float[] edg = array.new<float>()
for a = 0 to nv - 1
if grp.get(a) == g
edg.push(zT.get(vI.get(a))), edg.push(zB.get(vI.get(a)))
edg.sort(order.ascending)
float yLab = math.avg(gT, gB)
int bestN = 0
float bestD = na
if edg.size() > 1
for e = 0 to edg.size() - 2
float lo = edg.get(e)
float hi = edg.get(e + 1)
if hi > lo
float md = math.avg(lo, hi)
int nIn = 0
for a = 0 to nv - 1
if grp.get(a) == g and zB.get(vI.get(a)) <= md and zT.get(vI.get(a)) >= md
nIn += 1
float dP = math.abs(md - close)
if nIn > bestN or (nIn == bestN and dP < bestD)
bestN := nIn
bestD := dP
yLab := md
string txt = (anyN ? "◆ " : "") + nms
if showOvN and cnt > 1
txt := txt + " (" + str.tostring(cnt) + " TF)"
if showStr
txt := txt + " " + (mSt > 0 ? str.repeat("★", mSt) : "")
if mW > 0
txt := txt + " vol ×" + str.tostring(mW, "#.#") + (vxRank and not na(mRk) ? " top " + str.tostring(math.max(1, math.round(100 - mRk))) + "%" : "")
if labRange
txt := txt + " " + str.tostring(gB, format.mintick) + "–" + str.tostring(gT, format.mintick)
gLb.push(label.new(x = bar_index + labOff, y = yLab, text = txt, style = label.style_label_left, color = #ffffff00, textcolor = txtCol, size = obtxt.txSz()))
// ───────────────────────────── FVGs OF THE OTHER TFs (same principle as the OBs) ─────────────────────────────
var box[] gFx = array.new<box>()
var label[] gFl = array.new<label>()
var line[] gFm = array.new<line>()
if barstate.islast
for bx in gFx
bx.delete()
for lb in gFl
lb.delete()
for ln in gFm
ln.delete()
gFx.clear()
gFl.clear()
gFm.clear()
// all FVG zones: slot -1 = chart TF (original SMC code), otherwise the slot of the requested TF
// (with an FVG option, the chart TF comes from its request: slot 0)
float[] qT = array.new<float>()
float[] qB = array.new<float>()
int[] qL = array.new<int>()
int[] qD = array.new<int>()
int[] qS = array.new<int>()
float[] qFT = array.new<float>()
float[] qFB = array.new<float>()
float[] qSZ = array.new<float>()
float[] qIM = array.new<float>()
float[] qVR = array.new<float>()
float[] qDM = array.new<float>()
float[] qRL = array.new<float>()
if nSlot > 0
for k = 0 to nSlot - 1
bool chartReq = fvUseReq and fsh1 and k == 0
if gFv.get(k) or chartReq
string rs = gRes.get(k)
if not na(rs)
string[] parts = str.split(rs, "|")
if parts.size() > 1
string[] items = str.split(parts.get(1), ";")
int cU = 0
int cD = 0
for it in items
if str.length(it) > 0
string[] fp = str.split(it, ",")
if fp.size() >= 4
int dd = int(str.tonumber(fp.get(0)))
// chart TF: « Show Last » FVGs per side
bool okN = not chartReq or (dd == 1 ? cU < fvg_num : cD < fvg_num)
cU += dd == 1 ? 1 : 0
cD += dd == -1 ? 1 : 0
if okN
qD.push(dd)
qT.push(str.tonumber(fp.get(1)))
qB.push(str.tonumber(fp.get(2)))
qL.push(int(str.tonumber(fp.get(3))))
qS.push(chartReq ? -1 : k)
qFT.push(fp.size() >= 8 ? str.tonumber(fp.get(4)) : str.tonumber(fp.get(1)))
qFB.push(fp.size() >= 8 ? str.tonumber(fp.get(5)) : str.tonumber(fp.get(2)))
qSZ.push(fp.size() >= 8 ? str.tonumber(fp.get(6)) : na)
qIM.push(fp.size() >= 8 ? str.tonumber(fp.get(7)) : na)
qVR.push(fp.size() >= 11 ? str.tonumber(fp.get(8)) : na)
qDM.push(fp.size() >= 11 ? str.tonumber(fp.get(9)) : na)
qRL.push(fp.size() >= 11 ? str.tonumber(fp.get(10)) : na)
int nq = qT.size()
if nq > 0
// pass 1: filters → candidates (index, broken time)
int[] cI = array.new<int>()
int[] cBk = array.new<int>()
float[] cDs = array.new<float>()
int[] cOv = array.new<int>()
int[] cSt = array.new<int>()
for i = 0 to nq - 1
int sq = qS.get(i)
int fd = qD.get(i)
float fto = fv3 ? qFT.get(i) : qT.get(i)
float fbo = fv3 ? qFB.get(i) : qB.get(i)
bool ov = false
int ovC = 0
int lsq = -99
// the FVGs of one TF are consecutive in the arrays: a change of slot = a new TF
for j = 0 to nq - 1
if j != i and qS.get(j) != sq and qD.get(j) == fd and qB.get(j) <= fto and qT.get(j) >= fbo
ov := true
if qS.get(j) != lsq
ovC += 1
lsq := qS.get(j)
bool okF = fto > fbo
okF := okF and (maxDist <= 0 or f_dist(fto, fbo) <= maxDist)
// chart-TF FVGs: drawn here only with the overlap filter or an FVG option (otherwise by the original code)
okF := okF and (not fvgOnlyOv or ov)
okF := okF and (not fv1 or na(qSZ.get(i)) or qSZ.get(i) >= fv1Atr)
okF := okF and (not fv2 or na(qIM.get(i)) or qIM.get(i) >= fv2Min)
bool tOb = false
if okF and (fv5 or fsOn) and obCT.size() > 0
for m = 0 to obCT.size() - 1
if obCD.get(m) == fd and obCB.get(m) <= fto and obCT.get(m) >= fbo
tOb := true
break
if fv5
okF := okF and tOb
// FVG stars: V volume, D direction of the volume, T relative size, O touches an OB, I mostly intact
int fst = 0
if fsOn
float hgt = qT.get(i) - qB.get(i)
float remn = fd == 1 ? qFT.get(i) - qB.get(i) : qT.get(i) - qFB.get(i)
float fillP = hgt > 0 ? 100 - remn / hgt * 100 : 0.0
fst := (nz(qVR.get(i)) >= fsV ? 1 : 0) + (nz(qDM.get(i)) >= fsD ? 1 : 0) + (nz(qRL.get(i)) >= fsT ? 1 : 0) + (tOb ? 1 : 0) + (fillP < fsI ? 1 : 0)
okF := okF and fst >= fsMin
int bk = na
if okF and endOn and sq != -1
bk := f_breakTime(qL.get(i), qT.get(i), qB.get(i), fd, fvg_src)
if not na(bk) and endMode == "Hide broken zones"
okF := false
if okF
cI.push(i), cBk.push(bk), cOv.push(ovC), cSt.push(fst)
// signed distance: > 0 above price, < 0 below, 0 = price inside
cDs.push(fbo > close ? fbo - close : fto < close ? fto - close : 0.0)
// pass 2: nearest N per side of price (option 4); broken zones are not counted
int nc = cI.size()
bool[] cKeep = array.new<bool>(nc, true)
if fv4 and nc > 0
for c = 0 to nc - 1
float dc = cDs.get(c)
if dc != 0 and na(cBk.get(c))
int closer = 0
for e = 0 to nc - 1
float de = cDs.get(e)
if e != c and na(cBk.get(e)) and math.sign(de) == math.sign(dc) and (math.abs(de) < math.abs(dc) or (math.abs(de) == math.abs(dc) and e < c))
closer += 1
cKeep.set(c, closer < fv4N)
else if not na(cBk.get(c))
cKeep.set(c, false)
// pass 3: drawing
if nc > 0
for c = 0 to nc - 1
if cKeep.get(c)
int i = cI.get(c)
int sq = qS.get(i)
int fd = qD.get(i)
float fto = fv3 ? qFT.get(i) : qT.get(i)
float fbo = fv3 ? qFB.get(i) : qB.get(i)
int bk = cBk.get(c)
color c0 = fv8 ? (fd == 1 ? fv8Up : fv8Dn) : (fd == 1 ? fvg_upcss : fvg_dncss)
int fst = cSt.get(c)
c0 := color.new(c0, math.max(0, color.t(c0) - math.min(fvgOvCap, cOv.get(c) * fvgOvStep) - fst * fsStep))
// right edge: the break, the short box, or the right of the chart
int shortR = qL.get(i) + fv7Bars * timeframe.in_seconds() * 1000
int rgt = not na(bk) ? bk : fv7 ? shortR : time
bool ext = na(bk) and not fv7
if gBx.size() + gFx.size() >= 495
boxFull := true
else
int tier = sq == -1 ? f_tier(timeframe.in_seconds()) : f_tier(gSec.get(sq))
string bst = f_bs(tier)
color bc = fv6 ? color.new(c0, 40) : sq == -1 ? na : bst == "None" ? (fvgMtfOut ? color.new(c0, 60) : na) : color.new(c0, 20)
string bsy = fv6 ? line.style_dotted : bst == "None" ? line.style_dashed : f_bstyle(bst)
gFx.push(box.new(left = qL.get(i), top = fto, right = rgt, bottom = fbo, xloc = xloc.bar_time, extend = ext ? extend.right : extend.none,
bgcolor = fv6 ? na : c0, border_color = bc, border_style = bsy))
if fv6
gFm.push(line.new(x1 = qL.get(i), y1 = math.avg(fto, fbo), x2 = rgt, y2 = math.avg(fto, fbo), xloc = xloc.bar_time, color = color.new(c0, 40), style = line.style_dotted, extend = ext ? extend.right : extend.none))
string fsTx = fsOn and fst > 0 ? str.repeat("★", fst) : ""
if fvgMtfLab and sq != -1 and na(bk)
gFl.push(label.new(x = bar_index + labOff + (tier - 1) * labStep, y = math.avg(fto, fbo), text = "FVG " + f_tfName(gTf.get(sq)) + (fsTx != "" ? " " + fsTx : ""), style = label.style_label_left,
color = #ffffff00, textcolor = txtCol, size = size.small))
if fsOn and fsLab and fsTx != "" and na(bk)
gFl.push(label.new(x = qL.get(i), y = math.avg(fto, fbo), xloc = xloc.bar_time, text = fsTx, style = label.style_label_left,
color = #ffffff00, textcolor = txtCol, size = size.tiny))
// legend: TFs computed for the OBs and for the FVGs (in increasing order)
if showLeg
// short legend: lowest TF → highest TF (number of TFs)
int cO = 0
int cF = 0
string loO = ""
string hiO = ""
string loF = ""
string hiF = ""
if nSlot > 0
int[] asc = gSec.sort_indices(order.ascending)
for k in asc
string nmk = f_tfName(gTf.get(k))
if gOb.get(k)
loO := cO == 0 ? nmk : loO
hiO := nmk
cO += 1
if gFv.get(k)
loF := cF == 0 ? nmk : loF
hiF := nmk
cF += 1
string lt = not obShow ? "OB: hidden" : "OB: " + (cO == 0 ? "none" : cO == 1 ? loO : loO + " → " + hiO + " (" + str.tostring(cO) + " TFs)")
string ft = "FVG: " + (fsh1 ? f_tfName(timeframe.period) + " + " : "") + (cF == 0 ? "no other TF" : cF == 1 ? loF : loF + " → " + hiF + " (" + str.tostring(cF) + " TFs)")
table.cell(leg, 0, 0, lt, text_color = txtCol, text_size = size.small, text_halign = text.align_right)
table.cell(leg, 0, 1, fvg_enable ? ft : "", text_color = txtCol, text_size = size.small, text_halign = text.align_right)
table.cell(leg, 0, 2, boxFull ? "500-box limit reached: some zones are hidden. Lower the OBs per side or narrow the TF range." : "", text_color = color.orange, text_size = size.small, text_halign = text.align_right)