OPEN-SOURCE SCRIPT

Setup Expectancy Lab

499
Setup Expectancy Lab

█ OVERVIEW

The Setup Expectancy Lab is a measurement instrument, not a signal generator. You point it at a signal you already have — an event stream published by another indicator, or any plotted price line such as an EMA or VWAP — and it simulates the identical bracket trade on every occurrence across the loaded chart history. It then reports what that setup has actually been worth under one fixed mechanical rule: sample size, win rate with honest confidence intervals, expected R per trade, average time to resolution, and excursion diagnostics — optionally split by market regime.

It was originally built as the measurement companion to the HTF Regime Navigator [HRN] indicator, but it deliberately depends on nothing: the Price Line modes derive events from any visible plot on your chart, so the Lab is fully useful on its own from the first minute. The question it answers is the one most traders never quantify: is this setup worth taking — and under which conditions?

This is an indicator, not a strategy script. It places no orders and does not use the Strategy Tester; it is a statistics table driven by an internal trade simulator.

█ WHY IT'S ORIGINAL AND USEFUL

Pine has strategy() for backtesting complete systems. What it lacks is a lightweight, reusable instrument for measuring the quality of a RAW SIGNAL — any signal, from any indicator — under one fixed, comparable rule, without writing a new strategy script for every idea. That is the gap this tool fills, and several of its mechanisms are, to my knowledge, novel in combination:

• Universal signal intake. Three interpretation modes for the wired source: a ±1 event-stream protocol (any indicator that publishes hidden data plots), Price Line: Cross (long = close crosses above the wired line, short = below), and Price Line: Test (price holding above dips to touch the line and closes back above; mirrored for shorts). The line modes mean any plotted level — an EMA, a VWAP, a band — becomes a measurable entry with zero companion requirements.

• A data-integrity halt system. Pine source inputs default to `close`, and a lab wired to `close` would record every candle as an entry — confident-looking, meaningless statistics. This tool refuses: recording HALTS loudly until the source is wired, and type-aware validity checks catch both mistakes in both directions (a dollar-valued line wired as an event stream, and a ±1 stream wired as a line). Recording garbage that looks like data is worse than recording nothing.

• Statistical honesty machinery. Win rates carry a Wilson 95% confidence interval, chosen over the normal approximation because it stays honest at small N and extreme rates. A ★ is awarded only when the EXACT Wilson lower bound clears the bracket's breakeven win rate (stop ÷ (stop + target), shown live in the header) — meaning the edge is statistically distinguishable from chance at 95%. Rows below a minimum sample render dimmed, and tooltips carry gap-robust medians alongside means.

• A built-in control group. When the optional gate is on, every gate-REJECTED signal is fully simulated anyway with the identical bracket into a ✂ Reject row. One instance therefore runs a gated-vs-ungated A/B automatically: if the rejected signals underperform the accepted ones, the filter is earning its keep; if they carry edge, the filter is discarding value.

• A live pre-flight footer. A Next row shows exactly what would happen if a long or short confirmed at this bar's close — records, gate-rejected, in cooldown, direction-filtered, or halted — with an evaluation order that mirrors the recording logic precisely.

█ THE BRACKET ENGINE, MECHANICALLY

Entry is taken at the close of the confirmed signal bar. Target and stop are ATR multiples (defaults: 2×ATR(14) target, 1×ATR(14) stop), with a horizon expiry (default 20 bars; expiry marks to close and counts as a win only if R > 0). The simulator is deliberately conservative:

• Gap-aware: a bar OPENING beyond the stop or target fills at the open, not at the ideal price.
• Stop-first: when a single bar's range could have hit both levels, the loss is booked — OHLC cannot order intrabar events, so ambiguity always resolves against the setup.
• Confirmed bars only; a trade recorded this bar is not evaluated until the next. No lookahead anywhere.

The breakeven win rate for the current bracket — stop ÷ (stop + target), 33% at the defaults — is displayed in the Win% header, so every number in the table is read against the bar it must clear.

█ REGIME CONDITIONING (OPTIONAL)

Wire the Regime Source to a companion indicator's regime-code stream (protocol: 2 = Trend Up, 1 = Accumulation, 0 = Neutral, −1 = Distribution, −2 = Trend Down, read at the entry bar) and results split into five regime rows plus All — the same signal often carries edge in one environment and none in another, and this is how you find out. With no regime source on the chart, switch Condition by Regime off and the Lab reports a single All row. If the regime source is miswired, entries bucket to Neutral, the header warns, and the All row stays valid.

█ IMPORTANT: WHAT YOU SEE ON FIRST ADD (⛔)

