OPEN-SOURCE SCRIPT

Premium/Discount ML Zones [PickMyTrade]

442
What does it do?

Builds a Premium / Equilibrium / Discount map from a higher-timeframe dealing range, then runs an online logistic regression over every price level inside that map to detect the exact band where the model currently reads a directional edge. Because the range is read from one anchor timeframe, the zones sit at the same prices whether you view the 5m, 1h or Daily chart.

────────────────────────────────────

The intellectual problem

Premium/Discount is a location framework: above the 50% equilibrium of a dealing range price is expensive, below it price is cheap. Two problems show up the moment you try to automate it.

First — the range is usually drawn on whatever chart you are looking at. A 5-minute chart finds 5-minute swings, so it anchors to a micro-range that may be a few points wide. The Daily chart finds a range a hundred times larger. The same price is then simultaneously "premium" on one timeframe and "discount" on another, and the label stops meaning anything. The conventional discipline is to define the range on a higher timeframe and drop down only to execute — never to redraw the range on the execution chart.

Second — location alone is not an edge. Knowing price is in the lower half of a range tells you it is cheap relative to that range. It does not tell you whether cheapness is currently being rewarded. In a strong downtrend every discount print keeps getting cheaper. Location is a filter; something else has to decide whether the location is worth acting on.

This indicator separates those two jobs. The dealing range and its three zones are the map, anchored once on a higher timeframe. A logistic regression trained on the chart's own history is the decision, and it is what marks the actionable band inside the map.

────────────────────────────────────

How the dealing range is anchored

The range is built from confirmed swing highs and lows read from the Dealing Range Timeframe (default Daily) via
Pine Script®
. Each side re-anchors to its most recent confirmed swing, with guards that keep the pair coherent:

Pine Script®


Those guards are what make the range track the current leg rather than a fixed lookback window. In an uptrend each new higher low pulls the low side up with price, instead of leaving equilibrium pinned to an ancient low that price has long since left behind.

From that range:

  • [] Equilibrium — the exact 50% midpoint,
    Pine Script®
    [] Equilibrium band — a neutral fair-value zone of ±Equilibrium Band × range around the midpoint (default ±10%, i.e. the middle 20%). No signals fire inside it.
  • Premium — everything above the band. Discount — everything below it.


Break of structure — when price closes beyond the anchored range, the old range is stale until a new swing confirms. A bearish BOS blocks longs and a bullish BOS blocks shorts, so the model does not fade a breakout while waiting for the range to re-anchor.

────────────────────────────────────

How the logistic regression works

Step 1 — Three z-score normalised features

All three are standardised over the Z-Score Window (default 50) so the model is scale-invariant across instruments and timeframes.

  • [] F1 — Position in range: where the close sits between the range low and high, clamped to 0–1. This is the premium/discount coordinate itself. [] F2 — Dwell time: a rolling time-at-price measure — the fraction of the last N bars that closed within one price band of the current close. High dwell means price has spent real time here; a level touched once in a spike scores low.
  • F3 — Momentum: rate of change over the momentum length, normalised. Distinguishes a discount that is stabilising from one that is still falling.


Step 2 — Online gradient descent with L2 regularization

There is no fixed training window and no retraining pass. Each confirmed bar is labelled from its forward return over the Label Horizon, and the weights take one gradient step per bar, always evaluated on the previous bar's features so no current-bar information leaks into the update:

Pine Script®


The
Pine Script®
term is weight decay: it pulls weights back toward zero each step, which stops any single feature from running away to an extreme value on a stretch of trending data. The bias term
Pine Script®
is deliberately left unregularized — it carries the base rate, not a feature relationship.

Step 3 — Posterior

Pine Script®


Step 4 — The ML entry zone (what the model detects)

This is the part that does the work. Rather than only scoring the bar in front of it, the model scores every price level inside the discount half and the premium half — sweeping the position feature across the zone while holding dwell and momentum at their current values — and marks the contiguous band where its probability clears the Entry Threshold:

Pine Script®


That band is the ML Buy / Sell Zone drawn on the chart. It is the exact price range in which a signal would fire right now — visible before price arrives there. Its thickness is meaningful: a thin band means only a sliver of the zone clears the threshold, a thick band means the model reads an edge across most of the zone. When nothing clears the threshold, the band disappears entirely rather than showing a level the model does not support.

────────────────────────────────────

Reading the indicator

  • [] PREMIUM box (orange) — upper region of the HTF range. Shorts are considered here only. [] EQUILIBRIUM box (grey) — the fair-value band around the 50% midpoint. Nothing fires here by design. [] DISCOUNT box (blue) — lower region. Longs are considered here only. [] ML BUY / SELL ZONE (bright band) — the model-detected band inside the discount/premium region, labelled with the peak probability found in that band. [] ● circle (blue) — high-conviction long: P(Bull) ≥ 0.85. ▲ triangle (blue) — standard long: P(Bull) ≥ threshold. [] ● circle (orange) — high-conviction short: P(Bear) ≥ 0.85. ▼ triangle (orange) — standard short: P(Bear) ≥ threshold. [] Dashed equilibrium line — the exact 50% midpoint. [] Dashed SL / TP lines — reference levels from the range extreme at ATR × multiplier and the Risk:Reward ratio.


