Structural Language ModelOverview
Structural Language Model treats price action as a language. Each bar is tokenised into one of five structural symbols, and a low-order Markov model learns the grammar — the probability of what comes next given the recent context. Instead of "match the nearest historical shape" (fragile, overfit-prone k-NN), it estimates P(next token | last k tokens): a nonparametric conditional-move model that proves or disproves itself, live, on your symbol. It is a research/forecast read, not a signal service.
The five-symbol grammar
Every bar becomes one token, built from robust intrabar primitives (gap-immune, no fragile sweep/FVG detection), with adaptive thresholds so the alphabet stays balanced across symbols and timeframes:
X− down impulse · d ordinary down · c compression / indecision · u ordinary up · X+ up impulse
The model then learns grammar like c → X+ (breakout), X+ → X− (reversal), runs of u/X+ (trend), X+ → c (exhaustion), using order-1 or order-2 transition counts with Laplace smoothing, updated online.
Why these parts are one tool
The tokeniser turns raw OHLC into a balanced, information-rich alphabet — without it the Markov counts are dominated by whatever token is most common.
The Markov model reads out, each bar, a directional bias (P up-ish − P down-ish), a predictability score (how peaked the next-token distribution is, via normalized entropy), a structural-surprise spike (−log P of the token that just printed — a grammar break), and the full next-bar probability ladder.
The harness is the part that makes it honest. It's prequential (predict-then-update: each transition is scored from counts that exclude its own outcome, so every score is out-of-sample), it runs a walk-forward in-sample vs out-of-sample split with Wilson 95% intervals, and it draws a reliability curve — binning OOS predictions by predicted P(up) and showing the realized up-rate per bin. A rising, significant curve = real calibrated information; a flat one = none. Remove any part and you can no longer answer "is this model actually calibrated on this market?"
How to use it
Read the directional bias line against its conviction bands as context, not a trigger, and check predictability for how peaked the forecast is. Then read the harness — the model is only worth trusting where the out-of-sample up-lean lift is above 1 and/or the reliability spread is positive and significant (✓sig). A flat or insignificant curve means there's no calibrated edge here; treat it as descriptive only, or try another symbol/timeframe. The dashboard has a Compact layout (default: forecast + the one calibration line that matters) and a Pro layout (the full ladder, in/out-of-sample lift, and the three-bin reliability curve). Bias-turn crosses are optionally mirrored on the price chart. It is never a standalone signal.
Non-repainting
Tokens and counts update only on confirmed bars, and the score for bar t uses counts as they stood before bar t's transition was added — nothing reads its own future. The live next-bar forecast naturally refines as the current bar forms (it's a forecast, not a settled statistic). All harness figures are out-of-sample by construction.
Honest limits
OHLCV only. A per-bar tokeniser maximises samples but is coarser than a swing/event grammar (a documented future extension). Any edge is typically modest and market/timeframe-dependent — directional forecasting on noisy price is hard, and no indicator has an inherent edge. That's exactly why the harness is built in: validate it before trusting it.
Outputs for other scripts
Generic EXP_* plots — bias, predictability, structural surprise, live P(next up-ish), and the OOS lift — are published to the Data Window for use from other scripts via input.source().
Concept credits
Markov chains / n-gram language models — A. Markov (1913); C. Shannon (1948)
Prequential (predict-then-update) evaluation — A. P. Dawid (1984)
Additive (Laplace) smoothing — P.-S. Laplace
Entropy — C. Shannon (1948)
Wilson score interval — E. B. Wilson (1927)
Synthesis and Pine implementation are the author's own; no third-party Pine code reused.
Disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. Validate with your own testing, apply realistic costs, and manage risk. Indicador

Event Probability Engine [Quantum Algo]Event Probability Engine
====================================================
🔶 OVERVIEW
Event Probability Engine is a statistical probability indicator that answers one question at the close of every bar: based on the measurable conditions active right now, what is the historical probability that price closes higher one, three, and five days from today? Instead of subjective pattern reading, the script builds and maintains a live rolling database of forward returns conditioned on eighteen observable market events — day-of-week seasonality, oversold and overbought readings, volume spikes, streaks, range position, volatility regime, pivot touches, and an optional lunar control — then pools the currently active events into a single composite probability, displayed as a TODAY headline, a full per-event statistics table, and a shaded forecast cone projected on the chart.
It is designed for the daily timeframe. On other timeframes, the one, three, and five day horizons become one, three, and five bars.
🔶 WHAT IS AN EVENT STUDY?
An event study measures what a market historically did after a defined, observable condition occurred — for example, what happened over the next five days every time the Relative Strength Index closed oversold, or every Monday, or every time volume spiked two standard deviations above normal. This indicator runs eighteen such studies continuously, in real time, on the chart's own data, and keeps every study honest with the statistical safeguards described below.
🔶 WHY THIS SCRIPT IS ORIGINAL
1. A live event database in Pine. Each of the eighteen events maintains its own rolling, capped sample of forward returns at three horizons, tagged with the market regime at the moment the event fired — a self-updating event-study framework, not a fixed backtest.
2. Shrinkage estimation. Every win rate is pulled toward fifty percent by a configurable number of pseudo-samples. An event with fifteen samples cannot display an extreme probability, because fifteen samples cannot justify one.
3. Overlap correction. State-based events (for example, an oversold reading persisting for a week) generate autocorrelated, overlapping samples that inflate apparent sample size. The effective sample size is deflated by the horizon length before any confidence calculation.
4. Wilson score bounds. Next to each five-day win rate, the table shows the Wilson confidence lower bound computed on the corrected sample size — the number an event must clear before its edge deserves trust, not its raw point estimate.
5. Regime conditioning with fallback. When enough samples exist in the current regime (bull or bear, defined by the two-hundred period exponential moving average), statistics are computed on regime-matched samples only, marked ® in the table. A bear-market Thursday is not assumed to behave like a bull-market Thursday.
6. Quality-weighted log-odds pooling. Active events are combined by weighted log-odds — a method related to Bayesian evidence combination — rather than naive win-rate averaging, so one strong, well-sampled edge is not diluted by three weak ones.
7. A built-in falsification control. Lunar phase events are included deliberately so the engine can audit a popular claim empirically: if full and new moons carry no edge, their quality scores sit near zero and they contribute nothing to the composite. A probability framework should be able to demonstrate which inputs fail, not only which appear to work.
🔶 HOW IT WORKS
Event detection: On every bar close the script evaluates all eighteen conditions — Monday through Friday, adaptive or fixed oversold and overbought thresholds, volume z-score spikes, up and down streaks, range-low and range-high position, volatility expansion and compression by percentile rank, confirmed pivot support and resistance touches within an Average True Range distance, and the optional lunar events.
Database recording: Whenever an event was active one, three, or five bars ago, the realized forward return is stored in that event's arrays, first-in-first-out at a configurable cap, together with the regime tag from the moment the event fired.
Per-event statistics: The table reports, for every event, the shrinkage-adjusted win rate at each horizon, the Wilson lower bound, sample count, average forward return, profit factor, a zero-to-one-hundred quality score blending edge magnitude, sample sufficiency, and recent consistency, and the resulting directional bias.
Composite probability: Active events passing the minimum-sample filter are pooled by quality-weighted log-odds into the TODAY headline (next-day probability of an up close with a visual meter), the one, three, and five day composite row with expected returns and a strength grade, and a projected forecast path with a shaded plus-and-minus one standard deviation cone drawn from the current close.
Chart layer: Optional regime background tint, the regime line, live pivot support and resistance rails with prices, and historical event markers on the candles so past occurrences of every event can be reviewed directly on the chart.
🔶 HOW TO USE IT
1. Apply it to a daily chart of any liquid symbol — cryptocurrency, stocks, indices, forex, gold, futures. Let it load its history; sample counts grow with available bars.
2. Read the TODAY headline first: the next-day probability, the meter, and the expected one-day return.
3. Scan the table for the highlighted rows — those events are active right now. Judge each by its Wilson lower bound and quality score, not the raw win rate.
4. Use the composite row and forecast cone as context: STRONG requires both a meaningful probability distance from fifty percent and high average quality.
5. Treat readings near fifty percent as exactly what they are: weak evidence. This engine is intentionally built to display small honest numbers rather than large misleading ones.
6. Combine with your own analysis — the engine measures conditional history; it does not know tomorrow's news.
🔶 SETTINGS
- Database: sample cap per event, minimum samples for composite inclusion, minimum regime-matched samples, shrinkage strength.
- Events: oscillator length and thresholds (fixed or adaptive percentile), volume z-score, streak length, range lookback, pivot lookback and touch distance, lunar events on or off.
- Statistics: Wilson z-score (default 1.645, a ninety percent one-sided bound).
- Display: dashboard position and five text sizes, forecast cone, regime tint, regime line, pivot rails, candle markers.
🔶 ALERTS
- Composite Bias Change — fires once per bar close whenever the five-day composite bias flips state, with the current one-day and five-day probabilities in the message.
🔶 FREQUENTLY ASKED QUESTIONS
Does the indicator repaint? Statistics are recorded and evaluated on closed bars, and pivot events use confirmed pivots with their standard confirmation lag. The dashboard and forecast update on the live bar by design, as a dashboard should.
Why do most probabilities sit near fifty percent? Because genuine conditional edges in daily data are small, and the shrinkage and overlap corrections are built to say so. Extreme displayed probabilities on thin samples are the signature of a dishonest tool.
What does the ® mark mean? That event currently has enough regime-matched samples, so its statistics are computed only from the current bull or bear regime rather than the full history.
Why are moon phases in a statistics tool? As a falsification control. The engine should be able to show which inputs carry no edge — and the user can watch it do exactly that.
Can I use it intraday? Yes, but the horizons become bars instead of days, and day-of-week events lose their meaning. The design intent is the daily timeframe.
🔶 CREDITS
This script stands on standard, publicly documented statistical methods, gratefully credited: the Wilson score interval by Edwin B. Wilson (1927), Laplace-style shrinkage estimation, and the event-study methodology long established in quantitative finance. Their combination into a live, regime-conditional, overlap-corrected event database with quality-weighted log-odds composite pooling, implemented entirely in Pine Script with capped arrays and user-defined types, is original work — no third-party or open-source script code was reused.
🔶 LIMITATIONS
Probabilities derived from historical conditioning are estimates, not guarantees, and conditional edges in daily data are typically small. Sample databases need history to mature; young charts produce thin, heavily shrunk statistics by design. Day-of-week events assume a five-day session calendar. Regime conditioning depends on the two-hundred period regime definition. This is a research and confluence tool, not a standalone trading system.
🔶 DISCLAIMER
This script is provided strictly for educational and informational purposes. It is not financial advice, an investment recommendation, or a solicitation to buy or sell any financial instrument. Past statistical behavior does not assure future results. Trading involves substantial risk. Always do your own research and manage risk independently. Indicador

Naked POC Magnetism Fill Probability & Median WaitNaked POC Magnetism — Fill Probability & Median Wait
What it is
A naked POC is the highest-volume price of a past session that price has not revisited since. Traders treat them as magnets — but "it usually gets filled" is folklore until it's measured. This tool measures it. Every historical naked level on your chart becomes a data point (how many sessions it survived before being touched, or whether it never was), and a survival model (discrete-hazard life table) turns that history into, for each live naked level: the probability it fills within the next N sessions and the median wait. Levels are drawn with their measured magnetism, not just their location.
How the statistics work — and their honest limits
Each session's volume-at-price profile is built from that session's bars; at session close the peak-volume price (POC) becomes a naked level.
A level is filled the first time a later bar's range touches it; its age in sessions at that moment is one observation. Levels removed unfilled (history cap) are censored at their age — counted as "survived this long," never as fills. This is the standard treatment of incomplete observations from survival analysis (Kaplan–Meier 1958; classical life tables).
Hazard at age j = fills at age j ÷ levels at risk at age j. Survival multiplies (1 − hazard) across ages; fill-probability within a horizon and the median wait follow directly.
Reliability gates, enforced not footnoted: no probability is displayed until a minimum number of levels have resolved (input, default 20) — until then the tool says BUILDING and shows only counts. And hazard estimates at ages with fewer than 5 at-risk observations are truncated rather than trusted, per standard life-table convention.
Probabilities are empirical frequencies from this symbol and timeframe's own history — they change with regime and sample, and a 70% is not a promise.
Seeing the evidence
Every historical fill prints a small ◈ marker where a naked level was touched — the resolved observations the probabilities are measured from, visible on the chart rather than hidden in a table.
The dashboard shows both the NEAREST level and the STRONGEST magnet (highest fill probability) — they are often not the same level, and the strongest one is the better answer to "where is price most drawn".
An honest design note: this tool deliberately has NO multi-timeframe stack and NO state-debounce, unlike its siblings in this suite — sessions are the model's clock regardless of chart timeframe (a higher-timeframe copy would measure the same sessions with coarser bins), and nothing here chatters (levels are born at session close and resolve on touch). Features are added where they inform, not everywhere.
How to use it
Add to a liquid intraday chart; 5m–15m gives the model the most sessions to learn from. Let it run until the dashboard reads MEASURED.
Each rail is labelled like "NPOC 24512 · 68% /5s · med 3s" — the measured chance it fills within the horizon and the median sessions historically needed. Warm, saturated rails = strong magnets; faded = weak or unrated.
The dashboard shows the nearest level's read and — deliberately — the sample size behind every number.
Use magnetism as context about where price is drawn (targets, fade zones, expectations management), never as an entry signal by itself.
What makes it original
Naked-POC indicators draw lines. This one attaches a measured fill-probability and expected wait to each line, estimated with a proper survival model that handles censoring and refuses to show numbers it can't support. Turning a folklore level into a level with a live, honest statistic is the contribution.
Concept credits
Market Profile / point of control — J. Peter Steidlmayer. Naked (virgin) POC — market-profile trading literature. Survival estimation from incomplete observations — E. L. Kaplan & P. Meier (1958); classical life-table method. Implementation and charting design are the author's own.
Important disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. Fill probabilities are empirical frequencies measured on this chart's limited history. Validate independently and manage your own risk. Indicador

