Regression Market Profile [BOSWaves]Regression Market Profile - Curve-Following Distribution Analysis with TPO Letters, Heatmap, and Profile Modes
Overview
Regression Market Profile is a regression-anchored market profile system that maps the distribution of price activity relative to a best-fit regression curve rather than within fixed horizontal price boundaries, where row assignment, POC identification, value area construction, and interior visualization are all derived from how far actual price deviated from the regression prediction on each bar rather than from absolute price levels.
Instead of constructing a profile against a static price range, this system fits either a linear or polynomial regression to recent price history and measures each bar's deviation from the fitted curve, distributing that activity into horizontal rows centered on the regression line. As the curve bends and trends through price space, the entire profile follows it, revealing where price consistently clustered above or below the regression prediction and identifying the deviation offset with the highest time-at-price concentration as a dynamic POC that moves with the trend rather than anchoring to a fixed session boundary.
This creates a market profile framework that adapts to the prevailing directional structure of price rather than imposing a fixed container. The interior visualization communicates distribution in three configurable modes: a heatmap that reveals how the distribution migrated across time columns, a profile extending from the right edge showing the cumulative distribution shape, and TPO letter boxes that follow the regression curve encoding chronological time progression through gradient coloring. Standard deviation bounds, value area boundaries, and a dual-line POC glow all follow the curve simultaneously, providing a complete structural reference system that moves with the trend rather than remaining static.
Price is therefore evaluated not for its absolute level but for its position relative to the regression expectation, with the profile revealing which deviation offsets attracted the most sustained activity throughout the regression window.
Conceptual Framework
Regression Market Profile is founded on the principle that meaningful participation clustering should be measured relative to the expected price path defined by recent price history rather than within arbitrary time or price containers that carry no relationship to the actual directional structure of the market.
Traditional market profile approaches anchor distributions to calendar sessions or fixed price ranges, producing profiles that reflect where price traded within a time box rather than where it clustered relative to its own trend. This framework replaces fixed-container profiling with regression-relative distribution measurement, where each bar's contribution to the profile is determined by how far actual price deviated from the best-fit curve rather than where it sat in absolute price space. The profile therefore reveals the structural tendencies of price relative to its own trend dynamics rather than its behavior within an externally imposed boundary.
Three core principles guide the design:
Profile distribution should be measured as deviation from a fitted regression curve rather than as absolute price position, ensuring the profile captures participation clustering relative to trend expectation rather than within arbitrary price boundaries.
The interior visualization mode should be configurable between temporal migration analysis, cumulative distribution shape, and chronological letter encoding, allowing the same structural data to be interpreted through different analytical lenses depending on the trader's workflow.
All structural reference elements including POC, value area, standard deviation bounds, and centerline should follow the regression curve continuously rather than anchoring to static horizontal levels, maintaining relevance to the current trend structure throughout the regression window.
This shifts market profile analysis from session-bounded horizontal distribution tracking into regression-relative participation mapping where the profile reveals structural clustering tendencies within the context of the prevailing trend curvature.
Theoretical Foundation
The indicator combines matrix-based polynomial and linear regression fitting to recent HL2 price data, rolling standard deviation for channel scaling and SD bound construction, deviation-based row assignment for distribution building, POC identification through maximum row count, value area expansion from POC outward, and three distinct interior visualization systems that present the same distribution data through different geometric representations following the regression curve.
The regression is computed using ordinary least squares matrix operations: the design matrix is constructed with powers of bar index up to the polynomial degree, transposed and multiplied to form the normal equations, inverted, and multiplied by the price vector to produce regression coefficients, which are then applied to generate the full prediction array. Standard deviation of the HL2 series over the regression window provides the channel scaling unit and drives the SD bound envelopes. Row assignment divides the channel height by the number of rows and places each bar's deviation from its predicted value into the corresponding row bin. POC and value area use the same maximum-count and outward-expansion logic as conventional market profile, applied to the curved row counts.
Four internal systems operate in tandem:
Regression Engine : Computes linear or polynomial best-fit predictions for all bars in the lookback window using matrix least squares, providing the curved baseline that all distribution measurements, row positioning, and visual elements follow.
Distribution Construction System : Measures each bar's deviation from its regression prediction, assigns it to a horizontal row within the standard deviation channel, accumulates row counts across the full window, and derives POC and value area from the resulting distribution.
Interior Visualization Engine : Renders the distribution data inside the channel in one of three modes: curved polygon cells per time column normalized independently for heatmap temporal migration display, curved profile bars extending from the right edge scaled to global row counts for distribution shape display, or TPO letter boxes positioned at the regression-relative row boundaries with gradient chronological coloring for time period encoding.
Structural Reference System : Draws the dual-line POC glow following the regression curve at the POC row offset, value area boundary polylines at the VA top and bottom offsets, standard deviation envelope polylines at one through three sigma above and below the curve, and a dashed centerline following the regression prediction directly.
This design ensures the distribution and all structural reference elements continuously adapt to the regression curve while the three interior modes provide complementary analytical perspectives on the same underlying participation data.
How It Works
Regression Market Profile evaluates price through a sequence of regression-aware distribution and visualization processes:
Regression Calculation : On the last bar, the design matrix is constructed from bar index values raised to polynomial powers up to the configured degree. Ordinary least squares solves for the coefficient vector and applies it to produce a prediction array covering all bars in the lookback window.
Channel Scaling : The standard deviation of HL2 over the regression window multiplied by the configured channel width defines the maximum deviation distance, establishing the vertical extent of the distribution channel centered on the regression curve.
Row Assignment and Count Accumulation : Each bar's actual HL2 is compared to its regression prediction and the deviation is assigned to a horizontal row bin derived from the channel height divided by the row count. Row counts accumulate across all bars in the window.
POC Identification : The row with the maximum accumulated count is identified as the Point of Control, representing the deviation offset from the regression curve where price spent the most time during the lookback window.
Value Area Construction : Starting from the POC row, adjacent rows are added in order of greater count until the cumulative total reaches the configured value area percentage of all bar counts, defining the high-activity zone around the POC.
Interior Rendering - Heatmap Mode : The lookback window is divided into time columns and each column builds its own per-row counts, normalized independently so each column's internal distribution is shown on its own scale. Curved polygon cells are rendered for each occupied cell with hot-cold gradient coloring by normalized density.
Interior Rendering - Profile Mode : Each row's global count is expressed as a fraction of the maximum row count and scaled to a configurable proportion of the total regression length. Curved polygon bars extend leftward from the right edge by the scaled bar length, forming a profile shape that follows the regression curve.
Interior Rendering - Letters Mode : Each bar is assigned a sequential alphabetical letter based on its time period index relative to the TPO timeframe. Letters are accumulated per row and rendered as individual boxes positioned at the regression-relative row boundaries, with gradient coloring that progresses from cold to hot as the letter index advances chronologically.
POC Polyline Rendering : A wide low-opacity glow polyline and a thinner full-opacity core polyline follow the regression curve at the POC deviation offset, providing a continuously curving reference for the maximum activity level throughout the window.
Value Area and SD Bound Rendering : Dotted polylines follow the regression curve at the value area high and low offsets and at one, two, and three standard deviation distances above and below the curve, with opacity increasing with distance from the curve.
Together, these elements form a continuously recomputed regression-relative distribution system where every visual element adapts to the current curve shape and all three interior modes present the same participation data from different analytical perspectives.
Interpretation
Regression Market Profile should be interpreted as a regression-relative structural distribution system where clustering above or below the fitted curve reveals directional bias tendencies and participation concentration within the prevailing trend:
Regression Centerline : The dashed curve following the best-fit prediction represents the trend's expected price path. Price consistently above it indicates sustained positive deviation bias; price consistently below indicates sustained negative deviation bias.
POC Line : The dual glow and core polyline following the curve at the maximum activity offset marks the deviation level where price spent the most time relative to the regression prediction, representing the most accepted deviation from expected trend behavior during the window.
Value Area Boundaries : Dotted polylines above and below the POC line mark the deviation range containing the configured percentage of total activity, identifying the zone of concentrated acceptance around the POC.
Standard Deviation Bounds : One, two, and three sigma dotted envelopes around the curve mark statistically extreme deviation distances, with progressively greater opacity indicating greater statistical rarity of price reaching those offsets.
Heatmap Mode : Each time column displays its own normalized distribution, with hot colors indicating the most active deviation level within that column and cold colors indicating less active levels. Reading across columns from left to right reveals how the distribution migrated as the window progressed.
Profile Mode : Curved bars extending from the right edge show the cumulative distribution shape across the full window, with longer bars indicating deviation levels with greater total activity and hot coloring marking the densest regions.
Letters Mode : Sequential alphabet letters fill the channel rows at their regression-relative positions, with gradient coloring from cold early-window letters to hot late-window letters encoding chronological time progression. Single-letter rows indicate price visited that deviation level in only one time period, functioning as regression-relative single prints.
POC Offset Interpretation : A POC positioned above the regression centerline indicates that price has consistently traded at a positive deviation from expectations, reflecting bullish structural bias within the window. A POC below the centerline indicates bearish structural bias.
POC offset direction, value area extent, distribution shape across modes, and SD bound interactions collectively provide more structural context than any element in isolation.
Signal Logic & Visual Cues
Regression Market Profile does not generate discrete buy or sell signals but provides continuous structural reference through distribution-derived levels:
POC Reaction : Price returning to the deviation level corresponding to the POC polyline encounters the most accepted level within the regression window, frequently acting as magnetic reference for reversion or continuation assessment.
Value Area Boundary Interaction : Price moving outside the value area boundaries enters statistically less accepted deviation territory, suggesting either trend extension beyond typical participation or the beginning of structural repositioning relative to the regression curve.
Standard deviation bound interactions provide additional reference for statistically extreme deviation events that historically attract mean reversion activity back toward the regression curve and POC.
Strategy Integration
Regression Market Profile fits within regression-informed structural analysis and distribution-based approaches:
POC Reversion Framing : Use the POC polyline as a dynamic reversion target when price has extended to the outer standard deviation bounds, with the curved POC providing a continuously updating level that reflects the trend's accepted center rather than a static price.
Value Area Acceptance Testing : Monitor whether price is trading within or outside the value area boundaries to assess whether current price activity represents accepted trend behavior or extended deviation warranting mean reversion consideration.
Heatmap Migration Analysis : Use temporal migration visible in heatmap mode to assess whether distribution is shifting toward positive or negative deviation over the course of the window, providing directional bias evidence from the distribution's evolution rather than from price alone.
Profile Shape Assessment : Use profile mode to assess distribution symmetry around the regression curve. A distribution skewed above the centerline suggests persistent positive bias; skew below suggests persistent negative bias. A symmetric bell shape suggests balanced acceptance around the regression expectation.
Single Print Monitoring in Letters Mode : Treat single-letter rows in letters mode as regression-relative thin participation levels that price is likely to revisit, analogous to single prints in conventional market profile.
Regression Mode Selection : Use Linear mode for markets trending in a consistent direction where a straight best-fit line accurately represents the price path. Use Polynomial mode for markets with visible curvature in their trend structure where the quadratic bend better fits the actual price trajectory.
Technical Implementation Details
Regression Engine : Matrix OLS computation using design matrix construction, normal equation formation, matrix inversion, and coefficient application for linear or polynomial curve fitting to HL2
Channel Construction : Rolling standard deviation-scaled channel with configurable width multiplier providing deviation row boundaries
Distribution System : Deviation-based row assignment with global count accumulation, POC maximum identification, and outward value area expansion
Heatmap Engine : Per-column count normalization with curved polygon cell rendering using hot-cold gradient by normalized density
Profile Engine : Global count-scaled curved bar polylines extending from the right edge by proportional bar length
Letters Engine : TPO timeframe-ratio letter assignment with per-row accumulation and gradient chronological box rendering at regression-relative boundaries
Structural System : Dual-line POC glow, dotted VA boundary polylines, three-sigma dotted SD envelopes, and dashed centerline all following the regression curve via chart.point arrays
Performance Profile : All rendering triggered only on the last bar with full object cleanup and rebuild on each update, polyline-based curved geometry for all structural elements
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Intraday regression profiling with shorter length and tighter channel for fast-adapting curve that captures intraday trend structure
15 - 60 min : Session-level distribution analysis with balanced length and moderate channel width for meaningful participation mapping across typical session trends
4H - Daily : Swing-level regression profiling with longer lookback and polynomial mode for curve-following distribution across multi-session directional structures
Suggested Baseline Configuration:
Length : 200
Mode : Polynomial
Channel Width (SD×) : 3.0
Inner Display : Letters
Rows : 12
TPO Timeframe : 30
Value Area % : 70
Show POC : Enabled
Show Value Area : Enabled
Show SD Bounds : Enabled
These suggested parameters should be used as a baseline; their effectiveness depends on the instrument's trend characteristics, volatility profile, and preferred distribution granularity, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Curve fits too loosely to recent price : Decrease Length to shorten the regression window, producing a curve that adapts more quickly to recent price structure. Switch to Polynomial mode if the trend has visible curvature that a linear fit cannot capture.
Curve too reactive to short-term price movement : Increase Length to smooth the regression across more history, producing a more stable curve that reflects longer-term directional structure and reduces sensitivity to recent fluctuations.
Channel too narrow or wide : Adjust Channel Width to scale the standard deviation multiplier, expanding the channel to capture more price activity within the distribution or contracting it to focus on the core deviation range.
Distribution too coarse or granular : Adjust Rows to increase or decrease the number of horizontal price bins, calibrating vertical resolution to the channel height and the instrument's typical deviation behavior within the regression window.
Heatmap columns too few or many : Adjust Heatmap Columns to control the time resolution of the migration display, with fewer columns showing broader temporal patterns and more columns revealing finer migration detail at the cost of visual density.
Profile bars too short or long : Adjust Profile Width to scale the maximum bar length as a fraction of the regression window, calibrating how far the longest bars extend from the right edge relative to the available chart space.
Too few or many letters per row : Adjust TPO Timeframe to change the time period each letter represents. Higher timeframes produce fewer, broader letters; lower timeframes produce more letters with finer time resolution.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
Trending markets where the regression curve accurately represents the directional price path and the distribution reveals consistent deviation bias that reflects genuine structural tendencies
Instruments with smooth, curving price trends where polynomial mode produces a better-fitting curve than a straight line and the distribution around the curve is more meaningful than a session-anchored profile
Market profile-informed approaches that benefit from a continuously adapting POC and value area that follow the trend rather than anchoring to fixed session boundaries
Distribution analysis workflows where heatmap temporal migration or profile shape provides directional bias evidence from participation patterns rather than from price indicators alone
Reduced Effectiveness:
Choppy, directionless markets where the regression curve has no clear shape and the distribution is uniform across rows, reducing the interpretive value of POC location and value area extent
Markets with frequent sharp reversals where the regression window spans multiple opposing structural moves, producing a curve that represents none of them accurately and a distribution without meaningful clustering
Extremely short lookback windows where the matrix regression calculation is underdetermined or the distribution contains too few bars per row to produce statistically meaningful counts
Instruments with discontinuous price action including frequent gaps where the HL2 series used for regression produces curves that follow gap-distorted price paths rather than genuine trend structures
Integration Guidelines
Confluence : Combine with BOSWaves structural tools, momentum oscillators, or volume analysis to validate POC and value area interactions with broader analytical context before acting on regression-relative distribution levels
POC Offset Bias : Monitor the position of the POC relative to the centerline across successive sessions as a structural bias indicator. A POC consistently above the centerline across multiple regression windows suggests a persistent positive deviation tendency in the current trend phase.
Mode Selection by Objective : Use Letters mode for structural time-at-price analysis analogous to conventional market profile. Use Heatmap mode to assess how distribution shifted over the regression period. Use Profile mode to quickly assess distribution shape and skew relative to the centerline.
Regression Mode Discipline : Commit to a regression mode based on the instrument's observed trend curvature rather than switching between modes reactively. Polynomial mode adds a second degree of freedom that can overfit short-term noise if the lookback window is too short.
Window Length Stability : Maintain a consistent regression length when using the POC and value area as ongoing structural references. Changing the length significantly shifts the curve and redistributes the profile, making successive POC comparisons unreliable.
Disclaimer
Regression Market Profile is a professional-grade regression-relative distribution and market profile analysis tool. It uses ordinary least squares curve fitting with deviation-based participation mapping but does not predict future price movements. Results depend on market conditions, instrument trend characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates order flow context, structural analysis, and comprehensive risk management. Индикатор

True Time Price Profile - Hybrid Dynamic Bins[ALT_analyst]True Time Price Profile - Hybrid Dynamic Bins
◆ NOTICE / DISCLAIMER
This architecture is NOT a standard Volume Profile (VP) or a conventional Time Price Opportunity (TPO) indicator.
It is a highly advanced, multi-variable structural density engine.
It was specifically designed to mathematically extract institutional defense lines and localized price absorption in environments lacking reliable tick volume (e.g., Forex, CFD, Indices),
functioning as a rigorous technical benchmark for supply/demand extraction.
◆ EXECUTIVE SUMMARY
This script is deployed as a Proof of Concept (PoC) to demonstrate the integration of price absorption, time-based variance,
and strict pro-rata energy distribution within a localized UI rendering environment.
By discarding standard aggregation methods, this open-source architecture isolates the true "quality" of price stagnation,
exposing anomalous market states where large capital defends specific price buckets.
◆ ARCHITECTURE & QUANTITATIVE LOGIC
Standard profiles often struggle because they cannot distinguish between a "rapid vacuum passing" and a "defended consolidation."
This engine utilizes three proprietary layers to resolve this logic gap:
Pro-Rata Energy Distribution Engine
To prevent large-range bars (e.g., sudden momentum spikes) from artificially inflating the profile score across empty price vacuums, this script enforces a strict pro-rata allocation matrix.
Let N_bins be the total number of price bins a single bar intersects.
The assigned value for each specific bin is calculated as:
Apportioned Value = Base Value / N_bins
This completely neutralizes vacuum zones, correctly assigning mass only to true areas of conflict.
Velocity & Acceleration (Absorption) Evaluator
Instead of counting volume, the script measures the deceleration of price action.
It compares the high-low range of the current bar (v_curr) against the previous bar (v_prev). A negative acceleration (accel < 0) indicates kinetic energy is being absorbed by limit orders.
This absolute delta is extracted as the base absorption value (|a|).
Time Variance Logic (Market Memory)
A price level tested multiple times over a prolonged period holds significantly more structural integrity than a level tested only once.
The engine applies the statistical variance of the normalized time index (t) to scale the localized importance of a bin:
Variance (σ²) = (Sum of t² / n) - (Average t)²
The final Hybrid Score is the integration of absorbed energy scaled by the logarithmic variance:
Score = Sum( |a| * ln(1 + σ²) )
◆ PRACTICAL APPLICATION: HOW TO TRADE WITH THIS ENGINE
Instead of blindly treating every high-volume node as support/resistance, utilize this engine to identify Structural Friction:
Locating Hidden Institutional Limits:
Bins with exceptionally high Hybrid Scores often act as heavy liquidity pools.
Price action will typically stall or reverse sharply upon re-entering these zones.
Breakout Validation:
If price breaks out of a Value Area (VA) without generating new high-score bins, it indicates a lack of limit-order resistance (a vacuum).
These moves are prone to rapid continuation or swift mean-reversion sweeps.
Cross-Session Node Alignment (Breakout Threshold):
By anchoring the profile to short, sequential sessions, observe if high-scoring nodes (POCs) align horizontally at the same price level across multiple independent profiles.
This structural anomaly signifies a massive, sustained accumulation of limit orders.
A decisive price breach of this specific alignment typically triggers a high-probability volatility breakout, as the defended liquidity pool is rapidly consumed.
◆ SYSTEM CAPABILITIES AND LIMITATIONS
Visual Synthesis of Invisible Nodes:
Resolves precise support/resistance vectors purely from price action kinetics, independent of broker volume feeds.
Dynamic Resolution Scaling:
The bin size is strictly tethered to the Average True Range (ATR), ensuring the profile grid automatically calibrates to the underlying asset's volatility regime.
Limitations & Warnings:
TradingView enforces a strict cap of 500 max boxes/lines per indicator. To prevent script execution limits or array errors, the maximum lookback and bin count are dynamically capped.
Furthermore, if the scaled ATR drops to absolute zero, the geometric grid cannot initialize.
◆ INPUT PARAMETERS REFERENCE
Live Update Frequency:
Toggle between 'Update on Every Tick' and 'Update on Bar Close'.
CRITICAL WARNING: Using tick updates combined with multiple MTF arrays on a fast timeframe will cause localized UI lag. Use 'Bar Close' as a CPU saver.
Profile Calculation Mode:
Select 'Classic' for standard aggregation, or 'Hybrid' to engage the Absorption + Variance matrix (The core edge of this tool).
Grid Step Multiplier:
Lower values increase vertical resolution.
Warning: Values below 0.05 on high-volatility assets may trigger the 500-box rendering limit.
Show Debug Data Table:
Projects a live array matrix on the bottom right, displaying precise Price, Count, Absorption, Variance, and Hybrid Scores for absolute algorithmic transparency.
Индикатор

