Verdict Calibrator Edge vs Base RateOverview
A meta-tool that answers one honest question about any signal: does it actually beat chance?
Point it at another indicator's output (via the source input) or use a built-in reference signal, and it forward-tests every long/short call with a triple-barrier outcome, compares the hit rate to the unconditional base rate of the same move, and only calls an edge "proven" when a confidence-interval lower bound clears that base rate. It splits the result by side (long vs short) and by regime (trend vs range).
It grades a signal; it does not make one.
Why this exists
Most "win rate" readouts are misleading. 60% right means nothing until you know how often the same move happened anyway — if price rose 60% of the time regardless, your signal has an edge of exactly zero. And a 60% on 12 samples is noise, not evidence.
This tool is built so it can only ever say "no proven edge" when there isn't one. The base-rate comparison and the significance gate make false confidence structurally hard to produce.
Why these parts are ONE tool
Signal as a parameter. Connect any plot on your chart through the source input, or pick a built-in reference. The signal is an input, not baked in — so you can audit your indicators, not just this one. The ten built-ins span the families traders actually use:
FamilyBuilt-insTrend-followMA cross · MACD cross · Supertrend flipMomentumRSI 50-cross · Stochastic crossBreakoutDonchian breakout · VWAP crossMean-reversionRSI 30/70 reversal · Bollinger fadeControlRandom (coin flip)
The random control — the tool's own self-test. A deterministic coin flip that by construction has no edge. Grade it and the verdict should read "Not proven" with an Edge near zero. If a random signal ever comes back "PROVEN", the harness is broken — distrust the tool, not the market. No other calibrator on PulseWire ships with a falsification test built in. It is also the single fastest way for a sceptical user to satisfy themselves that this thing is honest.
Triple-barrier outcome. From each signal: did price reach +target, −target, or neither within the horizon? A well-defined outcome, not a vague "did it go up eventually".
Base-rate comparison. The honest yardstick — the unconditional rate of the same outcome, matched to the signal's own side and regime mix. Edge = Hit% − Base%, never raw Hit%.
Significance gate. A score-interval lower bound must clear the base rate before an edge is called proven — which matters most at small samples, exactly where point estimates lie.
Regime and side split. Edge is reported for long vs short and trend vs range separately, because a real edge usually lives in one and not the other.
Remove any one and the tool can be fooled into reporting confidence it hasn't earned.
How to use it
Pick the signal (external source or a built-in), set the outcome (horizon + target in ATR), and read the verdict: PROVEN +X% ★ / Not proven / Gathering data.
The two plotted lines are the running Hit % (of the signal) and Base % (unconditional) — the gap between them IS the edge, and you can watch it stabilise as samples accumulate. Switch the dashboard to Pro to see where the edge lives (long/short, trend/range).
If it says "no proven edge", believe it. That's the tool working, not failing.
Data & scope
Works on any symbol and timeframe — it needs only OHLC, no volume. Give it enough history to reach the minimum sample count, or the verdict will honestly read "Gathering data". Because the base rate is measured on the same chart, the yardstick always matches the instrument you're on.
Non-repainting & honest limits
Confirmed-bar reads; samples log at the signal bar and resolve on closed bars.
This is an in-sample, forward-from-signal study aid — NOT a walk-forward backtest. No costs or slippage. Overlapping forward windows correlate samples (the minimum-gap setting mitigates this; it does not eliminate it). Small-n edges are provisional even when starred. A proven in-sample edge is not a guarantee out-of-sample. Nothing here predicts price.
Concept credits
Built on standard, published techniques — triple-barrier forward labelling (M. López de Prado), base-rate / skill-vs-chance evaluation (a long tradition in forecast verification), the efficiency-ratio regime read (Perry Kaufman), and the Wilson score interval for a proportion (Edwin B. Wilson). The signal-agnostic intake, the coupling and the plain-language verdict are this script's own. No third-party Pine code is reused.
Disclaimer
Research and educational tool only. Not financial advice, no recommendation, no guarantee of results. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability. Indicator

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 PulseWire 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 Library

Triple Barrier Exit with Meta LabelingOverview
Most tools tell you when to enter. This one frames how a trade would be managed — and then keeps an honest record of how that framing actually resolved. It takes a primary entry signal (its own built-in breakout, or any external signal series you point it at), draws a volatility-scaled profit barrier, stop barrier and time barrier around it, watches which is touched first, and feeds every resolved outcome into a live track record. On top sits a meta-label gate: a small online model that learns, from those resolved outcomes, whether to take or skip the next signal.
It is a research and trade-framing study — not a strategy, not a signal service, and not a validated edge.
Why these parts are ONE tool (mashup rationale)
Each layer exists because the one before it leaves a question open:
The triple barrier. A raw entry signal has no definition of success. Profit / stop / time barriers, scaled by current volatility (ATR or an EWMA of returns), turn a signal into a labelled outcome: profit-hit, stop-hit, or timed-out. Widths are regime-asymmetric — the profit barrier widens in trend and tightens in chop — because a fixed frame misprices the same signal in different conditions.
The trend-scanning vertical. A fixed holding time is arbitrary. The time barrier is instead chosen from candidate horizons by the strongest |t-value| of a linear fit — the horizon over which price is actually trending most decisively.
The meta-label gate. Knowing outcomes isn't the same as acting on them. A small online logistic model, trained only on resolved outcomes, scores each new signal and says TAKE or SKIP. It stays disabled until enough trades have resolved, so it never acts on an untrained model.
The honesty layer. Overlapping trades are not independent samples — so wins are recency-decayed and reported with a Wilson 95% lower bound per regime, alongside a reliability table and a Brier score for the meta-gate itself. If the gate isn't calibrated, the panel says so.
Remove any layer and the tool either mislabels the trade, mistimes it, acts on an untested model, or reports a win-rate it hasn't earned.
How it works
A primary signal fires. If the meta-gate passes, the trade is framed: profit = entry ± (PT × regime multiplier × σ), stop = entry ∓ (SL × regime multiplier × σ), and a vertical barrier holdH bars ahead. The frame is drawn as a forward box that recolours green / red / grey on first touch. Same-bar ties resolve stop-first (the conservative assumption). MFE and MAE are tracked live on the open trade. On resolution, the outcome trains the meta-model and updates the per-regime statistics.
How to use it
Read the panel before you trust the frame.
Meta gate — whether the model would take or skip the current signal (stays "warming" until it has enough resolved samples).
Wilson 95% lower — the honest floor of the win-rate in the current regime. If it isn't above 50%, this framing has not demonstrated an edge here.
Meta Brier — below ~0.25 means the gate's probabilities are reasonably calibrated; above it, ignore the gate.
The most useful thing you can do with it: point it at your own entry signal via the external-source input, and see how your signal resolves under a disciplined exit frame. The suggested size is advisory arithmetic (risk ÷ stop distance), not a recommendation. Only one trade is managed at a time — this is a study of the framing, not a portfolio simulator. The dashboard has a Compact layout (default) and a Pro layout (adds the scanned horizon, Brier, reliability tiers, PT/SL/timeout counts, live MFE/MAE and suggested size).
Universal across markets
Entry source, σ source, barrier widths and horizons are all inputs, so it runs on any symbol and timeframe. It needs no volume. Defaults target intraday index futures.
Non-repainting
Entries are taken and outcomes resolved only on confirmed bars, and the meta-model is trained only on resolved outcomes — so no statistic reads its own future and nothing inflates intrabar. The live "next-trade frame" preview is a forward projection at the current bar only, by design.
Originality
The triple barrier, meta-labelling and trend-scanning are published research concepts, credited below. What's assembled here is the specific synthesis: the triple barrier used as a live exit/management frame rather than an offline training pipeline, regime-asymmetric barrier widths, an online meta-gate that trains itself on the chart in front of you, and an honesty panel that reports the Wilson lower bound, the reliability tiers and the gate's own Brier score. Clean-room implementation; no third-party code reused.
Concept credits
Triple-barrier labelling, meta-labelling, trend-scanning, and sample uniqueness / time-decay for non-IID overlapping outcomes — Marcos López de Prado (Advances in Financial Machine Learning). Here the triple barrier is used as an exit/management frame and a labelling substrate, not as a training pipeline.
Wilson score confidence interval — Edwin B. Wilson · Brier score — Glenn W. Brier
Average True Range — J. Welles Wilder · Efficiency Ratio — Perry Kaufman
Inverse-volatility position sizing — standard risk-management practice
Honest limits
Overlapping trades are not independent, which is exactly why wins are decayed and reported with a Wilson lower bound rather than a raw percentage — treat the win-rate as descriptive, not a probability of future results. The meta-model is a small online logistic fit on three features; it can be miscalibrated, which is why its Brier score is shown. All figures are in-sample, with no costs, slippage or spread. Nothing here predicts price.
Disclaimer
Research and educational tool only. Not financial advice, not a recommendation, and no guarantee of results. The position-size output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use. Indicator

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

