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

Trend Ribbon [MachineSuiteAI]Trend Ribbon
respect ranking, measured cross odds and auditable statistics
🟦 OVERVIEW
A five-average trend ribbon (8 / 21 / 50 / 100 / 200 by default; EMA, WMA, SMA, HMA or VWMA) built on one idea: the ribbon should measure itself.
Beyond the stack-based trend state and 50/100 cross markers, it keeps auditable statistics on the chart it is loaded on: which average price has actually been respecting (and how reliably), how every 50/100 cross resolved, what happened after squeeze expansions and after trend-health peaks — each statistic with its sample size, and each verifiable on the chart itself, dot by dot. It is built for traders who use layered moving averages and want the chart to answer two questions the ribbon genre normally leaves to folklore: which of these lines matters here, and what have these signals actually done on this symbol?
🟦 WHAT IS A TREND RIBBON?
Moving-average ribbons are a public-domain concept: several averages of increasing length plotted together. When they are stacked in order the trend is orderly; when they compress and interleave the market is ranging; crosses of a slower pair mark regime changes. Published ribbon scripts already color stacks, count touches, score trend strength and detect squeezes.
What the genre does not do is resolve outcomes. A ribbon will mark a "golden cross" without knowing how golden crosses have actually resolved on this chart; it will call an average "support" without a record of how often that support held. This script's contribution sits one level up: measurement with discipline, and evidence you can check.
🟦 WHY THIS SCRIPT IS ORIGINAL
- A cross odds engine. Every 50/100 cross is resolved N bars later (default 10) on the loaded symbol and timeframe: did the close move in the cross's direction? The win rate is tracked and split by volume confirmation, higher-timeframe agreement, and whipsaw-cluster membership — each split with its own sample size, greyed below a minimum. To the author's knowledge no published ribbon resolves its own crosses' outcomes, let alone per filter.
- Evidence-gated chart marks. The ✓ volume mark and ⚠ counter-HTF warning print on cross chips only where the measured split beats the chart's own base rate by a configurable margin with sufficient samples. Filters that have not helped on this chart do not decorate it.
- Auditable statistics. The respect record is drawn on the chart: numbered dots mark the counted touches of the leading average (gold = held, grey = failed) and a grey ✕ marks clean pass-throughs where nothing was tested and nothing entered the record. Every number in the panel can be verified visually — no other script found does this.
- Outcomes attached to the score and the squeeze. The 0–100 health score is not just decomposed from a stated formula — the panel reports how often the primary side was still intact at three horizons after past crossings above 80, on this chart. Squeeze expansions are likewise measured N bars later (median move, direction agreement, samples).
- Recency-weighted respect ranking. Touch counting exists in published scripts; here each average's last 12 touches form a rolling record where the newest touch weighs most, and the gold halo must be earned twice over: both the raw record and the weighted recent form have to clear a threshold. Below it the panel reads LOW RESPECT — price slicing through everything is itself information.
- Readability engineered like the statistics. Six engines share one chart only because the visual rules are strict: line identities never change (white 50, amber 100, thick grey 200 — the respect halo is an underlay beneath the leader's own line, never a recolor), whipsaw crosses are de-emphasized but never deleted so the visible ▲/▼ sequence always alternates, higher-timeframe levels identify themselves with end tags instead of a legend, and every mark on the chart has exactly one meaning. Nothing decorative, nothing unexplained.
🟦 HOW IT WORKS
- Trend state: the 50/100 pair picks the side; the state reads BULL or BEAR only when at least 3 of the 4 adjacent stack pairs agree, otherwise CHOP. Fill opacity scales with alignment.
- Respect engine: every touch of every average runs through a small state machine on confirmed bars. A touch requires the prior close beyond the average, a penetration into a tolerance band (default 0.25 × ATR(14)) and a close back on the original side; consecutive contacts merge into one event. The touch HOLDS if no close crosses the far tolerance edge within the resolve window (default 5 bars). Each average keeps its last 12 resolved touches; the best recency-weighted hold rate (minimum 5 touches) leads the ranking, and the leader earns a soft gold halo under its own line only when raw record and recent form both clear the threshold (default 50%).
- Cross odds engine: as described above — confirmed bars only, fixed-horizon resolution, per-filter splits, evidence-gated chip marks.
- Health score: 0–100 from a stated formula — 40% stack alignment + 25% slope consistency + 20% price position + 15% width behavior. The panel tooltip decomposes the live score and reports the measured survival after 80-crossings at half, full and double the outcome window.
- MTF strip and HTF anchors: a small table shows the 50/100 cross state on five timeframes, and up to three higher-timeframe averages plot as stepped level lines (default: the 50/100/200 one regime up, with an optional corridor fill between the pair, tinted by where price trades). Both are read from the last completed bar of their timeframe with confirmed-bar indexing, so they can appear one higher-timeframe bar late but never rewrite. Anchors render only once their timeframe has a full length of history — young symbols never show statistically meaningless levels.
- Squeeze and expansion: ribbon width (widest minus narrowest core average, as % of price) is percentile-ranked over a lookback (default 250 bars); below the threshold percentile the ribbon is squeezed. Every expansion out of a squeeze is measured N bars later: median move, direction agreement with the ribbon state, and an "A-grade" slice (state agreed with the higher timeframe AND volume confirmed) tracked separately.
- Cluster damping: several crosses inside a short window classify as whipsaw; rapid re-crosses shrink to dimmed dots rather than full chips — de-emphasized, never deleted, so the visible ▲/▼ sequence always alternates. A cross suppressed into a cluster can still print later, once, if the market settles on its side.
All statistics are collected on confirmed bars only.
🟦 HOW TO USE IT
- Line identities stay fixed: white 50, amber 100, thick grey 200, fast pair in the trend color. The pair that generates the signals is always findable.
- Read the panel top-down: state, health, stack, the respected average with its raw record and recent form, cross recency, the measured win-rate splits, then width and expansion.
- A typical workflow: before treating a pullback to an average as meaningful, check that average's record — the gold halo and its numbered dots are the evidence. Before taking a cross, check whether volume or higher-timeframe agreement has historically mattered on this particular chart — the ↑ marks in the odds rows answer that. Use the MTF strip for context and the HTF corridor as the higher-timeframe decision zone.
- Defaults suit swing timeframes (4H–1D); everything is length-adjustable.
🟦 SETTINGS
- Averages: type, five core lengths, up to three optional extras, curated price source.
- Respect engine: halo and audit-dot toggles, touch tolerance, hold window, ranking window, minimum touches, gold threshold, recency decay.
- Health score: panel row toggle, outcome window.
- Cross odds engine: outcome horizon, minimum sample, evidence-mark gating mode, improvement margin.
- MTF cross strip: five timeframes, strip position.
- HTF anchors: auto or fixed anchor timeframe, three levels with lengths and colors, corridor or lines-only rendering.
- Visuals and extras: marker style (chips/dots/off), cluster damping, line-coloring mode (stack state or per-line slope), price-scale labels, squeeze shading, conviction-scaled fill, panel position, colors, volume-confirmation multiple.
🟦 ALERTS
Primary 50/100 cross (bull/bear) · fast 8/21 cross (bull/bear) · full stack aligned (bull/bear) · cross + volume (bull/bear) · squeeze start · squeeze expansion + volume · respected-average touch · respected average changed · health crossed 80 · health dropped below 40.
🟦 REPAINT & DATA NOTES
- Chips, dots and all bookkeeping wait for bar confirmation; the live bar updates until it closes.
- Higher-timeframe reads use the last completed bar of their timeframe: repaint-safe, but up to one higher-timeframe bar late by construction.
- Statistics are computed over the loaded history and reset when the chart reloads with a different amount of history; low timeframes load fewer bars.
- Volume-based features — including the VWMA average type — require a feed that supplies volume.
- PulseWire caps a script's labels at 500, so on long intraday histories the oldest cross chips drop off the left edge; the statistics still cover the full loaded history.
- MTF strip rows set below the chart's own timeframe show a dash: a lower timeframe cannot be read repaint-safely from a higher-timeframe chart.
- The higher-timeframe anchor levels can sit far from current price (a weekly 200 on a daily chart, for example), which widens the chart's auto-fitted price scale. Enable "Scale price chart only" in your chart settings — or switch anchors off — if you prefer a tight fit around price.
🟦 CREDITS
Moving averages, ribbons, MA crosses and squeeze concepts are public domain. The implementation — the respect state machine, cross odds engine, evidence gating, health decomposition with measured outcomes, repaint-safe MTF/anchor reads and the audit-dot system — was written from scratch for this script.
🟦 LIMITATIONS
- Moving averages lag; ranging markets whipsaw the state and the crosses. The cluster logic labels that condition, it does not remove it.
- All win rates, hold rates and outcome stats are historical measurements on the loaded chart only. They change with symbol, timeframe and loaded history, are greyed below the minimum sample, and do not predict future results.
- The outcome definition is direction-only over a fixed horizon — no stops, fees, or sizing; this is not a strategy backtest.
🟦 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

HalfTrend Long/Short Signal Engine [BigBeluga]HalfTrend Long/Short Signal Engine is an institutional-grade trend tracking toolkit built for PulseWire. It filters out minor market noise to deliver definitive, non-repainting long and short entry signals based on asset volatility and structural swing pivots.
Instead of displaying standard lag-heavy moving averages, this system uses an adaptive directional engine to lock onto clean trend lines and overlay automatic risk-management matrices directly onto your chart. It calculates real-time win rates and scans multiple assets simultaneously so you can trade with systematic statistical backup.
🔵 MAIN ENGINE & MARKET CALCULATION MECHANICS
1. Pure HalfTrend Price Filter Matrix
Swing Pivot Trackers: The engine scans local high and low data using an adjustable lookback filter ( Amplitude ) to find actual structural swing points rather than temporary price spikes.
Volatility-Adjusted Bands: It establishes dynamic outer channel boundaries using a 100-period Average True Range calculation divided by two ( ATR/2 ). The total channel width automatically scales using your custom risk buffer parameter ( Channel Deviation ).
Regime Flip Architecture: The system locks into a Bullish Regime when price crosses above structural highs, shifting the main tracking baseline to Green. When price slips below structural lows, it forces a Bearish Regime and changes the tracking baseline to Red.
2. Automated Risk Matrix & Multi-Asset Scanner
Algorithmic Trade Execution: The moment a new trend regime initializes, the engine projects a strict trade tracking matrix showcasing an entry line, a clear stop-loss boundary, and three tiered profit targets (TP1, TP2, and TP3).
Live Performance Dashboard: An integrated on-screen table calculates real-time historical metrics, tracking active wins, losses, current target risk-to-reward ratios ($1:3$), and overall system win rate percentages.
Screener Security Matrix: The background engine leverages real-time multi-asset queries to stream concurrent trend statuses for five separate configurable symbols directly into a secondary visual dashboard.
// Automated Trade Risk & Multi-Asset Tracking Snippet
if buySignal
float dist = atr2 * baseRiskMult
activeSL := close - dist
activeTP1 := close + dist
activeTP2 := close + (dist * 2)
activeTP3 := close + (dist * 3)
tradeState := 1
entryPx := close
t1 = request.security(sym1, timeframe.period, trend)
🔵 WHY IT IS USEFUL
Elimination of Market Noise: Standard moving averages constantly whip back and forth during consolidations. The HalfTrend calculation filters out minor intraday fluctuations, only shifting when a definitive structural high or low is broken.
Mathematical Execution Blueprint: It takes the emotion out of trade management. Every signal comes equipped with dynamic, visually mapped stop losses and a $1:3$ risk-reward profit map that fills with real-time gradient paths.
Macro Market Synchronicity: The multi-asset side-panel allows you to keep an eye on major market drivers (like BTC, ETH, Gold, or major FX pairs) simultaneously, ensuring your trades line up with broader institutional market direction.
🔵 HOW TO USE THE SYSTEM
Trading Long Breakouts: When the system transitions from a bearish regime into a bullish regime, a Green LONG label will print beneath the breakout candle. Execute your position at the white entry line, setting your dynamic stop-loss boundary inside the red risk gradient.
Trading Short Breakdowns: Monitor the system for a shift into a bearish regime, indicated by a Red SHORT label appearing above the asset price. Execute short orders relative to the entry line and utilize the upper red gradient zone to map your protective risk ceiling.
Managing Exits and Targets: Take partial profits sequentially as the asset price moves through the Green target lines (TP1, TP2, and TP3). If a sudden trend reversal prints an opposing signal before your final targets are satisfied, the script automatically triggers a reversal exit rule to preserve accumulated gains.
Streamline your trade execution, manage portfolio risk systematically, and screen multiple sectors at once with the HalfTrend Long/Short Signal Engine workspace. 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

Indicator

Renaissance Mean Reversion [JOAT]RENAISSANCE MEAN REVERSION
A tribute to the Medallion-style statistical-arbitrage approach: do not trade price — trade the spread between price and its smoothed expectation , measure how reliably that spread mean-reverts using an AR(1) half-life regression , and only fire signals when the half-life is fast enough to be tradeable. The result is a discipline-enforcing engine that says no more often than yes : it refuses to take a reversion trade until the spread shows it actually reverts.
The synthetic spread
The script builds a synthetic pair from two views of the same instrument:
Leg 1 — current price (configurable source).
Leg 2 — long EMA of price (default 50-bar; configurable).
Spread = price − long EMA (or ln(price) − ln(EMA) when log-spread mode is on, removing scale).
The spread is then Z-scored over a configurable lookback (default 100 bars) to produce a stationary stationary signal that says: "how many standard deviations is the spread from its own mean right now?". This is the textbook stat-arb construction, single-leg version.
Half-life regression — the gate
This is what makes the script institutional rather than retail. Reversion is meaningless if the spread does not actually revert. The script fits an AR(1) regression over a configurable window (default 120 bars):
Δspread_t = α + β · spread_{t−1} + ε_t
The half-life of mean reversion is then:
HL = −ln(2) / ln(1 + β)
When β is negative and close to zero, HL is short — the spread reverts quickly. When β approaches −1, HL is huge — the spread barely reverts. When β is positive, the spread is anti-mean-reverting (trending) and the script will refuse to trade.
A configurable Max Half-Life (default 20 bars) gates signals — entries only fire when HL is below this threshold. A configurable Min Half-Life (default 0.5) floors the estimate to avoid degenerate near-zero values that would otherwise produce explosive signals.
This is the headline filter. Roughly 50–70% of bars on most instruments fail it — which is the point. You only trade when the spread has earned the right.
Entry / Exit logic
R-LONG — fires when Z < −entryZ (default −2.0) AND HL is below the max threshold AND the re-entry cooldown has elapsed. Spread is stretched too far below, will revert.
R-SHORT — fires when Z > +entryZ AND HL is below the max threshold AND cooldown elapsed.
R-EXIT — fires when |Z| drops below exitZ (default 0.25) OR when Max Hold Bars (default 40) has been reached, whichever comes first.
A configurable re-entry cooldown (default 3 bars) prevents immediate re-firing on the same side.
Visual system — minimal mono institutional
The aesthetic is intentionally austere — Renaissance's research-paper minimalism. Pure monochrome:
Z guides on right side of chart — small text labels showing current Z, HL, and tradeable status.
R-LONG / R-SHORT / R-EXIT labels — clean text tags on entry and exit bars.
Half-Life overlay label — current HL value displayed near the live close.
Shaded ribbon between price and slow EMA (configurable transparency).
Trade entry/exit shapes — small markers at signal bars.
Single-hue tradeable-regime tint (off by default) — subtle bgcolor when HL is fast AND Z is stretched.
A locked Minimal Mono palette: white bull / gray bear / pure-black background. No accent colours. The chart looks like a quant research paper. Intentional.
Dashboard
Monospaced table positionable to any of eight corners. Surfaces:
Current spread value and Z score.
Current half-life (in bars) with tradeable / non-tradeable flag.
AR(1) β coefficient (the regression's directional read).
Z thresholds in use.
Last signal direction with bars-ago.
Max-hold bars remaining (when in a position).
Rolling backtest tracker
The script tracks the last N closed reversion trades (configurable, default 200) and surfaces:
Total trades, wins, losses.
Win rate.
Average bars-to-exit.
Average Z magnitude at entry.
Hit-rate by side (R-LONG vs R-SHORT).
This is the script's own performance audit — you see whether the engine is finding genuine reversion or whether the current regime is breaking it.
Alerts
Three alert conditions, each independently controllable:
Reversion Entry (R-LONG or R-SHORT)
Reversion Exit (R-EXIT)
Half-Life crosses Max Half-Life (regime change — reversion is becoming unreliable)
How to read it
Three reads, in order of conviction:
R-LONG / R-SHORT with very fast HL (e.g. HL = 4 bars on a 1H chart) — the script's intended high-conviction setup. The spread is stretched, the math says it will revert quickly, the chart agrees. This is the institutional setup.
Half-life crossing above max (alert) — regime warning. The instrument is shifting from mean-reverting to trending. Any open R-positions should be re-evaluated; new R-entries should be paused until HL re-tightens.
Sustained R-EXIT triggers from time-stop (max-hold) rather than from Z returning to neutral — the script is exiting because the trade ran out of time, not because the thesis played out. Recurring time-stop exits mean the current parameters do not fit the instrument.
The rolling backtest win-rate is your auditor. When it climbs, the engine is finding edge. When it grinds flat or declines, the regime has changed and the parameters need adjustment.
Suggested settings
Defaults (long EMA 50, Z lookback 100, regression window 120, max HL 20 bars, entry Z 2.0, exit Z 0.25) are tuned for 1H–4H on liquid markets where mean reversion is statistically meaningful. For lower timeframes drop everything proportionally (long EMA 25, Z 50, regression 60). For HTF raise everything (long EMA 100, Z 200, regression 200). The max HL is the most sensitive parameter — narrow it (10–15) for high-conviction-only filtering; widen it (25–30) for more frequent signals.
Originality / what's reused
The synthetic-pair Z-score construction is textbook stat-arb. The AR(1) half-life regression is published quantitative finance — the Ornstein–Uhlenbeck-process speed-of-reversion estimator. The implementation here — the dual-leg synthetic spread with optional log construction, the rolling Z-normalisation pipeline, the AR(1) regression with HL formula and min/max-HL gating, the entry/exit state machine with cooldown and max-hold, the rolling N-trade backtest tracker, and the minimal-mono institutional aesthetic — is JOAT-original. No third-party code reused. The script is a tribute to the Medallion-style approach, not a direct replication of any proprietary Renaissance Technologies code.
Limitations
The single-leg "synthetic pair" (price vs its own EMA) is a degenerate stat-arb construction by design — true stat-arb uses two genuinely co-integrated instruments. Pine's per-script symbol limitation makes a two-instrument cointegration construction impractical for a standalone indicator; this script captures the methodology of stat-arb (spread + Z + HL gate) on the single-instrument case. The HL estimate is statistical and needs the regression window populated; early bars give a warm-up read.
—
-made with passion by jackofalltrades
Indicator

Mean Reversion Pro 📊 Mean Reversion Pro — Data-Driven Edge on Any Market, Any Timeframe
Most mean reversion indicators tell you the price is "too far" from the moving average. This one tells you exactly how far is statistically worth trading — using your own chart's historical data as proof.
Works on all instruments and timeframes: futures (NQ, ES, CL, GC…), crypto (BTC, ETH, SOL…), forex (EUR/USD, GBP/USD…), indices (SPX, DAX, NASDAQ…), stocks, commodities — anything with a price and volume.
─────────────────────────────────────────
🔍 WHAT THIS INDICATOR DOES
─────────────────────────────────────────
Mean Reversion Pro silently analyses every historical instance where price deviated from a moving average by a given distance. For each of 15 tested threshold levels it computes:
• Win rate — % of times price returned to the MA within the timeout
• Expectancy — (win-rate × avg MFE) − (loss-rate × avg MAE)
• Profit Factor — gross gain / gross loss ratio
• Avg MAE — average adverse excursion (how far against you before reverting)
• Avg MFE — average favourable excursion (how far in your favour)
• Avg return time — average bars needed to reach the MA
It then automatically selects the threshold with the highest expectancy that also satisfies your minimum win-rate and minimum occurrences filters — and only then shows a signal. No manual optimisation. No curve-fitting.
─────────────────────────────────────────
⚙️ KEY FEATURES
─────────────────────────────────────────
✅ Universal — works on futures, crypto, forex, indices, stocks, commodities
✅ 3 threshold modes: fixed Points, ATR multiples, Z-Score (adapts to any volatility regime)
✅ 5 MA types: EMA, SMA, WMA, VWMA, Hull MA
✅ Auto-optimised threshold — the indicator finds the best level by itself
✅ Real-time dashboard: win-rate, expectancy, profit factor, MAE, MFE, return time (Long & Short)
✅ Dynamic bands: 1× and 1.5× optimal threshold zones drawn on the chart
✅ Non-repainting signals — only fires on confirmed, closed bars
✅ Optional filters: trend (EMA 50), volume, US session, minimum ATR
✅ Minimum history guard — signals are held until enough bars have been analysed
✅ All parameters fully exposed and documented with tooltips
─────────────────────────────────────────
📈 WHO IS THIS FOR
─────────────────────────────────────────
• Futures traders — NQ, MNQ, ES, MES, CL, GC, SI, ZB…
• Crypto traders — BTC, ETH, SOL and all altcoins on any exchange
• Forex traders — all major, minor and exotic pairs
• Index traders — SPX, NDX, DAX, FTSE, CAC, Nikkei…
• Stock traders and swing traders looking for mean reversion pullbacks
• Prop firm traders who need a systematic, rules-based edge
• Any trader tired of arbitrary support/resistance levels with no statistical backing
─────────────────────────────────────────
🧠 HOW TO USE IT
─────────────────────────────────────────
1. Apply to any chart on any timeframe
2. Let at least 500 bars load (recommended: 1000–2000 for robust statistics)
3. Choose Threshold Mode:
— Points → best for futures and indices (fixed price distances)
— ATR → best for crypto and forex (volatility-adjusted)
— Z-Score → best for statistical/quant approaches
4. Set your minimum Win Rate (default 65%) and minimum Occurrences (default 15)
5. A signal appears only when all statistical conditions are met AND your filters pass
6. Read the dashboard to assess setup quality before entering a trade
─────────────────────────────────────────
💡 WHY EXPECTANCY MATTERS MORE THAN WIN RATE
─────────────────────────────────────────
A strategy with 80% win rate can still lose money if the average loss is 5× the average win. Mean Reversion Pro uses expectancy — the only metric that combines win rate, average gain and average loss into a single number — as its selection criterion. A signal only appears when the math is in your favour.
─────────────────────────────────────────
⚠️ DISCLAIMER
─────────────────────────────────────────
This indicator is a decision-support tool only. It does not provide financial advice and does not guarantee future results. Past statistical performance is not indicative of future performance. Always use proper risk management. Indicator

Trade Strategy Calculator [WillyAlgoTrader]📊 Trade Strategy Calculator is the first comprehensive mathematical strategy calculator built entirely inside PulseWire — a 4-panel dashboard that computes position sizing, risk analysis, deposit growth projection, and Kelly Criterion optimization in real time, directly on your chart. No spreadsheets, no external tools, no switching tabs. Every number you need before entering a trade — position size, stop loss level, take-profit targets, commission impact, expected value, probability of ruin, compound growth forecast, and optimal bet sizing — calculated from your strategy parameters and displayed in a single organized view.
This tool is useful for every trader regardless of market, instrument, or timeframe — stocks, forex, crypto, futures, indices, commodities. Whether you trade scalping on 1-minute charts or swing on daily, whether you use 1x spot or 125x futures leverage — the mathematics of position sizing, risk management, and bankroll growth are universal. This calculator puts those mathematics at your fingertips.
🧩 WHY ALL FOUR PANELS WORK TOGETHER
Most traders calculate position size in isolation — they know how much to risk but don't connect it to their long-term growth trajectory. They know their win rate but don't know if it's mathematically profitable after commissions. They have a "feel" for their risk level but haven't computed what happens after 7 consecutive losses.
This calculator connects four mathematical dimensions into one coherent picture:
🎯 TRADE panel answers: "How large should this specific trade be, and what are the exact entry/SL/TP prices?"
⚠️ RISK panel answers: "What happens when things go wrong — how many losses until I hit my daily limit, my max drawdown, and what's my expected value per trade?"
📈 GROWTH panel answers: "If I trade consistently with these parameters, where will my deposit be in 30/90/365 days — and how long to reach my target?"
📐 KELLY panel answers: "Am I betting the mathematically optimal amount — or am I over-betting (risking ruin) or under-betting (leaving growth on the table)?"
A trader who only uses the TRADE panel knows their position size but not whether their strategy has positive expected value. A trader who only uses KELLY knows the optimal bet size but not the specific position for their current trade. A trader who only uses GROWTH knows the projection but not whether the underlying math is sound. All four together give you the complete picture: "Is my strategy profitable? Am I sizing correctly? What's the worst case? And where does this lead?"
🔍 WHAT MAKES IT ORIGINAL
There is no other indicator on PulseWire that combines all four of these mathematical models — position sizing, risk stress testing, compound growth simulation, and Kelly Criterion — into a single, real-time, interactive dashboard. Each panel alone would be a useful tool. Together, they create something that doesn't exist elsewhere on the platform.
🎯 PANEL 1 — TRADE (Position Sizing + Targets)
This panel calculates the exact position size for your trade based on your deposit, risk percentage, stop loss distance, leverage, and commissions.
Core formula:
positionSize = riskAmount / (slDistance% + commissionBothSides)
Where:
— riskAmount = deposit × riskPerTrade%
— slDistance% = slPercent × (1 + slippage%) — slippage is added to the stop distance for realistic sizing
— commissionBothSides = commission% × 2 (open + close)
This formula ensures that if your stop loss is hit, you lose exactly riskAmount — not more, not less — after accounting for both slippage and round-trip commission.
What you see:
— Direction (Long / Short)
— Entry Price (manual or auto from chart)
— Stop Loss price (calculated from entry ± SL%)
— 💰 Position Size in USD — the headline number
— Margin Required (if leverage > 1)
— Quantity (units/coins/shares)
— 🔴 Risk (loss) in USD and % of deposit
— 🟢 Profit at TP — in USD, % of deposit, and net R:R after commission
— TP Price level
— Commission cost in USD
— Liquidation price (for leveraged positions)
— ⚠️ Insufficient margin warning (if position exceeds deposit)
Multi Take-Profit mode:
When enabled, the position is split across 2 or 3 TP levels with configurable volume allocation:
— TP1 at R:R 1.0 with 50% of position → locks partial profit early
— TP2 at R:R 2.0 with 30% → captures the main move
— TP3 at R:R 3.0 with 20% (if 3 TPs) → runner for extended moves
Each TP shows: profit in USD, target price. The panel also computes:
— Total blended profit across all TPs
— Net R:R (blended, after commissions)
— Breakeven price after TP1 — the price where your remaining position becomes zero-loss after banking TP1 profit. This is critical: after TP1, you move your stop to this price — the trade can no longer lose money.
Example:
Deposit: $10,000. Risk: 1% ($100). SL: 2%. Commission: 0.04%.
Position = $100 / (0.02 + 0.0008) = $4,808.
If BTC at $100,000 → SL at $98,000, TP1 at $102,000.
If stopped out → you lose exactly $100 (1% of deposit).
If TP1 hit → you gain ~$96 (after commission).
⚠️ PANEL 2 — RISK (Stress Testing + Expected Value)
This panel answers: "What happens when I have a losing streak, and is my strategy mathematically profitable?"
Daily risk limit:
maxLosingDaily = floor(dailyRiskLimit% / riskPerTrade%)
Example: 3% daily limit, 1% per trade → you stop after 3 losses in a day.
Max drawdown limit:
maxLosingTotal = floor(maxDrawdown% / riskPerTrade%)
Example: 20% max DD, 1% per trade → 20 consecutive losses to hit max DD.
Stress test — losing streaks:
The panel computes what happens after 5, 7, and 10 consecutive losses:
— depositAfterN = deposit × (1 − riskPerTrade%)^N
— drawdownAfterN = (1 − (1 − riskPerTrade%)^N) × 100%
— probabilityOfN = (1 − winrate%)^N × 100%
Example: $10,000 deposit, 1% risk, 55% winrate:
— 5 losses: −4.9% DD ($9,510), probability 1.85%
— 7 losses: −6.8% DD ($9,321), probability 0.37%
— 10 losses: −9.6% DD ($9,044), probability 0.03%
This tells you: a 5-loss streak WILL happen (1.85% probability over hundreds of trades). A 10-loss streak is extremely rare (0.03%). Your risk% must be sized so that even the realistic worst case doesn't blow your account.
Expected Value (EV):
EV per trade = winrate × riskAmount × avgR:R − (1 − winrate) × riskAmount − commission
This is the single most important number in trading. If EV > 0, your strategy makes money over time. If EV < 0, no amount of position sizing saves you.
The panel shows:
— 📈 EV per trade in USD (highlighted — this is the headline metric)
— EV per 100 trades
— Break-even winrate WITH commission — the minimum winrate needed to be profitable at your R:R, accounting for commission drag
— Your actual WR and R:R for comparison
Break-even winrate formula (with commission):
beWinrate = (1 + commissionCost / riskAmount) / (avgR:R + 1)
This is more accurate than the standard 1/(R:R+1) because it accounts for commission reducing your net edge.
📈 PANEL 3 — GROWTH (Deposit Projection + Scenarios)
This is the unique deposit growth simulator — it projects where your deposit will be after N days of consistent trading, using either compound (reinvest profits) or simple (fixed risk from initial deposit) growth.
Compound growth formula:
EV per trade as % = winrate × (risk% × R:R) − (1 − winrate) × risk%
totalTrades = tradesPerDay × projectionDays
finalDeposit = deposit × (1 + evPerTrade%)^totalTrades
Simple growth formula:
finalDeposit = deposit + deposit × evPerTrade% × totalTrades
The difference is massive. Compound growth reinvests profits — each winning trade increases the base for the next trade. Simple growth always risks a fixed amount from the initial deposit.
Example — compound vs simple:
$1,000 deposit, 55% WR, 1:2 R:R, 1% risk, 3 trades/day, 30 days:
— Simple: $1,000 + $1,000 × 0.65% × 90 = $1,585
— Compound: $1,000 × (1.0065)^90 = $1,795
Over 90 days: $1,585 vs $1,795. Over 365 days the gap becomes enormous. This is why compound growth (reinvesting profits) is the key to deposit acceleration.
Three scenarios:
— 🟢 Optimistic: your winrate + 10% (what happens if you're having a great month)
— 🟡 Realistic: your actual parameters
— 🔴 Pessimistic: your winrate − 10% (what happens during a drawdown period)
This gives you a range, not a single number. If even the pessimistic scenario is positive, your strategy is robust.
Goal milestones:
— Days to 2× deposit (double your money)
— Days to 3× deposit
— Days to custom target ($5,000, $10,000, etc.)
Formula: daysToTarget = log(target / deposit) / (log(1 + evPerTrade%) × tradesPerDay)
Risk metrics:
— Max estimated drawdown: based on expected worst losing streak × risk%
— Ruin probability: the probability of losing your entire bankroll at your current risk level
Ruin probability formula:
edge = winrate × R:R − (1 − winrate)
bankrollUnits = floor(100 / risk%)
ruinProb = ((1 − winrate) / (winrate × R:R))^bankrollUnits
If edge ≤ 0, ruin probability is effectively 100%. If edge > 0, ruin probability decreases exponentially with more bankroll units (lower risk%).
Presets for quick scenarios:
— Beginner: 45% WR, 1:2 R:R, 1% risk — conservative starting point
— Moderate: 55% WR, 1:2 R:R, 2% risk — typical intermediate trader
— Aggressive: 50% WR, 1:3 R:R, 3% risk — higher risk, needs discipline
— Custom: uses your exact My Strategy values
📐 PANEL 4 — KELLY CRITERION (Optimal Bet Sizing)
The Kelly Criterion is the mathematically optimal percentage of your bankroll to risk on each bet, given your edge. It maximizes the long-term growth rate of your account.
Kelly formula:
edge = winrate × avgR:R − (1 − winrate)
kellyPercent = edge / avgR:R
If edge ≤ 0 → Kelly = 0% (no edge, don't trade). If edge > 0 → Kelly tells you the maximum you should risk.
What the panel shows:
— Your winrate and avg R:R
— Break-even winrate (with commission)
— 📐 Edge per $1 risked — your mathematical advantage. If +$0.15, every $1 risked returns $1.15 on average.
— Full Kelly % — the theoretical maximum. Most traders should NOT use this — it's too aggressive.
— Half Kelly ✦ — the recommended practical value. Reduces variance by ~75% while giving up only ~25% of growth.
— Quarter Kelly — ultra-conservative, minimal variance.
— Your current risk % — so you can compare
— Status: 🟢 Optimal (between half and full Kelly), 🟡 Conservative (below half), 🔴 Over-bet (above full Kelly), 🚨 >2× Kelly (danger zone)
Growth rate comparison:
— Growth rate at Kelly %: the compound growth rate per trade at the optimal bet size
— Growth rate at your %: your actual compound growth rate per trade
Formula: growthRate = winrate × log(1 + risk% × R:R) + (1 − winrate) × log(1 − risk%)
If your rate is close to the Kelly rate, you're near-optimal. If it's much lower, you're leaving growth on the table. If it's negative (possible when over-betting!), you're actually losing money despite having a positive edge — the over-betting destroys the compounding.
Why this matters:
A trader with a 55% WR and 1:2 R:R has an edge. Kelly says risk ~4.6%. But if that trader risks 10% per trade (2× Kelly), their actual growth rate can become negative — they go broke despite having a winning strategy. This is the most counterintuitive result in trading mathematics: over-betting a winning system turns it into a losing system . The Kelly panel prevents this.
📖 HOW TO USE — STEP BY STEP
Step 1 — Enter your strategy parameters (My Strategy section):
— Deposit: your actual account balance in USD
— Risk per Trade: how much you risk per trade (start with 1% if unsure)
— Winrate: your historical win rate (be honest — check your journal)
— Average R:R: your average reward-to-risk on winning trades
— Trades per Day: how many trades you typically take
— Leverage: 1 for spot, or your futures leverage
— Commission: your exchange fee per side (Binance Futures taker: 0.04%)
Step 2 — Set up your current trade (Trade Setup section):
— Direction: Long or Short
— Stop Loss %: how far your SL is from entry
— Risk:Reward: your target R:R for this trade
— Entry Price: manual or auto from chart
Step 3 — Read the TRADE panel:
— The 💰 Position Size number is your order size in USD
— If using leverage, check Margin Required doesn't exceed your deposit
— Note the SL and TP prices — set these in your exchange
Step 4 — Check the RISK panel:
— Is your EV per trade positive? If not, your strategy loses money long-term
— Is your winrate above the break-even? If not, improve your R:R
— Check the stress test: can your deposit survive 7 losses in a row?
— If the risk badge shows 🚨 DANGER, reduce your risk% or leverage
Step 5 — Review the GROWTH panel:
— The projected deposit shows where you'll be in 30 days
— Check the pessimistic scenario — is it still above your starting deposit?
— Note the days to 2× — this is your compound growth timeline
— If ruin probability > 5%, your risk is too high
Step 6 — Optimize with KELLY panel:
— Compare your risk% to Half Kelly — this is the recommended level
— If Status shows 🔴 Over-bet, reduce your risk%
— If Status shows 🟡 Conservative, you could increase (but don't have to)
— Check Growth Rate at Your % — is it positive? Is it close to Kelly's rate?
🎯 PRACTICAL EXAMPLES
Example 1 — Conservative Spot Trader:
Deposit $5,000, Risk 1%, WR 55%, R:R 1:2, 2 trades/day, No leverage, Commission 0.1%
— Position: ~$2,500 per trade. Risk: $50.
— EV: +$5.60 per trade. Positive — strategy is profitable.
— 30-day projection (compound): $5,000 → $5,705 (+14.1%)
— Days to double: ~98 days
— Kelly: 4.6%. Your 1% = conservative. Status: 🟡
Example 2 — Crypto Futures Scalper:
Deposit $1,000, Risk 2%, WR 50%, R:R 1:3, 5 trades/day, Leverage 10x, Commission 0.04%
— Position: ~$10,000 per trade. Margin: $1,000. Risk: $20.
— EV: +$10.40 per trade. Strong positive edge.
— 30-day projection (compound): $1,000 → $4,680 (+368%)
— Days to double: ~14 days
— Kelly: 8.3%. Your 2% = well below Kelly. Room to grow.
— ⚠️ But 7-loss streak probability: 0.78%. DD: −13.2%. Manageable.
Example 3 — Why Over-Betting Kills:
Same as Example 2, but Risk 15% (almost 2× Kelly):
— EV per trade still positive (+$78)
— BUT growth rate per trade: NEGATIVE (−0.3%)
— 30-day projection: $1,000 → $620 (−38%)
— Kelly Status: 🚨 >2× Kelly
— Despite winning 50% with 1:3 R:R, you LOSE money because over-betting destroys compounding.
⚙️ KEY SETTINGS REFERENCE
⚙️ My Strategy:
— Deposit : account balance in USD
— Risk per Trade (default 1%): % of deposit risked per trade
— Winrate (default 55%): historical win rate
— Average R:R (default 2.0): average reward-to-risk on wins
— Trades per Day (default 3): daily trade count
— Leverage (default 1): 1 = spot, >1 = futures
— Commission (default 0.04%): exchange fee per side
🎯 Trade Setup:
— Direction : Long / Short
— Stop Loss % (default 1%): SL distance from entry
— Risk:Reward (default 2.0): target R:R
— Slippage (default 0.05%): expected execution slippage
— Entry Price : Manual or Auto (chart price)
🎯 Multi Take-Profit:
— Enable Multi TP (default Off): split into 2–3 targets
— R:R for TP1/TP2/TP3 (default 1.0/2.0/3.0)
— Volume allocation (default 50%/30%/20%)
📈 Growth Projection:
— Preset : Beginner / Moderate / Aggressive / Custom
— Projection Period (default 30 days)
— Compound (default On): reinvest profits
— Target Deposit (default 0 = off): goal amount
— Max Daily Risk (default 3%): daily loss limit
— Max Drawdown (default 20%): total DD limit
🎨 Visual:
— Font Size: Tiny / Small / Normal / Large
— Auto / Dark / Light theme
⚠️ IMPORTANT NOTES
— 📊 This is a calculator, not a signal generator. It does not produce buy/sell signals. It computes the mathematical framework for your trading decisions — position sizing, risk limits, growth projections, and optimal bet sizing. The math is universal and applies to any strategy.
— 📐 All calculations are deterministic — they depend only on your input parameters, not on price data. The dashboard updates in real-time when you change any input.
— ⚖️ The growth projection assumes consistent strategy parameters over the projection period. Real trading involves varying win rates, R:R ratios, and market conditions. The three scenarios (optimistic/realistic/pessimistic) partially address this by showing a range.
— 📏 The Kelly Criterion assumes known, fixed probabilities . In practice, your winrate and R:R fluctuate. This is why Half Kelly (not Full Kelly) is recommended — it accounts for parameter uncertainty.
— 💰 Commission is calculated as round-trip (both sides) and deducted from both profit calculations and expected value. This provides realistic net returns.
— 📊 The break-even winrate calculation includes commission drag — it's higher than the simplified 1/(R:R+1) formula because commission erodes your edge.
— 🔄 The compound growth formula uses logarithmic overflow protection — if the projected growth exceeds exp(23) ≈ 10 billion ×, it displays "∞" instead of crashing.
— 🛠️ Works on any chart, any instrument, any timeframe . The calculator is price-independent — it uses your manual inputs. "Auto" entry price mode uses the current chart close for convenience.
— 🌐 Useful for all markets : stocks (set leverage = 1, commission = 0.1%), forex (adjust for pip-based SL), crypto spot (leverage = 1), crypto futures (set your leverage), indices, commodities. Indicator

Breakout Probability (Expo)█ Overview
Breakout Probability is a valuable indicator that calculates the probability of a new high or low and displays it as a level with its percentage. The probability of a new high and low is backtested, and the results are shown in a table— a simple way to understand the next candle's likelihood of a new high or low. In addition, the indicator displays an additional four levels above and under the candle with the probability of hitting these levels.
The indicator helps traders to understand the likelihood of the next candle's direction, which can be used to set your trading bias.
█ Calculations
The algorithm calculates all the green and red candles separately depending on whether the previous candle was red or green and assigns scores if one or more lines were reached. The algorithm then calculates how many candles reached those levels in history and displays it as a percentage value on each line.
█ Example
In this example, the previous candlestick was green; we can see that a new high has been hit 72.82% of the time and the low only 28.29%. In this case, a new high was made.
█ Settings
Percentage Step
The space between the levels can be adjusted with a percentage step. 1% means that each level is located 1% above/under the previous one.
Disable 0.00% values
If a level got a 0% likelihood of being hit, the level is not displayed as default. Enable the option if you want to see all levels regardless of their values.
Number of Lines
Set the number of levels you want to display.
Show Statistic Panel
Enable this option if you want to display the backtest statistics for that a new high or low is made. (Only if the first levels have been reached or not)
█ Any Alert function call
An alert is sent on candle open, and you can select what should be included in the alert. You can enable the following options:
Ticker ID
Bias
Probability percentage
The first level high and low price
█ How to use
This indicator is a perfect tool for anyone that wants to understand the probability of a breakout and the likelihood that set levels are hit.
The indicator can be used for setting a stop loss based on where the price is most likely not to reach.
The indicator can help traders to set their bias based on probability. For example, look at the daily or a higher timeframe to get your trading bias, then go to a lower timeframe and look for setups in that direction.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Indicator

Strategy
