Historical Precedent Engine [HPE]WHAT IT DOES
HPE takes the last few candles on your chart, searches that chart's own history for
earlier sequences that resemble them, and shows you what price did after those earlier
sequences. It is an analog study. The output is a summary of precedent, not a forecast.
TUNING IS NOT OPTIONAL — READ THIS FIRST
This is a matcher, and a matcher only speaks when it finds something. Every enabled
filter is a hard gate applied to every candle in the fingerprint, and the gates compound:
a sequence qualifies only if candle 1 passes wick, body and volume, and candle 2 passes
all three, and so on, and the sequence momentum passes, and the direction rule passes.
Tighten two of those and the survivor count does not halve, it collapses.
So the normal failure mode is an empty dashboard. Median outcome, tolerance band, delta
and range all read "—", Bias reads Neutral, and Matches Used reads 0. That is not a bug
and it is not the tool being broken. It means nothing in this chart's history was close
enough to the present under the settings you have. The honest answer for that bar is
silence, and the tool gives it.
The tolerance units
Wick and body are measured as a percentage of the candle's own high-to-low range, not of
price. An upper wick occupying a fifth of its candle scores 20, whether that candle is a
one-minute Bitcoin bar or a daily equity bar. A tolerance of 12 therefore means "within
12 percentage points of range", and it means the same thing on every instrument and every
timeframe.
That is deliberate. Measured against price instead, the same tolerance would need to be
roughly a hundred times larger on a daily equity chart than on a one-minute crypto chart,
and no single default could serve both — one setting would accept everything on one chart
and nothing on the other.
On Auto-Tune, which ships OFF
Auto-Tune moves the wick and body tolerances based on how well recent projections
resolved. It ships disabled, for two measured reasons.
It cannot start from nothing. It does not act until at least five projections have been
scored, so if your tolerances are too tight to ever produce a match, there are no
projections, nothing is scored, and it never moves. It is a regulator, not a starter
motor.
And once it does start, it tends not to stop. It can only travel between a quarter and
four times your input, and when widening fails to improve fit — which is the usual case
if the matches were poor to begin with — it widens every bar until it pins at four times
your input and stays there. On the test chart it did exactly that, and the difference it
made was 50 resolved projections instead of 49. It bought one projection out of fifty
while making the number in the settings box a fiction.
So it is off, and what you type is what runs. Turn it on if you want it, knowing both of
the above.
The order to loosen in, most effective first:
1. Strict Direction off. With it on, every candle must match direction, which is a
1-in-2^N filter before any tolerance is applied. This is the single biggest lever.
2. Shorten Sequence Length. Fewer candles means fewer conjunctive conditions. Three is
the minimum and is the default for that reason.
3. Raise Wick and Body Tolerance, in the units described above.
4. Turn off Require Per-Candle Volume Match and Require Momentum Match. Volume ratios in
particular are noisy on short timeframes and reject a lot for little gain.
5. Lower Min Matches Required. It ships at 2 rather than 3 because on the instrument
these defaults were measured on, 3 never fires. Read the last paragraph of this
description before you take that as a recommendation.
Where the defaults came from
They were measured with a full 1,000-sequence library on three charts chosen to be as
unalike as possible, and they were picked to make the engine speak at all rather than to
make it look good:
COINBASE:BTCUSD 1-minute 73 projections over 25,837 bars
COINBASE:BTCUSD 1-hour 33 projections over 22,764 bars
AMEX:SPY daily 29 projections over 8,436 bars
That is between one bar in 290 and one bar in 690 — the same order of magnitude across a
crypto intraday chart and an equity daily chart, with no per-instrument tuning. It should
still be quiet, and you should still retune for your own instrument and horizon, but the
defaults are a measured starting point rather than a guess.
One note on reading the dashboard while you do that. The calibration row shows total
projections alongside how many sit in the calibration window, and that window is capped by
Calibration window (samples) — 50 by default. Watch the total, not the window. The window
fills early and then stops moving, which makes a well-tuned setup and a barely-working one
look identical.
ON LIBRARY SIZE
Max Stored Sequences is the pool the matcher searches, and a bigger pool is the one way
to get more matches without making each match mean less. It is capped at 1,000 by default
for a practical reason: raising it substantially can push the script past PulseWire's
calculation limit, at which point it stops reporting entirely. If you raise it and the
indicator goes blank rather than merely empty, that is what happened. Put it back. This
cap is also the real ceiling on how often the engine can fire at a tolerance tight enough
to be meaningful, and it is worth knowing that before you go hunting for settings.
HOW IT WORKS
1. Fingerprint. On every confirmed bar, the last N candles are reduced to a five-field
vector per candle: upper wick, lower wick, body, direction, and volume measured
against its own moving average.
2. Store. That fingerprint is written to a rolling library along with what price did over
the following bars.
3. Match. The current fingerprint is compared against every stored sequence. A stored
sequence qualifies only if each candle falls inside the wick, body and volume
tolerances, and only if the sequence momentum falls inside its tolerance. Direction
matching is separate: with Strict Direction on, every candle must match direction;
with it off, only the final candle must. An optional session filter restricts matches
to the same trading session.
4. Summarise. Qualifying matches are ranked by how well their own past projections
resolved, and the strongest are combined into a single percentile outcome — the median
by default. If fewer than Min Matches Required qualify, nothing is drawn.
5. Calibrate. Once the horizon elapses, each projection is scored against what actually
happened. That score weights how much a stored sequence counts in future matches, and
feeds Auto-Tune if you have enabled it.
READING THE CHART
Projection line and band — the percentile outcome of the current match set, extended to
the horizon.
Consensus paths — the individual paths of the top matches, drawn separately, so you can
see the spread the single summary line came from. A tight cluster and a wide scatter
produce the same median.
Rolling projection trail — past projections left on the chart beside what price actually
did. This is deliberate. A tool that hides its misses is not worth reading.
Dashboard — match count, median outcome, ±1σ range, session, library size, live
tolerances, and the calibration block. The projection values — median outcome, tolerance
band, delta, range, bias, match count and best-match error — are cleared at the start of
every confirmed bar, so those rows always show that bar's answer and never a leftover
from an earlier bar that happened to match. The library and calibration counters are
cumulative by design and do not clear.
The same state is also published to the Data Window as plain numbers, which is easier to
read than canvas text while you are tuning.
ON THE CALIBRATION NUMBERS
The dashboard reports mean projection error, not accuracy.
It is the average distance between projection and outcome, expressed as a share of the
size of the move that actually occurred, measured over the most recent resolved
projections on the chart you are looking at. It is computed in-sample, on bars the engine
had already stored, and it is not a forward result.
It is there so you can tell whether your tolerances are set sensibly. It is not evidence
that the tool works, and it should not be read as a hit rate. Because the actual move is
the denominator, the figure also moves with volatility regime rather than with skill
alone — quiet bars punish it, large moves flatter it.
ON REPAINTING
Two specific claims, both checkable in the source:
There are no request.security() calls anywhere in this script. Every value is computed
from the chart's own bars, so there is no higher-timeframe lookahead question to get
wrong in the first place.
Every drawing and every dashboard write sits inside a single barstate.isconfirmed gate.
Nothing is created, moved or deleted while the live bar is still forming.
A projection does extend to bars that have not happened yet. It does not move once drawn.
It is simply right or wrong, and the trail is there so you can see which.
SETTINGS WORTH KNOWING
Sequence Length — how many candles form the fingerprint. Longer is stricter and finds
fewer matches, and the effect is multiplicative rather than linear.
Min Matches Required — below this count nothing is drawn.
Delta Percentile — 50 is the median. Move it to read the pessimistic or optimistic tail
of the same match set rather than its centre.
Auto-Tune Tolerances — off by default; see above before enabling.
Strict Direction — the difference between "these candles had the same shape" and "these
candles had the same shape and went the same way."
WHAT THIS IS NOT
This is a visualization and analysis tool, not a trading system. It does not produce
advice. Nothing here is a signal to enter or exit a position, and no performance is
claimed or implied. Markets change regime, and any tool built on historical structure
will fail when they do. Use it as context alongside your own analysis.
One more thing worth saying plainly, and it is the honest counterweight to the tuning
advice above: a small sample of matches is a small sample. Two historical analogs tell
you very little, and the engine will draw a line from two just as readily as from thirty.
Min Matches ships at 2 because that is what it took to get the engine to speak on the
instrument it was measured on — which is a statement about how hard analogs are to find
in a 1,000-sequence library, not a claim that two is enough to believe. Loosening the
filters until something appears is easy, and it is exactly how you end up reading noise.
Watch the match count before you read the line, and treat a projection drawn from a
handful of precedents as the weak evidence it is.
Indicator

