OPEN-SOURCE SCRIPT

Precedent [ThrowMaster]

1 607
===============================================================
WHAT IT IS
===============================================================

Precedent does not predict. It measures.

Every time a defined market event confirms on your chart, Precedent
records what price actually did over the following N bars. Once enough
comparable records have accumulated, it displays the empirical
distribution of those recorded outcomes: how far price travelled, how
often it reached a given distance, and how many bars that took.

The question it answers is narrow and deliberately so:

"On this symbol, on this timeframe, when this kind of event happened
at this kind of price level in this kind of market condition, what
followed afterwards, and across how many cases?"

Every number shown is measured from the visible history of the chart you
are looking at. Nothing is imported from another market, no outcome
percentages are hard-coded, and no distribution shape is assumed. If the
chart has not yet produced enough comparable cases, the indicator stays
silent and tells you how many it has.

This is a context tool. It produces no buy or sell signals, no entry
prices, and no stop levels, and it is not designed to be used as one.
Please read the section titled THE MOST IMPORTANT WARNING before using
it on a live chart.


===============================================================
HOW IT WORKS
===============================================================

1. LEVEL MAP

A running inventory of prices that carry structural meaning is
maintained bar by bar:

- Swing pivots confirmed with a symmetrical left/right lookback
(default 21 bars each side for external structure, 5 for internal).
- Equal highs and equal lows: when a new pivot lands within the merge
tolerance of an existing level, that level's touch count increases
rather than a second level being created.
- Unfilled fair value gaps: a three-bar imbalance where the current
bar's low is above the high from two bars ago (or the mirror for
the bearish case). Each additional gap overlapping the same price
adds to that level's weight, so three gaps stacked at one price
are recorded as one level carrying three factors.
- Order blocks: the extreme of the last opposite-coloured candle
immediately before a displacement bar, where displacement means a
body in the top 15 percent of the last 100 bodies AND the move
takes out the most recent internal pivot. Displacement alone is not
enough; it must be tied to a structural break.
- Previous day and previous week high and low, requested with a
one-bar offset so no unclosed higher-timeframe data is used.

Each level accumulates a WEIGHT equal to the number of independent
factors coinciding there, plus a bonus for repeated touches and for age
beyond 200 bars. Two factors closer together than the merge tolerance
(default 0.25 x ATR) are treated as one level with two factors, never as
two levels. This prevents an order block that naturally sits inside a
fair value gap from being counted twice.

A level whose weight reaches the MAJOR threshold (default 4) is
classified MAJOR; weight 1 to 3 is MINOR; anything else is NONE.

Note on interpretation: a heavily touched level is treated as more
SIGNIFICANT, not as stronger. Repeatedly tested highs and lows are
exactly the prices that attract sweeps. The indicator does not assume
which way that resolves; it measures what actually followed.

2. EVENT CLASSES

Six event types are detected. Every one of them locks its state at bar
close.

SWP Sweep Price trades beyond a mapped level and closes back
inside it, with a wick in the top quartile of the
last 100 wicks on that side.
SHF Shift A close beyond the most recent confirmed external
swing, in either direction (break of structure or
change of character).
SQZ Squeeze Bollinger Bands (20, 2.0) contract entirely inside
Keltner Channels (20, 1.5 x ATR) for at least five
consecutive bars, then expand back out.
CLX Climax Volume in the top 5 percent of the last 200 bars
combined with a bar range in the top 10 percent.
Where volume is unavailable, range plus body size is
used instead and the dashboard states which.
REJ Reject A bullish or bearish engulfing bar, or a pin bar with
a wick in the top quartile of the last 100, but only
when it occurs at a mapped level. A rejection candle
floating in empty space is not recorded at all.
DIV Divergence Price makes a lower low while cumulative flow makes a
higher low, or the mirror case, measured at confirmed
pivots. Flow is signed by body position within the
bar range and scaled by volume where volume exists.

Divergence is measured against volume-weighted flow, not against an
oscillator. An oscillator derived from price and then compared back to
price adds no independent information; volume is a separate data source.

Two events of the same class are never recorded closer together than the
full horizon. This is a deliberate statistical constraint: it costs
sample size, and it buys the guarantee that no two stored outcomes share
an overlapping future.

