Supertrend Twincore [MachineSuiteAI]Supertrend Twincore
🟦 OVERVIEW
A fast Supertrend flips too often; a slow one flips too late. This script runs both at once and only signals when they agree — and then shows you, with win rates and sample sizes, how that agreement has actually performed on the chart you have loaded.
A signal only appears where the fast core (timing) and the slow core (structure) first align, and only if it passes a gate: clustered whipsaw flips always suppress, and every other filter blocks signals only where measurement shows it helps on this chart. Passed signals are graded A/B/C and draw an Entry / SL / TP1-3 ladder whose outcomes are tracked per grade. Suppressed candidates stay as grey ghost chips with the reason, and a five-row multi-timeframe strip shows the consensus state across timeframes from completed bars.
The idea throughout: the chart never claims more than the data supports, and anything the script believes is checkable in the panel.
🟦 WHAT IS A SUPERTREND?
Supertrend is a public-domain trailing-stop indicator: it offsets price by a multiple of the Average True Range and trails that stop behind the trend. Price above the stop means uptrend, below means downtrend; a close across it flips the state. This script computes its cores with the built-in ta.supertrend() — fast 2.0 × ATR(10) and slow 4.0 × ATR(20) by default.
Its known weakness is structural: in ranging markets the stop is repeatedly crossed and the indicator whipsaws. Filters are the usual answer; this script measures whether each one actually helps on the loaded symbol and timeframe, and the marks and the gate act only on that evidence.
🟦 WHY THIS SCRIPT IS ORIGINAL
The base calculation is a built-in, and the ingredients — win-rate panels, ADX gates, higher-timeframe confirmation, multi-timeframe dashboards, take-profit ladders, signal grades — are established ideas. What's different is the standard everything must meet: beyond one fixed whipsaw rule, nothing gets drawn, nothing blocks a signal, and nothing drives the engine unless the measurements on the loaded chart back it up.
- Graded ladder odds with the cost attached. Grades are fixed and published — A means structural confirmation plus volume, B one of the two, C neither; no opaque score. Every passed signal's ladder is tracked to resolution; the panel shows per grade: TP1-before-SL and SL-first rates, the median furthest level, the median heat (largest adverse move, in ATR units) and the median bars to TP1, each with its own sample size.
- An adaptive engine that has to beat the fixed one first. Both fast cores — fixed and adaptive — are measured as separate signal streams on the loaded chart, and the adaptive core only drives signals while it beats the fixed core by a set margin with enough samples. The A/B row shows the running comparison; on defaults it reports the adaptive layer as inert.
- Gates held to the same standard. The ✓ volume mark and ⚠ counter-trend warning only print where their split beats the base win rate by a configurable margin here. The ADX gate only blocks candidates where high-ADX candidates have beaten low-ADX candidates by that margin on this chart.
- Per-condition win-rate splits. The base candidate win rate, then the same measurement split by signal class, higher-timeframe agreement, volume confirmation, multi-timeframe alignment and volatility regime — six statistics, each with its own sample size, greyed below a minimum sample.
- Two kinds of signals, measured separately. A candidate exists only on the first bar the cores align and is classified as a structural confirmation (the slow core just flipped in) or a pullback rejoin (the fast core returned to a standing slow trend); a double flip on one bar is labeled same-bar. They are different trades, measured separately.
- Suppression you can audit. A gated-out candidate still prints — a hollow grey ghost chip with the specific reason — and still counts in every statistic, so the base rate is never inflated by counting only the survivors.
- Visual discipline. The band claims a direction only while both cores agree; its saturation drains as price nears the structural stop, so the exit warning arrives before the flip; NEUTRAL keeps a directional tint, so the last trend stays readable while standing aside. The price scale is held to the same rule — it carries the structural stop and the ladder's Entry, SL and TP1-3, each in its own colour, and nothing else; the band and the fast core draw on the chart but claim no axis label. Every visual property maps to something measured.
🟦 HOW IT WORKS
- Cores: two standard Supertrends — the fast core times entries, the slow core defines structure and is the ladder's trailing stop. Presets: Scalp 1.5×ATR(7)/3.0×ATR(14), Intraday 2.0×ATR(10)/4.0×ATR(20), Swing 3.0×ATR(14)/5.0×ATR(28), or Custom.
- Gate and state model: flip-cluster suppression (2+ fast flips in 10 bars, on by default), the measured ADX gate (default "Where it helps (measured)"), and an optional strict higher-timeframe gate (off by default). The band turns grey NEUTRAL on low ADX (default ADX(14) < 20) or flip clustering.
- Higher-timeframe filter: a third Supertrend one regime up (auto-mapped ≤15m→4H, ≤1H→1D, ≤4H→3D, ≤1D→1W, else 1M; or manual), read from the last completed HTF bar.
- Statistics: on confirmed bars, every candidate — passed and suppressed — resolves N bars later (default 10); a win means the close moved in its direction. Splits grey below the minimum sample (default 20). Chip marks need their split to beat the base rate by ≥3 points (configurable); the ADX gate needs the high-ADX split to beat the low-ADX split by the same margin; volume confirmation is volume above 1.5× its 20-bar average.
- Ladder: at a passed signal's close, Entry is the close, SL is the slow-core stop (or the fast core, or a fixed k×ATR cap), TP1/2/3 default to 1/2/3 × ATR. It trails, marks TP touches ✓, freezes ✕ on an SL break, dims when resolved or consensus is lost, and feeds the per-grade LADDER ODDS rows. A live ladder tracks the right edge of the chart; once its stop is hit it stops there, so it stays a bounded record of that trade — targets it never reached are not credited later just because price eventually passed them, and the frozen right edge makes clear the trade was already over. The stop's ray spans only the stretch where that level was actually in force, because a trailing stop is a staircase rather than one line: on a long it starts below the entry and can ratchet above it, locking in profit, and the amber slow core shows the whole path. Each level prints its exact price on the price scale, so the figure for an order ticket reads straight off the axis while the chart labels stay short. The colours carry the geometry: entry green, the targets in the trade's own direction and the stop in the opposite hue, so the level that ends a trade never reads like the levels that pay it — and the slow core keeps its amber, so the stop stays distinguishable from the line it trails.
- Adaptive engine: a per-volatility-regime fast core A/B-measured against the fixed one, as described above; default factors are inert.
- MTF strip: five rows of full consensus state (UP / DOWN / SPLIT / NEUTRAL, with bars-in-state), each read from that timeframe's last completed bar. Auto mode starts at the chart's own timeframe and climbs — 4H gives 4H/D/W/M/3M. Lower timeframes are omitted by default: their consensus flips many times during a single trade taken here, so it says little about an outcome measured over days. Manual mode accepts any five, defaulting to the classic 15m/1H/4H/D/W.
🟦 HOW TO USE IT
- Read the panel first: consensus state, cores, regime, HTF agreement, then the measured rows. An ↑ means that condition has earned its margin on this chart; its absence means it hasn't.
- Chips carry their evidence: grade letter, live per-grade TP1 odds at sufficient sample, ✓ where volume has helped, ⚠ where fighting the higher timeframe has hurt. Ghost chips mean the script stood aside — the reason is on the chip.
- NEUTRAL and SPLIT mean stand aside. The coach line says this in plain language, and notes that a retouch of the entry after TP1 does not invalidate a live ladder — only the SL does.
- Reversal-only signal mode reserves the headline presentation for slow-core reversals; Discipline display mode strips the chart to the band alone (note: TP/SL alerts only fire while the ladder is drawn).
- Defaults are tuned on liquid crypto from 15-minute to weekly charts; the multipliers and ADX threshold are worth reviewing on other asset classes.
🟦 SETTINGS
Grouped as in the inputs dialog: consensus core (presets or custom multipliers) · higher-timeframe filter · state model & signal gate (ADX, flip-cluster, optional HTF gate, ghost chips) · trade ladder (SL geometry, TP multiples) · grade engine (certified or dynamic wiring) · adaptive engine · MTF strip · visuals and display modes · volume multiple (default 1.5×) · signal stats engine (horizon, minimum sample, gating margin) · JSON webhook alerts.
🟦 ALERTS
Consensus long / short · confirmed reversal long / short · Grade A long / short · TP1 / TP2 / TP3 touched · SL break · NEUTRAL started / ended · volatility regime changed · adaptive engagement changed. Create the classic alert conditions with "Once Per Bar Close" — they evaluate on live bars, and an intrabar state can revert before it counts. Optional JSON alert() events via a single "Any alert() function call" alert: signal events carry grade, entry and levels; TP/SL events identify the touched level; all carry symbol, timeframe, regime and state. The JSON events are close-gated and fire for every passed candidate, including rejoins the Reversal-only display mode demotes.
🟦 REPAINT & DATA NOTES
- All bookkeeping runs on confirmed bars; chips, ladders and statistics commit at bar close. Inside a forming bar the panel's consensus, cores, agreement, volume and coach line update live and are therefore PROVISIONAL — they can revert before the bar shuts. Price can also sit beyond a ladder's stop for the rest of a bar without resolving it: in the core SL modes the stop breaks when that core flips, which needs a confirmed close. The coach line says so when it happens.
- Higher-timeframe and strip values come from each timeframe's last completed bar — no repaint; intrabar changes up there show after that bar closes. The design assumes the HTF sits above the chart's timeframe — with Manual selection, keep it there.
- Ladder TP touches — and the Fixed mode's hard-stop touches — are detected from confirmed bars' highs/lows, starting the bar after entry; a bar touching several levels credits TPs before the stop. In the core SL modes the stop is not touch-based: it resolves only when its core flips, which needs a confirmed close — so a wick through the stop does not end a ladder, and the touch-credited TP rates are structurally friendlier than a hard-stop backtest of the same levels. The Fixed k×ATR mode is the geometry closest to a real hard stop.
- Statistics cover the loaded history and reset when the chart reloads with different history; lower timeframes load fewer bars. Greyed rows just mean the sample is too small to trust.
- Only the most recent 250 chips and ghost chips stay on the chart, so a live ladder's own labels can never be pushed off by PulseWire's drawing limit; deep history keeps its band and cores but not its markers. Ladder odds count each ladder when it resolves, and in the rare case that more than 30 are open at once the oldest is counted at its current state rather than discarded — the sample is never silently trimmed.
- On a live bar the volume ratio is partial; judge it near the close. Volume features require a feed that supplies volume.
🟦 CREDITS
The Supertrend concept is public domain (popularized by Olivier Seban); ATR, ADX and the DMI are J. Welles Wilder's. The fixed cores use PulseWire's built-in ta.supertrend(); the adaptive core re-implements the same algorithm to accept a per-bar factor. The consensus model, candidate classes, statistics engine, gates, grades, measured ladder, ghost chips, strip and band rendering were written from scratch for this script.
🟦 LIMITATIONS
- Supertrend lags by construction, and requiring two cores to agree makes entries later still — fewer, later, more heavily filtered signals is the intended trade-off.
- The NEUTRAL state derives from lagging measures (ADX, flip counts), so the first signals of a new trend can still arrive grey or be suppressed.
- All statistics are direction-only measurements over a fixed horizon; ladder odds are level measurements (TPs credit on a wick touch, core-mode stops resolve only on a confirmed core flip) — no fees, slippage, sizing or equity math. They are not a strategy backtest, they differ per symbol and timeframe, and they do not predict future outcomes.
- Without volume data the volume filter and its split stay inactive, and certified Grade A (confirmation + volume) is out of reach — signals cap at Grade B on volume-less feeds. Sample sizes on higher timeframes are structurally small; expect greyed rows there.
- The same asset on two different venues can show opposite states. A Supertrend flip is a threshold event: when price sits within a fraction of a percent of the band, a normal inter-exchange spread of a few basis points decides whether it crosses, and once one venue flips its stop jumps to the other side of price, so two nearly identical charts diverge sharply. This is inherent to the calculation, not a data error — treat a signal as belonging to the feed it was measured on, and check the panel's sample sizes on the venue you actually trade.
🟦 DISCLAIMER
This is an educational analysis tool, not investment advice. Historical measurements, however carefully computed, do not predict future results. Trading involves substantial risk.
Indicator

