//@version=6 // ============================================================================= // J3P — 5-DMA Compression Bands + VCET (compression / expansion / trend) // Author handle: jdomino2 // BUILD: v4.5 <- shown in the status table so you can verify from the chart // // v4.5 RANGE-SCALED OVEREXTENSION + fixes. (1) OX now WAITS FOR THE // MEASURED MOVE: while price is still inside the last compression // range's projected objective (range height × mmMult from the range // edge), a 2σ close prints as EXPANSION, not OVEREXTENDED — it is // trend travel the range just paid for, not extension. Once the MM // level is tagged, OX arms; a new compression re-arms the gate. The // projected levels draw as thin steplines (the red-box top, drawn for // you). Entries are untouched — pull-ins at the vwap/rail stay the // buy; this only stops the flag yelling fade mid-move. (2) Band // colors: band 1 (0.5σ) is the purple one on the vwap frame, 1σ back // to gray. (3) Backsides AUTO-HIDE on the 1–29m execution frame (new // toggle, default on) — per-timeframe, no dropdown flipping; other // frames keep whatever Backside role is saved. // v4.4 BACKSIDE OFF SWITCH. "Backside role" gains a third option: // "Off — hide entirely". One dropdown darkens the whole backside layer // — no backside or base-break trades, NO labels, no EXTENDED warning // in the table, no backside alerts. (The reg-gate checkbox was never // built for this: it blocks TRADES only, and only when the 20-day // reference is actually trending against them — and it never touched // labels.) WAVE5 covers keep working: they read the raw 2σ re-entry, // not the backside layer. // v4.3 TIMEFRAME-AWARE DISPLAY + THE CLOUD (engine untouched). Each overlay // now draws only where it means something: 2-day / WTD / MTD vwaps on // the 1–29m execution frame only; session VWAP + PDH/PDL on any // intraday frame (they are the Play 1 / PDH-break references, incl. // the 30m setup frame), never on daily+ — a session-anchored vwap on // daily bars hugs every candle and reads as spaghetti. Daily+ shows // exactly: 20DMA basis + σ stack. vwapDisp = "Everywhere" restores the // old drawing. Execution-frame cosmetics: the 1σ band draws PURPLE to // match the vwap basis, the 50-min rail draws RED, and the MA-State // cloud is folded in between price and the rail — green = above a // rising rail, yellow = pull-in below a rising rail (the re-entry // zone), red = below a falling rail, orange = counter-trend pop. // v4.2 THE TREND RAIL. On a trend day price never returns to the session // VWAP — it pulls back to the fast mean (~50 minutes of price: 25 bars // on a 2-min, 10 on a 5-min). Play 1's PULL-IN / flush-reclaim // reference is now selectable: VWAP only (v4.1 behaviour), the fast // MA, or (default on the <30m frame) the NEAREST RAIL = // max(session VWAP, fast MA). Early day the two are the same line, so // chop behaves exactly like v4.1; on a trend day the rail carries the // re-entries. The LEG is still measured from VWAP and a CLOSE through // VWAP still voids the setup — trigger at the rail, void at the day's // line in the sand. The basis-trail stop option also rides the rail on // the execution frame. fastMins (default 50) sizes the rail in MINUTES // so it is the same object on any timeframe. // v4.1 THE EXECUTION FRAME (1–29 min). Below 30 minutes the basis auto- // switches to the SESSION VWAP (9:30 regular-session anchor, source = // the VWAP-group input, default ohlc4) and the bands become the // session's volume-weighted σ around that vwap — same 0.5/1/2/3σ stack, // same BW %ile compression engine, same regime/trade engine on top. // 30m+ keeps the true 5-DMA, daily+ the 20DMA: one engine, three zooms. // Warm-up guard (vwapWarm): session σ starts near zero at the open, // which would fake a coil every morning — no compression / expansion / // overextension reads until N bars into the session. Toggle: // useVwapBasis. Backside + OX-gating work is parked, not lost. // v4.0 Play 1S REMOVED (VWAP play is long-only per spec). Play 1 gains the // FASH-LATE trigger: a bar flushes below the hold low and closes back // above the VWAP — the failed shakeout is the entry, at the low, stop // under the flush bar. Box-break stays as the confirm trigger; default // Both. Structure gives the stop; the basis is the trail, not the risk. // v3.9 VWAP-play chop fix: a pull-in now requires a LEG (ride must travel // vpLeg × ATR away from the line first) — price straddling the VWAP // arms neither side, ending the Play 1/1S churn in chop. Plus regime // alignment: no 1S while the regime is UP, no Play 1 while it is DOWN. // v3.8 PLAY 1 / 1S — the J3P VWAP play itself, finally wired as a TRADE: // reclaim the session VWAP -> ride it -> pull IN and HOLD at the line // -> break the consolidation box -> enter. Stop = the HOLD low/high // (the structure that defines the trade), not the far-away basis. // Trend-class: WAVE5 cover, preempts fades, reversible. New VWAP L/S // buckets in the edge table. // v3.7 Default display mode = FULL (bands visible on fresh load). // v3.6 STOP MANAGEMENT (opt-in): Breakeven after +1R, or trail trend trades // behind the basis minus the ATR floor. R is ALWAYS measured against // ORIGINAL risk (tRisk0) so a moved stop cannot flatter the edge table. // Partials stay out of Pine by design — they corrupt per-trade R; that // layer belongs in KITE. Default = None (the measured baseline). // v3.5 REGIME-CHANGE markers: a tiny text tag on the exact candle where the // table's Regime row flips — including the missing half: expansion // ENDING ("◂ EXPANSION DN ended" = the trend break), overextension // entered/left, coil ending. States are now visible events, all modes. // Also: one file with display modes, NOT two forked versions — forks // double every bug; settings fork for free. // v3.4 DISPLAY MODES — computation separated from drawing. FULL = every // band/vwap (analysis & audit view). CLEAN (new default) = basis + // session VWAP + PDH + all signals/tables, faint regime tint carrying // the cycle instead of the band stack. STEALTH = bare candles, signals // and tables only. The engine is identical in all three. // v3.3 The basis ANNOUNCES ITSELF on every timeframe: table header + slope // row read 5DMA intraday and 20DMA (WMA/MMA) on daily+; the basis line // and inner fill turn RED on daily+ so the regime tool is unmistakable; // trade labels say "-> 20DMA" instead of a hardcoded 5DMA. // v3.2 Vertical WINDOW-START marker (all timeframes incl. daily): dashed // line at bar_index − (len − 1) — the first bar feeding the average. // len−1, not len, because the live open bar is bar #len of the window. // v3.1 Daily+ timeframes switch the basis to a 20 DMA (dailyLen input) — a // 5-period MA on daily bars hugs price; the swing-scale mean is the 20. // Intraday keeps the true N-day span. Matches the MA Cloud convention. // v3.0 VWAP OVERHAUL: all anchors moved to the REGULAR-SESSION open (9:30) // via session.isfirstbar_regular, so RTH / ETH / 24h chart views draw // identical vwaps — flipping the session toggle moves nothing. Added // month-to-date vwap (#0097a7 teal). Source default = OHLC4. Set: // 1D purple, 2D blue (rolling two sessions), WTD black, MTD teal. // Overnight bars accumulate into the running vwap; 9:30 is the reset. // v2.9 TRUE 5-DMA ON ANY SESSION, INCLUDING 24-HOUR EQUITY DATA. The old // syminfo detector could not see 24h stock sessions (type "stock", // session "extended" -> assumed 960 min; the MA ran ~33% short). Now // bars/day is MEASURED from the prior completed chart day, and the // basis / stdev / RVOL baseline are computed from cumulative sums so a // live (series) length is legal. Percentile & slow-MA windows still use // the preset day-length (simple-int APIs); structure targets now come // from the daily feed. Flip RTH/ETH/24h and it re-adapts by itself. // v2.8 REVERSE: an opposite TREND signal (CONT or EXP) now exits an open // trend trade at the close and takes the slot the same bar — a textbook // short firing IS the exit for the long. Logged REVERSE (scratch). // v2.7 CONT entry LOCATION mode: enter at the failed retest of the 5-DMA // (bounce tags the mean in phase 2, closes back through it, lower-high / // higher-low intact) instead of waiting for the leg break far from the // mean. Location vs confirmation is now a choice; default = Both. // v2.6 STRUCTURE target for trend trades: trendTgtMode option "Prior 5-day // low/high" — a coil-break short targets the trailing 5-day low (the // prior swing lows the market actually trades toward), mirrored for // longs. The swing-trade objective instead of an arbitrary R multiple. // v2.5 Trend-trade target is now a PARAMETER: trendTgtMode = far 2σ band // (entry snapshot, old behaviour) or Fixed R; trendRR (default 2.0) is // both the fixed multiple and the fallback when the band sits inside // 0.5R. Set it high (e.g. 20) to effectively ride to the WAVE5 cover. // v2.4 THE MISSING TRADE: expansion out of a coil is now an ENTRY (EXP L/S), // not just an annotation. Compression at the mean -> 1σ break with // widening bands, within coilRecent bars of a coil -> go with the break. // Trend-priority (with CONT), preempts open fades, WAVE5 cover applies. // Edge table grows to 8 buckets. bounceMode default -> "Reclaim 1σ band" // (the pullback-to-1σ IS the second-chance trend entry). // v2.3 WAVE-5 COVER (trend-cycle management): an open CONT short is flattened // when price re-enters UP through -2σ — the impulse leg is complete and // the correction to the mean is starting; that re-entry is the cover, // not a new long. Mirrored for CONT longs at +2σ. Logged WAVE5. // NOTE on scale: bounceMode STRICT (reclaim the 5-DMA) is the correct // setting for the swing-scale impulse->correction->resumption cycle; // the looser modes exist for intraday waterfalls that never reclaim. // v2.2 TREND ENTRIES WERE BEING STARVED (edge table: CONT N=1 across 743 // trades — a fade almost always held the one-trade slot when the CONT // trigger bar arrived, and the one-bar signal evaporated). Fixes: // - PREEMPT: a CONT signal flattens an open backside/base at the close // (logged PREEMPT, scratch) and takes the slot the same bar. // - PRIORITY: on a conflicting bar, a continuation overrides a backside // in the other direction; CONT wins kind/stop/target when both fire. // v2.1 Backside target = NEAREST objective (new default): whichever of session // VWAP / 5-DMA is on the profit side and closer. On low timeframes after // a gap the 5-DMA can sit 10%+ away — a fixed 5-DMA target is unreachable // and every backside dies as STOP or TIME (10R+ on a label = diagnostic, // not a gift). na-safe 2R fallback when neither objective is valid. // v2.0 SIZING + full trade block in the table: // - riskDollars input; shares = floor(risk$ / stop distance). Qty shown // on every entry label and in the table. Grade scaling (A/B/C) stays a // manual multiplier on top. // - Status table now shows Entry x Qty, Stop / Tgt, and R:R while a // trade is open. (E/S/T on CONT labels shipped in v1.9.) // v1.9 Entry labels now print the numbers: E entry / S stop / T target /(R:R). // Computed at the moment the trade opens (stop-cap already applied), so // the label always matches the actual position. In Warning-only mode the // label shows what the trade WOULD be without opening it. // v1.8 MEASUREMENT, not more signals: // - EDGE TABLE (bottom-right): per-signal-type N / W-L / Win% / TotR and // ExpR (expectancy in R per trade). Aggregate W-L cannot tell you WHICH // setup works; this can. Grey = N<10, not enough to judge. // - Backside ROLE: Entry (day-trade the extension) vs Warning only // (trend mode — label prints, table flags 'no chase / no adds', but no // trade opens). Fixes treating a risk flag as a trade signal. // - Optional DOUBLE-TAP: backside requires a SECOND 2s tag that failed to // exceed the first. The first tag in a trend is the expansion starting. // v1.7 Fixes the "wrong side of a waterfall" failure: // - bounceMode: STRICT (reclaim the 5-DMA) never arms in a waterfall, so // no short can fire during a straight-line decline. Looser modes arm on // the 2-3 bar bounces a trending tape actually gives. // - STOP-CAP go/no-go: skip the trade outright if the structural stop is // wider than maxStopATR. (A backside long risking 16 to make 7 is not a // trade.) This is the ADTR stop-cap scoped for j3p_STAGING. // - Loss-streak breaker: after N consecutive stops in one DIRECTION, that // direction pauses until a winner or a new day. Table shows PAUSED. // - Entry labels now only print when a trade actually opened. // v1.6 Hysteresis was TOO STICKY (exit at a fixed 40 %ile latched compression // on for ~40% of all bars, which made the 'out of a coil' gate useless). // Now a narrow band: exit = compPct + compHystPts (default 8). // PDH break fires ONCE PER DAY and only out of a COIL — previously price // oscillating around the prior-day high re-printed it on every cross. // v1.5 Compression gained hysteresis so one coil prints ONE label instead of // re-firing on every RVOL blip. // Compression is classified by LOCATION: near the mean = COIL (breaks // either way), beyond baseMinSD = BASE (a pause after a completed move). // New BASE BREAK entry: track the base range at an extreme, trigger on // the break of it — the 'handle' break. Stop = the base's far side. // v1.4 Continuation triggers are STRUCTURAL, not band crosses: // SHORT = weakness leg -> bounce (lower high) -> break the WEAKNESS LOW // LONG = strength leg -> dip (higher low) -> break the STRENGTH HIGH // Trigger reference selectable: leg level / session LOD-HOD / PDL-PDH. // PDL is now used in logic (it was plotted but dead). Setups expire // after phaseMax bars. Arming labels print the actual trigger price. // v1.3 Trade state engine: ONE position at a time. A signal only fires when // flat; the trade holds the slot until stop / target / timeout. Exits // labelled with R multiple; W-L-S tally + live stop/target in the table. // Optional higher-trend gate (slow reference, not the laggy 5-DMA). // v1.2 3s bands. Backside extension filter (opt-in). 5-DMA slope as a // MANAGEMENT readout (FLAT = revert to mean, sloping = runner) — NOT an // entry gate, since the MA always leans the extension's way at re-entry. // v1.1 VWAP overhaul: session (purple) / rolling 2-day (blue) / WTD (black), // all anchored to session boundaries; RTH / ETH / 24h auto-adjust. // Expansion fires on the 1s break itself; volume is a TAG, not a gate. // v1.0 True 5-DMA on any timeframe (days x bars-per-day), 0.5/1/2s bands, // BandWidth-percentile compression engine, backside re-entry flags. // ============================================================================= VER = "v4.6" indicator("J3P 5DMA Compression Bands + VCET [jdomino2]", overlay = true, max_labels_count = 400, max_bars_back = 5000) // --------------------------------------------------------------------------- // INPUTS // --------------------------------------------------------------------------- gD = "Display" dispMode = input.string("Full — all lines", "Display mode", group = gD, options = ["Full — all lines", "Clean — trade view", "Stealth — signals only"], tooltip = "FULL: every band + vwap — the analysis/debug view; when a label surprises you, this is how you audit it. CLEAN: basis + session VWAP + PDH + all signals/tables, with a faint background tint carrying the regime instead of the band stack. STEALTH: bare candles, signals and tables only. The ENGINE is identical in all three — only the drawing changes.") showShift = input.bool(true, "Mark REGIME CHANGES on price (all modes)", group = gD, tooltip = "A small text tag on the exact candle where the table's Regime row flips — expansion starting, expansion ENDING (the trend break), overextension entered/left, coil ending. States become visible events. Text-only, so it stays quiet even in Clean/Stealth.") regTint = input.bool(true, "Regime background tint (Clean / Stealth)", group = gD, tooltip = "Faint green = expansion up, faint red = expansion down, faint pink = overextended. Replaces the band stack as the where-am-I-in-the-cycle carrier. The orange coil shading always shows.") railCloud = input.bool(true, "State cloud on the 50-min rail (1–29m)", group = gD, tooltip = "v4.3 — the MA State Cloud folded in, drawn between price and the fast rail on the execution frame. Green = price above a rising rail; YELLOW = pull-in below a rising rail (the re-entry zone Play 1 now triggers from); red = below a falling rail; orange = above a falling rail (counter-trend pop).") railSlope = input.int(1, "Rail slope lookback (bars)", minval = 1, group = gD, tooltip = "Bars back used to judge the rail's direction for the cloud state. Raise to 3–5 to calm green/yellow flip chatter on the 2-min.") gMA = "5-DMA basis (auto length)" src = input.source(hlc3, "Source", group = gMA) dmaDays = input.int(5, "DMA — trading days", minval = 1, group = gMA) bpdMode = input.string("Measure the chart (any session)", "Bars/day mode", group = gMA, options = ["Measure the chart (any session)", "Preset (RTH 390 / ETH 960 / 24h crypto-fx)", "Manual"], tooltip = "MEASURE (default): counts the bars in the prior completed day, so RTH / ETH / 24-hour STOCK data all resolve to a true 5-DMA automatically — flip the chart session and it re-adapts. Preset = the old syminfo heuristic (cannot see 24h equity data). Manual = the minutes below.") sessMin = input.int(390, "Manual session minutes", minval = 1, group = gMA) dailyLen = input.int(20, "Daily+ MA length (daily / weekly / monthly)", minval = 1, group = gMA, tooltip = "On daily and higher timeframes a 5-period MA hugs price and the bands mean nothing — the swing-scale equivalent of the mean is the 20-day. Intraday charts always use the true N-day span above.") maType = input.string("SMA", "Basis MA type", options = ["SMA", "EMA"], group = gMA) showWin = input.bool(true, "Mark where the MA window starts (vertical line)", group = gMA, tooltip = "Dashed vertical at bar_index − (len − 1): the FIRST bar feeding the average. It sits len−1 back, not len, because the live (still-open) bar is bar #len of the window. 30m RTH: 64 back of a 65-bar window. Daily: 19 back of the 20 DMA.") useVwapBasis = input.bool(true, "1–29 min: basis = session VWAP + σ bands", group = gMA, tooltip = "v4.1 — THE EXECUTION FRAME. Below 30 minutes the swing MAs are the wrong mean; the execution frame's mean is the session VWAP. Basis becomes the 9:30-anchored session VWAP (source = the VWAP-group input, default ohlc4) and the bands become the session's volume-weighted σ around it. The whole engine — BW %ile compression, expansion, regime, trades, tables — runs unchanged on top. 30m+ keeps the true 5-DMA, daily+ the 20DMA.") vwapWarm = input.int(5, "VWAP σ warm-up (bars after the open)", minval = 0, group = gMA, tooltip = "Session σ starts near zero at 9:30, which would fake a compression every morning. No compression / expansion / overextension reads until this many bars into the session. Structure plays (Play 1, PDH logic) are not blocked by the warm-up.") gB = "Bands (SD multiples of the 5-DMA)" sIn = input.bool(true, "0.5s — coil / VWAP edge", group = gB) sMid = input.bool(true, "1.0s — trend break", group = gB) sOut = input.bool(true, "2.0s — over-extension", group = gB) sFar = input.bool(true, "3.0s — extreme (backside filter)", group = gB) mIn = input.float(0.5, "Inner mult", step = 0.1, group = gB) mMid = input.float(1.0, "Mid mult", step = 0.1, group = gB) mOut = input.float(2.0, "Outer mult", step = 0.1, group = gB) mFar = input.float(3.0, "Extreme mult", step = 0.1, group = gB) gV = "VWAPs (anchored to session boundaries)" vwapSrc = input.source(ohlc4, "VWAP source", group = gV, tooltip = "OHLC4 per spec. NOTE: if this shows hlc3 after loading, your saved setting is overriding the new default — set it to ohlc4 or reset settings.") sV1 = input.bool(true, "Session VWAP (1D) — purple", group = gV) sV2 = input.bool(true, "2-day VWAP — blue", group = gV) sVW = input.bool(true, "Week-to-date VWAP — black", group = gV) sVM = input.bool(true, "Month-to-date VWAP — teal (#0097a7)", group = gV) sPDH = input.bool(true, "Prior-day high / low", group = gV) vwapDisp = input.string("Auto — by timeframe", "Where vwaps + PDH/PDL draw", group = gV, options = ["Auto — by timeframe", "Everywhere (v4.2 behaviour)"], tooltip = "AUTO (v4.3): each line only where it means something. 2-day / WTD / MTD vwaps draw on the 1–29m execution frame only. The session VWAP and PDH/PDL draw on any INTRADAY frame — they are the Play 1 and PDH-break references, including the 30m setup frame — and never on daily+, where a session-anchored vwap hugs every candle and reads as spaghetti. The per-line toggles above still apply on top. EVERYWHERE restores the old drawing.") gC = "Compression / expansion engine" bwDays = input.int(20, "BandWidth lookback — days", minval = 1, group = gC) compPct = input.int(20, "Compression STARTS when BW %ile <", minval = 0, maxval = 100, group = gC) compHystPts = input.int(8, "Compression hysteresis (BW %ile pts)", minval = 1, maxval = 50, group = gC, tooltip = "Compression ENDS when BW %ile rises above compPct + this. Small band = just enough to stop RVOL flicker re-firing the label. Large band = compression latches on for long stretches (which makes any 'breaking out of a coil' gate useless).") baseMinSD = input.float(1.5, "Compression is a BASE beyond (× SD)", step = 0.25, group = gC, tooltip = "Compression near the mean = COIL (breaks either way). Compression this far from the mean = BASE (a pause after a completed move — the 'handle'). Same math, opposite trade.") shadeC = input.bool(true, "Shade compression zones", group = gC) useMMox = input.bool(true, "Overextension waits for the measured move", group = gC, tooltip = "v4.5 — price still inside the last compression range's projected objective (range height × the multiple below, measured from the range edge) cannot print OVEREXTENDED; a 2σ close there shows as EXPANSION instead. Once the measured-move level is tagged, OX arms until a new compression re-arms the gate. Entries are untouched — this only stops the regime/flag from yelling fade in the middle of the move the range just paid for.") mmMult = input.float(1.0, "Measured move (× range height)", step = 0.25, minval = 0.25, group = gC, tooltip = "1.0 = the classic full measured move. Drop to 0.75 if you want OX to arm as price gets NEAR the objective rather than exactly at it.") gVol = "Volume (RVOL) — confirmation tag only" volDays = input.int(20, "RVOL lookback — days", minval = 1, group = gVol) rvHot = input.float(1.5, "Volume-confirmed RVOL >=", step = 0.1, group = gVol) rvCold = input.float(1.0, "Compression RVOL <", step = 0.1, group = gVol) gS = "Continuation setups (weakness/strength engine)" sShort = input.bool(true, "Short: weakness after strength", group = gS) sLong = input.bool(true, "Long: strength after the dip", group = gS) pivLB = input.int(10, "Pivot lookback (bars)", minval = 2, group = gS) useLHLL = input.bool(true, "Require lower-high / higher-low", group = gS) contMode = input.string("Leg low / leg high", "Continuation trigger", group = gS, options = ["Leg low / leg high", "Session LOD / HOD", "Prior day L / H", "0.5σ band (old)"], tooltip = "What price must BREAK to trigger. 'Leg low/high' = the low of the weakness leg (short) or high of the strength leg (long) — a level the market actually watches. The 0.5σ band is the old behaviour and is not a structural level.") contEntry = input.string("Both — first to fire", "CONT entry location", group = gS, options = ["Break of leg low/high (confirm)", "Reject at the 5-DMA (location)", "Both — first to fire"], tooltip = "CONFIRM (old): enter on the break of the weakness low / strength high — confirmed but far from the mean, wide stop. LOCATION: enter at the failed retest of the 5-DMA — price tags the mean in phase 2 and closes back through it with the lower-high/higher-low intact. Entry near the mean, stop just beyond the tag. Better R:R, fires before confirmation, more failed bounces. BOTH: whichever comes first.") phaseMax = input.int(30, "Setup expires after (bars in phase)", minval = 3, group = gS, tooltip = "Stops a half-formed setup lingering forever waiting on a trigger.") useExpTrade = input.bool(true, "Trade the expansion break out of a coil", group = gS, tooltip = "THE core VCET trade: compression at the mean -> 1σ break with widening bands -> go with the break. Fires only when a COIL was present within coilRecent bars, so a bare 1σ cross in open air is not an entry. Stop = 3-bar swing + ATR floor; target = far band with 2R fallback. WAVE5 cover applies (rides the trend until the opposite 2σ re-entry).") coilRecent = input.int(12, "Coil must be within (bars)", minval = 1, group = gS) bounceMode = input.string("Reclaim 1σ band", "Bounce required to arm", group = gS, options = ["Reclaim 5-DMA (strict)", "Reclaim 1σ band", "2 bars against (loose)"], tooltip = "How big a counter-move arms phase 2. STRICT needs price back to the mean — in a waterfall decline that never happens, so no short ever arms. Looser settings let the machine arm on the small 2-3 bar bounces that are the only pullbacks a trending tape gives you.") gVP = "VWAP play (Play 1 / 1S)" useVwapPlay = input.bool(true, "Trade the VWAP pull-in — LONG ONLY (Play 1)", group = gVP, tooltip = "PLAY 1: price reclaims the session VWAP, rides it, pulls IN to the line and HOLDS, then breaks the consolidation high -> long. Stop = the hold low (the structure that defines the trade). PLAY 1S is the mirror below VWAP. Trend-class: WAVE5 cover, preempts fades, reversible.") vpTol = input.float(0.25, "Pull-in must reach within (× ATR of VWAP)", step = 0.05, minval = 0.0, group = gVP) vpFail = input.float(0.25, "Void if close beyond VWAP by (× ATR)", step = 0.05, minval = 0.0, group = gVP, tooltip = "A wick through the line is a hold; a CLOSE this far through it is a failed hold — setup void.") vpMinAbove = input.int(3, "Bars riding VWAP before a pull-in counts", minval = 1, group = gVP) vpLeg = input.float(1.0, "Ride must travel (× ATR from VWAP) before a pull-in counts", step = 0.25, minval = 0.0, group = gVP, tooltip = "A pull-in needs a LEG to pull in from. Price straddling the line never builds one, so neither side arms — this is what stops the machine churning shorts and longs in VWAP chop.") vpRegime = input.bool(true, "Align with regime (no Play 1 in a down regime)", group = gVP) vpTrigger = input.string("Both — first to fire", "Play 1 trigger", group = gVP, options = ["Box-high break (confirm)", "Undercut & reclaim (fash-late)", "Both — first to fire"], tooltip = "BOX BREAK: enter when the consolidation high snaps — confirmed but late. FASH-LATE: a bar FLUSHES below the hold low and closes back above the VWAP — the failed shakeout IS the entry, at the low, stop under the flush bar. Both = first to fire.") vpRefMode = input.string("Trend rail — nearest of VWAP / fast MA", "Pull-in reference (execution frame)", group = gVP, options = ["Session VWAP only (v4.1)", "Fast MA (50-min)", "Trend rail — nearest of VWAP / fast MA"], tooltip = "v4.2 — what a pull-in must reach for Play 1 to arm, and what the flush bar must reclaim. On a trend day price rides far above VWAP and only ever pulls back to the fast mean, so a VWAP-only reference gives you the open and then nothing. TREND RAIL (default) = the higher of session VWAP / fast MA: early day they overlap and nothing changes, trend day the rail carries the re-entries. The LEG is still measured from VWAP and a close through VWAP still voids. Only active on the <30m VWAP-basis frame; 30m+ always behaves like VWAP only.") fastMins = input.int(50, "Fast MA span (minutes)", minval = 4, group = gVP, tooltip = "The rail, sized in MINUTES so it is the same object on any execution timeframe: 50 min = 25 bars on a 2-min, 10 bars on a 5-min. EMA of close.") gBS = "Backside quality filters" useExt = input.bool(false, "Require deep extension before 2s re-entry", group = gBS, tooltip = "OFF by default. When on, only arms a backside if price reached bsMinExt SD during the >2s excursion. Note: a literal 3.0 tag is very rare intraday — 2.5 = deep past 2SD without muting everything.") bsMinExt = input.float(2.5, "Min extension (× SD)", step = 0.25, minval = 2.0, group = gBS) slopeLen = input.int(3, "5-DMA slope readout lookback (bars)", minval = 1, group = gBS) useRegGate = input.bool(false, "Block backsides fighting the higher trend", group = gBS, tooltip = "OFF by default. Uses a slow (default 20-day) reference the extension can't drag around — unlike the 5-DMA, which always leans the extension's way at a re-entry. When on: no backside LONGS while the slow trend is down and price is under it; no backside SHORTS in the mirror case. This is what kills a cluster of longs on a steady decline.") regDays = input.int(20, "Trend reference — days", minval = 5, group = gBS) bsEntry = input.string("Immediate 2σ re-entry", "Backside entry style", group = gBS, options = ["Immediate 2σ re-entry", "Wait for base break", "Both"], tooltip = "Immediate = fire on the re-entry bar (catches the knife). Base break = wait for a consolidation to form at the extreme, then trigger on the break of that base's high/low — the 'handle' break. Fewer signals, later entry, confirmation instead of prediction.") baseMinBars = input.int(3, "Base must be at least (bars)", minval = 2, group = gBS) baseMaxBars = input.int(20, "Base expires after (bars)", minval = 3, group = gBS) baseVolBrk = input.bool(false, "Require volume on the base break", group = gBS, tooltip = "IBD principle: breakouts should come on above-average volume. Uses the RVOL hot threshold.") bsRole = input.string("Entry", "Backside role", options = ["Entry", "Warning only", "Off — hide entirely"], group = gBS, tooltip = "ENTRY = mean-reversion trades fire normally (day-trading the extension). WARNING ONLY = backside and base-break labels still print and the table flags the environment, but NO trade opens — trend-trading mode, where an extension is a 'do not chase / do not add' flag rather than a signal to fade. OFF (v4.4) = the whole backside layer goes dark: no trades, no labels, no table warning, no backside alerts. Continuation / expansion / VWAP trades keep firing in every mode, and WAVE5 covers still work when Off.") bsAutoHide = input.bool(true, "Auto-hide backsides on the execution frame (1–29m)", group = gBS, tooltip = "v4.5 — per-timeframe darkness: on the <30m VWAP-basis frame the whole backside layer is hidden regardless of the role above (the execution frame is for compression -> expansion -> trend, not fades). 30m and daily keep whatever Backside role is saved. Untick to let the role above apply everywhere.") useDoubleTap = input.bool(false, "Backside needs a SECOND tag (double top/bottom)", group = gBS, tooltip = "Your rule applied to extensions: the FIRST 2s tag in a trend is the expansion starting, not ending — there is no information in it. Requires a prior excursion whose peak the current one failed to exceed. Later entry, far fewer signals.") tapWin = input.int(30, "Second tag within (bars)", minval = 3, group = gBS) tapTol = input.float(0.5, "Allow 2nd tag to exceed 1st by (%)", step = 0.1, minval = 0.0, group = gBS, tooltip = "A marginal higher high that immediately fails is a failed breakout — often the best version of the pattern. 0 = strict lower high.") gTr = "Trade state (one position at a time)" oneAtATime = input.bool(true, "Block new signals while a trade is open", group = gTr, tooltip = "A signal only fires when FLAT. The trade holds the slot until it resolves at stop, target, or timeout.") tgtMode = input.string("Nearest (VWAP or 5DMA)", "Backside target", options = ["Nearest (VWAP or 5DMA)", "5-DMA (mean)", "Session VWAP"], group = gTr, tooltip = "NEAREST = whichever of session VWAP / 5-DMA is on the profit side and closer — cover into VWAP first, 5-DMA is the runner. On low timeframes after a gap the 5-DMA can sit 10%+ away, making a fixed 5-DMA target unreachable (every trade dies as STOP or TIME).") trendTgtMode = input.string("2σ band (entry snapshot)", "Trend-trade target (EXP / CONT)", options = ["2σ band (entry snapshot)", "Fixed R", "Prior 5-day low/high (structure)"], group = gTr, tooltip = "2σ band: far band at entry (Fixed-R fallback usually takes over at a coil). Fixed R: explicit multiple. STRUCTURE: the trailing 5-day extreme — a short off a coil break targets the prior swing lows the market actually trades toward (the swing-trade objective). Fewer targets hit, bigger when they do; WAVE5 may cover first. The edge table arbitrates.") trendRR = input.float(2.0, "Fixed R multiple / fallback", step = 0.5, minval = 0.75, group = gTr) atrLen = input.int(14, "ATR length", minval = 1, group = gTr) useATRstop = input.bool(true, "ATR floor on stop", group = gTr) minStopATR = input.float(0.5, "Min stop (× ATR)", step = 0.1, group = gTr, tooltip = "Structural stop is pushed out if it sits closer than this. 0.5 ATR matches the j3p_STAGING min_stop_atr floor.") maxBars = input.int(26, "Max bars in trade (auto-flat)", minval = 2, group = gTr, tooltip = "Safety valve so one stuck trade can't silence the indicator forever.") coolBars = input.int(0, "Cooldown bars after an exit", minval = 0, group = gTr, tooltip = "0 = off. Raise it to stop immediate re-entry into the same failing idea.") showExits = input.bool(true, "Label exits (R multiple)", group = gTr) riskDollars = input.float(100.0, "Risk per trade ($)", step = 25.0, minval = 1.0, group = gTr, tooltip = "Dollar risk if the stop is hit. Shares = floor(risk$ / (entry - stop)). With a $500 daily stop budget, $100/trade = five full stops before the day is done. Grade-based scaling (A=1.5x, B=1.0x, C=0.5x) is a manual multiplier on top.") useStopCap = input.bool(true, "Skip trade if stop is too wide", group = gTr, tooltip = "Go/no-go: if the structural stop sits further than maxStopATR from entry, the R:R is not worth taking and the trade is skipped entirely. In a violent decline the 3-bar stop can be 10%+ away.") maxStopATR = input.float(2.0, "Max stop (× ATR)", step = 0.25, minval = 0.5, group = gTr) trailMode = input.string("None (fixed stop)", "Stop management", group = gTr, options = ["None (fixed stop)", "Breakeven after +1R", "Trail behind the basis (trend trades)"], tooltip = "NONE: stop never moves (current behaviour — the measured baseline). BREAKEVEN: once price runs +1R in your favor, the stop rises to entry — a winner can no longer become a full loser. TRAIL: trend trades (EXP/CONT) drag the stop behind the basis minus the ATR floor as it climbs; fades keep their fixed stop. R results are ALWAYS measured against the ORIGINAL risk, so a moved stop cannot flatter the edge table. Change this ONE dial at a time and compare ExpR.") useWaveCover = input.bool(true, "Cover a CONT at the opposite 2σ re-entry (wave-5 cover)", group = gTr, tooltip = "Trend-cycle management: if a continuation SHORT is open and price re-enters UP through -2σ, the impulse leg (wave 5) is complete and the correction back to the mean is starting — that re-entry is the COVER, not a new long. Mirrored for a CONT long at +2σ. Logged WAVE5.") maxLossStreak = input.int(2, "Pause a direction after N stops", minval = 0, group = gTr, tooltip = "0 = off. After N consecutive stop-outs in the SAME direction, that direction is blocked until a winner or a new day. This is what stops five backside longs walking a stock down.") g_wh = "Export / Webhook" sendEvents = input.bool(true, "Send ENTRY/EXIT events", group = g_wh, tooltip = "Fires alert() on every entry and exit so a TradingView webhook writes them to the database. Same contract as SMB2 Fashionably Late, so the existing ingest, the rt monitor and the dashboard FIFO all work unchanged. alertcondition() cannot do this - it only sends a fixed string.") eventTag = input.string("SMB_VCET_EVT", "Webhook tag / indicator name", group = g_wh, tooltip = "Lands in the `indicator` column so VCET rows separate from Fashionably Late and BOAT rows.") trade_prefix = input.string("VCET_1", "Trade ID prefix", group = g_wh) wh_tz = input.string("America/New_York", "Timezone for ts_ny", group = g_wh, options = ["America/New_York", "America/Chicago", "America/Denver"]) test_mode = input.bool(false, "Mark events as testing", group = g_wh, tooltip = "Adds testing:true so the backend can ignore these while the chain is being verified.") wh_json = input.bool(false, "Log the JSON payload", group = g_wh, tooltip = "Prints each payload to Pine Logs so the shape can be checked without sending anything.") // state + helpers MUST sit after the inputs above - sendEvent() reads // sendEvents and eventTag, and Pine rejects a forward reference. var string TRADE_ID = na var int LEG_ID = 0 var int wh_no = 0 f_num(_v, _f) => na(_v) ? "null" : str.tostring(_v, _f) f_tny() => str.format_time(time, "yyyy-MM-dd HH:mm", wh_tz) sendEvent(_m) => if sendEvents alert(eventTag + "|" + _m, alert.freq_once_per_bar_close) gT = "Status table" sTbl = input.bool(true, "Show status table", group = gT) sStats = input.bool(true, "Show per-signal EDGE table", group = gT, tooltip = "The aggregate W-L tells you nothing about WHICH setup works. This breaks results out by signal type and shows expectancy in R per trade — the number that says whether a setup has edge. Positive ExpR with a meaningful N = keep. Negative = the setup does not work on this symbol/timeframe, no amount of filtering will fix it.") fFull = dispMode == "Full — all lines" fClean = dispMode != "Stealth — signals only" // Full or Clean // --------------------------------------------------------------------------- // TIME BASIS + auto bars-per-day (RTH / ETH / 24h self-adjust) // --------------------------------------------------------------------------- newDay = timeframe.change("D") newWeek = timeframe.change("W") // v4.1: session anchor moved up from the VWAP section — the basis engine needs it newSessD = timeframe.isintraday ? session.isfirstbar_regular : newDay // Bars/day. MEASURED from the chart (prior completed day) so any session — // RTH, ETH, or 24-hour equity data — yields a true 5-day span. The syminfo // preset only distinguishes regular/extended/crypto-fx and CANNOT see 24h // stock sessions (type stays "stock", session stays "extended" -> wrong 960). // The preset survives as fallback and for the few simple-int-only contexts // (percentile / slow-MA windows), where an approximate day-length is fine. isExtSess = syminfo.session == session.extended is24h = syminfo.type == "crypto" or syminfo.type == "forex" autoMin = is24h ? 1440.0 : (isExtSess ? 960.0 : 390.0) sMinutes = bpdMode == "Manual" ? float(sessMin) : autoMin tfMin = timeframe.in_seconds() / 60.0 apxBPD = not timeframe.isintraday ? 1 : math.max(1, int(math.round(sMinutes / tfMin))) // simple int // v4.1: the execution frame — below 30 minutes the basis is the session VWAP vwapBasisOn = useVwapBasis and timeframe.isintraday and tfMin < 30 // v4.2: the fast trend rail, sized in minutes (50 min -> 25 bars @2m, 10 @5m) fastBars = math.max(2, int(math.round(fastMins / math.max(tfMin, 1.0)))) fastMA = ta.ema(close, fastBars) // v4.3 — timeframe-aware display policy (drawing only; the engine never changes) dispAll = vwapDisp == "Everywhere (v4.2 behaviour)" vwapSetOK = dispAll or vwapBasisOn // 2D / WTD / MTD: execution frame only sessOK = dispAll or timeframe.isintraday // session vwap + PDH/PDL: intraday only var int _dayCnt = 0 var int measBPD = 0 if newDay if _dayCnt > 0 measBPD := _dayCnt _dayCnt := 0 _dayCnt += 1 int barsPerDay = not timeframe.isintraday ? 1 : bpdMode == "Measure the chart (any session)" ? (measBPD > 0 ? measBPD : apxBPD) : apxBPD len = math.min(4900, not timeframe.isintraday ? math.max(1, dailyLen) : math.max(1, dmaDays * barsPerDay)) // intraday = true N-day span; daily+ = 20 DMA // what IS the basis on this chart — named + colored so it can't be mistaken maName = vwapBasisOn ? "VWAP" : timeframe.isintraday ? str.tostring(dmaDays) + "DMA" : str.tostring(dailyLen) + (timeframe.isweekly ? "WMA" : timeframe.ismonthly ? "MMA" : "DMA") basisCol = vwapBasisOn ? color.purple : timeframe.isintraday ? color.orange : #d32f2f // --------------------------------------------------------------------------- // 5-DMA BASIS + SD BANDS (v4.1: or session VWAP + volume-weighted σ <30m) // --------------------------------------------------------------------------- // SMA / stdev from cumulative sums so a MEASURED (series) length works; // ta.sma / ta.stdev demand a compile-time length and cannot adapt to session. csum = ta.cum(src) csum2 = ta.cum(src * src) smaS = (csum - csum[len]) / len varS = math.max(0.0, (csum2 - csum2[len]) / len - smaS * smaS) alphaS = 2.0 / (len + 1) var float emaS = na emaS := na(emaS[1]) ? src : alphaS * src + (1.0 - alphaS) * emaS[1] // v4.1 — execution-frame basis: session VWAP + volume-weighted σ from the open. // Same reset as the session vwap (9:30 regular-session anchor, per v3.0). σ is // the volume-weighted stdev of the source around the vwap since the anchor — // the vwap-native equivalent of the MA bands. Sums mirror the 2-day-vwap style. var float _sPV = 0.0 var float _sPV2 = 0.0 var float _sV = 0.0 var int sessBar = 0 if newSessD _sPV := 0.0 _sPV2 := 0.0 _sV := 0.0 sessBar := 0 _sPV += vwapSrc * volume _sPV2 += vwapSrc * vwapSrc * volume _sV += volume sessBar += 1 vwapB = _sV > 0 ? _sPV / _sV : vwapSrc vwapVar = _sV > 0 ? math.max(0.0, _sPV2 / _sV - vwapB * vwapB) : 0.0 // warm-up: session σ starts near zero — no comp/expansion/OX reads until seeded warmOK = not vwapBasisOn or sessBar > vwapWarm basis = vwapBasisOn ? vwapB : (maType == "EMA" ? emaS : smaS) dev = vwapBasisOn ? math.sqrt(vwapVar) : math.sqrt(varS) // window-start marker: the first bar inside the MA window (len-1 back — the // live bar is bar #len, so "len bars back" would overshoot by one). // v4.1: hidden in VWAP-basis mode — there the window starts at the 9:30 anchor. var line winL = na var label winT = na if showWin and fFull and barstate.islast and not vwapBasisOn int x0 = bar_index - (len - 1) if na(winL) winL := line.new(x0, close, x0, close + syminfo.mintick, extend = extend.both, color = color.new(color.orange, 45), style = line.style_dashed, width = 1) winT := label.new(x0, high, "", style = label.style_label_down, color = color.new(color.orange, 80), textcolor = color.new(#a06a00, 0), size = size.small) line.set_xy1(winL, x0, close) line.set_xy2(winL, x0, close + syminfo.mintick) label.set_xy(winT, x0, high) label.set_text(winT, maName + " window starts\n" + str.tostring(len) + " bars incl. live") u05 = basis + mIn * dev, l05 = basis - mIn * dev u10 = basis + mMid * dev, l10 = basis - mMid * dev u20 = basis + mOut * dev, l20 = basis - mOut * dev u30 = basis + mFar * dev, l30 = basis - mFar * dev plot(fClean ? basis : na, "Basis (VWAP <30m / 5DMA intraday / 20DMA daily+)", color = color.new(basisCol, 0), linewidth = 2) pU05 = plot(sIn and fFull ? u05 : na, "U 0.5s", color = vwapBasisOn ? color.new(color.purple, 25) : color.new(color.orange, 45), linewidth = 1) // v4.5: band 1 (0.5σ) purple to match the vwap basis pL05 = plot(sIn and fFull ? l05 : na, "L 0.5s", color = vwapBasisOn ? color.new(color.purple, 25) : color.new(color.orange, 45), linewidth = 1) plot(sMid and fFull ? u10 : na, "U 1.0s", color = color.new(color.gray, 15), linewidth = 1) // v4.5: 1σ back to gray everywhere plot(sMid and fFull ? l10 : na, "L 1.0s", color = color.new(color.gray, 15), linewidth = 1) plot(sOut and fFull ? u20 : na, "U 2.0s", color = color.new(#c2185b, 5), linewidth = 1) plot(sOut and fFull ? l20 : na, "L 2.0s", color = color.new(#c2185b, 5), linewidth = 1) plot(sFar and fFull ? u30 : na, "U 3.0s", color = color.new(#2e7d32, 10), linewidth = 1) plot(sFar and fFull ? l30 : na, "L 3.0s", color = color.new(#2e7d32, 10), linewidth = 1) fill(pU05, pL05, color = sIn and fFull ? color.new(basisCol, 92) : na) // --------------------------------------------------------------------------- // VWAPs // --------------------------------------------------------------------------- // ANCHOR = first bar of the REGULAR session (9:30), regardless of what the // chart displays. session.isfirstbar_regular fires on the 9:30 bar even with // premarket on screen, so RTH / ETH / 24h views all draw the SAME vwaps — // flipping the session toggle moves nothing. Overnight bars accumulate into // the running vwap (continuous anchored convention); the reset is 9:30 only. // (newSessD itself is defined up in the TIME BASIS section as of v4.1.) var bool _wPend = false var bool _mPend = false if timeframe.change("W") _wPend := true if timeframe.change("M") _mPend := true newSessW = newSessD and _wPend newSessM = newSessD and _mPend if newSessW _wPend := false if newSessM _mPend := false vwap1 = ta.vwap(vwapSrc, newSessD) // 1-day, purple var float pvT = 0.0 var float pvP = 0.0 var float vTs = 0.0 var float vP = 0.0 if newSessD pvP := pvT vP := vTs pvT := 0.0 vTs := 0.0 pvT += vwapSrc * volume vTs += volume den2 = vTs + vP vwap2 = den2 > 0 ? (pvT + pvP) / den2 : na // rolling 2-day, blue vwapW = ta.vwap(vwapSrc, newSessW) // week-to-date, black vwapM = ta.vwap(vwapSrc, newSessM) // month-to-date, teal plot(sVM and fFull and vwapSetOK ? vwapM : na, "VWAP MTD", color = color.new(#0097a7, 0), linewidth = 2) plot(sVW and fFull and vwapSetOK ? vwapW : na, "VWAP WTD", color = color.new(color.black, 0), linewidth = 2) plot(sV2 and fFull and vwapSetOK ? vwap2 : na, "VWAP 2D", color = color.new(color.blue, 0), linewidth = 2) plot(sV1 and fClean and sessOK and not vwapBasisOn ? vwap1 : na, "VWAP 1D", color = color.new(color.purple, 0), linewidth = 2) // v4.1: hidden when the basis IS the vwap; v4.3: intraday only // v4.3 — the rail in RED + the MA-State cloud folded in (execution frame only) railOn = vwapBasisOn and vpRefMode != "Session VWAP only (v4.1)" railRising = fastMA > fastMA[railSlope] railState = close > fastMA and railRising ? color.new(#26a69a, 78) : close <= fastMA and railRising ? color.new(#f5c518, 78) : close <= fastMA and not railRising ? color.new(#ef5350, 78) : color.new(#ff9800, 78) fastPlot = plot(railOn and fClean ? fastMA : na, "Fast rail (50-min MA)", color = color.new(#d32f2f, 0), linewidth = 2) priceAnch = plot(close, "Price (cloud anchor)", display = display.none) fill(fastPlot, priceAnch, color = railOn and railCloud and fClean ? railState : na, title = "Rail state cloud") pdh = request.security(syminfo.tickerid, "1D", high[1], lookahead = barmerge.lookahead_off) pdl = request.security(syminfo.tickerid, "1D", low[1], lookahead = barmerge.lookahead_off) plot(sPDH and fClean and sessOK ? pdh : na, "PDH", color = color.new(color.teal, 30), style = plot.style_stepline) plot(sPDH and fClean and sessOK ? pdl : na, "PDL", color = color.new(color.teal, 30), style = plot.style_stepline) // --------------------------------------------------------------------------- // COMPRESSION / EXPANSION (BandWidth percentile; RVOL as a tag, not a gate) // --------------------------------------------------------------------------- bwLook = math.max(2, math.min(2000, bwDays * apxBPD)) // simple int (ta.percentrank); approximate day-length bw = (u20 - l20) / basis * 100.0 bwRank = ta.percentrank(bw, bwLook) bwRise = bw > bw[1] cvol = ta.cum(volume) volWin = math.min(4900, math.max(1, volDays * barsPerDay)) avgVol = (cvol - cvol[volWin]) / volWin rvol = avgVol > 0 ? volume / avgVol : na volConf = not na(rvol) and rvol >= rvHot // --- COMPRESSION with HYSTERESIS ------------------------------------------- // Enter when the channel is tight (RVOL qualifies the START only). HOLD until // BandWidth widens past compPct+compHystPts. Without this, RVOL flickering one bar // above/below rvCold re-fires the label repeatedly inside a single coil. // v4.1: warmOK — no compression reads while the session σ is still seeding. compExit = math.min(99, compPct + compHystPts) var bool compOn = false if not compOn and bwRank < compPct and (na(rvol) or rvol < rvCold) and warmOK compOn := true else if compOn and bwRank > compExit compOn := false isComp = compOn compStart = isComp and not isComp[1] compEnd = not isComp and isComp[1] // --- WHERE the compression sits: near the mean = COIL, at an extreme = BASE distSD = dev > 0 ? (close - basis) / dev : 0.0 atExtreme = math.abs(distSD) >= baseMinSD compKind = not isComp ? "" : atExtreme ? "BASE" : "COIL" isCoil = isComp and not atExtreme coilAgo = ta.barssince(isCoil) recentCoil = not na(coilAgo) and coilAgo <= coilRecent // Expansion fires on the STRUCTURAL band break (+ bands widening). No volume gate. expUp = ta.crossover(close, u10) and bwRise and warmOK expDn = ta.crossunder(close, l10) and bwRise and warmOK // --- v4.5: MEASURED-MOVE GATE on overextension ------------------------------ // While price is still inside the last compression range's projected // objective, a 2σ close is trend travel, not overextension. Track the range, // project mmMult × height from its edge, and only arm OX once price has // tagged that level. A new compression re-arms the suppression. var float mmHi = na var float mmLo = na var bool mmHitUp = false var bool mmHitDn = false if compStart mmHitUp := false mmHitDn := false if isComp mmHi := isComp[1] ? math.max(nz(mmHi, high), high) : high mmLo := isComp[1] ? math.min(nz(mmLo, low), low) : low mmUpLvl = na(mmHi) or na(mmLo) ? na : mmHi + mmMult * (mmHi - mmLo) mmDnLvl = na(mmHi) or na(mmLo) ? na : mmLo - mmMult * (mmHi - mmLo) if not na(mmUpLvl) and high >= mmUpLvl mmHitUp := true if not na(mmDnLvl) and low <= mmDnLvl mmHitDn := true oxOKup = not useMMox or na(mmUpLvl) or mmHitUp oxOKdn = not useMMox or na(mmDnLvl) or mmHitDn plot(useMMox and fClean ? mmUpLvl : na, "Measured move ▲", color = color.new(#5b6470, 55), linewidth = 1, style = plot.style_stepline) plot(useMMox and fClean ? mmDnLvl : na, "Measured move ▼", color = color.new(#5b6470, 55), linewidth = 1, style = plot.style_stepline) // --------------------------------------------------------------------------- // PRICE-vs-BAND REGIME + BACKSIDE FLAGS (both directions) // --------------------------------------------------------------------------- outUp = close > u20 and warmOK and oxOKup outDn = close < l20 and warmOK and oxOKdn // --- backside quality: track peak extension during the >2s excursion --- var bool tagUp = false // reached ~3s above during this up-excursion? var bool tagDn = false // reached ~3s below during this down-excursion? if high >= basis + bsMinExt * dev tagUp := true if low <= basis - bsMinExt * dev tagDn := true // --- 5-DMA slope: MANAGEMENT signal only (cover-into-mean vs let-it-run). // NOT an entry gate — the MA lags, so at a re-entry it always points the // extension's way and would block every backside. --- basisSlope = basis - basis[slopeLen] slopeTxt = basisSlope > dev * 0.10 ? "RISING" : basisSlope < -dev * 0.10 ? "FALLING" : "FLAT" // --- DOUBLE-TAP: the first 2s tag in a trend is the expansion STARTING. Only a // second tag that fails to exceed the first is evidence of exhaustion. var float excPkUp = na var float excPkDn = na var float prevPkUp = na var float prevPkDn = na var int prevPkUpB = 0 var int prevPkDnB = 0 var bool inExUp = false var bool inExDn = false bool tapOKup = false bool tapOKdn = false if close > u20 inExUp := true excPkUp := math.max(nz(excPkUp, high), high) else if inExUp tapOKup := not na(prevPkUp) and (bar_index - prevPkUpB) <= tapWin and excPkUp <= prevPkUp * (1.0 + tapTol / 100.0) prevPkUp := excPkUp prevPkUpB := bar_index excPkUp := na inExUp := false if close < l20 inExDn := true excPkDn := math.min(nz(excPkDn, low), low) else if inExDn tapOKdn := not na(prevPkDn) and (bar_index - prevPkDnB) <= tapWin and excPkDn >= prevPkDn * (1.0 - tapTol / 100.0) prevPkDn := excPkDn prevPkDnB := bar_index excPkDn := na inExDn := false // backside = 2s re-entry (+ optional deep-extension and double-tap filters) backArmS = ta.crossunder(close, u20) and (not useExt or tagUp) and (not useDoubleTap or tapOKup) backArmL = ta.crossover(close, l20) and (not useExt or tagDn) and (not useDoubleTap or tapOKdn) // reset extension flags once the excursion ends (evaluated AFTER the arm above) if close <= u20 tagUp := false if close >= l20 tagDn := false // --- PDH break: FIRST break of the day only, and only out of a COIL --------- // Without the once-per-day latch, price oscillating around the prior-day high // re-crosses it repeatedly and prints a label every time. var bool pdhFired = false if newDay pdhFired := false bool pdhRaw = ta.crossover(close, pdh) pdhBreak = pdhRaw and not pdhFired and (isCoil or isCoil[1] or isCoil[2]) if pdhRaw pdhFired := true // --- BASE / HANDLE TRACKER -------------------------------------------------- // A compression that forms at an extreme is a base, not a coil. Track its // high/low; the trigger is the BREAK of that range — the handle break. This is // confirmation instead of prediction: later entry, far fewer signals. var bool baseOn = false var float baseHi = na var float baseLo = na var int baseBar = 0 var int baseDir = 0 // -1 = base at LOWER extreme (long setup), +1 = upper (short) bool baseBrkL = false bool baseBrkS = false bool baseNew = false if not baseOn and compStart and atExtreme baseOn := true baseHi := high baseLo := low baseBar := bar_index baseDir := distSD < 0 ? -1 : 1 baseNew := true else if baseOn bool ripe = (bar_index - baseBar) >= baseMinBars bool volOK = not baseVolBrk or (not na(rvol) and rvol >= rvHot) // check the break BEFORE extending the range, so baseHi/baseLo are prior-bar values if ripe and baseDir == -1 and close > baseHi and volOK baseBrkL := true baseOn := false else if ripe and baseDir == 1 and close < baseLo and volOK baseBrkS := true baseOn := false else if (bar_index - baseBar) > baseMaxBars or compEnd baseOn := false else baseHi := math.max(baseHi, high) baseLo := math.min(baseLo, low) regime = isComp ? "COMPRESSION" : outUp ? "OVEREXTENDED UP" : outDn ? "OVEREXTENDED DN" : close > u10 ? "EXPANSION UP" : close < l10 ? "EXPANSION DN" : "BALANCE" flag = outUp ? "NO NEW LONGS — fade / wait re-entry" : outDn ? "NO NEW SHORTS — fade / wait re-entry" : close > u10 ? "TREND UP — ride with VWAP" : close < l10 ? "TREND DN — ride with VWAP" : isComp ? "COIL — break PDH / reclaim VWAP" : "balance" // --------------------------------------------------------------------------- // CONTINUATION STATE MACHINE ("trade the 2nd move, not the 1st") // --------------------------------------------------------------------------- swingHi = ta.highest(high, pivLB) swingLo = ta.lowest(low, pivLB) // session high/low so far (prior-bar value is the level to break) var float sessLo = na var float sessHi = na if newDay sessLo := low sessHi := high else sessLo := math.min(nz(sessLo, low), low) sessHi := math.max(nz(sessHi, high), high) // cross helpers evaluated on EVERY bar (safe to read inside conditional blocks) xUpBasis = ta.crossover(close, basis) xDnBasis = ta.crossunder(close, basis) xDn1s = ta.crossunder(close, l10) xUp1s = ta.crossover(close, u10) // how big a counter-move arms phase 2 (strict = back to the mean; looser modes // let the machine arm on the small bounces a waterfall actually gives you) bounceUp = bounceMode == "Reclaim 5-DMA (strict)" ? xUpBasis : bounceMode == "Reclaim 1σ band" ? ta.crossover(close, l10) : (close > close[1] and close[1] > close[2]) bounceDn = bounceMode == "Reclaim 5-DMA (strict)" ? xDnBasis : bounceMode == "Reclaim 1σ band" ? ta.crossunder(close, u10) : (close < close[1] and close[1] < close[2]) contBrkOK = contEntry != "Reject at the 5-DMA (location)" contRejOK = contEntry != "Break of leg low/high (confirm)" // ---- SHORT: weakness -> strength (lower high) -> BREAK THE WEAKNESS LOW var int sSt = 0 var float sRefHi = na // swing high before the drop (void level) var float sWkLo = na // low of the weakness leg <- the level to break var float sBncHi = na // high of the bounce (lower-high test) var bool sTag = false // bounce tagged the 5-DMA (for the location entry) var int sBar = 0 bool shortSig = false if sSt == 0 and xDn1s // weakness impulse sSt := 1 sRefHi := swingHi[1] sWkLo := low sBncHi := na sBar := bar_index else if sSt == 1 sWkLo := math.min(nz(sWkLo, low), low) // extend the leg low if bar_index - sBar > phaseMax sSt := 0 else if bounceUp // strength: the counter-move sSt := 2 sBncHi := high sTag := high >= basis sBar := bar_index else if sSt == 2 sBncHi := math.max(nz(sBncHi, high), high) if high >= basis sTag := true float lvl = contMode == "Session LOD / HOD" ? sessLo[1] : contMode == "Prior day L / H" ? pdl : contMode == "0.5σ band (old)" ? l05 : sWkLo bool lhOK = not useLHLL or sBncHi <= sRefHi if close > nz(sRefHi, close) // new high -> real uptrend, void sSt := 0 else if bar_index - sBar > phaseMax sSt := 0 else if contBrkOK and not na(lvl) and close < lvl and close[1] >= lvl and lhOK shortSig := true sSt := 0 else if contRejOK and sTag and close < basis and (high >= basis or close[1] >= basis) and lhOK shortSig := true // failed retest of the mean -> enter AT the 5-DMA sSt := 0 // ---- LONG: strength -> dip (higher low) -> BREAK THE STRENGTH HIGH var int lSt = 0 var float lRefLo = na // swing low before the push (void level) var float lStrHi = na // high of the strength leg <- the level to break var float lDipLo = na // low of the dip (higher-low test) var bool lTag = false // dip tagged the 5-DMA (for the location entry) var int lBar = 0 bool longSig = false if lSt == 0 and xUp1s // strength impulse lSt := 1 lRefLo := swingLo[1] lStrHi := high lDipLo := na lBar := bar_index else if lSt == 1 lStrHi := math.max(nz(lStrHi, high), high) // extend the leg high if bar_index - lBar > phaseMax lSt := 0 else if bounceDn // dip: the counter-move lSt := 2 lDipLo := low lTag := low <= basis lBar := bar_index else if lSt == 2 lDipLo := math.min(nz(lDipLo, low), low) if low <= basis lTag := true float lvl = contMode == "Session LOD / HOD" ? sessHi[1] : contMode == "Prior day L / H" ? pdh : contMode == "0.5σ band (old)" ? u05 : lStrHi bool hlOK = not useLHLL or lDipLo >= lRefLo if close < nz(lRefLo, close) // new low -> real downtrend, void lSt := 0 else if bar_index - lBar > phaseMax lSt := 0 else if contBrkOK and not na(lvl) and close > lvl and close[1] <= lvl and hlOK longSig := true lSt := 0 else if contRejOK and lTag and close > basis and (low <= basis or close[1] <= basis) and hlOK longSig := true // held retest of the mean -> enter AT the 5-DMA lSt := 0 // live trigger levels (for the arming labels) sLvlNow = contMode == "Session LOD / HOD" ? sessLo[1] : contMode == "Prior day L / H" ? pdl : contMode == "0.5σ band (old)" ? l05 : sWkLo lLvlNow = contMode == "Session LOD / HOD" ? sessHi[1] : contMode == "Prior day L / H" ? pdh : contMode == "0.5σ band (old)" ? u05 : lStrHi // structural trend targets: the trailing N-day extremes (prior completed days, // via the daily feed — exact regardless of the chart session) p5Hi = request.security(syminfo.tickerid, "1D", ta.highest(high, dmaDays)[1], lookahead = barmerge.lookahead_off) p5Lo = request.security(syminfo.tickerid, "1D", ta.lowest(low, dmaDays)[1], lookahead = barmerge.lookahead_off) // backside target: nearest valid objective on the profit side (na -> 2R fallback downstream) f_tgtL() => tgtMode == "Session VWAP" ? vwap1 : tgtMode == "5-DMA (mean)" ? basis : (vwap1 > close and basis > close ? math.min(vwap1, basis) : vwap1 > close ? vwap1 : basis > close ? basis : na) f_tgtS() => tgtMode == "Session VWAP" ? vwap1 : tgtMode == "5-DMA (mean)" ? basis : (vwap1 < close and basis < close ? math.max(vwap1, basis) : vwap1 < close ? vwap1 : basis < close ? basis : na) // --------------------------------------------------------------------------- // TRADE STATE ENGINE — one position at a time // Order matters: resolve an open trade FIRST so its slot can free up on the // same bar, THEN evaluate new entries against the updated state. // --------------------------------------------------------------------------- atrV = ta.atr(atrLen) // v4.2 — the trend rail: what a pull-in must reach and what a flush must // reclaim (Play 1). max() so early-day (rail under VWAP) degrades to v4.1. vpRail = not vwapBasisOn or vpRefMode == "Session VWAP only (v4.1)" ? vwap1 : vpRefMode == "Fast MA (50-min)" ? fastMA : math.max(vwap1, fastMA) trailRef = vwapBasisOn and vpRefMode != "Session VWAP only (v4.1)" ? fastMA : basis // higher-trend reference (slow enough that the extension can't drag it) slowLen = math.max(2, math.min(4999, regDays * apxBPD)) // simple int (ta.sma); approximate day-length slowMA = ta.sma(close, slowLen) trendDnBig = close < slowMA and slowMA < slowMA[barsPerDay] trendUpBig = close > slowMA and slowMA > slowMA[barsPerDay] regOKlong = not useRegGate or not trendDnBig regOKshort = not useRegGate or not trendUpBig // --- PLAY 1: VWAP pull-in long. reclaim -> ride -> pull IN and HOLD -> break var int vlSt = 0 var float vlLo = na // the hold low = the structure stop var float vlFar = 0.0 // farthest the ride got from VWAP — the LEG var float vlBx = na // consolidation high = the trigger var int vlBar = 0 var int vlCnt = 0 bool vwapSigL = false if vlSt == 0 and ta.crossover(close, vwap1) vlSt := 1 vlCnt := 0 vlFar := 0.0 if vlSt == 1 vlCnt += 1 vlFar := math.max(vlFar, high - vwap1) if close < vwap1 - vpFail * atrV vlSt := 0 else if vlCnt >= vpMinAbove and vlFar >= vpLeg * atrV and low <= vpRail + vpTol * atrV vlSt := 2 vlLo := low vlBx := high vlBar := bar_index else if vlSt == 2 bool boxOK = vpTrigger != "Undercut & reclaim (fash-late)" bool flshOK = vpTrigger != "Box-high break (confirm)" if close < vwap1 - vpFail * atrV vlSt := 0 else if bar_index - vlBar > phaseMax vlSt := 0 else if boxOK and close > vlBx vwapSigL := true vlSt := 1 vlCnt := vpMinAbove else if flshOK and low < vlLo and close >= vpRail vlLo := low // the flush low = the stop anchor vwapSigL := true // failed shakeout -> enter at the low vlSt := 1 vlCnt := vpMinAbove else vlBx := math.max(vlBx, high) vlLo := math.min(vlLo, low) // (Play 1S removed per spec 2026-08-03 — the VWAP play is LONG-ONLY) var int tDir = 0 // 0 flat, 1 long, -1 short var float tEntry = na var float tStop = na var float tTgt = na var int tBarIx = 0 var string tKind = "" var float tRisk0 = na // ORIGINAL risk at entry — R is always measured against this var bool tIsBS = false // open trade is a fade (backside/base) -> preemptable by a CONT signal var int nWin = 0 var int nLoss = 0 var int nScr = 0 var string lastTxt = "-" var int coolUntil = 0 var int lossRunL = 0 var int lossRunS = 0 // per-signal EDGE stats. // idx: 0=BACKSIDE L 1=BACKSIDE S 2=BASE L 3=BASE S 4=CONT L 5=CONT S 6=EXP L 7=EXP S 8=VWAP L 9=VWAP S var int tIdx = 0 var kN = array.new_int(10, 0) var kW = array.new_int(10, 0) var kL = array.new_int(10, 0) var kR = array.new_float(10, 0.0) if newDay lossRunL := 0 lossRunS := 0 wh_no := 0 float exitPx = na string exitWhy = "" // ---- 1) resolve an open trade // PREEMPT: a continuation (trend) signal outranks an open FADE. If a // backside/base trade holds the slot when a CONT trigger fires, flatten it // at the close and let the trend entry take the slot this same bar. // (Without this, fades starve trend entries: CONT N=1 across 743 trades.) // --- stop management (runs before exit checks; stop only ever tightens) ---- if tDir != 0 and trailMode != "None (fixed stop)" if trailMode == "Breakeven after +1R" if tDir == 1 and high >= tEntry + nz(tRisk0, 0) tStop := math.max(tStop, tEntry) if tDir == -1 and low <= tEntry - nz(tRisk0, 0) tStop := math.min(tStop, tEntry) else if not tIsBS // v4.2: on the execution frame the trail rides the 50-min rail, not // the far-away session vwap; other frames keep trailing the basis if tDir == 1 tStop := math.max(tStop, trailRef - minStopATR * atrV) else tStop := math.min(tStop, trailRef + minStopATR * atrV) bool trendSigL = (sLong and longSig) or (useExpTrade and recentCoil and expUp) or (useVwapPlay and vwapSigL) bool trendSigS = (sShort and shortSig) or (useExpTrade and recentCoil and expDn) bool contFiring = trendSigL or trendSigS if tDir != 0 bool sHit = tDir == 1 ? low <= tStop : high >= tStop bool gHit = tDir == 1 ? high >= tTgt : low <= tTgt bool xHit = (bar_index - tBarIx) >= maxBars if sHit // stop checked first = worst case exitPx := tStop exitWhy := "STOP" else if gHit exitPx := tTgt exitWhy := "TARGET" else if xHit exitPx := close exitWhy := "TIME" else if tIsBS and contFiring exitPx := close exitWhy := "PREEMPT" else if not tIsBS and ((tDir == 1 and trendSigS) or (tDir == -1 and trendSigL)) exitPx := close exitWhy := "REVERSE" // opposite TREND signal exits an open trend trade; new entry takes the slot this bar else if useWaveCover and not tIsBS and ((tDir == -1 and backArmL) or (tDir == 1 and backArmS)) exitPx := close exitWhy := "WAVE5" if exitWhy != "" float risk = math.max(nz(tRisk0, math.abs(tEntry - tStop)), syminfo.mintick) float rMult = (tDir == 1 ? (exitPx - tEntry) : (tEntry - exitPx)) / risk if exitWhy == "STOP" nLoss := nLoss + 1 if tDir == 1 lossRunL := lossRunL + 1 else lossRunS := lossRunS + 1 else if exitWhy == "TARGET" nWin := nWin + 1 if tDir == 1 lossRunL := 0 else lossRunS := 0 else nScr := nScr + 1 lastTxt := tKind + " " + exitWhy + " " + str.tostring(rMult, "#.00") + "R" // ---- webhook: EXIT. Inside this block because rMult is local to it, and // rMult is measured against tRisk0 - the ORIGINAL risk - so a trailed or // breakeven stop can never flatter the recorded result. LEG_ID := LEG_ID + 1 string _x = "{" _x += "\"indicator\":\"" + eventTag + "\"," _x += "\"v\":\"vcet_" + VER + "\"," _x += "\"trade_id\":\"" + (na(TRADE_ID) ? "" : TRADE_ID) + "\"," _x += "\"leg_id\":\"" + str.tostring(LEG_ID) + "\",\"event_type\":\"EXIT\"," _x += "\"reason\":\"" + exitWhy + "\"," _x += "\"entry_type\":\"" + tKind + "\"," _x += "\"direction\":\"" + (tDir > 0 ? "LONG" : "SHORT") + "\"," _x += "\"sym\":\"" + syminfo.ticker + "\",\"tf\":\"" + timeframe.period + "\"," _x += "\"ts\":" + str.tostring(time) + ",\"ts_ny\":\"" + f_tny() + "\"," _x += "\"entry_px\":" + f_num(tEntry, "#.####") + "," _x += "\"exit_px\":" + f_num(exitPx, "#.####") + "," _x += "\"stop\":" + f_num(tStop, "#.####") + "," _x += "\"stop_1_atr\":" + f_num(tStop, "#.####") + "," _x += "\"r_multiple\":" + f_num(rMult, "#.###") + "," _x += "\"risk\":" + f_num(tRisk0, "#.####") + "," _x += "\"bars_held\":" + str.tostring(bar_index - tBarIx) + "," _x += "\"regime\":\"" + regime + "\"," _x += "\"bw_rank\":" + f_num(bwRank, "#.##") + "," _x += "\"rvol\":" + f_num(rvol, "#.##") + "," _x += "\"atr\":" + f_num(atrV, "#.####") + "," _x += "\"qty\":1.0,\"testing\":" + (test_mode ? "true" : "false") _x += "}" sendEvent(_x) if wh_json log.info("\nVCET EXIT {0}", _x) array.set(kN, tIdx, array.get(kN, tIdx) + 1) array.set(kR, tIdx, array.get(kR, tIdx) + rMult) if exitWhy == "TARGET" array.set(kW, tIdx, array.get(kW, tIdx) + 1) else if exitWhy == "STOP" array.set(kL, tIdx, array.get(kL, tIdx) + 1) if showExits label.new(bar_index, tDir == 1 ? high : low, exitWhy + " " + str.tostring(rMult, "#.00") + "R", yloc = tDir == 1 ? yloc.abovebar : yloc.belowbar, style = tDir == 1 ? label.style_label_down : label.style_label_up, color = exitWhy == "TARGET" ? color.new(#1b5e20, 15) : exitWhy == "STOP" ? color.new(#b71c1c, 15) : color.new(color.gray, 25), textcolor = color.white, size = size.tiny) tDir := 0 coolUntil := bar_index + coolBars // ---- 2) gated entry signals (these replace the raw flags for labels/alerts) canOpen = (not oneAtATime or tDir == 0) and bar_index >= coolUntil okLongDir = maxLossStreak == 0 or lossRunL < maxLossStreak okShortDir = maxLossStreak == 0 or lossRunS < maxLossStreak immOK = bsEntry != "Wait for base break" // immediate 2s re-entry allowed? baseOK = bsEntry != "Immediate 2σ re-entry" // base-break entries allowed? bsShow = bsRole != "Off — hide entirely" and not (bsAutoHide and vwapBasisOn) // v4.4 switch + v4.5 per-timeframe auto-hide fireBackS = backArmS and canOpen and regOKshort and immOK and bsShow fireBackL = backArmL and canOpen and regOKlong and immOK and bsShow fireBaseS = baseBrkS and canOpen and regOKshort and baseOK and bsShow fireBaseL = baseBrkL and canOpen and regOKlong and baseOK and bsShow fireContS = sShort and shortSig and canOpen fireContL = sLong and longSig and canOpen fireExpS = useExpTrade and expDn and recentCoil and canOpen fireExpL = useExpTrade and expUp and recentCoil and canOpen fireVwpL = useVwapPlay and vwapSigL and canOpen and (not vpRegime or (regime != "EXPANSION DN" and regime != "OVEREXTENDED DN")) bsTrades = bsRole == "Entry" contWantL = fireContL and okLongDir contWantS = fireContS and okShortDir expWantL = fireExpL and okLongDir expWantS = fireExpS and okShortDir vwpWantL = fireVwpL and okLongDir trendWantL = contWantL or expWantL or vwpWantL trendWantS = contWantS or expWantS bsWantL = (fireBackL or fireBaseL) and bsTrades and okLongDir bsWantS = (fireBackS or fireBaseS) and bsTrades and okShortDir // TREND OUTRANKS FADE: a continuation/expansion in one direction overrides a // backside in the other. Two trend signals opposing = stand aside. wantLong = trendWantL or (not trendWantS and bsWantL) wantShort = trendWantS or (not trendWantL and bsWantS) // ---- 3) open exactly one position (conflicting bar = stand aside) bool openedL = false bool openedS = false // numbers for the entry labels (stashed at open so labels never read a stale trade) var float lblEntry = na var float lblStop = na var float lblTgt = na var float lblRR = na var int lblQty = 0 if canOpen and wantLong and not wantShort bool asContL = contWantL // trend entry outranks fade for kind/stop/target bool asExpL = not asContL and expWantL bool asVwpL = not asContL and not asExpL and vwpWantL float structStop = asVwpL ? math.min(nz(vlLo, low), ta.lowest(low, 3)) : (not asContL and not asExpL and fireBaseL) ? math.min(nz(baseLo, low), low) : math.min(low, ta.lowest(low, 3)) float candStop = useATRstop ? math.min(structStop, close - minStopATR * atrV) : structStop float candRisk = math.max(close - candStop, syminfo.mintick) if not useStopCap or candRisk <= maxStopATR * atrV tDir := 1 tEntry := close tStop := candStop float baseT = (asContL or asExpL or asVwpL) ? (trendTgtMode == "Fixed R" ? close + trendRR * candRisk : trendTgtMode == "Prior 5-day low/high (structure)" ? p5Hi : u20) : f_tgtL() tTgt := not na(baseT) and baseT > close + candRisk * 0.5 ? baseT : close + trendRR * candRisk tBarIx := bar_index tRisk0 := candRisk tKind := asContL ? "CONT L" : asExpL ? "EXP L" : asVwpL ? "VWAP L" : fireBaseL ? "BASE BRK L" : "BACKSIDE L" tIdx := asContL ? 4 : asExpL ? 6 : asVwpL ? 8 : fireBaseL ? 2 : 0 tIsBS := not (asContL or asExpL or asVwpL) openedL := true lblEntry := tEntry lblStop := tStop lblTgt := tTgt lblRR := (tTgt - tEntry) / math.max(tEntry - tStop, syminfo.mintick) lblQty := math.max(0, math.floor(riskDollars / math.max(tEntry - tStop, syminfo.mintick))) if canOpen and wantShort and not wantLong bool asContS = contWantS // trend entry outranks fade for kind/stop/target bool asExpS = not asContS and expWantS float structStop = (not asContS and not asExpS and fireBaseS) ? math.max(nz(baseHi, high), high) : math.max(high, ta.highest(high, 3)) float candStop = useATRstop ? math.max(structStop, close + minStopATR * atrV) : structStop float candRisk = math.max(candStop - close, syminfo.mintick) if not useStopCap or candRisk <= maxStopATR * atrV tDir := -1 tEntry := close tStop := candStop float baseT = (asContS or asExpS) ? (trendTgtMode == "Fixed R" ? close - trendRR * candRisk : trendTgtMode == "Prior 5-day low/high (structure)" ? p5Lo : l20) : f_tgtS() tTgt := not na(baseT) and baseT < close - candRisk * 0.5 ? baseT : close - trendRR * candRisk tBarIx := bar_index tRisk0 := candRisk tKind := asContS ? "CONT S" : asExpS ? "EXP S" : fireBaseS ? "BASE BRK S" : "BACKSIDE S" tIdx := asContS ? 5 : asExpS ? 7 : fireBaseS ? 3 : 1 tIsBS := not (asContS or asExpS) openedS := true lblEntry := tEntry lblStop := tStop lblTgt := tTgt lblRR := (tEntry - tTgt) / math.max(tStop - tEntry, syminfo.mintick) lblQty := math.max(0, math.floor(riskDollars / math.max(tStop - tEntry, syminfo.mintick))) // In WARNING-ONLY mode no trade opens, but the labels should still show what // the trade WOULD be — so compute the candidates for the label alone. if not (openedL or openedS) and not (not bsTrades and (fireBackL or fireBackS or fireBaseL or fireBaseS)) lblEntry := na lblStop := na lblTgt := na lblRR := na lblQty := 0 if not bsTrades if fireBackL or fireBaseL float wStopL = fireBaseL ? math.min(nz(baseLo, low), low) : math.min(low, ta.lowest(low, 3)) wStopL := useATRstop ? math.min(wStopL, close - minStopATR * atrV) : wStopL float wRiskL = math.max(close - wStopL, syminfo.mintick) float wTgtL = f_tgtL() wTgtL := not na(wTgtL) and wTgtL > close + wRiskL * 0.5 ? wTgtL : close + trendRR * wRiskL lblEntry := close lblStop := wStopL lblTgt := wTgtL lblRR := (wTgtL - close) / wRiskL lblQty := math.max(0, math.floor(riskDollars / wRiskL)) if fireBackS or fireBaseS float wStopS = fireBaseS ? math.max(nz(baseHi, high), high) : math.max(high, ta.highest(high, 3)) wStopS := useATRstop ? math.max(wStopS, close + minStopATR * atrV) : wStopS float wRiskS = math.max(wStopS - close, syminfo.mintick) float wTgtS = f_tgtS() wTgtS := not na(wTgtS) and wTgtS < close - wRiskS * 0.5 ? wTgtS : close - trendRR * wRiskS lblEntry := close lblStop := wStopS lblTgt := wTgtS lblRR := (close - wTgtS) / wRiskS lblQty := math.max(0, math.floor(riskDollars / wRiskS)) // ---- webhook: ENTRY. Placed after both open blocks and after the label // numbers are stashed, so every field reflects the position actually taken. if openedL or openedS wh_no := wh_no + 1 TRADE_ID := trade_prefix + "-" + syminfo.ticker + "-vcet-" + str.format_time(time, "yyyy-MM-dd-HH:mm:ss", wh_tz) + "-" + str.tostring(wh_no) LEG_ID := 1 string _e = "{" _e += "\"indicator\":\"" + eventTag + "\"," _e += "\"v\":\"vcet_" + VER + "\"," _e += "\"trade_id\":\"" + TRADE_ID + "\"," _e += "\"leg_id\":\"1\",\"event_type\":\"ENTRY\"," _e += "\"entry_type\":\"" + tKind + "\"," _e += "\"direction\":\"" + (tDir > 0 ? "LONG" : "SHORT") + "\"," _e += "\"sym\":\"" + syminfo.ticker + "\",\"tf\":\"" + timeframe.period + "\"," _e += "\"ts\":" + str.tostring(time) + ",\"ts_ny\":\"" + f_tny() + "\"," _e += "\"entry_px\":" + f_num(tEntry, "#.####") + "," _e += "\"stop\":" + f_num(tStop, "#.####") + "," _e += "\"stop_1_atr\":" + f_num(tStop, "#.####") + "," _e += "\"target\":" + f_num(tTgt, "#.####") + "," _e += "\"target_1_5_atr\":" + f_num(tTgt, "#.####") + "," _e += "\"risk\":" + f_num(tRisk0, "#.####") + "," _e += "\"shares\":" + str.tostring(lblQty) + "," _e += "\"rr\":" + f_num(lblRR, "#.##") + "," _e += "\"basis_name\":\"" + maName + "\"," _e += "\"basis\":" + f_num(basis, "#.####") + "," _e += "\"regime\":\"" + regime + "\"," _e += "\"comp_kind\":\"" + compKind + "\"," _e += "\"bw_rank\":" + f_num(bwRank, "#.##") + "," _e += "\"rvol\":" + f_num(rvol, "#.##") + "," _e += "\"dist_sd\":" + f_num(distSD, "#.##") + "," _e += "\"ma_slope\":\"" + slopeTxt + "\"," _e += "\"atr\":" + f_num(atrV, "#.####") + "," _e += "\"vwap\":" + f_num(vwap1, "#.####") + "," _e += "\"u20\":" + f_num(u20, "#.####") + ",\"l20\":" + f_num(l20, "#.####") + "," _e += "\"qty\":1.0,\"testing\":" + (test_mode ? "true" : "false") _e += "}" sendEvent(_e) if wh_json log.info("\nVCET ENTRY {0}", _e) // one-line E/S/T string for entry labels f_est() => na(lblEntry) ? "" : "\nE " + str.tostring(lblEntry, format.mintick) + " S " + str.tostring(lblStop, format.mintick) + " T " + str.tostring(lblTgt, format.mintick) + " (" + str.tostring(lblRR, "#.0") + "R) " + str.tostring(lblQty) + " sh" // --------------------------------------------------------------------------- // ANNOTATIONS // --------------------------------------------------------------------------- bgcolor(shadeC and isComp ? color.new(color.orange, 90) : na, title = "Compression") bgcolor(regTint and not fFull and not isComp ? (outUp or outDn ? color.new(#c2185b, 94) : close > u10 ? color.new(#2e7d32, 96) : close < l10 ? color.new(#b71c1c, 96) : na) : na, title = "Regime tint") // --- REGIME-CHANGE markers: the bar where the table's Regime row flipped ---- if showShift and regime != regime[1] bool upish = regime == "EXPANSION UP" or regime == "OVEREXTENDED UP" color shC = regime == "COMPRESSION" ? #b26a00 : regime == "EXPANSION UP" ? #1b5e20 : regime == "EXPANSION DN" ? #b71c1c : (regime == "OVEREXTENDED UP" or regime == "OVEREXTENDED DN") ? #c2185b : #5b6470 string shTxt = regime == "BALANCE" ? ("◂ " + regime[1] + " ended") : ("▸ " + regime) label.new(bar_index, upish ? high : low, shTxt, yloc = upish ? yloc.abovebar : yloc.belowbar, style = label.style_none, textcolor = shC, size = size.tiny) if compStart and not atExtreme label.new(bar_index, low, "COMPRESSION — COIL\nbreaks either way: PDH / VWAP", yloc = yloc.belowbar, style = label.style_label_up, color = color.new(color.orange, 10), textcolor = color.white, size = size.small) if baseNew and bsShow label.new(bar_index, baseDir == -1 ? low : high, "BASE forming (" + (baseDir == -1 ? "low" : "high") + " extreme)\nwait for the range break", yloc = baseDir == -1 ? yloc.belowbar : yloc.abovebar, style = baseDir == -1 ? label.style_label_up : label.style_label_down, color = color.new(#6a1b9a, 15), textcolor = color.white, size = size.small) if fireBaseL and ((openedL and not contWantL) or not bsTrades) label.new(bar_index, low, "BASE BREAK long\nhandle break -> " + maName + f_est(), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(#1b5e20, 0), textcolor = color.white, size = size.normal) if fireBaseS and ((openedS and not contWantS) or not bsTrades) label.new(bar_index, high, "BASE BREAK short\nhandle break -> " + maName + f_est(), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(#8e0038, 0), textcolor = color.white, size = size.normal) bool expTrdL = openedL and tKind == "EXP L" bool expTrdS = openedS and tKind == "EXP S" if expUp label.new(bar_index, high, expTrdL ? "EXPANSION LONG — coil break\ntrend entry" + f_est() : "EXPANSION UP\n1s break" + (volConf ? " +vol" : " (low vol)"), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(color.green, expTrdL ? 0 : 10), textcolor = color.white, size = expTrdL ? size.normal : size.small) if expDn label.new(bar_index, low, expTrdS ? "EXPANSION SHORT — coil break\ntrend entry" + f_est() : "EXPANSION DN\n1s break" + (volConf ? " +vol" : " (low vol)"), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(color.red, expTrdS ? 0 : 10), textcolor = color.white, size = expTrdS ? size.normal : size.small) if fireBackS and ((openedS and not contWantS) or not bsTrades) label.new(bar_index, high, (bsTrades ? "BACKSIDE short\ncover VWAP -> " + maName + "\n(MA " : "EXTENDED UP — WARNING\nno chase / no adds\n(MA ") + slopeTxt + ": FLAT=revert, FALLING=runner)" + f_est(), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(#c2185b, 5), textcolor = color.white, size = size.small) if fireBackL and ((openedL and not contWantL) or not bsTrades) label.new(bar_index, low, (bsTrades ? "BACKSIDE long\ncover VWAP -> " + maName + "\n(MA " : "EXTENDED DN — WARNING\nno chase / no adds\n(MA ") + slopeTxt + ": FLAT=revert, RISING=runner)" + f_est(), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(#00897b, 5), textcolor = color.white, size = size.small) if pdhBreak label.new(bar_index, low, "PDH break\nVWAP play live", yloc = yloc.belowbar, style = label.style_label_up, color = color.new(color.blue, 10), textcolor = color.white, size = size.small) // continuation setups if sShort and sSt == 2 and sSt[1] == 1 and tDir == 0 label.new(bar_index, high, "short armed\nbreak < " + (na(sLvlNow) ? "-" : str.tostring(sLvlNow, format.mintick)), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(color.teal, 30), textcolor = color.white, size = size.tiny) if fireContS and openedS label.new(bar_index, high, "SHORT\nweakness after strength" + f_est(), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(#8e0038, 0), textcolor = color.white, size = size.normal) if sLong and lSt == 2 and lSt[1] == 1 and tDir == 0 label.new(bar_index, low, "long armed\nbreak > " + (na(lLvlNow) ? "-" : str.tostring(lLvlNow, format.mintick)), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(color.teal, 30), textcolor = color.white, size = size.tiny) if fireVwpL and openedL and tKind == "VWAP L" label.new(bar_index, low, "VWAP PULL-IN long (Play 1)\nheld the line -> box break" + f_est(), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(#4527a0, 0), textcolor = color.white, size = size.normal) if fireContL and openedL label.new(bar_index, low, "LONG\nstrength after the dip" + f_est(), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(#1b5e20, 0), textcolor = color.white, size = size.normal) // --------------------------------------------------------------------------- // STATUS TABLE // --------------------------------------------------------------------------- var table t = table.new(position.top_right, 2, 12, frame_color = color.gray, frame_width = 1, border_color = color.new(color.gray, 60), border_width = 1) if sTbl and barstate.islast regCol = isComp ? color.orange : (outUp or outDn) ? #c2185b : close > u10 ? color.new(color.green, 20) : close < l10 ? color.new(color.red, 20) : color.gray ceState = isComp ? ("COMPRESSION — " + compKind) : ((close > u10 or close < l10) and bwRise) ? "EXPANSION" : "-" slopeCol = slopeTxt == "RISING" ? color.new(color.green, 40) : slopeTxt == "FALLING" ? color.new(color.red, 40) : color.new(color.gray, 40) warnTxt = (close > u20) ? "EXTENDED UP — no chase / no adds" : (close < l20) ? "EXTENDED DN — no chase / no adds" : "" trTxt = tDir != 0 ? (tDir == 1 ? "LONG " : "SHORT ") + tKind : bsShow and not bsTrades and warnTxt != "" ? warnTxt : (not okLongDir and not okShortDir) ? "PAUSED both" : not okLongDir ? "PAUSED longs" : not okShortDir ? "PAUSED shorts" : "FLAT" trCol = tDir == 0 ? (bsShow and not bsTrades and warnTxt != "" ? color.new(#e65100, 15) : (not okLongDir or not okShortDir) ? color.new(#e65100, 25) : color.new(color.gray, 40)) : tDir == 1 ? color.new(#1b5e20, 25) : color.new(#8e0038, 25) stTxt = tDir == 0 ? "-" : str.tostring(tStop, format.mintick) + " / " + str.tostring(tTgt, format.mintick) float liveRisk = tDir == 0 ? na : nz(tRisk0, math.abs(tEntry - tStop)) enTxt = tDir == 0 ? "-" : str.tostring(tEntry, format.mintick) + " x " + str.tostring(math.max(0, math.floor(riskDollars / math.max(liveRisk, syminfo.mintick)))) + " sh" rrTxt = tDir == 0 ? "-" : str.tostring(tDir == 1 ? (tTgt - tEntry) / math.max(liveRisk, syminfo.mintick) : (tEntry - tTgt) / math.max(liveRisk, syminfo.mintick), "#.0") + "R" table.cell(t, 0, 0, maName + " / VCET " + VER, text_color = color.white, bgcolor = color.new(color.black, 20), text_size = size.small) table.cell(t, 1, 0, vwapBasisOn ? "session σ" : str.tostring(len) + " bars", text_color = color.white, bgcolor = color.new(color.black, 20), text_size = size.small) table.cell(t, 0, 1, "BW %ile", text_size = size.small) table.cell(t, 1, 1, str.tostring(bwRank, "#.0"), text_size = size.small) table.cell(t, 0, 2, "RVOL", text_size = size.small) table.cell(t, 1, 2, na(rvol) ? "-" : str.tostring(rvol, "#.00") + (volConf ? " ✓" : ""), text_size = size.small) table.cell(t, 0, 3, "C / E", text_size = size.small) table.cell(t, 1, 3, ceState, text_size = size.small) table.cell(t, 0, 4, maName + " slope", text_size = size.small) table.cell(t, 1, 4, slopeTxt, bgcolor = slopeCol, text_size = size.small) table.cell(t, 0, 5, "Regime", text_size = size.small) table.cell(t, 1, 5, regime, text_color = color.white, bgcolor = color.new(regCol, 20), text_size = size.small) table.cell(t, 0, 6, "Flag", text_size = size.small) table.cell(t, 1, 6, flag, text_size = size.small) table.cell(t, 0, 7, "Trade", text_size = size.small) table.cell(t, 1, 7, trTxt, text_color = color.white, bgcolor = trCol, text_size = size.small) table.cell(t, 0, 8, "Entry x Qty", text_size = size.small) table.cell(t, 1, 8, enTxt, text_size = size.small) table.cell(t, 0, 9, "Stop / Tgt", text_size = size.small) table.cell(t, 1, 9, stTxt, text_size = size.small) table.cell(t, 0, 10, "R : R", text_size = size.small) table.cell(t, 1, 10, rrTxt, text_size = size.small) table.cell(t, 0, 11, "Last (W-L-S)", text_size = size.small) table.cell(t, 1, 11, lastTxt + " (" + str.tostring(nWin) + "-" + str.tostring(nLoss) + "-" + str.tostring(nScr) + ")", text_size = size.small) // --------------------------------------------------------------------------- // EDGE TABLE — expectancy per signal type. This is how you tell which setup // actually works. ExpR = total R / trades. Positive with a meaningful N = edge. // --------------------------------------------------------------------------- var table st = table.new(position.bottom_right, 6, 12, frame_color = color.gray, frame_width = 1, border_color = color.new(color.gray, 60), border_width = 1) if sStats and barstate.islast hdrBg = color.new(color.black, 15) table.cell(st, 0, 0, "SIGNAL", text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 1, 0, "N", text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 2, 0, "W-L", text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 3, 0, "Win%", text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 4, 0, "TotR", text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 5, 0, "ExpR", text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) names = array.from("BACKSIDE L", "BACKSIDE S", "BASE BRK L", "BASE BRK S", "CONT L", "CONT S", "EXP L", "EXP S", "VWAP L", "—") float allR = 0.0 int allN = 0 for i = 0 to 9 int n = array.get(kN, i) int w = array.get(kW, i) int l = array.get(kL, i) float tr = array.get(kR, i) float ex = n > 0 ? tr / n : 0.0 allR := allR + tr allN := allN + n exCol = n < 10 ? color.new(color.gray, 55) : ex > 0.05 ? color.new(#1b5e20, 25) : ex < -0.05 ? color.new(#b71c1c, 25) : color.new(color.gray, 45) table.cell(st, 0, i + 1, array.get(names, i), text_size = size.tiny) table.cell(st, 1, i + 1, str.tostring(n), text_size = size.tiny) table.cell(st, 2, i + 1, str.tostring(w) + "-" + str.tostring(l), text_size = size.tiny) table.cell(st, 3, i + 1, n > 0 ? str.tostring(100.0 * w / n, "#") + "%" : "-", text_size = size.tiny) table.cell(st, 4, i + 1, str.tostring(tr, "#.0"), text_size = size.tiny) table.cell(st, 5, i + 1, n > 0 ? str.tostring(ex, "#.00") : "-", bgcolor = exCol, text_color = color.white, text_size = size.tiny) totCol = allN < 20 ? color.new(color.gray, 55) : allR > 0 ? color.new(#1b5e20, 25) : color.new(#b71c1c, 25) table.cell(st, 0, 11, "ALL", text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 1, 11, str.tostring(allN), text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 2, 11, "", bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 3, 11, "", bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 4, 11, str.tostring(allR, "#.0"), text_color = color.white, bgcolor = hdrBg, text_size = size.tiny) table.cell(st, 5, 11, allN > 0 ? str.tostring(allR / allN, "#.00") : "-", text_color = color.white, bgcolor = totCol, text_size = size.tiny) // --------------------------------------------------------------------------- // ALERTS // --------------------------------------------------------------------------- // v4.6: TRADE data now goes out through alert() above (ENTRY / EXIT with the // full payload) because alertcondition() can only send a fixed string. These // alertcondition lines are left intact - they still drive sound/popup alerts // and cost nothing. // --------------------------------------------------------------------------- alertcondition(compStart, "Compression start", "5DMA bands compressing") alertcondition(baseNew, "Base forming", "Compression at an extreme — base/handle forming") alertcondition(fireBaseL, "Base break long", "Handle break up — long into the 5DMA") alertcondition(fireBaseS, "Base break short", "Handle break down — short into the 5DMA") alertcondition(expUp, "Expansion up", "Break of +1s (5DMA)") alertcondition(expDn, "Expansion down", "Break of -1s (5DMA)") alertcondition(outUp, "Overextended up", "Close > +2s — no new longs") alertcondition(outDn, "Overextended down", "Close < -2s — no new shorts") alertcondition(fireBackS, "Backside short", "Re-entry < +2s — short into VWAP") alertcondition(fireBackL, "Backside long", "Re-entry > -2s — long into VWAP") alertcondition(fireContS, "Short continuation", "Weakness after strength — short trigger") alertcondition(fireContL, "Long continuation", "Strength after the dip — long trigger") alertcondition(fireExpS, "Expansion short", "Coil break down — trend short entry") alertcondition(fireExpL, "Expansion long", "Coil break up — trend long entry") alertcondition(fireVwpL, "VWAP pull-in long", "Play 1 — held session VWAP, box break up") alertcondition(exitWhy != "", "Trade exit", "Position resolved (stop / target / timeout)")