FractalMemoryLib [Jayadev Rana]FractalMemoryLib packages the pattern-memory engine used by the Fractal Memory Projection indicator and the Fractal Memory Strategy so any script can import it.
WHAT IT DOES
The library finds the historical window whose movement shape most resembles the most recent bars (mean squared distance between stdev-normalized log returns), replays what followed that window as a projected close path, and sizes stops and targets adaptively by volatility regime.
EXPORTED FUNCTIONS
logRet(src) - one-bar log return of a series.
bestMatch(src, winLen, scanDepth, gapAhead) - scans up to scanDepth bars back and returns the offset of the most similar window plus a 0-100 similarity score. gapAhead reserves bars after the match for a projection.
analogPath(src, offset, fcLen, scaleF) - array of fcLen projected closes built by replaying the returns that followed the match, rescaled by scaleF (for example current ATR over ATR at the match).
adaptiveR(atrLen, rankLen, base) - volatility-adaptive unit risk: ATR times (base plus its 0-1 percentile rank), plus the rank itself. Call on every bar.
volRegime(volRank) - "Low", "Normal" or "High" label from the rank.
targets(entry, dirSign, unitR, slMult) - stop loss and TP1/TP2/TP3 at 1R, 2R and 3R.
USAGE NOTES
Call adaptiveR on every bar for ta consistency. bestMatch and analogPath are loop-heavy; for display purposes call them on the last bar only, and make sure the chart has at least scanDepth plus gapAhead bars of history. When the library itself is added to a chart it draws a small demo projection line from the best analog.
The analog projection is a statistical reference to a similar past episode, not a prediction, and not financial advice. Library