Time-of-Day/Session Performance Stats [QuantAlgo]🟢 Overview
The Time-of-Day/Session Performance Stats is a comprehensive time-based analysis tool built for traders who want clear, ranked insight into when markets actually move. It measures average range, volume, bullish bias, and drift across every hour of the day and the four major sessions, then surfaces the strongest and weakest windows so you can focus activity where the data supports it. Whether you trade crypto around the clock or equity and forex sessions on a weekday schedule, the indicator turns raw historical bars into practical rankings, session comparisons, and non-repainting chart overlays.
🟢 What is Time-of-Day and Session Performance?
Markets are not uniform across the 24-hour cycle. Liquidity, volatility, and participation concentrate in specific hours and sessions. Sydney is typically the thinnest of the four major centers, Tokyo drives Asian activity, London often produces the widest ranges of the day, and the London-New York overlap is usually the busiest window. By averaging range, volume, the share of up closes, and net drift for each hour and each session over a configurable lookback, this tool converts those recurring patterns into ranked statistics instead of leaving you to rely on memory or anecdotal observation.
🟢 How It Works
The indicator walks a configurable window of past bars (limited by lookback days and a hard max-bar ceiling) in the timezone you select. Every usable bar is assigned to its hour of day and to any sessions it falls inside. Range can be measured in percent of close or in raw price units. Volume, directional closes, and drift are accumulated in parallel. Hours that do not meet a minimum bar-count threshold are dropped from every ranking so tiny samples cannot distort the boards.
Five ranking boards are produced: Activity (average range), Volume (when the symbol reports it), Bias (percentage of directional bars that closed higher), Drift (mean close-minus-open percentage), and Aggregated (the mean percentile of range, volume, and directional edge). Sessions are ranked solely on average range per bar and can be toggled or given custom windows. Overlaps count toward every session involved rather than being forced into one.
Chart overlays read a trailing window of the same length rather than the final ranking, so background shading and bar coloring never repaint. The Focus Hours panel converts the Aggregated ranking into three practical allocation plans plus the single quietest hour to avoid.
🟢 Key Features
▶ Ranking Boards
Five independent boards list every qualifying hour from strongest to weakest.
1. Activity Ranking: Orders hours by average bar range. Rank 1 is the hour with the most room; the last row is the quietest. This is the simplest and often most useful single board.
2. Volume Ranking: Orders hours by average volume. Read it alongside Activity. High range on low volume signals thin participation. The board is hidden automatically on symbols that report no volume.
3. Bias Ranking: Orders hours by the percentage of directional bars that closed above their open. Flat bars are excluded, so the figure reflects only bars that actually moved. There is no separate bearish column; the bottom of the board is the most bearish reading.
4. Drift Ranking: Orders hours by mean percentage change from open to close. An hour can post a high bull rate yet still show negative drift if its losing bars are larger than its winning ones. Divergences between Bias and Drift are often the most interesting signals.
5. Aggregated Ranking: Combines percentile ranks of range, volume (when present), and directional edge into a single composite score. This is the ranking that feeds both the Focus Hours panel and the Aggregated overlay option.
▶ Session Ranking Panel
The four major sessions are ranked by average range per bar and displayed with their window, bull rate, drift, and bar count. Rank 1 takes the bullish color and the last rank takes the bearish color on the same continuous gradient used by the boards. Because a bar inside an overlap is counted toward every session it belongs to, session bar totals can exceed the overall sample size.
▶ Focus Hours Panel
The Aggregated ranking is translated into four labeled plans: Aggressive (top hour only), Mix (top two with 80/20 weights), Conservative (top three with 50/30/20 weights), and Avoid (the single quietest hour by average range). Each row shows the relevant hours, their session affiliation, bull rate, drift, and score so the reading can be acted on immediately.
▶ Chart Overlay
Background shading and price-bar coloring can be driven independently by Session Ranking, Activity Ranking, Volume Ranking, Bias Ranking, Drift Ranking, Aggregated Ranking, or Focus Hours. All overlays are computed from a trailing window so they never repaint. Transparency controls let you keep the ranking obvious or keep it subtle enough not to compete with price.
▶ Session and Filter Controls
Sydney, Tokyo, London, and New York can each be enabled or disabled and given custom HHMM-HHMM windows in the selected timezone. A weekdays-only filter removes weekend bars for forex, futures, and equities while leaving crypto fully intact. The Bars To Include setting can restrict the entire study to all bars, any enabled session, or one named session.
▶ Built-in Alerts
Ready-made alert conditions fire when price enters the peak activity hour, the quietest hour, the peak volume hour, the most bullish or most bearish hour, or the top Aggregated hour. Separate alerts cover the open and close of each individual session, any session start or end, and the start and end of the London-New York overlap.
▶ Color Presets
Six presets (Classic, Aqua, Cosmic, Cyber, Neon, Custom) apply a continuous gradient from the bullish color at rank 1 to the bearish color at the last rank across every board, panel, and overlay. Custom mode exposes individual bullish and bearish color pickers; text contrast is calculated automatically so any chosen colors remain readable.
▶ Interval Warning
When the chart interval is higher than 1 hour, most of the 24 hour buckets never receive a bar, leaving the rankings incomplete. The indicator displays a clear warning label on the chart that explains the limitation and recommends switching to 5m, 15m, 30m, or 1h, for example. The warning can be turned off once the restriction is understood and a clean chart is preferred.
Indicator