Smart Ichimoku | GainzAlgoOverview
Most Ichimoku indicators give you the same signal everyone else gets, a raw cloud cross with no filter, no context, and no target. This indicator rethinks the system from the ground up by combining a smoothed Ichimoku cloud with an inline logistic regression classifier that scores every cloud break in real time, then projects statistically-derived price targets the moment a confirmed signal fires.
The result is a cleaner, higher conviction version of one of the most respected trend frameworks in technical analysis.
The Foundation: Why Smooth the Ichimoku?
Traditional Ichimoku uses simple high-low midpoints (Donchian midlines) for its Tenkan, Kijun, and Senkou components. This makes the cloud visually choppy and prone to false crosses on noisy, volatile instruments like crypto or high-beta equities.
This indicator replaces all three components with Hull Moving Averages (HMA), which are designed to be simultaneously smooth and responsive, reducing lag without the whipsaw of standard smoothing. The cloud body itself becomes cleaner, the baseline is less noisy, and the cross events that trigger signals are more structurally meaningful.
All default periods match classic Ichimoku settings (9 / 26 / 52 / 26 displacement) so the logic stays true to the original system, it's just rendered with better math underneath.
The Signal: Logistic Regression Cloud Break Classifier
Here's where this indicator separates itself. A cloud cross alone is not a signal, it's a candidate. What actually matters is whether the market conditions at the moment of the cross are consistent with a real, sustained breakout or breakdown.
The classifier answers that question with a probability score.
How it works
At the exact bar where price exits the cloud body, four normalized features are computed and fed into a logistic regression model:
1. RSI (centered at 50, scaled by 25)
Measures momentum. On a bearish break, is RSI already extended to the downside? On a bullish break, is it pointing up? RSI near 50 adds little conviction; RSI at 30 on a bear break adds a lot.
2. Stochastic Oscillator (centered at 50, scaled by 25)
Short-term overbought/oversold confirmation. Works similarly to RSI but captures faster-cycle momentum, giving the model a second read on the same question.
3. Z-Score (price vs 20-bar mean, normalized by standard deviation)
Measures how statistically extended price is relative to recent history. A cloud break accompanied by a Z-Score of -2 is much more meaningful than one at Z = -0.2. This feature effectively asks: "Is this break happening from an already-stretched position?"
4. Cloud Break Depth (normalized by ATR)
How far did price close through the cloud boundary, relative to recent volatility? A close that barely clips the edge is very different from one that punches through by a full ATR. This is the most direct measure of breakout conviction.
The Math
Each feature is multiplied by a weight and summed into a single score (z). That score is passed through the sigmoid function:
P = 1 / (1 + e^(-z))
This compresses the output to a probability between 0 and 1. If the probability clears the threshold (default 0.60), the break is confirmed and a signal fires. Below threshold, the cross is rejected — instead of being ignored, it's labeled with a risk tier so you can see exactly how close (or far) it came to confirming.
The probability score is displayed as a small percentage label directly on the signal bar so you always know how strong the classifier rated that particular break.
Self-Calibrating Weights — No Manual Tuning
Unlike a typical multi-feature model, none of the four weights are set by hand. Each one is derived automatically from that feature's own rolling correlation with next-bar returns, recalculated continuously over a user-set lookback window (the "Self-Calibration Window," default 100 bars).
In practice this means: if RSI has been a genuinely useful predictor of direction on this instrument and timeframe recently, its weight rises on its own. If Z-Score has been mostly noise in the current regime, its weight shrinks toward zero — automatically, without anyone touching a slider.
This was a deliberate design choice. Letting people hand-tune regression weights invites a lot of well-intentioned guesswork that usually overfits to a handful of recent candles. By having the model score its own features based on demonstrated, rolling predictive power, the classifier adapts to changing market conditions instead of running on opinions baked in at setup time.
Rejected Crosses: Risk-Tiered Labels
Not every cloud cross clears the threshold, and that's the point. Rather than silently discarding rejected crosses, this indicator labels every one of them with a risk tier so you know exactly what the model saw and how close it came to confirming:
Low Risk: Probability fell just short of the threshold (within 10 points below). A near-miss — the break had real conviction behind it, it simply didn't clear the bar.
Moderate Risk: Probability landed meaningfully below threshold (10–25 points). A weaker break with mixed signals underneath it.
High Risk: Probability came in far below threshold (25+ points). A break with little to no underlying conviction — most consistent with chop or noise.
Each label shows its tier and the actual probability (e.g. "Low Risk ▼ 54%"), so nothing is a black box. A cluster of Low/Moderate Risk labels in one zone often signals a contested area that's likely to resolve into a real breakout once it's worked through — useful context even though no trade signal fired. These labels can be toggled off entirely in settings if you'd rather only see confirmed signals.
The Targets: Mean, Median, Mode
Once a confirmed break fires, three dashed horizontal target lines project from the signal bar. These are not arbitrary multiples, they are derived from the actual statistical distribution of bar-to-bar price moves over the lookback window.
Mean (Yellow): The average absolute bar move over the lookback period, scaled by the target multiplier. This is the "expected" target under normal conditions.
Median (Cyan): The 50th percentile of historical moves. Because move distributions are right-skewed (a few large moves pull the mean up), the median is typically more conservative than the mean and often a more realistic first target.
Mode (Hot Pink): The most frequently occurring move size, derived by bucketing historical moves into ATR-width bins and finding the most populated bin. This represents what the market most commonly does — not what it averages, not the middle value, but the single most likely outcome based on observed frequency.
Together, the three targets give you a realistic range rather than a single arbitrary level — grounded in what this instrument has actually done over the recent past. Bull and bear target sets are tracked independently, so a new bearish break won't erase an active bullish target set still in play, and vice versa.
The Target Multiplier (default 3×) scales all three targets proportionally. Lower it for tighter, shorter-term targets; raise it for swing trades or higher-volatility instruments.
Reading the Chart
Green triangle (▲) below bar: Confirmed bullish cloud break. Price has exited the top of the cloud with sufficient classifier probability. Three upward target lines appear.
Pink triangle (▼) above bar: Confirmed bearish cloud break. Price has exited the bottom of the cloud with sufficient classifier probability. Three downward target lines appear.
Percentage label: The LR probability score for that break (e.g. "73%"). Higher is stronger.
Risk-tiered label (amber/orange/red): A cloud cross that was rejected, with its tier and probability shown.
Yellow dashed line: Mean target
Cyan dashed line: Median target
Hot pink dashed line: Mode target (thicker, as it represents the highest-frequency outcome)
Settings Guide
Smooth Ichimoku
Tenkan / Kijun / Senkou Period: Standard Ichimoku periods. Default 9/26/52 follows the classic system. Shorter periods = more sensitive, more signals. Longer = slower, fewer but stronger signals.
Displacement: How far forward the cloud is projected. Default 26.
Break Classifier
Self-Calibration Window: How many past bars the model uses to learn each feature's weight from its recent correlation with price moves. Shorter windows adapt faster to regime changes but can be noisier; longer windows are more stable but slower to react. Default 100.
Break Probability Threshold: The minimum probability required to confirm a signal. Default 0.60. Raise toward 0.75+ for fewer, higher-conviction signals. Lower toward 0.50 to see more cloud breaks confirmed (effectively turns the filter off at 0.50).
Targets
Lookback (bars): How many bars of historical move data to use for the distribution calculation. Default 60. Longer lookback = more stable targets based on longer-term behavior. Shorter = more reactive to recent volatility.
Target Multiplier: Scales all three target lines proportionally from the signal close. Default 3×. Adjust based on your timeframe and typical holding period.
Risk Labels
Show Risk Labels on Rejected Crosses: Toggles the Low/Moderate/High Risk labels on rejected cloud crosses. Off by default for a cleaner chart; turn on to see every cross the model evaluated, not just the confirmed ones.
How to Use It
As a trend confirmation tool: Use the cloud direction (cyan dominant = bullish structure, pink dominant = bearish) as your bias filter, and only trade signals that align with the cloud color. Bull signals below a cyan cloud, bear signals above a pink cloud.
As a breakout entry trigger: Wait for price to consolidate inside or near the cloud, then take the confirmed break as an entry signal. The probability label tells you how much conviction the model has at that moment.
Using rejected crosses as context: A string of Low Risk labels in a zone suggests the cloud is being tested seriously without quite breaking — often a precursor to a real move once the level finally gives.
For target setting: Use the median as a conservative first target, the mean as a mid-range objective, and the mode as a guide to where the most "normal" move tends to land. The hot pink mode line is often the most useful for setting realistic profit expectations.
For alerts — Four alert conditions are built in: "Confirmed Bull Break," "Confirmed Bear Break," "Rejected Bull Cross," and "Rejected Bear Cross." Set them on your preferred timeframe and let the classifier notify you rather than watching the chart.
Timeframe Notes
This indicator works across all timeframes but behaves differently depending on context:
1H–4H: Good balance of signal frequency and reliability. Recommended starting point.
Daily: Fewer signals, higher structural significance. Best for swing traders.
15m and below: More signals, more noise. Consider raising the threshold to 0.65–0.70 and reducing the lookback to 30. Watch the risk-tiered labels here in particular — they're most useful for filtering chop on fast timeframes.
Example on the Daily with SPY ETF:
Example on the 4 Hour with BTCUSD;
Example on the 15 Minute with QQQ:
A Note on the Model
The logistic regression here is not trained on historical data in the machine learning sense, and it no longer relies on manually-set weights either. Each feature's weight is derived from its own rolling correlation with subsequent price action, recalculated continuously. Think of it less as a black-box ML model and more as a structured, self-adjusting way to combine four momentum and positioning indicators into a single probability score, similar to our Directional Logistic Oscillator.
The advantage over a traditional multi-condition filter (RSI < 40 AND stoch < 30 AND...) is that the sigmoid function produces a continuous probability rather than a binary pass/fail, which means the model degrades gracefully, a break with three strong features and one neutral one still scores well, rather than getting blocked by an arbitrary threshold on the weak feature. And because every rejected cross is shown with its tier and score rather than discarded silently, nothing the model does is hidden from you.
We hope you enjoy! Indicador

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. Indicador

Options Probabilistic Bounds [InferredSignals]█ OVERVIEW
Options Probabilistic Bounds (OPB) draws a forward price corridor on the daily chart — an upper and a lower band projected over a horizon you choose (1 to 20 trading days) at a confidence level you choose (default 95%).
In plain words: given how this stock has actually been moving, where could the CLOSING price realistically land over the next few days? The corridor is calibrated so that, at each horizon, roughly your chosen percentage of closes finish inside it.
It is built for option sellers — short puts in particular. The lower band is a statistically calibrated reference for where to place a strike. And because the corridor takes no view on direction, OPB adds something most volatility tools don't: a drift readout that tells you which side currently has the wind at its back, so you can see whether puts or calls are the safer leg to sell right now.
No option-chain data is used anywhere — no implied volatility, no greeks, no implied-vol skew. "Options" describes who the tool is for, not what it reads. OPB is a pure statistical model of the underlying's own price history.
█ WHAT MAKES IT ORIGINAL
• Per-symbol MAP-style calibration, entirely in Pine.
Parameters are fitted to each ticker by minimizing a penalized negative log-posterior — Student-t likelihood, Bayesian-style priors, and residual-moment penalties combined in one objective — searched multi-start and coarse-to-fine, with the winner chosen on residual quality, not likelihood alone. The result: less in-sample curve-fitting and a steadier calibration than a plain best-fit vol model.
• Two-component, leverage-aware GJR-GARCH variance.
A slow long-run level plus a faster mean-reverting short-run component, so a volatility shock decays over a few days instead of holding the corridor wide for weeks. Negative-return days get a specific leverage response — downside risk is modeled, not averaged away.
• Filtered historical tails with EVT extension.
The residual body is empirical (Filtered Historical Simulation); each tail is extended with a Generalized Pareto fit whose shape and scale are estimated in closed form by Probability-Weighted Moments (Hosking-Wallis) — more stable than method-of-moments or MLE on the small tail samples you actually get. The shape is floored at zero so equity tails are never assumed bounded, and with too few exceedances it falls back to empirical quantiles rather than overfitting noisy extremes.
• Data-driven downside asymmetry.
The downside leverage increment is routed fully to the lower band; the upper band receives only a data-driven semivariance fraction. The corridor widens below only as far as the symbol's own history justifies.
█ THE DRIFT READOUT — WHICH SIDE TO SELL
The bands are DRIFT-NEUTRAL by design: centered on today's close, never tilted up or down. Over 1–20 days, direction is effectively unestimable from price history — and a wrong directional bet would quietly under-reserve the downside, the worst place to be short a put. So the whole band width is spent on dispersion, none of it gambled on a direction the data can't support.
OPB still measures the recent drift and reports it as a small number next to σ, in :
• ↑ : favors puts — the stock has been drifting up, so the put leg has had a cushion.
• ↓ : favors calls — drifting down, the call leg has had the cushion.
• flat — no meaningful drift.
Practical read: it is usually safer to sell the leg the drift is moving AWAY from — sell puts into an uptrend, calls into a downtrend. The wind at your back.
In the backtest this shows up cleanly: on a strongly trending stock the drift-neutral bands breach the TREND side more often than the nominal rate, while the opposite side stays close to it. This is expected, not miscalibration — the corridor is honestly direction-agnostic, so the band width itself stays unbiased and the extra breaches on the trend side are pure drift. The takeaway matches the readout: the side you should be selling — the one the trend is moving away from — is the side that stays calibrated. One caveat: the drift readout is the RECENT past, never a forecast — a strong reading is often exactly where mean-reversion becomes most likely. The fat-tailed band remains the real safety net.
MU · daily · walk-forward, monthly recals. On this uptrend the trend side (Brch+) runs well above nominal while the put-sell side (Brch−) holds at/below its 2.5% target — the drift asymmetry described above, in numbers.
█ HOW TO USE IT
• Set a horizon (e.g. 5 days) and a confidence level (e.g. 95%).
• Read the upper/lower band at your horizon as a strike-placement reference.
• Glance at the drift readout to pick the safer leg — puts vs calls.
• Turn on the walk-forward backtest and check: Close-in ≈ your confidence level; Brch+ / Brch− near the per-side rate and reasonably balanced; NT dn = how often a lower-band strike was never touched over the whole path — the number that matters for assignment.
• Optional PIT diagnostic: D ≈ 1 well-sized, D < 1 too wide, D > 1 too narrow. Read h = 1 first (least affected by overlapping windows).
• Anchor mode D-1…D-5 freezes the corridor as it looked N days ago, calibrated only on data known then — handy to inspect how past corridors held.
█ SETTINGS
Defaults are robust and research-oriented: Horizon 5d · Confidence 95% · Calibration window 252d · Two-component variance ON · Leverage-asymmetric bands ON · Earnings-gap neutralization ON.
"Long-run half-life" sets how steady the long-run volatility baseline is — a higher value keeps it stiffer after a shock, which (with the two-component model on) reduces post-shock over-widening.
Every input ships with a plain-language tooltip. Daily timeframe only. Calibration runs on the last bar for performance; walk-forward recalibration is monthly, a Pine execution-time constraint.
█ WHAT IT IS NOT
• Not a directional forecast — the corridor is drift-neutral, centered on the anchor close.
• Not a joint path bound — confidence targets the close at each horizon separately; the chance of touching a band along the path is the separate No-Touch figure (see backtest).
• Not an option-pricing model — no implied volatility, greeks, or option-chain data.
• Not a guarantee — the backtest and PIT diagnostics are historical calibration evidence, not a promise of future coverage.
Full methodology, equations, and references are documented section by section in the source code. This is a research and educational tool, not investment advice.
Indicador

