Machine Learning Statistics: kNN Win Rate vs Random EntriesBefore you trust a "machine learning" indicator - or pay for one - you
can test it. This script measures the method most published ML
indicators are built on against entries taken at random, on your
instrument, your timeframe, your chart.
Why random entries are the comparison that matters. A win rate
on its own tells you very little. Buy anything at any moment, put a
target above and a stop below, and you will win roughly half the time.
That is arithmetic, not skill. So the useful question about a signal is
not "how often does it win" but "how often does it win compared with
entering at a random moment instead". This script answers that
question. For every signal the method produces, it also places matched
random entries - same direction, same target and stop distances,
anchored at bars where no signal happened - then scores both and
reports the difference.
The measurement is tested before it is trusted. The script can
replace price with artificial data that contains one deliberate,
repeating pattern - put there on purpose, so there is definitely
something to find. A plain RSI rule - the relative strength index, a
standard overbought and oversold gauge - reads that pattern directly
and won 75.7% of its trades. Randomly timed trades on the same bars won
50.6%. The pattern was there, and a simple rule found it.
The same test then handed the widely published machine-learning method
the same data, with the pattern sitting in the exact measurements it
looks at. It won 39.9%. Randomly timed trades won 49.3%. It did not
merely fail to find the pattern. It finished 9.4 percentage points
behind random timing - a percentage point being the plain difference
between two percentages, so 51% against 50% is one point - and the gap
grew wider the stronger the pattern was made.
That is the demonstration this script exists to make possible: an
instrument that finds an edge when one is really there, and reports
nothing when there is not. What it reports on live market data is
below.
The script on a live chart, with both populations drawn. The green and
red pins are signals from the machine-learning method - green below the
bar for long, red above it for short - created only once the bar has
closed, so nothing is moved or redrawn afterwards. The grey dots are
the control: matched random entries, three for every signal, taken in
the same direction with the same target and stop distances but at bars
where no signal happened. Those are what the signals get measured
against, and the key in the corner names both. The panel reports the
two win rates and the gap between them: 50.1% for the signals against
49.5% for random entries, a difference of 0.6 percentage points across
812 signal trades.
What to Use It For
Checking an ML indicator before you trust it. The method measured
here is the one most published ML indicators are built on: nearest-
neighbor classification over oscillator readings. If you use one, this
tells you what its timing was worth on your instrument, over a window
you choose.
Seeing what a win rate is worth without a control. Every cell in
this study has a raw win rate near 50% and a controlled result near
zero. The raw number and the meaningful number look nothing alike. Run
the script with the control switched off and back on to see it.
Testing the measurement itself. Everything here can be checked.
The synthetic mode lets you plant a pattern and confirm the instrument
finds it, before you believe anything it says about a real market.
The Result in Plain Language
Across three instruments at the default settings, the method's signals
won 48.8% of the time. Matched random entries on the same instruments
won 49.9%. The difference is -1.1 percentage points.
That difference is smaller than what this test could reliably detect.
On this sample the smallest difference the measurement could resolve is
about 2.9 percentage points. So the honest statement is not "the method
is worthless" - it is this:
On this sample, the method's signal timing cannot be told apart from
random timing, and any real advantage larger than about 3 percentage
points would have shown up.
The same answer came back on every configuration tested: different
numbers of neighbors, fewer features, different training lengths,
different targets, both timeframes, and a separate year of data that
shares no bars with the main window. Twenty configurations, and not one
of them produced a result large enough to be distinguished from chance.
The sharpest single test came from switching both of the method's
filters off, which produces far more signals and therefore a finer
measurement. 2,782 signal trades against 8,181 random ones:
Signals 49.784%
Random 49.786%
Difference -0.002 percentage points
How the Test Works
The signal. The script rebuilds the published method from its
open source: five oscillator readings per bar, a search for past bars
whose readings look similar, and a vote among those neighbors. When
the vote changes sign, that is the signal, and that is the entry.
The trade. Every entry is taken at the close of the bar where
the signal appeared. A target and a stop are placed the same distance
above and below, measured in average true range, which is roughly how
far price travels in one bar. Whichever is reached first decides the
outcome. Trades that reach neither within the time limit are reported
separately and left out of the win rate.
The control. Each signal also creates three random entries, at
fixed distances later on the chart, in the same direction, with the
same target and stop distances. Nothing about them is tied to a signal.
They answer the question "what would any trade of this shape have
returned over this sample".
The comparison. Signals minus random entries, in percentage
points. That is the number this script exists to produce.
The same chart and run as above, with the full accounting shown. Every
signal the method produced is followed down the panel into exactly one
outcome, and every random entry alongside it: 862 signals, 821 of them
inside the chosen date window, and 2,430 matched random entries built
from those. Nothing is discarded quietly - each rejected signal is
counted on its own line, the trades still running when the window ended
are counted too, and the error counter near the bottom has to read zero
for the run to be valid.
Validation
Two tests with known answers, both built into the script.
The blank test. Price is replaced with a random walk containing
no pattern at all. Both signals and random entries must then land at
50%. Across sixteen different random walks, signals came in at 49.88%
and random entries at 49.52%, a difference of 0.27 percentage points.
Nothing was found, because there was nothing there.
The planted test. A pattern is added to the artificial data, at
three strengths, sitting in exactly the measurements the method reads.
A simple rule that looks at that pattern directly gains more as the
pattern gets stronger:
Pattern strength Simple rule beats random by
none +0.45 points
weak +3.90 points
medium +11.60 points
strong +25.15 points
This is what makes the market result believable. The measurement finds
a real edge when one is put there, and reports nothing when there is
nothing to find.
What the method did on the planted data. It went the other way.
The stronger the pattern, the further behind random timing it finished:
-2.48, then -6.75, then -9.40 percentage points. On the same bars, with
the same targets, the simple rule was gaining 25 points.
This is a result on artificial data with one setting per strength, and
it is reported as an observation, not an explanation. There is a
candidate reason in how the published method picks which past bars to
vote - it may keep the least similar ones rather than the most similar
- but that has not been tested and no claim is made here.
The test with a known answer. Price has been replaced by artificial
data carrying one deliberate, repeating pattern, so there is certainly
something to find. The lower block of the panel is a plain RSI rule
reading that pattern directly: it wins 75.9% against 50.6% for random
entries, a gap of 25.3 points. The upper block is the machine-learning
method given the same data: 39.7% against 49.3%, a gap of -9.6 points.
A simple rule found the pattern; the method finished behind random
timing. These figures move by a few tenths of a point as a chart loads
more bars, because this test uses all of them. The candles behind the
panel are artificial and show nothing meaningful.
Results
Baseline configuration, 30 minutes, 2025-01-01 to 2026-08-01, the
method's own default settings throughout:
Instrument Signals Random Difference
BTCUSDT 50.12% 49.52% +0.60 pts
EURUSD 47.24% 51.35% -4.11 pts
ES1! 48.68% 49.03% -0.35 pts
Pooled 48.84% 49.93% -1.10 pts
The three instruments do not disagree by more than ordinary sampling
variation, so the pooled figure stands. The range of plausible values
around the pooled -1.10 runs from -3.6 to +1.5 percentage points, and
includes zero.
Every other configuration tested, all on BTCUSDT at 30 minutes:
Neighbors 2 / 8 / 32 +0.77 / +0.60 / +0.19 pts
Two features only +0.71 pts
Training length 4 bars +0.42 pts, 8 bars +0.52 pts
Shorter memory +1.13 pts
Targets 1x / 3x +0.71 / +1.58 pts
On the hourly chart, across the same three instruments, +0.94 points.
Over calendar 2024, a window sharing no bars with the main one, -1.01
points. Both ranges of uncertainty include zero.
To reproduce these figures: the script's defaults match the
baseline. Switch the date range on, set 2025-01-01 to 2026-08-01, turn
compact panel mode off, and load the full chart history.
Terms Used in the Panel
Signals. Entries taken where the method's vote changed sign.
Random / placebo. Matched entries at fixed offsets later, same
direction and same target distances, anchored where no signal occurred.
Ambiguous outcome. A bar whose range contains both the target
and the stop. Bar data cannot show which came first, so the trade is
counted against the win rate - the cautious choice.
Censored outcome. A trade that reached neither target nor stop
before the time limit. Reported on its own and kept out of the win rate.
95% interval. The range of values the true answer plausibly sits
in. When it includes 50%, the result cannot be told apart from a coin
flip.
Smallest detectable difference. How small a difference this test
could have found on data with no edge. Anything smaller than it is not
evidence.
Settings
Classifier. Number of neighbors, training length, how many
oscillator readings to use, how far ahead the training labels look, and
which of the two labeling conventions to use. The method's own filters
can each be switched off.
Measurement. Target and stop size, the averaging length behind
them, and the time limit.
Control. How many random entries per signal and how far ahead
they are placed.
Sample. The date range uses explicit year, month and day fields
rather than a date picker, so a published sample can be reproduced
exactly.
Validation. Synthetic mode, seed, step size, drift, and the
planted-pattern strength.
Display. Compact panel, signal markers, marker size.
Limitations
The sample is smaller than intended. The target set before any
run was 1,000 completed trades per test. The main test produced 812,
and the platform's history limit made 1,000 unreachable at the
published settings on any instrument, timeframe or date range tried.
Every figure above is reported with the precision it actually achieved:
about 4.6 points for a single instrument and 2.9 points pooled.
The measurement has a small bias of its own. On data with no
edge, random entries come in at 49.62% rather than exactly 50%. Signals
carry the same offset, so it cancels when the two are subtracted, and
the difference on that data sits at +0.27 points. It is disclosed here
because it is real.
One decision was made after seeing data. When the validation
missed one of its own criteria by a small margin, the rule for what to
do next was written before the additional runs but after the result
that prompted them. That is a weaker guarantee than deciding everything
in advance, which is what the rest of this study did.
What was and was not measured. The classifier itself: readings,
similarity, neighbor vote, filters, entry when the vote flips. Not
included are the extra entry conditions and exit rules that individual
published indicators layer on top. Outcomes here are scored by a fixed
target-and-stop race, not by any indicator's own exits.
One family of method. Nearest-neighbor classification is one
class of ML indicator. These numbers apply to the method measured.
Loaded history bounds every test. How many bars your chart loads,
not only the calendar range, limits each run.
Direction splits are descriptive only. In a trending sample the
long and short win rates separate by around 20 points while the overall
comparison holds steady. Read the combined rows.
This is a measurement of the past. It reports what happened
under stated rules on stated samples. It does not predict anything.
Disclaimer
This script and its description are provided for educational and
research purposes only. They do not constitute financial, investment,
trading or other professional advice, and they do not recommend buying,
selling or holding any asset. Historical and simulated results do not
guarantee future performance. Trading involves risk, including the
possible loss of capital. You are solely responsible for your trading
and investment decisions and should conduct your own research and,
where appropriate, consult a qualified financial professional.
Indicator