TPO Auction & Value ProfileTPO Auction & Value Profile
Overview
A complete intraday auction-profile engine. For each session it counts how much time price spent at each level — the Time-Price-Opportunity (TPO) distribution — and reads off what an auction cares about: Point of Control (most-traded price), Value Area (central band holding ~70% of activity, with VAH/VAL edges), Initial Balance (the open's framing range), excess tails vs poor unfinished extremes, single prints, and naked POCs (prior fair-value magnets price hasn't revisited). It then layers what a profile alone can't show: the volume POC beside the time POC, an optional buy/sell delta tint per level, prior-day value projected forward, a rolling composite (multi-day) value, and a decision dashboard that turns it all into one at-a-glance verdict. Sessions auto-detect from the instrument's own trading day — no setup.
What makes it different — why these pieces are ONE engine (mashup rationale)
This is the part TradingView asks publishers to justify, so here it is explicitly. Every component answers a different question about the same auction, and each is only meaningful in the presence of the others:
The TPO distribution is the substrate (where did the auction spend time?). POC + Value Area summarise agreed value; Initial Balance frames the open; excess / poor / single prints read the auction's completeness at the edges; naked POCs carry unfinished value forward.
The volume POC is laid over the time POC because time and volume don't always agree on fair value — their divergence is information a pure TPO profile cannot show.
The delta-per-level tint adds who was active (buyers vs sellers) at each price — the order-flow dimension behind the time distribution, reconstructed from lower-timeframe bars.
Prior-day and composite (multi-day) value place today in context: initiative vs responsive, value migration (higher/lower/overlapping) and failed auctions are only definable relative to those references.
The dashboard fuses location, migration, range extension, open type, day type and the rotational TPO count into one bias — the synthesis a stack of separate indicators leaves you to do by eye.
Split apart, each piece is a fragment; together they describe one thing — the shape, location and completeness of the auction. That interdependence is why it's a single engine, not a bundle.
What this adds over a standard TPO / Market Profile script
Most profile scripts stop at drawing the TPO letters/rows, POC, value area and IB. This engine goes well beyond that, and these additions are what make it original:
Auto-session that works where others break. New-session detection keys off a calendar-day change in the instrument's own timezone, so it resets correctly on feeds that have no out-of-session bars (NSE index futures only print 09:15–15:30) — where edge-detection-based scripts silently fail and pile every day into one profile. Zero setup, adapts to any market.
Time POC vs Volume POC divergence. It overlays the volume point of control on the time POC and flags when they disagree — a tradeable tell a time-only profile can't surface.
Delta-per-level (order flow at price). An optional row-colour mode tints each level by net buy/sell delta, reconstructed from lower-timeframe signed volume — showing who was active at each price, not just how long. Rare on TPO tools.
Excess vs poor, done rigorously. A single-print run of ≥ N rows at an extreme is flagged excess (strong rejection / completed auction); a flat multi-TPO extreme is flagged poor (unfinished). Most scripts conflate the two; here they're distinct and coloured differently.
Prior-day value, projected forward. Yesterday's POC/VAH/VAL extend into today as labelled reference lines — the levels every auction trader marks pre-session.
Rolling composite (multi-day) value. A composite POC/VAH/VAL across the last N sessions shows the longer-timeframe balance single-day profiles miss.
Fused decision dashboard. Open type (drive / reject-reverse / auction), day type (balanced … trend), value migration vs prior, range extension vs IB, the rotational TPO count, failed-auction state and a colour-coded bias headline — turning raw structure into one at-a-glance verdict, theme-adaptive to your chart.
Failed-auction detection + alerts. Fires when price breaks prior-day value and closes back inside — the high-probability fade auction theory points to.
Split-profile time colouring. Rows tinted by the bracket that first reached them, exposing migration and double distributions at a glance.
How it works
Session: Auto groups each profile by the instrument's trading day in its native timezone (first/last bars = detected open/close); Manual pins a window. Rows: price is binned (tick multiple, ATR fraction, or fixed step); each bar adds a TPO + its volume + its delta to every row it covered; rows can be coloured by time bracket (split profile), delta, or value area. Value Area grows from the POC to the richer neighbour until the chosen % is enclosed. Structure: a single-print run ≥ N rows at an extreme is excess (strong rejection); a flat multi-TPO extreme is poor (unfinished); TPO count sums TPOs above vs below POC (singles excluded). Analytics: open type, day type, value migration, range extension, failed auctions. Developing vs completed: the live session updates on the forming bar and settles on close; finished sessions are drawn once; naked POCs extend until filled.
How to use
Lead with the dashboard's bias headline, then confirm with structure: value-area edges are acceptance/rejection levels; POC, volume POC and naked POCs are magnets; excess marks completed auctions, poor extremes mark unfinished business price tends to revisit; prior-day and composite value say where today sits; a failed auction back inside value is a high-odds fade. Context for your decisions — not a standalone trigger.
Originality
The auction concepts are public (credited below); the original work is the assembly and the code — auto-session detection that works on instruments with no out-of-session bars, the time-vs-volume POC divergence read, an original delta-per-level reconstruction, the rolling composite, the excess-vs-poor logic, and the fused decision dashboard. No third-party code is reused.
Concept credit
The auction / Market-Profile framework (time-price opportunities, value area, point of control, initial balance, excess, single prints, day/open types) originates with J. Peter Steidlmayer at the Chicago Board of Trade and was developed for traders by James Dalton. Volume-at-price is standard volume-profile practice. Buy/sell classification uses the tick rule (Lee & Ready, 1991).
Honesty / limitations
A TPO profile measures time at price, not size; the volume POC and delta add the volume view, but the delta is a tick-rule estimate from lower-timeframe bars, not true bid/ask data. The composite is a rolling window that refreshes periodically, not a fixed calendar range. Open type and day type are transparent heuristics. Row size changes the picture. Descriptive auction context — it does not predict price.
Disclaimer
Research / educational only. NOT financial advice; no guarantee of profitability. Indicators describe past behaviour. Trading carries risk of loss. Test out-of-sample. The author accepts no liability. Индикатор

Value-Distribution OscillatorValue-Distribution Oscillator
Overview
A volume-by-price value map expressed as a bounded pane oscillator. It rolls a decaying volume distribution of recent trade, finds the Point of Control (most-traded price) and the Value Area, then plots where price sits inside that value structure on a fixed −50 / +50 scale: 0 = at the POC (fair value), ±25 = the value-area edges (VAH / VAL), ±50 = stretched beyond the developed range. It is a study of acceptance and location — not a directional signal.
Why these parts are ONE tool (mashup rationale)
A volume profile is an overlay that shows where value is; it can't give you, as a single number, how far price has travelled from value or whether that travel reverts. This chains: a decaying distribution builds the map → a position transform turns price into one bounded location reading → a fade flag fires only when price is stretched into the tails and turning back → a calibration harness tests whether stretched-and-reverting readings actually return toward the POC on your instrument. Remove a part and the chain breaks: a profile is just a picture, the transform alone is just a number, the fade alone is an untested claim.
How it works
Each confirmed bar's volume is distributed across a price grid (body weighted heavier than wicks) and the whole grid decays geometrically, so the map tracks recent trade and re-anchors when price leaves its range. The POC is the heaviest level; the Value Area grows outward from the POC to the chosen volume share; the transform maps price piecewise-linearly (POC→0, VAH/VAL→±25, extremes→±50). The harness logs each stretched fade and checks a ≥ k×ATR move back toward the POC a fixed horizon later.
How to use
Read location: near 0 = fair value; the ±25 band = the edge of value; beyond ±40 = stretched into the tails, where reversion setups have context and breakouts that hold signal value migration. Then read the Edge row — fades in the tails only earn their keep if they beat the base rate. Context, never a standalone trigger.
Originality
The POC / Value-Area concept is public (credited below); the original work is the assembly — a decaying-grid distribution, the price-into-value position transform that turns a profile into a series, and the forward base-rate calibration. It's the pane-oscillator counterpart to a volume profile, not a re-skin of one.
Concept credit
Market / Volume Profile, Point of Control and Value-Area framing — J. Peter Steidlmayer and the CBOT Market Profile tradition; value-area / acceptance reading developed further by practitioners such as James Dalton. Implementation, transform and harness are this script's own.
Honesty / limitations
The distribution uses bar ranges, not exchange price-by-price prints or tick data — a probabilistic approximation. The grid decays, so it's a recent-trade view, not a session-anchored profile. Edge figures are in-sample, close-to-close, overlapping windows, no costs — descriptive context, not a backtest. Nothing here predicts direction.
Disclaimer
Research / educational only. NOT financial advice; no guarantee of profitability. Indicators describe past behaviour. Trading carries risk of loss. Test out-of-sample. The author accepts no liability. Индикатор

Footprint X-Ray [BOSWaves]Footprint X-Ray - Intrabar Delta Decomposition with Stacked Imbalance, Absorption, and Unfinished Business Detection
Overview
Footprint X-Ray is an intrabar order flow decomposition system that reconstructs the buy and sell volume distribution within each bar by pulling lower timeframe data and mapping participation to price rows, where row coloring, POC identification, stacked imbalance detection, and signal generation are driven by actual delta ratios at each price level rather than bar-level approximations or close-position estimates.
Instead of treating each bar as a single undifferentiated unit of buying or selling pressure, the indicator divides each bar's price range into rows sized relative to ATR, assigns lower timeframe bar volume to each row based on price overlap, and derives a per-row delta ratio that reflects whether buying or selling dominated at each specific price level within the bar. This creates a full participation map inside every candle showing not just what direction the bar moved but where within the bar each side was in control.
This creates an order flow framework that reveals the internal structure of price action invisible on a standard candlestick chart. The footprint cells expose per-level delta composition, the POC identifies the price row with the greatest participation, stacked imbalances highlight consecutive rows with dominant one-sided flow indicating aggressive institutional activity, absorption signals detect when extreme rows show opposing flow against the bar direction, and unfinished business zones project forward from bars where one side was entirely absent at the extreme, marking locations where price is statistically likely to return to complete the auction.
Price is therefore evaluated not at the bar level but at the price row level, exposing order flow dynamics that standard indicators cannot access.
Conceptual Framework
Footprint X-Ray is founded on the principle that the most actionable order flow information lives inside individual bars rather than across them, and that understanding which specific price levels within a bar attracted aggressive buying or selling reveals institutional positioning fingerprints that bar-level indicators systematically obscure.
Standard order flow approaches measure directional commitment at the bar level through delta, volume, or close positioning, but these metrics collapse the internal price distribution into a single reading that loses the structural detail of where within the bar each side dominated. This framework recovers that internal structure by reconstructing per-row participation from lower timeframe data, exposing the distribution of buying and selling pressure across the full price range of every bar.
Three core principles guide the design:
Each price row within a bar should have its own buy and sell volume measurement derived from lower timeframe participation overlap, providing per-level delta ratios rather than bar-level approximations.
Structural patterns within the footprint, specifically stacked consecutive dominant rows and opposing flow at extremes, carry meaningful institutional activity signals that justify dedicated detection and visualization separate from raw row coloring.
Unfinished auction levels where one side was entirely absent at a bar extreme should be projected forward as active reference zones until price returns to complete the participation, as incomplete auctions represent the highest-probability reversion targets within the footprint framework.
This shifts order flow analysis from bar-level delta measurement into per-row intrabar participation mapping where structural footprint patterns expose institutional activity with precision unavailable at the candlestick level.
Theoretical Foundation
The indicator combines lower timeframe OHLCV data retrieval, price overlap-weighted volume allocation to ATR-derived price rows, per-row delta ratio calculation, POC identification by maximum row volume, consecutive dominance run detection for stacked imbalances, extreme row opposing flow detection for absorption, and one-sided extreme row detection for unfinished business zone projection.
Lower timeframe bars are retrieved using security_lower_tf and each lower timeframe bar's volume is allocated to price rows proportionally based on the overlap between the lower timeframe bar's range and each row's boundaries. Bullish lower timeframe bars contribute their allocated volume to buy volume and bearish bars to sell volume, with doji bars split equally. CVD from TradingView's volume delta library provides the bar-level delta for divergence and exhaustion detection. Row size is automatically derived as a fraction of the 200-bar ATR, scaling the footprint granularity to the instrument's typical volatility.
Four internal systems operate in tandem:
Row Construction and Delta Allocation Engine : Divides each bar's price range into ATR-scaled rows, iterates through all lower timeframe bars within the current chart bar, allocates volume to overlapping rows by price range fraction, and derives per-row buy volume, sell volume, total volume, and delta ratio.
Footprint Analysis System : Identifies the POC as the row with maximum total volume, runs consecutive dominance detection in both bull and bear directions to classify stacked imbalance rows, and evaluates extreme rows for absorption by testing opposing side dominance against the configured threshold.
Unfinished Business Zone Engine : Tests the top and bottom rows of each bar for single-sided extreme dominance, creates forward-projecting zone boxes from qualifying rows, extends those zones rightward on each subsequent bar, and removes them when price midpoint is revisited.
Signal Detection System : Derives bar delta from the CVD series, tests for delta divergence against recent price highs and lows, and identifies exhaustion bars where volume significantly exceeds the SMA baseline but net delta remains near zero, indicating a contested bar where neither side achieved directional resolution.
This design provides a complete intrabar participation map with structural pattern detection across every dimension of order flow that is reconstructable from OHLCV data.
How It Works
Footprint X-Ray evaluates price through a sequence of intrabar decomposition and pattern detection processes:
Lower Timeframe Selection : The indicator automatically selects the most appropriate lower timeframe based on the current chart timeframe, using one-second for seconds charts, one-minute for intraday, five-minute for daily, and sixty-minute for higher timeframes, or the manually configured timeframe when auto selection is disabled.
Row Size Calculation : The ATR over 200 bars multiplied by 0.1 and rounded to the minimum tick produces the row height, scaled automatically to the instrument's volatility. Manual row sizing overrides this when auto sizing is disabled.
Lower Timeframe Data Retrieval : OHLCV arrays for the lower timeframe are retrieved via security_lower_tf and CVD is calculated using TradingView's volume delta library, providing both intrabar participation data and bar-level delta for signal detection.
Row Initialization : The bar's price range is divided into rows of equal height, with the number of rows derived from the range divided by the row size.
Volume Allocation per Row : For each row, all lower timeframe bars are iterated. Each lower timeframe bar contributing to a row has its volume allocated proportionally based on the fraction of its range overlapping the row boundary. Bullish lower timeframe bars contribute to buy volume and bearish bars to sell volume.
Delta Ratio Calculation : Each row's delta ratio is calculated as buy volume minus sell volume divided by total volume, producing a normalized score from negative one to positive one that drives cell coloring.
POC Identification : The row with the maximum total volume is identified as the Point of Control, receiving a distinct highlight color and an optional midpoint line.
Stacked Imbalance Detection : Consecutive bullish dominant rows exceeding the configured threshold ratio are identified as bullish stacked imbalances. The same logic in reverse identifies bearish stacks. Qualifying rows receive highlighted border coloring.
Absorption Detection : The top rows of green bars are tested for sell dominance and the bottom rows of red bars are tested for buy dominance. When opposing flow exceeds the absorption threshold at an extreme, an absorption signal is generated at the bar's high or low.
Unfinished Business Zone Creation : The top row of each bar is tested for buy dominance above the UB threshold and the bottom row for sell dominance above the threshold. Qualifying extreme rows generate forward-projecting zone boxes that extend rightward until price revisits the zone midpoint.
Delta Divergence Detection : Price making a new high within the lookback window while bar delta is negative generates a bearish divergence signal. Price making a new low while bar delta is positive generates a bullish divergence signal.
Exhaustion Bar Detection : Bars with volume exceeding the SMA baseline multiplied by the volume multiplier and with absolute delta-to-volume ratio below the configured maximum qualify as exhaustion bars, indicating high participation without directional resolution.
Candle Overlay Rendering : An optional transparent candle overlay with wicks colored by bar delta direction provides directional context on top of the footprint cell display without obscuring the underlying participation data.
Together, these elements form a continuously updating intrabar participation map where cell coloring reveals per-level delta composition, structural pattern detection identifies institutional activity signatures, and forward-projecting zones maintain active auction completion references.
Interpretation
Footprint X-Ray should be interpreted as an intrabar order flow decomposition system with layered structural pattern detection:
Footprint Cells : Each colored box represents a price row within the bar. Green shading indicates buy-dominant flow at that level, red shading indicates sell-dominant flow, and color intensity reflects the magnitude of the imbalance. Neutral rows with balanced participation appear at intermediate opacity.
Cell Text (Delta %) : The percentage displayed in each cell represents the net delta ratio for that row, quantifying how one-sided participation was at each specific price level within the bar.
Cell Text (Volume) : When volume mode is selected, each cell displays the net volume (buy minus sell) at that price row, providing absolute rather than relative participation data.
Accent Lines : A bright horizontal line on the dominant edge of each row highlights the side with greater participation, providing a clean visual boundary that reinforces the directional reading of each cell without requiring the text to be read.
POC Row : The row with the highest total volume receives a distinct highlight and optional midpoint line, marking the price level with the greatest participation concentration within the bar and the most significant auction reference point.
Stacked Imbalance Borders : Rows identified as part of a consecutive dominant run receive highlighted border coloring in the imbalance direction, signaling aggressive institutional one-sided flow across multiple consecutive price levels within the bar.
Absorption Diamonds : Diamond markers below bars indicate bullish absorption where buyers dominated the bottom rows of a red bar, suggesting selling pressure was being absorbed by aggressive buyers. Diamonds above bars indicate bearish absorption where sellers dominated the top rows of a green bar.
Unfinished Business Zones : Forward-projecting shaded boxes from extreme rows where one side was entirely absent mark incomplete auctions. Bullish UB zones project from bars where buyers dominated the top row without seller response. Bearish UB zones project from bars where sellers dominated the bottom row without buyer response.
Delta Divergence Crosses : Cross markers below price on bullish divergences and above price on bearish divergences identify structural disagreement between price direction and bar delta, flagging hidden weakness at new highs and hidden strength at new lows.
Exhaustion Circles : Orange circles on bars with extreme volume but near-zero net delta mark contested bars where neither side achieved resolution despite heavy participation, indicating potential inflection points where the prior directional move may be losing conviction.
Delta Wicks : Optional candle overlay wicks colored by bar delta direction provide an immediate visual cue for whether net buying or net selling dominated the bar as a whole, complementing the per-row cell analysis.
Per-row delta composition, POC location, stacked imbalance presence, absorption signals, unfinished business zones, and exhaustion bars collectively provide more order flow intelligence than any element in isolation.
Signal Logic & Visual Cues
Footprint X-Ray presents five distinct signal types derived from intrabar participation analysis:
Absorption Signal : Diamond markers generated when extreme rows show opposing flow against the bar direction, identifying institutional absorption of aggressive flow at price extremes.
Delta Divergence Signal : Cross markers generated when price makes new highs or lows within the lookback window but bar delta contradicts the directional move, flagging structurally weak breakouts.
Exhaustion Bar Signal : Orange circles generated on bars with exceptional volume and near-zero net delta, identifying participation battles where neither side achieved dominance despite heavy activity.
Unfinished business zones provide continuous passive signal context by projecting forward from incomplete auction extremes until price returns to complete the participation sequence.
Alert generation covers bullish and bearish CVD flips, bullish and bearish absorption events, bullish and bearish delta divergence, and exhaustion bar detection for comprehensive systematic order flow monitoring.
Strategy Integration
Footprint X-Ray fits within institutional order flow and auction theory-based trading approaches:
POC Reaction Trading : Use POC rows as high-probability reference levels within each bar. The highest-volume row represents the price level most accepted by both buyers and sellers and frequently acts as intrabar support, resistance, or reversion anchor on subsequent price interaction.
Stacked Imbalance Directional Bias : Use stacked imbalance detection as a directional conviction signal within bars. Consecutive buy-dominant rows from low to high indicate sustained aggressive buying across multiple price levels, suggesting institutional accumulation rather than isolated speculative activity.
Absorption Reversal Framing : Use absorption signals as potential reversal triggers where aggressive flow is meeting organized opposing participation at extremes. Bullish absorption at the low of a red bar suggests buyers are defending price levels despite selling pressure, while bearish absorption at the high of a green bar suggests sellers are resisting upside extension.
Unfinished Business Zone Targets : Use UB zones as reversion targets for subsequent price action, monitoring whether price returns to complete the auction at levels where one side was previously absent. The completion of an unfinished auction typically involves a return to the zone followed by the missing side finally participating.
Divergence-Confirmed Entries : Use delta divergence signals as structural warning indicators rather than standalone entries, weighting them more heavily when they coincide with other confluence factors such as absorption or unfinished business zone proximity.
Exhaustion Bar Context : Treat exhaustion bars as inflection point alerts requiring subsequent bar confirmation rather than immediate entry triggers. High volume with near-zero delta indicates a contested equilibrium that will resolve directionally on the following bars.
Technical Implementation Details
Delta Source : TradingView volume delta library providing CVD series with automatic lower timeframe selection
Row Construction : ATR-fraction row sizing with lower timeframe price overlap-weighted volume allocation per row
Analysis Engine : Maximum volume POC identification, consecutive dominance run detection for stacked imbalances, and extreme row opposing flow testing for absorption
UB System : Array-managed forward-projecting zone boxes with midpoint revisit detection and automatic removal
Signal Detection : CVD-based delta divergence against lookback window highs and lows, volume SMA ratio combined with delta ratio for exhaustion classification
Visualization : Gradient-colored footprint cells with accent lines, POC highlighting, stacked imbalance borders, absorption and divergence markers, exhaustion circles, UB zones, and optional delta wick candle overlay
Performance Profile : Optimized with object count caps and array management for real-time execution across intraday and higher timeframes
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Intrabar microstructure analysis for scalping with automatic one-minute lower timeframe providing high-resolution participation data within each chart bar
15 - 60 min : Session-level order flow decomposition for intraday trading with sufficient lower timeframe bar count per chart bar to produce meaningful row distributions
4H - Daily : Swing-level institutional footprint analysis with five-minute lower timeframe providing detailed participation mapping across larger price ranges
Suggested Baseline Configuration:
Auto Lower Timeframe : Enabled
Auto Row Size : Enabled
Cell Text : Delta %
Accent Lines : Enabled
Highlight POC Row : Enabled
Show Stacked Imbalances : Enabled
Min Consecutive Rows : 3
Dominance Threshold (SI) : 0.60
Show Absorption : Enabled
Show Unfinished Business : Enabled
Delta Divergence : Enabled
Exhaustion Bars : Enabled
Show Candle Overlay : Enabled
These suggested parameters should be used as a baseline; their effectiveness depends on the instrument's volume characteristics, typical bar range, and preferred signal sensitivity, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Too few rows per bar : Disable Auto Row Size and manually reduce the row size value to increase row count, producing a more granular footprint with finer price level resolution for the target instrument and timeframe combination.
Too many rows cluttering the display : Increase the manual row size or allow auto sizing to recalibrate. On higher timeframes with large bar ranges the automatic ATR fraction may produce excessive row counts that reduce readability.
Stacked imbalance signals too frequent : Increase the Min Consecutive Rows setting to require longer dominance runs before stacking is classified, or increase the Dominance Threshold toward 0.75 to demand stronger per-row directional conviction.
Absorption signals too frequent : Increase the Absorption Threshold toward 0.80 to require stronger opposing dominance at extremes before an absorption signal fires, filtering for only the most decisive institutional responses.
Too many unfinished business zones : Increase the UB Dominance Threshold toward 0.90 to restrict zone creation to only the most extreme single-sided bar extremes, reducing zone density on the chart.
Divergence signals firing too often : Increase the Divergence Lookback to require price to make a more significant new high or low before the divergence condition tests, reducing signal frequency to only the most structurally significant disagreements.
Exhaustion signals too frequent : Increase the Volume Multiplier to require a larger volume spike above the baseline before exhaustion classification, or decrease the Max Delta Ratio to require closer to zero net delta for a bar to qualify.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
Liquid instruments with consistent volume where lower timeframe bar allocation produces meaningful per-row participation distributions and reliable delta measurements
Intraday and session-level timeframes where sufficient lower timeframe bars exist within each chart bar to produce statistically representative row-level volume allocation
Order flow-based trading approaches where intrabar participation patterns provide entry confirmation or invalidation context that bar-level indicators cannot supply
Institutional activity monitoring where stacked imbalances and absorption patterns reveal aggressive positioning that precedes significant directional moves
Reduced Effectiveness:
Low-liquidity instruments where thin lower timeframe volume produces sparse row distributions with many empty cells and unreliable per-level delta ratios
Higher timeframes on instruments without lower timeframe data availability where security_lower_tf returns insufficient bars per chart bar for meaningful decomposition
Instruments without volume data, which the indicator detects and blocks with a runtime error
Extremely fast markets during news events where lower timeframe bars are so large relative to the chart bar range that overlap allocation produces distorted row distributions
Thin or extended-hours sessions where volume is too low to produce statistically meaningful per-row participation differences distinguishable from random distribution
Integration Guidelines
Confluence : Combine with BOSWaves structural tools, trend indicators, or momentum oscillators to validate footprint-derived signals with broader analytical context before acting on intrabar participation patterns
POC Context : Treat POC rows as the most significant intrabar reference levels. Subsequent price returning to a prior bar's POC is returning to its highest-participation level, which frequently acts as support, resistance, or magnetic reversion anchor.
Stacked Imbalance Direction : Use stacked imbalance direction as a short-term institutional bias indicator. Consecutive buy-dominant rows from low to high suggest aggressive accumulation that may continue on subsequent bars. Consecutive sell-dominant rows suggest distribution.
Unfinished Business Patience : Allow UB zones to be approached naturally rather than anticipating reactions immediately after formation. The auction completion process can take multiple bars and the zone should be monitored for participation behavior on arrival rather than treated as an automatic reversal level.
Exhaustion Confirmation Requirement : Never treat exhaustion bars as standalone entry triggers. The exhaustion condition identifies a contested state that requires subsequent directional resolution. Wait for the following bar to confirm which side won the participation battle before acting on the exhaustion signal.
Disclaimer
Footprint X-Ray is a professional-grade intrabar order flow decomposition and institutional activity detection tool. It uses lower timeframe volume allocation with per-row delta calculation but does not access true exchange-level bid and ask data. All participation measurements are reconstructed from OHLCV data and represent best-approximation estimates rather than actual order book information. Results depend on instrument liquidity, lower timeframe data availability, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates price structure, trend context, and comprehensive risk management. Индикатор