Self-Validating Elliott Wave EngineSELF-VALIDATING ELLIOTT WAVE ENGINE
A probabilistic Elliott Wave framework that does three things most wave tools do not: it weighs SEVERAL competing counts at once instead of asserting one, it CALIBRATES its own confidence against what actually happened on the instrument you are viewing, and it tells you honestly when no count is trustworthy. It is decision-support and context - not a signal generator, and never a claim of certainty.
WHY THESE PARTS BELONG TOGETHER (one engine, not a bundle)
Elliott Wave analysis is unavoidably ambiguous: the same swings can support an impulse, a zigzag, a flat or a triangle, and practitioners disagree constantly. A tool that draws one count and hides that ambiguity is misleading. This script is built as a single pipeline whose stages exist specifically to manage that ambiguity, and removing any one stage breaks it:
1. Structure - an alternating swing (ZigZag) series is built from confirmed pivots, and each pivot is tagged with momentum (RSI) and relative volume. This is the raw evidence every wave rule is tested against; without a clean swing series there is nothing to count.
2. Multi-count pattern engine - from that swing series the script forms several competing labelled hypotheses at once (impulse forming wave 3/4/5 or complete, zigzag, flat, contracting triangle). Because Elliott is ambiguous, evaluating alternatives is the whole point, not an add-on.
3. Scoring - each hypothesis is graded on Fibonacci fit, proportion and the alternation guideline (waves 2 and 4 should differ in form), and "wave energy" (does wave 3 thrust hardest, in trend direction, on rising volume?). These are combined deliberately: Fibonacci ratios alone mislabel corrections as impulses; momentum alone is directionless noise; only together do they discriminate real structure.
4. Regime context - a trend/range/compression read (from ADX and ATR) tilts the priors, because impulses are more likely in trends and corrections in ranges. It changes the odds, it does not override the structure.
5. Market-structure confirmation - an independent break-of-structure / change-of-character check raises or lowers the chosen count, so the wave read must agree with raw price action to score well.
6. Calibrated forecast - the forward zone is built from THIS chart's own distribution of historical retracement depths, not fixed ratios pulled from a textbook, so it reflects how the specific instrument actually behaves.
7. Outcome calibration - every forward call (target + invalidation + confidence) is logged and later checked: did price reach target before invalidation? Outcomes are bucketed by confidence, so the confidence number on screen can be mapped to a MEASURED hit-rate. This is the stage that makes the tool self-validating, and it is impossible without all the stages above feeding it.
So the components are not stacked for convenience - they form one loop: build competing hypotheses, score them on structure and momentum, tilt by regime, confirm against price structure, forecast from the instrument's own history, then grade that forecast against reality and report the measured reliability. That is why this is one indicator rather than seven separate overlays.
HOW IT WORKS ON THE CHART
- Wave labels and connecting lines draw the primary (highest-scoring) count's structure.
- A dashed projection line and a shaded forecast zone mark where the primary count expects price to go, with the zone width calibrated from the chart's own retrace history.
- A dashboard reports: the primary count with its probability share, its position and stage, the two best alternative counts, the raw confidence, the measured calibrated hit-rate once enough cases have resolved, the regime, the market-structure state (and whether it confirms or warns), the hard-rule pass/fail, wave energy, an opportunity read (confidence shaped by reward-to-risk and structure), and the target / invalidation levels.
HOW TO USE IT
- Read the ambiguity, not a single answer. The secondary and tertiary counts and their probabilities tell you how clear or murky the structure currently is.
- Trust "Calibrated" over "Confidence". Confidence is the raw structural score; the calibrated figure is the measured success rate for that confidence level on resolved cases - the honest number.
- Respect "stand aside". When confidence is below your threshold the panel says so instead of forcing a count. That is a feature.
- Use target and invalidation as context for your own plan. Invalidation is the level that would break the primary count; the forecast zone is where it expects to resolve. The script places no orders.
- Combine with your own method. The market-structure and regime rows are there so the wave read can be cross-checked against plain price action.
SETTINGS OVERVIEW
- Structure: swing sensitivity (pivot legs), max swings stored, and pivot source - wicks (high/low) or bodies (close), so it suits how you read a given market.
- Scoring weights: Fibonacci fit, proportion/look, wave-3 momentum.
- Context: ADX length and trend threshold.
- Forecast: inner/outer percentiles of the retrace distribution, minimum swings to calibrate, minimum resolved cases before the calibrated hit-rate is trusted.
- Display: minimum confidence for a "clean" count, label/zone/panel toggles, bull/bear colours.
- Alerts: new wave, count flip, invalidation breach, forecast-zone entry (via "Any alert() function call").
Pivot source is selectable and volume is used only when a symbol reports it, so the engine runs on futures, equities, forex, crypto and indices on any timeframe.
ORIGINALITY
Most Elliott tools draw a single count and stop. This one runs a bounded multi-count search, scores each hypothesis on structure plus momentum plus volume, tilts by regime and confirms against market structure, forecasts from the instrument's own retrace distribution, and - uniquely - measures its own realised hit-rate per confidence level so the number on screen is grounded in outcomes rather than asserted. It quantifies and reports its own reliability.
REPAINT NOTICE AND LIMITATIONS (honest)
- Swing detection uses confirmed pivots, which finalise a fixed number of bars after they form. The most recent leg is therefore always provisional and can change. This is inherent to Elliott structure detection and is disclosed deliberately, not hidden.
- Counts are probabilistic hypotheses, not predictions. Two analysts - and this engine on two settings - can read the same chart differently.
- Calibration is a long-run estimate over resolved cases on this chart; early on, and after a regime change, it needs samples before it means anything, and past hit-rate is not a future guarantee.
- This is context and decision-support. It is not a trading system and issues no orders.
DISCLAIMER
This script is for research and education only. It is not financial advice, not a recommendation, and not a solicitation to trade. It places no orders and guarantees no outcome. Markets carry risk; test any tool on your own data and timeframe and make your own decisions.
Indicador

Self Calibrating Probability ChannelSELF-CALIBRATING PROBABILITY CHANNEL
A forecast channel whose width is set by conformal prediction, tuned by a parameter-free online calibrator, and proven on your own chart. You pick a coverage level - say 90% - and the indicator shows you, live, the percentage it has actually achieved over recent bars, on every timeframe. Most bands assert a width; this one measures whether the width was right and corrects itself until it is, with nothing to tune.
WHAT IT IS
Bollinger Bands, Keltner Channels, Donchian Channels and standard-deviation regression channels all draw a width from a formula and ask you to trust it. None of them tell you what fraction of price actually landed inside. A "2 standard deviation" band is only a true 95% band if returns are normally distributed and stationary - which markets are not - so the real hit-rate drifts, usually without the user ever knowing.
This indicator inverts that. It forecasts where price should be next bar, measures how wrong that forecast has actually been, and builds the band directly from the empirical distribution of those errors. Then it watches its own hit-rate bar by bar and self-corrects. The result is a channel that earns its stated confidence level instead of assuming it - and reports, honestly, where it is and isn't holding.
THE METHOD (plain language)
1. Forecast path. Each bar, a one-step-ahead forecast of price is formed. You can pick a Kalman level-and-velocity tracker, a linear-regression slope, an EMA projection, or an anchored VWAP - or leave it on Auto, which runs all of them and blends them online by recent accuracy, so the centre line self-calibrates too. The forecast for the current bar uses only prior bars, so it is genuinely out-of-sample.
2. Error window. The gap between forecast and outcome is the forecast error. A rolling window of recent errors is kept, stored in volatility (ATR) units so the band breathes with the market. Each error is recorded only after its band has already been scored, so the band never includes the bar it is being tested on.
3. Conformal bands. For a chosen confidence level, the band edges sit at the matching quantiles of the recent error distribution (split-conformal prediction). Because it uses the actual error quantiles - including their skew - the bands are asymmetric when the errors are, rather than forcing a symmetric width. Four levels are drawn at once (50 / 70 / 90 / 95%) as nested zones, so the channel doubles as a probability heatmap: the dark core is where price spends most of its time, the faint outer edge marks rare excursions.
4. Parameter-free self-calibration (DtACI). After each bar the indicator checks whether price fell inside each level and nudges the width to hold the target. Rather than asking you to pick a calibration speed, it runs several speeds as competing "experts" and continuously blends them by how well each has tracked coverage recently (Dynamically-tuned Adaptive Conformal Inference). There is no rate to tune - the calibration tunes itself.
5. Live coverage proof, including by regime. The dashboard shows, for every level, the target versus the actually-achieved coverage over a rolling window, each tagged calibrated / under / over. It also reports the realised 90% coverage broken down by market regime - so you can see, for instance, that the band holds 92% in a quiet range but 87% in a volatile breakout. You are not asked to trust the band; you are shown its track record on the symbol, timeframe and regime in front of you.
6. Forward cone. A widening cone projects the likely range several bars ahead. Its width is built from actual multi-step forecast errors (not a square-root-of-time assumption), and its centre curves as projected momentum decays rather than extrapolating in a straight line. An optional bootstrap cloud resamples the real errors into sample forward paths - a direct picture of the distribution the bands come from.
7. Context and early warning. A two-axis regime read (trend strength x volatility) labels conditions; a turbulence detector watches for clustering of outer-band breaches and flags, in advance, when coverage is likely to degrade; a coiled-spring marker notes when a compressed range begins to expand; and an optional higher-timeframe row shows whether the larger trend agrees.
WHY THESE PARTS BELONG TOGETHER (one engine, not a bundle)
This is a single forecasting loop, not a collection of separate indicators sharing a chart. Each part is a required step, and removing any one breaks the whole:
- The forecast path produces an expected price and a drift. Without it there is no quantity whose error can be measured.
- The conformal band converts that path's own recent errors into prediction intervals. Without the forecast there is no error to bound; without the band the forecast is an unqualified guess.
- The online self-calibration adjusts the band to hold the target hit-rate as conditions change. Without it the intervals slowly drift out of calibration and the stated confidence becomes false.
- The live coverage readout verifies the loop is actually working, overall and per regime. It is the proof step a formula-based band cannot offer.
- The context layers (regime, turbulence early-warning, graded breaches, compression-release, higher-timeframe agreement) all read the same forecast errors and exist only to tell you WHEN the interval is most trustworthy and when it is about to fail.
So the components are not combined for convenience; they form a closed measure-and-correct cycle - forecast, bound the error, recalibrate, verify - which is precisely why they are published as one script rather than several overlays.
WHAT MAKES IT DIFFERENT
Conformal prediction is a distribution-free framework - its coverage guarantee holds for any underlying distribution given exchangeable errors, with no assumption that returns are Gaussian. It is standard in machine-learning uncertainty quantification but essentially absent from charting tools, which lean almost entirely on standard-deviation or ATR multiples. Pairing it with a parameter-free online recalibrator, a self-weighting forecast centre, and an on-chart coverage readout - including a per-regime breakdown - is the original contribution here. No moving-average envelope, regression channel or volatility band can state "I targeted 90% and have actually delivered 90% over the last 250 bars, and here is exactly where I don't" - this one can, and shows it.
WHAT YOU SEE ON THE CHART
- A multi-zone channel around a forecast centre line, shaded from the high-probability core out to the rare-excursion edge, coloured by forecast direction, and adaptive to dark or light chart backgrounds.
- A widening forward cone, optionally filled with a faint cloud of resampled paths.
- Right-side labels marking the forecast and the 90 / 95% edges as price levels.
- Small triangles when price breaks beyond the outer band; a ring when that breach is also high-quality (graded on displacement, close position, volume, range expansion and structure); an amber diamond when a quiet range starts to wake up.
- A dashboard with the live forecast, the 90% band range and where price sits within it, the full calibration table, the per-regime coverage, a reliability score, the forecast bias, the sample count, the calibration mode, and an optional higher-timeframe row.
- A plain-language "how to read" key, so the chart is approachable without any statistics background.
HOW TO READ AND USE IT
Mean reversion: when price reaches the outer (90 / 95%) zone in a ranging regime, it is statistically stretched and tends to revert toward the centre line. The "band position" readout and the calibration table tell you how stretched, and how trustworthy that edge currently is.
Trend continuation: a sustained walk along one side of the channel, especially with the cone tilted that way and the higher-timeframe row aligned, indicates a directional regime rather than noise.
Anomaly / breakout: a plain triangle is a volatility event; a ringed one is the same event confirmed as high-quality. A turbulence flag warns that the bands may be about to lose calibration.
Reliability and regime: treat the bands as most actionable when reliability is high, the calibration rows read "calibrated", and turbulence is quiet. The per-regime coverage tells you which conditions the channel is currently most trustworthy in.
SETTINGS OVERVIEW
- Forecast path (Auto / Kalman / Linear Regression / EMA / Anchored VWAP) and smoothing lengths.
- Calibration: residual window, recency window, volatility normalisation, parameter-free DtACI on/off (with a manual ACI rate as fallback), coverage-evaluation window.
- Forward projection length, cone momentum decay, optional bootstrap cloud.
- Anomaly sensitivity, swing pivot length, coiled-spring thresholds, turbulence sensitivity.
- Higher-timeframe context, price source, and full theme controls.
The price source is selectable and volume is borrowed where a symbol reports none, so it works across futures, equities, forex and crypto on any timeframe. Defaults read well intraday; longer windows suit higher timeframes.
HONESTY AND LIMITATIONS
- Non-repainting: each bar's forecast uses only prior bars, each error is recorded only after its band is scored, anomalies confirm on bar close, and the higher-timeframe row uses the last confirmed higher-timeframe value. Historical bands do not change after the fact.
- Conformal coverage is a statistical expectation over a window, not a per-bar guarantee. In a sharp regime break the realised hit-rate will dip until the window and calibrator re-adapt - and the dashboard, including its per-regime breakdown, shows that dip honestly rather than hiding it.
- The bands describe the distribution of short-horizon forecast error. They are a probabilistic context for price, not a prediction of direction and not a trading system.
- Calibration needs enough samples; on a fresh chart the channel needs its warm-up window before the figures are meaningful, and the cone needs a few extra bars beyond that.
This script is for research and education. It is not financial advice and not a solicitation to trade. Markets carry risk; test any tool on your own data and timeframe, and make your own decisions.
Indicador

Gap Fill Probability for SPY SPX XSPGap Fill Probability Viewer - open gaps with an adaptive fill probability
Gap Fill Probability Viewer automatically finds price gaps on your chart and draws each one as a colored zone - no more drawing rectangles by hand. It then tells you how likely each open gap is to "fill," and exactly how far price has to travel to close it.
What it shows
Gap zones - every gap-up and gap-down, drawn as a box that extends to the current bar.
Fill probability (P) - an estimate of how likely the gap is to close, shown as a % and color-coded (green = likely, orange = uncertain, red = unlikely).
p-value - the flip side of P: the chance the gap stays open.
Distance to close - how far the current price is from fully closing the gap, in both points and % of the charted symbol.
Stats table - a clean summary for the gap closest to filling.
How the probability works
The estimate adapts to three things research associates with gap fills:
- Size - bigger gaps are harder to fill.
- Distance - the closer price is to the gap, the higher the odds.
- Recency - fresh gaps fill faster; old, stubborn gaps lose momentum.
Handy options
- Auto-hide, fade, or keep gaps once they fill.
- Filter out tiny gaps by % or ATR.
- Detect gaps on wicks or candle bodies.
- Fully tunable probability model and colors.
⚠️ The fill probability is a heuristic estimate for study and education — not a guarantee or financial advice. Calibrate the settings to your own market and timeframe. Indicador

