SBSniper - HTF PSPHTF PSP
Six higher timeframes drawn as a compact candle column beside price, with correlated-asset
disagreement marked across all of them. Correlated markets normally move together. When one takes
out a high or low and the other refuses to follow, or one closes up while the other closes down,
that disagreement is information. This finds it on six timeframes at once so you are not flipping
charts to check.
Built for index traders watching NQ, ES and YM against each other, but it works on any correlated
set — metals, energies, or symbols you choose yourself.
CREDIT
Built on "ICT HTF Candles (fadi)" by @fadizeidan, published open-source under the
Mozilla Public License 2.0:
The HTF candle column, its swing and equilibrium lines, the fair value gap and volume imbalance
boxes, the trace lines, the info table, and the SMT divergence feature itself all come from that
script. Full credit for those to the original author. This publication is open-source under the
same licence.
WHAT IT MARKS
PSP — Precision Swing Point
An HTF candle that closes up while a correlated asset closes down, or the reverse. The candle takes
a coloured border and a halo, with a label naming which correlations disagreed and whether you are
on the strong (S) or weak (W) side. A still-forming candle is coloured differently, because a PSP
can vanish before the candle closes.
SMT divergence
One asset takes out a prior high or low, its partner fails to. Drawn as a line between the two
candles on the HTF column, and optionally across the real swing on your chart. It looks at every
pair of candles in a lookback window, not only the newest two, so a divergence anchored a few
candles back still shows. A divergence disappears once price takes the level it was built on — if
the line is still there, the level is still intact.
SMTF — divergence into a gap
An SMT where the diverging high or low landed inside a fair value gap that already existed. Price
reaching into an old imbalance at the same moment the correlation cracks. Prefixed "SMTF".
SSMT — sequential divergence
Divergence filtered by time. A cycle splits into four quarters, each quarter being one candle of the
timeframe below: the day into four 6H candles (Asia, London, NY AM, NY PM), the session into 90m,
the week into days, the month into weeks. A divergence between two CONSECUTIVE quarters is
sequential, prefixed "SSMT" — or "SSMTF" if it also delivered into a gap. Skip a quarter and it is
an ordinary divergence again, whatever the timeframe. These are never hidden by the decluttering
settings.
Strength Switch — off by default
Divergence filtered by the sweep instead of by time: which asset took the prior extreme, and which
failed to pair it. Tagged onto labels that are already on the chart rather than adding new marks.
"SS" for a single formation, "SS²" where a second confirms it.
NOTES
An analysis aid, not a trading system. It shows where correlated markets disagree. It does not
generate entries, exits, targets or alerts, and disagreement alone is not a reason to trade.
Readings on the currently forming HTF candle are live and can change until it closes — that is why
forming PSPs have their own colour.
Correlated data is requested with lookahead off. 指标

Footprint Delta Profile [SDT]A session volume profile built from TradingView's native footprint data. Every row is split into aggressive buys at the ask and sells at the bid, with a point of control and a value area.
Most delta profiles on the platform infer the side from candle direction: if a bar closes up, its whole volume counts as buying. That is an approximation, and it breaks exactly where it matters, on bars that reverse. This script takes the side from request.footprint(), where the aggressor is known per price row, so the split is measured rather than guessed.
HOW THE PROFILE IS BUILT
request.footprint() returns the volume rows of one bar at a time. Each confirmed bar is folded into a composite: every footprint row is assigned to a price bucket by its midpoint, and the bucket accumulates volume and delta. Buckets stay sorted, so the profile remains ordered as the window fills.
Aggressive volume per bucket is derived from bucket volume V and bucket delta D as sell = (V - D) / 2 and buy = (V + D) / 2. This is exact by the definition of delta.
The point of control is the heaviest bucket. The value area grows outward from it, repeatedly taking the heavier of the two neighbouring buckets until the requested share of total volume is enclosed.
The window resets on a period that is strictly larger than the chart timeframe. Auto uses the day on intraday charts, the month on daily charts, and no reset on weekly and above. A period that is not larger than the chart timeframe would reset on every bar, so it falls back to a bar count instead.
THREE INDEPENDENT DISPLAY SETTINGS
Data mode decides what the row length measures. Volume is the total traded at that price, coloured by delta sign. Delta is the size of the imbalance itself. Bid x Ask measures aggressive sells and buys separately.
Layout decides how the row is laid out. One-sided grows right from the axis. Two-sided sends one part left and the other right. The two combine freely: delta two-sided gives a multidirectional imbalance histogram, bid x ask two-sided gives the classic two-column profile, volume two-sided gives a symmetric butterfly.
Style decides how the row is drawn: filled blocks, a volume gradient, a single filled outline drawn as one polyline, or thin ticks.
A note on what to expect: under a shared wing scale, bid x ask looks nearly symmetric. That is a property of the data, not a drawing fault. Aggressive buying and selling at a given price are usually within a few percent of each other, so both wings are close to half the row volume. Switch the wing scale to independent to see the shape difference, or use the delta mode, where only the dominant side is drawn.
ROW RESOLUTION
ticks_per_row is declared as a simple int, so it cannot be computed from the bar range or the ATR at runtime. Auto scales it by chart timeframe, which keeps the row count sane but cannot account for the difference between instruments: four ticks is about one point on Nasdaq futures and a quarter of a five-minute range on Euro futures.
The script therefore measures the average bar range over the last fifty bars and shows, in the table, the tick count that would give the requested number of rows per bar on the current symbol. Set the input to that number. Where even the finest resolution cannot reach the target, as on Euro futures intraday, the readout says so instead of flagging an error.
The profile bucket height is a separate matter and is chosen automatically. On the first bar with data the script takes the footprint row height and an ATR-based estimate of the window range, then rounds the bucket up to the smallest multiple of the row height that keeps the profile under the row limit. Nothing to tune by hand, and the drawing limit cannot be exceeded.
ABSORPTION MARKERS
A circle appears when one third of a bar's range holds at least the configured share of that bar's volume while the delta in that third points against the direction of the bar. Aggression that meets size and fails to move price is the signature of a passive participant taking the other side. The circle sits below the bar when sellers were absorbed on an up bar, above it when buyers were absorbed on a down bar.
TABLE
Rows per bar shows the measured average, the tick setting in use, and the suggestion when it differs. Window shows the active reset period. Then the point of control, the value area bounds, the cumulative delta of the window and its total volume, and the number of profile rows currently held.
THEME
The palette follows the chart. Auto reads the background through chart.bg_color, computes its relative luminance and switches between a dark and a light variant of the chosen palette; text colour comes from chart.fg_color. Five palettes are included, plus a custom option.
NOTES AND LIMITS
Footprint data requires a TradingView plan that includes it, and is not available on every symbol. Without it the script draws nothing rather than substituting an estimate.
The forming bar is added to the profile only when it closes, so the profile lags the live bar by one bar. This keeps the composite free of double counting during real-time updates.
This is an observation tool. It produces no entries, exits or directional calls.
Built on FootprintKit, an open-source Pine library by the same author, which performs the row statistics and the composite profile. This script requests the footprint, feeds the profile and draws it.
指标

MTF Trend Dashboard [PineLogic]Multi-timeframe trend, momentum and bias in one compact table.
WHAT IT DOES
Reads five timeframes at once (default 15m / 1h / 4h / 1D / 1W, all configurable) and shows, for each one:
- Trend: "Up" when close is above the slow EMA and the fast EMA is above the slow EMA, "Down" for the mirror condition, "Flat" otherwise.
- RSI: the raw value, tinted when it reaches 70 or 30.
- MACD: the sign of the histogram (12/26/9).
A final Bias row sums the five trend readings into a score from -5 to +5. It reads BULLISH at +3 or more, BEARISH at -3 or less, and MIXED in between.
HOW TO USE IT
The point is to stop flipping through timeframes to check whether a setup agrees with the higher ones. Trade your working timeframe and use the Bias row as a filter, for example taking longs only while Bias reads BULLISH.
SETTINGS
Five timeframe slots, Fast EMA (default 21), Slow EMA (default 50), RSI length (default 14), plus table position and text size.
HONEST NOTE ON HIGHER-TIMEFRAME VALUES
Rows for timeframes above your chart update live while that bar is still forming, and settle only when it closes. This is normal behaviour for any dashboard of this kind, but it does mean the 1W row can change during the week. Read closed bars, not forming ones.
This is a context tool, not a signal generator. It produces no entries or exits and makes no claim about profitability. 指标