Chart-Pattern Analogs SMC-Graded Chart-Pattern Analogs — Empirical Matching, SMC-Graded & Calibrated
## What it is
A chart-pattern engine that does not trust textbook shapes — it predicts from **precedent**. Instead of asking "does this look like a Head & Shoulders?", it asks "**how did the closest historical shapes on this symbol actually resolve?**" and answers from data.
A PIP (Perceptually Important Points) skeleton of the recent window is matched by **Dynamic Time Warping** against a live memory of past shapes, each labelled by what happened next. The direction, probability and target come from the *k* nearest analogs. Each completed pattern is then graded with Smart-Money context (liquidity sweeps, premium/discount location, breakout quality), and its forward outcome is tracked **per family, per regime, with Wilson confidence intervals**. Templates and geometry survive only to *name* the family.
## Why these components belong in ONE script (not a stack of indicators)
This matters because the components form **one closed loop**, where each answers a question the others cannot:
- **PIP skeleton + Ehlers-adaptive window** reduce price to its structurally important turning points, over a window sized by the live dominant cycle so the skeleton tracks the market's actual rhythm rather than a fixed bar count.
- **DTW analog matching** replaces fixed templates: the current skeleton is compared to a memory of *resolved* shapes, and the forward outcome of its nearest neighbours **is** the prediction. Empirical, not assumed.
- **SMC context** (liquidity sweeps, EQH/EQL pools, premium/discount, breakout quality) answers *"is this the right place?"* — a pattern that forms after a real liquidity grab, in the correct half of the dealing range, is graded higher; one firing into opposing liquidity is withheld. Shape alone cannot tell you location.
- **Regime** (efficiency ratio) conditions trust: a family's edge is measured separately in trend vs chop, because the same shape behaves differently in each.
- **Calibration** closes the loop: per-family, per-regime hit-rate versus an unconditional directional base rate, recency-weighted, with Wilson 95% intervals — so reliability is *earned on this instrument*, not claimed.
The skeleton says **what**, the analogs say **how it resolved before**, SMC says **whether the location is right**, the grade **fuses** them, and calibration keeps the whole thing **honest**. Remove any layer and the read loses a dimension it cannot recover.
## How it works (mechanics)
On bar close, the PIP skeleton is extracted and matched by DTW k-NN to the analog memory. The consensus direction and probability, plus the single nearest analog's forward path (the **ghost overlay**), are drawn. The pattern is graded **A/B/C** from the calibrated probability + quality + sweep + location, and gated by a minimum grade and a location veto. Every directional emission locks entry and ATR, tracks MFE/MAE in R, and at the horizon records a win if the close moved the chosen ATR multiple in its direction — feeding both the analog memory and the per-family/per-regime calibration tables.
Detection, drawing and resolution happen **on bar close over closed bars only** — no `request.security`, no dynamic-length `ta()`, no intrabar revision. Patterns are drawn once and never moved.
## How to use
1. Read the dashboard: the active pattern's **analog probability**, its **A/B/C setup grade**, **sweep validation** and **premium/discount location**.
2. Favour higher grades — a calibrated-positive family, sweep-validated, in the correct half of the range, with the ghost pointing your way.
3. Check **"This family"** — the regime-conditional and recent hit-rate is the number that matters *now*; the Pro table lists every family with Wilson confidence intervals.
4. The **ghost** shows the single closest historical precedent; the **target** is the analog mean.
5. Everything here is descriptive, probabilistic context — never an instruction.
## Use on any market
Works on any symbol and timeframe. The **Data Source** inputs (High / Low / Close) drive the entire engine — PIP skeleton, pivots, liquidity, premium/discount — from any series, so you can run it on standard candles, Heikin-Ashi, or another instrument. All thresholds are **ATR-relative**, the detection window is **cycle-adaptive**, and the analog memory and calibration rebuild **per instrument** — nothing is hard-coded to a price scale or a single market. Defaults are set for NIFTY index-futures intraday; change the sources or lengths for other assets.
## Credits
This engine builds on established, published concepts:
- **Perceptually Important Points** — Chung, Fu, Luk & Ng
- **Dynamic Time Warping** — Sakoe & Chiba
- **Homodyne-discriminator dominant cycle / adaptive windows** — John F. Ehlers
- **Efficiency Ratio** (trend vs noise) — Perry Kaufman
- **Wilson score confidence interval** — Edwin B. Wilson
- **Liquidity, premium/discount and order-block context** — smart-money / auction-market concepts (Wyckoff lineage; popularised in the ICT body of work)
The empirical analog loop (label-by-outcome DTW matching), the SMC location-grading, and the per-family/per-regime Wilson-bounded calibration framework are the author's original implementation.
## Originality
The contribution is the **closed loop**, not the objects: empirical DTW analog matching (label by outcome, not by template), SMC location-grading, and per-family/per-regime Wilson-bounded calibration, fused into one self-prioritising read with a nearest-precedent ghost overlay. The shape is only the index into history.
## Limitations (honest)
The analog memory and calibration are **in-sample, close-to-close at a fixed horizon, with no costs, slippage or stops** — a study aid, not a backtest, and not a probability of future results. The engine needs to build memory before it leaves bootstrap (watch the "Analog mem" counter). Volume-derived quality degrades on symbols without real volume. Past behaviour of a pattern does not assure future behaviour.
## Disclaimer
Educational / informational study for chart analysis only. **NOT financial advice, NOT a strategy, NOT a recommendation.** It places no orders and guarantees no outcome. Markets carry risk; do your own research and manage your own risk. Paper-trade before risking real money.
Indicator