AI Trend Detector | Adaptive Signals [NeuraLib Machine Learning]🔷 AI Trend Detector | Adaptive Signals
AI Trend Detector is a NeuraLib-powered Machine Learning indicator. It trains a compact supervised neural model on confirmed historical movement, then uses the current market state to estimate Bear , Neutral , and Bull pressure.
The model output is converted into a clean visual system:
Trend Oscillator : A 0-100 pressure gauge. Lower values suggest bullish pressure or oversold conditions. Higher values suggest bearish pressure or overbought conditions.
Adaptive MA Cloud : A main-chart adaptive moving average with an AI-biased cloud that expands as model pressure moves away from neutral.
Confirmed Triangles : Optional chart markers for overbought and oversold interactions, with modes for zone entry, zone exit, or confirmed rotation inside a zone.
Dashboard : A compact readout showing the current state, signal value and confidence.
Triangle Alerts : Alert conditions tied to the same confirmed marker logic shown on the chart.
Directional Confidence : An optional 0-100 line showing the stronger directional model probability, calculated from the larger of Bull or Bear pressure. It does not include Neutral probability, so it reflects directional conviction rather than overall model certainty.
This is not a fixed crossover system. The signals are the visual layer of a model-driven trend pressure engine.
---
🔷 How The Model Learns
Each bar contributes a compact feature row based on price movement, adaptive MA context, and distance from the adaptive baseline. NeuraLib stores these rows in a rolling dataset, normalizes the inputs, and trains the model on recent time-series windows.
The model is trained as a 3-class classifier:
Bear
Neutral
Bull
Historical training examples use future-resolved movement to create their target class, but only after that movement has already occurred. This is the supervised learning setup: the model learns from completed historical outcomes, then applies its learned weights to the current live feature window.
The exposed settings allow users to experiment with model size, learning rate, training frequency, smoothing, trend horizon, and signal behavior.
---
🔷 Model Architecture
The model uses a compact temporal classification architecture:
Flattened state window : Recent feature rows are combined into one temporal input.
Temporal convolution stack : Conv1D-style layers extract short-term structure from the recent market sequence.
Global average pooling : The temporal output is compressed into a compact state representation.
Dense classifier head : One or two dense layers process the pooled state.
Three output logits : The model produces Bear, Neutral, and Bull logits, which are converted into display probabilities.
This keeps the model small enough for Pine Script while still giving it a true sequence-learning structure rather than a simple crossover or rule-based signal engine.
---
🔷 Reading The Signals
The oscillator is intentionally inverted for intuitive market reading:
Low values : Oversold or bullish pressure.
Mid values : Balanced or neutral pressure.
High values : Overbought or bearish pressure.
Triangles can be configured through the Triangle trigger setting:
Crossing into : Prints when the oscillator crosses into an overbought or oversold zone.
Going out of : Prints when the oscillator exits an overbought or oversold zone.
Rotation inside zone : Prints when the signal forms a confirmed turn while still inside the zone.
In rotation mode, Rotation confirmation controls how many bars must pass without breaking the candidate peak or trough before the marker is accepted. Rotation triangles print on the confirmation bar, not on the older pivot bar.
The adaptive MA cloud is visual only. The model is not trained on the shifted cloud edge. The cloud simply applies model pressure around the adaptive MA baseline.
---
⚠️ Repainting And Signal Timing
The training and signal system is designed around confirmed bars:
Training rows are pushed on confirmed bars.
Triangle signals are gated with barstate.isconfirmed .
Rotation markers print on the confirmation bar.
No negative plot offsets are used to move markers into the past.
The smoothing path uses current and past values only.
Because this model does not train on the full price history, but instead learns from the most recent N bars, repainting may occur when the script is reloaded at a later date. This happens because the model may begin training from a different market environment.
To help preserve the original model state, adjust the Historical Train Window setting to account for any new bars that have been added since the original run.
---
⚠️ Limitations
Machine Learning inside Pine Script is powerful, but it is still bounded by TradingView's execution model.
The model is compact by design.
Training history is bounded for performance.
Changing hyperparameters rebuilds the model.
Signals depend on the chosen horizon, threshold, smoothing, and triangle mode.
The model estimates directional pressure. It does not know your entries, exits, risk, fees, or position sizing.
This indicator is best treated as a model-based market pressure tool, not as a complete trading system by itself.
This indicator is powered by the NeuraLib Deep Learning Runtime
Disclaimer: This indicator is an analytical and educational tool. It does not guarantee future results, signal accuracy, or financial gain. Past behavior does not ensure future behavior. Use it as one component in a broader trading process, under your own responsibility. Conceptual architecture and quantitative development by Alien_Algorithms.
Indicador

Liquidity Sweep Probability [JOAT]Liquidity Sweep Probability is an open-source Pine Script v6 overlay that maps equal highs and equal lows, tracks sweeps through those levels, detects reclaim behavior, and records simple continuation samples after reclaim events. It is designed for traders who want a clean way to observe where price has built nearby liquidity and how price behaves after that liquidity is tested.
The script does not claim that a sweep must reverse price. Instead, it separates equal-level creation, sweep, reclaim, break, and continuation outcomes. The dashboard shows the most recent event, the side involved, sample counts, and an adaptive probability-style reading derived from the script's own observed samples.
Core Concepts
1. Equal High and Equal Low Detection
Confirmed pivots are compared against the previous pivot on the same side. If two pivot highs or lows are within an ATR-based tolerance, a liquidity zone is created.
pivotHigh = ta.pivothigh(high, pivotLength, pivotLength)
if not na(lastHighPivot) and math.abs(pivotHigh - lastHighPivot) <= equalTolerance
zoneTop = math.max(pivotHigh, lastHighPivot) + zonePadding
zoneBottom = math.min(pivotHigh, lastHighPivot) - zonePadding
2. Sweep State
A high-side sweep occurs when price trades beyond the equal high zone but closes back below the zone top. A low-side sweep occurs when price trades below the equal low zone but closes back above the zone bottom.
3. Reclaim State
After a sweep, the script watches a configurable reclaim window. A high-side reclaim requires price to close back below the lower boundary of the swept high zone. A low-side reclaim requires price to close back above the upper boundary of the swept low zone.
4. Continuation Sampling
After reclaim, the script stores a target distance based on ATR and tracks whether price reaches it within the outcome window. These counts are displayed as samples. They are descriptive statistics from the chart, not a prediction.
5. Probability Panel
The probability-style score blends observed sample rate, sweep distance, zone age, and reclaim status. It gives a compact read of the current event context.
sampleRate = total > 0 ? (wins * 100.0) / total : 50.0
score = clamp(sampleRate * 0.62 + 19.0 + distanceBoost + ageBoost + reclaimBoost, 5.0, 95.0)
Features
Equal high and equal low zones: ATR tolerance avoids exact-price-only matching
Sweep detection: Tracks confirmed high-side and low-side liquidity sweeps
Reclaim detection: Separates immediate breaks from reclaim behavior
Continuation samples: Counts historical reclaim outcomes within the active chart sample
Dashed midlines: Each zone includes a center reference line
Stateful labels: Zones update from Equal High/Low to Sweep, Reclaimed, or Broken
Probability panel: Shows side, status, chance value, samples, and age
Alerts: Sweep, reclaim, and zone break conditions
Input Parameters
Swings:
Swing Pivot Length: Pivot sensitivity for equal-level detection
Equal-Level Tolerance: ATR fraction used to compare pivots
Zone Padding: ATR fraction added around the equal level
ATR Length: Volatility length for tolerance and padding
Behavior:
Reclaim Window: Bars allowed for reclaim after sweep
Continuation Window: Bars allowed for measuring post-reclaim continuation
Continuation Distance: ATR target used for sample tracking
Maximum Zones Per Side: Object cap for high and low zones
Visual:
Palette: Selects bull and bear colors
Zone Extension Bars: Forward extension for boxes and midlines
Probability Panel: Shows or hides the dashboard
How to Use This Indicator
Step 1: Identify Equal-Level Zones
Equal highs can act as high-side liquidity references. Equal lows can act as low-side liquidity references.
Step 2: Watch for Sweep and Reclaim
A sweep alone is not enough. Reclaim behavior shows that price tested outside the zone and then closed back through the zone boundary.
Step 3: Read the Sample Count
The sample row shows how many observed reclaim events reached their ATR target on the current chart sample. A small sample should be treated carefully.
Step 4: Use Zones as Context
Use the zones to frame liquidity behavior, then combine the context with your own entry trigger and risk plan.
Indicator Limitations
Equal-level zones are based on confirmed pivots, so they appear after the pivot confirmation window
The probability value is descriptive and chart-dependent
A small number of samples should not be treated as statistically strong
Fast markets may sweep, reclaim, and break multiple zones quickly
Object limits require the script to delete older zones when caps are reached
Originality Statement
Liquidity Sweep Probability is original in its state machine for equal-level zones, sweep/reclaim/break classification, and live sample tracking. It uses public Pine v6 mechanics to build a self-contained liquidity map without copying another indicator's source.
Disclaimer
This script is provided for educational and informational use only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Liquidity sweeps can continue, reverse, or fail without warning. Always use independent analysis and proper risk management.
-Made with passion by jackofalltrades
Indicador

Viprasol Naive Bayes Order FlowOverview
This indicator is based on "Institutional Order Flow Signals " by PMT, an open-source script that classifies order-flow conditions with a Naive Bayes classifier trained on Cumulative Volume Delta (CVD) features. The original produces a posterior probability that the current bar belongs to a Bull, Bear, or Diverged regime, then prints directional signals when that probability clears a threshold and price agrees with a trend EMA. This version keeps that classifier intact and layers a Viprasol signal-filter stack on top: a signal cooldown, an optional volume-surge confluence requirement, a bar-close confirmation gate, live classifier hit-rate tracking, and regime-flip detection.
It is built for traders who want a probabilistic read on whether buying or selling pressure (measured through volume delta) is currently dominating, with explicit noise controls applied before any signal fires.
How It Works
Cumulative Volume Delta (from original):
Each bar's volume is split into buying and selling pressure by where the close sits inside the bar's range. Buy volume = volume × (close − low) / range; sell volume = volume × (high − close) / range. The bar delta is buy minus sell, and these deltas are summed into a running CVD line. CVD rising means net buying pressure is accumulating; falling means net selling.
Three Classifier Features (from original):
The classifier is trained on three z-score-normalised features so they are comparable across instruments:
- F1 — CVD rate of change over the momentum period, normalised against its own rolling mean and standard deviation.
- F2 — price/flow divergence: price ROC minus CVD ROC, normalised. Large values flag price moving without matching flow (or vice versa).
- F3 — CVD slope: the first difference of a linear regression on the CVD line, normalised. Captures the acceleration of flow.
Naive Bayes Classification (from original):
Every bar is labelled into one of three classes from the prior bar's outcome — Bull (price up and CVD up), Bear (price down and CVD down), or Diverged (anything else). For each class the script maintains running sums of each feature and each feature squared, from which it derives a per-class mean and standard deviation online (no arrays of history needed). The likelihood of the current feature vector under each class is the product of three Gaussian PDFs (the "naive" independence assumption). Combined with class priors (the observed class frequencies), Bayes' rule yields the posterior probability of each class:
posterior(class) = prior(class) × likelihood(class) / evidence
A signal requires the posterior to clear the entry threshold, price to be on the correct side of the trend EMA, and CVD to be moving in the signal's direction. Signals fire only on the first bar of a new cluster to avoid consecutive repeats.
Signal Cooldown (new):
After any signal fires, a configurable number of bars must elapse before the next signal of any direction is allowed, tracked as bar_index − lastSignalBar >= cooldown. During fast moves the classifier can re-cross the threshold repeatedly; the cooldown collapses those into one actionable signal. A cooldown of 5 bars on a 15-minute chart enforces a 75-minute minimum gap between entries.
Volume-Surge Confluence (new):
When enabled, a signal is additionally gated on current volume exceeding its rolling average by a multiplier (default 1.5×). The logic is volume > sma(volume, length) × multiplier. This filters out classifier signals that occur on thin participation, where flow estimates are least reliable.
Bar-Close Confirmation (new):
When enabled, signals are only confirmed on a fully closed bar (barstate.isconfirmed). Because the posterior and CVD update intrabar, a developing bar can flip in and out of a signal state before it closes; this gate holds the signal until the bar settles.
Classifier Hit-Rate Tracking (new):
On every live bar the script takes the argmax of the three posteriors as its prediction, then on the following bar compares that prediction to the realised class label. It accumulates a running hit count and evaluation count and displays the ratio as a live "Hit Rate" in the dashboard. This is an honest in-sample diagnostic of how often the classifier's single most-likely class matched the next realised label — not a trade win rate.
Regime-Flip Detection (new):
The script tracks the active regime (+1 bull, −1 bear, 0 neutral) and fires a dedicated alert whenever it transitions into a new bull or bear regime, independent of the entry-cluster logic. Useful for traders who want to be notified of context shifts rather than individual entries.
Diverged Class Surfaced (new):
The original computes a third "Diverged" class but never displays its posterior. This version surfaces P(Diverged) in the dashboard so the trader can see when the classifier considers the tape conflicted (price and flow disagreeing) rather than directional.
What Is Original (Viprasol Additions)
1. Signal cooldown system — enforces a minimum bar gap between signals to prevent clustering during fast moves.
2. Volume-surge confluence filter — optionally requires above-average volume on the signal bar so signals occur on real participation.
3. Bar-close confirmation gate — optionally holds signals until the bar closes, removing intrabar flip-flop.
4. Classifier hit-rate tracking — online comparison of the argmax-posterior prediction to the next realised class, displayed live.
5. Regime-flip detection — separate state machine and alert for bull/bear regime transitions.
6. Diverged-class posterior surfaced in the dashboard, exposing the third class the original computed but hid.
Key Features
From the Original (PMT):
- CVD line built from close-position volume splitting
- Three z-score-normalised classifier features (CVD ROC, price/flow divergence, CVD slope)
- Online Naive Bayes classifier over Bull / Bear / Diverged classes with Gaussian likelihoods
- Posterior-probability entry threshold with trend-EMA and CVD-direction agreement
- Confidence tiers (high / mid / normal) driving signal shape and band opacity
- Confidence-scaled posterior band and regime background shading
- ATR-based SL/TP projection lines
- Warmup gate (LIVE only after the classifier has trained on enough bars)
- Zen mode for clean screenshots
Added in This Version (Viprasol):
- Signal cooldown, volume-surge confluence, and bar-close confirmation filters
- Live classifier hit-rate diagnostic
- Regime-flip detection and alert
- Diverged-class posterior in the dashboard
- Colored TP / ENTRY / SL price labels on the projection lines
- Expanded info dashboard with selectable position
- Six alert conditions with dynamic {{ticker}} / {{close}} / {{interval}} messages
How to Use
Getting Started:
1. Add to a standard candlestick chart (not Heikin Ashi).
2. Wait for the dashboard to read LIVE — the classifier needs to train on enough bars first (status shows WARMUP and an N-trained counter until then).
3. Long signals print below the bar (circle = high conviction, triangle = normal); short signals print above the bar.
Reading the Dashboard:
- Bull P / Bear P / Diverged P — the three class posteriors. The dominant one drives the regime.
- CVD Flow — whether net delta is currently rising (buy) or falling (sell).
- Vol Surge — whether the current bar cleared the volume-surge threshold.
- Hit Rate — share of bars where the most-likely class matched the next realised class.
- N Trained — how many bars the classifier has trained on; ✓ once warmed up.
Recommended Starting Points:
- Crypto/Forex (5m-15m): Lookback 100, Threshold 0.70, Cooldown 3
- Stocks (15m-1H): Lookback 120, Threshold 0.72, Cooldown 5
- Indices (1H-4H): Lookback 150, Threshold 0.75, Cooldown 8
These are starting points only. Volume data quality and tape behaviour differ by instrument — backtest and adjust before trading live.
Settings
Naive Bayes Classifier: classifier lookback (bars before signals go live), entry threshold (minimum posterior), and prior bull probability.
CVD Features: CVD momentum period, CVD slope period, and the z-score normalisation window applied to all features.
Signal Filters (Viprasol): signal cooldown in bars, bar-close confirmation toggle, volume-surge requirement with average length and multiplier.
Signal Levels: show SL/TP lines, show price labels, SL ATR multiplier, risk:reward ratio, ATR period, and trend EMA period.
Visual: posterior band toggle, regime background toggle, and bull / bear / diverged colors.
Dashboard / Display: Zen mode, dashboard toggle, and dashboard position.
Alerts
1. Long Signal — bull posterior cleared the threshold with CVD rising and all filters passed
2. Short Signal — bear posterior cleared the threshold with CVD falling and all filters passed
3. Any Signal — either direction fired
4. High-Conviction Long — long signal with P(Bull) at or above 85%
5. High-Conviction Short — short signal with P(Bear) at or above 85%
6. Regime Flip — the active regime transitioned into a new bull or bear state
All alerts include {{ticker}}, {{close}}, and {{interval}} for dynamic notification messages.
Limitations & Disclaimer
- The classifier trains in-sample on the chart's own history and updates continuously; the displayed hit rate is a diagnostic of class-label agreement, not a trade win rate, and is not predictive of future results.
- CVD here is approximated from candle range and volume, not from true bid/ask tick data. Volume quality varies by broker and instrument, so the same symbol on different feeds can produce different signals.
- The classifier needs a warmup period before signals appear; on fresh charts or low-history symbols it may stay in WARMUP for a long time.
- Posteriors and CVD update intrabar; without bar-close confirmation enabled, signals can appear and disappear before a bar closes.
- SL/TP lines and price labels are visual references only — they do not place or manage trades.
- Filters reduce noise but also reduce signal count; in fast trends the cooldown may delay otherwise valid entries.
- Past performance does not guarantee future results. This indicator is for educational and analytical purposes only and is not financial advice. Always use proper risk management and test on historical data before trading live.
Credits & Attribution
Based on "Institutional Order Flow Signals " by PMT, which provided the CVD construction, the three z-score-normalised classifier features (CVD ROC, price/flow divergence, CVD slope), the online Naive Bayes classifier over Bull/Bear/Diverged classes with Gaussian likelihoods, the posterior-threshold entry logic with trend-EMA and CVD agreement, the confidence tiers, the posterior band and regime background, and the ATR-based SL/TP projection lines. Added by Viprasol: signal cooldown, volume-surge confluence filter, bar-close confirmation gate, live classifier hit-rate tracking, regime-flip detection and alert, the surfaced Diverged-class posterior, TP/ENTRY/SL price labels, an expanded dashboard, and a six-condition dynamic alert set.
Published open-source per TradingView House Rules.
Indicador