When you first add the Lab, the table header reads "⛔ WIRE SIGNAL SOURCE" and nothing records. This is intentional, not a defect. Pine cannot default a source input to an external plot — it defaults to `close` — and an unwired lab would otherwise record every bar as an entry. Open Settings → Sources, point Signal Source at a real stream or a plotted line, choose the matching Signal Type, and the entire chart history replays instantly: you start with a populated table, not an empty one. The header tooltip explains every halt state and how to clear it.

█ WIRING RECIPES

• Any moving average, no companions needed: Signal Type = Price Line: Cross, Signal Source = the MA's plot. The table now answers "what has buying this line's reclaim been worth?" Use the Direction Filter (Long Only) if you only care about one side, and note that in Both mode each row mixes reclaim-longs with breakdown-shorts of the same line.
• The pullback test: Signal Type = Price Line: Test on a fast EMA, Dedupe Cooldown 3–5 (a trend riding the line can legitimately test it on consecutive bars). Cross bars are deliberately excluded from Test, so the two modes partition events instead of double-counting.
• An event-emitting companion: Signal Type = Event Stream (±1), Signal Source = the companion's hidden event plot (values ≥ +0.5 = long event, ≤ −0.5 = short). Impulse mode records one entry per transition; State mode records every qualifying bar.
• Your own script, in one line: add `plot(myCondition ? 1 : 0, display = display.none)` to anything you've written and it becomes a measurable signal here.
• Gate + A/B: enable the gate, wire a confluence/zone/divergence stream (or a price line — "only while above the 200 EMA" is a two-click gate), set the memory window, and compare the real rows against the ✂ Reject row.

Because Pine scripts cannot read the NAME of a wired source — only its values cross into the script — you label what you wired via the Signal and Gate nickname inputs; the table and footer stay legible no matter what is connected.

█ QUICK START: COMPANION SETTINGS FOR THE HTF REGIME NAVIGATOR

The Lab was designed alongside the HTF Regime Navigator (HRN), whose hidden bus streams map one-to-one onto the Lab's inputs. If you run both, this is the recommended starting configuration — it measures HRN's mechanical entry signal, split by HRN's own regime read:

• Signal Type = Price Line: Test (the Impulse/State dropdown is ignored in line modes — one less thing to set)
• Signal Mode = Impulse (transitions only) — HRN's streams emit one ±1 event per confirmation, so the default is already correct.
• Regime Source = HTF Regime Navigator: EXT: Regime Code · Condition by Regime = ON. The footer's Regime row should immediately show the same regime HRN's dashboard displays — a five-second wiring check.
• Direction Filter = Both · Dedupe Cooldown = 0 — HRN's own confirmation closes and signal cooldown already space its entries; a Lab cooldown on top would drop legitimate signals.
• Confluence Gate = OFF for the first pass. Establish the unconditioned baseline before testing any filter.
• Bracket Engine = defaults (target 2×ATR(14), stop 1×ATR(14), 20-bar horizon; breakeven 33%, shown live in the header). Keep the bracket identical across every configuration you intend to compare.
• Table Position = Middle Right — the default, chosen specifically so it does not collide with HRN's top-right dashboard or bottom-left breakdown table.

Once the baseline has a sample, the natural second pass is the gate A/B: Enable Gate · Gate Type = Event/State Stream (±1) · Gate Source = HTF Regime Navigator: EXT: Confluence State (or EXT: Golden Zone State) · Gate Nickname = "Confluence" · Gate Memory = 0–3 · Direction Logic = Match Signal Direction · Reject Row = ON. The real rows now answer "the signal inside the confluence zone," and the ✂ Reject row answers "the same signal outside it" — the filter's value, in one table. HRN's EXT: Spring / Upthrust stream deserves the same treatment as a Signal Source in a second instance: what a qualified spring has been worth, per regime, under the identical bracket.

█ QUICK START WITH THE HTF REGIME NAVIGATOR (HRN)

The Lab was built alongside the HTF Regime Navigator, and the recommended starting configuration measures the setup that system is built around: price holding above the fast EMA, dipping to test it, and closing back above — the reclaim-and-test entry. HRN's fast EMA is a visible plot, so this recipe also demonstrates the Price Line mode: no event stream required, just the line itself.