Repainting Statistics: Displayed vs Tradeable Win RateRepainting means that an indicator draws or changes signals on bars
that have already closed, using information that did not exist when
those bars closed. Before you trust an indicator whose arrows mark
every top and bottom - or a backtest built on such arrows - this script
shows how much of that performance hindsight alone can create, on any
chart.
On randomly generated price bars - data with no trend and no pattern to
find - a pivot-reversal arrow showed a 75.84% win rate. The same arrow,
entered at the first moment it was actually visible on a live chart,
won 50.0% - the coin flip that random data must produce. The 25.9-point
gap is the repainting premium.
On real market data - a crypto pair, an FX pair and an equity index
future - the premium at the default settings is 18.9 percentage points
of win rate. That is the average amount by which the displayed history
of a repainting signal overstates what a real-time user of the same
signal could have achieved.
This script measures the two kinds of repainting that place future
information onto past bars: signals computed from data that had not yet
happened, and signals drawn backwards onto earlier bars with a plot
offset. A third kind - signals that appear and disappear while the live
bar is still forming - is a separate phenomenon and is out of scope
here. This script itself does not repaint: every marker it draws is
created only after the signal is confirmed, and is never moved.
The measurements behind this publication were made on BTCUSDT (crypto),
EURUSD (forex) and ES1! (an equity index future). The script runs on any
symbol and timeframe.
What to Use It For
Putting a number on a widely known warning. Traders are routinely
warned that repainting indicators look better than they perform. The
warning is correct, but it usually comes without a number. This script
produces the number, on your chart, with a method you can audit row by
row in its panel.
Understanding what a hindsight chart is worth. Arrows planted at
exact tops and bottoms - ZigZag-style reversal markers, fractal arrows
drawn several bars back - are the most common repainting signals. The
script scores the same signal twice on the same bars: where history
draws it, and where a live user could first have acted on it. The
difference is what the hindsight display is worth.
Testing before trusting. If a signal on your chart is drawn
in the past - the arrow sits several bars behind the bar where it first
appeared - this measurement applies to it. The pivot rule used here is
the cleanest representative of that family, with the hindsight distance
as an explicit setting, so you can see how the premium grows as signals
are drawn deeper into the past.
A pivot-reversal signal on a real chart. The orange triangle is the
displayed placement: history draws the signal at the exact swing bar.
The circle marks the confirmation bar: the first bar on which the signal
was actually knowable in real time. The dotted line connects the two -
the bars in between are the hindsight gap. The panel scores every such
pair on the loaded chart - 5,512 of them here, not just the two visible
- in both ways and reports the difference.
The Result in Plain Language
Every tested configuration showed a large, positive repainting premium.
Across three instruments at the default settings, the displayed version
of the signal won 18.9 percentage points more often than the tradeable
version of the same signal - about 68% against about 50%. The result
repeated on every instrument, on two timeframes, and in a separate
calendar year that shares no data with the main test window.
The deeper the hindsight, the larger the premium: painting the signal 2
bars into the past cost 13.1 points; painting it 10 bars back cost 34.5
points. Filling the trade at the exact swing price - which is what a
naive backtest of a repainting signal does - nearly doubled the premium
compared with filling at the signal bar's close.
The tradeable version of the signal, meanwhile, stayed at the baseline
in every cell. The gap between the two versions is not produced by the
rule finding good trades. It is produced by where history draws them.
Terms Used in the Panel
Displayed arm. The trade as the chart's history shows it: entry
at the close of the bar where the signal is drawn - the pivot bar, the
swing bar the arrow points at - even though the signal did not exist yet
on that bar.
Tradeable arm. The same signal entered at the close of the bar
where it first became knowable - the confirmation bar. This is the best
a real-time user of the signal could have done.
Premium ("disp - trad"). The displayed arm's win rate minus the
tradeable arm's win rate, in percentage points. This is the primary
result: the part of the displayed performance that hindsight placement
alone creates.
Percentage point (pp). An absolute difference between
percentages: 68% minus 50% is 18 percentage points.
Discordant pairs. Events where the two arms disagreed - one won
and the other lost. The premium's z score comes from a paired test
(McNemar's test) on exactly these events: it asks whether the
disagreements favour one arm more often than chance allows. A paired
test is used because both arms trade the same events on the same price
path, so their outcomes rise and fall together.
z score. The result divided by a measure of its statistical noise.
As a widely used threshold, an absolute z score above 2 is treated as a
first sign of a real effect; this study also required the result to
repeat on two more instruments before calling it a finding.
95% confidence interval (95% CI). A range around the estimate
showing its uncertainty. When the range excludes zero, the direction of
the effect is established at that confidence level.
Ambiguous outcome. A bar whose range contains both the target and
the stop. Bar data cannot show which was reached first, so the case is
counted against the win rate - the safe choice.
Censored outcome. A trade that reached neither barrier before the
time limit. It is reported separately and leaves the paired comparison;
a pair only counts when both arms produced a real outcome.
Replay errors. An internal integrity counter for the part of the
measurement that reconstructs the displayed arm's trade from closed
bars. It must read 0; any other value voids the run and says so.
The Rule Being Measured
A pivot low is a bar whose low is strictly below the lows of a set
number of bars on each side - the pivot length. A pivot high is the
mirror image. In this script a pivot low is a long signal and a pivot
high a short signal, ties disqualify the bar, and the test uses the
strict definition throughout.
A pivot with length 3 can only be recognised 3 bars after the pivot bar
prints: its definition depends on the bars that come after it. History
nevertheless draws the signal at the pivot bar. That gap - the signal
exists in the display 3 bars before it existed in reality - is not a
flaw of one particular indicator. It is the defining feature of the
whole family of reversal markers this rule represents, and its size is
the pivot length, which makes the hindsight distance measurable as a
setting rather than an accident.
How the Measurement Works
Both arms of every pair use one shared risk unit: the average true range
(ATR) measured at the pivot bar. Average true range is roughly how far
price typically travels in one bar, so barriers set in ATR mean the same
thing on a volatile instrument and a quiet one. A barrier size of 2R
places a target and a stop two risk units from the entry, one on each
side.
The displayed arm enters at the pivot bar's close. The tradeable arm
enters at the confirmation bar's close. Each arm then races its own
symmetric barriers: whichever of the target or stop is reached first
decides the outcome, with a time limit for trades that reach neither.
Entries are recorded at closes because a bar's high or low has no known
time inside the bar; a close is a defined moment.
The displayed arm's early bars are reconstructed at confirmation time
from bars that have already closed. Nothing about the measurement uses
future data; the future data is entirely inside the thing being
measured - the entry placement.
Why the displayed arm cannot help winning more. A pivot low is,
by definition, lower than every low for the next several bars. So while
the displayed trade runs through those bars, price cannot reach a stop
placed at or below the pivot low - but it can reach the target. Losing
outcomes are suppressed during the hindsight gap; winning outcomes are
not. The panel shows this directly: the displayed arm's average adverse
excursion (how far a trade goes against the entry before resolving) is
0.56-0.61R across the baseline cells, while the tradeable arm's is
0.85-0.89R on the same events.
The built-in validation. Price is replaced internally with a random walk
that contains no signal by construction, so the correct answer is known:
the tradeable arm must win 50%, and here it reads 50.2% with a
confidence interval containing 50. The displayed arm wins 76.1% on this
run of the test. The premium exists before any market data is involved,
because it is a property of hindsight placement, not of markets.
Results
The study contains 18 runs: 4 validation runs on synthetic data and 14
market runs producing 15 estimates. All 15 market estimates are
positive, ranging from +12.2 to +34.5 percentage points, with the
smallest z score at +12.8. The smallest difference the design can
detect is about 1 percentage point, measured on data with no edge.
The decision rule was fixed before any market run: an absolute z score
above 2 on one configuration, plus a repeat of the result on the two
other instruments, before anything counts as a finding. The rule was
met in full.
Baseline configuration, 30 minutes, 2025-01-01 to 2026-08-01:
Instrument Premium z Pairs
BTCUSDT +18.0pp +29.0 5,348
EURUSD +20.1pp +25.4 3,618
ES1! +19.2pp +22.6 3,276
Pooled +18.9pp 95% CI +18.1 to +19.7
A heterogeneity check (Cochran's Q, which asks whether the three
instruments disagree more than sampling noise allows) does not reject
pooling: Q 4.43, p 0.11.
The same three instruments, 1-hour timeframe: +17.4, +20.6 and +20.1
points - each within one point of its 30-minute counterpart. At 1 hour
the heterogeneity check is marginal (Q 6.02, p 0.049), so the 1-hour
result is reported as the range +17.4 to +20.6 rather than as one
pooled number.
Calendar year 2024, which shares no data with the window above: +15.8,
+18.0 and +18.9 points, pooled +17.3 (95% CI +15.8 to +18.7, Q p 0.19).
The premium grows with hindsight depth. On BTCUSDT 30m, changing
only the pivot length - how many bars into the past the signal is
drawn:
Hindsight depth Premium z Pairs
2 bars +13.1pp +27.6 7,364
3 bars (default) +18.0pp +29.0 5,348
5 bars +24.8pp +27.7 3,428
10 bars +34.5pp +24.0 1,775
The relationship is strictly monotone, and it was stated as the expected
pattern in the study design before any run: a longer protected gap
suppresses more losing outcomes. A measurement artifact would have no
reason to follow the dose this way.
The premium shrinks as barriers widen. Same events, scored at
three barrier sizes: +29.4 points at 1R, +18.0 at 2R, +12.2 at 3R. The
hindsight gap protects a fixed number of bars; a wider barrier makes the
race last longer, so the protected bars are a smaller share of it.
Filling at the arrow price nearly doubles the premium. The
default displayed fill is the signal bar's close. Filling at the pivot's
exact extreme instead - which is what a backtest that trusts the arrows
does - raises the premium from +18.0 to +34.2 points on the same
events. The displayed arm's average adverse excursion collapses to
0.28R: trades that appear to suffer almost no drawdown. In that
configuration, across 5,349 pairs, there was not a single event where
the tradeable arm won and the displayed arm lost. That is exactly what
the geometry requires, and it serves as an additional consistency check
on the measurement.
The tradeable arm stayed at its baseline everywhere. In all nine
baseline market cells its win rate was between 49.3% and 51.2%, and its
confidence interval contained 50% every time. This is reported as a
property of the measurement design, not as a claim about pivot trading;
see the limitations.
To reproduce the published figures: the script defaults match the
baseline configuration. Switch the date range on (2025-01-01 to
2026-08-01), disable compact panel mode, and load the full chart
history. The three instruments are BTCUSDT, EURUSD and ES1!.
Validation
Known-answer test. Synthetic mode replaces price internally with
a random walk that contains no signal, so the correct answers are known
in advance: the tradeable arm must win 50%, and the displayed arm must
win more - if either fails, the measurement is broken. Across three
seeds (three different artificial price series), the tradeable arm
pooled to 49.96% on 11,637 pairs, within a twentieth of a point of 50%,
with every seed's confidence interval containing 50%. The displayed arm
pooled to 75.84%. The premium on data with no edge: +25.9 points.
Drift stress test. The same test repeated with a steady upward
drift added to the artificial data. Drift moved the long and short win
rates apart, as it must - the tradeable arm read 59.0% long and 41.3%
short - but the premium barely moved: +24.9 points against +25.9
driftless. Both arms inherit the drift, and it cancels in the pairing.
This is the test that shows the premium is not a trend artifact.
The drift stress test. Artificial data with a steady upward drift and
still no signal by construction. Drift splits the tradeable arm's two
directions apart - 59.0% long against 41.3% short - exactly as a trend
must. The premium is nearly unchanged: +24.9 points against +25.9
without drift, because both arms inherit the drift and it cancels in
the pairing. Synthetic mode replaces price internally, so the chart
behind the panel does not show the tested data.
Resolution. On no-edge data the design resolves differences down
to about 1 percentage point. Every market estimate in this study is at
least twelve times that floor.
Accounting. The panel reconciles every confirmed pivot into
exactly one category (measured, out of range, no ATR available, or
filtered), reports any mismatch as an explicit error, and carries a
replay-error counter that must read zero. Across all 18 runs, every
reconciliation was exact and every replay-error count was zero.
Settings
Signal definition. Pivot length sets how many bars on each side
define a pivot - and with it, how far into the past the displayed signal
is drawn. Minimum separation optionally rejects events too close to the
previous one.
Measurement. ATR length sets the risk unit. Barrier size sets the
target and stop distance in risk units. The time limit censors trades
that reach neither barrier. Displayed fill chooses where the displayed
arm enters: the pivot bar's close (default) or the pivot's exact extreme
(labelled biased; it adds the fill bias on top of the placement bias).
Sample. The date range uses explicit year, month and day fields
rather than a date picker, so a published sample can be reproduced
exactly.
Validation. Synthetic mode, seed, step size and drift per bar.
Display. Compact panel mode, the signal markers with their gap
lines, and the marker size.
Limitations
One rule family was measured. The pivot-reversal signal is the
cleanest and most common representative of hindsight placement, but
other repainting mechanisms - such as higher-timeframe data requested
with lookahead - share the deception without being measured here. The
numbers in this description apply to the measured rule.
The tradeable arm's 50% is not a verdict on pivot trading. This
design pairs two versions of one rule; it contains no control for the
rule itself, so it cannot say whether pivot reversals have or lack an
edge against other entries. The premium - the difference between the
two versions - is the only claim.
Long/short splits are unreliable under trend. In the drift test,
drift displaced the two directions' win rates by about nine points each
way while the aggregate premium held. Read the aggregate rows; treat
directional splits as descriptive.
Instruments may differ by a small amount. BTCUSDT showed the
lowest premium in every window, and at 1 hour the heterogeneity check
was marginal. A real instrument-level spread of roughly two points
around +19 is possible. No cell was below +12.
Loaded chart history bounds every sample. The number of bars the
chart loads, not only the calendar range, limits each run. The windows
and sample sizes are stated per cell above.
Historical measurement is not a forecast. The script reports what
happened under the specified rules and samples. It does not predict the
future behavior of any signal or instrument.
Disclaimer
This script and its description are provided for educational and
research purposes only. They do not constitute financial, investment,
trading or other professional advice, and they do not recommend buying,
selling or holding any asset. Historical and simulated results do not
guarantee future performance. Trading involves risk, including the
possible loss of capital. You are solely responsible for your trading
and investment decisions and should conduct your own research and,
where appropriate, consult a qualified financial professional.
Indicator

Monthly Statistical LevelsMonthly Statistical Levels is an open-source indicator that plots monthly reference levels based on historical monthly price extensions from the monthly open.
The goal of the script is to provide a clean statistical map for the current and recent months. It is designed as a market structure and reference-level tool, not as a buy/sell signal system.
How it works
The script uses completed monthly candles from TradingView data.
For each completed month, it calculates two historical extensions:
High extension:
Monthly High minus Monthly Open, divided by Monthly Open.
Low extension:
Monthly Open minus Monthly Low, divided by Monthly Open.
These historical extensions are stored separately for upside and downside movement.
At the start of each new month, the script uses the current monthly open and projects five reference levels:
Strong High
Avg High
Open
Avg Low
Strong Low
Avg High is based on the historical average upside extension from the monthly open.
Avg Low is based on the historical average downside extension from the monthly open.
Strong High uses the average upside extension plus a configurable standard deviation multiplier.
Strong Low uses the average downside extension plus a configurable standard deviation multiplier.
By default, the strong multiplier is set to 1.0, meaning strong levels use the historical average extension plus one standard deviation.
Lookback options
Users can choose the statistical lookback used for the calculations:
24 months
36 months
60 months
120 months
All available history
Using all available history can make the levels more stable, but it may also mix different market regimes. This is especially important for assets with structural changes, short trading histories, or very different behavior across cycles.
No lookahead logic
The indicator uses completed monthly candles to build the historical sample.
Each month keeps the levels calculated with the information available at the start of that month. The current month is used only for its monthly open, which is known once the month begins.
This means the levels are not recalculated using future monthly highs or lows.
How to use it
The levels can be used as a visual reference for monthly range structure.
Possible uses include:
Identifying where price is trading relative to its monthly statistical range.
Comparing the current month with recent monthly behavior.
Observing when price reaches average or stronger historical extension zones.
Keeping a cleaner chart with only the most recent visible months.
Main settings
Visible months:
Controls how many recent months are displayed. The default is 6 and the maximum is 12 to keep the chart readable.
Statistical lookback:
Controls the historical sample used to calculate average and strong levels.
Minimum closed months:
Defines the minimum number of completed monthly candles required before plotting levels.
Strong multiplier:
Controls how far strong levels are placed from average extension levels using standard deviation.
Labels:
Users can show labels only for the current month, for all visible months, or turn labels off.
Alerts
The script includes optional alert conditions for touches of:
Strong High
Avg High
Open
Avg Low
Strong Low
Limitations
This indicator does not predict future price movement.
It does not identify support or resistance with certainty.
It does not generate buy or sell signals.
It does not evaluate trend, fundamentals, macro conditions, liquidity, positioning, or news.
The levels depend on the TradingView symbol selected, the available historical data, and the chosen lookback window.
Why it may be useful
Many traders look at monthly opens, monthly ranges, and volatility-based zones separately. This script combines those ideas into one clean open-source tool: monthly open-based statistical levels built from completed historical monthly extensions.
It helps traders visualize where price is trading relative to its own historical monthly behavior, while keeping the chart simple and readable. Indicator

AmendLogic Performance - Dynamic Matrix and Heatmap EngineOverview
AmendLogic_perf is a high-performance analytics utility library designed for Pine Script v6 strategy scripts. It automates the calculation, compounding, and visual rendering of closed and rolling equity structures into a clean, institutional-grade monthly and yearly return matrix.By separating performance rendering from your core entry/exit logic, your scripts remain lean, scannable, and modular.
Key Features
Real-Time Compounding Engine: Continuously tracks equity variations bar-by-bar, automatically computing exact monthly and yearly percentage returns ($P\&L$) alongside raw monetary value gains.
Smart History Reconstruction: Uses dynamic accumulators and arrays to handle historical lookback state tracking. It dynamically pushes and corrects current-period metrics on the final live bar (barstate.islast) without missing real-time fractional ticks.
Proportional Heatmap Scaling (f_getAlpha): Evaluates overall strategic history to locate relative historical maximums and minimums. The library automatically calibrates color transparency to match performance weight: highly profitable months or deep drawdowns receive intense color depth, while neutral periods gracefully fade into a subtle tint.
Native Ecosystem Visual Integration: Deeply integrated with the AmendLogic_css_SEC layout library. The matrix auto-adjusts its borders, cell text, and deep-space canvas framing to remain readable across both light and dark chart layouts.
How to Use (Quick Start)
To append this performance reporting dashboard directly to your strategy, reference the library at the top of your script and pass your live equity array at the final execution layer:
//@version=6
strategy("My Custom Quant Strategy", overlay=true, initial_capital=10000)
// 1. Import the performance matrix library
import Kevinroku/AmendLogic_perf_SEC/1 as perf
// ── ──
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 50))
if (longCondition)
strategy.entry("Long", strategy.long)
// 2. Pass the strategy equity into the engine at the very end
perf.ProfitTable(strategy.equity)
Interface Layout & Output MetricsPosition: Fixed to the bottom_right quadrant of your workstation screen to maintain unobstructed viewing of historical price bars.
Row Headers: Dynamically maps out historical years discovered within your dataset profile.
Column Tracks: Standardized 12-month sequence (Jan – Dec) completed by a bolded cumulative "Year" metrics tracking column.
Color Schemes: Standardizes emerald-green zones for expansion sequences and crimson-red highlights for contraction drawdowns.
Library