Market State Forecast Projection EngineThis indicator is a **forecast projection tool**. It looks at the current market environment, searches history for the most similar environments, then plots what usually happened afterward. It is not trying to predict the future with certainty. It is saying: “When the market looked like this before, what tended to happen next?”
The engine defines the current market environment using three things:
* **Trend**, based on moving averages.
* **Momentum**, based on RSI.
* **Volatility**, based on ATR.
Then it finds the closest historical matches, studies their future paths, and draws a forecast line with optional upper and lower bands.
---
## What You See on the Chart
### Forecast Midline
The main forecast line shows the **average path** of the selected historical matches.
In simple terms:
* If similar past situations usually moved higher, the line slopes up.
* If similar past situations usually moved lower, the line slopes down.
* If similar past situations were mixed, the line may be flat or choppy.
### Upper Band
The upper band shows the stronger side of historical outcomes.
It means:
* Some similar historical setups moved better than the average.
* The upper band gives you a visual idea of the upside range from those past examples.
* It is not a guaranteed target.
### Lower Band
The lower band shows the weaker side of historical outcomes.
It means:
* Some similar historical setups moved worse than the average.
* The lower band gives you a visual idea of downside risk from those past examples.
* It is not a guaranteed support level.
### Band Width
The space between the bands matters.
* Tight bands mean historical outcomes were more consistent.
* Wide bands mean historical outcomes were scattered and less reliable.
* A forecast with wide bands should be treated with more caution.
---
## Main Inputs
### Non-Repaint Mode
**Default: On**
This controls whether the forecast uses the live candle or the last completed candle.
Use **Non-Repaint Mode On** when:
* You want more stable signals.
* You want the forecast to update only after the candle closes.
* You care about cleaner historical testing.
Use **Non-Repaint Mode Off** when:
* You want the forecast to react during the current live candle.
* You accept that the forecast may change before the candle closes.
For most use cases, leave this **On**.
---
## Model Group
### Forecast Horizon
This controls how far into the future the indicator projects.
Example:
* On a daily chart, `20` means 20 trading days.
* On a 1-hour chart, `20` means 20 hours.
* On a 5-minute chart, `20` means 20 five-minute candles.
Use a lower value when:
* You are trading short-term moves.
* You want a tighter forecast window.
* You do not want the projection stretched too far.
Use a higher value when:
* You are looking for swing-trade context.
* You want to see the broader projected path.
* You are using higher timeframes.
A practical range is usually:
* `10–20` for shorter-term analysis.
* `20–50` for swing-style analysis.
---
### Search Depth
This controls how much history the engine searches.
Example:
* `1000` means the engine searches roughly 1,000 prior bars.
* `2000` means it searches more history.
* `500` means it searches less history.
Use a higher Search Depth when:
* You want a larger historical sample.
* You are on a short timeframe with lots of bars.
* You want more possible market-state comparisons.
Use a lower Search Depth when:
* You want the model to focus on more recent market behavior.
* You are on a slower chart like daily or weekly.
* You want less influence from older market regimes.
The tradeoff is simple:
* More history gives more examples.
* Less history may be more relevant to the current market regime.
---
### Pattern Matches
This controls how many of the closest historical matches are used.
This is one of the most important inputs.
If set to `30`, the engine finds the **30 closest historical market states** and builds the forecast from those.
Use fewer matches when:
* You want stricter, more specific comparisons.
* You want only the closest historical examples.
* You are okay with a forecast that may be more reactive.
Use more matches when:
* You want a smoother forecast.
* You want less noise from individual examples.
* You want a broader historical sample.
General interpretation:
* `10–20` = stricter, more selective.
* `25–40` = balanced.
* `50+` = broader, smoother, but less specific.
---
### Weight Closer Matches
This controls whether the best matches receive more influence.
When turned **On**:
* The closest historical matches matter more.
* Weaker matches still count, but less heavily.
* The forecast becomes more focused on the most similar examples.
When turned **Off**:
* Every selected match is treated equally.
* The forecast becomes more democratic.
* A very close match and a weaker match have the same influence.
For most users, leave this **On**.
---
## Advanced Model Inputs
### Forecast Model
This chooses how the engine defines the market environment.
All models use:
* EMA trend.
* RSI momentum.
* ATR volatility.
The difference is how each model emphasizes those ingredients.
---
### Conservative
Use **Conservative** when you want a slower, smoother model.
It is designed to:
* React less aggressively.
* Favor more stable market environments.
* Put more importance on trend and volatility.
* Reduce noisy forecast changes.
Best for:
* Daily charts.
* Swing trading.
* Slower-moving stocks or ETFs.
* Users who want fewer false shifts.
---
### Balanced
Use **Balanced** as the general-purpose default.
It is designed to:
* Give trend, momentum, and volatility a normal balance.
* Work across many markets.
* Avoid being too slow or too fast.
Best for:
* Most users.
* Most chart timeframes.
* General market forecasting.
* Starting point before testing other models.
---
### Aggressive
Use **Aggressive** when you want a faster model.
It is designed to:
* React more quickly to changing momentum.
* Give more influence to short-term market shifts.
* Be more sensitive to fresh moves.
Best for:
* Intraday trading.
* Fast-moving markets.
* Crypto.
* Momentum names.
* Traders who want earlier, more responsive shifts.
The downside is that it may be noisier.
---
### Trend Following
Use **Trend Following** when you want the model to emphasize persistent directional moves.
It is designed to:
* Care more about trend structure.
* Care less about short-term momentum noise.
* Favor markets that continue moving in the same direction.
Best for:
* Strong trending stocks.
* Indexes.
* Breakout environments.
* Higher-timeframe directional trading.
This model is less ideal in sideways or choppy markets.
---
### Mean Reversion
Use **Mean Reversion** when you want the model to focus on stretched conditions.
It is designed to:
* Emphasize momentum extremes.
* Look for environments where price may snap back or reverse.
* Care less about long-term trend persistence.
Best for:
* Range-bound markets.
* Overbought/oversold setups.
* Countertrend analysis.
* Shorter-term reversal ideas.
This model may fight strong trends, so use it carefully in momentum-heavy markets.
---
## Historical Lookback Inputs
### Lookback Bars
This lets you move the forecast backward in time.
Example:
* `0` means current forecast.
* `50` means show what the forecast would have looked like 50 bars ago.
* `250` means show what the forecast would have looked like 250 bars ago.
Use this for:
* Visual backtesting.
* Studying old setups.
* Checking whether the forecast was useful historically.
* Comparing forecast paths against what actually happened.
This is one of the most valuable testing features.
---
### Lock to Candle
This lets you anchor the forecast to a specific candle time instead of a simple bar offset.
Use it when:
* You want to test a specific time of day.
* You trade a regular session open.
* You want repeatable historical anchors.
Example:
* You can lock to the 13:30 UTC candle, which often corresponds to the U.S. stock market open during daylight saving time.
When this is off, the indicator uses **Lookback Bars** instead.
---
### Days Back
This works with **Lock to Candle**.
It tells the indicator how many matching anchor candles to go back.
Example:
* `0` = most recent matching candle.
* `1` = one matching session back.
* `2` = two matching sessions back.
Use this when:
* You want to test the most recent open.
* You want to test yesterday’s open.
* You want to step through past sessions one by one.
---
### Hour UTC
This is the UTC hour used for candle locking.
Use it with **Minute UTC** to identify the exact candle you want.
Example:
* `13` means 13:00 UTC.
* Combined with `30`, it means 13:30 UTC.
This is useful because TradingView symbols and sessions can vary, but UTC gives a consistent anchor.
---
### Minute UTC
This is the UTC minute used for candle locking.
Example:
* Hour UTC = `13`
* Minute UTC = `30`
Together, that means:
* Lock to the 13:30 UTC candle.
Use this for precise historical testing.
---
### Auto Previous Session
This controls what happens if today’s target candle has not printed yet.
When turned **On**:
* The indicator automatically uses the most recent previous matching candle.
* This keeps the forecast visible even before today’s target time exists.
When turned **Off**:
* If today’s target candle has not printed, the lock may show no match and fall back.
For most users, leave this **On**.
---
## Bias Logic Inputs
### Bias Threshold %
This controls how strong the bull or bear probability must be before the indicator labels the forecast bullish or bearish.
Example:
* If Bias Threshold is `60`, Bull Probability must be at least 60% before a bullish label can appear.
* If Bear Probability is at least 60%, a bearish label can appear.
Use a lower threshold when:
* You want more frequent bias labels.
* You are okay with weaker directional evidence.
Use a higher threshold when:
* You want stricter signals.
* You only want stronger historical agreement.
Practical range:
* `60%` = balanced.
* `70%+` = more conservative.
* `50–55%` = loose and more signal-heavy.
---
### Minimum Bull/Bear Edge %
This controls how large the gap must be between Bull Probability and Bear Probability.
Example:
* Bull Probability = 65%
* Bear Probability = 35%
* Edge = 30 percentage points
If the minimum edge is `15`, this would qualify.
But:
* Bull Probability = 58%
* Bear Probability = 42%
* Edge = 16 percentage points
This may still fail if Bull Probability is below the Bias Threshold.
This input prevents weak differences from being labeled as strong directional bias.
Use a higher edge when:
* You want cleaner bias labels.
* You want the model to avoid borderline calls.
Use a lower edge when:
* You want more frequent directional bias.
* You accept more uncertainty.
---
## Display Inputs
### Show Forecast Midline
This turns the main forecast line on or off.
Turn it **On** when:
* You want to see the projected average path.
Turn it **Off** when:
* You only want the info box probabilities.
* You want a cleaner chart.
---
### Show Confidence Bands
This turns the upper and lower forecast bands on or off.
Turn it **On** when:
* You want to see the historical range of outcomes.
* You care about uncertainty.
* You want to know whether the forecast is tight or messy.
Turn it **Off** when:
* You only want the central forecast.
* The chart feels too cluttered.
---
### Band Width Multiplier
This controls how wide the bands are.
Higher values make the bands wider.
Lower values make the bands tighter.
Use lower values when:
* You want a cleaner, tighter visual range.
* You want bands closer to the average forecast.
Use higher values when:
* You want to see a broader range of historical outcomes.
* You want a more conservative uncertainty envelope.
Default `1.0` is a good starting point.
---
## Forecast Midline Style Inputs
### Forecast Midline Color
Controls the color of the main projection line.
The default aqua color makes it visually distinct from price candles.
### Forecast Midline Width
Controls how thick the midline is.
Use a thicker line when:
* You want the forecast to stand out.
* You are using a busy chart.
Use a thinner line when:
* You want a cleaner chart.
* You use many overlays.
### Forecast Midline Type
Controls whether the line is:
* Solid.
* Dashed.
* Dotted.
Solid is usually best for the main forecast line.
---
## Upper Band Style Inputs
### Upper Band Color
Controls the color of the upper forecast band.
The default green tone suggests upside range.
### Upper Band Width
Controls how thick the upper band is.
A thin dashed line usually works best because it should be secondary to the midline.
### Upper Band Type
Controls whether the upper band is solid, dashed, or dotted.
Dashed is usually best because it visually communicates “range” rather than “target.”
---
## Lower Band Style Inputs
### Lower Band Color
Controls the color of the lower forecast band.
The default red tone suggests downside range.
### Lower Band Width
Controls how thick the lower band is.
A thin line keeps it useful without dominating the chart.
### Lower Band Type
Controls whether the lower band is solid, dashed, or dotted.
Dashed is usually best for the same reason as the upper band.
---
## Info Box Inputs
### Show Info Box
This turns the dashboard on or off.
Turn it **On** when:
* You want the probabilities and diagnostics visible.
* You are actively evaluating the forecast.
Turn it **Off** when:
* You only want the chart projection.
* You want a cleaner visual layout.
---
### Info Box Position
Controls where the dashboard appears.
Options:
* Top Left.
* Top Right.
* Bottom Left.
* Bottom Right.
Use the position that interferes least with price action on your chart.
---
### Text Size
Controls the dashboard text size.
Use:
* **Tiny** for compact charts.
* **Small** for normal use.
* **Normal** if you want easier reading.
* **Large** for presentations or large monitors.
---
### Background
Controls the info box background color.
A darker background usually works best on most TradingView chart themes.
### Border
Controls the info box border color.
This helps separate the dashboard from the chart.
### Header Text
Controls the title/header text color.
### Header Background
Controls the top header row background.
This gives the dashboard its polished look.
---
## Info Box Metrics
### Bull Prob %
This shows the weighted percentage of selected historical matches that ended bullish.
Simple meaning:
> Of the similar historical market states, how many tended to move up?
A high number means bullish outcomes dominated the selected historical matches.
---
### Bear Prob %
This shows the weighted percentage of selected historical matches that ended bearish.
Simple meaning:
> Of the similar historical market states, how many tended to move down?
A high number means bearish outcomes dominated the selected historical matches.
---
### Direction Bias
This shows the final label after applying the bias rules.
Possible outputs:
* Bullish.
* Bearish.
* None.
* Weak Data.
* No Matches.
A bullish or bearish label only appears when the probability and edge requirements are met.
---
### Bull/Bear/Flat
This shows how many selected matches ended:
* Bullish.
* Bearish.
* Flat.
Example:
* `18 / 9 / 3`
This means:
* 18 bullish historical outcomes.
* 9 bearish historical outcomes.
* 3 flat historical outcomes.
This gives you a quick look at the underlying distribution.
---
### Match Count
This shows how many historical matches were actually used.
If Pattern Matches is set to `30`, Match Count should usually show `30`.
If it shows less, there may not have been enough valid historical data.
---
### Fit Quality
This tells you how closely the selected historical matches resemble the current market state.
High Fit Quality means:
* The current market environment closely resembles the selected historical examples.
Low Fit Quality means:
* The engine found matches, but they were not very close.
Important:
* Fit Quality is not win rate.
* Fit Quality is not probability.
* Fit Quality is not accuracy.
* It only measures how good the historical comparisons are.
Best interpretation:
* High Fit Quality + strong Bull/Bear Probability = more compelling.
* High Fit Quality + split probabilities = similar markets existed, but outcomes were mixed.
* Low Fit Quality = be cautious.
---
### Model
This shows which Forecast Model is active.
Examples:
* Balanced.
* Conservative.
* Aggressive.
* Trend Following.
* Mean Reversion.
This is useful for screenshots and reviewing past setups.
---
### Anchor
This tells you where the forecast is anchored.
Examples:
* `0 bars · NR` means current forecast using Non-Repaint Mode.
* `50 bars · NR` means historical forecast from 50 bars ago.
* `Locked` means it is anchored to a specific UTC candle.
This helps you know whether you are looking at a current forecast or a historical replay.
---
### Search Depth
This shows the actual number of bars being searched.
It may be lower than your input if the chart does not have enough loaded history.
---
## Best Practical Way to Use It
A clean workflow would be:
* Start with **Balanced** model.
* Keep **Non-Repaint Mode On**.
* Use **Pattern Matches around 30**.
* Use **Search Depth around 1000**.
* Watch **Fit Quality**.
* Watch **Bull/Bear Probability**.
* Treat the forecast line as a scenario path, not a guaranteed prediction.
* Use **Lookback Bars** to test whether the forecast was historically useful.
* Avoid trusting any forecast where the bands are very wide and probabilities are split.
The strongest setup is usually when:
* Fit Quality is high.
* Bull or Bear Probability is clearly dominant.
* The forecast bands are not extremely wide.
* The projection agrees with price structure.
Indicador