MA Retest StrategyMA Retest Strategy
Overview
MA Retest Strategy is a trend-following system built around a simple but powerful idea: price rarely moves in a straight line — it pulls back to test a moving average before continuing in the direction of the trend. Instead of just plotting two moving averages and leaving you to guess, this indicator turns that pullback-and-continuation behavior into a complete, rule-based trade framework: it detects the retest, marks the exact entry, calculates a volatility-aware stop-loss and take-profit, tracks the outcome of every signal, and even scans four other symbols of your choice for the same setup in real time.
The trend direction is defined by two Exponential Moving Averages (EMA) — a fast one (default length 50) and a slow one (default length 200). Their relationship (fast above slow = uptrend, fast below slow = downtrend) is combined with a retest of the fast EMA: price must pierce through the fast EMA against the trend and then close back on the trend side. That close is the signal.
Trading Logic
Long entry conditions:
1. The fast EMA is above the slow EMA (uptrend).
2. Within the last few bars, price has pierced below the fast EMA (a genuine pullback, not just noise).
3. The current candle closes back above the fast EMA, confirming the retest is over and the trend is resuming.
When all three conditions align, the indicator plots a BUY label, and immediately draws four price levels: Entry, Stop-Loss, Take-Profit, and Breakeven, each as a line with a live price tag on the right edge for easy order placement.
Short entry conditions are the mirror image: fast EMA below slow EMA, a pierce above the fast EMA, and a close back below it.
If price is currently trading between the two moving averages (neither clearly above nor below), no new signal is evaluated — this "no man's land" filter avoids chasing signals in a choppy, undecided market.
Once a setup is triggered, it stays open (as a pending order, then as an active trade once price reaches the entry) until it's resolved by hitting the stop, hitting the target, timing out, or being invalidated by an opposite signal — only one setup per direction is ever open at a time, and an opposite signal automatically cancels whatever is currently active.
Risk Management
The stop-loss is never left to guesswork. You can choose between three calculation methods:
• Swing (High/Low): stop placed at the nearest swing low/high within a lookback window.
• ATR: stop placed at a multiple of the Average True Range from the entry price — automatically adapts to the current volatility of the instrument.
• Percent of Price: a fixed percentage distance from the entry price.
Regardless of the method chosen, a hard risk ceiling (expressed as % of price) prevents the stop from ever being placed unreasonably far away — for example because of a single abnormal wick or a bad tick in the data feed. Swing mode additionally has its own volatility-aware clamp (a maximum deviation expressed in ATR multiples), since raw swing highs/lows are the most exposed to being skewed by one outlier candle.
The take-profit is calculated as a multiple of the initial risk (an "R-multiple"), and a separate breakeven marker line shows where price would need to reach for you to consider moving your stop to entry — because in a mean-reversion-to-trend system like this, once price reaches roughly 1R in your favor, the probability of it snapping back toward the moving average (rather than continuing cleanly to the full target) increases, so protecting the trade at breakeven is a sound practice.
Dual Dashboard System
Statistics Panel — tracks every signal the indicator has generated on the current chart and breaks the results down into Take-Profit, Stop-Loss, and Breakeven outcomes (a stop hit after price already touched the breakeven level is counted separately from a "clean" stop-loss, since in practice you'd have moved your stop by then). You can filter the statistics to the full history, the last N days, or from a fixed date — ideal for quickly gauging how well the current settings are performing on a specific symbol before you commit to trading it.
Symbol Scanner — lets you monitor up to five other symbols for the exact same setup, in real time, without leaving your current chart. For each symbol it shows whether a signal is currently pending or already active, in which direction, and its entry/stop/target levels. Note: the scanner applies the same strategy settings (moving average lengths, stop method, R-multiple, etc.) that are set for the main chart — it is not independently configurable per symbol.
How to Use
1. Open the symbol and timeframe you're interested in, and check the Statistics panel — a strong win rate and consistent R:R suggest the market is currently trending cleanly enough for mean-reversion entries to work.
2. If the recent win rate is high, the market is respecting the moving average structure and the setup is worth trading. If it's dropping, the market may be entering consolidation — better to wait for a cleaner trend to re-establish.
3. Use the plotted Entry/Stop/Take-Profit/Breakeven lines and their price tags to place your actual order.
4. Once price reaches the breakeven marker, consider moving your live stop-loss to entry — this is a discretionary decision the indicator flags for you but does not automate.
5. Use the Symbol Scanner to keep an eye on other assets in your watchlist without switching charts constantly.
Settings Reference
General
• Source — the price series used to calculate both moving averages (default: Close).
Moving Average
• MA fast — length of the fast EMA (default 50).
• MA fast line width — plot thickness of the fast EMA.
• MA slow — length of the slow EMA (default 200).
• MA slow line width — plot thickness of the slow EMA.
• Bull color / Bear color — color of each MA line and of the shaded fill between them (tinted according to current trend direction).
Strategy
• MA Pierce Check Window (bars) — how many recent bars are checked to confirm price genuinely pierced the fast EMA before the retest close (default 3).
• Swing Point Lookback (bars) — lookback window used to find the nearest swing high/low for Swing-mode stops, and also used as part of the warm-up gate before the indicator starts evaluating signals (default 10).
• Take Profit, R (risk multiple) — target distance expressed as a multiple of the initial risk (default 3 = 3R).
• Max Bars in Open Setup (timeout) — if a signal doesn't resolve (neither stop nor target hit) within this many bars, it's force-closed and logged separately as a timeout rather than left open indefinitely (default 300).
• Stop Loss Calculation Method — choose between Swing (High/Low), ATR, or Percent of Price.
• ATR Length — averaging period for the ATR calculation (default 14).
• ATR Multiplier for Stop — multiplier applied to ATR when the Stop mode is set to ATR (default 1.5).
• Stop, % of Entry Price — fixed stop distance used only when the Stop mode is set to Percent of Price (default 1%).
• Max Allowed Risk, % of Price — hard ceiling on stop distance, applied regardless of the selected mode, to protect against abnormal candles or bad data ticks (default 5%).
• Also Cap Swing Stop by ATR (recommended) — an additional, volatility-adaptive safety clamp that applies only in Swing mode, tighter and more responsive than the flat percentage cap.
• Max Swing Stop Deviation, x ATR — multiplier for the clamp above (default 3).
• Move to Breakeven, R (risk multiple) — the R-distance at which the breakeven marker line is drawn (default 1 = 1R).
Visualization
• Show BUY/SELL Labels — toggle the signal labels on the chart.
• Show SL/TP/BE Price Tags on Lines — toggle the live price tags at the right edge of each level line.
• Fill Risk/Reward Zones — toggle the shaded risk/reward boxes.
• BUY Label Color / SELL Label Color — colors of the signal labels.
• Entry Line Color / Stop Loss Line Color / Take Profit Line Color / Breakeven Line Color — colors of the four level lines.
• Reward Zone Color / Risk Zone Color — colors of the shaded zones.
• Entry/SL/TP Line Width — thickness of the level lines.
Statistics
• Show Statistics Panel — toggle the on-chart stats table.
• Panel Position — corner of the chart where the table is drawn.
• Text Size — table font size.
• Statistics Period — All History, Last N Days, or From Fixed Date.
• N Days Back — used when Statistics Period is set to "Last N Days".
• Start Date — used when Statistics Period is set to "From Fixed Date".
Symbol Scanner
• Show Scanner for Other Symbols — toggle the scanner table.
• Symbol 1–5 — the five symbols to monitor.
• Scanner Timeframe — timeframe used for the scan; leave blank to match the current chart's timeframe.
• Scanner Panel Position — corner of the chart where the scanner table is drawn.
• Scanner Panel Text Size — scanner table font size.
Alerts
The indicator includes two ready-to-use alert conditions — Buy signal and Sell signal — that fire once per bar close and include the entry price, stop-loss, take-profit, and their distance in ticks directly in the alert message, so you can act on them without needing to open the chart.
Disclaimer
This indicator is a tool to assist with technical analysis and trade planning — it does not constitute financial advice, and past signal performance shown in the Statistics panel is not a guarantee of future results. Always combine it with your own risk management and market context.
Обзор
MA Retest Strategy — это трендовая система, построенная вокруг простой, но рабочей идеи: цена редко движется по прямой — она откатывается к скользящей средней для ретеста, прежде чем продолжить движение по тренду. Вместо того чтобы просто отрисовать две скользящие средние и оставить трейдера гадать, этот индикатор превращает такое поведение "откат-продолжение" в полноценную систему с чёткими правилами: он находит ретест, отмечает точный вход, рассчитывает стоп-лосс и тейк-профит с учётом волатильности, отслеживает исход каждого сигнала и даже сканирует ещё четыре выбранных вами актива на предмет такой же ситуации в реальном времени.
Направление тренда определяется двумя экспоненциальными скользящими средними (EMA) — быстрой (по умолчанию период 50) и медленной (по умолчанию период 200). Их взаимное расположение (быстрая выше медленной — восходящий тренд, быстрая ниже — нисходящий) сочетается с ретестом быстрой EMA: цена должна проколоть быструю EMA против тренда, а затем закрыться обратно на стороне тренда. Это закрытие и есть сигнал.
Логика торговли
Условия входа в лонг:
1. Быстрая EMA выше медленной EMA (восходящий тренд).
2. За последние несколько баров цена проколола быструю EMA вниз (настоящий откат, а не рыночный шум).
3. Текущая свеча закрывается обратно выше быстрой EMA, подтверждая, что ретест завершён и тренд возобновляется.
Когда все три условия совпадают, индикатор рисует ярлык BUY и сразу же размечает четыре ценовых уровня: вход, стоп-лосс, тейк-профит и безубыток — каждый в виде линии с "живым" ценником у правого края для удобной постановки ордера.
Условия входа в шорт зеркальны: быстрая EMA ниже медленной, прокол быстрой EMA вверх, и закрытие обратно ниже неё.
Если цена в данный момент находится между двумя скользящими средними (не выше и не ниже отчётливо), новый сигнал не рассматривается — этот фильтр "нейтральной зоны" не даёт индикатору гнаться за сигналами на "рваном", неопределившемся рынке.
После срабатывания сетап остаётся открытым (сначала как отложенный ордер, затем как активная сделка после достижения цены входа), пока не будет закрыт по стопу, по тейку, по тайм-ауту или отменён встречным сигналом — в каждый момент времени открыт только один сетап на направление, и встречный сигнал автоматически отменяет текущий активный.
Управление риском
Стоп-лосс никогда не рассчитывается "на глаз". Доступны три метода расчёта:
• Свинг (high/low): стоп ставится на ближайший минимум/максимум в пределах окна поиска.
• ATR: стоп ставится на расстоянии, кратном среднему истинному диапазону (ATR) от цены входа — автоматически подстраивается под текущую волатильность инструмента.
• Процент от цены: фиксированное процентное расстояние от цены входа.
Независимо от выбранного метода, жёсткий лимит риска (в % от цены) не позволяет стопу оказаться неоправданно далеко — например, из-за одиночного аномального фитиля или сбойного тика в данных биржи. У режима "Свинг" есть дополнительный, чувствительный к волатильности предохранитель (максимальное отклонение в множителях ATR), поскольку "сырые" свинг-хаи/лоу сильнее всего подвержены искажению одной нетипичной свечой.
Тейк-профит рассчитывается как кратное исходному риску значение ("R-множитель"), а отдельная линия безубытка показывает, на каком уровне цены имеет смысл задуматься о переводе стопа в точку входа — потому что в системе возврата-к-тренду вроде этой, как только цена проходит примерно 1R в вашу пользу, вероятность отката обратно к скользящей средней (вместо чистого продолжения до полного тейка) возрастает, поэтому защита сделки на безубытке — разумная практика.
Двойная система панелей
Панель статистики — отслеживает каждый сигнал, сгенерированный индикатором на текущем графике, и разбивает результаты на исходы "тейк-профит", "стоп-лосс" и "безубыток" (стоп, сработавший после того как цена уже коснулась уровня безубытка, считается отдельно от "чистого" стоп-лосса, поскольку на практике к этому моменту вы, скорее всего, уже перевели бы стоп). Статистику можно фильтровать по всей истории, последним N дням или с конкретной даты — удобно для быстрой оценки того, насколько хорошо текущие настройки работают на конкретном инструменте, прежде чем начинать торговать по нему.
Сканер монет — позволяет отслеживать до пяти других выбранных активов на предмет точно такой же ситуации в реальном времени, не покидая текущий график. По каждому активу показывается, есть ли сейчас отложенный или уже активный сигнал, в каком направлении, а также его уровни входа/стопа/тейка. Важно: сканер использует те же настройки стратегии (периоды скользящих средних, метод расчёта стопа, R-множитель и т.д.), что заданы для основного графика — отдельной настройки под каждый актив в сканере нет.
Применение
1. Откройте нужный актив и таймфрейм и посмотрите на панель статистики — высокий процент выигрышных сделок и стабильное R:R говорят о том, что рынок сейчас достаточно чисто трендовый для входов по возврату к средней.
2. Если недавний винрейт высокий, рынок соблюдает структуру скользящих средних, и сетап стоит торговать. Если он снижается, рынок может входить в фазу консолидации — лучше дождаться, пока тренд снова выровняется.
3. Используйте отрисованные линии входа/стопа/тейка/безубытка и их ценники для постановки реального ордера.
4. Когда цена достигает отметки безубытка, стоит рассмотреть перевод реального стоп-лосса в точку входа — это решение, на которое индикатор указывает, но не выполняет автоматически.
5. Используйте сканер монет, чтобы следить за другими активами из вашего вотчлиста, не переключаясь постоянно между графиками.
Описание настроек
General (Общие настройки)
• Source — ценовой ряд, по которому рассчитываются обе скользящие средние (по умолчанию — цена закрытия).
Moving Average
• MA fast — период быстрой EMA (по умолчанию 50).
• MA fast line width — толщина линии быстрой EMA.
• MA slow — период медленной EMA (по умолчанию 200).
• MA slow line width — толщина линии медленной EMA.
• Bull color / Bear color — цвет каждой линии MA и заливки между ними (окрашивается в зависимости от текущего направления тренда).
Strategy
• MA Pierce Check Window (bars) — сколько последних баров проверяется на предмет реального прокола быстрой EMA перед закрытием-ретестом (по умолчанию 3).
• Swing Point Lookback (bars) — окно поиска ближайшего свинг-хая/лоу для режима стопа "Свинг", а также используется как часть "прогрева" перед тем, как индикатор начнёт оценивать сигналы (по умолчанию 10).
• Take Profit, R (risk multiple) — целевое расстояние тейк-профита, выраженное как множитель исходного риска (по умолчанию 3 = 3R).
• Max Bars in Open Setup (timeout) — если сигнал не резолвится (не задет ни стоп, ни тейк) за это количество баров, он принудительно закрывается и учитывается отдельно как тайм-аут, а не остаётся открытым бесконечно (по умолчанию 300).
• Stop Loss Calculation Method — выбор между Свинг (high/low), ATR или Процент от цены.
• ATR Length — период усреднения для расчёта ATR (по умолчанию 14).
• ATR Multiplier for Stop — множитель ATR, применяемый, когда метод стопа — ATR (по умолчанию 1.5).
• Stop, % of Entry Price — фиксированное расстояние стопа, используется только в режиме "Процент от цены" (по умолчанию 1%).
• Max Allowed Risk, % of Price — жёсткий лимит расстояния стопа, применяется независимо от выбранного режима, для защиты от аномальных свечей или сбойных тиков в данных (по умолчанию 5%).
• Also Cap Swing Stop by ATR (recommended) — дополнительный, чувствительный к волатильности предохранитель, работающий только в режиме "Свинг", теснее и отзывчивее плоского процентного лимита.
• Max Swing Stop Deviation, x ATR — множитель для указанного выше лимита (по умолчанию 3).
• Move to Breakeven, R (risk multiple) — расстояние в R, на котором рисуется линия отметки безубытка (по умолчанию 1 = 1R).
Visualization
• Show BUY/SELL Labels — вкл/выкл ярлыков сигналов на графике.
• Show SL/TP/BE Price Tags on Lines — вкл/выкл "живых" ценников у правого края каждой линии уровня.
• Fill Risk/Reward Zones — вкл/выкл закрашенных зон риска/прибыли.
• BUY Label Color / SELL Label Color — цвета ярлыков сигналов.
• Entry Line Color / Stop Loss Line Color / Take Profit Line Color / Breakeven Line Color — цвета четырёх линий уровней.
• Reward Zone Color / Risk Zone Color — цвета закрашенных зон.
• Entry/SL/TP Line Width — толщина линий уровней.
Statistics
• Show Statistics Panel — вкл/выкл таблицы статистики на графике.
• Panel Position — угол графика, в котором рисуется таблица.
• Text Size — размер шрифта таблицы.
• Statistics Period — вся история, последние N дней или с фиксированной даты.
• N Days Back — используется, если период статистики — "последние N дней".
• Start Date — используется, если период статистики — "с фиксированной даты".
Symbol Scanner
• Show Scanner for Other Symbols — вкл/выкл таблицы сканера.
• Symbol 1–5 — пять отслеживаемых активов.
• Scanner Timeframe — таймфрейм для сканирования; оставьте пустым, чтобы использовать таймфрейм текущего графика.
• Scanner Panel Position — угол графика, в котором рисуется таблица сканера.
• Scanner Panel Text Size — размер шрифта таблицы сканера.
Алерты
Индикатор включает два готовых условия для алертов — Buy signal и Sell signal — которые срабатывают один раз на закрытии бара и содержат в тексте сообщения цену входа, стоп-лосс, тейк-профит и расстояние до них в тиках, так что действовать по ним можно, не открывая график.
Отказ от ответственности
Этот индикатор — инструмент для технического анализа и планирования сделок, он не является финансовой рекомендацией, а прошлая эффективность сигналов, показанная на панели статистики, не гарантирует результатов в будущем. Всегда сочетайте его использование с собственным управлением риском и оценкой рыночного контекста.
Indicator

Hype Check - Swing: Big Move. Or just HYPE?Is this move actually unusual?
Big candle. Big volume. Everyone suddenly has a thesis.
Cool.
A 4% move in PLTR and a 4% move in KO are not the same event. Over the
last two years PLTR did that once every 4 sessions. KO, once every 125.
Your screener paints both the same shade of green.
something special? NAH.
████░░░░░░ HOLDING THE LOWS
-7.3% from the peak
normal? yes · a normal stretch for QQQ
who's winning nobody · both sides matched
the crowd growing into the fall
next floor 658.20 · 3.4% below, tested twice
above you nothing until 712.40 · 4.6% up
but it closed well off the lows
YEAH . Something unusual is happening.
KINDA . Worth watching. Not enough for a decision.
NAH . Looks dramatic. Statistically, it isn't.
Then it names what the chart is actually doing: BREAKING DOWN, SNAPPING
BACK, HOLDING THE LOWS, COILING, GRINDING UP, RANGE BOUND, and a few more.
THREE THINGS IT DOES DIFFERENTLY
It measures the move, not the calendar. A three day collapse doesn't get
averaged away inside a 20 day window, and a bounce off the low doesn't
erase the fall that came before it.
It sizes levels in the stock's own daily range. Early versions put a
"level" 0.6% away on a stock that routinely moves 8% in a day. Useless.
Now a level only counts if price would have to work to reach it, and the
ones price has turned at more than once are drawn solid.
It will tell you nothing is happening . Most days that is the honest
answer, and most tools won't say it.
YEAH does not mean buy. It means pay attention. A rare move can continue,
reverse or stall, and a great looking setup can still be a bad trade.
No predictions. No magic arrows. No fake certainty.
Rare is not the same as actionable.
Daily swing charts. Free and open source.
Not financial advice.
Indicator

SuperTrend Engine [Quantum Algo]SuperTrend Engine
====================================================
🔶 OVERVIEW
SuperTrend Engine is a volatility-adaptive SuperTrend indicator built on one idea: every SuperTrend gives you signals — this one shows you the whipsaws it saved you from, tells you its real win rate on your chart, and admits when it is wrong.
The engine self-tunes its factor with a fully transparent formula, confirms flips through a Whipsaw Shield that absorbs fake-outs and marks every one it absorbed, stamps every buy and sell flip with its live, honestly-computed win rate on the current symbol, settles every marker into its real outcome ten bars later, and draws the trade geometry — entry, trailing stop, one-R and two-R references — the moment a flip confirms.
🔶 WHAT IS A SUPERTREND?
A SuperTrend is a trailing stop built from the Average True Range: a band placed a volatility-scaled distance from price that ratchets in the trend's favor and never retreats. While price holds above the band, the trend is up and the band trails below as a stop; a close through the band flips the state. It is one of the most followed trend-following tools in retail trading — and its famous weakness is the whipsaw: sideways markets flip it back and forth, and a fixed factor that survives chop is too slow in trends. This engine is built specifically against that weakness.
🔶 WHY THIS SCRIPT IS ORIGINAL
1. The Whipsaw Shield — visible absorbed fake-outs. A flip only confirms when the close clears the opposite band by a volatility margin. When the raw trail flips and reverses before clearing it, the engine holds its direction and prints a small ghost marker where the whipsaw died, with a running Whipsaws Shielded counter in the dashboard. Other tools try to reduce whipsaws quietly; to our knowledge, none renders the failures it absorbed. Here the evidence is on the chart.
2. Honest per-symbol flip statistics. Every flip is stamped with its live win rate on this exact symbol and timeframe — shrinkage-adjusted so thin history cannot show fake confidence, with a Wilson confidence bound and sample count in the hover tooltip. The indicator audits itself in public instead of asserting signals.
3. Markers that settle into their outcome. Each buy and sell marker resolves ten bars later: the trend color if the flip delivered, faded gray if it failed. Scroll any chart and read the engine's true track record directly off the markers — including the losses.
4. Transparent adaptation, not a black box. The factor self-tunes between your two bounds using Perry Kaufman's Efficiency Ratio — tight when price moves cleanly, wide in chop — and the dashboard shows the live factor and efficiency reading every bar. The adaptation can be verified with a calculator; nothing asks for trust.
5. A trade plan, not just a line. On every confirmed flip the engine draws the entry, the trailing stop, and one-R and two-R reference levels, and the dashboard tracks the open signal's running R-multiple live.
6. A breathing chart. The glow between price and trail intensifies with trend distance and fades as price returns to the stop, grade-A flips (volume, efficiency, and a decisive break together) print in the accent color, and the whole layer stays capped and clean.
🔶 HOW IT WORKS
Adaptive trail: Classic ratcheting SuperTrend bands are computed from the Average True Range, with the factor interpolated between the trend bound and the chop bound by the Efficiency Ratio — the ratio of net price movement to total path length over the lookback.
Whipsaw Shield: The raw band flip is treated as a candidate, not a signal. Only a close beyond the opposite band plus the margin confirms the flip; a raw flip that reverses first is counted, marked as a ghost, and absorbed.
Statistics: Each confirmed flip records what price did ten and thirty bars later, in the flip's direction, into capped first-in-first-out databases. Win rates are pulled toward fifty percent by pseudo-samples and carry Wilson lower bounds. Until the minimum sample is met, markers read "collecting history" instead of inventing a number.
Outcome settlement: Every marker stores its flip price and recolors by the realized ten-bar outcome, then joins the capped history.
Grading: Volume z-score, efficiency level, and break decisiveness combine into an A, B, C grade on every flip.
Non-repainting: Flips, shields, grades, statistics, and settlement are all evaluated on closed bars. Once printed, nothing moves.
🔶 HOW TO USE IT
1. Works on any market — cryptocurrency, forex, gold, indices, stocks, futures — and any timeframe. Trending instruments suit tighter trend bounds; choppy ones benefit from a wider chop bound and a larger shield margin.
2. Treat the flip as regime information and the trail as the stop: the line is the invalidation, and the one-R and two-R references scale targets to the risk the stop defines.
3. Read the ghost markers as the tool working: a cluster of × marks in a range is the chop a fixed-factor SuperTrend would have traded.
4. Judge fresh flips against the settled history and the statistics rows — a symbol whose markers keep settling gray is telling you trend-following struggles there, and that is information worth having before the next flip.
5. Use the grade for position confidence: an A-grade flip with volume, high efficiency, and a decisive break is a different event from a drift-through.
6. Watch the live factor and efficiency in the dashboard to see the adaptation reasoning in real time.
🔶 SETTINGS
- Adaptive trail: Average True Range length, factor in strong trend, factor in chop, Efficiency Ratio length.
- Whipsaw Shield: flip margin and ghost marker toggle.
- Statistics: sample cap, minimum samples to grade, shrinkage strength, Wilson z-score, markers to keep.
- Trade plan toggle and plans to keep.
- Visuals: all colors, glow fill, candle tinting.
- Themeable dashboard: position, four text sizes, title band, background, frame, grid, and three text colors.
🔶 ALERTS
- Buy Flip / Sell Flip — the adaptive trail flipped with the confirmation margin cleared.
- Whipsaw Shielded — a raw flip reversed before confirming; the engine held its direction.
- Grade A Flip — full quality confluence: volume, efficiency, and a decisive break.
🔶 FREQUENTLY ASKED QUESTIONS
Does the indicator repaint? No. Every flip, shield event, grade, statistic, and marker settlement is evaluated at bar close. Once printed, nothing moves.
How is this different from other adaptive or machine-learning SuperTrends? Adaptation itself is not the claim — several tools adapt the factor. The differences are transparency and honesty: the adaptation here is one verifiable formula shown live on the dashboard, the whipsaws it absorbs are rendered instead of hidden, every signal carries its real statistics with confidence bounds, and every marker settles into its true outcome.
What does a ghost × marker mean? The raw SuperTrend flipped there and reversed before clearing the confirmation margin. The engine held its direction and counted the whipsaw it absorbed.
Why does a marker turn gray? The flip failed: ten bars later, price had not moved in its direction. Gray markers are the audit trail working — an honest tool must be able to show its losses.
Why do the win rates hover near fifty percent on some symbols? Because that is the truth of trend-flip performance there. The shrinkage and confidence bounds are designed to display small honest numbers rather than large misleading ones.
🔶 CREDITS
The SuperTrend trailing stop was created by Olivier Seban; the Average True Range is by J. Welles Wilder Jr. (1978); the Efficiency Ratio is by Perry J. Kaufman; the Wilson score interval is by Edwin B. Wilson (1927). This script gratefully acknowledges all four. The Whipsaw Shield, the transparent adaptive-factor design, the per-symbol statistical engine, the outcome-settling markers, the trade plan layer, and all code in this script are original work — no third-party or open-source script code was reused.
🔶 LIMITATIONS
Trend-following flips underperform by nature in prolonged ranges; the shield reduces but cannot eliminate that cost, and shielded entries confirm slightly later than raw ones — the margin trades earliness for reliability. Statistics need history to mature and are honest about being thin early. Volume grading is less meaningful on symbols with unreliable volume reporting. No indicator replaces independent analysis.
🔶 DISCLAIMER
This script is provided strictly for educational and informational purposes. It is not financial advice, an investment recommendation, or a solicitation to buy or sell any financial instrument. Past behavior of any flip, statistic, or grade does not guarantee future results. Trading involves substantial risk. Always do your own research and manage risk independently. Indicator

Session Profitability Visualizer
What it shows
Session Profitability Visualizer breaks the trading day into its 24 hours and shows, for each hour, how price has historically behaved on your chart. It answers a simple statistical question: "When this market trades at 09:00 vs. 14:00 vs. 20:00, how have bars in that hour tended to move?"
For every hour with enough data it displays a table with:
- Hour — the hour-of-day bucket (00:00–23:00) in the symbol's exchange timezone
- Cum move — the cumulative close-minus-open of all completed bars in that hour (in points, or in % if you select the percent metric)
- Bars — how many completed bars contributed to that bucket (the sample size)
- % Pos — the share of those bars that closed above their open
Rows are tinted green or red by the sign of the cumulative move, with color intensity scaled by magnitude relative to the strongest hour, so the "heavier" hours stand out at a glance. An optional (off by default) background shading tints the chart by the historical statistics of the hour the current bar belongs to.
How it works
On every completed intraday bar inside the lookback window, the script:
1. Determines the bar's hour of day using the symbol's exchange timezone (syminfo.timezone).
2. Computes the bar's move — either close − open in points, or (close − open) / open × 100 in percent, depending on the Metric input.
3. Adds that move to the hour's running sum, increments the hour's bar count, and increments a positive-bar counter when the move is positive.
The per-hour sums, counts, and positive counts are held in three 24-element arrays. The table is rendered once on the last bar from those arrays. There is no request.security() call, no reference to future data, and only confirmed bars are counted — the statistics do not repaint on historical data (the live, still-forming bar is excluded until it closes).
Inputs
- Lookback (bars) — how many recent bars feed the statistics (default 5000). Larger windows are more stable; smaller windows react faster to regime changes.
- Metric — Points (close − open) or Percent (bar return %). Percent is more comparable across price levels and long histories.
- Min samples per hour — hours with fewer completed bars than this are hidden (default 30), so thin buckets don't masquerade as meaningful.
- Table position — where the table sits on the chart.
- Shade background — optional tint of the current bar's hour by its historical stats (off by default).
How to use it
Apply it to any intraday chart (15m or 1h are good starting points — on a 15m chart each hour bucket gets four bars per session). Look for hours where the cumulative move and the % positive rate agree and the sample count is healthy; those are the hours where the market has shown a persistent directional lean on your symbol. Compare the same symbol on different lookbacks to see whether the pattern is stable or an artifact of one period.
Limitations — please read
- Hour buckets use the symbol's exchange timezone, not your chart's display timezone. A "09:00" row on NASDAQ symbols means 09:00 America/New_York regardless of your local clock.
- Bar close-minus-open is a directional proxy, not trade P&L. It ignores spreads, slippage, position sizing, and intrabar path.
- The statistics are a historical observation, not a prediction. An hour that has drifted up for 5000 bars can stop doing so at any time; sample sizes shrink quickly on higher intraday timeframes.
- The script is intraday-only by design; on daily and above it shows an explanatory message instead of statistics.
This is a statistical visualization tool. It does not generate signals or recommendations of any kind.
Indicator

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

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

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

IB / ORB Live Stats# IB / ORB Live Stats — Publication Description
---
## What This Indicator Does
The **IB / ORB Live Stats** indicator studies the relationship between the **Initial Balance (IB)** and a user-defined **Opening Range Breakout (ORB)** window, and builds its probability statistics **live, from the history on your own chart** — there are no pre-supplied or hard-coded numbers anywhere in this script. Every percentage you see is computed from the completed sessions visible on the current symbol and timeframe, so the statistics describe exactly the instrument you are looking at.
Rather than issuing buy/sell signals, the indicator answers structural questions about how each session tends to behave:
- When the IB **high** forms before the IB **low**, which side tends to **break first** afterward — and vice versa?
- Does the side that formed first also tend to break first (a continuation tendency), or reverse?
- Do these tendencies change when the range is unusually **wide** or **narrow**?
- When the ORB closes bullish or bearish, how often does the IB end up bullish or bearish?
It draws a box and midpoint for both the IB and the ORB, and presents two independent, separately-configurable statistics tables — one for the IB, one for the ORB.
---
## Core Concepts and Definitions
Before the statistics make sense, it helps to define each term precisely as the script uses it.
### Initial Balance (IB)
The price range established during the IB window (default **09:30–10:30 ET**). The IB high is the highest traded price and the IB low the lowest traded price during that hour. The IB midpoint is the average of the two.
### Opening Range Breakout (ORB)
A shorter range measured from the open. You set its length in **minutes** (default **15**), and the script builds the corresponding session window automatically. The ORB high, low and midpoint are defined the same way as the IB's.
### Formed First (the order of the extremes)
For each window, "formed first" identifies whether the session **high** or the session **low** was reached **earlier in time**. This is the single most important measurement in the script, and it is deliberately **not** judged from chart bars. A single chart candle frequently contains both the session high and the session low, which makes any bar-by-bar guess unreliable. Instead, the script requests **1-minute intrabar data** and walks those sub-bars in chronological order: the first 1-minute bar whose high reaches the final session high, versus the first whose low reaches the final session low — whichever comes earlier is the extreme that "formed first."
### Broke First (the order of the breakouts)
Once a window's formation period closes, the script watches for price to trade **beyond** that window's high or low. "Broke first" records which side was exceeded **first** during the rest of the regular session. Like formed-first, this uses the 1-minute intrabar feed so a large chart candle cannot hide the true sequence. If neither side is exceeded before the regular session ends, broke-first is recorded as **"none" (Neither)**.
### Direction (Bullish / Bearish / Neutral)
A single composite read of the window, combining where it formed first with where it closed:
- **Bullish** — the **low** formed first **and** the window closed in its **upper** half.
- **Bearish** — the **high** formed first **and** the window closed in its **lower** half.
- **Neutral** — every other combination (mixed signals).
The same definition is applied to both the IB and the ORB so the two can be compared like-for-like.
### Range Size: Narrow / Normal / Wide
Each window's range (high minus low) is classified **relative to its own prior history on the chart**. The classification is computed **before** the current session is added to the history, so "Wide" genuinely means wide relative to the past, not relative to a sample that already includes today. Two methods are available:
- **Z-Score** — today's range is expressed as a number of standard deviations from the historical mean. A range at or below `−Z band` is **Narrow**; at or above `+Z band` is **Wide**; in between is **Normal**.
- **Percentile** — today's range is ranked against history. At or below the Narrow percentile cutoff it is **Narrow**; at or above the Wide cutoff it is **Wide**; in between is **Normal**.
---
## The Statistics Tables, Explained Line by Line
There are two tables — **IB LIVE STATS** and **ORB LIVE STATS** — each with the same structure. The ORB table adds one extra section (the ORB-to-IB contingency) at the bottom.
### Top block — today's live readout
- **Formed first** — for the current session: `HIGH`, `LOW`, `pending` (window not yet complete), or `—` (could not be resolved, e.g. no intrabar data).
- **Broke first** — `HIGH`, `LOW`, `pending` (window not complete), `watching…` (window complete, no break yet this session), or `none` (session ended with no break).
- **Range** — today's range value, followed where available by its z-score (`z=`) and its percentile rank (`%`) against history.
- **Type** — the Narrow / Normal / Wide classification of today's range.
- **Direction** — today's Bullish / Bearish / Neutral composite.
### Cross-tabulation block — the formed-first by broke-first matrix
This is the heart of the tool. It answers: *given which extreme formed first, which side then broke first?* The columns are **BrkH** (broke high first), **BrkL** (broke low first) and **Neither**. There are two rows:
- **HIGH (n)** — all completed sessions where the **high** formed first. The three percentages show how often, within those sessions, the high broke first, the low broke first, or neither side broke. `n` is the number of such sessions.
- **LOW (n)** — the same, for sessions where the **low** formed first.
Each row sums to 100% across its three columns. Reading across the HIGH row tells you, when the high formed first, whether the market tends to continue up (BrkH) or reverse down (BrkL).
- **Same side broke 1st** — a single summary figure: across **all** completed sessions, how often the side that formed first was also the side that broke first. This is the overall **continuation tendency**; a high value means formed-first tends to predict broke-first, a low value means the market tends to reverse the early extreme.
### BY SIZE block — does range size change behavior?
This block splits every completed session into its size bucket and reports, per bucket:
- **Size** — Narrow, Normal or Wide. The bucket matching **today's** session is highlighted.
- **n** — number of completed sessions in that bucket.
- **Brk%** — of those sessions, how often **any** side broke (i.e. the session was not a "Neither" day).
- **Cont%** — of those sessions, how often the side that formed first also broke first (the continuation tendency, but isolated to that size bucket).
This is where the size classification earns its place: you can see directly whether, say, Wide ranges break and continue more often than Narrow ones.
### ORB-to-IB contingency block (ORB table only)
This answers how the early ORB read relates to the later IB outcome. It is a small matrix with the columns **IB Bull**, **IB Bear** and **IB Neut**, and two rows:
- **Bullish (n)** — all completed days where the **ORB** direction was Bullish. The three percentages show how the **IB** direction turned out on those days. `n` is the count.
- **Bearish (n)** — the same, for days where the ORB direction was Bearish.
Each row sums to 100%. The Bullish row directly answers "when the ORB is bullish, how often is the IB also bullish, bearish, or neutral?"
### The "Min sample" dimming rule
Any percentage drawn from fewer completed days than the **Min sample** input is shown in grey rather than its normal colour. This is a guard against over-reading thin data — a 100% figure from 2 sessions is meaningless, and the dimming makes that visually obvious while still letting the count build.
---
## How To Use This Indicator
### Recommended setup
Run it on a **1-minute chart** for the most accurate formed-first and broke-first detection. A 5-minute chart is the practical maximum; on higher timeframes the 1-minute intrabar window loses resolution and the ordering of extremes becomes less reliable. Make sure your chart has enough history loaded — the statistics only accumulate from sessions actually present on the chart, so a fresh chart starts empty and fills in over days of scrolled-back or elapsed history.
### A typical workflow
1. **Let it build.** The longer the history on the chart, the larger every `n`. Figures stay greyed out until they pass the Min sample threshold.
2. **Read the cross-tab.** In the IB table, look at the HIGH and LOW rows to see whether the first extreme tends to lead to continuation or reversal on your instrument.
3. **Check the size split.** In the BY SIZE block, compare Brk% and Cont% across Narrow / Normal / Wide to see whether range size meaningfully changes behavior. Today's bucket is highlighted for quick reference.
4. **Use the ORB-to-IB contingency** to gauge whether the early ORB direction is informative about how the IB resolves.
5. **Combine with your own analysis.** These figures are descriptive context, not signals.
---
## Inputs and Configuration
Every input is listed below with its default and its effect.
### Sessions group
- **IB Period (ET)** — the Initial Balance window. Default `0930-1030`.
- **ORB Period (minutes from 09:30)** — the ORB length in minutes. Default `15`, range `1–120`. The script builds the actual session window from this (e.g. 15 → 09:30–09:45) so you never edit a session string for the ORB.
- **RTH (ET)** — the regular trading hours window during which breaks are tracked and after which each day's outcome is recorded. Default `0930-1600`.
- **Intrabar resolution** — the lower timeframe used for first-touch detection. Default `1` (one minute). This must be at or below your chart timeframe; one minute is strongly recommended.
### IB/ORB Type group
- **Size method** — `Z-Score` or `Percentile`, selecting how Narrow / Normal / Wide is decided. Default `Z-Score`.
- **Z band (Narrow<=-z, Wide>=+z)** — the z-score threshold used by the Z-Score method. Default `0.5`. A range at or below −0.5 SD is Narrow, at or above +0.5 SD is Wide.
- **Narrow <= percentile** — the percentile cutoff for Narrow when using the Percentile method. Default `33`.
- **Wide >= percentile** — the percentile cutoff for Wide when using the Percentile method. Default `67`.
### Display group
- **Show IB (box)** — draw the IB box and midpoint. Default on.
- **Show ORB (box)** — draw the ORB box and midpoint. Default on.
- **Show NY Open Line** — draw a vertical line at the regular-session open. Default on.
- **Box Transparency** — transparency of the box fills, `50–95`. Default `88` (higher is more transparent).
- **IB / ORB / NY Line colours** — colour pickers for each element.
### Tables group
- **Show IB Table** — master toggle for the IB statistics table. Default on.
- **IB Position** — one of nine on-chart positions for the IB table. Default Top Right.
- **IB Text Size** — Tiny / Small / Normal / Large. Default Tiny.
- **Show ORB Table** — master toggle for the ORB statistics table. Default on.
- **ORB Position** — nine-position selector for the ORB table. Default Top Left.
- **ORB Text Size** — Tiny / Small / Normal / Large. Default Tiny.
- **Min sample (dim below)** — the minimum number of completed days a percentage must be based on before it is shown in full colour rather than grey. Default `30`, range `5–200`.
---
## How the Calculations Work (methodology)
All statistics are computed on-chart, in real time, with no external data:
1. **During each window**, the script accumulates the running high and low and collects every 1-minute sub-bar's high and low.
2. **At window close (seal)**, it walks the collected 1-minute bars in order to determine which extreme was reached first, classifies the range size against prior history, computes the composite direction, and freezes the box and midpoint at the closing bar.
3. **After the window, through the regular session (watch)**, it scans the 1-minute feed for the first break of either side and records broke-first.
4. **At the regular-session close (tally)**, it increments the cumulative counters — the formed-first by broke-first cross-tab, the size buckets, and (for the ORB) the ORB-to-IB direction contingency — so each completed day is counted exactly once.
The boxes and midpoints are **frozen** at each window's close; they do not extend across the day.
---
## Important Limitations and Considerations
1. **History-dependent.** All statistics come only from sessions present on your chart. A fresh chart has no sample; figures grow over time and stay greyed until they pass the Min sample threshold. The depth of history PulseWire loads depends on your plan and the chart timeframe.
2. **Intrabar accuracy.** Formed-first and broke-first rely on the 1-minute feed and are most accurate at or below 5-minute chart resolution. On higher timeframes the ordering can be wrong.
3. **Same-sub-bar ties.** If a single 1-minute bar contains both a new extreme and a break of the opposite side simultaneously, the tie is resolved in favour of the high. This is rare but worth knowing.
4. **Descriptive, not predictive.** The indicator reports what has happened on your data. It does not forecast, and it issues no signals. Past frequency does not guarantee future behavior — a 70% tendency still failed 30% of the time.
5. **Not financial advice.** Use these statistics as objective context alongside your own strategy and risk management, never as a substitute for judgement.
---
*This is an analytical and educational tool. It does not provide buy or sell signals and makes no claim about future price direction.* 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

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

Indicator

Candle Pattern Winrate Stats ## 📊 Candle Pattern Winrate Stats
This indicator is designed to transform candlestick patterns from subjective, belief-based signals into objective, data-driven statistics.
It automatically evaluates the historical performance (winrate) of multiple candlestick patterns directly on your chart.
---
## 🔍 Core Concept
Instead of assuming that a pattern works, this script answers a more important question:
"Does this pattern actually have a statistical edge?"
The indicator:
- Detects predefined candlestick patterns (e.g., Hammer, Doji, Engulfing)
- Records each occurrence as a discrete event
- Evaluates price movement after a fixed number of candles (lookforward window)
- Classifies outcomes as Win or Loss
- Aggregates results into a measurable winrate
This allows traders to move from visual interpretation → to empirical validation.
---
## ⚙️ How It Works
### 1. Pattern Detection
Supports multiple pattern categories:
- Bullish Reversal (1 / 2 / 3 candles)
- Bearish Reversal
- Shadow-based patterns (Hammer, Shooting Star)
- Neutral patterns (Doji, Spinning Top)
Each pattern can be enabled or disabled independently.
---
### 2. Winrate Calculation Logic
For every detected pattern:
- A forward window (X candles) is defined
- Price movement is evaluated after that window
- If price moves in the expected direction → Win
- Otherwise → Loss
All results are stored and continuously updated to reflect real historical performance.
---
### 3. Filtering (Noise Reduction)
Optional filters improve signal quality:
- EMA Trend Filter
Restricts signals based on trend direction (e.g., bullish patterns only above EMA)
- Volume Filter
Filters out low-volume conditions using a moving average of volume
These filters help isolate higher-quality statistical samples.
---
### 4. Statistical Controls
- Min Samples
Displays only patterns with sufficient sample size to avoid unreliable conclusions
- Percentile Lookback
Normalizes performance relative to recent market conditions
- Tolerance (%)
Defines acceptable similarity between price values (e.g., open ≈ close)
---
## 🔬 Methodology & Statistical Framework
This script treats each candlestick pattern as a discrete statistical event rather than a visual signal.
For every detected pattern:
- A fixed forward return horizon is applied (lookforward window)
- Outcomes are simplified into binary classification (win / loss)
- Empirical probabilities are derived from aggregated historical samples
Unlike traditional candlestick indicators, this approach enables:
- Objective measurement of pattern performance
- Direct comparison across different pattern types
- Reduction of subjective bias in decision-making
---
## 📋 Output
- Winrate (%) for each pattern
- Number of samples (data reliability)
- On-chart summary table (customizable position)
---
## 🧠 Professional Usage
❌ Avoid:
- Using patterns as direct entry signals
✅ Recommended:
- Use winrate as a filtering tool
- Focus on statistically significant patterns
- Combine with:
- Market Structure
- Supply / Demand
- Trend context
---
## 📊 Example Interpretation
Pattern | Winrate | Sample | Insight
---|---|---|---
Hammer | 62% | 120 | Usable
Doji | 48% | 300 | No statistical edge
Engulfing | 68% | 80 | Strong signal
---
## ⚠️ Important Notes
- Winrate ≠ Profit (risk/reward must be considered)
- Market conditions evolve → statistics may change over time
- Results vary across different timeframes and assets
- Be cautious of overfitting when sample size is small
---
## 🎯 Who Is This For
- System traders
- Quantitative / data-driven traders
- Developers building trading bots (MQL5, Pine Script, Python)
- Traders seeking objective validation over subjective analysis
---
## 🚀 Key Insight
"Does this pattern actually work — or does it just look like it does?"
Indicator

ICT Weekly ProfilesOverview
ICT Weekly Profiles is an advanced analytical tool designed to map, classify, and quantify recurring weekly price behavior based on Inner Circle Trader (ICT) concepts.
This indicator transforms raw price action into a structured weekly profile by identifying where the market forms its high, low, and directional bias, while also providing a statistical ranking of recurring patterns.
The goal is simple:
to help traders understand how the market tends to behave throughout the week and use that information to anticipate future movements.
------------------------------------------------------------------------------------
Core Concept
Markets often follow recurring behavioral patterns during the week, such as:
Tuesday High or Low formations
Wednesday reversals
Thursday consolidations
Friday expansions
This indicator automatically detects and classifies these behaviors into well-defined weekly profiles, allowing traders to identify the dominant market structure.
Weekly Profile Structure
Each week is represented visually through:
------------------------------------------------------------------------------------
1. Price Range Box
A box is drawn from the weekly high to the weekly low.
Bullish profiles are highlighted in green
Bearish profiles are highlighted in red
This provides a clear visual representation of the weekly range and directional bias.
------------------------------------------------------------------------------------
2. Market Structure Lines
The weekly movement is broken down into three segments:
Open → High → Low → Close
or
Open → Low → High → Close
This reveals the order of price events, which is critical in ICT-style analysis.
------------------------------------------------------------------------------------
3. Profile Label
Each week is labeled according to its behavior, for example:
Classic Tuesday Low of the Week
Wednesday High of the Week
Consolidation Thursday Bullish Reversal
These labels describe how the market formed its structure during the week.
------------------------------------------------------------------------------------
Profile Classification Logic
The indicator classifies each week based on the day where the high and low occur.
Bullish Profiles
Tuesday Low of the Week
Wednesday Low of the Week
Thursday Bullish Reversal
Midweek Rally
Bearish Profiles
Tuesday High of the Week
Wednesday High of the Week
Thursday Bearish Reversal
Midweek Decline
This classification reflects institutional accumulation and distribution behavior.
------------------------------------------------------------------------------------
Live Mode (Real-Time Analysis)
While the week is still active, the indicator dynamically updates:
Current weekly high and low
Structure lines
Active profile classification
The label is displayed as (LIVE) until the week closes.
------------------------------------------------------------------------------------
Statistical Ranking System
One of the most powerful features of this indicator is its built-in ranking system.
It tracks:
Total number of analyzed weeks
Frequency of each profile
Percentage occurrence
Typical day where the high or low forms
This transforms the indicator from a visual tool into a quantitative decision-making system.
------------------------------------------------------------------------------------
Timezone Flexibility
The indicator allows you to select different timezones:
London
New York
Tokyo
This ensures accurate session alignment and correct weekly structure depending on the market being analyzed.
------------------------------------------------------------------------------------
Market Sessions Visualization
Optional session tracking is included:
Asia
London
New York
Features:
Session markers (dots)
Session labels
Optional background coloring
This helps identify where liquidity and volatility are concentrated during the week.
------------------------------------------------------------------------------------
Market Open Filter
The script automatically filters out periods when the market is closed:
After Friday 17:00 New York time
Before Sunday 17:00 New York time
This prevents distorted data and improves accuracy.
------------------------------------------------------------------------------------
Customization Options
Users can customize:
Box colors (bullish / bearish)
Text and line colors
Ranking table position
Session visualization settings
Transparency levels
------------------------------------------------------------------------------------
Practical Usage
This indicator can be used to:
Identify dominant weekly patterns
Anticipate where highs or lows are likely to form
Establish directional bias early in the week
Improve timing when combined with liquidity or structure-based strategies
------------------------------------------------------------------------------------
Strengths
Based on institutional trading concepts (ICT)
Combines structure and statistics
Works across all markets (Forex, Crypto, Indices)
Provides both real-time and historical analysis
Offers probabilistic insights through ranking
------------------------------------------------------------------------------------
Limitations
Does not incorporate volume analysis
Focuses on structural behavior rather than momentum strength
Relies on OHLC data only
------------------------------------------------------------------------------------
Conclusion
ICT Weekly Profiles is more than a visual indicator.
It is a structured framework for understanding how the market behaves on a weekly basis.
By combining pattern recognition with statistical validation, it helps traders answer key questions:
Where is the market likely to form its high or low?
Which weekly patterns are most frequent?
What is the current institutional bias? Indicator

Liquidity Entry ZonesLiquidity Entry Zones
Liquidity Entry Zones is an open-source liquidity-sweep entry framework built around one specific analytical idea:
when price moves through a recently formed liquidity level, then reclaims back through that area with acceptable candle quality and directional context, that event can be treated as a structured entry opportunity rather than as a generic wick sweep or random rejection candle.
This script is not designed to mark every swing high or swing low, and it is not intended to behave like a generic support/resistance overlay, a basic pivot script, or a simple “liquidity sweep detector” that treats every sweep in the same way. Its purpose is to store recent liquidity levels, detect meaningful sweeps through those levels, validate reclaim behavior, filter the candle using quality conditions, confirm the setup inside a limited time window, and optionally project a fixed-risk trade structure on the chart for review. :contentReference {index=1}
The script also includes optional sweep guides, signal visuals, a compact status panel, and an internal trade simulation layer so users can inspect how the framework behaves under the chosen settings. Those review tools are included to support chart study and comparison, not to imply future performance. :contentReference {index=2}
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 PulseWire 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 needing to reverse-engineer the code line by line.
OVERVIEW
At a high level, the script does seven things:
1. It stores recent pivot highs and pivot lows as liquidity reference levels.
2. It checks whether price sweeps through one of those stored levels by a minimum pip distance.
3. It requires reclaim behavior after the sweep, using either a close-back-inside rule or a stronger reclaim condition.
4. It filters the sweep candle using wick percentage, body percentage, candle range, optional EMA context, and optional midline confirmation.
5. It allows a limited confirmation window after the sweep so entries are not forced to happen only on the exact sweep bar.
6. It can project a fixed take-profit / stop-loss model and track simulated outcomes.
7. It summarizes the current state and projected results in a status panel.
The script is therefore meant to function as a complete liquidity-sweep reclaim framework rather than as a single-purpose pivot or line-drawing tool. :contentReference {index=3}
CORE IDEA
Many sweep-based tools detect only one event: price traded above a prior high or below a prior low.
This script takes a narrower and more selective approach.
Its central assumption is that a sweep alone is not enough. A useful entry event requires more than just temporary liquidity violation. The script therefore asks additional questions:
- Was the swept level a recent stored liquidity level derived from pivot structure?
- Did price move far enough beyond that level to qualify as a real sweep?
- Did price reclaim back through that area in a meaningful way?
- Was the sweep candle structurally acceptable in terms of wick, body, and range?
- Did the confirmation happen within a defined number of bars?
- Was the signal aligned with the optional EMA context?
- Did the confirmation candle behave the way the selected setup requires?
Because of that, the script does not treat all sweeps equally. It attempts to organize the process into a more selective sequence:
first identify liquidity,
then detect a sweep,
then validate reclaim quality,
then confirm within a limited window,
then project the resulting setup into a standardized chart-review structure.
That narrower focus is the main reason the script exists in its current form. :contentReference {index=4}
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 role inside the same analytical process:
- Pivot storage defines where recent liquidity levels exist.
- Sweep detection checks whether those levels have actually been taken by price.
- Reclaim logic checks whether price closes back through the swept area in a meaningful way.
- Candle-quality filters reduce weak or low-information sweeps.
- The EMA filter provides optional directional context.
- The confirmation window prevents stale sweeps from remaining valid indefinitely.
- The cooldown logic reduces clustered signals.
- The trade simulation layer maps the resulting setup into a consistent risk framework.
- The panel organizes current state and projected review metrics into one readable output.
These layers are interdependent.
Without the pivot-based liquidity storage, there is no structured level to sweep.
Without the minimum sweep distance, trivial overextensions would count too easily.
Without reclaim validation, the script would mark many sweeps that never actually regained the level.
Without wick/body/range filters, weak candles would be treated too similarly to stronger rejection candles.
Without the confirmation window, old sweep conditions could stay alive for too long.
Without the EMA filter, the framework would lose one of its optional directional context filters.
Without the simulation layer, the user would still need to draw projected entry, stop, and target structure manually.
Without the status panel, the user would have less organized feedback when monitoring current sweep state, bias, and simulated results.
For that reason, the script is intended as a single liquidity-reclaim framework, not as a random bundle of unrelated features. :contentReference {index=5}
WHAT THE SCRIPT DOES
The script stores recent pivot highs and lows as liquidity levels, then watches for price to trade through those levels by at least the selected sweep distance in pip terms.
Once a sweep occurs, the script can evaluate whether the candle reclaimed back through the level. That reclaim can be interpreted in one of two ways:
- Close Back Inside
- Strong Reclaim
After that, the script can apply candle-quality filters based on:
- wick percentage,
- body percentage,
- minimum candle range,
- optional EMA alignment,
- optional midline-break confirmation,
- and candle-body direction for long or short confirmation.
If the setup remains valid within the selected confirmation window, the script can confirm a BUY or SELL signal.
When enabled, the simulation layer can then project:
- entry,
- fixed stop loss,
- fixed take profit,
- entry zone,
- target box,
- stop box,
- entry and invalidation lines,
- and active trade labels.
The script can also show sweep guides, signal markers, bar coloring, and a status panel summarizing its current state and projected statistics. :contentReference {index=6}
HOW THE SCRIPT WORKS
1) LIQUIDITY LEVEL STORAGE
The script uses pivot highs and pivot lows to create recent liquidity reference points.
A pivot high becomes a candidate buy-side liquidity reference.
A pivot low becomes a candidate sell-side liquidity reference.
The script stores a configurable number of recent levels so that sweep detection is based on previously identified structural points rather than arbitrary price movement. This makes the framework level-based rather than purely candle-based. :contentReference {index=7}
2) SWEEP DETECTION
Once liquidity levels are stored, the script checks whether current price moves beyond a recent level by at least the configured minimum sweep distance.
For a bearish sweep setup:
price must move above a stored high.
For a bullish sweep setup:
price must move below a stored low.
This distance is measured in pip terms using the selected pip-size logic. That means the same script can adapt to forex, JPY pairs, gold, or index-style symbols more consistently, assuming the pip mode is set correctly. :contentReference {index=8}
3) RECLAIM RULE
A sweep alone is not enough.
After the level is taken, the script requires reclaim behavior. It supports two reclaim interpretations:
Close Back Inside:
price must close back inside the swept level.
Strong Reclaim:
price must close back inside the swept level and also close beyond the candle midline in the reclaim direction.
This is important because many sweep candles do not actually reclaim decisively. The reclaim rule exists to distinguish “level taken” from “level taken and then actively rejected back through.” :contentReference {index=9}
4) CANDLE QUALITY FILTERS
The script evaluates sweep-candle quality using:
- minimum wick percentage,
- maximum body percentage,
- minimum candle range in pips.
This means the framework prefers sweeps where the wick expresses the actual sweep behavior and the body does not dominate too heavily relative to the total candle. The minimum-range filter helps avoid very small candles that technically sweep a level but do not carry enough information.
The script also allows:
- long confirmation must be bullish,
- short confirmation must be bearish.
These body-direction filters make the confirmation stricter and help align the final signal with the intended reclaim direction. :contentReference {index=10}
5) OPTIONAL EMA CONTEXT
The script includes an optional EMA trend filter using a configurable EMA length.
If enabled:
- long-side confirmations require price above the EMA,
- short-side confirmations require price below the EMA.
This does not turn the script into a full trend-following system. Instead, it acts as a directional context filter designed to reduce signals that reclaim against the selected EMA bias. :contentReference {index=11}
6) CONFIRMATION WINDOW
The script does not require the final entry to happen only on the exact sweep candle.
Instead, when a valid sweep is detected, it can remain eligible for a limited number of bars. During that confirmation window, the script checks whether the final bullish or bearish confirmation conditions are met.
This matters because some traders want the sweep candle itself to reclaim strongly, while others want to allow one or two bars for the actual confirmation to develop. The confirmation window makes that possible without letting very old sweep conditions remain valid indefinitely. :contentReference {index=12}
7) MIDLINE CONFIRMATION
The script also supports an optional requirement that price close beyond the midpoint of the sweep candle.
For bullish confirmation:
price must close above the sweep candle midpoint.
For bearish confirmation:
price must close below the sweep candle midpoint.
This adds an additional reclaim-strength condition and is intended to reduce weaker closes that technically qualify but do not show enough directional reclaim behavior. :contentReference {index=13}
8) SIGNAL COOLDOWN
The script includes a cooldown period between signals.
Once a signal fires, the framework waits the configured number of bars before allowing a new one. This reduces clustered signals and prevents the chart from rapidly stacking similar setups in a short space of time. :contentReference {index=14}
9) QUALITY SCORE
The script computes an internal quality score for the sweep using a weighted combination of:
- wick contribution,
- body contribution,
- candle-range contribution,
- EMA alignment,
- reclaim success,
- and midline-break success.
This score is used as an internal summary of signal quality and also appears in the panel or labels depending on the visual configuration.
The score is not a guarantee of outcome. It is simply an internal ranking model that summarizes how well the current setup meets the script’s own filter conditions. :contentReference {index=15}
10) TRADE SIMULATION
When enabled, the script can simulate a fixed-risk trade projection.
For long signals:
- entry is placed at close,
- TP is placed above entry by the selected take-profit pip distance,
- SL is placed below entry by the selected stop-loss pip distance.
For short signals:
- entry is placed at close,
- TP is placed below entry by the selected take-profit pip distance,
- SL is placed above entry by the selected stop-loss pip distance.
The simulation can also:
- block new signals while a trade is active,
- keep or hide stopped trades,
- draw entry zone, target zone, stop zone, entry line, invalidation line, and projection line,
- track total trades, wins, losses, and net pips.
This is a chart-review tool, not an execution engine. Its purpose is to make the framework easier to inspect after the signal appears. :contentReference {index=16}
11) SAME-BAR PRIORITY
In the version you shared, same-bar TP/SL handling is conservative: if both target and stop appear to be touched on the same bar after entry, SL takes priority. This matters because bar data alone does not reveal exact intrabar order, and a strict rule prevents artificially optimistic results. :contentReference {index=17}
12) PANEL AND STATE MODEL
The status panel summarizes the current internal state of the framework. It can display items such as:
- whether simulation is on,
- current EMA-based bias,
- sweep state,
- signal state,
- quality score,
- volatility state,
- session state,
- risk state,
- total trades,
- win rate,
- net pips,
- max drawdown in pips.
This panel is meant to condense the script’s state into one readable location rather than force the user to infer everything visually from price bars and labels alone. :contentReference {index=18}
WHAT MAKES THIS SCRIPT ORIGINAL
This script uses familiar building blocks such as:
- pivots,
- liquidity sweeps,
- EMA filtering,
- candle wick/body analysis,
- fixed TP/SL simulation,
- status panels.
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 those familiar elements are arranged into one selective workflow:
pivot-based liquidity storage
→ minimum-distance sweep detection
→ reclaim validation
→ wick/body/range quality filtering
→ optional EMA alignment
→ limited-bar confirmation
→ cooldown control
→ fixed-risk trade projection
→ status-panel review
That full sequence is the main reason this script exists as its own publication.
It is not intended to be simply another pivot script, another stop-hunt detector, another EMA tool, or another TP/SL box script. It is specifically a liquidity-reclaim entry framework that combines structural level storage, sweep validation, candle-quality filtering, confirmation logic, and projected review in one workflow. :contentReference {index=19}
WHAT APPEARS ON THE CHART
Depending on settings, the chart may display:
- EMA filter,
- sweep guides,
- signal markers,
- BUY / SELL labels,
- signal bar coloring,
- entry zone,
- target zone,
- stop zone,
- entry line,
- invalidation line,
- projection path,
- status panel,
- TP / SL hit labels.
Users who want a cleaner chart can disable some visual components and keep only the layers most relevant to their workflow. :contentReference {index=20}
HOW TO USE THE SCRIPT
A practical workflow is:
1. Add the script to a standard candlestick chart.
2. Choose the correct pip mode for the instrument you are analyzing.
3. Set the pivot length and stored-level count to define how the script builds liquidity references.
4. Set the minimum sweep distance so trivial level violations are filtered out.
5. Choose the reclaim rule you want to use.
6. Configure candle-quality filters such as wick %, body %, and minimum range.
7. Decide whether to use the EMA trend filter.
8. Decide whether to require midline confirmation.
9. Choose the confirmation window and cooldown length.
10. If simulation is enabled, set TP and SL distances and decide whether new signals should be blocked while a trade is active.
11. Wait for a confirmed bullish or bearish liquidity reclaim.
12. Use the projected trade structure and panel as an analysis framework rather than as a blind instruction.
13. Review how the same rules behave over time and across symbols before relying on the framework in a live decision process. :contentReference {index=21}
This script is best understood as a structured decision-support and chart-review tool, not as a fully self-sufficient trading system.
SETTINGS REFERENCE
Trend Filter
- EMA Length: sets the EMA used for optional directional context.
- Use EMA Trend Filter: enables or disables EMA filtering.
Pip Settings
- Pip Mode: controls how pip size is interpreted for the current instrument.
Liquidity Sweep Detection
- Swing Pivot Length: defines the pivot depth used to create liquidity levels.
- Stored Liquidity Levels: controls how many recent levels remain in memory.
- Minimum Sweep Distance (Pips): defines how far price must move beyond a level to count as a sweep.
- Reclaim Rule: selects whether reclaim is based on close back inside or a stronger reclaim condition.
Candle Quality Filters
- Minimum Sweep Wick %: minimum wick contribution required from the sweep candle.
- Maximum Body %: maximum body share allowed for the sweep candle.
- Minimum Candle Range (Pips): minimum size required for the sweep candle.
- Long Confirmation Must Be Bullish: requires bullish body for long confirmations.
- Short Confirmation Must Be Bearish: requires bearish body for short confirmations.
Entry Confirmation
- Max Bars After Sweep For Confirmation: limits how many bars can pass before confirmation expires.
- Require Sweep Candle Midline Break: adds midpoint-based reclaim confirmation.
- Cooldown Bars Between Signals: prevents signals from clustering too closely.
Trade Simulation
- Enable Internal Trade Simulation: enables or disables projected trade logic.
- Take Profit (Pips): projected target distance.
- Stop Loss (Pips): projected stop distance.
- Block New Signals While Trade Is Active: prevents overlapping simulated trades.
- Show Stopped Trades: controls whether stopped-out trades remain visible.
Visual Settings
- Show Signal Labels: shows or hides BUY / SELL labels.
- Show Entry Line: shows or hides the projected entry line.
- Show Status Panel: enables or disables the panel.
- Color Signal Bars: colors confirmed signal bars.
- Show Sweep Guides: enables or disables sweep-guide visuals.
- Guide Extension Bars: controls how far guides extend.
- Signal Label Size: controls label size.
- Panel Position: controls panel location. :contentReference {index=22}
IMPORTANT PRACTICAL NOTE ON PIP MODE
The script uses pip-based calculations for:
- sweep distance,
- minimum candle range,
- take-profit distance,
- stop-loss distance.
Because of that, pip interpretation is critical.
If sweeps appear too small, too large, too frequent, too rare, or if projected TP/SL distances look inconsistent for the instrument being analyzed, the first setting to verify is Pip Mode. This is especially important on gold, JPY pairs, index-style symbols, and broker-specific tick formats. :contentReference {index=23}
LIMITATIONS AND SHORTCOMINGS
This script has important limitations:
- It is a liquidity-reclaim model, not a full market-structure engine.
- It only evaluates sweeps of stored pivot-based levels.
- It does not identify fair value gaps, order blocks, or discretionary structure beyond the stored liquidity levels.
- Signal quality depends heavily on the selected wick/body/range filters.
- EMA filtering is optional and only provides one form of directional context.
- The confirmation window can materially change signal frequency and behavior.
- The simulation layer uses simplified projected TP/SL logic and is not equivalent to real execution.
- Same-bar TP/SL handling uses a rule-based priority rather than true intrabar reconstruction.
- Historical projected outcomes should not be interpreted as guaranteed tradable results.
- No sweep-based 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. :contentReference {index=24}
WHO THIS SCRIPT MAY BE USEFUL FOR
This script may be useful for traders who:
- focus on liquidity sweeps and reclaim behavior,
- want a rules-based alternative to purely discretionary sweep reading,
- want candle-quality filters in addition to simple level breaks,
- want optional EMA context for directional alignment,
- want projected entry/TP/SL structure on the chart,
- want a compact state panel for monitoring the framework.
It may be less suitable for traders who:
- want a minimal pivot-only tool,
- want a complete multi-concept smart-money framework,
- want a full execution engine,
- want historical projected results to be treated as live-performance evidence.
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