Dual Log Regression Channels [BigBeluga]Dual Log Regression Channels is a highly advanced multi-timeframe mathematical modeling terminal engineered for TradingView. It maps, projects, and blends two independent logarithmic regression channels directly onto your asset layout screen to deliver an institutional-grade perspective on trend structure, market cycles, and structural volume distributions.
By separating price discovery parameters into a long-term Macro Channel and an execution-focused Short Term Channel, this tool effectively resolves the classic trader conflict of assessing structural trend directions while looking for immediate micro execution setups. Rather than treating market space as flat, standard geometric lines, this engine runs an advanced curve-fitting algorithm over your data to follow the exponential nature of capital expansion and distribution.
🔵 INTUITIVE SYSTEM ARCHITECTURE & ENGINE FEATURES
1. Logarithmic Regression Curve Optimization
Non-Linear Structural Tracking: Standard linear regression struggles with volatile crypto or high-growth equity trends over massive lookback structures. This script continuously converts incoming data matrices into mathematical log-space, computes a best-fit ordinary least squares (OLS) linear progression, and converts the output back into exponential value curves.
Dual Horizons Convergence Layer: Tracks an extensive trend anchor block (defaulting to 300 bars) simultaneously with a highly responsive, high-velocity swing lookback matrix (defaulting to 50 bars). This exposes localized micro contractions occurring right at major macro boundary extremes.
Visual Deviation Spacing Bands: Channels automatically map out distinct volatility boundaries based on real-time Standard Deviation multipliers. This defines predictable mathematical risk corridors where asset expansions typically exhaust and snap back toward the median baseline.
2. Predictive Channel Extension & Real-Time Trend Direction Arrows
Dynamic Origin Trend Arrows: The engine processes a dedicated directional diagnostic framework at the precise historical start (origin node) of each lookback channel. It generates sharp, high-visibility glyph trend arrows ( ⇗ for structural uptrends and ⇘ for structural downtrends). These arrows offer an instant, real-time assessment of the mathematically calculated baseline slope, entirely bypassing visual guesswork when channels run relatively flat.
Forward-Projected Space Models: When enabled, both the Macro and Short-Term structural bands project forward into the future chart space blank zone (e.g., 50 bars ahead for Macro, 20 bars for Short-Term). This lets you visually identify intercept locations and major trend crossroads long before price action arrives.
3. Adaptive Embedded Channel Volume Profiles (VP)
Integrated Block Volume Binning Matrix: Moving beyond basic fixed or visible range volume profiles, this module segments and collects transacted volume profiles exclusively inside the exact coordinate boundaries of each respective channel.
Dynamic Coordinate-Aligned Shading Bars: The volume profile rows scale and project outward utilizing advanced polyline geometry arrays, maintaining structural alignment with the slope of the moving channel boundaries.
Point of Control (POC) Trailing Baselines: Automatically tracks and renders a crisp, high-visibility solid horizontal baseline ( POC Line ) marking the exact price bin location that attracted the highest volume concentration throughout that lookback phase.
4. Volumetric Delta Tracking Panels
Buy vs. Sell Volume Accumulation Blocks: Aggregates total execution volume during the lookback period, classifying volume based on bar polarity.
Net Order Flow Delta Percentages: Computes and prints the precise net mathematical buying/selling pressure delta inside the channel. This reveals quiet accumulation behavior or hidden distribution trends directly alongside your spatial boundary drawings.
🔵 SYSTEMATIC EXECUTION STRATEGIES & RISK INTERPRETATION
Confluence Zone Intercept Trading: Look for setups where the Short Term Channel’s outer standard deviation boundaries align directly with the Macro Channel's major structural lines. When a high-velocity micro asset trend exhausts itself at a long-term macro floor or ceiling, it marks a highly efficient, asymmetric inflection zone for trend continuation entries or macro reversals.
Volume Profile POC Mean Reversion Matrix: The volume profile POC lines show where massive institutional blocks shifted hands inside that channel's lifespan. If the market stretches thin near an upper outer boundary but net volumetric volume indicators begin shifting toward seller control, look for a swift mean-reversion move down toward the high-liquidity POC baseline node.
Trend Acceleration vs. Overextended Breakouts: When an asset forces a candle close completely outside the projected log channel boundaries, it flags an exceptional shift in trend velocity. If the Volume Delta percentage prints an explosive spike in that direction, it supports a trend acceleration play. If volume is thin, it warns you of a predatory, overextended fakeout structure that is likely to snap back into the central channel values.
🔵 INTERFACE CONFIGURATION AND PARAMETERS
Lookback & Deviation Tuning Blocks: Customize historical calculation boundaries and volatility widths separately for both trend layers to match any asset class or time frame preference.
Volume Profile Customization: Control the precise resolution of the volume profile by adjusting row count bins and max bar widths to match your specific layout.
Clean Workspace Overrides: Toggle visibility filters to hide median baselines, remove raw background asset lines, or completely customize color theme hex codes to fit cleanly within your setup without causing visual clutter.
Transform your charting environment from basic straight lines into an exponential, volume-weighted structural map with the Dual Log Regression Channels terminal. Indicator

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

Generalized Fisher Transform [LB] Concept
The Generalized Fisher Transform extends John F. Ehlers' classic Fisher Transform (2002) by introducing an adjustable shape parameter that controls the sensitivity profile of the transformation. While the original Fisher Transform maps any normalized input to a near‑Gaussian output to highlight statistical extremes, this generalized version allows traders to emphasize central regions (shape < 1) or extreme tails (shape > 1) depending on their strategy.
Mathematical Foundation
The indicator first normalizes price to a bounded range using a rolling min‑max window of length N :
x = 2 × (P - L_min) / (H_max - L_min) - 1
A signed power is then applied with a shape factor p :
x_p = sign(x) × |x|^p
The generalized Fisher Transform is computed as :
F = 0.5 × ln( (1 + x_p) / (1 - x_p) )
When p = 1 , the formula reduces to the classic Fisher Transform. Values of p < 1 amplify sensitivity near zero (central price region), while p > 1 amplify sensitivity near the edges (extreme price region). The result is smoothed by an EMA for noise reduction.
What Problem Does It Solve ?
Classic oscillators such as RSI or Stochastic use fixed non‑linear mappings that cannot adapt to different market regimes or trader preferences. The classic Fisher Transform offers a single sensitivity profile. The Generalized Fisher Transform solves this by exposing the shape parameter p , giving traders direct control over where the indicator is most responsive — near the mean or near the extremes — without changing the underlying logic or introducing additional indicators.
How To Interpret
The indicator operates in two selectable modes :
Extremes Mode – the background turns red when Fisher exceeds the upper threshold (statistically overbought), and green when it drops below the lower threshold (statistically oversold). These zones suggest potential mean‑reversion.
Direction Mode – the background turns cyan when Fisher is above zero (bullish bias) and orange when below zero (bearish bias). This mode is suited for trend‑following or directional confirmation.
In both modes, the Fisher line crossing zero indicates a shift in the price distribution relative to its recent range.
Parameters
Source – price data used for the calculation (default: close).
Normalization Period – number of bars used to compute the rolling min‑max for the normalization.
Shape Factor – exponent applied to the normalized price before the Fisher transform. 1 = classic Fisher, < 1 = center‑sensitive, > 1 = tail‑sensitive.
Smoothing Period – EMA length applied to the raw Fisher output.
Coloration Mode – switches between "Extremes" (overbought/oversold highlighting) and "Direction" (bullish/bearish highlighting).
Upper Threshold – Fisher level above which the background turns red in Extremes mode.
Lower Threshold – Fisher level below which the background turns green in Extremes mode.
Reference
Ehlers J.F., "Using the Fisher Transform", Technical Analysis of Stocks & Commodities, Vol. 20, No. 11, pp. 40‑45, November 2002.
Ehlers J.F., "Cybernetic Analysis for Stocks and Futures", Chapter 4 – The Fisher Transform, John Wiley & Sons, 2004. Indicator

ALN Sessions [NQ Stats x CantoLab]A statistical tool for NQ intraday traders built around research from NQ Stats (NQStats on twitter / nqstats.com ). Credit to NQ Stats for the original concept and data — published here as an open source indicator with permission.
Introduction
This indicator visualizes Asia and London session ranges on NQ (NASDAQ futures), then overlays statistically-derived probability levels showing how likely price is to sweep each session's high or low — based on historical pattern data compiled by NQ Stats.
How to Read the Probability Numbers
When London session closes, two horizontal lines appear — one above (London High) and one below (London Low) — each labeled with a percentage like 81.1% or 74.9%.
These numbers answer: "Historically, how often does price return to sweep this level after London closes?"
For example, if you see 81.1% on the high line, it means: in roughly 8 out of 10 historical sessions matching this pattern, price eventually traded back up to or through the London High
What happens when a level is hit?
The label updates to show in blue — confirming that level was reached
The other line's probability updates to a new conditional probability, e.g. 46% , shown in brackets
This delta tells you how the odds of sweeping the second level changed now that the first was reached
The Four Patterns (Asia vs London relationship)
The probabilities change depending on how London's range relates to Asia's range that day. The indicator detects four patterns automatically:
London Engulfs Asia — London trades both above AND below Asia's range. The most expansive session structure.
Asia Engulfs London — Asia's range fully contains London's range. London consolidates inside the prior overnight range.
London High Break — London breaks only above Asia's high, leaving Asia's low intact.
London Low Break — London breaks only below Asia's low, leaving Asia's high intact.
Each pattern has its own set of historical probabilities, so the percentages you see are always contextual to that day's Asia/London relationship — not a fixed number.
Settings
Asia Session — color, session time window, and label text
London Session — color, session time window, and label text
Label Size — Tiny / Small / Normal / Large
Border — toggle, style (Solid/Dashed/Dotted), and width for session boxes
Probability Lines — toggle, Auto color or manual color pick, style (Solid/Dashed/Dotted), and width
Daily Dividers — toggle, color, style (Solid/Dashed/Dotted), and width
Notes
Built for NQ Futures. Behaviour on other instruments is untested
All times are New York time
Probability data is derived from 10 years of NQ historical data by nqstats.com
This indicator does not provide financial advice or a complete strategy. You are responsible for how you build around and execute on this data
⚠️ Important
This is a statistical study indicator. It does not guarantee that the London high or low will be hit. Over a large sample, this is the expected behaviour based on 10 years of NQ data. It is best combined with other confluences to confirm direction — this indicator alone is not a strategy.
Indicator