OHLC4 Structure Ribbon [RMA] OHLC4 Structure Ribbon is a multi-horizon market-structure indicator built from a fixed stack of Wilder Running Moving Averages applied to OHLC4. Rather than treating the ribbon as a collection of independent moving averages, the indicator analyzes the shape, ordering, compression, expansion, and directional geometry of the entire stack as one structural system.
The primary ribbon uses six RMA horizons: 5, 8, 13, 20, 34, and 50. A separate 75 / 110 pair provides a slower structural reference without influencing the primary ribbon's regime engine.
The objective is not simply to show whether a fast average is above or below a slow average. The ribbon is designed to answer a broader question: how organized is price structure across multiple horizons, how strong is that structure relative to current volatility, and is that structure being maintained, disrupted, or transferred to the opposite side?
Why OHLC4 and RMA?
Each average is calculated from OHLC4, giving equal representation to the open, high, low, and close of each candle rather than using the closing price alone. The smoothing method is Wilder's RMA, which reacts differently from a conventional EMA. RMA places more persistence into the series, allowing the ribbon to develop a slower, more structural character while still preserving enough responsiveness for shorter-timeframe use.
Because the six averages span several horizons, the resulting ribbon provides a continuous view from the fast edge of the market through the deeper intermediate structure.
➖REG BODY➖
At the center of the indicator is a measurement called REG BODY. Instead of measuring only the distance between two selected averages, REG BODY examines all six RMA levels together. Each RMA is assigned its theoretical Wilder lag, and a linear regression is calculated across those lag coordinates. That regression estimates the directional slope of the entire stack. The slope is then projected across the complete lag range to produce one signed structural spread.
A positive REG BODY means the faster horizons are structurally positioned above the slower horizons. A negative REG BODY means the opposite. The larger the absolute value, the more strongly the full ribbon is separating in that direction. This is important because two ribbons can have the same fast-to-slow distance while having very different internal structure. One may be cleanly ordered from front to back, while another may be folded, crossed, or compressed internally. REG BODY is intended to evaluate the complete structure rather than relying on a single moving-average spread.
➖Volatility normalization➖
Raw ribbon separation naturally varies by instrument, price level, and timeframe. To make the structural measurement more comparable, REG BODY is normalized by ATR14. This expresses ribbon expansion in volatility-relative terms rather than raw points. For example, a ten-point separation means something very different on an instrument whose ATR is 3 than on one whose ATR is 100. ATR normalization gives the engine a common structural language across those environments.
➖Peak-Persistence ATR-Drag Guard➖
Strong trends can occasionally create an unusual problem: volatility expands so rapidly that ATR rises faster than the ribbon itself. When that happens, a simple REG BODY / ATR calculation can make a structurally healthy trend appear to weaken even while the ribbon remains strongly ordered and continues expanding. The indicator addresses this with a Soft Peak-Persistence ATR-Drag Guard. The guard evaluates ribbon ordering, REG BODY persistence, directional continuity, and ATR expansion together. When the underlying structure remains intact, it can temporarily preserve part of the previously established normalized strength rather than allowing an abrupt ATR expansion to collapse the reading prematurely. The effect is intentionally limited. It decays automatically and releases when structure deteriorates, the ribbon body cools, directional ownership changes, or the qualifying conditions are no longer present. Its purpose is not to manufacture momentum. It is simply to reduce false structural decay caused by volatility expanding faster than an otherwise intact ribbon.
➖Wide Semantic and the CORE scale➖
After volatility normalization and the persistence guard, structural strength is translated through a non-linear mapping called Wide Semantic. Wide Semantic converts the normalized ribbon measurement into a bounded -100 to +100 CORE scale. The center of the scale provides greater resolution for ordinary market structure, while increasingly large structural expansions require progressively greater ATR-normalized separation to approach the extremes.
The principal absolute-value anchors are:
0.70 ATR → 34
1.25 ATR → 55
2.50 ATR → 65
4.00 ATR → 75
7.00 ATR → 89
12.0 ATR → 95
20.0 ATR → 100
Positive CORE values represent bullish structural direction, while negative values represent bearish direction. A CORE reading is not a probability, price target, or percentage. It is a volatility-normalized measurement of multi-horizon structural strength. This distinction becomes especially useful near the outer portions of the scale. A move from 89 to 95 represents a much larger increase in underlying structural expansion than a move from 34 to 55.
➖Global Regime architecture➖
The ribbon uses CORE together with the physical ordering of the RMA stack to maintain a persistent Global Regime. A fully ordered bullish stack can establish Bull Rise, while a fully reversed stack can establish Bear Fall. When an established bullish structure begins to lose internal ordering, the system can transition into Bull Resistance rather than immediately declaring the market bearish. Likewise, disrupted bearish structure can remain in Bear Support while the prior bearish lineage is still structurally relevant. This distinction allows the indicator to separate trend continuation, compression, transition, and actual directional transfer. Directional ownership uses fixed structural rails. Same-side full-stack re-entry occurs around ±34, while initial or opposite-side directional transfer requires approximately ±55. Larger structural expansions can progress into Extreme and Exceptional regimes around ±89 and ±95, with separate release thresholds to reduce unnecessary state flipping. The result is deliberately different from coloring a ribbon solely according to whether one moving average crossed another.
➖Contiguous ribbon transitions➖
The visible ribbon contains five adjacent bands:
5/8 → 8/13 → 13/20 → 20/34 → 34/50
Transition ownership begins at the fast 5/8 edge and progresses outward. A deeper portion of the ribbon is not allowed to visually transfer direction until the faster pairs in front of it have aligned first. This creates a contiguous transition rather than allowing isolated sections of the ribbon to change color independently. During a bullish rollover, for example, the fast edge can begin transferring into resistance while slower portions of the ribbon still retain bullish ownership. The reverse occurs during recovery from bearish structure. This makes the ribbon itself a visual representation of how far a structural transition has propagated through the stack.
➖Ribbon ORDER➖
The context table also displays Ribbon ORDER %. ORDER measures how efficiently the six averages form one monotonic path from OHLC5 through OHLC50. A perfectly ordered ribbon approaches 100%, while internal folding and crossover geometry progressively reduce the reading. The accompanying Bull/Bear x/5 value shows how many adjacent pairs have aligned contiguously from the fast edge. For example, Bull 3/5 means the first three adjacent relationships have transferred bullishly while the deeper structure has not yet completed the transition. ORDER describes the ribbon's current geometry. It does not override Global Regime ownership.
➖Developing higher-timeframe CORE➖
The table includes both the current chart-timeframe CORE and a Developing HTF CORE calculated on the automatically selected next higher timeframe. The higher-timeframe value is not created by resampling the chart-timeframe result. The complete six-RMA structural engine is calculated natively in the higher-timeframe context using the same REG BODY, ATR normalization, persistence guard, and Wide Semantic mapping. Because this is a developing higher-timeframe reading, it updates while the higher-timeframe candle is still forming. It can therefore change until that candle closes. This provides a direct comparison between current-timeframe structure and the developing structural condition immediately above it.
➖75 / 110 long structure➖
OHLC75 and OHLC110 form a separate slower structural pair. They do not participate in REG BODY, CORE, or Global Regime calculations. Their purpose is to provide a longer structural reference alongside the primary six-average ribbon. When 75 > 110, the long structure is displayed in orange. When 110 > 75, it is displayed in gray. The table also reports the current relationship directly—for example, 75 > 110—along with the number of bars since the most recent 75/110 crossover.
➖Price-relative OHLC labels➖
Each RMA level can be displayed in a right-side label containing the current level and its distance from price. The labels also maintain a persistent price-relative marker:
$⤴ means price most recently moved above that OHLC level.
$⤵ means price most recently moved below that OHLC level.
The marker persists until the opposite side takes ownership. This makes it possible to scan the right-side stack and quickly see where current price is positioned relative to multiple structural horizons. The short-horizon labels visually inherit the active ribbon gradient, while the 75/110 labels use their separate long-structure color owner.
➖Crossover events➖
Five crossover families are available. The 5/8 event represents the fast ribbon edge. 8/20 provides an optional early-intermediate structural crossover, while 13/34 represents a deeper middle-structure transition. 20/50 tracks slower primary-ribbon equilibrium, and 75/110 represents the separate long structural pair. Bullish crossover labels appear below the candle and bearish labels appear above it. Historical events preserve the exact Global Regime color that was active when the crossover occurred, allowing older events to retain their original structural context rather than being recolored by the current regime.
➖PlotCandles➖
Optional PlotCandles can color price directly from the active Global Regime while maintaining independent body, wick, and border transparency.
➖How I use the ribbon➖
The indicator is most useful when the components are read together rather than treating any one color or crossover as a standalone signal.
A clean, high-ORDER ribbon with expanding CORE reflects a very different structural environment from a similarly colored ribbon whose ORDER is deteriorating and whose fast-edge transition has already begun. When CORE is higher than its HTF value, tha'ts also a bullish sign (and vice versa). Likewise, disagreement between chart CORE and Developing HTF CORE can provide useful context. Strong local structure may be developing inside a weaker higher-timeframe environment, or a lower-timeframe transition may be occurring while the next timeframe remains firmly established.
The 75/110 pair provides another layer of context without contaminating the primary regime calculation. For that reason, I view the indicator primarily as a market-structure and context tool, rather than a mechanical entry/exit system.
➖Final note➖
Moving averages are inherently derived from historical price, and no ribbon can predict future market direction. CORE, ORDER, Global Regime states, crossover events, and Developing HTF readings should be interpreted as descriptions of current and developing structure—not guarantees of continuation or reversal.
The value of the indicator is in combining multi-horizon OHLC4 structure, volatility-normalized strength, persistent regime ownership, and visually progressive ribbon transitions into one coherent framework.
➖A few chart examples➖
指标

Market Effort Response ProfileMarket Effort Response Profile is a behavioral price-profile indicator designed to examine how market effort and realized price response have interacted across different occupied price regions.
Rather than treating every price level equally, the indicator organizes recent market behavior into adaptive price regions and evaluates the relative activity and effort-response balance observed within each region.
The purpose is not to predict where price will move next. The profile provides a spatial view of how price has behaved across the analyzed sample.
How It Works
The indicator evaluates market behavior through two related components:
Effort represents the relative intensity of market movement and activity observed during the analysis window.
Response measures how effectively that effort translated into realized price movement.
These components are normalized so that their relationship can be compared across changing volatility conditions.
The resulting information is then mapped into an adaptive price profile.
Adaptive Occupied-Price Profile
Instead of dividing the entire chart range into fixed price intervals, the indicator builds its profile from price regions that were actually occupied during the analysis window.
Observed prices are organized into adaptive quantile-based regions.
For each region, the indicator aggregates behavioral activity and the relationship between effort and response.
The horizontal width of each profile strip represents the region's relative behavioral activity within the current sample.
Wider regions therefore represent greater observed activity relative to other regions in the same profile.
Profile Colors
The profile uses restrained behavioral coloring:
Teal regions indicate comparatively response-led behavior.
Muted red regions indicate comparatively effort-led behavior.
Neutral regions indicate a more balanced relationship between the two components.
These classifications are relative descriptions of historical behavior within the current analysis window. They are not bullish or bearish trade signals.
Profile Peak
The Profile Peak identifies the adaptive price region containing the highest smoothed behavioral activity in the current profile sample.
It provides a reference for where the strongest concentration of measured activity occurred.
The Profile Peak is descriptive only. It is not a price target, reversal probability, expected return, or guarantee that price will react there again.
Structural References
The indicator also tracks confirmed structural references derived from price behavior.
To keep the chart readable, only the nearest relevant support and resistance references around current price are displayed.
Each reference label contains the structural price and a normalized relative activity reading associated with the nearest profile region.
These references provide additional context for interpreting the effort-response profile; they should not be treated as guaranteed support or resistance.
Dashboard
The compact Effort Profile dashboard summarizes the current behavioral state:
EFFORT — normalized market effort.
RESPONSE — normalized realized price response.
EFFICIENCY — the relationship between response and observed effort.
BALANCE — identifies whether the current measurement is comparatively effort-led, response-led, or balanced.
PROFILE PEAK — price associated with the highest-activity profile region.
These measurements describe current and historical market behavior. They do not represent probabilities or trading recommendations.
Originality and Intended Use
Market Effort Response Profile is built around the relationship between behavioral effort, realized response, and spatial price occupancy.
Its profile is not constructed from traditional volume-at-price data or reversal-frequency probabilities.
The adaptive occupied-price geometry allows the profile to adjust to the actual distribution of observed prices instead of forcing the sample into a fixed full-range grid.
The indicator is intended for traders studying market behavior, structural interaction, movement efficiency, and the distribution of activity across price.
It can be used as analytical context alongside an independent trading methodology.
Calculation Timing
The profile is recalculated from the available analysis sample as new market data becomes available.
Confirmed structural references are used for the displayed support and resistance context.
Because the active analysis window changes over time, profile geometry, Profile Peak, behavioral classifications, and displayed structural references can also change as new observations enter the sample.
Limitations
The indicator analyzes historical and current price behavior. It does not know future market direction.
High historical activity at a price region does not imply that price will revisit or react from that region.
Effort-response relationships can change when volatility, liquidity, market structure, or broader market conditions change.
The Profile Peak is not equivalent to a conventional volume point of control.
Support and resistance references can fail.
Normalized readings are comparative analytical measurements and should not be interpreted as probabilities, expected returns, or historical win rates.
The indicator does not generate Buy or Sell signals and should not be used as a standalone trading system. 指标

Gecko ORB Small Range Breakout Strategy v1.4**ORB Small Range Breakout Strategy**
This strategy trades breakouts of the opening range, but only when that range is small or medium relative to price — the idea being that a tight, low-volatility opening range has more room left to run than one that has already made a large move.
**How it works**
1. **Opening Range (ORB):** The script builds a high/low range over a configurable start and end time (default 08:00–08:25, exchange-local time). This window is fully configurable, so the script works on any market/session — LSE, JSE, or otherwise — without modification.
2. **Classification:** Once the opening range closes, its size is measured as a percentage of the opening price and classified as SMALL, MEDIUM, or LARGE based on two adjustable thresholds. Only SMALL and MEDIUM ranges are considered tradeable; LARGE ranges are skipped for that session.
3. **Entry:** Within a configurable entry window after the opening range closes (default cutoff 11:00), a long is triggered on a close above the range high, and a short on a close below the range low — one trade per session, first breakout only.
4. **Stop/Target:** The stop is placed at the opposite side of the opening range. Take-profit can be set to a fixed R-multiple, a projection of the opening range's size, or disabled entirely (stop-only).
5. **Session close:** Optionally, any open position is force-closed at a configurable time of day.
**Inputs**
- Opening Range start/end time
- Entry cutoff time
- SMALL/LARGE classification thresholds (%)
- Take-profit mode (R-multiple, ORB projection, or none) and multiplier
- Optional end-of-session exit time
**Notes**
- The opening range and entry window are drawn on the chart (box + lines) each session so you can visually verify what the strategy is reacting to.
- This script does not use repainting logic — all decisions are based on confirmed price action within the defined windows.
- Backtest results shown in the Strategy Tester do not account for slippage or commissions unless configured in the strategy properties; please set these to match your broker before drawing conclusions from the equity curve.
- This script is provided for educational and informational purposes only. Past performance, whether real or simulated, is not indicative of future results. Nothing here constitutes financial advice — always test thoroughly and understand the logic before using any strategy with real capital. 策略

