本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// anchored VWAP + MTF OBs+FVGs
// Version 1.22 - enforce one-pixel deviation lines without a width override.
// Deviation curves are colored by the latest profile volume at their endpoint.
// Historical curve colors therefore reflect the CURRENT profile, not past order flow.
// Solid boxes: order blocks. Dashed boxes: fair value gaps.
// SD means standard deviation; all source and user-interface text is ASCII.
// Value statistics, volume distribution, market structure and liquidity distance.
//
// VWAP = sum(HLC3 * volume) / sum(volume), from the start of the source window.
// Dispersion is volume-weighted population standard deviation (Welford update).
// The histogram covers the FULL source-window price range, not a sigma cutoff.
// Candle volume is distributed by overlap with each price bin. Up/down colors
// classify candle direction, not aggressive buying/selling or order-book delta.
// Value area grows from the highest-volume bin toward the larger neighbor.
//
// OB: last opposite candle before a confirmed close through a structural pivot;
// optional break-body ATR filter; full candle range; own-source close invalidation.
// FVG: confirmed three-candle price gap; removal by first touch or full fill.
// Liquidity: confirmed two-sided pivots with optional ATR excursion filtering.
// These are inferred liquidity locations, not a feed of resting orders.
//
// Chart formations are confirmed at chart close. Other source formations are
// processed on the first update of the next source candle, using candle [1].
// Historical pivot origin is drawn only AFTER its confirmation becomes available.
// Live wick contact removes a liquidity level / filled gap from the display.
// Profile live mode includes the open source candle and intentionally develops.
//
// METER SOURCES are independent of VISIBLE LIQUIDITY SOURCES:
// - All enabled liquidity timeframes: the enabled chart/layer sources.
// - Chart timeframe only: chart liquidity, even when its lines are hidden.
// - Selected timeframes: enable one or more of the three dedicated meter
// source switches. Visible liquidity layers do not affect this mode.
// Upper distance = (BSL-price)/(BSL-SSL); lower = 1-upper. NOT probabilities.
// Missing one side: no fabricated range, no boxes, an English status is shown.
// No timer: latest price updates trigger the indicator at the feed's own rate.
// This indicator is a chart-analysis tool, not a backtested trading strategy.
indicator("anchored VWAP + MTF OBs+FVGs", shorttitle = "aVWAP 1.22", overlay = true, max_bars_back = 2000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_polylines_count = 100, dynamic_requests = true)
// SETTINGS - grouped by feature; manual-only sources are inactive in Automatic mode.
string G_MODE = "00 - Timeframe Mode"
string timeframeMode = input.string("Automatic", "Timeframe mode", options = ["Automatic", "Manual"], group = G_MODE, tooltip = "Automatic follows the chart for VWAP/profile and selects higher liquidity and meter sources. Example: 1m chart -> 15m/1H liquidity and 5m meter. Manual unlocks the individual source settings.")
bool automaticTF = timeframeMode == "Automatic"
string G_VALUE_SOURCE = "01 - VWAP / Profile - Source"
bool valueOnChartManual = input.bool(true, "Use chart timeframe", group = G_VALUE_SOURCE, active = not automaticTF, tooltip = "Manual mode: use chart candles for VWAP, deviations and the profile. Turn off to use the manual profile source timeframe.")
string valueCustomTF = input.timeframe("240", "Manual profile source timeframe", group = G_VALUE_SOURCE, active = not automaticTF and not valueOnChartManual, tooltip = "Source timeframe for VWAP, deviations and the profile when Manual mode is selected and Use chart timeframe is off.")
int valueLength = input.int(300, "Source candles", minval = 10, maxval = 500, group = G_VALUE_SOURCE, tooltip = "Number of source candles used for VWAP, deviations and the profile. More candles cover a longer period. The window advances with new source candles.")
bool valueClosed = input.bool(false, "Closed source candles only", group = G_VALUE_SOURCE, tooltip = "Use completed source candles only. Turn off to include the open candle and let the profile develop live.")
string G_VWAP = "02 - VWAP - Line Style"
color valueColor = input.color(#FFB300, "VWAP line", group = G_VWAP, tooltip = "Color of the main VWAP line, its price label and the profile heading.")
int vwapStroke = input.int(2, "VWAP line width", minval = 1, maxval = 5, group = G_VWAP, tooltip = "Thickness of the main VWAP curve. Deviation lines have a separate width setting.")
string G_DEVIATIONS = "03 - VWAP - Deviation Channels"
bool deviationVisible = input.bool(true, "Show VWAP deviation lines", group = G_DEVIATIONS, tooltip = "Show volume-weighted standard deviation lines above and below VWAP. These measure price dispersion, not reversal probabilities.")
int deviationCount = input.int(3, "Deviation channels (1 / 2 / 3 sigma)", minval = 1, maxval = 3, group = G_DEVIATIONS, tooltip = "Maximum deviation distance on each side of VWAP: 1, 2 or 3 standard deviations.")
bool channelFill = input.bool(true, "Shade deviation channels", group = G_DEVIATIONS, tooltip = "Add a light background fill inside the VWAP deviation channels. Requires Show VWAP deviation lines.")
string deviationGrid = input.string("Dense grid (0.10 sigma)", "Deviation line density", options = ["Main levels (1 / 2 / 3 sigma)", "Fine grid (0.25 sigma)", "Dense grid (0.10 sigma)"], group = G_DEVIATIONS, tooltip = "Choose main deviation lines only, or add a finer grid every 0.25 or 0.10 standard deviations.")
bool deviationLabels = input.bool(true, "Label main deviation levels", group = G_DEVIATIONS, tooltip = "Show prices for the main positive and negative deviation levels. Requires visible deviation lines.")
color deviationColor = input.color(#4E858D, "Deviation low-volume color", group = G_DEVIATIONS, tooltip = "Low-volume end of the deviation color gradient. Colors use the latest profile volume at each line endpoint.")
color deviationHighColor = input.color(#00F5FF, "Deviation high-volume color", group = G_DEVIATIONS, tooltip = "High-volume deviation color. More volume gradually increases brightness toward pale cyan-white. Only the highest-volume lines are solid; all deviations are fixed at one pixel.")
int deviationFade = input.int(10, "High-volume deviation transparency", minval = 0, maxval = 100, group = G_DEVIATIONS, tooltip = "Transparency of deviation lines near high-volume profile prices. 0 is solid; 100 is invisible.")
int deviationLowFade = input.int(85, "Low-volume deviation transparency", minval = 0, maxval = 100, group = G_DEVIATIONS, tooltip = "Transparency of deviation lines near low-volume profile prices. 0 is solid; 100 is invisible.")
string G_PROFILE = "04 - Volume Profile - Layout and Colors"
bool densityVisible = input.bool(true, "Show volume distribution", group = G_PROFILE, tooltip = "Show the volume histogram to the right of the chart. Bar length represents estimated volume at each price level.")
float valueAreaPercent = input.float(70, "Value area volume (%)", minval = 50, maxval = 95, step = 5, group = G_PROFILE, tooltip = "Share of estimated profile volume included in the value area around the POC. VAH and VAL mark its upper and lower edges.")
int densityBins = input.int(64, "Volume price bins", minval = 16, maxval = 80, group = G_PROFILE, tooltip = "Number of horizontal price rows in the profile. More rows give finer detail; fewer rows combine wider price ranges.")
int densityWidth = input.int(20, "Distribution width (chart bars)", minval = 10, maxval = 180, group = G_PROFILE, tooltip = "Maximum histogram width, measured in chart bars. Smaller values keep the right side more compact.")
int densityGap = input.int(2, "Distribution gap after meter (bars)", minval = 1, maxval = 30, group = G_PROFILE, tooltip = "Space between the meter and the profile, measured in chart bars. Without the meter, this is the gap after the current candle.")
bool valueLabels = input.bool(true, "Show VWAP / POC / VAH / VAL prices", group = G_PROFILE, tooltip = "Show prices for VWAP, POC (highest-volume row), VAH (value area high) and VAL (value area low).")
color profileUpLow = input.color(#428F9B, "Profile up-volume: low volume", group = G_PROFILE, tooltip = "Low-volume color for profile volume allocated from rising candles. Candle direction is not a measure of buyer-initiated trades.")
color profileUpColor = input.color(#55F8FF, "Profile up-volume: high volume", group = G_PROFILE, tooltip = "High-volume color for profile volume allocated from rising candles.")
color profileDownLow = input.color(#263D4D, "Profile down-volume: low volume", group = G_PROFILE, tooltip = "Low-volume color for profile volume allocated from falling candles. Candle direction is not a measure of seller-initiated trades.")
color downColor = input.color(#3B7185, "Profile down-volume: high volume", group = G_PROFILE, tooltip = "High-volume color for profile volume allocated from falling candles.")
color controlColor = input.color(#FF3D00, "POC / value area", group = G_PROFILE, tooltip = "Color of the POC and value-area markings, their price labels and the light value-area background.")
string G_ZONE_SOURCES = "05 - OB / FVG - Sources and Labels"
bool zonesChart = input.bool(false, "Chart timeframe", group = G_ZONE_SOURCES, tooltip = "Show order blocks and fair value gaps from the chart timeframe, subject to the bullish and bearish visibility switches.")
bool z1ob = input.bool(false, "Layer 1 OB", group = G_ZONE_SOURCES, tooltip = "Show order blocks from layer 1. Automatic mode assigns this layer timeframe; Manual mode uses its manual timeframe. Bullish and bearish switches still apply.")
bool z1gap = input.bool(false, "FVG", group = G_ZONE_SOURCES, tooltip = "Show fair value gaps from layer 1. Automatic mode assigns this layer timeframe; Manual mode uses its manual timeframe. Bullish and bearish switches still apply.")
string z1tfManual = input.timeframe("240", "Manual TF", group = G_ZONE_SOURCES, active = not automaticTF and (z1ob or z1gap), tooltip = "Manual source timeframe for BOTH order blocks and fair value gaps in layer 1. Automatic mode sets this source for you.")
bool z2ob = input.bool(false, "Layer 2 OB", group = G_ZONE_SOURCES, tooltip = "Show order blocks from layer 2. Automatic mode assigns this layer timeframe; Manual mode uses its manual timeframe. Bullish and bearish switches still apply.")
bool z2gap = input.bool(false, "FVG", group = G_ZONE_SOURCES, tooltip = "Show fair value gaps from layer 2. Automatic mode assigns this layer timeframe; Manual mode uses its manual timeframe. Bullish and bearish switches still apply.")
string z2tfManual = input.timeframe("1D", "Manual TF", group = G_ZONE_SOURCES, active = not automaticTF and (z2ob or z2gap), tooltip = "Manual source timeframe for BOTH order blocks and fair value gaps in layer 2. Automatic mode sets this source for you.")
bool z3ob = input.bool(false, "Layer 3 OB", group = G_ZONE_SOURCES, tooltip = "Show order blocks from layer 3. Automatic mode assigns this layer timeframe; Manual mode uses its manual timeframe. Bullish and bearish switches still apply.")
bool z3gap = input.bool(false, "FVG", group = G_ZONE_SOURCES, tooltip = "Show fair value gaps from layer 3. Automatic mode assigns this layer timeframe; Manual mode uses its manual timeframe. Bullish and bearish switches still apply.")
string z3tfManual = input.timeframe("1W", "Manual TF", group = G_ZONE_SOURCES, active = not automaticTF and (z3ob or z3gap), tooltip = "Manual source timeframe for BOTH order blocks and fair value gaps in layer 3. Automatic mode sets this source for you.")
int zoneAgeLimit = input.int(1500, "Maximum zone age (source candles)", minval = 50, maxval = 5000, group = G_ZONE_SOURCES, tooltip = "Maximum age of an order block or fair value gap, counted in candles of its own source timeframe.")
string G_BLOCKS = "06 - Order Blocks - Detection and Colors"
bool bullishBlocks = input.bool(true, "Bullish order blocks", group = G_BLOCKS, tooltip = "Allow bullish order blocks from enabled sources. A bullish block is the last opposite candle before a confirmed upward structure break.")
bool bearishBlocks = input.bool(true, "Bearish order blocks", group = G_BLOCKS, tooltip = "Allow bearish order blocks from enabled sources. A bearish block is the last opposite candle before a confirmed downward structure break.")
int structureStrength = input.int(5, "Structure pivot strength", minval = 2, maxval = 30, group = G_BLOCKS, tooltip = "Source candles required on each side of a structural pivot. Higher values confirm larger swings but take longer.")
int oppositeSearch = input.int(20, "Opposite candle search", minval = 2, maxval = 100, group = G_BLOCKS, tooltip = "Maximum number of source candles to search backward for the opposite candle that defines an order block, within the broken swing.")
float breakBodyATR = input.float(0.5, "Minimum break body (ATR)", minval = 0, maxval = 5, step = 0.1, group = G_BLOCKS, tooltip = "Minimum breakout candle body as a multiple of ATR, a measure of typical price movement. Higher values filter weaker breaks; 0 disables the size filter.")
int blockLimit = input.int(6, "Active blocks per side / source", minval = 1, maxval = 10, group = G_BLOCKS, tooltip = "Maximum active bullish blocks and bearish blocks kept separately for each source. Older blocks are removed when the limit is reached.")
color bullBlockColor = input.color(color.new(#22C55E, 82), "Bullish OB (green)", group = G_BLOCKS, tooltip = "Fill color and transparency of bullish order blocks. Borders and labels use the same base color.")
color bearBlockColor = input.color(color.new(#EF4444, 82), "Bearish OB (red)", group = G_BLOCKS, tooltip = "Fill color and transparency of bearish order blocks. Borders and labels use the same base color.")
string G_GAPS = "07 - Fair Value Gaps - Detection and Colors"
bool bullishGaps = input.bool(true, "Bullish fair value gaps", group = G_GAPS, tooltip = "Allow bullish three-candle fair value gaps from enabled sources. These form when the third candle low is above the first candle high.")
bool bearishGaps = input.bool(true, "Bearish fair value gaps", group = G_GAPS, tooltip = "Allow bearish three-candle fair value gaps from enabled sources. These form when the third candle high is below the first candle low.")
float gapSizeATR = input.float(0.1, "Minimum gap (ATR)", minval = 0, maxval = 5, step = 0.05, group = G_GAPS, tooltip = "Minimum gap height as a multiple of ATR. Higher values hide smaller gaps; 0 disables the size filter.")
string gapRemoval = input.string("Full fill", "Remove gap after", options = ["First touch", "Full fill"], group = G_GAPS, tooltip = "First touch removes a gap when price reaches its near edge. Full fill keeps it until price reaches the far edge.")
int gapLimit = input.int(8, "Active gaps per side / source", minval = 1, maxval = 15, group = G_GAPS, tooltip = "Maximum active bullish gaps and bearish gaps kept separately for each source. Older gaps are removed when the limit is reached.")
color bullGapColor = input.color(color.new(#2DD4BF, 93), "Bullish FVG (turquoise)", group = G_GAPS, tooltip = "Fill color and transparency of bullish fair value gaps. Dashed borders and labels use the same base color.")
color bearGapColor = input.color(color.new(#F472B6, 93), "Bearish FVG (pink)", group = G_GAPS, tooltip = "Fill color and transparency of bearish fair value gaps. Dashed borders and labels use the same base color.")
string G_LIQ_SOURCES = "08 - Liquidity - Sources"
bool liquidityLines = input.bool(true, "Show liquidity lines and labels", group = G_LIQ_SOURCES, tooltip = "Show lines and labels for unswept BSL above swing highs and SSL below swing lows. Hiding these drawings does not disable the meter.")
bool liquidityChartManual = input.bool(true, "Enable chart timeframe", group = G_LIQ_SOURCES, active = not automaticTF, tooltip = "Manual mode: include chart-timeframe swing liquidity. Automatic mode includes chart liquidity automatically.")
bool q1onManual = input.bool(true, "Enable layer 1", group = G_LIQ_SOURCES, active = not automaticTF, tooltip = "Manual mode: enable liquidity layer 1. It can supply visible lines and the meter when All enabled liquidity timeframes is selected.")
string q1tfManual = input.timeframe("240", "Manual TF", group = G_LIQ_SOURCES, active = not automaticTF and q1onManual, tooltip = "Manual source timeframe for liquidity layer 1. Automatic mode uses its preset sources instead.")
bool q2onManual = input.bool(true, "Enable layer 2", group = G_LIQ_SOURCES, active = not automaticTF, tooltip = "Manual mode: enable liquidity layer 2. It can supply visible lines and the meter when All enabled liquidity timeframes is selected.")
string q2tfManual = input.timeframe("1D", "Manual TF", group = G_LIQ_SOURCES, active = not automaticTF and q2onManual, tooltip = "Manual source timeframe for liquidity layer 2. Automatic mode uses its preset sources instead.")
bool q3onManual = input.bool(false, "Enable layer 3", group = G_LIQ_SOURCES, active = not automaticTF, tooltip = "Manual mode: enable liquidity layer 3. It can supply visible lines and the meter when All enabled liquidity timeframes is selected.")
string q3tfManual = input.timeframe("1W", "Manual TF", group = G_LIQ_SOURCES, active = not automaticTF and q3onManual, tooltip = "Manual source timeframe for liquidity layer 3. Automatic mode uses its preset sources instead.")
string G_LIQ_DETECT = "09 - Liquidity - Swing Detection"
int liquidityStrength = input.int(10, "Liquidity pivot strength", minval = 2, maxval = 50, group = G_LIQ_DETECT, tooltip = "Source candles required on EACH side of a liquidity pivot before it is confirmed. Larger values identify broader swings with more delay.")
float liquidityExcursion = input.float(0.75, "Minimum excursion on both sides (ATR)", minval = 0, maxval = 10, step = 0.25, group = G_LIQ_DETECT, tooltip = "Minimum price excursion on both sides of a liquidity pivot, measured in ATR. Higher values filter smaller swings; 0 disables the excursion filter.")
int liquidityLimit = input.int(6, "Unswept levels per side / source", minval = 1, maxval = 30, group = G_LIQ_DETECT, tooltip = "Maximum unswept BSL levels and SSL levels kept separately for each source. BSL is removed on a high touching it; SSL on a low touching it.")
int liquidityAge = input.int(3000, "Maximum level age (source candles)", minval = 100, maxval = 10000, group = G_LIQ_DETECT, tooltip = "Maximum age of a liquidity level, counted in candles of its own source timeframe.")
string G_LIQ_STYLE = "10 - Liquidity - Lines and Labels"
int liquidityStroke = input.int(1, "Liquidity line width", minval = 1, maxval = 4, group = G_LIQ_STYLE, tooltip = "Thickness of the horizontal BSL and SSL lines. This does not change the meter borders.")
color bslColor = input.color(#22C55E, "BSL lines", group = G_LIQ_STYLE, tooltip = "Color of visible buy-side liquidity (BSL) lines and labels. Meter box colors are set separately.")
color sslColor = input.color(#EF4444, "SSL lines", group = G_LIQ_STYLE, tooltip = "Color of visible sell-side liquidity (SSL) lines and labels. Meter box colors are set separately.")
string G_METER_SOURCES = "11 - Barometer - Visibility and Sources"
bool meterVisible = input.bool(true, "Show live distance meter", group = G_METER_SOURCES, tooltip = "Show green and red boxes between current price and the nearest eligible BSL/SSL. Both sides are required. Percentages split the total distance into 100%; they are not probabilities.")
string meterModeManual = input.string("Selected timeframes", "Meter source mode", options = ["All enabled liquidity timeframes", "Chart timeframe only", "Selected timeframes"], group = G_METER_SOURCES, active = not automaticTF and meterVisible, tooltip = "Manual mode: use all enabled liquidity sources, the chart timeframe only, or the selected meter sources A/B/C. Missing levels are never replaced with another timeframe.")
bool meterSource1OnManual = input.bool(true, "Use source A", group = G_METER_SOURCES, active = not automaticTF and meterVisible and meterModeManual == "Selected timeframes", tooltip = "Include source A in the meter when Manual mode and Selected timeframes are selected. Enable one source to restrict both boundaries to a single timeframe.")
string meterSource1TFManual = input.timeframe("240", "Manual TF", group = G_METER_SOURCES, active = not automaticTF and meterVisible and meterModeManual == "Selected timeframes" and meterSource1OnManual, tooltip = "Manual timeframe for meter source A. Independent of visible liquidity layers. If an eligible boundary is missing, the meter waits without using another source.")
bool meterSource2OnManual = input.bool(false, "Use source B", group = G_METER_SOURCES, active = not automaticTF and meterVisible and meterModeManual == "Selected timeframes", tooltip = "Include source B in the meter when Manual mode and Selected timeframes are selected. Enable one source to restrict both boundaries to a single timeframe.")
string meterSource2TFManual = input.timeframe("1D", "Manual TF", group = G_METER_SOURCES, active = not automaticTF and meterVisible and meterModeManual == "Selected timeframes" and meterSource2OnManual, tooltip = "Manual timeframe for meter source B. Independent of visible liquidity layers. If an eligible boundary is missing, the meter waits without using another source.")
bool meterSource3OnManual = input.bool(false, "Use source C", group = G_METER_SOURCES, active = not automaticTF and meterVisible and meterModeManual == "Selected timeframes", tooltip = "Include source C in the meter when Manual mode and Selected timeframes are selected. Enable one source to restrict both boundaries to a single timeframe.")
string meterSource3TFManual = input.timeframe("1W", "Manual TF", group = G_METER_SOURCES, active = not automaticTF and meterVisible and meterModeManual == "Selected timeframes" and meterSource3OnManual, tooltip = "Manual timeframe for meter source C. Independent of visible liquidity layers. If an eligible boundary is missing, the meter waits without using another source.")
bool meterSourceCaption = input.bool(true, "Show selected sources", group = G_METER_SOURCES, tooltip = "Show the active meter mode and source timeframes above the meter. Verified means the returned data matches the requested timeframe, not that a trade is confirmed.")
string G_METER_LAYOUT = "12 - Barometer - Layout and Text"
int meterGap = input.int(2, "Gap before meter (chart bars)", minval = 1, maxval = 20, group = G_METER_LAYOUT, tooltip = "Horizontal space between the current candle and the meter, measured in chart bars.")
int meterProjection = input.int(12, "Box projection (chart bars)", minval = 1, maxval = 200, group = G_METER_LAYOUT, tooltip = "Width of the meter boxes in chart bars. The boxes move forward with each new chart candle and update with received price ticks.")
int meterStroke = input.int(1, "Box border width", minval = 0, maxval = 5, group = G_METER_LAYOUT, tooltip = "Thickness of both meter borders. Set to 0 to hide the borders while keeping the fills and text.")
string G_METER_COLORS = "13 - Barometer - Colors"
color meterUpper = input.color(color.new(#22C55E, 86), "Upper box fill", group = G_METER_COLORS, tooltip = "Fill color and transparency of the upper box, from current price to the selected BSL. This does not change its border.")
color meterLower = input.color(color.new(#EF4444, 86), "Lower box fill", group = G_METER_COLORS, tooltip = "Fill color and transparency of the lower box, from current price to the selected SSL. This does not change its border.")
color meterUpperEdge = input.color(#22C55E, "Upper box border", group = G_METER_COLORS, tooltip = "Border color of the upper BSL box. Also used for its text when Match text to each box border is on.")
color meterLowerEdge = input.color(#EF4444, "Lower box border", group = G_METER_COLORS, tooltip = "Border color of the lower SSL box. Also used for its text when Match text to each box border is on.")
bool meterMatchText = input.bool(true, "Match text to each box border", group = G_METER_COLORS, tooltip = "Use each box border color for its percentage, source timeframe and price text. Turn off to use the custom text color.")
color meterInk = input.color(color.white, "Custom box text color (matching off)", group = G_METER_COLORS, tooltip = "Color of meter text when border matching is off. Also used for the current-price divider and waiting messages.")
string G_LABELS = "14 - Labels - Text Sizes and Background"
string profileFont = input.string("Small", "Profile prices and heading", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = G_LABELS, tooltip = "Text size for profile prices, the profile heading and main deviation price labels.")
string zoneFont = input.string("Small", "OB and FVG labels", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = G_LABELS, tooltip = "Text size inside order block and fair value gap boxes.")
string liquidityFont = input.string("Small", "Liquidity labels", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = G_LABELS, tooltip = "Text size of the BSL and SSL labels beside visible liquidity lines.")
string meterFont = input.string("Small", "Barometer box text", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = G_LABELS, tooltip = "Text size of percentages and details inside the meter, and waiting messages. Percentages stay bold; the other details stay regular.")
color labelBackground = input.color(color.new(#241F18, 8), "Label background", group = G_LABELS, tooltip = "Background color for profile price labels, liquidity labels and meter source/status labels.")
f_font(string selection) =>
switch selection
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
=> size.huge
// Resolve actual source timeframes once, in the main chart context.
// No fallback to another source is used when a meter boundary is missing.
f_autoSources(float seconds) =>
switch
seconds <= 60 => ["15", "60", "1D", "5"]
seconds <= 300 => ["30", "240", "1D", "30"]
seconds <= 900 => ["60", "240", "1D", "60"]
seconds <= 3600 => ["240", "1D", "1W", "240"]
seconds <= 14400 => ["1D", "1W", "1M", "1D"]
seconds <= 86400 => ["1W", "1M", "3M", "1W"]
seconds <= 604800 => ["1M", "3M", "6M", "1M"]
seconds <= 2678400 => ["3M", "12M", "12M", "3M"]
=> ["12M", "12M", "12M", "12M"]
[autoSource1, autoSource2, autoSource3, autoMeterTF] = f_autoSources(timeframe.in_seconds())
bool valueOnChart = automaticTF or valueOnChartManual
string z1tf = automaticTF ? autoSource1 : z1tfManual
string z2tf = automaticTF ? autoSource2 : z2tfManual
string z3tf = automaticTF ? autoSource3 : z3tfManual
bool liquidityChart = automaticTF or liquidityChartManual
bool q1on = automaticTF or q1onManual
bool q2on = automaticTF or q2onManual
bool q3on = not automaticTF and q3onManual
string q1tf = automaticTF ? autoSource1 : q1tfManual
string q2tf = automaticTF ? autoSource2 : q2tfManual
string q3tf = automaticTF ? autoSource3 : q3tfManual
string meterMode = automaticTF ? "Selected timeframes" : meterModeManual
bool meterSource1On = automaticTF or meterSource1OnManual
bool meterSource2On = not automaticTF and meterSource2OnManual
bool meterSource3On = not automaticTF and meterSource3OnManual
string meterSource1TF = automaticTF ? autoMeterTF : meterSource1TFManual
string meterSource2TF = meterSource2TFManual
string meterSource3TF = meterSource3TFManual
string valueTF = valueOnChart ? timeframe.period : valueCustomTF
f_equalTF(string a, string b) =>
timeframe.in_seconds(a) == timeframe.in_seconds(b)
f_tf(string tf) =>
float sec = timeframe.in_seconds(tf)
sec < 60 ? str.tostring(sec, "#") + "s" : sec < 3600 ? str.tostring(sec / 60, "#") + "m" : sec < 86400 ? str.tostring(sec / 3600, "#.##") + "H" : tf
f_visibleLiquidity(string tf) =>
(liquidityChart and f_equalTF(tf, timeframe.period)) or (q1on and f_equalTF(tf, q1tf)) or (q2on and f_equalTF(tf, q2tf)) or (q3on and f_equalTF(tf, q3tf))
f_meterSource(string tf) =>
bool chosen = false
if meterMode == "All enabled liquidity timeframes"
chosen := f_visibleLiquidity(tf)
else if meterMode == "Chart timeframe only"
chosen := f_equalTF(tf, timeframe.period)
else
chosen := (meterSource1On and f_equalTF(tf, meterSource1TF)) or (meterSource2On and f_equalTF(tf, meterSource2TF)) or (meterSource3On and f_equalTF(tf, meterSource3TF))
meterVisible and chosen
// DATA RECORDS
type ValueCandles
array<int> stamp
array<float> highPrice
array<float> lowPrice
array<float> typicalPrice
array<float> weight
array<bool> rising
type ZoneSeed
float ceiling
float floor
int originTime
int originIndex
int formedTime
int formedIndex
int category
type ZoneBook
array<ZoneSeed> seeds
float liveHigh
float liveLow
int liveTime
type LevelSeed
float price
int stamp
int originIndex
bool upper
type LevelBook
array<LevelSeed> seeds
float liveHigh
float liveLow
string sourceTF
type LevelView
float price
int stamp
bool upper
string tf
// SOURCE WINDOW
f_valueCandles() =>
ValueCandles packet = na
if barstate.islast or barstate.islastconfirmedhistory
int offset = valueClosed ? 1 : 0
int available = math.min(valueLength, bar_index + 1 - offset)
array<int> ts = array.new<int>()
array<float> hs = array.new<float>()
array<float> ls = array.new<float>()
array<float> ps = array.new<float>()
array<float> vs = array.new<float>()
array<bool> ds = array.new<bool>()
if available > 0
for k = 0 to available - 1
int at = available - k - 1 + offset
array.push(ts, time[at])
array.push(hs, high[at])
array.push(ls, low[at])
array.push(ps, hlc3[at])
array.push(vs, math.max(0.0, nz(volume[at])))
array.push(ds, close[at] >= open[at])
packet := ValueCandles.new(ts, hs, ls, ps, vs, ds)
packet
// STRUCTURE ENGINE
// Category +1/-1: bullish/bearish OB. Category +2/-2: bullish/bearish FVG.
f_storeZone(array<ZoneSeed> seeds, ZoneSeed seed, int cap) =>
int count = 0
int oldest = -1
bool duplicate = false
if array.size(seeds) > 0
for i = 0 to array.size(seeds) - 1
ZoneSeed prior = array.get(seeds, i)
if prior.category == seed.category
count += 1
if oldest < 0
oldest := i
duplicate := duplicate or prior.originTime == seed.originTime
if not duplicate and seed.ceiling > seed.floor
if count >= cap and oldest >= 0
ZoneSeed discarded = array.remove(seeds, oldest)
count -= 1
array.push(seeds, seed)
0
f_structure(bool chartContext) =>
var array<ZoneSeed> active = array.new<ZoneSeed>()
var float upperPivot = na
var float lowerPivot = na
var int upperOrigin = na
var int lowerOrigin = na
var bool upperBroken = false
var bool lowerBroken = false
float volatility = ta.atr(14)
float ph = ta.pivothigh(high, structureStrength, structureStrength)
float pl = ta.pivotlow(low, structureStrength, structureStrength)
int offset = chartContext ? 0 : 1
if (chartContext ? barstate.isconfirmed : bar_index > 0)
int sourceIndex = bar_index - offset
if array.size(active) > 0
for i = array.size(active) - 1 to 0
ZoneSeed z = array.get(active, i)
bool bullish = z.category > 0
bool gap = math.abs(z.category) == 2
bool invalid = false
if gap
invalid := bullish ? low[offset] <= (gapRemoval == "First touch" ? z.ceiling : z.floor) : high[offset] >= (gapRemoval == "First touch" ? z.floor : z.ceiling)
else
invalid := bullish ? close[offset] < z.floor : close[offset] > z.ceiling
if invalid or sourceIndex - z.formedIndex > zoneAgeLimit
ZoneSeed discarded = array.remove(active, i)
invalid := true
if not na(ph[offset])
upperPivot := ph[offset]
upperOrigin := sourceIndex - structureStrength
upperBroken := false
if not na(pl[offset])
lowerPivot := pl[offset]
lowerOrigin := sourceIndex - structureStrength
lowerBroken := false
for direction = 0 to 1
bool bullish = direction == 0
bool crossed = bullish ? not na(upperPivot) and not upperBroken and close[offset] > upperPivot : not na(lowerPivot) and not lowerBroken and close[offset] < lowerPivot
if crossed
if bullish
upperBroken := true
else
lowerBroken := true
float body = bullish ? close[offset] - open[offset] : open[offset] - close[offset]
if body > 0 and body >= volatility[offset] * breakBodyATR
int originIndex = bullish ? upperOrigin : lowerOrigin
int depth = math.min(oppositeSearch, sourceIndex - originIndex)
if depth > 0
for step = 1 to depth
int at = offset + step
bool opposite = bullish ? close[at] < open[at] : close[at] > open[at]
if opposite
bool clear = bullish ? close[offset] > high[at] : close[offset] < low[at]
if clear
ZoneSeed seed = ZoneSeed.new(high[at], low[at], time[at], bar_index - at, time[offset], sourceIndex, bullish ? 1 : -1)
f_storeZone(active, seed, blockLimit)
break
if sourceIndex >= 2
if low[offset] > high[offset + 2] and low[offset] - high[offset + 2] >= volatility[offset] * gapSizeATR
f_storeZone(active, ZoneSeed.new(low[offset], high[offset + 2], time[offset + 2], sourceIndex - 2, time[offset], sourceIndex, 2), gapLimit)
if high[offset] < low[offset + 2] and low[offset + 2] - high[offset] >= volatility[offset] * gapSizeATR
f_storeZone(active, ZoneSeed.new(low[offset + 2], high[offset], time[offset + 2], sourceIndex - 2, time[offset], sourceIndex, -2), gapLimit)
ZoneBook packet = na
if barstate.islast or barstate.islastconfirmedhistory
packet := ZoneBook.new(array.copy(active), high, low, time)
packet
// LIQUIDITY ENGINE
f_storeLevel(array<LevelSeed> seeds, LevelSeed seed) =>
int count = 0
int oldest = -1
bool duplicate = false
if array.size(seeds) > 0
for i = 0 to array.size(seeds) - 1
LevelSeed prior = array.get(seeds, i)
if prior.upper == seed.upper
count += 1
if oldest < 0
oldest := i
duplicate := duplicate or math.abs(prior.price - seed.price) < syminfo.mintick * 0.5
if not duplicate
if count >= liquidityLimit and oldest >= 0
LevelSeed discarded = array.remove(seeds, oldest)
count -= 1
array.push(seeds, seed)
0
f_liquidity(bool chartContext) =>
var array<LevelSeed> active = array.new<LevelSeed>()
float volatility = ta.atr(14)
float ph = ta.pivothigh(high, liquidityStrength, liquidityStrength)
float pl = ta.pivotlow(low, liquidityStrength, liquidityStrength)
float leftBottom = ta.lowest(low, liquidityStrength)[liquidityStrength + 1]
float rightBottom = ta.lowest(low, liquidityStrength)
float leftTop = ta.highest(high, liquidityStrength)[liquidityStrength + 1]
float rightTop = ta.highest(high, liquidityStrength)
int offset = chartContext ? 0 : 1
if (chartContext ? barstate.isconfirmed : bar_index > 0)
int sourceIndex = bar_index - offset
if array.size(active) > 0
for i = array.size(active) - 1 to 0
LevelSeed q = array.get(active, i)
bool swept = q.upper ? high[offset] >= q.price : low[offset] <= q.price
if swept or sourceIndex - q.originIndex > liquidityAge
LevelSeed discarded = array.remove(active, i)
swept := true
float threshold = nz(volatility[liquidityStrength + offset], volatility[offset]) * liquidityExcursion
bool significantHigh = not na(ph[offset]) and rightTop[offset] < ph[offset] and ph[offset] - math.max(leftBottom[offset], rightBottom[offset]) >= threshold
bool significantLow = not na(pl[offset]) and rightBottom[offset] > pl[offset] and math.min(leftTop[offset], rightTop[offset]) - pl[offset] >= threshold
if significantHigh
f_storeLevel(active, LevelSeed.new(ph[offset], time[liquidityStrength + offset], sourceIndex - liquidityStrength, true))
if significantLow
f_storeLevel(active, LevelSeed.new(pl[offset], time[liquidityStrength + offset], sourceIndex - liquidityStrength, false))
LevelBook packet = na
if barstate.islast or barstate.islastconfirmedhistory
packet := LevelBook.new(array.copy(active), high, low, timeframe.period)
packet
// Source-local scalar meter engine. The tuple carries native source seconds
// and source candle time, so the chart can verify the returned context.
f_meterPair(bool chartContext) =>
var array<LevelSeed> active = array.new<LevelSeed>()
float volatility = ta.atr(14)
float ph = ta.pivothigh(high, liquidityStrength, liquidityStrength)
float pl = ta.pivotlow(low, liquidityStrength, liquidityStrength)
float leftBottom = ta.lowest(low, liquidityStrength)[liquidityStrength + 1]
float rightBottom = ta.lowest(low, liquidityStrength)
float leftTop = ta.highest(high, liquidityStrength)[liquidityStrength + 1]
float rightTop = ta.highest(high, liquidityStrength)
int offset = chartContext ? 0 : 1
if (chartContext ? barstate.isconfirmed : bar_index > 0)
int sourceIndex = bar_index - offset
if array.size(active) > 0
for i = array.size(active) - 1 to 0
LevelSeed q = array.get(active, i)
bool swept = q.upper ? high[offset] >= q.price : low[offset] <= q.price
if swept or sourceIndex - q.originIndex > liquidityAge
LevelSeed discarded = array.remove(active, i)
swept := true
float threshold = nz(volatility[liquidityStrength + offset], volatility[offset]) * liquidityExcursion
bool significantHigh = not na(ph[offset]) and rightTop[offset] < ph[offset] and ph[offset] - math.max(leftBottom[offset], rightBottom[offset]) >= threshold
bool significantLow = not na(pl[offset]) and rightBottom[offset] > pl[offset] and math.min(leftTop[offset], rightTop[offset]) - pl[offset] >= threshold
if significantHigh
f_storeLevel(active, LevelSeed.new(ph[offset], time[liquidityStrength + offset], sourceIndex - liquidityStrength, true))
if significantLow
f_storeLevel(active, LevelSeed.new(pl[offset], time[liquidityStrength + offset], sourceIndex - liquidityStrength, false))
float nearestUpper = na
float nearestLower = na
if array.size(active) > 0
for q in active
bool swept = q.upper ? high >= q.price : low <= q.price
if not swept
if q.upper and q.price > close and (na(nearestUpper) or q.price < nearestUpper)
nearestUpper := q.price
if not q.upper and q.price < close and (na(nearestLower) or q.price > nearestLower)
nearestLower := q.price
[nearestUpper, nearestLower, timeframe.in_seconds(), time]
// SOURCE REQUESTS: latest bounded snapshots, no historical drawing objects
ValueCandles valueData = na
if f_equalTF(valueTF, timeframe.period)
valueData := f_valueCandles()
else
valueData := request.security(syminfo.tickerid, valueTF, f_valueCandles(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 502)
ZoneBook chartZones = f_structure(true)
ZoneBook zones1 = na
ZoneBook zones2 = na
ZoneBook zones3 = na
if z1ob or z1gap
zones1 := request.security(syminfo.tickerid, z1tf, f_structure(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 6000)
if z2ob or z2gap
zones2 := request.security(syminfo.tickerid, z2tf, f_structure(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 6000)
if z3ob or z3gap
zones3 := request.security(syminfo.tickerid, z3tf, f_structure(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 6000)
LevelBook chartLevels = f_liquidity(true)
LevelBook levels1 = na
LevelBook levels2 = na
LevelBook levels3 = na
bool needQ1 = q1on
bool needQ2 = q2on
bool needQ3 = q3on
if needQ1
levels1 := request.security(syminfo.tickerid, q1tf, f_liquidity(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 10200)
if needQ2
levels2 := request.security(syminfo.tickerid, q2tf, f_liquidity(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 10200)
if needQ3
levels3 := request.security(syminfo.tickerid, q3tf, f_liquidity(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 10200)
// Selected sources each use the same scalar-returning engine. There is no
// separate single/multiple policy and no collection-based selected-source path.
bool selectedMeterMode = meterVisible and meterMode == "Selected timeframes"
float meterUpper1 = na
float meterLower1 = na
int meterSeconds1 = na
int meterTime1 = na
if selectedMeterMode and meterSource1On
if f_equalTF(meterSource1TF, timeframe.period)
[rawUpper, rawLower, rawSeconds, rawTime] = f_meterPair(true)
meterUpper1 := rawUpper
meterLower1 := rawLower
meterSeconds1 := rawSeconds
meterTime1 := rawTime
else
[rawUpper, rawLower, rawSeconds, rawTime] = request.security(syminfo.tickerid, meterSource1TF, f_meterPair(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 10200)
meterUpper1 := rawUpper
meterLower1 := rawLower
meterSeconds1 := rawSeconds
meterTime1 := rawTime
float meterUpper2 = na
float meterLower2 = na
int meterSeconds2 = na
int meterTime2 = na
if selectedMeterMode and meterSource2On
if f_equalTF(meterSource2TF, timeframe.period)
[rawUpper, rawLower, rawSeconds, rawTime] = f_meterPair(true)
meterUpper2 := rawUpper
meterLower2 := rawLower
meterSeconds2 := rawSeconds
meterTime2 := rawTime
else
[rawUpper, rawLower, rawSeconds, rawTime] = request.security(syminfo.tickerid, meterSource2TF, f_meterPair(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 10200)
meterUpper2 := rawUpper
meterLower2 := rawLower
meterSeconds2 := rawSeconds
meterTime2 := rawTime
float meterUpper3 = na
float meterLower3 = na
int meterSeconds3 = na
int meterTime3 = na
if selectedMeterMode and meterSource3On
if f_equalTF(meterSource3TF, timeframe.period)
[rawUpper, rawLower, rawSeconds, rawTime] = f_meterPair(true)
meterUpper3 := rawUpper
meterLower3 := rawLower
meterSeconds3 := rawSeconds
meterTime3 := rawTime
else
[rawUpper, rawLower, rawSeconds, rawTime] = request.security(syminfo.tickerid, meterSource3TF, f_meterPair(false), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, calc_bars_count = 10200)
meterUpper3 := rawUpper
meterLower3 := rawLower
meterSeconds3 := rawSeconds
meterTime3 := rawTime
bool selectedSourcesVerified = (not meterSource1On or (not na(meterSeconds1) and meterSeconds1 == timeframe.in_seconds(meterSource1TF))) and (not meterSource2On or (not na(meterSeconds2) and meterSeconds2 == timeframe.in_seconds(meterSource2TF))) and (not meterSource3On or (not na(meterSeconds3) and meterSeconds3 == timeframe.in_seconds(meterSource3TF)))
// DRAWING CANVAS: active-state view, rebuilt on every last-bar update
var array<box> tiles = array.new<box>()
var array<line> strokes = array.new<line>()
var array<label> captions = array.new<label>()
var array<polyline> paths = array.new<polyline>()
f_clear() =>
if array.size(tiles) > 0
for tile in tiles
box.delete(tile)
array.clear(tiles)
if array.size(strokes) > 0
for stroke in strokes
line.delete(stroke)
array.clear(strokes)
if array.size(captions) > 0
for caption in captions
label.delete(caption)
array.clear(captions)
if array.size(paths) > 0
for path in paths
polyline.delete(path)
array.clear(paths)
0
f_tag(int x, float y, string captionText, color tint) =>
array.push(captions, label.new(x = x, y = y, text = captionText, style = label.style_label_left, color = color.new(labelBackground, 5), textcolor = tint, size = f_font(profileFont)))
0
f_horizontal(int left, int right, float y, color tint, string style) =>
array.push(strokes, line.new(x1 = left, y1 = y, x2 = right, y2 = y, color = tint, style = style))
0
f_zones(ZoneBook book, string tf, bool obs, bool gaps) =>
if not na(book)
if array.size(book.seeds) > 0
for z in book.seeds
bool gap = math.abs(z.category) == 2
bool bullish = z.category > 0
bool selected = gap ? gaps and (bullish ? bullishGaps : bearishGaps) : obs and (bullish ? bullishBlocks : bearishBlocks)
bool touched = gap and book.liveTime > z.formedTime and (bullish ? book.liveLow <= (gapRemoval == "First touch" ? z.ceiling : z.floor) : book.liveHigh >= (gapRemoval == "First touch" ? z.floor : z.ceiling))
if selected and not touched
color tint = gap ? (bullish ? bullGapColor : bearGapColor) : (bullish ? bullBlockColor : bearBlockColor)
string captionText = (bullish ? "Bullish " : "Bearish ") + (gap ? "FVG" : "OB") + " | " + f_tf(tf)
array.push(tiles, box.new(left = z.originTime, top = z.ceiling, right = time_close, bottom = z.floor, xloc = xloc.bar_time, bgcolor = tint, border_color = color.new(tint, gap ? 40 : 15), border_style = gap ? line.style_dashed : line.style_solid, border_width = 1, text = captionText, text_color = color.new(tint, 0), text_size = f_font(zoneFont), text_halign = text.align_right))
0
f_levels(LevelBook book, string tf, array<LevelView> outputLevels) =>
if not na(book) and f_visibleLiquidity(tf)
if array.size(book.seeds) > 0
for q in book.seeds
bool swept = q.upper ? book.liveHigh >= q.price : book.liveLow <= q.price
if not swept
array.push(outputLevels, LevelView.new(q.price, q.stamp, q.upper, book.sourceTF))
0
// Strict provenance gate: both the requested source and the source book must
// match. Missing levels remain missing; this function never searches other TFs.
f_meterLevels(LevelBook book, string expectedTF, array<LevelView> candidates) =>
if not na(book)
if f_equalTF(book.sourceTF, expectedTF) and f_meterSource(book.sourceTF)
if array.size(book.seeds) > 0
for q in book.seeds
bool swept = q.upper ? book.liveHigh >= q.price : book.liveLow <= q.price
if not swept
array.push(candidates, LevelView.new(q.price, q.stamp, q.upper, book.sourceTF))
0
f_addMeterPair(float upperPrice, float lowerPrice, int sourceSeconds, int sourceTime, string sourceTF, array<LevelView> candidates) =>
if f_meterSource(sourceTF) and not na(sourceSeconds) and sourceSeconds == timeframe.in_seconds(sourceTF)
if not na(upperPrice) and upperPrice > close
array.push(candidates, LevelView.new(upperPrice, sourceTime, true, sourceTF))
if not na(lowerPrice) and lowerPrice < close
array.push(candidates, LevelView.new(lowerPrice, sourceTime, false, sourceTF))
0
f_meterSourcesLabel() =>
string description = "All enabled liquidity timeframes"
if meterMode == "Chart timeframe only"
description := f_tf(timeframe.period)
else if meterMode == "Selected timeframes"
description := ""
if meterSource1On
description += f_tf(meterSource1TF)
if meterSource2On
description += (description == "" ? "" : " / ") + f_tf(meterSource2TF)
if meterSource3On
description += (description == "" ? "" : " / ") + f_tf(meterSource3TF)
if description == ""
description := "No selected source"
description
// VALUE STATISTICS / VOLUME ALLOCATION / INDEPENDENT CHANNEL DISPLAY
type ValueSummary
float mean
float control
float areaHigh
float areaLow
int candles
// Sample profile volume at a deviation endpoint using neighboring bin centers.
f_endpointVolume(float endpoint, float floorPrice, float ceilingPrice, float rowSize, array<float> volumeAtPrice) =>
float sampled = 0.0
int rows = array.size(volumeAtPrice)
if rows > 0 and rowSize > 0 and endpoint >= floorPrice and endpoint <= ceilingPrice
float location = math.max(0.0, math.min(float(rows - 1), (endpoint - floorPrice) / rowSize - 0.5))
int lowerBin = int(math.floor(location))
int upperBin = math.min(rows - 1, lowerBin + 1)
float fraction = location - lowerBin
sampled := array.get(volumeAtPrice, lowerBin) * (1.0 - fraction) + array.get(volumeAtPrice, upperBin) * fraction
sampled
f_value(ValueCandles data, int left, int right) =>
ValueSummary summary = na
int count = na(data) ? 0 : array.size(data.stamp)
if count > 0
array<float> means = array.new<float>()
array<float> spreads = array.new<float>()
float weight = 0.0
float mean = 0.0
float moment = 0.0
for i = 0 to count - 1
float w = array.get(data.weight, i)
float p = array.get(data.typicalPrice, i)
if w > 0
float total = weight + w
float delta = p - mean
float next = mean + delta * w / total
moment += w * delta * (p - next)
weight := total
mean := next
array.push(means, weight > 0 ? mean : na)
array.push(spreads, weight > 0 ? math.sqrt(math.max(moment / weight, 0.0)) : 0.0)
if weight > 0
// Fixed price bins span all source highs/lows, retaining all volume.
float floorPrice = array.min(data.lowPrice) - syminfo.mintick * 0.5
float ceilingPrice = array.max(data.highPrice) + syminfo.mintick * 0.5
float step = (ceilingPrice - floorPrice) / densityBins
array<float> risingVolume = array.new<float>(densityBins, 0.0)
array<float> fallingVolume = array.new<float>(densityBins, 0.0)
array<float> volumeAtPrice = array.new<float>(densityBins, 0.0)
for i = 0 to count - 1
float h = array.get(data.highPrice, i)
float l = array.get(data.lowPrice, i)
float w = array.get(data.weight, i)
bool up = array.get(data.rising, i)
int firstBin = math.max(0, math.min(densityBins - 1, int(math.floor((l - floorPrice) / step))))
int lastBin = math.max(0, math.min(densityBins - 1, int(math.floor((h - floorPrice) / step))))
for bin = firstBin to lastBin
float overlap = math.max(0.0, math.min(h, floorPrice + (bin + 1) * step) - math.max(l, floorPrice + bin * step))
float share = h > l ? w * overlap / (h - l) : w
if up
array.set(risingVolume, bin, array.get(risingVolume, bin) + share)
else
array.set(fallingVolume, bin, array.get(fallingVolume, bin) + share)
int peak = 0
float peakVolume = 0.0
float allocatedVolume = 0.0
for bin = 0 to densityBins - 1
float total = array.get(risingVolume, bin) + array.get(fallingVolume, bin)
array.set(volumeAtPrice, bin, total)
allocatedVolume += total
if total > peakVolume
peakVolume := total
peak := bin
int areaBottom = peak
int areaTop = peak
float acceptedVolume = peakVolume
float target = allocatedVolume * valueAreaPercent / 100.0
while acceptedVolume < target and (areaBottom > 0 or areaTop < densityBins - 1)
float below = areaBottom > 0 ? array.get(volumeAtPrice, areaBottom - 1) : -1.0
float above = areaTop < densityBins - 1 ? array.get(volumeAtPrice, areaTop + 1) : -1.0
if above >= below and areaTop < densityBins - 1
areaTop += 1
acceptedVolume += math.max(above, 0.0)
else
areaBottom -= 1
acceptedVolume += math.max(below, 0.0)
float control = floorPrice + (peak + 0.5) * step
float areaHigh = floorPrice + (areaTop + 1) * step
float areaLow = floorPrice + areaBottom * step
summary := ValueSummary.new(mean, control, areaHigh, areaLow, count)
// Shade broad sigma envelopes, then draw just the six boundaries.
if deviationVisible and channelFill and count > 1
for band = deviationCount to 1
array<chart.point> envelope = array.new<chart.point>()
for i = 0 to count - 1
float m = array.get(means, i)
if not na(m)
array.push(envelope, chart.point.from_time(array.get(data.stamp, i), m + band * array.get(spreads, i)))
for i = count - 1 to 0
float m = array.get(means, i)
if not na(m)
array.push(envelope, chart.point.from_time(array.get(data.stamp, i), m - band * array.get(spreads, i)))
if array.size(envelope) >= 4
array.push(paths, polyline.new(envelope, closed = true, xloc = xloc.bar_time, line_color = color.new(deviationColor, 100), fill_color = color.new(deviationColor, band == 1 ? 94 : 97)))
int subdivisions = deviationGrid == "Fine grid (0.25 sigma)" ? 4 : deviationGrid == "Dense grid (0.10 sigma)" ? 10 : 1
int gridExtent = deviationCount * subdivisions
// Rank only displayed deviation lines, excluding VWAP itself.
// This highlights the strongest available lines even if none sits
// exactly on the profile's highest-volume bin.
float strongestDeviationVolume = 0.0
if deviationVisible and peakVolume > 0
for candidate = -gridExtent to gridExtent
if candidate != 0
float endpoint = mean + float(candidate) / subdivisions * array.get(spreads, count - 1)
float sampled = f_endpointVolume(endpoint, floorPrice, ceilingPrice, step, volumeAtPrice)
strongestDeviationVolume := math.max(strongestDeviationVolume, sampled)
for grid = -gridExtent to gridExtent
float multiplier = float(grid) / subdivisions
bool mainLevel = math.abs(multiplier - math.round(multiplier)) < 0.001
if grid == 0 or deviationVisible
float endpoint = mean + multiplier * array.get(spreads, count - 1)
float lineVolume = peakVolume > 0 ? f_endpointVolume(endpoint, floorPrice, ceilingPrice, step, volumeAtPrice) : 0.0
float intensity = strongestDeviationVolume > 0 ? math.min(1.0, math.max(0.0, lineVolume / strongestDeviationVolume)) : 0.0
bool highestVolume = grid != 0 and strongestDeviationVolume > 0 and intensity >= 0.995
int transparency = int(math.round(deviationLowFade + (deviationFade - deviationLowFade) * intensity))
// Smooth brightness gradient, with no line-width boost.
color brightestTint = color.from_gradient(0.70, 0.0, 1.0, deviationHighColor, color.white)
color volumeTint = intensity <= 0.75 ? color.from_gradient(intensity, 0.0, 0.75, deviationColor, deviationHighColor) : color.from_gradient(intensity, 0.75, 1.0, deviationHighColor, brightestTint)
color curveTint = grid == 0 ? valueColor : color.new(volumeTint, transparency)
array<chart.point> trace = array.new<chart.point>()
for i = 0 to count - 1
float m = array.get(means, i)
if not na(m)
array.push(trace, chart.point.from_time(array.get(data.stamp, i), m + multiplier * array.get(spreads, i)))
if array.size(trace) > 1
if grid == 0
array.push(paths, polyline.new(trace, xloc = xloc.bar_time, line_color = curveTint, line_width = vwapStroke, line_style = line.style_solid))
else
// All deviations, including the highest-volume one,
// use exactly one pixel. No input can widen them.
array.push(paths, polyline.new(trace, xloc = xloc.bar_time, line_color = curveTint, line_width = 1, line_style = highestVolume ? line.style_solid : line.style_dotted))
if deviationVisible and deviationLabels and mainLevel and grid != 0
float levelPrice = mean + multiplier * array.get(spreads, count - 1)
string levelCaption = (multiplier > 0 ? "+" : "") + str.tostring(multiplier, "#") + " SD " + str.tostring(levelPrice, format.mintick)
f_tag(left, levelPrice, levelCaption, curveTint)
if densityVisible and peakVolume > 0
// Quiet full-width panel behind the accepted value area.
array.push(tiles, box.new(left = left, top = areaHigh, right = right, bottom = areaLow, bgcolor = color.new(controlColor, 95), border_color = color.new(controlColor, 90)))
for bin = 0 to densityBins - 1
float total = array.get(volumeAtPrice, bin)
if total > 0
int width = math.max(1, int(math.round(densityWidth * total / peakVolume)))
int rising = int(math.round(width * array.get(risingVolume, bin) / total))
int falling = width - rising
float bottom = floorPrice + (bin + 0.025) * step
float top = floorPrice + (bin + 0.975) * step
bool accepted = bin >= areaBottom and bin <= areaTop
int fade = int(math.round(85 - 75 * total / peakVolume))
color upTint = color.from_gradient(total, 0.0, peakVolume, profileUpLow, profileUpColor)
color dnTint = color.from_gradient(total, 0.0, peakVolume, profileDownLow, downColor)
if rising > 0
array.push(tiles, box.new(left = left, top = top, right = left + rising, bottom = bottom, bgcolor = color.new(upTint, fade), border_color = color.new(upTint, 100)))
if falling > 0
array.push(tiles, box.new(left = left + rising, top = top, right = left + width, bottom = bottom, bgcolor = color.new(dnTint, fade), border_color = color.new(dnTint, 100)))
f_horizontal(bar_index, right, mean, valueColor, line.style_solid)
f_horizontal(bar_index, right, control, controlColor, line.style_solid)
array.push(strokes, line.new(x1 = bar_index, y1 = areaHigh, x2 = left, y2 = areaHigh, extend = extend.left, color = color.new(controlColor, 25), style = line.style_dotted, width = 1))
array.push(strokes, line.new(x1 = bar_index, y1 = areaLow, x2 = left, y2 = areaLow, extend = extend.left, color = color.new(controlColor, 25), style = line.style_dotted, width = 1))
string heading = "PROFILE | " + f_tf(valueTF)
array.push(captions, label.new(x = left, y = ceilingPrice + (ceilingPrice - floorPrice) * 0.035, text = heading, style = label.style_label_lower_left, color = labelBackground, textcolor = valueColor, size = f_font(profileFont)))
if valueLabels
f_tag(left, mean, "VWAP " + str.tostring(mean, format.mintick), valueColor)
f_tag(left, control, "POC " + str.tostring(control, format.mintick), controlColor)
f_tag(left, areaHigh, "VAH " + str.tostring(areaHigh, format.mintick), controlColor)
f_tag(left, areaLow, "VAL " + str.tostring(areaLow, format.mintick), controlColor)
else
f_tag(left, high, "VALUE MAP / " + f_tf(valueTF) + " / No usable volume", valueColor)
else
f_tag(left, high, "VALUE MAP / " + f_tf(valueTF) + " / Waiting for source data", valueColor)
summary
// Draw meter text LAST as foreground labels. Unlike box text, these labels
// are not clipped to a narrow or shallow meter rectangle. The shared anchor
// keeps the bold first line directly above the normal two-line details.
f_meterText(int left, int right, float top, float bottom, string percentage, string details, color ink) =>
int centerIndex = left + int(math.round((right - left) * 0.5))
float centerPrice = (top + bottom) * 0.5
color textInk = color.new(ink, 0)
array.push(captions, label.new(x = centerIndex, y = centerPrice, text = percentage, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_down, color = na, textcolor = textInk, size = f_font(meterFont), textalign = text.align_center, text_formatting = text.format_bold))
array.push(captions, label.new(x = centerIndex, y = centerPrice, text = details, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_up, color = na, textcolor = textInk, size = f_font(meterFont), textalign = text.align_center, text_formatting = text.format_none))
0
// LAST-BAR COMPOSITION
if barstate.islast
f_clear()
// Draw each structure source once, combining duplicate layer switches.
bool activeZ1 = z1ob or z1gap
bool activeZ2 = z2ob or z2gap
bool activeZ3 = z3ob or z3gap
bool chartOB = zonesChart or (z1ob and f_equalTF(z1tf, timeframe.period)) or (z2ob and f_equalTF(z2tf, timeframe.period)) or (z3ob and f_equalTF(z3tf, timeframe.period))
bool chartGap = zonesChart or (z1gap and f_equalTF(z1tf, timeframe.period)) or (z2gap and f_equalTF(z2tf, timeframe.period)) or (z3gap and f_equalTF(z3tf, timeframe.period))
if chartOB or chartGap
f_zones(chartZones, timeframe.period, chartOB, chartGap)
if activeZ1 and not f_equalTF(z1tf, timeframe.period)
bool obs = z1ob or (z2ob and f_equalTF(z2tf, z1tf)) or (z3ob and f_equalTF(z3tf, z1tf))
bool gaps = z1gap or (z2gap and f_equalTF(z2tf, z1tf)) or (z3gap and f_equalTF(z3tf, z1tf))
f_zones(zones1, z1tf, obs, gaps)
if activeZ2 and not f_equalTF(z2tf, timeframe.period) and not (activeZ1 and f_equalTF(z2tf, z1tf))
f_zones(zones2, z2tf, z2ob or (z3ob and f_equalTF(z3tf, z2tf)), z2gap or (z3gap and f_equalTF(z3tf, z2tf)))
if activeZ3 and not f_equalTF(z3tf, timeframe.period) and not (activeZ1 and f_equalTF(z3tf, z1tf)) and not (activeZ2 and f_equalTF(z3tf, z2tf))
f_zones(zones3, z3tf, z3ob, z3gap)
array<LevelView> pool = array.new<LevelView>()
f_levels(chartLevels, timeframe.period, pool)
if needQ1 and not f_equalTF(q1tf, timeframe.period)
f_levels(levels1, q1tf, pool)
if needQ2 and not f_equalTF(q2tf, timeframe.period) and not (needQ1 and f_equalTF(q2tf, q1tf))
f_levels(levels2, q2tf, pool)
if needQ3 and not f_equalTF(q3tf, timeframe.period) and not (needQ1 and f_equalTF(q3tf, q1tf)) and not (needQ2 and f_equalTF(q3tf, q2tf))
f_levels(levels3, q3tf, pool)
// Visible liquidity labels are drawn from the visible-only pool.
if array.size(pool) > 0
for level in pool
if liquidityLines and f_visibleLiquidity(level.tf)
color tint = level.upper ? bslColor : sslColor
string captionText = (level.upper ? "BSL" : "SSL") + " | " + f_tf(level.tf) + " " + str.tostring(level.price, format.mintick)
array.push(strokes, line.new(x1 = level.stamp, y1 = level.price, x2 = time_close, y2 = level.price, xloc = xloc.bar_time, color = tint, width = liquidityStroke, style = line.style_dashed))
array.push(captions, label.new(x = time_close, y = level.price, text = captionText, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(labelBackground, 10), textcolor = tint, size = f_font(liquidityFont)))
array<LevelView> meterCandidates = array.new<LevelView>()
if meterVisible
if meterMode == "All enabled liquidity timeframes"
if array.size(pool) > 0
for q in pool
if f_visibleLiquidity(q.tf)
array.push(meterCandidates, q)
0
else if meterMode == "Chart timeframe only"
f_meterLevels(chartLevels, timeframe.period, meterCandidates)
else
if meterSource1On
f_addMeterPair(meterUpper1, meterLower1, meterSeconds1, meterTime1, meterSource1TF, meterCandidates)
if meterSource2On
f_addMeterPair(meterUpper2, meterLower2, meterSeconds2, meterTime2, meterSource2TF, meterCandidates)
if meterSource3On
f_addMeterPair(meterUpper3, meterLower3, meterSeconds3, meterTime3, meterSource3TF, meterCandidates)
// Fresh NA values on every update prevent stale levels from surviving a
// source change, sweep or missing-side condition.
float upper = na
float lower = na
string upperTF = ""
string lowerTF = ""
if array.size(meterCandidates) > 0
for level in meterCandidates
if f_meterSource(level.tf)
if level.upper and level.price > close and (na(upper) or level.price < upper)
upper := level.price
upperTF := f_tf(level.tf)
if not level.upper and level.price < close and (na(lower) or level.price > lower)
lower := level.price
lowerTF := f_tf(level.tf)
// A source mismatch clears the entire selected range. Missing sides are
// always left NA; visible daily or chart levels are never used as substitutes.
if selectedMeterMode and not selectedSourcesVerified
upper := na
lower := na
int meterLeft = bar_index + meterGap
int meterRight = meterLeft + meterProjection
bool rangeReady = not na(upper) and not na(lower) and upper > lower
string rangeStatus = "Meter off"
if meterVisible
if rangeReady
array.push(tiles, box.new(left = meterLeft, top = upper, right = meterRight, bottom = close, bgcolor = meterUpper, border_color = meterUpperEdge, border_width = meterStroke))
array.push(tiles, box.new(left = meterLeft, top = close, right = meterRight, bottom = lower, bgcolor = meterLower, border_color = meterLowerEdge, border_width = meterStroke))
f_horizontal(meterLeft, meterRight, close, color.new(meterInk, 35), line.style_solid)
rangeStatus := upperTF + " BSL / " + lowerTF + " SSL"
else
bool noneSelected = meterMode == "Selected timeframes" and not meterSource1On and not meterSource2On and not meterSource3On
rangeStatus := noneSelected ? "Select a meter source" : na(upper) and na(lower) ? "Waiting for BSL + SSL" : na(upper) ? "Waiting for BSL above price" : "Waiting for SSL below price"
if selectedMeterMode and not selectedSourcesVerified
rangeStatus := "Waiting for verified selected source data"
rangeStatus := f_meterSourcesLabel() + " | " + rangeStatus
array.push(captions, label.new(x = bar_index + 1, y = close, text = rangeStatus, style = label.style_label_left, color = labelBackground, textcolor = meterInk, size = f_font(meterFont)))
if meterVisible and meterSourceCaption
string sourceCaption = "METER v1.22 | " + (automaticTF ? "AUTO | " : "MANUAL | ") + f_meterSourcesLabel()
if selectedMeterMode
sourceCaption += selectedSourcesVerified ? " | Verified" : " | Waiting"
float captionPrice = rangeReady ? upper + (upper - lower) * 0.025 : high
array.push(captions, label.new(x = meterLeft, y = captionPrice, text = sourceCaption, style = label.style_label_lower_left, color = labelBackground, textcolor = selectedMeterMode and not selectedSourcesVerified ? meterLowerEdge : valueColor, size = size.tiny))
int left = bar_index + (meterVisible ? meterGap + meterProjection : 0) + densityGap
int right = left + densityWidth
f_value(valueData, left, right)
// Foreground composition: no liquidity/profile label is drawn after this.
if meterVisible and rangeReady
float upperShare = math.round((upper - close) / (upper - lower) * 1000.0) / 10.0
float lowerShare = 100.0 - upperShare
string upDetails = "BSL | " + upperTF + "\n" + str.tostring(upper, format.mintick)
string dnDetails = "SSL | " + lowerTF + "\n" + str.tostring(lower, format.mintick)
color upperInk = meterMatchText ? meterUpperEdge : meterInk
color lowerInk = meterMatchText ? meterLowerEdge : meterInk
f_meterText(meterLeft, meterRight, upper, close, str.tostring(upperShare, "0.0") + "%", upDetails, upperInk)
f_meterText(meterLeft, meterRight, close, lower, str.tostring(lowerShare, "0.0") + "%", dnDetails, lowerInk)