Cost Basis Map [FEELS]Who is in profit at this level, and who is trapped? Cost Basis Map estimates the answer for any symbol and any timeframe from nothing but price and volume. On-chain analytics answers the same question for Bitcoin with realized price and supply in profit, but those metrics need blockchain data, so they stop at BTC. This script rebuilds that framework from OHLCV for everything else.
The headline number is the share of open positions that is underwater right now. Everything else on the chart is built from the same ledger.
HOW THE LEDGER WORKS
The script maintains a ledger of open positions. Every bar adds its traded volume to the ledger at that bar's price, and the same volume closes a proportional share of the older positions. Old entries rotate out at a pace set by turnover rather than time: a few high-volume bars can replace a big part of the book, a quiet stretch barely touches it. The result is a bar-by-bar estimate of which positions are still open and what they paid. From it the script derives:
- Break-even line: the volume-weighted average entry of all open positions. This is the market's collective cost basis, the same construction on-chain research calls realized price.
- Underwater share: the % of open positions whose entry sits above the current price. It drives the headline, the fill color and the sentiment states (euphoria, healthy uptrend, mixed, majority trapped, extreme pain).
- Open-positions profile: the right-side histogram shows where the open positions were entered. Red rows above price are trapped positions waiting overhead, which tends to act as resistance and as squeeze fuel once price runs through it. Teal rows below are holders in profit, where support usually forms. The widest row is tagged as the heaviest entries.
- Capitulation marker: printed when an unusually large amount of volume (a z-score test) realizes losses below break-even. On everything I tested these cluster near major bottoms.
- Euphoria marker: printed when nearly every position is in profit and turnover is elevated, a condition typical of late trend.
- Recent entries line: the average entry of the newest cohort, the positions most likely to panic or chase first.
Positions are money-weighted by default (volume × price), with an option to weight by raw volume units instead.
HOW TO TRADE IT
1. Regime first. Price holding above a rising break-even line with a low underwater share is a healthy trend, and pullbacks into the line are buyable by ordinary trend rules. When price loses the break-even line the regime flips: the average holder is now at a loss, and rallies back into the line run into their exit orders.
2. Read the profile as a map of who needs what. Heavy red rows above price mark where trapped holders wait to break even, so expect supply there. Heavy teal rows below mark profitable entries that tend to get defended.
3. Extremes are mean-reversion territory. A capitulation marker on top of an extreme underwater share has marked the areas where selling exhausts. A euphoria marker with a single-digit underwater share is the same warning on the upside.
HONESTY
This is an estimation model built from price and volume. Real per-account position data does not exist anywhere on any platform; on-chain analytics estimates it too, just from a different source. The model's assumptions are simple and disclosed: entries at the bar's typical price, proportional volume-driven rotation of old positions. A fixed marker cooldown keeps signal episodes readable. Markers print on bar close and do not repaint. The tool is most informative on volatile assets and intraday-to-daily timeframes; on slow index weeklies the market spends years in profit and the picture is honestly boring. Volume quality matters: prefer a real exchange feed (e.g. Bitstamp, Coinbase, a specific futures contract) over composite indices, because aggregated feeds smooth out the volume spikes the engine reads. On symbols with no volume data the script falls back to equal weighting.
ALERTS
Cost basis reclaimed · Cost basis lost · Majority underwater (60%+) · Nearly all in profit · Capitulation volume · Euphoria turnover.
SETTINGS
Every input has a tooltip. The main ones: "Position memory" sets how long the ledger remembers (volume-weighted), "Ledger resolution" sets the price granularity, profile size/spacing and all colors are adjustable, "Text size" scales the captions for presentations.
ORIGINALITY
A volume profile shows where volume traded. This ledger goes one step further and estimates which of those positions are still open and what they paid, i.e. cost-basis analytics of the kind used in on-chain research, reconstructed from OHLCV for any market. The break-even line is not an MA or a VWAP band in disguise: it is computed from the position ledger, not from a lookback window. Engine and rendering are written from scratch. Indicator

Indicator

TE Feature ScreenStop Trading on Lagging Indicators. Start Measuring True Predictive Power.
Are your indicators actually predicting the next move, or are they just taking credit for a trend that’s already happening?
Introducing the Transfer Entropy Feature Screen. Built for quantitative researchers and serious algorithmic traders, this script leverages Information Theory to mathematically separate predictive signals from random market noise.
Instead of relying on standard correlation, this engine uses Conditioned Transfer Entropy (TE). It deliberately strips out the stock's past momentum, forcing every indicator to prove it is bringing new, independent information to the table about where the price will be h bars from now.
Tailored Specifically for the Stock Market
This Equities Edition focuses strictly on institutional footprints and structural market mechanics:
Order Flow & Volume Kinetics: Track Limit Order Absorption (churn), Close Location Value (CLV), and Unusual Volume (RVOL) Z-scores to spot institutional accumulation before the breakout.
Structural Edges: Measure Overnight Gap extent and Standard Deviation Distance from the daily VWAP.
Index Relative Strength: Dynamically compare the stock's acceleration against a benchmark index (like the SPY or QQQ) to find true market leaders.
Built for Rigorous Quant Research
To prevent curve-fitting, the script features a strict Walk-Forward backtesting engine.
Input your exact calendar dates for In-Sample (Training) and Out-of-Sample (Testing) windows.
The engine benchmarks every feature against randomized "null shuffle" data to generate a definitive Z-score, proving whether an indicator's edge is mathematically significant or just a lucky streak.
Seamless Data Export: Bypassing PulseWire's execution limits, the engine processes massive historical windows in the background and delivers a cleanly formatted CSV spreadsheet of the Z-scores directly to your email via alerts—perfect for building your own regime classification models.
Stop guessing which features matter. Let the math tell you what actually moves the market.
Setup Note for Users: To extract the data, set your IS/OOS calendar dates, toggle your desired features, and create a PulseWire alert with "Send Email" checked. The script will automatically crunch the historical data and email you the CSV results upon the next bar close Indicator