Initial Balance Breaks [NQ stats x CantoLab]An open source indicator built around the Initial Balance break statistics from NQ Stats (nqstats.com). Credit to NQ Stats for the original research — published here with permission.
⚠️ Important
This is a statistical study indicator. It does not guarantee that the IB high or low will be hit. Over a large sample, this is the expected behaviour based on 10 years of NQ data. It is best combined with other confluences to confirm direction — this indicator alone is not a strategy.
What is the Initial Balance?
The Initial Balance (IB) is the price range established during the first hour of the New York equity session — 09:30 to 10:30 ET. The high and low set within this window become key levels for the rest of the trading day.
Based on 10 years of NQ data, IB breaks 83% of the time before noon and 96% of the time before 4:00 PM. The stat alone doesn't give you direction — but combined with where the IB closes relative to its own midpoint, you get a directional edge:
IB closes in the upper half → high breaks 82% of the time
IB closes in the lower half → low breaks 76% of the time
What it does
Once the IB window closes at 10:30, the indicator plots the IB High, Low and Mid as levels on the chart and automatically determines the directional bias based on where price closed within the IB range.
The expected break side is labelled with its probability and a tracking line extends forward tracking whether that level gets hit. When the level is breached the label updates to show Success or Failed in real time.
IB High — upper boundary of the initial balance range
IB Low — lower boundary of the initial balance range
IB Mid — equilibrium of the range, plotted in orange.
When price closes above mid, high break is expected.
When price close below mid, low break is expected.
Probability line — extends from IB close forward on the expected side, updates to Success or Failed when hit
Settings
IB Time — configurable session window, default 09:30–10:30 NY time
Label Size — Tiny / Small / Normal / Large / Huge
Per-level line style and width — IB High, Low, Mid and vertical markers
Auto color — IB High and Low auto-adapt to chart theme, or set manually
Notes
Built for NQ Futures. Behaviour on other instruments is untested
All times are New York time
Current version tracks directional bias from IB close relative to midpoint. The 83% before noon and 96% before 4PM time-based breach tracking and IB formation order confluence are not yet implemented
Probability data derived from 10 years of NQ historical data by NQ Stats.
This indicator does not provide financial advice or a complete strategy. You are responsible for how you build around and execute on this data
Indicator

Hour Stats [NQ Stats x CantoLab]A statistical tool for NQ intraday traders built around research from NQ Stats (NQStats on twitter / nqstats.com). Credit to NQ Stats for the original concept and data — published here as an open source indicator with permission.
What it does?
For each New York session hour (08:00 – 16:00 NY time), the indicator tracks a specific setup:
1)Price opens strictly inside the prior hour's range
2)Price breaches the prior hour high or low by at least 1 tick (0.25 pts)
3)Whether price reverts back to the current hour open before the hour closes
Only the first breach per hour is counted. Reversion is confirmed when any bar's wick touches or crosses the hour open after the breach occurs.
What gets plotted
When the setup triggers, the indicator draws the following levels for that hour:
Hour Open — the high probability reversion target. In Simple mode labelled as "High Prob. Retrace", in Advanced mode shows the statistical probability based on which 20-minute segment the breach occurred in
PHH / PHL Swept — marks the breached prior hour high or low
PHH / PHL Target — the opposite side of the prior hour range, the secondary target if reversion extends further
PHM (Prior Hour Mid) — the equilibrium of the prior hour range, visible in Advanced mode only
Sweep Mark — a small shape plotted on the candle where the breach is first detected (x, +, or diamond, configurable)
Vertical dividers — split each hour into its three 20-minute segments
Simple vs Advanced mode
Simple — shows Hour Open, swept level, and opposite target. Clean and uncluttered for execution focus.
Advanced — adds the Prior Hour Mid level and overlays per-segment reversion probabilities directly on the prior hour high and low, showing the statistical likelihood of reversion depending on when in the hour the breach occurs.
Advanced Mode - The 20-minute breakdown
Each hour is divided into three 20-minute windows (00–20, 20–40, 40–60). The timing of the breach within these windows significantly affects reversion probability.
As a general rule, first segment breaches carry the highest probability of reversion — the 09:00 hour first segment sits at 87.4% historically. Probabilities are pulled from 10 years of NQ data.
Settings
Mode — Simple or Advanced
Show History — keep or clear previous setups as new ones form
Time Filter — toggle NY session filter on/off, adjustable session window
Show Optimal Timeframe Message — on-chart warning if you are above 5min timeframe
Per-level toggles — color, style (Solid/Dotted/Dashed) and width for each plotted level
Sweep Mark — toggle, color, and shape
Notes
Built for NQ Futures. Behaviour on other instruments is untested
Best used on 1m – 5min timeframes. Warning displays above 5min, error displays at 60min and above
All times are New York time
Probability data is derived from 10 years of NQ historical data by @NQStats
This indicator does not provide financial advice or a complete strategy. You are responsible for how you build around and execute on this data
Indicator