3. CONTEXT SCORE

Three voices contribute to an additive score from 0 to 100. Nothing
gates. No voice can block a signal; each only adds weight.

STRUCTURE 35 Whether the recent sequence of confirmed swing highs
and lows agrees with the event's direction.
FLOW 30 The percentile rank of the bar's signed flow over the
last 200 bars, cut to one fifth when its sign
disagrees with the event direction.
HTF 35 Whether the higher timeframe close sits above or below
its own 50-period EMA, in agreement with the event.

The score is then discounted by regime and renormalised back to a 0-100
scale, so scores remain comparable across regimes:

RANGE structure x 0.70 (structure breaks constantly and means
little inside a range)
TRANSITION higher tf x 0.80 (higher timeframe bias is least
reliable while it is turning)
TREND flow x 0.85 (large volume is ordinary in a trend
and therefore less informative)

One correction is applied automatically: Climax and Divergence are
themselves defined from flow, so for those two classes the flow weight
is halved and the freed weight is split evenly between structure and
higher timeframe. Without this, the flow voice would confirm an event
that flow itself created.

The score is converted into a two-level tier by comparing it to the 60th
percentile of past scores for the same event class on this chart. There
is no fixed cut-off number.

4. SIGNATURE AND BACKOFF

Each recorded event is filed under a discrete key:

event class x location class x regime x direction x score tier

Direction is never merged at any level, because upward and downward
outcomes are not symmetrical.

When a new event confirms, the engine looks for stored outcomes sharing
that key. If fewer than the minimum sample (default 20) exist, it drops
the finest component and looks again:

L3 event + location + regime + direction + tier
L2 event + location + regime + direction
L1 event + regime + direction
L0 event + direction

The first level with a sufficient sample is used, and the dashboard
always states which level was used and how many records it contained.
If even L0 is short, nothing is drawn and the dashboard shows
CALIBRATING with the current count.

Seeing L1 or L0 rather than L3 is normal, not a fault. Non-overlapping
sampling produces a limited number of independent cases per chart, and
the backoff exists precisely to handle that honestly rather than
displaying a percentage built on four observations.

5. OUTCOME STORE

For each recorded event the engine tracks, for the following H bars
(default 24):

- excursion at H/4, H/2, 3H/4 and H, expressed in R where R is the
ATR(14) value at the event bar
- maximum favourable and maximum adverse excursion
- the bar number at which the move first reached +1R, +2R and +3R,
or zero if it never did

The record is written to the store only after H bars have fully elapsed.
A projection displayed today is therefore built exclusively from events
that had already finished before it was issued. This is a structural
property of the design, not a discipline that has to be maintained.

6. WHAT IS DRAWN

- An empirical quantile fan. The outer envelope traces the 5th and
95th percentiles of the matched outcomes at each of the four
checkpoints; the inner envelope traces the 25th and 75th; the
dashed centre line traces the 50th. The shape is asymmetric and
heavy-tailed whenever the underlying data is, because the values
are measured percentiles rather than a fitted curve.
- A target line. The median maximum favourable excursion of the
matched set is converted to a price, then snapped to a mapped
structural level if one lies within half an ATR. Statistics choose
the zone; structure chooses the exact price. The label states
"level" when a snap occurred and "stat" when it did not.
- Hit rate and expected bars. Both are read at the nearest whole R
ring (+1R, +2R or +3R) to the target distance, and the ring is
named on the label. Hit rate is the share of matched records that
reached that ring within H bars. The bar count is the median
first-passage time among those records that reached it.

7. RUN TRACKER

A run begins at a confirmed structure shift and ends at the next
confirmed shift in the opposite direction. Within a run, occurrences of
each event class and direction are counted. When the run closes, one
record per class is stored: how many had occurred before the reversal.

The observation unit is therefore the run, not the event. This matters:
counting events directly would produce heavily overlapping samples,
since several events inside one run share the same future. Counting runs
does not.

The panel answers a question most tools ignore entirely: given that a
third bearish divergence has now printed in this uptrend, in what
fraction of past runs on this chart did the reversal arrive by the
third, and in what fraction did the run extend to a fourth or beyond.

