AetherEdge - Gaussian Process Bands🖊️ Overview
AE-GAUSS models price as a Gaussian Process and draws the predictive mean plus its uncertainty (±1σ, ±2σ) as nested translucent bands — a "fog of probability" that narrows where the model is confident and widens where it isn't. When price punches outside the 2σ band and snaps back, it fires a mean-reversion BUY/SELL as a statistically extreme excursion. It implements Gaussian Process Regression (GPR), a genuine Bayesian machine-learning method, the numerically-stable way without a matrix inverse.
🔶 Key Features
Gaussian Process Regression (GPR): models price as a stochastic process
RBF kernel + Cholesky decomposition: numerically-stable exact GP prediction
Linear detrend: trend-following extrapolation
Uncertainty bands: nested ±1σ / ±2σ "fog"
Volatility-adaptive kernel: σf scaled by ATR so bands breathe
2 signal modes: 2σ excursion reversion, or predictive-mean cross
Fit-quality tracking: online monitoring of prediction error
HUD showing σ-position gauge and z-score
Per-event 2σ excursion and signal alerts
🧠 Technical Architecture
This implements Gaussian Process Regression (GPR). Training is the last N prices; a linear trend is removed by least squares first, the GP models the stationary residual, and the trend is added back to the forecast. The RBF kernel k(i,j) = σf²·exp(−(i−j)²/2ℓ²) builds the N×N covariance K (+ σn² noise on the diagonal). Cholesky K = LLᵀ solves the linear systems K·α = y and K·v = k* by forward/back substitution (avoiding a matrix inverse — numerically stable). At x* = N (current bar), predictive mean μ* = trend + kᵀα and variance σ² = σf² − kᵀv. σf is ATR-scaled so band width changes with volatility. z-score = (close − μ)/σ* measures the statistical position. Signals fire when price exits the ±2σ band and re-enters, or crosses the predictive mean. GP computation runs on confirmed bars only.
⚙️ Recommended Settings & Tuning Guide
Training Points (N) 16 is a starting point — cost is O(N³), keep modest; lower if your chart lags (min 6). Length Scale (ℓ) 5 is RBF smoothness in bars — larger is smoother and longer-memory, smaller is local and reactive. Signal Amplitude 1.0×ATR is kernel signal std σf, setting the band's vertical scale. Observation Noise 0.4×ATR is σn — higher gives a smoother mean, wider bands, more tolerance. Signal Mode "2σ reversion" is mean-reverting; "Mean cross" is more trend-following.
💡 How to Use in Practice
Apply to chart and fog-like uncertainty bands appear around the predictive mean. Narrow bands mean the model confidently predicts price; wide bands mean uncertainty. When price punches through the lower 2σ band it's a statistically rare oversold — buy on the re-entry. Vice versa above. The HUD's "price σ-position" gauge shows where price sits in the prediction (● position), and the z-score shows how many σ it deviates. Smaller "fit error" means the model fits well, raising signal reliability. Raising length scale gives smooth swing bands; lowering gives reactive ones. In trends the predictive mean follows the trend; in ranges band-edge reversions work.
⚠️ Important Notes
GPR is a genuine machine-learning method (Bayesian non-parametric regression). To stay inside Pine's compute budget, N is kept small and the kernel hyper-parameters (ℓ, σf, σn) are user-set (with ATR scaling), not marginal-likelihood-optimized. The GP math, however, is exact for the chosen N. This indicator is the most compute-heavy of the set, O(N³) per bar; lower N if your chart is slow. GP computation runs on confirmed bars only and does not repaint, but real-time bars show the last confirmed value. All signals are probabilistic decisions based on historical data and do not guarantee future profits.
🚨 Disclaimer
This indicator is provided for educational and informational purposes only and does not constitute financial or investment advice. No signal guarantees future profit, and past performance does not indicate future results. All trading decisions are made at your own risk. Indicator

AetherEdge - Hidden Markov Regime🖊️ Overview
AE-HMM treats the market regime as a hidden state you can't observe directly (Bull/Bear/Range) and infers each state's probability from observable returns using a Hidden Markov Model's forward algorithm. The background bleeds a continuous "mood gradient" — green when Bull dominates, red for Bear, neutral grey for Range — visualizing the market's current mood. Online EM learns each state's emission parameters, auto-adapting to what Bull/Bear/Range look like on this instrument.
🔶 Key Features
3-state Hidden Markov Model: probabilistic Bull/Bear/Range via forward algorithm
Gaussian emission likelihood: each state has a return distribution
Sticky transition matrix: tunable regime persistence
Online EM learning: auto-learns each state's mean/variance from data
Sign clamping: keeps Bull>0, Bear<0, preventing label switching
Mood gradient background: red→grey→green continuum visualizing sentiment
State-colored EMA: moving average color changes with the most-likely state
State probability stack (optional): probability mass of 3 states below price
BUY/SELL on most-likely-state transitions
HUD showing each state's probability and learned parameters
Per-event alerts
🧠 Technical Architecture
This implements an HMM forward algorithm. Three hidden states (Bull/Bear/Range) each carry a Gaussian emission b_j(o) over ATR-normalized returns, with a sticky transition matrix A (diagonal = persistence). The scaled forward recursion γ_t(j) ∝ [Σ_i γ_{t-1}(i)·A ]·b_j(o_t) computes the filtered posterior of each state per bar, normalized for stability. Online EM updates emissions via μ_j ← μ_j + η·γ_j·(o−μ_j) and σ²_j ← σ²_j + η·γ_j·((o−μ_j)²−σ²_j), sign-clamping Bull mean positive and Bear mean negative to preserve label meaning. Most-likely state = argmax γ. The bull-bear score = γ_bull − γ_bear drives the background gradient. Signals fire when the most-likely state transitions into Bull/Bear and probability exceeds threshold. State updates occur on confirmed bars only — no repaint.
⚙️ Recommended Settings & Tuning Guide
Regime Persistence 0.90 is a starting point — the transition matrix diagonal (regime stickiness). Higher = smoother, slower state changes; lower = more sensitive. Return Smoothing 1 smooths the observed return; raise for noisy instruments. Learn Emission Parameters ON is recommended; Learning Rate 0.03 is standard speed. Initial |Bull/Bear Mean| 0.5 sets the initial separation of Bull(+)/Bear(−) emission means. Min State Probability to Signal 0.4 requires the new dominant state to reach this probability before signaling — higher means only high-conviction transitions. Min Variance Floor bounds the variance.
💡 How to Use in Practice
Apply to chart and the background colors continuously with the market mood. Deeper green means higher Bull-state conviction, deeper red means Bear, pale grey means Range (no direction). The state-colored EMA shows the most-likely regime at a glance. Check STATE POSTERIOR in the HUD for the three probabilities; a sharp rise in Bull probability overtaking Bear marks a turning point. LEARNED EMISSIONS shows the model-learned mean return and volatility of Bull/Bear/Range for this instrument. Standing aside while Range probability is high, and entering once Bull/Bear is clear, is effective. Combining with other trend tools and trading only when regimes agree is another approach.
⚠️ Important Notes
This uses an online-EM approximation (not full Baum-Welch EM), a filtered forward posterior (not the Viterbi algorithm), Gaussian emissions, and sign-clamped labels. The forward-algorithm math, however, is the genuine HMM recursion. With 1-D return observations, Bull/Bear are clear by sign, while Range is represented as a near-zero mean. Online learning needs convergence time per instrument; emissions are not optimized initially. All regime estimates are probabilistic decisions based on historical data and do not guarantee future profits.
🚨 Disclaimer
This indicator is provided for educational and informational purposes only and does not constitute financial or investment advice. No signal guarantees future profit, and past performance does not indicate future results. All trading decisions are made at your own risk. Indicator

AetherEdge - Bayesian Changepoint Shift🖊️ Overview
AE-SHIFT detects trend reversals as a probability using Bayesian Online Changepoint Detection (BOCPD, Adams & MacKay 2007). Rather than "did a moving average cross?", it asks "what is the probability that the current price regime just ended?" — computing a full posterior distribution over how long the current trend has lasted (run-length). An adaptive layer learns the hazard (reversal frequency) online from the spacing between changepoints, auto-adapting to each instrument's rhythm.
🔶 Key Features
Faithful BOCPD: sequential Bayesian update of the run-length posterior
Gaussian predictive likelihood + Welford online statistics: probabilistic evaluation of each regime hypothesis
Adaptive hazard learning: auto-estimates expected run-length λ from changepoint intervals
Quantifies changepoint probability 0-100%: clear reversal signal
Multi-layer glow rendering: luminous vertical lines at changepoints
Run-length distribution mini-heatmap: visualizes the distribution shape in the HUD
Probability-linked background pulse and segment trend line
BUY/SELL markers + per-event alerts
🧠 Technical Architecture
This implements the core BOCPD algorithm. Each bar maintains P(run-length = r | data) for r = 0..Rmax, with each hypothesis carrying Welford online statistics (mean/variance) of returns inside the segment. For each new observation, a Gaussian predictive likelihood π(x|r) is computed, weighted by the hazard function H = 1/λ, propagated forward (growth: r→r+1), with changepoint mass collapsed to r=0 and normalized. P(r=0) is the changepoint probability. Observations are ATR-normalized returns for scale stability. Adaptive hazard re-estimates λ from a moving average of detected changepoint intervals, dynamically adjusting the hazard. Signals fire when changepoint probability exceeds threshold + peaks + new segment direction. State updates occur on confirmed bars only to avoid repainting.
⚙️ Recommended Settings & Tuning Guide
Expected Run Length (λ) 50 is a starting point — larger for rare-reversal instruments and higher timeframes, smaller for frequently-flipping ones. Adaptive Hazard Learning ON is recommended to auto-learn the instrument's rhythm. Max Run Length Tracked 60 is a compute trade-off; raise to track longer regimes at higher cost. Changepoint Probability Threshold 0.25 baseline; 0.15 more sensitive, 0.4 stricter. Prior Variance / Observation Noise Variance tune the predictive distribution; raise Observation Noise for noisy instruments. Direction Confirmation 3 sets reversal-direction sensitivity.
💡 How to Use in Practice
Apply to chart and changepoints print luminous vertical lines with BUY/SELL labels. The glowing sub-band below price shows changepoint probability in real time — the hotter it glows, the nearer a reversal. The HUD's RUN-LENGTH DIST section is most important: high r=0 (reset) probability means a reversal is imminent, while dense r=21+ means a stable trend continues — read market state from the distribution shape. A sudden drop in expected run-length is a reversal precursor. The adaptive λ value tells you how many bars, on average, this instrument runs between reversals. Combining with other trend indicators and entering only when changepoint probability is high is effective.
⚠️ Important Notes
This is a truncated approximation of BOCPD (run-length truncated at Max) using a Gaussian predictive likelihood (a simplification of the full Student-t conjugate). The adaptive hazard is a heuristic estimate. It is classical sequential Bayesian inference — not deep Bayesian methods or machine learning — but the core BOCPD recursion is faithful to the original paper. Changepoint probability indicates the "possibility" of a reversal, not a certain prediction. Estimates become unstable in extreme volatility or with little initial data. Compute scales with the run-length limit; lower Max Run Length Tracked if it's heavy.
🚨 Disclaimer
This indicator is provided for educational and informational purposes only and does not constitute financial or investment advice. No signal guarantees future profit, and past performance does not indicate future results. All trading decisions are made at your own risk. Indicator

