Dynamic Buying and Selling Power (ADTM)
什么是 ADTM?
ADTM(Dynamic Buying and Selling Power Indicator,动态买卖气指标)是一种经典的动量与反转量化指标。它通过对比开盘价的跃升与下挫,精确量化开盘后多空双方的推进力度(即爆发力),并将这种力量对比归一化在 的固定区间内。
与传统单纯依赖收盘价(Close)的振荡指标不同,ADTM 更加关注 开盘价(Open)相对于前一交易日的位置以及当日极值(High/Low)的延伸空间 ,从而能够更敏锐地捕捉到市场资金的日内异动。
---
为什么使用它?
在波诡云谲的市场中,单纯的均线或 lagging 指标容易产生钝化。ADTM 的优势在于:
无量纲化区间:其输出被严格限制在 之间,避免了绝对数值对趋势研判的干扰。
日内真实动能:通过计算买方动态能量(DTM)和卖方动态能量(DBM),能够更早地在左侧识别出多空力量的衰竭点。
极佳的反转提示:特别适合配合超买超卖边界进行逆势(反转)波段的卡点操作。
---
怎么用?
本指标的使用逻辑非常直观,默认参数为经典配置: N = 23(求和周期),M = 8(信号均线周期)。
左侧买点(超卖区):
当蓝色 ADTM 曲线跌破 -0.5 时,意味着市场短期内空头宣泄极快,进入超卖状态。这通常是极佳的左侧分批布局或观察止跌反转的买点。
左侧风险(超买区):
当蓝色 ADTM 曲线突破 +0.5 时,意味着多头短期冲锋过急,进入超买状态。此时应防范多头力竭回撤,注意锁定利润或降低仓位。
中轴信号:
0轴为多空分界线。当 ADTM 在 0 轴上方运行时,多头占优;反之,空头占优。
均线交叉:
蓝色主线(ADTM)与橙色信号线(MA_ADTM)的黄金交叉与死亡交叉,可作为右侧动能确认的辅助信号。
---
在哪里用?
本指标采用纯粹的价格几何结构算法,具有极强的普适性:
适用市场:广泛适用于 A 股、美股、加密货币、商品期货以及外汇等主流交易市场。
适用周期:在日线(Daily)及以上大周期中表现尤为稳定,能够有效过滤盘整期的日内噪音;在小周期(如 1H/4H)中,配合趋势背景亦可用于日内波段捕捉。
---
原创与致谢声明
指标原创作者: 本指标的核心算法源自经典量化分析领域的经典设计。
脚本重构与发布: 由本人进行 Pine Script v6 的标准化重构、算法优化与开源发布。
风险提示: 任何技术指标都无法百分之百预测市场。建议将 ADTM 融入自身的交易系统中,结合量价结构、关键支撑阻力位以及严谨的资金管理共同使用。
---
What is ADTM?
ADTM (Dynamic Buying and Selling Power Indicator) is a classic momentum and reversal quantification tool. It precisely quantifies the offensive strength (i.e., explosive power) of both bulls and bears after the market opens by comparing the upward jumps and downward drops of the opening price, and normalizes this power comparison within a fixed range of .
Unlike traditional oscillators that rely solely on the closing price (Close), ADTM places greater emphasis on the opening price (Open) relative to the previous trading day's position, as well as the extension space of the day's extremes (High/Low) , enabling it to more keenly capture intraday anomalies in market capital flow.
---
Why Use It?
In volatile and unpredictable markets, simple moving averages or lagging indicators are prone to desensitization (flattening). The advantages of ADTM are:
Dimensionless interval: Its output is strictly confined within , eliminating the interference of absolute price levels on trend assessment.
Intraday true momentum: By calculating Dynamic Buying Momentum (DTM) and Dynamic Selling Momentum (DBM), it can identify exhaustion points of bullish/bearish power earlier on the left side.
Excellent reversal signals: Particularly well-suited for contrarian (reversal) swing trading by utilizing overbought/oversold boundaries.
---
How to Use It?
The usage logic of this indicator is highly intuitive, with default parameters set to the classic configuration: N = 23 (Summation Period), M = 8 (Signal MA Period).
Left-side Buy Signal (Oversold Zone):
When the blue ADTM line drops below -0.5, it indicates that bearish forces have been excessively unleashed in the short term, entering an oversold state. This is typically an excellent opportunity for left-side accumulation or observing for a bullish reversal.
Left-side Risk Signal (Overbought Zone):
When the blue ADTM line rises above +0.5, it indicates that bullish forces have pushed too aggressively in the short term, entering an overbought state. At this point, one should be cautious of bullish exhaustion and pullbacks, and consider locking in profits or reducing positions.
Zero-Line Signal:
The 0.0 axis serves as the bull-bear dividing line. When ADTM is above 0, bulls are in control; when below 0, bears are in control.
Moving Average Crossover:
The golden cross and death cross between the blue main line (ADTM) and the orange signal line (MA_ADTM) can serve as auxiliary signals for right-side momentum confirmation.
---
Where to Use It?
This indicator employs a pure geometric price-structure algorithm, offering strong universality:
Applicable Markets: Widely applicable to A-shares, U.S. stocks, cryptocurrencies, commodity futures, forex, and other major trading markets.
Applicable Timeframes: Performs particularly well on Daily and higher timeframes, effectively filtering out intraday noise during consolidation periods. On lower timeframes (e.g., 1H/4H), it can also be used for intraday swing trading when combined with the broader trend context.
---
Acknowledgments & Originality Statement
Original Author: The core algorithm of this indicator originates from classic designs in the field of quantitative analysis.
Script Re-engineering & Release: This script has been fully refactored, optimized, and released as open-source by myself.
Risk Disclaimer: No technical indicator can predict the market with 100% accuracy. It is strongly recommended to integrate ADTM into your own trading system, combining it with volume-price structure, key support/resistance levels, and strict risk management practices. אינדיקטור

