Premium/Discount ML Zones [PickMyTrade]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 request.security(..., lookahead=barmerge.lookahead_off) . Each side re-anchors to its most recent confirmed swing, with guards that keep the pair coherent:
if not na(ph) and (na(swingLow) or ph > swingLow) swingHigh := ph if not na(pl) and (na(swingHigh) or pl < swingHigh) swingLow := pl
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, (rangeHigh + rangeLow) / 2 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:
_pred = f_sigmoid(w0 + w1f1 + w2f2 + w3*f3 ) _label = label_bull ? 1.0 : 0.0 _err = _label - _pred w1 := w1 + i_learn_rate * (_err * f1 - i_l2_lambda * w1)
The - i_l2_lambda * w1 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 w0 is deliberately left unregularized — it carries the base rate, not a feature relationship.
Step 3 — Posterior
post_bull = f_sigmoid(w0 + w1f1 + w2f2 + w3*f3) post_bear = 1.0 - post_bull
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:
for j = 0 to i_nbins float p = rangeLow + (eq_bot - rangeLow) * j / i_nbins float f1p = ((p - rangeLow) / range_size - pos_mean) / pos_std float pbup = f_sigmoid(base + w1 * f1p) if pbup >= i_posterior_thresh ml_long_lo := na(ml_long_lo) ? p : math.min(ml_long_lo, p) ml_long_hi := na(ml_long_hi) ? p : math.max(ml_long_hi, p)
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. request.security uses lookahead_off , 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. אינדיקטור

Streaming ML Probability Triple-Barrier, Conformal & CalibratedStreaming-ML Probability — Triple-Barrier, Conformal & Calibrated
What it is
A self-training probability model that estimates P(up-barrier resolves before down-barrier) and — crucially — reports its own calibration. The differentiator is not the classifier; it is the labelling and the honesty layer wrapped around it. The pane shows a probability, an honest uncertainty band, a plain-language verdict, and a reliability diagram that tells you whether to believe any of it.
Why these components belong in ONE script (not a stack of indicators)
They are the stages of one honest prediction pipeline, each fixing a failure mode of a naive "ML" overlay:
Triple-barrier labels define what is predicted as a real, path-dependent outcome (which barrier is hit first) instead of an arbitrary "next bar up?", and resolve forward in time so training only ever sees confirmed results — no look-ahead.
Z-scored, bounded features keep every input finite so no single bar can blow up the online weights.
Logistic SGD + Lorentzian k-NN, fused in log-odds with a Kish decorrelation shrink — a linear model for the trend and a fat-tail-tolerant neighbour vote for non-linear structure, combined without double-counting the shared features.
Regime engine (efficiency + ADX + Hawkes) gives each market state its own calibration and shrinks the probability toward 0.5 where a regime is barely seen — the model defers to a coin flip where it has not learned.
Adaptive Conformal Inference turns the point estimate into a coverage-controlled band that holds under drift, so the uncertainty is honest rather than a fake point estimate.
Conviction + hard vetoes (regime, MTF, participation/CVD, calibration quality) stop the model acting on a number it cannot back up.
The calibration harness — reliability table, Brier score, and forward edge versus an unconditional base rate — is the whole point: a probability is only useful if 70% means 70%.
Labels say what to learn, features feed it, the fused classifier predicts, regime + conformal say how much to trust it, the vetoes gate it, and calibration proves whether any of it held. Remove a stage and the honesty breaks — that is why they ship as one engine.
How it works (mechanics)
Each confirmed bar opens a triple-barrier sample (unless the OU half-life says reversion is too slow to resolve in the horizon). When a sample resolves, the model takes one online gradient step on its own features and outcome, the resolved sample enters the k-NN memory, and the nonconformity score updates the conformal band via Gibbs-Candès ACI. The live probability is the log-odds fusion of the logistic output and the Lorentzian k-NN vote, regime-shrunk during warm-up. A directional signal fires only when the probability band clears the signal margin, conviction clears its floor, and no hard veto trips. Every resolved directional call is then scored against an unconditional same-horizon base rate (Hit% vs Base%, Wilson-bounded, regime- and recency-weighted).
Non-repaint: training only on resolved triple-barrier outcomes, signals on bar close, MTF requested with lookahead_off, no dynamic-length ta(). The live probability updates each bar — a current estimate from fixed historical training.
How to use
Read the VERDICT line first — ACT, STAND ASIDE (no calibrated edge), or WAIT, based on the live signal and the model's own calibration.
Check the reliability diagram / Brier. Points off the diagonal, or Brier ≥ 0.25 (worse than a coin flip), mean the probability is not trustworthy yet — the engine will tell you to stand aside.
A signal fires only on confluence: probability past the band-margin, conviction past the floor, no hard veto.
The conformal band is the honest uncertainty — a wide band means low confidence.
Everything here is descriptive, probabilistic context — never an instruction.
Note on honesty: on pure intraday noise (e.g. NIFTY 1-minute) this model will often show NO EDGE / VETO with Brier ≈ worse than a coin flip — and it says so plainly rather than inventing a signal. That is the intended behaviour.
Use on any market
The Data Source inputs (Close / High / Low / Volume) drive the features, the triple-barrier labels and the calibration, so the model runs on any series (standard candles, Heikin-Ashi, etc.) and any market. All thresholds are ATR-relative. Defaults are set for NIFTY index-futures intraday; change the source or lengths for other assets. Assets with no volume simply contribute nothing through the volume feature.
Originality
Most "machine-learning" indicators emit an uncalibrated score that is never checked against what actually happened. The contribution here is the closed, honest loop: real path-dependent labels, a fused-but-decorrelated classifier, regime-conditional shrinkage, a drift-robust conformal band, conviction/veto gating, and a built-in reliability + Brier + edge harness that can — and often does — tell you the model has no edge right now. It is built to be disprovable, which is the opposite of most signal scripts.
Credits
Triple-barrier labelling & meta-labelling — Marcos López de Prado
Logistic regression / SGD — classical statistics
Lorentzian (non-Euclidean) distance for k-NN — relativistic-distance concept
Conformal prediction — Vovk, Gammerman & Shafer; Adaptive Conformal Inference — Gibbs & Candès
Brier score — Glenn W. Brier
Wilson score interval — Edwin B. Wilson
Efficiency Ratio — Perry Kaufman · ADX / DMI — J. Welles Wilder
Hawkes self-exciting process — Alan G. Hawkes
Ornstein-Uhlenbeck / AR(1) half-life — Ornstein & Uhlenbeck
Effective-sample decorrelation — Leslie Kish
The pipeline assembly, the regime-conditional calibration and the conviction/veto layer are the author's original implementation.
Limitations (honest)
A well-calibrated probability is not an edge after costs. The forward stats are in-sample, close-to-close at a fixed horizon, with no costs, slippage or stops — a study aid, not a backtest. The model is small (six features, online weights); it warms up slowly and will stand aside often. Past behaviour does not assure future behaviour.
Disclaimer
Educational / informational study for chart analysis only. NOT financial advice, NOT a strategy, NOT a recommendation. It places no orders and guarantees no outcome. Markets carry risk; do your own research and manage your own risk. Paper-trade before risking real money. אינדיקטור