AetherEdge - Wavelet Multi-Resolution🖊️ Overview
AE-WAVE decomposes price into multiple frequency scales using the à trous ("with holes") wavelet transform and reconstructs a clean "true price" by removing high-frequency noise. The scales are drawn as stacked translucent ribbons — a "frequency strata" of the market — revealing its hierarchical structure from raw chatter (top layer) to macro trend (bottom). Thanks to perfect reconstruction, denoise strength 0 means zero lag; higher values mean smoother. An adaptive layer learns each band's predictive power online.
🔶 Key Features
à trous wavelet decomposition: causal decomposition into 5 frequency scales
Soft-threshold denoising: removes high-frequency noise while preserving structure
Perfect reconstruction: denoise 0 = raw price (zero lag), strength tunes smoothness
3 scaling filters: B3 Spline (smoothest) / Linear / Haar (sharpest)
Adaptive scale reliability: learns online which bands predict
Frequency strata rendering: high freq thin/light, low freq thick/deep stacked ribbons
High-frequency bias: extra denoising on noise-heavy high-freq bands
BUY/SELL on denoised slope flip + macro trend filter
HUD showing band energy, reliability, dominant band
Per-event alerts
🧠 Technical Architecture
This implements the à trous (starlet) wavelet transform. From c0 = price, each scale c_{j+1} smooths c_j with a scaling filter (B3 spline /16, etc.), spacing the filter taps by 2^j bars (causal, past only). Detail w_j = c_{j-1} − c_j is the band component. The telescoping identity c0 = c_J + Σ w_j means reconstruction equals raw price exactly with no thresholding (zero lag). Each detail is soft-thresholded w' = sign(w)·max(|w|−λ,0) (λ = estimated noise σ × strength × high-freq bias), reconstructed as denoised = c_J + Σ(thresholded w_j). The adaptive layer scores each scale's detail sign against forward returns, learning reliability via EWMA. Confidence blends reliability, trend agreement, and low noise. Signals fire on denoised slope flip + macro trend direction, or on a macro trend cross.
⚙️ Recommended Settings & Tuning Guide
Wavelet Levels (J) 5 is a starting point — higher for a smoother macro trend. B3 Spline filter is smoothest and common; Haar for faster response in ranges; Linear in between. Denoise Strength 1.0 baseline; 0 gives raw price (no denoise), higher is smoother but adds lag. Noise Estimation Window 50 estimates noise σ. High-Freq Denoise Bias 1.5 adds denoising to high-freq bands; raise for noisy instruments. Signal Mode "slope + trend filter" is robust; "macro trend cross" gives clearer signals. Adaptive Scale Reliability ON is recommended.
💡 How to Use in Practice
Apply to chart and 5 frequency-strata ribbons appear with the denoised main line in directional color. The ribbon "thickness" shows each band's activity; the HUD's FREQUENCY BANDS shows each band's energy and learned reliability. A dominant "S5 macro" band means macro-trend-driven; "S1 chatter" means noise-dominant ranging — read the market's character. When high-reliability bands align with the trend, signal conviction rises. Divergence/convergence of denoised price from the macro trend line gauges trend strength. Higher denoise strength gives smooth swing signals; lower gives sensitive ones.
⚠️ Important Notes
This is a causal, undecimated wavelet (B3 spline / Linear / Haar), not a full Daubechies decimated DWT. The adaptive scale reliability is online EWMA, not deep learning. The transform math, however, is genuine à trous. Due to the scaling filter's group delay, the macro scale (c_J) represents a lagged macro trend. The denoised price has minimal lag thanks to perfect reconstruction, but higher denoise strength introduces smoothing lag. It uses past data only, so it does not repaint. All signals are probabilistic decisions based on historical data and do not guarantee future profits.
🚨 Disclaimer
This indicator is provided for educational and informational purposes only and does not constitute financial or investment advice. No signal guarantees future profit, and past performance does not indicate future results. All trading decisions are made at your own risk. Indicator

Bipower Jump Detector [forexobroker]🔶 OVERVIEW
Bipower Jump Detector implements the Barndorff-Nielsen jump test: realized variance (RV) captures both diffusion and jump risk, while bipower variation (BV) — built from products of adjacent absolute returns scaled by pi/2 — is jump-robust. Their non-negative difference isolates the jump component J; the standardized Jump-Z statistic tests whether that difference is significant. When Jump-Z exceeds the cutoff (default 1.96, 95% one-sided), the script enters in the direction of the largest absolute return inside the window. The unique angle is using a peer-reviewed jump test rather than ad-hoc bar-size thresholds.
🔶 ALGORITHM
1. Log-returns r_t = log(close / close ) are computed each bar.
2. Realized variance RV = sum of r_t^2 over the window (default 20).
3. Bipower variation BV = (pi/2) * sum of |r_t| * |r_{t-1}| over the window (jump-robust by construction).
4. Jump component J = max(RV - BV, 0) is plotted as a histogram.
5. Jump-Z = sqrt(N) * (RV - BV) / sqrt(theta * BV^2 * 0.5) with theta = pi^2/4 + pi - 5 (Barndorff-Nielsen and Shephard, 2006).
6. Direction is the sign of the largest |r_k| inside the window — the dominant jump bar drives the entry side.
7. Significant jump = Jump-Z > threshold (default 1.96); a 15-bar cooldown and position state flip-prevention stop the same jump cluster from firing multiple entries.
🔶 SIGNAL LOGIC
- Buy: Jump-Z above threshold AND dominant return in the window is positive AND session filter passes AND position is not already long AND cooldown bars elapsed AND barstate.isconfirmed.
- Sell: Jump-Z above threshold AND dominant return in the window is negative AND session filter passes AND position is not already short AND cooldown bars elapsed AND barstate.isconfirmed.
The Z test is the gate, the dominant return is the direction.
🔶 INPUTS
- Jump Calculation group: window length default 20, significance Z default 1.96 (raise to 2.58 for stricter 99%).
- Signal Logic group: cooldown bars default 15.
- Filters group: session restriction (default 0000-2400).
- Visual group: dashboard, 3-layer glow, jump markers, jump component color, Jump-Z color, buy and sell colors.
🔶 ALERTS
BJD Buy, BJD Sell, BJD Any Signal, BJD Significant, BJD Jump Up, BJD Jump Down, BJD Z Rising, BJD J Rising, BJD High Jump Ratio, BJD Quiet Diffusion, BJD Webhook JSON.
🔶 LIMITATIONS
- The Barndorff-Nielsen test was designed for high-frequency intraday returns; on daily timeframes the diffusion-jump decomposition is harder to interpret and BV becomes a less precise diffusion proxy.
- Bipower variation needs at least two adjacent non-zero absolute returns; a window with one or two zero returns inflates Jump-Z artificially.
- The direction comes from the single dominant return in the window — when two large opposite jumps occur back-to-back, the entry side may not reflect the most recent move.
- Defaults are tuned for liquid crypto and intraday futures; thin instruments with frequent zero-volume bars produce noisy BV estimates.
- The Z formula uses a simplified variance approximation (theta * BV^2 * 0.5); under extreme volatility the small-sample distribution deviates from the normal approximation.
Indicator