8. SELF-AUDIT

Every displayed projection resolves into exactly one of four states, and
these are never merged:

HIT the target was reached first
ADV the -1R reference was reached first
AMB both were touched inside the same bar, so the order is
unknowable from bar data and the case is discarded rather
than claimed
EXP H bars elapsed with neither touched

The dashboard reports the running counts, and separately compares the
average hit rate the tool projected against the hit rate it actually
realised. If those two numbers diverge, the tool is telling you its own
estimates are miscalibrated on this chart.

Two further panels report whether the classification axes carry any
information at all: median outcome for tier A versus tier B, and median
outcome for MAJOR versus MINOR versus NONE locations. If a pair does not
separate, that axis is not contributing, and you are meant to see that.


===============================================================
WHAT MAKES IT ORIGINAL
===============================================================

- Outcome statistics are conditioned on a discrete event signature
and computed from the chart's own history, rather than assumed from
a parametric distribution or imported as fixed percentages.
- Projection targets are snapped onto mapped structural levels, so
the displayed price is a real level rather than a quantile value
floating in empty space.
- The hierarchical backoff makes sparse conditioning explicit: the
display always names the level of specificity that was achievable
and the sample size behind it.
- Sequence statistics use the completed run as the observation unit,
which removes the sample overlap that direct event counting creates.
- The indicator scores its own past projections against outcomes and
displays projected versus realised hit rate on the chart.


===============================================================
HOW TO READ THE CHART
===============================================================

HORIZONTAL LINES

The image below shows the level map alone, with the projection layer
switched off, so the two grades of level can be compared directly: gold
solid lines mark MAJOR levels, thin dotted lines mark MINOR ones.

снимок

Two families of horizontal line exist, and they are drawn so that they
can never be confused with each other.

THE LEVEL MAP owns thin dotted lines and gold:

Gold, solid, width 2 A MAJOR level: four or more independent
structural factors coincide at this price.
Washed white, DOTTED, A MINOR level: one to three factors.
width 1

THE TARGET FAMILY owns solid width-2 lines in mint, coral and slate.
No target line is ever drawn dotted or at width 1.

Mint, solid, width 2, The target of the live projection.
full opacity Extends to the right. Only one is live at
a time.
Coral, dotted, width 1 The -1R adverse reference of the live
projection. Removed the moment the
projection resolves. This is a measurement
boundary used to classify the outcome. It
is NOT a stop loss and must not be used as
one.

Once a projection resolves, its target line keeps its full width and
stays solid. Only its colour and opacity change:

Mint, faded HIT: price reached it within the horizon.
Coral, faded ADV: price reached the -1R reference
first.
Slate blue-grey, faded EXP or AMB: the horizon elapsed with
neither touched, or both were touched in
the same bar and the case was discarded.

Resolved lines are retained deliberately. A price that the statistics
selected, and that was then snapped onto a structural level, often
remains structurally relevant afterwards, and it is useful to see where
those prices were. The number retained is configurable and defaults to
six.

Read the fade as expiry of a claim, not as expiry of the price. The
faded line is a record that this price was once selected as a target and
of what happened next. It is not a live target and carries no ongoing
claim about the future.

The image below shows several resolved projections on one chart, so the
three outcome colours can be compared side by side: a faded mint line
where price reached the target, a faded coral line where it reached the
adverse reference first, and a faded slate line where the horizon
elapsed without either being touched. The markers carry the matching
three-letter outcome. Projections that did not work out are shown here
deliberately; the indicator records its own failures and so should its
description.

снимок

Level lines are redrawn on each new bar and only levels within six ATR
of current price are displayed, up to fourteen at a time.

THE FAN

Outer shaded band 5th to 95th percentile of matched
historical outcomes.
Inner shaded band 25th to 75th percentile.
Dashed centre line 50th percentile, the median path.
Teal the event pointed upward.
Coral the event pointed downward.

The fan is frozen at the moment the projection is issued and is never
recalculated. It reaches forward exactly H bars.