SuperTrend Logistic Regression | Flux ChartsGENERAL OVERVIEW
The SuperTrend Logistic Regression indicator combines the classic SuperTrend trend-following tool with a self-training logistic regression model that assigns a probability percentage to every SuperTrend flip. Each time the SuperTrend changes direction, the indicator evaluates the market conditions at the flip across 14 features spanning candle structure, trend context, and technical indicators, then outputs a probability score between 0% and 100% representing how similar the current setup is to past flips that resolved profitably on the same chart.
The model trains itself in real time using past SuperTrend signals as labeled examples. Each historical flip becomes a training example: the features captured at the flip are paired with the outcome at the next opposite flip, producing a continuously growing dataset that the model uses to refine its weights. The probability displayed on each new flip reflects what the model has learned about this specific instrument and timeframe, not a universal assumption about what makes a good signal.
screenshot: Full chart showing SuperTrend line with multiple flips and probability labels
🔹What is the purpose of the indicator?
The indicator addresses a common problem with SuperTrend: not every flip leads to a sustained trend. Many flips occur during choppy or transitional conditions and reverse quickly, producing losing signals. By scoring each flip with a probability, traders get a quantitative sense of how much confidence the model has in that specific signal based on similar past setups. The indicator does not change the SuperTrend calculation itself, so every flip is still detected and visualized. The probability score adds a filtering layer that helps traders separate high-confidence flips from low-confidence ones.
🔹What is the theory behind the indicator?
The indicator is built on the idea that market behavior around trend reversals is not random. Certain combinations of candle structure, volatility conditions, volume patterns, and prior trend context tend to precede trends that follow through, while different combinations tend to precede trends that reverse quickly. Logistic regression is a statistical method well-suited to learning these relationships. Given a set of input features and historical outcomes, it produces a set of weights that map feature combinations to probability estimates.
In this indicator, each SuperTrend flip becomes a data point. The features at the flip are recorded, and the outcome is determined at the next opposite flip. If price moved in the signal's direction (higher for bull, lower for bear), the signal is labeled as a win. Otherwise, it is labeled as a loss. The model continuously retrains on this growing dataset, adjusting weights so that feature patterns historically associated with wins produce higher probabilities, and feature patterns associated with losses produce lower probabilities.
SUPERTREND LOGISTIC REGRESSION FEATURES
SuperTrend Core
Logistic Regression Model
Candle Features
Trend Context Features
Technical Features
Separate Bull and Bear Models
Exponential Decay Weighting
Minimum Sample Gating
Probability Labels and Filtering
Gradient-Colored SuperTrend Visualization
Optional Momentum Dots
Alerts
SUPERTREND CORE
The SuperTrend is the foundation of every signal. All detection, training, and prediction is tied to SuperTrend flips. The core SuperTrend calculation in this indicator is standard: ATR multiplied by a user-defined factor produces the trailing line, and a flip occurs when price crosses through the line, changing the direction state.
🔹How SuperTrend is calculated
The SuperTrend is derived from Average True Range (ATR) with a user-configurable period and factor. When the calculated line is below price, the indicator is in an uptrend state and the line acts as dynamic support. When the line is above price, the indicator is in a downtrend state and the line acts as dynamic resistance. A flip occurs at the exact bar where price crosses through the line, changing the direction from bullish to bearish or vice versa.
🔹Why SuperTrend was chosen
SuperTrend is one of the most widely used trend-following tools on TradingView. It produces clean, deterministic signals with well-understood behavior. Rather than reinventing or modifying the underlying calculation, this indicator treats SuperTrend as a signal source and adds a separate statistical layer on top. This keeps the core behavior familiar to traders already using SuperTrend and ensures that every flip is still detected, regardless of the probability score.
🔹SuperTrend Inputs
Two inputs control the SuperTrend calculation: Factor (the ATR multiplier, default 3.0) and ATR Period (the number of bars in the ATR calculation, default 10). These correspond to the standard SuperTrend parameters. Changing these values affects where flips occur, which in turn affects what signals the model trains on.
LOGISTIC REGRESSION MODEL
Logistic regression is a statistical model that predicts binary outcomes from a set of input features. It takes each feature, multiplies it by a learned weight, sums the results, adds a bias term, and passes the total through a sigmoid function that maps the output to a probability between 0 and 1. The model learns the weights by comparing its predictions against actual outcomes and adjusting through gradient descent.
🔹What is Logistic Regression?
Logistic regression works by finding the set of weights that best separates winning signals from losing signals in feature space. A large positive weight on a feature means that higher values of that feature are associated with winning outcomes. A large negative weight means higher values are associated with losing outcomes. A weight near zero means the feature does not discriminate between winners and losers on this chart.
The sigmoid function is what turns the weighted sum into a probability. It outputs values near 0 when the weighted sum is very negative, values near 1 when the weighted sum is very positive, and values near 0.5 when the weighted sum is near zero. This gives the output a natural probability interpretation.
🔹How the model is trained
Training happens every time a new SuperTrend flip occurs. The indicator looks at all past resolved signals (signals that have already seen their next opposite flip and therefore have a known outcome) and runs gradient descent over them. Gradient descent calculates how much each weight should change to reduce the model's prediction error, then applies those changes iteratively. The indicator runs multiple training epochs on each update to ensure the weights converge reasonably well to the current data.
L2 regularization is applied to prevent any single weight from becoming extreme. Weight clipping further constrains weights to a reasonable range, avoiding instability when training data is thin or features are noisy. Together, these make the model more robust on small sample sizes.
🔹Outcome evaluation
For training to work, every historical signal needs a win/loss label. The indicator uses flip-to-flip evaluation: a bull signal is considered a win if the close at the next bear flip is higher than the close at the bull flip. A bear signal is considered a win if the close at the next bull flip is lower than the close at the bear flip. This matches the natural lifecycle of a SuperTrend trade, where entry and exit are both on flips.
🔹A Winning Signal Example
A winning bull signal forms when a bull flip occurs and, by the time the next bear flip occurs, the close at the bear flip is higher than the close at the bull flip. The probability label on the bull flip reflects the model's confidence at entry, while the outcome is confirmed at the next flip.
🔹A Losing Signal Example
A losing signal forms when price fails to move in the signal's direction by the next opposite flip. For example, a bull flip where price immediately reverses and ends lower than entry when the next bear flip occurs.
CANDLE FEATURES
Candle features describe the shape and volume of the flip candle itself, compared against recent averages. These are the most direct, local features the model uses. All candle features are toggleable in the "Candle Features" input group and are normalized to a range centered at zero, where zero means the feature value matches the recent average.
🔹Body
Body measures the size of the flip candle's body (the absolute distance from open to close) relative to the average body size over the recent lookback window. A value above zero means the flip candle had a larger body than recent candles, suggesting stronger conviction. A value below zero means the body was smaller than usual, suggesting indecision. The model learns whether strong-bodied flips tend to produce winning trends on this chart.
🔹Upper Wick
Upper Wick measures the length of the upper wick (the distance from the body top to the high) relative to recent average upper wicks. Long upper wicks can indicate rejection at highs, while short upper wicks suggest price accepted the top of the candle cleanly. The model learns how upper wick behavior at flips correlates with outcomes.
🔹Lower Wick
Lower Wick measures the length of the lower wick (the distance from the body bottom to the low) relative to recent average lower wicks. Long lower wicks can indicate rejection at lows, while short lower wicks suggest clean acceptance. This feature is disabled by default because it historically showed the weakest predictive signal across tested instruments.
🔹Range
Range measures the total high-to-low range of the flip candle relative to the recent average range. A wide-range flip candle indicates volatility expansion, while a tight-range candle suggests contraction. The model learns whether flips during volatility expansion tend to perform differently from flips during contraction.
🔹Volume
Volume compares the flip candle's volume to the average volume over the recent lookback window. Higher than average volume at a flip generally indicates stronger participation, while lower than average volume suggests weak conviction. The model learns how volume conviction at flips relates to trend outcomes.
🔹Delta Volume
Delta Volume estimates the net buying versus selling pressure within the flip candle by sampling 1-minute lower timeframe bars. The indicator distributes each 1-minute bar's volume to either the bullish or bearish side based on whether that bar closed up or down, then outputs the net direction as a feature value from fully bearish to fully bullish. This gives the model a finer-grained view of what happened inside the flip candle beyond the aggregate close.
TREND CONTEXT FEATURES
Trend context features describe the market conditions leading into the flip, not just the flip candle itself. These are calculated from the lookback window before the flip. All trend context features are toggleable in the "Trend Features" input group.
🔹Momentum
Momentum counts consecutive candle direction leading into the flip. Each bullish candle increments the streak in the positive direction, and each bearish candle increments it in the negative direction. The value is capped so very long streaks do not dominate. A strongly positive momentum value before a bull flip indicates buying was already building; a strongly negative value before a bull flip indicates a sharp reversal from recent selling. The model learns which regime tends to produce better bull outcomes.
🔹Pre-Flip Trend
Pre-Flip Trend averages the signed candle bodies (close minus open) over the recent lookback window, normalized by the average range. This gives a broader picture of whether the market was drifting up, drifting down, or chopping sideways before the flip. Unlike momentum, which only counts direction, pre-flip trend captures the magnitude of the directional bias.
🔹ATR Slope
ATR Slope compares the current ATR value to the ATR value from the lookback period ago. A positive slope means volatility is expanding into the flip, often associated with stronger follow-through. A negative slope means volatility is contracting, often associated with weaker signals. The model learns whether volatility expansion at the flip is a positive or negative factor for the specific instrument.
🔹Volume Trend
Volume Trend compares the average volume of recent bars to the average volume of bars further back. A positive value means participation is increasing; a negative value means it is fading. This feature is disabled by default because it historically showed weak signal across tested instruments.
🔹ST Distance
ST Distance measures how far price was from the SuperTrend line before the flip, normalized by ATR. A value near zero means the flip was a tight cross; a larger absolute value means price was well above or below the line and had to travel significantly to trigger the flip. The model learns whether tight crosses or aggressive breaks produce better outcomes.
🔹Trend Duration
Trend Duration measures how many bars the previous trend lasted before flipping. Short previous trends might indicate choppy conditions where flips come and go quickly. Longer previous trends might signal genuine exhaustion at reversal. The model learns how previous trend length relates to the success of the current flip.
TECHNICAL FEATURES
Technical features bring in classic technical indicator readings at the flip point. These are toggleable in the "Technical Features" input group.
🔹RSI
RSI (Relative Strength Index) is calculated with the same lookback as the other features and then centered around the 50 level. Values near the oversold end push the feature toward -1, values near the overbought end push it toward +1, and values near 50 are near zero. The model learns whether overbought or oversold RSI readings at flips correlate with different outcomes on the specific chart. On some instruments, flips at extreme RSI readings perform well; on others, they perform poorly. The model discovers this from the data.
🔹BB Position
BB Position measures where price sits within Bollinger Bands at the flip. Price at the lower band gives a value of -1, price at the basis gives 0, and price at the upper band gives +1. The Bollinger Bands are calculated with the same lookback as the other features. This feature captures mean-reversion versus breakout context: a flip near the lower band is different from a flip near the upper band, and the model learns which band positions tend to precede successful trends.
SEPARATE BULL AND BEAR MODELS
The indicator maintains completely independent models for bull signals and bear signals. Each has its own set of weights, its own training dataset, and its own prediction logic.
🔹Why separate models?
A single model that assumes features mean opposite things for opposite directions would be an oversimplification. For example, a long lower wick on a bull flip might indicate strong buyer defense, while a long lower wick on a bear flip might indicate weak sellers. These are different setups with different implications, and forcing them into one model with flipped signs would blur the signal.
By training separate bull and bear models, the indicator gives each direction room to learn its own relationships. A feature that strongly predicts bull wins might be irrelevant or even negatively correlated for bear wins, and the separate models can capture this without interference.
🔹Implementation
Each direction has its own array of signals and its own weights array. When a bull flip occurs, the bull signals array is updated and the bull model is retrained. When a bear flip occurs, the bear signals array and bear model are updated separately. The two models never share state, and their predictions are based only on their own training data.
EXPONENTIAL DECAY WEIGHTING
Not all training examples are equally relevant. Recent signals reflect current market conditions, while older signals may reflect regimes that no longer apply. The indicator addresses this with exponential decay weighting during training.
🔹How decay works
Each resolved signal is assigned a weight based on its age. The newest resolved signal gets the highest weight (1.0 after normalization), and older signals get progressively smaller weights based on a decay factor. A decay factor close to 1 means old and new signals are weighted roughly equally. A decay factor close to 0 means recent signals dominate and old signals are effectively ignored.
🔹Why decay is important
Markets change. A feature that strongly predicted wins six months ago might have weak or reversed predictive power now. Without decay weighting, the model would be slow to adapt to new conditions because old data would dilute the influence of recent outcomes. With decay weighting, the model naturally updates its weights to reflect the most recent dynamics while still using historical data to maintain stability.
PROBABILITY LABELS AND FILTERING
When a new flip passes the minimum sample gate, the indicator calculates the probability from the current feature values and the trained weights. This is displayed as a colored triangle label at the flip bar.
🔹Label Appearance
Bull flip labels appear below the bar as upward-pointing green triangles with the probability percentage inside. Bear flip labels appear above the bar as downward-pointing red triangles with the probability percentage inside. The colors are partially transparent so the labels do not obscure price action.
🔹High Probability Example
A high probability label means the model found the current flip's features similar to past flips that resolved as wins. For example, a bull flip with strong pre-flip momentum, expanding volatility, positive delta volume, and price well above the SuperTrend line might receive a probability above 65% if those conditions have historically preceded successful bull trends.
🔹Low Probability Example
A low probability label means the model found the current flip's features similar to past flips that resolved as losses. Low probability signals might share characteristics with flips that occurred during choppy conditions or weak momentum regimes.
🔹Min Probability Filter
A Min Probability input lets users hide labels below a confidence threshold. Setting it to 0 shows every signal. Setting it to 60 only shows labels where the model estimates at least 60% probability of a profitable outcome. This filter only affects visual display and alerts. The SuperTrend line and color change still appear on every flip, and the model still trains on every signal regardless of the filter.
🔹Interpreting the probability
The probability represents the model's estimate that the current flip will resolve profitably by the next opposite flip, based on how similar past flips performed. A 70% label does not guarantee a win; it means the model finds this flip's conditions more similar to past winners than past losers. Probabilities should be interpreted relative to the base rate (the overall percentage of past flips that won) rather than as absolute guarantees.
VISUAL CUSTOMIZATION
The indicator includes several visual elements that help traders see the SuperTrend state and the probability labels clearly.
🔹Gradient-Colored SuperTrend
The SuperTrend line is plotted with a color gradient based on how far current price has moved from the line since the most recent flip. The color intensifies as price extends further in the trend direction, giving a visual indication of how developed the trend is at any point. Fills between the body midpoint and the SuperTrend line reinforce this gradient effect.
🔹Momentum Dots
An optional momentum dots display overlays circles on the SuperTrend line with colors that shift between yellow and the trend color (green or red) based on price position. This provides a secondary visual cue for trend strength. The Enable Momentum Dots input toggles this display on or off.
INPUTS
🔹SuperTrend
Factor: ATR multiplier used in the SuperTrend calculation. Default is 3.0. Increasing this value makes the SuperTrend less sensitive and produces fewer, wider flips. Decreasing it makes the SuperTrend more sensitive and produces more frequent flips.
ATR Period: Number of bars used in the ATR calculation. Default is 10. Larger periods smooth the ATR, while smaller periods make it more reactive.
🔹Display
Enable Momentum Dots: Toggles the momentum dots overlay on the SuperTrend line. Default is on.
🔹Filters
Min Probability %: Minimum probability required for a signal label to appear on the chart. Default is 0 (show all signals). Setting this to a higher value hides lower-confidence signals.
🔹Candle Features
Body: Enable body size feature. Default is on.
Upper Wick: Enable upper wick feature. Default is on.
Lower Wick: Enable lower wick feature. Default is off.
Range: Enable candle range feature. Default is on.
Volume: Enable volume feature. Default is on.
Delta Vol: Enable delta volume feature using 1-minute LTF data. Default is on.
🔹Trend Features
Momentum: Enable consecutive candle direction feature. Default is on.
Pre-Flip Trend: Enable average directional body feature. Default is on.
ATR Slope: Enable volatility expansion feature. Default is on.
Volume Trend: Enable volume building feature. Default is off.
ST Distance: Enable distance from SuperTrend line feature. Default is on.
Trend Duration: Enable previous trend length feature. Default is on.
🔹Technical Features
RSI: Enable RSI feature. Default is on.
BB Position: Enable Bollinger Band position feature. Default is on.
ALERTS
The indicator includes alert conditions for the following events:
Bull Flip: Fires on a confirmed bullish SuperTrend flip that passes the Min Probability filter.
Bear Flip: Fires on a confirmed bearish SuperTrend flip that passes the Min Probability filter.
Users can configure alerts from the TradingView alerts menu and choose which condition to subscribe to.
IMPORTANT NOTES
🔹Non-Repainting Behavior
Signals are detected and probability labels are calculated on the bar where the SuperTrend flip confirms. The probability value is based only on feature values at the time of the flip and the model weights as of that bar. The outcome label used for training is only recorded after the next opposite flip has occurred, so the current bar's prediction never uses future data.
🔹Probability Interpretation
The probability represents the model's learned estimate from past data on the current chart. It is not a guaranteed win rate. Markets can shift in ways the model has not yet seen, and sample size is always a limitation. Probabilities should be used as one input among many in a trading decision, not as a standalone signal.
UNIQUENESS
The SuperTrend Logistic Regression indicator takes a distinct approach to SuperTrend enhancement. Rather than altering the SuperTrend calculation itself, it preserves the classic SuperTrend behavior and adds a statistical layer on top that scores each flip independently. Every flip is still detected, so users never miss signals; the probability only determines what gets visually emphasized. The logistic regression implementation uses proper gradient descent with L2 regularization, weight clipping, and exponential decay weighting, making the training process stable and adaptive. Weights persist across bars and are refined with each new resolved signal rather than being recalculated from scratch. Separate bull and bear models learn direction-specific feature relationships independently, avoiding the oversimplification of assuming features have opposite meanings for opposite directions. All 14 features are toggleable, spanning candle structure, trend context, and technical indicators, so users can customize which market characteristics feed into the model. The probability is backed by a concrete, testable definition: the likelihood that the current flip will resolve profitably by the time the next opposite flip occurs, based on how similar past flips performed. This matches how SuperTrend is naturally traded on flip-to-flip cycles. Minimum sample gating ensures that probability labels only appear once the model has enough training data to make meaningful predictions, preventing misleading early signals. Together, these choices make the indicator a disciplined, data-driven extension of SuperTrend that adapts to each instrument and timeframe it runs on, rather than applying a one-size-fits-all scoring system. אינדיקטור