Wedge Polaris [JOAT]Wedge Polaris
Wedge Polaris is a multi-pattern auto-detector. It identifies five distinct converging-channel pattern families from zigzag pivots — Ascending Triangle, Descending Triangle, Symmetric Wedge, Rising Wedge, Falling Wedge — and on confirmed breakout projects a three-target ladder (Fibonacci times ATR times historical-duration blend). Pattern statistics, breakout probabilities, target hit / miss tracking, completed-pattern history, and a right-side bias gauge are all surfaced on the chart.
What makes it different
Most wedge / triangle indicators detect a single pattern type. This script classifies five families using slope analysis of the top and bottom channels.
Collinearity tolerance is adaptive. It scales with ATR percentile so the script is strict in low-volatility regimes (clean pivots) and forgiving in high-volatility regimes (noisier pivots) without being retuned.
Breakout probability is computed from the standard-normal CDF on the z-scored duration of the current pattern against a rolling history of completed patterns. Class-conditional bull / bear probabilities are blended with net-volume polarity inside the pattern.
A strong-break filter requires the breakout candle's body Z-score to exceed three AND its 25th or 75th body percentile to be on the correct side of the boundary. This distinguishes decisive expansion from noise probes.
A completed-pattern history strip tracks the last ten patterns with their outcomes (Target 1 hit, Stop hit, expired) so you can see the recent quality of the detector on the current instrument.
How it works
Zigzag pivots are tracked via standard ta.pivothigh and ta.pivotlow with parallel arrays.
Collinearity is tested between the two outer pivots and a middle pivot. Tolerance widens in high-volatility environments.
Two collinear lines (one for highs, one for lows) form a channel. Convergence, alignment, and inside-the-channel tests confirm a valid pattern.
Slope analysis classifies the pattern family.
On breakout confirmation, target lines are projected. T1 equals entry plus or minus 0.5 times width. T2 equals entry plus or minus 1.0 times width. T3 equals entry plus or minus (1.618 times width plus atr-z times ATR). SL is symmetric at width times the user SL multiplier.
Each completed pattern's duration and direction is appended to a 200-entry history buffer, which feeds the probability statistics.
Reading the chart
Pattern channels: two lines plus a linefill between them. Line style differentiates pattern type (solid for triangles, dashed for wedges, dotted for channels).
Completed-pattern ghost outlines fade for a user-configurable number of bars after the pattern ends.
A pattern stats label at the channel midpoint reads, for example: WEDGE 23 bars P(bull) 64% P(break) 78% ATR x.xx.
A three-target ladder on confirmed breakout: entry / SL / T1 / T2 / T3 horizontal lines plus price-only right-edge labels (no arrows, no shout text). Linefills shade the risk and reward zones.
Volume confluence: if breakout-bar volume exceeds 1.5 times the 20-bar SMA, target labels append VOL+.
A right-side bias gauge: 21-segment vertical band with a pointer.
Optional right-side breakout-probability gauge (separate from bias gauge).
A completed-pattern history strip above past pattern midpoints.
A strong-break flash: bgcolor pulse on the strong-break bar.
Signals
Pattern formed
Bullish / bearish breakout
Strong bullish / strong bearish breakout
Target 1 / Target 2 / Target 3 hit
Stop loss hit
All gated on barstate.isconfirmed or barstate.ishistory. No future references.
Inputs
Zigzag : zigzag length.
Collinearity : base tolerance (as a fraction of price).
Breakout : SL width multiplier, target line extension bars.
Visual : bullish / bearish colors, bias gauge, breakout probability gauge, pattern stats label, target ladder.
On-chart : completed-pattern history, ghost outlines extension bars, line-style differentiation.
Dashboard : position, size.
How traders use this
Pattern plus volume : a confirmed breakout with the VOL+ tag and a high P(bull) reading is a higher-probability continuation entry.
Mean-reversion fades : when a wedge's third or later touch happens at the convergence apex with low P(break), the pattern often fails to break. Fade trades inside the channel are possible.
R-multiple management : once target 1 prints, common practice is to move stops to breakeven and let the remainder run for T2 / T3. The target ladder makes this straightforward.
Pattern history : the strip lets you assess whether the detector is performing well on the current instrument and timeframe before sizing up new signals.
Limitations
Pivot detection inherits the right-bar delay of ta.pivothigh and ta.pivotlow. Patterns are confirmed only after the pivot-right-window passes.
Collinearity tolerance is a heuristic. Extremely volatile or extremely clean charts may need tuning of the base tolerance.
The class-conditional probability statistics need a minimum sample (five completed patterns) before they are meaningful.
Pattern recognition is fundamentally interpretive. Even confirmed patterns fail.
Compatibility
Pine Script v6 open-source indicator. Imports TradingView/ta/12 for ta.atr2 (series-period ATR used in duration-adaptive target projection). Any symbol, any timeframe. No request.security calls.
Defaults
7-bar zigzag, 0.5 percent base collinearity tolerance, mint / red colors, top-right medium dashboard. For very fast charts shorten the zigzag length. For slow charts lengthen it and tighten the collinearity tolerance.
Indicador

Machine Learning Random Forest Strategy | GainzAlgoMachine Learning Random Forest Strategy
We are excited to introduce the Machine Learning Based Random Forest Strategy indicator.
What Even Is a Random Forest?
Machine learning and AI get thrown around so loosely these days that they've almost lost all meaning. So let's start from the beginning.
A Random Forest is an ensemble learning method. Instead of relying on a single model, it combines many models that work together and vote on an outcome.
The individual models are called decision trees.
A decision tree is essentially a flowchart:
Is a feature above or below a threshold?
If yes, go left.
If no, go right.
Continue until a prediction is reached.
The problem with a single decision tree is that it is fragile. Train it on slightly different data and you may get a completely different tree. This creates high variance and causes overfitting.
This is the same weakness many rule-based indicators suffer from. They perform well in one market regime and break down when conditions change.
A Random Forest solves this problem through two core mechanisms:
Bootstrap Sampling — Each tree is trained on a random subset of historical data using sampling with replacement.
Random Feature Selection — Each tree can only evaluate a random subset of features at every split.
Without random feature selection, every tree would focus on the same dominant signal and become nearly identical.
By forcing trees to learn different relationships, prediction errors become less correlated. When many uncorrelated predictors are averaged together, noise tends to cancel out while useful signal remains.
This is the foundation of ensemble learning and the reason Random Forests remain one of the most widely used machine learning models.
The Pine Script Problem (And How We Solved It)
Pine Script was never designed to support traditional machine learning workflows.
There are no native machine learning primitives, no recursion, strict execution limits, and memory is largely restricted to arrays and matrices.
Building a traditional multi-level decision tree inside Pine Script is therefore extremely difficult.
The solution was to use decision stumps.
A decision stump is simply a decision tree with exactly one split.
By themselves, stumps are weak predictors. However, when many stumps are combined together using random feature selection, they form a legitimate shallow Random Forest.
The core ensemble behavior remains intact:
Each stump learns a slightly different relationship.
Prediction errors become decorrelated.
Averaging outputs creates a more stable forecast.
This is not a workaround.
A depth-1 Random Forest is still a Random Forest. Production libraries such as scikit-learn simply allow deeper trees, while the underlying ensemble mechanism remains the same.
Threshold Optimization Using Information Gain
A naive stump implementation would select completely random thresholds.
The problem is that random thresholds often produce meaningless 50/50 predictions.
To solve this, the model performs a threshold search.
Each stump evaluates multiple candidate thresholds and selects the one that maximizes Information Gain using Gini Impurity.
Gini Impurity Explained
Gini = 0 → Perfectly pure node.
Gini = 0.5 → Completely mixed node.
Lower values are better.
Information Gain measures how much impurity is reduced after a split.
The model evaluates multiple threshold candidates and selects the threshold that best separates bullish and bearish outcomes.
This is the same methodology used by scikit-learn's DecisionTreeClassifier using the Gini criterion.
The Two Models Running In Parallel
The indicator actually runs two separate Random Forest models simultaneously.
1. RF Classifier
The classifier answers a binary question:
"Is the next move likely bullish or bearish?"
It outputs a probability representing the likelihood that the next close will be higher than the current close.
This probability drives the signal generation process.
Bull probability exceeds threshold → ▲ Bullish Signal
Bear probability exceeds threshold → ▼ Bearish Signal
2. Regression Forest
The regression forest estimates the magnitude of the next move.
Instead of predicting direction, it predicts expected return.
This value appears as "Exp. Ret" inside the statistics table.
Having both models creates stronger confirmation.
High Bull Probability + Positive Expected Return = Strong Confirmation
High Bear Probability + Negative Expected Return = Strong Confirmation
Conflicting Signals = Reduced Conviction
Features: What The Model Actually Looks At
All features are normalized to a 0-100 scale.
Anchor Oscillator
Users can select:
RSI
MFI
Stochastic
Z-Score
This acts as the model's primary momentum or mean reversion feature.
Trend Correlation Feature
The model measures how strongly price has been correlated with time over a specified lookback period.
High values indicate strong directional trends.
Low values indicate choppy or sideways conditions.
Momentum / ATR Feature
Raw momentum is normalized using ATR.
This allows momentum strength to remain comparable across different volatility environments.
The Rolling Training Window
The model does not train on all historical data.
Instead, it continuously trains on the most recent N bars.
Every new bar:
Oldest sample is removed.
Newest sample is added.
Model retrains using current market conditions.
This is critical because markets are non-stationary.
Patterns that worked years ago may no longer be relevant today.
The rolling window helps the model adapt to changing market conditions.
Preventing Lookahead Bias
Many TradingView machine learning indicators accidentally introduce lookahead bias.
This occurs when a model trains using information that would not have been available at the time of the prediction.
This implementation avoids that problem by using lagged feature values and future returns as targets.
The model only learns from information that genuinely existed before the outcome occurred.
Adaptive Threshold: The Self-Correcting Layer
One of the most unique aspects of this indicator is its adaptive threshold system.
The default probability threshold is 60%.
However, that threshold is not fixed.
After trades resolve:
Strong recent performance → Threshold remains relaxed.
Weak recent performance → Threshold automatically increases.
This forces the model to demand greater conviction during difficult market conditions.
When active, an orange ▲ marker appears next to the threshold value inside the statistics table.
This indicates that the model has tightened its own standards due to recent underperformance.
Signal Logic & Cooldown
Signals are not generated continuously.
Instead, the indicator uses edge-detection logic.
Signals only trigger when probability crosses above the required threshold.
Cross Above Threshold → New Signal
Remain Above Threshold → No New Signal
Additionally, a cooldown period prevents repetitive signals in the same direction.
The default cooldown is 10 bars.
This reduces signal clustering and improves overall readability.
Reading The Statistics Table
The table provides a complete snapshot of model activity.
Bull Prob — Current bullish probability estimate.
Signal — Current directional bias.
Exp. Ret — Expected return estimate.
Anchor — Selected oscillator value.
Eff. Thresh — Current effective threshold.
The backtest section includes:
Total Signals
Win Rate
Cumulative PnL
Average Trade PnL
Profit Factor
Wins & Losses
These values serve as a reality check based on current settings and chart conditions.
How To Use The Indicator
Do not blindly chase every arrow.
The strongest opportunities occur when multiple components align.
Look for:
High Bull Probability
Positive Expected Return
Clear Trend Structure
Supportive Market Conditions
When Bull Probability and Expected Return disagree, consider that a warning sign and reduce conviction.
Training Window & Tree Selection
The training window controls how much recent history the model learns from.
Short Window = Faster Adaptation
Long Window = Greater Stability
The number of trees controls prediction smoothness.
More Trees = Smoother Predictions
Fewer Trees = Faster Computation
Default settings provide a balanced starting point for most markets.
ADX Filtering
Optional ADX filtering can be enabled to isolate signals during stronger trending environments.
This tends to perform particularly well on higher timeframes.
What This Isn't
A few honest disclaimers:
This is not a deep neural network.
This is not a full-depth Random Forest implementation.
This is not a guaranteed profit system.
This is not immune to changing market conditions.
The model uses depth-1 decision stumps due to Pine Script limitations.
While this prevents complex nonlinear interactions, it preserves the core ensemble learning principles that make Random Forests effective.
The indicator intentionally uses only a handful of carefully selected features rather than overwhelming the model with unnecessary inputs.
Wrapping It Up
The Machine Learning Random Forest Strategy combines legitimate ensemble learning concepts with practical market analysis.
By leveraging Random Forest classification, regression forecasting, adaptive probability thresholds, and rolling retraining windows, the indicator provides a unique framework for evaluating both direction and expected magnitude of future price movement.
Use it as a decision-support tool, combine it with sound risk management, and let probability—not prediction—guide your trading process. Indicador

The Strat Sequence Continuation / Reclaim Engine v1.0The Strat Sequence Continuation / Reclaim Engine
The Strat Sequence Continuation / Reclaim Engine is a body-close-based study designed to help traders review how specific Strat candle sequences have historically resolved on the selected chart timeframe.
This indicator combines two separate views:
1. **Markov Regime Permission Panel**
A regime-style table that evaluates recent price behavior and displays market state, return, transition probabilities, permission, and trade behavior context. This table can be turned on/off by the user.
2. **Strat Sequence Continuation / Reclaim Table**
A focused table that measures whether selected Strat sequences continued by body close or failed/reclaimed the relevant reference level.
The sequence table evaluates setups such as:
* Failed 2U → x
* Failed 2D → x
* F2U → 2D → x
* F2D → 2U → x
* F2U → 2D → 2D → x
* F2D → 2U → 2U → x
* 2-2U → x
* 2-2D → x
* 2-1-2U → x
* 2-1-2D → x
* 3-1-2U → x
* 3-1-2D → x
* 3H → x
* 3L → x
For bullish sequences, continuation is counted only when the next candle closes above the applicable reference candle high.
For bearish sequences, continuation is counted only when the next candle closes below the applicable reference candle low.
If price does not close beyond the reference level, the event is classified as reclaim/fail.
The table also includes:
* User-selected lookback
* Live setup candle read
* Live sequence watch
* Body-close decision rule
* Row visibility controls
* Minimum sample threshold filtering
* Optional bull/bear color coding
This tool is intended for historical sequence review, market context, and discretionary analysis. It does not predict future price movement, generate buy/sell signals, or provide financial advice. All outputs depend on the selected symbol, timeframe, lookback settings, and available chart history.
Indicador