Analogue Matcher | GainzAlgoAnalogue Matcher: Dual-Path Regression Projection
What It Is
The Analogue Matcher is a high-performance pattern recognition engine designed to find historical "price twins." Unlike standard fractals that look for raw shape similarity, this tool utilizes Linear Regression Analysis to identify periods in the past where market velocity (slope) and trend consistency ($R^2$) were near-identical to current conditions. It then projects those historical outcomes forward as "Ghost Candles," providing a probabilistic roadmap of where price might go.
How It Works
The indicator operates by scanning a user defined amount of lookback bars of history in real-time (Default 500).
• The Scan: It calculates the current regression slope over a user-defined window.
• The Match: It iterates through the lookback period to find the closest matches based on a strict Slope Tolerance .
• Dual-Path Intelligence: In "Dual Mode," the script identifies the single best Bullish outcome and the single best Bearish outcome simultaneously. This prevents "bias-blindness" by showing you the best-case scenarios for both directions.
Understanding Confidence & R2
The "Conf (R²)" column in your dashboard is the heart of the script's decision-making.
• Slope Similarity: Measures how closely the historical angle matches the current angle.
• R2 (Coefficient of Determination) : Measures the "cleanliness" of the trend. An R2 of 100.0 is a perfect straight line; 0.0 is pure noise.
• The Percentage: Our algorithm combines these two factors. A 90%+ Confidence rating means you have found a historical twin that moved at the same speed and with the same level of trend maturity as the current bar.
How to Use: A Risk Management Approach
This is not a "magic signal" generator—it is a Risk Management and Bias Tool .
• Identify Convergence: If both the Bullish and Bearish paths show high confidence (>80%) and both point in the same direction, you have high-probability confluence.
• Divergence Warning: If the Bullish path has 95% confidence but the Bearish path has only 10%, the historical precedent for a trend reversal is mathematically weak. Your bias in this case would lean bullish. Inverse if it’s flipped with a high bearish confidence and a low bullish confidence.
• Filtering Noise: Use the R2 percentage to ignore "messy" matches. If the confidence is below 50%, the analogue is likely too "noisy" to be used for a high-conviction trade entry.
• Single Mode for Speed: Switch to Single Mode on lower timeframes (1m, 5m) to find the absolute "Best Fit" twin for quick scalping targets.
Master the Engine: Key Inputs
To get the most out of the Analogue Matcher , it’s essential to understand the "knobs" you are turning. Tuning these correctly is the difference between finding a perfect twin and seeing random noise.
• Mode Selection (Single vs. Dual): Single Mode: Focuses the processing power on finding the absolute "Best Fit" regardless of direction. Ideal for high-speed scalping or very large lookbacks. Dual Mode: The full "Risk Management" suite. It forces the script to find both a Bullish and a Bearish path to show you the two most likely outcomes.
• Projection Window: This determines the size of the "Ghost." If set to 50, the script analyzes a 50-bar trend and projects a 50-bar future.
• Lookback Period: This is how far into the past the engine scans. While the script is optimized for performance, keeping this within a reasonable range (500–2000) ensures fast UI response.
• Slope Tolerance: This is your "Sensitivity" setting. Lower Values (0.001 - 0.004): Very strict. The script will only show matches that have a nearly identical angle of attack. Higher Values (>0.01): More lenient. Use this in highly volatile markets (like Crypto) where trends are aggressive and vary in steepness.
Examples
In this image, we can see BTCUSD on the daily. The confidence favours a bullish move, both Bearish and Bullish possible paths are plotted. Let’s see what happens.
The outcome was an initial bullish move though with a bit of a neutral tilt, as it ended relatively flat.
Now let us look at ES1!:
In this case, the indicator is showing 2 possible paths (Dual Mode), with a bullish tilt. Let’s see what happened next:
The move was indeed bullish, and volatility remained intact through the move.
Important Considerations
The indicators true strength stems from its ability to act as a risk management tool and compare the degree of “fit” of each respective path (i.e. bullish vs. bearish). If you are looking to take a bearish position on a ticker, but you see that the R2 skew slightly favours a move to the upside, you may want to hold off on pulling the short trigger until you have a skew that fits your bias.
While the paths are likely not going to be a perfect, identical match, the power comes from understanding the confidence skew of the bullish vs bearish path. This is your saving grace for managing risk in your positions.
Though the matches are not likely to be perfect, they are scaled to the ticker’s ATR and thus can be used to help you gauge potential entries, exits and positioning areas.
For example, if we look at SPY on the hourly timeframe:
We see we have a bearish skew. The bearish path has sizeable upside. We can use this forecasted range to identify potential entry/resistance areas like so:
Now let’s see how it plays out:
You can see that the key forecast areas provided actual levels for support and resistance!
Concluding Remarks
In a market driven by algorithmic repetition, the Analogue Matcher gives you the power to see the "scripts" the market has run before. By quantifying the similarity of price action through regression, traders can move away from "gut feelings" and toward data-driven forecasts.
Indicator