Support and Resistance Logistic Regression | Flux Charts💎 GENERAL OVERVIEW
Introducing our new Logistic Regression Support / Resistance indicator! This tool leverages advanced statistical modeling "Logistic Regressions" to identify and project key price levels where the market is likely to find support or resistance. For more information about the process, please check the "HOW DOES IT WORK ?" section.
Logistic Regression Support / Resistance Features :
Intelligent S/R Identification : The indicator uses a logistic regression model to intelligently identify and plot significant support and resistance levels.
Predictive Probability : Each identified level comes with a calculated probability, indicating how likely it is to act as a true support or resistance based on historical data.
Retest & Break Labels : The indicator clearly marks on your chart when a detected support or resistance level is retested (price touches and respects the level) or broken (price decisively crosses through the level).
Alerts : Real-time alerts for support retests, resistance retests, support breaks, and resistance breaks.
Customizable : You can change support & resistance line style, width and colors.
🚩 UNIQUENESS
What makes this indicator truly unique is its application of logistic regression to the concept of support and resistance. Instead of merely identifying historical highs and lows, our indicator uses a statistical model to predict the future efficacy of these levels. It analyzes underlying market conditions (like RSI and body size at pivot formation) to assign a probability to each potential S/R zone. This predictive insight, combined with dynamic, real-time labeling of retests and breaks, provides a more robust and adaptive understanding of market structure than traditional, purely historical methods.
📌HOW DOES IT WORK ?
The Logistic Regression Support / Resistance indicator operates in several key steps:
First, it identifies significant pivot highs and lows on the chart based on a user-defined "Pivot Length." These pivots are potential areas of support or resistance.
For each detected pivot, the indicator extracts relevant market data at that specific point, including the RSI (Relative Strength Index) and the Body Size (the absolute difference between the open and close price of the candle). These serve as input features for the model.
The core of the indicator lies in its logistic regression model. This model is continuously trained on past pivot data and their subsequent behavior (i.e., whether they were "respected" as support/resistance multiple times). It learns the relationship between the extracted features (RSI, Body Size) and the likelihood of a pivot becoming a significant S/R level.
When a new pivot is identified, the model uses its learned insights to calculate a prediction value—a probability (from 0 to 1) that this specific pivot will act as a strong support or resistance.
If the calculated probability exceeds a user-defined "Probability Threshold," the pivot is designated a "Regression Pivot" and drawn on the chart as a support or resistance line. The indicator then actively tracks how price interacts with these levels, displaying "R" labels for retests when the price bounces off the level and "B" labels for breaks when the price closes beyond it.
⚙️ SETTINGS
1. General Configuration
Pivot Length: This setting defines the number of bars used to determine a significant high or low for pivot detection.
Target Respects: This input specifies how many times a level must be "respected" by price action for it to be considered a strong support or resistance level by the underlying model.
Probability Threshold: This is the minimum probability output from the logistic regression model for a detected pivot to be considered a valid support or resistance level and be plotted on the chart.
2. Style
Show Prediction Labels: Enable or disable labels that display the calculated probability of a newly identified regression S/R level.
Show Retests: Toggle the visibility of "R" labels on the chart, which mark instances where price has retested a support or resistance level.
Show Breaks: Toggle the visibility of "B" labels on the chart, which mark instances where price has broken through a support or resistance level. אינדיקטור

