Supply Demand AI [PickMyTrade]Supply Demand AI asks the question every supply/demand tool skips: when price returns to a zone, does this arrival look like the ones that reversed — or like the ones that ate straight through?
Every supply/demand indicator draws the zone. None of them score the arrival. This one does. Each time price re-enters a zone, nine properties of the return are frozen before the outcome is known — approach speed, prior tap count, zone age, departure strength, base tightness, base volume, trend pressure, relative volume and zone width — and the arrival is voted on by a Lorentzian nearest-neighbour search over every similar return this chart has already resolved. The result is stated in the past tense: of the arrivals that looked like this, X% produced the configured reaction move before the zone failed.
The script also scores two doctrines stated everywhere in supply/demand teaching and measured almost nowhere: whether fresh zones genuinely outperform tapped ones on this chart, and whether heavy-volume bases genuinely outperform quiet ones. The info table reports what actually happened, not what the doctrine says should have.
――――――――――――――――――――――――――――――――――――――
🔷 WHAT IT MEASURES
🔸 Zone formation — base-and-departure, not pivot clustering A zone is born from a run of compressed candles (the base) followed by an impulsive leg away of a configurable ATR multiple within a fixed window — the Rally-Base-Drop / Drop-Base-Rally shape, detected as a sequence rather than asserted from a single bar. A pivot cluster has no departure to measure; a base-and-departure zone has three properties frozen at birth that a pivot never carries: how hard the market left, how tight the base was, and which side was trading volume while it sat there.
🔸 Zone geometry The origin block (solid segment) marks the actual base candles. The projection (lighter band) carries those prices forward to where they can be tested. The departure measure (vertical bar on the departure candle) shows the full distance the move reached — readable straight off the price scale. Freshness is written as text ("fresh" / "2 taps"), not encoded in a line style that has to be decoded.
🔸 Outcome — reaction magnitude, not hold-or-break A return that drives the configured ATR multiple back away from the zone edge before closing decisively through it = REACTED. A return that closes beyond the far edge by the break buffer = FAILED. A return that does neither inside the timeout window = STALLED and discarded from training — price sitting inside a zone is not evidence either way.
🔸 Two doctrine read-outs The info table reports the freshness edge (did untouched zones react more often than tapped ones on this chart?) and the base-volume edge (did heavy-volume bases outperform quiet ones?). Either can come back negative, and the table says so when it does.
――――――――――――――――――――――――――――――――――――――
🔷 THE LORENTZIAN NEAREST-NEIGHBOUR CLASSIFIER
🔸 Why Lorentzian, not Naive Bayes A Naive Bayes model was the obvious alternative and is the wrong tool here: it assumes the features are conditionally independent given the class. Departure strength, base tightness and zone width all describe the same underlying impulse from three angles — multiplying their densities counts one piece of evidence three times. A nearest-neighbour vote makes no independence assumption at all. It asks a narrower, more honest question: of the returns already resolved on this chart, what happened to the ones that arrived most like this one?
🔸 Distance metric Distance is Lorentzian — log(1 + |a − b|) — applied per axis and summed. Against a library of this size, plain Euclidean distance lets one outlier axis dominate; the log compresses extremes, so a return that is typical on eight features and unusual on the ninth still finds its true neighbours.
🔸 Shared library — supply and demand in one pool Every feature is written relative to the direction of the test, so a fast approach into demand and a fast approach into supply are the same event described the same way. Sharing one library across both directions doubles the effective sample count without mixing unlike distributions.
🔸 Shrinkage The neighbour vote is shrunk toward the library's own base rate. Without it, k unanimous neighbours read as a certainty the sample size cannot support. The shrinkage weight is expressed in neighbour-equivalents so it is independent of k.
🔸 Honest caveat — stated here, not buried in a tooltip The classifier learns as history replays, so loading a different amount of chart history changes how many returns have trained it and therefore the percentage shown on a zone. The zones themselves, their boundaries and which bars they appear on are unaffected. This is inherent to on-chart learning.
――――――――――――――――――――――――――――――――――――――
🔷 SIGNALS AND DISPLAY
🔸 Zone appearance Full-strength blue (demand) or orange (supply) border at or above the conviction threshold. Muted at the opposite end. Neutral while price is inside — the zone is neither reacting nor failing yet. Grey once consumed. A zone born from twice the required departure draws with a heavier border — the one property worth reading before any text.
🔸 Zone label Nearest live demand, nearest live supply, and any zone with a return open right now receive a worded label: zone type · departure in ATR · evidence grade (A–D) · tap count · classifier read. Every other zone speaks through colour alone, which caps visible labels at roughly three regardless of timeframe or zoom.
🔸 Evidence grade (A–D) Measures accumulated evidence only — departure strength (35%), base tightness (25%), resolved return count (20%), age (20%). Deliberately excludes the classifier's probability so the grade and the percentage remain two different statements: the grade says how much stands behind the zone; the percentage says how similar arrivals resolved.
🔸 Return history ticks A coloured tick inside the zone at every bar where one of its own returns resolved — blue for a reaction, orange for a failure. Renders each zone's individual track record in place so the percentage can be read against the evidence behind it.
🔸 Order flow band A band above the trend EMA while cumulative volume delta is rising, below it while delta is falling. Opacity scales with how strong that pressure is against its own recent range — a faint band means the tape is undecided; a solid band means one side is leaning on it. Context, not a signal: it says which side is pressing when price arrives at a zone.
🔸 Info table Zones on chart · returns graded · overall reaction rate · freshness edge · base-volume edge · base-flow edge · live order flow direction and z-score · nearest demand and supply with ATR distance. Reads LEARNING until the warmup sample count is met.
🔸 Alerts Four alertcondition() calls: price entered a zone · return reacted · return failed · any resolved return. Worded as observations. Recommended alert setting: Once Per Bar Close.
――――――――――――――――――――――――――――――――――――――
🔷 INPUTS
🔸 Zone Detection Base Candle Max Range (ATR ×) — a candle counts as base while its range is below this multiple. Lower = cleaner zones, fewer of them. Default 0.60. Min / Max Base Candles — fewest and most candles that form a valid base. Default 1 / 6. Departure Strength (ATR ×) — how far price must travel from the base before the base qualifies as a zone. The single most important setting. Default 1.60. Departure Window (bars) — bars allowed for the departure to reach its target. Default 5. Zone Boundaries — Wick or Body extent for the base. Wick is the conservative read. Default Wick. Minimum Zone Height (ATR ×) — floor on zone thickness, expanded symmetrically about the base midpoint. Default 0.45. ATR Period — volatility yardstick for all distances. Default 14.
🔸 Return Resolution Reaction Target (ATR ×) — how far back away from the zone counts as a REACTION. Default 1.50. Break Buffer (ATR ×) — how far beyond the far edge price must CLOSE to count as a failure. Default 0.30. Return Timeout (bars) — bars a return stays open before being discarded as STALLED. Default 20. Zone Consumed On — Wick Touch / Body Touch / 50% Fill / Full Fill. Governs retirement only; returns always measure from the first wick. Default Body Touch. Max Returns Per Zone — a zone revisited this many times behaves like a range boundary. Default 4.
🔸 Probability Engine Warmup Samples — resolved returns required before the classifier replaces the running reaction rate. Default 25. Neighbours Compared — k in the nearest-neighbour vote. Smaller = more local; larger drifts toward the library rate. Default 8. Conviction Threshold — probability at or above which a zone draws at full conviction. Default 0.62. Approach Window — bars used to measure how fast price entered the zone. Default 5. Volume Baseline — averaging window for relative volume. Default 20. Trend EMA Period — reference for the trend-pressure feature. Default 50.
🔸 Order Flow Order Flow Band — show / hide. Default on. Flow Momentum Period — lookback for the rate of change of CVD. Default 14. Flow Band Width (ATR ×) — height of the band from the EMA to its outer edge. Default 1.00. Flow Normalisation Window — z-score window so the band reads the same across instruments. Default 50.
🔸 Visual Demand / Supply / In-zone / Consumed Colours · Show Zones · Zone Labels · Return History Ticks · Keep Consumed Zones · Max Live Zones (cap on live slots; consumed zones are free) · Zones Per Side (nearest N zones above and below price) · Show Zones Within ATR × (safety ceiling) · Label Every Zone · Label Size · Zone Border Width · Zone Evidence Grade.
🔸 Display Zen Mode — hides labels and info table; zones and ticks remain. Show Info Table.
――――――――――――――――――――――――――――――――――――――
🔷 REQUIREMENTS AND LIMITATIONS
🔸 The classifier reads what this chart has seen — not a pre-trained model and not a fixed statistical table. On a chart with thin history or a symbol the market has recently repriced, the library may be small and the read thin. The sample count travels with every zone label and the table header so this is never hidden. 🔸 Loading a different amount of chart history changes how many returns have trained the classifier, which changes the percentage shown on a zone. The zones themselves are unaffected — this is inherent to on-chart instance-based learning. 🔸 Zone geometry is fixed at birth and never re-centred. No request.security() call is made anywhere. Test state advances only on barstate.isconfirmed. No future data is referenced. 🔸 The departure is measured over bars that have already closed. A zone appears on the bar its departure qualifies and never moves afterwards. 🔸 Base volume and base flow are estimated from the close-position formula — a synthetic proxy, not true bid/ask data. The classifier adapts to the noise, but the quality of the read improves on instruments with genuine intrabar price travel. 🔸 The evidence grade (A–D) and the classifier percentage are two different statements by design. Do not read either alone. 🔸 Past resolved returns are hypothetical observations — no commission, no slippage — and are not a record of trading results. This script does not issue trade instructions and nothing in it is financial advice.
――――――――――――――――――――――――――――――――――――――
Built natively in Pine Script® v6. Lorentzian k-nearest-neighbour classifier trained on-chart from resolved supply/demand returns — no external libraries, no lookahead, no repainting. Zone formation uses a base-and-departure state machine; outcome is reaction magnitude, not hold-or-break. Attribution: the Rally-Base-Drop / Drop-Base-Rally construction is long-established public technical analysis, implemented independently here. The evidence grade and drawing layer are shared with the author's own Support Resistance AI — stated here plainly rather than left for a reader to find.
Open source — Mozilla Public License 2.0.
Chỉ báo






