Baseline — the signature entry, measured raw:
• Signal Type = Price Line: Test (the Impulse/State dropdown is ignored in line modes — one less thing to set)
• Signal Source = HTF Regime Navigator: MA 1 (the fast EMA — chart-timeframe 50 at HRN's defaults) · Nickname "EMA1 Test"
• Regime Source = HTF Regime Navigator: EXT: Regime Code · Condition by Regime = ON
• Direction Filter = Long Only for the classic buy-the-test question — in Both, each regime row mixes tests of the EMA as support with tests of it as resistance
• Dedupe Cooldown = 3 — Test mode fires on each qualifying bar, and price riding an EMA in a trend can legitimately test it on consecutive bars; 3–5 thins them to distinct episodes
• Gate = OFF · Bracket Engine = defaults (2×ATR target, 1×ATR stop, 20-bar horizon → 33% breakeven)

Result: what buying the test of HRN's fast EMA has been worth on this chart, split by the regime it fired in. Wiring note: because MA 1 is a dollar-valued line, it must be wired under a Price Line type — under Event Stream it correctly trips the ⛔ magnitude halt, whose message points to this exact fix.

The upgrade — "inside the fibs" (location on trial):
• Enable the Gate · Gate Type = Event/State Stream (±1)
• Gate Source = HTF Regime Navigator: EXT: Golden Zone State (or EXT: Confluence State) · Nickname "Golden Zone"
• Gate Memory = 0–3 (state streams stay active while the condition holds, so a small window is correct — the default 8 is tuned for impulse-style divergence gates) · Direction Logic = Match Signal Direction

Result: the real rows become "the EMA test inside the Fibonacci value zone" and the ✂ Reject row becomes the identical test outside it — one table answering whether location is paying rent on this symbol.

Worth a second instance: Signal Type = Price Line: Cross on the same MA 1 measures the reclaim itself rather than the later test (the two modes partition events — a cross bar never double-counts as a test), and Signal Source = EXT: Entry Signal Confirmed (Event Stream, Impulse, Dedupe Cooldown 0 — HRN's engine applies its own confirmation and cooldown) measures the full mechanical signal engine. Keep brackets identical across instances so the expectancies are comparable. The Lab's table defaults to Middle Right specifically so it doesn't collide with HRN's Top Right and Bottom Left tables.

█ READING THE TABLE

• N — resolved simulated trades in the bucket. Rows below the minimum sample dim automatically.
• Win% — win rate ± the Wilson 95% half-width (the displayed ± approximates an asymmetric interval; the exact bounds are in each cell's tooltip). ★ = the exact lower bound clears the bracket's breakeven rate.
• Exp R — average R per resolved trade, the expectancy.
• Bars — average bars from entry to resolution.
• L·MFE — average maximum favorable excursion of LOSING trades, in R: how far losers ran in your favor before dying. Approaching the target multiple suggests the target is too far.
• W·MAE — average maximum adverse excursion of WINNING trades, in R: heat winners took. Well under 1.0 suggests the stop is wider than the setup needs. Excursions exclude each trade's resolution bar (OHLC cannot order intrabar events), so both are slightly understated — conservative by design.
• Last K — a rolling window over the most recent resolved trades with its own interval and a median-R tooltip; compare against All to spot edge decay or improvement.
• ✂ Reject — the gate's control group, aggregate only.
• Conditions footer — the live signal read (nickname, type, ▲/▼ when firing this bar), the live regime bucket, gate ages versus the memory window, and the Next pre-flight row (✔ records · ✂ gated · ⏸n cooldown · ✗off filtered · ⛔ halted).

Entry markers print on the chart for every recorded trade (five styles, fully customizable), and gated-out signals can be marked in gray so you can see exactly what a filter removed.

█ HONEST LIMITATIONS

• The statistics measure raw signal behavior under one fixed mechanical rule on the loaded chart's history. They are not a backtest of a complete trading plan, they include no commissions, slippage, or position sizing, and they are not predictive of future results.
• One symbol per instance — Pine cannot aggregate across a portfolio.
• The confidence interval assumes independent trades; overlapping open positions weaken it somewhat (stated in the header tooltip rather than hidden).
• Small samples are noise. The dimming and the intervals exist precisely so that small samples LOOK like noise.

█ SETTINGS NOTES

Every input carries a tooltip. The highest-leverage settings: Signal Type and Source (the wiring), the Bracket Engine multiples and horizon (changing the bracket changes the breakeven rate — the header recomputes it live), the Dedupe Cooldown for dense line tests, the Gate group with its memory window and direction logic, and Min N for the dimming threshold. For side-by-side comparisons, run multiple instances with tables at different positions — and keep the brackets identical, because expectancy is only comparable when the trade definition is fixed.

█ DISCLAIMER

This script and its description are for educational and informational purposes only and do not constitute financial advice. Win rates and expectancies shown are measurement outputs of historical, single-symbol simulations under one fixed mechanical rule — instruments for evaluating a process, never a promise about future trades. Always do your own research and manage your own risk.

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.