The next image shows a single live projection close up: the two shaded
bands, the dashed median path, the mint target line, and the label
carrying hit rate, sample size and remaining bars. Note that the bands
are not symmetrical around the median, because they are measured
percentiles rather than a fitted curve.

снимок

EVENT MARKERS

A small label prints at each recorded event, below the bar for upward
events and above for downward ones. It contains a three-letter code and
a number:

SWP sweep SHF shift SQZ squeeze
CLX climax REJ rejection DIV divergence

The number is the count of that event class and direction so far inside
the current run. "DIV 3" means this is the third divergence of that
direction since the last structure shift.

When a projection resolves, its marker gains a suffix and changes
colour:

HIT green target reached first
ADV red the -1R reference reached first
AMB amber both touched in the same bar; discarded
EXP amber the horizon elapsed with neither touched

THE TARGET LABEL

Three lines at the right end of the projection:

line 1 the target price, followed by "level" if it was snapped onto
a mapped structural level or "stat" if no level was near
line 2 hit rate and sample size, for example: hit 61% n=38
line 3 while the projection is live: bars remaining and the R ring
the hit rate refers to. Once it resolves, this line is
replaced by "RESOLVED" followed by HIT, ADV, AMB or EXP, and
the whole label takes the matching colour.

The bar count was frozen when the projection was issued and only counts
down. Nothing behind it is recalculated.

THE DASHBOARD

EVENT class, direction, and sequence number in this run
LOCATION MAJOR / MINOR / NONE and the level weight
REGIME RANGE / TRANS / TREND, the context score, tier
SIGNATURE backoff level used and sample size
WITH q50 q75 q95 terminal excursion quantiles measured ALONG the
event's own direction, in R
AGAINST q25 q05 the same distribution's tail measured AGAINST the
event's direction, in R
TARGET price and hit rate
ETA bars remaining and the R ring, or "no open
projection"
RUN EXT how far the current run has extended, in R
FLOW SOURCE "volume" or "proxy"
SEQ 1 / 2 / 3 / 4+ share of past completed runs that reversed after
that many events of this class
RUNS median median count before reversal, and number of runs
TIER A / B median outcome in R for each tier, with counts
LOC MAJ/MIN/NONE median outcome in R for each location class
LEDGER running totals of hit, adv, amb and exp
CALIBRATION average projected hit rate against realised

The dashboard is reproduced below at readable size, since every claim
made in the HOW IT WORKS section is meant to be verifiable there: the
backoff level actually used, the sample size behind it, the quantiles,
the sequence distribution, the two axis-health rows, and the running
comparison of projected against realised hit rate.

снимок

WITH and AGAINST are measured relative to the event's own direction, not
relative to the chart. For a downward event, a WITH value of +1.4R means
price fell by 1.4 ATR, and an AGAINST value of -1.8R means price rose by
1.8 ATR before the horizon closed. AGAINST is the row that tells you how
violent the route can be, and it is the row most worth reading before
deciding on any position size.


===============================================================
THE MOST IMPORTANT WARNING
===============================================================

DO NOT TREAT THE GREEN LINE AS A TARGET TO TRADE TOWARD, AND DO NOT
TREAT ANY MARKER AS AN ENTRY SIGNAL.

You will observe the following, and it is the single most dangerous
thing about this indicator:

The projection expires. The bars run out. The label reads "closed". And
then, twenty or fifty bars later, price finally reaches the green line.

It is tempting to read that as the tool having been right after all. It
was not, and here is why that reading destroys accounts:

1. The green line is snapped to a structural level. Structural levels
get revisited eventually, because that is what they are. Price
arriving there after the horizon has expired is not evidence of
anything. It is what levels do.

2. The expected bar count is a median of the cases that reached the
ring. By definition, roughly half of the successful cases took
longer than that. "The estimate elapsed and it is not there yet"
is an ordinary outcome, not a malfunction.

3. Route is not measured. The indicator records where price ended up
and how far it travelled. It does not promise that the path there
was survivable. Price can travel far against you first, and still
arrive. The AGAINST row is the only place the route appears at all,
and even there it is a summary, not a guarantee.

A faded line is a closed case. It has no ETA, no live claim and no
implication that price is still heading there. If price later reaches a
faded line, that is not a delayed hit. It is a structural level being
revisited, which is what structural levels do.