Rolling KPSS Statistic [LuxAlgo]The Rolling KPSS Statistic indicator evaluates the stationarity of price action within a rolling window using the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test. This tool helps traders identify whether the current market environment is ranging, trending, or undergoing a structural regime shift by providing a continuous statistical measure of mean reversion.
🔶 USAGE
The indicator is designed to distinguish between stationary price action (where price fluctuates around a mean or trend) and non-stationary price action (where price exhibits random walk or breakout behavior). By applying a rolling window calculation, it provides a real-time assessment of market stability.
The script offers two primary modes of operation tailored to different market conditions:
🔹 Level Mode
This mode tests for stationarity around a constant mean. It is the optimal setting for detecting ranging or mean-reverting environments. When the KPSS statistic is low in this mode, it suggests the market is staying within a defined horizontal corridor.
🔹 Trend Mode
This mode tests for stationarity around a linear trend. It is used to identify if the market is moving consistently within a trending channel. A low KPSS value here indicates that while the price is moving up or down, it is doing so in a mathematically stable "stationary" trend rather than an erratic or parabolic one.
🔶 DETAILS
The KPSS test operates on the null hypothesis that the series is stationary. Unlike other unit root tests (like the Augmented Dickey-Fuller test), a low value in KPSS indicates stationarity, while a high value suggests the presence of a unit root (non-stationarity).
🔹 Critical Levels
The indicator plots three significance thresholds: 10%, 5%, and 1%.
KPSS < 5% Level: The market is considered stationary. In "Level" mode, this implies a Range. In "Trend" mode, this implies a stable Trend.
KPSS > 5% Level: The null hypothesis is rejected. The market is "Non-Stationary," suggesting a breakout, a trend reversal, or a transition into a random walk state.
KPSS > 1% Level: This indicates a highly significant deviation from stationarity, often seen during impulsive market expansions.
🔹 Visual Feedback
The indicator uses a Viridis gradient theme. Brighter colors (yellow/green) represent stationary, mean-reverting behavior, while darker colors (purple/blue) represent non-stationary or trending behavior. A real-time dashboard is also included to provide an immediate summary of the current market state.
🔶 SETTINGS
🔹 Main Settings
Window Length: The number of bars used for the rolling window. The default of 100 provides a balanced statistical lookback for most timeframes.
Source: The price data used for the calculation (default is Close).
Test Type: Select between "Level" (for ranges) or "Trend" (for trending stationarity).
Newey-West Bandwidth: A lag truncation parameter used to account for serial correlation in the residuals.
🔹 Visuals & Dashboard
Show Critical Levels: Toggles the visibility of the 10%, 5%, and 1% dashed lines.
Dashboard: Enables or disables the on-screen information table.
Position/Size: Controls the location and scale of the dashboard on the chart.
Indicator