Session Pulse [JOAT]Session Pulse
Introduction
Session Pulse is an open-source multi-session gap statistics engine that tracks, categorizes, and accumulates gap data across Asia, London, and New York trading sessions, marks every session boundary transition with labeled vertical lines on the chart, and presents a unified session statistics dashboard. It answers a specific and persistent question that many traders examine manually: how often, in which direction, and by how much does this instrument gap between sessions?
Gap behavior is one of the most systematically consistent patterns across many instruments. Session close-to-open gaps represent a measurable directional displacement — one that either fills (mean reverts) or extends (confirms momentum) in predictable proportions over sufficiently large samples. Session Pulse automates the data collection and visualization for that entire analysis, providing live cumulative statistics on gap frequency, average gap size, maximum gap, and directional bias, refreshed on every bar.
Core Concepts
1. Session Detection
Each of the three sessions (Asia, London, New York) is detected using Pine Script's time() function with a user-configurable session string and timezone. Session transitions are identified by comparing the current bar's session membership to the previous bar's membership. A session start occurs on the first bar where the current bar is inside the session and the previous bar was outside:
inAsia = not na(time(timeframe.period, asiaSess, tzString))
inLondon = not na(time(timeframe.period, londonSess, tzString))
inNY = not na(time(timeframe.period, nySess, tzString))
asiaStart = inAsia and not inAsia
londonStart = inLondon and not inLondon
nyStart = inNY and not inNY
2. Gap Calculation and Categorization
A gap is calculated at each session open as the difference between the current bar's open and the previous bar's close, expressed as a percentage of the previous close. Gaps are categorized as Gap Up (positive gap, open above prior close) or Gap Down (negative gap, open below prior close). A minimum gap percentage threshold filters out negligible noise-level gaps that do not qualify as meaningful session displacements:
gapPct = (open - close ) / close * 100
isGapUp = asiaStart and gapPct > minGap
isGapDown = asiaStart and gapPct < -minGap
3. Session Boundary Visualization
At each session start, a vertical dotted line is drawn extending across the chart, and a labeled arrow points down from the top of the price range with the session name (ASIA, LONDON, NEW YORK). This creates a clear visual demarcation of every session boundary on the chart without requiring manual annotation. The lines and labels are drawn live on the current bar and persist across the chart history:
if showSessLns and londonStart
line.new(bar_index, low * 0.9999, bar_index, high * 1.0001,
color=color.new(#01579B, 55), style=line.style_dotted,
width=2, extend=extend.both)
label.new(bar_index, high, "LONDON",
style=label.style_label_down,
color=color.new(#01579B, 50), textcolor=color.white, size=size.tiny)
4. Cumulative Statistics Accumulation
Statistics are accumulated across the full chart history using running counters and accumulators for each direction. For each session type (Asia, London, NY), the indicator tracks: total gap count by direction, cumulative gap size sum for average computation, and the maximum gap in each direction. These statistics build bar by bar and display the full historical picture at any point in time:
if isGapUp
upCount += 1
upTotal += gapPct
upMax := math.max(upMax, gapPct)
5. Unified Statistics Dashboard
A single unified table presents all gap statistics in a structured layout: Gap Up rows at the top, a separator, Gap Down rows below, a final separator, and a summary row showing total gap count and the percentage of gaps that were up (directional bias). The entire table is positioned at a single user-configurable location on the chart, eliminating split-panel layouts:
// Row 0-1: Gap Up (Count, Avg, Max)
// Row 2: Separator
// Row 3-4: Gap Down (Count, Avg, Max)
// Row 5: Separator
// Row 6: Summary (Total, Up Bias %)
Features
Three-session gap tracking: Asia, London, and New York sessions each independently tracked with configurable session strings
Session boundary vertical lines: Dotted vertical lines with session name labels (ASIA, LONDON, NEW YORK) at every session transition
Gap categorization: Gap Up and Gap Down separated by direction with independent counters, average, and maximum for each
Minimum gap filter: Configurable threshold eliminates negligible gaps below a specified percentage
Directional bias calculation: Summary row shows Up Bias % — what proportion of all detected gaps have been upward
Unified statistics table: Single table with Gap Up, separator, Gap Down, separator, and summary rows at a single configurable position
Table position selector: Top-right, bottom-right, bottom-left, or bottom-center placement
Session boundary line toggle: Session vertical lines and labels can be independently enabled or disabled
Configurable session strings: All three session time windows are fully user-adjustable for different broker timezones
Timezone input: Single timezone string applied consistently to all three session detectors
Alerts: Six alertconditions — Gap Up and Gap Down for each of the three sessions, plus Asia, London, and New York session open alerts
Input Parameters
Session Settings:
Timezone: Timezone string for session detection (default: America/New_York)
Asia Session: Session time string (default: 1800-0000)
London Session: Session time string (default: 0200-0500)
New York Session: Session time string (default: 0930-1600)
Gap Detection:
Min Gap %: Minimum gap size to qualify as a gap event (default: 0.05%)
Enable Gap Tracking toggles per session
Display:
Show Session Lines toggle
Show Stats Table toggle
Table Position: Top Right, Bottom Right, Bottom Left, Bottom Center
Session line colors for Asia, London, and New York
How to Use This Indicator
Step 1: Read the Directional Bias
The summary row of the statistics table shows Up Bias % — the percentage of all gaps that have been upward. An Up Bias above 60% on a large sample indicates this instrument has a persistent tendency to gap up at session opens. This is the first, most actionable piece of information from the table.
Step 2: Compare Average Gap Sizes
The average gap rows for Gap Up and Gap Down show the typical magnitude of each type. If the average Gap Down is significantly larger than the average Gap Up, the downside gaps — when they occur — tend to be more violent even if they are less frequent. This asymmetry has implications for stop sizing around session opens.
Step 3: Use Maximum Gap for Range Planning
The maximum gap rows show the largest gap in each direction recorded on the chart. This establishes the worst-case session displacement for this instrument at the current timeframe — useful for setting session-open risk boundaries.
Step 4: Use Session Boundary Lines for Chart Context
The vertical lines with session name labels divide the chart into session periods. On lower timeframes this makes it immediately clear which session each group of bars belongs to, providing context for patterns that occur predominantly in specific sessions.
Step 5: Monitor for Session Open Alerts
Set the session open alerts to receive notifications at each session transition. This is particularly useful on instruments where specific sessions (London or New York) have consistent volatility expansion patterns at open.
Indicator Limitations
Gap detection measures the open of the first bar inside a session versus the close of the last bar outside the session. On timeframes where session transitions do not align cleanly with bar boundaries, gaps may be slightly misattributed
On instruments that trade continuously (24/7 crypto) with no actual session close, the concept of a gap between sessions is less meaningful — the session boundaries exist but price does not actually stop between them
The minimum gap filter is a flat percentage threshold. Instruments with different typical volatility levels require different minimum gap values to produce meaningful categorization
Statistics accumulate from the beginning of the chart's data history. On very long charts or charts with intraday data going back years, early data may represent a different market regime than the current one, diluting the relevance of cumulative statistics
This indicator tracks and categorizes gaps. It does not predict gap fill probability, gap extension probability, or provide entry/exit signals
Originality Statement
Session Pulse is original in its simultaneous three-session gap tracking system with unified cumulative statistics, directional bias calculation, and session boundary visualization integrated into a single tool. This indicator is published because:
Tracking gap statistics across three named, independently configurable sessions simultaneously — with separate counters, averages, and maximums for each direction per session — in a single unified table is uncommon in published open-source Pine Script
The directional bias percentage (Up Bias %) derived from cumulative historical gap data provides a single, immediately actionable summary statistic that characterizes the instrument's session gap behavior over the entire charted history
The session boundary vertical lines with labeled session name arrows provide a visual calendar overlay that applies the same session detection logic used for gap calculation to the chart itself, creating consistency between the chart elements and the statistical table
The unified single-table layout with section separators — merging Gap Up, Gap Down, and summary into one table at one position — avoids the visual fragmentation of split multi-table layouts
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Session gap statistics reflect historical data and do not guarantee future gaps will occur with the same frequency, size, or direction. The directional bias percentage is a historical observation, not a predictive probability. Session open behavior is subject to news, earnings, and macroeconomic events that historical statistics do not account for. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Premium & Discount Zones with Bias═══════════════════════════════════════════════
PREMIUM & DISCOUNT ZONES WITH BIAS
═══════════════════════════════════════════════
A statistical mean-reversion framework that identifies premium (sell) and discount (buy) zones on your entry timeframe, derived from higher-timeframe structure. Built for intraday traders who want meaningful, stable reference levels without the noise of lower-timeframe volatility.
WHAT IT DOES
─────────────────────────────────────────────
This indicator projects five statistical zones from higher-timeframe candle distributions:
• Upper Sell Zone (95th percentile) — extreme premium, mean reversion likely
• Sell Zone (75th percentile) — standard premium zone
• EQ / Equilibrium (50th percentile) — the statistical midpoint, natural target
• Buy Zone (25th percentile) — standard discount zone
• Lower Buy Zone (5th percentile) — extreme discount, mean reversion likely
The zones are calculated from the distribution of recent higher-timeframe candles (default: 18 × 4H candles = 3 days of structure) using Monte Carlo projection. A Naive Bayes classifier runs on the current chart timeframe to produce a directional bias based on relative volume and momentum.
The key advantage: zones update only when a new HTF candle closes, giving you stable reference levels that stay fixed for hours at a time. No more chasing shifting lines on a 1m chart.
INSPIRATION & CREDIT
─────────────────────────────────────────────
This indicator is inspired by and builds on "Monte Carlo CT " by © Steversteves, published on TradingView under Mozilla Public License 2.0 at mozilla.org
The original script provided the mathematical foundation of Monte Carlo price projection combined with a Naive Bayes directional classifier. This version reimagines that concept as a premium/discount zone framework: instead of projecting bands forward across the chart, zones are derived from higher-timeframe structure and displayed as stable horizontal reference levels on the entry timeframe. Session awareness, bias table, and full visual customisation have been added for intraday traders.
Full credit and thanks to Steversteves for the original work.
HOW TO USE IT
─────────────────────────────────────────────
RECOMMENDED SETUP
Apply to your entry timeframe (1m, 3m, or 5m recommended). The zones will reflect your chosen higher timeframe (default 4H), giving you structural context without cluttering the entry chart.
CORE CONCEPT
The indicator identifies where price is statistically extended relative to recent structure. When price enters a buy or sell zone, it has a statistical tendency to revert toward the EQ (equilibrium). This is NOT a signal to blindly buy or sell — it is a confluence tool that tells you whether your chosen entry is at a statistically favourable location.
EXAMPLE SETUPS
─────────────────────────────────────────────
BULLISH SETUP (long from discount)
Wait for London or NY kill zone — the Session cell in the table will turn active
Price trades down into the Buy Zone (25th percentile) or Lower Buy Zone (5th percentile)
Check the Bias table — is it showing LONG with elevated probability?
Confirm with your own entry trigger (sweep + reclaim, break of structure, CISD, order block, etc.)
Enter long, targeting EQ as first target or the opposing Sell Zone as runner target
Why this works: you are entering long at a statistically discounted price with directional bias confirmation, targeting the statistical mean or opposing extreme.
BEARISH SETUP (short from premium)
Wait for an active kill zone
Price trades up into the Sell Zone (75th percentile) or Upper Sell Zone (95th percentile)
Check the Bias table — is it showing SHORT with elevated probability?
Confirm with your own entry trigger (failure to break, rejection candle, bearish CISD, etc.)
Enter short, targeting EQ as first target or the opposing Buy Zone as runner target
Why this works: you are selling at a statistically premium price against the likely mean reversion move.
WHAT NOT TO DO
─────────────────────────────────────────────
• Do not trade against the Bias signal. If price is in the Buy Zone but Bias shows SHORT, the setup lacks confluence — skip it
• Do not trade outside active kill zones unless you have another strong edge — the zones are most reliable during high-volume sessions
• Do not treat this indicator as a standalone entry signal. It is a confluence filter that works best combined with your existing framework
• Do not expect zones to hold every time. These are statistical probabilities, not guarantees
SETTINGS EXPLAINED
─────────────────────────────────────────────
ZONE CALCULATION
• Higher Timeframe — Controls which timeframe the zones are derived from. Default 240 (4H) balances structure and responsiveness. For longer-term reference, try Daily. For faster updates, try 60 or 120.
• HTF Candles Lookback — How many HTF candles feed the distribution. Default 18 = 3 days of 4H data. Minimum 10-12 for statistical significance. Higher values give smoother zones; lower values adapt faster to regime changes.
• Use Monte Carlo Projection — ON uses Monte Carlo simulation for distribution projection (more robust, slightly slower). OFF uses direct percentile calculation of historical returns (faster, tighter zones).
• Monte Carlo Simulations — Number of simulation runs when MC is enabled. 200 is the sweet spot. More sims give smoother bands but slower calculation.
• MC Forecast Horizon — How many HTF candles ahead to project. Default 6 × 4H = 24 hours. Increase for longer-term projection, decrease for closer zones.
• Line Offset — How far right the horizontal zone lines extend on your chart. Adjust for visual preference.
BIAS CLASSIFIER SETTINGS
• NB Train Lookback — Training window in current chart bars for the Naive Bayes classifier. Default 240.
• NB Momentum Period — ROC period for the momentum feature. Higher = smoother and less noisy on low timeframes. Default 30.
KILL ZONES
• London and NY kill zone windows in NY time. Adjust if you trade different sessions or different time zones.
COLOURS
• Fully customisable for both the zone lines and the bias table. Separate controls for background, borders, header text, label text, value text, and all highlight colours. Works on both light and dark chart themes.
TABLE DISPLAY
• Toggle table on/off
• Six position options (top/middle/bottom × left/right)
• Three size options: Normal, Small, Tiny
ALERTS
─────────────────────────────────────────────
Two alert conditions are available:
• Price entered BUY ZONE — when close drops below the 25th percentile line
• Price entered SELL ZONE — when close rises above the 75th percentile line
Set these as audio alerts if you want to focus on other charts and be notified only when price reaches a zone.
INSTRUMENTS & TIMEFRAMES
─────────────────────────────────────────────
This indicator is designed for:
• Futures (Gold, Silver, Indices, Oil, etc.)
• Forex majors
• Major crypto pairs
Best performance on liquid instruments with consistent volume. Recommended entry timeframes: 1m, 3m, 5m. Recommended higher timeframe for zones: 4H (default), 2H for faster updates, Daily for swing trading.
FINAL NOTES
─────────────────────────────────────────────
This is a confluence indicator, not a signal generator. Use it in combination with your own entry methodology — order flow reading, structure analysis, liquidity concepts, or any systematic entry framework.
The zones tell you WHERE. Your framework tells you WHEN.
Feedback and suggestions welcome. Trade safe. Indicator

Regime Transition Intelligence [AGPro Series]Regime Transition Intelligence
Most regime scripts answer a single question: "what regime are we in right now?". Regime Transition Intelligence is designed to answer a different, more actionable set of questions: how long does this regime usually last, how close to its typical end is it, how likely is it to flip within the next N bars, and where does it historically go when it does flip. Instead of treating the current regime as a standalone snapshot, it builds a living, self-calibrating statistical profile of the symbol's own regime behavior and presents it in a compact on-chart dashboard.
The engine runs on three independent axes — Trend Strength (Kaufman Efficiency Ratio + ADX), Chop Risk (Choppiness Index + inverse trend), and Volatility (ATR% normalized over a user-defined lookback). Each axis is classified as LOW / MID / HIGH, either with fixed 33/67 thresholds or with an adaptive percentile rank engine that learns the symbol's own statistical envelope over a rolling window. The three axes are then combined into a discrete regime state: TREND, MIXED, or RANGE / CHOP.
🟦 Overview / What it does
Regime Transition Intelligence is a single-pane overlay indicator that continuously classifies the market into one of three regimes and then layers a full transition intelligence stack on top of that classification:
- A per-regime dwell-time distribution learned from the chart's own completed regime blocks
- A Bayesian-style flip probability that answers "how likely is a regime change within the next N bars, given the current age"
- A 3x3 transition matrix that ranks the most likely next regime with a secondary fallback
- A fatigue score comparing the current regime's age to its historical mean (FRESH / MATURE / EXTENDED)
- A confidence decay tracker that shows whether conviction is BUILDING, STABLE, or FADING within the current regime block
- A compact history ribbon showing the last completed regime blocks with their durations
- Higher-timeframe alignment with a SYNC / DIV indicator and a live beacon at the right edge of the chart
All of this is delivered inside a single configurable dashboard, a directional transition marker layer on the chart, optional regime tint and candle coloring, and a right-edge beacon summarizing the current state.
🟣 Unique Edge / Why it is not a basic mashup
Standard regime indicators report the current state and stop there. Regime Transition Intelligence adds six distinct statistical layers that together form a transition-aware view:
1. Dwell Time Statistics — the script stores every completed regime block in a rolling array (configurable depth) and continuously updates running mean, running variance, running max, and running count per regime code. Statistics are only shown after a minimum number of blocks per regime have been collected, so the user always knows when the sample size is still too small.
2. Exponential Hazard Flip Probability — the baseline flip probability uses P(flip within H bars) = 1 - exp(-H / mean), a standard survival-analysis construction assuming constant hazard. The result is then fatigue-adjusted: if the current age is far above the historical mean, the probability is boosted; if the regime has just started, the probability is damped. The final value is capped at 95% to avoid certainty claims.
3. Transition Matrix — a 3x3 counter records every observed regime transition and is read as a conditional distribution: "given the current regime ends, which regime is it most likely to move to, and what is the runner-up". Both the top candidate and the secondary candidate are displayed with their percentages.
4. Fatigue Score — the ratio of the current age to the historical mean is bucketed into three zones (FRESH, MATURE, EXTENDED) using user-configurable thresholds. It tells the user whether the current regime is still in its early lifecycle or already past its typical end.
5. Confidence Decay Tracker — conviction in the current regime is sampled at the start of each new block and compared to the current conviction. The delta is classified as BUILDING, STABLE, or FADING, which gives an early read on whether the regime is strengthening or losing its grip.
6. History Ribbon — the last N completed regime blocks are compressed into a single compact line such as "C2·M4·C8·M1·M7*", where letters are regime codes and numbers are bar counts, with the current block marked by an asterisk. It gives immediate context on recent regime rhythm at a single glance.
None of these layers is a repackaged classic indicator. They are built on top of a trend / chop / volatility engine but deliver information that is categorically different from a simple "regime yes / no" readout.
🟢 Methodology / Conceptual data flow
1. Feature extraction. Kaufman Efficiency Ratio (net move over lookback divided by summed absolute moves) and normalized ADX are combined into a trend score. The Choppiness Index is normalized against its operating range and blended with inverse trend to produce a chop score. ATR as a percentage of price is normalized against its own lookback min/max to produce a volatility score.
2. Classification. Each score is mapped to LOW / MID / HIGH using either fixed thresholds (Static mode) or percentile rank over an adaptive lookback (Adaptive mode). The three bands are combined into a discrete regime state: TREND when trend is HIGH and chop is LOW, RANGE / CHOP when chop is HIGH, and MIXED otherwise.
3. Block tracking. Every time the regime state changes on a confirmed bar, the previous block is closed: its duration is pushed to a rolling history array and added to the running sum / sum-of-squares / count / max for its regime code. When the history array exceeds its configured depth, the oldest block is popped and its contribution is subtracted from the running totals, which keeps the statistics adaptive and non-expanding.
4. Transition matrix update. When a block closes into a new regime, the 3x3 counter is incremented at the corresponding cell, and the row total is incremented. The conditional distribution for the current regime is read from its row at display time.
5. Statistical outputs. Mean dwell, fatigue ratio, exponential-hazard flip probability, fatigue-adjusted flip probability, top and secondary next regimes, and confidence delta are all derived from the running state and rendered into the dashboard.
6. Higher-timeframe alignment. The same three-axis engine is run on a user-selected higher timeframe via request.security and compared against the current-timeframe regime; the result appears as SYNC or DIV in the header and as an optional HTF row in the dashboard.
🔔 Signals & Alerts / Interpretation
Regime Transition Intelligence is a state-mapping and statistical context tool rather than a directional buy / sell engine. The main on-chart events are:
- Regime Shift — fires when the regime state changes on a confirmed bar
- High Flip Probability — fires when the fatigue-adjusted flip probability crosses a high threshold
- Regime Fatigue Extended — fires on the transition into the EXTENDED fatigue zone
- Confidence Fading — fires on the transition into the FADING confidence zone
How to read the panel:
- Summary + Age tells the user which regime is active and how long it has been active.
- Dwell Context compares the current age to the historical mean in the form "age / mean · % of typical lifespan".
- Fatigue summarizes that comparison as FRESH, MATURE, or EXTENDED.
- Flip Probability reports the statistical odds of a regime change within the user-defined horizon.
- Next Likely names the most probable next regime with its percentage and a secondary fallback.
- Confidence and Conf Decay together tell the user whether the current read is reliable and whether conviction is rising or fading.
- History gives quick situational awareness of recent regime rhythm.
None of these rows should be interpreted as a trade instruction. They are a context layer meant to be combined with the user's own structure and entry framework.
🎛️ Key Inputs
Regime Engine Core — Trend Persistence Length, DMI/ADX Length, Chop Length, ATR Length, Volatility Normalize Lookback.
Adaptive Boundaries — Band Classification Mode (Adaptive / Static), Adaptive Lookback, Adaptive Low / High Percentile.
Transition Intelligence — Regime History Depth, Flip Probability Horizon, Min Blocks Before Stats Activate, Fatigue Fresh / Extended thresholds.
HUD — Display Mode (PRO / MINIMAL), HUD Position, Text Size, transparency controls, individual row toggles, history ribbon length.
Add-ons — Chart Regime Tint, Regime Candle Coloring (Soft / Strong), HTF Peek Timeframe, Transition Markers (location, cooldown, stagger, size, ATR offset), Live Regime Beacon (position, size, stats toggle).
🧭 How to use
1. Add the script to any chart and timeframe. The engine is tuned to work from 15m up to Daily; very low timeframes on illiquid instruments can produce unstable regime blocks and are not the intended use case.
2. Give the script time to collect blocks. Statistics stay in N/A until the configured minimum number of completed blocks per regime has accumulated. On a fresh chart or an illiquid instrument this is expected behavior, not a bug.
3. Read the dashboard top-down. Start with the three axis rows to understand the current market shape, then move to Summary and Age to see what is active and for how long, then use Dwell / Fatigue / Flip / Next Likely to place the current regime inside its historical distribution, and finally use Conf Decay and HTF to sanity-check reliability and alignment.
4. Treat EXTENDED fatigue and high flip probability as context, not as a reversal signal. Regimes can remain in the EXTENDED zone for a while before actually flipping; the statistical profile is descriptive, not deterministic.
5. Combine with structural context. The script does not know about support / resistance, order blocks, or news. It only knows about the symbol's own regime rhythm. Use it as a regime-aware filter on top of the user's existing framework.
⚠️ Limitations & Transparency
This is not a strategy and not a complete trading system. It does not predict price direction and does not generate buy or sell signals. All statistics are estimated from a rolling history of the chart's own regime blocks, so they are sensitive to the chosen engine parameters, the timeframe, and the symbol; different timeframes and different instruments will produce different statistical profiles, and that is by design.
The exponential-hazard flip probability assumes a constant hazard within the current regime, which is a simplification. Real-world regime durations are not perfectly memoryless and the fatigue multiplier is a heuristic correction, not a formal model. The probability is capped at 95% on purpose, because even a heavily aged regime cannot be considered a certainty and the script deliberately avoids certainty language.
The transition matrix is read as a conditional frequency over completed blocks; it is informative about the symbol's own past behavior and should not be interpreted as a forward-looking forecast. Very small samples produce unstable conditional probabilities, which is why stats stay in N/A until a minimum number of blocks is collected.
Regime classification itself reacts to confirmed bars and can change as new data arrives, which is expected for any regime filter. Users who prefer fully non-repainting alerts should rely on the barstate.isconfirmed-gated alert conditions provided.
📜 Risk Disclosure
Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. This indicator is provided for educational and analytical purposes only and should not be interpreted as financial advice, an investment recommendation or a solicitation to trade. Always combine multiple forms of analysis, manage position size responsibly, and never risk capital you cannot afford to lose. Indicator

Swap Engine - Pair Rotation (Z-Score) [AGPro Series]Swap Engine - Pair Rotation (Z-Score)
🔷 OVERVIEW
Swap Engine - Pair Rotation (Z-Score) transforms the log-ratio between two correlated crypto assets into a disciplined tier ladder decision framework. Rather than signalling single-asset direction, the engine measures how stretched one pair has become relative to its rolling mean and proposes rotation between the two assets when the spread reaches statistically meaningful extremes. Every decision is evaluated on confirmed Engine TF bar close, keeping suggestions non-repainting under the configured execution model.
🟣 UNIQUE EDGE
Unlike single-symbol mean-reversion or trend indicators, this engine treats the ratio itself as the tradable variable and pairs it with a full operational stack: a tiered exposure ladder (T0 to T3), an Integrity Gate that blocks entries when the pair relationship deteriorates, a Trend Regime filter that respects persistent one-sided moves, and a confirm-first execution model that converts raw signals into auditable decisions. A dedicated Signal Quality score (Q 0-100) and Integrity Score (IN 0-100) make every suggestion inspectable, not a black box.
🟢 METHODOLOGY
The engine fetches the closing price of Pair A and Pair B on the chosen Engine TF, computes the log-ratio L = ln(A / B), then derives a rolling z-score using user-defined lookback length. Entry thresholds (Z1, Z2, Z3) define the three tiers of exposure; exit thresholds (hysteresis) define when each tier is scaled back. A cost filter requires the expected mean-reversion edge to exceed a configurable multiple of estimated roundtrip cost before any entry is allowed. The Integrity Gate continuously validates rolling return correlation, ratio drift, and spread-volatility expansion, halting new entries when the pair relationship degrades.
🟡 SIGNALS & ALERTS
Each signal renders as a clearly tagged label on chart showing the action type (ENTRY / EXIT), source tier, target tier, direction (A->B or B->A), z-score snapshot, delta %, and Reason Code. Alerts are provided for: entry and exit events per direction, pending lifecycle (created, confirmed, skipped, expired), trend regime activation edges, duplicate suppression, and configuration warnings. All alerts fire on Engine TF bar close to remain consistent with the visible suggestions.
⚙️ KEY INPUTS
Pair A / Pair B: the two assets to rotate between (same quote currency recommended).
Engine TF: timeframe used for all ratio, z-score, and decision logic (240 / 4H default).
Lookback: bars used for rolling mean and standard deviation.
Entry Z1/Z2/Z3, Exit Z1/Z2/Z3: tiered thresholds for scaling in and out.
Tier Sizing (T1 / T2 / T3 %): rotation size per tier as a percentage of the active pool.
Trade Profile: preset gate behavior (Conservative, Balanced, Aggressive, Volatile Alt, High-Cost, Custom).
Integrity Gate: correlation, drift, and volatility expansion filter with configurable minimum score.
Execution Model: ASSUME (auto-advance), CONFIRM (pending + manual commit), or SIGNAL_ONLY (display only).
🔵 HOW TO USE
Start on the default BTCUSDT vs ETHUSDT pair on 4H Engine TF with the Balanced profile. Keep the chart timeframe equal to or lower than the Engine TF (the script warns otherwise). Watch the status panel for the current tier, direction, confidence strip (Q / IN / PH), and next action preview. In CONFIRM mode, a PENDING card appears when a signal fires; increase CONFIRM +1 to commit the rotation state, or SKIP +1 to discard. Use the Trade Profile dropdown to tighten or loosen effective gates without changing your base inputs.
🟠 LIMITATIONS & TRANSPARENCY
This is an indicator, not a strategy; no orders are placed and no backtest statistics are produced. Signals reflect statistical extremes in the pair's log-ratio and do not guarantee mean reversion. Performance depends heavily on pair selection - assets with persistent trends, broken correlation, or structural regime changes can cause extended adverse periods. The Integrity Gate mitigates but does not eliminate this risk. Costs, slippage, tax, and execution details are the user's responsibility; the Min Edge x filter is an estimate, not a realized-cost guarantee. Always validate on your own pair, timeframe, and account conditions before relying on any suggestion.
🔴 RISK DISCLOSURE
Trading and rotating between crypto assets involves substantial risk, including loss of capital. Past or simulated behavior of the ratio does not guarantee future results. This tool is shared for educational and analytical purposes only and does not constitute financial, investment, or trading advice. Users are solely responsible for their own decisions and should consult a qualified professional before committing capital. Indicator

Indicator

Indicator

Descriptive Statistics [Median, Quartiles, Outliers]This indicator seeks to provide insight to traders by modeling market structure using widely accepted statistical methods applied to price data. It does not predict direction; instead, it describes how current price behaves relative to its historical distribution.
It is built around non-parametric statistics, making it resistant to distortion from extreme price movements.
What it shows?
1. Median (Q2): The central equilibrium level of price distribution.
2. Quartiles (Q1, Q3): Boundaries of the “normal” trading range.
3. Interquartile Range (IQR): Measures the width of the core market structure.
4. Outlier Bands (1.5 × IQR rule): Statistical extremes where price becomes unusual relative to recent behavior.
How it works?
The indicator collects price data either through:
1. Reset Mode: Builds a new distribution each session (Daily, Weekly, Monthly, or chart timeframe).
2. Length Mode: Uses a rolling window of the last N candles.
All values are sorted to construct a real-time price distribution, from which median, quartiles, and outlier thresholds are derived.
How to use it?
1. Price inside Q1–Q3 range → normal market conditions
2. Price near Median → equilibrium / fair value zone
3. Price outside Outlier bands → statistically extreme conditions (potential exhaustion, expansion zones or news driven events)
4. Large expansions between Q1 and Q3 → increased volatility and potential momentum in either direction
Key concept?
This tool does not forecast price. It provides a distribution map of market behavior, helping traders understand structure, deviation, and statistical positioning of price.
⚠️ Note
This indicator is for educational and analytical purposes only and should not be used as standalone trading advice.
Author: TUGUME WILLIAM MUTARA Indicator

Smart Reversal EntrySmart Reversal Entry
Smart Reversal Entry is an open-source reversal-entry indicator built around one specific analytical idea:
after a short, directional three-candle expansion move, the first confirmed candle closing back in the opposite direction can create a structured reversal-entry opportunity when it appears in the correct EMA context.
This script is not designed to mark every bullish or bearish candle, and it is not intended to behave like a generic trend-following overlay, a standard candlestick-pattern indicator, or a broad “signal generator” that reacts to every small reversal. Its purpose is to measure short-term directional exhaustion in a standardized way, filter that move through an EMA context, require close-confirmed reversal behavior, and then project a fixed-risk trade structure directly on the chart for analysis and review.
The script also includes an internal background optimizer and review tables so users can compare how the same reversal framework behaves under different parameter combinations. These review tools are included to support study and comparison, not to imply future performance.
OPEN-SOURCE NOTE
This script is published open-source so users can inspect the logic directly, verify what the script is doing, and adapt parts of the workflow for their own research if they wish.
Even though the code is open, this description is intentionally detailed because many TradingView users do not read Pine Script. The goal is for a user to understand what the script does, how it works, why its parts belong together, and how it may be used in practice without having to study the code line by line.
OVERVIEW
At a high level, the script does six things:
1. It measures whether the last three candles produced a directional move large enough to matter in pip terms.
2. It checks whether price is positioned on the correct side of a selected EMA filter.
3. It requires the current candle to close in the opposite direction as confirmation of a possible reversal.
4. It maps a fixed stop-loss and a selectable take-profit multiple directly onto the chart.
5. It tracks projected trade outcomes and summarizes them in a review table and a daily PnL table.
6. It runs a hidden background optimizer over multiple EMA and move-threshold combinations so the user can compare the current settings to an internal parameter sweep.
The script is therefore meant to function as a complete reversal-entry and review framework rather than as a single-purpose candle-pattern marker.
CORE IDEA
Many reversal-style tools identify isolated candles or basic candlestick formations, but they do not standardize the market context around them.
This script is built around the idea that a reversal signal becomes more meaningful when three specific things happen together:
1. price has already made a clear short-term directional move,
2. that move is large enough to matter relative to the chosen pip structure,
3. and the next confirmed candle closes back in the opposite direction while price remains on the correct side of an EMA filter.
The model is intentionally narrow.
It does not try to identify every turning point in the market.
It does not try to classify broad market structure.
It does not use discretionary support and resistance interpretation.
It does not rely on vague candle descriptions such as “looks weak” or “looks exhausted”.
Instead, it defines reversal-entry conditions using a fixed sequence:
first measure a three-candle directional push,
then filter it using EMA context,
then require an opposite close-confirmed candle,
then project a standardized risk framework,
then review the resulting projected outcomes over time.
That narrower focus is the main reason this script exists in its current form.
WHY THIS SCRIPT IS NOT A SIMPLE MASHUP
This script combines multiple components, but they are not included simply to place more features into one publication.
Each component has a specific function inside the same analytical workflow:
- The EMA filter defines directional context.
- The three-candle move measurement defines whether a short-term push is large enough to qualify.
- The reversal candle confirmation defines the actual entry trigger.
- The pip-based stop-loss and RR framework standardize trade projection.
- The summary and daily review tables organize projected outcomes into a readable review structure.
- The internal optimizer compares the same reversal logic across multiple hidden EMA and move-threshold combinations.
These layers are interdependent.
Without the three-candle move measurement, the script would react to many small candles that do not represent meaningful short-term expansion.
Without the EMA filter, the script would lose its directional context and become a more generic reversal marker.
Without the close-confirmed reversal candle, the script would identify momentum but not the actual reversal-entry moment.
Without the risk projection layer, the user would still need to manually draw the entry, stop, and target after every signal.
Without the review tables, the user would have less organized feedback when reviewing results under the selected settings.
Without the internal optimizer, the user would see only the current configuration and not how the same logic behaves across a broader parameter range.
For that reason, the script is intended as a single reversal-entry framework, not as a random collection of unrelated features.
WHAT THE SCRIPT DOES
The script identifies reversal-entry setups using a strict, rule-based structure.
Long setup requirements:
- price must be above the selected EMA,
- the prior three candles must all be bearish,
- the combined bearish move across that sequence must reach the minimum pip threshold,
- the current candle must close bullish.
Short setup requirements:
- price must be below the selected EMA,
- the prior three candles must all be bullish,
- the combined bullish move across that sequence must reach the minimum pip threshold,
- the current candle must close bearish.
When a valid signal appears, the script can:
- place a BUY or SELL label,
- project a fixed stop loss in pips,
- project a take-profit level using the selected RR multiple,
- draw TP/SL boxes,
- draw an entry line,
- keep historical projected trades visible for later review,
- summarize projected outcomes in a summary table,
- summarize recent daily projected behavior in a daily PnL table.
The script also evaluates an internal optimizer in the background. That optimizer tests multiple EMA lengths and minimum-move combinations using the same reversal logic and displays the best-performing parameter combination inside the summary table over the shared analysis window.
HOW THE SCRIPT WORKS
1) EMA CONTEXT FILTER
The script uses a single EMA as a directional filter.
For long setups:
price must close above the selected EMA.
For short setups:
price must close below the selected EMA.
This does not turn the script into a pure trend-following system. Instead, it acts as a directional context filter so that reversal entries are only considered when price is positioned on the chosen side of the EMA.
In practical terms, the EMA filter is used to reduce context-free reversal signals. A bullish candle appearing after a bearish push is not enough by itself. The script still wants price to be trading above the selected EMA for longs, and below it for shorts.
2) THREE-CANDLE DIRECTIONAL MOVE MEASUREMENT
The script looks at the three candles immediately before the signal candle.
For a long setup:
those three candles must all be bearish.
For a short setup:
those three candles must all be bullish.
The script then measures the total directional move across that sequence in pip terms.
For long setups, it calculates the bearish move from the open of the first candle in the sequence to the close of the third bearish candle.
For short setups, it calculates the bullish move from the open of the first candle in the sequence to the close of the third bullish candle.
That move must be at least as large as the user-defined “Minimum 3-Candle Move (Pips)” setting.
This is one of the key parts of the script’s logic. It ensures that the setup is not based on three arbitrary candles, but on a directional push that is large enough to meet the minimum threshold selected by the user.
3) REVERSAL CANDLE CONFIRMATION
After the three-candle directional push is identified, the current candle must close in the opposite direction.
For long setups:
the current candle must close bullish.
For short setups:
the current candle must close bearish.
This requirement is intentionally strict. The script does not treat intrabar movement or unfinished candles as a valid signal. Signals are confirmed only when the bar closes.
This matters because a reversal that looks valid intrabar can disappear by the close. By waiting for close confirmation, the script reduces premature signal marking.
4) COOLDOWN FILTER
The script includes a cooldown period between signals.
Once a signal has fired, a new signal is not allowed until a defined number of bars has passed. In the current implementation, that cooldown is handled internally.
The purpose of this filter is to reduce signal clustering and prevent the chart from producing multiple nearby entries from the same short-term market behavior.
5) PIP-BASED RISK PROJECTION
When a valid signal appears, the script creates a projected trade framework using:
- entry at the signal close,
- a fixed stop-loss distance in pips,
- a take-profit level based on the selected risk/reward multiple.
This makes the projection logic standardized across signals.
For long setups:
- stop loss is placed below entry,
- take profit is placed above entry.
For short setups:
- stop loss is placed above entry,
- take profit is placed below entry.
The script can draw:
- entry line,
- TP box,
- SL box,
- BUY / SELL label,
- TP / SL hit labels.
This projection layer is not meant to claim that a setup will succeed. Its purpose is to reduce manual chart annotation and make the behavior of the signal model easier to inspect after the fact.
6) SAME-BAR TP/SL PRIORITY RULE
The script uses a strict and conservative rule when both target and stop would appear to be touched on the same bar after entry:
if TP and SL are both reached on the same bar, SL takes priority.
This is an important implementation detail because it directly affects projected statistics. It makes the review logic more conservative and avoids optimistic ambiguity when bar data alone cannot determine exact intrabar order.
7) SHARED ANALYSIS WINDOW
The script uses a shared analysis window internally.
Projected results and optimizer comparisons are evaluated over a rolling historical range rather than over the full unlimited chart history. This keeps the internal review process more controlled and makes the optimizer comparison consistent inside the same defined lookback window.
8) INTERNAL OPTIMIZER
One of the script’s more advanced components is the internal optimizer.
The optimizer runs in the background and is intentionally not exposed as a user-facing optimization panel. Instead of asking the user to manually test every variation, the script internally evaluates combinations of:
- 10 EMA values,
- 10 minimum-move thresholds.
That produces 100 total internal combinations.
Each combination uses the same reversal logic:
- EMA context,
- three-candle directional sequence,
- minimum move threshold,
- opposite close-confirmed candle,
- same stop-loss and RR structure.
The optimizer then tracks projected wins, losses, net R, gross profit, and gross loss for each combination, and the summary table displays the current best combination based on the script’s internal comparison rules.
This optimizer is not intended to present a “perfect setting”. It is a comparative review aid that helps the user understand how the same reversal framework behaves across multiple hidden parameter combinations.
WHAT MAKES THIS SCRIPT ORIGINAL
This script uses familiar technical-analysis building blocks such as:
- EMA filtering,
- candle-sequence logic,
- pip-based move measurement,
- fixed stop-loss projection,
- risk/reward mapping,
- performance review tables.
Those building blocks are not original by themselves.
The originality of this script is not in inventing a completely new primitive indicator. The originality lies in how these familiar elements are arranged into one tightly defined reversal-entry workflow:
EMA context
→ three-candle directional expansion
→ minimum pip-threshold validation
→ opposite candle close confirmation
→ fixed-risk trade projection
→ on-chart review
→ internal background parameter comparison
That full sequence is the main reason this script exists as its own publication.
It is not intended to be simply another EMA filter, another candlestick marker, another TP/SL visualizer, or another optimizer dashboard. It is specifically a short-term reversal-entry framework that combines directional context, expansion measurement, confirmation logic, risk mapping, and review in one workflow.
WHAT APPEARS ON THE CHART
Depending on settings, the chart may display:
- EMA line,
- BUY labels,
- SELL labels,
- signal-bar background highlights,
- entry line,
- TP box,
- SL box,
- TP hit labels,
- SL hit labels,
- summary table,
- daily PnL table.
Users who want a cleaner chart can disable some visual layers and keep only the ones most relevant to their workflow.
HOW TO USE THE SCRIPT
A practical workflow is:
1. Add the script to a standard candlestick chart.
2. Select the EMA length you want to use as directional context.
3. Set the minimum three-candle move threshold in pips.
4. Set the pip preset correctly for the instrument, or use manual pip size if needed.
5. Choose the stop-loss distance in pips.
6. Select the RR mode used for take-profit projection.
7. Wait for a valid long or short setup to appear.
8. Use the projected entry, stop, and target structure as a chart-analysis framework rather than as a blind instruction.
9. Review projected trade behavior in the summary table and daily table.
10. Compare your selected settings with the optimizer’s best internal combination, but do not treat the optimizer output as a guaranteed best future configuration.
This script is best understood as a structured decision-support and reversal-review tool, not as a self-sufficient trading system.
SETTINGS REFERENCE
Signal Settings
- EMA Length: sets the EMA used as the directional filter.
- Minimum 3-Candle Move (Pips): defines how large the directional three-candle move must be before a reversal candle can qualify.
Pip Settings
- Pip Preset: selects a predefined pip-size interpretation for common instrument types.
- Manual Pip Size: allows direct control when the selected symbol needs a custom pip conversion.
Risk Management
- Stop Loss (Pips): sets the fixed stop-loss distance in pip units.
- Take Profit RR: sets the projected target multiple relative to the stop-loss distance.
Visual Settings
- Show Buy/Sell Labels: shows or hides the signal labels.
- Highlight Signal Bars: adds background color to signal bars.
- Show Entry Line: shows or hides the projected entry line.
- Show TP/SL Hit Labels: controls whether projected outcomes are labeled.
- Show TP Hit Labels: controls TP hit labels specifically.
- Show SL Hit Labels: controls SL hit labels specifically.
Summary Table
- Show Summary Table: enables or disables the main review table.
- Table Position: sets the table location.
- Table Text Size: controls summary-table text size.
Daily PnL Table
- Show Daily PnL Table: enables or disables the daily review table.
- Daily Table Position: sets the daily table location.
- Daily Table Text Size: controls daily-table text size.
INTERNAL LOGIC NOTES
The current code also includes internal settings that are not exposed as user-facing optimization controls. These include:
- signal cooldown,
- shared analysis window,
- maximum stored closed-trade visuals,
- hidden optimizer activation,
- internal optimizer parameter combinations.
These internal elements exist to keep the public interface simpler while still allowing the script to maintain consistent review behavior in the background.
IMPORTANT PRACTICAL NOTE ON PIP SIZE
The script uses pip-based calculations for:
- the minimum three-candle move,
- stop-loss distance,
- take-profit distance,
- optimizer comparison logic.
Because of that, correct pip interpretation is extremely important.
If signals appear too frequent, too rare, too compressed, or visually inconsistent for the instrument being analyzed, the first setting to verify is Pip Preset or Manual Pip Size.
This matters especially for:
- gold symbols,
- 5-digit forex symbols,
- JPY forex pairs,
- indices and CFD-style instruments,
- custom broker symbols with unusual decimal formatting.
LIMITATIONS AND SHORTCOMINGS
This script has important limitations:
- It is a short-term reversal model, not a full market-structure engine.
- It only evaluates one specific reversal pattern based on a three-candle directional push and an opposite close-confirmed candle.
- It does not use support/resistance structure, volume profile, or discretionary context.
- It relies on pip conversion, so poor pip settings can distort signal behavior.
- The internal optimizer compares parameter combinations only inside the defined shared analysis window.
- The optimizer output is a comparative review tool, not a guarantee that the best historical combination will remain best in future market conditions.
- Projected results depend on the script’s own simplified outcome logic.
- If TP and SL are both touched on the same bar, SL is prioritized by design, which makes the logic more conservative but also affects outcome statistics.
- Historical projected trades and review metrics are chart-based review aids, not proof of tradable real-world execution.
- No reversal-entry model can remove all false signals or all regime-dependent behavior.
For those reasons, the script should be used as a structured analysis and review framework, not as a promise of future profitability.
WHO THIS SCRIPT MAY BE USEFUL FOR
This script may be useful for traders who:
- want a rules-based short-term reversal-entry model,
- want EMA-based directional context,
- want a minimum expansion threshold before a reversal is allowed,
- want fixed-risk trade projection on the chart,
- want review tables for projected outcomes,
- want background comparison of multiple EMA and move-threshold combinations.
It may be less suitable for traders who:
- want a broad trend-following system,
- want a discretionary support/resistance engine,
- want a multi-pattern candlestick library,
- want a fully automated strategy with no outside confirmation,
- want outcome metrics interpreted as live performance promises.
DISCLAIMER
This script is provided for educational and informational purposes only.
It does not constitute financial, investment, or trading advice.
Market conditions change, historical behavior does not guarantee future results, and users should perform their own analysis, validation, and risk management before using the script in live decision-making. Indicator

