Market Regime LensMarket Regime Lens
Market Regime Lens reads the market on four independent axes and gives you one honest sentence about the current tape. It is a context descriptor, not a signal — it never tells you which way to trade. It tells you whether the tape is readable, how it moves, how long things take, and how risk is arriving.
WHY FOUR AXES, ONE COMPONENT EACH
Most multi-indicator tools stack measures that secretly say the same thing — three complexity metrics agreeing is not confirmation, it is autocorrelation. This tool deliberately uses one component per independent axis, so each number tells you something the others cannot.
STRUCTURE — Complexity-Entropy plane. Bandt-Pompe permutation entropy paired with Martin-Plastino-Rosso statistical complexity, classifying the tape as structured, mixed, or noise. Thresholds are adaptive by default: the reading is ranked against the instrument's own recent range, so it self-calibrates to any market and timeframe instead of relying on absolute cutoffs that break when you change the window.
PERSISTENCE — Anomalous-diffusion exponent. Fitted from mean-squared-displacement scaling across lags: alpha above 1 means super-diffusive (trending), alpha near 1 is a random walk, alpha below 1 is sub-diffusive (mean-reverting). This describes the character of the motion, not its direction.
TIME — First passage and null odds. Expected bars to reach the target versus the stop under a driftless diffusion, plus the null barrier probability P = b/(a+b) — what a coin flip gives you at your chosen reward-to-risk. At 1.5R that is 40%. That is the breakeven any setup must clear, stated plainly.
TAIL — Extremal index. Measures whether extreme moves cluster (theta below 1) or arrive independently. Clustered tails mean gap risk shows up in bursts, which matters for stop placement.
ON THE CHART
The main line is the diffusion exponent, colored by state and filled against the alpha = 1 random-walk baseline, so deviation from randomness is visible at a glance. Faint guides mark the trending and reverting thresholds. Background tint shows the structure class. The panel adapts to your chart theme and colors each row by meaning — including green or amber on the null-odds row depending on whether your chosen R gives better-than-even odds.
PAIRS WITH RISK & LEVELS COCKPIT
Optionally wire the target and stop sources to the Cockpit's exported levels, and the timing and null-probability rows use your real trade levels instead of internal ATR references.
WORKS ON ANY MARKET AND TIMEFRAME
All lookbacks are in bars with no session, expiry, or clock anchors. Non-repainting: everything uses the current bar's data and confirms at close.
LIMITATIONS
Not a signal and not investment advice — no axis forecasts direction. Permutation entropy and complexity require a window much larger than d factorial; at dimension 4 use at least 300 bars, since short windows are undersampling-biased and pin to a constant. Adaptive thresholds classify relative to the instrument's own recent range, so "structured" means structured for this market lately, not in any absolute sense. First-passage times and the null probability assume driftless diffusion with constant volatility — a deliberate null baseline, not a forecast. The extremal index needs enough exceedances; too short a window pins it at 1.00.
CREDITS
Original implementation. Bandt and Pompe permutation entropy; Martin-Plastino-Rosso and Lopez-Ruiz statistical complexity via Jensen-Shannon divergence; anomalous-diffusion MSD scaling; Ferro-Segers runs estimator for the extremal index; first-passage-time and gambler's-ruin barrier theory. Indicator

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

Auction Regime Router Entropy Gate & Hurst MemoryAuction Regime Router — Entropy Gate & Hurst Memory
What it is
Every structure playbook fails in the wrong regime. Fading the value-area edge works when price is anti-persistent (stretches snap back); riding a breakout works when price is persistent (moves feed on themselves); and nothing structural works when the tape is noise. This tool measures two things — how much structure exists, and what kind it is — and routes to a plain-language answer: FADES VIABLE / BREAKOUTS VIABLE / STAND ASIDE. It decides which of your tools to trust, never buy or sell.
The two measurements (and how they work together)
Permutation entropy (Bandt–Pompe 2002) — the gate. It measures how disordered the recent price sequence is from the frequencies of ordinal patterns (which of the 6 orderings each price triplet takes). High entropy = all patterns equally likely = noise = no structural edge. The gate is self-calibrated: entropy is ranked against its own recent history, so "noisy" means noisy for this symbol and timeframe.
Hurst exponent (Hurst 1951; Mandelbrot) — the router. Memory via diffusion scaling: how the dispersion of K-bar returns grows with K. H > 0.5 = persistent → continuation regime; H < 0.5 = anti-persistent → reversion regime. Research supports the routing: mean reversion is empirically more probable and faster during anti-persistent periods.
The mashup logic is a hierarchy, not a mixture: the entropy gate overrides the Hurst read. If the tape is noise, the router says STAND ASIDE regardless of what H says — because a memory estimate on noise is meaningless.
The honesty steps
A dead zone around H = 0.5 (default 0.45–0.55): near a random walk the memory read is unreliable, so the router says MIXED rather than pretending. Practitioners commonly require a margin before activating a playbook; both thresholds are inputs.
A minimum-dwell filter (the standard anti-chattering design from switched-systems control): a new regime is announced only after it survives a set number of confirmed bars, so the read doesn't flip-flop bar to bar. The cost is that many bars of lag — stated, and adjustable.
Estimates are proxies from bar data with overlapping windows — descriptive of the recent past, not a prediction. The dashboard shows the state, how long it has persisted (regime age), how dominant it has been recently (stability %), and any pending regime with a countdown — nothing more.
How to use it
Add to any liquid symbol/timeframe; defaults suit intraday index futures. The script requests no external data of any kind, so it runs on every plan and every symbol.
Glance at the regime lane — the thin colored strip at the bottom of the pane: blue = continuation, violet = reversion, amber = noise, gray = mixed. The palette is deliberately direction-neutral — no green or red anywhere in regime coding, so nothing can be misread as a buy or sell.
The HTF STACK row shows the raw regime on three higher timeframes derived as multiples of the chart (defaults 3×, 5×, 15× — so a 5m chart reads 15m/25m/75m automatically, adapting to any chart). A ✓ in green = every timeframe agrees on the same actionable regime (strongest context). A ⚠ in amber = a higher timeframe reads NOISE or the opposite regime while the chart claims a playbook (weakest — reduce or wait).
Read the dashboard for detail: REVERSION → your value-area fade / band-reversion tools are in their element; CONTINUATION → your breakout / drive tools are; NOISE → the gate is closed, stand aside; MIXED → no clear routing, reduce. STABILITY shows how settled the read is; PENDING shows a forming regime with a countdown.
Regime-change tags print only on announced (dwell-confirmed) changes; alerts fire on entering each state.
Best used as the selector above your structure toolkit rather than as a standalone display.
What makes it original
Hurst and entropy oscillators exist. What this adds: (1) the hierarchy — a self-calibrated entropy gate that can veto the memory read, instead of two numbers side by side; (2) routing to auction playbooks in plain language (fade vs breakout viability), not a raw statistic; (3) honest dead zones, a minimum-dwell announcement filter, and stability/pending context instead of a binary flip at H = 0.500. It is a decision-hygiene tool for structure traders.
Concept credits
Ordinal-pattern (permutation) entropy — C. Bandt & B. Pompe (2002). Long-memory / rescaled-range analysis — H. E. Hurst (1951); fractal market framing — B. Mandelbrot. Regime-gated strategy selection — standard quantitative practice. Implementation and charting design are the author's own.
Important disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. Regime labels are descriptive statistics of recent bars; regimes change without warning and estimates are proxies. Validate independently and manage your own risk. Indicator

Adaptive Predictability Engine Entropy Gate, Regime RouterAdaptive Predictability Engine — Entropy Gate, Regime Router & Expert Committee
What it is
The Adaptive Predictability Engine is a governed decision framework, not another confluence average. It refuses to treat all market conditions as tradable. It applies a strict hierarchy: first it asks whether price is forecastable at all right now; if it is, it decides whether trend-style or reversion-style logic is appropriate; and only then does a small committee of transparent experts vote — with the committee continuously re-weighting itself toward whichever experts have been correct recently. When the market is unpredictable, the whole engine stands aside and shows nothing to trade.
It plots directly on price: long/short signals, the live entry/target/stop of the active trade, a plain-language dashboard, and an optional self-calibration panel that scores past signals in R-multiple expectancy (not just win rate).
Why these components are combined (mashup justification)
This is a deliberate, dependent stack — each layer conditions the next, so removing any one changes the layer below it. That is the difference between a governed engine and a bag of averaged indicators.
Predictability gate (permutation entropy + structure). Permutation entropy (Bandt–Pompe) measures the ordinal randomness of recent price across three time scales; this is blended with |Hurst − 0.5|, the distance of the market from a random walk, which is high for strong trends and strong mean-reversion. The blended predictability is percentile-ranked so the gate self-tunes per symbol and timeframe. If the tape is unpredictable, nothing downstream may fire. This is the master switch, and it is why the engine spends much of its time deliberately doing nothing.
Regime router (Hurst exponent). When structure exists, the Hurst exponent (generalized, via a structure-function slope) decides whether it is persistent (trend) or anti-persistent (mean-revert), and routes weight toward the appropriate family of experts rather than averaging trend and reversion logic together.
Expert committee (Hedge / multiplicative weights). Six deliberately diverse experts — price trend, volume-weighted price, order-flow delta, momentum exhaustion, volatility extreme, and range extreme — each cast a directional vote. Their weights update every bar by exponential regret (right experts gain influence, wrong ones lose it), with fixed-share regularization so no single expert can dominate and make the vote fragile.
Distribution-shift guard. If the recent return distribution moves materially versus a reference window, the engine freezes learning and cuts conviction until conditions settle, so stale weights don't drive trades through a regime change.
The output is a single decision = the regret-weighted vote of only the currently-appropriate experts, gated to zero whenever the tape is unpredictable.
How to use it
Add it to any liquid symbol and timeframe. Defaults are tuned for index futures (e.g. NIFTY) but every input is adjustable, and the Data source group lets you repoint price and volume for any market.
Watch the dashboard headline: LONG / SHORT / WAIT / STAND ASIDE. When a signal fires, the engine draws the entry, ATR target, and ATR stop so the action is concrete.
Treat the shaded background as a hard "do not trade" — the engine has judged the tape unpredictable.
Open the Edge calibration (advanced) panel to see, per market memory, the past R-expectancy of the engine's own signals versus a direction-matched baseline. Positive expectancy means the sample was profitable before costs; this is descriptive of the past, not a forward guarantee.
Use the Ablation (research) toggles to switch each layer off and see, on your own data, whether it earns its place.
What makes it original
Most published tools average indicators and hope. This one inverts the approach by asking whether to act at all before what to do, using information-theoretic predictability (permutation entropy) as a master gate, a memory estimate (Hurst) as a router, and online regret-minimization (Hedge) to arbitrate a diverse expert set — with built-in R-expectancy self-calibration so users can judge it honestly rather than on a cherry-picked screenshot. The order-flow expert reads finest-available lower-timeframe signed volume with automatic fallback. The coupling and governance order are the contribution; the individual estimators are classical and credited below.
Concept credits
Permutation entropy — Bandt & Pompe. Hurst exponent / long-range dependence — H. E. Hurst; Mandelbrot. Hedge / multiplicative-weights online learning — Freund & Schapire; Littlestone & Warmuth; Vovk. Efficiency/structure framing — Kaufman. Triple-barrier labelling and R-multiple expectancy — M. López de Prado. Wilson score interval — E. B. Wilson. Synthesis, governance design, and implementation are the author's own.
Important disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. No indicator has an inherent edge. The calibration panel is a descriptive summary of past behaviour on the current chart — not a backtest and not a forward prediction. Always validate independently, apply realistic costs and slippage, and manage risk. You are solely responsible for your trading decisions. Indicator

