OPEN-SOURCE SCRIPT
Aggiornato Pattern Match Price Projection

Pattern Match Price Projection is a price forecasting tool built on historical analog analysis. It scans past market data to find segments of price action that closely resemble the most recent pattern, then uses what followed those similar setups to construct a forward projection. Instead of relying on a single historical match, the model aggregates multiple high-quality analogs and produces an averaged path, along with adaptive upper and lower bands that reflect the dispersion of those outcomes.
The projection is derived from return-based pattern matching, with optional normalization to focus on structural similarity rather than magnitude. This allows the model to identify recurring behaviors across different volatility regimes and price levels. The result is a forward estimate that reflects how the market has historically behaved after similar conditions, rather than a purely reactive or lagging indicator.
A visual overlay of the current pattern is included to provide context for what the model is evaluating in real time, making it easier to interpret why a projection is being generated. The forecast itself can be anchored either to the most recent closing price or to a smoothed price reference, depending on preference. Non-repaint mode ensures the projection remains stable during an active candle, while live mode allows it to update dynamically as price evolves.
This tool is best used as a contextual framework for anticipating potential price paths based on historical precedent. It does not attempt to predict exact outcomes, but instead highlights probabilistic structure derived from prior market behavior.
The projection is derived from return-based pattern matching, with optional normalization to focus on structural similarity rather than magnitude. This allows the model to identify recurring behaviors across different volatility regimes and price levels. The result is a forward estimate that reflects how the market has historically behaved after similar conditions, rather than a purely reactive or lagging indicator.
A visual overlay of the current pattern is included to provide context for what the model is evaluating in real time, making it easier to interpret why a projection is being generated. The forecast itself can be anchored either to the most recent closing price or to a smoothed price reference, depending on preference. Non-repaint mode ensures the projection remains stable during an active candle, while live mode allows it to update dynamically as price evolves.
This tool is best used as a contextual framework for anticipating potential price paths based on historical precedent. It does not attempt to predict exact outcomes, but instead highlights probabilistic structure derived from prior market behavior.
Note di rilascio
Added info box with stats.Note di rilascio
Updated default inputs.Note di rilascio
This update transforms the indicator from a single averaged projection into a scenario-based forecasting tool. In the original version, the script identified similar historical patterns and produced one blended forward path, along with confidence bands and internal quality metrics like fit, confidence, and score. The new version keeps the same core idea of pattern matching and forward projection, but restructures how the results are interpreted and displayed.Instead of relying on a single averaged outcome, the script now separates historical matches into bullish and bearish groups based on how price actually moved after those patterns. It then builds independent projection paths for each group, allowing you to see both the upside and downside scenarios that have historically followed similar conditions. Alongside this, it calculates the percentage of bullish versus bearish outcomes, giving a clear directional bias rather than forcing interpretation from a single averaged line.
The center line still exists and is effectively the same averaged projection from the original version, but it is no longer the primary signal. It now serves as a reference, while the bull and bear paths provide a clearer view of how price tends to behave under different outcomes. This makes it much easier to identify when the average is masking meaningful divergence between scenarios.
The confidence bands have also been reworked to align with this new structure. Instead of being drawn around the blended average, they are now applied separately to the bull and bear projections, showing the range of variation within each scenario. This makes the uncertainty more relevant and consistent with the directional breakdown.
On the interface side, the indicator has been simplified. The previous fit, confidence, and score metrics have been removed, along with their associated inputs, and replaced with a more intuitive readout focused on Bull Probability, Bear Probability, and Direction Bias. The default number of matched patterns has been adjusted to improve readability of the percentages, and the overall visual output has been cleaned up to emphasize the scenario-based structure.
Overall, the update keeps the original concept intact but shifts the indicator from a single averaged forecast to a more informative model that highlights both direction and uncertainty through clearly defined bullish and bearish outcomes.
Note di rilascio
The new version replaces the DTW-based matching system with a simpler and more efficient similarity-based approach, removing all DTW-specific inputs and complexity. Instead of selecting a fixed number of best matches, it now filters matches using a minimum similarity threshold while enforcing minimum and maximum match counts to improve statistical stability and reduce noise.A major addition is the option to switch between equal-weight and similarity-weighted projections, allowing higher-quality matches to have greater influence on the forecast path. The model also introduces a 60% probability threshold for directional bias, replacing the previous always-on bullish/bearish classification with a more conservative bullish, bearish, or neutral interpretation.
The info box has been simplified and enhanced to display the number of matches instead of candidates, improving clarity around sample size. Overall, the update shifts the model toward a more transparent, statistically controlled, and computationally efficient framework with improved signal quality and interpretability.
Note di rilascio
Defaults updated.Note di rilascio
Internal min/max limits updated.Note di rilascio
Internal updates.Note di rilascio
Internal updates. Bug fixes.Note di rilascio
Internal updates. Bug fixes.Note di rilascio
This update introduces two optional upgrades to the pattern-matching engine that significantly improve how analogs are selected and how forecasts are constructed, while preserving the original behavior when disabled.A new “Use Correlation Similarity” setting replaces the original distance-based matching with a correlation-based approach. Instead of measuring how far two patterns are numerically, the model now evaluates how closely their shapes align. This allows it to recognize structurally similar price behavior regardless of scale or amplitude, resulting in cleaner and more relevant pattern matches. Negative correlation is ignored, ensuring only positively aligned patterns contribute to the forecast.
A second setting, “Use Outcome-Based Weighting,” enhances how selected matches influence the projection. Rather than weighting matches purely by similarity, the model now factors in the historical forward performance of each match. Patterns that led to stronger moves in the past are given greater influence, while weaker outcomes contribute less. This shifts the model from simple pattern recognition toward emphasizing patterns that have demonstrated meaningful follow-through.
Both features can be enabled independently or combined. When used together, the model prioritizes patterns that not only look similar but also historically produced stronger directional outcomes, resulting in more informative projections and probability estimates.
Note di rilascio
This update introduces an optional regime filter that improves pattern matching by restricting comparisons to similar volatility environments. Instead of allowing all historical patterns to compete purely on shape, the model now evaluates whether each candidate formed under comparable market conditions using normalized ATR (ATR%). Only patterns within a defined volatility range relative to the current setup are considered valid matches. This prevents the model from mixing low-volatility structures with high-volatility expansions, which often behave differently despite appearing similar. The result is a cleaner, more context-aware selection process that reduces noise, improves match quality, and produces more stable projections and probabilities.Note di rilascio
The indicator has been updated to behave cleanly when no valid matches are found. Instead of disappearing, it now keeps the current pattern line visible while removing all projection lines. The info box explicitly shows 0 matches, sets both bull and bear probabilities to 0.0%, and labels the bias as “No Matches,” making it clear the model simply found no usable historical analogs.The forecast horizon now defaults to 10, which keeps projections tighter and more stable. All filtering features still work the same, but it’s important that the regime filter remains the only setting that disables the minimum matches fallback, meaning stricter configurations can legitimately result in zero matches.
Note di rilascio
Updated Bull/Bear Probability colors in the info box.Note di rilascio
Internal defaults updated.Note di rilascio
Info box updated to show % Expected Move and Bull & Bear signal counts & total.Note di rilascio
Added tool tips.Note di rilascio
Internal updates.Note di rilascio
Pine category updated.Note di rilascio
Internal min/max/step defaults adjusted for more user functionality.No change to indicator logic.
Note di rilascio
Added indicator Title Name to Stats Info Box.Added additional Tool Tips for a better user experience.
Note di rilascio
Updated the confidence band behavior.The **Show Confidence Bands** option now works directly with the main **Forecast Midline (All Matches)**. Previously, confidence bands were only drawn when the bull or bear cluster midlines were enabled. Now, users can display upper and lower confidence bands around the primary forecast midline even when the bull and bear cluster midlines are turned off.
This makes the default forecast view cleaner and more useful, since the main projection can now include its own uncertainty range without requiring cluster-specific projections to be visible.
The bull and bear cluster confidence bands still work as before when their respective cluster midlines are enabled.
Note di rilascio
Three improvements over the original release:**1. Regime Tolerance is now adjustable**
The volatility filter that controls which historical periods are eligible for pattern matching was previously locked at a fixed internal value with no way to change it. It's now a user-facing input in the Model group (default 0.35, range 0.05–1.0). If you're seeing very few matches, lowering this setting is usually the first thing to try. If you're seeing too many low-quality matches, tighten it.
**2. Faster pattern selection**
The internal logic that ranks and selects the best matching patterns from the candidate pool was rebuilt using a native sort instead of a nested loop. No change to results — same matches, same output — just meaningfully faster computation, especially at higher Search Depth and Maximum Matches settings.
**3. Diagnostic row in the info table**
The info table now has a bottom row that shows how many candidates were removed by the Regime Filter (R) and Similarity threshold (S) during the current scan. When zero matches are found, the row turns orange and tells you specifically which filter is responsible and what to adjust. Previously the table just displayed zeroes with no explanation, leaving you to guess why the projection wasn't drawing.
Note di rilascio
**Update — Separate Confidence Band Controls**Each projection line now has its own independent confidence band settings. Previously, a single toggle and width multiplier controlled the bands for all three lines at once. Now the Forecast Midline, Bull Cluster, and Bear Cluster each have their own band toggle, width multiplier, and separate color, width, and style options for both the upper and lower band.
This means you can show bands on the midline but not the clusters, widen the bull bands without affecting the bear bands, or color each band pair differently to keep the chart clean and readable at a glance.
Note di rilascio
### Update SummaryThis update does **not** change how the indicator finds historical pattern matches or generates forecasts. The core model remains exactly the same.
What changed is the way the indicator decides whether to display a **Bullish**, **Bearish**, or **Neutral** bias. The goal is to make that final directional label more robust and less sensitive to small differences in the probabilities.
Previously, the indicator used a single threshold. If the Bull Probability reached the threshold (60% by default), the indicator would immediately label the setup Bullish. Likewise, if the Bear Probability reached the threshold, it would label the setup Bearish.
The issue is that this could sometimes produce a directional bias even when the bull and bear probabilities were relatively close to one another.
---
### New User Inputs
A new **Bias Logic** section has been added directly below the **Model** settings and above the **Display** settings.
#### Bias Threshold %
This setting controls the minimum probability required before the indicator is allowed to classify the pattern as Bullish or Bearish.
**Default:** 60%
In practical terms:
* Bull Probability must be at least 60% before a Bullish bias can be shown.
* Bear Probability must be at least 60% before a Bearish bias can be shown.
* If neither side reaches the threshold, the indicator remains Neutral.
A higher value makes the indicator more conservative. A lower value makes it more willing to issue directional signals.
---
#### Minimum Bull/Bear Edge %
This setting controls how much one side must outperform the other before the indicator will commit to a Bullish or Bearish bias.
**Default:** 15%
This is measured as the difference between Bull Probability and Bear Probability.
For example:
* Bull Probability = 70%
* Bear Probability = 30%
* Edge = 40%
Since the edge is greater than 15%, the directional bias requirement is satisfied.
Another example:
* Bull Probability = 61%
* Bear Probability = 50%
* Edge = 11%
Even though Bull Probability exceeds the 60% threshold, the lead over Bear Probability is only 11%, which is below the required 15% edge. In this case the indicator remains Neutral.
---
### What This Accomplishes
The indicator now requires **both** of the following before displaying a directional bias:
* The probability must be strong enough.
* The winning side must have a meaningful lead over the losing side.
This helps prevent situations where a very small difference between bull and bear outcomes produces a strong directional label.
As a result, Bullish and Bearish readings become less frequent, but generally carry more conviction because the historical analogs are showing a clearer directional preference.
---
### What Did Not Change
The following parts of the indicator are completely unchanged:
* Pattern matching methodology
* Pattern Length logic
* Search Depth logic
* Forecast Horizon logic
* Similarity calculations
* Regime filtering
* Outcome weighting
* Forecast projections
* Confidence bands
* Bull and bear cluster calculations
* Probability calculations
The indicator is still doing exactly what it did before: finding the best historical analogs and analyzing what happened after those analogs. The update only changes how much evidence is required before the final bias label commits to Bullish or Bearish rather than remaining Neutral.
Note di rilascio
## Historical Lookback Feature — What It DoesThis update adds a single new setting called **Lookback Bars**, found under a new **"Historical Lookback"** group in the indicator's settings panel.
---
### The Core Idea
By default, the indicator always analyzes the most recent price action and projects forward from the current bar. The lookback feature lets you **rewind the indicator to any point in the past** — as if you had been running it at that exact moment in history — so you can see what it would have projected, and then compare that projection against what actually happened.
This is purely a **visual backtesting and validation tool**. It does not change how the model works; it simply moves the entire analysis window backward in time by however many bars you specify.
---
### What Changes When You Use It
- **The pattern it reads changes.** Instead of reading the most recent 50 bars (or whatever your Pattern Length is set to), it reads the 50 bars that ended at your chosen point in the past.
- **The forecast lines shift back in time.** The projection lines draw forward from that historical anchor point, not from the current bar — so they land in what is now visible, completed price history.
- **The purple current pattern line shifts back.** The highlighted pattern that shows what the model was "matching against" also moves to reflect that past window.
- **The info box updates to reflect the historical read.** Bull/Bear probabilities, match counts, and direction bias all recalculate based on what the data looked like at that historical point. When a lookback is active, the header of the info box will show a small `[LB: N]` tag so you always know you're in replay mode.
- **Nothing about the underlying model changes.** All your other settings — pattern length, similarity thresholds, regime filter, projection mode — continue to work exactly the same way. The lookback simply moves where in time the model is anchored.
---
### How to Use It for Validation
1. Set **Lookback Bars** to a number that moves the indicator back to a point before a significant price move you remember.
2. The forecast projection will now draw across that historical period, ending somewhere in what is now the past.
3. Compare the projected path to the actual candles that formed after that point.
4. Increase or decrease the lookback value to step through different historical scenarios.
5. Set it back to **0** to return to live, real-time analysis.
---
### Key Practical Notes
- **Setting it to 0 (the default) means nothing changes.** The indicator behaves exactly as it always did. There is no disruption to existing setups.
- **Higher lookback values reduce the available search pool.** The further back you anchor, the less historical data exists before that point for the model to search through. If you go too far back, the info box will display a warning prompting you to reduce the lookback or increase search depth.
- **It is not a predictive tool in replay mode.** When you're looking at a historical projection, you already know what happened — the purpose is to evaluate whether the model's logic was sound, not to generate new signals.
- **Alerts do not trigger based on historical lookback readings.** Alerts only fire on live, current-bar conditions.
Note di rilascio
## Pattern Matches & Advanced Model Inputs — What ChangedThis update represents a significant simplification of how the indicator finds and selects historical analog patterns, while also giving you better visibility into what the model is actually doing under the hood.
---
### **The Biggest Change — How Matches Are Found**
Previously, you had to manually set three separate controls — Minimum Matches, Maximum Matches, and Min Similarity % — and balance them against each other to get a useful result. That was easy to misconfigure and hard to reason about.
The new design replaces all three with a single **Pattern Matches** target. You tell the indicator how many historical analogs you want, and it figures out the similarity threshold automatically.
- The search always starts at the strictest possible standard — 100% similarity — and works its way down one step at a time.
- It stops the moment it finds enough matches to hit your target, then collects the entire match pool at that single consistent standard.
- Every match in the final set was held to the same bar — there is no mixing of high-quality and low-quality analogs in the same pool.
- If the search reaches the **Similarity Floor** before hitting your target, it stops there, collects whatever it found, and warns you — rather than silently building a projection on essentially unrelated patterns.
---
### **The New Similarity Floor**
This is a safety net, not a primary control. It defines the lowest similarity standard the auto-search will ever accept.
- Think of it as the point where you're saying "if patterns aren't at least this similar, I don't trust the output."
- If the floor is hit, the info box displays a warning so you know the projection is built on weaker-than-ideal matches.
- The default is 50%, which is permissive enough to find matches in most market conditions while still excluding genuinely unrelated history.
---
### **The New Sim Floor Row in the Info Box**
This is one of the most useful additions. It shows you the similarity threshold the auto-search actually landed on for the current bar.
- **Green** means the algorithm found your target match count at 75% similarity or higher — the pattern is well-represented in history and the matches are tight.
- **Yellow** means it had to loosen to somewhere between 60–74% — usable, but hold the output with moderate confidence.
- **Red** means it dropped below 60% to find enough matches — the current pattern is relatively rare or unusual, and the projection should be treated cautiously.
- A **⚠ symbol** appears next to the percentage if the hard floor was hit before reaching your target count.
---
### **Advanced Model Inputs — Now a Separate Group**
The more technical model settings have been moved into their own collapsible group called **Advanced Model Inputs**, keeping the main settings panel clean for everyday use.
- **Use Log Returns** — stays on by default. Mathematically the more correct approach for comparing patterns across different price levels.
- **Use Regime Filter** — stays on by default, moved directly below Log Returns. The most impactful quality guard in the model.
- **Regime Tolerance** — stays at 0.35 default, directly beneath the Regime Filter toggle where it logically belongs.
- **Normalize Pattern** — now off by default. An opt-in for users who want shape-only comparison regardless of magnitude.
- **Use Correlation Similarity** — now off by default. A fundamentally different similarity method that should be a conscious choice.
- **Use Outcome-Based Weighting** — now off by default. An opt-in for users who want stronger past outcomes to carry more influence.
The philosophy here is that the default state of the indicator should be clean, transparent, and hard to misconfigure. Advanced options are there when you want them but don't require attention when you don't.
---
### **What the Filtered Out Row Tells You**
The bottom diagnostic row in the info box now shows two numbers — for example **12R / 3S** — which tell you how many candidates were eliminated at each stage of the filtering process.
- **R (Regime Removed)** is the count of historical patterns that were eliminated before similarity was even measured, purely because their volatility environment didn't match the current market. A large R means the current regime is relatively unusual in history.
- **S (Similarity Removed)** is the count of patterns that passed the regime check but still didn't score high enough to make the final pool. Under the new design this number will usually be very small or zero, since the threshold adjusts automatically to hit your target.
---
### **Suggested Pattern Matches Settings**
The tooltip on the Pattern Matches input now includes concrete guidance built in:
- **15–25** for conservative, high-quality analysis on liquid instruments with deep history.
- **25–40** as the balanced default suitable for most use cases.
- **40–60** for a smoother, more averaged projection with more analogs feeding it.
- **Above 60** is not recommended — match quality degrades and the projection starts converging toward general historical averages rather than anything pattern-specific.
Note di rilascio
**Pattern Match Price Projection — Update Notes**This update makes two small but practical improvements to the indicator's settings panel, focused entirely on organization and control. No logic, calculations, or visual outputs were changed.
---
**Current Pattern Group Repositioned**
The "Current Pattern" settings group has been moved to sit directly above the "Forecast Midline" group in the settings panel. Previously it was isolated at the bottom of the display settings, separated from the forecast line controls it naturally relates to. Now the layout follows a more intuitive visual order:
- Current Pattern (what the indicator is matching against)
- Forecast Midline (where the model projects price going)
- Bull/Bear Clusters and their bands
This keeps the flow logical — you see the pattern first, then the projections it generates.
---
**Show Current Pattern Toggle Added**
A new on/off toggle called "Show Current Pattern" has been added as the first control inside the Current Pattern group. It defaults to on, so behavior is identical to before unless you actively switch it off.
- When **on**, the purple line tracing the recent price pattern is drawn on the chart as usual.
- When **off**, the pattern line is hidden entirely — useful when you want a cleaner chart focused only on the forecast lines, or when you're familiar enough with the pattern window that the visual trace adds clutter rather than clarity.
- The color, width, and line style options remain directly below the toggle, unchanged.
Note di rilascio
**Pattern Match Price Projection — Update Notes**This update contains adjustments to settings organization and default values only. No logic or calculations were changed.
---
**Settings Panel Organization**
- The "Show Current Pattern" toggle has been moved into the main "Display" group alongside all other show/hide visibility controls, keeping them in one place.
- The "Current Pattern" group now contains only the color, width, and line style options for the pattern line.
---
**Default Value Changes**
- The bull and bear cluster lines are now **hidden by default**. The chart loads with just the average midline visible. The clusters can be enabled manually when needed.
- The midline **confidence bands are now on by default**, immediately showing the dispersion around the average projection on first load.
- The confidence band width multiplier now defaults to **1.0**, showing exactly one standard deviation either side of the midline.
- The ATR flat zone multiplier now defaults to **0**, meaning the cluster outcome filter is present but inactive until the multiplier is raised deliberately. The maximum value has been raised to 5.0, allowing more aggressive filtering on volatile instruments if needed.
Note di rilascio
**Lock to Candle — What's New**The update adds the ability to pin the projection to a specific historical candle and have it stay there. Previously the indicator would always anchor to the most recent bar, or shift backward by however many bars you manually typed into Lookback Bars. That offset was fragile — it had no memory of *which* candle you actually cared about, so switching timeframes or reloading the chart would silently move your anchor without any warning.
The new lock solves that by anchoring to a point in time rather than a bar count. Once locked, the indicator finds the right candle automatically no matter what timeframe you're on or how many new bars have formed since you set it.
**Three new inputs have been added to the Historical Lookback section:**
- **Lock to Candle** — the main toggle, off by default. Flip this on when you want the projection frozen to a specific candle. When it's off, everything behaves exactly as it did before and the Days Back and Time inputs are ignored entirely.
- **Days Back** — a number from 0 to 30 that tells the indicator how far back to look. 0 means today, 1 means yesterday, 2 means two days ago, and so on. This replaces the need to manually count bars, and it works correctly across different timeframes because it's measured in calendar days rather than bars.
- **Time** — the specific time of day for the candle you want to anchor to, expressed in the exchange's timezone. Set this to the opening time of your target candle. For example, 9:30 AM for the regular session open on US equities.
**The info box also gets a new row** that tells you the current state of the lock at a glance — whether it's active and how many bars back the resolved anchor sits, or a warning in orange if the target candle couldn't be found in the chart's loaded history. The title of the info box stays clean as just "Price Projection" regardless of lock state.
**One thing worth knowing:** weekends and market holidays have no candles. If Days Back lands on a Saturday, Sunday, or a holiday, the lock won't find a match and will show a warning. Just adjust Days Back to the nearest valid trading session in that case.
Note di rilascio
**Lock to Candle — Time Input Update**This was a small but meaningful quality-of-life improvement to how you specify the time of the candle you want to anchor to. The previous version used a session format input which required typing a start and end time in a string format like `0930-0931`. That was a workaround — the indicator only needed a single point in time, but Pine's session input inherently defines a range, so a fake one-minute window was being used just to approximate a single candle. It worked, but it was awkward and unintuitive.
The new version replaces that single session input with two clean integer inputs that live in the same place in the Historical Lookback settings group.
**What changed:**
- **Hour** — a whole number from 0 to 23 representing the hour of your target candle in the exchange's timezone. The default is 9, meaning 9 o'clock. Uses standard 24-hour time, so 13 would be 1 PM, 15 would be 3 PM, and so on.
- **Minute** — a whole number from 0 to 59 representing the minute. The default is 30, so combined with the default hour the indicator points to 9:30 — the US equity session open — right out of the box.
Together these two inputs replace what was previously one confusingly formatted field. Under the hood the match logic now checks the exact hour and minute of each bar directly, rather than testing whether a bar falls inside a session window. The result is a true single-candle point in time with no approximation involved.
Everything else about the lock — Days Back, the toggle, the info box status row, the fallback behavior — is unchanged.
Note di rilascio
Here's the full changelog from the previous version to the current version.---
**What Changed: Lock to Candle System**
The entire Lock to Candle mechanism was rebuilt from scratch. Everything else in the indicator is identical to the previous version.
**The Problem with the Previous Version**
The previous version had three compounding issues that caused "No Match" pre-market and unreliable behavior across instruments:
- `hour(time)` and `minute(time)` were used without a timezone argument, which behaves inconsistently depending on the instrument's exchange. For non-US instruments this could silently return the wrong hour entirely.
- Calendar day matching used raw millisecond arithmetic (`timenow % 86400000`) to approximate UTC midnight, which is imprecise and breaks around day boundaries.
- Both bugs together meant that pre-market the lock couldn't find today's candle (it hadn't printed yet) and the broken date math couldn't correctly fall back to yesterday, so it showed "No Match" instead of something useful.
**What Was Fixed**
- All time matching now uses `hour(time, "UTC")` and `minute(time, "UTC")` — explicit, portable, consistent across every instrument and exchange worldwide.
- The date arithmetic was removed entirely. Instead, the indicator now collects every bar that matches the UTC hour and minute into a running list as it reads through history bar by bar. At the end it simply picks the right entry by counting back through that list.
- Pre-market with Days Back = 0, the most recent match is yesterday's session candle and the projection shows immediately. Once today's candle closes at that time it flips automatically — no user action needed.
- Weekends and holidays are handled automatically. Those days have no candles so they never appear in the list. Days Back now counts only real trading sessions, not calendar days.
- The NonRepaint offset is intentionally left to stack on top of the lock offset. This means the projection is always anchored to a fully closed candle — the current live bar never influences the output. This is by design.
**Input Changes**
- **Hour (exchange timezone)** → renamed to **Hour (UTC)**. Enter the UTC equivalent of your target time. NYSE open at 9:30 AM ET is 13:30 UTC in summer and 14:30 UTC in winter.
- **Minute** → renamed to **Minute (UTC)**. Same field, clarified to reflect UTC.
- **Days Back** — same input, meaningfully different behavior. Previously counted calendar days and required the user to manually account for weekends and holidays. Now counts actual trading sessions only — Days Back = 1 always means the previous real session regardless of the day of the week.
- **Lock to Candle tooltip** — updated to describe the automatic pre-market behavior and the UTC time requirement.
Note di rilascio
**What Changed**---
**New User Input: Auto Previous Session**
The only new user-facing input added in this version is **"Auto Previous Session,"** located in the **Historical Lookback** section. It is a true/false toggle that defaults to **ON** and is only active when **"Lock to Candle"** is also enabled. It controls what the indicator does in the window of time between when a new session starts and when the target candle actually prints:
- When **ON**, the indicator automatically falls back to the most recent prior session's matching candle and keeps showing a projection. Pre-market users always see a live forecast — no blank screen, no manual adjustment needed.
- When **OFF**, the indicator abandons the lock entirely during that window and reverts to using the **"Lookback Bars"** value instead. The lock only activates once today's target candle has actually printed.
This input gives users direct control over a behavior that previously happened automatically with no way to override it. Traders who want the lock to behave strictly — only anchoring to today's candle, never silently substituting a prior session — now have that option.
---
**Improved Anchor Time-Awareness**
Supporting the new input above, the lock-to-candle resolution logic was upgraded to store the actual UTC timestamp of each matched candle alongside its bar index. Version 1 only tracked bar positions, so it had no reliable way to know whether a matched candle belonged to today or a prior session. Version 2 uses the stored timestamp to make that determination precisely, which is what allows the Auto Previous Session toggle to function correctly.
---
**Bias Label Wording Change**
When neither a bullish nor bearish signal is present, the Direction Bias label previously read **"Neutral"** and now reads **"None."** Behavior is identical — only the display text changed.
---
**Code Structure Cleanup**
The `anchor` variable was moved to an earlier point in the script, before the lock resolution block runs. This prevents a potential variable scoping issue in Pine Script's execution order. No visible change to the indicator's output.
Note di rilascio
# Pattern Match Price Projection & Prediction — Updated Indicator Guide## What This Indicator Does
This indicator finds historical price patterns that closely resemble what the market has done over a recent lookback window, then projects forward by averaging how those similar historical periods played out. The result is a visual forecast line on your chart, along with bull/bear probability scores based on how those historical analogs resolved.
---
## What Changed in the Updated Version
### **Momentum Filter (New Feature)**
The most significant addition is a Momentum Filter, which adds a second layer of candidate screening on top of the existing Volatility Filter. Here is what it does and how to use it:
- When enabled, the filter checks the RSI (Relative Strength Index) at each historical candidate bar and compares it to the RSI at your current pattern's anchor point. If a historical period looked similar in price shape but occurred under very different momentum conditions — for example, the current RSI is 65 (moderately overbought) but a candidate occurred when RSI was 28 (deeply oversold) — that candidate gets excluded before similarity scoring even begins.
- This matters because price patterns that look geometrically identical can behave very differently depending on whether the market was in an overbought, oversold, or neutral momentum state at the time. The filter prevents you from mixing apples and oranges in your analog pool.
- **Use Momentum Filter** is the on/off toggle. It defaults to OFF, which preserves the original behavior of the indicator so existing users see no change.
- **Momentum Length** controls the RSI period used for this comparison. It defaults to 14, which is the standard RSI setting. You can raise or lower this depending on your timeframe and style, but 14 is a solid starting point for most use cases.
- **Momentum Tolerance** sets how many RSI points of difference are allowed before a candidate is excluded. At the default of 15, a candidate's RSI must be within 15 points of your current pattern's RSI to survive the filter. Lower values make the filter stricter and will shrink your candidate pool significantly. Higher values are more permissive. If you enable this filter and notice the indicator struggling to find enough matches or throwing a warning, raise this tolerance first before changing anything else.
- Be aware that combining the Momentum Filter with the Volatility Filter simultaneously is powerful but can aggressively thin the candidate pool. If both filters are on and strict, you may frequently hit the Similarity Floor warning. Raise one or both tolerances, or increase Search Depth, if that happens.
---
### **Info Box Header Background Color (New Input)**
A small but practical visual improvement. The column headers inside the info box — the row that reads "Metric / Value / Move" and the title bar that reads "Price Projection" — now have their own independent background color control.
- In the previous version, the header cells used the same background color setting as the rest of the table.
- The new **Header Background** input under the Info Box settings lets you give the headers a distinct color, making the table easier to read at a glance. It defaults to a semi-transparent blue.
- This is purely cosmetic and has no effect on the indicator's calculations.
---
### **Info Box Diagnostic Row — Momentum Filter Awareness**
The diagnostic row at the bottom of the info box (the row that shows filter removal counts and warnings) has been updated to reflect the new filter:
- When the Momentum Filter is active, the filtered-out count now shows three numbers: **R** for regime/volatility removals, **M** for momentum removals, and **S** for similarity removals. Previously it only showed R and S.
- If the indicator finds zero matches and the Momentum Filter removed more than half the total candidates, it will display a specific warning pointing to the Momentum Filter as the likely cause, telling you to raise the tolerance. This makes diagnosis faster — you won't have to guess which filter is choking the pool.
- The warning priority order is: Momentum Filter warning first, then Volatility Filter warning, then Similarity Floor warning, then a generic no-data message. This ordering ensures the most actionable warning surfaces first.
---
### **Label Rename: Regime Filter → Volatility Filter**
The internal filter previously called "Use Regime Filter" and "Regime Tolerance" has been renamed to **Use Volatility Filter** and **Volatility Tolerance** in the settings panel. The underlying logic is unchanged — it still compares ATR-based volatility between the current pattern and historical candidates. This is purely a label change for clarity, making it more obvious what the filter is actually measuring.
---
## Quick-Start Recommendations for the New Inputs
- If you are new to the indicator or migrating from the previous version, leave the Momentum Filter **off** initially. Get familiar with how your existing settings behave first.
- Turn the Momentum Filter on when you want tighter, more contextually relevant analogs — particularly useful on lower timeframes where momentum state tends to have a strong influence on short-term outcomes.
- Start with Momentum Tolerance at **15–20** and tighten it only after confirming you have enough matches to maintain a stable projection.
- Use the diagnostic row in the info box as your early-warning system. If you see M removals climbing while your match count drops, that is your signal to loosen Momentum Tolerance.
Note di rilascio
# Price Projection — Update Notes## What Changed
This update brings a second analytical methodology directly into the Price Projection indicator, eliminating the need to run two separate indicators to get both signals. Everything now lives in one place, with both methodologies displayed side by side in a redesigned info box.
---
## The Core Idea
Price Projection has always matched historical price patterns to project where price might go next. The second methodology takes a completely different approach — instead of looking at what price *did*, it looks at what market *conditions* were like. By combining both in one indicator, you now get two independent reads on the same anchor point simultaneously.
When both methodologies agree, that is a stronger signal than either alone. When they disagree, that is useful information too — it tells you the price pattern and the underlying market conditions are pointing in different directions, which is worth knowing before acting.
---
## The Redesigned Info Box
The info box has been restructured with three columns — Metric, Projection, and Forecast — so you can read both signals on every row at a glance.
- **Projection** refers to the pattern matching methodology — it compares the shape and sequence of recent price action against historical analogs to determine what happened next under similar price conditions
- **Forecast** refers to the market state methodology — it compares the current combination of trend structure, momentum, and volatility against historical periods with similar conditions, regardless of what price looked like getting there
- Every key metric now shows both readings on the same row, making agreement and divergence immediately visible without any mental math
The rows in the updated info box are:
- **Bull Prob %** — the probability that price moves higher over the forecast horizon, shown separately for Projection and Forecast. Projection derives this from the weighted proportion of bull analog patterns. Forecast derives this from the weighted proportion of historical bars where similar market conditions were followed by higher prices
- **Bear Prob %** — the probability that price moves lower over the forecast horizon, shown separately for Projection and Forecast, derived the same way as Bull Prob % but for downside outcomes
- **Direction Bias** — the directional label (Bullish, Bearish, or None) for both Projection and Forecast. This is the quickest read on whether the two methodologies agree. Both showing Bullish or both showing Bearish is the highest conviction signal the indicator can produce. A divergence between the two — where one shows a directional label and the other does not, or they point in opposite directions — is a signal to slow down and look more carefully before acting
- **Bull/Bear/Flat** — the raw analog counts and total match count for both Projection and Forecast, showing how the historical matches were distributed between bullish, bearish, and flat outcomes. This is useful context for understanding what is driving the probability numbers — a 70% bull probability built on 25 bull analogs and 10 bear analogs tells a different story than one built on 7 bull analogs and 3 bear analogs
- **Sim Floor / Fit** — for Projection this shows the similarity threshold that was used and the average fit quality of the selected matches. For Forecast it shows just the fit quality score since the market state methodology does not use a similarity floor. Higher fit quality means the historical matches are very close to current conditions, which generally makes the probability readings more reliable
- **Anchor** — where in time the projection is anchored to
- **Filtered Out** — diagnostic information showing how many candidates were removed by the regime filter, momentum filter, and similarity threshold during the Projection matching process
The projected move percentages that previously appeared in the info box have been removed. The projection lines on the chart already show that information visually, and removing the percentages makes the box cleaner and easier to read at a glance.
---
## New User Input
There is one new input group with a single setting called **Forecast Model**. This controls which internal model the Forecast column uses to score and compare historical market states. All five options use the same three components — trend structure, momentum, and volatility — but weight them differently and use different indicator lengths:
- **Conservative** uses slower, longer-period indicators with more weight on trend and volatility. Best suited for higher timeframes or instruments with smoother price action where you want to avoid noise
- **Balanced** is the default. It uses standard indicator lengths and equal weighting across trend, momentum, and volatility. A good starting point for most instruments and timeframes
- **Aggressive** uses short, fast indicators with high weight on momentum and low weight on volatility. Most responsive to recent price action and better suited for active intraday trading where momentum is the primary driver
- **Trend Following** puts the heaviest weight on the trend component and uses a very slow secondary moving average. Best for trending markets where you want the state matching to be dominated by whether price is structurally above or below a long-term trend
- **Mean Reversion** puts the heaviest weight on momentum and uses the shortest momentum length available. Designed to identify extreme momentum conditions — overbought or oversold states — as the primary matching criterion
---
## How to Use It
The simplest approach is to watch the Direction Bias row for both columns.
- If Projection shows **Bullish** and Forecast shows **Bullish**, that is the strongest long signal the indicator can produce — two independent methodologies with completely different matching logic both pointing the same way
- If Projection shows **Bearish** and Forecast shows **Bearish**, that is the strongest short signal
- If one shows a directional label and the other shows **None**, treat it as a moderate signal with some uncertainty
- If Projection and Forecast point in opposite directions, treat it as a warning to wait for more clarity — the price shape and the market conditions are in conflict, and acting on one while ignoring the other increases risk
For the Forecast Model setting, start with **Balanced** and leave it there unless you have a specific reason to change it. If you are trading a strongly trending instrument and want the Forecast column to focus on trend conditions, switch to **Trend Following**. If you are primarily looking for momentum exhaustion setups, **Mean Reversion** will make the Forecast column more sensitive to extreme momentum readings.
Note di rilascio
# Price Projection — Update Notes## What Changed
This update improves how the Volatility Filter compares historical market conditions to the current environment. The change makes the filter more accurate, more stable, and more meaningful — particularly when using tight tolerance settings.
---
## The Problem with the Old Approach
Previously the Volatility Filter checked a single bar's ATR at the anchor point of each historical candidate. This was a snapshot — one moment in time — and snapshots can be misleading.
- A candidate pattern could have an anomalous volatility spike right at its anchor bar that doesn't represent how volatile the market actually was across the full pattern
- Conversely, a candidate could pass the filter because its anchor bar happened to have a similar ATR reading, even though the surrounding volatility environment was completely different
- Setting a tight tolerance was unreliable because you were at the mercy of whatever happened to ATR on that one specific bar
- This made low tolerance values noisy and unpredictable in practice
---
## What Changed
The filter now computes the **average ATR% across the entire pattern length** for both the current pattern and each historical candidate, then compares those averages.
- Instead of asking "did this one bar have similar volatility?", it now asks "was the overall volatility environment similar across this entire pattern window?"
- A candidate no longer gets excluded because of a single noisy ATR bar at its anchor point
- A candidate no longer passes through because one bar happened to match while the rest of the pattern lived in a different volatility regime
- The comparison is now a true environment-level assessment rather than a point-in-time snapshot
---
## What This Means in Practice
The most immediate practical effect is that tight tolerance values now work as intended.
- At the old default of 0.35, the filter was loose enough that single-bar noise didn't matter much — almost everything passed through anyway
- With pattern-window averaging, a tolerance of 0.15 is now a genuinely meaningful constraint — it means the average volatility environment across the full pattern has to be within 15% of the current average, which filters out truly incomparable regimes without being so strict it starves the match pool
- Very tight values like 0.05 are now viable and can produce noticeably cleaner projections on instruments where volatility regime is a strong predictor of pattern behavior
---
## Settings Changes
Three settings have been updated to reflect the improvement:
- **Volatility Tolerance default** has been lowered from 0.35 to 0.15. With pattern-window averaging in place, 0.35 was unnecessarily permissive. The new default of 0.15 is a more meaningful constraint that takes advantage of the improved accuracy without being so tight that it regularly starves the match pool under normal market conditions
- **Volatility Tolerance minimum** has been lowered from 0.05 to 0.01, and the **step size** has been reduced from 0.05 to 0.01. This gives you much finer control at the low end where the interesting precision work happens. You can now dial in values like 0.05, 0.08, or 0.12 rather than being limited to coarse 0.05 increments
---
## A Note on the Momentum Filter
The Momentum Filter was reviewed as part of this update and intentionally left unchanged. Unlike volatility — which is an environmental condition best measured across the full pattern window — momentum is near-term and directional. The current RSI reading at the anchor bar is the most meaningful single data point for matching momentum conditions, and averaging it across the pattern length would dilute that signal. The single-bar check is the correct behavior for momentum matching.
---
## How to Use It
Start with the new default of 0.15 and observe how many matches the filter passes through in the Filtered Out diagnostic row at the bottom of the info box.
- If the regime filter is removing a very large proportion of candidates and you are frequently hitting the Similarity Floor, loosen the tolerance slightly — try 0.20 or 0.25
- If you want to tighten the match quality and are working on a liquid instrument with deep history and a Search Depth of 2000 or more, try lowering toward 0.10 or even 0.05
- Values below 0.05 are viable but will significantly reduce the candidate pool and may require increasing Search Depth to compensate
- If the filter is removing very few candidates at 0.15, the current volatility environment is well represented in history and the default is working well — no adjustment needed
The tooltips for both the Volatility Filter and Volatility Tolerance inputs have been updated to accurately describe the new pattern-window averaging behavior.
Note di rilascio
Got it — comparing your pasted document (the base) against the final code we built. Let me diff them properly.Good. I have a clear picture of every difference. Here's the precise changelog.---
# Price Projection — Changes from Previous Version
## 1. Volatility Filter — Pattern-Window Averaging
This is the most significant functional change. The Volatility Filter previously checked a single bar's ATR at the candidate's anchor point. It now averages ATR% across the full pattern length for both the current pattern and each historical candidate before comparing them.
- The reference ATR is now computed by summing `atrPct` across all `patternLen` bars of the current pattern window and dividing by the count of valid bars
- Each candidate ATR is computed the same way across its own pattern window
- The tolerance comparison is unchanged — only what it compares has improved
- This makes tight tolerance values meaningful and reliable rather than noise-sensitive. A tolerance of 0.05 now genuinely means the average volatility environment across the full pattern must be within 5% — not just one arbitrary bar
---
## 2. Volatility Tolerance Default and Range
Three input parameter changes to the Volatility Tolerance setting:
- **Default** lowered from `0.35` to `0.15` — appropriate now that pattern-window averaging removes the need for extra slack to compensate for single-bar noise
- **Minimum** lowered from `0.05` to `0.01` — enables much finer control at tight settings
- **Step size** reduced from `0.05` to `0.01` — allows precise values like `0.08` or `0.12` rather than being limited to coarse increments
- **Tooltip** updated to accurately describe pattern-window averaging and corrects the default reference from 0.35 to 0.15
---
## 3. Forecast Column Fit Quality
The Sim Floor / Fit row now shows a fit quality score in the Forecast column.
- `feAvgDiff` computes the mean state score distance across all selected Forecast matches
- `feFitScore` converts that to a percentage using `100 / (1 + avgDiff)` — the same formula as the standalone Forecast Engine
- Color thresholds match the Projection fit quality — lime ≥85%, yellow ≥70%, orange ≥55%, red below that
- Displays as `— · 99.5%` to make clear the sim floor concept does not apply to the Forecast methodology
---
## 4. Vol Filter and Mom Filter Rows Added to Info Box
Two new rows added to the info box after the Anchor row, before the Filtered Out diagnostic row.
- **Vol Filter** — shows `ON · 0.15` or `OFF · 0.15` in the Projection column. The Forecast column shows `—` since these filters only apply to Projection
- **Mom Filter** — shows `ON · 15.0` or `OFF · 15.0` in the Projection column. The Forecast column shows `—`
- Both on/off state and tolerance value are combined in a single cell in the Projection column
- Text is plain white — no color coding
- Vol tolerance displays to two decimal places, Mom tolerance to one decimal place
---
## 5. Info Box Table Size
The info box table was increased from 11 rows to 13 rows to accommodate the two new filter rows. Both the initial `table.new` declaration and the position-change rebuild inside the execution block are updated. The `table.clear` call is updated to cover all 11 data rows.
---
## 6. Diagnostics Row Shift
The Filtered Out diagnostic row shifted from row 8 to row 10 to make room for the Vol Filter (row 8) and Mom Filter (row 9) rows above it.
---
## 7. Info Box Column Headers
The column headers were updated from `"PP"` and `"FE"` to `"Projection"` and `"Forecast"` — immediately readable without needing to know what the abbreviations stand for.
Note di rilascio
Quick info box bug fix. All internal.Note di rilascio
Internal default updates, Input name updates, and Info Box label updates to enhance and make the user interface and experience more intuitive. No change to internal logic or inputs.Note di rilascio
## Version Update NotesThis update was primarily focused on improving the information box rather than changing the forecasting engine itself. No forecasting logic, probability calculations, pattern matching routines, weighting systems, or model-selection behavior were modified. The goal was to make the displayed information easier to read and easier to interpret at a glance while preserving all existing functionality.
One of the most noticeable changes is the use of the previously empty Forecast cell on the Anchor row. Rather than leaving that space unused, it now displays the currently selected Forecast Engine model. This gives immediate context for the Forecast column without increasing the size of the table or introducing an additional row. The selected model is always visible, allowing the user to instantly know whether the Forecast Engine is operating in Balanced, Conservative, Aggressive, Trend Following, or Mean Reversion mode.
To keep the display compact, abbreviated model labels were introduced. Instead of displaying longer descriptions or adding prefixes such as "Mod:", the table now simply shows:
* Balanced
* Conservative
* Aggressive
* Trend
* Mean
This reduces visual clutter and makes the information feel like a natural part of the table rather than an additional diagnostic label.
The Bull/Bear/Flat statistics row was also tightened up. The original formatting included spaces around each slash, which consumed unnecessary horizontal space. The new format removes those spaces while retaining readability. The result is a cleaner presentation that allows more information to fit comfortably within the same table width. This is a subtle change, but it improves the overall density and appearance of the information box.
The Sim Floor / Fit row received a small formatting adjustment as well. Previously the values were separated using a dot-style divider. The display now uses a slash separator, creating a more intuitive relationship between the two values. The row reads more naturally as a comparison between the effective similarity threshold and the resulting average fit quality.
The Forecast Engine fit score presentation was also improved. Instead of displaying a placeholder symbol followed by the fit percentage, the table now explicitly labels the value as "Fit". This makes the Forecast column more self-explanatory and removes any ambiguity about what the percentage represents. Users can immediately identify it as a Forecast Engine quality metric rather than needing to infer its meaning.
Taken together, these changes move the information box toward a cleaner, more professional layout. Several previously unused or underutilized areas now provide meaningful information, while unnecessary characters and visual noise have been removed. The result is a more efficient display that communicates the same amount of information with less effort from the user.
Note di rilascio
Internal code grammatical updates only. No change to inputs or logic.Note di rilascio
**What Changed and Why**The Forecast Engine — the right column in the info box — has been rebuilt from the ground up. Here's what it was doing before, what it does now, and why that matters.
---
**The Old Version's Problem**
The original Forecast Engine was running its own independent search through price history, hunting for bars where a composite market state score (built from EMAs, RSI, and ATR) was numerically close to today's reading. On the surface that sounds reasonable. The problem is that it was never actually independent — it was scanning the same price data, over the same time window, producing results that were quietly correlated with the main model anyway. Worse, its internal weighting mechanism had no logical connection to outcome quality. It weighted matches by how close their state score was to today's, which tells you nothing about whether those historical moments were actually followed by meaningful price moves.
The result was a second column that *looked* like a confirmation signal but was really just noise dressed up as information. When both columns agreed, it felt like double confirmation. It wasn't.
---
**What the New Version Does**
The Forecast Engine no longer runs its own search at all. Instead, it takes the exact same validated match pool that the main Projection model already found — the same analog patterns, already filtered by volatility regime and momentum if those filters are on — and re-examines them through a completely different lens.
Specifically, for every matched analog it now looks at two things:
- **How similar the pattern was** to the current one, the same similarity score the main model already computed
- **How decisively price actually moved** after that analog's pattern completed, measured as the absolute magnitude of the forward price change over the forecast horizon
It then blends those two factors together into a single weight for each match, and uses those weights to compute the Forecast column's bull and bear probabilities. The `Forecast Model` input — Conservative, Balanced, Aggressive, Trend Following, Mean Reversion — now controls how that blend is split between similarity and outcome magnitude, rather than controlling EMA and RSI lengths as it did before.
---
**What the Two Columns Now Actually Mean**
This is the key practical difference:
- The **Projection column** asks: *among the matches that looked most like today's pattern, how many went up vs. down?* It weights by shape similarity.
- The **Forecast column** asks: *among those same matches, which ones were followed by the strongest, most decisive moves, and which direction did those go?* It weights by outcome magnitude blended with similarity.
Both columns are looking at the same pool of analogs. They're just asking different questions about that pool.
---
**Why Divergence Between the Columns Is Now Meaningful**
Before, when the two columns disagreed it was essentially random — two loosely correlated systems occasionally landing on different answers for no coherent reason. Now, divergence actually tells you something:
- If **Projection says Bullish but Forecast says None**, the patterns looked similar to today but the historical follow-through was weak or mixed. Shape match is there, conviction isn't.
- If **Forecast says Bullish but Projection is weaker**, the analogs that moved most decisively after their patterns were bullish, even if the overall similarity-weighted count was less lopsided.
- If **both agree**, you have shape confirmation *and* outcome confirmation from the same pool simultaneously — that's a genuinely higher bar than the old version's fake double-confirmation.
---
**The OS% Metric**
The `OS:` figure in the Forecast column of the Sim Floor / Fit row stands for Outcome Strength. It measures how decisively the selected analogs moved on average, expressed as a percentage of the strongest single move in the pool. Think of it as a quality indicator for the Forecast column specifically — the same way the Fit % is a quality indicator for the Projection column. A high OS% means the match pool has strong historical follow-through behind it. A low OS% means the analogs drifted rather than moved, so the Forecast column's probabilities carry less conviction regardless of which direction they point.
Note di rilascio
---**Forecast Engine — Replaced Entirely with Structure Engine**
The original ran an independent scan through price history looking for bars where a composite state score (built from EMA spread, RSI, and ATR%) was numerically close to today's. It had its own separate lookback, its own weighting mechanism, and its own match pool. The result was a second column that looked independent but was silently correlated with the main model, and whose weighting had no logical connection to outcome quality.
The new version replaces this entirely with the **Structure Engine** — a live, independent assessment of current market conditions built from five components, each casting a directional vote of +1 bull, -1 bear, or 0 neutral:
- **T** = EMA Trend — fast EMA vs slow EMA
- **P** = Price Position — where close sits relative to both EMAs
- **R** = RSI Momentum — RSI vs 50 midline with a neutral zone between 40 and 60
- **V** = Volatility Expansion — current ATR vs its rolling average, confirming trend direction when expanding
- **S** = Swing Structure — higher lows vs lower highs counted over the pattern window
The net score runs from -5 to +5. Bullish requires a net score of +2 or above, Bearish requires -2 or below, everything else is Neutral.
---
**Inputs — Forecast Engine Group Replaced**
The original had a single `Forecast Model` dropdown with five options (Conservative, Balanced, Aggressive, Trend Following, Mean Reversion) controlling EMA/RSI/ATR lengths and weighting multipliers for the state score scan.
The new version replaces this with a `Structure Speed` dropdown — Fast, Medium, Slow — with preset EMA, RSI, ATR, and ATR MA lengths baked in for each setting. No weighting multipliers, no state score math.
- **Fast** — EMA 10/34, RSI 7, ATR 7, ATR MA 30. Reactive, good for volatile instruments or shorter timeframes.
- **Medium** — EMA 21/55, RSI 14, ATR 14, ATR MA 50. Balanced default.
- **Slow** — EMA 34/89, RSI 21, ATR 21, ATR MA 100. Smoother, better for higher timeframe context.
---
**Info Box — Column Header**
"Forecast" renamed to "Structure."
---
**Info Box — Table Structure**
The original used a 3-column table throughout. The new version expands to a 7-column table. All rows except the component row use merged cells to maintain the same visual appearance as before. The Sim Floor / Fit row uses all seven columns — col 0 for the metric label, col 1 for the Projection value, and cols 2–6 for one individual component letter each.
---
**Info Box — Bull Prob % and Bear Prob % rows**
The original showed the Forecast Engine's independently scanned bull and bear probabilities. The new version shows Structure bull % and bear % derived from the five-component vote, where each component is worth 20%. So 3 bear votes = 60% bear, 1 bull vote = 20% bull.
---
**Info Box — Direction Bias row**
The original showed the Forecast Engine's bias label based on its independent scan. The new version shows Bullish, Bearish, or Neutral based on the net structural vote score.
---
**Info Box — Reliability row (new, not in original)**
Not present in the original at all. The new version adds a Reliability row directly under Direction Bias.
- The **Projection column** shows a composite score from 0–100 labeled High / Moderate / Weak / Low, combining Fit%, bull/bear edge, match count, and whether the similarity floor was hit.
- The **Structure column** shows a directional edge label — Edge: Strong / Moderate / Weak / No Edge — based on the absolute spread between Structure bull % and bear %, mapped directly to vote counts. A 3/2 split = Moderate, 4/1 or 5/0 = Strong, 2/3 = Weak, 1/4 or less = No Edge.
---
**Info Box — Sim Floor / Fit row**
The original showed a Fit% score in the Forecast column — a number derived from average state-score distance that had no demonstrated connection to outcome quality.
The new version shows five individually colored component letters — **T P R V S** — one per cell, each colored green for bull, red for bear, and gray for neutral. This tells you at a glance exactly which structural components are driving the read and which are neutral or contradicting it.
---
**Info Box — Bull/Bear/Flat row**
The original showed the Forecast Engine's raw bull/bear/flat match counts from its independent scan. The new version shows **ATR: Expanding**, **ATR: Contracting**, or **ATR: Neutral** — whether current volatility is meaningfully above, below, or in line with its own rolling average. Color coded by context: Expanding in a Bearish structure shows red, Expanding in a Bullish structure shows green, Contracting shows gray, Neutral shows yellow.
---
**Info Box — Anchor row**
The original showed the `feModelShort` label (e.g. "Balanced") in the Forecast column. The new version shows **MOD: Medium / Fast / Slow** — the Structure Engine speed setting.
---
**What Didn't Change**
Every single line of the Projection column logic is identical to the original. This includes the pattern scanning, similarity threshold auto-scan, volatility and momentum filtering, weighting, cluster direction assignment, probability calculation, projection line drawing, confidence bands, bull and bear cluster lines, and all Projection column info box cells. The core model is completely untouched.
Note di rilascio
---**Info Box — Column Mode Toggle**
A new dropdown input was added to the Info Box settings group, sitting directly below the "Show Info Box" toggle. It lets you choose between two display modes:
- **Projection & Structure** (default) — shows both the Projection and Structure columns exactly as the original did, with the full two-column layout including all Structure Engine data.
- **Projection Only** — renders a clean two-column table showing only the Metric and Projection columns, with no extra whitespace or ghost columns to the right.
The toggle works by dynamically creating the table with the correct number of columns (2 or 7) whenever the setting changes, using Pine Script's `var` inside `barstate.islast` pattern so the table is only recreated when necessary and never causes runtime errors.
---
**Structure Column — Row Content Changes**
Three rows in the Structure column were reorganized to improve the information hierarchy:
- The **T/P/R/V/S component letter row** (which appeared next to Sim Floor / Fit) has been removed entirely. These five colored letters showing individual Structure Engine vote breakdown are no longer displayed in the table.
- **ATR context** (`ATR: Expanding`, `ATR: Contracting`, or `ATR: Neutral`) has moved up to fill the vacated slot next to the Sim Floor / Fit row, where T/P/R/V/S previously lived.
- **MOD: Fast/Medium/Slow** has moved up one row to sit next to Bull/Bear/Flat, where the ATR context previously lived.
- The Anchor row's Structure column, which previously showed MOD, now shows a neutral dash since MOD shifted up.
---
**No Logic or Calculation Changes**
Everything under the hood is identical to the original:
- All pattern matching, similarity scoring, and threshold scanning logic is unchanged.
- The Structure Engine's five-component voting system (Trend, Price, RSI, Volatility, Swing) still runs in full on every bar regardless of which display mode is selected.
- All filters — Volatility Filter, Momentum Filter, ATR Flat Zone Filter — are unchanged.
- The Forecast Midline, Confidence Bands, Bull and Bear Cluster lines, and Current Pattern drawing logic are all identical.
- All three alert conditions (Bullish, Bearish, Directional) are unchanged.
- The Historical Lookback, Lock to Candle, and Bias Logic systems are unchanged.
- All input defaults are preserved exactly as they were in the original.
Note di rilascio
Minor Info Box grammatical fixes.No change to indicator logic.
Note di rilascio
**Price Projection Indicator — Change Log****Overview**
This update strips the indicator back to its core purpose: finding historical price patterns that resemble the current one and projecting forward based on what happened next. A secondary analysis layer that had been added — the Structure Engine — was removed in full, along with the interface option that toggled it. The result is a leaner, faster, and more focused tool.
---
**What Was Removed**
*Structure Engine*
The Structure Engine was an independent market analysis system bolted onto the side of the projection model. It ran five separate technical votes — trend direction via dual EMAs, price position relative to those EMAs, RSI momentum, ATR volatility expansion, and swing structure — and combined them into a directional score and reliability rating. While the intent was to give extra context alongside the pattern projection, in practice it added a second opinion that competed with rather than complemented the core model.
- The entire Structure Engine input group was removed, including the Speed setting (Fast / Medium / Slow) that controlled the EMA, RSI, and ATR lengths it used.
- All five vote calculations — EMA trend, price position, RSI momentum, ATR expansion, and swing structure — were deleted.
- The net structure score, directional label (Bullish / Bearish / Neutral), strength percentage, edge label, ATR context label, and vote breakdown counts were all removed.
- The Structure Engine's own reliability score, which was separate from the projection reliability score, was removed.
- All the color variables associated with the Structure Engine's display output were removed.
*Info Box Columns Dropdown*
Previously the info box had a dropdown setting called "Info Box Columns" with two options: "Projection Only" and "Projection & Structure." This toggle controlled whether the Structure Engine's results appeared as a third column alongside the projection data.
- The dropdown input itself was removed from the settings panel.
- The internal logic that read this setting and conditionally rendered the Structure column was removed.
- All the table cell calls that populated the Structure column — including bull/bear vote percentages, structure direction, edge label, ATR context, and model speed — were removed.
- The table merge calls that spanned the Structure column across multiple rows were removed.
---
**What Changed as a Result**
- The info box is now a clean two-column layout — one column for the metric label, one for the projection value — with no conditional logic branching based on a column mode setting.
- The table is always initialized at exactly two columns, simplifying the internal setup and removing a variable that tracked column count changes between renders.
- The indicator's settings panel is shorter and easier to navigate, with no structural analysis group to configure.
---
**What Was Not Changed**
Everything related to the core pattern matching model remains exactly as it was. The projection midline, confidence bands, bull and bear cluster lines, similarity scoring, volatility and momentum filters, bias logic, reliability score, lookback and lock-to-candle controls, and all three alert conditions are untouched. The only thing this update does is remove the Structure Engine and the interface that supported it.
Note di rilascio
Defaults updated.Note di rilascio
**Price Projection Indicator — Change Log**---
**Momentum Filter Now On By Default**
The Momentum Filter was previously turned off when you first loaded the indicator, requiring you to manually enable it. It now defaults to on, meaning the indicator will immediately filter historical analog candidates to only those that occurred under similar RSI momentum conditions to the current market. This produces more contextually relevant matches right out of the box without any setup required. Existing charts with saved settings are not affected by this change.
---
**Info Box Columns Dropdown Removed**
The settings panel previously included a dropdown called "Info Box Columns" that let you switch between showing just the projection data or adding a second Structure Engine column alongside it. Since the Structure Engine was removed in a prior update, this dropdown no longer served any purpose and has been cleaned out entirely. The info box is now always a straightforward two-column layout — one column for the metric name, one for the value — with no toggle needed.
---
**"Reliability" Renamed to "Match Quality"**
The row previously labeled "Reliability" in the info box has been renamed to "Match Quality." Nothing about the underlying score changed — it still combines four things to judge how trustworthy the current analog selection is:
- How closely the historical pattern shapes matched the current pattern.
- How strong the directional edge is between bull and bear outcomes.
- How many matches were found relative to your target.
- Whether the similarity floor had to be hit to find enough matches.
The rename was made because "Reliability" implied a broader promise — as if it were rating the indicator itself. "Match Quality" is more honest. It is specifically telling you how good the historical matches are, nothing more.
---
**New "Projection ATR" Row Added to Info Box**
This is the most meaningful new addition. A new row called "Projection ATR" now appears in the info box between Bull/Bear/Flat and the Anchor row. It answers a question the info box previously had no way to express: even if the analog matches are good and the direction bias is clear, how much do the historical outcomes actually agree at the end of the forecast window?
The value is expressed in ATR units — for example, "2.40 ATR" — which makes it immediately meaningful regardless of what instrument or timeframe you are on. A trader who already thinks in ATR terms can instantly translate that number into a price range in their head. The key things to understand about how it works:
- It measures the spread between the upper and lower outcome boundaries specifically at the final bar of the projection, not averaged across the whole forecast. The endpoint is what matters for decision-making.
- It is calculated from the raw dispersion of analog outcomes and is completely independent of the Band Width Multiplier setting. Changing that multiplier changes how the bands look on the chart but does not affect this number.
- It is self-calibrating across instruments and timeframes. The same reading means the same thing on QQQ intraday as it does on a daily chart of anything else, because it is always expressed relative to that instrument's own current volatility.
The color coding is intuitive and maps directly to trading confidence:
- Green — below 1.0 ATR — the analog outcomes converged tightly. High agreement.
- Yellow — 1.0 to 2.0 ATR — moderate spread, reasonable uncertainty.
- Orange — 2.0 to 3.0 ATR — wide spread, the direction bias should be treated with more caution than usual.
- Red — above 3.0 ATR — outcomes scattered badly. Low conviction regardless of what Direction Bias or Match Quality show.
The practical implication is that Projection ATR acts as a confidence modifier on everything else in the info box. A Bearish bias with High Match Quality but a red Projection ATR is a materially weaker signal than the same bias with a green Projection ATR. That combination was previously invisible and is now surfaced directly.
Note di rilascio
Info Box warning labels updated.Note di rilascio
Info Box enhancements.Info Box now shows Pattern Length, Search Depth, and Forecast Horizon.
Now these things can easily been seen at a glance rather than needing to open the settings menu.
Note di rilascio
# Pattern Match Price Projection — Change LogThis update introduces a new visual layer that allows users to actually see the historical patterns the model is using to build its forecast. The goal was to improve transparency and confidence in the projection process by making the underlying analogs visible directly on the chart.
Previously, the indicator identified historical matches behind the scenes and used them to generate the forecast, but there was no way to inspect those matches visually. Users could see the final projection and statistics, but they could not verify whether the selected analogs truly resembled the current market structure.
With this enhancement, the indicator now provides a way to display those matched patterns on the chart itself.
## New Feature: Matched Pattern Visualization
A new display option has been added that allows historical pattern matches to be drawn directly on the chart.
When enabled, the indicator overlays the historical price structures that most closely resemble the current market pattern. This makes it much easier to understand *why* the projection is behaving the way it is.
Rather than relying solely on statistics or probabilities, users can visually compare the current setup against the historical analogs that contributed to the forecast.
This change helps transform the indicator from a purely predictive tool into one that is also more explainable and easier to validate.
## New Input Group
A dedicated **Matched Patterns** settings group has been added to the Inputs tab.
This group keeps all controls related to the new visualization feature organized in one place and separate from the existing forecast and information display settings.
The controls were intentionally placed within the Inputs tab rather than the Style tab so that all customization options remain part of the indicator's own configuration interface.
## New User Controls
Several new customization settings have been introduced to give users full control over how matched patterns appear.
Users can now adjust:
* Whether matched patterns are displayed at all.
* How many matched patterns are shown simultaneously.
* The color used for the matched pattern overlays.
* The line thickness used for those overlays.
* The line style used for the overlays.
These settings allow users to tailor the visualization to their own chart preferences without affecting the forecast lines or other indicator elements.
## Updated Default Settings
After testing and review, the default appearance of matched patterns was adjusted to improve visibility.
The finalized defaults are:
* **Visible Matches:** 10
* **Color:** Yellow
* **Transparency:** 0%
* **Width:** 4
* **Line Style:** Solid
These defaults were selected because they make the matched analogs easy to identify while still allowing the forecast projections to remain visible.
## Improved Transparency of the Model
One of the biggest benefits of this update is the increased transparency it provides.
Users can now answer questions such as:
* "Do these historical examples genuinely resemble the current market?"
* "Are the selected analogs clustered around similar market environments?"
* "Does the projection appear to be based on reasonable comparisons?"
This additional visibility can help users build greater confidence in the projection when the analogs look convincing, or encourage more caution when the historical matches appear less relevant.
## No Changes to Forecast Calculations
It is important to note that this update does **not** alter the underlying forecasting engine.
The following components remain unchanged:
* Pattern scoring methodology.
* Similarity calculations.
* Volatility filtering.
* Momentum filtering.
* Match selection logic.
* Projection weighting methodology.
* Bull and bear probability calculations.
* Reliability scoring.
* Alert behavior.
The indicator continues to generate projections exactly as it did before.
The new functionality only adds a visual representation of the historical matches that were already being used internally.
## User Experience Improvements
Overall, this update improves the usability of the indicator in several important ways.
It provides:
* Greater insight into the forecasting process.
* Easier visual validation of selected analogs.
* More confidence when evaluating projection quality.
* Additional customization options without increasing complexity.
* A clearer understanding of what historical data is influencing the forecast.
## Summary
This release adds a significant quality-of-life enhancement to the Pattern Match Price Projection indicator.
While the mathematical engine behind the forecast remains unchanged, users now have the ability to visually inspect the historical analogs that drive the projection.
The result is an indicator that is not only predictive, but also more transparent, interpretable, and user-friendly.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.