FVG Retest Entry Engine [trade_w_samet]🎯 FVG Retest Entry Engine
FVG Retest Entry Engine is a structured Fair Value Gap retest analysis indicator designed to help traders study confirmed gap reactions, structure alignment, filtered entry conditions, and multi-target visual trade models directly on the price chart.
This script focuses on one main concept:
FVG retest-based entry visualization.
It is not designed to be a simple buy/sell signal generator.
It is not designed to show every possible Fair Value Gap.
It is not designed to create constant chart noise.
Instead, the goal of FVG Retest Entry Engine is to detect confirmed structure events, identify eligible Fair Value Gaps, monitor their retests, apply configurable quality checkpoints, and visualize accepted setups using one entry level, one protective stop, and three take-profit levels.
The indicator includes:
• Bullish and bearish market-structure detection
• BOS and CHoCH classification
• Three-candle Fair Value Gap detection
• Internal FVG memory and invalidation handling
• Structure-linked FVG candidate selection
• FVG quality scoring and setup grading
• Armed-zone retest monitoring
• Multiple retest confirmation models
• Volume, Directional Force, and confirmed HTF bias filters
• FVG Retest Passport
• Blocker Lens state reporting
• Confirmed-close signal commitment
• Optional Live Preview dashboard state
• Gap-protected and ATR-based stop-loss models
• TP1, TP2, and TP3 risk-multiple projections
• Optional breakeven movement after TP1
• Active and historical TP / SL areas
• Executed FVG retest zones
• One-active-trade-at-a-time logic
• Mobile chart layout
• Multiple visual themes
• Advanced entry and lifecycle alerts
• JSON webhook support
• Compact bottom-right dashboard
The purpose of this script is to help users visually study where a structure event and an eligible Fair Value Gap combine with a confirmed retest condition.
It should be treated as a chart-analysis and educational decision-support tool.
It is not financial advice.
It is not an automated trading system.
It does not guarantee profitable trades.
It does not execute broker orders.
It does not replace personal analysis, risk management, or trade validation.
━━━━━━━━━━━━━━━━━━━━━━
📌 OVERVIEW
━━━━━━━━━━━━━━━━━━━━━━
At a high level, FVG Retest Entry Engine does the following:
• Detects confirmed bullish and bearish structure breaks.
• Classifies structure events as BOS or CHoCH.
• Detects bullish and bearish three-candle Fair Value Gaps.
• Stores valid FVG zones in internal memory.
• Tracks zone direction, boundaries, age, displacement, volume context, and prior interactions.
• Searches for an eligible FVG after a matching structure event.
• Scores and ranks available FVG candidates.
• Arms the best available zone for retest monitoring.
• Waits for the selected minimum retest delay.
• Detects the selected FVG retest pattern.
• Evaluates reaction quality and optional confluence filters.
• Assigns a setup grade such as A+, A, B, or FILTERED.
• Confirms final entry conditions only when the chart candle closes.
• Draws one Entry, one SL, and three TP levels.
• Tracks TP1, TP2, TP3, stop-loss, and breakeven events.
• Allows only one active trade projection at a time.
• Keeps completed trade areas when historical display is enabled.
• Marks completed models as bullish or bearish FVG Retest outcomes.
• Displays the current bias, engine state, and active levels in the dashboard.
• Provides entry, armed-zone, target, stop, breakeven, and webhook alert options.
The script is intentionally built as a structured process.
It does not include machine-learning prediction.
It does not include guaranteed performance claims.
It does not attempt to forecast every future market movement.
It provides a transparent way to study structure-linked FVG retests and their projected trade lifecycle.
━━━━━━━━━━━━━━━━━━━━━━
🧠 CORE IDEA
━━━━━━━━━━━━━━━━━━━━━━
The core idea behind FVG Retest Entry Engine is based on the relationship between market structure and Fair Value Gap reactions.
A Fair Value Gap represents a three-candle price imbalance.
A bullish FVG is formed when the current candle’s low is above the high from two candles earlier.
A bearish FVG is formed when the current candle’s high is below the low from two candles earlier.
The script does not treat every FVG as an entry.
Instead, it waits for a confirmed structure event and then searches for an eligible FVG that matches that directional context.
The selected FVG becomes an armed zone.
Price must later return to that zone and satisfy the chosen retest condition.
The engine can then evaluate:
• gap size relative to ATR
• formation displacement
• formation volume context
• FVG age
• prior zone interactions
• structure-break quality
• retest depth
• reaction-candle quality
• volume participation
• DI / ADX directional force
• confirmed higher-timeframe bias
• minimum setup grade
The goal is not to show more signals.
The goal is to create a documented and understandable process from structure event to confirmed FVG retest model.
━━━━━━━━━━━━━━━━━━━━━━
🧩 WHY THIS SCRIPT IS NOT A SIMPLE BUY/SELL INDICATOR
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine is not intended to be used as a blind buy/sell system.
The script is structured as a visual review workflow:
Structure event is confirmed
→ matching FVG candidates are reviewed
→ one eligible FVG is selected
→ the FVG becomes armed
→ price returns to the armed zone
→ the retest pattern is checked
→ reaction quality is evaluated
→ enabled filters are checked
→ the setup receives a grade
→ the candle must close with all conditions still valid
→ Entry, SL, TP1, TP2, and TP3 are projected
→ the active model is monitored
→ the model closes at TP3, stop loss, targets complete, or breakeven
→ the completed FVG Retest model is archived visually
Each part has a specific purpose.
The structure system identifies a directional event.
The FVG memory system stores imbalance zones.
The candidate-ranking system selects a relevant gap instead of using every gap.
The armed-zone system separates observation from entry.
The retest logic defines what qualifies as a valid return.
The quality checkpoints reduce setups that fail enabled conditions.
The grading system summarizes internal setup quality.
The entry model provides visual planning levels.
The stop model creates a consistent risk reference.
The three-target model provides staged reward references.
The Blocker Lens explains the current engine state.
The Passport explains why an accepted setup qualified.
The alert system supports monitoring of confirmed events.
This makes the script a structured FVG retest analysis tool, not a guaranteed trade signal generator.
━━━━━━━━━━━━━━━━━━━━━━
⚙️ HOW THE SCRIPT WORKS
━━━━━━━━━━━━━━━━━━━━━━
The script operates through several connected stages.
First, it identifies confirmed swing highs and swing lows.
Price breaking a confirmed swing level can create a bullish or bearish structure event.
The break may be classified as BOS when it continues the current structure bias or CHoCH when it changes that bias.
The engine separately detects three-candle Fair Value Gaps and stores their contextual information.
bool tws_bullish_fvg = bar_index >= 2 and low > high
bool tws_bearish_fvg = bar_index >= 2 and high < low
float tws_bullish_fvg_top = low
float tws_bullish_fvg_bottom = high
float tws_bearish_fvg_top = low
float tws_bearish_fvg_bottom = high
float tws_bullish_fvg_size = tws_bullish_fvg_top - tws_bullish_fvg_bottom
float tws_bearish_fvg_size = tws_bearish_fvg_top - tws_bearish_fvg_bottom
When a structure event occurs, the engine reviews matching FVG candidates within the selected distance and timing limits.
The available candidates are compared using the active profile’s rules.
The selected zone becomes armed and remains under observation until:
• a confirmed retest creates an entry
• the setup expires
• the FVG is invalidated
• another structure search replaces it
Once price interacts with the armed zone, the selected retest model and reaction-quality conditions are checked.
Volume, DI / ADX, and higher-timeframe bias can also be required.
Only a setup that passes the active rules and remains valid at candle close can create a permanent entry model.
━━━━━━━━━━━━━━━━━━━━━━
🔵 BULLISH FVG RETEST LOGIC
━━━━━━━━━━━━━━━━━━━━━━
A bullish FVG Retest setup begins with bullish structure context.
The script requires a confirmed bullish BOS or CHoCH event and then searches for a directionally matching FVG candidate.
The selected zone must remain valid while the engine waits for price to return.
Depending on the chosen profile and retest model, bullish confirmation may require:
• wick contact with the zone
• real-body contact
• a close inside the zone
• a bullish reaction reclaim
• directional recovery above the zone midpoint
• a close above the relevant FVG edge
• a bullish rejection wick
The engine may then check:
• reaction strength
• volume participation
• positive DI dominance
• minimum ADX strength
• confirmed bullish HTF alignment
• minimum accepted grade
When every enabled condition remains valid at candle close, the script creates:
• a bullish FVG RETEST label
• an executed FVG retest box
• an entry reference at the confirmation close
• a protective stop below the setup reference
• TP1, TP2, and TP3 above entry
• blue reward visualization
• red risk visualization
This does not mean price must continue upward.
It means the script detected a bullish FVG retest condition that satisfied the selected rules at the time of confirmation.
━━━━━━━━━━━━━━━━━━━━━━
🔴 BEARISH FVG RETEST LOGIC
━━━━━━━━━━━━━━━━━━━━━━
A bearish FVG Retest setup begins with bearish structure context.
The script requires a confirmed bearish BOS or CHoCH event and then searches for a directionally matching FVG candidate.
The selected zone must remain valid while the engine waits for price to return.
Depending on the chosen profile and retest model, bearish confirmation may require:
• wick contact with the zone
• real-body contact
• a close inside the zone
• a bearish reaction reclaim
• directional recovery below the zone midpoint
• a close below the relevant FVG edge
• a bearish rejection wick
The engine may then check:
• reaction strength
• volume participation
• negative DI dominance
• minimum ADX strength
• confirmed bearish HTF alignment
• minimum accepted grade
When every enabled condition remains valid at candle close, the script creates:
• a bearish FVG RETEST label
• an executed FVG retest box
• an entry reference at the confirmation close
• a protective stop above the setup reference
• TP1, TP2, and TP3 below entry
• blue reward visualization
• red risk visualization
This does not mean price must continue downward.
It means the script detected a bearish FVG retest condition that satisfied the selected rules at the time of confirmation.
━━━━━━━━━━━━━━━━━━━━━━
💎 FVG QUALITY FILTER SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
The script includes a multi-layer FVG quality system to reduce unnecessary chart signals.
This is important because not every gap has the same context and not every retest should create an entry model.
The quality system may evaluate:
• minimum gap size relative to ATR
• displacement of the formation candle
• gap location inside the recent dealing range
• formation-volume context
• gap age
• previous interactions with the zone
• distance from the matching structure event
• structure-break strength
• reaction-candle strength
• volume participation on retest
• DI / ADX directional force
• confirmed HTF bias
• final setup grade
The exact behavior depends on the selected Engine Style.
Original Sync uses the first validated calibration and star-based acceptance logic.
Balanced Flow uses moderate filtering.
Precision Flow applies stricter FVG and retest requirements.
Fast Flow accepts more active conditions.
Position Flow uses wider structural and timing windows.
Custom Lab exposes the advanced thresholds for manual configuration.
The filter system does not guarantee better future outcomes.
It controls how selective the engine is before creating a confirmed visual model.
━━━━━━━━━━━━━━━━━━━━━━
📏 GAP / ATR FILTER
━━━━━━━━━━━━━━━━━━━━━━
The gap-width filter measures the detected FVG against ATR.
This helps the engine reject extremely small imbalance zones relative to current market volatility.
A higher minimum gap-width value makes FVG storage and candidate selection more selective.
A lower value allows smaller gaps to enter the internal memory.
The filter is volatility-adjusted because the same absolute price distance can have different meaning across symbols and timeframes.
The active threshold depends on the chosen profile or Custom Lab value.
A larger gap is not automatically a better setup.
Gap size is only one component of the complete selection and retest process.
━━━━━━━━━━━━━━━━━━━━━━
🕯️ DISPLACEMENT QUALITY FILTER
━━━━━━━━━━━━━━━━━━━━━━
The displacement filter evaluates the directional body of the candle associated with FVG formation.
The formation body is compared with ATR and converted into a bounded internal score.
This helps the script distinguish a stronger directional imbalance from a gap created during weak or narrow price action.
When the Gap Impulse Check is enabled, an FVG must satisfy the selected displacement threshold before it is stored as a valid candidate.
A higher threshold reduces the number of eligible FVGs.
A lower threshold accepts more moderate formations.
The displacement score is an internal quality measurement.
It does not predict whether the zone will hold in the future.
━━━━━━━━━━━━━━━━━━━━━━
📊 REACTION STRENGTH FILTER
━━━━━━━━━━━━━━━━━━━━━━
The reaction-strength filter evaluates the candle that interacts with the armed FVG.
The score can include:
• close location inside the candle
• directional wick quality
• body size relative to ATR
• bullish or bearish candle direction
• penetration depth inside the FVG
The purpose is to separate a basic touch from a more structured directional response.
A higher minimum reaction-strength value requires a clearer response from the zone.
A lower value accepts more retest conditions.
Original Sync can use its original reaction logic without the same adaptive score requirement.
The reaction score is not a win probability.
It is a standardized way to evaluate whether the retest candle matches the selected profile’s quality requirements.
━━━━━━━━━━━━━━━━━━━━━━
🧼 CONFIRMED RETEST FILTER
━━━━━━━━━━━━━━━━━━━━━━
The confirmed-retest layer requires price to satisfy the active retest model and remain valid at candle close.
Available Original Sync reaction patterns include:
• Any Wick Contact
• Real Body Contact
• Close Within Gap
• Reaction Reclaim
Available adaptive reaction models include:
• First Contact
• Directional Recovery
• Edge Reclaim
• Rejection Wick
First Contact accepts basic interaction with the zone.
Directional Recovery requires directional behavior after the interaction.
Edge Reclaim requires price to close through the relevant boundary.
Rejection Wick applies a stricter wick-and-close response.
The script can also use an interaction margin to tolerate minor boundary differences.
A minimum delay prevents the engine from confirming a retest too soon after the structure event.
An expiry window prevents stale armed zones from producing entries too far from their original context.
Final entry commitment remains bar-close based.
━━━━━━━━━━━━━━━━━━━━━━
🎯 ENTRY MODEL
━━━━━━━━━━━━━━━━━━━━━━
When an armed FVG retest passes all enabled conditions, the script creates a visual entry model.
The entry reference is the close of the candle that confirms the retest.
Permanent entries, labels, boxes, and entry alerts are committed only after candle close.
tws_preview_ready := tws_eval_zone_touched and tws_eval_reaction_pass and tws_direction_filters_pass and tws_eval_grade_pass
bool tws_confirmed_entry = tws_preview_ready and barstate.isconfirmed
if tws_confirmed_entry
tws_long_signal := tws_armed_direction == 1
tws_short_signal := tws_armed_direction == -1
tws_entry_event := true
tws_trade_active := true
tws_trade_direction := tws_armed_direction
tws_trade_open_bar := bar_index
tws_trade_entry := close
Confirmed Close mode waits for the candle to finish before the dashboard treats the setup as an entry.
Live Preview can show that current conditions are ready while the realtime candle is still open.
The preview may change intrabar because the candle is unfinished.
It does not create a permanent historical entry model unless the setup remains valid when the candle closes.
The entry is a visual analysis reference.
It is not a broker order and does not require the user to enter a trade.
━━━━━━━━━━━━━━━━━━━━━━
🛑 ATR STOP-LOSS MODEL
━━━━━━━━━━━━━━━━━━━━━━
The script includes two stop-placement models.
Gap-Protected Stop uses the selected FVG boundary plus an ATR-based protective buffer.
For bullish setups, the stop is projected below the FVG.
For bearish setups, the stop is projected above the FVG.
Volatility Stop projects the stop at an ATR multiple from entry.
A minimum stop-distance percentage can prevent extremely narrow visual stops.
float tws_raw_stop =
tws_stop_mode == "Gap-Protected Stop" ?
(
tws_trade_direction == 1 ?
tws_armed_bottom - tws_atr * tws_fvg_stop_buffer_atr :
tws_armed_top + tws_atr * tws_fvg_stop_buffer_atr
) :
(
tws_trade_direction == 1 ?
tws_trade_entry - tws_atr * tws_atr_stop_multiplier :
tws_trade_entry + tws_atr * tws_atr_stop_multiplier
)
float tws_raw_stop_distance = math.abs(tws_trade_entry - tws_raw_stop)
float tws_guaranteed_distance = tws_trade_entry * tws_minimum_stop_percent / 100.0
float tws_final_stop_distance = math.max(tws_raw_stop_distance, tws_guaranteed_distance)
ATR is used because volatility changes across markets and timeframes.
A wider stop changes the projected risk distance and therefore also changes all three target levels.
The displayed SL is a visual planning level only.
It does not place or manage a real broker stop order.
━━━━━━━━━━━━━━━━━━━━━━
🎯 TAKE-PROFIT RR MODEL
━━━━━━━━━━━━━━━━━━━━━━
The script uses three take-profit levels.
Each target is calculated from the distance between entry and the original stop.
float tws_trade_risk = math.abs(tws_trade_entry - tws_trade_original_stop)
tws_trade_tp1 := tws_trade_direction == 1 ? tws_trade_entry + tws_trade_risk * tws_tp1_r : tws_trade_entry - tws_trade_risk * tws_tp1_r
tws_trade_tp2 := tws_trade_direction == 1 ? tws_trade_entry + tws_trade_risk * tws_tp2_r : tws_trade_entry - tws_trade_risk * tws_tp2_r
tws_trade_tp3 := tws_trade_direction == 1 ? tws_trade_entry + tws_trade_risk * tws_tp3_r : tws_trade_entry - tws_trade_risk * tws_tp3_r
The default concept is:
TP1 = first risk-multiple target
TP2 = second risk-multiple target
TP3 = final risk-multiple target
The exact R values can be adjusted in Position Architecture.
The script also contains visual position-share percentages for TP1, TP2, and TP3.
These shares are used by the internal lifecycle model.
They do not represent a broker account, real position size, or verified financial performance.
The RR settings only control projected visual distances.
They should not be interpreted as recommendations or guaranteed objectives.
━━━━━━━━━━━━━━━━━━━━━━
📦 ACTIVE TP / SL BOX SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
When a confirmed FVG Retest entry appears, the script can draw a complete visual trade model.
The visual model includes:
• executed FVG retest zone
• entry line
• original stop line
• active stop line
• TP1 line
• TP2 line
• TP3 line
• red risk box
• blue reward box
• Entry price label
• SL price label
• TP1, TP2, and TP3 price labels
• bullish or bearish entry label
The active boxes extend to the right while the model is open.
When the model closes, the right edge is fixed at the closing candle.
If Keep Completed Trade Areas is enabled, completed boxes and lines remain visible for historical review.
The Completed Trade History Limit controls how many previous visual models are retained.
The TP area uses a blue-toned visual palette.
TP price labels use a different, darker background so they remain distinct from the reward box.
The SL area remains red for clearer risk separation.
━━━━━━━━━━━━━━━━━━━━━━
🚦 ONE ACTIVE TRADE AT A TIME
━━━━━━━━━━━━━━━━━━━━━━
The script includes one-active-trade-at-a-time logic.
If a trade model is active, the engine does not create another trade model until the current one closes.
The active model may close through:
• TP3
• targets complete
• stop loss
• breakeven exit
This design separates:
• FVG and structure detection
• trade-model creation permission
The engine can continue calculating market context while a model is active, but another entry model is not opened.
This helps prevent overlapping TP / SL areas and keeps the chart easier to interpret.
The one-active-model rule is a visual management decision.
It is not a restriction on the user’s personal trading activity.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ SAME-CANDLE TP / SL HANDLING
━━━━━━━━━━━━━━━━━━━━━━
If a target and the active stop are both touched on the same candle, standard OHLC data cannot reveal the true intrabar sequence.
The script therefore includes two selectable assumptions:
Protective First
Target First
Protective First assumes the stop is processed before target events.
Target First processes available target events before the stop check.
bool tws_conservative_mode =
tws_intrabar_priority == "Protective First"
if tws_conservative_mode and tws_stop_touched
tws_trade_remaining_percent := 0.0
tws_close_trade := true
tws_close_reason := tws_trade_active_stop == tws_trade_entry ? "BREAKEVEN" : "STOP LOSS"
tws_final_exit_price := tws_trade_active_stop
else
if not tws_tp1_reached and tws_tp1_touched
tws_tp1_reached := true
tws_tp1_event := true
Protective First is the more conservative bar-based assumption.
Target First is more optimistic.
Neither option reproduces exact tick-by-tick broker execution.
The model does not include spread, slippage, commissions, latency, or partial-fill behavior.
━━━━━━━━━━━━━━━━━━━━━━
🏷️ FVG RETEST LABELS
━━━━━━━━━━━━━━━━━━━━━━
The script uses clear directional FVG Retest labels.
Bullish entry labels use:
🟢 FVG RETEST
📈 LONG
Bearish entry labels use:
🔴 FVG RETEST
📉 SHORT
Entry labels can also display:
• grade
• setup score
• FVG age
• retest depth
• Passport information
Completed-model labels emphasize that the closed model originated from an FVG retest.
A completed bullish model can display:
🟢 BULLISH FVG RETEST
🔒 MODEL CLOSED
🎯 close reason
⭐ grade
TP1 / TP2 / TP3 status
A completed bearish model uses the corresponding bearish wording and color.
The labels do not display USD profit or account-profit claims.
All chart labels use bold and italic text formatting.
The signal-label size can be adjusted from the settings.
━━━━━━━━━━━━━━━━━━━━━━
📍 FVG ZONE DISPLAY MODES
━━━━━━━━━━━━━━━━━━━━━━
The FVG display system includes three modes:
Hidden
Selected Gap
All Active Gaps
Hidden mode removes active FVG memory boxes from the chart while allowing the engine to continue calculating them internally.
Selected Gap shows only the FVG currently armed for retest monitoring.
All Active Gaps displays every currently stored and valid FVG zone.
Show Executed FVG Retests separately controls whether the FVG zone that created an entry remains highlighted as part of the trade model.
The selected display mode affects visual presentation only.
It does not change the underlying FVG calculations.
For the cleanest chart, Selected Gap is generally the most focused mode.
All Active Gaps can be useful for research but may create more chart density.
━━━━━━━━━━━━━━━━━━━━━━
🧹 FVG INVALIDATION
━━━━━━━━━━━━━━━━━━━━━━
The script can automatically remove invalidated FVG zones.
A bullish FVG may be invalidated when confirmed price action closes through the zone in the opposite direction.
A bearish FVG may be invalidated when confirmed price action closes through its opposite boundary.
An armed zone can also be cleared when:
• its retest window expires
• the zone exceeds the permitted lifetime
• the internal memory limit removes an older gap
• the active structure search is replaced
When an armed FVG becomes invalid, the Blocker Lens can display FVG INVALIDATED.
When the retest window expires, it can display SETUP EXPIRED.
Removing invalidated or stale zones helps prevent outdated FVGs from creating later entries outside their intended context.
Users can disable automatic invalidation removal if they prefer to retain more zones visually.
━━━━━━━━━━━━━━━━━━━━━━
📟 DASHBOARD
━━━━━━━━━━━━━━━━━━━━━━
The script includes a compact dashboard positioned in the bottom-right corner.
The dashboard displays:
• BIAS
• STATE
• ENTRY
• TP1
• TP2
• TP3
• SL
BIAS uses the confirmed higher-timeframe filter when that filter is enabled and valid.
Otherwise, it reflects the current internal structure bias.
STATE is powered by the Blocker Lens.
Possible states include:
• WAITING STRUCTURE
• SCANNING FVG
• NO ELIGIBLE FVG
• FVG ARMED
• RETEST DELAY
• WAITING RETEST
• VOLUME BLOCK
• DI BLOCK
• HTF BLOCK
• WEAK REACTION
• GRADE BLOCK
• LIVE PREVIEW READY
• WAITING BAR CLOSE
• TRADE ACTIVE
• COOLDOWN
• SETUP EXPIRED
• FVG INVALIDATED
The dashboard size can be set to Micro, Compact, or Standard.
The dashboard is designed to summarize engine state and current price references.
It is not a performance report.
It is not a replacement for TradingView Strategy Tester.
━━━━━━━━━━━━━━━━━━━━━━
🚨 ALERT SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine includes advanced alert options for:
• FVG armed
• bullish FVG Retest entry
• bearish FVG Retest entry
• any FVG Retest entry
• TP1 reached
• TP2 reached
• TP3 reached
• breakeven activated
• stop loss
• breakeven exit
Alert packages include:
Off
Qualified Entries
Premium Entries
Full Lifecycle
Webhook JSON
Qualified Entries focuses on confirmed accepted entries.
Premium Entries applies stricter grade-based alert delivery.
Full Lifecycle includes entry and management events.
Webhook JSON sends structured event messages for external processing.
Alert Direction can be limited to Both Directions, Bullish Only, or Bearish Only.
Minimum Alert Grade can be set to All Qualified, A / A+, or A+ Only.
Alert filtering affects alert delivery only.
It does not change the chart’s signal calculations.
alertcondition(tws_armed_alert_event, title="trade_w_samet • FVG ARMED", message='trade_w_samet FVG ARMED | {{ticker}} | TF: {{interval}} | Score: {{plot("SIGNAL_SCORE")}}')
alertcondition(tws_entry_alert_event and tws_trade_direction == 1, title="trade_w_samet • BULLISH FVG RETEST", message='trade_w_samet BULLISH FVG RETEST | {{ticker}} | TF: {{interval}} | Score: {{plot("SIGNAL_SCORE")}} | Entry: {{plot("ENTRY")}} | SL: {{plot("SL")}} | TP1: {{plot("TP1")}} | TP2: {{plot("TP2")}} | TP3: {{plot("TP3")}}')
alertcondition(tws_entry_alert_event and tws_trade_direction == -1, title="trade_w_samet • BEARISH FVG RETEST", message='trade_w_samet BEARISH FVG RETEST | {{ticker}} | TF: {{interval}} | Score: {{plot("SIGNAL_SCORE")}} | Entry: {{plot("ENTRY")}} | SL: {{plot("SL")}} | TP1: {{plot("TP1")}} | TP2: {{plot("TP2")}} | TP3: {{plot("TP3")}}')
alertcondition(tws_tp1_alert_event, title="trade_w_samet • TP1 REACHED", message='trade_w_samet TP1 REACHED | {{ticker}} | TP1: {{plot("TP1")}}')
alertcondition(tws_stop_alert_event, title="trade_w_samet • STOP LOSS", message='trade_w_samet STOP LOSS | {{ticker}} | SL: {{plot("SL")}}')
Alerts are monitoring tools only.
They do not execute trades or place broker orders.
━━━━━━━━━━━━━━━━━━━━━━
🔔 HOW TO USE ALERTS
━━━━━━━━━━━━━━━━━━━━━━
A practical alert workflow:
1. Add FVG Retest Entry Engine to the chart.
2. Select the desired Engine Style and confirmation settings.
3. Open TradingView’s alert window.
4. Select the indicator as the alert condition.
5. Choose the desired entry or lifecycle condition.
6. Select the alert frequency appropriate for confirmed-candle monitoring.
7. Use the Alert Package, direction, and grade controls inside the indicator when needed.
8. Add a webhook URL only when using a compatible external workflow.
9. Test the alert configuration before depending on it.
10. Confirm every event with personal analysis and risk management.
For confirmed entry monitoring, users should avoid treating provisional realtime candle conditions as permanent signals.
Entry alerts are designed around the script’s confirmed event variables.
Alert delivery can still depend on TradingView servers, the user’s alert configuration, data availability, and any external webhook destination.
━━━━━━━━━━━━━━━━━━━━━━
🧪 HOW TO USE THE INDICATOR
━━━━━━━━━━━━━━━━━━━━━━
A practical workflow:
1. Add FVG Retest Entry Engine to a standard candlestick chart.
2. Begin with Original Sync or Balanced Flow.
3. Keep Signal Timing on Confirmed Close for the clearest workflow.
4. Use Selected Gap to keep the chart focused.
5. Observe the dashboard STATE value.
6. Wait for a confirmed structure event and an armed FVG.
7. Review the FVG zone before the retest occurs.
8. When price returns, allow the selected retest model and filters to complete.
9. Review the FVG Retest Passport when an entry appears.
10. Use the displayed Entry, SL, TP1, TP2, and TP3 as visual references only.
11. Evaluate whether the setup fits personal structure, liquidity, session, and risk rules.
12. Use alerts for monitoring rather than blind execution.
13. Review completed FVG Retest labels to understand the model lifecycle.
14. Test settings on the exact markets and timeframes personally studied.
The indicator is best used as a structured FVG retest review tool.
It should not be used as an automatic decision-maker.
━━━━━━━━━━━━━━━━━━━━━━
⚙️ SETTINGS REFERENCE
━━━━━━━━━━━━━━━━━━━━━━
⚡ Signal Blueprint
Engine Style
Controls the active configuration profile.
Available profiles:
Original Sync
Balanced Flow
Precision Flow
Fast Flow
Position Flow
Custom Lab
Allow Bullish Setups
Enables or disables bullish FVG Retest models.
Allow Bearish Setups
Enables or disables bearish FVG Retest models.
━━━━━━━━━━━━━━━━━━━━━━
🪪 Retest Experience
FVG Retest Passport
Controls whether Passport information is Off, Compact, or Detailed.
Show Blocker Lens
Shows or hides the engine STATE explanation in the dashboard.
Signal Timing
Selects Confirmed Close or Live Preview behavior.
Live Preview affects the dashboard’s provisional realtime state. Permanent entries remain candle-close confirmed.
━━━━━━━━━━━━━━━━━━━━━━
🧬 Original Sync Engine
Original Signal Calibration
Selects Manual Sync, Bitcoin Map, Ethereum Map, Solana Map, or Gold Map.
Structure Window
Controls pivot sensitivity in Manual Sync.
Minimum Gap Footprint — ATR
Controls the minimum FVG width.
Gap Lifetime
Controls how long stored FVGs remain eligible.
Gap Memory Capacity
Controls the number of stored zones.
Break-to-Gap Distance
Controls the maximum allowed distance between structure context and FVG eligibility.
After-Break Scan Window
Controls how long the engine continues searching after a break.
Reaction Pattern
Selects Any Wick Contact, Real Body Contact, Close Within Gap, or Reaction Reclaim.
Reaction Margin %
Adds tolerance around FVG boundaries.
Minimum Reaction Delay
Controls how many bars must pass before retest confirmation.
Reaction Expiry Bars
Controls how long the armed setup may wait.
Participation Multiplier
Controls the Original Sync volume requirement.
Minimum Directional Force
Controls the Original Sync ADX threshold.
Minimum Sync Rating
Controls the minimum accepted star rating.
Minimum Risk Distance %
Prevents extremely narrow stops.
━━━━━━━━━━━━━━━━━━━━━━
🧭 Structure Pulse
Structure Sensitivity
Controls pivot detection in Custom Lab.
Display Structure Tags
Shows or hides BOS / CHoCH labels.
Close-Lock Breaks
Requires a candle close beyond structure when enabled.
Break Momentum Check
Requires directional expansion on the break candle.
Break Body Threshold — ATR
Controls the required break-candle body size.
Break Clearance — ATR
Adds an ATR-based buffer beyond the structure level.
━━━━━━━━━━━━━━━━━━━━━━
🧱 Gap Intelligence
Minimum Gap Width — ATR
Controls the minimum stored FVG size.
Gap Impulse Check
Enables displacement filtering.
Minimum Gap Impulse
Controls the required formation displacement.
Minimum Gap Score
Controls the minimum candidate-quality score.
Allowed Prior Reactions
Controls how many previous zone interactions are accepted.
Gap Expiry Bars
Controls maximum FVG age.
Active Gap Capacity
Controls stored-zone capacity.
Maximum Structure Link
Controls the maximum structure-to-FVG distance.
Break Follow-Through Window
Controls post-break candidate scanning.
Delete Invalidated Gaps
Removes zones invalidated by confirmed opposite price action.
━━━━━━━━━━━━━━━━━━━━━━
🎯 Reaction Trigger
Reaction Model
Selects First Contact, Directional Recovery, Edge Reclaim, or Rejection Wick.
Gap Interaction Margin %
Adds tolerance around FVG boundaries.
Minimum Reaction Strength
Controls the required retest-candle score.
Reaction Delay Bars
Controls the minimum delay before retest confirmation.
Setup Expiry Bars
Controls how long the armed zone remains available.
Signal Cooldown Bars
Controls the delay after a completed model before another entry is permitted.
━━━━━━━━━━━━━━━━━━━━━━
🛂 Quality Checkpoints
Volume Participation Check
Enables or disables the retest-volume filter.
Volume Baseline Length
Controls the volume moving-average period.
Required Volume Expansion
Controls the required volume multiplier.
Directional Force Check
Enables or disables DI / ADX filtering.
Directional Force Length
Controls the DI period.
Trend Strength Smoothing
Controls ADX smoothing.
Minimum Trend Strength
Controls the required ADX value.
Higher-Timeframe Bias Check
Enables or disables HTF directional alignment.
Bias Timeframe
Selects the higher timeframe.
Bias Fast EMA
Controls the fast HTF EMA length.
Bias Slow EMA
Controls the slow HTF EMA length.
Minimum Setup Grade
Selects B Grade or Better, A Grade or Better, or A+ Only.
The HTF layer uses previous completed higher-timeframe values.
float tws_htf_close = request.security(
syminfo.tickerid,
tws_htf_timeframe,
close ,
barmerge.gaps_off,
barmerge.lookahead_on
)
float tws_htf_fast_ema = request.security(
syminfo.tickerid,
tws_htf_timeframe,
ta.ema(close, tws_htf_fast_length) ,
barmerge.gaps_off,
barmerge.lookahead_on
)
float tws_htf_slow_ema = request.security(
syminfo.tickerid,
tws_htf_timeframe,
ta.ema(close, tws_htf_slow_length) ,
barmerge.gaps_off,
barmerge.lookahead_on
)
━━━━━━━━━━━━━━━━━━━━━━
🛡️ Position Architecture
ATR Calculation Length
Controls ATR calculation.
Stop Placement Model
Selects Gap-Protected Stop or Volatility Stop.
Volatility Stop Multiplier
Controls ATR stop distance from entry.
Gap Stop Buffer — ATR
Controls the protective distance beyond the FVG.
Minimum Stop Distance %
Prevents extremely narrow risk zones.
TP1 Risk Multiple
Controls the first target distance.
TP2 Risk Multiple
Controls the second target distance.
TP3 Risk Multiple
Controls the final target distance.
TP1 Position Share %
Controls the internal visual share assigned to TP1.
TP2 Position Share %
Controls the internal visual share assigned to TP2.
TP3 Position Share %
Controls the internal visual share assigned to TP3.
Move Stop to Entry After TP1
Moves the active stop to entry after TP1 according to confirmed lifecycle rules.
Same-Candle Priority
Selects Protective First or Target First.
━━━━━━━━━━━━━━━━━━━━━━
🎨 Chart Design
Color System
Selects Obsidian Signal, Carbon Grid, Ivory Pulse, Neon Voltage, Acid Circuit, or Violet Flux.
Gap Display Mode
Selects Hidden, Selected Gap, or All Active Gaps.
Show Executed FVG Retests
Shows or hides the FVG zone used by a confirmed trade model.
Display TP / SL Areas
Shows or hides the reward and risk boxes.
Keep Completed Trade Areas
Keeps completed model boxes and lines.
Completed Trade History Limit
Controls the maximum historical visual models.
Active Area Projection
Controls the initial right-side projection length.
Chart Layout
Selects Desktop or Mobile.
Signal Label Size
Selects Micro, Compact, Standard, or Large.
Dashboard Size
Selects Micro, Compact, or Standard.
Display Bias EMA
Shows or hides the confirmed HTF fast EMA reference.
Display Setup Dashboard
Shows or hides the bottom-right dashboard.
━━━━━━━━━━━━━━━━━━━━━━
📡 Alert Center
Alert Package
Selects Off, Qualified Entries, Premium Entries, Full Lifecycle, or Webhook JSON.
Alert Direction
Selects Both Directions, Bullish Only, or Bearish Only.
Minimum Alert Grade
Selects All Qualified, A / A+, or A+ Only.
Alert When FVG Is Armed
Enables armed-zone alerts for compatible packages.
Alert When Stop Moves to Entry
Enables breakeven-activation alerts for compatible packages.
━━━━━━━━━━━━━━━━━━━━━━
🧠 WHAT MAKES THIS SCRIPT ORIGINAL
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine uses familiar analytical concepts such as:
• Fair Value Gaps
• swing-point structure
• BOS and CHoCH
• ATR
• volume analysis
• DI / ADX
• higher-timeframe EMA bias
• risk/reward projection
• staged targets
• breakeven management
These concepts are not unique by themselves.
The originality of this script lies in how they are organized into a transparent FVG retest workflow:
Structure confirmation
→ directional FVG memory
→ contextual candidate comparison
→ selected armed zone
→ configurable retest validation
→ reaction-quality evaluation
→ optional volume, DI, and HTF checkpoints
→ setup grading
→ confirmed-close entry commitment
→ three-target visual management
→ optional breakeven movement
→ completed FVG Retest archiving
→ Blocker Lens state reporting
→ Passport explanation
→ lifecycle alerts
Distinctive implementation features include:
• structure-linked FVG selection instead of signaling every gap
• multiple Engine Style profiles
• Original Sync market calibrations
• an armed-zone state before entry
• candidate ranking using several FVG characteristics
• multiple retest models
• a visible reason when an entry is waiting or blocked
• a Passport explaining accepted setup context
• confirmed-close permanent signal commitment
• previous-completed HTF values
• executed FVG zone preservation
• three-stage target management
• Desktop and Mobile display modes
• alert filtering separated from chart calculations
This structure is designed to provide a focused and explainable review process without relying on hidden prediction claims.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ IMPORTANT PRACTICAL NOTES
━━━━━━━━━━━━━━━━━━━━━━
The script’s behavior depends heavily on settings and market conditions.
Signal frequency and visual output may change based on:
• Engine Style
• structure sensitivity
• close-based or wick-based breaks
• break momentum requirements
• minimum FVG width
• displacement filtering
• candidate-score threshold
• previous zone interactions
• FVG lifetime
• retest model
• reaction-strength threshold
• retest delay
• setup expiry
• volume filter settings
• DI / ADX settings
• HTF timeframe and EMA lengths
• minimum setup grade
• stop model
• target multiples
• signal cooldown
• timeframe
• symbol volatility
• market session
• available historical bars
A setting that appears clean on one market may behave differently on another.
A profile that produces suitable frequency on one timeframe may be too strict or too active on another.
Volume behavior can differ across asset classes and data providers.
Higher-timeframe filtering only operates as intended when the selected bias timeframe is genuinely higher than the chart timeframe.
Users should test the exact symbol, timeframe, profile, and session they personally study.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ LIMITATIONS AND SHORTCOMINGS
━━━━━━━━━━━━━━━━━━━━━━
This script has important limitations:
It does not guarantee profitable trades.
It does not predict future price movement.
It does not replace risk management.
It does not execute trades.
It does not place broker orders.
It does not include broker slippage.
It does not include commissions.
It does not include spreads.
It does not include execution delay.
It does not include partial-fill behavior.
It uses bar-based chart data.
Same-candle TP / SL order cannot be known from standard OHLC data.
Same-Candle Priority is a modeling assumption.
Live Preview can change intrabar because the realtime candle is unfinished.
Permanent entry models are committed only after bar close.
Confirmed pivots require future bars before becoming available as confirmed swing points.
The dashboard is not TradingView Strategy Tester.
The internal target-share model is not account-performance reporting.
Historical boxes and completed labels do not guarantee similar future behavior.
Setup grades are internal classifications, not win probabilities.
Filter settings do not guarantee improved future results.
Higher-timeframe values depend on selected timeframe and available data.
Data-feed revisions or chart-history differences can affect historical calculations.
Alert delivery depends on TradingView and the user’s alert configuration.
Webhook delivery also depends on the external destination.
One-active-trade logic is a visual management rule, not broker execution logic.
For these reasons, FVG Retest Entry Engine should be used as an educational decision-support and chart-analysis tool, not as a standalone automated trading strategy.
━━━━━━━━━━━━━━━━━━━━━━
👤 WHO THIS SCRIPT MAY BE USEFUL FOR
━━━━━━━━━━━━━━━━━━━━━━
This script may be useful for traders who:
• study Fair Value Gap retests
• use BOS and CHoCH context
• prefer selected FVGs instead of every raw gap
• want a visible armed-zone workflow
• want to understand why a setup is waiting or blocked
• prefer confirmed-close entries
• want a setup-grade framework
• want Entry, SL, TP1, TP2, and TP3 visualization
• want optional breakeven behavior
• want completed FVG Retest models preserved visually
• use higher-timeframe directional context
• want mobile-friendly chart presentation
• use lifecycle alerts for monitoring
• want a structured educational analysis framework
It may be less suitable for users who:
• want guaranteed buy/sell signals
• want a fully automated trading bot
• want every raw FVG to create an entry
• expect one profile to work on every market
• expect grades to represent guaranteed probability
• require exact tick-level execution simulation
• expect visual projections to match broker fills
• expect alerts to execute trades automatically
• want an indicator to replace independent decision-making
━━━━━━━━━━━━━━━━━━━━━━
🧭 BEST PRACTICE SUGGESTIONS
━━━━━━━━━━━━━━━━━━━━━━
For cleaner review:
• Start with Original Sync or Balanced Flow.
• Keep Signal Timing on Confirmed Close.
• Use Selected Gap to reduce chart clutter.
• Enable Blocker Lens while learning the engine workflow.
• Use Compact Passport for concise context.
• Use Detailed Passport when reviewing why a setup qualified.
• Review the armed FVG before the entry appears.
• Check whether the FVG retest agrees with personal market-structure analysis.
• Evaluate the displayed stop against nearby structure and volatility.
• Treat TP1, TP2, and TP3 as planning references only.
• Keep Protective First when a conservative same-candle assumption is preferred.
• Use Precision Flow when fewer, stricter setups are preferred.
• Use Fast Flow only after understanding its higher signal frequency.
• Use Custom Lab only after learning how each threshold affects the engine.
• Use Mobile layout on smaller screens.
• Use alerts for monitoring, not blind execution.
• Always apply independent analysis, risk management, and position sizing.
━━━━━━━━━━━━━━━━━━━━━━
🔓 PUBLICATION NOTE
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine is published as an educational and visual market-analysis tool.
The purpose of this description is to explain:
• what the script does
• how structure events are confirmed
• how three-candle FVGs are detected
• how FVGs are stored and invalidated
• how structure and FVG candidates are linked
• how an FVG becomes armed
• how retest models work
• how reaction quality is evaluated
• how volume, DI / ADX, and HTF checkpoints operate
• how setup grades are assigned
• how Confirmed Close and Live Preview differ
• how Entry and stop levels are calculated
• how TP1, TP2, and TP3 are projected
• how breakeven and same-candle assumptions work
• how active and completed trade areas behave
• what the Passport and Blocker Lens show
• what the dashboard displays
• what the alert packages do
• what the limitations are
• how the indicator should and should not be used
The script is designed to support structured analysis.
It does not promise profitable results.
It does not remove market risk.
It does not execute trades.
It should not be used as a blind buy/sell system.
It is best used as a visual framework for reviewing structure-linked FVG retests and projected risk/reward behavior.
━━━━━━━━━━━━━━━━━━━━━━
🛡️ DISCLAIMER
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine is provided for educational and informational purposes only.
It does not constitute financial, investment, trading, legal, or tax advice.
No indicator can guarantee future results.
Markets are uncertain, conditions change, and historical behavior does not ensure future performance.
Every user is responsible for their own analysis, validation, risk management, position sizing, alert configuration, trading decisions, and broker execution.
The structure labels, FVG zones, armed-zone states, Passport values, Blocker Lens messages, grades, scores, entry references, stop-loss levels, take-profit levels, TP / SL boxes, dashboard values, completed-model labels, and alerts are visual analysis tools only.
Use this script as a structured decision-support and visual review framework, not as a promise of profitability or a substitute for independent judgment.
Индикатор