Entropy Oscillator [JOAT]ENTROPY OSCILLATOR
A pane oscillator that measures the Shannon entropy of recent returns — the information-theoretic measure of how uncertain (chaotic) vs how predictable (directional) the recent distribution of price moves has been. Low entropy = the market is in a directional regime; high entropy = the market is chopping. Unlike volatility, entropy does not care about how big moves are — only how concentrated their distribution is. That distinction is what makes it one of the cleanest regime-classification tools in quantitative finance.
Shannon entropy, applied to markets
For a sequence of N recent log returns, the script:
Bins the returns into B equal-width bins across the empirical range.
Computes the probability of each bin (count / N).
Computes the Shannon entropy: H = −Σ p(i) · log(p(i)) over non-zero bins.
Normalises to by dividing by log(B) — the maximum possible entropy for B bins, which corresponds to a perfectly uniform distribution.
A perfectly uniform distribution (returns evenly spread across all bins → chaotic chop) produces normalised entropy of 1.0. A perfectly concentrated distribution (all returns in one bin → directional regime) produces entropy of 0. Real markets sit in between, and the script's job is to tell you where.
Two-threshold regime classification
Normalised entropy < low threshold (default 0.30) → DIRECTIONAL regime. The distribution of returns is concentrated; momentum tools work.
Normalised entropy > high threshold (default 0.70) → CHOP regime. The distribution is spread; reversion tools work.
Between the thresholds → MIXED regime. Neither side has the edge.
The thresholds are the spec-default institutional values; tighten or loosen for your instrument.
Slope-coloured entropy line
The smoothed entropy series is plotted in the pane with a slope-driven colour gradient — bull colour when entropy is falling toward directional, bear colour when entropy is rising toward chop. At a glance you can see which way the regime is moving even before it has crossed a threshold.
Visual system (pane + chart overlay)
In the pane:
Slope-coloured entropy line.
Threshold lines at low / 0.5 / high (toggleable).
Translucent fill zones for the low and high regions.
Pane background tint by current regime (toggleable).
On the chart (force_overlay):
Bar colouring — chart bars tinted by regime (cool when directional, hot when chop, neutral when mixed). Off by default.
Overlay background — subtle bgcolor projected onto the main chart marking the current regime. Off by default.
A locked Crimson Pulse palette (electric blue directional / lime-yellow chop / muted mauve mixed on a crimson-black ground) gives the pane a distinctive structural identity.
Regime Suggestion dashboard row
Like its sister script Hurst Regime Sentinel, Entropy Oscillator exposes a Suggested JOAT Indicator row that names the best companion script for the current regime. Defaults: AlphaTrend / Kalman Quantum Drift / Doppler Velocity Shift family for Directional regimes; Z-Score Reversion / Heisenberg Uncertainty Bands / Brownian Motion Residual / Renaissance Mean Reversion for Chop; Liquidity Magnet / Schrödinger Zone Probability / Fractal Dimension Index for Mixed. Every suggestion is user-configurable — you pick from the JOAT suite which tool the dashboard recommends per regime.
Dashboard
Monospaced table positionable to any of nine corners. Surfaces:
Current normalised entropy value.
Smoothed entropy and its slope direction.
Regime classification.
Bars in current regime.
Distance from entropy to nearest threshold.
Source series + window length + bin count in use.
Suggested JOAT Indicator (toggleable).
Alerts
Three alert conditions, each independently controllable:
Cross into Low Entropy (directional regime entry).
Cross into High Entropy (chop regime entry).
Any Regime Change (any classification flip).
How to read it
Two reads, in order of conviction:
Entry into Low Entropy — the directional commitment signal. The recent distribution of returns has narrowed; the market is in a momentum regime. Pair with a directional indicator (the dashboard's suggestion row tells you which).
Entry into High Entropy — the chop confirmation signal. Returns are widely distributed; momentum tools whipsaw, reversion tools work. Pair with a reversion indicator.
The "slope of entropy" itself is the leading read — when the line is falling toward the low threshold, a directional regime is forming; when it is rising toward the high threshold, chop is building. You do not need to wait for the threshold cross if you trust the slope gradient.
Suggested settings
Defaults (window 50 returns, 10 bins, EMA smoothing 3) are tuned for 15m–4H on liquid markets. The rule of thumb is window / bins ≥ 5 so each bin has enough samples to be statistically meaningful. For lower timeframes drop window to 30 and bins to 6. For HTF raise window to 100 and bins to 12.
Originality / what's reused
Shannon entropy is textbook 1948 information theory — public domain. The implementation here — the rolling N-return histogram pipeline with configurable bins, the log(B)-normalised entropy formula, the two-threshold regime classifier with mixed centre, the slope-coloured entropy line, the chart-overlay bar-colouring projection from the pane, and the user-configurable Suggested JOAT Indicator dashboard row — is JOAT-original. No third-party code reused.
Open source
Published open-source under the default Mozilla Public License 2.0. The histogram + entropy loop, the regime classifier, the slope-colour pipeline, and the dashboard are isolated modules. Forks welcome with credit.
Limitations
Shannon entropy describes the recent distribution of returns — it does not predict direction. A directional regime tells you momentum tools should work; it does not say which way. The histogram is sensitive to bin count and window length; the rule-of-thumb window / bins ≥ 5 is the default sanity check. EMA smoothing trades some lag for substantially reduced flicker; turn smoothing to 1 to see raw entropy.
—
-made with passion by jackofalltrades
Indicator

Permutation Entropy Complexity OscillatorPermutation Entropy — Complexity Oscillator
What this script does
This is a complexity oscillator: it measures, on a 0–1 scale, how random versus structured recent price action is — not which direction price is going, but whether there is any exploitable order to go on. It reads the order of successive moves (not their size): every three consecutive prices form one of six up/down shapes ("ordinal patterns"), and the oscillator measures how evenly those shapes are spread over a rolling window. Near 1, all shapes are equally likely — the tape is effectively random. Near 0, a few shapes dominate — the tape is structured and, in principle, more predictable.
Why these components are combined (mashup justification)
This is not several indicators shown side by side. There is exactly one plotted value — the normalized ordinal-pattern entropy — and every other element is a decision-support layer built on that single value:
The entropy engine is the core. Conventional price-level oscillators tell you where price is in its range; none of them tell you whether the range is even worth trading. Ordinal-pattern entropy is amplitude-free and noise-robust, so it isolates one orthogonal question — is there structure right now? — that the price-level family cannot answer.
The predictable / random thresholds classify the reading into a regime (structured / mixed / random). They don't add a second indicator; they interpret the one oscillator.
The statistical-complexity measure (complexity–entropy plane) is computed from the same ordinal-pattern counts and answers the question entropy cannot: low entropy alone can be genuinely structured or trivially degenerate (near-periodic). Pairing entropy with complexity separates "richly structured and potentially exploitable" from "low-entropy but trivial," so a signal only treats the tape as structured when both agree.
The momentum sign does nothing on its own — it only sets the direction of an already-armed regime signal. The bet is "a structured tape tends to keep doing what it's doing"; momentum just says which way that is.
The calibration harness is the reason the rest is trustworthy. It logs every signal the oscillator arms and, a fixed horizon later, checks whether price actually extended ≥ k×ATR in that direction — then reports Hit %, the unconditional Base %, and the Edge (Hit − Base).
Every part answers one question about the same entropy reading, which is why they belong in one script rather than as separate studies.
What makes it original
Two things. First, it brings an information-theoretic structure measure — usually seen only in research, not on charts — into a live, bounded oscillator with regime bands and a clean visual. Second, and more importantly, it does not assume the common claim that "low entropy means predictable, tradeable price." It tests that claim, live, on your instrument, with the built-in calibration harness. If low-entropy signals don't actually precede a forward move on your symbol and timeframe, the Edge row shows it plainly — often at or below zero. That honesty layer, not the entropy calculation alone, is the contribution.
How to use it
Add to a chart. Defaults target intraday index futures (e.g. NSE NIFTY); for other markets simply change the chart, or set the Price source input (group 01) — you can even feed it another indicator's output.
Read the regime at a glance from the background tint: green = genuine structure (low entropy and high complexity → the actionable state), amber = low-complexity / trivial low entropy (caution), grey = random / efficient tape (stand aside), no tint = mixed (wait). The line carries the same colour, with a bright line confirming genuine structure; the dashboard "Tape (plane)" chip shows the same state in words.
Optionally enable the statistical-complexity overlay (group 05) to see the complexity–entropy plane directly: it peaks at intermediate entropy where structure is richest and falls toward zero for both pure noise and trivial tapes. The dashboard shows the live complexity value and a ● when it clears the genuine-structure threshold.
Tie-robustness and delay τ (group 02): on discrete / tick-quantised instruments (index futures, where equal consecutive prints are common) equal values bias ordinal-pattern entropy toward false structure. The tie-robust dither (on by default) and an optional delay τ > 1 mitigate this; τ also probes a coarser timescale. Set τ = 1 and tie-robust off to reproduce the plain estimator.
Triangles mark the moment a predictable regime starts, with direction set by recent momentum — points to investigate, not automatic entries. With the complexity gate on (default), a signal only arms when complexity also confirms genuine structure; turn it off to A/B that choice against the entropy-only signal in the Edge row.
Read the Edge row before trusting the signal. A positive Edge means structured starts preceded a forward move more often than chance here; near or below zero means low entropy is not buying you predictability on this instrument.
Window length, smoothing, embedding delay, the two entropy thresholds, the complexity threshold, the momentum length, and the calibration horizon / threshold are all configurable.
Limitations
Entropy describes the tape's structure, not its direction — low entropy can precede a clean trend or a clean oscillation. The momentum-direction bet is one testable interpretation, not a law; the calibration row is there precisely so you don't take it on faith.
Statistics are in-sample, close-to-close, without costs — a study aid, not a backtest.
The reading needs a full window before it is meaningful (the panel shows "warm" until then).
This is an analytical complexity study. It issues no automated buy/sell instructions and is not a strategy.
Concept credit
Permutation entropy / ordinal-pattern analysis — Christoph Bandt and Bernd Pompe (2002).
Information entropy — Claude E. Shannon (1948).
Statistical complexity (the complexity–entropy plane) — the MPR statistical-complexity measure of P. W. Lamberti, M. T. Martín, A. Plastino and O. A. Rosso, applied to markets via the complexity–entropy causality plane of L. Zunino, M. Zanin, B. M. Tabak, D. G. Pérez and O. A. Rosso (2010).
Tie / equal-value bias in ordinal patterns — informed by the work of D. Cuesta-Frau and colleagues (2018).
The implementation, the regime/threshold logic, the complexity gate, the tie-robust dither, the calibration harness and the packaging are original.
Disclaimer
For research and educational purposes only. This script is not financial advice, not a recommendation, and not a guarantee of future results. Indicators describe price behaviour; they do not predict the future. Trading carries risk of loss. Test on out-of-sample data and make your own decisions. The author accepts no liability for any use of this script. Indicator

Entropy VZO [Alpha Extract]A sophisticated volume-flow and market-information oscillator that combines pressure-weighted volume, statistical normalization, directional entropy, fractal efficiency, Gaussian smoothing, and signal-line analysis into one complete momentum framework. Entropy VZO is designed to measure whether bullish or bearish price movement is supported by meaningful volume while adapting its sensitivity to the quality and organization of current market structure.
Unlike a conventional oscillator displayed in a separate pane, Entropy VZO projects its momentum structure directly onto price using an ATR-scaled anchor. This provides a clear overlay of volume momentum, signal direction, histogram expansion, threshold zones, and dynamic pulse activity without separating the analysis from the underlying chart.
🔶 Pressure-Weighted Volume Flow Engine
Calculates directional volume using a blend of candle pressure and source-price direction. Candle pressure measures the relationship between the candle body and its full range, while source direction determines whether price is advancing or declining.
candlePressure = (close - open) / priceRange
closePressure = ta.change(src) > 0 ? 1.0 : ta.change(src) < 0 ? -1.0 : 0.0
signedPressure = clamp(candlePressure * 0.65 + closePressure * 0.35, -1.0, 1.0)
signedVolume = volume * signedPressure
volumeBase = math.max(ta.ema(volume, vzoLength), 1.0)
vzo = 100.0 * ta.ema(signedVolume, vzoLength) / volumeBase
This produces a more detailed estimate of bullish and bearish participation than assigning all volume according to candle direction alone.
🔶 Normalized VZO Framework
Standardizes the raw VZO against its recent average and standard deviation. This allows the indicator to evaluate current volume pressure relative to the instrument’s own recent behaviour.
Positive readings indicate stronger-than-normal bullish volume flow, while negative readings represent stronger bearish pressure. Larger absolute readings show that the current volume imbalance is becoming increasingly unusual relative to its recent history.
🔶 Directional Entropy Analysis
Measures how evenly upward and downward price changes are distributed across the selected lookback period.
Low entropy indicates that price direction is more ordered and consistent. High entropy indicates a less predictable environment where upward and downward movements are more evenly balanced.
This allows the indicator to give greater weight to volume signals occurring during organized directional movement and reduce their influence during noisy or indecisive conditions.
🔶 Fractal Efficiency Framework
Evaluates how efficiently price has travelled between the beginning and end of the selected lookback relative to the total path taken.
High efficiency indicates that price is moving directly with limited back-and-forth movement. Low efficiency indicates a more irregular path with greater noise and weaker directional structure.
🔶 Information-Weighted Momentum Engine
Combines directional entropy and fractal efficiency into a unified information-quality weight. This weight adjusts the normalized VZO according to how organized and efficient the current market environment is.
informationWeight = clamp((1.0 - entropy) * 0.55 + efficiency * 0.45, 0.05, 1.0)
spectralInput = vzoZ * sensitivity * (0.65 + informationWeight)
fisherCore = tanhSafe(spectralInput) * maxLevel
Volume pressure receives greater emphasis when price movement is both directional and efficient. Signals are moderated when market structure becomes noisy, balanced, or fragmented.
🔶 Bounded Nonlinear Transformation
Applies a protected nonlinear transformation to compress extreme readings into a stable visual range.
This prevents isolated volume spikes from overwhelming the indicator while preserving momentum direction and relative strength. The result is a bounded oscillator centered around zero.
🔶 Gaussian Signal Polishing
Uses custom Gaussian-weighted smoothing to reduce short-term noise while preserving recent momentum information.
Separate smoothing stages are applied to the main oscillator and histogram. Traders can adjust these settings to make the indicator more responsive or more selective depending on their market and timeframe.
🔶 Bullish, Bearish & Neutral Regimes
Classifies the market into three momentum conditions:
• Bullish when the oscillator is above its signal and above zero
• Bearish when the oscillator is below its signal and below zero
• Neutral when momentum direction and zero-line position are not fully aligned
This dual-confirmation structure helps distinguish established directional momentum from weaker signal-line movements.
🔶 ATR-Scaled Price Projection
Projects the oscillator directly onto the price chart using an EMA-based anchor and an ATR-adjusted visual range.
The projection automatically adapts to current volatility, allowing the indicator to maintain a consistent appearance across different assets, prices, and timeframes. The Visual Height setting controls how widely the oscillator is displayed around its price anchor.
🔶 Soft & Hard Momentum Zones
Displays configurable soft and hard momentum thresholds above and below the central price anchor.
Soft levels highlight developing momentum extremes, while hard levels identify stronger volume-flow displacement. These areas provide context for momentum intensity rather than acting as automatic reversal signals.
🔶 Dynamic Pulse Band
Displays a smoothed measure of absolute oscillator strength around the price anchor.
The pulse band expands as momentum intensity increases and contracts when momentum weakens. Its color follows the active regime, creating a visual representation of both directional bias and momentum amplitude.
🔶 Momentum Histogram
Measures the difference between the main oscillator and its signal line to show whether momentum is expanding or contracting.
Bright bullish readings indicate strengthening positive momentum, while faded bullish readings indicate that positive momentum is slowing. Bright bearish readings represent strengthening negative momentum, while faded bearish readings show bearish pressure losing force.
🔶 Signal Ribbon & Glow Architecture
Plots the main Entropy VZO line with a layered glow and an optional ribbon between the oscillator and signal line.
The ribbon changes color according to the active bullish, bearish, or neutral regime. This makes momentum alignment, crossovers, and transition periods easier to identify while maintaining chart readability.
🔶 Dynamic Candle Coloring
Optionally colors OHLC candles according to the current oscillator regime.
Bullish coloring appears when the oscillator is above both its signal and zero. Bearish coloring appears when it is below both references. Neutral coloring identifies mixed, transitional, or weakly confirmed conditions.
🔶 Real-Time Status Dashboard
Features a compact dashboard displaying the indicator’s most important information:
• Current bullish, bearish, or neutral regime
• Main oscillator value
• Normalized VZO Z-score
• Directional entropy percentage
• Fractal efficiency percentage
• Current volume relative to its EMA baseline
This provides an immediate overview of momentum direction, volume abnormality, market organization, directional efficiency, and participation strength.
🔶 Comprehensive Alert System
Includes alerts for the indicator’s primary momentum events:
• Entropy VZO Bull Swing
• Entropy VZO Bear Swing
• Entropy VZO Bull Trend
• Entropy VZO Bear Trend
Swing alerts trigger when the oscillator crosses its signal line. Trend alerts trigger when the oscillator crosses the zero level, allowing traders to monitor both early momentum shifts and broader directional transitions.
🔶 Why Choose Entropy VZO ?
Entropy VZO expands traditional volume-flow analysis by combining pressure-weighted volume, statistical normalization, directional entropy, and fractal efficiency within one adaptive momentum framework. Instead of treating every increase in volume equally, the system evaluates whether that participation is occurring inside an organized and efficient market environment.
The oscillator and signal line identify direction, the histogram measures momentum expansion, the pulse band displays intensity, and the soft and hard zones provide context for elevated readings. Its ATR-scaled projection keeps the complete framework connected directly to price, while the live dashboard provides fast insight into volume flow, entropy, efficiency, and the active regime.
Perfect for momentum traders, swing traders, trend-following traders, and systematic analysts who want a cleaner way to determine whether directional price movement is supported by meaningful and structurally efficient volume flow. Indicator

Stochastic Resonance Signal [JOAT]Stochastic Resonance Signal
Introduction
Stochastic Resonance Signal is an open-source indicator built on the physical principle of stochastic resonance — the counterintuitive phenomenon where a moderate level of random noise actually enhances the detection of weak periodic signals rather than degrading it. In trading terms: markets with low volatility noise may suppress trend signals, while a calibrated level of volatility noise can help reveal underlying directional structure.
This indicator computes a signal-to-noise score that normalizes a smoothed price derivative against ATR-based noise. The score peaks when a meaningful directional signal is present within a noise environment that is neither too quiet (which produces false flatness) nor too loud (which obscures the signal entirely).
Core Concepts
1. Signal Component
The raw signal is the smoothed rate of change of price — the first derivative of a filtered price series. An EMA is applied to close to produce a noise-reduced price, then the bar-to-bar difference of that EMA serves as the signal. Positive signal indicates upward momentum; negative indicates downward:
float emaPrice = ta.ema(close, i_signalLen)
float rawSignal = emaPrice - emaPrice
float normSig = rawSignal / (ta.stdev(rawSignal, i_normLen) + 0.0001)
The signal is normalized by its own rolling standard deviation, making it dimensionless and comparable across instruments.
2. Noise Component
Noise is defined as ATR normalized by its rolling standard deviation. This separates the volatility component from the directional component. When noise is very low, it contributes little penalty. When noise is very high, it heavily discounts the signal. The optimal noise range produces the highest SR score:
float noisePenalty = ta.stdev(atrVal, i_normLen) / (ta.sma(atrVal, i_normLen) + 0.0001)
float srScore = math.abs(normSig) / (1.0 + noisePenalty)
3. SR Score and Threshold
The final SR score combines signal strength divided by noise penalty. The score is plotted as a histogram and compared against a configurable threshold. When the score exceeds the threshold in the positive signal direction, a bullish event fires. When in the negative direction, a bearish event fires. Both require barstate.isconfirmed.
4. Regime Context
The indicator categorizes the current noise state as Low, Optimal, or High. The Optimal zone — where stochastic resonance theory predicts signal enhancement — is highlighted in the background. Signals fired during the Optimal noise zone are the primary intended use case.
Features
Normalized signal derivative: EMA-smoothed price rate of change, dimensionless
ATR noise penalty: Volatility normalized by its own distribution, not a fixed threshold
SR Score histogram: Visual representation of the signal-to-noise ratio each bar
Threshold crossover signals: Bull and bear signals when SR score exceeds the gate
Noise regime classification: Low, Optimal, and High noise zones labeled
Optimal zone background: Chart shading during the resonance-optimal noise window
Candle coloring: Candles tinted by current SR score direction and magnitude
Dashboard: Current SR score, signal value, noise level, and regime state
Alerts: Configurable bull and bear SR threshold crossing alerts
Input Parameters
Signal Engine:
Signal EMA Length: Smoothing for price derivative calculation (default: 10)
Normalization Length: Rolling window for z-score normalization (default: 50)
Noise Engine:
ATR Period: ATR length for noise estimation (default: 14)
Optimal Noise Low: Lower bound of optimal noise zone (default: 0.3)
Optimal Noise High: Upper bound of optimal noise zone (default: 0.8)
Signal Gate:
SR Score Threshold: Minimum SR score to fire a signal (default: 1.5)
How to Use This Indicator
Step 1: Identify the Noise Regime
Check whether the background shading is active (Optimal zone). Signals fired during optimal noise conditions have the theoretical backing of stochastic resonance theory behind them.
Step 2: Read the SR Score
A rising histogram above the threshold line in positive territory indicates a developing bullish signal. Crossing below the negative threshold indicates a bearish signal.
Step 3: Apply as a Momentum Filter
Use SR score direction to confirm or reject signals from other tools. An SR score rising strongly above its threshold while a support level holds adds conviction to a long setup.
Indicator Limitations
Stochastic resonance as a trading construct is a theoretical analogy, not a proven quantitative edge on its own
The optimal noise zone boundaries are heuristic; the true optimal noise level varies by instrument and timeframe
Normalization requires a minimum lookback before scores stabilize — expect less meaningful output in the first normLen bars
Originality Statement
The application of stochastic resonance theory to price signal detection — computing a signal-to-noise ratio using a normalized price derivative divided by an ATR noise penalty, with an explicit optimal noise zone classification — is an original analytical framing not found in existing published Pine Script indicators. This is not a standard oscillator; it is a physics-inspired signal processing approach adapted to price data.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. The stochastic resonance framework is a conceptual model and does not guarantee profitable signals. Trading involves substantial risk of loss.
-Made with passion by jackofalltrades
Indicator

Entropic Structure Bands [JOAT]Entropic Structure Bands
Introduction
Entropic Structure Bands is an open-source overlay indicator that dynamically selects the best-fitting Ordinary Least Squares regression window from recent structural pivots and surrounds that regression channel with entropy-adjusted deviation bands. The key innovation over standard regression channel indicators is twofold: the window length is selected optimally each bar by searching through available pivot anchors for the highest R² × log(N) quality score, and the band width is modulated by the current Shannon entropy of log returns — widening during chaotic periods and tightening during orderly ones.
Core Concepts
1. Optimal Regression Window Search
Rather than using a fixed lookback, the indicator records the bar index of every confirmed pivot high and low. Each bar, it tests several candidate windows anchored at recent pivots and selects the one that maximizes a performance score: R² multiplied by the natural log of the window length. This rewards both fit quality and window depth simultaneously:
float score = r2 * math.log(float(N))
// highest score wins; window updates every bar
if trial.perfScore > bestScore
bestScore := trial.perfScore
bestMdl := trial
The regression channel therefore adapts to where significant price structure has occurred, not to an arbitrary fixed period.
2. Shannon Entropy Modulation
Shannon entropy of the log return distribution is computed using a histogram-binning approach. Low entropy means returns are concentrated — price is moving in an organized, directional way. High entropy means returns are evenly distributed — chaotic, noisy conditions. Band width scales with entropy:
float entAdjDev = bestMdl.stdErr * (1.0 + entNorm * 0.8)
When entropy is low (below the configurable threshold), the market is classified as orderly and signals are enabled. This prevents signals from firing into chaotic conditions where regression bands have less predictive value.
3. Trend-Confluence Signal Logic
Signals require simultaneous alignment of six conditions: regression slope direction, price position relative to midline, recent pullback to the inner band, momentum confirmation, optional HTF slope alignment, optional ADX trending gate, and optional RSI gate. Each condition is individually toggleable. This multi-factor gate replaces simple band-crossover logic with a structured confluence requirement.
4. Forward Projection
The regression channel extends forward by a configurable number of bars beyond the right edge of the chart. A projection target label marks the estimated price at the end of the projection window based on the current slope and intercept. This gives visual context for where the regression model expects price to be if the current trend continues.
5. Z-Score Candle Coloring
Each candle's position within the channel is expressed as a Z-score (standard deviations from the regression midline). Candles far above the midline (overbought extension) are tinted bear-color; candles far below (oversold extension) are tinted bull-color. This provides immediate visual context for where price stands within its current regression structure.
Features
Dynamic regression window: Optimal window selected each bar from pivot anchor scan
R² quality gate: Configurable minimum R² prevents low-fit windows from being used
Entropy-adjusted bands: Band width scales with Shannon entropy of log returns
Multi-factor signal gate: Six independently configurable confluence conditions
Forward projection: Channel extended beyond right edge with target label
Z-score candle coloring: Candles painted by standard deviation position in channel
Inner and outer bands (±1σ, ±2σ): Gradient-filled channel layers
Glow-effect midline: Double-drawn center line with transparency for depth
10-row dashboard: R², entropy, Z-score, duration, HTF alignment, ADX, RSI, signal state
JSON webhook alerts: Alert messages formatted as JSON with EP, TP, SL, and R²
Input Parameters
Regression Engine:
Pivot Scan Horizon: Number of pivots to evaluate as regression anchors (default: 20)
Pivot Sensitivity: Left/right bars for pivot confirmation (default: 5)
Min R² Quality Gate: Minimum fit quality to use a window (default: 0.50)
Band Multiplier 1/2: Inner and outer band standard deviation multiples (default: 1.0, 2.0)
Entropy System:
Entropy Lookback: Bars for entropy calculation (default: 20)
Entropy Bins: Histogram bins for return distribution (default: 10)
Low Entropy Threshold: Threshold below which market is classified as orderly (default: 2.5)
How to Use This Indicator
Step 1: Read the Slope Bias
Check the dashboard's Slope Bias row. BULLISH or BEARISH indicates the current regression direction. This is the primary directional input.
Step 2: Check Entropy State
LOW (orderly) entropy is the condition under which signals are most reliable. HIGH entropy warns that the regression model is operating in a chaotic environment.
Step 3: Wait for Signal Labels
LONG and SHORT labels appear only when the full confluence gate is satisfied. Each label shows entry price, TP1, TP2, stop loss, and R² quality.
Indicator Limitations
Regression channels repaint historically when the optimal window shifts to a new anchor; use the confirmed-bar signals for non-repainting entry logic
In markets with very few pivots, the scan horizon may find suboptimal windows with low R²
Shannon entropy requires sufficient lookback to produce stable estimates
Originality Statement
The dynamic pivot-anchored regression window search using R² × log(N) scoring, combined with Shannon entropy-modulated band width and a six-condition confluence signal gate, is the original analytical architecture of this publication. No existing published Pine Script regression channel indicator implements adaptive window selection from pivot anchors with entropy modulation in this manner.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Regression channels are mathematical models of past price behavior and do not predict future price. Trading involves substantial risk of loss.
-Made with passion by jackofalltrades
Indicator

Entropic Regime Field [JOAT]Entropic Regime Field is an open-source market state classifier that uses three quantitative measures — Fractal Efficiency Ratio, a synthetic Hurst Exponent approximation, and a Garman-Klass volatility estimator — to classify each bar into one of three entropy states: LOW (predictable, directional structure present), TRANSITION (regime shift underway), and HIGH (chaotic, low-predictability environment). Directional signals from an Adaptive Momentum Oscillator are filtered to fire only during LOW entropy states, where momentum signals have historically more reliable edge than during random or chaotic market behavior.
The foundational premise is that markets alternate between periods of organized directional behavior and periods of disorganized random movement. Trading momentum signals indiscriminately across both environments degrades overall performance because the same signal that has edge in a trending market produces random outcomes in a chaotic one. By measuring the structural organization of price movement directly — rather than relying on ADX alone, which is a lagging momentum derivative — Entropic Regime Field attempts to identify when the market's behavior is organized enough for directional signals to have context.
Core Concepts
1. Fractal Efficiency Ratio (FER)
The FER measures how efficiently price has moved over a lookback period — the ratio of the net directional distance to the total path length of individual bar-to-bar changes. A value near 1.0 indicates straight-line directional movement; a value near 0.0 indicates constant reversals:
float ferNet = math.abs(close - close )
float ferPath = math.sum(math.abs(ta.change(close)), ferLen)
float ferVal = ferPath > 0.0 ? ferNet / ferPath : 0.0
2. Synthetic Hurst Exponent
The Hurst Exponent characterizes the memory of a time series. Values above 0.5 indicate persistence (trending), values near 0.5 indicate randomness, and values below 0.5 indicate anti-persistence (mean-reversion). A simplified Hurst estimate is computed using the variance ratio method:
float var1 = ta.variance(ta.change(close, 1), hurstWindow)
float var5 = ta.variance(ta.change(close, 5) / 5, hurstWindow)
float hurstEst= 0.5 * math.log(var1 / var5) / math.log(5) + 0.5
3. Garman-Klass Volatility Estimator
Standard ATR uses only the prior close and current high/low. The Garman-Klass estimator uses all four OHLC prices, producing a more statistically efficient estimate of true volatility:
gkBar = 0.5 * math.pow(math.log(high / math.max(low, syminfo.mintick)), 2.0)
- (2.0 * math.log(2.0) - 1.0) * math.pow(math.log(close / math.max(open, syminfo.mintick)), 2.0)
The GK estimate is averaged over a configurable period and normalized to a 0-100 percentile rank over the trailing 100 bars.
4. Three-Factor Entropy Classification
LOW entropy requires FER above a threshold AND ADX above a minimum AND Hurst estimate above 0.52. HIGH entropy is triggered when FER falls below a lower threshold OR ADX falls below a minimum. TRANSITION is the state between the two.
5. Adaptive Momentum Oscillator (AMO)
The AMO blends three momentum inputs with fixed weights: RSI(14) centered at 50 (40%), Stochastic(14) centered at 50 (35%), and Williams Percent Range(14) centered at -50 (25%). Directional signals fire only in LOW entropy when AMO crosses zero and KAMA confirms via crossover/under.
Features
Fractal Efficiency Ratio: Net directional move divided by total path length, configurable lookback
Synthetic Hurst Exponent: Variance ratio approximation identifying persistent vs. anti-persistent price behavior
Garman-Klass volatility: OHLC-based volatility estimator normalized to percentile rank over 100 bars
Three entropy states: LOW, TRANSITION, HIGH — each with distinct visual treatment
10-line entropy ribbon: EMA lines colored by entropy state for visual history of regime transitions
Adaptive Momentum Oscillator: RSI + Stochastic + WPR composite with fixed optimal weights
Entropy-gated signals: AMO + KAMA confirmation signals fire only in LOW entropy state
Regime background tint: Background tinted by entropy state, cleared after 10 bars
Trade block on signal: ATR-based TP and stop rendered as boxes on signal bars
12-row institutional dashboard: FER, Hurst estimate, GK volatility percentile, ADX, AMO, entropy state, signal, win rate, bars in current state
Non-repainting: All signals gated by barstate.isconfirmed; no future data referenced
Four color themes: Phantom, Neon, Classic, Solar
Input Parameters
Fractal Efficiency:
FER Lookback (default: 14)
LOW Entropy FER Minimum (default: 0.60)
HIGH Entropy FER Maximum (default: 0.35)
Hurst Exponent:
Hurst Window (default: 20)
LOW Entropy Hurst Minimum (default: 0.52)
Garman-Klass Volatility:
GK Averaging Length (default: 14)
ADX Gate:
Min ADX for LOW Entropy (default: 22)
Signal:
AMO Cross Threshold, KAMA Period, Cooldown Bars
TP ATR Multiple, SL ATR Multiple
How to Use This Indicator
Step 1: Read the Entropy State
Check the dashboard. LOW entropy means the market is behaving in an organized, directional way — this is when momentum signals carry more weight. HIGH entropy means the market is chaotic — avoid directional signals.
Step 2: Watch FER and Hurst Together
FER and Hurst are independent measures of market organization. When both agree (high FER AND Hurst > 0.52 simultaneously), the LOW entropy classification is more reliable.
Step 3: Enter on AMO + KAMA Confirmation
Signals fire only when the AMO crosses zero in the signal direction AND price crosses the KAMA level simultaneously. Both conditions must occur on the same confirmed bar in a LOW entropy environment.
Indicator Limitations
The Hurst approximation via variance ratio is a simplified estimate. It should be treated as a directional indicator of persistence, not a precise statistical measure
The FER computation on every bar may affect chart loading performance for very long lookback periods on large datasets
LOW entropy classifications can persist during slow grinding trends that produce high FER but low volatility. These environments may produce signals with narrower ATR-based targets
The GK estimator can return unreliable values when open equals close (as occurs on some synthetic instruments or during gaps)
This indicator classifies entropy state. It does not predict how long the state will persist or when it will change
Originality Statement
The combination of Fractal Efficiency Ratio, synthetic Hurst Exponent via variance ratio, and Garman-Klass volatility estimator as a three-factor entropy classification system gating AMO momentum signals is not replicated in any existing open-source Pine Script v6 publication as of this writing
The Garman-Klass estimator as a volatility input provides a more statistically efficient OHLC-based volatility measure that captures intraday range information not available in ATR
Gating a composite three-input momentum oscillator by an entropy state derived from completely different mathematical principles (efficiency, persistence, and OHLC volatility) rather than using a single lagging derivative like ADX as the sole filter is an original analytical architecture
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Trading involves substantial risk of loss. Entropy classifications are approximations based on historical price data and do not guarantee future market behavior will repeat. The Hurst approximation used is a simplified estimate, not a statistically rigorous computation. Past win rates do not predict future performance. The author accepts no responsibility for trading losses resulting from use of this indicator.
Made with passion by jackofalltrades
Indicator

Quantum Flux Bands [JOAT]Quantum Flux Bands
Quantum Flux Bands is an institutional-style regime detector. It stationarizes the price series via Fixed-Window Fractional Differentiation (FFD), runs a classical CUSUM change-point test on the stationarized stream, and draws a baseline that snaps to a new price level on every confirmed regime shift. Around the baseline, three percentile envelopes (50%, 68%, 90%) are drawn and modulated by a windowed Shannon entropy estimator so the bands narrow in low-noise regimes and widen in high-noise regimes.
What makes it different
Most regime filters hard-code a differentiation order (typically the first difference). FFD takes a real-valued differentiation order d between 0 and 1, retaining long-memory while making the series statistically stationary. This script chooses d adaptively from a rolling Hurst estimate so it responds to the market's persistence regime instead of being a fixed magic number.
The CUSUM trigger is fed by FFD-stationarized values, not raw returns. This reduces baseline whipsaws in trending markets that violate stationarity assumptions of classical CUSUM.
The bands are entropy-weighted. When the local windowed Shannon entropy is high (low signal-to-noise) the bands expand. When entropy is low (clean regime) they contract. The bands lock at the moment of a confirmed regime shift so they describe the regime under which the baseline was established.
How it works
A two-point Hurst estimator (rescaled-range over short and long windows) drives an adaptive differentiation order d in the range 0.30 to 0.90.
FFD weights are recomputed only when d drifts by more than 0.05 from its cached value. Caching keeps per-bar work near zero.
FFD weights are applied to a sliding window of close prices to produce a stationarized series.
Classical CUSUM tracks cumulative positive and negative deviations of the stationarized series from a running baseline reference, with user-configurable drift and threshold parameters.
When CUSUM exceeds the threshold, the baseline snaps to the current close and the trend state is set to bull or bear.
Inner, mid, and outer envelopes are drawn from percentile_linear_interpolation of the absolute distance between close and baseline, multiplied by an entropy modulator.
A bull probability is computed from the Abramowitz and Stegun standard-normal CDF on the signed band-distance and surfaced as a numeric label.
Reading the chart
Baseline line tinted purple in bull regimes, cyan in bear regimes, muted in neutral.
Six percentile band lines (upper and lower inner, mid, outer) with three pairs of atmospheric gradient fills calibrated so candles remain readable through every layer.
Optional iridescent candle recolor scales tint by signed regime score.
A probability label at the right edge of the chart shows the live bull probability.
Seven right-edge price labels, one per envelope level plus baseline, each sit at their own price.
Regime-shift timeline labels record every confirmed regime change with its baseline price and bull probability at the time of the shift.
A 21-segment vertical strength gauge at the right edge maps the continuous regime strength score onto a bull / bear / neutral scale, with a dashed sight-line drawing the gauge level back into the chart.
A short forward probability cone: two dashed segments at outer band levels with opacity scaled by class probability.
Signals
Bull / bear regime entry (CUSUM trigger with direction)
Outer band touch
Outer band rejection (wick pierces the outer band but the body closes back inside)
Baseline reclaim (close re-crosses the baseline)
All gated on barstate.isconfirmed or barstate.ishistory. No future references. No lookahead_on.
Inputs
Fractional Differentiation : FFD window length.
CUSUM : volatility period, drift parameter, threshold parameter.
Regime : Hurst short / long lookbacks, entropy window / bins / z-score length.
Bands : percentile lookback.
Visual : bullish, bearish, quantum purple, quantum cyan colors. Band visibility toggles. Iridescent candles. Regime pulse. Probability label.
Labels : right-edge level labels, regime timeline (offset off candle wicks by ATR), baseline reclaim markers (direction-sensitive Y offset, configurable minimum-bar spacing), band touch and rejection labels (configurable minimum-bar spacing per type), strength gauge, sight-line needle, probability cone, FFD memory label, entropy state strip.
Dashboard : position, size.
How traders use this
Mean-reversion fades from outer-band touches inside a stable regime (Hurst mean-reverting, low entropy z) are statistically supported setups.
Regime-shift entries : when the baseline snaps and the trend turns, the first inner-band retest is a higher-quality continuation entry than chasing the breakout bar.
Probability filter : use the bull probability label as a confidence multiplier for other systems. Below 30% or above 70% are the actionable zones.
Entropy context : high entropy z (band-multiplier expanded) is a low conviction, wider stops warning. Low entropy z (bands tight) is a high conviction, tighter stops green light.
Limitations
Fractional differentiation is a smoothing and filtering tool. It cannot create information that is not already in the price series.
CUSUM, like any change-point detector, lags real-time tops and bottoms. It is calibrated to balance whipsaw against responsiveness.
The two-point Hurst estimator is a fast approximation. For long-horizon classification it agrees with the full R/S statistic. For very short windows it is noisier.
Past regime persistence does not guarantee future regime persistence.
Compatibility
Pine Script v6 open-source indicator. Any symbol, any timeframe (longer timeframes give the FFD window more meaningful history). No external request.security calls. Non-repainting: regime shifts are committed on confirmed bars and baseline values are not retroactively rewritten.
Defaults
Mint and red bullish / bearish defaults. Purple and cyan quantum accents. Top-right medium dashboard. All on-chart visualizations on. Increase the FFD window for very high timeframes (daily and above) and decrease the percentile lookback for fast intraday charts.
Credits
Fractional differentiation methodology popularized by López de Prado, Advances in Financial Machine Learning (2018).
CUSUM change-point test as published by E. S. Page, Biometrika (1954).
Standard-normal CDF approximation per Abramowitz and Stegun (1964).
Indicator

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

Markowitz Frontier Compass [JOAT]Markowitz Frontier Compass
Introduction
Markowitz Frontier Compass compares the chart symbol against a peer basket using inverse-volatility weights, correlation drag, diversification benefit, factor scores, and active risk budget.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Inverse-Volatility Basket
Each peer receives an inverse-volatility weight to form a portfolio-context benchmark.
2. Correlation Drag
Average pairwise correlation reduces diversification value when assets move together.
3. Factor Composite
Quality, momentum, low-volatility, and carry-style behavior are combined.
4. Risk Budget
Institutional grade, entropy, concentration, and factor state become active or defensive budget context.
frontierScore = efficiency + diversification - correlationDrag - concentration
Features
Peer basket context
Inverse-volatility weighting
Correlation drag and diversification benefit
Factor composite and allocation entropy
Risk-on, defense, and factor-prime states
Input Parameters
Peer symbols
Return window and smoothing
Risk-free annual percent
Correlation stress and concentration gates
Display toggles and HUD position
How to Use This Script
Use MFC as cross-asset context. Risk-on or factor-prime states suggest constructive basket behavior; defense states warn of stress.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
MFC is original in combining portfolio theory, factor scoring, entropy, and risk-budget logic in one open-source study.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades
Indicator

Veyra Delta Lens [JOAT]Veyra Delta Lens
Introduction
Veyra Delta Lens estimates delta pressure from OHLCV data and converts it into auction pressure, CVD z-score, participation entropy, absorption, and pressure-shift events.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Signed Volume Pressure
Candle close location and body impact estimate directional volume pressure.
2. CVD Normalization
Cumulative pressure is normalized so current pressure can be compared with recent history.
3. Participation Entropy
Volume concentration and close location distinguish balanced absorption from directional release.
4. Pressure Envelope
An auction mean and delta rails display pressure on the price chart.
delta = signedVolume * 0.65 + impactVolume * 0.35
Features
Estimated signed volume pressure
CVD z-score and impulse scoring
Absorption and divergence context
Auction mean and pressure rails
Sparse VX+ and VX- labels
Input Parameters
Delta smoothing and impulse memory
CVD normalization window
Participation entropy window
Event score and cooldown
Rails, trace, and candle toggles
How to Use This Script
Use VX+ and VX- labels as confirmed pressure shifts. Gold circles show absorption or divergence conditions aligned with the current regime.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
Veyra is original in combining estimated delta, CVD normalization, entropy, auction rails, absorption, and divergence in one restrained overlay.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades
Indicator

Sidereal Session Lattice [JOAT]Sidereal Session Lattice
Introduction
Sidereal Session Lattice is an open-source intraday session-orbit indicator. It maps session phase, VWAP drift, volatility harmonics, entropy, and anomaly pressure into adaptive orbit bands and compact phase cells.
The indicator is designed to answer a session-context question: is price moving with the current session phase, stretching beyond its orbit, or compressing into balance?
Core Concepts
1. Session Phase
Each active session is counted bar by bar. The bar count is converted into a normalized phase value from 0 to 1.
2. Harmonic Orbit
The phase value is transformed with sine waves to create an intraday harmonic component. This does not predict price; it creates a reference curve for studying session rhythm.
3. VWAP Drift
The script tracks the distance between price and session VWAP, then normalizes the drift by ATR.
4. Entropy and Anomaly Rank
The script compares recent up/down candle energy and return magnitude to estimate balance and anomaly pressure.
5. Phase Cells
Compact cells mark upper-orbit events, lower-orbit events, and balance compression.
Features
Session phase model: Tracks where the market is inside the active session cycle
VWAP drift: Measures price displacement from session VWAP
Harmonic orbit bands: Adaptive bands based on phase, volatility, and drift
Entropy score: Measures up/down energy balance
Anomaly rank: Highlights unusual movement relative to recent behavior
Phase cells: Compact boxes show session-orbit events
Dashboard: Shows phase, lattice score, drift, entropy, anomaly, and current state
Input Parameters
Primary session defines the active session window
Cycle bars controls the phase cycle length
Drift smoothing controls VWAP drift smoothing
Entropy memory controls bid/ask balance memory
Anomaly memory controls return-rank comparison
How to Use This Indicator
Step 1: Read the phase state
The dashboard names the current session phase, such as open drive, balance, or close risk.
Step 2: Watch orbit events
Upper and lower orbit cells mark when price stretches beyond the adaptive session orbit.
Step 3: Use entropy for balance context
High entropy with low anomaly often indicates balanced conditions.
Indicator Limitations
The harmonic orbit is a reference model, not a forecast
Session behavior varies by symbol and exchange hours
Entropy and anomaly values are derived from chart bars and may change with timeframe
Originality Statement
Sidereal Session Lattice combines session phase, VWAP drift, harmonic references, entropy, and anomaly ranking. It is not a standard session high/low tool; it provides a structured way to study intraday rhythm and displacement.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Session models can fail in news, gaps, and unusual liquidity conditions.
-Made with passion by jackofalltrades
Indicator

Kairo Pressure Reversal [JOAT]Kairo Pressure Reversal
Introduction
Kairo Pressure Reversal is an open-source pressure-tensor study that maps how candle structure, volume, volatility stress, entropy, and pressure curvature interact. It is not a conventional POC or value-area script. Its purpose is to identify pressure shocks, curvature reversions, and compression states as market-context events.
Core Concepts
1. Pressure Atom
Each candle is converted into a signed pressure value using close location, body direction, wick balance, and volume.
pressureAtom = (signedRange * 0.42 + bodyImpulse * 0.42 + wickBalance * 0.16) * volume
2. Pressure Tensor
The pressure atom is normalized by recent absolute pressure and smoothed. This produces the main pressure tensor used throughout the indicator.
3. Curvature and Jerk
The script calculates pressure velocity, curvature, and jerk. These values show how quickly pressure is changing rather than simply whether pressure is positive or negative.
4. Entropy
Bid and ask energy are converted into an entropy score. Higher entropy means pressure is more balanced. Lower entropy means one side is more dominant.
5. Stress Bands
ATR and pressure stress expand or contract the tensor bands. Events occur when price and pressure move into stressed areas with sufficient curvature.
Features
Pressure tensor: Normalized pressure model derived from candle structure and volume
Curvature analysis: Tracks pressure velocity, curvature, and jerk
Entropy score: Measures bid/ask balance
Volatility stress rank: Uses ATR and range ranking to identify stressed conditions
Shock cells: Compact boxes mark bid shocks, ask shocks, and reversion events
Tensor bands: Adaptive bands visualize pressure expansion and stress
Dashboard: Shows tensor, stress, entropy, curvature, jerk, and current event state
Input Parameters
Tensor memory controls pressure normalization
Entropy memory controls bid/ask energy balance
Stress rank memory controls volatility ranking
Shock gate controls event sensitivity
Reversion gate controls curvature reversion sensitivity
How to Use This Indicator
Step 1: Read the tensor direction
Positive tensor values indicate bid-side pressure; negative values indicate ask-side pressure.
Step 2: Watch stress and entropy
High stress with low entropy suggests one-sided pressure. High entropy suggests balance or compression.
Step 3: Treat cells as context
Shock and reversion cells mark pressure events. They are not standalone trade recommendations.
Indicator Limitations
Volume-based pressure is an approximation from chart candles, not true order flow
Curvature events can occur during volatility spikes that do not continue
The indicator provides context, not certain reversal points
Originality Statement
Kairo Pressure Reversal is original in its combined use of candle-derived pressure, entropy, curvature, jerk, volatility stress, and compact event cells. It focuses on pressure behavior rather than standard oscillator thresholds.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Pressure events can fail or persist longer than expected. Always use independent analysis and proper risk management.
-Made with passion by jackofalltrades
Indicator

[GYTS-CE] Pattern Texture Codex (PTC)Pattern Texture Codex (Community Edition)
🌸 Part of GoemonYae Trading System (GYTS) 🌸
🌸 --------- INTRODUCTION --------- 🌸
💮 What is the Pattern Texture Codex?
Standard technical analysis focuses on two dimensions: Amplitude (how far price moves) and Momentum (how fast price moves). The Pattern Texture Codex introduces a third: Structure (how price moves).
This indicator implements Permutation Entropy (PE), a complexity measure from dynamical systems theory that captures whether price evolves in structured patterns or chaotic noise. We call this "Market Texture":
🫧 Smooth Texture (Low Entropy): Price evolves in ordered, predictable patterns. Trends are durable and causality is high. Momentum strategies favoured.
🌵 Rough Texture (High Entropy): Price evolves chaotically. The market is noisy, trends are fragile. Mean reversion or defensive sizing recommended.
💮 Why Use This Indicator?
Most "entropy" indicators on PulseWire fall into common traps:
Shannon entropy of price histograms — measures value distribution but ignores temporal sequence
Approximate Entropy (ApEn) — measures amplitude similarity with O(N²) computational cost
Volatility metrics labelled "entropy" — captures magnitude, not pattern structure
Mathematical errors — normalised values that don't form valid probability distributions
The Pattern Texture Codex provides true ordinal pattern analysis — it examines the sequence of price movements, not just their distribution or magnitude. A smooth uptrend and choppy consolidation may have identical volatility, but their texture is completely different.
↑ Pattern Texture Codex with dynamic threshold bands. Rough Texture (high entropy) often indicates reversals, while Smooth Texture (low entropy) often precedes trend continuation.
🌸 --------- HOW IT WORKS --------- 🌸
💮 Core Concept: Ordinal Patterns
Instead of analysing raw price values, Permutation Entropy converts price into ordinal patterns — the relative ordering of consecutive data points.
For example, with embedding dimension D=3 (three points per pattern):
Pattern "012": first < second < third → ascending
Pattern "210": first > second > third → descending
Pattern "102": middle value smallest → valley shape
The indicator counts how often each pattern appears over a lookback window, then calculates the Shannon entropy of this distribution.
↑ With D=3, three consecutive data points determine each pattern. Left: ascending pattern "012" (first point smallest, second middle, third greatest). Right: descending pattern "210" (first point greatest, second middle, third smallest).
💮 Calculation Overview
The normalised Permutation Entropy is computed as:
H = −∑ p(π) · ln(p(π)) / ln(D!)
Where:
• p(π) is the probability of each ordinal pattern π
• D is the embedding dimension (number of points per pattern)
• D! is the total possible patterns (e.g., 4! = 24 for D=4)
The result ranges from 0 to 1:
• H → 0 : One pattern dominates — highly structured, predictable
• H → 1 : All patterns equally likely — pure randomness
↑ Full calculation example at D=3 showing the lowest entropy point (green vertical line). With 3!=6 possible patterns, the monotonic rising pattern "012" dominates while three other patterns occur only once. The frequency column feeds into the entropy contribution formula, yielding H(3)=1.039. Normalising produces 0.4019 — matching the indicator output exactly.
💮 Theoretical Background
Permutation Entropy has deep theoretical foundations. For piecewise monotone maps, it converges to the Kolmogorov-Sinai entropy — the fundamental measure of chaos in dynamical systems.
Key scientific properties:
• Scale invariance — analyses rank orderings, invariant to monotonic transformations
• Noise robustness — ordinal encoding naturally filters high-frequency noise
• Computational efficiency — O(1) amortised per bar with lookup acceleration
• Micro-structure sensitivity — captures specific sequence patterns, not just distribution
🌸 --------- KEY FEATURES --------- 🌸
💮 Lookup Table Acceleration
Standard PE requires sorting each embedding vector — O(D log D) operations per bar. This implementation uses precomputed transition tables from Unakafova & Keller (2013), reducing complexity to O(D) per bar.
The key insight: successive ordinal patterns in overlapping windows share (D−1) data points. Rather than recomputing from scratch, the algorithm derives the new pattern from the previous one using a single table lookup.
Enabled by default for Delay=1 and Dimension ∈ {3, 4, 5}
Falls back to standard calculation for D=2, D=6
💮 Flexible Threshold Modes
The indicator supports four independent threshold modes for both Smooth and Rough detection:
Static — Fixed threshold values you define
Dynamic — Adaptive bands based on entropy baseline ± standard deviation
Percentile — Threshold at Nth percentile of recent entropy history
Disabled — No threshold for that direction
You can mix modes: for example, Dynamic for Smooth detection while using Percentile for Rough detection.
🌸 --------- CONFIGURATION --------- 🌸
💮 General Settings
• Source — Price series to analyse (default: close)
• Smoothing Critical Period — Smoothing via 2-pole Ultimate Smoother (default: 0 = disabled). Reveals underlying texture by filtering entropy noise.
💮 Entropy Calculation
Dimension (D) — Points per ordinal pattern:
• D=3: 6 patterns — fast, stable. Good for limited lookback.
• D=4: 24 patterns — balanced, captures V-reversals. Recommended.
• D=5: 120 patterns — sensitive, captures W/M patterns. Noisier.
• D=6: 720 patterns — maximum sensitivity. No lookup acceleration.
Lookback — Estimation window size. Hard minimum: D × 5. Statistical recommendation: 5 × D! (e.g., 120 for D=4). Default: 100.
Delay (τ) — Stride between points in each pattern (default: 1). Change only for oversampled data.
Lookup Acceleration — Enables transition tables for D ∈ {3, 4, 5} with Delay=1.
💮 Threshold Management
Rough/Smooth Mode — Static, Dynamic, Percentile, or Disabled for each threshold
Static Values — Fixed threshold when Static mode selected
Std Dev Multiplier — Band width for Dynamic mode (default: 2.0σ)
Baseline/Deviation Length — Lookback for Dynamic mode calculations
Percentile Settings — Lookback and percentile values for Percentile mode
💮 Visualisation & Alerts
Palette — Colour scheme (default: GYTS Purple)
Colouring Bars — Applies texture colours to chart candles
Dark Mode — Optimises colour intensity for dark backgrounds
Alerts — Triggers when entropy crosses above/below thresholds
🌸 --------- USAGE GUIDE --------- 🌸
💮 Getting Started
Apply the indicator with default settings:
• Dimension: 4 (balanced complexity, captures V-shaped reversals)
• Lookback: 100 (responsive; statistical ideal: ≥120 for 5× coverage)
• Smooth Threshold: Dynamic mode with 2.0σ multiplier
Observe how entropy rises during choppy consolidation and falls during clean trends.
💮 Interpretation
Entropy Value (0 to 1):
Below 0.6: Strong pattern dominance — highly ordered
0.7–0.9: Normal complexity — typical market behaviour
Above 0.95: Near-random — patterns uniformly distributed
Transitions:
Watch for regime changes. When entropy rises sharply after a prolonged smooth period, the trend may be losing coherence. When entropy falls from elevated levels, a new trend may be establishing.
↑ Texture transitions during a trend-to-consolidation regime change. During the uptrend, similar patterns (D=3) recur frequently and entropy decreases. As the market transitions to consolidation, entropy rises — signalling the trend is losing structure.
💮 Trading Applications
Trend Filtering — Only take trend-following signals during Smooth texture.
Mean Reversion Timing — Elevated entropy often precedes mean reversion.
Position Sizing — Reduce exposure during Rough texture.
Exit Management — Tighten stops when entropy rises during a position.
💮 Integration with GYTS Suite
The Pattern Texture Codex exports two signals:
PE Continuous — Raw entropy value (0 to 1)
PE Ternary — State signal (+1 = Rough, 0 = Neutral, −1 = Smooth)
These can be read by Flux Composer or used as filter conditions with Market Regime Detector .
🌸 --------- PARAMETER TUNING --------- 🌸
💮 Lookback Selection
Shorter lookbacks react faster but may produce unstable estimates:
50–100: Responsive. Good for intraday regime detection.
100–200: Balanced. Recommended for swing trading.
200–500: Stable. Better for position trading or noisy instruments.
The indicator enforces a hard minimum of D × 5 to prevent meaningless output.
↑ Three dimensions (D=3, D=4, D=5) with their academically recommended minimum lookback periods.
💮 Threshold Tuning
For Smooth Detection:
Dynamic mode with 2.0σ works well across most instruments. Lower multipliers (1.5σ) detect structure earlier but may false-trigger.
For Rough Detection:
Percentile mode at 90th percentile identifies only extreme chaos. Static threshold of 0.95+ focuses on near-random conditions.
Consider disabling Rough detection entirely if your strategy only cares about identifying structured trends.
↑ The three threshold modes on the same PTC calculation. Both upper and lower thresholds are independently configurable.
🌸 --------- LIMITATIONS --------- 🌸
Amplitude Blindness — PE treats all patterns equally regardless of magnitude. A 0.1% drift and a 10% crash produce identical entropy if their ordinal patterns match.
Equal Values (Ties) — Handled via temporal tie-breaking (recent values rank higher), but heavily discretised data may produce edge-case behaviour.
Sample Size Requirements — Very short lookbacks (below D × 5) produce unreliable estimates. Statistical reliability improves with larger samples.
Not Predictive Alone — Low entropy indicates structure exists, not that the trend will continue. Combine with directional analysis for trading decisions.
Lag During Transitions — The sliding window approach introduces inherent lag when market texture changes.
🌸 --------- CREDITS --------- 🌸
💮 Academic Sources
Bandt, C., & Pompe, B. (2002). Permutation entropy: A natural complexity measure for time series. Physical Review Letters, 88 (17), 174102. DOI
Unakafova, V., & Keller, K. (2013). Efficiently measuring complexity on the basis of real-world data. Entropy, 15 (10), 4392-4415. DOI
Ehlers, J. F. (2024). The Ultimate Smoother. Technical Analysis of Stocks & Commodities , 2024-04. TASC
💮 Libraries Used
FiltersToolkit — Ultimate Smoother and other curated filters
PatternTransitionTables — Precomputed lookup tables for O(1) pattern transitions
ColourUtilities — Gradient palette generation and colour management
Indicator

AlphaQuant Statistical Intelligence█ ALPHAQUANT STATISTICAL INTELLIGENCE (QSI)
Quantitative Market Quality Analysis
A quantitative market analysis tool that measures the statistical "quality" of market conditions using three core modules: Hurst Regime Engine , Shannon Entropy Flow , and Price Efficiency Ratio . These combine into a single QSI Composite Score (0-100) that rates whether current conditions are favorable for trading or not.
Free and Open Source.
█ THE CONCEPT: WHY STATISTICAL MARKET QUALITY MATTERS
Most indicators answer "which direction?" — QSI answers a different question: "Should I be trading right now?"
Markets alternate between regimes: trending, mean-reverting, chaotic, and efficient. QSI identifies these regimes in real-time so you can adapt your strategy accordingly. A trending Hurst regime favors breakout strategies. A mean-reverting regime favors fading. High entropy means the market is chaotic — reduce size. High efficiency means clean directional moves — increase conviction.
█ CORE MODULES
1. Hurst Regime Engine
Calculates the Hurst Exponent via Rescaled Range (R/S) analysis — a robust statistical method from hydrology adapted for financial markets.
H > 0.55 — Trending regime. Price has "memory" — breakout/trend-following strategies work well.
H = 0.50 — Random Walk. No statistical edge — the market is coin-flipping. Reduce size.
H < 0.45 — Mean-Reverting regime. Price has "anti-memory" — fade strategies work well.
2. Shannon Entropy Flow
Measures the information entropy of the return distribution using the Shannon Entropy formula from information theory.
High Entropy (>70) — Returns spread across many bins = chaotic, unpredictable. Reduce exposure.
Low Entropy (<30) — Returns cluster in few bins = ordered, predictable. Good for systematic strategies.
3. Price Efficiency Ratio
Measures directional efficiency by comparing net price movement to gross price movement over N bars.
High Efficiency (>30%) — Price moving cleanly in one direction. Trend-following conditions.
Low Efficiency (<10%) — Price chopping with no net progress. Avoid or use range strategies.
█ QSI COMPOSITE SCORE
The three modules combine into a single 0-100 score with fixed weights:
Hurst Edge: 40% — How strong is the regime signal?
Inverse Entropy: 35% — How ordered is the market?
Efficiency: 25% — How clean are the price moves?
Score interpretation:
> 70 — PRIME — Optimal conditions, full conviction
55-70 — FAVORABLE — Good conditions, normal sizing
40-55 — NEUTRAL — Mixed signals, proceed with caution
25-40 — CAUTION — Poor conditions, reduce size
< 25 — AVOID — Worst conditions, stay out
█ DASHBOARD
A compact, dark-themed info panel displaying:
QSI INDEX — Current composite value with regime label
HURST — Current Hurst exponent with regime classification
ENTROPY — Current entropy score with regime classification
EFFICIENCY — Current efficiency ratio with regime classification
WEIGHTS — Module weight distribution (H:40 E:35 F:25)
█ ALERTS (8 CONDITIONS)
QSI: PRIME Conditions — Composite entered prime zone (>70)
QSI: AVOID Conditions — Composite dropped to avoid zone (<25)
QSI: Conditions Improving — Composite crossed above 55
QSI: Conditions Deteriorating — Composite dropped below 40
QSI: Hurst → Trending — Hurst crossed above 0.55
QSI: Hurst → Mean-Reversion — Hurst crossed below 0.45
QSI: Entropy → Chaos — Entropy spiked above 70
QSI: Entropy → Order — Entropy dropped below 30
█ PRO VERSION
The PRO version adds:
Markov Transition Probabilities — Statistical prediction of next-bar direction
Correlation Intelligence — Auto-benchmark correlation with breakdown detection
Fractal Dimension — Higuchi fractal complexity analysis
Absorption Detection — High volume + low range = institutional activity
Trading Style Presets — Auto/Scalping/Daytrading/Swing/Position
Asset Auto-Optimization — Automatic parameter tuning per asset class
Profile-Adaptive Weighting — Dynamic composite weights based on style + asset
█ NON-REPAINTING
All calculations use confirmed bar data only. The Hurst Exponent is calculated from historical log-returns. Shannon Entropy uses a rolling window of past data. Price Efficiency uses closed bars only. No future data leakage. No repainting.
█ WORKS ON
Crypto, Forex, Stocks, Futures, Indices — any timeframe from 1 minute to Monthly.
█ DISCLAIMER
This indicator is for educational and informational purposes only. It does not constitute financial advice. Always do your own research and manage your risk. Past performance does not guarantee future results. Trading involves substantial risk of loss.
Indicator

Indicator

Chaotic Hyperbolic Entropy Divergence Oscillator (CHEDO)Chaotic Hyperbolic Entropy Divergence Oscillator (CHEDO)-
Traditional momentum oscillators measure the velocity of price, but they often fail to account for market disorder, structural breaks, or chaotic divergence. The Chaotic Hyperbolic Entropy Divergence Oscillator (CHEDO) addresses this by leveraging concepts from information theory and chaos mathematics to quantify not just the direction of a trend, but its underlying structural stability.
Instead of relying solely on simple moving averages, CHEDO fuses five distinct mathematical models to determine if a market is trending cleanly, collapsing into chaos, or reaching maximum entropy (exhaustion).
The Mathematical Engine: Under the Hood
To ensure complete transparency, here are the five core components that drive this indicator. These metrics are dynamically normalised and fused into a single oscillator bounded between -1 and 1.
Hyperbolic Geodesic Curvature: Measures non-linear trend strength. It uses an arcsinh transformation of volatility-weighted returns to compress extreme outliers while preserving the core directional pull of the market.
Local Lyapunov Proxy: Adapted from chaos theory, this component measures the divergence rate of consecutive returns. It detects when price action is becoming unstable or unpredictable.
Kolmogorov-Smirnov (KS) Regime Shift: A distributional shift detector. It compares short-term and long-term volatility alongside skewness differentials to flag structural breaks in the market regime.
Shannon Entropy (Rolling): Information theory applied to price action. It computes the true rolling entropy of the return distribution. High entropy means the market is heavily disordered.
Edge Denoise Factor: A directional persistence metric that acts as a choppiness filter, distinguishing between clean moves and high-alternation noise.
Reading the Oscillator and State Machine
The fusion of these components is mapped through a directionally-aware sigmoid function, creating clear, actionable zones:
The Zero Line (Regime Shift): Crosses above zero indicate the initiation of a bullish regime. Crosses below zero indicate a bearish regime.
+0.7 Threshold (Exhaustion Zone): The market has reached a state of maximum entropy and parabolic stretch. The current directional move is highly disordered and vulnerable to a mean-reversion event.
-0.7 Threshold (Chaos Zone): The market is in a state of high chaos and accumulation. This zone typically precedes volatility expansions or major structural bottoming processes.
Honest Limitations and Caveats
Traders must be aware of the structural realities of this indicator:
Computational Lag: Because CHEDO relies on heavy statistical calculations and double-smoothing to filter noise, it carries inherent lag. It is designed to identify regime shifts, not to catch the absolute top or bottom tick.
OHLCV Dependency: While CHEDO is inspired by quantitative physics, it is ultimately calculating derivatives of OHLCV (Open, High, Low, Close, Volume) data. It is a highly advanced proxy, but it is not a replacement for true footprint or bid/ask order flow data.
Computation Cost: The rolling Shannon Entropy calculation is intensive. While optimised, it may cause minor loading delays on 1-minute charts with maximum historical bars loaded.
Best Practices: A Filter, Not a Standalone System
Due to its smoothing and mathematical depth, CHEDO is best deployed as a higher-timeframe regime filter rather than a lower-timeframe entry trigger.
Exhaustion Fades: When CHEDO enters the Exhaustion zone (above +0.7), exercise extreme caution taking trend-continuation breakout trades.
Volatility Breakouts: When CHEDO drops deep into the Chaos zone (below -0.7), the market is heavily compressed. Prepare for a volatility expansion and trade the structural breakout.
Multi-Timeframe Confirmation: If you are trading lower-timeframe setups, consult a higher-timeframe CHEDO. Only take the trade if the higher-timeframe oscillator is on the correct side of the zero line.
Disclaimer: CHEDO is an advanced statistical analysis tool, not a standalone trading system or financial advice. Always pair it with proper risk management and structural price analysis. Indicator

Adaptive Entropy Trend [QuantAlgo]🟢 Overview
Adaptive Entropy Trend is a trend-following indicator built on Shannon information theory rather than conventional price averaging. It quantifies the statistical disorder of recent log returns to determine whether the market is in a directional regime or a random one, then feeds this entropy reading into every layer of the system simultaneously, helping traders identify directional shifts that are validated by both low-entropy momentum conditions and genuine volatility expansion across different timeframes and markets.
🟢 How It Works
The foundation of the indicator is a per-bar entropy calculation built from the distribution of log returns over the lookback window. Log returns are computed and their range is divided into equal-width histogram bins:
logReturn = math.log(close / close )
minReturn = ta.lowest(logReturn, lookbackLen)
maxReturn = ta.highest(logReturn, lookbackLen)
returnRange = maxReturn - minReturn
Each historical return within the lookback is assigned to a bin, building a frequency distribution. Shannon entropy is then calculated from the probability of each bin, measuring how uniformly returns are spread across the range:
probability = array.get(binCounts, i) / lookbackLen
if probability > 0
entropy := entropy - probability * math.log(probability) / math.log(2)
A uniform distribution produces maximum entropy, reflecting a chaotic, non-directional market. A concentrated distribution produces low entropy, reflecting a market where returns are clustering in a consistent direction. The raw entropy is normalized against the theoretical maximum for the bin count to produce a stable 0-1 score:
normalizedEntropy = maxEntropy > 0 ? entropy / maxEntropy : 0.5
This score is then wired directly into the EMA smoothing factor. Higher entropy lengthens the effective period of the EMA, insulating it from noise. Lower entropy shortens it, allowing the EMA to track price closely during genuine trends:
adaptiveAlpha = 2.0 / (lookbackLen * (0.3 + normalizedEntropy * 1.4) + 1.0)
adaptiveEma := na(adaptiveEma) ? close : adaptiveEma + adaptiveAlpha * (close - adaptiveEma)
The same entropy reading drives band width through an inverted trend strength factor. Unlike volatility-based bands that widen during noise, these bands widen specifically during trending conditions and tighten during choppy ones:
trendStrength = 1.0 - normalizedEntropy
fastBandWidth = atr * fastMultiplier * (0.5 + trendStrength)
slowBandWidth = atr * slowMultiplier * (0.5 + trendStrength)
Finally, trend state is determined when price breaks beyond the inner bands, and transitions are tracked for alert conditions:
if close > innerUpper
trendDirection := 1
else if close < innerLower
trendDirection := -1
trendTurnedBullish = trendDirection == 1 and trendDirection != 1
trendTurnedBearish = trendDirection == -1 and trendDirection != -1
This creates a self-regulating trend system where the EMA baseline, the trigger threshold, and the visual envelope all adapt together from the same entropy source, rather than using a fixed center with adaptive edges or vice versa.
🟢 Signal Interpretation
▶ Bullish Trend (Price Above Inner Upper Band, Green): When price closes above the inner upper band, the indicator switches to bullish mode with bullish coloring across all visual elements = Confirmed uptrend signal for trend-following long positions. Because the inner band expands in low-entropy trending conditions, a bullish confirmation in a genuinely directional market requires a more meaningful breakout than in a noisy one. The trend remains bullish until price breaks below the inner lower band, allowing traders to stay positioned through normal pullbacks that remain within the band range.
▶ Bearish Trend (Price Below Inner Lower Band, Red): When price closes below the inner lower band, the indicator switches to bearish mode with bearish coloring throughout all visual elements = Confirmed downtrend signal for short positions or long exit signals. The adaptive band floor ensures the trigger threshold in choppy, high-entropy markets is tighter, reducing the risk of false breakdowns on thin directional moves. The trend remains bearish until price breaks above the inner upper band.
▶ Neutral Zone (Price Between Inner Bands): When price trades between the inner upper and lower bands, the indicator holds its previous trend direction = Continuation of existing trend during consolidation or normal volatility retracements. This prevents whipsaws during sideways action by requiring price to make a statistically meaningful move beyond the entropy-scaled band boundaries rather than reacting to minor crosses of the adaptive EMA centerline.
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets for different trading approaches and timeframes. "Default" provides balanced trend detection for swing trading on 4-hour and daily charts, "Fast Response" delivers quicker trend signals for intraday trading on 1-minute to 1-hour charts, and "Smooth Trend" focuses on major trend changes for position trading on daily to weekly timeframes.
▶ Built-in Alerts: Three alert conditions enable automated monitoring of trend changes without constant chart watching. "Bullish Trend Signal" triggers when the indicator switches to bullish mode after price breaks above the inner upper band, alerting for potential long entries. "Bearish Trend Signal" activates when the indicator switches to bearish mode after price breaks below the inner lower band, signaling potential short entries or long exits. "Trend Direction Changed" provides a combined alert for any trend transition regardless of direction, allowing traders to monitor both bullish and bearish opportunities with a single alert setup.
▶ Visual Customization: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart backgrounds and aesthetic preferences, with coordinated bullish, bearish, and neutral color schemes applied across all indicator elements. Inner and outer band fills create a two-layer gradient envelope around the adaptive EMA, with the inner zone between the two bands rendered slightly more transparent than the outer zone to preserve natural depth, both controlled by a single fill transparency input (0-100%) so the visual weight of the envelope can be adjusted without disrupting the gradient relationship. Optional bar coloring tints price bars with trend-appropriate colors during bullish and bearish periods, enabling instant visual confirmation of trend state across multiple timeframes without switching between chart and indicator panels.
Indicator

Precision Market Entropy Heatmap [LuxAlgo]The Precision Market Entropy Heatmap indicator provides a high-resolution visualization of volume distribution and market activity within specific anchor intervals using intrabar data.
By utilizing lower timeframe (LTF) precision, it maps out where the most significant trading activity occurred, allowing traders to identify institutional interest zones and "fair value" areas through a dynamic heat-mapped profile.
🔶 USAGE
The indicator segments the chart into blocks based on the selected Anchor Interval. Within each block, a vertical distribution of volume is calculated using the Intrabar Precision setting to ensure the heatmap accurately reflects market participation at specific price levels.
Heatmap Blocks : Brighter colors represent higher volume concentrations (high entropy). These areas often act as significant support or resistance zones where the market has previously found "fair value" or high liquidity.
Identifying Institutional Interest : High-volume "bright" nodes represent price levels where heavy institutional participation occurred. These nodes act as powerful magnets or barriers for future price action.
Navigating Liquidity Voids : Darker areas indicate low volume nodes (low entropy). Price often "slips" through these gaps quickly. Traders can use these zones to anticipate fast-moving price action or set targets beyond the void.
Trend Direction via POC : Observe the slope and shifts of the Developing POC polyline. An ascending POC confirms bullish value migration, while a descending one suggests bearish value migration.
Mean Reversion : Significant price deviations from the largest high-volume node, when the POC remains static, can signal that the market is overextended and likely to return to "fair value."
Breakout Validation : Use the blocks to identify compression zones. A breakout is more reliable when the POC shifts into the new range, confirming that the move is backed by volume and accepted by the market.
POC Extensions : Dashed lines extend the session's final POC. These are dynamically colored based on their relationship to the current price: Green if the POC is below the current price (potential support) and Red if above (potential resistance).
🔶 DETAILS
Unlike standard Volume Profiles that look at fixed ranges, this script focuses on "Entropy" by visualizing the density of distribution across a user-defined grid.
By requesting security data from lower timeframes, it provides a much more granular view of price action than what is visible on the current chart timeframe alone.
The indicator uses a gradient-based coloring system to distinguish between low-activity areas and high-volume nodes, making it easier to spot "Liquidity Voids" (darker areas) and "High Volume Nodes" (brighter areas).
🔶 SETTINGS
🔹 Heatmap Settings
Anchor Interval : Sets the timeframe that defines each heatmap block (e.g., "D" for Daily blocks).
Intrabar Precision : Determines the lower timeframe used to calculate the volume distribution. Lower values (like "1m") provide higher precision but are limited by available historical data.
Number of Rows : Controls the vertical price resolution of the heatmap grid. Higher values create a more detailed but computationally heavier profile.
🔹 Style Settings
Heatmap Intensity : A three-color gradient selector that defines the color transition from low to high volume areas.
Heatmap Transparency : Adjusts the visibility of the heatmap blocks on the chart.
POC Extension (Bull/Bear) : Sets the colors for the dashed POC lines based on whether they are currently below (Bull) or above (Bear) the market price.
Show Developing POC : Toggles the visibility of the real-time POC polyline.
Auto : When enabled, the developing POC color automatically syncs with your chart theme's foreground color.
🔹 Display Settings
Max Sessions to Show : Limits the number of historical heatmap blocks rendered on the chart to maintain performance.
Extend POCs to Current Bar : When enabled, historical POC lines will extend to the far right of the chart until they are replaced by newer sessions.
Indicator

PineStats█ OVERVIEW
PineStats is a comprehensive statistical analysis library for Pine Script v6, providing 104 functions across 6 modules. Built for quantitative traders, researchers, and indicator developers who need professional-grade statistics without reinventing the wheel.
For building mean-reversion strategies, analyzing return distributions, measuring correlations, or testing for market regimes.
█ MODULES
CORE STATISTICS (20 functions)
• Central tendency: mean, median, WMA, EMA
• Dispersion: variance, stdev, MAD, range
• Standardization: z-score, robust z-score, normalize, percentile
• Distribution shape: skewness, kurtosis
PROBABILITY DISTRIBUTIONS (17 functions)
• Normal: PDF, CDF, inverse CDF (quantile function)
• Power-law: Hill estimator, MLE alpha, survival function
• Exponential: PDF, CDF, rate estimation
• Normality testing: Jarque-Bera test
ENTROPY (9 functions)
• Shannon entropy (information theory)
• Tsallis entropy (non-extensive, fat-tail sensitive)
• Permutation entropy (ordinal patterns)
• Approximate entropy (regularity measure)
• Entropy-based regime detection
PROBABILITY (21 functions)
• Win rates and expected value
• First passage time estimation
• TP/SL probability analysis
• Conditional probability and Bayes updates
• Streak and drawdown probabilities
REGRESSION (19 functions)
• Linear regression: slope, intercept, forecast
• Goodness of fit: R², adjusted R², standard error
• Statistical tests: t-statistic, p-value, significance
• Trend analysis: strength, angle, acceleration
• Quadratic regression
CORRELATION (18 functions)
• Pearson, Spearman, Kendall correlation
• Covariance, beta, alpha (Jensen's)
• Rolling correlation analysis
• Autocorrelation and cross-correlation
• Information ratio, tracking error
█ QUICK START
import HenriqueCentieiro/PineStats/1 as stats
// Z-score for mean reversion
z = stats.zscore(close, 20)
// Test if returns are normally distributed
returns = (close - close ) / close
isGaussian = stats.is_normal(returns, 100, 0.05)
// Regression channel
= stats.linreg_channel(close, 50, 2.0)
// Correlation with benchmark
spyReturns = request.security("SPY", timeframe.period, close/close - 1)
beta = stats.beta(returns, spyReturns, 60)
█ USE CASES
✓ Mean Reversion — z-scores, percentiles, Bollinger-style analysis
✓ Regime Detection — entropy measures, correlation regimes
✓ Risk Analysis — drawdown probability, VaR via quantiles
✓ Strategy Evaluation — expected value, win rates, R:R analysis
✓ Distribution Analysis — normality tests, fat-tail detection
✓ Multi-Asset — beta, alpha, correlation, relative strength
█ NOTES
• All functions return `na` on invalid inputs
• Designed for Pine Script v6
• Fully documented in the library header
• Part of the Pine ecosystem: PineStats, PineQuant, PineCriticality, PineWavelet
█ REFERENCES
• Abramowitz & Stegun — Normal CDF approximation
• Acklam's algorithm — Inverse normal CDF
• Hill estimator — Power-law tail estimation
• Tsallis statistics — Non-extensive entropy
Full documentation in the library header.
mean(src, length)
Calculates the arithmetic mean (simple moving average) over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Arithmetic mean of the last `length` values, or `na` if inputs invalid
wma_custom(src, length)
Calculates weighted moving average with linearly decreasing weights
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Weighted moving average, or `na` if inputs invalid
ema_custom(src, length)
Calculates exponential moving average
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Exponential moving average, or `na` if inputs invalid
median(src, length)
Calculates the median value over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Median value, or `na` if inputs invalid
variance(src, length)
Calculates population variance over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Population variance, or `na` if inputs invalid
stdev(src, length)
Calculates population standard deviation over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Population standard deviation, or `na` if inputs invalid
mad(src, length)
Calculates Median Absolute Deviation (MAD) - robust dispersion measure
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: MAD value, or `na` if inputs invalid
data_range(src, length)
Calculates the range (highest - lowest) over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Range value, or `na` if inputs invalid
zscore(src, length)
Calculates z-score (number of standard deviations from mean)
Parameters:
src (float) : Source series
length (simple int) : Lookback period for mean and stdev calculation (must be >= 2)
Returns: Z-score, or `na` if inputs invalid or stdev is zero
zscore_robust(src, length)
Calculates robust z-score using median and MAD (resistant to outliers)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 2)
Returns: Robust z-score, or `na` if inputs invalid or MAD is zero
normalize(src, length)
Normalizes value to range using min-max scaling
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Normalized value in , or `na` if inputs invalid or range is zero
percentile(src, length)
Calculates percentile rank of current value within lookback window
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Percentile rank (0 to 100), or `na` if inputs invalid
winsorize(src, length, lower_pct, upper_pct)
Winsorizes values by clamping to percentile bounds (reduces outlier impact)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
lower_pct (simple float) : Lower percentile bound (0-100, e.g., 5 for 5th percentile)
upper_pct (simple float) : Upper percentile bound (0-100, e.g., 95 for 95th percentile)
Returns: Winsorized value clamped to bounds
skewness(src, length)
Calculates sample skewness (measure of distribution asymmetry)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 3)
Returns: Skewness value (negative = left tail, positive = right tail), or `na` if invalid
kurtosis(src, length)
Calculates excess kurtosis (measure of distribution tail heaviness)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 4)
Returns: Excess kurtosis (>0 = heavy tails, <0 = light tails), or `na` if invalid
count_valid(src, length)
Counts non-na values in lookback window (useful for data quality checks)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Count of valid (non-na) values
sum(src, length)
Calculates sum over lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Sum of values, or `na` if inputs invalid
cumsum(src)
Calculates cumulative sum (running total from first bar)
Parameters:
src (float) : Source series
Returns: Cumulative sum
change(src, length)
Returns the change (difference) from n bars ago
Parameters:
src (float) : Source series
length (simple int) : Number of bars to look back (must be >= 1)
Returns: Current value minus value from `length` bars ago
roc(src, length)
Calculates Rate of Change (percentage change from n bars ago)
Parameters:
src (float) : Source series
length (simple int) : Number of bars to look back (must be >= 1)
Returns: Percentage change as decimal (0.05 = 5%), or `na` if invalid
normal_pdf_standard(x)
Calculates the standard normal probability density function (PDF)
Parameters:
x (float) : The value to evaluate
Returns: PDF value at x for standard normal N(0,1)
normal_pdf(x, mu, sigma)
Calculates the normal probability density function (PDF)
Parameters:
x (float) : The value to evaluate
mu (float) : Mean of the distribution (default: 0)
sigma (float) : Standard deviation (default: 1, must be > 0)
Returns: PDF value at x for normal N(mu, sigma²)
normal_cdf_standard(x)
Calculates the standard normal cumulative distribution function (CDF)
Parameters:
x (float) : The value to evaluate
Returns: Probability P(X <= x) for standard normal N(0,1)
@description Uses Abramowitz & Stegun approximation (formula 7.1.26), accurate to ~1.5e-7
normal_cdf(x, mu, sigma)
Calculates the normal cumulative distribution function (CDF)
Parameters:
x (float) : The value to evaluate
mu (float) : Mean of the distribution (default: 0)
sigma (float) : Standard deviation (default: 1, must be > 0)
Returns: Probability P(X <= x) for normal N(mu, sigma²)
normal_inv_standard(p)
Calculates the inverse standard normal CDF (quantile function)
Parameters:
p (float) : Probability value (must be in (0, 1))
Returns: x such that P(X <= x) = p for standard normal N(0,1)
@description Uses Acklam's algorithm, accurate to ~1.15e-9
normal_inv(p, mu, sigma)
Calculates the inverse normal CDF (quantile function)
Parameters:
p (float) : Probability value (must be in (0, 1))
mu (float) : Mean of the distribution
sigma (float) : Standard deviation (must be > 0)
Returns: x such that P(X <= x) = p for normal N(mu, sigma²)
power_law_alpha(src, length, tail_pct)
Estimates power-law exponent (alpha) using Hill estimator
Parameters:
src (float) : Source series (typically absolute returns or drawdowns)
length (simple int) : Lookback period (must be >= 10 for reliable estimates)
tail_pct (simple float) : Percentage of data to use for tail estimation (default: 0.1 = top 10%)
Returns: Estimated alpha (tail index), typically 2-4 for financial data
@description Alpha < 2 indicates infinite variance (very heavy tails)
@description Alpha < 3 indicates infinite kurtosis
@description Alpha > 4 suggests near-Gaussian behavior
power_law_alpha_mle(src, length, x_min)
Estimates power-law alpha using maximum likelihood (Clauset method)
Parameters:
src (float) : Source series (positive values expected)
length (simple int) : Lookback period (must be >= 20)
x_min (float) : Minimum threshold for power-law behavior
Returns: Estimated alpha using MLE
power_law_pdf(x, alpha, x_min)
Calculates power-law probability density (Pareto Type I)
Parameters:
x (float) : Value to evaluate (must be >= x_min)
alpha (float) : Power-law exponent (must be > 1)
x_min (float) : Minimum value / scale parameter (must be > 0)
Returns: PDF value
power_law_survival(x, alpha, x_min)
Calculates power-law survival function P(X > x)
Parameters:
x (float) : Value to evaluate (must be >= x_min)
alpha (float) : Power-law exponent (must be > 1)
x_min (float) : Minimum value / scale parameter (must be > 0)
Returns: Probability of exceeding x
power_law_ks(src, length, alpha, x_min)
Tests if data follows power-law using simplified Kolmogorov-Smirnov
Parameters:
src (float) : Source series
length (simple int) : Lookback period
alpha (float) : Estimated alpha from power_law_alpha()
x_min (float) : Threshold value
Returns: KS statistic (lower = better fit, typically < 0.1 for good fit)
is_power_law(src, length, tail_pct, ks_threshold)
Simple test if distribution appears to follow power-law
Parameters:
src (float) : Source series
length (simple int) : Lookback period
tail_pct (simple float) : Tail percentage for alpha estimation
ks_threshold (simple float) : Maximum KS statistic for acceptance (default: 0.1)
Returns: true if KS test suggests power-law fit
exp_pdf(x, lambda)
Calculates exponential probability density function
Parameters:
x (float) : Value to evaluate (must be >= 0)
lambda (float) : Rate parameter (must be > 0)
Returns: PDF value
exp_cdf(x, lambda)
Calculates exponential cumulative distribution function
Parameters:
x (float) : Value to evaluate (must be >= 0)
lambda (float) : Rate parameter (must be > 0)
Returns: Probability P(X <= x)
exp_lambda(src, length)
Estimates exponential rate parameter (lambda) using MLE
Parameters:
src (float) : Source series (positive values)
length (simple int) : Lookback period
Returns: Estimated lambda (1/mean)
jarque_bera(src, length)
Calculates Jarque-Bera test statistic for normality
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 10)
Returns: JB statistic (higher = more deviation from normality)
@description Under normality, JB ~ chi-squared(2). JB > 6 suggests non-normality at 5% level
is_normal(src, length, significance)
Tests if distribution is approximately normal
Parameters:
src (float) : Source series
length (simple int) : Lookback period
significance (simple float) : Significance level (default: 0.05)
Returns: true if Jarque-Bera test does not reject normality
shannon_entropy(src, length, n_bins)
Calculates Shannon entropy from a probability distribution
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 10)
n_bins (simple int) : Number of histogram bins for discretization (default: 10)
Returns: Shannon entropy in bits (log base 2)
@description Higher entropy = more randomness/uncertainty, lower = more predictability
shannon_entropy_norm(src, length, n_bins)
Calculates normalized Shannon entropy
Parameters:
src (float) : Source series
length (simple int) : Lookback period
n_bins (simple int) : Number of histogram bins
Returns: Normalized entropy where 0 = perfectly predictable, 1 = maximum randomness
tsallis_entropy(src, length, q, n_bins)
Calculates Tsallis entropy with q-parameter
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 10)
q (float) : Entropic index (q=1 recovers Shannon entropy)
n_bins (simple int) : Number of histogram bins
Returns: Tsallis entropy value
@description q < 1: emphasizes rare events (fat tails)
@description q = 1: equivalent to Shannon entropy
@description q > 1: emphasizes common events
optimal_q(src, length)
Estimates optimal q parameter from kurtosis
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Estimated q value that best captures the distribution's tail behavior
@description Uses relationship: q ≈ (5 + kurtosis) / (3 + kurtosis) for kurtosis > 0
tsallis_q_gaussian(x, q, beta)
Calculates Tsallis q-Gaussian probability density
Parameters:
x (float) : Value to evaluate
q (float) : Tsallis q parameter (must be < 3)
beta (float) : Width parameter (inverse temperature, must be > 0)
Returns: q-Gaussian PDF value
@description q=1 recovers standard Gaussian
permutation_entropy(src, length, order)
Calculates permutation entropy (ordinal pattern complexity)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 20)
order (simple int) : Embedding dimension / pattern length (2-5, default: 3)
Returns: Normalized permutation entropy
@description Measures complexity of temporal ordering patterns
@description 0 = perfectly predictable sequence, 1 = random
approx_entropy(src, length, m, r)
Calculates Approximate Entropy (ApEn) - regularity measure
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 50)
m (simple int) : Embedding dimension (default: 2)
r (simple float) : Tolerance as fraction of stdev (default: 0.2)
Returns: Approximate entropy value (higher = more irregular/complex)
@description Lower ApEn indicates more self-similarity and predictability
entropy_regime(src, length, q, n_bins)
Detects market regime based on entropy level
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback period
q (float) : Tsallis q parameter (use optimal_q() or default 1.5)
n_bins (simple int) : Number of histogram bins
Returns: Regime indicator: -1 = trending (low entropy), 0 = transition, 1 = ranging (high entropy)
entropy_risk(src, length)
Calculates entropy-based risk indicator
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback period
Returns: Risk score where 1 = maximum divergence from Gaussian 1
hit_rate(src, length)
Calculates hit rate (probability of positive outcome) over lookback
Parameters:
src (float) : Source series (positive values count as hits)
length (simple int) : Lookback period
Returns: Hit rate as decimal
hit_rate_cond(condition, length)
Calculates hit rate for custom condition over lookback
Parameters:
condition (bool) : Boolean series (true = hit)
length (simple int) : Lookback period
Returns: Hit rate as decimal
expected_value(src, length)
Calculates expected value of a series
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Expected value (mean)
expected_value_trade(win_prob, take_profit, stop_loss)
Calculates expected value for a trade with TP and SL levels
Parameters:
win_prob (float) : Probability of hitting TP (0-1)
take_profit (float) : Take profit in price units or %
stop_loss (float) : Stop loss in price units or % (positive value)
Returns: Expected value per trade
@description EV = (win_prob * TP) - ((1 - win_prob) * SL)
breakeven_winrate(take_profit, stop_loss)
Calculates breakeven win rate for given TP/SL ratio
Parameters:
take_profit (float) : Take profit distance
stop_loss (float) : Stop loss distance
Returns: Required win rate for breakeven (EV = 0)
reward_risk_ratio(take_profit, stop_loss)
Calculates the reward-to-risk ratio
Parameters:
take_profit (float) : Take profit distance
stop_loss (float) : Stop loss distance
Returns: R:R ratio
fpt_probability(src, length, target, max_bars)
Estimates probability of price reaching target within N bars
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback for volatility estimation
target (float) : Target move (in same units as src, e.g., % return)
max_bars (simple int) : Maximum bars to consider
Returns: Probability of reaching target within max_bars
@description Based on random walk with drift approximation
fpt_mean(src, length, target)
Estimates mean first passage time to target level
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback for volatility estimation
target (float) : Target move
Returns: Expected number of bars to reach target (can be infinite)
fpt_historical(src, length, target)
Counts historical bars to reach target from each point
Parameters:
src (float) : Source series (typically price or returns)
length (simple int) : Lookback period
target (float) : Target move from each starting point
Returns: Array of first passage times (na if target not reached within lookback)
tp_probability(src, length, tp_distance, sl_distance)
Estimates probability of hitting TP before SL
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback for estimation
tp_distance (float) : Take profit distance (positive)
sl_distance (float) : Stop loss distance (positive)
Returns: Probability of TP being hit first
trade_probability(src, length, tp_pct, sl_pct)
Calculates complete trade probability and EV analysis
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback period
tp_pct (float) : Take profit percentage
sl_pct (float) : Stop loss percentage
Returns: Tuple:
cond_prob(condition_a, condition_b, length)
Calculates conditional probability P(B|A) from historical data
Parameters:
condition_a (bool) : Condition A (the given condition)
condition_b (bool) : Condition B (the outcome)
length (simple int) : Lookback period
Returns: P(B|A) = P(A and B) / P(A)
bayes_update(prior, likelihood, false_positive)
Updates probability using Bayes' theorem
Parameters:
prior (float) : Prior probability P(H)
likelihood (float) : P(E|H) - probability of evidence given hypothesis
false_positive (float) : P(E|~H) - probability of evidence given hypothesis is false
Returns: Posterior probability P(H|E)
streak_prob(win_rate, streak_length)
Calculates probability of N consecutive wins given win rate
Parameters:
win_rate (float) : Single-trade win probability
streak_length (simple int) : Number of consecutive wins
Returns: Probability of streak
losing_streak_prob(win_rate, streak_length)
Calculates probability of experiencing N consecutive losses
Parameters:
win_rate (float) : Single-trade win probability
streak_length (simple int) : Number of consecutive losses
Returns: Probability of losing streak
drawdown_prob(src, length, dd_threshold)
Estimates probability of drawdown exceeding threshold
Parameters:
src (float) : Source series (returns)
length (simple int) : Lookback period
dd_threshold (float) : Drawdown threshold (as positive decimal, e.g., 0.10 = 10%)
Returns: Historical probability of exceeding drawdown threshold
prob_to_odds(prob)
Calculates odds from probability
Parameters:
prob (float) : Probability (0-1)
Returns: Odds (prob / (1 - prob))
odds_to_prob(odds)
Calculates probability from odds
Parameters:
odds (float) : Odds ratio
Returns: Probability (0-1)
implied_prob(decimal_odds)
Calculates implied probability from decimal odds (betting)
Parameters:
decimal_odds (float) : Decimal odds (e.g., 2.5 means $2.50 return per $1 bet)
Returns: Implied probability
logit(prob)
Calculates log-odds (logit) from probability
Parameters:
prob (float) : Probability (must be in (0, 1))
Returns: Log-odds
inv_logit(log_odds)
Calculates probability from log-odds (inverse logit / sigmoid)
Parameters:
log_odds (float) : Log-odds value
Returns: Probability (0-1)
linreg_slope(src, length)
Calculates linear regression slope
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 2)
Returns: Slope coefficient (change per bar)
linreg_intercept(src, length)
Calculates linear regression intercept
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 2)
Returns: Intercept (predicted value at oldest bar in window)
linreg_value(src, length)
Calculates predicted value at current bar using linear regression
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Predicted value at current bar (end of regression line)
linreg_forecast(src, length, offset)
Forecasts value N bars ahead using linear regression
Parameters:
src (float) : Source series
length (simple int) : Lookback period for regression
offset (simple int) : Bars ahead to forecast (positive = future)
Returns: Forecasted value
linreg_channel(src, length, mult)
Calculates linear regression channel with bands
Parameters:
src (float) : Source series
length (simple int) : Lookback period
mult (simple float) : Standard deviation multiplier for bands
Returns: Tuple:
r_squared(src, length)
Calculates R-squared (coefficient of determination)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: R² value where 1 = perfect linear fit
adj_r_squared(src, length)
Calculates adjusted R-squared (accounts for sample size)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Adjusted R² value
std_error(src, length)
Calculates standard error of estimate (residual standard deviation)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Standard error
residual(src, length)
Calculates residual at current bar
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Residual (actual - predicted)
residuals(src, length)
Returns array of all residuals in lookback window
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Array of residuals
t_statistic(src, length)
Calculates t-statistic for slope coefficient
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: T-statistic (slope / standard error of slope)
slope_pvalue(src, length)
Approximates p-value for slope t-test (two-tailed)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Approximate p-value
is_significant(src, length, alpha)
Tests if regression slope is statistically significant
Parameters:
src (float) : Source series
length (simple int) : Lookback period
alpha (simple float) : Significance level (default: 0.05)
Returns: true if slope is significant at alpha level
trend_strength(src, length)
Calculates normalized trend strength based on R² and slope
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Trend strength where sign indicates direction
trend_angle(src, length)
Calculates trend angle in degrees
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Angle in degrees (positive = uptrend, negative = downtrend)
linreg_acceleration(src, length)
Calculates trend acceleration (second derivative)
Parameters:
src (float) : Source series
length (simple int) : Lookback period for each regression
Returns: Acceleration (change in slope)
linreg_deviation(src, length)
Calculates deviation from regression line in standard error units
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Deviation in standard error units (like z-score)
quadreg_coefficients(src, length)
Fits quadratic regression and returns coefficients
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 4)
Returns: Tuple: for y = a*x² + b*x + c
quadreg_value(src, length)
Calculates quadratic regression value at current bar
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Predicted value from quadratic fit
correlation(x, y, length)
Calculates Pearson correlation coefficient between two series
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 3)
Returns: Correlation coefficient
covariance(x, y, length)
Calculates sample covariance between two series
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 2)
Returns: Covariance value
beta(asset, benchmark, length)
Calculates beta coefficient (slope of regression of y on x)
Parameters:
asset (float) : Asset returns series
benchmark (float) : Benchmark returns series
length (simple int) : Lookback period
Returns: Beta coefficient
@description Beta = Cov(asset, benchmark) / Var(benchmark)
alpha(asset, benchmark, length, risk_free)
Calculates alpha (Jensen's alpha / intercept)
Parameters:
asset (float) : Asset returns series
benchmark (float) : Benchmark returns series
length (simple int) : Lookback period
risk_free (float) : Risk-free rate (default: 0)
Returns: Alpha value (excess return not explained by beta)
spearman(x, y, length)
Calculates Spearman rank correlation coefficient
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 3)
Returns: Spearman correlation
@description More robust to outliers than Pearson correlation
kendall_tau(x, y, length)
Calculates Kendall's tau rank correlation (simplified)
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 3)
Returns: Kendall's tau
correlation_change(x, y, length, change_period)
Calculates change in correlation over time
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period for correlation
change_period (simple int) : Period over which to measure change
Returns: Change in correlation
correlation_regime(x, y, length, ma_length)
Detects correlation regime based on level and stability
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period for correlation
ma_length (simple int) : Moving average length for smoothing
Returns: Regime: -1 = negative, 0 = uncorrelated, 1 = positive
correlation_stability(x, y, length, stability_length)
Calculates correlation stability (inverse of volatility)
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback for correlation
stability_length (simple int) : Lookback for stability calculation
Returns: Stability score where 1 = perfectly stable
relative_strength(asset, benchmark, length)
Calculates relative strength of asset vs benchmark
Parameters:
asset (float) : Asset price series
benchmark (float) : Benchmark price series
length (simple int) : Smoothing period
Returns: Relative strength ratio (normalized)
tracking_error(asset, benchmark, length)
Calculates tracking error (standard deviation of excess returns)
Parameters:
asset (float) : Asset returns
benchmark (float) : Benchmark returns
length (simple int) : Lookback period
Returns: Tracking error (annualize by multiplying by sqrt(252) for daily data)
information_ratio(asset, benchmark, length)
Calculates information ratio (risk-adjusted excess return)
Parameters:
asset (float) : Asset returns
benchmark (float) : Benchmark returns
length (simple int) : Lookback period
Returns: Information ratio
capture_ratio(asset, benchmark, length, up_capture)
Calculates up/down capture ratio
Parameters:
asset (float) : Asset returns
benchmark (float) : Benchmark returns
length (simple int) : Lookback period
up_capture (simple bool) : If true, calculate up capture; if false, down capture
Returns: Capture ratio
autocorrelation(src, length, lag)
Calculates autocorrelation at specified lag
Parameters:
src (float) : Source series
length (simple int) : Lookback period
lag (simple int) : Lag for autocorrelation (default: 1)
Returns: Autocorrelation at specified lag
partial_autocorr(src, length)
Calculates partial autocorrelation at lag 1
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: PACF at lag 1 (equals ACF at lag 1)
autocorr_test(src, length, max_lag)
Tests for significant autocorrelation (Ljung-Box inspired)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
max_lag (simple int) : Maximum lag to test
Returns: Sum of squared autocorrelations (higher = more autocorrelation)
cross_correlation(x, y, length, lag)
Calculates cross-correlation at specified lag
Parameters:
x (float) : First series
y (float) : Second series (lagged)
length (simple int) : Lookback period
lag (simple int) : Lag to apply to y (positive = y leads x)
Returns: Cross-correlation at specified lag
cross_correlation_peak(x, y, length, max_lag)
Finds lag with maximum cross-correlation
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period
max_lag (simple int) : Maximum lag to search (both directions)
Returns: Tuple: Library