Clock_Live and Replay AwareClock — Live / Replay Aware
A simple on-chart clock that always tells you the truth about what time it's showing — whether you're trading live or running Bar Replay.
Why this exists
Most clock indicators only show your real-world time, which becomes misleading (or useless) the moment you activate TradingView's Bar Replay feature — you end up staring at a clock that has nothing to do with the price action on screen. This indicator detects which mode you're in and adapts automatically.
Features
LIVE mode (green): Displays your actual real-time clock, synced to live incoming ticks.
REPLAY mode (orange): Displays the timestamp of the bar currently being replayed, so the clock always matches what you're watching, not your wall clock.
CHART mode (gray): Shown when you're simply scrolled through history with no live feed active.
Countdown timer: Shows time remaining until the next bar closes — exact in live mode, and estimated in replay mode using a rolling average of how long recent replayed bars have taken to form (adapts automatically if you change replay speed).
Configurable timezone, 12h/24h format, date display, table position, and colors.
How replay detection works
Pine Script has no official flag for "is Bar Replay active." This script uses a reliable heuristic instead: on a genuine live (still-forming) bar, its scheduled close time is always in the future relative to the current time. During replay, the bar being replayed is historical, so its close time has already passed. Comparing the two lets the script tell live and replay bars apart with no false positives in normal use.
Notes
The replay countdown is an estimate, not exact — replay speed isn't exposed to Pine Script, so it's inferred from recent bar timing and may lag by a bar or two after you change speeds.
Clock updates are tick-driven (a Pine Script constraint), so on very quiet symbols the seconds display may not tick with perfect real-time smoothness. 指标

ES Clean Major Market Structure - HH HL LH LLES Clean Major Market Structure – HH HL LH LL
This indicator is designed to provide a clean visual representation of market structure by identifying meaningful swing highs and swing lows while filtering out smaller price movements.
The script classifies confirmed swing points as:
HH – Higher High: A swing high above the previous swing high.
HL – Higher Low: A swing low above the previous swing low.
LH – Lower High: A swing high below the previous swing high.
LL – Lower Low: A swing low below the previous swing low.
The goal is to make it easier to identify developing bullish and bearish market structure without filling the chart with signals from every small price fluctuation.
Market Structure
The indicator maintains a directional structure bias:
Bullish Structure
Higher Highs (HH)
Higher Lows (HL)
Dashboard displays: BULLISH
Watch for continued HL → HH development
Bearish Structure
Lower Lows (LL)
Lower Highs (LH)
Dashboard displays: BEARISH
Watch for continued LH → LL development
The structure dashboard is intended as a quick visual reference and should not be interpreted as an automatic trade signal.
Swing Strength
Swing Strength determines how many bars on each side of a potential swing are required before that swing can be confirmed.
For example, with Swing Strength set to 2, a pivot requires two bars on the left and two bars on the right.
Because right-side bars are required, HH/HL/LH/LL labels are confirmed after the actual pivot occurs and are plotted back on the pivot bar. They should not be interpreted as signals that were available at the exact moment of the labeled candle.
Minimum Swing Move
Minimum Swing Move filters smaller changes between swing points.
Increasing this value produces fewer, more significant structure labels. Decreasing it makes the indicator more sensitive to smaller price movements.
For ES, the default settings are:
Swing Strength: 2
Minimum Swing Move: 1.50 points
These settings can be adjusted depending on timeframe and trading style.
Additional Chart References
The indicator also displays:
EMA 14 – Short-term price momentum reference
SMA 20 – Trend reference
Session Open – Daily/session opening level
50% Session Midpoint – Midpoint between the developing session high and session low
Intended Use
This indicator is designed primarily as a market-structure visualization tool, not an automated entry system.
One possible way to interpret the structure is:
Bullish: HH → HL → HH
Bearish: LL → LH → LL
Traders may use the structure labels together with their own price-action, support/resistance, liquidity, risk-management, and higher-timeframe analysis.
The indicator can be used on different intraday timeframes. Lower timeframes generally produce more structure changes, while higher timeframes naturally filter more market noise.
Disclaimer: This script is provided for educational and informational purposes only. It does not provide financial advice or guarantee future market performance. Users are responsible for their own trading decisions and risk management. 指标

Impulse Retention Map [MQLSoftware]OVERVIEW
Impulse Retention Map shows how much of a sharp price move remains after it forms. It automatically fixes the move's origin, halfway level and closing endpoint, then follows subsequent closes to distinguish a partial retracement, a full unwind and a recovery after a deep retracement.
The question is simple: has price kept the move, given half of it back, or returned all the way to its origin? No manual anchors, external signal source or volume feed are required.
DETECTION AND ORIGINAL CONTRIBUTION
The script measures a short close-to-close displacement. With the default settings, a qualifying impulse must satisfy all of these conditions:
1. The absolute change from the close three bars earlier to the current close is at least 2.0 times ATR, with a minimum size of two price ticks. The 20-bar ATR reading is taken at the origin bar, before the three subsequent price changes being measured. The move therefore does not increase its own volatility benchmark.
2. Path efficiency is at least 0.75: the absolute net change divided by the sum of the three absolute close-to-close changes. A reading of 1 means no closing-price retracement inside the window.
3. The final close is in the directional outer 30% of the impulse window's high-low range: near the high for an upward move or near the low for a downward move.
ATR scaling, path efficiency and halfway retracements are established concepts. The contribution here is their use in one automatic, frozen displacement episode: detection uses a pre-window volatility reference, the resulting map has fixed price boundaries, and the subsequent close-based events follow an explicit lifecycle. It measures a short move's retention rather than constructing pivot-based trend waves, projecting reversal targets or evaluating signals supplied by another indicator.
A map is admitted on the first qualifying bar of a fresh directional burst, subject to spacing of at least one impulse window since the previous admission. Consecutive qualifying bars in the same direction do not create repeated maps. A burst blocked by the spacing rule is not queued for later admission. A newly admitted map replaces any still-active previous map; replacement is not treated as a successful outcome.
READING THE MAP
The three fixed references are:
100% — the close at which the impulse was detected.
50% — halfway between that close and the origin.
0% — the closing price at the beginning of the measured move.
Move retained (%) = 100 x (evaluated close - origin) / (impulse close - origin).
The same formula works for upward and downward impulses. For an upward move from 100 to 110, a later close at 107 retains 70%; a close at 112 retains 120%. Values above 100% describe extension beyond the original move. Values below 0% mean price closed beyond the origin in the opposite direction. These percentages are price-distance measurements, not success rates or probabilities.
Teal identifies upward impulses and rose identifies downward impulses. The half between the impulse close and midpoint uses the direction colour; the half between midpoint and origin uses a quieter amber tint. These are measurement areas, not prescribed entry, stop or target zones.
The UP/DOWN label reports the initial move in units of its pre-impulse ATR. The status panel shows retained movement, the lowest retained reading observed on a confirmed close since detection, the original price distance, the initial ATR multiple and the number of bars tracked. When an episode finishes, the panel shows a final snapshot until a new map is admitted.
EVENTS AND LIFECYCLE
Subsequent evaluation starts on the bar after detection. The impulse's own formation bars cannot supply a later outcome.
HALF BACK — the first subsequent close retains 50% or less, but remains above 0%.
UNWOUND — a close retains 0% or less. Tracking ends. A direct jump through the origin is recorded as UNWOUND without inventing an earlier HALF BACK event.
RECOVERED — after a HALF BACK event, a later close reaches or exceeds 100% retention. Tracking ends. This does not mean the entire intervening path held above the halfway line.
EXPIRED — the tracking limit is reached without an earlier terminal outcome; 60 bars by default. An unwind or recovery on the final allowed bar takes precedence over expiry.
REPLACED — a fresh qualifying impulse is admitted while the earlier map is still active. The earlier map stops at that bar. Its final status is available in the original impulse label's tooltip and as an event in the Data Window. Expiry also has a Data Window event; neither creates a separate outcome label on the chart.
Between events, the panel can show NEW IMPULSE, HOLDING, EXTENDED, DEEP RETRACE or REBUILDING. REBUILDING means a map that previously returned at least half has moved back above 50% but has not yet recovered the full original move.
The old episode is evaluated before a new one is admitted. Consequently, an outcome for the old map and a new impulse can occur on the same closed bar.
CONFIRMED BARS AND DISPLAY CHANGES
Detection, retained readings, outcome flags and alerts update only on confirmed chart bars. The script uses no higher-timeframe requests, future-bar data, pivots or backward-shifted event markers. A map starts at the detection bar, although its origin price comes from the earlier close. It is not drawn across the formation window as if it had been known then.
The display does evolve: an active map extends to each newly confirmed bar; finishing a map dims its existing drawings and updates its tooltip; older maps and their outcome labels are removed as the retention limits are reached. The latest reference labels move with the chart's right edge. These presentation changes do not move the recorded event bars or change a map's fixed price boundaries. They also mean the final historical appearance is not a literal recording of how bright each zone looked at every earlier moment.
Changing inputs, symbol, timeframe, feed or available history recalculates the script. Provider corrections and price adjustments can change past input data. Closed-bar processing does not prevent those external changes.
SETTINGS AND ALERTS
Detection controls the impulse window, minimum ATR-scaled move, minimum path efficiency, ATR baseline length and tracking duration. Defaults are 3 bars, 2.0 ATR, 0.75 efficiency, 20-bar ATR and a 60-bar tracking limit. The directional closing-location filter stays fixed at 70%.
Display controls how many maps remain visible (six by default), outcome labels, the status panel and its position, latest-map reference labels, and colours. Display settings do not alter detection or outcomes. The panel distinguishes initial warmup, unavailable price data, a flat price range and waiting for a qualifying move when no map has yet been created.
Five alert conditions are available: new up impulse, new down impulse, half of impulse returned, impulse fully unwound, and impulse recovered. Create the desired TradingView alert and select Once Per Bar Close. Alerts must be configured by the user; adding the indicator does not create them automatically.
USE AND LIMITATIONS
Add the indicator to a standard candlestick chart and read the latest fixed references alongside the panel. Higher movement or efficiency thresholds generally select fewer impulses. The parameters are heuristic filters, not optimized probabilities. The tool can use price data across crypto, forex, indices and stocks; it does not require traded or tick volume.
Only closes resolve the tracked outcomes. A wick through halfway or origin that closes back beyond it does not establish the corresponding close-based event. Session gaps are included in close-to-close displacement and can qualify as impulses. The script does not reconstruct intrabar order, identify participants, estimate order flow or distinguish a session gap from continuously traded movement.
Only one episode is active at a time. New impulses can replace unresolved ones, so the displayed map history is not a complete sample of every possible retracement. No aggregate win rate, trading expectancy, order fills, fees, slippage or profitability backtest is calculated. Synthetic chart types produce measurements of synthetic prices and should not be interpreted as execution-price evidence.
This is a descriptive chart-analysis tool, not a prediction of recovery or a recommendation to enter or exit a position. 指标

指标