Session CVD DivergenceSession CVD Divergence splits Cumulative Volume Delta into three independent session streams (Asian, London, and New York) and automatically detects all four divergence types between price and order flow.
TWO-SCRIPT SETUP
This indicator comes as a pair:
Session CVD Divergence (this script) — add to a new pane. Shows the CVD lines for each session and draws divergence lines between the CVD pivots.
Session CVD — Chart Labels — add as an overlay. Draws the same divergence lines between the price pivots on the main chart, with labels at each signal.
Both scripts must be on the chart together for the full picture. Settings (session times, pivot length, colors) are identical between the two, keep them in sync.
Session CVD Chart Labels:
WHY SESSION-SCOPED CVD?
A standard CVD indicator runs continuously across the entire day. That means London's aggressive buying gets buried inside Asia's quiet accumulation, and by the time New York opens you're reading a blended signal with no session context.
This indicator resets CVD to zero at the open of each session. What you see is the net order flow within that session only, independent of what happened before.
THE FOUR DIVERGENCE TYPES
Regular divergences (reversal signals, solid lines)
BD — Bullish Divergence: price makes a lower low, CVD makes a higher low. Selling pressure is drying up.
BrD — Bearish Divergence: price makes a higher high, CVD makes a lower high. Buying pressure is fading.
Hidden divergences (continuation signals, dashed lines)
hBD — Hidden Bullish Divergence: price makes a higher low, CVD makes a lower low. Uptrend remains intact beneath the surface.
hBrD — Hidden Bearish Divergence: price makes a lower high, CVD makes a higher high. Downtrend continuation despite apparent strength.
Each signal draws a line directly between the two pivots that form the divergence: on the CVD pane between the CVD pivot values, and on the main chart between the price pivot values. Solid lines for reversals, dashed lines for continuations.
SAME-SESSION CONSTRAINT
Divergence is only detected between two pivots that belong to the same session. A CVD pivot from the Asian session and a pivot from the London session are never compared, as their CVD scales are incompatible since each resets independently. This eliminates a significant source of false signals present in most divergence tools.
DELTA APPROXIMATION
Each bar's volume delta is estimated using the close-position formula:
delta = V x ( 2 x (C - L) / (H - L) - 1 )
A bar closing at its high contributes its full volume as buying. A bar closing at its low contributes its full volume as selling. Everything between is proportional.
SETTINGS
Session Boundaries — all session open/close times are configurable in UTC hours. Defaults: Asian 00 to 08, London 08 to 16, NY 13 to 21.
Pivot Detection Bars — controls sensitivity. Lower = more signals. Higher = only major pivots confirmed by more bars on each side.
Regular / Hidden divergence — each type can be toggled independently.
Colors — all four divergence types and all three session lines are individually customizable.
Session background — subtle shading shows which session each bar belongs to.
RECOMMENDED TIMEFRAME
15m to 4H. A warning label appears if the indicator is applied to a daily or higher timeframe.
Индикатор