Indicator Configuration Forecasting [LuxAlgo]The Indicator Configuration Forecasting tool identifies historical market regimes that share a similar technical configuration to the current market and projects future price action based on those historical outcomes. By encoding multiple technical indicators into a state vector and employing a K-Nearest Neighbors (KNN) search, the script provides a probabilistic forecast including a median path and confidence intervals.
🔶 USAGE
The indicator works by "memorizing" the state of various user-selected technical indicators at every bar. When the current bar's configuration matches or closely resembles a previous historical state, the script records how the price moved in the subsequent N bars from that point in time.
🔹 Forecast Interpretation
Median Forecast (Dashed Gray): Represents the 50th percentile (median) of all matched historical outcomes. This is the central tendency of the forecast.
Upper Bound (Dashed Green): Represents the 75th percentile of historical outcomes, suggesting a bullish boundary for the projected move.
Lower Bound (Dashed Red): Represents the 25th percentile of historical outcomes, suggesting a bearish boundary for the projected move.
Match Labels: Small labels appearing on the historical price action indicate exactly where the most similar configurations were found in the past.
🔹 Configuration Strategy
Users can toggle various indicators to define what constitutes a "similar" market state. For example, if only "SMA Cross" and "Supertrend" are enabled, the script will look for historical periods where the trend relationship and SMA positioning were identical to the current bar, regardless of RSI or MACD values.
🔶 DETAILS
The script utilizes a state-encoding methodology to calculate distances between the current market environment and the past. Each enabled indicator is converted into a discrete value (e.g., 1 for bullish, -1 for bearish, 0 for neutral). These values form a vector for the current bar.
The algorithm then scans through the "Historical Lookback" period to find the "Top K" neighbors—the points in history where the vector distance to the current state is minimized. To ensure variety in the forecast, the script includes logic to prevent overlapping matches, ensuring that the selected historical points are distinct events.
Once the matches are identified, the script calculates the percentage returns for the specified "Forecast Horizon (N)" and projects those returns onto the current price to generate the visual forecast.
🔶 SETTINGS
🔹 Parameters
Top K Neighbors: The number of similar historical configurations to include in the forecast calculation.
Forecast Horizon (N): How many bars into the future the forecast should extend.
Historical Lookback: The maximum number of historical bars the script will search through to find matches.
🔹 Indicator Configuration
RSI/SMA/Supertrend/MACD/ADX/etc.: Toggle switches to include or exclude specific technical conditions from the similarity search.
RSI: Looks for similar overbought (>70) or oversold (<30) states.
SMA Cross: Looks for similar Fast/Slow SMA relationships.
Supertrend: Matches the current direction of the Supertrend.
MACD: Matches the relationship between the MACD Line and Signal Line.
🔹 Visibility & Style
Show Individual Match Paths: When enabled, draws the actual historical price paths from the match points directly on the current chart for visual comparison.
Median/Upper/Lower Colors: Customizes the colors of the forecast lines and the shaded confidence intervals.
Dashboard: Toggles the information panel showing the number of matches found and forecast confidence.
Indicator