Only the first bar of each signal cluster fires — if conditions stay true for several bars, only the transition bar is marked.

Info table (top-right)

  • [] ● LIVE (green) — the model has taken ≥ Training Samples Needed gradient steps. ● WARMUP (yellow) — still accumulating; signals suppressed. [] Zone — Premium / Equilibrium / Discount, or BOS ↑ / BOS ↓ (yellow) when price has broken the range. [] P(Bull) / P(Bear) — live posterior at the current bar. [] N Trained — total gradient updates taken.


────────────────────────────────────

Inputs

Dealing Range
  • [] Dealing Range Timeframe — whose swings define the map (default D). Set it equal to or higher than your execution chart. This is the input that makes the zones identical across timeframes. [] Swing Left / Right Bars — swing definition on the anchor timeframe (default 3/3). Right Bars is the confirmation delay: the range re-anchors that many anchor-timeframe bars after a swing forms.
  • Equilibrium Band — half-width of the neutral zone as a fraction of range (default 0.10). Set 0 to collapse it to a single line.


Dwell-Time Feature
  • Scan / Dwell Bands (default 20) — price resolution for the entry-zone scan and the dwell band width. Dwell Lookback (default 50).


Logistic Regression
  • [] Training Samples Needed — gradient updates before signals activate (default 80). [] Entry Threshold — minimum probability to fire a signal and to light the ML zone (default 0.65). [] Learning Rate — gradient step size (default 0.05). Higher adapts faster but noisier. [] L2 Regularization — weight decay (default 0.001). 0 disables it.
  • Label Horizon (default 5), Momentum Length (default 14), Z-Score Window (default 50).


Signal Levels
  • Show SL/TP Lines, ATR Period, SL ATR Buffer (default 1.2), Risk:Reward (default 1.8).


Visual / Display
  • [] Show Premium/Discount Map, Show ML Entry Zone, Zone Left Extent / Forward Extend, Show Equilibrium Line, Regime Background, zone colours. [] Zen Mode — hides SL/TP lines and the table; map and ML zone remain.


────────────────────────────────────

Three alerts included

  • [] PD ML - Long — discount long fired [] PD ML - Short — premium short fired
  • PD ML - Any Signal — either direction


────────────────────────────────────

Technical notes

  • [] Swing detection on the anchor timeframe needs Swing Right Bars of that timeframe to confirm. With the Daily default that is a three-day confirmation delay before the range re-anchors. This is inherent to non-repainting swing detection, not a tunable away. []
    Pine Script®
    uses
    Pine Script®
    , so historical bars use only confirmed anchor-timeframe values. The developing anchor bar updates in real time, which is expected behaviour for a live higher-timeframe reference. [] The dwell feature counts closes within one band of the current close over the lookback — a bar-based proxy for time-at-price. It does not use tick or volume-profile data. [] The entry-zone scan holds dwell and momentum fixed while sweeping position. It answers "if price were at level X, with today's momentum and dwell, what would the model read?" — a counterfactual across location, not a forecast of the path.
  • Logistic regression assumes a monotonic relationship between each feature and the log-odds. Real price behaviour is not always monotonic in position-within-range; the model captures the dominant direction of that relationship, not its curvature.


────────────────────────────────────

Requirements and limitations

The model needs Training Samples Needed gradient steps before signals activate; on short-history charts the table shows WARMUP and nothing fires. Weights are learned per chart and per timeframe — switching symbol or timeframe restarts the learning from zero.

Probabilities are the model's read of patterns in its own training history. They are not a probability of profit, and patterns that historically preceded a directional move may not repeat.

The equilibrium band is deliberately dead space. If you want signals nearer the midpoint, reduce the band toward 0 — but the closer to fair value you trade, the less the premium/discount premise is contributing.

If the Dealing Range Timeframe is left blank or set below your chart's timeframe, the range is computed on the chart timeframe and the cross-timeframe consistency is lost. That is the failure mode this indicator exists to avoid.

The three zones describe location within one dealing range. They carry no information about ranges above them — a Daily discount can sit inside a Weekly premium.

────────────────────────────────────

Risk disclosure

Nothing here forecasts price. The zones describe where price sits inside a measured range; the classifier reports what its training history associates with that location. Use with your own position sizing and risk management. Not financial advice.

Built natively in Pine Script® v6. Online logistic regression trained by per-bar gradient descent with L2 weight decay, a rolling dwell-time feature, and a higher-timeframe swing-anchored dealing range. No external libraries, no data feeds.

Open source — Mozilla Public License 2.0.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.