Volatility Z-Score [NovaLens]Volatility Z-Score is a statistical volatility indicator that measures how far the current ATR deviates from its historical average, expressed in standard deviations. Built on the Z-Score method used by quantitative desks to detect anomalies, it self-normalizes across any asset and timeframe - no parameter guessing needed.
◉ HOW IT WORKS
Most traders watch ATR to measure volatility - but raw ATR numbers are meaningless without context. ATR = 50 tells you nothing unless you know the asset's history. Is that high? Low? Normal?
The Z-Score solves this by standardizing ATR against its own rolling distribution:
Z = (ATR_current - ATR_mean) / ATR_stddev
A Z-Score of +2 means current ATR is two standard deviations above the historical mean - statistically extreme. A score of 0 means volatility is exactly average. This is the same standardization method used across quantitative finance to detect regime changes and anomalies.
◈ HOW TO READ IT
• Z > +2 : Statistically extreme volatility. Breakout in progress or capitulation event. Consider tightening stops or waiting for mean reversion.
• Z between −1 and +1 : Normal volatility range. Trade your usual setups with standard risk parameters.
• Z < −2 : Unusually quiet market. Compression before expansion. Watch for pre-breakout positioning opportunities.
✦ USE CASES
• Filter entries - only take trades when volatility is in your preferred regime (e.g., avoid extreme Z for trend-following)
• Time exits - extreme Z-Scores often precede reversals or consolidation phases
• Risk management - scale position size inversely with Z-Score: smaller in high-vol, larger in low-vol
• Regime detection - sustained high or low Z indicates a volatility regime shift, not just noise
• Combine with trend tools - high Efficiency Ratio + low Z-Score = quiet strong trend about to expand
⚙ SETTINGS
• ATR Period - Period for Average True Range calculation. Higher values smooth the ATR, lower values make it more responsive to recent price action.
• Z-Score Lookback - Number of bars for computing mean and standard deviation of ATR. Longer lookback = more stable reference, shorter = faster regime detection.
△ LIMITATIONS
Z-Score assumes a roughly normal distribution of ATR values. In assets with structural volatility shifts (e.g., post-halving crypto), the lookback window may not capture the new regime quickly. Works best on liquid instruments with sufficient history. Not a directional signal - tells you about volatility magnitude, not trend direction.
⌁ NOTES
• Based on standard Z-Score normalization - a foundational technique in quantitative finance
• Validated against Python implementation (1.000 correlation via PyneCore)
• Open-source - read the code and verify the math
• Built for traders who want volatility context in standardized units, not raw ATR values Indicator