Allan Variance Stability Index [forexobroker]Allan Variance Stability Index adapts the Allan deviation — the standard tool for measuring atomic clock frequency stability — to financial returns. By computing the standard deviation of block-averaged log-returns across multiple timescales tau in {1, 2, 4, 8, 16, 32}, the script asks whether price drift behaves consistently or fragments across horizons. The single stability index S then collapses that multi-scale picture into one number that an adaptive median-and-sigma floor can monitor. The unique angle is borrowing a frequency-domain stability metric instead of a price-domain volatility one, so the script reads regime change rather than range size.
🔶 ALGORITHM
1. Log-returns r_t = log(close / close ) are computed and the last M (default 128) are used.
2. For each lag tau in {1, 2, 4, 8, 16, 32}: the return window is split into floor(M / tau) contiguous blocks, each block-averaged, and sigma(tau) is the standard deviation of those block averages.
3. The six log-sigmas are averaged and S = -stdev(log sigma(tau)) is computed — higher S means returns scale predictably across tau, lower S means timescales disagree.
4. An adaptive floor is computed each bar as median(S, adaptive median length default 80) minus k (default 1.0) times stdev(S) over the same window.
5. When S falls below the floor the regime is destabilising; the sign of close - close arms a directional bias.
6. When S crosses back above the floor inside that armed bias, the entry fires — the script trades the trend that survived the instability.
🔶 SIGNAL LOGIC
- Buy: S crosses up through the floor AND active bias is bullish (close was above close while S was under the floor) AND session filter passes AND position is not already long AND cooldown bars elapsed AND barstate.isconfirmed.
- Sell: S crosses up through the floor AND active bias is bearish AND session filter passes AND position is not already short AND cooldown bars elapsed AND barstate.isconfirmed.
The cross-back is the trigger; the bias is set during the instability window.
🔶 INPUTS
- Stability Calculation group: return window M default 128, adaptive median length default 80, floor k x sigma default 1.0.
- Signal Logic group: momentum lookback default 3, cooldown bars default 15.
- Filters group: session restriction (default 0000-2400).
- Visual group: dashboard, 3-layer glow, stability line color, floor color, buy and sell colors.
🔶 ALERTS
AVS Buy, AVS Sell, AVS Any Signal, AVS Floor Break, AVS Floor Reclaim, AVS Arm Up, AVS Arm Down, AVS Vol Expanding, AVS Vol Contracting, AVS Bias Flip, AVS Webhook JSON.
🔶 LIMITATIONS
- Needs M plus 32 confirmed returns of history before sigma(32) is reliable, so early-chart bars produce noisy S values.
- The Allan-style estimator was designed for stationary frequency oscillators; under structural market shifts S can stabilise around a new floor for several bars before the adaptive median catches up.
- Block averaging at large tau reduces the number of blocks, so sigma(32) is the noisiest leg of the curve and dominates S in low-history regimes.
- Defaults are tuned for liquid futures and crypto on intraday timeframes; very thin instruments produce zero-return blocks that pin sigma(1) and inflate S.
- The bias is set on the instability bar but only fires on the reclaim, so very short instability episodes can fire a signal with stale momentum context.
Indicator

RSI-MFI History FinderDescription:
This indicator replicates the original RSI-MFI (Money Flow wave/band) found in popular systems like Market Cipher B and VuManChu (VMC), enhancing it with a unique historical search engine. It is built specifically for traders who rely on contextual market analysis, pattern matching, and backtesting identical historical setups.
The indicator automatically scans the chart's history to find the most recent candle where the Money Flow index reached an extremity identical to (or deeper than) the current level (or a manually specified target), helping you instantly cross-reference the current setup with historical precedents.
Key Features:
Original VMC Math: Fully complies with the original formula calculating RSI-MFI based on the smoothed ratio of candle bodies to their wicks. The values perfectly match classical sub-window oscillators.
Smart Directional Search: The algorithm automatically adapts to the sign of your target value:
- If the RSI-MFI target is negative (oversold conditions), the script searches for the closest historical bar where the value was equal to or lower than the target (matching similar or deeper exhaustion).
- If the RSI-MFI target is positive (overbought conditions), the script looks for a bar where the value was equal to or higher than the target (matching similar or stronger momentum).
Local Noise Filter (Skip Recent Bars): A fully customizable setting allows you to exclude the N most recent bars from the search. This prevents the script from catching candles within the current consolidation or immediate market move, forcing it to look back into previous isolated market cycles.
Perfect Independent Scaling: Operating in a dedicated sub-window (overlay=false) with a fixed range from -100 to +100 and static boundary lines (0, ±50), the oscillator remains perfectly readable and will never get flattened by the absolute price of the asset.
Instant Candle Navigation: The script pushes the exact date and time of the matched historical point directly to the Pine Logs panel, allowing you to copy it with a single click.
How to Use:
Open the Pine Logs tab at the bottom of PulseWire (located next to the Pine Editor and Strategy Tester).
Once the indicator identifies a match, an orange dashed vertical line and a label will appear in the sub-window, and a log entry will generate: GO-TO DATE: YYYY-MM-DD HH:MM .
Highlight and copy ( Ctrl+C / Cmd+C ) this date from the logs.
Press Alt + G (or Option + G on Mac) to bring up PulseWire's native "Go to" navigation window, paste the copied date ( Ctrl+V ), and hit Enter. The chart will instantly snap to that precise historical candle.
If you want to simulate the price action from that point forward, press Alt + B to activate the Bar Replay tool and click right on the highlighted candle to cut the chart there.
Inputs & Settings:
What to look for? – Switch between tracking the live closing value of the oscillator (Current Value) or looking for a custom predefined level (Manual Input Value).
Skip Recent Bars – Number of recent candles excluded from the scan (default is 7). Protects against triggering within the current market impulse.
Historical Search Depth – Max number of bars to scan backwards (supports up to 5000 bars with automated memory buffer extension).
Original RSI-MFI Settings – Core period, multiplier, and offset variables to keep the oscillator aligned with your existing trading strategy.
Indicator

Risk Controller | MouryaRisk Controller | Mourya - Complete Indicator Guide
Overview
Risk Controller | Mourya is an institutional-grade, real-time risk management matrix and position layout dashboard built directly onto your chart. Instead of forcing traders to context-switch between spreadsheets and their charting screen, this terminal brings complete mathematical clarity to active position-sizing, trailing stops, real-time tracking, and multi-tier target distributions. Designed for both professional execution and sleek workspace integration, it features absolute flexibility from pure cash or spot accounts to heavily leveraged derivative trades.
How to Use (Setup and Workflow)
* Apply the indicator to your chart and open the settings menu.
* Select your Position Type (Long or Short) and pick your preferred currency symbol from the dropdown menu.
* Enter the exact Quantity or Shares you are trading.
* Enter your Leverage multiplier. If you are using a standard spot or cash account without leverage, enter 0.
* Choose your Brokerage Fee type (Fixed Value or Percentage) and enter the corresponding fee amount so the dashboard can calculate your true net profits.
* Enter your total account balance into the Net Cash Available field to enable automatic account risk percentage tracking.
* Set your levels visually by clicking the price lines directly on your chart to wake up the PulseWire drag handles, then drag your Entry, Stop Loss, and up to 4 Take Profit targets to your desired locations.
* If you prefer strict mathematical targets instead of dragging lines, type a value into the Percentage Overrides settings to automatically lock a Take Profit target to an exact asset percentage move.
* Customize your workspace by navigating to the Dashboard Settings to move the terminal to any corner of the screen, scale the overall size from tiny to huge, and select custom colors for the header background, header text, and chart lines.
* For a quick reset when scanning multiple tickers, open the settings menu, click the Defaults button in the bottom left corner, and select Reset Settings to wipe the board clean back to zero.
How it Works (Core Features)
* Interactive Chart Synchronization: Bypasses manual price typing by letting you drag and drop your target lines on the live chart. The dashboard matrix instantly recalculates all metrics the moment you release the line.
* Live P and L Tracking Module: A dedicated real-time row sits beneath your entry, constantly tracking your exact active Profit and Loss, tick distance, and live Return on Equity (ROE) as the market moves tick-by-tick.
* Trailing Stop Loss Support: The mathematical engine adapts instantly. If you drag your Stop Loss line past your Entry price into profit territory, the dashboard flips its internal logic, converting the red loss metrics into secured green profits.
* Percentage Overrides: Overrides your manual chart line placement, locking in exact percentage-based profit targets while keeping the Stop Loss manually adjustable.
* Dynamic Hide Logic: Automatically collapses and hides Take Profit rows 2, 3, and 4 on your dashboard if you leave their values at zero, keeping your screen clutter-free.
* Account Risk Diagnostics: Evaluates your Stop Loss distance against your Net Cash Available to show the exact percentage of your total account at risk. It also flashes a critical margin warning if your required margin exceeds your cash balance.
* Margin and Breakeven Engine: Identifies the actual cash margin required to open the position and calculates the exact asset price you need to hit to exit the trade at absolute zero after all entry and exit brokerage fees are deducted.
* True Return on Equity (ROE): Scales your return metrics accurately. If you input 0 leverage, it mirrors the raw asset movement. If you input leverage, it calculates the amplified return strictly on your invested margin.
* Risk-to-Reward (R:R) Tracking: Instantly evaluates the structural viability of your trade setup by calculating the ratio between your Stop Loss risk and Take Profit 1 potential.
* Wick-Sensitive Hit Engine: Mimics real broker limit fills by actively tracking live high and low wicks instead of waiting for a candle to close. The moment a price touches your Stop Loss or Take Profit, the dashboard row flashes in vivid solid colors (Institutional Green for TP, Red for SL) and the chart label flashes yellow.
* True Market Context Module: Calculates the exact percentage distance between the real-time live price and critical historical extremes. Includes today's High/Low, a mathematically pure 52-Week High/Low (calculated using exactly 252 trading days to account for weekends and holidays), and the All-Time High/Low.
* Context Toggles: Allows you to independently check or uncheck the Day, 52-Week, and All-Time context metrics to save screen space when you do not need them.
* Built-in Settings Tooltips: Every single input in the settings menu features an integrated guide next to the small info icon explaining its exact function and mathematical behavior. Indicator