Индикатор

Market State Forecast Projection EngineThis indicator is a **forecast projection tool**. It looks at the current market environment, searches history for the most similar environments, then plots what usually happened afterward. It is not trying to predict the future with certainty. It is saying: “When the market looked like this before, what tended to happen next?”
The engine defines the current market environment using three things:
* **Trend**, based on moving averages.
* **Momentum**, based on RSI.
* **Volatility**, based on ATR.
Then it finds the closest historical matches, studies their future paths, and draws a forecast line with optional upper and lower bands.
---
## What You See on the Chart
### Forecast Midline
The main forecast line shows the **average path** of the selected historical matches.
In simple terms:
* If similar past situations usually moved higher, the line slopes up.
* If similar past situations usually moved lower, the line slopes down.
* If similar past situations were mixed, the line may be flat or choppy.
### Upper Band
The upper band shows the stronger side of historical outcomes.
It means:
* Some similar historical setups moved better than the average.
* The upper band gives you a visual idea of the upside range from those past examples.
* It is not a guaranteed target.
### Lower Band
The lower band shows the weaker side of historical outcomes.
It means:
* Some similar historical setups moved worse than the average.
* The lower band gives you a visual idea of downside risk from those past examples.
* It is not a guaranteed support level.
### Band Width
The space between the bands matters.
* Tight bands mean historical outcomes were more consistent.
* Wide bands mean historical outcomes were scattered and less reliable.
* A forecast with wide bands should be treated with more caution.
---
## Main Inputs
### Non-Repaint Mode
**Default: On**
This controls whether the forecast uses the live candle or the last completed candle.
Use **Non-Repaint Mode On** when:
* You want more stable signals.
* You want the forecast to update only after the candle closes.
* You care about cleaner historical testing.
Use **Non-Repaint Mode Off** when:
* You want the forecast to react during the current live candle.
* You accept that the forecast may change before the candle closes.
For most use cases, leave this **On**.
---
## Model Group
### Forecast Horizon
This controls how far into the future the indicator projects.
Example:
* On a daily chart, `20` means 20 trading days.
* On a 1-hour chart, `20` means 20 hours.
* On a 5-minute chart, `20` means 20 five-minute candles.
Use a lower value when:
* You are trading short-term moves.
* You want a tighter forecast window.
* You do not want the projection stretched too far.
Use a higher value when:
* You are looking for swing-trade context.
* You want to see the broader projected path.
* You are using higher timeframes.
A practical range is usually:
* `10–20` for shorter-term analysis.
* `20–50` for swing-style analysis.
---
### Search Depth
This controls how much history the engine searches.
Example:
* `1000` means the engine searches roughly 1,000 prior bars.
* `2000` means it searches more history.
* `500` means it searches less history.
Use a higher Search Depth when:
* You want a larger historical sample.
* You are on a short timeframe with lots of bars.
* You want more possible market-state comparisons.
Use a lower Search Depth when:
* You want the model to focus on more recent market behavior.
* You are on a slower chart like daily or weekly.
* You want less influence from older market regimes.
The tradeoff is simple:
* More history gives more examples.
* Less history may be more relevant to the current market regime.
---
### Pattern Matches
This controls how many of the closest historical matches are used.
This is one of the most important inputs.
If set to `30`, the engine finds the **30 closest historical market states** and builds the forecast from those.
Use fewer matches when:
* You want stricter, more specific comparisons.
* You want only the closest historical examples.
* You are okay with a forecast that may be more reactive.
Use more matches when:
* You want a smoother forecast.
* You want less noise from individual examples.
* You want a broader historical sample.
General interpretation:
* `10–20` = stricter, more selective.
* `25–40` = balanced.
* `50+` = broader, smoother, but less specific.
---
### Weight Closer Matches
This controls whether the best matches receive more influence.
When turned **On**:
* The closest historical matches matter more.
* Weaker matches still count, but less heavily.
* The forecast becomes more focused on the most similar examples.
When turned **Off**:
* Every selected match is treated equally.
* The forecast becomes more democratic.
* A very close match and a weaker match have the same influence.
For most users, leave this **On**.
---
## Advanced Model Inputs
### Forecast Model
This chooses how the engine defines the market environment.
All models use:
* EMA trend.
* RSI momentum.
* ATR volatility.
The difference is how each model emphasizes those ingredients.
---
### Conservative
Use **Conservative** when you want a slower, smoother model.
It is designed to:
* React less aggressively.
* Favor more stable market environments.
* Put more importance on trend and volatility.
* Reduce noisy forecast changes.
Best for:
* Daily charts.
* Swing trading.
* Slower-moving stocks or ETFs.
* Users who want fewer false shifts.
---
### Balanced
Use **Balanced** as the general-purpose default.
It is designed to:
* Give trend, momentum, and volatility a normal balance.
* Work across many markets.
* Avoid being too slow or too fast.
Best for:
* Most users.
* Most chart timeframes.
* General market forecasting.
* Starting point before testing other models.
---
### Aggressive
Use **Aggressive** when you want a faster model.
It is designed to:
* React more quickly to changing momentum.
* Give more influence to short-term market shifts.
* Be more sensitive to fresh moves.
Best for:
* Intraday trading.
* Fast-moving markets.
* Crypto.
* Momentum names.
* Traders who want earlier, more responsive shifts.
The downside is that it may be noisier.
---
### Trend Following
Use **Trend Following** when you want the model to emphasize persistent directional moves.
It is designed to:
* Care more about trend structure.
* Care less about short-term momentum noise.
* Favor markets that continue moving in the same direction.
Best for:
* Strong trending stocks.
* Indexes.
* Breakout environments.
* Higher-timeframe directional trading.
This model is less ideal in sideways or choppy markets.
---
### Mean Reversion
Use **Mean Reversion** when you want the model to focus on stretched conditions.
It is designed to:
* Emphasize momentum extremes.
* Look for environments where price may snap back or reverse.
* Care less about long-term trend persistence.
Best for:
* Range-bound markets.
* Overbought/oversold setups.
* Countertrend analysis.
* Shorter-term reversal ideas.
This model may fight strong trends, so use it carefully in momentum-heavy markets.
---
## Historical Lookback Inputs
### Lookback Bars
This lets you move the forecast backward in time.
Example:
* `0` means current forecast.
* `50` means show what the forecast would have looked like 50 bars ago.
* `250` means show what the forecast would have looked like 250 bars ago.
Use this for:
* Visual backtesting.
* Studying old setups.
* Checking whether the forecast was useful historically.
* Comparing forecast paths against what actually happened.
This is one of the most valuable testing features.
---
### Lock to Candle
This lets you anchor the forecast to a specific candle time instead of a simple bar offset.
Use it when:
* You want to test a specific time of day.
* You trade a regular session open.
* You want repeatable historical anchors.
Example:
* You can lock to the 13:30 UTC candle, which often corresponds to the U.S. stock market open during daylight saving time.
When this is off, the indicator uses **Lookback Bars** instead.
---
### Days Back
This works with **Lock to Candle**.
It tells the indicator how many matching anchor candles to go back.
Example:
* `0` = most recent matching candle.
* `1` = one matching session back.
* `2` = two matching sessions back.
Use this when:
* You want to test the most recent open.
* You want to test yesterday’s open.
* You want to step through past sessions one by one.
---
### Hour UTC
This is the UTC hour used for candle locking.
Use it with **Minute UTC** to identify the exact candle you want.
Example:
* `13` means 13:00 UTC.
* Combined with `30`, it means 13:30 UTC.
This is useful because TradingView symbols and sessions can vary, but UTC gives a consistent anchor.
---
### Minute UTC
This is the UTC minute used for candle locking.
Example:
* Hour UTC = `13`
* Minute UTC = `30`
Together, that means:
* Lock to the 13:30 UTC candle.
Use this for precise historical testing.
---
### Auto Previous Session
This controls what happens if today’s target candle has not printed yet.
When turned **On**:
* The indicator automatically uses the most recent previous matching candle.
* This keeps the forecast visible even before today’s target time exists.
When turned **Off**:
* If today’s target candle has not printed, the lock may show no match and fall back.
For most users, leave this **On**.
---
## Bias Logic Inputs
### Bias Threshold %
This controls how strong the bull or bear probability must be before the indicator labels the forecast bullish or bearish.
Example:
* If Bias Threshold is `60`, Bull Probability must be at least 60% before a bullish label can appear.
* If Bear Probability is at least 60%, a bearish label can appear.
Use a lower threshold when:
* You want more frequent bias labels.
* You are okay with weaker directional evidence.
Use a higher threshold when:
* You want stricter signals.
* You only want stronger historical agreement.
Practical range:
* `60%` = balanced.
* `70%+` = more conservative.
* `50–55%` = loose and more signal-heavy.
---
### Minimum Bull/Bear Edge %
This controls how large the gap must be between Bull Probability and Bear Probability.
Example:
* Bull Probability = 65%
* Bear Probability = 35%
* Edge = 30 percentage points
If the minimum edge is `15`, this would qualify.
But:
* Bull Probability = 58%
* Bear Probability = 42%
* Edge = 16 percentage points
This may still fail if Bull Probability is below the Bias Threshold.
This input prevents weak differences from being labeled as strong directional bias.
Use a higher edge when:
* You want cleaner bias labels.
* You want the model to avoid borderline calls.
Use a lower edge when:
* You want more frequent directional bias.
* You accept more uncertainty.
---
## Display Inputs
### Show Forecast Midline
This turns the main forecast line on or off.
Turn it **On** when:
* You want to see the projected average path.
Turn it **Off** when:
* You only want the info box probabilities.
* You want a cleaner chart.
---
### Show Confidence Bands
This turns the upper and lower forecast bands on or off.
Turn it **On** when:
* You want to see the historical range of outcomes.
* You care about uncertainty.
* You want to know whether the forecast is tight or messy.
Turn it **Off** when:
* You only want the central forecast.
* The chart feels too cluttered.
---
### Band Width Multiplier
This controls how wide the bands are.
Higher values make the bands wider.
Lower values make the bands tighter.
Use lower values when:
* You want a cleaner, tighter visual range.
* You want bands closer to the average forecast.
Use higher values when:
* You want to see a broader range of historical outcomes.
* You want a more conservative uncertainty envelope.
Default `1.0` is a good starting point.
---
## Forecast Midline Style Inputs
### Forecast Midline Color
Controls the color of the main projection line.
The default aqua color makes it visually distinct from price candles.
### Forecast Midline Width
Controls how thick the midline is.
Use a thicker line when:
* You want the forecast to stand out.
* You are using a busy chart.
Use a thinner line when:
* You want a cleaner chart.
* You use many overlays.
### Forecast Midline Type
Controls whether the line is:
* Solid.
* Dashed.
* Dotted.
Solid is usually best for the main forecast line.
---
## Upper Band Style Inputs
### Upper Band Color
Controls the color of the upper forecast band.
The default green tone suggests upside range.
### Upper Band Width
Controls how thick the upper band is.
A thin dashed line usually works best because it should be secondary to the midline.
### Upper Band Type
Controls whether the upper band is solid, dashed, or dotted.
Dashed is usually best because it visually communicates “range” rather than “target.”
---
## Lower Band Style Inputs
### Lower Band Color
Controls the color of the lower forecast band.
The default red tone suggests downside range.
### Lower Band Width
Controls how thick the lower band is.
A thin line keeps it useful without dominating the chart.
### Lower Band Type
Controls whether the lower band is solid, dashed, or dotted.
Dashed is usually best for the same reason as the upper band.
---
## Info Box Inputs
### Show Info Box
This turns the dashboard on or off.
Turn it **On** when:
* You want the probabilities and diagnostics visible.
* You are actively evaluating the forecast.
Turn it **Off** when:
* You only want the chart projection.
* You want a cleaner visual layout.
---
### Info Box Position
Controls where the dashboard appears.
Options:
* Top Left.
* Top Right.
* Bottom Left.
* Bottom Right.
Use the position that interferes least with price action on your chart.
---
### Text Size
Controls the dashboard text size.
Use:
* **Tiny** for compact charts.
* **Small** for normal use.
* **Normal** if you want easier reading.
* **Large** for presentations or large monitors.
---
### Background
Controls the info box background color.
A darker background usually works best on most TradingView chart themes.
### Border
Controls the info box border color.
This helps separate the dashboard from the chart.
### Header Text
Controls the title/header text color.
### Header Background
Controls the top header row background.
This gives the dashboard its polished look.
---
## Info Box Metrics
### Bull Prob %
This shows the weighted percentage of selected historical matches that ended bullish.
Simple meaning:
> Of the similar historical market states, how many tended to move up?
A high number means bullish outcomes dominated the selected historical matches.
---
### Bear Prob %
This shows the weighted percentage of selected historical matches that ended bearish.
Simple meaning:
> Of the similar historical market states, how many tended to move down?
A high number means bearish outcomes dominated the selected historical matches.
---
### Direction Bias
This shows the final label after applying the bias rules.
Possible outputs:
* Bullish.
* Bearish.
* None.
* Weak Data.
* No Matches.
A bullish or bearish label only appears when the probability and edge requirements are met.
---
### Bull/Bear/Flat
This shows how many selected matches ended:
* Bullish.
* Bearish.
* Flat.
Example:
* `18 / 9 / 3`
This means:
* 18 bullish historical outcomes.
* 9 bearish historical outcomes.
* 3 flat historical outcomes.
This gives you a quick look at the underlying distribution.
---
### Match Count
This shows how many historical matches were actually used.
If Pattern Matches is set to `30`, Match Count should usually show `30`.
If it shows less, there may not have been enough valid historical data.
---
### Fit Quality
This tells you how closely the selected historical matches resemble the current market state.
High Fit Quality means:
* The current market environment closely resembles the selected historical examples.
Low Fit Quality means:
* The engine found matches, but they were not very close.
Important:
* Fit Quality is not win rate.
* Fit Quality is not probability.
* Fit Quality is not accuracy.
* It only measures how good the historical comparisons are.
Best interpretation:
* High Fit Quality + strong Bull/Bear Probability = more compelling.
* High Fit Quality + split probabilities = similar markets existed, but outcomes were mixed.
* Low Fit Quality = be cautious.
---
### Model
This shows which Forecast Model is active.
Examples:
* Balanced.
* Conservative.
* Aggressive.
* Trend Following.
* Mean Reversion.
This is useful for screenshots and reviewing past setups.
---
### Anchor
This tells you where the forecast is anchored.
Examples:
* `0 bars · NR` means current forecast using Non-Repaint Mode.
* `50 bars · NR` means historical forecast from 50 bars ago.
* `Locked` means it is anchored to a specific UTC candle.
This helps you know whether you are looking at a current forecast or a historical replay.
---
### Search Depth
This shows the actual number of bars being searched.
It may be lower than your input if the chart does not have enough loaded history.
---
## Best Practical Way to Use It
A clean workflow would be:
* Start with **Balanced** model.
* Keep **Non-Repaint Mode On**.
* Use **Pattern Matches around 30**.
* Use **Search Depth around 1000**.
* Watch **Fit Quality**.
* Watch **Bull/Bear Probability**.
* Treat the forecast line as a scenario path, not a guaranteed prediction.
* Use **Lookback Bars** to test whether the forecast was historically useful.
* Avoid trusting any forecast where the bands are very wide and probabilities are split.
The strongest setup is usually when:
* Fit Quality is high.
* Bull or Bear Probability is clearly dominant.
* The forecast bands are not extremely wide.
* The projection agrees with price structure.
Индикатор