Quant Reversal Index [AlgoPoint]Overview
The AlgoPoint Quant Reversal Index is a normalized (0-100) oscillator designed to measure mean-reverting tendencies in financial time series. By combining the Hurst Exponent, an Autoregressive AR(1) Half-Life model, and Ornstein-Uhlenbeck (OU) boundaries, this indicator evaluates whether an asset is in a trending or ranging regime and calculates its proportional deviation from a dynamic historical mean.
Mathematical Core & Components
This indicator relies on three primary quantitative concepts:
1. Hurst Exponent ( H ) : Approximated using the log variance ratio of price differences over distinct time lags. It determines the current market regime:
- H < 0.5: Indicates a Mean Reverting (ranging) regime.
- H > 0.5: Indicates a Trending (momentum) regime.
2. AR(1) Half-Life : Calculates the estimated time (in bars) it takes for the price to revert to its mean. This is derived from the linear regression slope (covariance/variance) of price changes against previous prices. This dynamic half-life dictates the lookback length for the oscillator's mean and standard deviation.
3. Ornstein-Uhlenbeck (OU) Conversion : Calculates the mean ($\mu$) and standard deviation ($\sigma$) over the dynamic half-life period to establish upper and lower OU boundaries. The current price is then normalized into a 0 to 100 index based on its position relative to these boundaries.
Visual Elements & Interpretation
- The 0-100 Scale : * A value of 50 represents the dynamic mean ($\mu$).
- A value of 0 represents the Lower OU boundary (Standard Deviation limit).
- A value of 100 represents the Upper OU boundary.
- Values extending beyond 0 or 100 highlight statistical extremes.
- Dynamic Regime Background : When the Hurst Exponent is strictly below the user-defined threshold (default 0.5), the oscillator's background is highlighted. This visually confirms that the asset exhibits stationary, mean-reverting properties. If the background is not highlighted, the asset is considered to be trending, and mean-reversion logic is disabled.
- Signal Generation : The indicator plots "Buy" and "Sell" labels strictly when the market is in a confirmed mean-reverting regime ($H < 0.5$) AND the oscillator crosses back into the 0-100 range from an extreme (e.g., crossing above 0 or crossing below 100). All signals use barstate.isconfirmed to prevent repainting.
- Quant Dashboard : Displays real-time data for the current market regime, exact Hurst Exponent value, and the estimated Half-Life in bars.
How to Use
- Wait for the background to highlight, confirming a mean-reverting regime.
- Monitor the index as it reaches extreme values (< 0 or > 100).
- A statistical reversion is indicated when the index crosses back inside the core 0-100 range.
- Signals should be combined with broader macro analysis and strict risk management protocols.
Alerts
The indicator includes standard alert conditions and dynamic JSON webhook strings for automated trading systems, providing variables such as asset name, price, hurst value, and half-life duration on signal generation. Indicator