Structure-Anchored VWAP [WillyAlgoTrader]📐 Structure-Anchored VWAP is an overlay indicator that anchors a true volume-weighted average price to market structure and re-anchors it automatically at every confirmed swing pivot, structure break, fast extreme, or one manual date — combining a pivot-based structure engine, an O(1) prefix-sum VWAP core, volume-weighted sigma bands, a retest entry model with ATR risk management, and a sectioned dashboard with session statistics.
The core insight: a VWAP anchored to the start of the current structural leg tells you the average price at which volume actually changed hands since this move began. That is the level participants in this leg are collectively break-even at. Session VWAP resets at midnight and ignores structure. Manual anchored VWAP requires you to drag it and re-drag it. This indicator keeps the anchor synchronised with the structure itself, and measures how stretched price is from that anchor in the leg's own volume-weighted standard deviations rather than in generic ATR units.
It works on any market and any timeframe. On instruments with no volume feed it falls back to time weighting automatically and says so in the dashboard.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A VWAP alone has no memory of structure — it does not know whether the market is making higher highs or lower lows, so it cannot know when its own anchor has gone stale. A structure detector alone tells you HH / HL / LH / LL but gives you no price level to trade against. Deviation bands built on ATR describe candle size, not participation, so they say nothing about where volume was actually transacted. And an entry signal without a fixed stop and target is not a trade, it is an opinion.
This indicator connects all four into one chain:
Pivot structure engine → anchor selection → prefix-sum anchored VWAP → volume-weighted sigma bands → retest detection → ATR risk model → session statistics
The structure engine finds confirmed swing highs and lows, filters them by ATR amplitude and enforces strict high/low alternation, so every anchor is a real structural turn rather than a passing wick. Anchor selection decides which of those turns starts a new leg, with four different policies for four trading styles. The prefix-sum core then computes the anchored VWAP for that leg — and because it also accumulates the sum of squared prices, the same pass produces the leg's own volume-weighted standard deviation, so the bands are derived from the same data as the line instead of being bolted on. The retest engine watches the distance between price and that line, requires price to leave and come back, and only then produces an entry. The risk model turns the entry into a fixed stop and three targets, and the statistics layer records what happened to each of them.
Remove any link and the chain stops working. Without structure anchoring, the VWAP measures a leg that ended days ago. Without the ATR amplitude filter, every minor wick creates a new anchor and the line resets constantly. Without the sigma bands, "far from VWAP" has no unit. Without the retest rule, every touch of the line is a signal, including the fifty touches that happen while price is glued to it. Without the risk layer, you know where to enter but not where you are wrong.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Prefix-sum VWAP core — any anchor evaluated in O(1), including a decayed one.
Three running totals are maintained on every bar, where p is the price source and w is the bar weight:
— S_w(t) = lam × S_w(t−1) + w(t)
— S_pw(t) = lam × S_pw(t−1) + p(t) × w(t)
— S_p2(t) = lam × S_p2(t−1) + p(t)² × w(t)
The sum over any leg is then recovered without looping:
— sum = S(t) − lam^(t−a+1) × S(a−1)
With lam = 1 this is an exact cumulative anchored VWAP — every bar of the leg keeps its full weight, the same quantity the built-in Anchored VWAP tool computes. With lam < 1 the same identity still holds, which is what makes the optional Half-life mode possible without a second engine.
Why this matters: re-anchoring becomes cheap. Moving the anchor does not require replaying the whole leg bar by bar, so the indicator can afford four anchor modes and legs up to 4000 bars long without a performance penalty.
2️⃣ Volume-weighted sigma bands — dispersion of the leg, not size of the candle.
Because the squared-price sum is already accumulated, the leg's variance comes out of the same pass:
— VWAP = sum_pw / sum_w
— sigma = sqrt( max( sum_p2 / sum_w − VWAP², 0 ) )
Bands are drawn at VWAP ± multiplier × sigma. Band 1 defaults to 0.5 sigma (the value-area edge of this leg), Band 2 to 2.0 sigma and is off by default.
Why this matters: an ATR band tells you how big recent candles were. A volume-weighted sigma band tells you how widely the volume of this specific leg was distributed around its own average price. Two markets with identical ATR but different participation profiles get different bands, and the "Premium / Fair value / Discount" classification in the dashboard becomes comparable across instruments.
3️⃣ Four anchor modes — one engine, four trading styles.
— Swing (default): a new leg starts at every confirmed pivot. The anchor is the opposite extreme, so a bullish leg is anchored at the swing low that preceded it.
— Structure break : a new leg starts only when price closes beyond the previous swing. The anchor is then the extreme that preceded the break, found by scanning back from that swing. Fewer legs, each tied to an actual break of structure.
— Fast : no confirmation delay. The bar printing the highest high or lowest low of the last N bars (default 30) is treated as a new extreme, and the leg flips the moment an extreme opposite to the previous one appears. When a bar prints both a new high and a new low, the candle direction decides which one is taken.
— Manual : a single leg from a chosen date and time, which reproduces the behaviour of the built-in Anchored VWAP tool inside the same framework — useful for comparing against a manual anchor or pinning a level.
4️⃣ Structure engine with ATR amplitude filter and strict alternation.
Pivots come from equal left/right lookback (default 55/55). A new pivot of the opposite type is only accepted when it clears an ATR-scaled amplitude:
— accept a new high when: pivotHigh − lastSwingLow ≥ minSwing × ATR(atrLen)
— accept a new low when: lastSwingHigh − pivotLow ≥ minSwing × ATR(atrLen)
Default minSwing 1.5, ATR length 13. A pivot of the same type as the last one does not create a new structural point — it only supersedes the previous extreme if it is more extreme. This enforces a clean alternating high-low-high-low sequence instead of clusters of adjacent highs.
Classification against the previous extreme of the same type, with an equality tolerance (default 0.1 × ATR):
— |current − previous| ≤ eqTol × ATR → EQH or EQL
— current > previous → HH or HL
— current < previous → LH or LL
5️⃣ Retest entry model — price must leave before it can come back.
Every bar the engine measures the relationship between the bar range and the anchored VWAP:
— tol = sigma × touchTolerance (default 0.25), or ATR × 0.1 while sigma is still zero
— touch = low ≤ VWAP + tol and high ≥ VWAP − tol
— outside = bullish leg ? low > VWAP + tol : high < VWAP − tol
An "away" counter increments on every outside bar and resets to zero on every touch. A retest fires only when a touch happens while the committed away counter has already reached the threshold (default 5 bars).
Why this matters: a raw "price touched VWAP" condition fires continuously in the chop that surrounds every mean. Requiring a genuine departure first converts an omnipresent condition into a discrete, countable event.
6️⃣ Volume balance — who controlled this leg.
While the leg accumulates, every bar's weight is assigned to one of two buckets by where it closed relative to the VWAP at that moment:
— close ≥ VWAP → volUp += w
— close < VWAP → volDn += w
— balance = volUp / (volUp + volDn) × 100
The dashboard shows this as a percentage with a bar gauge, and relabels it "Bars above VWAP" automatically when the instrument has no volume data. Above 50 % means most of the leg's participation happened above its own average price.
7️⃣ Signal strength — a transparent 0-100 context score.
Four independent components, published in full so the number is auditable rather than a black box:
— 40 pts × (volume balance aligned with leg direction, 0..1). For a bearish leg the balance is inverted before scoring.
— 25 pts if price sits on the leg's own side of the VWAP.
— 20 pts if price is not stretched beyond Band 2, i.e. |distance in sigma| ≤ band 2 multiplier.
— 15 pts if the leg has already produced at least one retest.
The score is clamped to 100 and shown with a gauge. This is a context filter, not a proven edge — it says how coherent the current leg is, nothing more.
8️⃣ VWAP memory levels — dead legs leave a level behind.
When a leg ends on a genuine direction flip, its final VWAP value is written to the chart as a dashed horizontal line. That line extends forward until price trades through it, then it is either removed or faded to dotted, depending on a setting. Up to four such levels are kept (configurable), and the newest push out the oldest.
When a level is created, the bars between the anchor and the current bar are scanned first, so a level that was already traded through is never shown as untouched.
9️⃣ Single-position trade model with break-even and outcome tracking.
A retest signal opens a trade only while flat — signals never stack. On entry, the levels are fixed once and never recalculated:
— slDistance = ATR(riskAtrLen) × slMultiplier
— long: SL = entry − slDistance, TP(n) = entry + slDistance × tpMult(n)
— short: SL = entry + slDistance, TP(n) = entry − slDistance × tpMult(n)
Presets set all four multipliers at once — Conservative 2.5 / 1R / 2R / 4R, Balanced 1.5 / 1R / 2R / 3R, Aggressive 1.0 / 1.5R / 2.5R / 4R, Scalping 0.8 / 0.8R / 1.5R / 2R, or Custom.
Break-even is optional and on by default: the first touch of TP1 moves the stop to the entry price, the entry label changes to show it now acts as the stop, and the stop line dims. TP1 still counts as a win. Hit checks begin only on the bar after entry and only on confirmed bars, so the entry bar's own range cannot close the trade it just opened.
🔟 Persistent trade forensics — the chart keeps the last result.
SL and TP lines are not deleted when the trade closes. They stay until the next entry, so the last trade remains readable on the chart: any target that was reached is redrawn as a solid teal line and its label gets a check mark, while untouched targets keep their original dashed style. Labels can show the distance from entry in percent, for example "SL 78120.5 (-0.36%)".
1️⃣1️⃣ Realtime correctness — ring buffers and a commit/undo pattern.
Functions that only run on some bars cannot use the history operator safely, because the history they see is sparse and does not correspond to chart bars. All per-bar values this indicator needs later are therefore written to explicit ring buffers on every single bar, and read back by index.
On top of that, the live leg uses a commit/undo pattern: statistics are always recomputed from the last confirmed state, and the provisional point for the forming bar is popped before a new one is pushed. A bar being formed can therefore never be counted twice, no matter how many ticks arrive.
1️⃣2️⃣ Continuous curve across anchor changes.
When a new anchor appears, the previous leg is not erased — it is cut exactly at the new anchor bar and frozen. The curve therefore has no gaps at handover points, including the case where a stronger extreme of the same type supersedes the previous one.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — Structure: On each confirmed bar the engine evaluates pivot highs and lows with equal left/right lookback, applies the ATR amplitude filter, enforces high/low alternation and classifies the result as HH, HL, LH, LL, EQH or EQL.
Step 2 — Weighting: The bar weight is volume, or 1.0 when the instrument has no volume. If spike clamping is on, the weight is capped at N × the 50-bar median volume so a single print cannot dominate the average.
Step 3 — Accumulation: The three running totals of weight, price × weight and price² × weight are advanced, decayed by lam if Half-life weighting is selected.
Step 4 — Buffering: The totals plus high, low, close and ATR are appended to ring buffers, one entry per bar, with the current bar's provisional entry overwritten rather than duplicated on repeat ticks.
Step 5 — Anchor decision: The active anchor mode decides whether this bar starts a new leg and where that leg's anchor sits.
Step 6 — Leg build: On a new anchor the previous leg is trimmed to the anchor bar, frozen and archived, a memory level is created if the direction actually flipped, and the new leg is replayed once from the anchor to the current bar. On every other bar the live leg simply advances by one point.
Step 7 — Readouts: VWAP, sigma, distance in sigma and percent, zone, volume balance, leg age and the strength score are computed for the current bar.
Step 8 — Signal: The retest rule is evaluated. A qualifying retest, on a confirmed and warmed-up bar, while flat, becomes an entry.
Step 9 — Risk: On entry the stop and three targets are fixed. On later confirmed bars they are tested for hits, break-even is applied after TP1, and the trade is closed by stop or final target.
Step 10 — Reporting: Lines, labels, markers, the dashboard and alerts are updated. Closed trades update the win/loss counters and the form strip.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator. Defaults are tuned for 15m to 4H swing structure.
2. Watch the coloured curve — it is the anchored VWAP of the leg the market is currently in.
3. Wait for a Long ▲ or Short ▼ marker. That is a retest of the VWAP in the direction of the leg.
4. Read the Trade section of the dashboard for the stop, the three targets and the R:R.
5. If signals are too frequent, raise "Bars away before a retest counts". If legs are too frequent, raise pivot strength or the minimum swing size.
👁️ Reading the chart:
— 🟢 Green curve = bullish leg, anchored at the swing low that started it.
— 🔴 Red curve = bearish leg, anchored at the swing high that started it.
— Shaded band around the curve = ± sigma of this leg. Price inside it is at fair value for the leg.
— 🟢 Long ▲ / 🔴 Short ▼ marker = a retest entry was taken on that bar.
— Dotted blue line = entry. Solid red line = stop. Dashed green lines = TP1, TP2, TP3.
— A target that turns solid teal with a ✓ in its label was reached.
— An orange entry label reading "→ SL (BE)" means the stop has been moved to break-even.
— Dashed horizontal level far from the curve = a memory level, the final VWAP of a finished leg.
— HH / HL / LH / LL / EQH / EQL tags mark every confirmed pivot.
📊 Dashboard fields:
— Trend : direction of the current leg.
— Signal : LONG, SHORT or Wait. A new trade can only open while flat.
— Strength : the 0-100 context score with a gauge.
— Last event : the most recent new leg or retest.
— Timeframe : the chart resolution.
— Mode : active anchor mode and weighting, plus a note when the symbol has no volume.
— Anchor : structure tag and price of the bar the leg is anchored to.
— Leg age : bars since the anchor and the price move from it.
— VWAP : the anchored VWAP on the current bar.
— Price vs VWAP : distance in sigma and in percent.
— Zone : Premium above Band 2, Discount below it, Fair value in between.
— Vol above VWAP : share of the leg's weight transacted above the VWAP, with a gauge.
— SL / TP1 / TP2 / TP3 : the fixed levels of the open trade. A ✓ marks a reached target, "BE @" marks a stop moved to entry.
— R:R (TP1) and SL Dist % : reward-to-risk at the first target and the stop distance as a percentage of entry.
— Trades / W / L / Win rate / Form : closed trades in the loaded history, the win-loss split, the win rate with a gauge and the last ten outcomes as ▰ and ▱.
🔧 Tuning guide:
— Too many legs, the line resets constantly: raise pivot strength (55/55 → 80/80) or the minimum swing size (1.5 → 3.0).
— Legs appear too late: lower pivot strength, or switch the anchor mode to Fast for immediate flips.
— Too many entries: raise "Bars away before a retest counts" and lower the touch tolerance.
— The line drifts too far from price on long legs: switch Weighting to Half-life. This is no longer a textbook VWAP, and the dashboard says so.
— Comparing against the built-in Anchored VWAP tool: set the mode to Manual with the same anchor time, price source to hl2, weighting to Cumulative, and turn volume clamping off.
— Stops feel too tight or too wide: change the Risk Preset before touching individual multipliers.
⚙️ KEY SETTINGS
⚙️ Main Settings:
— Pivot strength left / right (default 55 / 55): bars required on each side of a swing. Right is the confirmation delay.
— Minimum swing size (default 1.5 × ATR): amplitude filter for new pivots. 0 disables it.
— ATR Length (default 13): ATR used by the swing filter and the equality tolerance.
— Re-anchor on (default Swing): Swing, Structure break, Fast or Manual.
— Fast mode: extreme lookback (default 30): lookback for the Fast mode only.
— Equal high/low tolerance (default 0.1 × ATR): threshold for EQH and EQL tags.
— Manual anchor : date and time for the Manual mode, shown in the chart's timezone.
📐 Anchored VWAP:
— Price source (default hl2): hl2 matches the built-in tool, hlc3 weights closes more, close is the most reactive.
— Weighting (default Cumulative): Cumulative is a true VWAP, Half-life fades older bars.
— Half-life (default 21 bars): only used by Half-life weighting.
— Clamp volume spikes (default on, 4 × median): caps outlier volume bars.
— Max leg length (default 4000 bars): keeps very old anchors bounded.
📏 Deviation Bands:
— Band 1 (default on, 0.5 sigma): inner band.
— Band 2 (default off, 2.0 sigma): outer band, also defines the Premium and Discount zones.
— Fill transparency (default 90).
🎯 Signals & Levels:
— Bars away before a retest counts (default 5).
— Touch tolerance (default 0.25 sigma).
— VWAP memory levels (default on, max 4, crossed levels removed).
🛡️ Risk Management:
— Risk Preset (default Balanced): Conservative, Balanced, Aggressive, Scalping or Custom.
— ATR Length (SL) (default 13).
— SL ×ATR / TP1 / TP2 / TP3 ×Risk (defaults 1.5 / 1.0 / 2.0 / 3.0): used by the Custom preset.
— Break-Even After TP1 (default on).
— Show SL/TP Lines, Labels, % Distance (all on by default).
— Entry / SL / TP Line Style (defaults Dotted / Solid / Dashed).
🎨 Visual:
— Theme (default Auto): Auto detects the chart background, Dark and Light force it.
— Show Buy/Sell Signals, HH/HL/LH/LL, Leg Background, Watermark .
— SL/TP Label Font Size (default Small).
— Finished legs kept on chart (default 30).
📊 Dashboard:
— Position (default Top Right) and four independent section switches: Market, VWAP, Trade, Stats.
🔔 ALERTS
— 🟢 LONG — VWAP retest entry, with price, VWAP, SL, TP1, TP2, TP3 and R:R
— 🔴 SHORT — same payload, short side
— 🛑 SL HIT — entry and stop price. Reported as 🛡️ BE STOP-OUT when the stop had already been moved to break-even
— 🛡️ BREAK-EVEN — stop moved to entry after TP1 (optional)
— 🎯 TP1 HIT, 🎯🎯 TP2 HIT, 🏆 TP3 HIT — first touch of each target (optional)
— 🟢 New bullish leg / 🔴 New bearish leg — a new anchor was set (optional)
— 🔵 Close above VWAP / 🔵 Close below VWAP — the close crossed the anchored VWAP (optional)
Entry alerts support both plain text and a JSON webhook payload. All alerts fire on bar close.
⚠️ IMPORTANT NOTES
— 🚫 No repainting of confirmed values. Every structure event, entry, stop, target and alert is evaluated only when barstate.isconfirmed is true. Pivots use equal left and right lookback, so the swing point is in the past by the "right" value at the moment it becomes known — that is delayed confirmation, not a look into the future. Stop and target hits are tested only from the bar after entry. Alerts fire once per bar close.
— 📐 What does update intrabar. The VWAP value of the leg currently in progress moves while the bar is forming, because that is what an anchored average does. Values on closed bars never change. A commit/undo pattern makes sure a forming bar is never counted twice in the statistics.
— 📐 The unfinished leg can be shortened. When a stronger extreme of the same type is confirmed, the current leg is cut at that point and a new leg starts there. Legs that have already been archived are never modified.
— 📊 The statistics are not a backtest. Trades, win rate and the form strip are counted over the history currently loaded on the chart and reset when the chart reloads or a setting changes. They describe how this rule set behaved on the visible data. Past performance does not guarantee future results.
— 🧮 The strength score is a context filter. Its four components and weights are published above precisely so it can be judged on its merits. It measures the internal coherence of the current leg, not the probability of any outcome.
— ⚖️ Half-life weighting is not a VWAP. When that mode is selected the line is an exponentially weighted average, useful on instruments without volume, but it is no longer the textbook volume-weighted average price. The dashboard states the active mode at all times.
— 🌐 Universal compatibility. Works on stocks, futures, forex, crypto and indices, on every timeframe. Where no volume data exists the weighting falls back to time and the dashboard relabels the volume-balance row accordingly.
— 🛠️ Decision support, not automation. This is an anchored VWAP and structure analysis tool with a risk framework attached. It marks anchors, measures distance in the leg's own units, detects retests and lays out stops and targets — trade decisions remain yours. 指标

