Order Blocks FVG and Price Gaps with Volume Profile

TheScalpingAnt · study · 1204 行 · 点赞 64 · TradingView 原页

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

Pine Script

//@version=6
indicator("Order Blocks FVG and Price Gaps with Volume Profile", "OB FVG GAP VP", overlay = true, behind_chart = false, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 1200)
 
string G_ZONE = "Zones shared"
string G_AGE  = "Zone age filter"
string G_OB   = "Order blocks"
string G_FVG  = "Fair value gaps"
string G_GAP  = "Price gaps"
string G_VP   = "Right side volume profile"
string G_DASH = "Dashboard"
string G_VIS  = "Candles and confluence"
string G_CONF = "Confirmation and alerts"
 
int   extendBars       = input.int(12, "Active zone projection bars", minval = 1, maxval = 200, tooltip = "How many bars into the future every still-active zone rectangle is projected, measured from the current bar. This only changes the length of the drawing. It does not change detection, fill logic, confluence, or alerts.", group = G_ZONE, display = display.data_window)
int   maxZonesPerType  = input.int(40, "Maximum stored zones per type", minval = 1, maxval = 40, tooltip = "Maximum number of zones kept in memory for each type separately: order blocks, fair value gaps, and price gaps. When the limit is reached the oldest zone of that type is dropped, preferring zones already hidden by the age filter. Lower values reduce drawing and calculation load on very fast timeframes. Zone rectangles, removable candle marks, and profile rows all share the Pine limit of 500 boxes, so removable candle marks are capped automatically and the newest zones are always kept first.", group = G_ZONE, display = display.data_window)
bool  showZoneLabels   = input.bool(false, "Zone labels", tooltip = "Draws a small tag at the right edge of each visible zone showing its type, direction, confluence state, and whether it sits at the point of control or inside the value area. Hovering a tag reveals top, bottom, live status, impulse or gap size in ATR, volume versus its 20-period average, and touch count. Off by default to keep the chart clean.", group = G_ZONE, display = display.data_window)
int   borderTransp     = input.int(0, "Boundary transparency", minval = 0, maxval = 100, tooltip = "Transparency of the zone boundary lines, from 0 (fully opaque) to 100 (invisible). Shared by all three zone types. Boundary lines must also be enabled for the type you want to see.", group = G_ZONE, display = display.data_window)
bool  dedupeFvgGap     = input.bool(true, "Show only one of an aligned FVG and price gap", tooltip = "A single displacement candle can satisfy both the three-candle fair value gap test and the two-candle price gap test over the same price window, which would otherwise draw two rectangles for one event and count it twice as confluence. When this is on, only the preferred type is kept for same-direction overlaps between fair value gaps and price gaps. Opposite-direction overlaps are always kept, because those are genuine conflict signals. Order blocks are never affected.", group = G_ZONE, display = display.data_window)
string fvgGapPriority   = input.string("Keep fair value gap", "Preferred type when both align", options = ["Keep fair value gap", "Keep price gap"], tooltip = "Which of the two survives when a fair value gap and a price gap cover the same price window in the same direction. The default keeps the fair value gap, because its boundaries are set by the two outer candles of the three-candle sequence and therefore describe the full imbalance that the displacement left behind. Choose Keep price gap if you prefer the narrower void measured strictly between two adjacent candles. The surviving zone keeps its own original boundaries; the two ranges are never merged.", group = G_ZONE, display = display.data_window)
int   borderWidth      = input.int(1, "Boundary width", minval = 1, maxval = 3, tooltip = "Thickness of the zone boundary lines in pixels, from 1 to 3. Shared by all three zone types.", group = G_ZONE, display = display.data_window)
bool  scaleGuardOn     = input.bool(false, "Protect chart scale", tooltip = "Off by default so distant active order blocks and fair value gaps stay visible. If candles look compressed, right-click the price scale and enable Scale price chart only. When enabled, hides zone rectangles, boundaries, and labels when the zone is outside the recent 100-bar candle price range plus a margin, so distant active zones do not stretch the price scale and compress the candles. Zones remain active internally and reappear when they are inside the protected range. This does not change detection, alerts, candle colors, or the volume profile. For best chart scaling, also right-click the price scale and enable Scale price chart only.", group = G_ZONE, display = display.data_window)
float scaleGuardMarginPct = input.float(10.0, "Scale guard margin percent", minval = 0.0, maxval = 100.0, step = 1.0, tooltip = "Extra price range above and below the recent 100-bar candle high/low, as a percent of that recent range, before a zone is hidden by Protect chart scale.", group = G_ZONE, display = display.data_window)
string candleColorFrom = input.string("Fill color", "Candle color source", options = ["Fill color", "Boundary color"], tooltip = "Boundary colors are independent inputs. Boundary lines do not need to be enabled for candles to use boundary colors. By default boundary colors match fill colors, so change a boundary color to see a difference.", group = G_VIS, display = display.data_window)
string paintPriority   = input.string("OB then FVG then Gap", "Overlap priority", options = ["Gap then FVG then OB", "FVG then OB then Gap", "OB then FVG then Gap"], tooltip = "Decides which zone type colors the candle when more than one type confirms on the same bar. Exactly one color is applied per bar, never a blend. The default gives order blocks the highest priority, then fair value gaps, then price gaps.", group = G_VIS, display = display.data_window)
string candleMode         = input.string("Actual candles", "Candle color mode", options = ["Actual candles", "Removable drawings"], tooltip = "Default. Actual candles colors the native confirming candle body and wick. That color is permanent after the zone fills, breaks, or is touched, so historical confirming candles remain colored. Removable drawings is an optional overlay mode: it draws a candle-body and wick overlay centered on the confirming candle only while the zone is active, untouched, and age-visible, and deletes it on first touch, fill, break, age-out, or eviction. It uses drawing objects, not native candle color.", group = G_VIS, display = display.data_window)
int    candleBodyWidthPct = input.int(70, "Removable body width percent", minval = 20, maxval = 100, tooltip = "Width of the removable candle body overlay as a percent of one bar of chart time, centered on the confirming candle. Used only when Removable drawings is selected. Increase it if the overlay looks narrower than the candles on your chart, decrease it if it looks too fat.", group = G_VIS, display = display.data_window)
int    candleWickWidth    = input.int(2, "Removable wick width", minval = 1, maxval = 4, tooltip = "Approximate wick thickness as a percent of one bar, used only when Removable drawings is selected. The wick is drawn as a thin box so it can stay in front of zone rectangles.", group = G_VIS, display = display.data_window)
 
bool  ageFilterOn      = input.bool(true, "Enable zone age filter", tooltip = "Restricts which zones are drawn and counted by their age. Detection still runs across the whole loaded history; the filter controls visibility, dashboard counts, and which zones are allowed to trigger alerts. In Actual candles mode the selected age window determines which historical confirming candles are eligible to be colored, but those native colors are not erased when a zone later fills or is touched. In Removable drawings mode candle colors are deleted when a zone ages out of the selected window.", group = G_AGE, display = display.data_window)
string ageView         = input.string("Last 1 year", "Zone age view", options = ["Last 1 month", "Last 6 months", "Current year", "Last 1 year", "Last 2 years"], tooltip = "Age window used by the filter. Last 1 month and Last 6 months are rolling windows approximated as 30.4375 and 182.625 days. Last 1 year and Last 2 years are rolling windows of 365.25 and 730.5 days. Current year uses the calendar year in the exchange timezone of the symbol. Age is measured from the close time of the confirming candle to the last bar of the chart, so rolling windows move forward as new bars arrive.", group = G_AGE, display = display.data_window)
 