Neural Pulse System [Alpha Extract]Neural Pulse System (NPS)
The Neural Pulse System (NPS) is a custom technical indicator that analyzes price action through a probabilistic lens, offering a dynamic view of bullish and bearish tendencies.
Unlike traditional binary classification models, NPS employs Ordinary Least Squares (OLS) regression with dynamically computed coefficients to produce a smooth probability output ranging from -1 to 1.
Paired with ATR-based bands, this indicator provides an intuitive and volatility-aware approach to trend analysis.
🔶 CALCULATION
The Neural Pulse System utilizes OLS regression to compute probabilities of bullish or bearish price action while incorporating ATR-based bands for volatility context:
Dynamic Coefficients: Coefficients are recalculated in real-time and scaled up to ensure the regression adapts to evolving market conditions.
Ordinary Least Squares (OLS): Uses OLS regression instead of gradient descent for more precise and efficient coefficient estimation.
ATR Bands: Smoothed Average True Range (ATR) bands serve as dynamic boundaries, framing the regression within market volatility.
Probability Output: Instead of a binary result, the output is a continuous probability curve (-1 to 1), helping traders gauge the strength of bullish or bearish momentum.
Formula:
OLS Regression = Line of best fit minimizing squared errors
Probability Signal = Transformed regression output scaled to -1 (bearish) to 1 (bullish)
ATR Bands = Smoothed Average True Range (ATR) to frame price movements within market volatility
🔶 DETAILS
📊 Visual Features:
Probability Curve: Smooth probability signal ranging from -1 (bearish) to 1 (bullish)
ATR Bands: Price action is constrained within volatility bands, preventing extreme deviations
Color-Coded Signals:
Blue to Green: Increasing probability of bullish momentum
Orange to Red: Increasing probability of bearish momentum
Interpretation:
Bullish Bias: Probability output consistently above 0 suggests a bullish trend.
Bearish Bias: Probability output consistently below 0 indicates bearish pressure.
Reversals: Extreme values near -1 or 1, followed by a move toward 0, may signal potential trend reversals.
🔶 EXAMPLES
📌 Trend Identification: Use the probability output to gauge trend direction.
📌Example: On a 1-hour chart, NPS moves from -0.5 to 0.8 as price breaks resistance, signaling a bullish trend.
Reversal Signals: Watch for probability extremes near -1 or 1 followed by a reversal toward 0.
Example: NPS hits 0.9, price touches the upper ATR band, then both retreat—indicating a potential pullback.
📌 Example snapshots:
Volatility Context: ATR bands help assess whether price action aligns with typical market conditions.
Example: During low volatility, the probability signal hovers near 0, and ATR bands tighten, suggesting a potential breakout.
🔶 SETTINGS
Customization Options:
ATR Period – Defines lookback length for ATR calculation (shorter = more responsive, longer = smoother).
ATR Multiplier – Adjusts band width for better volatility capture.
Regression Length – Controls how many bars feed into the coefficient calculation (longer = smoother, shorter = more reactive).
Scaling Factor – Adjusts the strength of regression coefficients.
Output Smoothing – Option to apply a moving average for a cleaner probability curve
אינדיקטור