Pump-and-Dump / Volatility Spike FlagPump-and-Dump / Volatility Spike Flag flags abnormal single-candle volatility — not the manipulation scheme, but the classic sharp-spike-then-reverse price shape that shows up around news events (frequently seen on MCX crude oil and silver).
HOW IT WORKS
A candle is flagged only when two conditions occur together: its true range (which includes gap-opens) expands well beyond its rolling ATR, AND its volume expands well beyond its rolling average. Flagged spikes are tracked for a short window afterward — if price closes back through that candle's open before the window expires, it is separately flagged as a "Fade," indicating the initial move has started reversing.
HOW TO USE
Use the Spike flag as an early heads-up that a candle is statistically abnormal for current conditions. Use the Fade flag as the more actionable signal — it confirms the spike has already started giving back its move. This is an informational/analytical tool, not a buy or sell signal, and should be combined with your own risk management and market context.
LIMITATIONS
ATR and volume averages are backward-looking, so the first spike after a long quiet period needs a relatively larger move to trigger. This is a single-candle geometry and volume-shape detector — it cannot identify why a move happened (news, order-flow, or otherwise), and it does not predict direction after the fade.
DISCLAIMER
For educational/informational purposes only. Not financial advice. Past performance does not guarantee future results. Trade at your own risk and always use proper risk management. Indicator

Regime Classifier [RC Tools]RC Tools — Regime Classifier
─────────────────────────────────────────────────────────────
█ OVERVIEW
Most indicators assume a single market condition and quietly fail in another. This tool doesn't generate signals — it tells you which of four market regimes you are currently in, so you can judge whether your existing tools are operating in conditions that suit them. It is a context tool, not a decision tool.
█ WHAT IT DOES
Classifies each confirmed bar into one of four states and colours the chart background accordingly:
• Trending — Expansion: directional, volatility rising
• Trending — Exhaustion: directional, volatility compressing
• Ranging — Quiet: no direction, low volatility
• Ranging — Volatile: no direction, high volatility (chop)
A table (top-right by default, repositionable) shows the current regime, how long price has been in it, and historical base rates — the average forward return and win rate seen after each regime, going back over the chart's full history.
█ THE THEORY BEHIND IT
Market behaviour is not stationary. A trend-following tool that performs well in directional expansion will bleed in volatile chop; a mean-reversion tool does the reverse. Rather than attempting to fix any single indicator, this tool identifies which environment you are in, using two independent dimensions — directionality and volatility state — that measure genuinely different properties of price behaviour rather than two correlated views of the same one.
█ HOW IT IS CALCULATED
DIRECTIONALITY — Efficiency Ratio over N bars:
ER = |close − close | ÷ Σ|close − close |
Bounded 0–1. A value near 1 means price travelled almost directly from A to B (trending); near 0 means it wandered (ranging). No fitted parameters beyond the lookback. The Efficiency Ratio was introduced by Perry Kaufman as the core input to his Adaptive Moving Average (KAMA); it is used here purely as a directionality measure, independent of any moving average.
VOLATILITY STATE — realised volatility, percentile-ranked:
RV = stdev(log(close/close ), N)
RV is then ranked as a percentile against its own trailing distribution (default: 750 bars, ≈3 years on daily). An absolute volatility threshold is meaningless across assets — percentile ranking makes the classification behave identically on BTC, gold and equities with no parameter tuning.
The two dimensions are crossed to yield the four states. Classification occurs ONLY on confirmed bar close — the background never updates mid-bar and then flips back.
The base-rate table works by recording, for every historical bar, the forward N-bar return and whether it was positive, attributed back to whichever regime was active N bars earlier. Only fully-elapsed, already-known returns are used — nothing is looked up ahead of the current bar.
█ SETTINGS & CONFIGURATION
• Efficiency Ratio Lookback (default 20) — shorter = more responsive, noisier
• Realised Volatility Lookback (default 20)
• Percentile Ranking Window (default 750 bars ≈ 3 years daily) — longer = more stable, needs more history
• Directionality Threshold (default 0.35) — the ER above which price is considered trending
• Volatility Percentile Threshold (default 50) — the split between low and high volatility states
• Forward Return Window (default 20 bars) — the horizon used for the base-rate table
• Table position and background colours are fully configurable; the main-chart background painting can be toggled off if you only want the diagnostic pane
█ HOW TO USE IT
Use it as a filter on your existing process, not as an entry trigger. Example: if you run a breakout system, check whether it has historically performed in Ranging — Volatile; if not, consider standing aside when the background flags that state. Example: a mean-reversion system will typically show its worst results in Trending — Expansion.
Works on any asset and timeframe with sufficient history for the percentile window. Best used on daily and above, where regime persistence is greatest.
█ LIMITATIONS
This tool classifies the PRESENT. It does not predict the future, and any use of it as a forecast is a misuse.
• Regime identification is backward-looking by construction. The tool will confirm a regime change several bars AFTER it occurred. This lag cannot be removed without curve-fitting or repainting, and has not been.
• Classification is unstable near threshold boundaries; expect flickering between states when ER or volatility percentile sit close to the cut-offs.
• The percentile ranking requires substantial history. On assets with short histories, the ranking is unreliable and the tool should not be trusted.
• The base-rate table's early entries are built on fewer samples than its later ones — treat statistics as provisional until a state has accumulated a meaningful sample count.
• Four states is a deliberate simplification of a continuous reality. Markets do not actually occupy discrete regimes.
• This script does NOT repaint. All classification is computed on confirmed bar close only.
█ DISCLAIMER
For educational and informational purposes only. Nothing here is financial advice. Past behaviour of any market regime does not indicate future results. Trade at your own risk.
Indicator

ICT Pulse - Bias & Stats DashboardICT Pulse — Bias & Session Dashboard
ICT Pulse is a dashboard-style indicator designed to summarize higher-timeframe context, session status, and liquidity conditions for discretionary ICT-style futures trading.
The script does not generate buy or sell signals. Its purpose is to organize market context into a compact dashboard so traders can quickly understand where price is trading relative to previous ranges and whether session liquidity has been taken.
How it works
ICT Pulse compares the current price to the previous daily, weekly, and monthly ranges. For each range, it calculates whether price is trading in premium or discount by measuring the current close relative to the prior high, low, and midpoint.
The dashboard then combines this higher-timeframe information with session conditions. It tracks the active Asia, London, and New York sessions, records each session’s high and low, and monitors whether those levels have later been traded through.
The confluence score is a simple context score, not a signal system. Bullish and bearish scores are built from five conditions:
* Daily range position
* Weekly range position
* Monthly range position
* Whether opposing-side liquidity has been taken
* Whether price is above or below the active session midpoint
For example, the bullish score increases when price is in premium on higher timeframes, when downside liquidity has been taken, and when price is holding above the current session midpoint. The bearish score uses the opposite conditions.
Main features
* Daily, weekly, and monthly bias summary
* Premium/discount status for previous daily, weekly, and monthly ranges
* Active session detection
* Current session range tracking
* Asia, London, and New York high/low sweep status
* Bullish and bearish confluence score
* Dashboard-only layout to reduce chart clutter
How to use it
ICT Pulse is best used as a market-context tool before looking for entries. A trader can use it to check whether higher-timeframe conditions are aligned, whether important session liquidity has already been taken, and whether the current session is supporting bullish, bearish, or neutral conditions.
Suggested workflow:
1. Check daily, weekly, and monthly bias.
2. Check whether price is in premium or discount.
3. Check whether Asia, London, or New York liquidity has been taken.
4. Compare the bullish and bearish confluence scores.
5. Use a separate execution model for entries, stops, and trade management.
This script is intended for educational and analytical use only. It does not provide financial advice, trade recommendations, or guaranteed outcomes. Futures and financial market trading involves risk.
Indicator