bool   showOB          = input.bool(true, "Enable order blocks", tooltip = "Enables order block detection. An order block is the last opposite-direction candle before a displacement candle that closes beyond the extreme of that origin candle. Turning this off stops new order blocks from forming; zones already stored keep being managed until they fill or break.", group = G_OB, display = display.data_window)
bool   obCandles       = input.bool(false, "Color candles", tooltip = "Colors only the single candle that confirmed the order block. The origin candle and the rest of the pattern are never colored. Independent of rectangle fill and boundary lines. Off by default. In the default Actual candles mode the native color is permanent. In optional Removable drawings mode the color is deleted on the first touch of the zone, or when the zone breaks, ages out, or is evicted.", group = G_OB, display = display.data_window)
bool   obFill          = input.bool(true, "Rectangle fill", tooltip = "Draws the filled rectangle of the order block. Independent of candle coloring and boundary lines, so you can show the fill only, the outline only, both, or neither.", group = G_OB, display = display.data_window)
bool   obBorders       = input.bool(false, "Boundary lines", tooltip = "Draws the outline of the order block rectangle. Independent of the fill. Off by default because the fill alone is usually enough and outlines add visual density.", group = G_OB, display = display.data_window)
string obRangeMode     = input.string("Wicks", "OB range", options = ["Wicks", "Bodies"], tooltip = "Defines the vertical range of the order block from the origin candle. Wicks uses the full high-to-low range. Bodies uses only the open-to-close range, which produces a tighter zone that is easier to defend but easier to break.", group = G_OB, display = display.data_window)
float  obAtrMult       = input.float(0.65, "Displacement body ATR multiple", minval = 0.1, maxval = 5.0, step = 0.05, tooltip = "Minimum body size of the confirming impulse candle, expressed as a multiple of the 14-period ATR of the previous bar. Higher values demand a stronger impulse and produce fewer, more selective order blocks. The default of 0.65 is the original calibration and is intentionally permissive.", group = G_OB, display = display.data_window)
int    obImpulseBars   = input.int(3, "Maximum impulse run bars", minval = 1, maxval = 10, tooltip = "Maximum number of consecutive same-direction impulse candles allowed between the origin candle or cluster and the confirming candle. A value of 1 restores the strict one-candle displacement test. Larger values let a strong move confirm over a short run instead of requiring the very first candle after the origin to qualify.", group = G_OB, display = display.data_window)
int    obClusterBars   = input.int(3, "Maximum origin cluster bars", minval = 1, maxval = 10, tooltip = "Maximum number of consecutive opposite-direction origin candles merged into one order block. A value of 1 uses only the last single opposite-direction candle. Larger values allow the last bearish cluster before an upward impulse or the last bullish cluster before a downward impulse to define the zone.", group = G_OB, display = display.data_window)
string obConfirmMode  = input.string("Close beyond origin", "Order block confirmation", options = ["Close beyond origin", "Wick beyond origin", "Displacement body only"], tooltip = "How the impulse candle has to clear the origin candle or cluster before an order block is created. Close beyond origin is the original test and the default: a bullish block needs the confirming candle to close above the origin cluster high, and a bearish block needs a close below the origin cluster low. Wick beyond origin accepts a wick that reaches beyond the origin extreme even when the candle closes back inside, which adds the blocks that displaced price without closing outside the origin range. Displacement body only skips the breakout test and accepts every displacement candle that follows an opposite-direction origin, which is the most permissive setting and the closest match to tools that mark every displacement.", group = G_OB, display = display.data_window)
string obInvalidationMode = input.string("Close beyond opposite edge", "Order block invalidation", options = ["Close beyond opposite edge", "Wick beyond opposite edge", "Keep until aged out"], tooltip = "Decides when an active order block stops being drawn. Close beyond opposite edge is the original rule and the default: a bullish block ends when a candle closes below its bottom, a bearish block ends when a candle closes above its top. Wick beyond opposite edge waits for a wick to trade fully through the block, which is slightly slower. Keep until aged out never ends a block because of price, so every block stays on the chart until the zone age filter hides it or the storage limit evicts it. Looser settings keep far more blocks visible, but they also keep blocks that price already traded through.", group = G_OB, display = display.data_window)
bool   obIgnoreAge    = input.bool(false, "Order blocks ignore the zone age filter", tooltip = "Lets order block rectangles, boundaries, labels, and candle colors stay visible outside the age window selected in the Age group. Detection, alerts, and dashboard counting keep working exactly as before for fair value gaps and price gaps. On high timeframes this is the single biggest reason for a sparse order block chart, because one year is only about fifty two weekly candles.", group = G_OB, display = display.data_window)
bool   obIgnoreScaleGuard = input.bool(false, "Order blocks ignore the scale guard", tooltip = "Draws order blocks even when they sit outside the recent 100 bar price range plus the scale guard margin, the same way price gaps already behave. If a distant block that is drawn still compresses the candles, right click the price scale and enable Scale price chart only, or disable Protect chart scale.", group = G_OB, display = display.data_window)
int    obFillTransp    = input.int(80, "Fill transparency", minval = 0, maxval = 100, tooltip = "Transparency of the order block rectangle fill, from 0 (solid) to 100 (invisible). The default of 80 keeps the candles readable through the zone.", group = G_OB, display = display.data_window)
bool   obVolumeFilter  = input.bool(false, "Require volume above 1.10x its 20 SMA", tooltip = "When enabled, an order block is accepted only if the volume of the displacement candle is greater than 1.10 times its 20-period simple moving average of volume. The multiplier is fixed. Useful on symbols with reliable volume; leave it off on symbols that do not report volume.", group = G_OB, display = display.data_window)
color  obBullColor     = input.color(#1B881F, "Bullish fill candle", tooltip = "Fill color of bullish order blocks, and the candle color of the confirming bullish candle when Candle color source is set to Fill color. Default is green.", group = G_OB, display = display.data_window)
color  obBearColor     = input.color(#B10606, "Bearish fill candle", tooltip = "Fill color of bearish order blocks, and the candle color of the confirming bearish candle when Candle color source is set to Fill color. Default is dark red.", group = G_OB, display = display.data_window)
color  obBullBorder    = input.color(#1B881F, "Bullish boundary", tooltip = "Boundary color of bullish order blocks. Also used as the candle color when Candle color source is set to Boundary color, even if boundary lines are disabled. By default it matches the bullish fill, so change it if you want a visible difference.", group = G_OB, display = display.data_window)
color  obBearBorder    = input.color(#B10606, "Bearish boundary", tooltip = "Boundary color of bearish order blocks. Also used as the candle color when Candle color source is set to Boundary color, even if boundary lines are disabled. By default it matches the bearish fill, so change it if you want a visible difference.", group = G_OB, display = display.data_window)
string obBorderStyle   = input.string("Solid", "Boundary style", options = ["Solid", "Dashed", "Dotted"], tooltip = "Line style of the order block boundary: solid, dashed, or dotted. Only visible when boundary lines are enabled for order blocks.", group = G_OB, display = display.data_window)
 
bool   showFVG         = input.bool(true, "Enable fair value gaps", tooltip = "Enables fair value gap detection. A fair value gap is a three-candle imbalance where the range of the current candle does not overlap the range of the candle two bars back, leaving an untraded price window between them.", group = G_FVG, display = display.data_window)
bool   fvgCandles      = input.bool(false, "Color candles", tooltip = "Colors only the single candle that confirmed the fair value gap, which is the third candle of the three-candle pattern. Independent of rectangle fill and boundary lines. Off by default. In the default Actual candles mode the native color is permanent. In optional Removable drawings mode the color is deleted on the first touch of the zone, or when the zone fills, ages out, or is evicted.", group = G_FVG, display = display.data_window)
bool   fvgFill         = input.bool(true, "Rectangle fill", tooltip = "Draws the filled rectangle of the fair value gap. Independent of candle coloring and boundary lines.", group = G_FVG, display = display.data_window)
bool   fvgBorders      = input.bool(false, "Boundary lines", tooltip = "Draws the outline of the fair value gap rectangle. Independent of the fill. Off by default.", group = G_FVG, display = display.data_window)
float  fvgAtrMult      = input.float(0.10, "Minimum gap ATR multiple", minval = 0.0, maxval = 3.0, step = 0.05, tooltip = "Minimum height of the fair value gap as a multiple of the ATR of the previous bar. Zero accepts every gap that is at least one minimum tick. Raise it to keep only meaningful imbalances and filter out micro gaps on fast timeframes.", group = G_FVG, display = display.data_window)
float  fvgImpulseAtrMult = input.float(0.65, "Middle candle impulse ATR multiple", minval = 0.0, maxval = 5.0, step = 0.05, tooltip = "Minimum body size of the middle candle of the three-candle fair value gap sequence, expressed as a multiple of the previous ATR. The middle candle must also point in the gap direction when this value is above zero. This filters geometric gaps that are not produced by a directional impulse. Set to zero to use the three-candle gap geometry only.", group = G_FVG, display = display.data_window)
string fvgFillRule     = input.string("Full fill", "FVG removal rule", options = ["Full fill", "First touch"], tooltip = "Decides when a fair value gap is removed. Full fill keeps the zone until price trades completely through it. First touch removes it as soon as price enters the gap, which is the more conservative mitigation rule.", group = G_FVG, display = display.data_window)
int    fvgFillTransp   = input.int(80, "Fill transparency", minval = 0, maxval = 100, tooltip = "Transparency of the fair value gap rectangle fill, from 0 (solid) to 100 (invisible). The default of 80 keeps the candles readable through the zone.", group = G_FVG, display = display.data_window)
color  fvgBullColor    = input.color(#1FF500, "Bullish fill candle", tooltip = "Fill color of bullish fair value gaps, and the candle color of the confirming candle when Candle color source is set to Fill color. Default is light green, deliberately different from the order block green so the two types stay distinguishable.", group = G_FVG, display = display.data_window)
color  fvgBearColor    = input.color(#FF0000, "Bearish fill candle", tooltip = "Fill color of bearish fair value gaps, and the candle color of the confirming candle when Candle color source is set to Fill color. Default is red, deliberately different from the order block dark red.", group = G_FVG, display = display.data_window)
color  fvgBullBorder   = input.color(#1FF500, "Bullish boundary", tooltip = "Boundary color of bullish fair value gaps. Also used as the candle color when Candle color source is set to Boundary color, even if boundary lines are disabled. By default it matches the bullish fill.", group = G_FVG, display = display.data_window)
color  fvgBearBorder   = input.color(#FF0000, "Bearish boundary", tooltip = "Boundary color of bearish fair value gaps. Also used as the candle color when Candle color source is set to Boundary color, even if boundary lines are disabled. By default it matches the bearish fill.", group = G_FVG, display = display.data_window)
string fvgBorderStyle  = input.string("Solid", "Boundary style", options = ["Solid", "Dashed", "Dotted"], tooltip = "Line style of the fair value gap boundary: solid, dashed, or dotted. Only visible when boundary lines are enabled for fair value gaps.", group = G_FVG, display = display.data_window)
 
bool   showGAP         = input.bool(true, "Enable price gaps", tooltip = "Enables adjacent-candle price gap detection. Unlike a fair value gap, this compares only two consecutive candles, so it also catches displacements that a three-candle imbalance test would miss.", group = G_GAP, display = display.data_window)
bool   gapCandles      = input.bool(false, "Color candles", tooltip = "Colors only the single candle that confirmed the price gap, which is the second candle of the two-candle pattern. Independent of rectangle fill and boundary lines. Off by default. In the default Actual candles mode the native color is permanent. In optional Removable drawings mode the color is deleted on the first touch of the zone, or when the zone fills, ages out, or is evicted.", group = G_GAP, display = display.data_window)
bool   gapFill         = input.bool(true, "Rectangle fill", tooltip = "Draws the filled rectangle of the price gap. Independent of candle coloring and boundary lines.", group = G_GAP, display = display.data_window)
bool   gapBorders      = input.bool(false, "Boundary lines", tooltip = "Draws the outline of the price gap rectangle. Independent of the fill. Off by default.", group = G_GAP, display = display.data_window)
string gapMode         = input.string("Wick gap", "Gap definition", options = ["Wick gap", "Body gap"], tooltip = "Wick gap requires a genuinely empty range between the full high-low ranges of two consecutive candles. Body gap only requires the candle bodies to be separated, so the wicks may still overlap. Body gap produces more zones and is useful on continuous intraday charts where true wick gaps are rare.", group = G_GAP, display = display.data_window)
float  gapAtrMult      = input.float(0.05, "Minimum gap ATR multiple", minval = 0.0, maxval = 3.0, step = 0.05, tooltip = "Minimum height of the price gap as a multiple of the ATR of the previous bar. Zero accepts every gap that is at least one minimum tick.", group = G_GAP, display = display.data_window)
string gapFillRule     = input.string("Full fill", "Gap removal rule", options = ["Full fill", "First touch"], tooltip = "Decides when a price gap is removed. Full fill keeps the zone until price trades completely through it. First touch removes it as soon as price enters the gap.", group = G_GAP, display = display.data_window)
int    gapFillTransp   = input.int(80, "Fill transparency", minval = 0, maxval = 100, tooltip = "Transparency of the price gap rectangle fill, from 0 (solid) to 100 (invisible). The default of 80 keeps the candles readable through the zone.", group = G_GAP, display = display.data_window)
color  gapBullColor    = input.color(#FFEB3B, "Bullish fill candle", tooltip = "Fill color of bullish price gaps, and the candle color of the confirming candle when Candle color source is set to Fill color. Default is yellow.", group = G_GAP, display = display.data_window)
color  gapBearColor    = input.color(#1848CC, "Bearish fill candle", tooltip = "Fill color of bearish price gaps, and the candle color of the confirming candle when Candle color source is set to Fill color. Default is blue.", group = G_GAP, display = display.data_window)
color  gapBullBorder   = input.color(#FFEB3B, "Bullish boundary", tooltip = "Boundary color of bullish price gaps. Also used as the candle color when Candle color source is set to Boundary color, even if boundary lines are disabled. By default it matches the bullish fill.", group = G_GAP, display = display.data_window)
color  gapBearBorder   = input.color(#1848CC, "Bearish boundary", tooltip = "Boundary color of bearish price gaps. Also used as the candle color when Candle color source is set to Boundary color, even if boundary lines are disabled. By default it matches the bearish fill.", group = G_GAP, display = display.data_window)
string gapBorderStyle  = input.string("Solid", "Boundary style", options = ["Solid", "Dashed", "Dotted"], tooltip = "Line style of the price gap boundary: solid, dashed, or dotted. Only visible when boundary lines are enabled for price gaps.", group = G_GAP, display = display.data_window)
bool   gapIgnoreScaleGuard = input.bool(true, "Price gaps ignore scale guard", tooltip = "When enabled, price gap rectangles, boundaries, and labels are never hidden by Protect chart scale, so an unfilled gap stays on the chart no matter how far price has travelled from it. This is what makes the same gap appear on a 4-hour chart and on a 3-day chart. Because distant rectangles can then influence automatic scaling, right-click the price scale and enable Scale price chart only. Order blocks and fair value gaps keep using the scale guard exactly as before.", group = G_GAP, display = display.data_window)
int    maxGapZones     = input.int(200, "Maximum stored price gaps", minval = 1, maxval = 300, tooltip = "Storage limit reserved for price gaps alone, independent of the shared per-type limit used by order blocks and fair value gaps. A low limit silently drops the oldest unfilled gaps on lower timeframes, where two years of history contains far more gaps than on a daily chart. The effective limit is also capped by the shared Pine budget of 500 boxes after reserving room for the profile and for order blocks and fair value gaps. The dashboard reports the stored count, the effective limit, and how many gaps were dropped, so eviction is never silent.", group = G_GAP, display = display.data_window)
 
bool   showVP          = input.bool(true, "Show volume profile", tooltip = "Draws a horizontal volume profile in the right-hand margin only, so it never covers your candles. The profile is rebuilt on the last bar from the stored lookback window and reports the point of control and the value area.", group = G_VP, display = display.data_window)
bool   vpUseLtf        = input.bool(true, "Use lower timeframe volume", tooltip = "Builds the profile from lower-timeframe intrabar volume instead of spreading each chart candle across its full high-low range. This is much closer to TradingView volume profile, but it is still an intrabar estimate, not tick-exact volume at price.", group = G_VP, display = display.data_window)
string vpLtfOverride   = input.timeframe("", "Intrabar timeframe override", tooltip = "Leave empty for Auto. Auto chooses the finest common intrabar timeframe that should fit the lookback inside the intrabar data budget. Manual seconds timeframes may require a TradingView plan and data feed that support them. If the override is not lower than the chart, the profile falls back to a chart-bar estimate.", group = G_VP, display = display.data_window)
int    vpIntrabarBudget = input.int(100000, "Intrabar data budget", minval = 10000, maxval = 200000, step = 10000, tooltip = "Lower-timeframe bars requested. Default 100000 matches the non-professional TradingView intrabar limit. Expert plans can raise this to 125000 and Ultimate to 200000. Auto resolution uses this budget; a finer manual timeframe may cover fewer chart bars and show LTF+est.", group = G_VP, display = display.data_window)
int    vpLookback      = input.int(250, "Lookback chart bars", minval = 20, maxval = 1000, tooltip = "Fixed number of confirmed chart bars used by the profile. To compare with TradingView Fixed Range or Visible Range, match this range as closely as possible on the chart.", group = G_VP, display = display.data_window)
int    vpRows          = input.int(24, "Price rows", minval = 12, maxval = 80, tooltip = "Default 24 matches the common TradingView volume profile Number of Rows default. If your built-in profile uses a different Row Size, set this to the same value for a fair comparison. Very high row counts reserve more of the shared 500-box drawing budget, which reduces how many removable candle marks can be drawn at once.", group = G_VP, display = display.data_window)
int    vpWidth         = input.int(55, "Profile width bars", minval = 10, maxval = 100, tooltip = "Horizontal length of the profile histogram measured in bars of chart space. The longest row spans this width and every other row is scaled against it.", group = G_VP, display = display.data_window)
int    vpOffset        = input.int(10, "Offset from latest bar bars", minval = 0, maxval = 200, tooltip = "Empty space, measured in bars, between the latest chart bar and the start of the profile. Increase it if the profile sits too close to price. The profile is always drawn to the right of price, never on top of it.", group = G_VP, display = display.data_window)
float  vpValueArea     = input.float(70.0, "Value area percent", minval = 10.0, maxval = 95.0, step = 1.0, tooltip = "Percentage of total profile volume that the value area must contain. The area expands from the point of control, each step adding the heavier of the two adjacent rows, until the target is reached. Seventy percent is the conventional default.", group = G_VP, display = display.data_window)
string vpMode          = input.string("Up down split white levels", "Profile coloring", options = ["Up down split white levels", "Value area three color"], tooltip = "Up down split white levels draws each row as a down-volume segment and an up-volume segment with white level outlines. Value area three color instead colors rows by position: above value, inside value, and below value. One-sided and zero-volume highlighting takes priority in both modes.", group = G_VP, display = display.data_window)
bool   vpExtendLevels  = input.bool(false, "Extend POC and VA lines across lookback", tooltip = "Extends the point of control and value area lines to the left across the whole lookback window instead of only across the profile. Useful for seeing how price reacted to those levels, but it adds visual density.", group = G_VP, display = display.data_window)
bool   vpShowLabels    = input.bool(false, "Show POC VA and bar count labels", tooltip = "Shows the POC, VAH, VAL, and VP bar count labels beside the volume profile. Off by default to keep the right side clean and reduce scale pressure.", group = G_VP, display = display.data_window)
color  vpUpColor       = input.color(#FFFFFF, "Up or above value solid", tooltip = "Color of the up-volume segment in split mode, and of the rows above the value area in three-color mode. Default is white. Up volume means the source bar closed at or above its open; it is not buy-side order flow.", group = G_VP, display = display.data_window)
color  vpDownColor     = input.color(#000000, "Down or below value solid", tooltip = "Color of the down-volume segment in split mode, and of the rows below the value area in three-color mode. Default is black. Down volume means the source bar closed below its open; it is not sell-side order flow.", group = G_VP, display = display.data_window)
color  vpLevelColor    = input.color(#FFFFFF, "POC value area and row outline color", tooltip = "Color of the point of control line, the value area high and low lines, the outline of every populated profile row, the rows inside the value area in three-color mode, and the POC and VA text in the dashboard. Default is white. The point of control uses a thicker line than the value area edges so it stays distinguishable at any color.", group = G_VP, display = display.data_window)
bool   vpShowOneSided  = input.bool(true, "Highlight one sided volume rows", tooltip = "Highlights rows where one side dominates. At a threshold of 100 percent only rows built exclusively from up bars or exclusively from down bars are flagged, which usually marks one-way participation or unusually thin data.", group = G_VP, display = display.data_window)
bool   vpShowZeroVol   = input.bool(true, "Highlight zero volume rows", tooltip = "Marks price rows inside the profile range that received no volume at all in the lookback window. These are genuine voids and often behave as fast-move areas on a retest.", group = G_VP, display = display.data_window)
int    vpZeroVolWidth  = input.int(2, "Zero volume marker width bars", minval = 1, maxval = 10, tooltip = "Width, measured in bars, of the zero-volume marker drawn at the right edge of the profile.", group = G_VP, display = display.data_window)
color  vpOneSidedColor = input.color(#CA2727, "One sided and zero volume color", tooltip = "Color used for both one-sided rows and zero-volume rows. Default is red. These two conditions share one color so the profile keeps a single warning tone.", group = G_VP, display = display.data_window)
float  vpOneSidedShare = input.float(100.0, "One sided threshold percent", minval = 50.0, maxval = 100.0, step = 1.0, tooltip = "Dominance threshold for the one-sided highlight. At 100 percent a row must be entirely up volume or entirely down volume. Lower values, for example 80 percent, also flag rows that are strongly but not perfectly one-sided.", group = G_VP, display = display.data_window)
 
bool   waitForClose    = input.bool(true, "Wait for candle close", tooltip = "Keep this ON for non-repainting behavior. When ON, zones are created, tested, filled, and removed only after the candle closes, so a signal can never appear and then disappear inside the same candle. Turning it OFF previews signals while the candle is still forming; those previews can change before the close and must not be used for alerts or historical evaluation.", group = G_CONF, display = display.data_window)
bool   useAlertCalls   = input.bool(false, "Send combined alert() messages", tooltip = "Sends one dynamic alert message per closed candle listing every event that occurred on it, together with the symbol, timeframe, and closing price. Use it with the TradingView alert condition named Any alert() function call. Leave it OFF if you prefer the individual alert conditions, otherwise you may receive two notifications for the same event.", group = G_CONF, display = display.data_window)
 
bool   showDash        = input.bool(true, "Show dashboard", tooltip = "Shows the summary panel: live and tested zone counts per type and direction, the nearest zone edge, value-area overlap counts, point of control and value area prices, same-direction and opposite-direction confluence pairs, zones containing the current close, and the profile status line.", group = G_DASH, display = display.data_window)
string dashPos         = input.string("Bottom left", "Position", options = ["Top left", "Top right", "Bottom left", "Bottom right", "Middle left", "Middle right"], tooltip = "Screen anchor of the dashboard. The default bottom-left position keeps it away from the right-side volume profile.", group = G_DASH, display = display.data_window)
string dashSize        = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large"], tooltip = "Text size used inside the dashboard cells. The panel geometry and position do not change, only the text.", group = G_DASH, display = display.data_window)
 
float atrValue    = ta.atr(14)
float atrFallback = math.max(high - low, syminfo.mintick)
float atrRef      = math.max(nz(atrValue[1], nz(atrValue, atrFallback)), syminfo.mintick)
float volSma      = ta.sma(nz(volume), 20)
float volRatio    = volSma > 0 ? nz(volume) / volSma : 0.0
 
float recentHigh = ta.highest(high, 100)
float recentLow  = ta.lowest(low, 100)
var float guardHi  = na
var float guardLo  = na
var float guardMid = na
 
f_zoneColor(int kind, int dir) =>
    kind == 0 ? (dir == 1 ? obBullColor : obBearColor) : kind == 1 ? (dir == 1 ? fvgBullColor : fvgBearColor) : (dir == 1 ? gapBullColor : gapBearColor)
 
f_kindName(int kind) =>
    kind == 0 ? "OB" : kind == 1 ? "FVG" : "GAP"
 
f_borderColor(int kind, int dir) =>
    kind == 0 ? (dir == 1 ? obBullBorder : obBearBorder) : kind == 1 ? (dir == 1 ? fvgBullBorder : fvgBearBorder) : (dir == 1 ? gapBullBorder : gapBearBorder)
 
f_candleColor(int kind, int dir) =>
    candleColorFrom == "Boundary color" ? f_borderColor(kind, dir) : f_zoneColor(kind, dir)
 
f_lineStyle(string s) =>
    switch s
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        => line.style_solid
 
f_textOn(color c) =>
    color.r(c) * 0.299 + color.g(c) * 0.587 + color.b(c) * 0.114 > 150 ? color.black : color.white
 
f_rank(int kind) =>
    int r = 1
    if paintPriority == "Gap then FVG then OB"
        r := kind == 2 ? 3 : kind == 1 ? 2 : 1
    else if paintPriority == "FVG then OB then Gap"
        r := kind == 1 ? 3 : kind == 0 ? 2 : 1
    else
        r := kind == 0 ? 3 : kind == 1 ? 2 : 1
    r
 
f_ageVisible(int bornTime) =>
    bool vis = true
    if ageFilterOn
        int refTime = na(last_bar_time) ? time_close : last_bar_time
        float ageYears = (refTime - bornTime) / 31557600000.0
        int calAge = year(refTime, syminfo.timezone) - year(bornTime, syminfo.timezone)
        vis := switch ageView
            "Last 1 month" => ageYears <= 1.0 / 12.0
            "Last 6 months" => ageYears <= 0.5
            "Current year" => calAge == 0
            "Last 1 year" => ageYears <= 1.0
            "Last 2 years" => ageYears <= 2.0
            => true
    vis
 
f_ageVisibleKind(int kind, int bornTime) =>
    bool vis = f_ageVisible(bornTime)
    if kind == 0 and obIgnoreAge
        vis := true
    vis
 
f_tablePos(string s) =>
    switch s
        "Top left" => position.top_left
        "Top right" => position.top_right
        "Bottom left" => position.bottom_left
        "Bottom right" => position.bottom_right
        "Middle left" => position.middle_left
        "Middle right" => position.middle_right
        => position.bottom_left
 
f_tableSize(string s) =>
    switch s
        "Tiny" => size.tiny
        "Small" => size.small
        "Normal" => size.normal
        "Large" => size.large
        => size.small
 
f_barDuration() =>
    math.max(1, nz(time_close - time, nz(time - time[1], 60000)))
 
type Zone
    int kind
    int dir
    float top
    float bottom
    int left
    int leftTime
    int born
    int bornTime
    int right
    bool active = true
    bool visible = true
    bool scaleVisible = true
    bool tested = false
    int touches = 0
    float impulse = 0.0
    float volRatio = 0.0
    bool aligned = false
    bool conflict = false
    string endReason = ""
    int cCenter
    int cHalf
    float cOpen
    float cHigh
    float cLow
    float cClose
    float originHigh
    float originLow
    float confirmHigh
    float confirmLow
    float displacementAtr
    box body
    label tag
 
var array<Zone> zones = array.new<Zone>()
var array<int> gapDropCounter = array.new<int>(1, 0)
var array<int> gapDedupeCounter = array.new<int>(1, 0)
var int lastBullObOrigin = na
var int lastBearObOrigin = na
 
f_deleteZone(Zone z) =>
    if not na(z.body)
        box.delete(z.body)
    if not na(z.tag)
        label.delete(z.tag)
 
f_labelText(Zone z, float poc, float vaH, float vaL) =>
    string t = f_kindName(z.kind) + (z.dir == 1 ? " BULL" : " BEAR")
    if z.conflict
        t += " OPPOSITE"
    else if z.aligned
        t += " SAME DIR"
    if z.active and not na(poc)
        if z.bottom <= poc and z.top >= poc
            t += " POC"
        else if not na(vaH) and z.bottom <= vaH and z.top >= vaL
            t += " VA"
    t
 
f_styleZone(Zone z) =>
    color c = f_zoneColor(z.kind, z.dir)
    bool useFill = z.kind == 0 ? obFill : z.kind == 1 ? fvgFill : gapFill
    bool useBorders = z.kind == 0 ? obBorders : z.kind == 1 ? fvgBorders : gapBorders
    int ft = z.kind == 0 ? obFillTransp : z.kind == 1 ? fvgFillTransp : gapFillTransp
    int dur = f_barDuration()
    int rTime = time + dur * extendBars
    bool vis = z.visible and z.scaleVisible
    float drawTop = vis ? z.top : nz(guardMid, close)
    float drawBottom = vis ? z.bottom : nz(guardMid, close)
    color bg = vis and useFill ? color.new(c, ft) : na
    color bc = vis and useBorders ? color.new(f_borderColor(z.kind, z.dir), borderTransp) : na
    string bs = f_lineStyle(z.kind == 0 ? obBorderStyle : z.kind == 1 ? fvgBorderStyle : gapBorderStyle)
    if na(z.body)
        z.body := box.new(z.leftTime, drawTop, rTime, drawBottom, xloc = xloc.bar_time, border_color = bc, bgcolor = bg, border_width = borderWidth, border_style = bs)
    else
        box.set_left(z.body, z.leftTime)
        box.set_right(z.body, rTime)
        box.set_top(z.body, drawTop)
        box.set_bottom(z.body, drawBottom)
        box.set_bgcolor(z.body, bg)
        box.set_border_color(z.body, bc)
        box.set_border_width(z.body, borderWidth)
        box.set_border_style(z.body, bs)
    if showZoneLabels and na(z.tag)
        z.tag := label.new(rTime + dur, vis ? (z.top + z.bottom) * 0.5 : nz(guardMid, close), "", xloc = xloc.bar_time, style = label.style_label_left, color = c, textcolor = f_textOn(c), size = size.tiny)
    if not na(z.tag)
        label.set_xy(z.tag, rTime + dur, vis ? (z.top + z.bottom) * 0.5 : nz(guardMid, close))
        label.set_text(z.tag, vis ? f_labelText(z, na, na, na) : "")
        label.set_color(z.tag, vis ? c : na)
        label.set_textcolor(z.tag, f_textOn(c))
        string tip = f_kindName(z.kind) + (z.dir == 1 ? " bullish" : " bearish") + "\nTop: " + str.tostring(z.top, format.mintick) + "\nBottom: " + str.tostring(z.bottom, format.mintick) + "\nStatus: " + (z.active ? (z.tested ? "tested active" : "fresh active") : z.endReason) + "\nImpulse or gap: " + str.tostring(z.impulse, "#.##") + " ATR" + "\nDisplacement body: " + str.tostring(z.displacementAtr, "#.##") + " ATR" + "\nOrigin high: " + str.tostring(z.originHigh, format.mintick) + "\nOrigin low: " + str.tostring(z.originLow, format.mintick) + "\nConfirm high: " + str.tostring(z.confirmHigh, format.mintick) + "\nConfirm low: " + str.tostring(z.confirmLow, format.mintick) + "\nVolume vs 20 SMA: " + str.tostring(z.volRatio, "#.##") + "x" + "\nTouches: " + str.tostring(z.touches)
        label.set_tooltip(z.tag, tip)
 
f_newZone(int kind, int dir, float top, float bottom, int left, int leftTime, float impulse, float vr) =>
    int dur = f_barDuration()
    int bt = time_close
    bool vis = f_ageVisibleKind(kind, bt)
    int half = math.max(1, int(math.round(dur * candleBodyWidthPct / 200.0)))
    int center = time
    Zone z = Zone.new(kind = kind, dir = dir, top = top, bottom = bottom, left = left, leftTime = leftTime, born = bar_index, bornTime = bt, right = bar_index + extendBars, impulse = impulse, volRatio = vr, visible = vis, scaleVisible = true, cCenter = center, cHalf = half, cOpen = open, cHigh = high, cLow = low, cClose = close, body = na, tag = na)
    z
 
f_gapCap() =>
    int vpReserve = showVP ? vpRows * 3 : 0
    int freeForGaps = 500 - vpReserve - maxZonesPerType * 2 - 8
    math.max(1, math.min(maxGapZones, freeForGaps))
 
f_addZone(Zone z) =>
    array.push(zones, z)
    int kept = 0
    for q in zones
        if q.kind == z.kind
            kept += 1
    int cap = z.kind == 2 ? f_gapCap() : maxZonesPerType
    int dropped = 0
    while kept > cap
        int removeIdx = -1
        int n = array.size(zones)
        for j = 0 to n - 1
            Zone q = array.get(zones, j)
            if q.kind == z.kind and not q.visible and q.born != z.born
                removeIdx := j
                break
        if removeIdx == -1
            for j = 0 to n - 1
                Zone q = array.get(zones, j)
                if q.kind == z.kind and q.born != z.born
                    removeIdx := j
                    break
        if removeIdx == -1
            break
        Zone victim = array.get(zones, removeIdx)
        f_deleteZone(victim)
        array.remove(zones, removeIdx)
        kept -= 1
        dropped += 1
    if z.kind == 2 and dropped > 0
        array.set(gapDropCounter, 0, array.get(gapDropCounter, 0) + dropped)
 
f_hasPriorityClash(int kind, int dir, float top, float bottom) =>
    int other = kind == 1 ? 2 : 1
    bool clash = false
    for q in zones
        if q.active and q.kind == other and q.dir == dir and math.min(q.top, top) - math.max(q.bottom, bottom) > 0
            clash := true
    clash
 
f_removeSuperseded(int kind, int dir, float top, float bottom) =>
    int other = kind == 1 ? 2 : 1
    int removedThisBar = 0
    int i = array.size(zones) - 1
    while i >= 0
        Zone q = array.get(zones, i)
        if q.active and q.kind == other and q.dir == dir and math.min(q.top, top) - math.max(q.bottom, bottom) > 0
            if q.born == bar_index
                removedThisBar += 1
            f_deleteZone(q)
            array.remove(zones, i)
        i -= 1
    removedThisBar
 
f_confluence(Zone z) =>
    bool same = false
    bool opp = false
    for q in zones
        if q.active and q.kind != z.kind and math.min(q.top, z.top) - math.max(q.bottom, z.bottom) > 0
            if q.dir == z.dir
                same := true
            else
                opp := true
    [same, opp]
 
bool processBar = waitForClose ? barstate.isconfirmed : true
bool alertGate = barstate.isconfirmed
bool newOBBull = false
bool newOBBear = false
bool newFVGBull = false
bool newFVGBear = false
bool newGAPBull = false
bool newGAPBear = false
bool firstTouchAny = false
bool invalidationAny = false
bool newZoneAny = false
bool firstTouchOB = false
bool firstTouchFVG = false
bool firstTouchGAP = false
bool firstTouchBull = false
bool firstTouchBear = false
bool invalidOB = false
bool invalidFVG = false
bool invalidGAP = false
bool zoneCloseEnter = false
bool obConfSame = false
bool obConfOpp = false
bool fvgConfSame = false
bool fvgConfOpp = false
bool gapConfSame = false
bool gapConfOpp = false
bool confSameDir = false
bool confOppDir = false
var array<box> candleBoxes = array.new<box>()
 
f_clearCandleMarks() =>
    while array.size(candleBoxes) > 0
        box.delete(array.pop(candleBoxes))
 
f_drawCandleMark(Zone z) =>
    color c = f_candleColor(z.kind, z.dir)
    int dur = f_barDuration()
    int wickHalf = math.max(1, int(math.round(dur * candleWickWidth / 200.0)))
    float wickTop = z.cHigh
    float wickBottom = z.cLow
    if wickTop - wickBottom < syminfo.mintick
        wickTop += syminfo.mintick * 0.5
        wickBottom -= syminfo.mintick * 0.5
    float top = math.max(z.cOpen, z.cClose)
    float bottom = math.min(z.cOpen, z.cClose)
    if top - bottom < syminfo.mintick
        top += syminfo.mintick * 0.5
        bottom -= syminfo.mintick * 0.5
    box w = box.new(z.cCenter - wickHalf, wickTop, z.cCenter + wickHalf, wickBottom, xloc = xloc.bar_time, border_color = na, bgcolor = c)
    box b = box.new(z.cCenter - z.cHalf, top, z.cCenter + z.cHalf, bottom, xloc = xloc.bar_time, border_color = na, bgcolor = c)
    array.push(candleBoxes, w)
    array.push(candleBoxes, b)
 
f_candleEnabled(int kind) =>
    kind == 0 ? obCandles : kind == 1 ? fvgCandles : gapCandles
 
f_actualCandleColor() =>
    color c = na
    if obCandles or fvgCandles or gapCandles
        int rank = -1
        for z in zones
            if z.active and z.visible and z.born == bar_index and f_candleEnabled(z.kind)
                int r = f_rank(z.kind)
                if r > rank
                    rank := r
                    c := f_candleColor(z.kind, z.dir)
    c
 
f_refreshCandleMarks() =>
    f_clearCandleMarks()
    if candleMode == "Removable drawings"
        int zoneBoxCount = 0
        for q in zones
            if not na(q.body)
                zoneBoxCount += 1
        int vpReserve = showVP ? vpRows * 3 : 0
        int freeBoxes = 500 - zoneBoxCount - vpReserve - 8
        int maxMarks = math.max(0, int(math.floor(freeBoxes / 2.0)))
        int drawn = 0
        int i = array.size(zones) - 1
        while i >= 0 and drawn < maxMarks
            Zone z = array.get(zones, i)
            if z.active and not z.tested and z.visible and f_candleEnabled(z.kind)
                bool best = true
                for q in zones
                    if q.active and not q.tested and q.visible and f_candleEnabled(q.kind) and q.born == z.born and f_rank(q.kind) > f_rank(z.kind)
                        best := false
                if best
                    f_drawCandleMark(z)
                    drawn += 1
            i -= 1
 
 
if processBar
    int i = array.size(zones) - 1
    while i >= 0
        Zone z = array.get(zones, i)
        if z.active and bar_index > z.born
            bool overlap = high >= z.bottom and low <= z.top
            if z.visible and close <= z.top and close >= z.bottom and (close[1] > z.top or close[1] < z.bottom)
                zoneCloseEnter := true
            if overlap
                if not z.tested and z.visible
                    firstTouchAny := true
                    if z.kind == 0
                        firstTouchOB := true
                    else if z.kind == 1
                        firstTouchFVG := true
                    else
                        firstTouchGAP := true
                    if z.dir == 1
                        firstTouchBull := true
                    else
                        firstTouchBear := true
                z.tested := true
                z.touches := z.touches + 1
            bool broken = false
            if z.kind == 0
                if obInvalidationMode == "Wick beyond opposite edge"
                    broken := z.dir == 1 ? low < z.bottom : high > z.top
                else if obInvalidationMode == "Keep until aged out"
                    broken := false
                else
                    broken := z.dir == 1 ? close < z.bottom : close > z.top
            bool filled = false
            if z.kind == 1
                filled := fvgFillRule == "First touch" ? overlap : (z.dir == 1 ? low <= z.bottom : high >= z.top)
            if z.kind == 2
                filled := gapFillRule == "First touch" ? overlap : (z.dir == 1 ? low <= z.bottom : high >= z.top)
            if broken or filled
                z.active := false
                z.right := bar_index
                z.endReason := broken ? (obInvalidationMode == "Wick beyond opposite edge" ? "broken by wick" : "broken by close") : "filled"
                if z.visible
                    invalidationAny := true
                    if z.kind == 0
                        invalidOB := true
                    else if z.kind == 1
                        invalidFVG := true
                    else
                        invalidGAP := true
            if not z.active
                f_deleteZone(z)
                array.remove(zones, i)
        i -= 1
 
    float bodyNow = math.abs(close - open)
    bool volumeOK = not obVolumeFilter or (volSma > 0 and nz(volume) > volSma * 1.10)
    bool bullImpulse = close > open and bodyNow >= atrRef * obAtrMult and volumeOK
    bool bearImpulse = close < open and bodyNow >= atrRef * obAtrMult and volumeOK
    bool bullOB = false
    bool bearOB = false
    int obDir = 0
    float obTop = na
    float obBottom = na
    int obLeft = na
    int obLeftTime = na
    float obOriginHigh = na
    float obOriginLow = na
    if showOB and (bullImpulse or bearImpulse)
        int dir = bullImpulse ? 1 : -1
        int run = 0
        while run < obImpulseBars and bar_index >= run
            bool sameDir = dir == 1 ? close[run] > open[run] : close[run] < open[run]
            if not sameDir
                break
            run += 1
        int originIdx = run
        bool originOK = bar_index >= originIdx and (dir == 1 ? close[originIdx] < open[originIdx] : close[originIdx] > open[originIdx])
        if originOK
            int cluster = 1
            while cluster < obClusterBars and bar_index >= originIdx + cluster
                bool sameOrigin = dir == 1 ? close[originIdx + cluster] < open[originIdx + cluster] : close[originIdx + cluster] > open[originIdx + cluster]
                if not sameOrigin
                    break
                cluster += 1
            float cHi = na
            float cLo = na
            float bHi = na
            float bLo = na
            for k = 0 to cluster - 1
                int idx = originIdx + k
                cHi := na(cHi) ? high[idx] : math.max(cHi, high[idx])
                cLo := na(cLo) ? low[idx] : math.min(cLo, low[idx])
                float bodyTop = math.max(open[idx], close[idx])
                float bodyBottom = math.min(open[idx], close[idx])
                bHi := na(bHi) ? bodyTop : math.max(bHi, bodyTop)
                bLo := na(bLo) ? bodyBottom : math.min(bLo, bodyBottom)
            float zTop = obRangeMode == "Wicks" ? cHi : bHi
            float zBottom = obRangeMode == "Wicks" ? cLo : bLo
            bool breakNow = false
            if obConfirmMode == "Displacement body only"
                breakNow := true
            else if obConfirmMode == "Wick beyond origin"
                breakNow := dir == 1 ? high > zTop : low < zBottom
            else
                breakNow := dir == 1 ? close > zTop : close < zBottom
            int leftIdx = originIdx + cluster - 1
            int originTime = time[leftIdx]
            bool duplicate = dir == 1 ? originTime == lastBullObOrigin : originTime == lastBearObOrigin
            if breakNow and not duplicate
                bullOB := dir == 1
                bearOB := dir == -1
                obDir := dir
                obTop := zTop
                obBottom := zBottom
                obLeft := bar_index - leftIdx
                obLeftTime := originTime
                obOriginHigh := zTop
                obOriginLow := zBottom
                if dir == 1
                    lastBullObOrigin := originTime
                else
                    lastBearObOrigin := originTime
    if bullOB or bearOB
        Zone z = f_newZone(0, obDir, obTop, obBottom, obLeft, obLeftTime, bodyNow / atrRef, volRatio)
        z.originHigh := obOriginHigh
        z.originLow := obOriginLow
        z.confirmHigh := high
        z.confirmLow := low
        z.displacementAtr := bodyNow / atrRef
        if z.visible
            [cs, co] = f_confluence(z)
            obConfSame := obConfSame or cs
            obConfOpp := obConfOpp or co
        f_addZone(z)
        newOBBull := bullOB and z.visible
        newOBBear := bearOB and z.visible
        newZoneAny := newZoneAny or z.visible
 
    float fvgSize = 0.0
    int fvgDir = 0
    if showFVG and bar_index >= 2
        if low > high[2]
            fvgSize := low - high[2]
            fvgDir := 1
        else if high < low[2]
            fvgSize := low[2] - high
            fvgDir := -1
    float fvgImpulseBody = math.abs(close[1] - open[1])
    bool fvgImpulseOK = fvgDir != 0 and (fvgImpulseAtrMult <= 0 or ((fvgDir == 1 ? close[1] > open[1] : close[1] < open[1]) and fvgImpulseBody >= atrRef * fvgImpulseAtrMult))
    bool validFVG = fvgDir != 0 and fvgImpulseOK and fvgSize >= atrRef * fvgAtrMult and fvgSize >= syminfo.mintick
    if validFVG
        float top = fvgDir == 1 ? low : low[2]
        float bottom = fvgDir == 1 ? high[2] : high
        bool keepFVG = true
        if dedupeFvgGap
            if fvgGapPriority == "Keep fair value gap"
                f_removeSuperseded(1, fvgDir, top, bottom)
            else
                keepFVG := not f_hasPriorityClash(1, fvgDir, top, bottom)
        if keepFVG
            Zone z = f_newZone(1, fvgDir, top, bottom, bar_index - 2, time[2], fvgSize / atrRef, volRatio)
            z.originHigh := high[2]
            z.originLow := low[2]
            z.confirmHigh := high
            z.confirmLow := low
            z.displacementAtr := fvgImpulseBody / atrRef
            if z.visible
                [cs, co] = f_confluence(z)
                fvgConfSame := fvgConfSame or cs
                fvgConfOpp := fvgConfOpp or co
            f_addZone(z)
            newFVGBull := fvgDir == 1 and z.visible
            newFVGBear := fvgDir == -1 and z.visible
            newZoneAny := newZoneAny or z.visible
 
    float gapTop = na
    float gapBottom = na
    int gapDir = 0
    if showGAP and bar_index >= 1
        if gapMode == "Wick gap"
            if low > high[1]
                gapTop := low
                gapBottom := high[1]
                gapDir := 1
            else if high < low[1]
                gapTop := low[1]
                gapBottom := high
                gapDir := -1
        else
            float bodyHiNow = math.max(open, close)
            float bodyLoNow = math.min(open, close)
            float bodyHiPrev = math.max(open[1], close[1])
            float bodyLoPrev = math.min(open[1], close[1])
            if bodyLoNow > bodyHiPrev
                gapTop := bodyLoNow
                gapBottom := bodyHiPrev
                gapDir := 1
            else if bodyHiNow < bodyLoPrev
                gapTop := bodyLoPrev
                gapBottom := bodyHiNow
                gapDir := -1
    float gapSize = gapDir != 0 ? gapTop - gapBottom : 0.0
    bool validGAP = gapDir != 0 and gapSize >= atrRef * gapAtrMult and gapSize >= syminfo.mintick
    if validGAP
        bool keepGAP = true
        if dedupeFvgGap
            if fvgGapPriority == "Keep price gap"
                int superseded = f_removeSuperseded(2, gapDir, gapTop, gapBottom)
                if superseded > 0
                    newFVGBull := false
                    newFVGBear := false
                    fvgConfSame := false
                    fvgConfOpp := false
            else
                keepGAP := not f_hasPriorityClash(2, gapDir, gapTop, gapBottom)
        if not keepGAP
            array.set(gapDedupeCounter, 0, array.get(gapDedupeCounter, 0) + 1)
        if keepGAP
            Zone z = f_newZone(2, gapDir, gapTop, gapBottom, bar_index - 1, time[1], gapSize / atrRef, volRatio)
            z.originHigh := high[1]
            z.originLow := low[1]
            z.confirmHigh := high
            z.confirmLow := low
            z.displacementAtr := bodyNow / atrRef
            if z.visible
                [cs, co] = f_confluence(z)
                gapConfSame := gapConfSame or cs
                gapConfOpp := gapConfOpp or co
            f_addZone(z)
            newGAPBull := gapDir == 1 and z.visible
            newGAPBear := gapDir == -1 and z.visible
            newZoneAny := newZoneAny or z.visible
 
confSameDir := obConfSame or fvgConfSame or gapConfSame
confOppDir := obConfOpp or fvgConfOpp or gapConfOpp
 
 
if barstate.islast
    for z in zones
        bool nv = f_ageVisibleKind(z.kind, z.bornTime)
        if nv != z.visible
            z.visible := nv
    float hi = nz(recentHigh, high)
    float lo = nz(recentLow, low)
    if hi <= lo
        hi += atrRef
        lo -= atrRef
    float margin = (hi - lo) * scaleGuardMarginPct / 100.0
    guardHi := hi + margin
    guardLo := lo - margin
    guardMid := (guardHi + guardLo) * 0.5
    for z in zones
        if z.active
            bool sv = true
            if scaleGuardOn and not (z.kind == 2 and gapIgnoreScaleGuard) and not (z.kind == 0 and obIgnoreScaleGuard)
                sv := z.bottom <= guardHi and z.top >= guardLo
            z.scaleVisible := sv
            f_styleZone(z)
    f_refreshCandleMarks()
 
color actualCandleColor = candleMode == "Actual candles" ? f_actualCandleColor() : na
barcolor(actualCandleColor, title = "Actual zone candle color")
 
f_spreadVolume(array<float> upBins, array<float> dnBins, float bHi, float bLo, float v, float upShare, float lo, float binSize, int rows) =>
    if v > 0 and binSize > 0
        if bHi <= bLo
            int j = int(math.floor((bLo - lo) / binSize))
            j := math.max(0, math.min(rows - 1, j))
            array.set(upBins, j, array.get(upBins, j) + v * upShare)
            array.set(dnBins, j, array.get(dnBins, j) + v * (1.0 - upShare))
        else
            int first = int(math.floor((bLo - lo) / binSize))
            int last = int(math.floor((bHi - lo) / binSize))
            first := math.max(0, math.min(rows - 1, first))
            last := math.max(0, math.min(rows - 1, last))
            for j = first to last
                float binLo = lo + j * binSize
                float binHi = binLo + binSize
                float overlap = math.max(0.0, math.min(bHi, binHi) - math.max(bLo, binLo))
                if overlap > 0
                    float part = v * overlap / (bHi - bLo)
                    array.set(upBins, j, array.get(upBins, j) + part * upShare)
                    array.set(dnBins, j, array.get(dnBins, j) + part * (1.0 - upShare))
 
f_autoLtfSec(int chartSec, int lookback, int budget) =>
    int sec = 0
    if chartSec > 60
        int maxPerBar = math.max(1, int(math.floor(float(budget) / float(math.max(1, lookback)))))
        if 60 < chartSec and int(math.ceil(float(chartSec) / 60.0)) <= maxPerBar
            sec := 60
        else if 180 < chartSec and int(math.ceil(float(chartSec) / 180.0)) <= maxPerBar
            sec := 180
        else if 300 < chartSec and int(math.ceil(float(chartSec) / 300.0)) <= maxPerBar
            sec := 300
        else if 600 < chartSec and int(math.ceil(float(chartSec) / 600.0)) <= maxPerBar
            sec := 600
        else if 900 < chartSec and int(math.ceil(float(chartSec) / 900.0)) <= maxPerBar
            sec := 900
        else if 1800 < chartSec and int(math.ceil(float(chartSec) / 1800.0)) <= maxPerBar
            sec := 1800
        else if 3600 < chartSec and int(math.ceil(float(chartSec) / 3600.0)) <= maxPerBar
            sec := 3600
        else if 7200 < chartSec and int(math.ceil(float(chartSec) / 7200.0)) <= maxPerBar
            sec := 7200
        else if 14400 < chartSec and int(math.ceil(float(chartSec) / 14400.0)) <= maxPerBar
            sec := 14400
        else if 21600 < chartSec and int(math.ceil(float(chartSec) / 21600.0)) <= maxPerBar
            sec := 21600
        else if 43200 < chartSec and int(math.ceil(float(chartSec) / 43200.0)) <= maxPerBar
            sec := 43200
        else if 86400 < chartSec and int(math.ceil(float(chartSec) / 86400.0)) <= maxPerBar
            sec := 86400
    sec
 
f_tfString(int s) =>
    s >= 86400 and s % 86400 == 0 ? str.tostring(int(math.floor(s / 86400.0))) + "D" : str.tostring(int(math.floor(s / 60.0)))
 
f_tfName(int s) =>
    s < 60 ? str.tostring(s) + "s" : s < 3600 ? str.tostring(int(math.floor(s / 60.0))) + "m" : s < 86400 ? str.tostring(int(math.floor(s / 3600.0))) + "h" : str.tostring(int(math.floor(s / 86400.0))) + "D"
 
type VpSlice
    float hi
    float lo
    array<float> up
    array<float> dn
    bool ltf
    int intrabars
 
var array<VpSlice> vpSlices = array.new<VpSlice>()
int vpMicroRows = math.max(64, vpRows)
int vpChartSec = int(nz(timeframe.in_seconds(), 0))
bool vpTimeChart = chart.is_standard and (timeframe.isseconds or timeframe.isminutes or timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly)
int vpAutoSec = f_autoLtfSec(vpChartSec, vpLookback, vpIntrabarBudget)
string vpAutoTf = vpAutoSec > 0 ? f_tfString(vpAutoSec) : ""
string vpLtfTf = str.length(vpLtfOverride) > 0 ? vpLtfOverride : vpAutoTf
int vpLtfSec = str.length(vpLtfTf) > 0 ? int(nz(timeframe.in_seconds(vpLtfTf), 0)) : 0
bool vpLtfValid = vpUseLtf and vpTimeChart and vpLtfSec > 0 and vpLtfSec < vpChartSec
string vpLtfName = vpLtfValid ? f_tfName(vpLtfSec) : "chart"
 
if barstate.isconfirmed and showVP and bar_index >= last_bar_index - vpLookback
    array<float> rHigh = na
    array<float> rLow = na
    array<float> rOpen = na
    array<float> rClose = na
    array<float> rVol = na
    if vpLtfValid
        [qOpen, qHigh, qLow, qClose, qVol] = request.security_lower_tf(syminfo.tickerid, vpLtfTf, [open, high, low, close, volume], ignore_invalid_timeframe = true, calc_bars_count = vpIntrabarBudget)
        if not na(qHigh)
            rOpen := qOpen
            rHigh := qHigh
            rLow := qLow
            rClose := qClose
            rVol := qVol
    int nIntra = na(rHigh) ? 0 : array.size(rHigh)
    bool sliceLtf = nIntra > 0
    float sHi = na
    float sLo = na
    if sliceLtf
        for k = 0 to nIntra - 1
            float h = array.get(rHigh, k)
            float l = array.get(rLow, k)
            if not na(h) and not na(l)
                sHi := na(sHi) ? h : math.max(sHi, h)
                sLo := na(sLo) ? l : math.min(sLo, l)
    else
        sHi := high
        sLo := low
    if na(sHi) or na(sLo)
        sHi := close
        sLo := close
    if sHi <= sLo
        sHi += syminfo.mintick * 0.5
        sLo -= syminfo.mintick * 0.5
    array<float> up = array.new<float>(vpMicroRows, 0.0)
    array<float> dn = array.new<float>(vpMicroRows, 0.0)
    float microSize = (sHi - sLo) / vpMicroRows
    if sliceLtf
        for k = 0 to nIntra - 1
            float h = array.get(rHigh, k)
            float l = array.get(rLow, k)
            float o = array.get(rOpen, k)
            float c = array.get(rClose, k)
            float v = nz(array.get(rVol, k))
            if not na(h) and not na(l) and not na(o) and not na(c) and v > 0
                float bHi = math.max(h, l)
                float bLo = math.min(h, l)
                float upShare = c >= o ? 1.0 : 0.0
                f_spreadVolume(up, dn, bHi, bLo, v, upShare, sLo, microSize, vpMicroRows)
    else
        float v = nz(volume)
        float upShare = close >= open ? 1.0 : 0.0
        f_spreadVolume(up, dn, high, low, v, upShare, sLo, microSize, vpMicroRows)
    VpSlice slice = VpSlice.new(hi = sHi, lo = sLo, up = up, dn = dn, ltf = sliceLtf, intrabars = nIntra)
    array.push(vpSlices, slice)
    if array.size(vpSlices) > vpLookback
        array.shift(vpSlices)
 
var array<box> vpBoxes = array.new<box>()
var array<line> vpLines = array.new<line>()
var array<label> vpLabels = array.new<label>()
 
f_clearProfile() =>
    while array.size(vpBoxes) > 0
        box.delete(array.pop(vpBoxes))
    while array.size(vpLines) > 0
        line.delete(array.pop(vpLines))
    while array.size(vpLabels) > 0
        label.delete(array.pop(vpLabels))
 
var float pocPrice = na
var float vaHigh = na
var float vaLow = na
var int vpBarsUsed = 0
var int vpLtfBars = 0
var int vpEstBars = 0
var int vpIntrabarsUsed = 0
var int vpOneSidedRows = 0
var int vpZeroVolRows = 0
var string vpStatus = "waiting"
 
if barstate.islast
    f_clearProfile()
    pocPrice := na
    vaHigh := na
    vaLow := na
    vpBarsUsed := 0
    vpLtfBars := 0
    vpEstBars := 0
    vpIntrabarsUsed := 0
    vpOneSidedRows := 0
    vpZeroVolRows := 0
    vpStatus := "off"
    if showVP
        int n = array.size(vpSlices)
        vpBarsUsed := n
        vpStatus := n > 0 ? "waiting" : "no bars"
        if n > 0
            float hi = na
            float lo = na
            for s in vpSlices
                hi := na(hi) ? s.hi : math.max(hi, s.hi)
                lo := na(lo) ? s.lo : math.min(lo, s.lo)
                if s.ltf
                    vpLtfBars += 1
                    vpIntrabarsUsed += s.intrabars
                else
                    vpEstBars += 1
            if na(hi) or na(lo)
                hi := close + syminfo.mintick
                lo := close - syminfo.mintick
            if hi <= lo
                hi += syminfo.mintick * vpRows * 0.5
                lo -= syminfo.mintick * vpRows * 0.5
            float binSize = (hi - lo) / vpRows
            array<float> upVol = array.new<float>(vpRows, 0.0)
            array<float> dnVol = array.new<float>(vpRows, 0.0)
            array<float> totalVol = array.new<float>(vpRows, 0.0)
            for s in vpSlices
                float microSize = (s.hi - s.lo) / vpMicroRows
                for m = 0 to vpMicroRows - 1
                    float u = array.get(s.up, m)
                    float d = array.get(s.dn, m)
                    float t = u + d
                    if t > 0
                        float bLo = s.lo + m * microSize
                        float bHi = bLo + microSize
                        float upShare = u / t
                        f_spreadVolume(upVol, dnVol, bHi, bLo, t, upShare, lo, binSize, vpRows)
            float maxVol = 0.0
            float sumVol = 0.0
            int pocIdx = 0
            for j = 0 to vpRows - 1
                float t = array.get(upVol, j) + array.get(dnVol, j)
                array.set(totalVol, j, t)
                sumVol += t
                if t > maxVol
                    maxVol := t
                    pocIdx := j
            int vaLoIdx = pocIdx
            int vaHiIdx = pocIdx
            if sumVol > 0 and maxVol > 0
                pocPrice := lo + (pocIdx + 0.5) * binSize
                float target = sumVol * vpValueArea / 100.0
                float remaining = target - array.get(totalVol, pocIdx)
                while remaining > 0 and (vaLoIdx > 0 or vaHiIdx < vpRows - 1)
                    float below = vaLoIdx > 0 ? array.get(totalVol, vaLoIdx - 1) : -1.0
                    float above = vaHiIdx < vpRows - 1 ? array.get(totalVol, vaHiIdx + 1) : -1.0
                    if below < 0 and above < 0
                        break
                    bool chooseAbove = false
                    if above > below
                        chooseAbove := true
                    else if below > above
                        chooseAbove := false
                    else
                        int distAbove = vaHiIdx + 1 - pocIdx
                        int distBelow = pocIdx - (vaLoIdx - 1)
                        chooseAbove := distAbove <= distBelow
                    float nextVol = chooseAbove ? above : below
                    if nextVol > remaining
                        break
                    if chooseAbove
                        vaHiIdx += 1
                    else
                        vaLoIdx -= 1
                    remaining -= nextVol
                vaLow := lo + vaLoIdx * binSize
                vaHigh := lo + (vaHiIdx + 1) * binSize
            vpStatus := sumVol > 0 ? (vpLtfBars == n ? "LTF " + vpLtfName : vpLtfBars > 0 ? "LTF+est" : "chart est") : "no volume"
            int profileRight = bar_index + vpOffset + vpWidth
            int profileLeft = profileRight - vpWidth
            for j = 0 to vpRows - 1
                float bLo = lo + j * binSize
                float bHi = bLo + binSize
                float t = array.get(totalVol, j)
                float upV = array.get(upVol, j)
                float dnV = array.get(dnVol, j)
                if t == 0
                    vpZeroVolRows += 1
                    if vpShowZeroVol
                        box z = box.new(profileRight - vpZeroVolWidth, bHi, profileRight, bLo, xloc = xloc.bar_index, border_color = na, bgcolor = color.new(vpOneSidedColor, 0))
                        array.push(vpBoxes, z)
                else
                    float dominantShare = math.max(upV, dnV) / t
                    bool pureOneSided = (upV > 0 and dnV == 0) or (dnV > 0 and upV == 0)
                    bool oneSidedRow = vpOneSidedShare >= 100.0 ? pureOneSided : dominantShare >= vpOneSidedShare / 100.0
                    bool oneSided = vpShowOneSided and oneSidedRow
                    if oneSidedRow
                        vpOneSidedRows += 1
                    int totalW = math.max(1, int(math.round(vpWidth * t / maxVol)))
                    int leftX = profileRight - totalW
                    bool isPOC = j == pocIdx and sumVol > 0
                    if totalW > 0
                        box base = box.new(leftX, bHi, profileRight, bLo, xloc = xloc.bar_index, border_color = color.new(vpLevelColor, isPOC ? 0 : 65), border_width = isPOC ? 2 : 1, bgcolor = color.new(vpLevelColor, 88))
                        array.push(vpBoxes, base)
                        if oneSided
                            box os = box.new(leftX, bHi, profileRight, bLo, xloc = xloc.bar_index, border_color = na, bgcolor = color.new(vpOneSidedColor, 0))
                            array.push(vpBoxes, os)
                        else if vpMode == "Up down split white levels"
                            int dnW = int(math.round(vpWidth * dnV / maxVol))
                            int upW = int(math.round(vpWidth * upV / maxVol))
                            if dnW > 0
                                box d = box.new(leftX, bHi, leftX + dnW, bLo, xloc = xloc.bar_index, border_color = na, bgcolor = color.new(vpDownColor, 0))
                                array.push(vpBoxes, d)
                            if upW > 0
                                box u = box.new(profileRight - upW, bHi, profileRight, bLo, xloc = xloc.bar_index, border_color = na, bgcolor = color.new(vpUpColor, 0))
                                array.push(vpBoxes, u)
                        else
                            color regionC = j > vaHiIdx ? vpUpColor : j < vaLoIdx ? vpDownColor : vpLevelColor
                            box r = box.new(leftX, bHi, profileRight, bLo, xloc = xloc.bar_index, border_color = na, bgcolor = color.new(regionC, 0))
                            array.push(vpBoxes, r)
            if sumVol > 0 and maxVol > 0
                int levelLeft = vpExtendLevels ? math.max(0, bar_index - n + 1) : profileLeft
                line pocL = line.new(levelLeft, pocPrice, profileRight, pocPrice, xloc = xloc.bar_index, color = vpLevelColor, width = 2, style = line.style_solid)
                line vahL = line.new(levelLeft, vaHigh, profileRight, vaHigh, xloc = xloc.bar_index, color = vpLevelColor, width = 1, style = line.style_dashed)
                line valL = line.new(levelLeft, vaLow, profileRight, vaLow, xloc = xloc.bar_index, color = vpLevelColor, width = 1, style = line.style_dashed)
                array.push(vpLines, pocL)
                array.push(vpLines, vahL)
                array.push(vpLines, valL)
                if vpShowLabels
                    label pocTag = label.new(profileRight + 1, pocPrice, "POC " + str.tostring(pocPrice, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = vpLevelColor, textcolor = f_textOn(vpLevelColor), size = size.tiny)
                    label vahTag = label.new(profileRight + 1, vaHigh, "VAH " + str.tostring(vaHigh, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = vpLevelColor, textcolor = f_textOn(vpLevelColor), size = size.tiny)
                    label valTag = label.new(profileRight + 1, vaLow, "VAL " + str.tostring(vaLow, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = vpLevelColor, textcolor = f_textOn(vpLevelColor), size = size.tiny)
                    label titleTag = label.new(profileRight, hi + binSize * 2, "VP " + str.tostring(n) + " bars " + vpStatus, xloc = xloc.bar_index, style = label.style_label_down, color = color.black, textcolor = vpLevelColor, size = size.tiny)
                    array.push(vpLabels, pocTag)
                    array.push(vpLabels, vahTag)
                    array.push(vpLabels, valTag)
                    array.push(vpLabels, titleTag)
            else
                if vpShowLabels
                    label noVol = label.new(profileRight, hi, "No volume data in lookback", xloc = xloc.bar_index, style = label.style_label_left, color = color.black, textcolor = vpLevelColor, size = size.small)
                    array.push(vpLabels, noVol)
 
var table dash = table.new(f_tablePos(dashPos), 5, 11, bgcolor = #000000, frame_color = #000000, frame_width = 1, border_color = #000000, border_width = 1)
if barstate.isfirst
    table.merge_cells(dash, 0, 10, 4, 10)
 
if barstate.islast
    array<int> liveCount = array.new<int>(6, 0)
    array<int> testedCount = array.new<int>(6, 0)
    array<int> vaCount = array.new<int>(6, 0)
    array<float> nearDist = array.new<float>(6, na)
    array<float> nearPrice = array.new<float>(6, na)
    int alignedPairs = 0
    int conflictPairs = 0
    int atPrice = 0
    int gapStored = 0
    int gapAgeHidden = 0
    for q in zones
        if q.kind == 2
            gapStored += 1
            if not q.visible
                gapAgeHidden += 1
    int zoneN = array.size(zones)
    for z in zones
        z.aligned := false
        z.conflict := false
        if z.active and z.visible
            int idx = z.kind * 2 + (z.dir == 1 ? 0 : 1)
            array.set(liveCount, idx, array.get(liveCount, idx) + 1)
            if z.tested
                array.set(testedCount, idx, array.get(testedCount, idx) + 1)
            if not na(vaHigh) and z.bottom <= vaHigh and z.top >= vaLow
                array.set(vaCount, idx, array.get(vaCount, idx) + 1)
            float dist = close < z.bottom ? z.bottom - close : close > z.top ? close - z.top : 0.0
            float edge = close < z.bottom ? z.bottom : close > z.top ? z.top : close
            if na(array.get(nearDist, idx)) or dist < array.get(nearDist, idx)
                array.set(nearDist, idx, dist)
                array.set(nearPrice, idx, edge)
            if close <= z.top and close >= z.bottom
                atPrice += 1
    if zoneN > 1
        for i = 0 to zoneN - 2
            Zone a = array.get(zones, i)
            if a.active and a.visible
                for j = i + 1 to zoneN - 1
                    Zone b = array.get(zones, j)
                    if b.active and b.visible and a.kind != b.kind
                        float overlap = math.min(a.top, b.top) - math.max(a.bottom, b.bottom)
                        if overlap > 0
                            if a.dir == b.dir
                                alignedPairs += 1
                                a.aligned := true
                                b.aligned := true
                            else
                                conflictPairs += 1
                                a.conflict := true
                                b.conflict := true
    for z in zones
        if not na(z.tag)
            label.set_text(z.tag, z.visible and z.scaleVisible ? f_labelText(z, pocPrice, vaHigh, vaLow) : "")
    if showDash
        color panel = #000000
        color header = #000000
        string ts = f_tableSize(dashSize)
        table.cell(dash, 0, 0, "OB FVG GAP VP", bgcolor = header, text_color = color.white, text_size = ts)
        table.cell(dash, 1, 0, "LIVE", bgcolor = header, text_color = color.white, text_size = ts)
        table.cell(dash, 2, 0, "TESTED", bgcolor = header, text_color = color.white, text_size = ts)
        table.cell(dash, 3, 0, "NEAREST", bgcolor = header, text_color = color.white, text_size = ts)
        table.cell(dash, 4, 0, "PROFILE", bgcolor = header, text_color = color.white, text_size = ts)
        for row = 0 to 5
            int kind = int(math.floor(row / 2))
            int dir = row % 2 == 0 ? 1 : -1
            color c = f_zoneColor(kind, dir)
            string name = f_kindName(kind) + (dir == 1 ? " BULL" : " BEAR")
            string nearText = na(array.get(nearPrice, row)) ? "" : str.tostring(array.get(nearPrice, row), format.mintick)
            string profileText = array.get(vaCount, row) > 0 ? "VA x" + str.tostring(array.get(vaCount, row)) : "0"
            table.cell(dash, 0, row + 1, name, bgcolor = c, text_color = f_textOn(c), text_size = ts)
            table.cell(dash, 1, row + 1, str.tostring(array.get(liveCount, row)), bgcolor = panel, text_color = color.white, text_size = ts)
            table.cell(dash, 2, row + 1, str.tostring(array.get(testedCount, row)), bgcolor = panel, text_color = color.white, text_size = ts)
            table.cell(dash, 3, row + 1, nearText, bgcolor = panel, text_color = color.white, text_size = ts)
            table.cell(dash, 4, row + 1, profileText, bgcolor = panel, text_color = color.white, text_size = ts)
            if kind == 2
                string gapTip = "Price gaps stored: " + str.tostring(gapStored) + "\nEffective storage limit: " + str.tostring(f_gapCap()) + "\nHidden by the age view: " + str.tostring(gapAgeHidden) + "\nDropped by the storage limit so far: " + str.tostring(array.get(gapDropCounter, 0)) + "\nSuppressed by the FVG dedupe rule: " + str.tostring(array.get(gapDedupeCounter, 0)) + "\nScale guard exempt: " + (gapIgnoreScaleGuard ? "yes" : "no") + "\nIf dropped is above zero, raise Maximum stored price gaps or reduce the profile price rows. If hidden by age is above zero, widen the zone age view."
                table.cell_set_tooltip(dash, 0, row + 1, gapTip)
        table.cell(dash, 0, 7, "POC", bgcolor = panel, text_color = vpLevelColor, text_size = ts)
        table.cell(dash, 1, 7, na(pocPrice) ? vpStatus : str.tostring(pocPrice, format.mintick), bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 2, 7, "VA", bgcolor = panel, text_color = vpLevelColor, text_size = ts)
        table.cell(dash, 3, 7, na(vaLow) ? vpStatus : str.tostring(vaLow, format.mintick), bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 4, 7, na(vaHigh) ? vpStatus : str.tostring(vaHigh, format.mintick), bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 0, 8, "SAME DIR", bgcolor = panel, text_color = fvgBullColor, text_size = ts)
        table.cell(dash, 1, 8, str.tostring(alignedPairs), bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 2, 8, "OPPOSITE", bgcolor = panel, text_color = fvgBearColor, text_size = ts)
        table.cell(dash, 3, 8, str.tostring(conflictPairs), bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 4, 8, "pairs", bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 0, 9, "AT PRICE", bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 1, 9, str.tostring(atPrice), bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 2, 9, "VP BARS", bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 3, 9, str.tostring(vpBarsUsed), bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 4, 9, vpStatus, bgcolor = panel, text_color = color.white, text_size = ts)
        table.cell(dash, 0, 10, "Close confirmed VP " + vpStatus + " one sided " + str.tostring(vpOneSidedRows) + " zero volume " + str.tostring(vpZeroVolRows) + " age " + (ageFilterOn ? ageView : "All ages") + " gaps " + str.tostring(gapStored) + "/" + str.tostring(f_gapCap()) + (array.get(gapDropCounter, 0) > 0 ? " dropped " + str.tostring(array.get(gapDropCounter, 0)) : ""), bgcolor = header, text_color = color.white, text_size = size.tiny)
        table.cell(dash, 1, 10, "", bgcolor = header, text_size = ts)
        table.cell(dash, 2, 10, "", bgcolor = header, text_size = ts)
        table.cell(dash, 3, 10, "", bgcolor = header, text_size = ts)
        table.cell(dash, 4, 10, "", bgcolor = header, text_size = ts)
    else
        table.clear(dash, 0, 0, 4, 10)
 
alertcondition(alertGate and newOBBull, "OB bullish", "OB FVG GAP VP: bullish order block confirmed on {{ticker}} {{interval}}")
alertcondition(alertGate and newOBBear, "OB bearish", "OB FVG GAP VP: bearish order block confirmed on {{ticker}} {{interval}}")
alertcondition(alertGate and newFVGBull, "FVG bullish", "OB FVG GAP VP: bullish fair value gap confirmed on {{ticker}} {{interval}}")
alertcondition(alertGate and newFVGBear, "FVG bearish", "OB FVG GAP VP: bearish fair value gap confirmed on {{ticker}} {{interval}}")
alertcondition(alertGate and newGAPBull, "Gap bullish", "OB FVG GAP VP: bullish price gap confirmed on {{ticker}} {{interval}}")
alertcondition(alertGate and newGAPBear, "Gap bearish", "OB FVG GAP VP: bearish price gap confirmed on {{ticker}} {{interval}}")
alertcondition(alertGate and firstTouchAny, "Zone first retest", "OB FVG GAP VP: first retest of a stored zone on {{ticker}} {{interval}}")
alertcondition(alertGate and invalidationAny, "Zone filled or broken", "OB FVG GAP VP: a stored zone was filled or broken on {{ticker}} {{interval}}")
alertcondition(alertGate and newZoneAny, "Any new zone", "OB FVG GAP VP: a new zone was confirmed on {{ticker}} {{interval}}")
alertcondition(alertGate and firstTouchOB, "OB first retest", "OB FVG GAP VP: first retest of an order block on {{ticker}} {{interval}}")
alertcondition(alertGate and firstTouchFVG, "FVG first retest", "OB FVG GAP VP: first retest of a fair value gap on {{ticker}} {{interval}}")
alertcondition(alertGate and firstTouchGAP, "Gap first retest", "OB FVG GAP VP: first retest of a price gap on {{ticker}} {{interval}}")
alertcondition(alertGate and firstTouchBull, "Bullish zone first retest", "OB FVG GAP VP: first retest of a bullish zone on {{ticker}} {{interval}}")
alertcondition(alertGate and firstTouchBear, "Bearish zone first retest", "OB FVG GAP VP: first retest of a bearish zone on {{ticker}} {{interval}}")
alertcondition(alertGate and invalidOB, "OB filled or broken", "OB FVG GAP VP: an order block was filled or broken on {{ticker}} {{interval}}")
alertcondition(alertGate and invalidFVG, "FVG filled", "OB FVG GAP VP: a fair value gap was filled on {{ticker}} {{interval}}")
alertcondition(alertGate and invalidGAP, "Gap filled", "OB FVG GAP VP: a price gap was filled on {{ticker}} {{interval}}")
alertcondition(alertGate and zoneCloseEnter, "Close entered a zone", "OB FVG GAP VP: price closed inside a stored zone on {{ticker}} {{interval}}")
alertcondition(alertGate and confSameDir, "Same direction confluence", "OB FVG GAP VP: a new zone overlaps a different zone type in the same direction on {{ticker}} {{interval}}")
alertcondition(alertGate and confOppDir, "Opposite direction confluence", "OB FVG GAP VP: a new zone overlaps a different zone type in the opposite direction on {{ticker}} {{interval}}")
 
bool pocTouched = barstate.isconfirmed and not na(pocPrice) and low <= pocPrice and high >= pocPrice
bool vahTouched = barstate.isconfirmed and not na(vaHigh) and low <= vaHigh and high >= vaHigh
bool valTouched = barstate.isconfirmed and not na(vaLow) and low <= vaLow and high >= vaLow
alertcondition(alertGate and pocTouched, "POC touched", "OB FVG GAP VP: price touched the volume profile point of control on {{ticker}} {{interval}}")
alertcondition(alertGate and vahTouched, "Value area high touched", "OB FVG GAP VP: price touched the value area high on {{ticker}} {{interval}}")
alertcondition(alertGate and valTouched, "Value area low touched", "OB FVG GAP VP: price touched the value area low on {{ticker}} {{interval}}")
 
if useAlertCalls and barstate.isconfirmed
    string ev = ""
    if newOBBull
        ev += "Bullish order block confirmed. "
    if newOBBear
        ev += "Bearish order block confirmed. "
    if newFVGBull
        ev += "Bullish fair value gap confirmed. "
    if newFVGBear
        ev += "Bearish fair value gap confirmed. "
    if newGAPBull
        ev += "Bullish price gap confirmed. "
    if newGAPBear
        ev += "Bearish price gap confirmed. "
    if firstTouchOB
        ev += "Order block first retest. "
    if firstTouchFVG
        ev += "Fair value gap first retest. "
    if firstTouchGAP
        ev += "Price gap first retest. "
    if invalidOB
        ev += "Order block filled or broken. "
    if invalidFVG
        ev += "Fair value gap filled. "
    if invalidGAP
        ev += "Price gap filled. "
    if zoneCloseEnter
        ev += "Close entered a stored zone. "
    if confSameDir
        ev += "Same direction confluence. "
    if confOppDir
        ev += "Opposite direction confluence. "
    if pocTouched
        ev += "Point of control touched. "
    if vahTouched
        ev += "Value area high touched. "
    if valTouched
        ev += "Value area low touched. "
    if str.length(ev) > 0
        alert("OB FVG GAP VP " + syminfo.ticker + " " + timeframe.period + ": " + ev + "Close " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)

← 返回列表