VolProfex Volatility Time Window AnalyzerVolProfex Volatility Time Window Analyzer (VPX VTWA) analyzes intraday volatility across user-defined time windows within a trading session. It displays a table ranking windows by average and median move size (price % or ATR multiples), using historical data over a lookback period, with optional trend quality filtering out choppy periods using Directional Efficiency Ratio (Kaufman ER).
Session
Session (HHMM-HHMM): Defines trading session in exchange local time (e.g., 0930-1600 for NYSE/NASDAQ).
Session Timezone: Selects timezone handling DST automatically (e.g., America/New_York).
Calculation
Analysis Window (min): Time slot size for table display (options: 5,10,15,30,60,120,240).
Intrabar Resolution (min): Lower TF for accurate intrabar data (options: 1,2,3,5,10,15,30); smaller = better precision, longer load.
Lookback Days: Recent days analyzed (1-5000, default 1000).
Move Method: High-Low Range (absolute) or Open-to-Close (directional).
ATR Normalisation: ON shows moves as ATR multiples for regime-independent comparison.
ATR Period: ATR lookback (1-200, default 14).
Trend Quality Filter
Enable Trend Quality Filter: Excludes choppy windows based on efficiency ratio.
Min Trend Quality (%): Threshold (0-100, default 30); higher = stricter directional moves.
Consolidation
Enable Consolidation: Shows top N individually, groups rest.
Show Top N Individually: Highest-vol windows at full detail (1-100, default 10).
Group Remaining Into (min): Block size for lower-vol averages (options: 5,10,15,30,60,120).
Display
Highlight Top N Rows: Green highlight count (1-10, default 3).
Table Position: Corner placement.
Text Size: Table font (Tiny,Small,Normal,Large).
Indicator