Arbor_Gradient_Boosting_GainzAlgoGainzAlgo is excited to bring the ability to perform gradient boosting and feature importance selection to Pine Script. Currently, there are no native capabilities within Pine Script for gradient boosting or feature importance selection. Arbor fills this significant gap by introducing a from-scratch Gradient Boosting Machine (GBM) engineered with XGBoost-style mechanics.
Designed to support both classification and regression tasks, and building on our Random Forest approach to Pinescript, Arbor utilizes depth-1 stumps, meaning it performs one split per round without column subsampling.
Because TradingView automatically lists the exported types and function parameters, the following outlines the core mechanics and capabilities you unlock by importing Arbor.
Core Mechanics
Arbor brings advanced machine-learning concepts directly into your Pine Script workflows:Advanced Training: Utilizes Newton leaf steps (second-order hessian weighting) and the exact XGBoost gain formula.
Regularization & Pruning: Integrates L2 regularization (lambda), minimum gain pruning (gamma), and minimum child weight checks to manage model complexity and prevent overfitting.
Stochasticity: Implements Fisher-Yates row subsampling to provide genuine round-to-round stochasticity matching XGBoost's subsample behavior.
Reproducibility: You can pass an optional seed to any fit function to ensure reproducible training runs across reloads.
Model Tiers
The library supports models scaled across three specific feature tiers:
GBM (1 Feature): Built for rapid classification or regression implementations.
GBM3 (3 Features): Purpose-built specifically for classification tasks.
GBM4 (4 Features): Supports both classification and regression, and uniquely offers XGBoost-style, gain-based feature importance evaluation.
Library "Arbor_Gradient_Boosting_GainzAlgo"
Arbor — gradient boosting for Pine Script. From-scratch GBM v2
with XGBoost-style mechanics: Fisher-Yates row subsampling, Newton leaf steps
(second-order hessian weighting), exact XGBoost gain formula with L2
regularization (lambda), minimum gain pruning (gamma), and minimum child
weight. Trees are depth-1 stumps (one split per round) and there is no
column (feature) subsampling — this is an XGBoost-style boosting scheme,
not a full XGBoost reimplementation. Supports classification and regression
across three feature tiers:
- GBM (1 feature) : gbm_fit / gbm_predict
classification or regression via is_classifier
- GBM3 (3 features) : gbm3_fit / gbm3_predict
classification only
- GBM4 (4 features) : gbm4_fit / gbm4_predict / gbm4_importance_pct
classification or regression with XGBoost-style
gain-based feature importance
All variants use Newton leaf steps, exact gain formula, L2 regularization,
Fisher-Yates shuffle subsampling, and gamma/min_child_weight pruning. Pass
an optional seed to any fit function for reproducible training runs.
gbm_fit(feat, target, n_rounds, lr, n_thresh, is_classifier, lambda, gamma, min_child_w, subsample, seed)
Fits a single-feature gradient-boosted stump ensemble using
XGBoost-style mechanics: Newton leaf steps (second-order hessian weighting),
exact gain formula with L2 regularization, gamma pruning, minimum child
weight, and Fisher-Yates row subsampling. Each round fits one depth-1 stump
(this is not a full multi-level tree, and there is no column subsampling).
Supports both binary classification (log-odds + sigmoid) and regression (MSE).
Parameters:
feat (array) : Array of feature values, one per training row
target (array) : Array of targets — 0.0/1.0 for classification, continuous for regression
n_rounds (int) : Number of boosting rounds / stumps to fit
lr (float) : Learning rate / shrinkage applied to each round's leaf contribution
n_thresh (int) : Candidate split thresholds to scan per round
is_classifier (bool) : True = binary classification, False = squared-error regression
lambda (float) : L2 leaf regularization — Ridge-style shrinkage toward zero (XGBoost default: 1.0)
gamma (float) : Minimum gain required to accept a split — prunes weak splits (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node — prevents tiny noisy splits (XGBoost default: 1.0)
subsample (float) : Fraction of rows randomly sampled per round via Fisher-Yates (default: 1.0 = all rows)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM object ready for gbm_predict()
gbm_predict(model, x)
Scores a single feature value against a fitted GBM ensemble.
Parameters:
model (GBM) : A GBM object previously returned by gbm_fit()
x (float) : Feature value to score (same feature definition used in training)
Returns: Predicted probability if classifier, raw predicted value if regressor
gbm3_fit(feat1, feat2, feat3, target, n_rounds, lr, n_thresh, lambda, gamma, min_child_w, subsample, seed)
Fits a 3-feature gradient-boosted classifier using XGBoost-style
mechanics: Newton leaf steps, exact gain formula, L2 regularization, gamma
pruning, minimum child weight, and Fisher-Yates row subsampling. Selects the
best (feature, threshold) pair each round and boosts in log-odds space.
Each round fits a single depth-1 stump; there is no column subsampling.
Parameters:
feat1 (array) : Array of feature 1 values, one per training row
feat2 (array) : Array of feature 2 values, one per training row
feat3 (array) : Array of feature 3 values, one per training row
target (array) : Array of binary targets (0.0 or 1.0), one per training row
n_rounds (int) : Number of boosting rounds
lr (float) : Learning rate / shrinkage
n_thresh (int) : Candidate thresholds scanned per feature per round
lambda (float) : L2 leaf regularization (Ridge shrinkage, XGBoost default: 1.0)
gamma (float) : Minimum gain to accept a split (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node (XGBoost default: 1.0)
subsample (float) : Row sampling fraction per round via Fisher-Yates (default: 1.0)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM3 object ready for gbm3_predict()
gbm3_predict(model, x1, x2, x3)
Scores 3 feature values against a fitted GBM3 classifier.
Parameters:
model (GBM3) : GBM3 object from gbm3_fit()
x1 (float) : Current value of feature 1
x2 (float) : Current value of feature 2
x3 (float) : Current value of feature 3
Returns: Predicted probability
gbm4_fit(feat1, feat2, feat3, feat4, target, n_rounds, lr, n_thresh, is_classifier, lambda, gamma, min_child_w, subsample, seed)
Fits a 4-feature gradient-boosted ensemble with Newton steps, exact gain
formula, L2 regularization, gamma pruning, minimum child weight, Fisher-Yates
row subsampling, and gain-based feature importance tracking.
Supports both binary classification and regression. Each round fits a single
depth-1 stump; there is no column subsampling.
Parameters:
feat1 (array) : Array of feature 1 values, one per training row
feat2 (array) : Array of feature 2 values, one per training row
feat3 (array) : Array of feature 3 values, one per training row
feat4 (array) : Array of feature 4 values, one per training row
target (array) : Array of targets — 0.0/1.0 for classification, continuous for regression
n_rounds (int) : Number of boosting rounds
lr (float) : Learning rate / shrinkage
n_thresh (int) : Candidate thresholds scanned per feature per round
is_classifier (bool) : True = binary classification, False = regression
lambda (float) : L2 leaf regularization (Ridge shrinkage, XGBoost default: 1.0)
gamma (float) : Minimum gain to accept a split (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node (XGBoost default: 1.0)
subsample (float) : Row sampling fraction per round via Fisher-Yates (default: 1.0)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM4 object with importance scores, ready for gbm4_predict() / gbm4_importance_pct()
gbm4_predict(model, x1, x2, x3, x4)
Scores 4 feature values against a fitted GBM4 ensemble.
Parameters:
model (GBM4) : GBM4 object from gbm4_fit()
x1 (float) : Current value of feature 1
x2 (float) : Current value of feature 2
x3 (float) : Current value of feature 3
x4 (float) : Current value of feature 4
Returns: Predicted probability if classifier, raw predicted value if regressor
gbm4_importance_pct(model, feat_idx)
Returns normalized feature importance as % of total gain for one feature.
Importance = accumulated gain credited to this feature across all boosting rounds,
matching XGBoost's xgb.importance() Gain column definition.
Parameters:
model (GBM4) : GBM4 object from gbm4_fit()
feat_idx (int) : Feature index to query (0-3)
Returns: Percentage of total ensemble gain attributed to this feature (0.0–100.0)
GBM
Holds a fitted gradient-boosted stump ensemble (1 feature).
Fields:
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
base_score (series float) : Log-odds of training mean (classifier) or mean (regressor)
lr (series float) : Learning rate stored for inference
is_classifier (series bool) : True = sigmoid probability output, False = raw regression output
GBM3
Holds a fitted 3-feature gradient-boosted stump ensemble (classification only).
Fields:
stump_feat (array) : Which feature index (0-2) each round's stump split on
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
base_score (series float) : Log-odds of training mean
lr (series float) : Learning rate stored for inference
GBM4
Holds a fitted 4-feature gradient-boosted ensemble with gain-based importance.
Fields:
stump_feat (array) : Which feature index (0-3) each round's stump split on
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
importance (array) : Accumulated gain per feature (indices 0-3), raw — normalize via gbm4_importance_pct()
base_score (series float) : Log-odds (classifier) or mean (regressor)
lr (series float) : Learning rate stored for inference
is_classifier (series bool) : True = sigmoid probability output, False = raw regression output ספרייה

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

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

Parallel Transport & Holonomy [DAFE]Parallel Transport & Holonomy - (⟡ PTH)
This publication presents the quantitative mechanics and theoretical architecture behind the Parallel Transport & Holonomy engine. This system models price and volume dynamics as trajectories on a continuous two-dimensional manifold. By computing the parallel transport of multi-scale momentum vectors, tracking their covariant derivatives, and integrating their path-dependent rotational deficit ( Holonomy ), the indicator identifies macro regime shifts, structural pivots, and trend continuations.
The architecture is entirely self-contained, featuring a Legit Footprint Toggle that automatically falls back to an advanced Synthetic Footprint Engine when tick-level footprint data is unavailable. It is strictly anchored by a Rolling Confidence Matrix (RCM) and modulated by an Ensemble Dynamic Volatility Scaling (DVS) engine.
The core principle of this system is geometric invariance: signal evaluation is not based on static, lagging thresholds but on the coordinate-invariant deviation of momentum from its natural geodesic path.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Riemannian Price-Volume Manifold & Metric Tensor
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
We define the market state as a coordinate point on a two-dimensional Riemannian manifold
M, where the coordinates are:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Parallel Transport & Covariant Derivatives
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Let V be a momentum vector on the tangent space of the manifold, constructed at three distinct temporal scales: Fast (vecFast), Medium (vecMed), and Slow (vecSlow). The coordinate components of the vector scale k are computed as:
Geodesic Deviation
A path is geodesic if its covariant derivative along the direction of travel is zero (representing the path of least resistance on the manifold). We define the geodesic deviation Zgeodesic as the rolling z-score of the absolute transport deviation:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Holonomy & Phase Accumulation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Holonomy describes the geometric phenomenon where parallel transporting a vector along a closed loop returns a vector with a changed orientation. This angular deficit directly measures the total curvature enclosed by the loop.
Holonomy Group Classifications
Based on the magnitude of the accumulated rotation (HolonomyNorm), the local coordinate space is classified into four geometric groups:
Trivial (Norm<0.10): The manifold is flat; parallel transport is path-independent, indicating quiet consolidated ranges.
Abelian (Norm<0.25): Minor commutative drift; the vector field undergoes predictable linear shifts.
Non-Abelian (Norm<0.50): Significant non-commutative curvature. Parallel transport is highly path-dependent, signaling complex trend development and institutional accumulation.
Singular (Norm≥0.50): Severe rotational deficit. The manifold geometry has collapsed or rotated sharply, marking high-probability reversal peaks and structural transitions.
Holonomy Regime Shifts
A Regime Shift is triggered when HolonomyNorm exceeds the user-defined threshold (i_holoThresh). Depending on the sign of the accumulated loop (sgn(H)) and the divergence between the fast and slow vectors, the engine classifies the transition into one of the following states:
Bull Rotation : Enclosed path yields a positive rotational deficit combined with positive multi-scale momentum.
Bear Rotation : Enclosed path yields a negative rotational deficit combined with negative multi-scale momentum.
Geodesic Break : Extreme localized acceleration causing the momentum field to tear away from its expected trajectory.
Scale Divergence : High-frequency (fast) and low-frequency (slow) vectors rotate in opposite directions, enclosing a singular point.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Rolling Confidence Matrix (RCM)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Rolling Confidence Matrix (RCM) acts as a structural anchor. It takes multi-scale geometric indicators from the transport engine and compiles them into a state-space model that dynamically controls signal permissions.
State Space Representation
The matrix maintains a rolling assessment of market structure across three distinct states:
Established (State 0): The trend is structurally intact; manifold bands are compressed, and parallel transport confirms high directional persistence.
Transition (State 1): Price is approaching key structural levels or experiencing a holonomy spike. Manifold bands widen, and standard signals are gated.
Damaged (State 2): Price has broken through primary defensive corridors. Structural confidence is compromised; bands expand by the Damage Band Expansion multiplier
(i_damageWiden), and counter-trend positions are heavily penalized.
External Evidence Injection
On every bar, the system injects external geometric parameters from the manifold:
This evidence is integrated into the RCM, outputting structural permissions (allowLong, allowShort) and score modulations that are applied to the final signal scoring calculations.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Ensemble Dynamic Volatility Scaling (DVS)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
To adapt the mathematical models to varying market volatility, the script runs three independent volatility estimators concurrently on every bar:
Ensemble Combinatorics
The baseline values are calculated as moving averages over the memory period. The script then computes the ratios of the current estimators to their historical baselines:
This ratio dynamically scales the width of the holographic manifold bands and the RCM damage thresholds: during highly volatile regimes, thresholds are expanded to prevent whipsaws; during compression regimes, thresholds are tightened to capture early breakouts.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Footprint & Synthetic Fallback Engine
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The script includes a Use Legit Footprint toggle (i_useFp). When enabled on charts supporting tick databases, the system requests official exchange-traded order flow data:
fp=request.footprint(i_fpTicks,i_fpVA)
The Advanced Synthetic Footprint Engine
If the user deactivates the footprint toggle, or if the asset/timeframe does not support tick database access (e.g., historical bars or Forex), the Synthetic Footprint Fallback Engine** takes over, simulating volume-at-price and directional delta using high-frequency mathematical approximations:
This estimated delta reconstructs the synthetic buy and sell pressures:
Kyle's Lambda (Price Impact & Liquidity Risk)
Using these directional volumes, we calculate Kyle's price impact coefficient λ, measuring the price change per unit of volume flow:
High values of λ represent illiquid, thin, or toxic conditions. The system calculates the z-score of lambda (Zλ). If Zλ > 2.0, signal scores are dynamically penalized to protect capital from low-liquidity slippage.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Structural Scoring & Signal Gating
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The system generates a directional Signal Score using a two-tier quantitative scoring process.
Stage 1: Structural Base (Minimum of one required)
Siege Corridor Proximity : Price is within 1.2 ⋅ ATR of a verified support or resistance level.
ScoreBase = 0.28+(Hold Probability⋅0.18)
EMA21 Geodesic Pullback : Price pulls back to the EMA21 in trend alignment.
ScoreBase = 0.25
RSI Extreme Exhaustion : RSI is below 25 (for longs) or above 75 (for shorts).
ScoreBase = 0.28
Stage 2: Confirmations (Additive)
Multi-pattern confluence (2+ patterns matching): +0.15
Pressure bar strength exceeds thresholds: +0.08 to +0.15
Metric curvature aligns with structural turn: +0.10
Volume expansion exceeds historical average: +0.10
Holonomy phase shifts or loop spikes: +0.12
Directional Scaling & Gating
The score is adjusted based on trend alignment. With-Trend (WT) setups (longs above the EMA50, shorts below) are evaluated using standard thresholds. Counter-Trend (CT) setups face a strict scaling penalty:
ScoreCT = ScoreRaw ⋅ clamp(1.0−Trend Strength⋅0.15,0.45,1.0)
Additionally, the score passes through three gates:
Liquidity Penalty : Reduced by up to 30% if order flow thickness is classified as Desert or Frozen.
Kyle Lambda Gate : Penalized if price impact is highly volatile (Zλ > 2.0).
Danger Gate : Score is multiplied by 0.60 if the composite risk danger index exceeds 75.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Input Reference
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
═══ GEOMETRY ENGINE ═══
Hurst Period (30 to 200, default 80): Lookback window for R/S calculations to evaluate trend persistence.
Pivot Length (2 to 15, default 5): Lookback/lookahead buffer for swing pivot detection.
TF Preset (Auto, 1m-5m Scalp, 10m-15m Intra, 30m-1H Swing, 4H-D Position): Set the timeframe scaling preset. Auto dynamically scales lookbacks based on the current chart timeframe.
Use Legit Footprint (Boolean, default true): Toggles whether to query exchange tick database for real footprint data.
Footprint Ticks/Row (1 to 500, default 100): Height of the footprint rows in tick units.
Footprint VA % (50 to 90, default 70): Percentage of volume enclosed within the Value Area.
═══ TRANSPORT & HOLONOMY ═══
Vector Fast Scale (3 to 21, default 8): Periods for tracking short-term momentum vectors.
Vector Medium Scale (10 to 55, default 21): Periods for intermediate momentum geometry.
Vector Slow Scale (21 to 144, default 55): Baseline vector window representing the macro manifold.
Holonomy Window (13 to 89, default 34): Size of the temporal loop used to integrate local deviations.
Holonomy Spike Threshold (0.10 to 0.90, default 0.35): Sensitivity threshold for identifying rotational shifts.
Geodesic Deviation Sensitivity (0.5 to 3.0, default 1.5): Sensitivity for flagging off-path momentum.
Enable Continuation Signals (Boolean, default true): Toggles secondary pullback entries in strong trends.
═══ ROLLING CONFIDENCE MATRIX ═══
Block Transition Signals (Boolean, default true): If active, blocks standard entry signals when the matrix is in transition state.
Conf Band Tightening Factor (0.0 to 1.0, default 0.35): Compression multiplier for manifold bands under high confidence.
Damage Band Expansion (1.0 to 1.5, default 1.15): Expansion multiplier for manifold bands under structural damage.
═══ DYNAMIC VOLATILITY SCALING (DVS) ═══
Enable Ensemble DVS Engine (Boolean, default true): Toggles whether to scale target multiples and thresholds by volatility.
DVS Method (ATR Ratio, Parkinson, Garman-Klass, Ensemble): Method for calculating real-time volatility.
DVS Memory Period (20 to 200, default 100): Baseline lookback window for historical volatility.
DVS Sensitivity (0.3 to 1.5, default 0.7): Exponent scaling parameter for the DVS ratio.
═══ SIGNAL GATING ═══
Signal Threshold (0.10 to 0.85, default 0.40): Minimum score required to fire a signal.
Cooldown Bars (1 to 50, default 6): Minimum bar spacing between consecutive signals.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Visual System & Dashboard Interpretation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Transport Field Manifold : A multi-layered band surrounding price. It contracts during clean, high-confidence geodesic flow and expands during high-entropy, damaged, or volatile regimes. Its color is determined by the RCM state: Green for bullish stability, Red for bearish, and Purple during transitions.
Siege Corridors : Plotted as horizontal support (Green) and resistance (Red) zones with an ATR-scaled boundary. At the right-hand side of the chart, these corridors display critical metrics: the total historical hit count, the estimated break probability (Pbreak), and the fail/reversal probability (Pfail).
Vector Field Lines : Small arrow-headed lines plotted on every third bar. They show the mathematical direction of the Fast momentum vector. They visually represent the difference between the actual observed path of the market and the expected parallel-transported baseline.
Holonomy Phase Ring : An indicator plotted at the right edge of the chart displaying the current phase angle (e.g., ◐ 144∘).
Glitch Markers: Flagged on the chart as ◈ GLITCH when anomalous pricing data or sudden coordinate jumps are detected on the manifold.
Dashboard: Displays real-time metric readings from all quantitative modules:
Tensor Metrics: Curvature, Entropy, Hurst Exponent, and Price Pressure.
Volatility: Dynamic DVS Ratio, active estimator method, and scaling state.
RCM Brain: State classification, integrity index, and gate permissions.
Performance: Total trades, win rate, total profit (R-multiple), profit factor, and max drawdown.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Limitations and Disclaimers
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This tool is for analytical purposes only and does not predict future market direction.
Historical Simulation: The built-in simulator represents hypothetical performance on historical data. Past results do not guarantee future performance.
Volume Approximations: The synthetic footprint engine uses OHLCV approximations to estimate volume-at-price and directional delta. It is not an actual connection to L2 exchange data feeds or a central clearing book.
Persistence: Reinforcement learning weights are state-space variables that exist within the local execution thread; they reset to 1.0 on every chart load or browser reload.
— Dskyz. Trade with insight. Trade with anticipation. (It's lonely at the top) אינדיקטור

Fractional CUSUM Regime Filter [Jamallo]🔹 Intro
The Fractional CUSUM Regime Filter is a quantitative trend and volatility channel indicator designed to identify structural market regimes with high stability. Unlike traditional filters that suffer from lag or whipsaw signals, this indicator applies a dual-layered preprocessor combining Lopez de Prado’s Fixed-Window Fractional Differentiation (FFD) with a classic Cumulative Sum (CUSUM) statistical trigger.
🔹 Break down
Fractional Differentiation (FFD) : Stationarizes pricing input while retaining long-term historical memory (controlled by the "d" parameter).
Classic CUSUM Filter : Accumulates deviations from a rolling baseline relative to current volatility. When cumulative deviation exceeds the threshold multiplier (h), a new regime change is triggered, and the baseline steps dynamically to the new price level.
Vol-Adjusted Percentile Bands : Linear interpolation percentiles of price deviation relative to the stepped baseline. The distances are "locked" and only update on CUSUM regime triggers to prevent wobbly bands.
🔹 Visual Guide: Indicator Anatomy
Here we have the structure of the indicator, including the CUSUM baseline, the 68% inner percentile band, and the 95% outer percentile band.
How to use: Mean Reversion (Pullbacks to the Mean)
The channel boundaries represent statistical extremes. When the price is pushed outside the bands, it is mathematically overextended and highly likely to revert back to the CUSUM baseline.
Long Setup (Pullbacks in Bullish Trend): During a green CUSUM uptrend, watch for price to pull back to the lower bands ("micro pullback") and enter as it heads back up to the baseline mean.
Short Setup (Pullbacks in Bearish Trend): During a red CUSUM downtrend, watch for price to rally into the upper bands ("micro pullback") and enter as it reverts down to the baseline mean.
🔹 How to use: Trend Following & Risk Management
The indicator is designed to capture sustained macro trends while providing clear risk parameters.
Entering on Breakthroughs : Enter when the BUY/SELL signal flags appear (indicating a new CUSUM regime shift).
Stop Loss Placement : Place stop loss orders just below the opposite outer band or below the stepped baseline.
Letting Winners Run : Ride the trend as long as the CUSUM baseline maintains its colored regime state (Green for Long, Red for Short).
🔹 Settings Parameters
d (0.01 - 0.99) : Differentiation order. Lower values retain more historical memory; higher values approach first-difference.
CUSUM Drift & Threshold : Controls baseline sensitivity to regime changes.
Percentile Lookback & Targets : Set the statistical width of the inner and outer boundaries.
אינדיקטור

Momentum Engine - [DecodingFlowLab]Decoding Lab – Momentum Engine is a quantitative momentum analysis indicator designed to detect real market expansion and institutional-grade directional pressure.
Unlike traditional momentum indicators that rely on a single source such as RSI or MACD, Momentum Engine combines multiple market dynamics into one unified scoring model, including:
• Volatility Expansion (ATR Expansion)
• Candle Body Strength
• Relative Volume Activity
• Breakout Velocity
• Pullback Efficiency
The indicator calculates a dynamic Momentum Score ranging from 0 to 100, helping traders identify whether the current move is supported by genuine market participation or simply random price fluctuation.
━━━━━━━━━━━━━━━━━━
How It Works
━━━━━━━━━━━━━━━━━━
Momentum Engine analyzes five core components of market behavior:
• ATR Expansion
Measures whether volatility is expanding relative to normal market conditions.
• Candle Body Strength
Evaluates the dominance of buyers or sellers through candle body size relative to total range.
• Volume Expansion
Detects abnormal trading activity compared to average market participation.
• Breakout Speed
Measures how aggressively price moves after breaking key highs or lows.
• Pullback Efficiency
Analyzes whether retracements remain shallow or become excessively deep.
All factors are normalized and combined into a weighted Momentum Score to classify market conditions as:
• Bullish Momentum
• Bearish Momentum
• Weak / No Momentum
The indicator also prints “M” labels when strong momentum first appears.
━━━━━━━━━━━━━━━━━━
How Traders Use It
━━━━━━━━━━━━━━━━━━
Traders use Momentum Engine to:
• Detect strong breakout conditions
• Confirm trend continuation strength
• Filter weak or low-quality market moves
• Identify institutional momentum expansion
• Avoid trading during weak or ranging conditions
• Improve timing for entries during impulsive moves
Common use cases include:
• Breakout Trading
• Momentum Trading
• Smart Money Concepts (SMC)
• Scalping & Intraday Trading
• Trend Continuation Strategies
The indicator is especially powerful when combined with:
• Market Structure
• BOS / CHOCH
• Liquidity Sweeps
• Higher Timeframe Bias
• Volume Analysis
━━━━━━━━━━━━━━━━━━
Main Features
━━━━━━━━━━━━━━━━━━
• Detects strong bullish and bearish momentum
• Identifies explosive breakout conditions
• Measures trend continuation quality
• Detects early momentum ignition using M labels
• Includes real-time quantitative momentum dashboard
• Combines Price Action + Volume + Volatility in one engine
Momentum Engine is built for traders who want to move beyond traditional oscillators and analyze the true strength behind market movements.
Disclaimer:
This indicator is provided for educational and informational purposes only and should not be considered financial advice, investment advice, or a recommendation to buy or sell any financial instrument.
The indicator does not provide guaranteed entry or exit signals for trading positions. Financial markets involve significant risk, and past performance does not guarantee future results.
Users are solely responsible for their own trading decisions, risk management, and use of this indicator in any market or trading environment.
The publisher, developer, and distributor of this indicator assume no responsibility or liability for any financial losses, damages, or outcomes resulting from the use or misuse of this indicator.
אינדיקטור

Adaptive Sharpe Ratio (Robust & Regime-Aware)Adaptive Sharpe Ratio (Robust & Regime-Aware) — ASR+
ASR+ (Adaptive Sharpe Ratio) on a daily chart, highlighting regime shifts and dynamically adjusted risk-aware performance.
WHAT IS ASR+
ASR+ (Adaptive Sharpe Ratio) is an enhanced version of the traditional Sharpe Ratio designed to remain statistically reliable in real market conditions.
It improves on the standard model by correcting for autocorrelation, fat tails, and regime-dependent volatility—factors that routinely distort conventional Sharpe readings.
The result is a more stable, realistic measure of risk-adjusted performance that adapts across timeframes, asset classes, and market environments.
WHY THIS MATTERS
The standard Sharpe Ratio assumes:
Stable volatility
Independent returns
Normally distributed returns
Real markets violate all of these assumptions.
Result: Sharpe can become inflated, unstable, and misleading—often underestimating risk, especially on lower timeframes.
ASR+ is designed to overcome these shortcomings.
WHAT “ROBUST” MEANS
ASR+ is built to resist common distortions:
Outliers & fat tails → adjusted
Skewed returns → penalized
Autocorrelation → corrected (HAC / Newey–West)
Small samples → estimation bias reduced
Result: more stable and realistic Sharpe values.
WHAT “REGIME-AWARE” MEANS
Markets change — volatility and behavior shift.
ASR+ adapts dynamically:
High volatility → stronger risk penalty
Calm markets → normalized evaluation
Regime shifts → reflected in real time
Result: avoids false confidence during risky conditions.
─────────────────────────────────────────
WHAT MAKES ASR+ DIFFERENT
─────────────────────────────────────────
🔹 HAC Autocorrelation Correction (Newey-West)
Uses a 4-lag Bartlett kernel to correct for serial correlation in returns. When returns are trending or mean-reverting, standard volatility estimates are biased. ASR+ adjusts variance to prevent Sharpe inflation during momentum regimes.
🔹 Cornish-Fisher Tail Adjustment
Incorporates skewness and excess kurtosis into the risk estimate. Markets with fat tails or negative skew carry more downside risk than standard deviation alone captures. This adjustment penalizes asymmetric or heavy-tailed return distributions at the 95% confidence level.
🔹 Volatility Regime Penalty
Detects when current volatility is elevated relative to its historical average and applies a dynamic penalty. ASR+ becomes more conservative exactly when standard Sharpe is most likely to mislead.
🔹 Small-Sample Uncertainty Correction
Applies a bias correction to the mean return estimate, accounting for statistical uncertainty from limited observations. Shorter lookbacks carry more estimation error, which ASR+ reflects.
🔹 Adaptive Risk Adjustment
All adjustments — tail risk, volatility regime, autocorrelation, and estimation uncertainty — are combined through an interaction-aware framework. This prevents double-counting while allowing interacting risk factors to generate appropriately compounded penalties. The total adjustment is capped to avoid over-penalization.
🔹 Multi-Asset, Multi-Timeframe Scaling
Automatically detects asset type (crypto, equities, forex, futures) and timeframe (seconds through monthly) and applies appropriate annualization.
Crypto → 365-day, 24-hour markets
Equities → 252-day, 6.5-hour sessions
No manual configuration required.
🔹 Extreme Value Moderation
During periods of high volatility or reduced estimation reliability, ASR+ moderates extreme Sharpe values in both directions. Positive readings may be reduced, while negative readings may move closer to zero, reflecting lower statistical confidence rather than a change in underlying performance.
🔹 Logarithmic Returns
ASR+ uses logarithmic (log) returns instead of arithmetic returns. Log returns are time-additive and more statistically consistent across timeframes, improving the stability and comparability of risk-adjusted performance, particularly over longer horizons and in the presence of compounding.
ADAPTIVE VS STANDARD SHARPE
Toggle between:
Standard Sharpe → baseline calculation (thinner line)
ASR+ → adjusted, real-world version (thicker line)
Use this to:
Detect inflated Sharpe values
Reveal hidden risk
Validate strategy robustness
─────────────────────────────────────────
REGIME CLASSIFICATION
─────────────────────────────────────────
Light theme view for clarity and accessibility. The same regime classification logic is applied across themes.
ASR+ colors both the plotted line and background for instant interpretation:
🔴 Red → Below 0 — Negative risk-adjusted return
⚫ Gray → 0 to 1 — Subpar performance
🟢 Green → 1 to 2 — Good performance
💚 Lime → Above 2 — Exceptional performance
─────────────────────────────────────────
KEY INPUTS & SETTINGS
─────────────────────────────────────────
→ Lookback Period
Minimum: 50 bars (Daily & Intraday), 36 (Weekly), 24 (Monthly)
Recommended: 63 (Daily), 100 (4H), 252 (1H), 500 (30M)
For high-volatility assets (e.g., growth stocks, crypto), longer lookbacks are recommended to reduce sensitivity to short-term trends
Short lookbacks during strong trending conditions can produce elevated readings that reflect momentum rather than sustainable risk-adjusted performance
→ Risk-Free Rate
Annualized (default 4.5%), adjustable to reflect prevailing rates
→ Show Adaptive vs Standard Sharpe
Plot both to visualize adjustment magnitude
→ EMA Smoother
Optional smoothing to reduce noise
→ Background Regime Colors
Fully customizable
─────────────────────────────────────────
WHO THIS IS FOR
─────────────────────────────────────────
→ Quantitative traders evaluating strategies
→ Multi-asset traders needing consistent metrics
→ Risk-conscious traders focused on efficiency, not just returns
→ Systematic traders monitoring regime shifts in real time
IMPORTANT
ASR+ is not a buy/sell signal.
It measures the quality of returns to support:
Strategy evaluation
Risk control
Position sizing
All calculations are based on confirmed historical data and do not rely on future values.
─────────────────────────────────────────
Built with statistical rigor for traders who demand more accurate evaluation tools.
─────────────────────────────────────────
אינדיקטור

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.
אינדיקטור

Quantum Momentum Wave [Pineify]Quantum Momentum Wave
Quantum Momentum Wave is a signed peak-momentum oscillator paired with a Kaufman-style adaptive filter. Instead of measuring the net change from one point to another, the wave scans the full lookback window and returns the largest absolute price displacement with its original sign. The wave is linearly smoothed and then tracked by an adaptive signal line, so entry markers fire on context-filtered reversals rather than every momentum flip.
Key Features
Signed peak-momentum engine that isolates the strongest move inside the lookback
Linear regression smoothing to tame the step-change behavior of raw peak readings
Adaptive signal line that speeds up when the wave is stretched and slows down in noise
Zone-filtered BUY and SELL markers that only fire when the wave is past zero in the opposite direction
Gradient fill between the wave and zero — bullish above, bearish below
Alerts for reversal setups and for zero-line regime shifts
How It Works
The core function is a QMW scan. On each bar it walks the last Momentum Lookback bars, computes price minus each historical bar, and keeps the comparison that produced the largest absolute change. It returns that value with its original sign. So a -6 reading means the single strongest move inside the window was a 6-unit drop, even if the bar-to-bar change right now is small.
Raw peak readings step when a new candle takes over as the dominant move, so the output is passed through linear regression over the Signal Smoothing length. LR fits a straight line through the recent raw values and returns its endpoint, preserving signed direction while cutting short-term jitter.
The adaptive signal runs a Kaufman-style update on top of the smoothed wave. Its coefficient is the ratio of the wave's absolute value to the sum of its recent absolute one-bar changes. When momentum is clearly extended and directional, the ratio is high and the signal follows quickly. When the wave oscillates near zero, the ratio collapses and the line nearly freezes.
How the Components Work Together
Three layers combine into one output. The peak scan answers how hard has price moved inside the window, not just where it ended. Linear regression answers what is the underlying direction of the peak reading after filtering out one-bar swaps between competing peak bars. The adaptive signal answers when has that direction actually shifted by providing a responsive reference line.
Entries layer a location filter on top. A crossover only qualifies when the wave is on the opposite side of zero — buys look for the wave turning up while stretched below zero, sells for the wave rolling over while stretched above it. Crosses near the midline are ignored because they tend to be low-conviction flips without prior displacement, so the setup is biased toward reversals from extended states rather than trend-chasing entries.
Trading Ideas and Insights
BUY triangles below zero can flag exhaustion of a downside push and a possible rotation back toward the mean
SELL triangles above zero can flag fading upside strength after an extended rally
Zero-line crosses act as broader regime markers; alerts on those can frame intraday bias
During strong trends the wave may stay on one side of zero for many bars. Counter-trend BUY or SELL labels in that state often need extra confirmation from price structure or higher-timeframe context
Signals are context aids, not standalone trade instructions. Past reactions at these conditions do not guarantee future ones.
Unique Aspects
The momentum calculation returns the peak signed displacement within the lookback, not a simple close-minus-close value. The reading stays elevated while the dominant move is still inside the window, which tracks the strongest displacement in memory rather than just endpoint delta
The adaptive signal uses a non-standard variation of Kaufman's efficiency ratio — absolute wave value divided by total absolute wave travel — tuned for oscillator input rather than raw price
Entry markers require both a crossover and a zone match. No label prints for a crossover that happens in the neutral zone around zero, which filters out the weakest setups
How to Use
Add the indicator to the chart and start with the defaults. The thicker line is the Quantum Wave; the fainter line is the Adaptive Signal
Read the wave color and the gradient fill to see which side of zero the wave is on and how stretched it is
Watch for BUY triangles when the wave is clearly below zero and turning up through the signal line
Watch for SELL triangles when the wave is clearly above zero and turning down through the signal line
Configure alerts for buy, sell, or zero-cross conditions if you want notifications outside the chart
Customization
Source Data (default: close) — Price series used for the peak momentum scan
Momentum Lookback (default: 14) — Window size for the peak displacement scan. Higher values capture broader swings; lower values react faster
Signal Smoothing (default: 9) — Linear regression length applied to the raw wave. Higher values produce a cleaner line with more lag
Bullish Color / Bearish Color — Wave color in positive and negative territory, and the BUY/SELL marker colors
Adaptive Signal Color — Color of the adaptive reference line; a subtle contrast against the wave usually reads cleanest
Limitations
Linear regression smoothing introduces a small amount of lag. On fast reversals the wave can reach the crossover a few bars after price has already moved
Because the adaptive ratio uses the wave's own value, very small wave readings near zero make the signal line nearly freeze. This is deliberate but means the reference reacts slowly while momentum is mild
Mean-reversion style BUY and SELL labels can occur repeatedly during strong trends. Pair them with price structure or higher-timeframe bias instead of using them in isolation
Conclusion
Quantum Momentum Wave is for traders who want an oscillator that reflects the strongest recent move rather than the endpoint delta. Its value comes from the combination of peak-momentum measurement, linear regression smoothing, and an adaptive reference line that only produces labels when the wave is both stretched past zero and visibly turning back. אינדיקטור

ontagion & Shock System (CSS) - Systemic Risk TrackerThe Contagion & Shock System (CSS) is an advanced quantitative indicator designed to measure systemic risk and sector contagion in real-time. Instead of looking at a single asset in isolation, this system tracks how sudden price shocks ripple across a configurable basket of proxy assets, helping traders identify true macro risk-on or risk-off environments.
1. Shock Detection
The system continuously monitors the base asset for sudden volatility spikes. It triggers an active "Shock" if a single bar exceeds a specific percentage threshold, or if a cumulative multi-bar move indicates sustained, aggressive buying or selling pressure.
2. Dynamic Correlation Engine (Wave Assignment)
The indicator runs a live Pearson Correlation (using log returns) between your base chart and 10 configurable proxy assets (e.g., SPY, QQQ, VIX, XLF). It automatically buckets these assets into three contagion waves:
Wave 1 (Immediate Impact): Correlation >= 0.70
Wave 2 (Lagging Impact): Correlation >= 0.40
Wave 3 (Distant/Isolated): Correlation < 0.40
3. Contagion Pressure Index (CPI)
Displayed as a central histogram, the CPI aggregates the correlation strength and directional movement of all 10 proxies. A positive score indicates risk-on contagion (assets are rising together), while a negative score indicates risk-off contagion (assets are falling together).
4. Systemic Risk Score (0-100)
Located in the dashboard, this gauge blends the magnitude of the CPI, the number of assets currently caught in Wave 1, and the recency of the last price shock. A score above 80 indicates severe market-wide stress.
Users can fully customize the shock thresholds, cumulative lookback windows, correlation lengths, and all 10 proxy tickers via the indicator settings to tailor the system to specific sectors or asset classes. אינדיקטור

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. אינדיקטור

אינדיקטור

אינדיקטור

Volatility Expansion Indicator - D_QuantVolatility Expansion Indicator - D_Quant |V|C|E|
1. Concept & Overview
The Volatility Expansion Indicator (VCE) is a composite quantitative tool designed to identify robust trend states by aggregating signals from three distinct market dimensions: Relative Position (Volatility), Cyclical Momentum, and Price Velocity.
Unlike single-source indicators which often generate false positives during choppy markets, the VCE utilizes a "Consensus Engine." It normalizes signals from Bollinger %B, CCI, and ROC into a unified trend score (-1 to +1). This score drives the visual coloring of the price action and background, allowing traders to instantly gauge whether the market is in a state of volatility expansion (trending) or contraction (ranging).
2. Methodology & Calculation
The core logic relies on a weighted aggregation of three technical components. Users can toggle these components on or off in the settings to isolate specific market mechanics.
A. Component 1: Bollinger %B (Relative Positioning)
Logic: Measures where the price is located relative to the Bollinger Bands.
Bullish Condition: If %B > 0.5 (Price is operating in the upper hemisphere of the bands).
Bearish Condition: If %B < 0.0 (Price has broken below the lower band).
Purpose: Filters out weak trends by ensuring price is statistically significant relative to its recent volatility.
B. Component 2: CCI (Commodity Channel Index)
Logic: Measures current price levels relative to an average price level over a specific period.
Thresholds: A standard +100 / -100 threshold is used. Values above 100 add to the bullish score; values below -100 add to the bearish score.
Purpose: Identifies cyclical momentum extremes.
f_cci(_len) =>
cci_val = ta.cci(close, _len)
val = 0
if cci_val > 100
val := 1
if cci_val < -100
val := -1
val
C. Component 3: ROC (Rate of Change)
Logic: Calculates the percentage change between the current price and the price n periods ago.
Thresholds: Simple zero-line crossover. Positive ROC implies bullish velocity; negative implies bearish.
Purpose: Provides a raw directional bias based on pure price speed.
D. The Aggregation Engine: The script sums the active signals and divides by the number of active components.
Bullish Trend: Composite Score > 0 (Visualized as Deep Navy).
Bearish/Neutral: Composite Score ≤ 0 (Visualized as White).
E. Multi-Timeframe (MTF) Capability: The indicator includes a request.security module. This allows you to calculate the consensus trend on a higher timeframe (e.g., Daily) while viewing price action on a lower timeframe (e.g., 15-minute), ensuring you are trading in alignment with the macro trend.
// NEW: Timeframe Selection
tf_input = input.timeframe("", "VCE Timeframe", group=grp_sets, tooltip="Empty = Current Chart. Set to 'D' for fixed Daily trend.")
= request.security(syminfo.tickerid, tf_input, , lookahead=barmerge.lookahead_on)
3. Visualizations
The indicator overlays the following elements on the chart:
Trend SMMA: A central Smoothed Moving Average (SMMA 20) representing the mean.
Volatility Bands: Upper and Lower bands calculated at 2 Standard Deviations from the SMMA.
Bar Coloring:
Navy Blue: Indicates a confirmed Volatility Expansion (Bullish Confluence).
White: Indicates Neutrality, Retracement, or Bearish conditions.
Dynamic Fills: The space between the bands fills with color to highlight the strength of the current regime.
4. How to Use
Trend Following: Look for the bar color to switch to Navy. This indicates that momentum, volatility, and velocity have aligned bullishly. This is often an entry trigger for long positions.
Exits: When the bars switch from Navy back to White/Gray, the volatility expansion has ceased or momentum is diverging. This serves as a warning to tighten stops or take profits.
MTF Filter: Set the "VCE Timeframe" input to "D" (Daily). Trade on the H1 chart. Only take long positions when the Daily VCE paints the background/bands in the Bullish color.
5. Settings
Bollinger %B: Adjust Length and Multiplier (Default: 20, 2.0).
CCI: Adjust Length (Default: 23).
ROC: Adjust Length (Default: 50).
Signal Components: Toggle specific logic blocks on/off to customize the sensitivity of the composite score.
VCE Timeframe: Select the resolution for the calculation (Leave empty for current chart).
Disclaimer: This tool is for informational purposes only. Past performance of volatility expansion does not guarantee future results. Always manage risk appropriately. אינדיקטור

Institutional Alpha Vector | D_QUANT Institutional Alpha Vector | D_QUANT
Overview
The Institutional Alpha Vector (IAV) is an original trend-following framework that replaces single-indicator bias with a Weighted Composite Score . Instead of relying on a simple moving average, this script aggregates four distinct quantitative dimensions—Price, Momentum, Volatility, and Volume—into a normalized value called the "Alpha Vector."
The goal of this tool is to identify "Institutional Consensus"—periods where multiple mathematical models align in the same direction, reducing the likelihood of false breakouts in choppy markets.
How It Works: The Quantitative Engines
The script calculates four independent signals. For each module, a state is stored (1 for Bullish, -1 for Bearish, 0 for Neutral).
1. Price Filter (Hull Moving Average):
The script uses an HMA (a weighted moving average that reduces lag by using the square root of the period). A signal is triggered when the price crosses over/under this "Spine."
2. Volatility Regime (RMA + ATR):
This module uses a Moving Average (RMA) combined with an Average True Range (ATR) offset. It acts as a volatility filter that price must move beyond 1 ATR from the mean to register a trend, ensuring the market isn't just "drifting."
3. Momentum Physics (ADX/DMI):
Based on J. Welles Wilder’s Directional Movement Index. It checks if the is above (or vice versa) but only if the ADX (Average Directional Index) is above a user-defined threshold (default: 10), confirming the presence of a strong trend.
4. Institutional Flow (Chaikin Money Flow):
This confirms price action with volume. It calculates the accumulation/distribution of money flow over a specific period. A signal is only valid if the CMF is positive (Bullish) or negative (Bearish).
The Alpha Vector Calculation
This is the core "originality" of the script. The indicator takes the active modules and calculates a Composite Score :
This results in a value between -1.0 and +1.0 .
* High Confidence Long: When the score exceeds +0.1 (adjustable).
* High Confidence Short: When the score drops below -0.1 (adjustable).
* Neutral Zone: When the score is near 0, the script colors the bars grey, signaling a lack of institutional consensus.
Visual Intelligence: The "Electric Conduit"
The script visualizes market energy through a custom rendering engine:
* The Spine: A central line representing the HMA trend.
* The Conduit (Fill): A dynamic gradient that expands or contracts based on the ATR (Average True Range) . This allows traders to see "volatility expansion" (wide ribbon) vs "compression" (tight ribbon) at a glance.
* Bar Coloring : Automatically aligns the chart candles with the Alpha Vector state to remove cognitive load.
How to Use
1. Define your Strategy: In the settings, you can toggle specific modules. If you are trading a low-volume asset, you might disable the **CMF** module.
2. Identify the Consensus: Look for the ribbon to change from Grey (Neutral) to Cyan/Gold.
3. Monitor the HUD: A small dashboard in the bottom right displays the live Alpha Vector score. A score of 1.0 means all four engines are in 100% bullish agreement.
Disclaimer: Trading involves significant risk. This tool is for educational and analytical purposes and does not constitute financial advice. אינדיקטור

Cycle & Flow Indicator - D_QuantCycle & Flow Architecture (CFA) | Multi-Factor Regime Analysis
Overview
The Cycle & Flow Architecture (CFA) is a trend-following visualization engine that utilizes a triple-confirmation "Voting Mechanism" to identify market regimes. Rather than relying on a single lagging indicator, the CFA aggregates Cyclical Momentum, Directional Bias, and Volume Flow from the Daily timeframe to provide a unified consensus signal on your current chart.
The goal of this script is to filter market noise by requiring a quantitative agreement between three non-correlated mathematical models before a "Regime Change" is visualized.
The Quantitative Logic
The core of the CFA is its Aggregation Engine, which calculates a normalized Quant Score ranging from -1.0 to +1.0. The engine polls three distinct components:
Schaff Trend Cycle (STC): This component identifies the cyclical nature of price. It applies a double-smoothed stochastic process to a MACD line. In this script, the STC contributes a bullish signal when the cycle is above 25 and a bearish signal when the cycle is below 75 and falling.
Parabolic SAR (PSAR): Used as a rigid directional filter. It calculates the "Stop and Reverse" points, if the price is above the PSAR, it contributes a +1 to the consensus, if below, a -1.
Ease of Movement (EOM): This is the volume-validation component. It analyzes the relationship between price change and volume. A positive EOM suggests price is moving up on light resistance (conviction), while negative EOM suggests easy downward movement.
How it Works: The Voting Mechanism
The script calculates these three values on the Daily (D) timeframe using request.security to ensure higher-timeframe confluence.
Bullish Regime: Triggered when the average score exceeds the Bullish Threshold (Default: 0.2).
Bearish Regime: Triggered when the average score falls below the Bearish Threshold (Default: -0.2).
Neutral Regime: When the components disagree or the scores hover near zero, the engine renders a "Grey" noise state, signaling a high-probability "sit on hands" environment.
How to Use
The Ghost Cloud: The central Hull Moving Average (HMA 20) acts as the baseline. The "cloud" fills between this baseline and the price, colored by the current Score.
Volatility Extensions: The script plots ATR-based bands (14-period) that only appear during confirmed regimes. In a Bullish regime, the upper band appears, in a Bearish regime, the lower.
Trade Execution: Traders typically look for the "Bullish/Bearish Start" alerts to signal the beginning of a new regime and use the "Grey" neutral zones to tighten stop-losses or exit positions.
Settings
Thresholds: Increase the Bullish/Bearish thresholds (e.g., to 0.5) to require more stringent agreement between the STC, PSAR, and EOM.
Timeframe Note: The calculations are hardcoded to the Daily timeframe to provide a "North Star" directional bias regardless of whether you are viewing the 15m or 4h chart.
Disclaimer: This tool is for educational and analytical purposes only. Quantitative models represent mathematical probabilities, not guarantees.
© D_QUANT אינדיקטור

Keltner-Aroon-EFI FlowKeltner-Aroon-EFI Flow (KAE)
KAE Flow is a quantitative composite indicator designed to identify dominant market trends by fusing three distinct dimensions of price action: Volatility, Trend Age, and Volume Pressure.
Unlike standard indicators that rely on a single data point (like a moving average crossover), KAE Flow aggregates three independent logic engines into a single normalized "Flow" score. This score is then smoothed using an Arnaud Legoux Moving Average (ALMA) to filter out noise while retaining responsiveness to genuine trend reversals.
This script operates strictly on the current chart timeframe, ensuring all signals are causal, non-repainting, and reliable for real-time analysis.
1. The Quantitative Engine (How it Works)
The indicator polls three separate components. Each component votes "1" (Bullish), "-1" (Bearish), or "0" (Neutral). These votes are averaged to create the raw signal.
K — Keltner Channels (Volatility Dimension)
Concept: Measures volatility expansion.
Logic: The script calculates Keltner Channels using an EMA center line and ATR bands.
Bullish (+1): Price closes above the Upper Channel.
Bearish (-1): Price closes below the Lower Channel.
This component ensures we only trade when price is breaking out of its expected volatility range.
A — Aroon (Trend Age Dimension)
Concept: Measures the strength and "freshness" of a trend.
Logic: We utilize the Aroon Up and Aroon Down metrics.
Bullish (+1): Aroon Up is greater than Aroon Down AND Aroon Up is > 70.
Bearish (-1): Aroon Down is greater than Aroon Up AND Aroon Down > 70.
This filters out weak or aging trends, ensuring the move has mathematical momentum.
E — Elder’s Force Index (Volume Dimension)
Concept: Measures volume-weighted price change.
Logic: We calculate the raw Force Index (Close - Close ) * Volume and smooth it with an EMA.
Bullish (+1): Smoothed EFI > 0.
Bearish (-1): Smoothed EFI < 0.
This component confirms that price movement is supported by actual volume flow (accumulation/distribution).
2. Signal Processing (ALMA Smoothing)
Raw aggregation can be noisy. The composite score is passed through an ALMA (Arnaud Legoux Moving Average) filter.
Why ALMA? It uses a Gaussian distribution to provide smoothness without the significant lag associated with SMA or EMA. This creates the "Flow" line that resists false flips during choppy consolidation.
3. How to Use
The indicator plots a signal line and dynamically colors the price bars and background to reflect the dominant bias.
Deep Blue (Bullish Flow): The KAE Score is > 0.1. All three engines (or the majority) are aligned bullishly. Traders typically look for long entries or hold existing long positions.
White (Bearish Flow): The KAE Score is < -0.1. The majority of engines detect bearish volatility and volume. Traders typically look for short entries.
Gray (Neutral): The score is between -0.1 and 0.1. The market is in equilibrium or transition. Trend-following strategies should be paused.
4. Configuration
Logic Engine: You can toggle individual components (K, A, or E) on or off to isolate specific market dimensions.
Smoothing: Adjust the ALMA Window and Offset to fine-tune the sensitivity of the signal line.
Lengths: Fully customizable periods for Keltner, Aroon, and EFI to adapt to different asset classes (e.g., Crypto vs. Forex). אינדיקטור

DeeptestDeeptest: Quantitative Backtesting Library for Pine Script
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ OVERVIEW
Deeptest is a Pine Script library that provides quantitative analysis tools for strategy backtesting. It calculates over 100 statistical metrics including risk-adjusted return ratios (Sharpe, Sortino, Calmar), drawdown analysis, Value at Risk (VaR), Conditional VaR, and performs Monte Carlo simulation and Walk-Forward Analysis.
█ WHY THIS LIBRARY MATTERS
Pine Script is a simple yet effective coding language for algorithmic and quantitative trading. Its accessibility enables traders to quickly prototype and test ideas directly within TradingView. However, the built-in strategy tester provides only basic metrics (net profit, win rate, drawdown), which is often insufficient for serious strategy evaluation.
Due to this limitation, many traders migrate to alternative backtesting platforms that offer comprehensive analytics. These platforms require other language programming knowledge, environment setup, and significant time investment—often just to test a simple trading idea.
Deeptest bridges this gap by bringing institutional-level quantitative analytics directly to Pine Script. Traders can now perform sophisticated analysis without leaving TradingView or learning complex external platforms. All calculations are derived from strategy.closedtrades.* , ensuring compatibility with any existing Pine Script strategy.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ ORIGINALITY AND USEFULNESS
This library is original work that adds value to the TradingView community in the following ways:
1. Comprehensive Metric Suite: Implements 112+ statistical calculations in a single library, including advanced metrics not available in TradingView's built-in tester (p-value, Z-score, Skewness, Kurtosis, Risk of Ruin).
2. Monte Carlo Simulation: Implements trade-sequence randomization to stress-test strategy robustness by simulating 1000+ alternative equity curves.
3. Walk-Forward Analysis: Divides historical data into rolling in-sample and out-of-sample windows to detect overfitting by comparing training vs. testing performance.
4. Rolling Window Statistics: Calculates time-varying Sharpe, Sortino, and Expectancy to analyze metric consistency throughout the backtest period.
5. Interactive Table Display: Renders professional-grade tables with color-coded thresholds, tooltips explaining each metric, and period analysis cards for drawdowns/trades.
6. Benchmark Comparison: Automatically fetches S&P 500 data to calculate Alpha, Beta, and R-squared, enabling objective assessment of strategy skill vs. passive investing.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ KEY FEATURES
Performance Metrics
Net Profit, CAGR, Monthly Return, Expectancy
Profit Factor, Payoff Ratio, Sample Size
Compounding Effect Analysis
Risk Metrics
Sharpe Ratio, Sortino Ratio, Calmar Ratio (MAR)
Martin Ratio, Ulcer Index
Max Drawdown, Average Drawdown, Drawdown Duration
Risk of Ruin, R-squared (equity curve linearity)
Statistical Distribution
Value at Risk (VaR 95%), Conditional VaR
Skewness (return asymmetry)
Kurtosis (tail fatness)
Z-Score, p-value (statistical significance testing)
Trade Analysis
Win Rate, Breakeven Rate, Loss Rate
Average Trade Duration, Time in Market
Consecutive Win/Loss Streaks with Expected values
Top/Worst Trades with R-multiple tracking
Advanced Analytics
Monte Carlo Simulation (1000+ iterations)
Walk-Forward Analysis (rolling windows)
Rolling Statistics (time-varying metrics)
Out-of-Sample Testing
Benchmark Comparison
Alpha (excess return vs. benchmark)
Beta (systematic risk correlation)
Buy & Hold comparison
R-squared vs. benchmark
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK START
Basic Usage
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as *
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ METRIC EXPLANATIONS
The Deeptest table displays 23 metrics across the main row, with 23 additional metrics in the complementary row. Each metric includes detailed tooltips accessible by hovering over the value.
Main Row — Performance Metrics (Columns 0-6)
Net Profit — (Final Equity - Initial Capital) / Initial Capital × 100
— >20%: Excellent, >0%: Profitable, <0%: Loss
— Total return percentage over entire backtest period
Payoff Ratio — Average Win / Average Loss
— >1.5: Excellent, >1.0: Good, <1.0: Losses exceed wins
— Average winning trade size relative to average losing trade. Breakeven win rate = 100% / (1 + Payoff)
Sample Size — Count of closed trades
— >=30: Statistically valid, <30: Insufficient data
— Number of completed trades. Includes 95% confidence interval for win rate in tooltip
Profit Factor — Gross Profit / Gross Loss
— >=1.5: Excellent, >1.0: Profitable, <1.0: Losing
— Ratio of total winnings to total losses. Uses absolute values unlike payoff ratio
CAGR — (Final / Initial)^(365.25 / Days) - 1
— >=10%: Excellent, >0%: Positive growth
— Compound Annual Growth Rate - annualized return accounting for compounding
Expectancy — Sum of all returns / Trade count
— >0.20%: Excellent, >0%: Positive edge
— Average return per trade as percentage. Positive expectancy indicates profitable edge
Monthly Return — Net Profit / (Months in test)
— >0%: Profitable month average
— Average monthly return. Geometric monthly also shown in tooltip
Main Row — Trade Statistics (Columns 7-14)
Avg Duration — Average time in position per trade
— Mean holding period from entry to exit. Influenced by timeframe and trading style
Max CW — Longest consecutive winning streak
— Maximum consecutive wins. Expected value = ln(trades) / ln(1/winRate)
Max CL — Longest consecutive losing streak
— Maximum consecutive losses. Important for psychological risk tolerance
Win Rate — Wins / Total Trades
— Higher is better
— Percentage of profitable trades. Breakeven win rate shown in tooltip
BE Rate — Breakeven Trades / Total Trades
— Lower is better
— Percentage of trades that broke even (neither profit nor loss)
Loss Rate — Losses / Total Trades
— Lower is better
— Percentage of unprofitable trades. Together with win rate and BE rate, sums to 100%
Frequency — Trades per month
— Trading activity level. Displays intelligently (e.g., "12/mo", "1.5/wk", "3/day")
Exposure — Time in market / Total time × 100
— Lower = less risk
— Percentage of time the strategy had open positions
Main Row — Risk Metrics (Columns 15-22)
Sharpe Ratio — (Return - Rf) / StdDev × sqrt(Periods)
— >=3: Excellent, >=2: Good, >=1: Fair, <1: Poor
— Measures risk-adjusted return using total volatility. Annualized using sqrt(252) for daily
Sortino Ratio — (Return - Rf) / DownsideDev × sqrt(Periods)
— >=2: Excellent, >=1: Good, <1: Needs improvement
— Similar to Sharpe but only penalizes downside volatility. Can be higher than Sharpe
Max DD — (Peak - Trough) / Peak × 100
— <5%: Excellent, 5-15%: Moderate, 15-30%: High, >30%: Severe
— Largest peak-to-trough decline in equity. Critical for risk tolerance and position sizing
RoR — Risk of Ruin probability
— <1%: Excellent, 1-5%: Acceptable, 5-10%: Elevated, >10%: Dangerous
— Probability of losing entire trading account based on win rate and payoff ratio
R² — R-squared of equity curve vs. time
— >=0.95: Excellent, 0.90-0.95: Good, 0.80-0.90: Moderate, <0.80: Erratic
— Coefficient of determination measuring linearity of equity growth
MAR — CAGR / |Max Drawdown|
— Higher is better, negative = bad
— Calmar Ratio. Reward relative to worst-case loss. Negative if max DD exceeds CAGR
CVaR — Average of returns below VaR threshold
— Lower absolute is better
— Conditional Value at Risk (Expected Shortfall). Average loss in worst 5% of outcomes
p-value — Binomial test probability
— <0.05: Significant, 0.05-0.10: Marginal, >0.10: Likely random
— Probability that observed results are due to chance. Low p-value means statistically significant edge
Complementary Row — Extended Metrics
Compounding — (Compounded Return / Total Return) × 100
— Percentage of total profit attributable to compounding (position sizing)
Avg Win — Sum of wins / Win count
— Average profitable trade return in percentage
Avg Trade — Sum of all returns / Total trades
— Same as Expectancy (Column 5). Displayed here for convenience
Avg Loss — Sum of losses / Loss count
— Average unprofitable trade return in percentage (negative value)
Martin Ratio — CAGR / Ulcer Index
— Similar to Calmar but uses Ulcer Index instead of Max DD
Rolling Expectancy — Mean of rolling window expectancies
— Average expectancy calculated across rolling windows. Shows consistency of edge
Avg W Dur — Avg duration of winning trades
— Average time from entry to exit for winning trades only
Max Eq — Highest equity value reached
— Peak equity achieved during backtest
Min Eq — Lowest equity value reached
— Trough equity point. Important for understanding worst-case absolute loss
Buy & Hold — (Close_last / Close_first - 1) × 100
— >0%: Passive profit
— Return of simply buying and holding the asset from backtest start to end
Alpha — Strategy CAGR - Benchmark CAGR
— >0: Has skill (beats benchmark)
— Excess return above passive benchmark. Positive alpha indicates genuine value-added skill
Beta — Covariance(Strategy, Benchmark) / Variance(Benchmark)
— <1: Less volatile than market, >1: More volatile
— Systematic risk correlation with benchmark
Avg L Dur — Avg duration of losing trades
— Average time from entry to exit for losing trades only
Rolling Sharpe/Sortino — Dynamic based on win rate
— >2: Good consistency
— Rolling metric across sliding windows. Shows Sharpe if win rate >50%, Sortino if <=50%
Curr DD — Current drawdown from peak
— Lower is better
— Present drawdown percentage. Zero means at new equity high
DAR — CAGR adjusted for target DD
— Higher is better
— Drawdown-Adjusted Return. DAR^5 = CAGR if max DD = 5%
Kurtosis — Fourth moment / StdDev^4 - 3
— ~0: Normal, >0: Fat tails, <0: Thin tails
— Measures "tailedness" of return distribution (excess kurtosis)
Skewness — Third moment / StdDev^3
— >0: Positive skew (big wins), <0: Negative skew (big losses)
— Return distribution asymmetry
VaR — 5th percentile of returns
— Lower absolute is better
— Value at Risk at 95% confidence. Maximum expected loss in worst 5% of outcomes
Ulcer — sqrt(mean(drawdown^2))
— Lower is better
— Ulcer Index - root mean square of drawdowns. Penalizes both depth AND duration
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ MONTE CARLO SIMULATION
Purpose
Monte Carlo simulation tests strategy robustness by randomizing the order of trades while keeping trade returns unchanged. This simulates alternative equity curves to assess outcome variability.
Method
Extract all historical trade returns
Randomly shuffle the sequence (1000+ iterations)
Calculate cumulative equity for each shuffle
Build distribution of final outcomes
Output
The stress test table shows:
Median Outcome: 50th percentile result
5th Percentile: Worst 5% of outcomes
95th Percentile: Best 95% of outcomes
Success Rate: Percentage of simulations that were profitable
Interpretation
If 95% of simulations are profitable: Strategy is robust
If median is far from actual result: High variance/unreliability
If 5th percentile shows large loss: High tail risk
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ WALK-FORWARD ANALYSIS
Purpose
Walk-Forward Analysis (WFA) is the gold standard for detecting strategy overfitting. It simulates real-world trading by dividing historical data into rolling "training" (in-sample) and "validation" (out-of-sample) periods. A strategy that performs well on unseen data is more likely to succeed in live trading.
Method
The implementation uses a non-overlapping window approach following AmiBroker's gold standard methodology:
Segment Calculation: Total trades divided into N windows (default: 12), IS = ~75%, OOS = ~25%, Step = OOS length
Window Structure: Each window has IS (training) followed by OOS (validation). Each OOS becomes the next window's IS (rolling forward)
Metrics Calculated: CAGR, Sharpe, Sortino, MaxDD, Win Rate, Expectancy, Profit Factor, Payoff
Aggregation: IS metrics averaged across all IS periods, OOS metrics averaged across all OOS periods
Output
IS CAGR: In-sample annualized return
OOS CAGR: Out-of-sample annualized return ( THE key metric )
IS/OOS Sharpe: In/out-of-sample risk-adjusted return
Success Rate: % of OOS windows that were profitable
Interpretation
Robust: IS/OOS CAGR gap <20%, OOS Success Rate >80%
Some Overfitting: CAGR gap 20-50%, Success Rate 50-80%
Severe Overfitting: CAGR gap >50%, Success Rate <50%
Key Principles:
OOS is what matters — Only OOS predicts live performance
Consistency > Magnitude — 10% IS / 9% OOS beats 30% IS / 5% OOS
Window count — More windows = more reliable validation
Non-overlapping OOS — Prevents data leakage
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ TABLE DISPLAY
Main Table — Organized into three sections:
Performance Metrics (Cols 0-6): Net Profit, Payoff, Sample Size, Profit Factor, CAGR, Expectancy, Monthly
Trade Statistics (Cols 7-14): Avg Duration, Max CW, Max CL, Win, BE, Loss, Frequency, Exposure
Risk Metrics (Cols 15-22): Sharpe, Sortino, Max DD, RoR, R², MAR, CVaR, p-value
Color Coding
🟢 Green: Excellent performance
🟠 Orange: Acceptable performance
⚪ Gray: Neutral / Fair
🔴 Red: Poor performance
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ IMPLEMENTATION NOTES
Data Source: All metrics calculated from strategy.closedtrades , ensuring compatibility with any Pine Script strategy
Calculation Timing: All calculations occur on barstate.islastconfirmedhistory to optimize performance
Limitations: Requires at least 1 closed trade for basic metrics, 30+ trades for reliable statistical analysis
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK NOTES
➙ This library has been developed and refined over two years of real-world strategy testing. Every calculation has been validated against industry-standard quantitative finance references.
➙ The entire codebase is thoroughly documented inline. If you are curious about how a metric is calculated or want to understand the implementation details, dive into the source code -- it is written to be read and learned from.
➙ This description focuses on usage and concepts rather than exhaustively listing every exported type and function. The library source code is thoroughly documented inline -- explore it to understand implementation details and internal logic.
➙ All calculations execute on barstate.islastconfirmedhistory to minimize runtime overhead. The library is designed for efficiency without sacrificing accuracy.
➙ Beyond analysis, this library serves as a learning resource. Study the source code to understand quantitative finance concepts, Pine Script advanced techniques, and proper statistical methodology.
➙ Metrics are their own not binary good/bad indicators. A high Sharpe ratio with low sample size is misleading. A deep drawdown during a market crash may be acceptable. Study each function and metric individually -- evaluate your strategy contextually, not by threshold alone.
➙ All strategies face alpha decay over time. Instead of over-optimizing a single strategy on one timeframe and market, build a diversified portfolio across multiple markets and timeframes. Deeptest helps you validate each component so you can combine robust strategies into a trading portfolio.
➙ Screenshots shown in the documentation are solely for visual representation to demonstrate how the tables and metrics will be displayed. Please do not compare your strategy's performance with the metrics shown in these screenshots -- they are illustrative examples only, not performance targets or benchmarks.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ HOW-TO
Using Deeptest is intentionally straightforward. Just import the library and call DT.runDeeptest() at the end of your strategy code in main scope. .
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as DT
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
And yes... it's compatible with any TradingView Strategy! 🪄
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ CREDITS
Author: @Fractalyst
Font Library: by @fikira - @kaigouthro - @Duyck
Community: Inspired by the @PineCoders community initiative, encouraging developers to contribute open-source libraries and continuously enhance the Pine Script ecosystem for all traders.
if you find Deeptest valuable in your trading journey, feel free to use it in your strategies and give a shoutout to @Fractalyst -- Your recognition directly supports ongoing development and open-source contributions to Pine Script.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ DISCLAIMER
This library is provided for educational and research purposes. Past performance does not guarantee future results. Always test thoroughly and use proper risk management. The author is not responsible for any trading losses incurred through the use of this code. ספרייה

Fractal Fade Pro IndicatorA revolutionary contrarian trading indicator that applies chaos theory, fractal mathematics, and market entropy to generate high-probability reverse signals. This indicator fades traditional technical signals, providing BUY signals when conventional indicators say SELL, and SELL signals when they say BUY.
Full Description:
Most traders follow the herd. QFCI does the opposite. It identifies when conventional technical analysis is about to fail by detecting mathematical patterns of exhaustion in market structure.
How It Works (Technical Overview):
The indicator combines three sophisticated mathematical approaches:
Fractal Dimension Analysis: Measures the "roughness" of price movements using fractal mathematics
Market Entropy Calculation: Quantifies the randomness and disorder in price returns using information theory
Phase Space Reconstruction: Analyzes price evolution in multi-dimensional state space from chaos theory
Signal Generation Process:
Step 1: Market Regime Detection
Chaotic Regime: High fractal complexity + rising entropy (avoid trading)
Trending Regime: Low fractal complexity + high phase space distance (fade breakouts)
Mean-Reverting Regime: Very low fractal complexity (fade extremes)
Step 2: Reverse Signal Logic
When traditional indicators would give:
BUY signal (breakout, oversold bounce, volatility spike) → QFCI shows SELL
SELL signal (breakdown, overbought rejection, volatility crash) → QFCI shows BUY
Step 3: Smart Signal Filtering
No consecutive same-direction signals
Adjustable minimum bars between signals
Multiple confirmation layers required
Unique Features:
1. Mathematical Innovation:
Original fractal dimension algorithm (not standard indicators)
Market entropy calculation from information theory
Phase space reconstruction from chaos theory
Multi-regime adaptive logic
2. Trading Psychology Advantage:
Contrarian by design - profits from market overreactions
Fades retail trader mistakes - enters when others are exiting
Reduces overtrading - strict signal frequency controls
3. Clean Visual Interface:
Only BUY/SELL labels - no chart clutter
Clear directional arrows - immediate signal recognition
Built-in alerts - never miss a trade
Recommended Settings:
Default (Balanced Approach):
Fractal Depth: 20
Entropy Period: 200
Min Bars Between Signals: 100
Aggressive Trading:
Fractal Depth: 10-15
Entropy Period: 100-150
Min Bars Between Signals: 50-75
Conservative Trading:
Fractal Depth: 30-40
Entropy Period: 300-400
Min Bars Between Signals: 150-200
Optimal Timeframes:
Primary: Daily, Weekly (best performance)
Secondary: 4-Hour, 12-Hour
Can work on: 1-Hour (with adjusted parameters)
How to Use:
For Beginners:
Apply indicator to chart
Use default settings
Wait for BUY/SELL labels
Enter on next candle open
Use 2:1 risk/reward ratio
Always use stop losses
For Advanced Traders:
Adjust parameters for your trading style
Combine with support/resistance levels
Use volume confirmation
Scale in/out of positions
Track performance by regime
Risk Management Guidelines:
Position Sizing:
Conservative: 1-2% risk per trade
Moderate: 2-3% risk per trade
Aggressive: 3-5% risk per trade (not recommended)
Stop Loss Placement:
BUY signals: Below recent swing low or -2x ATR
SELL signals: Above recent swing high or +2x ATR
Take Profit Targets:
Primary: 2x risk (minimum)
Secondary: Previous support/resistance
Tertiary: Trailing stops after 1.5x risk
IMPORTANT RISK DISCLOSURE
This indicator is for educational and informational purposes only. It is not financial advice. Past performance does not guarantee future results. Trading involves substantial risk of loss and is not suitable for every investor. The risk of loss in trading can be substantial. You should therefore carefully consider whether such trading is suitable for you in light of your financial condition. אינדיקטור

India Vix based Strangle StrikesA clean Nifty–VIX dashboard that converts India VIX into expected daily moves, price ranges, and suggested strangle strikes. Includes VIX %, expanded 1.2× range, and smart rounded strike levels for options trading.
This script provides a professional on-chart dashboard that converts India VIX into actionable trading levels for Nifty. It calculates the VIX-based expected daily move, projected price ranges, expanded 1.2× ranges, and suggested strangle strike prices. Includes clean formatting, color-coded sections, and real-time updates.
Ideal for traders using straddles, strangles, intraday volatility models, range-bound setups, and options-based risk management.
1.2x expanded range is better success probability, may keep 20% of strangle value as stop loss.
The vix based system is intended to give approx. 70%+ success rate. אינדיקטור

Historical Matrix Analyzer [PhenLabs]📊Historical Matrix Analyzer
Version: PineScriptv6
📌Description
The Historical Matrix Analyzer is an advanced probabilistic trading tool that transforms technical analysis into a data-driven decision support system. By creating a comprehensive 56-cell matrix that tracks every combination of RSI states and multi-indicator conditions, this indicator reveals which market patterns have historically led to profitable outcomes and which have not.
At its core, the indicator continuously monitors seven distinct RSI states (ranging from Extreme Oversold to Extreme Overbought) and eight unique indicator combinations (MACD direction, volume levels, and price momentum). For each of these 56 possible market states, the system calculates average forward returns, win rates, and occurrence counts based on your configurable lookback period. The result is a color-coded probability matrix that shows you exactly where you stand in the historical performance landscape.
The standout feature is the Current State Panel, which provides instant clarity on your active market conditions. This panel displays signal strength classifications (from Strong Bullish to Strong Bearish), the average return percentage for similar past occurrences, an estimated win rate using Bayesian smoothing to prevent small-sample distortions, and a confidence level indicator that warns you when insufficient data exists for reliable conclusions.
🚀Points of Innovation
Multi-dimensional state classification combining 7 RSI levels with 8 indicator combinations for 56 unique trackable market conditions
Bayesian win rate estimation with adjustable smoothing strength to provide stable probability estimates even with limited historical samples
Real-time active cell highlighting with “NOW” marker that visually connects current market conditions to their historical performance data
Configurable color intensity sensitivity allowing traders to adjust heat-map responsiveness from conservative to aggressive visual feedback
Dual-panel display system separating the comprehensive statistics matrix from an easy-to-read current state summary panel
Intelligent confidence scoring that automatically warns traders when occurrence counts fall below reliable thresholds
🔧Core Components
RSI State Classification: Segments RSI readings into 7 distinct zones (Extreme Oversold <20, Oversold 20-30, Weak 30-40, Neutral 40-60, Strong 60-70, Overbought 70-80, Extreme Overbought >80) to capture momentum extremes and transitions
Multi-Indicator Condition Tracking: Simultaneously monitors MACD crossover status (bullish/bearish), volume relative to moving average (high/low), and price direction (rising/falling) creating 8 binary-encoded combinations
Historical Data Storage Arrays: Maintains rolling lookback windows storing RSI states, indicator states, prices, and bar indices for precise forward-return calculations
Forward Performance Calculator: Measures price changes over configurable forward bar periods (1-20 bars) from each historical state, accumulating total returns and win counts per matrix cell
Bayesian Smoothing Engine: Applies statistical prior assumptions (default 50% win rate) weighted by user-defined strength parameter to stabilize estimated win rates when sample sizes are small
Dynamic Color Mapping System: Converts average returns into color-coded heat map with intensity adjusted by sensitivity parameter and transparency modified by confidence levels
🔥Key Features
56-Cell Probability Matrix: Comprehensive grid displaying every possible combination of RSI state and indicator condition, with each cell showing average return percentage, estimated win rate, and occurrence count for complete statistical visibility
Current State Info Panel: Dedicated display showing your exact position in the matrix with signal strength emoji indicators, numerical statistics, and color-coded confidence warnings for immediate situational awareness
Customizable Lookback Period: Adjustable historical window from 50 to 500 bars allowing traders to focus on recent market behavior or capture longer-term pattern stability across different market cycles
Configurable Forward Performance Window: Select target holding periods from 1 to 20 bars ahead to align probability calculations with your trading timeframe, whether day trading or swing trading
Visual Heat Mapping: Color-coded cells transition from red (bearish historical performance) through gray (neutral) to green (bullish performance) with intensity reflecting statistical significance and occurrence frequency
Intelligent Data Filtering: Minimum occurrence threshold (1-10) removes unreliable patterns with insufficient historical samples, displaying gray warning colors for low-confidence cells
Flexible Layout Options: Independent positioning of statistics matrix and info panel to any screen corner, accommodating different chart layouts and personal preferences
Tooltip Details: Hover over any matrix cell to see full RSI label, complete indicator status description, precise average return, estimated win rate, and total occurrence count
🎨Visualization
Statistics Matrix Table: A 9-column by 8-row grid with RSI states labeling vertical axis and indicator combinations on horizontal axis, using compact abbreviations (XOverS, OverB, MACD↑, Vol↓, P↑) for space efficiency
Active Cell Indicator: The current market state cell displays “⦿ NOW ⦿” in yellow text with enhanced color saturation to immediately draw attention to relevant historical performance
Signal Strength Visualization: Info panel uses emoji indicators (🔥 Strong Bullish, ✅ Bullish, ↗️ Weak Bullish, ➖ Neutral, ↘️ Weak Bearish, ⛔ Bearish, ❄️ Strong Bearish, ⚠️ Insufficient Data) for rapid interpretation
Histogram Plot: Below the price chart, a green/red histogram displays the current cell’s average return percentage, providing a time-series view of how historical performance changes as market conditions evolve
Color Intensity Scaling: Cell background transparency and saturation dynamically adjust based on both the magnitude of average returns and the occurrence count, ensuring visual emphasis on reliable patterns
Confidence Level Display: Info panel bottom row shows “High Confidence” (green), “Medium Confidence” (orange), or “Low Confidence” (red) based on occurrence counts relative to minimum threshold multipliers
📖Usage Guidelines
RSI Period
Default: 14
Range: 1 to unlimited
Description: Controls the lookback period for RSI momentum calculation. Standard 14-period provides widely-recognized overbought/oversold levels. Decrease for faster, more sensitive RSI reactions suitable for scalping. Increase (21, 28) for smoother, longer-term momentum assessment in swing trading. Changes affect how quickly the indicator moves between the 7 RSI state classifications.
MACD Fast Length
Default: 12
Range: 1 to unlimited
Description: Sets the faster exponential moving average for MACD calculation. Standard 12-period setting works well for daily charts and captures short-term momentum shifts. Decreasing creates more responsive MACD crossovers but increases false signals. Increasing smooths out noise but delays signal generation, affecting the bullish/bearish indicator state classification.
MACD Slow Length
Default: 26
Range: 1 to unlimited
Description: Defines the slower exponential moving average for MACD calculation. Traditional 26-period setting balances trend identification with responsiveness. Must be greater than Fast Length. Wider spread between fast and slow increases MACD sensitivity to trend changes, impacting the frequency of indicator state transitions in the matrix.
MACD Signal Length
Default: 9
Range: 1 to unlimited
Description: Smoothing period for the MACD signal line that triggers bullish/bearish state changes. Standard 9-period provides reliable crossover signals. Shorter values create more frequent state changes and earlier signals but with more whipsaws. Longer values produce more confirmed, stable signals but with increased lag in detecting momentum shifts.
Volume MA Period
Default: 20
Range: 1 to unlimited
Description: Lookback period for volume moving average used to classify volume as “high” or “low” in indicator state combinations. 20-period default captures typical monthly trading patterns. Shorter periods (10-15) make volume classification more reactive to recent spikes. Longer periods (30-50) require more sustained volume changes to trigger state classification shifts.
Statistics Lookback Period
Default: 200
Range: 50 to 500
Description: Number of historical bars used to calculate matrix statistics. 200 bars provides substantial data for reliable patterns while remaining responsive to regime changes. Lower values (50-100) emphasize recent market behavior and adapt quickly but may produce volatile statistics. Higher values (300-500) capture long-term patterns with stable statistics but slower adaptation to changing market dynamics.
Forward Performance Bars
Default: 5
Range: 1 to 20
Description: Number of bars ahead used to calculate forward returns from each historical state occurrence. 5-bar default suits intraday to short-term swing trading (5 hours on hourly charts, 1 week on daily charts). Lower values (1-3) target short-term momentum trades. Higher values (10-20) align with position trading and longer-term pattern exploitation.
Color Intensity Sensitivity
Default: 2.0
Range: 0.5 to 5.0, step 0.5
Description: Amplifies or dampens the color intensity response to average return magnitudes in the matrix heat map. 2.0 default provides balanced visual emphasis. Lower values (0.5-1.0) create subtle coloring requiring larger returns for full saturation, useful for volatile instruments. Higher values (3.0-5.0) produce vivid colors from smaller returns, highlighting subtle edges in range-bound markets.
Minimum Occurrences for Coloring
Default: 3
Range: 1 to 10
Description: Required minimum sample size before applying color-coded performance to matrix cells. Cells with fewer occurrences display gray “insufficient data” warning. 3-occurrence default filters out rare patterns. Lower threshold (1-2) shows more data but includes unreliable single-event statistics. Higher thresholds (5-10) ensure only well-established patterns receive visual emphasis.
Table Position
Default: top_right
Options: top_left, top_right, bottom_left, bottom_right
Description: Screen location for the 56-cell statistics matrix table. Position to avoid overlapping critical price action or other indicators on your chart. Consider chart orientation and candlestick density when selecting optimal placement.
Show Current State Panel
Default: true
Options: true, false
Description: Toggle visibility of the dedicated current state information panel. When enabled, displays signal strength, RSI value, indicator status, average return, estimated win rate, and confidence level for active market conditions. Disable to declutter charts when only the matrix table is needed.
Info Panel Position
Default: bottom_left
Options: top_left, top_right, bottom_left, bottom_right
Description: Screen location for the current state information panel (when enabled). Position independently from statistics matrix to optimize chart real estate. Typically placed opposite the matrix table for balanced visual layout.
Win Rate Smoothing Strength
Default: 5
Range: 1 to 20
Description: Controls Bayesian prior weighting for estimated win rate calculations. Acts as virtual sample size assuming 50% win rate baseline. Default 5 provides moderate smoothing preventing extreme win rate estimates from small samples. Lower values (1-3) reduce smoothing effect, allowing win rates to reflect raw data more directly. Higher values (10-20) increase conservatism, pulling win rate estimates toward 50% until substantial evidence accumulates.
✅Best Use Cases
Pattern-based discretionary trading where you want historical confirmation before entering setups that “look good” based on current technical alignment
Swing trading with holding periods matching your forward performance bar setting, using high-confidence bullish cells as entry filters
Risk assessment and position sizing, allocating larger size to trades originating from cells with strong positive average returns and high estimated win rates
Market regime identification by observing which RSI states and indicator combinations are currently producing the most reliable historical patterns
Backtesting validation by comparing your manual strategy signals against the historical performance of the corresponding matrix cells
Educational tool for developing intuition about which technical condition combinations have actually worked versus those that feel right but lack historical evidence
⚠️Limitations
Historical patterns do not guarantee future performance, especially during unprecedented market events or regime changes not represented in the lookback period
Small sample sizes (low occurrence counts) produce unreliable statistics despite Bayesian smoothing, requiring caution when acting on low-confidence cells
Matrix statistics lag behind rapidly changing market conditions, as the lookback period must accumulate new state occurrences before updating performance data
Forward return calculations use fixed bar periods that may not align with actual trade exit timing, support/resistance levels, or volatility-adjusted profit targets
💡What Makes This Unique
Multi-Dimensional State Space: Unlike single-indicator tools, simultaneously tracks 56 distinct market condition combinations providing granular pattern resolution unavailable in traditional technical analysis
Bayesian Statistical Rigor: Implements proper probabilistic smoothing to prevent overconfidence from limited data, a critical feature missing from most pattern recognition tools
Real-Time Contextual Feedback: The “NOW” marker and dedicated info panel instantly connect current market conditions to their historical performance profile, eliminating guesswork
Transparent Occurrence Counts: Displays sample sizes directly in each cell, allowing traders to judge statistical reliability themselves rather than hiding data quality issues
Fully Customizable Analysis Window: Complete control over lookback depth and forward return horizons lets traders align the tool precisely with their trading timeframe and strategy requirements
🔬How It Works
1. State Classification and Encoding
Each bar’s RSI value is evaluated and assigned to one of 7 discrete states based on threshold levels (0: <20, 1: 20-30, 2: 30-40, 3: 40-60, 4: 60-70, 5: 70-80, 6: >80)
Simultaneously, three binary conditions are evaluated: MACD line position relative to signal line, current volume relative to its moving average, and current close relative to previous close
These three binary conditions are combined into a single indicator state integer (0-7) using binary encoding, creating 8 possible indicator combinations
The RSI state and indicator state are stored together, defining one of 56 possible market condition cells in the matrix
2. Historical Data Accumulation
As each bar completes, the current state classification, closing price, and bar index are stored in rolling arrays maintained at the size specified by the lookback period
When the arrays reach capacity, the oldest data point is removed and the newest added, creating a sliding historical window
This continuous process builds a comprehensive database of past market conditions and their subsequent price movements
3. Forward Return Calculation and Statistics Update
On each bar, the indicator looks back through the stored historical data to find bars where sufficient forward bars exist to measure outcomes
For each historical occurrence, the price change from that bar to the bar N periods ahead (where N is the forward performance bars setting) is calculated as a percentage return
This percentage return is added to the cumulative return total for the specific matrix cell corresponding to that historical bar’s state classification
Occurrence counts are incremented, and wins are tallied for positive returns, building comprehensive statistics for each of the 56 cells
The Bayesian smoothing formula combines these raw statistics with prior assumptions (neutral 50% win rate) weighted by the smoothing strength parameter to produce estimated win rates that remain stable even with small samples
💡Note:
The Historical Matrix Analyzer is designed as a decision support tool, not a standalone trading system. Best results come from using it to validate discretionary trade ideas or filter systematic strategy signals. Always combine matrix insights with proper risk management, position sizing rules, and awareness of broader market context. The estimated win rate feature uses Bayesian statistics specifically to prevent false confidence from limited data, but no amount of smoothing can create reliable predictions from fundamentally insufficient sample sizes. Focus on high-confidence cells (green-colored confidence indicators) with occurrence counts well above your minimum threshold for the most actionable insights. אינדיקטור

Expected Value Monte CarloI created this indicator after noticing that there was no Expected Value indicator here on TradingView.
The EVMC provides statistical Expected Value to what might happen in the future regarding the asset you are analyzing.
It uses 2 quantitative methods:
Historical Backtest to ground your analysis in long-term, factual data.
Monte Carlo Simulation to project a cone of probable future outcomes based on recent market behavior.
This gives you a data-driven edge to quantify risk, and make more informed trading decisions.
The indicator includes:
Dual analysis: Combines historical probability with forward-looking simulation.
Quantified projections: Provides the Expected Value ($ and %), Win Rate, and Sharpe Ratio for both methods.
Asset-aware: Automatically adjusts its calculations for Stocks (252 trading days) and Crypto (365 days) for mathematical accuracy.
The projection cone shows the mean expected path and the +/- 1 standard deviation range of outcomes.
No repainting
Calculation:
1. Historical Expected Value:
This is a systematic backtest over thousands of bars. It calculates the return Rᵢ for N past trades (buy-and-hold). The Historical EV is the simple average of these returns, giving a baseline performance measure.
Historical EV % = (Σ Rᵢ) / N
2. Monte Carlo Projection:
This projection uses the Geometric Brownian Motion (GBM) model to simulate thousands of future price paths based on the market's recent behavior.
It first measures the drift (μ), or recent trend, and volatility (σ), or recent risk, from the Projection Lookback period. It then projects a final return for each simulation using the core GBM formula:
Projected Return = exp( (μ - σ²/2)T + σ√T * Z ) - 1
(Where T is the time horizon and Z is a random variable for the simulation.)
The purple line on the chart is the average of all simulated outcomes (the Monte Carlo EV). The cone represents one standard deviation of those outcomes.
The dashed lines represent one standard deviation (+/- 1σ) from the average, forming a cone of probable outcomes. Roughly 68% of the simulated paths ended within this cone.
This projection answers the question: "If the recent trend and volatility continue, where is the price most likely to go?"
Here's how to read the indicator
Expected Value ($/%): Is my average trade profitable?
Win Rate: How often can I expect to be right?
Sharpe Ratio: Am I being adequately compensated for the risk I'm taking?
User Guide
Max trade duration (bars): This is your analysis timeframe. Are you interested in the probable outcome over the next month (21 bars), quarter (63 bars), or year (252 bars)?
Position size ($): Set this to your typical trade size to see the Expected Value in real dollar terms.
Projection lookback (bars): This is the most important input for the Monte Carlo model. A short lookback (e.g., 50) makes the projection highly sensitive to recent momentum. Use this to identify potential recency bias. A long lookback (e.g., 252) provides a more stable, long-term projection of trend and volatility.
Historical Lookback (bars): For the historical backtest, more data is always better. Use the maximum that your TradingView plan allows for the most statistically significant results.
Use TP/SL for Historical EV: Check this box to see how the historical performance would have changed if you had used a simple Take Profit and Stop Loss, rather than just holding for the full duration.
I hope you find this indicator useful and please let me know if you have any suggestions. 😊 אינדיקטור