Pattern Analog ProjectionPattern Analog Projection
OVERVIEW
This tool searches historical price action for the sequences that most closely
resemble the current market structure, then projects what typically followed
those analogous sequences. It is a context and probability tool, not a buy/sell
signal generator.
HOW IT WORKS
- Shape matching: the last N bars are compared against historical windows using
Pearson correlation, which is invariant to price level and scale. This compares
pattern geometry rather than absolute prices.
- Volatility gating: candidates whose relative-volatility profile differs too much
from the current window are rejected, so analogs share a similar character.
- Top analogs: the best non-overlapping matches are ranked and stored (up to 5).
- Forecast cone: the future paths that followed each analog are aggregated. The
dashed center line is the average projection; the shaded envelope spans the most
bullish and most bearish analog outcomes.
- Probability: the share of analogs that finished bullish, bearish, or neutral
over the projection horizon.
- Confidence: a 0-100 score (graded A+ to C) combining match quality, directional
agreement, and outcome consistency.
- Market regime: the current structure is classified (Strong Trend, Trending,
Range, Compression, Volatile Expansion) using an efficiency ratio and ATR.
INPUTS
- Pattern Length, Projection Length, Search Depth, Search Step
- Number of Analogs, Min Correlation Filter, Forecast Mode (Average / Best / Median)
- Volatility Matching and tolerance, Neutral Band
- Toggles for cone, historical analogs, similarity heatmap, dashboard
- Dashboard position and colors
HOW TO USE
1. Add to any symbol and timeframe; load plenty of history for better matches.
2. Read the Confidence grade first. Treat low-confidence forecasts with caution.
3. Use the cone as a likely-path context, combined with your own trade plan and
risk management - not as a standalone entry trigger.
4. The highlighted region shows the closest historical analog for reference.
NOTES
- The projection re-derives as each new bar closes. It draws forward only and does
not repaint historical bars; there are no historical signals to restate.
- Heavy calculation runs on the last bar. If you see a loop-timeout, lower Search
Depth or raise Search Step.
- Past structural resemblance does not guarantee future outcomes. This script is
for research and education only and is not financial advice. Indicator

Asset Class Correlation MatrixAsset Class Correlation Matrix
█ OVERVIEW
This indicator displays a Pearson correlation matrix for instruments in the asset class of the symbol you are currently viewing. Open a EUR pair and you see the forex matrix. Open gold and you see the metals matrix. Open Bitcoin and you see the crypto matrix. The relevant basket loads automatically, so there is nothing to configure for the common cases.
Each cell shows the rolling correlation between two instruments over a lookback period you control. The goal is to make cross-instrument relationships inside an asset class visible at a glance, rather than checking pairs one at a time, or relying on visual comparison.
█ AUTOMATIC ASSET CLASS DETECTION
The current symbol is matched to a category in three stages:
1. Exact ticker match against the built-in lists below.
2. Name-fragment match for common broker and CFD names. For example XAU and GOLD map to Metals, US500, SP500, NAS100, US100, US30 and DJ30 map to US Indices, DAX, FTSE and NIKKEI map to Global Indices, and WTI, BRENT and NATGAS map to Energy.
3. Asset type fallback using the instrument type, covering crypto, forex, and stocks.
If the current symbol is not already part of a built-in list, it is added as the first row and column of the matrix, so the instrument you are on is always included. If no category can be determined, the table shows a short prompt to use the custom symbol list instead of rendering empty.
█ BUILT-IN CATEGORIES
Forex: 28 majors and crosses across USD, EUR, GBP, JPY, AUD, CAD, CHF and NZD.
US Indices: ES, NQ, YM, EMD, RTY.
Global Indices: DAX, Euro Stoxx 50, Nikkei, FTSE, ASX 200, Hang Seng.
Metals: Gold, Silver, Copper, Platinum, Palladium.
Energy: WTI Crude, Natural Gas, Heating Oil, RBOB Gasoline.
Agricultural: Corn, Soybeans, Wheat, Soybean Oil, Soybean Meal, Cocoa, Coffee, Sugar, Cotton, Orange Juice.
Livestock: Live Cattle, Lean Hogs, Feeder Cattle.
Interest Rates: 2Y, 10Y, 30Y US notes, Euro Bund, Euro Buxl.
Crypto: BTC, ETH, BCH, LTC.
Stocks: SPX, QQQ, AAPL, MSFT, NVDA, AMZN, GOOGL, META, TSLA, AMD.
█ READING THE MATRIX
Pearson correlation ranges from -1 to +1.
Values near +1 mean the two instruments move strongly together. Values near -1 mean they move strongly opposite to each other, which is still a strong relationship, just inverted. Values near 0 mean little to no linear relationship.
The strength of a relationship is the distance from zero, in either direction. A reading of -0.9 is just as tight as +0.9.
█ COLORS
Positive correlation is shown in green, with a stronger shade above the high threshold and a lighter shade above the moderate threshold. Inverse correlation is shown in purple, using the same two strength levels. Everything between the negative and positive moderate threshold is shown as low. All five colors and both thresholds are adjustable in the settings. The thresholds apply symmetrically to positive and inverse values.
█ CUSTOM SYMBOL LIST
You can override the auto-detected basket with your own comma-separated list of symbols. Spaces are ignored. The custom list is applied only when the current chart symbol is one of the symbols in the list, which keeps the chart instrument anchored in the matrix.
You can include an exchange or broker prefix, for example OANDA:EURUSD. A bare ticker such as GBPJPY inherits the current chart prefix. Bare futures contracts such as ES1! resolve on their native exchange.
█ SETTINGS
Period: lookback in bars for the correlation calculation. Shorter reacts faster and is noisier. Longer is more stable and slower to update.
High and Moderate Correlation Thresholds: the cutoffs for the color bands.
Colors: the five correlation colors.
Symbol List: the optional custom basket.
Table Size: text size of the matrix.
█ HOW TO USE IT
Add the indicator to any chart in a supported asset class. Use it to find pairs that move together or opposite each other, to check diversification across a basket, to spot when a normally correlated pair is diverging, or to choose hedges and pairs-trade candidates. The left column shows the full applied symbol for each row, so you can confirm exactly which feed each value comes from.
█ NOTES AND LIMITATIONS
Correlation is period-dependent. For tightly linked instruments, a long lookback pushes most values toward the extremes, while a short lookback spreads them out and reacts faster. Choose the period to match the question you are asking.
Correlation measures linear co-movement of closing prices on the chart timeframe. It does not imply causation and does not capture non-linear relationships.
Broker naming for CFDs varies widely, so some instruments may not auto-detect. When that happens, use the custom symbol list.
A maximum of 28 instruments can be loaded in one matrix. Indicator

Indicator

OMSF Learning SpaceWelcome to the Omsf Learning Space.
This is not a commercial "holy grail" indicator, nor is it a rigid, corporate course. This is my personal sandbox and educational archive where I dissect market structure, breakout mechanics, and reversal setups.
THE CORE PHILOSOPHY:
Everything in this space is built upon my Omsf (Objective Market Structure Framework). Whether you are a beginner trying to understand how charts breathe, or an advanced trader looking for mechanical rules – this space is designed to give you a clear, visual reality check.
WHAT TO EXPECT:
This script is dynamic and will change organically over time. As I publish new trading ideas, research notes, or structural concepts, this indicator will adapt. Old parts might get swapped out, new experiments will be added, or it might evolve into a v2.0 down the road. There is no fixed schedule. It updates when it updates.
CURRENT VERSION (Launch):
Right now, we are looking at the foundational mechanics: Classic, rigid Pivots alongside the dynamic volatility adjustment of the Omsf.
- Toggle "Exercise 1" to stress-test both engines in the configuration sandbox.
- Toggle "Outlook" to see how classic Pivots perform when taken literally as a trend filter.
Enjoy the sandbox, play with the parameters, and use the Bar Replay. See you in the ideas section!
— arni Indicator

Indicator

Industry Group Strength v2Based on Amphibiantrading's Industry Group Strength indicator.
This indicator shows which companies are the strongest and weakest within the same industry as the stock you're currently viewing.
Open any US stock on a daily or weekly chart, and the indicator automatically detects which industry that stock belongs to, then displays the major companies in that same industry as a compact, colour-coded strip. Tickers are ranked from strongest on the left to weakest on the right, and each one is shaded from green (leading its industry) to red (lagging it), so you can read an entire industry's pecking order in about a second.
The stock you currently have open is highlighted in yellow with a dot (●), so you can instantly see how it stacks up against its peers. If it isn't strong enough to appear among the leaders on display, it's added onto the end of the strip anyway — you'll always see where your stock stands.
You decide how strength is measured, using the Data setting:
- Since the start of the year — how much each company has risen or fallen so far this calendar year.
- Performance versus a comparison index — how much each company has beaten or lagged the overall market (the S&P 500 by default; you can point it at any symbol) over a time window you choose.
- Plain price change — how much each company's price has simply moved over that same time window.
The time window applies to the last two options (the start-of-year option always measures from January). By default the window is 90 bars — that's 90 days on a daily chart, or 90 weeks on a weekly chart.
Adjustable settings:
- which strength measure to use,
- the length of the time window,
- how many companies to show (1 to 40),
- light or dark colour mode,
- the comparison index,
- the text size,
- and whether to print the actual numbers beneath each company.
A few things to know:
- Use it on a daily or weekly chart. It will ask you to switch if you load it on a shorter timeframe (such as 5-minute or hourly).
- It works on United States stocks that carry an industry classification. On other symbols — indexes, currencies, and so on — the display will be blank.
- The company lists hold the larger, more established names in each industry rather than every single stock, so the strip stays readable and quick to load.
Credit & thanks: the original Industry Group Strength concept and script were created by Amphibiantrading, thanks to him for sharing his code. The main changes in this v2 are the UI and a refresh of tickers' industry membership. Indicator

