本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PhenLabs
//@version=6
indicator(
title = "Fair Value Gap Mitigation & Target Zones [PhenLabs]",
shorttitle = "FVGM [PhenLabs]",
overlay = true,
max_boxes_count = 300,
max_lines_count = 400,
max_labels_count = 400
)
// Explicit single-identifier history reservations for stored timestamps & pivots
max_bars_back(time, 64)
max_bars_back(high, 64)
max_bars_back(low, 64)
max_bars_back(close, 64)
max_bars_back(volume, 64)
// ═══════════════════════════════════════════════════════════════════════════
// 1. ENUMS & INPUTS
// ═══════════════════════════════════════════════════════════════════════════
enum ProfileMode
auto = "Auto-Optimize (Best Chart History)"
bal = "Balanced (50% CE · 58% Def)"
cons = "Conservative (50% CE · 65% Def)"
aggr = "Aggressive (Edge Reclaim · 50% Def)"
scalp = "Scalp Fast (Quick Test · 54% Def)"
swing = "Swing Wide (Deep Imbalance · 56% Def)"
vol = "Volume Climax (50% CE · 1.25x Vol)"
enum TableSz
tiny = "Tiny"
small = "Small"
normal = "Normal"
large = "Large"
const string G1 = "1. FVG Detection & Auto-Optimizer"
const string G2 = "2. Entry, Stop Loss & TP1–TP3 Targets"
const string G3 = "3. Visuals & Declutter"
const string G4 = "4. Alerts"
ProfileMode profIn = input.enum(ProfileMode.auto, "Filter Profile", group = G1, tooltip = "Auto-Optimize runs all 6 built-in FVG mitigation profiles in parallel on separate trade ledgers across the full chart history and displays the profile with the strongest verified performance (positive Net R, win rate and expectancy). Note: the winner is picked in hindsight — check the 'Auto Live Record' row on the dashboard for the walk-forward result.")
float minGapAtr = input.float(0.25, "Min Gap Size (× ATR)", minval = 0.05, maxval = 2.50, step = 0.05, group = G1, tooltip = "Minimum 3-candle Fair Value Gap height measured in ATR(14) units. Raise this to filter out micro-gaps and keep only high-displacement imbalances.")
int zoneAgeIn = input.int(120, "Zone Lifetime (bars)", minval = 20, maxval = 600, group = G1, tooltip = "Base number of bars an unmitigated Fair Value Gap remains active before expiring. Scalp Fast scales this by 0.5× and Swing Wide scales it by 1.6×.")
int maxZones = input.int(3, "Max Live Zones Per Side", minval = 1, maxval = 6, group = G1, tooltip = "Maximum number of unmitigated Bullish and Bearish FVG zones displayed simultaneously.")
int trendLen = input.int(50, "Trend Filter EMA Length", minval = 10, maxval = 200, group = G1, tooltip = "EMA trend filter length used alongside Kaufman Trend Efficiency to keep mitigation entries aligned with directional flow.")
bool useHtf = input.bool(false, "HTF Bias Filter", group = G1, inline = "htf")
string htfTf = input.timeframe("60", "", group = G1, inline = "htf")
int htfLen = input.int(50, "EMA", minval = 5, maxval = 400, group = G1, inline = "htf", tooltip = "Only take longs when the last CLOSED higher-timeframe bar is above its EMA, and shorts when below. Uses the prior HTF bar, so it does not repaint. Ignored if the HTF is not higher than the chart timeframe.")
float tp1In = input.float(1.0, "Targets: TP1 / TP2 / TP3 (R)", minval = 0.5, step = 0.25, group = G2, inline = "tp")
float tp2In = input.float(2.0, "", minval = 1.0, step = 0.25, group = G2, inline = "tp")
float tp3In = input.float(3.0, "", minval = 1.5, step = 0.25, group = G2, inline = "tp", tooltip = "Risk-reward target ladder in multiples of initial risk (default 1.0R, 2.0R, 3.0R).")
bool useBE = input.bool(true, "Move Stop to Breakeven After TP1", group = G2, tooltip = "When enabled, once TP1 is reached on a confirmed bar, the active Stop Loss ratchets to the Entry price (Breakeven) for remaining targets.")
bool useMagnet = input.bool(true, "Snap Targets to Opposing Gaps / Swings", group = G2, tooltip = "When enabled, if an opposing unmitigated FVG boundary or untaken structural swing high/low sits between 1.4R and 3.8R, TP2 or TP3 snaps to that liquidity magnet.")
int timeoutBars = input.int(60, "Plan Timeout (bars)", minval = 10, maxval = 240, group = G2, tooltip = "Maximum bars an open trade plan remains active before expiring.")
int scale1In = input.int(33, "Scale-Out %: TP1 / TP2", minval = 0, maxval = 100, group = G2, inline = "sc")
int scale2In = input.int(33, "", minval = 0, maxval = 100, group = G2, inline = "sc", tooltip = "Percent of the position closed at TP1 and TP2. The remainder exits at TP3, the stop, or the timeout. All stats are computed from these partials, so a TP1-then-breakeven trade is booked as its real blended R instead of a full TP1 win.")
float costR = input.float(0.05, "Round-Trip Cost (R)", minval = 0.0, maxval = 0.5, step = 0.01, group = G2, tooltip = "Commission + slippage deducted from every closed trade, in R. 0.05R is a reasonable default for liquid futures/crypto on intraday timeframes.")
float riskCash = input.float(0.0, "Risk Per Trade ($, 0 = off)", minval = 0.0, step = 25.0, group = G2, tooltip = "When set, the dashboard shows the position size that risks this amount at the plan's stop (uses syminfo.pointvalue).")
bool showZones = input.bool(true, "Show Unmitigated FVG Zones", group = G3)
bool showCE = input.bool(true, "Show 50% CE Midline", group = G3, active = showZones)
bool showZoneText = input.bool(false, "Show Zone Labels", group = G3, active = showZones)
bool fadeZones = input.bool(true, "Fade Zones With Age", group = G3, active = showZones)
bool showEntrySL = input.bool(true, "Show Entry & Stop Zone", group = G3)
bool showTPs = input.bool(true, "Show TP1 / TP2 / TP3 Ladder", group = G3)
bool showPastPlans = input.bool(false, "Keep Historical Trade Plans (Last 3)", group = G3, tooltip = "Off by default so only the latest focal trade plan ladder and its mitigated FVG origin stay on price. Enable to keep the last 3 trade ladders visible.")
bool showBadges = input.bool(true, "Show Signal Callout Badges", group = G3)
bool showBg = input.bool(false, "Show Trend Background Tint", group = G3)
bool showDash = input.bool(true, "Show Summary Dashboard", group = G3)
TableSz tblSzIn = input.enum(TableSz.small, "Table Size", group = G3, active = showDash)
color bullCol = input.color(#00E6A8, "Bullish / Bearish Accent Colors", group = G3, inline = "col")
color bearCol = input.color(#FF3B69, "", group = G3, inline = "col")
bool dynAlerts = input.bool(true, "Detailed alert() Payloads (JSON)", group = G4, tooltip = "Create the alert with condition 'Any alert() function call' to receive entry / SL / TP / exit payloads with prices, R-result and profile. Fires once per bar close. Good for webhooks and bots.")
// Enforce strictly ascending TP1 < TP2 < TP3
float tp1R = tp1In
float tp2R = math.max(tp2In, tp1R + 0.25)
float tp3R = math.max(tp3In, tp2R + 0.25)
// Scale-out weights (always sum to 1)
float w1 = scale1In / 100.0
float w2 = math.min(scale2In / 100.0, 1.0 - w1)
float w3 = math.max(0.0, 1.0 - w1 - w2)
// ═══════════════════════════════════════════════════════════════════════════
// 2. USER-DEFINED TYPES (UDTs)
// ═══════════════════════════════════════════════════════════════════════════
type Zone
int dir
float top
float bot
float ce
int birthBar
int leftTime
float effort
bool touched = false
int lastTouchBar = -1
bool dead = false
int firedMask = 0
box bx
line ceLn
label tagLb
type Plan
int prof
int dir
float entry
float sl
float curSL
float tp1
float tp2
float tp3
float r1
float r2
float r3
float risk
int entryBar
int entryTime
int exitBar
int exitTime
float exitPrice
float sigPrice
float score
int fvgLeftTime
float fvgTop
float fvgBot
float fvgCe
bool mag2 = false
bool mag3 = false
bool hit1 = false
bool hit2 = false
bool hit3 = false
bool slHit = false
bool beHit = false
bool isOpen = true
bool wf = false
float resultR = 0.0
string outcome = "OPEN"
f_px(float v) => str.tostring(v, format.mintick)
// Blended R of a plan given scale-out weights, the targets already hit and the exit price of the remainder
f_realR(Plan ap, float exitPx) =>
float rk = math.max(ap.risk, syminfo.mintick)
float d = ap.dir * 1.0
float done = 0.0
float acc = 0.0
if ap.hit1
acc += w1 * (ap.tp1 - ap.entry) * d / rk
done += w1
if ap.hit2
acc += w2 * (ap.tp2 - ap.entry) * d / rk
done += w2
if ap.hit3
acc += w3 * (ap.tp3 - ap.entry) * d / rk
done += w3
acc + math.max(0.0, 1.0 - done) * (exitPx - ap.entry) * d / rk - costR
// ═══════════════════════════════════════════════════════════════════════════
// 3. PROFILE DEFINITIONS (6 Parallel Engines: 0..5)
// ═══════════════════════════════════════════════════════════════════════════
f_clamp(float v, float lo, float hi) =>
math.min(math.max(v, lo), hi)
// 0: Balanced, 1: Conservative, 2: Aggressive, 3: Scalp Fast, 4: Swing Wide, 5: Volume Climax
f_name(int p) =>
switch p
0 => "Balanced (50% CE · 58% Def)"
1 => "Conservative (50% CE · 65% Def)"
2 => "Aggressive (Edge · 50% Def)"
3 => "Scalp Fast (Quick · 54% Def)"
4 => "Swing Wide (Deep · 56% Def)"
=> "Volume Climax (50% CE · 1.25x Vol)"
f_shortName(int p) =>
switch p
0 => "Balanced"
1 => "Conservative"
2 => "Aggressive"
3 => "Scalp Fast"
4 => "Swing Wide"
=> "Volume Climax"
f_json(string ev, Plan pp) =>
'{"src":"FVGM","event":"' + ev + '","side":"' + (pp.dir == 1 ? "long" : "short") +
'","ticker":"' + syminfo.tickerid + '","tf":"' + timeframe.period + '","price":' + f_px(close) +
',"entry":' + f_px(pp.entry) + ',"sl":' + f_px(pp.curSL) + ',"tp1":' + f_px(pp.tp1) + ',"tp2":' + f_px(pp.tp2) + ',"tp3":' + f_px(pp.tp3) +
',"score":' + str.tostring(pp.score, "0") + ',"outcome":"' + pp.outcome + '","r":' + str.tostring(pp.resultR, "0.00") +
',"profile":"' + f_shortName(pp.prof) + '"}'
f_dMin(int p) => p == 0 ? 0.52 : p == 1 ? 0.60 : p == 2 ? 0.44 : p == 3 ? 0.48 : p == 4 ? 0.52 : 0.54
f_scoreMin(int p) => p == 0 ? 58.0 : p == 1 ? 65.0 : p == 2 ? 50.0 : p == 3 ? 54.0 : p == 4 ? 56.0 : 60.0
f_erMin(int p) => p == 0 ? 22.0 : p == 1 ? 30.0 : p == 2 ? 15.0 : p == 3 ? 18.0 : p == 4 ? 24.0 : 22.0
f_buf(int p) => p == 0 ? 0.22 : p == 1 ? 0.28 : p == 2 ? 0.18 : p == 3 ? 0.16 : p == 4 ? 0.36 : 0.22
f_minRisk(int p) => p == 3 ? 0.35 : p == 4 ? 0.50 : 0.40
f_trend(int p) => p != 2
f_ceReq(int p) => p == 0 or p == 1 or p == 5
f_effMin(int p) => p == 0 ? 35.0 : p == 1 ? 48.0 : p == 2 ? 25.0 : p == 3 ? 30.0 : p == 4 ? 42.0 : 45.0
f_actMin(int p) => p == 5 ? 1.25 : 0.0
f_ageMult(int p) => p == 3 ? 0.5 : p == 4 ? 1.6 : 1.0
f_cooldown(int p) => p == 0 ? 5 : p == 1 ? 8 : p == 2 ? 3 : p == 3 ? 4 : p == 4 ? 8 : 6
f_bit(int p) =>
switch p
0 => 1
1 => 2
2 => 4
3 => 8
4 => 16
=> 32
f_hasFired(Zone z, int p) =>
int b = f_bit(p)
math.floor(z.firedMask / b) % 2 == 1
// Auto-Optimizer selects the profile with the strongest positive Net R & Win Rate (net of scale-outs and costs)
f_pickAuto(array<int> tr, array<int> w, array<float> nr) =>
int best = -1
float bestScore = -1e9
float bestNr = -1e9
// Pass 1: Profiles with >= 4 closed trades and positive Net R
for i = 0 to 5
int n = tr.get(i)
float net = nr.get(i)
if n >= 4 and net > 0.0
float wr = (w.get(i) * 100.0) / n
float avg = net / n
float sc = wr + avg * 22.0 + math.min(net, 40.0) * 0.45
if sc > bestScore or (sc == bestScore and net > bestNr)
best := i
bestScore := sc
bestNr := net
// Pass 2: Any profile with >= 3 closed trades ranked by combined Win Rate + Expectancy
if best == -1
for i = 0 to 5
int n = tr.get(i)
float net = nr.get(i)
if n >= 3
float wr = (w.get(i) * 100.0) / n
float avg = net / n
float sc = wr + avg * 25.0
if sc > bestScore or (sc == bestScore and net > bestNr)
best := i
bestScore := sc
bestNr := net
// Pass 3: Fallback when chart has fewer than 3 closed trades
if best == -1
for i = 0 to 5
int n = tr.get(i)
float net = nr.get(i)
if n > 0
float wr = (w.get(i) * 100.0) / n
if wr > bestScore or (wr == bestScore and net > bestNr)
best := i
bestScore := wr
bestNr := net
best == -1 ? 0 : best
// ═══════════════════════════════════════════════════════════════════════════
// 4. CORE SERIES (Computed on Every Bar)
// ═══════════════════════════════════════════════════════════════════════════
float rawAtr = ta.atr(14)
float atr = nz(rawAtr, math.max(high - low, syminfo.mintick * 10.0))
float ema = ta.ema(close, trendLen)
float emaSlope = ema - nz(ema[3], ema)
float vol = nz(volume)
float volSma = ta.sma(vol, 20)
bool volOK = not na(volSma) and volSma > 0
float trv = ta.tr(true)
float relAct = volOK ? vol / volSma : (atr > 0 ? trv / atr : 1.0)
float barRng = math.max(high - low, syminfo.mintick)
float bodyEff = math.abs(close - open) / barRng
float actN = f_clamp(relAct / 2.0, 0.0, 1.0)
// Kaufman Trend Efficiency Ratio (0-100%) over 10 bars
int erLen = 10
float netMove = math.abs(close - nz(close[erLen], close))
float pathMove = nz(ta.sma(math.abs(close - nz(close[1], close)), erLen), 0.0) * float(erLen)
float erPct = pathMove > 0 ? f_clamp((netMove / pathMove) * 100.0, 0.0, 100.0) : 0.0
float erNorm = f_clamp(erPct / 55.0, 0.0, 1.0)
float effortNow = 100.0 * (0.55 * bodyEff + 0.45 * actN)
float effortPrev = nz(effortNow[1], effortNow)
int barDur = math.max(1, nz(time_close - time, nz(time - time[1], 60000)))
int t2ago = nz(time[2], time)
float hi2 = nz(high[2], high)
float lo2 = nz(low[2], low)
float hi1 = nz(high[1], high)
float lo1 = nz(low[1], low)
float ph = ta.pivothigh(high, 5, 5)
float pl = ta.pivotlow(low, 5, 5)
// Non-repainting HTF bias (previous closed HTF bar)
bool htfOn = useHtf and timeframe.in_seconds(htfTf) > timeframe.in_seconds()
float htfEma = request.security(syminfo.tickerid, htfTf, ta.ema(close, htfLen)[1], lookahead = barmerge.lookahead_on)
float htfClose = request.security(syminfo.tickerid, htfTf, close[1], lookahead = barmerge.lookahead_on)
int htfBias = not htfOn or na(htfEma) or na(htfClose) ? 0 : htfClose > htfEma ? 1 : -1
// 5-bar crash/spike guard to prevent stepping in front of vertical liquidation cascades
float fiveBarMoveAtr = (close - nz(close[5], close)) / math.max(atr, syminfo.mintick)
bool bearCascade = fiveBarMoveAtr < -3.5 and close < open
bool bullCascade = fiveBarMoveAtr > 3.5 and close > open
bool gapBull = not na(rawAtr) and low > hi2 and (low - hi2) >= minGapAtr * atr and close[1] > open[1]
bool gapBear = not na(rawAtr) and high < lo2 and (lo2 - high) >= minGapAtr * atr and close[1] < open[1]
float dBull = f_clamp((close - low) / barRng, 0.0, 1.0)
float dBear = f_clamp((high - close) / barRng, 0.0, 1.0)
float scBull = math.round(f_clamp((0.45 * dBull + 0.30 * erNorm + 0.25 * actN) * 100.0 * (close > open ? 1.0 : 0.82), 0.0, 100.0), 0)
float scBear = math.round(f_clamp((0.45 * dBear + 0.30 * erNorm + 0.25 * actN) * 100.0 * (close < open ? 1.0 : 0.82), 0.0, 100.0), 0)
// ═══════════════════════════════════════════════════════════════════════════
// 5. DETERMINISTIC CLOSED-BAR STATE MACHINE (6 Parallel Profile Ledgers)
// ═══════════════════════════════════════════════════════════════════════════
var array<Zone> bullZ = array.new<Zone>()
var array<Zone> bearZ = array.new<Zone>()
var array<float> swingHi = array.new<float>()
var array<float> swingLo = array.new<float>()
var array<Plan> plans = array.new<Plan>()
var array<Plan> active = array.new<Plan>(6)
// Ledger index 6 = Auto walk-forward (trades actually taken by whatever profile Auto had selected at entry time)
var array<int> lgTrades = array.new<int>(7, 0)
var array<int> lgWins = array.new<int>(7, 0)
var array<int> lgLosses = array.new<int>(7, 0)
var array<int> lgTp1 = array.new<int>(6, 0)
var array<int> lgTp2 = array.new<int>(6, 0)
var array<int> lgTp3 = array.new<int>(6, 0)
var array<float> lgNetR = array.new<float>(7, 0.0)
var array<float> lgGrossW = array.new<float>(7, 0.0)
var array<float> lgGrossL = array.new<float>(7, 0.0)
var array<float> lgPeak = array.new<float>(7, 0.0)
var array<float> lgMaxDD = array.new<float>(7, 0.0)
var array<int> lastSigBar = array.new<int>(6, -999)
var float lastScore = na
Plan nullPlan = na
array<string> evMsgs = array.new<string>()
f_book(int i, float r) =>
lgTrades.set(i, lgTrades.get(i) + 1)
lgNetR.set(i, lgNetR.get(i) + r)
if r > 0
lgWins.set(i, lgWins.get(i) + 1)
lgGrossW.set(i, lgGrossW.get(i) + r)
else
lgLosses.set(i, lgLosses.get(i) + 1)
lgGrossL.set(i, lgGrossL.get(i) - r)
float eq = lgNetR.get(i)
lgPeak.set(i, math.max(lgPeak.get(i), eq))
lgMaxDD.set(i, math.max(lgMaxDD.get(i), lgPeak.get(i) - eq))
true
int profIdx = switch profIn
ProfileMode.bal => 0
ProfileMode.cons => 1
ProfileMode.aggr => 2
ProfileMode.scalp => 3
ProfileMode.swing => 4
ProfileMode.vol => 5
=> -1
int sel = profIdx >= 0 ? profIdx : f_pickAuto(lgTrades, lgWins, lgNetR)
bool evBull = false
bool evBear = false
bool evTp1 = false
bool evTp2 = false
bool evTp3 = false
bool evStop = false
bool evBE = false
bool evTime = false
bool ready = barstate.isconfirmed and not na(rawAtr) and atr > 0
// ─── Step 1: Confirmed Swing Liquidity Registry ─────────────────────────────
if barstate.isconfirmed
if not na(ph)
swingHi.push(ph)
if swingHi.size() > 8
swingHi.shift()
if not na(pl)
swingLo.push(pl)
if swingLo.size() > 8
swingLo.shift()
if swingHi.size() > 0
for i = swingHi.size() - 1 to 0
if high > swingHi.get(i)
swingHi.remove(i)
if swingLo.size() > 0
for i = swingLo.size() - 1 to 0
if low < swingLo.get(i)
swingLo.remove(i)
// ─── Step 2: Active Trade Plan Lifecycle (Conservative Stop-First, Partial Scale-Outs) ──
if ready
for p = 0 to 5
Plan ap = active.get(p)
if not na(ap) and bar_index > ap.entryBar
bool isL = ap.dir == 1
bool done = false
if isL ? low <= ap.curSL : high >= ap.curSL
ap.exitPrice := ap.curSL
ap.beHit := ap.hit1 and useBE
ap.slHit := not ap.beHit
ap.outcome := ap.hit1 ? ((ap.hit2 ? "TP2" : "TP1") + (useBE ? ">BE" : ">SL")) : "SL"
done := true
if p == sel
evStop := not ap.hit1
evBE := ap.hit1
else
if not ap.hit1 and (isL ? high >= ap.tp1 : low <= ap.tp1)
ap.hit1 := true
lgTp1.set(p, lgTp1.get(p) + 1)
if useBE
ap.curSL := ap.entry
if p == sel
evTp1 := true
evMsgs.push(f_json("TP1", ap))
if ap.hit1 and not ap.hit2 and (isL ? high >= ap.tp2 : low <= ap.tp2)
ap.hit2 := true
lgTp2.set(p, lgTp2.get(p) + 1)
if p == sel
evTp2 := true
evMsgs.push(f_json("TP2", ap))
if ap.hit2 and not ap.hit3 and (isL ? high >= ap.tp3 : low <= ap.tp3)
ap.hit3 := true
ap.exitPrice := ap.tp3
ap.outcome := "TP3"
lgTp3.set(p, lgTp3.get(p) + 1)
done := true
if p == sel
evTp3 := true
if not done and bar_index - ap.entryBar >= timeoutBars
ap.exitPrice := close
ap.outcome := ap.hit1 ? ((ap.hit2 ? "TP2" : "TP1") + ">TIME") : "TIME"
done := true
if p == sel
evTime := true
if done
ap.resultR := f_realR(ap, ap.exitPrice)
ap.isOpen := false
ap.exitBar := bar_index
ap.exitTime := time
f_book(p, ap.resultR)
if ap.wf
f_book(6, ap.resultR)
if p == sel
evMsgs.push(f_json("EXIT", ap))
active.set(p, nullPlan)
// ─── Step 3: Zone Touch Tracking, Invalidation & Expiry ─────────────────────
if ready
for z in bullZ
if bar_index > z.birthBar and not z.dead
if low <= z.top
z.touched := true
z.lastTouchBar := bar_index
if close < z.bot - 0.10 * atr or bar_index - z.birthBar > zoneAgeIn * 2
z.dead := true
for z in bearZ
if bar_index > z.birthBar and not z.dead
if high >= z.bot
z.touched := true
z.lastTouchBar := bar_index
if close > z.top + 0.10 * atr or bar_index - z.birthBar > zoneAgeIn * 2
z.dead := true
// ─── Step 4: Evaluate FVG Mitigation Entries Across All 6 Profiles ──────────
if ready
for p = 0 to 5
Plan ap = active.get(p)
bool cooledDown = (bar_index - lastSigBar.get(p)) >= f_cooldown(p)
if na(ap) and cooledDown and erPct >= f_erMin(p) and relAct >= f_actMin(p)
int ageLim = int(math.round(zoneAgeIn * f_ageMult(p)))
bool trendOkL = (not f_trend(p) or (not na(ema) and close > ema and emaSlope >= -0.05 * atr)) and htfBias != -1
bool trendOkS = (not f_trend(p) or (not na(ema) and close < ema and emaSlope <= 0.05 * atr)) and htfBias != 1
Zone bz = na
Zone sz = na
if bullZ.size() > 0 and trendOkL and not bearCascade
for i = bullZ.size() - 1 to 0
Zone z = bullZ.get(i)
if na(bz) and not z.dead and z.touched and bar_index - z.lastTouchBar <= 2 and not f_hasFired(z, p) and bar_index - z.birthBar <= ageLim and z.effort >= f_effMin(p)
bool reclaimOk = close > open and close >= (f_ceReq(p) ? z.ce : z.bot) and close >= (hi1 - 0.25 * atr)
if reclaimOk and dBull >= f_dMin(p) and scBull >= f_scoreMin(p)
bz := z
if bearZ.size() > 0 and trendOkS and not bullCascade
for i = bearZ.size() - 1 to 0
Zone z = bearZ.get(i)
if na(sz) and not z.dead and z.touched and bar_index - z.lastTouchBar <= 2 and not f_hasFired(z, p) and bar_index - z.birthBar <= ageLim and z.effort >= f_effMin(p)
bool reclaimOk = close < open and close <= (f_ceReq(p) ? z.ce : z.top) and close <= (lo1 + 0.25 * atr)
if reclaimOk and dBear >= f_dMin(p) and scBear >= f_scoreMin(p)
sz := z
bool takeL = not na(bz)
bool takeS = not na(sz)
if takeL and takeS
takeL := false
takeS := false
if takeL
bz.firedMask += f_bit(p)
float rawSl = math.min(bz.bot, low) - f_buf(p) * atr
float rk = f_clamp(close - rawSl, f_minRisk(p) * atr, 2.8 * atr)
float slv = close - rk
if (close - rawSl) <= 3.0 * atr
float t1 = close + tp1R * rk
float t2 = close + tp2R * rk
float t3 = close + tp3R * rk
float r2v = tp2R
float r3v = tp3R
bool m2 = false
bool m3 = false
if useMagnet
float best = na
for z2 in bearZ
if not z2.dead and z2.bot > close
float d = (z2.bot - close) / rk
if d >= 1.4 and d <= 3.8 and (na(best) or z2.bot < best)
best := z2.bot
for v in swingHi
if v > close
float d = (v - close) / rk
if d >= 1.4 and d <= 3.8 and (na(best) or v < best)
best := v
if not na(best)
float dBest = (best - close) / rk
if dBest < 2.4
t2 := best
r2v := math.round(dBest, 1)
m2 := true
else
t3 := best
r3v := math.round(dBest, 1)
m3 := true
t2 := math.min(t2, best - 0.25 * rk)
r2v := math.round((t2 - close) / rk, 1)
t2 := math.max(t2, t1 + 0.2 * rk)
t3 := math.max(t3, t2 + 0.2 * rk)
r2v := math.round((t2 - close) / rk, 1)
r3v := math.round((t3 - close) / rk, 1)
Plan np = Plan.new(
prof = p,
dir = 1,
entry = close,
sl = slv,
curSL = slv,
tp1 = t1,
tp2 = t2,
tp3 = t3,
r1 = tp1R,
r2 = r2v,
r3 = r3v,
risk = rk,
entryBar = bar_index,
entryTime = time,
exitBar = bar_index,
exitTime = na,
exitPrice = na,
sigPrice = low - 0.18 * atr,
score = scBull,
fvgLeftTime = bz.leftTime,
fvgTop = bz.top,
fvgBot = bz.bot,
fvgCe = bz.ce,
mag2 = m2,
mag3 = m3,
wf = profIdx < 0 and p == sel
)
plans.push(np)
active.set(p, np)
lastSigBar.set(p, bar_index)
if p == sel
evBull := true
lastScore := scBull
evMsgs.push(f_json("ENTRY", np))
if takeS
sz.firedMask += f_bit(p)
float rawSl = math.max(sz.top, high) + f_buf(p) * atr
float rk = f_clamp(rawSl - close, f_minRisk(p) * atr, 2.8 * atr)
float slv = close + rk
if (rawSl - close) <= 3.0 * atr
float t1 = close - tp1R * rk
float t2 = close - tp2R * rk
float t3 = close - tp3R * rk
float r2v = tp2R
float r3v = tp3R
bool m2 = false
bool m3 = false
if useMagnet
float best = na
for z2 in bullZ
if not z2.dead and z2.top < close
float d = (close - z2.top) / rk
if d >= 1.4 and d <= 3.8 and (na(best) or z2.top > best)
best := z2.top
for v in swingLo
if v < close
float d = (close - v) / rk
if d >= 1.4 and d <= 3.8 and (na(best) or v > best)
best := v
if not na(best)
float dBest = (close - best) / rk
if dBest < 2.4
t2 := best
r2v := math.round(dBest, 1)
m2 := true
else
t3 := best
r3v := math.round(dBest, 1)
m3 := true
t2 := math.max(t2, best + 0.25 * rk)
r2v := math.round((close - t2) / rk, 1)
t2 := math.min(t2, t1 - 0.2 * rk)
t3 := math.min(t3, t2 - 0.2 * rk)
r2v := math.round((close - t2) / rk, 1)
r3v := math.round((close - t3) / rk, 1)
Plan np = Plan.new(
prof = p,
dir = -1,
entry = close,
sl = slv,
curSL = slv,
tp1 = t1,
tp2 = t2,
tp3 = t3,
r1 = tp1R,
r2 = r2v,
r3 = r3v,
risk = rk,
entryBar = bar_index,
entryTime = time,
exitBar = bar_index,
exitTime = na,
exitPrice = na,
sigPrice = high + 0.18 * atr,
score = scBear,
fvgLeftTime = sz.leftTime,
fvgTop = sz.top,
fvgBot = sz.bot,
fvgCe = sz.ce,
mag2 = m2,
mag3 = m3,
wf = profIdx < 0 and p == sel
)
plans.push(np)
active.set(p, np)
lastSigBar.set(p, bar_index)
if p == sel
evBear := true
lastScore := scBear
evMsgs.push(f_json("ENTRY", np))
while plans.size() > 180
plans.shift()
// ─── Step 5: Prune Invalidated Zones & Register Fresh 3-Candle FVGs ─────────
if ready
if bullZ.size() > 0
for i = bullZ.size() - 1 to 0
Zone z = bullZ.get(i)
if z.dead
box.delete(z.bx)
line.delete(z.ceLn)
label.delete(z.tagLb)
bullZ.remove(i)
if bearZ.size() > 0
for i = bearZ.size() - 1 to 0
Zone z = bearZ.get(i)
if z.dead
box.delete(z.bx)
line.delete(z.ceLn)
label.delete(z.tagLb)
bearZ.remove(i)
if gapBull
Zone z = Zone.new(dir = 1, top = low, bot = hi2, ce = (low + hi2) * 0.5, birthBar = bar_index, leftTime = t2ago, effort = effortPrev)
bullZ.push(z)
if bullZ.size() > maxZones
Zone old = bullZ.shift()
box.delete(old.bx)
line.delete(old.ceLn)
label.delete(old.tagLb)
if gapBear
Zone z = Zone.new(dir = -1, top = lo2, bot = high, ce = (lo2 + high) * 0.5, birthBar = bar_index, leftTime = t2ago, effort = effortPrev)
bearZ.push(z)
if bearZ.size() > maxZones
Zone old = bearZ.shift()
box.delete(old.bx)
line.delete(old.ceLn)
label.delete(old.tagLb)
// ═══════════════════════════════════════════════════════════════════════════
// 6. PINE SCREENER / DATA WINDOW PLOTS (First Plots)
// ═══════════════════════════════════════════════════════════════════════════
Plan selPlan = active.get(sel)
int selN = lgTrades.get(sel)
float selWr = selN > 0 ? lgWins.get(sel) * 100.0 / selN : 0.0
float sigVal = evBull ? 1.0 : evBear ? -1.0 : 0.0
float actDir = na(selPlan) ? 0.0 : selPlan.dir * 1.0
plot(sigVal, "Screener: FVG Mitigation Signal (+1=Buy, -1=Sell)", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(actDir, "Screener: Active Trade Plan (+1=Long, -1=Short)", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(evBull ? scBull : evBear ? scBear : 0.0, "Screener: Defense Quality Score % (0-100)", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(erPct, "Screener: Trend Efficiency % (0-100)", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(selWr, "Screener: Historical Win Rate % (net of costs)", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(lgNetR.get(sel), "Screener: Cumulative Net R", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(selN > 0 ? lgNetR.get(sel) / selN : 0.0, "Screener: Expectancy (R / trade)", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(htfBias, "Screener: HTF Bias (+1 / 0 / -1)", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(bullZ.size(), "Screener: Live Bullish Gaps", color = chart.fg_color, display = display.data_window + display.pine_screener)
plot(bearZ.size(), "Screener: Live Bearish Gaps", color = chart.fg_color, display = display.data_window + display.pine_screener)
// Invisible pane-displayed price anchors keep drawings locked to the price scale without distorting zoom
plot(high, "Price Scale High Anchor", color = color.new(color.white, 100), display = display.pane, editable = false)
plot(low, "Price Scale Low Anchor", color = color.new(color.white, 100), display = display.pane, editable = false)
bgcolor(showBg and not na(ema) ? (close > ema ? color.new(bullCol, 94) : color.new(bearCol, 94)) : na, title = "Trend Tint")
// ═══════════════════════════════════════════════════════════════════════════
// 7. INSTITUTIONAL CHART RENDERING (Rebuilt Cleanly on the Last Bar)
// ═══════════════════════════════════════════════════════════════════════════
var array<line> rLines = array.new<line>()
var array<label> rLabels = array.new<label>()
var array<box> rBoxes = array.new<box>()
color INK = #0B0E14
f_fmt(float v) => f_px(v)
if barstate.islast
for l in rLines
line.delete(l)
rLines.clear()
for lb in rLabels
label.delete(lb)
rLabels.clear()
for b in rBoxes
box.delete(b)
rBoxes.clear()
int projRightTime = nz(time("", bars_back = -6), time + 6 * barDur)
// ─── A. Render Live Unmitigated Bullish & Bearish FVG Zones ─────────────
for z in bullZ
box.delete(z.bx)
line.delete(z.ceLn)
label.delete(z.tagLb)
z.bx := na
z.ceLn := na
z.tagLb := na
if showZones and not z.dead
bool isMit = f_hasFired(z, sel)
// Hide live zone if it already fired for the selected profile (the Trade Plan renders its own Mitigated FVG origin box)
if not isMit
string zTag = showZoneText ? ("Bull FVG" + (z.touched ? " · tested" : "")) : ""
float ageF = fadeZones ? math.min(1.0, (bar_index - z.birthBar) / math.max(1.0, zoneAgeIn * f_ageMult(sel))) : 0.0
float fillT = math.min(97.0, (z.touched ? 90.0 : 86.0) + 8.0 * ageF)
float edgeT = math.min(90.0, (z.touched ? 50.0 : 60.0) + 25.0 * ageF)
z.bx := box.new(
left = z.leftTime,
top = z.top,
right = projRightTime,
bottom = z.bot,
xloc = xloc.bar_time,
bgcolor = color.new(bullCol, fillT),
border_color = color.new(bullCol, edgeT),
border_width = 1,
border_style = z.touched ? line.style_dashed : line.style_solid,
text = zTag,
text_size = size.tiny,
text_color = color.new(bullCol, 20),
text_halign = text.align_right,
text_valign = text.align_center
)
if showCE
z.ceLn := line.new(z.leftTime, z.ce, projRightTime, z.ce, xloc = xloc.bar_time, color = color.new(bullCol, math.min(85.0, 45.0 + 30.0 * ageF)), style = line.style_dotted, width = 1)
for z in bearZ
box.delete(z.bx)
line.delete(z.ceLn)
label.delete(z.tagLb)
z.bx := na
z.ceLn := na
z.tagLb := na
if showZones and not z.dead
bool isMit = f_hasFired(z, sel)
if not isMit
string zTag = showZoneText ? ("Bear FVG" + (z.touched ? " · tested" : "")) : ""
float ageF = fadeZones ? math.min(1.0, (bar_index - z.birthBar) / math.max(1.0, zoneAgeIn * f_ageMult(sel))) : 0.0
float fillT = math.min(97.0, (z.touched ? 90.0 : 86.0) + 8.0 * ageF)
float edgeT = math.min(90.0, (z.touched ? 50.0 : 60.0) + 25.0 * ageF)
z.bx := box.new(
left = z.leftTime,
top = z.top,
right = projRightTime,
bottom = z.bot,
xloc = xloc.bar_time,
bgcolor = color.new(bearCol, fillT),
border_color = color.new(bearCol, edgeT),
border_width = 1,
border_style = z.touched ? line.style_dashed : line.style_solid,
text = zTag,
text_size = size.tiny,
text_color = color.new(bearCol, 20),
text_halign = text.align_right,
text_valign = text.align_center
)
if showCE
z.ceLn := line.new(z.leftTime, z.ce, projRightTime, z.ce, xloc = xloc.bar_time, color = color.new(bearCol, math.min(85.0, 45.0 + 30.0 * ageF)), style = line.style_dotted, width = 1)
// ─── B. Collect Plans for the Selected / Auto-Best Profile ──────────────
array<Plan> selPlans = array.new<Plan>()
if plans.size() > 0
for i = 0 to plans.size() - 1
Plan cand = plans.get(i)
if cand.prof == sel
selPlans.push(cand)
int totalSel = selPlans.size()
if totalSel > 0
int startSig = showPastPlans ? math.max(0, totalSel - 6) : math.max(0, totalSel - 4)
int startPln = showPastPlans ? math.max(0, totalSel - 3) : (totalSel - 1)
// 1. Render Compact Signal Callout Badges (BUY 89% / SELL 92%)
if showBadges
for idx = startSig to totalSel - 1
Plan pp = selPlans.get(idx)
bool isLatest = idx == totalSel - 1
bool isL = pp.dir == 1
color dc = isL ? bullCol : bearCol
string stateTag = pp.isOpen ? "OPEN" : pp.outcome + " (" + (pp.resultR >= 0 ? "+" : "") + str.tostring(pp.resultR, "0.00") + "R)"
string sigTag = (isL ? "▲ " : "▼ ") + str.tostring(pp.score, "0")
string tipTxt = (isL ? "Bullish FVG Mitigation Entry\n" : "Bearish FVG Mitigation Entry\n") +
"Defense Score: " + str.tostring(pp.score, "0") + " / 100 (quality grade, not a probability)\n" +
"Profile: " + f_shortName(pp.prof) + "\n" +
"Entry: " + f_fmt(pp.entry) + " | SL: " + f_fmt(pp.sl) + "\n" +
"TP1: " + f_fmt(pp.tp1) + " | TP2: " + f_fmt(pp.tp2) + " | TP3: " + f_fmt(pp.tp3) + "\n" +
"Status: " + stateTag
rLabels.push(label.new(
x = pp.entryTime,
y = pp.sigPrice,
text = sigTag,
xloc = xloc.bar_time,
yloc = yloc.price,
color = color.new(dc, isLatest ? 5 : 45),
style = isL ? label.style_label_up : label.style_label_down,
textcolor = INK,
size = size.tiny,
text_formatting = text.format_bold,
tooltip = tipTxt
))
// 2. Render Trade Plan Ladders & Origin Mitigated FVG Zones
for idx = startPln to totalSel - 1
Plan pp = selPlans.get(idx)
bool isLatest = idx == totalSel - 1
bool isL = pp.dir == 1
color dc = isL ? bullCol : bearCol
bool beOn = useBE and pp.hit1
// Keep the latest focal plan projected cleanly to projRightTime when open OR when it resolved within the last 10 bars so right-edge labels never collide with live candles
bool projectToMargin = pp.isOpen or (isLatest and (bar_index - pp.exitBar) <= 10)
int x1Time = pp.entryTime
int x2Time = math.max(projectToMargin ? projRightTime : pp.exitTime, x1Time + barDur)
// Draw the Mitigated Origin FVG Zone that anchored this Trade Plan (from gap birth to entryTime)
if showZones and not na(pp.fvgLeftTime) and not na(pp.fvgTop)
string origTag = isLatest and showZoneText ? (isL ? "Mitigated bull FVG" : "Mitigated bear FVG") : ""
rBoxes.push(box.new(
left = pp.fvgLeftTime,
top = pp.fvgTop,
right = pp.entryTime,
bottom = pp.fvgBot,
xloc = xloc.bar_time,
border_color = color.new(dc, 35),
border_width = 1,
border_style = line.style_dashed,
bgcolor = color.new(dc, isLatest ? 84 : 92),
text = origTag,
text_size = size.tiny,
text_color = color.new(dc, 15),
text_halign = text.align_left,
text_valign = text.align_center
))
if showCE
rLines.push(line.new(pp.fvgLeftTime, pp.fvgCe, pp.entryTime, pp.fvgCe, xloc = xloc.bar_time, color = color.new(dc, 30), style = line.style_dotted, width = 1))
// Draw Risk & Reward Shaded Boxes and Level Lines
if showEntrySL
rBoxes.push(box.new(x1Time, math.max(pp.entry, pp.sl), x2Time, math.min(pp.entry, pp.sl), xloc = xloc.bar_time, border_color = color.new(bearCol, 65), border_width = 1, bgcolor = color.new(bearCol, 90)))
rLines.push(line.new(x1Time, pp.entry, x2Time, pp.entry, xloc = xloc.bar_time, color = color.new(chart.fg_color, 20), width = 1, style = line.style_solid))
rLines.push(line.new(x1Time, pp.sl, x2Time, pp.sl, xloc = xloc.bar_time, color = color.new(bearCol, 20), width = 1, style = line.style_solid))
if showTPs
rBoxes.push(box.new(x1Time, math.max(pp.entry, pp.tp3), x2Time, math.min(pp.entry, pp.tp3), xloc = xloc.bar_time, border_color = color.new(bullCol, 65), border_width = 1, bgcolor = color.new(bullCol, 92)))
rLines.push(line.new(x1Time, pp.tp1, x2Time, pp.tp1, xloc = xloc.bar_time, color = color.new(bullCol, 35), width = 1, style = line.style_dotted))
rLines.push(line.new(x1Time, pp.tp2, x2Time, pp.tp2, xloc = xloc.bar_time, color = color.new(bullCol, 25), width = 1, style = line.style_dashed))
rLines.push(line.new(x1Time, pp.tp3, x2Time, pp.tp3, xloc = xloc.bar_time, color = color.new(bullCol, 15), width = 1, style = line.style_solid))
// Right-edge institutional level pills (rendered on the latest focal plan to prevent clutter)
if isLatest
if showEntrySL
string entryTxt = "ENTRY " + f_fmt(pp.entry)
string slState = pp.slHit ? " ✗" : pp.beHit ? " (BE ✓)" : beOn ? " (BE)" : " (-1R)"
string slTxt = "SL " + f_fmt(pp.sl) + slState
rLabels.push(label.new(x2Time, pp.entry, entryTxt, xloc = xloc.bar_time, yloc = yloc.price, color = color.new(chart.bg_color, 20), style = label.style_label_left, textcolor = chart.fg_color, size = size.tiny, text_formatting = text.format_bold))
rLabels.push(label.new(x2Time, pp.sl, slTxt, xloc = xloc.bar_time, yloc = yloc.price, color = color.new(bearCol, pp.slHit ? 20 : 82), style = label.style_label_left, textcolor = chart.fg_color, size = size.tiny, text_formatting = text.format_bold))
if showTPs
string magTag2 = pp.mag2 ? "·MAG" : ""
string magTag3 = pp.mag3 ? "·MAG" : ""
string tp1Txt = "TP1 " + f_fmt(pp.tp1) + " (" + str.tostring(pp.r1, "#.#") + "R)" + (pp.hit1 ? " ✓" : "")
string tp2Txt = "TP2 " + f_fmt(pp.tp2) + " (" + str.tostring(pp.r2, "#.#") + "R" + magTag2 + ")" + (pp.hit2 ? " ✓" : "")
string tp3Txt = "TP3 " + f_fmt(pp.tp3) + " (" + str.tostring(pp.r3, "#.#") + "R" + magTag3 + ")" + (pp.hit3 ? " ✓" : "")
rLabels.push(label.new(x2Time, pp.tp1, tp1Txt, xloc = xloc.bar_time, yloc = yloc.price, color = color.new(bullCol, pp.hit1 ? 20 : 84), style = label.style_label_left, textcolor = pp.hit1 ? INK : chart.fg_color, size = size.tiny, text_formatting = text.format_bold))
rLabels.push(label.new(x2Time, pp.tp2, tp2Txt, xloc = xloc.bar_time, yloc = yloc.price, color = color.new(bullCol, pp.hit2 ? 20 : 84), style = label.style_label_left, textcolor = pp.hit2 ? INK : chart.fg_color, size = size.tiny, text_formatting = text.format_bold))
rLabels.push(label.new(x2Time, pp.tp3, tp3Txt, xloc = xloc.bar_time, yloc = yloc.price, color = color.new(bullCol, pp.hit3 ? 15 : 80), style = label.style_label_left, textcolor = pp.hit3 ? INK : chart.fg_color, size = size.tiny, text_formatting = text.format_bold))
// ═══════════════════════════════════════════════════════════════════════════
// 8. SUMMARY DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════
var table dash = table.new(position.top_right, 2, 10, border_width = 1)
f_rs(float v) => (v >= 0 ? "+" : "") + str.tostring(v, "0.00") + "R"
f_pf(int i) =>
float gw = lgGrossW.get(i)
float gl = lgGrossL.get(i)
gl > 0 ? str.tostring(gw / gl, "0.00") : gw > 0 ? "∞" : "—"
if barstate.islast
table.clear(dash, 0, 0, 1, 9)
if showDash
string ts = switch tblSzIn
TableSz.tiny => size.tiny
TableSz.small => size.small
TableSz.normal => size.normal
=> size.large
color bgHeader = color.new(chart.bg_color, 5)
color bgRow = color.new(chart.bg_color, 15)
color txtMain = chart.fg_color
color txtMuted = color.new(chart.fg_color, 45)
table.set_bgcolor(dash, bgHeader)
table.set_border_color(dash, color.new(chart.fg_color, 88))
int trendBias = not na(ema) ? (close > ema ? 1 : close < ema ? -1 : 0) : 0
color biasCol = trendBias == 1 ? bullCol : trendBias == -1 ? bearCol : txtMuted
bool erClear = erPct >= f_erMin(sel)
int row = 0
// Header
string regStr = (trendBias == 1 ? "Bull" : trendBias == -1 ? "Bear" : "Flat") + " · " + str.tostring(erPct, "#") + "% eff" + (htfOn ? (" · HTF " + (htfBias == 1 ? "▲" : htfBias == -1 ? "▼" : "–")) : "")
table.cell(dash, 0, row, "FVGM", text_color = txtMain, bgcolor = bgHeader, text_size = ts, text_formatting = text.format_bold, text_halign = text.align_left)
table.cell(dash, 1, row, regStr, text_color = erClear ? biasCol : txtMuted, bgcolor = bgHeader, text_size = ts, text_formatting = text.format_bold, text_halign = text.align_right, tooltip = "EMA trend · 10-bar Kaufman efficiency (muted = below the profile minimum, no new entries)")
row += 1
// Profile
table.cell(dash, 0, row, "Profile", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, (profIdx < 0 ? "Auto · " : "") + f_shortName(sel), text_color = txtMain, bgcolor = bgRow, text_size = ts, text_formatting = text.format_bold, text_halign = text.align_right, tooltip = f_name(sel))
row += 1
// Trades & win rate
int wins = lgWins.get(sel)
int losses = lgLosses.get(sel)
float netR = lgNetR.get(sel)
float expR = selN > 0 ? netR / selN : 0.0
string wrStr = selN > 0 ? (str.tostring(selN) + " · " + str.tostring(selWr, "0") + "% (" + str.tostring(wins) + "W/" + str.tostring(losses) + "L)") : "No closed trades"
table.cell(dash, 0, row, "Trades · Win", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, wrStr, text_color = txtMain, bgcolor = bgRow, text_size = ts, text_halign = text.align_right, tooltip = "Win = trade closed above 0R after scale-outs and costs")
row += 1
// Expectancy & profit factor
color expCol = selN == 0 ? txtMuted : expR > 0 ? bullCol : bearCol
table.cell(dash, 0, row, "Expectancy · PF", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, selN > 0 ? (f_rs(expR) + " · PF " + f_pf(sel)) : "—", text_color = expCol, bgcolor = bgRow, text_size = ts, text_formatting = text.format_bold, text_halign = text.align_right)
row += 1
// Net R & max drawdown
table.cell(dash, 0, row, "Net · Max DD", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, selN > 0 ? (f_rs(netR) + " · " + str.tostring(lgMaxDD.get(sel), "0.0") + "R") : "—", text_color = selN == 0 ? txtMuted : netR >= 0 ? txtMain : bearCol, bgcolor = bgRow, text_size = ts, text_halign = text.align_right)
row += 1
// Auto walk-forward (honest out-of-sample-ish record)
if profIdx < 0
int nWf = lgTrades.get(6)
float netWf = lgNetR.get(6)
string wfStr = nWf > 0 ? (str.tostring(nWf) + " · " + f_rs(netWf / nWf) + " · PF " + f_pf(6)) : "—"
table.cell(dash, 0, row, "Auto Live Record", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, wfStr, text_color = nWf == 0 ? txtMuted : netWf >= 0 ? bullCol : bearCol, bgcolor = bgRow, text_size = ts, text_halign = text.align_right, tooltip = "Trades actually taken by whichever profile Auto had selected AT ENTRY TIME. The rows above show the winning profile's full history, which is picked in hindsight and will look better than reality. Trust this row more.")
row += 1
// Target hits
string tpStr = str.tostring(lgTp1.get(sel)) + " / " + str.tostring(lgTp2.get(sel)) + " / " + str.tostring(lgTp3.get(sel))
table.cell(dash, 0, row, "TP1 / TP2 / TP3", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, tpStr, text_color = txtMain, bgcolor = bgRow, text_size = ts, text_halign = text.align_right)
row += 1
// Nearest live gap
float nearCe = na
int nearDir = 0
float bestD = 1e18
for z in bullZ
if not z.dead and not f_hasFired(z, sel)
float d = math.abs(close - z.ce)
if d < bestD
bestD := d
nearCe := z.ce
nearDir := 1
for z in bearZ
if not z.dead and not f_hasFired(z, sel)
float d = math.abs(close - z.ce)
if d < bestD
bestD := d
nearCe := z.ce
nearDir := -1
string gapStr = str.tostring(bullZ.size()) + "▲ " + str.tostring(bearZ.size()) + "▼" + (not na(nearCe) ? " · CE " + f_fmt(nearCe) + " (" + str.tostring(bestD / atr, "0.0") + " ATR)" : "")
table.cell(dash, 0, row, "Live FVGs", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, gapStr, text_color = nearDir == 1 ? bullCol : nearDir == -1 ? bearCol : txtMain, bgcolor = bgRow, text_size = ts, text_halign = text.align_right)
row += 1
// Current / last plan (+ sizing)
Plan focalPlan = selPlan
if na(focalPlan) and plans.size() > 0
for i = plans.size() - 1 to 0
Plan cand = plans.get(i)
if cand.prof == sel and na(focalPlan)
focalPlan := cand
string planStr = "Waiting for FVG test"
color planCol = txtMuted
if not na(focalPlan)
planCol := focalPlan.dir == 1 ? bullCol : bearCol
string stTag = focalPlan.isOpen ? (focalPlan.hit2 ? "TP2 ✓" : focalPlan.hit1 ? "TP1 ✓" : "open") : (focalPlan.outcome + " " + f_rs(focalPlan.resultR))
planStr := (focalPlan.dir == 1 ? "Long " : "Short ") + f_fmt(focalPlan.entry) + " · " + stTag
if riskCash > 0 and focalPlan.isOpen
float qty = riskCash / math.max(focalPlan.risk * syminfo.pointvalue, syminfo.mintick)
planStr += " · qty " + str.tostring(qty, qty >= 10 ? "#" : "#.##")
table.cell(dash, 0, row, "Plan", text_color = txtMuted, bgcolor = bgRow, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, row, planStr, text_color = planCol, bgcolor = bgRow, text_size = ts, text_formatting = text.format_bold, text_halign = text.align_right)
// ═══════════════════════════════════════════════════════════════════════════
// 9. ALERTS
// ═══════════════════════════════════════════════════════════════════════════
alertcondition(evBull, title = "1. Bullish FVG Mitigation Entry (BUY)", message = "FVGM [PhenLabs]: Confirmed Bullish FVG mitigation entry on {{ticker}} ({{interval}}) at {{close}}. Entry, SL, and TP1-TP3 trade plan active.")
alertcondition(evBear, title = "2. Bearish FVG Mitigation Entry (SELL)", message = "FVGM [PhenLabs]: Confirmed Bearish FVG mitigation entry on {{ticker}} ({{interval}}) at {{close}}. Entry, SL, and TP1-TP3 trade plan active.")
alertcondition(evBull or evBear, title = "3. Any Confirmed FVG Mitigation Entry (BUY or SELL)", message = "FVGM [PhenLabs]: Confirmed Fair Value Gap mitigation signal on {{ticker}} ({{interval}}) at {{close}}.")
alertcondition(evTp1, title = "4. Trade Plan TP1 Reached", message = "FVGM [PhenLabs]: Active trade plan reached TP1 on {{ticker}} ({{interval}}).")
alertcondition(evTp2, title = "5. Trade Plan TP2 Reached", message = "FVGM [PhenLabs]: Active trade plan reached TP2 on {{ticker}} ({{interval}}).")
alertcondition(evTp3, title = "6. Trade Plan TP3 Reached", message = "FVGM [PhenLabs]: Active trade plan reached TP3 on {{ticker}} ({{interval}}).")
alertcondition(evStop, title = "7. Trade Plan Stop Loss Hit", message = "FVGM [PhenLabs]: Active trade plan hit Stop Loss on {{ticker}} ({{interval}}).")
alertcondition(evBE, title = "8. Runner Stopped After TP1 (BE / Trail)", message = "FVGM [PhenLabs]: Remaining position stopped after TP1 on {{ticker}} ({{interval}}).")
alertcondition(evTime, title = "9. Trade Plan Timed Out", message = "FVGM [PhenLabs]: Active trade plan reached its bar timeout on {{ticker}} ({{interval}}).")
if dynAlerts and barstate.isconfirmed and evMsgs.size() > 0
alert(evMsgs.join("\n"), alert.freq_once_per_bar_close)