Moving Averages TrendFour independently configurable moving averages (type, length, source, color each) let you build the classic multi-MA trend stack in one indicator — a long-term filter to define the overall regime, an intermediate MA for the broader trend, and a fast pair for tactical entries on pullbacks within it. Used purely as an overlay, this is a continuation tool: you only take trades in the direction the slower MAs already agree on, using the faster pair to time entries once price pulls back into alignment.
The MA3/MA4 cross-signal layer is what sets this apart from a plain crossover system. Instead of waiting for the two faster MAs to physically cross — which is already stale information by the time it happens — it takes each MA's recent slope and projects it forward by a configurable number of bars, firing the buy/sell label as soon as that projected path crosses rather than the actual one, giving you a signal a few bars earlier than a textbook crossover. A minimum-separation filter (scaled to ATR) throws out weak "touch and go" near-misses, and the signal only fires when price is already sitting on the correct side of both MAs and each MA is still actively moving in that direction on the current bar — all of which is meant to filter out low-conviction crosses in choppy conditions. An optional daily+-only restriction keeps the signal from firing on intraday noise for traders who only want to act on it at swing timeframes.
Best applied in trending or newly-trending markets, as a combined trend filter (from the 4 plotted MAs) and tactical entry trigger (from the cross signal) rather than as a mean-reversion tool — it has little to offer in a flat, range-bound market since the slope and separation conditions are designed specifically to avoid firing in that environment. Indicator

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

Martingale Range Breakout# Martingale Range Breakout
**Martingale Range Breakout** is a session-based breakout and flip-tracking indicator designed to study range expansion behavior after a defined range.
This script builds a custom time-based range, tracks breakout direction, monitors flip attempts, and displays live trade-state data with rolling performance stats directly on the chart.
---
## Core Concept
The indicator creates a range from a selected session window.
By default, the range is built from:
**8:00 AM – 8:50 AM New York Time**
Once the range locks, the script watches for price to break above or below the range.
* Break above the range = **Long Active**
* Break below the range = **Short Active**
* If price reverses and breaks the opposite side, the script counts that as a **flip**
* If price reaches the full range extension before 4 flips, it marks the setup as a **WIN**
* If the setup reaches 4 flips, it marks the setup as a **LOSS**
---
## Martingale Flip Logic
This indicator is based on a Martingale-style flip model.
The idea is that when a breakout fails and price flips to the opposite side of the range, the next position size is increased to help recover the previous failed attempt.
Example position sequence:
* Flip 1: **1 contract**
* Flip 2: **2 contracts**
* Flip 3: **4 contracts**
* Flip 4: **Loss**
Each flip represents the market failing in one direction and then triggering the opposite side of the range.
The goal of the Martingale model is for the final successful breakout to recover the previous failed flips and still finish the sequence in profit.
The table tracks the current trade state and flip count, allowing traders to see what stage of the Martingale sequence the setup is currently in.
---
## Visual Range Boxes
The script draws two clean visual zones on the chart.
**Yellow Box**
Shows the original session range.
**Green Box**
Shows the full expansion zone based on the range size.
The final target levels are calculated as:
* Buy final target = **Range High + Full Range Distance**
* Sell final target = **Range Low - Full Range Distance**
This makes it easy to see both the breakout levels and the final expansion targets.
---
## Live Trade State Tracking
The table displays the current setup condition in real time.
Possible states include:
* **WAITING**
* **LONG ACTIVE**
* **SHORT ACTIVE**
* **WIN**
* **LOSS**
The table also shows the current flip count, helping traders quickly identify how many times the setup has reversed.
---
## Built-In Rolling Statistics
The indicator tracks the last selected number of completed setups and displays performance data inside the chart table.
Stats include:
* Last N trade count
* Wins and losses
* Rolling win rate
* Rolling R total
* Average winning range size
* Average losing range size
* Current range size
* Win sample count
* Loss sample count
* Average minutes to win
* Average minutes to loss
The rolling sample size can be adjusted in the settings.
---
## Breakeven Win Rate Requirement
This model uses a negative-risk-reward structure, meaning each win is smaller than each full loss.
The R Total calculation is based on:
* Win = **+0.14285R**
* Loss = **-1R**
Because each full loss is much larger than each win, the system needs a very high win rate to be profitable.
The approximate breakeven win rate is:
**87.5%**
That means the strategy must win more than **87.5%** of completed setups to show positive expectancy under this model.
* Below **87.5% win rate** = negative expectancy
* At **87.5% win rate** = around breakeven
* Above **87.5% win rate** = positive expectancy
This is why the rolling win-rate tracker is important. It helps traders quickly see whether the most recent sample is performing above or below the required profitability threshold.
Even though the Martingale flip model can create a high win rate, the full loss is much larger than the average win. Because of that, risk management is extremely important.
---
## R-Multiple Model
The R Total section helps estimate whether the recent rolling sample is profitable based on the script’s fixed reward-to-risk model.
Instead of only showing win rate, the script also calculates the overall R performance across the selected sample.
This helps traders avoid focusing only on a high win rate and instead evaluate whether the system is actually profitable after accounting for the larger full-loss event.
---
## Customizable Settings
You can adjust:
* Session start hour
* Session start minute
* Session end hour
* Session end minute
* Rolling trade sample size
* Show or hide the stats section
* Table position:
* Top Right
* Middle Right
* Bottom Right
---
## Best Use Case
This indicator is best used as a visual research tool for traders studying:
* Morning range breakouts
* Range expansion behavior
* Flip-based entry models
* Martingale-style recovery logic
* High-win-rate breakout systems
* Negative-risk-reward models
* Breakeven win-rate requirements
* Time-to-outcome behavior
* Rolling sample performance
---
## Important Risk Notice
This is an indicator only. It does not place trades automatically and should not be considered financial advice.
Martingale-style systems can increase risk quickly because each failed flip requires a larger position size. While the model may recover losses when the breakout eventually succeeds, the downside can become large when multiple flips fail.
A system like this does not only need to win often — it needs to win enough to overcome the size of its losses. Under this model, that means maintaining a win rate above approximately **87.5%**.
Always test thoroughly, use proper risk management, and understand the full risk before applying any strategy live.
Indicator

Indicator

Strategy