MTF CVD Synchrony | Rainbow MatrixGENERAL OVERVIEW
MTF CVD Synchrony is a multi-timeframe directional flow oscillator that condenses five independent CVD (Cumulative Volume Delta) readings — one per Fibonacci-spaced timeframe — into a single weighted Master Line on a zero-centered 0-100 scale, surrounded by per-TF "ghost lines" that fade visually as they diverge from the consensus. The defining feature: 50 is true neutral. Above 50 means buyers are dominating; below 50 means sellers are dominating. The further from 50, the stronger the directional pressure. When the five timeframes align, the rainbow becomes a solid band; when they diverge, the disagreement becomes a visible density property of the indicator itself.
A background histogram visualizes the Master score's deviation from the neutral 50 line — green columns extend up when buyers dominate, red columns extend down when sellers dominate. A compact 7×9 MTF Legend Table surfaces every dimension simultaneously: per-TF resolutions, score values, trend direction, divergence flags, raw flow magnitude, and named directional State — with an antenna marker flagging the row whose timeframe matches your chart's native resolution.
Designed as the directional member of a three-indicator family. Apply all three side-by-side for a complete read: MTF RSI Synchrony shows where price sits in its momentum range; MTF Volume Delta Bar Synchrony shows whether the move has volume magnitude behind it; MTF CVD Synchrony shows who is actually winning — buyers or sellers. Same visual signature, same canonical Fibonacci ratios, same Legend Table layout — instant cross-indicator readability.
WHAT IS THE THEORY BEHIND THIS INDICATOR
Cumulative Volume Delta attempts to answer a question that price and volume alone cannot: in any given bar, were buyers or sellers more aggressive? Traditional volume tells you HOW MUCH traded, but not the DIRECTION of the pressure. A high-volume bar that closes flat tells a very different story from a high-volume bar that closes at its highs — yet raw volume scores them identically.
CVD approximates directional pressure by weighting each bar's volume by where price closed within its range. This indicator uses the Close Location Value (CLV) for that weighting:
clv = ((close − low) − (high − close)) / (high − low)
CLV ranges from +1 (close exactly at the high — maximum buying pressure) to −1 (close exactly at the low — maximum selling pressure), with 0 at the midpoint. Multiplying CLV by volume produces a signed directional contribution per bar: delta_raw = clv × volume. This is more nuanced than the binary tick rule (close > open = buy) used by most "delta" indicators — CLV captures HOW DECISIVELY price closed in its range, not just the sign.
The per-bar delta is then smoothed by EMA and normalized into a bounded 0-100 zero-centered score:
cvd_smooth = EMA(delta_raw, smoothing_length)
max_abs = highest(|cvd_smooth|, normalization_window)
score = 50 + (cvd_smooth / max_abs) × 50
The genius of the zero-centered approach: 50 always means balance, regardless of the asset's structural bias. A score of 75 means buyers are exerting 50% of the maximum recent pressure to the upside; a score of 25 means sellers are exerting 50% of maximum recent pressure to the downside. This is fundamentally different from a percentile rank (which would anchor 50 at the historical median, skewing with structural trends).
Five such scores — one per timeframe (default 5 / 15 / 60 / 240 / D) — are fused via canonical Fibonacci weights (0.15 / 0.20 / 0.25 / 0.25 / 0.15, peak weight on the macro TF3/TF4 where institutional positioning consolidates) into the weighted Master Line.
FEATURES
🔹 Multi-Timeframe CVD Fusion Engine (zero-centered directional scale)
🔹 CVD Histogram (deviation from neutral 50 — green buy / red sell)
🔹 Adaptive Fibonacci Channel (Z-Breathing → Z-Alert → Z-Exhaustion → Black Swan)
🔹 Hybrid Black Swan Zones (static or dynamic — default dynamic)
🔹 Classic Price↔CVD Divergence Detection (per-TF + Master)
🔹 MTF Legend Table (7 columns × 9 rows, with Raw Flow + State, multilingual)
🔹 Multilingual Interface (EN / PT / ES / RU / ZH)
🔹 Multi-Timeframe CVD Fusion Engine
What It Does
Runs five independent CVD scores on Fibonacci-spaced timeframes and fuses them into a single weighted Master Line, with each per-TF reading plotted as a ghost line that fades by distance to the consensus.
Method
On each timeframe, f_cvd_full() computes CLV × volume per bar, smooths it via EMA, and normalizes against a rolling-max window to produce the zero-centered score. The five scores fuse via Fibonacci weights (0.15 / 0.20 / 0.25 / 0.25 / 0.15). Both smoothing length and normalization window are independently configurable per timeframe.
Per-TF smoothing defaults (Wilder-anchored on TF3+TF4):
◇ TF1 (5m): 7 — scalping
◇ TF2 (15m): 10 — day-trading
◇ TF3 (60m): 14 — Wilder canonical
◇ TF4 (240m): 14 — Wilder canonical
◇ TF5 (D): 21 — swing/position
Per-TF normalization windows (each TF's natural horizon):
◇ TF1: 30 (≈2.5h on 5m)
◇ TF2: 50 (≈12.5h on 15m)
◇ TF3: 80 (≈3.3 days on 1h)
◇ TF4: 100 (≈16 days on 4h)
◇ TF5: 150 (≈5 months on Daily)
All request.security calls use lookahead=barmerge.lookahead_off for anti-repaint integrity.
Why It Matters
A 5-minute buy surge means little if the 4-hour and daily flows are decisively selling. The fusion engine reveals whether directional pressure is aligned across timescales (high conviction) or contradictory (a counter-trend bounce inside a larger trend). The ghost-line rainbow makes that alignment visible at a glance.
🔹 Adaptive Fibonacci Channel
What It Does
Six color-coded bands around the Master Line that adapt to its own recent volatility, using the brand's canonical Fibonacci ratios.
Method
Highest/lowest of the Master over a configurable lookback (default 50) are smoothed by EMA (default 10) to form the channel envelope. Bands sit at canonical Fibonacci proportions: Z-Breathing (1.50/1.85), Z-Alert (1.85σ anchor), Z-Exhaustion (2.75/1.85), Black Swan (3.85/1.85). All six band values are mathematically clamped to before rendering, keeping the rainbow inside the visible pane.
Why It Matters
Static thresholds can't adapt to regime changes. The Fibonacci channel calibrates the warning zones to the asset's current directional-flow volatility, so a "climax" on a calm pair and a "climax" on a volatile one both trigger at appropriate statistical extremes.
🔹 Hybrid Black Swan Zones
What It Does
Flags directional flow climax extremes — either at static 85/15 thresholds (BUY CLIMAX / SELL CLIMAX boundaries) or at the dynamic Fibonacci 3.85σ band.
Method
Dynamic Black Swan Mode is ON by default (Fibonacci 3.85σ proportion of the Master channel). Toggle OFF for static 85/15. Each zone renders as a glow line that brightens as the Master approaches. The static reference lines (15/50/85) are shown by default to anchor the zero-centered scale: 85 = purple (buy climax boundary), 50 = yellow (neutral), 15 = aqua (sell climax boundary).
Why It Matters
Directional flow climaxes mark exhaustion points — a BUY CLIMAX (score ≥ 85) means buyers have pushed to a recent extreme, often preceding a pause or reversal; a SELL CLIMAX (≤ 15) marks capitulation. The dynamic mode self-calibrates per asset and regime.
🔹 Classic Price↔CVD Divergence Detection
What It Does
Detects regular bear divergences (price higher high while CVD makes lower high — rally on weakening buy pressure) and bull divergences (price lower low while CVD makes higher low — selling exhausting). Runs on each timeframe AND on the Master line.
Method
Per-TF divergence runs inside request.security via pivot detection on the per-TF CVD score. Master divergence runs on the chart-TF directly, rendering a connecting line + label between pivots (red bear / green bull) on the pane. Per-TF results surface in the Legend Table's "Div" column.
Why It Matters
Price↔flow divergence is one of the most powerful applications of CVD. When price makes a new high but directional flow doesn't confirm, the rally is running on fading conviction — a classic distribution warning. Detecting this per-TF AND on the Master gives both early granular warnings and high-conviction confirmations.
🔹 MTF Legend Table
What It Does
A compact 7×9 table surfacing every dimension of the analysis at a glance.
Method
Rendered via table.new(force_overlay=false) on the pane. Layout:
◇ Row 0: title (spans all columns)
◇ Row 1: column headers — Indicator / Timeframe / Value / Trend / Div / Raw / State
◇ Rows 2-6: per-TF data
◇ Row 7: Master row ("🌈 Master (~XhYm)" with effective TF)
◇ Row 8: MTF Divergence status row
Per-TF cells show: ● TF label (+ antenna 📡 if chart-native), TF resolution, zero-centered score (zone-colored), trend arrow (±0.5 deadzone), divergence (🔺/🔻/—), Raw Flow (compact K/M/B signed magnitude, green if positive / red if negative), and State (directional name, zone-colored).
Why It Matters
The Raw Flow column complements the Value column: Value answers "how strong is the directional pressure?" (the normalized score), while Raw answers "how much actual volume is behind it?" (the absolute flow). A score of 75 with a small raw magnitude is weaker conviction than 75 with a huge raw magnitude. Together with State, the table tells a complete directional story per timeframe.
🔹 Multilingual Interface
What It Does
Translates all HUD labels, status messages, alert text, Legend Table headers, and directional State names to 5 languages: English, Português, Español, Русский, 中文.
Method
A single language dropdown selects the active language via Pine v6's ternary-chain pattern. Code, comments, and configuration tooltips remain in English by convention.
Why It Matters
The Rainbow Matrix family is built for traders worldwide. Multilingual UI removes friction for non-English-native users.
HOW TO USE
Reading the Pane
◇ Master near 50 with ghost lines tight: balanced flow, no directional edge (absorption / equilibrium).
◇ Master rising above 50: buyers gaining control. Above 62 = BUY PRESSURE; above 71 = STRONG BUY.
◇ Master falling below 50: sellers gaining control. Below 38 = SELL PRESSURE; below 29 = STRONG SELL.
◇ Master touches Black Swan High (≥85, purple glow): BUY CLIMAX — buyers at a recent extreme, watch for exhaustion.
◇ Master touches Black Swan Low (≤15, aqua glow): SELL CLIMAX — capitulation, watch for reversal.
◇ Histogram green/red columns: immediate bar-by-bar directional read around the 50 centerline.
Reading the Legend Table
The antenna marker (📡) flags your chart's native timeframe — start there, then scan up/down to see whether faster/slower TFs confirm or contradict the directional bias. Compare Value (pressure strength), Raw (actual flow magnitude), and State (named classification) for each row. The status row summarizes MTF alignment between TF1 and TF5.
Reading Divergences
Master bear divergence (price up + CVD down) = rally on fading buy conviction, distribution warning. Master bull divergence (price down + CVD up) = selling exhausting, potential bottom. Per-TF divergences in the Div column give early granular warnings.
Tactical Combinations
◇ Master BUY CLIMAX + bear divergence + multiple TFs diverging = strongest reversal-from-high signal.
◇ Master SELL CLIMAX + bull divergence = strongest reversal-from-low signal.
◇ Master near 50 + all TFs near 50 + tight ghosts = absorption / coiling, often precedes a directional break.
◇ Triple confluence (the full family): RSI overbought + Volume EXTREME magnitude + CVD STRONG SELL = distribution at the top. RSI oversold + Volume EXTREME + CVD STRONG BUY = accumulation at the bottom. These three indicators answering momentum + magnitude + direction simultaneously is the strongest read the Rainbow Matrix family offers.
INPUTS EXPLAINED
GLOBAL SETTINGS — System Language (EN/PT/ES/RU/ZH), table/label font sizes.
MULTI-TIMEFRAME — AI Auto-Sync TFs; TF1-TF5 manual resolutions (default 5/15/60/240/D); per-TF CVD Smoothing Length (7/10/14/14/21); per-TF CVD Normalization Window (30/50/80/100/150).
ENGINE — Dynamic Black Swan Mode (default ON); Dynamic Channel Lookback (50) and Smoothing (10); Divergence Pivot Lookback (5).
VISUALIZATION — TF1-TF5 colors + show toggles (all ghost lines OFF by default — only Master visible on install); Ghost Fade Sensitivity (3.5); Show Master Line / Rainbow Fills / Black Swan / Dynamic Channel; Show CVD Histogram; Show MTF Legend Table; Show Divergence Column; Show Raw Flow Column; Show State Column; Show Master Divergence Chart Line; Legend position; Show Divergence Event Markers; Show Static Reference Lines (15/50/85, ON by default).
ALERTS — Black Swan crossings (high/low); Strong MTF Divergence; Z-Exhaustion zone entries; Master Classic Divergence.
IMPORTANT NOTES
🔸 Pine Script v6 — uses request.security with lookahead=barmerge.lookahead_off. 16 total security calls (5 CVD score + 5 per-TF divergence + supporting channel calculations). Chart load may take a moment longer than a single-TF indicator.
🔸 CLV approximation, not order-flow tick data — Directional pressure is approximated via the Close Location Value (where price closed within each bar's range), NOT real bid/ask order flow. Pine Script v6 has no tick-by-tick data access in indicator scripts. CLV is a more nuanced approximation than the binary tick rule used by most free-tier "delta" indicators, but it remains an approximation. For true order-flow delta, use dedicated footprint/order-flow tools.
🔸 Zero-centered scale — Unlike the percentile-rank siblings (RSI, Volume Delta Bar), this indicator's 50 is a TRUE neutral (zero net directional flow), not a historical median. This is intentional — direction is inherently signed, so a fixed zero-point is more meaningful than a regime-relative median.
🔸 Normalization warmup — During the first normalization_window bars on each TF, the rolling-max anchor (max_abs) is built from a small sample, so early bars may show exaggerated swings until the window fills. Normal warmup behavior for any rolling-window indicator.
🔸 Repaint behavior — Historical bars use confirmed close data; the current real-time bar updates as ticks arrive. Pivot-based divergence requires confirmation bars before triggering (standard pivot divergence behavior).
🔸 Fibonacci ratios are canonical — The channel proportions (1.50/1.85/2.75/3.85) and fusion weights (0.15/0.20/0.25/0.25/0.15) match the Rainbow Matrix brand standard across all sibling indicators, preserving cross-indicator visual consistency.
🔸 License: MPL 2.0 — open source. Free to fork, modify, and republish under the same license terms.
UNIQUENESS
Three pillars differentiate this from other CVD indicators on PulseWire:
1. Multi-timeframe CVD fusion with synchrony as a visual property. Most CVD tools run on a single timeframe. This indicator runs five, fuses them via Fibonacci weights, and expresses directional alignment as a rainbow density — solid when timeframes agree on direction, spread when they disagree. The cross-TF directional consensus becomes immediately readable.
2. True zero-centered scale with CLV weighting. The 50 midpoint is a mathematically meaningful neutral (zero net flow), not a regime-skewed median. And the directional weighting uses Close Location Value — capturing how decisively price closed within each bar's range — rather than the cruder binary tick rule. This combination produces a directional read that stays honest across structural trends.
3. Three complementary readings in one Legend Table, designed as a family. Value (pressure strength), Raw Flow (actual magnitude), and State (named classification) disambiguate a single timeframe's directional picture. And as the directional member of the Rainbow Matrix trio (alongside RSI for momentum and Volume Delta Bar for magnitude), it completes a three-dimensional read of any market: where price is, how big the move is, and who's winning.
Rainbow Matrix AI | Multi-timeframe institutional analysis tools for traders.
🌐 rainbowmatrix.ai
✉️ Contact: [email protected]
Indicator

K-NN Pattern ForecastK-NN Pattern Forecast
K-NN Pattern Forecast is an educational forecast indicator that uses historical pattern similarity to project a probabilistic future price path.
The indicator compares the most recent confirmed price pattern with similar historical patterns on the same chart. It then calculates the average forward movement of the closest historical matches and displays a projected path, probability estimates, a quality grade, and a dashboard summary.
This is a forecast indicator, not a trading strategy. It does not place trades, does not simulate orders, and does not provide backtested strategy results. The forecast is probabilistic and based only on historical similarity. It should not be interpreted as a guaranteed prediction, financial advice, or an automatic buy/sell signal.
What the indicator does
The script analyzes recent price behavior and searches historical chart data for similar patterns.
It then estimates what happened after those similar historical patterns and uses that information to create a forward projection.
The indicator displays:
* Forecast direction.
* Forecast path.
* Probability of upward movement.
* Probability of downward movement.
* Projected move percentage.
* ±1 standard deviation forecast band.
* Normalized pattern distance.
* Number of historical matches used.
* Quality score.
* A / B / C grade classification.
* Dashboard summary.
Core concept
The indicator uses a K-Nearest Neighbors style approach.
K-NN is a similarity-based method. Instead of using fixed trend rules or moving-average crosses, the script compares the current market pattern to past patterns and studies the forward movement that followed those historical matches.
The logic is based on the idea that similar price structures may sometimes lead to similar short-term outcomes, but the result is never guaranteed.
How the pattern matching works
1. Current pattern construction
The script builds the current pattern from recent confirmed candles.
It uses log returns between consecutive closes rather than raw price values. This helps normalize the pattern so that the comparison focuses more on shape and movement structure than absolute price level.
2. Historical search
The script searches through a selected historical window and builds comparable historical patterns using the same pattern length.
Each historical candidate is compared with the current pattern.
3. Distance calculation
The script calculates the Euclidean distance between the current pattern and each historical pattern.
A smaller distance means the historical pattern is more similar to the current pattern.
4. K nearest matches
The script selects the closest historical matches based on the K Nearest Neighbors setting.
These selected matches are then used to calculate the forecast.
5. Forward projection
For each selected match, the script studies what happened during the selected forecast horizon after that historical pattern.
The average forward movement becomes the main projected forecast path.
6. Forecast band
The script also calculates dispersion around the forecast using a standard deviation band.
The ±1σ band is intended to show uncertainty around the projected path. A wider band means the historical outcomes were more dispersed and less consistent.
Dashboard explanation
The dashboard summarizes the forecast output:
Direction
Shows whether the average projected move is bullish, bearish, or neutral.
Grade
Classifies forecast quality as A Grade, B Grade, or C Grade.
A Grade means the forecast has stronger alignment according to the script’s scoring model.
B Grade means moderate alignment.
C Grade means weak, noisy, or lower-quality alignment.
The grade is not a guarantee of future movement. It is only a quality classification based on the script’s internal probability, distance, and forecast-band criteria.
Score
Shows the total quality score out of 100.
The score combines:
* Directional probability.
* Normalized distance between the current pattern and historical matches.
* Width of the ±1σ forecast band.
Status
Shows a simplified interpretation of the grade:
* Strong Setup.
* Moderate Setup.
* Weak / Noisy.
Projected Move
Shows the average projected percentage move over the selected forecast horizon.
P(up)
Shows the percentage of selected historical matches that moved upward over the forecast horizon.
P(down)
Shows the percentage of selected historical matches that moved downward over the forecast horizon.
±1σ Band
Shows the estimated one-standard-deviation forecast band percentage.
A smaller band suggests that the selected historical outcomes were more clustered. A larger band suggests more uncertainty.
Normalized Distance
Shows the average similarity distance adjusted by pattern length.
Lower values indicate closer historical similarity. Higher values indicate weaker similarity.
Matches
Shows how many historical matches were used compared with the selected K value.
Forecast grading model
The script uses an internal scoring model based on three elements:
1. Direction probability
Higher directional probability receives a higher score.
For example, if most selected historical matches moved in the same direction, the probability component improves.
2. Normalized distance
Lower normalized distance means the selected historical patterns are more similar to the current pattern.
Closer matches improve the score.
3. Forecast band width
A narrower ±1σ band suggests the historical outcomes were more consistent.
A wider band reduces the score because the forecast has more uncertainty.
A Grade / B Grade / C Grade
A Grade
Represents the strongest forecast quality according to the selected scoring thresholds. It usually means the direction probability is stronger, historical matches are closer, and the forecast band is more controlled.
B Grade
Represents a moderate forecast quality. The setup has some useful alignment, but the forecast is not as strong as A Grade.
C Grade
Represents a weaker or noisier forecast. This can happen when historical similarity is poor, probability is not strong, or the forecast band is wide.
Users can choose to hide C Grade forecasts if they want the chart to display only higher-quality forecast conditions.
Important note about the forecast
This indicator is a forecast tool, but it does not know the future.
The forecast is generated from historical similarity only. Market conditions can change, and a pattern that looked similar in the past may behave differently in the future.
The projected path should be treated as a probabilistic scenario, not a price target and not a trade recommendation.
How to use it
A practical workflow is:
1. Choose a liquid symbol and timeframe.
2. Set the Pattern Length to define how many recent bars form the current pattern.
3. Set the History Search Window to define how much past data the script searches.
4. Set K Nearest Neighbors to control how many similar historical patterns are used.
5. Set the Forecast Horizon to define how many bars forward the projection extends.
6. Review the forecast direction and projected move.
7. Check the probability values and the ±1σ band.
8. Give more weight to forecasts with better grades and lower normalized distance.
9. Avoid treating the forecast path as a guaranteed outcome.
10. Combine the forecast with independent market structure, liquidity, volume, risk management, and higher-timeframe analysis.
Inputs
Pattern Matching
* Pattern Length: number of bars used to define the current pattern.
* History Search Window: number of historical bars searched for similar patterns.
* K Nearest Neighbors: number of closest historical matches used in the forecast.
* Forecast Horizon: number of bars projected forward.
Forecast Quality Filter
* Hide C Grade Forecasts: hides lower-quality forecasts from the chart.
* A Grade Min Score: minimum score required for A Grade.
* B Grade Min Score: minimum score required for B Grade.
* Strong Direction Probability %: probability threshold used in the scoring model.
* Good Direction Probability %: secondary probability threshold used in the scoring model.
* Good Normalized Distance: stricter distance threshold for better similarity.
* Medium Normalized Distance: moderate distance threshold for similarity.
* Good ±1σ Band %: stricter band-width threshold.
* Medium ±1σ Band %: moderate band-width threshold.
Display
* Show Forecast Path: shows or hides the projected forecast path.
* Forecast Path Width: controls the forecast line thickness.
* Show ±1σ Confidence Band: shows or hides the forecast uncertainty band.
* Up Forecast Color: color used for bullish forecasts.
* Down Forecast Color: color used for bearish forecasts.
* Band Color: color used for the ±1σ band.
Dashboard Table
* Show Dashboard Table: shows or hides the dashboard.
* Table Position: controls dashboard location.
* Table Size: controls text size.
* Table Background: controls table background color.
* Table Text Color: controls dashboard text color.
* Table Border Color: controls dashboard border color.
Originality and usefulness
This indicator is designed as a historical-similarity forecast framework rather than a standard trend or momentum overlay.
Its usefulness comes from combining:
* Pattern matching using recent confirmed candle behavior.
* K-nearest historical comparison.
* Average forward path projection.
* Directional probability.
* Forecast dispersion using ±1σ band.
* A transparent quality score and grade.
* A dashboard that explains the current forecast state.
The goal is to help traders study whether the current price structure resembles prior market structures and what the average forward behavior looked like after those historical examples.
Limitations
This indicator does not predict future price with certainty.
A bullish forecast does not guarantee price will rise.
A bearish forecast does not guarantee price will fall.
An A Grade forecast does not guarantee a successful trade.
A C Grade forecast does not mean price cannot move strongly.
The forecast can change when new candles close because the current pattern changes.
The indicator uses confirmed candles only, but the displayed projection is recalculated as new confirmed data becomes available.
The quality of the forecast depends heavily on:
* Symbol.
* Timeframe.
* Available historical data.
* Pattern length.
* Search window.
* Number of neighbors.
* Forecast horizon.
* Market regime.
* Volatility conditions.
* Liquidity conditions.
Historical similarity does not guarantee future repetition.
Recommended use
K-NN Pattern Forecast is best used as an educational probabilistic forecast indicator.
It can help traders compare the current price pattern with similar historical patterns and evaluate possible forward scenarios, but it should always be used with independent analysis and proper risk management.
Indicator

Obj_XABCD_HarmonicLibrary "Obj_XABCD_Harmonic"
Harmonic XABCD Pattern object and associated methods. Easily validate, draw, and get information about harmonic patterns. See example code at the end of the script for details.
init_params(pct_error, pct_asym, types, w_e, w_p, w_d)
Create a harmonic parameters object (used by xabcd_harmonic object for pattern validation and scoring).
Parameters:
pct_error (float) : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym (float) : Allowed leg length/period asymmetry % (a leg is considered invalid if it is this % longer or shorter than the average length of the other legs)
types (array) : Array of pattern types to validate (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark, 6=Cypher, 7=Alt-Bat, 8=Deep Butterfly, 9=Deep Crab)
w_e (float) : Weight of ratio % error (used in score calculation, dft = 1)
w_p (float) : Weight of PRZ confluence (used in score calculation, dft = 1)
w_d (float) : Weight of Point D / PRZ confluence (used in score calculation, dft = 1)
Returns: harmonic_params object instance. It is recommended to store and reuse this object for multiple xabcd_harmonic objects rather than creating new params objects unnecessarily.
method erase_pattern(p)
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic)
init(x, a, b, c, d, params, tp, p)
Initialize an xabcd_harmonic object instance from a given set of points
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
x (point type from reees/Pattern/1) : Point X
a (point type from reees/Pattern/1) : Point A
b (point type from reees/Pattern/1) : Point B
c (point type from reees/Pattern/1) : Point C
d (point type from reees/Pattern/1) : Point D
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
init(xX, xY, aX, aY, bX, bY, cX, cY, dX, dY, params, tp, p)
Initialize an xabcd_harmonic object instance from a given set of x and y coordinate values.
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
xX (int) : Point X bar index (required)
xY (float) : Point X price/level (required)
aX (int) : Point A bar index (required)
aY (float) : Point A price/level (required)
bX (int) : Point B bar index (required)
bY (float) : Point B price/level (required)
cX (int) : Point C bar index (required)
cY (float) : Point C price/level (required)
dX (int) : Point D bar index
dY (float) : Point D price/level
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
init(pattern, params, tp, p)
Initialize an xabcd_harmonic object instance from a given pattern
If the pattern is valid, an xabcd_harmonic object instance is returned. If you want to specify your
own validation and scoring parameters, you can do so by passing a harmonic_params object (params).
Or, if you prefer to do your own validation, you can explicitly pass the harmonic pattern type (tp)
and validation will be skipped. You can also pass in an existing xabcd_harmonic instance if you wish
to re-initialize it (e.g. for re-validation and/or re-scoring).
Parameters:
pattern (pattern type from reees/Pattern/1) : Pattern
params (harmonic_params) : harmonic_params used to validate and score the pattern. Validation will be skipped if a type (tp) is explicitly passed in.
tp (int) : Pattern type
p (xabcd_harmonic) : xabcd_harmonic object instance to initialize (optional, for re-validation/re-scoring)
Returns: xabcd_harmonic object instance if a valid harmonic, else na
method get_name(p)
Get the pattern name
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern name (string)
method get_symbol(p)
Get the pattern symbol from a pattern instance
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern symbol string
get_symbol(tp)
Get the pattern symbol for a given pattern type integer.
Static overload — does not require a pattern instance.
Parameters:
tp (int) : Pattern type (1=Gartley, 2=Bat, 3=Butterfly, 4=Crab, 5=Shark,
6=Cypher, 7=Alt-Bat, 8=Deep Butterfly, 9=Deep Crab)
Returns: Pattern symbol string
method get_pid(p)
Get the Pattern ID. Patterns of the same type with the same coordinates will have the same Pattern ID.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern ID (string)
method prz_range(p)
Returns cached PRZ upper and lower bounds.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns:
method incomplete_pid(p)
Returns the pattern ID as if point D were unconfirmed (na).
Used to match incomplete patterns against their completed counterparts
during deduplication. Ensures pid format is consistent with the
library's internal pid generation.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: Pattern ID string with D forced to na
method set_target(p, target, target_lvl, calc_target)
Set value for a target. Use the calc_target parameter to automatically calculate the target for a specific harmonic ratio.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
target (int) : Target (1 or 2)
target_lvl (float) : Target price/level (required if calc_target is not specified)
calc_target (string) : Target to auto calculate (required if target is not specified)
Options:
Returns: Target price/level (float)
method draw_pattern(p, clr)
Draw the pattern
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color)
Returns: Pattern lines
method erase_label(p)
Erase the pattern label
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: p
method draw_prz_levels(p, clr, extendBars)
Draw PRZ target levels as horizontal dashed lines for incomplete patterns.
Shows where point D needs to land without implying a specific price path.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color) : Line color
extendBars (int) : Number of bars to extend the lines to the right (default 50)
Returns: — the two PRZ level lines
method draw_label(p, clr, txt_clr, txt, tooltip)
Draw the pattern label. Default text is the pattern name.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
clr (color) : Label color
txt_clr (color) : Text color
txt (string) : Label text
tooltip (string) : Tooltip text
Returns: Label
method is_complete(p)
Returns true if the pattern has a confirmed point D.
A pattern is complete when D exists AND is not an unconfirmed pivot.
Use this instead of checking na(p.d.x) directly — invalid_d being
false is a required condition that bare na checks miss.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
Returns: bool
method age_pct(p, tLimitMult)
Returns how far through the pattern's time limit it is, as a 0.0–1.0 float.
0.0 = just confirmed, 1.0 = time limit reached.
Returns na if pattern has no confirmed D point.
Namespace types: xabcd_harmonic
Parameters:
p (xabcd_harmonic) : Instance of xabcd_harmonic object
tLimitMult (float) : Pattern time limit multiplier (same value used in main script)
Returns: float 0.0–1.0
harmonic_params
Validation and scoring parameters for a Harmonic Pattern object (xabcd_harmonic)
Fields:
pct_error (series float) : Allowed % error of leg retracement ratio versus the defined harmonic ratio
pct_asym (series float)
types (array)
w_e (series float)
w_p (series float)
w_d (series float)
xabcd_harmonic
Harmonic Pattern object
Fields:
bull (series bool) : Bullish pattern flag
tp (series int)
x (point type from reees/Pattern/1)
a (point type from reees/Pattern/1)
b (point type from reees/Pattern/1)
c (point type from reees/Pattern/1)
d (point type from reees/Pattern/1)
r_xb (series float)
re_xb (series float)
r_ac (series float)
re_ac (series float)
r_bd (series float)
re_bd (series float)
r_xd (series float)
re_xd (series float)
score (series float)
score_eAvg (series float)
score_prz (series float)
score_eD (series float)
prz_bN (series float)
prz_bF (series float)
prz_xN (series float)
prz_xF (series float)
przUpper (series float)
przLower (series float)
t1Hit (series bool) : Target 1 flag
t1 (series float)
t2Hit (series bool)
t2 (series float)
sHit (series bool) : Stop flag
stop (series float) : Stop level
entry (series float) : Entry level
eHit (series bool)
e (point type from reees/Pattern/1)
invalid_d (series bool)
pLines (array)
pLabel (series label)
cdLine (series line)
pid (series string)
params (harmonic_params) Library