Nova Statistical Filtering Oscillator [Pineify]Nova Statistical Filtering Oscillator - Advanced Mean Reversion Trading Tool
A sophisticated statistical oscillator that identifies overbought and oversold market conditions using Z-Score normalization and dynamic volatility bands
The Nova Statistical Filtering Oscillator (NSFO) is an advanced technical analysis tool designed to help traders identify potential mean reversion opportunities in financial markets. By combining statistical price normalization with adaptive smoothing techniques, this indicator provides a unique approach to detecting extreme price conditions and anticipating momentum reversals.
Z-Score based statistical analysis
Triple Exponential Moving Average (TEMA) smoothing
Dynamic volatility bands
Automatic mean reversion signal generation
Gradient color visualization
Customizable parameters
Statistical overbought/oversold detection
Noise reduction through TEMA smoothing
Adaptive bands that adjust to market volatility
Clear buy and sell signal indicators
Visual gradient coloring for quick analysis
Configurable alert conditions
The NSFO operates through a sophisticated three-step statistical process that transforms raw price data into actionable trading signals.
Step 1: Z-Score Calculation
The indicator first calculates the Z-Score, which measures how many standard deviations the current price is from its historical mean. This statistical normalization allows traders to objectively identify when price has moved to statistically extreme levels. The formula uses a configurable lookback period (default 20 bars) to compute both the simple moving average (mean) and standard deviation. A Z-Score greater than +2 or less than -2 indicates statistically rare extreme conditions, occurring approximately only 5% of the time.
Step 2: TEMA Smoothing
Raw Z-Score values can be volatile and produce choppy signals. The NSFO applies Triple Exponential Moving Average (TEMA) smoothing to reduce market noise while maintaining responsiveness. TEMA combines three successive EMAs using the formula: 3×EMA1 - 3×EMA2 + EMA3, achieving smoother results with less lag compared to traditional moving averages.
Step 3: Dynamic Volatility Bands
Unlike static overbought/oversold levels, the NSFO creates adaptive bands based on the volatility of the smoothed oscillator itself. This self-referential approach automatically adjusts to changing market conditions - becoming wider during volatile markets and narrower during calm periods. The bands are calculated using the standard deviation of the smoothed oscillator multiplied by a configurable factor (default 2.0).
The NSFO is built on the fundamental principle of mean reversion - the statistical observation that prices tend to return to their average over time. This concept has been validated through decades of market research and forms the basis of many successful trading strategies.
Statistical Extremes as Trade Setups : When the oscillator reaches the upper or lower bands, it indicates the price has moved to a statistically extreme level. These conditions often precede reversals as the market corrects itself back toward the mean.
Momentum Confirmation : The gradient coloring system provides instant visual feedback on current momentum. When the oscillator transitions from extreme levels toward the center, it confirms that momentum is shifting and the reversal may be gaining strength.
Time Frame Flexibility : The NSFO performs well across various time frames, from intraday charts to weekly frames. Shorter time frames generate more signals but require tighter risk management, while longer time frames produce fewer but potentially more reliable signals.
The NSFO uniquely combines three distinct technical concepts into a cohesive system:
Statistical Analysis (Z-Score) : Provides the mathematical foundation for identifying extreme price conditions using probability theory. This transforms subjective "overbought" or "oversold" labels into quantifiable statistical measurements.
Moving Average Smoothing (TEMA) : Reduces the inherent noise in raw statistical values while maintaining sensitivity to genuine price movements. The triple-layer EMA approach minimizes lag that typically affects simple moving averages.
Volatility-Based Bands : Creates adaptive thresholds that automatically adjust to current market conditions. This dynamic approach outperforms fixed-level indicators by accounting for the reality that market volatility changes over time.
The synergy between these three components creates a robust system where each element addresses a weakness in the others. The Z-Score provides statistical rigor, TEMA adds smoothness for actionable signals, and dynamic bands ensure the indicator remains effective across varying market conditions.
The Nova Statistical Filtering Oscillator offers several distinctive features that set it apart from traditional technical indicators:
Self-Referential Adaptation : The volatility bands are calculated from the oscillator's own standard deviation, creating a truly adaptive system that automatically adjusts to current market conditions without manual parameter changes.
Gradient Visualization : The color gradient provides at-a-glance understanding of current market position relative to statistical extremes, making it easy to identify both extreme conditions and transitions.
Zero Baseline Clarity : The central baseline at zero represents the statistical mean, providing an immediate visual reference point for understanding whether price is above or below its historical average.
Clean Signal Generation : Buy and sell signals are generated only when the oscillator crosses back from extreme levels, filtering out premature entries and focusing on confirmed reversals.
Using the NSFO effectively requires understanding both its signals and its limitations. Here's how to integrate it into your trading strategy:
Identifying Overbought Conditions : When the oscillator crosses below the upper band (red line), it indicates the price has extended statistically above its average. This suggests a potential selling opportunity as the market may revert toward the mean.
Identifying Oversold Conditions : When the oscillator crosses above the lower band (green line), it indicates the price has dropped statistically below its average. This suggests a potential buying opportunity as the price may bounce back toward the mean.
Signal Confirmation : Wait for the oscillator to cross back toward the center (zero line) before entering a trade. This confirms the reversal is underway rather than just touching the extreme level.
Trend Context : Always consider the broader trend direction. In strong trending markets, the oscillator may remain at extreme levels for extended periods. Use additional trend indicators for confirmation.
Important Note: No indicator guarantees profitable trades. Always use proper risk management and consider combining NSFO with other technical or fundamental analysis tools for better decision-making.
The NSFO provides several customizable parameters to suit different trading styles and market conditions:
Statistical Window (default: 20) : Controls the lookback period for calculating mean and standard deviation. Higher values produce more stable readings but respond slower to price changes. Lower values are more responsive but may generate more false signals.
Smoothing Length (default: 10) : TEMA period for reducing noise in the Z-Score. Higher values create smoother lines with more lag, while lower values are more responsive but potentially noisier.
Bands Multiplier (default: 2.0) : Controls the width of dynamic bands in standard deviations. Higher values create wider bands, reducing false signals but potentially missing some opportunities. Lower values generate more signals but with increased noise.
Color Customization : Traders can customize bullish (green) and bearish (red) colors to match their visual preferences or other indicators in their chart setup.
The Nova Statistical Filtering Oscillator represents a sophisticated approach to identifying statistical extremes in financial markets. By combining Z-Score normalization with TEMA smoothing and dynamic volatility bands, it provides traders with a powerful tool for detecting potential mean reversion opportunities.
Its adaptive nature ensures effectiveness across various market conditions, while the clear visual signals make it accessible to traders of all experience levels. Whether used as a primary trading system or as a confirmation tool alongside other indicators, the NSFO offers a unique perspective on market dynamics that can enhance your trading decisions.
Remember to always test any new indicator thoroughly on historical data before using it with real capital, and maintain disciplined risk management practices regardless of the signals generated.
This indicator is provided for educational and informational purposes only. Past performance does not guarantee future results. Trading financial markets involves substantial risk, and you should only trade with capital you can afford to lose. Always conduct your own research and consider your financial situation before making any trading decisions.
Indicator

Indicator

Sigmoid Risk AllocatorThe Sigmoid Risk Allocator is a dynamic position sizing indicator that tells you how much of your capital to allocate based on current market conditions. Unlike simple "risk-on/risk-off" signals, this indicator gives you smooth, gradual transitions based on a sigmoid function.
Why a Sigmoid Curve?
Most position sizing approaches use fixed thresholds: "If drawdown > 20%, buy. Otherwise, don't." This creates all-or-nothing decisions.
Using the sigmoid (S-curve) makes this decision different. It creates a smooth transition where:
Small drawdowns → Stay near your baseline allocation
Moderate drawdowns → Gradually increase exposure
Large drawdowns → Approach maximum allocation
The sigmoid curve naturally "saturates" at the extremes, preventing you from going all-in too early or panicking out too fast. This is very useful to meek traders psychology and risk management in check.
What's a Sigmoid Function?
The sigmoid function is a mathematical S-curve defined as:
σ(x) = 1 / (1 + e^(-x))
This formula takes any input value and smoothly maps it to a number between 0 and 1. The curve has three key properties that make it ideal for position sizing in investing:
Smooth transitions: No sudden jumps. Allocation changes gradually.
Saturation at extremes: The curve flattens near 0 and 1, preventing overreaction and overexposure.
Sensitive in the middle: Most of the action happens around the midpoint.
To convert this into an allocation percentage, the indicator uses:
Allocation = α_min + (α_max - α_min) × σ(k × (Risk - Midpoint))
Where:
- `α_min` = Your minimum allocation (default 50%)
- `α_max` = Your maximum allocation (default 100%)
- `Risk` = Current risk metric (drawdown %, volatility, or Kelly %)
- `Midpoint` = The risk level where allocation sits halfway between min and max (default 15%)
- `k` = Steepness—how quickly allocation changes around the midpoint
Example : With defaults, if drawdown hits 15% (the midpoint), your allocation will be 75% (halfway between 50% and 100%). As the drawdown increases beyond 15%, the allocation curves toward 100%. As it decreases toward 0%, allocation curves toward 50%.
Cool, isn't it?
Asymmetric Response: Fast In, Slow Out
The indicator uses different steepness values for scaling in vs. scaling out. This is great to increase trend following. This is something I'm proud of too in this indicator.
k_increase = 30 (steep curve): When drawdowns appear, allocation ramps up quickly to catch the opportunity
k_decrease = 5 (slower curve): When conditions normalize, allocation decreases slowly to avoid selling the rebound
This asymmetry reflects how markets behave—drawdowns often overshoot fundamentals (rewarding quick entries), while recoveries tend to be more orderly (rewarding patience on exits).
Three Risk Metrics
You can choose what drives your allocation:
Drawdown (Default)
Volatility - Scales your position inversely to current market volatility.
Kelly Criterion - Automatically calculates optimal position size. The indicator applies a conservative "half Kelly" by default.
Use Cases
Position sizing for swing trading or trend following
Risk management overlay for any existing strategy
Drawdown-based DCA (dollar cost averaging) decisions
Volatility-adjusted exposure management
Feel free to provide feedback and share your thoughts!
- Henrique Centieiro Indicator