ChatgptLibraryLibrary "ChatgptLibrary"
TODO: add library description here
effective_period(high_series, low_series, volume_series, period_length, lookback_length, max_search)
Calculates adaptive effective period.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive effective period.
adaptive_ema(source, high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive EMA using effective period.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive EMA, alpha and effective period.
adaptive_channel(high_series, low_series, volume_series, period_length, lookback_length, smooth_length, max_search)
Adaptive price channel.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
smooth_length (simple int) : EMA smoothing.
max_search (int) : Maximum search distance.
Returns: Effective period, upper, lower, middle and width.
adaptive_rsi(source, high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive RSI.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive RSI and effective period.
adaptive_atr(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive ATR.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Adaptive ATR and effective period.
adaptive_macd(source, high_series, low_series, volume_series, fast_period, slow_period, signal_period, lookback_length, max_search)
Adaptive MACD.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
fast_period (simple int) : Fast adaptive period.
slow_period (simple int) : Slow adaptive period.
signal_period (int) : Signal EMA period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: MACD, Signal, Histogram.
adaptive_bollinger(source, high_series, low_series, volume_series, period_length, deviation, lookback_length, max_search)
Adaptive Bollinger Bands.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
deviation (float) : Standard deviation multiplier.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Upper band, Middle band, Lower band, Band width and Effective period.
adaptive_supertrend(high_series, low_series, close_series, volume_series, period_length, multiplier, lookback_length, max_search)
Adaptive SuperTrend.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
multiplier (float) : ATR multiplier.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: SuperTrend, Trend Direction and Effective Period.
adaptive_donchian(high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive Donchian Channel.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Upper band, Lower band, Middle line, Width and Effective period.
adaptive_keltner(source, high_series, low_series, close_series, volume_series, period_length, multiplier, lookback_length, max_search)
Adaptive Keltner Channel.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
multiplier (float) : ATR multiplier.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Upper band, Middle band, Lower band, Width and Effective period.
adaptive_adx(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive ADX.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: ADX, +DI, -DI and Effective Period.
adaptive_stochastic(close_series, high_series, low_series, volume_series, period_length, smooth_k, smooth_d, lookback_length, max_search)
Adaptive Stochastic.
Parameters:
close_series (float) : Close price series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
smooth_k (int) : K smoothing.
smooth_d (int) : D smoothing.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: K, D and Effective Period.
adaptive_cci(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive Commodity Channel Index.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: CCI and Effective Period.
adaptive_williams_r(high_series, low_series, close_series, volume_series, period_length, lookback_length, max_search)
Adaptive Williams %R.
Parameters:
high_series (float) : High price series.
low_series (float) : Low price series.
close_series (float) : Close price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: Williams %R and Effective Period.
adaptive_roc(source, high_series, low_series, volume_series, period_length, lookback_length, max_search)
Adaptive Rate of Change.
Parameters:
source (float) : Source series.
high_series (float) : High price series.
low_series (float) : Low price series.
volume_series (float) : Volume series.
period_length (simple int) : Base period.
lookback_length (simple int) : EMA lookback multiplier.
max_search (int) : Maximum search distance.
Returns: ROC and Effective Period.
adaptive_pivot(source, left_bars, right_bars)
Adaptive Pivot Detector.
Parameters:
source (float) : Source series.
left_bars (int) : Left pivot bars.
right_bars (int) : Right pivot bars.
Returns: Pivot High, Pivot Low, Pivot High Price, Pivot Low Price.
adaptive_divergence(price_source, indicator_source, pivot_length)
Adaptive Divergence Detector.
Parameters:
price_source (float) : Price series.
indicator_source (float) : Indicator series.
pivot_length (int) : Pivot length.
Returns: Bullish divergence, Bearish divergence and Divergence strength.
adaptive_pivot_divergence(price_source, signal_source, pivot_length)
Adaptive Pivot Divergence Detector.
Parameters:
price_source (float) : Price series.
signal_source (float) : Indicator series.
pivot_length (int) : Pivot length.
Returns: Bullish divergence, Bearish divergence and Divergence strength.
adaptive_flat_channel(upper_channel, lower_channel, flat_length, tolerance)
Adaptive Flat Channel Detector.
Parameters:
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
flat_length (int) : Number of bars to evaluate.
tolerance (float) : Maximum allowed movement.
Returns: Flat upper, Flat lower and Flat channel.
adaptive_breakout_strength(close_series, upper_channel, lower_channel, channel_width, volume_series, volume_length)
Adaptive Breakout Strength.
Parameters:
close_series (float) : Close price.
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
channel_width (float) : Channel width.
volume_series (float) : Volume.
volume_length (simple int) : Volume EMA length.
Returns: Breakout direction and Breakout strength.
adaptive_channel_rejection(open_series, high_series, low_series, close_series, upper_channel, lower_channel)
Adaptive Channel Rejection.
Parameters:
open_series (float) : Open price.
high_series (float) : High price.
low_series (float) : Low price.
close_series (float) : Close price.
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
Returns: Rejection direction and Rejection strength.
adaptive_channel_compression(channel_width, compression_length)
Adaptive Channel Compression.
Parameters:
channel_width (float) : Width of the channel.
compression_length (simple int) : Number of bars.
Returns: Compression ratio, Is compressing, Is expanding.
adaptive_market_energy(channel_width, volume_series, volume_length)
Adaptive Market Energy.
Parameters:
channel_width (float) : Width of channel.
volume_series (float) : Volume series.
volume_length (simple int) : Volume EMA length.
Returns: Energy score.
adaptive_market_phase(adx, rsi, compression_ratio, breakout_strength)
Adaptive Market Phase.
Parameters:
adx (float) : Adaptive ADX.
rsi (float) : Adaptive RSI.
compression_ratio (float) : Channel compression ratio.
breakout_strength (float) : Breakout strength.
Returns: Market phase.
adaptive_rsi_zigzag(rsi_series, center_level, lookback_length)
Adaptive RSI Zigzag Detector.
Parameters:
rsi_series (float) : RSI series.
center_level (float) : Center level.
lookback_length (int) : Number of bars.
Returns: Zigzag count and Zigzag detected.
adaptive_flat_level(level_series, flat_length, tolerance)
Adaptive Flat Level Detector.
Parameters:
level_series (float) : Channel upper or lower series.
flat_length (int) : Number of bars.
tolerance (float) : Maximum allowed movement.
Returns: Flat state and Flat strength.
adaptive_level_strength(level_series, high_series, low_series, tolerance, lookback_length)
Adaptive Level Strength.
Parameters:
level_series (float) : Support or resistance level.
high_series (float) : High price series.
low_series (float) : Low price series.
tolerance (float) : Touch tolerance.
lookback_length (int) : Number of bars.
Returns: Touch count and Level strength.
adaptive_breakout_probability(breakout_strength, level_strength, compression_ratio, volume_ratio)
Adaptive Breakout Probability.
Parameters:
breakout_strength (float) : Breakout strength.
level_strength (float) : Level strength.
compression_ratio (float) : Channel compression ratio.
volume_ratio (float) : Volume ratio.
Returns: Breakout probability.
adaptive_reversal_probability(rsi, divergence_strength, rejection_strength, flat_strength, channel_width_percent)
Adaptive Reversal Probability.
Parameters:
rsi (float) : Relative Strength Index.
divergence_strength (float) : Divergence strength.
rejection_strength (float) : Rejection strength.
flat_strength (float) : Flat level strength.
channel_width_percent (float) : Channel width percentage.
Returns: Reversal probability.
adaptive_trend_exhaustion(rsi, adx, momentum, roc)
Adaptive Trend Exhaustion.
Parameters:
rsi (float) : Relative Strength Index.
adx (float) : Average Directional Index.
momentum (float) : Momentum.
roc (float) : Rate of Change.
Returns: Trend exhaustion score.
adaptive_channel_memory(upper_channel, lower_channel, tolerance, lookback_length)
Adaptive Channel Memory.
Parameters:
upper_channel (float) : Upper channel.
lower_channel (float) : Lower channel.
tolerance (float) : Maximum channel difference.
lookback_length (int) : Number of bars.
Returns: Memory score.
adaptive_false_breakout(breakout_strength, rejection_strength, volume_ratio)
Adaptive False Breakout Detector.
Parameters:
breakout_strength (float) : Breakout strength.
rejection_strength (float) : Rejection strength.
volume_ratio (float) : Current volume divided by average volume.
Returns: False breakout probability.
adaptive_trap_detector(breakout_direction, breakout_strength, rejection_strength, rsi)
Adaptive Trap Detector.
Parameters:
breakout_direction (int) : Breakout direction.
breakout_strength (float) : Breakout strength.
rejection_strength (float) : Rejection strength.
rsi (float) : Relative Strength Index.
Returns: Trap direction and Trap probability.
adaptive_rsi_behavior(rsi, zigzag_count, divergence_strength, rejection_strength)
Adaptive RSI Behavior.
Parameters:
rsi (float) : Relative Strength Index.
zigzag_count (int) : RSI zigzag count.
divergence_strength (float) : Divergence strength.
rejection_strength (float) : Rejection strength.
Returns: RSI behavior score.
adaptive_market_behavior(trend_strength, reversal_probability, breakout_probability, exhaustion, energy, rsi_behavior)
Adaptive Market Behavior.
Parameters:
trend_strength (float) : Trend strength.
reversal_probability (float) : Reversal probability.
breakout_probability (float) : Breakout probability.
exhaustion (float) : Trend exhaustion.
energy (float) : Market energy.
rsi_behavior (float) : RSI behavior.
Returns: Market behavior score. Library

For-Loop Consensus MA | MiesOnChartsFor-Loop Consensus MA
Overview
For-Loop Consensus MA is a trend indicator that replaces a single moving average with an ensemble of exponential moving averages (EMAs) and asks them to "vote" on the direction of the market. Instead of committing to one length -- where a value of 20 and a value of 50 can disagree and either can be wrong at any given time -- it evaluates many lengths at once and only signals a trend when a large majority of them agree. The result is a single line whose colour reflects the level of agreement across the whole set of lookbacks.
The idea behind it
A recurring problem with moving-average trend tools is parameter sensitivity: the "best" length is only known in hindsight and changes with market conditions. A short EMA reacts quickly but whipsaws in noise; a long EMA is stable but late. Picking one is a compromise.
This indicator borrows a concept from statistics and machine learning known as model averaging (also called ensembling or bagging): rather than trusting one model, you build many variations of it and combine their outputs. The aggregate is generally more robust than any single member, because the idiosyncratic errors of individual lengths tend to cancel out while the shared trend signal reinforces.
Two things are aggregated here:
The line itself -- the average of all EMAs in the ensemble, producing a smoothed consensus curve.
The direction vote -- the fraction of EMAs that price is currently trading above.
How it works
The script uses a for loop to construct and maintain a series of EMAs spanning a range of lengths:
It steps from Min EMA Length to Max EMA Length in increments of Length Step (for example 20, 40, 60… 140).
Each EMA is computed manually from its smoothing factor alpha = 2 / (length + 1), and its running value is stored in a persistent array -- one slot per length -- so every member carries its state forward bar to bar.
On each bar the loop does two things: it sums the EMA values (to build the consensus line), and it counts how many EMAs price closes above (to build the vote).
From these:
Consensus line = the mean of all EMAs in the ensemble.
Vote share = number of EMAs price is above ÷ total number of EMAs, a value between 0 and 1.
Signal logic
The vote share drives the trend state through a symmetric threshold:
Bullish when the vote share is greater than or equal to the Supermajority Vote Share input (default 0.7) -- i.e. at least 70% of the lookbacks agree price is in an uptrend. The line turns green.
Bearish when the vote share is at or below its mirror (1 - threshold, so 0.3 at the default) -- at least 70% agree on a downtrend. The line turns red.
Neutral in between, when the ensemble is split and no supermajority exists. The line is grey, indicating indecision or a ranging market.
Requiring a supermajority rather than a simple majority is deliberate: it filters out the marginal, split-vote conditions where moving averages are least reliable, and only commits to a trend colour when the evidence across timescales is broad.
Inputs
Source -- the price series the EMAs are built from (default: close).
Min EMA Length / Max EMA Length -- the shortest and longest lookbacks in the ensemble. A wider span blends more timescales.
Length Step -- the spacing between ensemble members. A smaller step packs in more EMAs (finer, heavier); a larger step uses fewer.
Supermajority Vote Share -- how strong the agreement must be before a trend is declared. Higher values (e.g. 0.8) demand stronger consensus and produce fewer, more selective signals; lower values (e.g. 0.6) are more responsive but less discriminating.
How to use it
Trend context -- read the colour of the line as a regime filter. Green suggests a broad-based uptrend across lookbacks; red a broad downtrend; grey a lack of consensus where trend-following is riskier.
Trend confirmation -- the line can be used alongside price structure or other tools to confirm that a move is supported across multiple horizons rather than by one arbitrary length.
Neutral zones -- grey stretches highlight indecision and can be treated as periods to stand aside or tighten expectations.
Two alert conditions are included -- Consensus MA Long (bullish) and Consensus MA Short (bearish) -- so the trend states can be wired to PulseWire alerts.
Notes and limitations
Like all moving-average-based tools, this indicator is reactive: it describes the trend that price is already in and will lag turning points. It does not predict future prices.
Signals reflect agreement among lagging averages, so expect the trend colour to change after a reversal has begun, not before it.
Wider length ranges and larger supermajority thresholds increase robustness at the cost of responsiveness. There is no universally correct setting; adjust to the instrument and timeframe you trade.
This script is a decision-support tool, not a standalone trading system and not financial advice. It does not include risk management and makes no representation about future performance.
Test any settings on your market before relying on them. Indicator

ATR Divided by 4he Average True Range (ATR) is the gold standard for measuring market volatility. However, for active intraday traders, scalpers, or those looking to fine-tune their risk management, the standard ATR can often feel too wide.
Enter the Fractional ATR (ATR / 4). This indicator calculates the traditional Average True Range and divides it by four, isolating exactly 25% of the asset’s recent average volatility.
Why Divide ATR by 4?
Using a fraction of the ATR allows traders to adapt to market noise on a more granular level. Here is how you can apply the ATR/4 to your trading strategy:
High-Probability Intraday Targets: If an asset typically moves $4 a day (Standard ATR), aiming for a $1 move (ATR/4) represents a highly realistic, high-probability profit target for day traders and scalpers.
Tighter, Volatility-Adjusted Stop Losses: Using a full 1x or 2x ATR for a stop loss can sometimes mean risking too much capital or giving back too much floating profit. Using ATR/4 allows you to trail your stops tightly while still factoring in the asset's current micro-volatility, keeping you out of the standard "market noise."
Grid Trading and Scaling In: If you build positions over time, using an arbitrary static number (like buying every $0.50 down) ignores market conditions. Spacing your limit orders by an ATR/4 distance ensures your grid adapts to expanding or contracting volatility.
How it Works
The math is straightforward and transparent:
It calculates the standard Average True Range based on your chosen period.
It divides that exact value by 4.
It plots the resulting value as an easy-to-read oscillator in a separate pane below your chart.
Features & Settings
Customizable ATR Length: By default, the indicator uses the industry-standard 14-period lookback. You can easily adjust this in the settings menu to fit your specific timeframe or strategy (e.g., a 5-period for hyper-responsive data, or a 21-period for smoother data).
Clean Visuals: Plots cleanly in a lower pane so it does not clutter your main price chart.
Best Timeframes
This indicator is universally applicable but shines particularly well on lower timeframes (1m, 5m, 15m) when trying to capture a fraction of the Higher Timeframe (1H, 4H, Daily) volatility.
Disclaimer: This script is for educational and analytical purposes only. Always backtest your risk management strategies before applying them to live capital. Indicator

Isotropic Coordinate System (ICS)Library "ICS"
Isotropic Coordinate System (ICS): a dimensionless price-time space
for scale-invariant chart geometry.
Vertical axis: y = ln(price) / sigma, where sigma is the Yang-Zhang (2000)
minimum-variance, drift-independent, gap-consistent OHLC volatility estimator.
Horizontal axis: two scalings via the XScale enum.
legacy : x = bars / lookback. Linear window fraction. Backward compatible.
isotropic : x = sqrt(bars / lookback), with y additionally divided by
sqrt(lookback). Diffusion-consistent (sqrt-time scaling), so that
tan(theta) equals the z-score of the move and 45 degrees
corresponds to a move of exactly one standard deviation
of the n-bar log-return distribution. Assumes approximately
iid returns within the sigma window (the standard assumption
behind sqrt-time scaling; see Danielsson & Zigrand, 2006, for
its known limits under vol clustering and jumps).
Every output (angle, length, area, centroid) is a pure dimensionless number,
comparable across symbols, currencies, and timeframes.
Reference: Yang, D. & Zhang, Q. (2000), "Drift-Independent Volatility
Estimation Based on High, Low, Open, and Close Prices",
The Journal of Business, 73(3), 477-492.
yangZhangSigma(length)
Yang-Zhang volatility estimator. Minimum-variance, unbiased,
drift-independent, and consistent with opening gaps
(Yang & Zhang, 2000). Uses the unbiased sample variance
(biased = false) for both the overnight and open-to-close
components, matching the estimator's unbiasedness claim.
Parameters:
length (simple int) : (simple int) Rolling window length. Must be >= 2.
Returns: (series float) Per-bar sigma, floored at 1e-10.
toX(bars, lookback, mode)
Dimensionless horizontal coordinate.
Parameters:
bars (int) : (series int) Signed bar distance from the anchor.
lookback (int) : (series int) Window length acting as the horizontal unit.
mode (series XScale) : (series XScale) Scaling mode.
Returns: (series float) Signed dimensionless x.
toY(price, sigma, lookback, mode)
Dimensionless vertical coordinate.
Parameters:
price (float) : (series float) Price. Must be > 0.
sigma (float) : (series float) Yang-Zhang sigma. Must be > 1e-10.
lookback (int) : (series int) Window length (used by isotropic mode only).
mode (series XScale) : (series XScale) Scaling mode.
Returns: (series float) Dimensionless y, or na when inputs are invalid.
moveZScore(dLogPrice, sigma, bars)
Z-score of a log-price move over n bars: dLog / (sigma * sqrt(n)).
In isotropic mode this equals tan(theta) of the same move.
Parameters:
dLogPrice (float) : (series float) ln(target) - ln(anchor).
sigma (float) : (series float) Per-bar Yang-Zhang sigma. Must be > 1e-10.
bars (int) : (series int) Number of bars in the move. Must be > 0.
Returns: (series float) The z-score, or na when inputs are invalid.
triangle(td, anchorPrice, anchorBar, targetPrice, targetBar, sig, lookback, mode)
Right triangle between an anchor and a target, computed entirely
in ICS space. Writes results in place into `td` and returns it.
On invalid inputs every field is set to na, so world X never
receives contaminated numbers.
Parameters:
td (TriangleData) : (TriangleData) Output object, updated in place.
anchorPrice (float) : (series float) Anchor price (world A). Must be > 0.
anchorBar (int) : (series int) Anchor bar_index.
targetPrice (float) : (series float) Target price (world A). Must be > 0.
targetBar (int) : (series int) Target bar_index. Must differ from anchorBar.
sig (float) : (series float) Yang-Zhang sigma. Must be > 1e-10.
lookback (int) : (series int) Horizontal unit window.
mode (series XScale) : (series XScale) Scaling mode.
Returns: (TriangleData) The same `td`, for chaining.
pinTriangle(td, anchorPrice, anchorBar, extremePrice, bodyPrice, curBar, sig, lookback, mode)
Pin (wick) triangle with three vertices in ICS space:
A = anchor, B = candle extreme, C = candle body edge.
Side BC is the wick. theta = signed angle at A between AB and AC.
Since xB = xC, the shoelace area reduces exactly to
0.5 * |yB - yC| * |dx|.
Parameters:
td (TriangleData) : (TriangleData) Output object, updated in place.
anchorPrice (float) : (series float) Anchor price (hh or ll). Must be > 0.
anchorBar (int) : (series int) Anchor bar_index.
extremePrice (float) : (series float) Candle extreme (high or low). Must be > 0.
bodyPrice (float) : (series float) Candle body edge. Must be > 0.
curBar (int) : (series int) Current bar_index. Must differ from anchorBar.
sig (float) : (series float) Yang-Zhang sigma. Must be > 1e-10.
lookback (int) : (series int) Horizontal unit window.
mode (series XScale) : (series XScale) Scaling mode.
Returns: (TriangleData) The same `td`, for chaining.
zeroTri(td)
Resets a TriangleData to na. Use when the structure is inactive,
so inactive periods never enter moving averages or normalization
as fake zero values.
Parameters:
td (TriangleData) : (TriangleData) Object to reset, updated in place.
Returns: (TriangleData) The same `td`, for chaining.
TriangleData
One triangle's measurements in ICS space. All fields dimensionless.
Fields:
theta (series float) : Signed hypotenuse angle in degrees; in isotropic mode tan(theta) is the z-score of the move.
dy (series float) : Signed Euclidean magnitude of the hypotenuse.
area (series float) : Triangle area (>= 0).
centroidY (series float) : Vertical centroid of the triangle.
FrozenAnchors
Anchors frozen at a reference bar, plus activity state.
Fields:
hh (series float) : Highest high at the freeze bar (world-A price units).
ll (series float) : Lowest low at the freeze bar (world-A price units).
mid (series float) : Geometric mean sqrt(hh * ll) at the freeze bar.
bar_x (series int) : bar_index of the freeze bar.
time_x (series int) : time of the freeze bar.
is_active (series bool) : Whether the frozen structure is currently active. Library

RS/Correlation Panel**RS/Correlation Panel**
A single-table dashboard that benchmarks the current chart's symbol against any reference ticker you choose (SPY, QQQ, BTC, or any other symbol) across multiple timeframes — correlation, today's relative performance, short-term relative strength, and a longer IBD-style relative strength rating — plus historical daily move statistics for the symbol itself.
**Inputs**
- **Benchmark Ticker** — the symbol to compare against. Defaults to SPY, but accepts any ticker (QQQ, individual stocks, or crypto via its exchange prefix, e.g. COINBASE:BTCUSD).
- **Correlation Lookback (bars)** — number of bars used for the rolling correlation calculation. Default 20.
- **Daily Stats Lookback (days)** — number of trading days used to calculate average rise/fall and green/red day percentages. Default 60.
- **Short-Term RS/RW Lookback (bars)** — the window used for the medium-term relative strength/weakness reading, sitting between the 1-day and quarterly reads. Default 10.
- **Table Position** — corner of the chart where the table is displayed.
**Table Rows**
- **Correlation** — rolling correlation coefficient between the symbol and the benchmark over the chosen lookback, tagged Strong / Moderate / Weak based on absolute value.
- **Symbol's Today's Move / Benchmark's Today's Move** — each instrument's current-session percent change, calculated from that day's open to the live/last close.
- **RS/RW Today** — the difference between the symbol's and benchmark's daily percent change. Positive means the symbol is outperforming the benchmark today; negative means it's underperforming.
- **N-Bar RS/RW** — the same outperformance/underperformance concept, but measured as the difference in rate-of-change over the user-defined short-term lookback (default 10 bars). This fills the gap between a single day's move and a full quarterly trend.
- **IBD-Style RS** — a quarterly-weighted relative strength calculation modeled on the classic IBD Relative Strength methodology: the symbol's and benchmark's trailing performance are each computed across four rolling quarters (weighted 40/20/20/20, most recent quarter weighted heaviest), then compared as a percentage difference. This is a slower-moving, trend-level strength read — it won't react much to a single day's move, by design.
- **Avg % Rise / Fall** — average percentage gain on up days and average percentage loss on down days, calculated over the Daily Stats Lookback period.
- **Green Days % / Red Days %** — percentage of days in the lookback period that closed up versus down.
**Notes**
- All relative-strength and correlation metrics reference the same user-selected benchmark, so switching the input updates every row consistently.
- The IBD-Style RS calculation is a reproduction of the standard quarterly-weighted RS methodology and is intended to complement — not replace — short-term price action analysis.
- This is a decision-support tool, not a standalone trading signal. Always confirm readings against price structure, volume, and catalysts before acting. Indicator

Indicator

Clean LevelsAllows you to manually enter GEX Levels, HVL, Globex VAH, VAL, POC, PW VAH, VAL, and POC, as well as Previous Previous Week (PWPW) VAH, VAL, POC and Current Week (CW) VAH, VAL, POC Indicator

StocksDeveloperAlertsLibrary "StocksDeveloperAlerts"
AutoTrader Web alert builder by Stocks Developer — turn PulseWire alerts into real broker orders across many accounts and brokers. Ready-made functions for single orders, options the easy way, 8 option structures (straddle/strangle/spreads/iron condor/iron fly), custom multi-leg, account or group targeting, and your own risk limits. No alert-text typing. stocksdeveloper.in
order(symbol, exchange, producttype, tradetype, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, optiontype, strike, expiry, spothint, usespot, onslicefailure, risk, extra)
Build an alert message for a single order (stock, futures or one option leg). This is the full builder; equity() and option() are shorter wrappers over it. Set exactly one of account/group and exactly one of lots/quantity. Add optiontype to make it an option order.
Parameters:
symbol (string) : (series string) Broker-independent symbol, e.g. "NIFTY", "BANKNIFTY", "SBIN". For options, pass the underlier (e.g. "NIFTY"), not a full contract.
exchange (string) : (series string) Exchange code, e.g. "NSE"/"BSE" for stocks, "NFO" for options and futures.
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
account (string) : (series string) Place in this single account. Set this OR group.
group (string) : (series string) Place in every live account in this group. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
optiontype (string) : (series string) CE for a call, PE for a put. Adding this makes it an option order.
strike (string) : (series string) ATM (default), ATM+1 / ATM-2, OTM / OTM2, ITM / ITM2, or an exact strike like "24500". Requires optiontype.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date like "10-JUL-2026". Requires optiontype.
spothint (string) : (series string) Advanced: a spot price to help option-strike selection.
usespot (bool) : (series bool) Advanced: use the spot hint for strike selection.
onslicefailure (string) : (series string) Advanced: continue (default), alert or retry, if a large order that was auto-split has a slice fail.
risk (string) : (series string) A risk block from risk() — for example risk=atw.risk(maxloss=5000).
extra (string) : (series string) Advanced: any extra "key=value" lines to pass through unchanged (one per line).
Returns: (series string) The ready-to-send alert message.
equity(symbol, exchange, producttype, tradetype, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, risk, extra)
Build an alert for a single stock or futures order (no option fields). Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) Broker-independent symbol, e.g. "SBIN".
exchange (string) : (series string) Exchange code, e.g. "NSE" or "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
option(symbol, exchange, producttype, tradetype, optiontype, strike, expiry, account, group, lots, quantity, ordertype, price, triggerprice, validity, amo, spothint, usespot, risk, extra)
Build an option order the easy way — give the underlier and pick the strike + expiry; no need to type the full option symbol. Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY", "BANKNIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
tradetype (string) : (series string) BUY or SELL.
optiontype (string) : (series string) CE for a call, PE for a put.
strike (string) : (series string) ATM (default), ATM+1 / ATM-2, OTM / OTM2, ITM / ITM2, or an exact strike like "24500".
expiry (string) : (series string) weekly (default), next, monthly, or an exact date like "10-JUL-2026".
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
ordertype (string) : (series string) MARKET (default), LIMIT, STOP_LOSS or SL_MARKET.
price (float) : (series float) Limit price (required for LIMIT).
triggerprice (float) : (series float) Trigger price (for stop-loss orders).
validity (string) : (series string) DAY (default) or IOC.
amo (bool) : (series bool) true for an after-market order.
spothint (string) : (series string) Advanced: a spot price to help strike selection.
usespot (bool) : (series bool) Advanced: use the spot hint for strike selection.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
straddle(symbol, exchange, producttype, account, group, lots, quantity, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Straddle — buy (or sell) a call and a put at the money. direction "BUY" = long straddle, "SELL" = short straddle.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) builds the structure as named; SELL flips every leg.
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue, if one leg cannot be placed.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
strangle(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Strangle — buy (or sell) an out-of-the-money call and put, each 'width' strikes out. direction "BUY" = long strangle, "SELL" = short strangle.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) How far out of the money the legs sit, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bullCall(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bull call spread — buy a call at the money and sell a call 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bearPut(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bear put spread — buy a put at the money and sell a put 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bullPut(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bull put spread (credit) — sell a put at the money and buy a put 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
bearCall(symbol, exchange, producttype, account, group, lots, quantity, width, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Bear call spread (credit) — sell a call at the money and buy a call 'width' strikes out. Use direction "SELL" to reverse.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) Distance between the two strikes, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
ironCondor(symbol, exchange, producttype, account, group, lots, quantity, width, wing, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Iron condor — sell a call and a put 'width' strikes out, and buy a call and a put 'width'+'wing' strikes out as protection. direction "BUY" builds this credit condor; "SELL" reverses it.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
width (int) : (series int) How far out the sold legs sit, in strike steps (default 2).
wing (int) : (series int) Extra distance out to the protective legs, in strike steps (defaults to width).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
ironFly(symbol, exchange, producttype, account, group, lots, quantity, wing, expiry, direction, ordertype, price, onlegfailure, risk, extra)
Iron fly — sell a call and a put at the money, and buy a call and a put 'wing' strikes out as protection. direction "BUY" builds this credit fly; "SELL" reverses it.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
wing (int) : (series int) How far out the protective legs sit, in strike steps (default 2).
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
direction (string) : (series string) BUY (default) or SELL (flips every leg).
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
leg(optiontype, strike, tradetype, multiplier)
Build one option leg string for use with multiLeg(), e.g. atw.leg("CE", "ATM+2", "SELL", 2) -> "CE ATM+2 SELL x2".
Parameters:
optiontype (string) : (series string) CE for a call, PE for a put.
strike (string) : (series string) ATM, ATM+2, OTM2, ITM1, or an exact strike like "24500".
tradetype (string) : (series string) BUY or SELL for this leg.
multiplier (int) : (series int) Size multiplier for this leg (default 1).
Returns: (series string) The leg descriptor.
multiLeg(symbol, exchange, producttype, legs, account, group, lots, quantity, expiry, ordertype, price, onlegfailure, risk, extra)
Build an alert for a fully custom multi-leg order from a list of legs (1 to 10) made with leg(). Set exactly one of account/group and exactly one of lots/quantity.
Parameters:
symbol (string) : (series string) The underlier, e.g. "NIFTY".
exchange (string) : (series string) Options exchange code, e.g. "NFO".
producttype (string) : (series string) INTRADAY, DELIVERY, NORMAL or MTF.
legs (array) : (array) The legs, e.g. array.from(atw.leg("PE","ATM-2","SELL"), atw.leg("PE","ATM-6","BUY")).
account (string) : (series string) Single account. Set this OR group.
group (string) : (series string) Group of accounts. Set this OR account.
lots (int) : (series int) Number of lots. Set this OR quantity.
quantity (int) : (series int) Exact quantity. Set this OR lots.
expiry (string) : (series string) weekly (default), next, monthly, or an exact date.
ordertype (string) : (series string) MARKET (default) or LIMIT.
price (float) : (series float) Limit price (required for LIMIT).
onlegfailure (string) : (series string) alert (default), cancel or continue.
risk (string) : (series string) A risk block from risk().
extra (string) : (series string) Extra "key=value" lines to pass through unchanged.
Returns: (series string) The ready-to-send alert message.
riskLimits(maxloss, forceexit, entrywindow, blockExpiry)
Build a risk-limits block to attach to any order via risk=. Example: risk=atw.riskLimits(maxloss=5000). These are your own limits; see the Alert Automation guide for exactly how each one behaves.
Parameters:
maxloss (float) : (series float) Maximum day loss for the account, in your account currency.
forceexit (string) : (series string) A square-off time as "HH:mm", e.g. "15:15".
entrywindow (string) : (series string) An allowed entry-time window "HH:mm-HH:mm", e.g. "09:30-14:30".
blockExpiry (bool) : (series bool) Block new entries on the instrument's expiry day.
Returns: (series string) The risk lines, ready to pass as risk=. Library