Indicator

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 PulseWire 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. Indicator

SeasonalTrader Pro - Seasonal Edge ScannerSeasonalTrader Pro - Seasonal Edge Scanner is a Daily-based seasonal statistics scanner. It searches for recurring calendar-window behavior by comparing the current seasonal period with the same historical periods over a configurable lookback range.
The script scans potential entry and exit windows within a defined Daily scan horizon and evaluates Long, Short, and Range/Mean-Reversion candidates. All statistical calculations are based on Daily data. Lower chart timeframes can be used for visualization and trade observation, but they do not change the scan basis.
Methodology
For each tested seasonal window, the script compares the same calendar period across historical years and calculates directional and range-based statistics.
Directional Long/Short statistics include:
- historical win rate
- average return
- average drawdown
- SQN-style consistency metric
- sample count
- MAE/MFE-based risk and target reference levels
- recent stability and outlier impact checks
Range/Mean-Reversion statistics include:
- average historical range size
- net movement relative to the full range
- range efficiency
- close-inside rate
- breakout rate
- range quality and range eligibility
The scanner then applies an Auto Quality layer. This layer ranks and filters candidates using sample confidence, raw score, final quality grade, separation from competing Long/Short/Range candidates, outlier risk, stability, plateau robustness, and tradeability context.
AutoQ / Quality Engine
The AutoQ system is used to reduce weak or isolated seasonal candidates. It is not a trade signal by itself.
Quality evaluation includes:
- confidence-adjusted win rate
- minimum sample depth
- average return and drawdown requirements
- SQN contribution
- Long/Short/Range separation
- outlier and overfit checks
- recent-year stability
- plateau robustness around the selected window
- tradeability state of the current seasonal window
The Quality Strength setting controls how strict this filter is. A value of 0 enables a reference scan mode based mainly on the raw minimum win rate.
Bias Classification
The indicator can classify the current seasonal context as:
- LONG Bias
- SHORT Bias
- RANGE / MR Bias
- NO EDGE
The bias classifier compares the best eligible directional and range candidates. In Auto mode, Range only wins when the range score and quality context are strong enough compared with the directional alternatives. Directional-only and Range-only modes are also available.
Seasonal Potential Panel
The Seasonal Potential panel evaluates the currently selected Daily edge after the quality filter. It does not describe a general market bias. It evaluates whether the selected seasonal idea still has usable potential at the current point in the window.
The panel combines:
- current tradeability state: Pre, Active, Late, Expired, Invalidated, No Edge
- volatility fit
- move used or range position
- remaining potential
- seasonal risk/reward
- invalidation distance or breakout risk
- robustness score
- outlier risk
- final quality summary
For directional setups, the potential model uses historical MFE/MAE behavior to estimate remaining move, late-entry risk, and invalidation context. For range setups, it evaluates range position, range expansion, mean-reversion behavior, and breakout risk.
Risk / Reward Bands
The optional Risk/Reward bands are derived from the selected Daily seasonal window and its historical MAE/MFE distribution.
Displayed levels may include:
- Median MFE
- 75th percentile MFE
- Median MAE
- 75th percentile MAE
These levels are statistical reference areas only. They are not fixed targets, stops, or execution rules.
Historical Verification
The script can display historical verification periods on the chart and in a table. This allows visual inspection of how the selected seasonal window behaved in previous years.
Directional verification shows yearly profit/loss and drawdown.
Range verification shows range efficiency, range size, net movement, and whether the historical window behaved as range, mean-reversion, or breakout.
Projection and Zone Locking
Future seasonal zones are projected from Daily timestamps. The script supports projected Long, Short, Range, Best Zone, or All Regime views.
Visible zones are stabilized through a lock mechanism:
- active zones remain locked until expiry
- pending zones can update depending on the selected pending-lock policy
- projected timestamps can use either trading-day estimation or calendar-day projection
This is intended to prevent visible zones from shifting unnecessarily once a seasonal window becomes active.
Alerts
The script provides alert conditions for selected seasonal state changes, including:
- potential becoming strong or weak
- late-entry risk
- move exhaustion
- invalidation
- 75% MFE reached
- weak robustness
- high outlier risk
- expired or invalidated window
- range breakout risk
Alerts refer to the selected seasonal edge and should be interpreted together with the chart context.
Important Limitations
This is a statistical analysis tool, not a standalone trading system.
The indicator does not place orders, define position sizing, or account for commissions, spread, slippage, funding costs, or execution quality. Seasonal behavior can change due to regime shifts, macro conditions, liquidity changes, market structure changes, or symbol-specific events.
All main calculations are Daily-based. Lower timeframes may help with execution timing, but they do not increase the statistical sample size or change the seasonal scan.
Historical recurrence does not guarantee future behavior. The output should be used as contextual information together with independent market analysis and risk management. Indicator

