1. Orderflow Memory Average Strategy Description
A k-NN style pattern-matching indicator that scans historical bars for market states similar to the current one across 6 features, then builds a "smart" average line by extrapolating the trailing momentum of the closest historical matches onto the current price
1.1 Indicator Concept
This indicator treats "market memory" as a nearest-neighbor search problem. At every bar, the current market is described as a 6-dimensional feature vector - short-term momentum (1/3/5-bar rate of change), RSI, ATR-based volatility, and relative volume. The indicator then scans up to scanDepth bars into the past, computes the same 6-feature vector at every historical point, and measures how "distant" each historical state is from the current one using a weighted absolute-difference sum. That distance is converted into a similarity score with an exponential decay kernel (closer = higher similarity, exactly 100% at zero distance). The topMatches most similar historical states are then used to build a single projected value: the current close nudged by the similarity-weighted average of those historical states' own trailing 5-bar momentum. Smoothed with an EMA, this becomes the "Market Memory Average" line, with a directional Cloud and boxes marking exactly where on the chart those historical analogs occurred.
- The "smart line" replays trailing momentum, not future outcomes: it does not look at what happened after each historical match - it borrows each match's own trailing 5-bar momentum (the same momentum that made it a match) and projects that forward from the current close, on the assumption that regimes which "feel" the same tend to keep moving the same way.
- Fixed, hand-tuned feature weights: unlike some of LuxAlgo/Zeiierman's other k-NN indicators that auto-optimize feature weighting, this one uses hardcoded scaling divisors/multipliers per feature (chosen to bring RSI, ROC%, ATR% and volume ratio onto comparable numeric scales) - not exposed as inputs.
- Historical match boxes with overlap-merging: when the most similar historical windows overlap in both time and price, their boxes are merged into one combined box (summed direction, concatenated rank/similarity text) instead of being drawn as separate overlapping rectangles.
- Fully static alerting: every alert in this script is defined via alertcondition() - 7 conditions in total, all individually selectable from TradingView's standard alert-creation dropdown, with no dynamic alert() calls anywhere in the script.
1.2 Indicator Features
- Market Memory Average Line (toggleable): the EMA-smoothed similarity-weighted projection line, colored bullish/bearish/neutral based on its own slope over a configurable lookback.
- Memory Cloud (toggleable): a 4-layer gradient cloud drawn between the Market Memory Average and an ATR-offset reference line, positioned below the line when bullish and above it when bearish, fading in transparency as it moves away from the line.
- Historical Match Boxes (toggleable): boxes drawn around the exact bars of the top similarity-ranked historical matches (only on the most recent bar), colored by their net historical direction, with overlapping matches automatically merged into a single box.
- Historical Match Labels (toggleable): a label on each match box showing rank (#1, #2, ...) and similarity percentage for every match folded into that box, configurable text size and color.
- Similarity Feature Controls: independently configurable RSI length, ATR length, and Volume MA length used purely as inputs to the similarity search (not plotted themselves).
- Alerts: 7 fully static alertcondition() entries - price crossing above/below the average, the average's slope flipping bullish, bearish, or neutral, plus 3 "any of the above" combination alerts - every one of them individually selectable in TradingView's alert dialog.
1.3 How to Use the Indicator
- Treat the Market Memory Average as a momentum-echo baseline, not a support/ resistance level in the traditional sense - it sits where price would be if it continued moving the way its closest historical analogs were already moving.
- Use the historical match boxes to sanity-check the story - if the boxes cluster around clearly bullish or clearly bearish past episodes, the average's slope has a more coherent historical basis than if the boxes are scattered and mixed-direction.
- Read the Cloud's side as a trend-strength cue - a wide, strongly one-sided cloud (fully below in an uptrend, fully above in a downtrend) reflects a persistent slope, while a cloud that keeps flattening/flipping sides suggests the average's slope is unstable.
- Raise Historical Scan Depth and Similarity Sensitivity together for stricter, rarer signals - a deeper scan finds more candidate analogs, and higher sensitivity demands they be closer matches before they influence the average, which together trade responsiveness for confidence.
- Cross-check against the underlying RSI/ATR/Volume settings if the matches look off - since these three feature lengths directly control what "similar" means, a mismatch between the feature timeframe and the chart's actual volatility regime can make historical matches feel less relevant.
1.4 How the Indicator Works
Inputs & Their Roles
- scanDepth ("Historical Scan Depth", default: 300, range 20-2000): how many bars into the past the similarity search scans on every bar to find candidate matches. Higher values search more history but scale the per-bar computation cost linearly.
- topMatches ("Top Similar Matches", default: 5, range 2-20): how many of the highest-similarity candidates (after sorting) are actually used to build the weighted average and, on the last bar, drawn as match boxes.
- patternBars ("Historical Pattern Length", default: 10, range 3-50): how many bars are included inside each historical match box (the high/low envelope spans this many bars ending at the matched point) - a display-only sizing parameter, not part of the similarity distance calculation itself.
- sensitivity ("Similarity Sensitivity", default: 1.5, range 0.1-5.0): the exponent multiplier in the similarity kernel (100 * exp(-distance * sensitivity)) - higher values punish distance more harshly, so only very close historical states retain meaningful similarity.
- rsiLength / atrLength / volLength ("RSI Length" default 14 / "ATR Length" default 14 / "Volume MA Length" default 20): the lookback lengths for the RSI, ATR, and relative- volume features that feed the similarity comparison - these are used purely as matching inputs and are never plotted on their own.
- showSmartLine ("Show Market Memory Average", default: true): toggles the projected average line - but also gates the entire underlying calculation pipeline that feeds the Cloud (see the note below).
- smartSmoothLength ("Average Smoothing", default: 50, range 1-200): the EMA length applied to the raw similarity-weighted projection to produce the final plotted line.
- smartTrendLength ("Slope Detection Length", default: 20, range 1-200): how many bars back the smoothed line's current value is compared against to determine bullish/bearish/neutral slope coloring.
- showCloud ("Show Cloud", default: true) / cloudSpread ("Cloud Spread", default: 1.5) / cloudTransp ("Cloud Transparency", default: 65, range 0-95): toggles the Memory Cloud, controls how many ATRs the cloud's outer edge extends from the average line, and sets its base transparency (the 4 gradient layers are offset ±18/±6 from this base value).
- showMatchBoxes ("Show Historical Match Boxes", default: true): toggles drawing the historical pattern boxes on the last bar.
- bullColor / bearColor / neutralColor ("Bullish"/"Bearish"/"Neutral", defaults: lime / red / blue): shared coloring for both the average line's slope state and the historical match boxes' net direction.
- showMatchLabels ("Show Historical Match Labels", default: true) / matchLabelSizeIn ("Label Text Size", default: "Small") / matchLabelColor ("Label Text Color", default: gray): toggles and styles the rank/similarity-percentage labels attached to each match box.
Main Logic Flows
🎯 Flow 1: What You See
- A smoothed "Market Memory Average" line colored by its own slope, a 4-layer gradient Cloud on the side opposite the slope direction, and (only refreshed on the latest bar) colored boxes with rank/similarity labels marking exactly where in history the current market's closest analogs occurred.
📐 Flow 2: Building the Feature Vector
- Every bar computes 6 features: 1/3/5-bar rate of change (roc1/roc3/roc5), RSI normalized to a 0-1 scale, ATR expressed as a percentage of close, and relative volume (current volume divided by its own moving average, defaulting to 1.0 if the average is zero). Because the similarity scan below indexes these series by a variable offset up to scanDepth bars back, each series is given an explicit max_bars_back(…, 2000) declaration so Pine allocates enough history buffer for the loop to read from.
🔍 Flow 3: Scanning History for Matches
- Once enough bars exist (bar_index > scanDepth + patternBars), the match list is cleared and rebuilt every bar. The loop walks backward from patternBars + 1 to min(scanDepth, bar_index - patternBars - 1) bars ago, reading each historical bar's own 6-feature snapshot via series offset indexing.
- For each historical point, a weighted absolute-difference distance is computed: ROC1 difference ÷2, ROC3 difference ÷4, ROC5 difference ÷6, RSI difference ×2, ATR% difference ÷2, relative-volume difference ÷1.5. These divisors/multipliers are fixed constants chosen to bring each feature's typical range onto a comparable scale (RSI is 0-1 so it's amplified; ROC5 tends to have the widest spread so it's dampened most).
- The total distance feeds an exponential similarity kernel: similarity = 100 * exp(-distance * sensitivity) - identical states score 100%, and similarity decays smoothly as the states diverge, with sensitivity controlling how fast that decay happens.
- Each candidate also records its own momentum (that historical bar's own trailing 5-bar ROC) and a direction sign (+1/-1/0) derived from that momentum's sign - this is what later determines both the projected line's push and the match boxes' bull/bear/neutral coloring.
⚖️ Flow 4: Building the Weighted Average Projection
- After scanning, all candidates are sorted by similarity descending and the top topMatches are kept. Their trailing momentum values are averaged, weighted by each match's own similarity score (higher-similarity matches pull the average toward their own momentum more strongly).
- That weighted average momentum is applied to the current close - close * (1 + avgWeightedMomentum / 100) - producing the raw, unsmoothed "smart line" value for the current bar. This value is na whenever showSmartLine is off or no matches were found.
🧱 Flow 5: Drawing Historical Match Boxes (Last Bar Only)
- Only when barstate.islast is true: all previously drawn boxes/labels are deleted, and (if showMatchBoxes is on) each of the top matches gets a candidate box spanning its patternBars- bar window's actual high/low envelope, positioned at its true historical bar location.
- Before creating an actual box object, each candidate is checked against already- accumulated candidates for both time overlap and price overlap; if both overlap, the two are merged into one (expanded time/price bounds, concatenated rank/similarity text, summed direction) rather than drawn as two separate boxes.
- Once merging is finished, each final box is colored bull/bear/neutral by the sign of its summed direction, and (if showMatchLabels is on) gets a label with the concatenated rank/similarity text, positioned above or below the box depending on that net direction.
📈 Flow 6: Smoothing, Slope & Coloring
- The raw smart-line value is smoothed with an EMA of length smartSmoothLength. Its slope is measured as the difference between the current smoothed value and the value smartTrendLength bars ago; the sign of that difference selects bullish/bearish/neutral coloring, shared by both the line itself and, later, the Cloud.
☁️ Flow 7: The Memory Cloud
- A reference level is placed cloudSpread ATRs away from the smoothed line, on the side opposite the slope direction (below the line when bullish, above it when bearish, coincident with the line when perfectly flat). Three intermediate levels are interpolated at 25%/50%/75% of the way toward that reference, and four separate fill() calls shade the gaps between consecutive levels with progressively higher transparency moving away from the line - producing a fading gradient rather than one flat-colored band.
🔔 Flow 8: Alerts
- All 7 alert conditions are defined with alertcondition(): price crossing above/below the smoothed average, the slope changing to bullish, bearish, or neutral (each detected as an edge-trigger against the previous bar's state), plus 3 convenience "any of" combinations (any cross, any color change, any alert at all). Because every one is static, each appears as its own selectable option in TradingView's alert-creation dialog - no "Any alert() function call" catch-all is required here.
Outputs & Usage Roles
- Market Memory Average line: the main directional signal, extrapolating the trailing momentum of the closest historical analogs onto the current price.
- Memory Cloud: a visual gauge of trend persistence/strength via its width and which side of the line it sits on.
- Historical match boxes & labels: the evidence trail - exactly which past bars drove the current average and how similar they were.
- Alerts: 7 fully static alertcondition() entries (see Flow 8), each individually selectable in TradingView's alert dialog.