FrenchFinance_Funding v0.1Shows the perpetual funding rate of the charted coin, averaged across Binance, Bybit and OKX USDT perpetuals, as coloured columns. It is a display tool: it tells you who is paying to hold a position and how unusual that is. It gives no buy or sell signal.
HOW IT WORKS
• The coin is detected from the chart's base currency (BTC, ETH…). The funding rate of its USDT perpetual is requested on each selected venue through TradingView's crypto derivatives data (the same "Funding Rate" metric as TradingView's built-in indicators) and averaged with equal weights; venues without that perpetual are skipped. On a stock, index or forex chart nothing is shown, unless you set a coin manually.
• Column height: z-score of the funding over the last 100 bars (default), or the raw funding in %.
• Colour: green when longs pay, red when shorts pay. The further the value is from its recent norm, the brighter the colour.
• Label on the last bar: current funding in %, or "Funding not available on this pair".
SETTINGS
• Extremes: z-score threshold (default 1.5 over 100 bars) or absolute thresholds in %.
• Venues can be switched on and off. Bar height, clipping, data scale and colours are adjustable.
ALERTS
Two alerts: funding extremely positive (longs pay) and funding extremely negative (shorts pay). They report a state, not a trade.
NOTES
• The last bar shows the predicted funding, which keeps updating until settlement; closed bars do not change.
• Built with the open-source TradingView "Request" library (cryptoDerivativeMetric). Funding is information about positioning, not a forecast. 指标

OSOK Opening TimesOSOK Opening Times marks the opening times of active trading periods with vertical lines. It automatically adjusts the periods shown to match your chart timeframe, using solid lines for the larger period and dotted lines for the smaller active period.
Each boundary pair marks the current period's opening and the next period's opening . This creates a clear time reference for the active day, week, month or quarter.
Timeframe visibility
The breakdown below shows the default line styles when all visibility settings are enabled.
Intraday below 1D, including 15m, 1H and 4H
Solid: current week opening to next week opening.
Dotted: active day opening to next day opening.
Daily - 1D
Solid: current month opening to next month opening.
Dotted: active week opening to next week opening.
Weekly - 1W
Solid: current quarter opening to next quarter opening.
Dotted: active month opening to next month opening.
Monthly - 1M
Solid: none.
Dotted: current quarter opening to next quarter opening.
Other intervals above 1D, such as 2D, 2W and 3M
No lines are displayed.
A quarter is a three-month period. Quarterly boundaries appear on the 1W and 1M charts; the 3M chart itself displays no lines.
Active periods and shared boundaries
Only the active periods are displayed. As new periods begin, their boundaries replace the previous markers. On intraday charts, daily dotted lines bracket only the active daily candle.
When two displayed boundaries coincide, the larger period's line takes precedence. The first daily candle of the week uses the weekly opening line as its starting boundary, avoiding a duplicate daily line.
Appearance and customization
Solid lines: black at 30% opacity by default.
Dotted lines: black at 100% opacity by default.
Line width: 1 by default.
Visibility, color, opacity, style and width can be adjusted in the indicator's settings. Separate style settings are available for the different chart contexts.
Opening times and chart support
The indicator follows the symbol's TradingView candle sessions. Changing the chart's display timezone does not redefine those openings.
Upcoming boundaries use projected opening times. The active periods are determined by the latest chart bar, including when using Bar Replay.
The indicator supports standard time-based charts and Heikin Ashi. Tick, Renko, Range, Kagi, Line Break and Point & Figure charts are excluded.
指标

ORB 15 Break + Retest ConfirmationThis indicator is designed for use on a 5-minute chart and identifies a specific Opening Range Breakout setup using the first 15 minutes of the regular trading session.
It automatically calculates the ORB 15 High (15H) and ORB 15 Low (15L) from the 9:30 AM to 9:45 AM New York session. Once those levels are established, the script waits for a valid breakout.
A bullish setup begins only when a completed 5-minute candle closes above ORB 15H. After the breakout, the indicator waits for price to return and retest the 15H level. If price touches or slightly penetrates the level and the 5-minute candle closes back above it, the script generates a LONG confirmation.
A bearish setup works the same way in reverse. A completed 5-minute candle must first close below ORB 15L. The script then waits for price to retest the 15L level from below. If price touches or slightly crosses the level and the candle closes back below it, the script generates a SHORT confirmation.
The script uses a sequential state-based approach, so a retest signal cannot occur unless a valid breakout happened first. Wick-only breakouts are ignored, and signals are evaluated only on completed 5-minute candles.
The indicator also includes a configurable retest tolerance and a maximum number of bars allowed for the retest to occur. If the breakout fails or the retest does not happen within the defined window, the setup is reset.
This tool is intended to help identify structured breakout → retest → confirmation setups around the 15-minute opening range.
Disclaimer: This indicator is provided for educational and informational purposes only and does not constitute financial or investment advice. Signals may be inaccurate, delayed, or fail under certain market conditions. Always perform your own analysis, use appropriate risk management, and trade at your own risk. The author is not responsible for any losses resulting from the use of this script. 指标

Session Breakout ContextMulti-Market Session Breakout Context
Description
Multi-Market Session Breakout Context is a rule-based intraday indicator designed to help traders organize session structure across gold, forex pairs, and selected index instruments. It was originally developed for XAUUSD and can also be applied to other markets whose session behavior, liquidity, and data quality are suitable for this type of analysis.
The indicator tracks the Asia, London, and New York session ranges using the America/Chicago timezone. It displays session highs, lows, and midpoint reference levels, then classifies selected price movements as directional breakouts or sweep/fade conditions. The chart markers and dashboard are intended to support discretionary analysis and trade planning. They do not place orders, manage positions, or guarantee a market outcome.
The main session conditions are:
•London breakout: price moves beyond the completed Asia session range.
•London fade: price sweeps an Asia range boundary and satisfies the rule-based reversal filters.
•New York breakout: price moves beyond the completed London session range.
•New York fade: price sweeps a London range boundary and satisfies the rule-based reversal filters.
•Asia breakout: price moves beyond the completed New York session range.
The indicator also provides additional market context through pivot-based directional readings, RSI divergence conditions, volatility measurements, volume-derived pressure and spread classifications, prior-day levels, previous-week levels, daily range references, weekly open, four-hour swing references, and a fixed time blackout window. These components are contextual filters. They are not independent guarantees of direction, probability, or profitability.
The optional dashboard summarizes the current session state, rule-based directional alignment, reference levels, entry and stop planning zones, target reference levels, and hypothetical point movement. Any displayed score is a rule-based alignment score, not a statistically validated probability or accuracy rate. Any displayed point movement is hypothetical and does not represent broker P&L, account performance, or a Strategy Tester result.
How to use the indicator
1.Apply the indicator to a standard candlestick chart.
2.Begin with XAUUSD and a lower intraday timeframe such as 5 minutes or 15 minutes.
3.Confirm that the chart symbol, exchange or broker feed, timezone, and session schedule are appropriate for your market.
4.Allow the relevant session range to form before interpreting its breakout or fade conditions.
5.Use the plotted levels as analytical references rather than guaranteed entry or exit prices.
6.Independently evaluate market structure, spread, volatility, scheduled events, liquidity, and position risk before making any trading decision.
7.Test the indicator on historical data and in a simulated environment before considering live use.
The displayed session schedule is based on fixed Chicago-time windows. The indicator should therefore be checked after daylight-saving changes and on every symbol or data feed where it is used. Session behavior can differ between spot metals, forex pairs, CFDs, futures, and other instruments.
Signal interpretation
A green or red breakout marker identifies a rule-based directional breakout classification. A blue or orange fade marker identifies a rule-based sweep/fade classification. These classifications describe what the indicator detected; they are not instructions to buy or sell and do not predict how far price will move.
Signals may depend on the active chart bar and on confirmed pivot information. A condition can change before the realtime bar closes. Users should evaluate signals on confirmed bars when they require stable, repeatable readings and should not assume that every historical marker was available at the beginning of the bar where it appears.
The indicator is intended for standard time-based candles. Signal interpretation may be misleading on non-standard chart types such as Heikin Ashi, Renko, Kagi, Point & Figure, Line Break, or Range charts.
Example screenshots
The following screenshots show selected visual examples on XAUUSD. They demonstrate how the indicator labels different session conditions. They are illustrative examples only and are not a complete record of all signals.
1. Full XAUUSD overview
Full overview of the indicator on XAUUSD showing session ranges, reference levels, breakout and fade markers, and the rule-based dashboard.
2. London fade long
London fade-long example after price sweeps the lower boundary of the completed Asia range. The marker represents a rule-based condition, not a guaranteed reversal.
3. London fade short
London fade-short example after price sweeps the upper boundary of the completed Asia range. Traders should independently evaluate confirmation, stop placement, and market conditions.
4. London sell
London bearish breakout example showing a downside break of the Asia session range. The displayed level is an analytical reference and does not represent an executed order.
5. New York sell
New York bearish breakout example showing a downside break of the completed London session range. Results may vary according to symbol, data feed, spread, liquidity, and execution conditions.
6. New York fade long
New York fade-long example after price sweeps the lower boundary of the completed London range. This is a rule-based signal classification for discretionary analysis.
7. New York fade short
New York fade-short example after price sweeps the upper boundary of the completed London range. The indicator does not guarantee continuation or reversal.
The screenshots are visual examples of the indicator’s signal classifications and are not a performance record. They do not show every signal, guarantee future results, or account for spread, slippage, commissions, liquidity, or execution delay. Signal behavior may vary across instruments, brokers, data feeds, and timeframes.
Limitations
This indicator is a decision-support and chart-organization tool. It is not investment advice, an automated trading system, a broker connection, or a guarantee of profit. It does not determine position size, account risk, contract quantity, execution quality, or whether a trade is appropriate for a particular user.
The indicator does not use a broker-level order book or guarantee access to true exchange-level volume. Volume-derived calculations may behave differently on symbols with limited, synthetic, tick, or unavailable volume. Reference levels and classifications can also vary according to the selected symbol, historical data, chart timeframe, session template, and data provider.
Historical examples should not be interpreted as evidence of future performance. Any decision to trade remains the user’s responsibility. Always consider the possibility of loss and use risk controls appropriate to your own circumstances.
Release notes
Initial public release of the Multi-Market Session Breakout Context indicator. This version provides Asia, London, and New York session levels, rule-based breakout and fade classifications, contextual reference levels, and an optional dashboard for discretionary chart analysis.
指标

FootprintKitAnalysis toolkit for the native footprint API introduced in Pine v6. It turns a `footprint` object into aggregated row statistics, price-interval measurements, low and high volume node runs, stacked imbalances, unfinished auction reads, absorption reads and multi-bar composite profiles.
It is written for script authors who build their own footprint tools and who would otherwise re-implement the same row loops in every script.
WHY THE LIBRARY NEVER CALLS request.footprint()
Pine allows only one unique footprint request per script. If the library issued that request internally it would consume the caller's single slot, and the importing script could no longer query the footprint on its own terms. So the caller makes the one allowed call and passes the resulting object into every function.
The consequence is that the library performs no requests, draws nothing and keeps no persistent state outside the Profile object you create yourself. There is nothing in it that can repaint.
WHAT IT COMPUTES THAT THE API DOES NOT EXPOSE
- Stacked imbalances. The API flags imbalance per row; the stack of consecutive flagged rows is what carries meaning in footprint reading, and it has to be assembled.
- Unfinished auction at the extremes of a bar, i.e. an extreme row that still shows trade on both sides.
- Volume traded inside an arbitrary price interval, with rows that only partly overlap the interval counted pro rata.
- Runs of thin rows, the price pockets a move passed through without trade, and runs of heavy rows, the shelves inside the bar.
- A composite profile across several bars with its own point of control and value area. request.footprint() returns one bar at a time; feeding successive bars into a Profile builds the multi-bar picture the single call cannot give.
- Distribution shape metrics that read the whole profile rather than only its peak.
FORMULAS
Aggressive volume per row and per interval is derived from total volume V and delta D as buy = (V + D) / 2 and sell = (V - D) / 2. This is exact by the definition of delta and avoids depending on optional per-row accessors.
slice() weights each row by the fraction of its height that falls inside the requested interval, k = overlap / rowHeight, clamped to 1. Counting a boundary row either whole or not at all is the usual source of error in hand-written versions.
concentration() is POC row volume divided by mean row volume. A value near 1 means volume was spread evenly, a high value means one price row absorbed most of the activity.
dispersion() is the Shannon entropy of the row volume distribution, normalised by ln(n) to the 0 to 1 range: H = -sum(p * ln p) / ln(n), where p is a row's share of bar volume. Zero means all volume sat in one row, one means a perfectly even spread. Unlike concentration it distinguishes a bar with two heavy rows from a bar with one.
deltaCentroid() returns the centre of mass of absolute delta as a fraction of the bar range from the low, showing where aggression concentrated regardless of which side was aggressive.
absorption() splits the bar range into thirds, measures each extreme third with slice(), and reports absorption when a third holds at least the requested share of bar volume while its delta points against the direction of the bar. Aggression that meets size and fails to move price is the signature of a passive participant taking the other side.
The composite value area grows outward from the point of control, repeatedly taking the heavier of the two neighbouring buckets until the requested share of total volume is enclosed.
USAGE
import Smart-Day-Trader/FootprintKit/1 as fpk
footprint fp = request.footprint(4, 70, 300)
fpk.RowStats s = fpk.stats(fp)
float conc = fpk.concentration(s)
float pos = fpk.pocPosition(s, high, low)
array voids = fpk.runs(fp, s, 0.4, 3, true)
= fpk.wicks(fp, open, high, low, close)
NOTES
A plan with footprint data access is required for the data itself; the library compiles on any plan because it makes no requests.
Choose ticks per row relative to the instrument's tick size rather than copying a default. On NASDAQ 100 E-mini futures the tick is 0.25 points, so 4 ticks per row equals one point and yields roughly 20 to 30 rows on a 5 minute bar. A value of 20 there would collapse the same bar into 4 rows, at which point concentration, entropy and row runs stop carrying information.
All functions accept a na footprint and return empty or na results rather than failing, so they are safe to call on bars without data.
REFERENCE
stats(fp)
Aggregates every row of a footprint in a single pass: totals, POC, delta,
imbalance counts and the price bounds actually covered by rows. Reading these values
one by one costs several loops over the same array; this does it once.
Parameters:
fp (footprint) : Footprint object returned by request.footprint(). Safe to pass na.
Returns: A RowStats object. When the footprint is na or empty, `n` is 0 and the
float fields are na.
concentration(s)
Concentration of the bar's volume: POC row volume divided by the mean row
volume. A value near 1 means volume was spread evenly across the bar; a high value
means a single price row absorbed most of the activity.
Parameters:
s (RowStats) : RowStats produced by stats().
Returns: The ratio, or na when statistics are empty.
dispersion(fp, s)
Normalised Shannon entropy of the volume distribution across rows, scaled to
0 to 1. Zero means all volume sat in one row, one means perfectly even spread. Unlike
concentration() this reads the whole shape rather than just the peak, so a bar with
two heavy rows is distinguished from a bar with one.
Parameters:
fp (footprint) : Footprint object.
s (RowStats) : RowStats produced by stats() for the same footprint.
Returns: Entropy in the 0 to 1 range, or na when fewer than two rows carry volume.
pocPosition(s, barHigh, barLow)
Where the POC sits inside the bar's range, as a fraction from the low.
0 places the heaviest row at the low of the bar, 1 at the high.
Parameters:
s (RowStats) : RowStats produced by stats().
barHigh (float) : High of the bar.
barLow (float) : Low of the bar.
Returns: Position clamped to 0 to 1, or na when the range is degenerate.
deltaCentroid(fp, barHigh, barLow)
Centre of mass of absolute delta inside the bar, as a fraction from the low.
Shows where aggression was concentrated regardless of which side was aggressive,
which often differs from where total volume sat.
Parameters:
fp (footprint) : Footprint object.
barHigh (float) : High of the bar.
barLow (float) : Low of the bar.
Returns: Position in the 0 to 1 range, or na when there is no delta to weight by.
slice(fp, priceA, priceB)
Volume traded inside an arbitrary price interval. Rows that only partly
overlap the interval are counted in proportion to the overlapped fraction of their
height, so the result is correct even when the interval boundaries fall mid-row.
This is the primitive behind wick, zone and level measurements.
Parameters:
fp (footprint) : Footprint object.
priceA (float) : One boundary of the interval. Order does not matter.
priceB (float) : The other boundary of the interval.
Returns: A Slice object. All fields are 0 and `share` is na when nothing overlaps.
wicks(fp, o, h, l, c)
Splits the bar's volume into upper wick, body and lower wick using slice(),
so partially overlapped rows are handled correctly. An empty upper wick slice on a
bar with a long upper shadow means price travelled there without trading size, which
reads very differently from a wick that carries volume.
Parameters:
fp (footprint) : Footprint object.
o (float) : Open of the bar.
h (float) : High of the bar.
l (float) : Low of the bar.
c (float) : Close of the bar.
Returns: A tuple of Slice objects.
runs(fp, s, ratio, minRun, below)
Finds every group of consecutive rows whose volume is below or above a
multiple of the bar's mean row volume, and returns them as price spans. With
below = true this locates thin rows, the price pockets a move passed through without
trade; with below = false it locates the heavy shelves inside the bar.
Parameters:
fp (footprint) : Footprint object.
s (RowStats) : RowStats produced by stats() for the same footprint.
ratio (float) : Multiplier applied to the mean row volume to form the threshold.
minRun (int) : Minimum number of consecutive rows required to report a span.
below (bool) : When true, keep rows at or below the threshold; when false, at or above.
Returns: An array of Span objects, ordered as the rows are ordered. Empty when nothing
qualifies.
stacks(fp, minRun, buySide)
Finds stacked imbalances: runs of consecutive rows all flagged on the same
side. The native API exposes the flag per row, but the stack is what carries meaning
in footprint reading, and stacks have to be assembled by hand.
Parameters:
fp (footprint) : Footprint object.
minRun (int) : Minimum number of consecutive flagged rows to report, commonly 3.
buySide (bool) : When true, collect buy imbalance stacks; when false, sell imbalance stacks.
Returns: An array of Span objects covering each stack. Empty when none reach minRun.
unfinished(fp, tol)
Tests the extreme rows for an unfinished auction: an extreme that still shows
trade on both sides, meaning the move stopped before either side was cleared out.
A finished extreme has one side at or near zero.
Parameters:
fp (footprint) : Footprint object.
tol (float) : Fraction of the extreme row's own volume below which a side counts as empty.
Use 0 for a strict test, or a small value such as 0.05 to tolerate noisy feeds.
Returns: A tuple of booleans. Both false when the footprint is empty.
absorption(fp, s, o, c, minShare)
Reads absorption at the extremes of the bar: one third of the bar's range
holding a large share of the volume with delta pointing against the bar's direction.
Aggression that meets size and fails to move price is the signature of a passive
participant taking the other side.
Parameters:
fp (footprint) : Footprint object.
s (RowStats) : RowStats produced by stats() for the same footprint.
o (float) : Open of the bar.
c (float) : Close of the bar.
minShare (float) : Minimum share of bar volume the third must hold, for example 0.4.
Returns: 1 when sellers were absorbed at the lows of an up bar, -1 when buyers were
absorbed at the highs of a down bar, 0 otherwise.
newProfile(step)
Creates an empty composite profile. request.footprint() delivers one bar at a
time; feeding successive bars into a profile builds the multi-bar picture the single
call cannot give on its own.
Parameters:
step (float) : Price bucket height. Use the row height from RowStats to keep the composite
at the same resolution as the footprint itself.
Returns: An empty Profile object.
method feed(p, fp)
Folds one bar's rows into the profile. Buckets are keyed by rounded row
midpoint and kept sorted, so repeated calls stay ordered and lookups stay cheap.
Call once per confirmed bar.
Namespace types: Profile
Parameters:
p (Profile) : Profile to update, modified in place.
fp (footprint) : Footprint object for the bar being added.
Returns: Nothing. The profile is mutated.
method sum(p)
Total volume held by the profile.
Namespace types: Profile
Parameters:
p (Profile) : Profile to read.
Returns: Sum of all bucket volumes, or 0 when the profile is empty.
method poc(p)
Point of control of the composite profile.
Namespace types: Profile
Parameters:
p (Profile) : Profile to read.
Returns: Centre price of the heaviest bucket, or na when the profile is empty.
method valueArea(p, pct)
Value area of the composite profile, grown outward from the point of control
by repeatedly taking the heavier neighbouring bucket until the requested share of
total volume is enclosed.
Namespace types: Profile
Parameters:
p (Profile) : Profile to read.
pct (float) : Share of total volume to enclose, expressed 0 to 1, for example 0.7.
Returns: A tuple of prices, both na when the profile is empty.
method reset(p)
Empties the profile while keeping its bucket size, ready for a new window.
Namespace types: Profile
Parameters:
p (Profile) : Profile to clear, modified in place.
Returns: Nothing. The profile is mutated.
RowStats
Aggregated statistics for every row of a single bar's footprint.
Fields:
n (series int) : Number of rows. Zero when the footprint holds no data.
total (series float) : Sum of row volume across the bar.
avg (series float) : Mean volume per row.
maxVol (series float) : Volume of the heaviest row, i.e. the POC row.
minVol (series float) : Volume of the lightest row.
pocVol (series float) : Same as maxVol, kept for readability at call sites.
pocTop (series float) : Upper price bound of the POC row.
pocBot (series float) : Lower price bound of the POC row.
pocMid (series float) : Midpoint of the POC row.
pocIdx (series int) : Index of the POC row inside the rows array, -1 when empty.
buy (series float) : Aggressive buy volume of the bar, derived as (total + delta) / 2.
sell (series float) : Aggressive sell volume of the bar, derived as (total - delta) / 2.
delta (series float) : Net delta of the bar summed across rows.
buyImb (series int) : Count of rows flagged as buy imbalances.
sellImb (series int) : Count of rows flagged as sell imbalances.
top (series float) : Highest price covered by any row.
bot (series float) : Lowest price covered by any row.
rowH (series float) : Height of one row in price units.
Span
A contiguous group of rows inside one bar, reported as a price span.
Fields:
top (series float) : Upper price bound of the span.
bot (series float) : Lower price bound of the span.
idxA (series int) : Index of the first row of the span.
idxB (series int) : Index of the last row of the span.
count (series int) : Number of rows in the span.
vol (series float) : Total volume inside the span.
delta (series float) : Net delta inside the span.
Slice
Volume measured over an arbitrary price interval, with partial rows counted pro rata.
Fields:
total (series float) : Volume inside the interval.
buy (series float) : Aggressive buy volume inside the interval.
sell (series float) : Aggressive sell volume inside the interval.
delta (series float) : Net delta inside the interval.
share (series float) : Interval volume divided by the bar's total volume, 0 to 1.
Profile
Composite volume profile accumulated from several bars' footprints.
Fields:
step (series float) : Price bucket size. Rows are folded into buckets of this height.
price (array) : Bucket centre prices, kept sorted ascending.
vol (array) : Volume per bucket, index-aligned with `price`.
dlt (array) : Delta per bucket, index-aligned with `price`.
脚本库

Market Transition Pressure EngineMarket Transition Pressure Engine is a behavioral-state framework designed to evaluate whether current market behavior remains relatively stable or is developing internal pressure consistent with a potential state transition.
Rather than attempting to predict the direction of the next move, the framework measures changes occurring inside the current market environment and organizes that evidence into a confirmed lifecycle.
How It Works
The engine evaluates five normalized behavioral dimensions:
• Directional Efficiency Shift — measures how current directional efficiency differs from its behavioral baseline.
• Volatility Shift — evaluates changes in ATR-normalized volatility conditions.
• Structural Persistence Deterioration — measures whether recent directional persistence is weakening relative to its baseline.
• Directional Conflict — identifies disagreement between shorter-term directional behavior and the broader directional baseline.
• Range Shift — evaluates changes in local price-range behavior relative to its longer baseline.
These components are combined into a normalized Transition Pressure measure.
The pressure value represents the degree of behavioral instability detected by the framework. It is not a probability of reversal or continuation.
Pressure Lifecycle
The framework organizes transition pressure into five states:
STABLE — transition evidence remains comparatively limited.
BUILDING — internal behavioral changes are beginning to accumulate.
ELEVATED — multiple components are producing stronger transition-pressure evidence.
CRITICAL — transition pressure has reached a comparatively high state under the framework.
RELEASED — previously elevated pressure has subsequently contracted sufficiently to register a confirmed pressure release.
RELEASED is a temporary lifecycle state rather than a directional conclusion.
Confirmation and State Persistence
Lifecycle changes are evaluated using confirmed bars.
Both upgrades and downgrades require persistence before a replacement state is confirmed. This helps reduce one-bar state switching and distinguishes a developing candidate state from an established lifecycle state.
The information panel therefore separates:
STATE — current confirmed pressure state.
PRESSURE — confirmed normalized pressure measurement.
LIFECYCLE — whether the state is confirmed or a replacement is developing.
CANDIDATE — the developing replacement state when applicable.
TIMING — identifies the confirmed-bar basis of the displayed lifecycle information.
Adaptive Pressure Bands
The chart visualization uses an adaptive behavioral field around price.
Its width responds to ATR-normalized volatility and the engine's measured transition pressure. Lower-pressure environments generally produce a more subdued field, while increasing pressure changes the structure and visual emphasis of the bands.
Boundary proximity can also receive additional visual emphasis.
The bands are analytical context. They are not price targets, support/resistance guarantees, or projected future ranges.
Originality and Intended Use
Market Transition Pressure Engine is built around the interaction between behavioral baselines, normalized feature shifts, composite transition pressure, symmetric state confirmation, pressure-release detection and lifecycle persistence.
Its analytical focus is not conventional trend direction or entry generation.
The primary question is:
Is the current behavioral environment remaining stable, or is measurable internal pressure for a state change developing?
This distinction allows transition pressure to be studied separately from market direction.
Calculation Timing
Lifecycle decisions use confirmed-bar information.
The dashboard reports confirmed measurements so the displayed pressure value and confirmed lifecycle state are based on the same information set.
The adaptive visual field may continue developing during the current bar, while lifecycle confirmation intentionally waits for confirmed information.
This confirmation delay is part of the methodology.
Limitations
Transition-pressure states describe measured behavioral conditions; they do not represent reversal probabilities, continuation probabilities, expected returns, or guaranteed future outcomes.
A CRITICAL state does not necessarily mean that price will reverse.
A STABLE state does not imply that a significant move cannot occur.
Results depend on the selected market, timeframe, available history and settings. ATR normalization improves comparability across volatility environments but does not make different instruments behaviorally identical.
Historical state transitions do not imply that future transitions will develop in the same manner.
The indicator is intended as an analytical and research framework and should be interpreted alongside broader market context. 指标

SpxSnipper - Intraday Candle vs Daily ATRIntraday Candle vs Daily ATR
This indicator is designed to identify significant intraday candles by comparing each intraday candle’s size against the Daily ATR.
It is useful for traders who want to quickly spot unusually large 5-minute, 15-minute, or 30-minute candles relative to the stock/index’s normal daily volatility.
How it works:
The indicator pulls Daily ATR data from the daily timeframe and applies it to the intraday chart. Each intraday candle is then measured as a percentage of the Daily ATR.
For example:
If the Daily ATR is 100 points and the selected threshold is 25%, the indicator will mark any intraday candle with a range or body greater than 25 points.
Main features:
- Uses Daily ATR on intraday charts
- Custom ATR length
- Custom percentage threshold
- Option to measure full candle range or real body
- Option to use previous completed Daily ATR or current developing Daily ATR
- Bullish and bearish candle signals
- Optional candle coloring
- Optional percentage labels
- Alert conditions included
Measurement modes:
- Full Candle Range: high minus low
- Real Body: absolute difference between close and open
Suggested use:
This tool can help identify important impulse candles, volatility expansion, breakout candles, rejection candles, and strong intraday moves.
It can be used on SPX, SPY, QQQ, individual stocks, futures, or other liquid instruments.
For 15-minute charts, a threshold around 20%–25% of Daily ATR can highlight only the more important candles. Lower values will generate more signals, while higher values will show only the strongest volatility candles.
This indicator is intended for discretionary trading analysis and should be used together with price action, trend, support/resistance, VWAP, volume, and proper risk management.
Not financial advice. 指标

Amit## Strategy Overview
This strategy is a price-action-based intraday trading system designed to identify high-probability entries using **market structure, CHoCH (Change of Character), BOS (Break of Structure), liquidity sweeps, and multi-timeframe confirmation**.
The strategy focuses on letting the market establish its direction first rather than entering immediately on a breakout. Once structure confirms the move, the lower timeframe is used to identify a more precise entry.
### How It Works
The strategy primarily follows this sequence:
**1. Higher-Timeframe Structure**
* Identifies a Change of Character (CHoCH) to establish a potential directional bias.
* Looks for confirmation through a Break of Structure (BOS).
**2. Lower-Timeframe Confirmation**
* After higher-timeframe confirmation, the strategy moves to the lower timeframe.
* A corresponding CHoCH is identified in the same direction.
**3. Liquidity Sweep**
* The strategy waits for price to sweep the relevant structure/liquidity.
* The sweep helps avoid entering immediately into a false breakout.
**4. Entry**
* Once the required structure and liquidity conditions are satisfied, the strategy generates a long or short signal.
### Trading Philosophy
The core idea is:
**Structure → Confirmation → Liquidity Sweep → Entry**
Instead of chasing price after a breakout, the strategy waits for the market to confirm its intention and then looks for an entry after liquidity has been taken.
### Important Note
This is a systematic strategy designed for backtesting and research. Results can vary depending on market conditions, execution, slippage, commissions, and the instrument being traded.
Past backtest performance does not guarantee future results. Always test the strategy thoroughly before using it with real capital.
策略

Advanced kNN Dip Pattern [The Quant Science]Advanced kNN Dip Pattern is designed to identify significant price drops and evaluate their bounce probability using historical past patterns through our kNN Lorentzian Classification machine learning library.
To train the machine learning model, the script extracts and normalizes four fundamental geometric metrics of each candle using a fifty-period min-max scaling function.
🔹 The first feature is the candle body size , calculated as the absolute value between the close and the open.
🔹 The second feature is the total candle range , defined by the difference between the high price and the low price.
🔹 The third and fourth features measure the wicks instead, calculating respectively the space between the high and the highest point between the close and the open for the upper wick, and the distance between the lowest point between the close and the open and the low for the lower wick.
👉 About our kNN Lorentzian Classification Library:
🔷 What It Does
The script analyzes real-time candle structure and detects sudden downturns by comparing them against a dynamic historical database.
Detects the dip by monitoring the market for user-defined percentage drops relative to the recent high price.
Performs kNN classification by extracting four geometric candle features, namely body size, total range, upper wick, and lower wick, normalizing them, and comparing them with historical patterns through the algorithm.
Finally, applies a signal filter , generating an entry only when a significant drop occurs in conjunction with a positive prediction based on the most similar historical neighbors.
🔷 What It Is Used For
This indicator is a key tool for mean reversion and dip buying strategies.
Helps filter out false crashes by distinguishing healthy, high-probability bounce corrections from strongly bearish trends.
The automatically drawn boxes and lines also allow you to visually assess the extent of the movement and price reaction in historical tests.
Thanks to the percentage confidence, the trader also knows how closely the current pattern historically resembles winning setups.
🔷 Who Uses It
Quantitative and systematic traders who want to leverage statistical classification models without leaving the TradingView environment.
Swing traders looking for optimal entry points on volatile assets such as cryptocurrencies or growth stocks during market correction phases.
Algo-trading enthusiasts interested in understanding how to implement matrices, arrays, and external libraries in Pine Script v6.
🔷 How to Use It
Add the script to your chart , which requires importing the dedicated library.
Configure the main parameters in the settings panel by defining the analysis period in bars and the minimum percentage drawdown threshold required to trigger the analysis.
Monitor the chart , and when the signal turns on, the script colors the bar, draws a transparent box highlighting the magnitude of the drop from the peak to the low, and prints an HUD label with the statistical details.
🔷 User Interface Management
Configure the main parameters in the settings group by defining the Analysis Period expressed in bars, set to a default of 2, and the percentage Dip Threshold, set to a default of -5 percent.
Analysis Period indicates the number of bars the script considers to calculate the recent high price against which the drawdown is measured.
Dip Threshold represents the minimum percentage price drop threshold required for the system to recognize a movement as a valid dip and initiate the machine learning analysis.
Machine Learning Vs. Traditional Dip Patterns
Traditional patterns historically suffer from the severe flaw of triggering right in the middle of strong downward trends, catching what is jargon-wise called the falling knife and leading to massive losses. The integration of k Nearest Neighbors in this script brilliantly overcomes this limit by analyzing the geometric microstructure of the candle and comparing it with thousands of past events. The system does not merely observe how far the price has dropped, but evaluates whether that precise candle profile historically has a good probability of generating a bounce or if it instead anticipates a prolonged collapse, filtering out false signals and protecting capital.
Below you can find a quickly comparison analysis between a classic Dip and a kNN Dip.
To do that, we used our Dip & Rip Patterns indicator:
指标

DCA HelperDisciplines your DCA strategy by splitting your buy zone into N pre-calculated levels. Triggers buy signals only when price touches a level within the discount zone.
How it works:
The indicator automatically divides the discount zone (bottom 20% of a 50-bar range) into N equal parts. Each part is a potential DCA entry (L1, L2, ..., LN). Signals fire ONLY when price touches a specific level — never in "no man's land" between levels.
Entry filters (all must pass):
Price below both MA(50) AND MA(200) → double trend confirmation
RSI(14) below 35 → oversold filter
Price within bottom 20% of range (discount zone)
Price sustained in discount for 3 consecutive bars (anti-spike)
20-bar cooldown between signals
Within 0.5% of a level (no in-between triggers)
Chart visualization:
🟩 Light green box = discount zone (where levels operate)
🟦 Blue dashed box = full high/low range (context)
➕ White dotted line = 50% equilibrium level
🟧 Orange line = average DCA price
🔷 Green "DCA" diamond below bar = each executed level
🟢➖🟢 Horizontal green lines = the N levels, labeled L1 price (% vs current), L2 ..., etc.
Level color: more intense the deeper (better price)
Info table (top-right):
Now: current price
Avg: current average + # buys/N
Complete: average if ALL N levels fill (ideal position avg)
L1, L2, ..., LN: each level price + % vs current, colored by risk:
🟢 Green = close (entry ready)
🟠 Orange = medium
🔴 Red = far below (better discount but more waiting)
Configurable inputs:
DCA levels (1-10) — number of staggered buys
Trigger proximity to level (%) — max distance for level trigger
Filter MA length (fast/slow)
RSI buy level
Range lookback
Discount threshold
Sustained bars
Min bars between signals
How to use for real DCA:
1.
Check the "Complete" row in the table → that's your avg if you split position across N levels
2.
Decide total size (e.g., $10k) and divide into N parts
3.
Set alerts on "DCA" diamonds for each level
4.
Buy the corresponding part when each level triggers 指标

Volume Footprints**Footprints (Volume Footprints) — Description**
Footprints breaks down each price bar to show where trading activity concentrated within it. Instead of a single volume number per bar, it splits a bar into horizontal price levels and reports how much volume traded at each level, along with an estimated buy/sell breakdown. Everything is presented in a compact, docked information box rather than drawn across the chart, keeping the price panel clean. The indicator's full name is "Volume Footprints," shown in the library and settings, while the chart legend displays the short name "Footprints."
**What it shows**
The indicator samples a finer timeframe inside each bar to reconstruct how volume was distributed across price. It then displays that distribution as a price ladder, with the highest price at the top. For each level it shows the volume attributed to buying, the volume attributed to selling, and the net difference between them (delta). A totals row at the bottom sums buying, selling, and net delta for the whole bar.
Two reference points are marked with colored dots in their own narrow columns: the Point of Control (P), which is the single price level where the most total volume traded, and the current price level (C), which shows where live price sits within the bar. A volume heatmap shades each row so that busier levels appear more saturated, making the most active prices easy to spot at a glance.
An optional candlestick column runs down the far-left side of the box, drawn to scale against the same price ladder so it mirrors the inspected bar's candle on the chart — a solid body between the open and close, thin wicks to the high and low, and colored green when the bar closed up or red when it closed down. Because it is drawn from table cells, its smoothness depends on how many rows the ladder has; a coarse ladder produces a blockier candle.
The information box also carries a title row showing the indicator name, which bar is being examined, the timeframe settings in use, and a live countdown to the close of the forming bar.
**Buy/sell estimation**
The buy and sell figures are estimated from price direction within the sampled sub-bars rather than from actual bid/ask transaction data. Rising sub-bars are counted as buying and falling sub-bars as selling. As a result, the buy, sell, and delta values are an approximation of activity, not a measurement of true order flow.
**Timeframe guidance and warnings**
For the indicator to work, the chart timeframe must sit between the two timeframe settings: the cell granularity must be below the chart timeframe, and the footprint bar timeframe must be at or above it. If the chart is on a higher timeframe than the footprint setting, the box displays a warning in place of the ladder. If the cell granularity is not below the chart timeframe, the box reports that as well. The footprint timeframe may also be left as "Chart" to match the chart's own timeframe, in which case no timeframe warning is shown.
**User Inputs**
- **Footprint bar timeframe** — Sets which bar the box analyzes, such as one hour. This should be at or above the chart's timeframe. Volume from finer sub-bars is accumulated across chart bars until this bar completes, then organized into price levels.
- **Cell granularity** — Sets the finer timeframe used to build the price levels inside each bar. This must be below the chart's timeframe; otherwise no data is returned and the box reports this.
- **Stable cells (closed sub-bars only)** — Affects the forming bar only. When on, buy/sell figures count only sub-bars that have fully closed, so numbers accumulate steadily instead of shifting between buy and sell as price moves; this introduces a slight lag at the live level. When off, the still-forming sub-bar is included for maximum responsiveness, at the cost of the current level's figures fluctuating.
- **Row bucketing mode** — Chooses how price levels are formed. Fixed price step builds a continuous ladder on a fixed price grid, giving every level from the bar's low to high a permanent row that does not shift as the bar develops. Range slices instead divides the bar's high-to-low range into a set number of equal parts, which rescales as the bar's range grows.
- **Price step (ticks)** — Used in Fixed price step mode. Sets the height of each row in ticks. Smaller values create more, finer rows; larger values create fewer, coarser rows. If a bar spans more levels than the display can hold, the highest levels are truncated, which is resolved by raising this value.
- **Price rows (Range slices mode)** — Used in Range slices mode. Sets the number of equal divisions of the bar's range. It has no effect in Fixed price step mode, which sizes the ladder automatically.
- **Footprint bar to inspect** — Selects which bar the box displays, counting back from the newest. Zero is the bar currently forming, one is the last completed bar, and so on.
- **Info box position** — Anchors the information box to a chosen area of the chart, such as a corner or middle edge, so it can be moved clear of price.
- **Info box text size** — Sets the font size inside the box, from tiny to large.
- **Show candlestick column** — Toggles the far-left candlestick column. When off, the column is removed entirely and the box narrows.
- **Show chart marker** — Toggles an on-chart arrow that points to the most recent candle of the bar being analyzed.
- **Marker color** — Sets the color of that on-chart arrow.
- **Buy color** — Sets the color used for net-buying delta figures.
- **Sell color** — Sets the color used for net-selling delta figures.
- **Candle up color** — Sets the candlestick column's color when the bar closed at or above its open. Defaults to a standard chart green.
- **Candle down color** — Sets the candlestick column's color when the bar closed below its open. Defaults to a standard chart red.
- **Heat (volume) tint** — Sets the hue of the volume heatmap that shades each row by activity, with the busiest level appearing brightest.
- **Info box background** — Sets the solid background color of the box, over which the heatmap tint blends.
- **Text** — Sets the color of the text inside the box.
- **Title text color** — Sets the color of the title-row text.
- **Title background** — Sets the background color of the title row.
- **POC dot color** — Sets the color of the dot marking the Point of Control.
- **Current price dot color** — Sets the color of the dot marking the row where live price currently sits. 指标

Winchester 10X1T Cipher - Zone-Gated WaveTrend DotsWHAT THIS IS
A single-pane momentum panel that marks the exact bar on which a WaveTrend cycle turns while price sits in an extreme zone. It is a confluence display: WaveTrend for the cycle turn, an RSI+MFI pressure band for money-flow context, RSI for the trend regime, and a Stochastic RSI pair for the short-term swing. All four sit in one pane, so a trader does not have to read four windows to answer one question: is this turn happening in a place where a turn matters?
HOW IT IS CALCULATED
WaveTrend follows the classic construction published by LazyBear: an EMA of the source (HLC3, channel length 9), an EMA of the absolute distance to it, a channel index scaled by 0.015, then an EMA of that index (length 12) as the fast line and a 3-period SMA of the fast line as the signal line. The area between both lines is filled so the cycle body is visible at a glance.
The pressure band uses the RSI+MFI area concept popularised by VuManChu's Cipher B: the average of (close-open)/(high-low) over 60 bars, scaled and drawn as a band at the bottom of the pane - white above zero, gold below.
RSI (14) is plotted in three states: white at or below 30, gold at or above 60, purple in between.
Stochastic RSI (14/14, K and D smoothed by 3) is plotted on a log-transformed source.
THE DOTS
A dot is printed only when the WaveTrend fast line crosses its signal line AND the signal line is already inside an extreme zone. Two sizes are used on each side, so the quality of the location is visible without reading numbers:
- Small dot: the cross happens between the first and the second zone (53 to 60 above, -53 to -60 below).
- Large dot: the cross happens beyond the second zone (60 and above, -60 and below).
Top dots are sky blue; bottom dots are white with a gold core. Each of the four dot types has its own alert condition.
WHY THE COMBINATION
WaveTrend on its own crosses constantly in the middle of the range, which is where most of its false signals live. Gating the cross on the zone removes those. The RSI colour states and the pressure band then answer the second question - whether the turn is a counter-trend stab or a continuation in the direction of the dominant flow. RSI at 60+ (gold) with a top dot is a different situation from RSI at 30 (white) with a bottom dot, and the panel shows both facts on the same bar without adding a second indicator.
HOW TO USE IT
Add it to any symbol and any timeframe. Nothing repaints once a bar has closed, so wait for the bar to close before acting on a dot. Treat the large dots as the primary event and the small dots as early warnings. All lengths, zone levels and visibility switches are inputs, so the zones can be tightened or widened per market. The four alert conditions can be wired to TradingView alerts.
CREDITS
The WaveTrend oscillator is the open-source work of LazyBear; the RSI+MFI area concept comes from VuManChu's open-source Cipher B. This script re-implements both in Pine v6 and adds the zone-gated two-size dot logic, the RSI regime colouring, the combined pane layout and the alert set. It is published open source so that anyone can read exactly what it does. 指标