Swing Gradient TPOs [BOSWaves]Swing Gradient TPOs - Swing-Anchored Time Price Opportunity Profiles with Gradient Chronology and Single Print Detection
Overview
Swing Gradient TPOs is a swing-anchored market profile system that constructs Time Price Opportunity profiles within each detected swing range, where letter assignment, gradient coloring, POC identification, and single print detection are driven by chronological time period progression across the swing rather than fixed session boundaries or arbitrary time windows.
Instead of applying TPO profiles to calendar sessions or user-defined time blocks, this system anchors each profile to the confirmed swing structure of the instrument itself, building a complete letter-by-letter participation map for every swing from high to low and low to high. Each time period within the swing receives a sequential alphabetical letter, and those letters are colored using a configurable gradient that visually encodes the chronological progression of price activity from swing origin to completion.
This creates a profile framework that reflects how participation distributed across price within each structural swing rather than within arbitrary time containers. The gradient coloring reveals whether price visited certain levels early or late in the swing's development, the POC identifies the price level with the greatest time-based participation, the value area captures the range containing the configured percentage of total activity, and single print zones mark levels touched by only a single time period and project them forward as potential reaction areas until price revisits them.
Price structure and participation distribution are therefore evaluated together, with each swing producing a self-contained profile that answers both where price spent time and when within the swing that activity occurred.
Conceptual Framework
Swing Gradient TPOs is founded on the principle that TPO-based market profile analysis becomes structurally meaningful when profiles are anchored to confirmed swing boundaries rather than to session times that carry no relationship to the instrument's actual directional behavior.
Traditional market profile approaches build TPO distributions within daily or weekly sessions, which imposes a time container on the data that is independent of how price is actually behaving structurally. This framework replaces session-based profile construction with swing-event-driven profile building, where each profile begins at a confirmed swing extreme and ends at the next confirmed swing extreme in the opposing direction, ensuring the participation map covers exactly one complete directional structural move.
Three core principles guide the design:
TPO profiles should be anchored to swing structure rather than calendar time, ensuring each profile captures participation within a single directional move rather than across an arbitrary time boundary that may span multiple structural events.
Gradient coloring should encode chronological letter progression visually, revealing whether price visited particular levels early or late in the swing rather than treating all activity within the swing as temporally equivalent.
Single print zones represent structurally significant levels visited by only one time period and should be projected forward as active reference areas until price returns to test them, at which point reclaim or rejection behavior provides actionable signal context.
This shifts market profile analysis from session-container-based participation tracking into swing-anchored structural profile construction with gradient-encoded temporal intelligence and forward-projecting single print monitoring.
Theoretical Foundation
The indicator combines swing high and low detection through highest and lowest lookback comparison, alphabetical letter assignment by configurable TPO timeframe period, three-color gradient interpolation for chronological letter coloring, POC identification through maximum TPO count per price bin, value area expansion from POC outward, single print detection and forward projection, and retest signal generation when price sweeps and reclaims a single print zone.
Swing detection tracks whether the most recent extreme high or low is the highest or lowest reading in the lookback window, registering a swing point when price rotates away from a prior extreme. TPO letter assignment maps each bar within the swing to a time period based on the ratio between the chart timeframe and the configured TPO timeframe, with sequential alphabet letters A through Z then a through z assigned chronologically across the swing's duration. Gradient coloring maps each letter's alphabetical index to a position along a three-stop gradient, producing a color sequence that progresses from swing start to swing end. Price bins are calculated from the swing range divided into segments sized relative to recent ATR, with each bin's letter count determining POC and value area membership.
Four internal systems operate in tandem:
Swing Detection Engine : Tracks highest and lowest readings over the configurable lookback window, registering confirmed swing highs and lows when price rotates away from prior extremes and triggering profile construction on each swing direction change.
TPO Profile Builder : Assigns sequential alphabetical letters to time periods within each swing, maps each bar's high and low range to the appropriate price bins, accumulates letter strings and counts per bin, and derives POC and value area from the resulting distribution.
Gradient Chronology Engine : Maps each letter's sequential index to a position along a configurable three-stop gradient, producing coloring that encodes when within the swing each price level was visited rather than applying uniform directional color across the entire profile.
Single Print Detection and Signal System : Identifies price bins touched by exactly one time period letter, projects those zones forward as extended boxes until price revisits them, monitors for sweep-and-reclaim behavior with configurable cooldown, and generates directional retest signals when qualifying conditions are met.
This design allows each swing to produce a complete participation profile with temporal depth encoded visually, while structurally significant single print zones remain active as forward reference areas with signal generation capability.
How It Works
Swing Gradient TPOs evaluates price through a sequence of structure-aware and profile-building processes:
Swing Direction Tracking : On each bar, price is compared against the highest high and lowest low over the configured lookback. When the current high matches the lookback high, the swing is classified as transitioning to a downswing. When the current low matches the lookback low, it is classified as transitioning to an upswing.
Swing Point Registration : When price rotates away from a prior extreme, the swing point price and bar index are recorded for both highs and lows independently, maintaining the most recent confirmed swing high and low as profile anchors.
Profile Build Trigger : When swing direction changes, a profile build is triggered using the recorded swing high and low as boundaries, constructing the complete TPO distribution for the completed swing.
Price Bin Calculation : The swing range is divided into bins sized relative to a smoothed ATR-derived tick amount, capped at 80 bins to maintain visual clarity and computational efficiency.
Letter Assignment and Accumulation : Each bar within the swing is mapped to a time period letter based on the ratio of the configured TPO timeframe to the chart timeframe. For each bar, its high and low determine which price bins it touches, and the period letter is appended to each qualifying bin's letter string if not already present.
POC Identification : The bin with the greatest accumulated letter count is identified as the Point of Control, representing the price level with the most time-based participation across the swing.
Value Area Expansion : Starting from the POC bin, the value area expands outward by adding the adjacent bin with the greater letter count, continuing until the accumulated count reaches the configured value area percentage of total swing activity.
Gradient Color Mapping : Each letter's alphabetical index is divided by the maximum period index to produce a normalized position along the three-stop gradient, assigning colors that progress from the gradient start color early in the swing to the gradient end color late in the swing.
Single Print Identification and Projection : Bins with exactly one letter in their string are classified as single prints and, when the extension setting is enabled, receive forward-projecting zone boxes that extend rightward on each bar until price enters the zone.
Single Print Sweep and Reclaim Detection : When price enters a single print zone the zone is marked as swept. If price then exits the zone in the opposing direction and closes beyond the zone boundary with sufficient cooldown observed, a directional retest signal is generated.
Real-Time Profile Rendering : On the last bar, the developing swing from the most recent confirmed extreme to current price is rendered as a live TPO profile that updates with each new bar, providing a continuously refreshing participation map for the current incomplete swing.
Together, these elements form a continuously updating swing profile system where each completed swing produces a gradient-encoded participation map, single print zones project forward as active structural references, and retest signals identify price reclaims of structurally thin areas.
Interpretation
Swing Gradient TPOs should be interpreted as a swing-anchored participation distribution system with temporal depth encoding and forward-projecting structural reference zones:
TPO Letter Boxes : Each lettered box represents a single time period's visit to that price level within the swing. The letter itself identifies which time period made the visit, and the gradient color reveals where in the swing's chronological sequence that period falls.
Gradient Coloring : The gradient progression from swing start to swing end colors early-swing activity in the gradient start color and late-swing activity in the gradient end color, visually encoding whether price visited each level early or late in the structural move.
Point of Control (POC) : The horizontal line through the price level with the most accumulated TPO letters represents the level where price spent the greatest amount of time within the swing, acting as a gravitational reference for the swing's dominant auction zone.
Value Area : The vertical line at the swing origin spanning the value area high and low with dotted horizontal boundary projections marks the price range containing the configured percentage of total swing TPO activity, identifying the zone of concentrated acceptance during the swing.
Single Print Zones (Highlighted) : Price bins touched by exactly one time period letter are visually distinguished within the profile, indicating levels that price passed through quickly without sustained participation, representing structurally thin areas vulnerable to future reaction.
Single Print Extensions (Projected) : When extension is enabled, single print zones project forward as shaded boxes beyond the swing boundary, maintaining active visual reference until price revisits the zone and the extension is consumed.
Retest Signals : Arrow signals generated when price sweeps through an extended single print zone and then reclaims it by closing beyond the zone boundary, identifying potential continuation opportunities at structurally thin levels that have now been tested and defended.
Real-Time Profile : The developing profile on the current incomplete swing updates continuously with each new bar, providing a live participation map anchored to the most recent confirmed swing extreme using the same gradient, POC, and value area logic as completed historical swings.
POC location, value area boundaries, gradient temporal distribution, and single print zone positioning collectively provide more structural and participatory intelligence than any element in isolation.
Signal Logic & Visual Cues
Swing Gradient TPOs presents two retest signal types derived from single print zone interaction:
Bullish Single Print Reclaim : Generated when price sweeps into a bullish single print zone from an upswing and subsequently closes above the zone's upper boundary, indicating the structurally thin area has been swept and reclaimed with bullish resolution.
Bearish Single Print Rejection : Generated when price sweeps into a bearish single print zone from a downswing and subsequently closes below the zone's lower boundary, indicating the structurally thin area has been swept and rejected with bearish resolution.
Both signal types require the zone to have been swept before reclaim or rejection can register, and a configurable cooldown enforces minimum bar separation between consecutive signals to prevent clustering during active zone interaction.
Alert generation covers completed swing high and swing low events as well as bullish and bearish single print reclaim signals for systematic structural and zone-based monitoring workflows.
Strategy Integration
Swing Gradient TPOs fits within market profile-informed and structure-based participation analysis approaches:
POC Reaction Trading : Monitor price behavior when it returns to a prior swing's POC level. The POC represents the most accepted price within the swing and frequently acts as a reference for future support, resistance, or reversion behavior.
Value Area Boundary Framing : Use value area high and low projections as structural boundary references, with price outside the value area representing potential imbalance and price returning to the value area suggesting reversion toward prior acceptance.
Single Print Zone Trading : Use extended single print zones as anticipatory structural references, monitoring price behavior on approach for the sweep-and-reclaim or sweep-and-reject patterns that trigger retest signals.
Gradient Temporal Analysis : Use gradient distribution within each swing to assess whether participation at key levels occurred early or late in the move. Heavily late-swing activity at a level suggests climactic behavior, while early-swing concentration may indicate initial acceptance or rejection zones.
Real-Time Profile Monitoring : Use the developing live profile to assess current swing participation distribution in real time, identifying emerging POC levels and single prints within the active structural move before it completes.
Multi-Swing Profile Comparison : Compare POC locations, value area widths, and single print density across successive swings to assess whether participation is concentrating or dispersing as the broader trend develops.
Technical Implementation Details
Swing Detection : Highest and lowest lookback comparison with direction tracking and confirmed extreme registration on price rotation
TPO Construction : Alphabetical letter assignment by timeframe-ratio-derived period with per-bin letter string accumulation and count tracking
Profile Analytics : Maximum count POC identification, outward value area expansion to configurable percentage threshold, and single print bin classification
Gradient Engine : Three-stop gradient interpolation with letter index normalized to maximum period for chronological color mapping
Single Print System : Array-managed forward-projecting zone boxes with sweep state tracking, reclaim direction testing, and cooldown-gated signal generation
Real-Time Rendering : Last-bar-triggered live profile construction rebuilding on every bar update with independent box and line arrays cleared and redrawn each render cycle
Visualization : Per-letter TPO boxes with gradient, POC, and value area coloring, POC dual-line overlay, value area vertical and horizontal boundary lines, single print zone extensions, and retest signal arrows
Performance Profile : Optimized with calc_bars_count and max_bars_back configuration and array size caps for object management across extended histories
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Intraday swing profile mapping with shorter swing length and faster TPO timeframe for responsive participation tracking within intraday structural moves
15 - 60 min : Session-level swing profile analysis with balanced swing length and TPO timeframe producing meaningful letter distributions across typical session swings
4H - Daily : Swing-level structural participation mapping with longer swing detection and higher TPO timeframe for profiles that reflect multi-day directional move participation
Suggested Baseline Configuration:
Swing Length : 12
TPO Timeframe : 30
Box Width : 2
Show POC : Enabled
Show Value Area : Enabled
Value Area % : 70
Gradient Preset : Sunset
Highlight Single Prints : Enabled
Extend Single Prints : Enabled
Show Retest Signals : Enabled
Signal Cooldown : 5
These suggested parameters should be used as a baseline; their effectiveness depends on the instrument's swing frequency, typical swing range, and preferred profile granularity, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Swings too frequent : Increase Swing Length to require more bars on each side of an extreme before it registers as a confirmed swing point, filtering minor oscillations and producing fewer, more structurally significant profiles.
Swings too infrequent : Decrease Swing Length toward 10 for more sensitive swing detection, producing profiles on smaller structural moves within the overall trend.
Too few letters per profile : Decrease TPO Timeframe to assign letters to shorter time periods, increasing letter density within each swing and producing more granular participation distributions.
Too many letters cluttering the profile : Increase TPO Timeframe so each letter covers a longer period, reducing letter density and producing cleaner, more readable profiles on the target timeframe.
Profile bins too coarse : The bin count derives from the swing range divided by a smoothed ATR-based tick size. On instruments with large typical bar ranges relative to the swing, the profile may appear coarse. Consider using a higher timeframe chart or adjusting swing length to capture larger swings with more granular bin resolution.
Too many single print signals : Increase Signal Cooldown to enforce greater bar separation between consecutive retest signals, or increase Swing Length to produce swings with fewer single print zones through greater overall participation density.
Single print extensions cluttering the chart : Disable Extend Single Prints to remove forward projection boxes while retaining single print highlighting within the historical profile, or reduce Max Zones (capped internally at 50) by allowing older zones to naturally expire as price revisits them.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
Trending markets with clear directional swings where each profile captures a single sustained move and produces meaningful POC and value area levels that serve as ongoing structural references
Instruments with sufficient intrabar participation where TPO letter accumulation produces well-distributed profiles with identifiable concentration zones rather than sparse single-print-dominated structures
Market profile-based trading approaches that benefit from swing-anchored rather than session-anchored participation context, aligning profile boundaries with actual structural events
Single print zone strategies where structurally thin levels within completed swings provide anticipatory reference areas for future price reactions with defined signal criteria
Reduced Effectiveness:
Choppy, low-range markets where frequent swing direction changes produce thin profiles with minimal letter accumulation and limited POC or value area differentiation
Extremely fast-moving instruments where swing ranges are so large relative to the TPO timeframe that letters are thinly distributed across a wide range, reducing profile interpretive value
Low-liquidity instruments where participation is insufficient to produce meaningful time-at-price distributions, resulting in profiles dominated by single prints with no identifiable acceptance zones
Markets where the relationship between swing structure and participation distribution is inconsistent, reducing the reliability of POC and value area levels as structural references across successive swings
Very short timeframe charts where the ratio between chart timeframe and TPO timeframe produces insufficient letter differentiation to build interpretable profiles within typical swing durations
Integration Guidelines
Confluence : Combine with BOSWaves structural tools, order flow analysis, or momentum indicators to validate POC and value area reactions with broader analytical context before acting on profile-based reference levels
POC Migration Awareness : Track whether POC levels across successive swings are migrating higher, lower, or remaining stable as a secondary indicator of directional participation bias beyond raw trend direction
Single Print Zone Patience : Allow single print zones to extend and be approached naturally rather than anticipating reactions prematurely. The sweep-and-reclaim or sweep-and-reject sequence that triggers signals requires zone interaction to complete before directional evidence is confirmed.
Gradient Reading : Use gradient distribution within profiles to contextualize POC and value area location. A POC formed late in the gradient sequence suggests late-swing acceptance, potentially indicating exhaustion. An early-forming POC suggests early directional commitment that may carry more structural weight.
Real-Time Profile Monitoring : Treat the live developing profile as probabilistic rather than confirmed. POC and value area locations in the real-time profile will shift as new bars are added and should be interpreted as dynamic rather than fixed until the swing completes and the historical profile is committed.
Disclaimer
Swing Gradient TPOs is a professional-grade swing-anchored market profile and structural participation analysis tool. It uses TPO letter accumulation with gradient chronology encoding and single print zone projection but does not predict future price movements. Results depend on market conditions, instrument participation characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates momentum context, order flow analysis, and comprehensive risk management. Индикатор