Gap Analyzer[KG] Overview:
Gap Analyzer is a statistical research tool that scans every bar on your chart, identifies significant gap-down and gap-up events beyond a user-defined threshold, and summarizes what historically happens inside those gap bars — from open to high, open to low, and open to close.
What is a Gap?
A gap occurs when a bar's open is meaningfully higher or lower than the prior bar's close, leaving an empty zone on the chart with no traded price. This indicator flags:
Gap Down — when (Open − Prior Close) / Prior Close × 100 is at or below your threshold (default: −1%)
Gap Up — when the same calculation is at or above your threshold (default: +1%)
Visual Markers on the Chart:
Every qualifying gap is marked directly on the price pane with three layers:
Gap Zone Box — a semi-transparent dashed box fills the exact price area between the prior close and the current open, making the gap size immediately visible
Bar Highlight — a subtle background tint on the gap bar itself (red for gap down, teal for gap up)
Arrow + Label — a triangle arrow above/below the bar paired with the exact gap percentage printed inside the gap zone box (e.g. −6.43% or +5.91%)
Statistical Tables:
Two summary tables are rendered in the price pane — one for gap downs (bottom right by default) and one for gap ups (opposite corner). Each table contains 10 columns across 3 rows:
Gap Down Table:
Column Meaning Coun Total number of gap-down bars detectedΦGapAverage gap size across all qualifying bars O>C %% of gap-down bars that closed bearish (continuation) ΦO→HAverage % move from Open to High on continuation barsΦO→LAverage % move from Open to Low on continuation bars ΦO→CAverage % move from Open to Close on continuation bars O C)
All percentage values are colour-coded — teal for positive, red for negative — for instant readability.
The Φ Notation-
The symbol Φ (Phi) denotes an average (mean) across all qualifying bars in that category. So ΦO→H means "the average percentage move from the Open to the High across all gap bars in this group" — a measure of how much intraday upside was available on average after the gap open.
Inputs:
Input Default Description Gap-Down Threshold−5%Minimum gap size to qualify as a gap down Gap-Up Threshold+5%Minimum gap size to qualify as a gap up Table Position Bottom Right Where to anchor the gap-down table (gap-up table auto-mirrors) Show Gap % Label On Toggles the arrow and % label on each gap bar
Use Cases:
Intraday traders — know statistically how far price tends to travel from open toward the high or low after a gap, helping size entries and targets
Swing traders — quickly assess whether gaps on your instrument tend to fill (bounce) or continue, and by how much on average
Back testing context — apply to any timeframe and ticker to build a historical gap behavior profile before trading a live gap event
Notes:
Works on any ticker and any timeframe
All statistics are computed from the full visible history loaded on the chart; extending your chart history will give more robust sample sizes
Past statistical behavior does not guarantee future results — use as context, not as a signal in isolation Indicator