Institutional Order Flow Signals [PMT]Institutional Order Flow Signals applies a Gaussian Naive Bayes classifier — trained entirely within Pine Script® v6 — to cumulative volume delta divergence in order to surface, in real time, three mutually exclusive market regime states: bullish re-alignment, bearish re-alignment, and order flow divergence.
The core question this indicator addresses is distinct from threshold-crossover approaches: given the current statistical pattern of delta momentum, price/CVD divergence, and delta slope, what is the posterior probability that the market is entering — or exiting — a directional institutional order flow regime?
――――――――――――――――――――――――――――――――――――――
🔷 WHAT IT MEASURES
🔸 Cumulative Volume Delta (CVD)
CVD is the running sum of intrabar net order flow — buy volume minus sell volume — estimated via the close-position formula: bull_vol = volume × (close − low) / (high − low). The cumulative series tracks persistent institutional buying or selling pressure independently of price direction, making it a first-order proxy for directional order flow without requiring exchange-level bid/ask data.
🔸 Three Z-Score Normalised Features
Each bar, the classifier receives three inputs derived from CVD and z-score normalised for cross-instrument compatibility:
F1 — CVD Momentum : rate of change of CVD over N bars, normalised by its rolling mean and standard deviation. Encodes how rapidly buying or selling pressure is accelerating relative to its own recent baseline.
F2 — Price/CVD Divergence : price rate of change minus CVD rate of change. A large positive value signals price rising while order flow is falling — the classic institutional distribution pattern. Near-zero values indicate price and flow agreement.
F3 — CVD Slope : linear regression slope of CVD over a short window, z-score normalised. Provides a direction-of-flow signal independent of F1's momentum measure, satisfying the Naive Bayes conditional independence assumption as closely as CVD-derived features can.
🔸 Market Regime Labels
Three mutually exclusive regimes are recognised. A bullish re-alignment bar is one where both price ROC and CVD ROC are positive — institutional flow and price confirm each other to the upside. A bearish re-alignment bar is the symmetric case. A divergence bar occurs when price and order flow point in opposite directions — historically associated with regime transitions and distribution/accumulation activity.
――――――――――――――――――――――――――――――――――――――
🔷 THE CLASSIFIER
🔸 Welford Online Learning
The classifier accumulates running sufficient statistics — count, mean, and variance — for each of the nine (feature × regime) combinations using Welford's numerically stable online update. No historical arrays are stored. The model's parameters shift gradually with each new bar, making it adaptive to changing market microstructure conditions without a fixed lookback window.
🔸 Gaussian Likelihood + Bayesian Posterior
Each feature is modelled as a Gaussian distribution under each class. The joint likelihood of the current feature vector is computed by multiplying the three per-feature probability densities under the Naive Bayes independence assumption. A class prior — updated empirically from observed regime frequencies — is combined with the joint likelihood via Bayes' theorem to produce posterior probabilities P(Bull | F1,F2,F3) and P(Bear | F1,F2,F3) for the current bar. A warmup gate suppresses signals until the classifier has accumulated statistically meaningful training observations.
――――――――――――――――――――――――――――――――――――――
🔷 SIGNALS AND DISPLAY
🔸 High-Conviction Buy — P(Bull) > 85%
A long signal fires when the bull posterior clears the configurable threshold, CVD momentum confirms, and price is above the trend EMA. The threshold is surfaced on the label itself, making the confidence level explicit at every entry rather than hidden inside an opaque signal.
🔸 Bear Signal — CVD Divergence
A short signal fires when the bear posterior clears threshold and F2 is in active divergence territory — price moving up while order flow is declining, or the symmetric distribution case. CVD divergence without posterior confirmation does not produce a signal; both conditions are required simultaneously.
🔸 Bull Regime Band — CVD Aligned
A fill band anchored to the trend EMA expands when the classifier assigns high posterior probability to a sustained bullish re-alignment regime. The opacity of the band scales with the posterior — faint during low-confidence periods, saturated when the classifier considers the regime firmly established.
🔸 Info Table
Live readout displays current bull and bear posteriors, CVD direction, and training bar count. The Trained N counter confirms the classifier has completed warmup before acting on any signal.
――――――――――――――――――――――――――――――――――――――
🔷 INPUTS
Classifier Lookback — minimum training bars before signals activate. Default 100.
Entry Posterior Threshold — minimum posterior required. 0.60 permissive; 0.70 default; 0.80 high-conviction only.
CVD Momentum Period — lookback for F1 and F2 rate of change.
CVD Slope Period — regression window for F3.
Z-Score Period — normalisation window applied across all three features.
Trend EMA Period — macro filter; long signals only fire above EMA, short signals below.
――――――――――――――――――――――――――――――――――――――
🔷 REQUIREMENTS AND LIMITATIONS
The classifier requires a warmup period before signals are valid. The CVD estimator is synthetic — derived from intrabar price position, not actual bid/ask data — and introduces noise on instruments with low liquidity or wide spreads. The Naive Bayes independence assumption is partially violated because all three features are CVD-derived; the posteriors function as relative confidence scores rather than calibrated frequentist probabilities.
――――――――――――――――――――――――――――――――――――――
Built natively in Pine Script® v6. No external libraries, no data feeds, no fixed lookback arrays. The Gaussian Naive Bayes classifier trains continuously from the chart's own bar history using Welford's online algorithm. Open source — Mozilla Public License 2.0. Indicador

Probabilistic Regime Tensor [JOAT]Probabilistic Regime Tensor
Introduction
Probabilistic Regime Tensor classifies market state into Trend, Mean Reversion, or Shock using logistic transforms of statistical inputs.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Trend Probability
Regression slope, variance ratio, and normalized return behavior feed the trend model.
2. Mean-Reversion Probability
Contracting variance ratio, weak slope, and autocorrelation behavior feed the reversion model.
3. Shock Probability
Volatility rank and fast/slow return divergence feed the shock model.
4. Probability Entropy
The three probabilities are normalized and entropy shows whether the classifier is decisive or uncertain.
pTrend = logistic(trendInput) / probabilitySum
Features
Three-state probability model
Trend, mean, and shock probabilities
Dominant confidence and entropy
Sparse regime labels
Movable quant HUD
Input Parameters
Statistical and fast windows
Dominant probability gate
Cooldown
Candle and HUD toggles
HUD position selector
How to Use This Script
Use PRT to decide which style of analysis is more appropriate: continuation, mean reversion, or volatility caution.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
PRT is original in using normalized logistic probabilities and entropy to classify market regime.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades
Indicador

Signal Forge [LuxAlgo]The Signal Forge indicator is a modular technical analysis engine that allows users to blend 11 distinct technical filters into a unified signal and backtest the results in real-time. This tool aims to simplify strategy development by providing a visual framework for testing indicator confluence and risk management settings without writing code.
🔶 USAGE
The script provides a flexible logic system for generating signals based on the alignment of multiple technical components. Users can toggle specific indicators on or off and choose between "strict" mode (requiring ALL active indicators to agree) or "any" mode (where ANY active indicator can trigger a signal).
Signals are displayed on the chart as glowing orbs connected to the price action. Each signal includes a real-time historical win rate label at the moment of entry, allowing for a visual audit of the strategy's performance over time.
🔹 Indicator Selection
The tool includes 11 harmonized indicators:
SMA Crossover
RSI Filter (Levels)
MACD Crossover
Supertrend
Stochastic (Trend-based)
Bollinger Bands (Basis Filter)
EMA Crossover
Awesome Oscillator
Parabolic SAR
CCI Filter
ADX/DI Filter
🔹 Risk Management
Users can enable ATR-based Take Profit, Stop Loss, and Trailing Stop levels. When active, these levels are plotted on the chart. The Trailing Stop feature includes a specialized gradient fill that highlights the "breathing room" between the price and the exit level.
🔶 DETAILS
🔹 Dashboards
The script features two distinct dashboards to provide a comprehensive overview of the strategy:
Indicator Dashboard: Shows the real-time bullish/bearish status of all 11 indicators, their individual "standalone" win rates visualized with histograms, and their current toggle status.
Performance Dashboard: Provides a high-level summary of the combined strategy performance, including Net Profit %, Win Rate, Profit Factor, and Total Trades.
🔹 Logic Harmonization
To ensure different indicator types work together effectively, mean-reversion tools like the Stochastic and Bollinger Bands have been reconfigured to act as trend-confirmation filters. For example, the Stochastic signal is bullish when the %K is in the upper half of its range (> 50) rather than looking for oversold extremes, ensuring it aligns with trend-following components like Moving Averages.
🔶 SETTINGS
🔹 Signal Logic
Require All Enabled Indicators to Align: When enabled, every checked indicator must have the same directional bias to generate a signal.
🔹 Risk Management (ATR)
ATR Length: The period used for volatility-based exit calculations.
Take Profit/Stop Loss/Trailing Stop: Toggles and multipliers for managing trade exits.
🔹 Visuals
Orb Distance (ATR): Controls the vertical offset of signal orbs from the price candle.
Orb Base Size: Adjusts the thickness and glow intensity of the signal markers.
🔹 Dashboards
Dashboards: Enable or disable the table overlays.
Position/Size: Options to move and scale the Indicator and Performance tables to fit different screen layouts.
Indicador

MLP - BTC Breakout Probability [Deep Learning] [Open Source]I trained a single Multilayer Perceptron on 13 years of Bitcoin price history and open-sourced the result. Not because it's perfect, but because the idea is worth sharing.
The concept is simple.
Most breakout strategies are rule-based. Fixed levels, static conditions. This one is different, instead of predicting direction, the model learned the distribution of Bitcoin's daily price moves. You pick a threshold, it gives you the probability. Same model, any level.
How to use it
Pick a percentage threshold , by doing that you're asking the model to evaluate. When price breaks that level and the model is showing meaningful confidence, a label is shown on the chart.. Daily only. BTC only.
Under the hood
A lightweight Multilayer Perceptron (MLP) trained on ~4,700 daily candles of raw OHLC data from May 2009 to May 2022 . The architecture is two hidden layers (16→8), ReLU activations throughout, and a sigmoid output that squashes the result into a clean 0–1 probability score. ReLU keeps the internal representations sparse and non-linear, sigmoid makes the output as a probability.
What makes this interesting is that the model didn't just learn a raw number, it learned the underlying distribution of Bitcoin's daily price moves. That's what allows a single model to answer probability questions across different thresholds rather than being hardcoded to one fixed level.
The output isn't a prediction, it's a calibrated belief about where price is likely to go, derived from 13 years of market structure.
Honest limitations
Fat tails eat this model alive. The features are correlated and the model has no concept of liquidity. It underestimates the extremes.
Daily timeframe only. Bitcoin only. Long only.
This was built as a personal project, mostly for fun and to serve as a working example of how ML concepts can be applied to market data.
Disclaimer
This indicator is provided for educational and informational purposes only. It does not constitute financial advice, trading recommendations, or a guarantee of future results. Past performance does not predict future returns. You alone are responsible for your trading decisions. Always test thoroughly in a simulated environment before trading with real capital. Indicador

Predictive Breakout Channels | GainzAlgoAbout the Indicator
The Predictive Breakout Channels indicator is a predictive machine-learning engine designed to map institutional market structure and calculate the statistical probability of impending breakouts. Instead of relying on traditional lagging indicators, the system dynamically anchors itself to major market pivots using a rolling Linear Regression Channel framework.
By evaluating a combination of localized trend correlation, relative strength, institutional volume distribution, and variance metrics, the engine projects real-time target zones while simultaneously calculating a directional probability score directly on the chart the moment a breakout occurs.
Dynamically anchors to institutional pivot structures
Uses a rolling Linear Regression Channel
Evaluates trend correlation, RSI, and variance metrics
Projects real-time ATR-based target zones
Calculates breakout probability scores directly on-chart
Designed to distinguish genuine breakouts from fakeouts
The Core Theory of Breakouts
Markets spend the majority of their time consolidating rather than trending. During these equilibrium phases, liquidity pools accumulate on both sides of the range while volatility compresses beneath the surface.
A breakout represents the structural transition from equilibrium into expansion.
When institutional order flow aggressively consumes localized liquidity, price breaches structural boundaries and volatility rapidly expands outward. The challenge for traders has never been identifying that a breakout occurred — the real challenge is determining whether the move has enough structural backing to sustain itself or whether it is simply a liquidity trap designed to reverse shortly afterward.
The Predictive Breakout Channels engine was specifically designed to address that exact problem.
The Logic Engine — ANOVA & The Power of Variance
To help solve the fakeout problem, this engine incorporates ANOVA, short for Analysis of Variance.
Originally developed by legendary statistician Ronald Fisher, ANOVA has historically served as one of the foundational statistical tools used throughout medical research, behavioral science, and high-level quantitative analysis. Its purpose is to determine whether differences between groups of data are statistically meaningful or simply random noise.
In this indicator, that same statistical framework is adapted directly to price action.
The engine continuously evaluates the structural differences between groups of candle data — including highs, lows, and closes — in real time in order to measure the quality and significance of underlying market expansion.
The Niche Secret — F-Statistic & Volatility Compression
Quantitative modeling revealed a particularly powerful characteristic regarding variance measurements inside the ANOVA engine.
When the raw ANOVA F-Statistic becomes drastically elevated, or when the standardized Z-Score breaches extreme thresholds such as 2 standard deviations, it often signals a state of hyper-compressed market consolidation.
Think of it like winding a mechanical spring tighter and tighter.
As variance compresses to rare statistical extremes, market energy begins building beneath the surface. Eventually that stored pressure releases through aggressive volatility expansion.
This variance surge acts as a leading indicator for impending volatility before the actual breakout even occurs.
However, variance alone cannot determine directional bias. Because of this, the engine layers in additional confirmation modules such as RSI and Trend Correlation Length to help determine whether institutional momentum is favoring bullish or bearish continuation.
Indicator Settings & Customization
The system is fully modular, allowing traders to fine-tune the engine based on their preferred asset class, timeframe, or trading style.
Anchored LinReg Channel Settings: Customize left and right pivot lookbacks alongside standard deviation multipliers to control how the channel dynamically anchors itself to price structure.
ANOVA Confirmation: Fine-tune the lookback period and baseline Z-Score thresholds required for breakout validation.
Feature Filters: Adjust RSI and Trend Correlation baseline lengths to make directional probability scoring more aggressive or more selective.
High Variance Alert Label: Disabled by default. When enabled, the engine plots visual warning labels whenever variance compression reaches statistically elevated levels.
Include HTF Trend Filter: Controls whether breakout signals are filtered using higher timeframe trend conditions.
The Strategic Dilemma — Higher Timeframe Trend Filtering
The indicator includes a dedicated HTF Trend Filter toggle that leverages higher timeframe EMA spreads to determine whether lower timeframe breakout signals align with broader institutional trend conditions.
Choosing whether to enable this filter depends entirely on the type of market environment you prefer trading.
1. HTF Filter ON — Trend Following Regime
Filters out a significant amount of lower timeframe noise
Produces fewer but statistically stronger breakout signals
Aligns entries with broader institutional money flow
Increases overall follow-through probability
However, because the engine becomes heavily biased toward the macro trend, it may intentionally suppress counter-trend reversals or early-stage trend shifts.
2. HTF Filter OFF — Agile / Mean-Reversion Regime
Allows the engine to react dynamically in both directions
Captures sharp intraday reversals more aggressively
Performs well in swinging or range-bound environments
Increases breakout frequency substantially
The tradeoff is naturally higher exposure to lower timeframe noise and shorter average continuation during counter-trend conditions.
How to Trade with the Indicator
When price closes outside the Linear Regression Channel while simultaneously satisfying the statistical validation criteria, the engine prints a breakout entry signal alongside a projected probability score.
At the same time, the system projects 4 distinct ATR-based Target Zones labeled T1 through T4.
Aggressive Traders: May choose to execute immediately on the breakout close while targeting T2 or T3 with structural stops positioned back within the channel.
Conservative Traders: May choose to use the Probability Score as a filter or wait for a localized retest of the broken channel boundary before entering.
The High Variance Play
When the High Variance Alert label appears, traders should avoid impulsively chasing the immediate candle.
Instead, the label should be treated as an early warning that volatility expansion is rapidly approaching.
The preferred approach is to wait for the subsequent confirmed breakout signal, then trade the resulting momentum expansion into the projected target zones.
High variance does not predict direction
It predicts volatility expansion
Directional confirmation comes afterward through breakout validation
Wrapping It Up
The Predictive Breakout Channels indicator bridges quantitative data science with classic market microstructure principles.
By treating volatility as a measurable statistical property rather than a visual guessing game, the engine helps traders identify where the market is coiling, estimate the probability of expansion, and navigate breakout environments using structured statistical confirmation instead of emotion.
Whether used for momentum continuation, volatility expansion, or intraday breakout trading, the system was designed to provide traders with a clearer framework for distinguishing meaningful expansion from market noise. Indicador