Machine Learning: Multiple Logistic Regression
Multiple Logistic Regression Indicator
The Logistic Regression Indicator for TradingView is a versatile tool that employs multiple logistic regression based on various technical indicators to generate potential buy and sell signals. By utilizing key indicators such as RSI, CCI, DMI, Aroon, EMA, and SuperTrend, the indicator aims to provide a systematic approach to decision-making in financial markets.
How It Works:
Technical Indicators:
The script uses multiple technical indicators such as RSI, CCI, DMI, Aroon, EMA, and SuperTrend as input variables for the logistic regression model.
These indicators are normalized to create categorical variables, providing a consistent scale for the model.
Logistic Regression:
The logistic regression function is applied to the normalized input variables (x1 to x6) with user-defined coefficients (b0 to b6).
The logistic regression model predicts the probability of a binary outcome, with values closer to 1 indicating a bullish signal and values closer to 0 indicating a bearish signal.
Loss Function (Cross-Entropy Loss):
The cross-entropy loss function is calculated to quantify the difference between the predicted probability and the actual outcome.
The goal is to minimize this loss, which essentially measures the model's accuracy.
// Error Function (cross-entropy loss)
loss(y, p) =>
-y * math.log(p) - (1 - y) * math.log(1 - p)
// y - depended variable
// p - multiple logistic regression
Gradient Descent:
Gradient descent is an optimization algorithm used to minimize the loss function by adjusting the weights of the logistic regression model.
The script iteratively updates the weights (b1 to b6) based on the negative gradient of the loss function with respect to each weight.
// Adjusting model weights using gradient descent
b1 -= lr * (p + loss) * x1
b2 -= lr * (p + loss) * x2
b3 -= lr * (p + loss) * x3
b4 -= lr * (p + loss) * x4
b5 -= lr * (p + loss) * x5
b6 -= lr * (p + loss) * x6
// lr - learning rate or step of learning
// p - multiple logistic regression
// x_n - variables
Learning Rate:
The learning rate (lr) determines the step size in the weight adjustment process. It prevents the algorithm from overshooting the minimum of the loss function.
Users can set the learning rate to control the speed and stability of the optimization process.
Visualization:
The script visualizes the output of the logistic regression model by coloring the SMA.
Arrows are plotted at crossover and crossunder points, indicating potential buy and sell signals.
Lables are showing logistic regression values from 1 to 0 above and below bars
Table Display:
A table is displayed on the chart, providing real-time information about the input variables, their values, and the learned coefficients.
This allows traders to monitor the model's interpretation of the technical indicators and observe how the coefficients change over time.
How to Use:
Parameter Adjustment:
Users can adjust the length of technical indicators (rsi_length, cci_length, etc.) and the Z score length based on their preference and market characteristics.
Set the initial values for the regression coefficients (b0 to b6) and the learning rate (lr) according to your trading strategy.
Signal Interpretation:
Buy signals are indicated by an upward arrow (▲), and sell signals are indicated by a downward arrow (▼).
The color-coded SMA provides a visual representation of the logistic regression output by color.
Table Information:
Monitor the table for real-time information on the input variables, their values, and the learned coefficients.
Keep an eye on the learning rate to ensure a balance between model adjustment speed and stability.
Backtesting and Validation:
Before using the script in live trading, conduct thorough backtesting to evaluate its performance under different market conditions.
Validate the model against historical data to ensure its reliability.
אינדיקטור