Hidden Markov Model: Regime Probability [AlgoPoint]Hidden Markov Model: Regime Probability
Traditional technical indicators are deterministic and lagging; they tell you what the price has already done. The Hidden Markov Model (HMM) Regime Probability system takes a completely different, quantitative approach. It uses probabilistic mathematics to estimate the unobservable "Hidden State" (Market Regime) the price is currently operating in.
Inspired by the mathematical models used by institutional quantitative hedge funds, this script doesn't just look at price direction—it calculates the probability of the market being in a specific regime based on real-time observations of Momentum and Volatility.
1. The Three Hidden States (Regimes)
The market is modeled as existing in one of three hidden states:
↗ Bullish Regime: High positive momentum with low or stable volatility. (Steady, grinding uptrends).
↘ Bearish Regime: High negative momentum with high volatility. (Aggressive sell-offs and panic).
↕ Chop / Chaos Regime: Zero/low momentum with high volatility. (Whipsaw, ranging, and unpredictable noise).
2. How It Works (The Quant Engine)
Since Pine Script does not natively support complex matrix optimization, this script builds a robust Pseudo-HMM using a predefined Transition Matrix and Bayesian Updates.
Observables (Emissions): The script calculates the Z-Scores of Smoothed Momentum (Rate of Change) and Volatility (ATR).
Emission Probabilities (Gaussian PDF): It feeds these Z-Scores into a Gaussian Probability Density Function to see how well the current market matches the expected profile of a Bull, Bear, or Chop regime.
Bayesian Update: Using a predefined Markov Transition Matrix (the statistical inertia of a trend), it updates the prior probabilities to give you a real-time percentage (0-100%) for each regime.
3. Advanced Visual Features & UI
We built a custom UI/UX engine to make digesting complex probabilities instantaneous:
Exponential Color Smoothing (Bar Colors): As the probability of a regime increases, the bar colors smoothly transition. We implemented an exponential color blending algorithm to prevent abrupt, distracting color changes and eliminate "muddy" colors during transitions.
Pro Quant Dashboard: A built-in HUD (Heads-Up Display) provides a quick summary. It features a dominant state readout, an overall "Confidence Score", and ASCII-style mini progress bars (████░░░) for rapid visual processing of probabilities without needing to read the numbers.
Stacked Area Oscillator: The bottom panel displays a 0-100 stacked area chart, showing the exact distribution of probabilities across Bull (Green), Chop (Purple), and Bear (Red) states.
4. How to Use This Tool
This is not a standalone Buy/Sell signal indicator. It is a Strategy Filter and a Risk Manager.
When Bull/Bear Probability is Dominant (>50%): The market is trending. Turn ON your trend-following indicators (like Moving Averages or Breakout systems) and ignore overbought/oversold signals.
When Chop Probability is Dominant (>50%): The market is noisy. Turn OFF your trend-following systems. Either switch to Mean Reversion strategies (like RSI or Bollinger Bands) or stay in cash until a clear regime emerges.
Watch the Confidence Score: If the Dashboard shows "LOW" confidence, it means the probabilities are split (e.g., 34% Bull, 33% Chop, 33% Bear). Wait for the model to gain confidence before committing capital.
5. Alerts
The script includes non-repainting alerts that trigger only when the dominant regime changes:
HMM Regime: BULLISH 🚀 * HMM Regime: BEARISH 🩸 * HMM Regime: CHOP ⚖️
6. Settings
Lookback Period: The window used to calculate the Z-scores for momentum and volatility.
Transition Matrix: Allows advanced users to tweak the statistical likelihood of the market staying in its current state versus transitioning to a new one.
Color Transition Speed: Adjusts the smoothness of the bar coloring. A lower value creates a buttery-smooth fade between regimes, while a value of 1.0 makes it instant. Indicator