SAO RUBIQ Regime v2# SAO · RUBIQ — Regime Visualizer (v2)
**by SNP420 · Jarvis Claudos · Finexus s.r.o.**
*Pine Script v6 · Build 2026-05-26*
---
## What is it
A research-grade market regime overlay that classifies every confirmed
bar into one of **five regimes** and paints the chart accordingly.
Born out of a simple insight:
> *"The right algorithm in the wrong phase of the market still fails —
> even when it is 100% correct under ideal conditions."*
This is the central thesis of the **SAO · RUBIQ** project: every
strategy lives or dies inside a specific regime × timeframe cell.
Without active regime perception, every trading system is necessarily
under-performing on the bars it was not designed for. This indicator
makes those cells visible.
## What's new in v2
v2 throws out the v1 AND-stack of ADX / BB-width / drift cutoffs and
replaces it with four orthogonal signals that vote together:
- **Fractal pivots** (3-bar centered) labeled **HH / LH / HL / LL**
- **Trend state machine** with **re-anchoring**:
UP / DOWN / RANGE / REVERSAL_UP / REVERSAL_DOWN
- **Multi-TF RSI** on M30 / H1 / H4 / D1 / W1 with per-TF thresholds
and a **≥3 of 5 agreement** rule
- **S/R level clustering** (±0.3 ATR tolerance) with **double-bounce**
reversal flag that persists for 10 bars
Measured improvements over v1.1 on EUR/USD M30, 2024-2025 (24,863 bars):
| Metric | v1.1 calibrated | v2 |
| ----------------------- | --------------- | ----------- |
| Confident coverage | 44.87% | **53.96%** |
| Transitions (less whipsaw) | 1,567 | **855** |
| BULL_CALM Sharpe (h=5) | +0.085 | **+0.271** |
| BEAR_CALM direction | +0.04 ⚠ (wrong)| **−0.19 ✅** |
| Shuffle F-stat (h=5) | 0.0027 | **0.0068** |
| Strategy diagonal score | 1 / 5 | **2 / 5** |
All validated by 1000-iter shuffle Monte Carlo (p < 0.001) and a
strategy × regime P&L matrix.
## The five regimes
| Regime | Meaning |
| ------------- | -------------------------------------------------------- |
| **BULL_CALM** | Trend UP + ≥3 of 5 RSI TFs agree bullish |
| **BEAR_CALM** | Trend DOWN + ≥3 of 5 RSI TFs agree bearish |
| **RANGE** | Mixed last pivots (no clean HH+HL or LH+LL) |
| **CHOPPY** | Trend UP/DOWN without RSI agreement, or active reversal |
| **STRESS** | Volatility spike: rv20_norm > 2 OR atr_z > 2 |
| *UNCERTAIN* | Fallback — pre-warmup or no labels yet (no box drawn) |
Priority order (highest wins): **STRESS > BULL > BEAR > CHOPPY > RANGE.**
## How it works
For every confirmed bar the indicator:
1. Computes ATR(14), realized vol (20), z-scored ATR — used by stress
detection and S/R cluster tolerance.
2. Requests RSI(14) on five timeframes via `request.security`
(M30 / H1 / H4 / D1 / W1) and counts bull / bear agreements.
3. Detects fractal pivots with `ta.pivothigh / pivotlow(3, 3)` and
labels each as HH / LH / HL / LL versus the previous same-type
pivot.
4. Adds each pivot to a greedy S/R level cluster (±0.3 ATR). On the
second touch within 500 bars it fires a **double-bounce reversal**
flag (type H → REVERSAL_DOWN, type L → REVERSAL_UP) that persists
for 10 bars.
5. Maintains a trend state machine: **UP** when last H=HH and last L=HL,
**DOWN** when last H=LH and last L=LL, **RANGE** otherwise.
6. Combines trend × RSI × stress into the final label, then applies
a hysteresis smoother (`min_run = 5 bars`) so single-bar flips
never get committed.
## Visualization (FX-Sessions-style)
- **Dashed segment box** per confirmed regime run, sized to that
segment's high/low.
- **Background tint** — semi-transparent regime color over the span.
- **Bar color** (off by default) — paints OHLC bars with regime color.
- **Segment label** anchored to the top of each box.
- **Pivot markers** — HH / LH / HL / LL drawn at every confirmed pivot
with bull/bear tint.
- **Reversal arrows** — ▲ green at support double-bounces, ▼ red at
resistance double-bounces.
- **Info table** (top-right) — current state, trend, last H and L labels,
RSI per TF, bull/bear agree counts, rv20_norm, atr_z.
- **Stats table** (bottom-right) — N bars and % share per regime across
the visible history.
UNCERTAIN bars deliberately render no box and no tint (clean chart).
## Settings worth knowing
- **Hysteresis min_run** (5) — bars of consistent raw state before
commit. Bigger = less flicker, more boundary lag.
- **Pivot left/right** (3) — fractal pivot window. Smaller catches
more pivots but more noise.
- **Per-TF RSI thresholds** — defaults are 65/35 (M30), 62/38 (H1),
60/40 (H4), 55/45 (D1), 50/50 (W1). Overridable per pair / TF.
- **RSI agree min** (3) — TFs that must agree to qualify as
BULL_CALM / BEAR_CALM. Lower = more sensitive.
- **S/R cluster tolerance** (0.3 × ATR) — width of an S/R level zone.
- **S/R max age** (500 bars) — oldest first-touch still eligible for
double-bounce reversal.
- **Reversal persistence** (10 bars) — how long after the second touch
the REVERSAL state stays active.
- **Max active S/R levels** (200) — FIFO ceiling on level memory.
- **All six regime colors + reversal arrow colors** — fully overridable.
## Sanity-check expectation (EUR/USD M30, 2 years)
If the v2 baseline distribution holds on your data window:
| State | Share |
| --------- | ------ |
| BULL_CALM | ~2.6% |
| BEAR_CALM | ~1.8% |
| RANGE | ~2.4% |
| CHOPPY | ~38.7% |
| STRESS | ~8.4% |
| UNCERTAIN | ~46.0% |
v2 deliberately has stricter BULL / BEAR (needs trend state + 3-of-5
RSI agreement) and a wider CHOPPY (catches trend bars without RSI
agreement + all active reversals). Cleaner regime blocks, better
direction mapping.
## Honest limitations — please read
- **Tuned to EUR/USD M30 vol scale.** Features and rules are
TF-agnostic in math, but the thresholds were calibrated on M30.
On H1 / D1 / crypto / equities the distribution will be approximate
unless you re-tune.
- **v2 direction mapping is improved but not perfect.** Diagonal
score = 2 / 5 (vs 1 / 5 in v1.1). BULL_CALM and BEAR_CALM now point
the right way; RANGE drifts slightly up; CHOPPY and STRESS still
show counter-intuitive mean-reversion edge. **Treat the indicator
as a labeled regime overlay for research, not a stand-alone
trade-direction signal.**
- **Streaming lags exist.** Pivot detection lag ≈ 3 bars,
hysteresis commit lag ≈ `min_run − 1` bars, multi-TF RSI uses
`lookahead=barmerge.lookahead_off` so higher-TF RSI updates only on
higher-TF bar close.
- **S/R level memory capped at 200 (FIFO).** The Python reference
keeps levels unbounded; on very long charts you may see different
bounce decisions than the offline version near the cap.
## Alerts
Seven alert conditions ship in:
- Regime → STRESS
- Regime → BULL_CALM
- Regime → BEAR_CALM
- Regime → RANGE
- Regime → CHOPPY
- Double-bounce UP (support held, second touch)
- Double-bounce DOWN (resistance held, second touch)
Regime alerts fire on transition (state differs from previous bar).
Double-bounce alerts fire at the second-touch bar of any cluster.
## Credits & attribution
- **Visual style** inspired by *FX Market Sessions* by **boitoki**
(Mozilla Public License 2.0). The segment-box-per-run pattern is
borrowed from that script; all classifier logic, feature math,
pivot state machine and S/R clustering is original to SAO · RUBIQ.
- **RUBIQ thesis** — *Rubik's-cube model of the market*: the right
algorithm in the wrong market phase still fails. Distilled from
100+ failed variants across the SAO portfolio.
- **Built by** SNP420 · Jarvis Claudos · Finexus s.r.o.
## License
Same as the parent SAO_RUBIQ project. Use freely, modify freely,
attribute when republishing.
---
*"Trh je proměnlivé prostředí. RUBIQ je centrální nervová soustava,
která to řeší pro všechny SAO strategie."*
— SNP420
Индикатор