Machine Learning: Logistic RegressionMulti-timeframe Strategy based on Logistic Regression algorithm
Description:
This strategy uses a classic machine learning algorithm that came from statistics - Logistic Regression (LR).
The first and most important thing about logistic regression is that it is not a 'Regression' but a 'Classification' algorithm. The name itself is somewhat misleading. Regression gives a continuous numeric output but most of the time we need the output in classes (i.e. categorical, discrete). For example, we want to classify emails into “spam” or 'not spam', classify treatment into “success” or 'failure', classify statement into “right” or 'wrong', classify election data into 'fraudulent vote' or 'non-fraudulent vote', classify market move into 'long' or 'short' and so on. These are the examples of logistic regression having a binary output (also called dichotomous).
You can also think of logistic regression as a special case of linear regression when the outcome variable is categorical, where we are using log of odds as dependent variable. In simple words, it predicts the probability of occurrence of an event by fitting data to a logit function.
Basically, the theory behind Logistic Regression is very similar to the one from Linear Regression, where we seek to draw a best-fitting line over data points, but in Logistic Regression, we don’t directly fit a straight line to our data like in linear regression. Instead, we fit a S shaped curve, called Sigmoid, to our observations, that best SEPARATES data points. Technically speaking, the main goal of building the model is to find the parameters (weights) using gradient descent.
In this script the LR algorithm is retrained on each new bar trying to classify it into one of the two categories. This is done via the logistic_regression function by updating the weights w in the loop that continues for iterations number of times. In the end the weights are passed through the sigmoid function, yielding a prediction.
Mind that some assets require to modify the script's input parameters. For instance, when used with BTCUSD and USDJPY, the 'Normalization Lookback' parameter should be set down to 4 (2,...,5..), and optionally the 'Use Price Data for Signal Generation?' parameter should be checked. The defaults were tested with EURUSD.
Note: TradingViews's playback feature helps to see this strategy in action.
Warning: Signals ARE repainting.
Style tags: Trend Following, Trend Analysis
Asset class: Equities, Futures, ETFs, Currencies and Commodities
Dataset: FX Minutes/Hours/Days אינדיקטור

אינדיקטור