That third point is what actually costs money. A leveraged position
opened on the strength of a hit rate can be liquidated by an adverse
excursion long before the target is reached. The account is closed; the
target being reached afterwards is irrelevant to it. This is not a
remote scenario. It is the ordinary case whenever leverage is applied to
a statistic that describes destinations rather than routes.

The -1R red line does not protect you either. It is a measurement
boundary chosen so outcomes can be classified consistently. It is not a
risk parameter and was never sized to be one.

Precedent is a context tool. It tells you what has typically followed
this kind of moment on this chart, with the sample size attached. Entry
timing, position size, stop placement, leverage and the decision to
trade at all remain entirely yours and must come from a method this
indicator does not contain and does not attempt to contain.

If the only thing you take from a projection is "hit 61 percent, so buy"
you have misread it. The intended reading is closer to: "in 38
comparable cases on this chart, price reached this level within 24 bars
in 61 percent of them, taking a median of 9 bars, and the adverse tail
of that distribution ran to -1.8R."


===============================================================
LIMITATIONS AND REPAINT POLICY
===============================================================

REPAINT BEHAVIOUR, ELEMENT BY ELEMENT

- Event detection, tier assignment and score sampling are locked at
bar close. They do not change afterwards.
- Swing pivots confirm with a delay equal to the pivot length in bars
(default 21). A level cannot appear before its pivot is confirmed.
That delay is the cost of not looking ahead, and it is not avoided
anywhere in this script.
- Higher timeframe values are requested with a one-bar offset, so
only completed higher timeframe bars are used. On the chart
timeframe this means the higher timeframe bias lags by one higher
timeframe bar.
- The fan, the target line and the adverse line are computed once, at
the confirmed bar that issued them, and are never recalculated.
- The dashboard and the countdown update live within the forming bar
by design. The countdown only subtracts from a number that was
frozen at issue; no statistic behind it is recomputed.

KNOWN LIMITATIONS

- The statistics are descriptive, not predictive. They summarise what
has already happened on the chart in front of you. They are not a
forecast and are not out-of-sample.
- Sample sizes are small by construction. Requiring non-overlapping
outcomes limits the number of independent cases available, which is
why the backoff and the visible sample counts exist.
- Until enough completed outcomes exist, nothing is drawn at all. The
image below shows that state: the dashboard reports CALIBRATING and
the current count against the required minimum, and no fan, target
or hit rate appears anywhere on the chart.

[IMAGE 5 - CALIBRATING STATE]

- Chart history is finite. On low timeframes the available bars may
cover only a matter of weeks, and possibly only one market regime.
Treat a large sample drawn from a single regime with caution.
- Outcomes are measured at bar resolution. When a bar touches both
the target and the adverse reference, the order is unknowable and
the case is marked ambiguous and discarded rather than assumed.
- Statistics apply only to events this indicator itself defined. If
you identify a setup it did not mark, no displayed percentage
describes it. Borrowing a number from a different occasion is a
misuse.
- Where a symbol provides no usable volume, flow falls back to a
body-position proxy on the same percentile scale. The dashboard
states which is in use. Mixing the two would corrupt the store, so
the fallback applies to the whole session or not at all.
- Changing the higher timeframe from Auto to Manual changes what the
signature key means. The stored outcomes are therefore cleared and
rebuilt from zero when you do it. This is intentional.
- Nothing here is tuned. There is no optimiser and no fitted weight.
Thresholds are percentiles over disclosed rolling windows. If a
parameter is changed, the level map and the statistics change with
it, and the sample must accumulate again.


===============================================================
DISCLAIMER
===============================================================

This script is published for educational and analytical purposes. It is
not financial advice, not a recommendation to buy or sell any
instrument, and not a trading system. It produces no entry signals, no
stop levels and no position sizing.

Historical measurement does not indicate future results. Markets change
regime, and a distribution measured on past bars may not describe the
next ones. Trading carries risk of loss, and leveraged trading carries
risk of total loss. Any decision taken while this indicator is on the
chart remains entirely the responsibility of the person taking it.

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.