Simple MA TPO
Simple MA TPO
■Description
■Concept & Purpose
This indicator was developed with a single core concept: to discover the "true power" and foster a deeper understanding of the Time Price Opportunity (TPO) profile—often considered a super-tool in market analysis. By combining traditional TPO mechanics with market gravity (Moving Averages), this script aims to provide traders with a clearer, more visual representation of value and price deviation over time.
■Originality & How It Works
While traditional TPO profiles use letters (A, B, C...) to denote time periods and static colors for volume/time areas, this script introduces two highly original mechanics to add value to the community:
Sequential Numbering: Instead of letters, each TPO block is numbered sequentially (1, 2, 3...) based on its formation order. This drastically simplifies reading the flow of time within a session.
MA Deviation Gradient Coloring: The most unique feature is its coloring logic. TPO blocks are not colored randomly. Instead, their color is determined by their deviation from a baseline Moving Average (acting as the market's center of gravity).
■Calculations & Output
To ensure complete transparency in how the visual data is generated, here is the specific calculation used for the block colors:
Formula: Deviation % = ((Price / MA) - 1.0) * 100.0
Why this calculation? This calculates the exact percentage distance between the TPO block's price level and the baseline Moving Average at the time that specific block was formed. It visualizes how "overextended" the market was when time was spent at that price.
Actual Output: The output is a percentage float value (e.g., if the MA is $100 and the block price is $102, the output is 2.0 or 2%). This value is then clamped by the user-defined Max Deviation % input (default 2.0%).
Color Mapping: The clamped percentage is fed into a gradient. Negative deviations (undervalued relative to MA) shift towards Cyan, while positive deviations (overvalued) shift towards Magenta.
■How to Use
Identify Value Areas: Look for the "POC" (Point of Control) line, which indicates the price level where the most time (highest number of blocks) was spent.
Assess Reversion Risk: Blocks that are bright Magenta or bright Cyan indicate that time was spent far away from the Moving Average. Traders can use this to visually gauge if a breakout is sustainable or if a mean-reversion is likely.
Customize Your View: You can adjust the TPO timeframes (Daily/Weekly/Monthly), the block interval (e.g., 30 minutes), and choose your preferred MA type (SMA, EMA, WMA, HMA).
Disclaimer: This indicator is designed for educational and analytical purposes. TPO is a tool for understanding market structure and time spent at price levels, not a standalone trading signal generator. Past performance of price around value areas does not guarantee future results.
説明文
コンセプトと開発目的
このインジケーターは「相場分析におけるスーパーツールであるTPO(マーケットプロファイル)の真の力を見出し、深い理解を得る」というコアコンセプトのもとに開発されました。伝統的なTPOの仕組みと相場の重心(移動平均線)を融合させることで、時間の経過に伴う価値の推移と価格の乖離を、より視覚的かつ明確にトレーダーに提供します。
オリジナリティと機能
従来のTPOプロファイルは時間枠をアルファベット(A、B、C...)で表し、静的な色を使用しますが、このスクリプトはコミュニティに新たな付加価値を提供するために2つの独自機能を備えています。
連番表示: アルファベットの代わりに、各TPOブロックは形成された順番に沿って(1、2、3...)と連番で表示されます。これにより、セッション内での時間の流れを直感的に読み取ることが劇的に容易になります。
MA乖離率によるグラデーション着色: 最大の特徴はその着色ロジックです。TPOブロックは、相場の重心として機能する基準移動平均線(MA)からの「乖離率」に基づいて色が決定されます。
計算式と出力値の根拠
視覚データがどのように生成されているかを完全に透明化するため、ブロックの着色に使用されている具体的な計算式を明記します:
計算式: 乖離率(%) = ((価格 / MA) - 1.0) * 100.0
なぜこの計算なのか? この式は、特定のTPOブロックが形成された瞬間において、その価格水準が基準となる移動平均線からパーセンテージでどの程度離れているか(価格がどれほど伸びきっているか)を正確に測定するために使用されます。
実際の出力値: 出力はパーセンテージの浮動小数点数になります(例:MAが100ドルで、ブロックの価格が102ドルの場合、出力は 2.0 つまり2%になります)。この値は、ユーザーが設定した「最大の限界乖離率」(デフォルト2.0%)によって制限されます。
カラーマッピング: 制限されたパーセンテージはグラデーション関数に渡されます。マイナスの乖離(MAに対して割安)はシアン(水色)に近づき、プラスの乖離(割高)はマゼンタ(赤紫)に近づくように色が変化します。
使用方法
バリューエリアの特定: 最も多くの時間(ブロック数)が費やされた価格帯を示す「POC(Point of Control)」ラインを探し、相場の中心的価値を把握します。
平均回帰リスクの評価: 鮮やかなマゼンタやシアンのブロックは、移動平均線から遠く離れた場所で時間が費やされたことを示します。トレーダーはこれを視覚的な基準として、ブレイクアウトが持続可能か、あるいは平均回帰(MAへの戻り)が起こりやすいかを判断できます。
柔軟なカスタマイズ: TPOの期間(日/週/月)、ブロックの区切り(例:30分)、そして好みのMAタイプ(SMA、EMA、WMA、HMA)を自由に変更できます。
免責事項:このインジケーターは教育および分析目的で設計されています。TPOは市場構造と価格帯での滞在時間を理解するためのツールであり、単独の売買シグナルではありません。バリューエリア周辺での過去の価格動向は、将来の結果を保証するものではありません。
Индикатор

Quant Synthesis Strategy [JOAT]Quant Synthesis Strategy
Introduction
QSS Quant Synthesis Strategy is an open-source TradingView strategy that integrates regime detection, higher-timeframe bias, confirmed structure, session opening-range context, volume participation, trend energy, ATR exits, cooldowns, and session risk controls.
The strategy is designed as a realistic research baseline, not an optimized profit promise. Its purpose is to demonstrate how the JOAT indicator concepts can be combined into a non-repainting strategy framework with explicit risk management.
Core Concepts
1. Market Regime Detection
The regime model uses EMA spread, ADX from DMI, and ATR percentage context to classify Trend, Expansion, Balance, or Transition.
2. Higher-Timeframe Bias
The strategy requests higher-timeframe EMAs with lookahead disabled. Long bias requires the HTF fast EMA above the slow EMA with positive slope; short bias is mirrored.
3. Confirmed Structure
Pivot-based structure checks whether recent highs and lows form bullish or bearish structure. Pivot confirmation is delayed by design to avoid repainting.
4. Session Opening Range
The strategy tracks a configurable trading session and opening range. Entries can require session context so trades are not taken randomly outside the selected window.
5. Risk and Exits
Position size is estimated from a percentage of equity and ATR stop distance. Exits include ATR stop, ATR target, maximum bars in trade, regime/bias exit, cooldown, and session flattening.
Features
Regime engine: Trend, Expansion, Balance, and Transition classification
HTF bias filter: Uses non-lookahead request.security() higher-timeframe EMAs
Confirmed structure filter: Pivot-based bullish/bearish structure state
Session opening range: Optional session context for entries
Volume participation filter: Uses volume z-score and directional volume
Confluence score: Separate long and short scores gate entries
ATR exits: Stop loss and take profit scale with volatility
Risk controls: Risk percent, cooldown, max entries per session, max bars in trade, and session flattening
Visuals: EMA cloud, opening-range lines, stop/target plots, and top-right dashboard
Default Strategy Properties
Initial capital: 100000
Commission: 0.01 percent
Slippage: 1 tick
Pyramiding: 0
Order processing: process orders on close
Position sizing: fixed quantity calculated internally from risk settings
How to Use
Step 1: Select a market and timeframe with enough historical data.
Step 2: Review the dashboard regime and HTF bias before interpreting trades.
Step 3: Adjust risk percent, ATR stop, ATR target, cooldown, and session settings conservatively.
Step 4: Evaluate results across multiple symbols and timeframes. Avoid optimizing only one market segment.
Limitations
Backtest results are historical simulations and do not guarantee future performance
More trades can increase sample size but can also increase noise and transaction costs
Pivot confirmation creates intentional signal delay
Strategy results depend on symbol liquidity, timeframe, session settings, slippage, and commission assumptions
The strategy is a research framework, not a recommendation to trade
Originality Statement
QSS is an original JOAT strategy framework that integrates regime detection, HTF bias, structure, session context, volume participation, and ATR risk management into one non-repainting Pine Script v6 strategy.
Disclaimer
This strategy is for educational and informational purposes only. It is not financial advice and does not guarantee profitability. Trading involves substantial risk of loss. Historical backtests can be inaccurate or misleading if assumptions do not match live execution.
Made with passion by jackofalltrades
Стратегия

Pure Matrix Profile [TPO & Link]Pure Matrix Profile
Description:
This indicator is a highly visual, ASCII-based environment recognition tool designed to map market structure, liquidity, and momentum within specific sessions. It is NOT a standalone entry signal generator. Rather, it provides a deep situational awareness of "price wall thickness" (Volume) and "market heat" (RSI) to help traders build robust defensive and offensive strategies.
1. Pine Script Limitations & Memory Management
In Pine Script, there is an absolute limit of 500 historical objects (Boxes, Labels, Lines) per script to prevent system overload, regardless of your account tier (Basic, Pro, Premium).
• Remaining Quota: 0 (This script maximizes the 500 limit for detailed rendering).
• How it works: To bypass this limitation and maintain a beautiful UI without crashing, the script uses a professional garbage collection technique (barstate.islast). It deletes all previous objects and recalculates/redraws the entire matrix exclusively on the most recent bar, ensuring optimal performance within the limits.
2. Core Calculations & Output Values
The visual beauty of this tool is driven by strict mathematical logic.
A. Price Bin Resolution (vp_step)
vp_step = (top_y - bot_y) / row_count
• Why: To divide the session's high-low range into equal tiers to distribute volume accurately.
• Output: A float value representing the price width of a single text row.
B. Binning (Data Assignment)
bin_idx = Math.floor( (c_price - bot_y) / vp_step )
• Why: To determine exactly which vertical "box" (row) the volume belongs to.
C. Volume-Weighted RSI (Heat)
Avg_RSI = Sum(Current_RSI * Volume) / Sum(Volume)
• Why: This reveals the true momentum only where significant institutional money was traded.
D. Histogram Normalization (Bottom-Up Heights)
val = (chunk_vol / max_chunk_vol) * hist_height
• Why: To normalize raw volume into a fixed visual height constraint for the bottom ASCII histogram.
E. ASCII Texture Logic (Wall Hardness)
The "density" of the ASCII character changes dynamically based on the Avg_RSI:
• Overheated (Avg_RSI >= 60): Renders "█" (Full Block). Represents a "Hard Wall" with strong momentum.
• Neutral (Avg_RSI 40.1 - 59.9): Renders "▒" (Medium Shade). Represents stable consolidation.
• Freezing (Avg_RSI <= 40): Renders "░" (Light Shade). Represents a "Soft Wall" with weak momentum.
3. Pros (Merits)
• Visualizing "Hardness": By combining volume depth and RSI texture, you can intuitively differentiate between strong support/resistance zones (Hard Walls) and fragile ones (Soft Walls).
• Risk Management: Helps prevent trading directly into "Hard Walls" or getting trapped in low-liquidity vacuums.
4. Cons (Limitations)
• Not an Entry Strategy: Provides zero edge as a standalone trigger.
• Lagging Nature: Session profiles form after the price has moved.
• Visual Clutter: High row counts on small screens may cause text overlap.
Japanese Description
このインジケーターは、特定のセッション内における市場構造、流動性、モメンタムをマッピングするための、ASCIIベースの視覚的な環境認識ツールです。これは単体でエントリーシグナルを生成するものではありません。トレーダーが堅牢な戦略を構築できるよう、「価格の壁の分厚さ(出来高)」と「相場の熱(RSI)」の状況認識を提供します。
1. 描画制限とメモリ管理について
Pine Scriptには、システム負荷を防ぐため、アカウントランクに関わらず1スクリプトにつき描写オブジェクトの最大上限が「500個」に厳格に設定されています。
・ 現在の残量: 0個(精密な描画のため、この500個の枠を最大限使い切る設定にしています)。
・ 動作の仕組み: 高度なメモリ管理(barstate.islast)を行っています。最新のローソク足でのみ過去のオブジェクトを全削除し、必要な分だけを一気に再計算して描き直すことで、制限枠内で安定稼働させています。
2. コアとなる計算式と出力値の解剖
A. 価格帯をスライスする計算 (VP Step)
vp_step = (top_y - bot_y) / row_count
・ なぜこの計算なのか: セッションの高安値を指定した行数で均等に分割し、1行あたりの価格幅を決定するため。
B. ローソク足の格納先判定 (Binning)
bin_idx = Math.floor( (c_price - bot_y) / vp_step )
・ なぜこの計算なのか: 出来高を正しい価格帯(行)に割り当てるため。
C. 出来高加重RSI(熱量の算出)
Avg_RSI = Sum(Current_RSI * Volume) / Sum(Volume)
・ なぜこの計算なのか: 大口の取引(出来高)が集中した価格帯のモメンタムだけを抽出するため。
D. ボトムヒストグラムの高さ計算 (Normalization)
val = (chunk_vol / max_chunk_vol) * hist_height
・ なぜこの計算なのか: 出来高を、指定した最大の高さ(行数)に正規化して当てはめるため。
E. ASCIIテクスチャ・ロジック(壁の硬度)
Avg_RSIの値に基づいて、描画される文字の密度(硬さ)が3段階で変化します。
・ 加熱帯 (RSI 60以上): 「█」(フルブロック)を描画。モメンタムを伴う「硬い壁」を意味します。
・ 中立帯 (RSI 40.1 - 59.9): 「▒」(ミディアムシェード)を描画。安定した攻防が行われているゾーンです。
・ 冷却帯 (RSI 40以下): 「░」(ライトシェード)を描画。モメンタムが弱まっている「柔らかい壁」を意味します。
3. メリット(優位性)
・ 壁の硬度の視覚化: 出来高の厚みとRSIのテクスチャを組み合わせることで、突破困難な「硬い壁」と、崩れやすい「柔らかい壁」を直感的に判別できます。
・ 無駄な被弾の回避: 強力な壁への無謀な突撃を防ぐための強力な環境認識根拠となります。
4. デメリット(限界と注意点)
・ エントリー戦略にはならない: 本ツール単体ではエントリーの優位性は一切ありません。
・ 遅行指標の性質: プロファイルは価格が動いた「後」に形成されます。
・ 視覚的なノイズ: 低解像度の環境で行数を大きく設定しすぎるとテキストが重なります。 Индикатор

Индикатор

Nexus Sentiment & Risk Matrix [Pineify]Nexus Sentiment and Chandelier Risk Matrix
Nexus Sentiment and Chandelier Risk Matrix blends a three-oscillator momentum score with a Chandelier-style ATR risk state. RSI, smoothed Stochastic, and normalized CCI form one 0-100 sentiment line; BUY/SELL markers appear only when that line agrees with a fresh risk flip.
Key Features
Composite sentiment from RSI, Stochastic, and CCI.
Chandelier risk direction used as a signal filter.
Gradient fills around the 50 equilibrium level.
Alerts for bullish and bearish alignment events.
How It Works
The script calculates RSI , 3-bar smoothed Stochastic , and CCI with one oscillator length.
CCI is clipped around +100/-100 and remapped to 0-100 so it can be averaged with the other oscillators.
The average becomes the sentiment line. Above 50 suggests bullish pressure; below 50 suggests bearish pressure.
The risk layer uses ATR and recent extremes to maintain a persistent direction.
A BUY needs an upward risk flip above 50. A SELL needs a downward flip below 50.
How the Components Work Together
The oscillator stack gives context but does not trigger trades alone. RSI tracks relative strength, Stochastic checks close location inside the recent range, and CCI adds a deviation-from-mean view.
The Chandelier layer adds volatility-aware confirmation. Instead of reacting to every move through 50, the script waits for an ATR threshold break. This may filter weak bounces, but it can enter late on sharp reversals.
Trading Ideas and Insights
A BUY after a pullback may indicate risk shifting back up above 50.
A SELL below 50 can warn that bearish pressure and ATR risk are aligned.
If price makes a new high while sentiment fades, consider waiting for stronger follow-through.
Unique Aspects
Three different momentum tools are normalized into one readable sentiment line.
Signals are event-based, so markers do not repeat while the same condition remains active.
How to Use
Add the indicator and watch the line around 50.
Read green zones as bullish pressure and red zones as bearish pressure.
Treat markers as confluence events, then confirm with structure, volume, or higher timeframe.
Use the built-in alert conditions for notifications.
Customization
Oscillator Length (default: 14) - Higher values smooth the line; lower values react faster.
ATR Length (default: 22) - Sets the volatility lookback.
ATR Multiplier (default: 3.0) - Larger values reduce flips but add lag; smaller values can whipsaw.
Conclusion
This is a compact sentiment-and-risk panel for traders who want oscillator context filtered through ATR direction. Signals may help identify regime changes, but they still need price-action and risk checks. Индикатор

Dual Volume Profile Dual Volume Profile overlays two independent volume profiles on your chart simultaneously: a session profile built from intraday trading hours, and a composite range profile built from a configurable lookback period. Comparing the two reveals whether short-term auction activity is confirming or diverging from the broader volume structure.
Inspired by TradingView's built-in VRVP and SVP HD indicators, the Dual VP combines both concepts into a single overlay — pairing the structural range view of VRVP with the per-session granularity of SVP HD — and adds a signal layer that detects when the two profiles agree or diverge.
Session profile
Builds a volume-at-price histogram for each trading session using your selected hours — CME RTH, NYSE RTH, Full Globex, or a custom window. Up to 5 historical sessions are displayed alongside the current developing session. Each session shows its own POC, VAH, and VAL.
Range profile
Builds a composite volume-at-price histogram across a configurable lookback (default 200 bars). This acts as a multi-session structural view similar to TradingView's built-in VRVP, positioned in the right margin of the chart. POC, VAH, and VAL are drawn across the full range.
Signals
The indicator generates three optional signals based on the relationship between the session and range profiles:
POC Alignment — fires when the session POC and range POC converge within a user-defined threshold, indicating agreement on fair value between the short-term and structural auctions.
Dual VA Breakout — fires when price trades above both value area highs or below both value area lows simultaneously, suggesting a directional move accepted by both timeframes.
VA Divergence — fires when the session's value area midpoint shifts significantly away from the range's value area midpoint, indicating the developing session is repricing relative to the composite structure.
How to use it
Add the indicator and select the session type matching your instrument. The session profiles draw inline over price history; the range profile anchors to the right margin. Use the info table (top-right by default) to monitor both sets of levels and active signals at a glance. Session transparency is adjustable so the histograms don't obscure candles.
Settings overview
Session Type, Sessions to Show, Session Bar Thickness, Session Transparency, Lookback Bars, Right Margin Offset, Price Rows (session and range independently), Value Area %, Up/Down volume colors, POC/VA line visibility, and signal thresholds for alignment, breakout, and divergence.
Индикатор

Индикатор

Quantum Liquidity Map - VP, VWAP & CVD Confluence [NikaQuant]Info:
An overlay that combines three institutional order-flow methods — visible-range Volume Profile, session-anchored VWAP with standard-deviation bands, and Cumulative Volume Delta with divergence detection — into one coordinated tool for reading liquidity and order-flow conviction.
## Why This Combination Exists
Each of the three methods answers a different question about price, and none of them can answer the others alone. Volume Profile answers "where has the market actually traded?" — it locates the price levels participants have defended with size. Anchored VWAP answers "how far is the current price from the session's true volume-weighted average?" — it measures stretch from fair value. CVD divergence answers "is this move real?" — it exposes when a new price high or low is being printed on weakening order-flow pressure.
Used in isolation, each method produces false signals. A Value Area edge can be tagged without any participation. A VWAP band touch can continue for hours without mean-reverting. A CVD divergence can fire in a vacuum away from any structural level. The coordination is the entire point of this script: a Value Area edge touched while price is already two standard deviations stretched from VWAP, with a confirmed CVD divergence printing at the same bar — three independent systems agreeing — is a structurally different event than any one of them firing alone. The script exists to make that specific confluence visible in a single overlay without chart clutter or flipping between tools.
## How It Works
Volume Profile — The visible range is split into horizontal price buckets. Each completed bar's volume is distributed into the bucket containing its midpoint. The highest-volume bucket becomes the Point of Control (POC). From the POC outward, buckets are added alternately above and below (whichever neighbour carries more volume) until a configurable percentage of total volume is captured — 70% by default, following the CBOT value-area method. The upper and lower boundaries of that expansion become Value Area High (VAH) and Value Area Low (VAL). A previous-session POC that current price has not yet revisited is drawn as a "naked POC" — an untested volume cluster that tends to act as a magnet.
Anchored VWAP — The volume-weighted average price is calculated from scratch each time the anchor period resets (thirteen anchor options from one hour through yearly). Two standard-deviation bands are derived from the running variance of the weighted price distribution, with multipliers adjustable for both the inner and outer bands. Bands are deliberately suppressed for the first five bars of every new anchor period, because variance is mathematically unstable immediately after a reset and early spikes would be misleading.
CVD Divergence — Cumulative Volume Delta is estimated per bar using the close-location-within-range method: a bar that closes near its high is interpreted as predominantly buy-driven, one that closes near its low as sell-driven, and the net difference is summed across the session. Structural swing highs and lows are detected with equal left and right confirmation windows, which prevents repainting because a pivot is only recognised once both sides are closed. A divergence is flagged only when three conditions are met: (1) price prints a new swing extreme relative to the previous one, (2) the CVD value at that swing fails to confirm the new extreme, and (3) the swing itself exceeds 1.5 times the 14-bar Average True Range. The ATR gate is the key noise filter — it throws out minor pivots that would otherwise generate meaningless divergences during tight consolidations.
## How To Use It
- Start with the profile: locate POC, VAH, and VAL. These are the decision levels.
- Check the VWAP band zone (shown live in the dashboard). Inside ±1 standard deviation of VWAP, price is near fair value. Beyond ±2 standard deviations, it is statistically stretched and mean-reversion odds improve.
- Look for confluence at profile levels. A rejection candle at VAH while price is also outside the +2 standard deviation band on VWAP and a bearish CVD divergence has just fired is the highest-probability setup the indicator produces. The inverse applies at VAL.
- A naked POC tag accompanied by CVD trending in the same direction as the test is more likely to hold than one where CVD disagrees.
- Recommended timeframes: 5-minute through 4-hour for intraday; 1-hour through daily for swing. The VWAP anchor period should match the trading horizon — Session for intraday, Weekly or Monthly for swing.
- Recommended markets: liquid futures, major FX pairs, large-cap equities, and liquid crypto perpetuals — any market where per-bar volume is meaningful enough for the close-location-within-range buy/sell estimate to be informative.
- Avoid using on illiquid symbols where volume is sparse or spiky, and on non-standard chart types (Heikin Ashi, Renko, Kagi, Point & Figure, Range) — they distort both the profile inputs and the CVD calculation.
## Settings
- Profile Rows (default 60): number of horizontal buckets. Higher values give finer resolution at the cost of more noise per bucket.
- Value Area % (default 0.70): volume percentage that defines the value area, following the CBOT convention.
- Lookback Bars (default 48): how many completed bars of history feed the profile.
- Show Naked POC (default on): draws previous-session POCs that current price has not yet revisited.
- Profile Width (default 0.30): horizontal footprint of the heatmap as a fraction of the lookback window.
- CVD Pivot Lookback (default 5): bars required on each side to confirm a swing. Higher values produce fewer but stronger divergence signals.
- VWAP Period (default Session): anchor period from one hour through yearly.
- Inner SD Multiplier (default 1.0) and Outer SD Multiplier (default 2.0): standard-deviation band widths.
- Dashboard position, size, and dark-mode toggle: cosmetic only.
## Alerts
Four alert conditions are included, each with a JSON payload suitable for webhook routing:
- Price touches POC (within half an ATR)
- Price enters the VAH zone
- Price enters the VAL zone
- CVD divergence detected (bullish or bearish)
## Notes
- Non-repainting. Divergence signals fire only on confirmed (closed) bars and require both-sided pivot confirmation. The profile, VWAP and CVD values use historical bar data only, with no lookahead.
- The CVD estimate is range-based (close-location-within-range), not tick-based. On very short timeframes, where a single bar can contain many aggressive sweeps, this is an approximation of true order flow — it correlates well with tick CVD on liquid instruments but is not a substitute for it on sub-minute scalping.
- Overlay indicator, pinned to the right scale. Pine Script v6.
─────────────────────────────────────────
════════════════════════
Индикатор

FX24HR Market Volume ProfileFX24HR Market Volume Profile
The FX24HR Market Volume Profile is a high-resolution analysis tool designed specifically for intraday traders who need to visualize the distribution of price and time across the three major global trading sessions: Asia, Europe, and America.
Unlike standard Volume Profiles that aggregate data into a single block, this indicator color-codes the market's "footprint" by session, allowing you to identify which time-of-day holds the most significant structural levels (Value Areas and High-Volume Nodes).
Key Features
3-Session Color Coding: Instantly distinguish between Asian (Cyan), European (Gold), and American (Purple) market activity.
Perfect Axis Alignment: This indicator solves the "stair-step" issue found in many profile scripts. All sessions within a 24-hour day are anchored to the same vertical starting line (the daily open), creating a clean, professional "wall" for easier visual comparison.
Ultra-Resolution Polylines: Built using Pine Script V6’s optimized polyline architecture, providing smooth, high-fidelity histograms without lagging your chart.
Customizable Resolution: Adjust the Row Resolution to fine-tune the granularity of the profile—from broad structural blocks to razor-sharp price levels.
Historical Backlook: Display up to 10 days of session history to identify recurring institutional levels.
How to Use
Identify Strength: If the American session profile (Purple) is significantly wider than the European session, it indicates higher participation and stronger validation of those price levels.
Session Overlaps: Watch how the European profile interacts with the Asian range. An expansion outside the Asian "wall" often signals the trend for the remainder of the day.
Point of Control (Visual): The widest part of each colored segment represents the "Point of Control" for that specific session. Use these as magnets for price in future sessions.
Settings
Days to Display: How many previous days of profiles to render.
Histogram Width Multiplier: Adjust the horizontal scale of the profiles to fit your screen.
Vertical Resolution: Higher values create smoother profiles but require more processing.
Session Times: Fully adjustable to match your specific broker’s timezone or preferred exchange hours.
Technical Details
Version: Pine Script v6
Индикатор

Индикатор

Weekly Initial BalanceThis indicator marks the Weekly Initial Balance — the price range established during the first two trading days of the week — and projects extension levels for the remainder of the week.
The idea behind it
Monday sets the opening range for the week. Tuesday may extend that range — it could produce a false break, a range extension, a reversal, or an inside day. In a large majority of weeks, by the time Monday and Tuesday have traded, the high and low extremes are already in place for the rest of the week. One of these extremes will tend to hold, while the other may get broken.
The default window (Sunday 18:00 – Tuesday 16:00 New York time) captures exactly this: the full Monday session plus Tuesday's contribution. Once the IB window closes, the remaining days of the week tend to trade in relation to these established levels.
What makes this different
Most Initial Balance indicators focus on the first 30 or 60 minutes of a single session. This indicator applies the IB concept to the weekly timeframe — capturing the Mon-Tue range that statistically defines the week's extremes. The configurable window, range extension multipliers, and clean label handling (current week only) make it a practical tool rather than a theoretical overlay.
How it works
- A shaded box marks the IB range (high and low) as it forms during the configured window
- After the window closes, the IB high, low, and 50% midpoint extend as horizontal reference levels
- Configurable range extensions (default 0.5x and 1.0x of the IB range) project above and below as potential targets
- Price labels display the exact level at each line (current week only — historical weeks show clean lines without clutter)
How to use it
- **Which side holds?** After the IB window closes, one extreme tends to hold for the week while the other gets broken — watch for which side price tests and rejects first
- **Range extensions as targets:** When the IB high or low breaks, the 0.5x and 1.0x extensions provide measured-move targets
- **Inside weeks:** If price stays within the IB range through Friday, the 50% midpoint often acts as a magnet
- **Volatility read:** A wide Monday–Tuesday range suggests the week's extremes may already be set; a narrow range suggests expansion is still ahead
- **Alerts:** Built-in alerts fire when price breaks the IB high or low after the window closes
Settings
- Fully configurable start/end day, hour, and minute (New York time)
- Adjustable number of historical weeks to display
- Configurable extension multipliers (not limited to 0.5x and 1.0x)
- Toggle individual levels, labels, and extensions on/off
- Works on any instrument with sufficient intraweek data (futures, forex, crypto)
Recommended timeframes: 30min and 1H charts for best visual clarity. Intraday only — the indicator requires sufficient chart history to display the configured number of weeks.
Индикатор

Индикатор