Indicator

ADF Stationarity Pulse [forexobroker]ADF Stationarity Pulse runs the Augmented Dickey-Fuller test live on price and gates mean-reversion entries by whether the test currently rejects the unit-root null. The ADF test is the standard econometric tool for asking "is this series mean-reverting or does it have a random-walk component?". When ADF says mean-reverting AND the price z-score says price is stretched away from its rolling mean, the script trades the reversion. Built for crypto pairs, where statistical regimes flip between trending and choppy mean-reversion frequently.
🔶 ALGORITHM
1. Over the ADF window (default N=40 closes), the regression Dp_t = a + g * p_{t-1} + b * Dp_{t-1} + e is fit via closed-form OLS using cross-sum accumulation (single loop, no nested O(N^2)).
2. The variables are centered to absorb the intercept, then a 2x2 system solves for gamma (the unit-root coefficient) and beta (the lag-differenced coefficient).
3. Residual sum of squares is used to compute sigma^2 and the standard error of gamma.
4. ADF statistic = gamma / SE(gamma). Compared to the 5% critical value of -2.86 (approximate, for AR(1)-with-drift).
5. Z-score = (close - SMA(N)) / stdev(N) measures how far price is from its mean.
6. Buy fires when ADF rejects the unit root (mean-reverting) AND z-score is stretched below -threshold. Sell mirrors above +threshold.
🔶 SIGNAL LOGIC
- Buy: ADF stat < critical value AND z-score < -threshold AND session filter passes AND position is not already long AND cooldown bars elapsed AND barstate.isconfirmed.
- Sell: ADF stat < critical value AND z-score > +threshold AND session filter passes AND position is not already short AND cooldown bars elapsed AND barstate.isconfirmed.
Both conditions are required — being stretched in a trending regime is not enough, the test has to first confirm mean-reversion.
🔶 INPUTS
- Calculation group: ADF window N (default 40), 5% critical value (default -2.86), warning line (default -1.5).
- Signal Logic group: z-score threshold (default 1.0), cooldown bars (default 15).
- Filters group: session restriction (default 0000-2400).
- Visual group: z-score plot, dashboard, 3-layer glow, colors.
🔶 ALERTS
ADF Buy, ADF Sell, ADF Any Signal, ADF Regime On, ADF Regime Off, ADF Warning Cross, ADF Z Stretched Down, ADF Z Stretched Up, ADF Z Mean Reclaim, ADF Webhook JSON.
🔶 LIMITATIONS
- The 5% critical value is approximate; published tables vary slightly with sample size and specification. -2.86 is the conventional reference for AR(1)-with-drift at N around 50.
- ADF assumes a specific lag structure (one differenced lag); on higher-order autocorrelated series the test may misclassify regimes.
- The regression uses a fixed window of N closes; very early chart history has insufficient data and the test returns near zero.
- Mean-reversion entries can fight strong trends if the ADF window happens to span a flat patch inside the larger trend — use higher timeframes or a longer N to suppress this.
- Crypto pairs with frequent gap behavior (weekend lulls, exchange halts) violate the i.i.d. residual assumption ADF rests on.
Indicator

Indicator