Probability Horizon - Bayesian SVJD Model# Probability Horizon — Bayesian SVJD Model
## What it does
Probability Horizon is a forward-looking probability projection tool. It does **not** generate buy or sell signals, does **not** act as a strategy, and does **not** place orders. Its single purpose is to display, at each bar, where price **may** be over a user-set horizon, drawn as a forward cone with three percentile lines (25%, 50%, 75%) plus an 8-row diagnostic dashboard.
The cone is the visual answer to two questions the indicator computes every bar:
1. **How wide should the distribution of forward outcomes be?** — set by expected total variance over the horizon.
2. **Should the distribution tilt up or down?** — set by a Bayesian-averaged probability of an up-move.
The wider the cone, the more uncertain the model is. The more the cone tilts, the more directionally confident the model is. A flat, narrow cone means "I expect range-bound, low-vol conditions." A wide, steeply tilted cone means "I expect a directional move under elevated variance."
## Why these components are combined (justification for the mashup)
This script combines several quantitative methods — KAMA, z-score, Haar wavelet, Kalman filter, Hamilton regime-switching, Hawkes process, Heston stochastic volatility, Merton jump-diffusion, Bayesian model averaging, and a calibration tracker. To a reviewer this can look like a collection of indicators bolted together, but it is not. It is **one** statistical model — a Stochastic Volatility Jump-Diffusion (SVJD) framework — whose pieces are mathematically required to produce a forward probability distribution.
Each component has a specific structural role:
- **Forward variance estimation.** A probability cone needs a forward-variance number. The naive choice is realized volatility × √horizon (pure Brownian motion), but this ignores two well-documented facts about financial returns: variance is mean-reverting (Heston, 1993) and returns have fat tails from discrete jumps (Merton, 1976). The Heston + jump-diffusion combination addresses both. The script uses the Heston integrated-variance closed form for the mean-reverting diffusion component, adds a Merton jump-variance contribution, and optionally adds a vol-of-vol uncertainty term. The result is a horizon-dependent variance estimate that dynamically narrows when volatility is elevated (expected to decay back to mean) and widens when volatility is depressed (expected to rise).
- **Directional probability.** To tilt the cone, a probability of direction is required. A single signal is unreliable, so five orthogonal sub-models each output their own P(up):
- A short-term KAMA-trend model
- A z-score mean-reversion model
- A Haar wavelet decomposition model (price denoised into trend + cycle + noise; signal fires only on the trend band)
- A Kalman-adaptive smoothing model (smoothing factor adapts to noise level in real time)
- A Hamilton 3-state regime model with Gaussian observation likelihoods (Bull / Bear / Range)
- **Sub-model combination.** The five P(up) values are combined via Bayesian model averaging with online weight updates. Each bar, after a fixed evaluation horizon, every sub-model is scored by log-loss against the actual outcome. Weights update via exponential decay: a model that predicted correctly gains weight; a model that failed loses weight. A minimum weight floor prevents any model from being silenced completely, so it can recover if its regime returns. Weights are renormalised to sum to 1.
- **Crisis dampening.** A Hawkes self-exciting point process monitors volatility clustering. Each large absolute return is treated as an event that boosts the process's intensity by α and decays exponentially at rate β. When intensity rises above a threshold multiple of its baseline, the final Bayesian probability is shrunk toward 0.5 — the higher the intensity, the stronger the shrinkage. This is how the model says "I have no idea — treat this as a coin flip" during regime breaks.
- **Self-correcting calibration.** A calibration tracker logs every prediction and checks the realized outcome after a fixed horizon. Predictions are binned by predicted probability (50–60%, 60–70%, etc.). If a bin's actual historical hit rate is below its predicted midpoint, future predictions in that bin are shrunk further toward 0.5. This is the model's honesty mechanism: it learns from its own miscalibration and tones itself down where it has been overconfident.
Each component answers a specific structural question. Remove any one and a specific capability disappears: no Heston → cone width does not adapt to vol regime; no calibration → no self-correction; no Hawkes → no crisis dampening; no Bayesian averaging → one model dominates and the system becomes brittle.
## How the components interact (data flow)
Every confirmed bar, the script executes the following pipeline:
1. **Measure** five raw market dimensions: KAMA slope, z-score vs trend, realized-vol percentile, OBV/price divergence, higher-TF trend.
2. **Each sub-model** maps its directional bias and strength to a probability in . The maximum single-model probability is capped at 0.60 because empirical calibration on multiple markets showed that anything higher is overconfident.
3. **Bayesian model averaging** combines the five sub-model probabilities into a single raw P(up), weighted by each sub-model's recent log-loss accuracy.
4. **Hawkes modifier** is applied: if intensity is above its warning threshold, the raw P(up) is pulled toward 0.5 in proportion to how far above threshold the intensity is.
5. **Calibration shrinkage** is applied: the post-Hawkes probability is checked against its calibration bin's historical hit rate, and shrunk further toward 0.5 if that bin has been overconfident.
6. **Forward variance** is computed separately: Heston integrated variance + Merton jump variance + optional vol-of-vol uncertainty, all over the projection horizon.
7. **The cone is drawn** with width set by the square root of forward variance and tilt set by the final shrunk probability. Three percentile lines (P25, P50, P75) are plotted from the current bar to the horizon endpoint.
Direction (sub-model probabilities → Bayesian average → Hawkes modifier → calibration shrinkage) is one half of the pipeline. Variance (Heston + jumps + vol-of-vol) is the other half. They meet at the cone, where one determines tilt and the other determines width.
## How to use it
**On the chart.** The cone shows the model's current view of the forward distribution. The P50 line is the median expected level given the implied drift. The P25 and P75 lines bracket the interquartile range. If P25 and P75 are roughly equidistant from current price, the model has no strong directional view; if the cone tilts noticeably up or down, the Bayesian probability favours that direction. A wider cone means more uncertainty; a narrower cone means tighter forward variance.
**The optional Monte Carlo cloud** (off by default) overlays bootstrap-resampled forward paths drawn from the asset's actual recent returns. Unlike the cone, it makes no Gaussian assumption — it shows the empirical distribution of forward outcomes given the asset's own recent return history.
**The 8-row dashboard** (top-right) is where the model exposes its full state:
- **Row 1 — Verdict.** Current direction (Bull / Bear / Neutral) and final P(up) percentage.
- **Row 2 — Direction.** A 10-character probability bar plus the size of the calibration shrinkage applied in percentage points.
- **Row 3 — 5 Models.** Up/down icons for each sub-model and the agreement count (e.g., "4/5 agree"). Trust the verdict more when 4 or 5 of 5 agree; trust it less when only 3 of 5 agree.
- **Row 4 — Regime.** Combined market regime (Quiet Bull / Quiet Bear / Volatile-Range / Crisis) plus the Hamilton dominant state.
- **Row 5 — Vol.** Volatility state vs long-run mean: HIGH (above mean, cone narrowing as vol decays), LOW (below mean, cone widening as vol rises), or AT MEAN. Includes the current sigma.
- **Row 6 — Risk.** Hawkes status: ✓ calm or ⚠ CRISIS. When CRISIS fires, the probability has been shrunk toward 0.5.
- **Row 7 — Honesty.** This is the most important diagnostic. It shows the actual historical hit rate for predictions in the 50–60% probability bin, with a Wilson confidence interval. If the system has predicted 55% many times and the actual rate is 53–58%, it is well-calibrated. If actual is below 50%, the system is currently overconfident and shrinkage is active.
- **Row 8 — Samples.** Total confirmed predictions and a trust level (low / warm-up / OK). Trust the cone less when total samples are below 50; trust it most when samples exceed 200.
## Suitable timeframes
The script auto-scales internal lookbacks to the chart timeframe relative to a 15-minute reference, so the same defaults work across 15-minute, 1-hour, 4-hour, and daily charts without manual tuning. Below 15 minutes the Hamilton 3-state model is automatically disabled because sample sizes become too small for reliable likelihood estimation; the other four sub-models continue to operate.
## What is original
Combining KAMA, wavelets, Kalman, Hamilton, Heston, Merton jumps, and a Hawkes process is not by itself new — these are all published methods. The original aspects of this script are:
- The **specific combination**: a five-model Bayesian ensemble for direction, with Hawkes-process crisis dampening and a self-correcting calibration tracker, all wrapped around a Heston + jump-diffusion variance estimate. I am not aware of a public Pine Script that combines all of these into a single probability cone with this data flow.
- The **calibration shrinkage mechanism**: the model logs every prediction, scores it after a fixed horizon, and applies bin-specific shrinkage to future predictions in bins where it has been overconfident. This is a self-correcting honesty layer that runs entirely on-chart, with Wilson confidence intervals and optional regime-specific calibration tables (Bull / Bear / Range).
- The **transparent diagnostic dashboard**: rather than hiding the model behind a single line, the dashboard exposes the verdict, model agreement, regime, vol state, crisis indicator, calibration quality, and sample size in eight rows. Users can see at a glance not only what the model thinks, but how much to trust it.
## Limitations (please read)
- **Pine Script cannot perform true maximum-likelihood estimation.** Heston and jump-diffusion parameters are estimated using approximation methods (AR(1) regression on log-variance, exponential moving averages for jump moments, rolling averages for long-term variance). The directional behaviour is correct — when vol is high, the cone narrows; when jumps are frequent, the cone widens — but exact parameter values are not equivalent to those a quantitative research desk would produce with MLE on tick data.
- **OHLCV data only.** No order-book data, no alternative-data feed, no options input, no fundamental input.
- **Calibration needs sample accumulation.** The Honesty row shows "warming up" until at least ~30 confirmed predictions have matured. Pine has no cross-session persistence, so calibration is rebuilt from chart history each time the indicator loads on a new chart.
- **Monte Carlo is deterministic.** Paths use a Linear Congruential Generator seeded by bar_index for reproducibility within a session. The same chart at the same moment produces the same cloud. This is intentional.
- **This is a probability indicator, not a strategy.** There are no backtest results, no equity curve, no position management. The script cannot tell you what to do; it only tells you what its model currently thinks the distribution of forward outcomes is.
- **Past calibration does not guarantee future calibration.** Market regimes change, parameters drift, and the cone should be treated as a visualisation aid rather than a prediction.
## Inputs of note
The defaults work without modification on most liquid instruments at most timeframes. Inputs worth knowing:
- **Auto-scale lookbacks** (on by default) — keeps the same defaults usable across timeframes.
- **Bayesian learning rate η** (default 0.15) — how fast sub-model weights adapt. Higher = faster but noisier.
- **Min Bayesian Probability** (default 0.62) — the threshold the dashboard uses to call a bar "Bull" or "Bear" rather than "Neutral".
- **Heston κ floor / ceiling** — bounds the mean-reversion-speed estimate. Defaults (0.02 to 0.30) handle most markets.
- **Hawkes warning threshold** (default 2.0× baseline) — when crisis dampening kicks in.
- **Monte Carlo Cloud** (off by default) — overlays bootstrap paths. Turn on if you want an empirical (non-Gaussian) view of forward outcomes alongside the cone.
## Disclaimer
This script is published for educational and analytical purposes only. It does not constitute financial advice, investment advice, a recommendation to buy or sell any financial instrument, or a solicitation of any transaction. The author is not a registered investment adviser and nothing in this script should be construed as personalised investment guidance.
Past performance does not guarantee future results. The probability projections shown by this indicator are model outputs, not forecasts of what will actually happen. Trading and investing involve substantial risk of loss and are not suitable for every investor. Users are solely responsible for their own trading decisions and for verifying that any approach is appropriate for their personal financial situation, risk tolerance, and applicable regulations.
The author and Market_Logic_India accept no liability for any losses, damages, or trading outcomes resulting from the use, misuse, or interpretation of this script. Use at your own risk.
Indicador

Nyx Transition Corridor [JOAT]Nyx Transition Corridor
Introduction
Nyx Transition Corridor is an open-source probabilistic regime corridor. It estimates whether the current bullish, bearish, or neutral state has recently tended to persist, then draws adaptive volatility corridors around price. The indicator is built for context, probability, and controlled visualization rather than aggressive signal clutter.
Core Concepts
1. Regime State
The script classifies each bar as bullish, bearish, or neutral using EMA alignment, adaptive basis location, and return behavior.
2. Rolling Transition Model
Recent state transitions are counted to estimate continuation probability for the current state.
pBullBull = math.sum(fromBull * toBull, transitionLen) / math.sum(fromBull, transitionLen)
3. Adaptive Basis
The basis reacts faster when price movement is efficient and slower when the market is choppy.
4. Probability Corridor
ATR, volatility rank, and continuation probability determine the corridor width. Outer rails identify stretched conditions.
5. Compact Execution Rails
Optional small rails mark educational entry, stop, and targets when a probability reclaim or continuation event occurs.
Features
Three-state regime model: Bull, bear, and neutral states
Transition probability: Rolling persistence estimate for current state
Adaptive basis: Efficiency-weighted smoothing
Volatility-ranked corridor: Bands expand and contract with market stress
Confirmed HTF filter: Optional higher-timeframe EMA uses confirmed previous HTF data
Compact trade rails: Smaller educational rails to reduce chart obstruction
Dashboard: Shows probabilities, spread, efficiency, volatility rank, and HTF state
Input Parameters
Adaptive basis length controls centerline memory
Transition memory controls probability stability
Continuation threshold controls signal selectivity
Rail settings control optional educational projections
How to Use This Indicator
Step 1: Read the regime
The dashboard shows whether the model is bullish, bearish, or neutral.
Step 2: Compare probabilities
Large spreads between bull and bear odds indicate clearer directional context.
Step 3: Use the corridor
The corridor shows where price is trading relative to the adaptive probability field.
Indicator Limitations
Transition probabilities are historical estimates, not forecasts
Neutral markets can persist even when price briefly crosses the basis
The optional rails are visual projections and not trading advice
Originality Statement
Nyx Transition Corridor combines a state-transition model, efficiency-adjusted basis, volatility-ranked width, confirmed HTF filtering, and compact execution visuals. Its purpose is to map probabilistic state context, not to duplicate a standard moving-average band.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Probability estimates are based on historical state transitions and do not predict future behavior.
-Made with passion by jackofalltrades
Indicador
