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

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

Chart-Pattern Analogs SMC-Graded Chart-Pattern Analogs — Empirical Matching, SMC-Graded & Calibrated
## What it is
A chart-pattern engine that does not trust textbook shapes — it predicts from **precedent**. Instead of asking "does this look like a Head & Shoulders?", it asks "**how did the closest historical shapes on this symbol actually resolve?**" and answers from data.
A PIP (Perceptually Important Points) skeleton of the recent window is matched by **Dynamic Time Warping** against a live memory of past shapes, each labelled by what happened next. The direction, probability and target come from the *k* nearest analogs. Each completed pattern is then graded with Smart-Money context (liquidity sweeps, premium/discount location, breakout quality), and its forward outcome is tracked **per family, per regime, with Wilson confidence intervals**. Templates and geometry survive only to *name* the family.
## Why these components belong in ONE script (not a stack of indicators)
This matters because the components form **one closed loop**, where each answers a question the others cannot:
- **PIP skeleton + Ehlers-adaptive window** reduce price to its structurally important turning points, over a window sized by the live dominant cycle so the skeleton tracks the market's actual rhythm rather than a fixed bar count.
- **DTW analog matching** replaces fixed templates: the current skeleton is compared to a memory of *resolved* shapes, and the forward outcome of its nearest neighbours **is** the prediction. Empirical, not assumed.
- **SMC context** (liquidity sweeps, EQH/EQL pools, premium/discount, breakout quality) answers *"is this the right place?"* — a pattern that forms after a real liquidity grab, in the correct half of the dealing range, is graded higher; one firing into opposing liquidity is withheld. Shape alone cannot tell you location.
- **Regime** (efficiency ratio) conditions trust: a family's edge is measured separately in trend vs chop, because the same shape behaves differently in each.
- **Calibration** closes the loop: per-family, per-regime hit-rate versus an unconditional directional base rate, recency-weighted, with Wilson 95% intervals — so reliability is *earned on this instrument*, not claimed.
The skeleton says **what**, the analogs say **how it resolved before**, SMC says **whether the location is right**, the grade **fuses** them, and calibration keeps the whole thing **honest**. Remove any layer and the read loses a dimension it cannot recover.
## How it works (mechanics)
On bar close, the PIP skeleton is extracted and matched by DTW k-NN to the analog memory. The consensus direction and probability, plus the single nearest analog's forward path (the **ghost overlay**), are drawn. The pattern is graded **A/B/C** from the calibrated probability + quality + sweep + location, and gated by a minimum grade and a location veto. Every directional emission locks entry and ATR, tracks MFE/MAE in R, and at the horizon records a win if the close moved the chosen ATR multiple in its direction — feeding both the analog memory and the per-family/per-regime calibration tables.
Detection, drawing and resolution happen **on bar close over closed bars only** — no `request.security`, no dynamic-length `ta()`, no intrabar revision. Patterns are drawn once and never moved.
## How to use
1. Read the dashboard: the active pattern's **analog probability**, its **A/B/C setup grade**, **sweep validation** and **premium/discount location**.
2. Favour higher grades — a calibrated-positive family, sweep-validated, in the correct half of the range, with the ghost pointing your way.
3. Check **"This family"** — the regime-conditional and recent hit-rate is the number that matters *now*; the Pro table lists every family with Wilson confidence intervals.
4. The **ghost** shows the single closest historical precedent; the **target** is the analog mean.
5. Everything here is descriptive, probabilistic context — never an instruction.
## Use on any market
Works on any symbol and timeframe. The **Data Source** inputs (High / Low / Close) drive the entire engine — PIP skeleton, pivots, liquidity, premium/discount — from any series, so you can run it on standard candles, Heikin-Ashi, or another instrument. All thresholds are **ATR-relative**, the detection window is **cycle-adaptive**, and the analog memory and calibration rebuild **per instrument** — nothing is hard-coded to a price scale or a single market. Defaults are set for NIFTY index-futures intraday; change the sources or lengths for other assets.
## Credits
This engine builds on established, published concepts:
- **Perceptually Important Points** — Chung, Fu, Luk & Ng
- **Dynamic Time Warping** — Sakoe & Chiba
- **Homodyne-discriminator dominant cycle / adaptive windows** — John F. Ehlers
- **Efficiency Ratio** (trend vs noise) — Perry Kaufman
- **Wilson score confidence interval** — Edwin B. Wilson
- **Liquidity, premium/discount and order-block context** — smart-money / auction-market concepts (Wyckoff lineage; popularised in the ICT body of work)
The empirical analog loop (label-by-outcome DTW matching), the SMC location-grading, and the per-family/per-regime Wilson-bounded calibration framework are the author's original implementation.
## Originality
The contribution is the **closed loop**, not the objects: empirical DTW analog matching (label by outcome, not by template), SMC location-grading, and per-family/per-regime Wilson-bounded calibration, fused into one self-prioritising read with a nearest-precedent ghost overlay. The shape is only the index into history.
## Limitations (honest)
The analog memory and calibration are **in-sample, close-to-close at a fixed horizon, with no costs, slippage or stops** — a study aid, not a backtest, and not a probability of future results. The engine needs to build memory before it leaves bootstrap (watch the "Analog mem" counter). Volume-derived quality degrades on symbols without real volume. Past behaviour of a pattern does not assure future behaviour.
## Disclaimer
Educational / informational study for chart analysis only. **NOT financial advice, NOT a strategy, NOT a recommendation.** It places no orders and guarantees no outcome. Markets carry risk; do your own research and manage your own risk. Paper-trade before risking real money.
Indicator