Market Regime AnalyzerStatistical regime detection with forward-looking transition probabilities. Combines drift testing, variance ratios, and volume delta to classify markets into 5 regimes and quantify transition probabilities.
What Regime Are We In, and What's Likely Next?
That's the question this indicator answers with statistical rigor and forward-looking probabilities.
The Problem:
Most traders classify regimes arbitrarily: "Bull if price > 200 MA" or "Bear if RSI < 30." These rules ignore statistical significance, volume confirmation, and mean reversion patterns. The result? Late entries, false signals, and confusion when markets transition.
The Solution:
Market Regime Analyzer combines drift detection, variance ratio testing, and volume delta analysis to classify markets into 5 distinct regimes. Then it calculates the probability of transitioning to each regime based on historical patterns.
The Benefit:
Know not just where you are, but where you're likely going - with probabilities, not guesses.
The Five Market Regimes
🟢 Strong Bull (Regime 1)
- Statistically significant upward drift (t-stat > 1.96)
- Strong buying pressure (volume delta > 0.3)
- No mean reversion detected
- **Trade:** Trend-following strategies, ride the momentum
🟢 Weak Bull (Regime 2)
- Upward drift present
- BUT weak volume OR mean reversion detected
- **Trade:** Reduce position size, tighten stops, prepare for consolidation
⚪ Consolidation (Regime 3)
- No statistically significant drift
- Mixed volume signals
- Mean reversion likely present
- **Trade:** Range-trading, avoid trend-following systems
🔴 Weak Bear (Regime 4)
- Downward drift present
- BUT weak volume pressure
- **Trade:** Cautious shorts, reduce exposure, prepare for bounce
🔴 Strong Bear (Regime 5)
- Statistically significant downward drift (t-stat < -1.96)
- Strong selling pressure (volume delta < -0.3)
- No mean reversion detected
- **Trade:** Trend-following shorts, protective puts
The Statistical Framework
1. Drift Detection with T-Statistics
Instead of guessing if there's a trend, we test it statistically.
How it works:
- Calculates mean return over lookback period
- Standardizes by volatility
- Compares to significance threshold (default 1.96 = 95% confidence)
What it tells you:
- T-stat > 1.96: Statistically significant uptrend
- T-stat < -1.96: Statistically significant downtrend
- In between: No significant trend (consolidation)
Why it matters:
Only trades trends that are statistically validated, not just visually apparent.
2. Mean Reversion Testing (Variance Ratio)
Based on Lo & MacKinlay (1988) research, this detects when markets are range-bound.
How it works:
- Compares variance at different time scales
- Variance Ratio < 0.8 indicates mean reversion
What it tells you:
- Mean reversion = NO: Trends can continue
- Mean reversion = YES: Expect price to return to mean, not breakout
Why it matters:
Prevents chasing breakouts in range-bound markets.
3. Volume Delta Analysis
Total volume tells you HOW MUCH traded. Volume delta tells you WHO won.
How it works:
- Buying pressure - Selling pressure = Volume Delta
- Normalized to show relative strength
What it tells you:
- Strong positive delta (>0.3): Buyers in control
- Strong negative delta (<-0.3): Sellers in control
- Weak delta: No clear winner
Why it matters:
Price can move up on weak buying or down on weak selling. Volume delta reveals the truth.
4. Transition Probability Matrix
Historical regime changes predict future regime changes.
How it works:
- Tracks every regime transition over last 100 bars (configurable)
- Builds probability distribution for next regime
- Updates continuously
Example:
Current: Strong Bull
Historical transitions from Strong Bull:
- Stayed Strong Bull: 45%
- Became Weak Bull: 30%
- Became Consolidation: 20%
- Became Weak Bear: 4%
- Became Strong Bear: 1%
What it tells you:
Strong Bull has 75% chance of staying bullish (45% + 30%), only 5% chance of bearish turn.
Why it matters:
Adapts to your specific market's behavior patterns.
How to Use This Indicator
Strategy Adaptation
In Strong Bull/Bear Regimes:
- Use trend-following strategies
- Wider stops, let winners run
- Add to positions on pullbacks
- High confidence in directional trades
In Weak Bull/Bear Regimes:
- Reduce position sizes by 50%
- Tighter stops
- Take profits earlier
- Prepare for regime change
In Consolidation:
- Switch to range-trading strategies
- Avoid trend-following systems
- Sell resistance, buy support
- Wait for regime change before trend trades
Risk Management
Position Sizing:
- Strong regime + high continuation probability (>60%) = Normal size
- Weak regime OR high transition probability = Half size
- Consolidation = Quarter size or skip
Stop Loss Placement:
- Strong regime: Use wider stops (2x ATR)
- Weak regime: Tighter stops (1x ATR)
- Consolidation: Very tight stops (0.5x ATR)
Entry Timing
Best entries:
- Regime just changed to Strong Bull/Bear
- High probability (>50%) of staying in current regime
- No divergence signals present
- Drift and volume delta aligned
Avoid entries:
- High probability of regime change
- Divergence signals appearing
- Mean reversion detected in trending regime
- Weak volume despite price movement
Reading the Dashboard
Current Regime
Color-coded for instant recognition:
- Dark Green = Strong Bull
- Light Green = Weak Bull
- Gray = Consolidation
- Light Red = Weak Bear
- Dark Red = Strong Bear
Annualized Drift
Expected annual return based on recent trend.
- Positive = Upward bias
- Negative = Downward bias
- Near zero = No directional edge
T-Statistic
Measures statistical significance of drift.
- > 1.96 = 95% confident in uptrend
- < -1.96 = 95% confident in downtrend
- Between = Not statistically significant
Mean Reversion
- Yes = Expect price to return to mean (range-bound)
- No = Trends can continue (trending market)
Volume Pressure
Normalized volume delta strength.
- > 0.3 = Strong buying
- < -0.3 = Strong selling
- Near 0 = Balanced
Transition Probabilities
Shows most likely next regime.
- Highest probability = Most likely outcome
- Evenly distributed = High uncertainty
- Concentrated = High confidence in direction
Practical Examples
Example 1: Strong Bull with High Continuation
Dashboard shows:
Current Regime: Strong Bull
Drift: +22% annualized
T-Stat: 3.2
Mean Reversion: No
Volume Pressure: +0.45
Probabilities:
→ Strong Bull: 50%
→ Weak Bull: 25%
→ Consolidation: 20%
→ Bears: 5%
Interpretation:
- Strong uptrend (t-stat 3.2 >> 1.96)
- No mean reversion = trends can continue
- Strong buying pressure (0.45 > 0.3)
- 75% chance stays bullish (50% + 25%)
Action:
- Full position size on long setups
- Use trend-following entries
- Wider stops (2x ATR)
- High conviction trades
Example 2: Weak Bull Before Consolidation
Dashboard shows:
Current Regime: Weak Bull
Drift: +8% annualized
T-Stat: 1.2
Mean Reversion: Yes
Volume Pressure: +0.15
Probabilities:
→ Strong Bull: 10%
→ Weak Bull: 30%
→ Consolidation: 50%
→ Weak Bear: 10%
Interpretation:
- Weak drift (t-stat 1.2 < 1.96)
- Mean reversion detected = range-bound likely
- Weak volume (0.15 < 0.3)
- 50% chance of consolidation
Action:
- Reduce long positions
- Tighten stops
- Prepare for range-bound trading
- Avoid new trend trades
Example 3: Regime Transition Alert
Previous: Weak Bull
Current: Consolidation
Volume divergence signal appeared:
Price made new high, volume delta weakened
Interpretation:
- Trend exhausted
- Buyers losing control
- Regime confirmed the transition
Action:
- Exit trend-following longs
- Switch to range-trading approach
- Wait for new regime before new directional trades
Settings Guide
### Regime Detection Period (50)
Number of bars for statistical calculations.
- **30-40:** More responsive, catches changes faster, more regime switches
- **50 (default):** Balanced for daily/4H charts
- **75-100:** More stable, fewer false regime changes, slower to adapt
Transition History Depth (100)
How much history to use for probabilities.
- **50-75:** Adapts quickly to recent behavior
- **100 (default):** Balanced robustness
- **150-200:** More stable probabilities, slower to adapt
Volume Delta Period (14)
Period for volume calculations.
- **7-10:** More sensitive to volume shifts
- **14 (default):** Standard period
- **20-30:** Smoother, less noise
Significance Threshold (1.96)
T-statistic required for trend classification.
- **1.64:** 90% confidence, more trend regimes detected
- **1.96 (default):** 95% confidence, balanced
- **2.58:** 99% confidence, very conservative, mostly consolidation
Best Practices
Do:
- Wait for regime confirmation (at least 3-5 bars in new regime)
- Use probabilities to size positions appropriately
- Combine with support/resistance for entries
- Respect mean reversion signals
- Adapt strategy to current regime
Don't:
- Trade every regime change immediately
- Ignore high transition probabilities
- Use trend strategies in consolidation
- Override statistical signals with gut feel
- Trade against Strong regimes without clear setup
Timeframe Recommendations
Daily Charts:
- Default settings work well
- Most reliable regime detection
- Best for swing trading
4H Charts:
- Use default or slightly higher lookback (60-75)
- Good for active swing trading
- More regime changes than daily
1H Charts:
- Reduce lookback to 30-40
- More noise, use with caution
- Better for intraday position trading
15M and below:
- Not recommended
- Too much noise for statistical validity
- Regimes change too frequently
Combining with Other Indicators
Works Well With:
Moving Averages
- Use regime for directional bias
- MAs for specific entry/exit points
Support/Resistance
- Regime shows context
- S/R shows specific levels
- High probability at confluence
Volume Profile
- Regime shows regime
- Profile shows where volume is
- Target high-volume nodes
RSI/MACD
- Regime provides context
- Momentum shows entry timing
- Combine for higher probability
Example Combined Setup
Regime: Strong Bull
Price: Above 200 MA
Level: Pullback to support
RSI: Oversold (30)
Volume Delta: Still positive
Setup: Long entry
Reason: Trend intact, healthy pullback, buyers still present
Divergence Signals
The indicator shows volume divergence warnings:
Bearish Divergence (Red Triangle Down)
- Price makes new high
- Volume delta makes lower high
- Warning: Buyers weakening, potential reversal
Bullish Divergence (Green Triangle Up)
- Price makes new low
- Volume delta makes higher low
- Warning: Sellers weakening, potential reversal
How to use:
- Divergence in Strong regime = early warning of regime change
- Confirms when regime actually transitions
- Don't trade divergence alone, wait for regime confirmation
Limitations
This Indicator Cannot:
**Predict black swan events** - Unexpected news overrides all technical regimes
**Work in all markets** - Needs liquid markets with reliable volume data
**Guarantee profits** - Probabilities are not certainties
**Replace fundamental analysis** - Technical regimes can diverge from fundamentals
Works Best:
- Liquid markets (major indices, forex, crypto, large-cap stocks)
- Daily and 4H timeframes
- Combined with other analysis
- With proper risk management
- In normal market conditions
Common Questions
"Why did the regime stay consolidation despite strong price move?"
The indicator detected mean reversion (variance ratio < 0.8), indicating the move will likely reverse. Or the move wasn't statistically significant (t-stat < 1.96). Trust the statistics over visual appearance.
"Probabilities show 30% for each regime. What does that mean?"
High uncertainty. The market is at an inflection point. Reduce position sizes and wait for clearer regime formation.
"Can I use this for day trading?"
Not recommended on timeframes below 1H. Statistical tests need sufficient data. Better suited for swing trading.
"Why does this show Strong Bull when my momentum indicators show weakness?"
Momentum can weaken while the trend remains statistically significant. The indicator focuses on drift and volume, not momentum. Consider it a different perspective.
Technical Notes
Volume Delta Approximation
Uses OHLCV data to approximate order flow:
- Buy volume ≈ Volume on up-closes
- Sell volume ≈ Volume on down-closes
- Delta = Buy - Sell
**Note:** Real order flow (from futures or Level 2) is more precise. This approximation works well on liquid markets.
Statistical Tests
Drift T-Test:
- Null hypothesis: No drift (mean return = 0)
- Reject if |t-stat| > threshold
- Based on standard hypothesis testing
Variance Ratio:
- Compares 2-period variance to 1-period variance
- Ratio = 1 for random walk
- Ratio < 1 for mean reversion
- Threshold of 0.8 based on empirical testing
Transition Probability Implementation
Due to Pine Script v5 limitations (no native 2D arrays), the 5×5 transition matrix is stored as a flat 1D array of 25 elements:
- Position maps to index: `row × 5 + col`
- Example: Transition from Regime 2 to Regime 4 is at index `1 × 5 + 3 = 8`
- Laplace smoothing (0.1) prevents zero probabilities
- Row sums normalized to calculate probabilities
This approach is computationally efficient and maintains statistical accuracy.
No Repainting
All calculations confirmed on bar close. Regime changes appear when the bar closes, not during formation. Historical analysis is accurate.
Alert Conditions
Regime Change
- Triggers when regime transitions to any new state
- Message shows new regime number (1-5)
Bearish Divergence
- Triggers when price makes new high but volume delta doesn't confirm
Bullish Divergence
- Triggers when price makes new low but volume delta doesn't confirm
Disclaimer
FOR EDUCATIONAL PURPOSES ONLY
This indicator uses statistical methods to analyze market regimes. It does not predict the future or guarantee trading success.
Markets are probabilistic, not deterministic. A 70% probability of staying bullish means 30% chance of regime change. Always use proper risk management.
Past regime transitions do not guarantee future transitions. Market structure can change. Statistical relationships can break down.
Never risk more than you can afford to lose. Use stop losses on every trade. Test thoroughly before live trading. Consult a qualified financial advisor.
© 2026 | Open Source
Statistical rigor meets practical application Indicator

Indicator

Monte Carlo Simulation BandsMonte Carlo Simulation v2.4.2
Plots a one-bar-ahead price distribution band built from many simulated paths. The green band shows empirical percentiles of simulated final prices—these are distribution bounds, not a confidence interval of the mean.
What It Does
Simulates many one-bar price paths using a directional random walk with volatility scaling (uniform shocks, not Gaussian GBM).
Plots Mean Forecast, Median Forecast, and configurable percentile bounds (default 5th/95th).
Optional rolling HTF-days mean line (yellow) for trend context.
Optional labels and forward projection lines.
Alerts when the confirmed close breaks above or below the percentile band.
Non-Repainting & HTF Behavior (Fail-Closed)
All calculations are gated to confirmed bars only via explicit no_repaint_ok gate (barstate.isconfirmed).
If you select an HTF Resolution, the script uses a strict request.security(..., lookahead_off, gaps_off) pipeline.
If HTF data is unavailable, outputs are na—no silent fallback to chart timeframe.
A separate "HTF Alignment (lagged)" plot shows the prior HTF close (htf_price ) as visual proof of no look-ahead.
Volatility Source & Scaling
If "Use Historical Volatility" is enabled, volatility is estimated from log returns on the selected resolution (HTF if set, otherwise chart).
Annualization adapts to session type:
Equities: 6.5 hours/day, 252 trading days/year
Crypto: 24 hours/day, 365 days/year
Substeps increase path smoothness within the same one-bar horizon—they do not extend the forecast to multiple bars.
Key Inputs
• Prob Up / Prob Down — Must satisfy Prob Up + Prob Down ≤ 1.0. If violated, simulation is skipped and table shows "✗ PROB>1".
• # Simulations / # Substeps — Higher = smoother/more stable, but slower. Default 100×100 is a good balance.
• Lower/Upper Percentile — Define the band width (e.g., 5 and 95 for a 90% distribution band).
• Run On Last Bar Only — Performance mode (recommended). Skips historical computation; updates on each new confirmed bar.
• Resolution (HTF) — Leave blank for chart timeframe, or set to Weekly/Monthly for HTF-aligned simulation.
• Crypto 24/7 Session? — Enable for crypto markets to use correct annualization (365d, 24h).
How to Use (Quickstart)
Start with defaults and keep Run On Last Bar Only = true for speed.
Set Prob Up and Prob Down so their sum ≤ 1.0 (e.g., 0.5 + 0.5 = 1.0 for neutral).
Enable "Use Historical Volatility" and set a Volatility Lookback (e.g., 20 bars) for data-driven vol.
Set Resolution (HTF) if you want the model to run on higher timeframe data (e.g., 1W). Expect updates only when a new HTF interval starts.
Choose percentiles (e.g., 5 and 95) to define your distribution band width.
Enable alerts for "Price Above Upper Percentile" or "Price Below Lower Percentile" to get notified of breakouts.
Limitations & Disclosures
Forecast horizon is one bar only. Substeps do not create a multi-bar forecast.
Model uses uniform shocks with direction chosen from Prob Up/Down. This is not Geometric Brownian Motion (GBM) and is not calibrated to any option-implied distribution.
Bounds are percentiles of final simulated prices, not a statistical confidence interval of the mean.
HTF mode updates at the start of a new HTF interval (first chart bar where the HTF timestamp changes), so the band appears "step-like" in realtime.
Historical volatility requires enough bars for the selected lookback; until then, values may be na.
Performance depends on Sims × Substeps; extreme settings (e.g., 500×500) can be slow.
This indicator does not predict direction—it shows a probabilistic range based on your inputs.
Indicator
