本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Open Legacy Layer Master Official", overlay = true, max_labels_count = 500, max_boxes_count = 500)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// OPEN LEGACY PULSE — a live health check for the open trade.
// Set it up exactly like Open Legacy (same entry method, sensitivity, SL / TP,
// sessions and timezone) and it follows the same trades. On top of the signal it
// reads where TP and SL sit against the market structure, then flags the trade
// green / orange / red and says: LAYER, LET IT RUN, or EXPECT WORSE.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ── 1. STRATEGY ──────────────────────────────────────────────────────────
G1 = "1. Strategy"
entryMethod = input.string("FVG Pullback", "Entry Method", options = ["FVG Pullback", "EMA Trend"], group = G1,
tooltip = "FVG Pullback — price leaves a fair value gap (a candle so fast it leaves an untouched gap), then a signal fires when price pulls back into the gap and turns.\n\nEMA Trend — signals at the start of a new trend leg: fast EMA above slow EMA, price above the fast EMA and RSI above 50 (the reverse for sells).")
sensitivity = input.string("Balanced", "Sensitivity", options = ["Aggressive", "Balanced", "Conservative"], group = G1,
tooltip = "Aggressive — the most signals, any timeframe.\n\nBalanced — only signals that agree with the 50 EMA trend.\n\nConservative — also needs the trend on a timeframe 4x your chart to agree, and real trend strength (ADX 20+). The fewest signals, the highest quality.")
// ── 2. TARGETS ───────────────────────────────────────────────────────────
G2 = "2. Targets"
slPips = input.float(79, "Stop Loss (pips)", minval = 0.1, step = 0.1, group = G2,
tooltip = "Use the same number as Open Legacy.")
tpPips = input.float(55, "Take Profit (pips)", minval = 0.1, step = 0.1, group = G2,
tooltip = "Use the same number as Open Legacy.")
pipPoints = input.int(10, "Points Per Pip", minval = 1, group = G2,
tooltip = "10 for gold, indices, BTC and 5-decimal FX.")
// ── 3. FILTERS ───────────────────────────────────────────────────────────
G4 = "3. Filters"
hoursOn = input.bool(true, "Session 1", group = G4, inline = "h1",
tooltip = "Up to 8 sessions. Tick a session, pick its start and end time (overnight works, e.g. 22:00-02:00) and its days (your Timezone below). Each session has its own days, e.g. Session 1 Mon-Fri 07:00-12:00 and Session 2 Thu-Fri 14:00-18:00. Leave all unticked to trade any time.")
hoursWin = input.session("0100-1430", "", group = G4, inline = "h1")
hoursDays = input.string("Mon", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h1")
hours2On = input.bool(true, "Session 2", group = G4, inline = "h2")
hoursWin2 = input.session("1900-2300", "", group = G4, inline = "h2")
hoursDays2 = input.string("Mon", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h2")
hours3On = input.bool(true, "Session 3", group = G4, inline = "h3")
hoursWin3 = input.session("0700-1200", "", group = G4, inline = "h3")
hoursDays3 = input.string("Tue", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h3")
hours4On = input.bool(true, "Session 4", group = G4, inline = "h4")
hoursWin4 = input.session("0130-1300", "", group = G4, inline = "h4")
hoursDays4 = input.string("Tue", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h4")
hours5On = input.bool(true, "Session 5", group = G4, inline = "h5")
hoursWin5 = input.session("0100-0700", "", group = G4, inline = "h5")
hoursDays5 = input.string("Wed", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h5")
hours6On = input.bool(true, "Session 6", group = G4, inline = "h6")
hoursWin6 = input.session("1200-1430", "", group = G4, inline = "h6")
hoursDays6 = input.string("Wed", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h6")
hours7On = input.bool(true, "Session 7", group = G4, inline = "h7")
hoursWin7 = input.session("0200-0630", "", group = G4, inline = "h7")
hoursDays7 = input.string("Thu", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h7")
hours8On = input.bool(true, "Session 8", group = G4, inline = "h8")
hoursWin8 = input.session("1500-1800", "", group = G4, inline = "h8")
hoursDays8 = input.string("Fri", "", options = ["Every Day", "Mon-Fri", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Sat", "Mon-Sun", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", "Wed-Thu", "Wed-Fri", "Wed-Sat", "Wed-Sun", "Thu-Fri", "Thu-Sat", "Thu-Sun", "Fri-Sat", "Fri-Sun", "Sat-Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Sun-Fri"], group = G4, inline = "h8")
// ── 4. DISPLAY ───────────────────────────────────────────────────────────
G3 = "4. Display"
buyColor = input.color(#4CAF50, "BUY", group = G3, inline = "c")
sellColor = input.color(#FF5252, "SELL", group = G3, inline = "c")
sessionTz = input.string("Europe/Dublin", "Timezone", group = G3,
tooltip = "Your timezone, IANA format (e.g. Europe/Dublin, America/New_York). Used for Trading Hours and the market-closed status.")
replayMode = input.bool(false, "Bar Replay Mode", group = G3,
tooltip = "Turn on while using Bar Replay so the HUD keeps updating.")
// ── 5. PULSE ─────────────────────────────────────────────────────────────
G5 = "5. Layer Master"
layerMin = input.float(20, "Zone starts (% of the way to your stop)", minval = 5, maxval = 90, group = G5,
tooltip = "WHERE THE BOX BEGINS.\nThe box is drawn between your entry and your stop. 20 means it starts 20% of the way from your entry to your stop.\nSmaller number = box starts closer to your entry.")
layerMax = input.float(55, "Zone ends (% of the way to your stop)", minval = 10, maxval = 95, group = G5,
tooltip = "WHERE THE BOX ENDS.\n55 means it ends 55% of the way to your stop. If price goes deeper than this, the box turns red: too close to the stop to add.")
layerWhen = input.string("Normal", "How picky to be", options = ["Relaxed", "Normal", "Strict"], group = G5,
tooltip = "HOW OFTEN THE BOX TURNS GREEN (layer window open).\nRelaxed = green more often.\nNormal = recommended.\nStrict = green only on the cleanest dips.\n\nBox colours: teal = waiting, green = layer window open, red = too risky, don't add.")
int layerMinHealth = layerWhen == "Relaxed" ? 45 : (layerWhen == "Strict" ? 75 : 60)
pivLen = 5
rangeLen = 50
stallHours = 6.0
showFlags = false
showZone = true
showDetail = false
alertsOn = true
//── Internal constants ──
useExchangeTz = false
useCorrFilter = true
buyBgColor = buyColor
buyTextColor = color.white
sellBgColor = sellColor
sellTextColor = color.white
corrEmaLen = 9
corrConfBars = 3
gracePeriodBars = 6
maxRampBars = 12
getTablePosition(string pos) =>
switch pos
"Top Left" => position.top_left
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.bottom_right
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🌐 UNIVERSAL HANDS-FREE BENCHMARK ROUTER
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Returns [benchmarkSymbol, isInverseRelationship]
// isInverseRelationship = true -> benchmark moving UP pushes asset toward SL if asset is a BUY
// (i.e. benchmark should move OPPOSITE the asset to favor TP)
// isInverseRelationship = false -> benchmark should move WITH the asset to favor TP
getUniversalInverseBenchmark() =>
string p = syminfo.prefix
string t = str.upper(syminfo.ticker)
string base = syminfo.basecurrency
string quote = syminfo.currency
string symbol = "TVC:DXY"
bool inverse = true
if t == "USDX" or t == "DXY" or t == "USDOLLAR" or t == "DX"
symbol := "TVC:GOLD"
inverse := true
else if p == "NSE" or p == "BSE" or quote == "INR"
symbol := "NSE:INDIAVIX"
inverse := true
else if str.contains(t, "SPX") or str.contains(t, "US500") or str.contains(t, "SP500") or str.contains(t, "NDX") or str.contains(t, "US100") or str.contains(t, "NAS100") or str.contains(t, "US30") or str.contains(t, "DJI") or str.contains(t, "GER") or str.contains(t, "DAX") or str.contains(t, "UK100") or str.contains(t, "EU50") or p == "NASDAQ" or p == "NYSE"
symbol := "TVC:VIX"
inverse := true
else if base == "USD"
if quote == "JPY"
symbol := "TVC:JXY"
inverse := true
else if quote == "CAD"
symbol := "TVC:CXY"
inverse := true
else if quote == "CHF"
symbol := "TVC:SXY"
inverse := true
else
// USD is the BASE here (USDSEK, USDMXN, USDZAR, USDTRY, USDHKD, etc.)
// DXY moves WITH these pairs, not against them — DIRECT correlation
symbol := "TVC:DXY"
inverse := false
else if quote == "USD"
symbol := "TVC:DXY"
inverse := true
else if quote == "JPY"
symbol := "TVC:JXY"
inverse := true
else if quote == "GBP"
symbol := "TVC:BXY"
inverse := true
else if quote == "EUR"
symbol := "TVC:EXY"
inverse := true
[symbol, inverse]
getBenchmarkDisplayName(string symbol) =>
switch symbol
"NSE:INDIAVIX" => "India VIX"
"TVC:VIX" => "VIX"
"TVC:DXY" => "DXY"
"TVC:GOLD" => "Gold"
"TVC:JXY" => "Yen Index"
"TVC:BXY" => "Pound Index"
"TVC:EXY" => "Euro Index"
"TVC:CXY" => "CAD Index"
"TVC:SXY" => "CHF Index"
=> symbol
[routedBenchSymbol, routedBenchInverse] = getUniversalInverseBenchmark()
string activeBenchSymbol = routedBenchSymbol
bool activeBenchInverse = routedBenchInverse
string activeBenchName = getBenchmarkDisplayName(activeBenchSymbol)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🌙 MARKET-CLOSE DETECTOR — scheduled weekly close OR unscheduled outage
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
bool isCrypto = syminfo.type == "crypto" or str.contains(syminfo.ticker, "BTC") or str.contains(syminfo.ticker, "ETH")
// Scheduled weekly close, evaluated against the REAL current clock (timenow) in
// the chosen timezone. DST is handled automatically via IANA tz names.
// • Mon-Fri: closed 22:00-22:59 local (daily break), reopens 23:00
// • Fri 22:00 onward through all of Sat through Sun 22:59: weekend closed
// • Reopens Sunday 23:00 local
f_isScheduledClose(string tz) =>
int dow = dayofweek(timenow, tz) // Pine: 1 = Sunday ... 7 = Saturday
int hr = hour(timenow, tz)
bool weekdayBreak = (dow >= 2 and dow <= 6) and (hr == 22)
bool weekendClosed = (dow == 6 and hr >= 22) or (dow == 7) or (dow == 1 and hr < 23)
weekdayBreak or weekendClosed
bool scheduledClosedNow = f_isScheduledClose(useExchangeTz ? syminfo.timezone : sessionTz)
// Live "no fresh data" detector — catches an UNSCHEDULED outage or maintenance
// break of any length (not a fixed window): as long as no new bar has printed
// for 15+ minutes on a genuinely live last bar, it stays flagged closed for
// however long that gap continues, and clears the moment fresh data resumes.
// Only ever evaluated on barstate.isrealtime, so historical/replay bars never
// trigger this regardless of how old their timestamps are.
bool dataStaleNow = barstate.isrealtime and barstate.islast and (timenow - time_close > 900000)
// DXY/forex benchmark closes on the standard schedule even when crypto itself
// keeps trading — bypass the correlation filter during that window.
bool isCryptoDxyOffline = not replayMode and isCrypto and scheduledClosedNow
// Main HUD "market closed" status:
// • non-crypto: closed if EITHER the scheduled weekly window applies OR the
// feed has genuinely gone stale (unscheduled maintenance/outage)
// • crypto: trades 24/7, so the fixed weekly schedule doesn't apply to the
// asset itself — only genuine exchange downtime (stale feed) marks it closed
bool isMarketClosedRT = not replayMode and (dataStaleNow or (not isCrypto and scheduledClosedNow))
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 📊 SIGNAL ENGINE
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Sensitivity presets (literal values keep lengths "simple" for ta.* calls)
fvgLife = sensitivity == "Aggressive" ? 12 : sensitivity == "Balanced" ? 24 : 40
fvgMin = sensitivity == "Aggressive" ? 0.10 : sensitivity == "Balanced" ? 0.25 : 0.40
emaFastL = sensitivity == "Aggressive" ? 8 : sensitivity == "Balanced" ? 13 : 21
emaSlowL = sensitivity == "Aggressive" ? 21 : sensitivity == "Balanced" ? 34 : 55
atrV = ta.atr(14)
ema50 = ta.ema(close, 50)
[diP, diM, adxV] = ta.dmi(14, 14)
// Higher-timeframe trend (4x chart), previous completed candle — never repaints.
htfTf = timeframe.from_seconds(timeframe.in_seconds() * 4)
htfC = request.security(syminfo.tickerid, htfTf, close[1], lookahead = barmerge.lookahead_on)
htfE = request.security(syminfo.tickerid, htfTf, ta.ema(close, 50)[1], lookahead = barmerge.lookahead_on)
bool htfUp = not na(htfE) and htfC > htfE
bool htfDn = not na(htfE) and htfC < htfE
// ── FVG Pullback ──
var float bullTop = na
var float bullBot = na
var int bullBar = na
var float bearTop = na
var float bearBot = na
var int bearBar = na
bool fvgBuy = not na(bullBar) and bar_index - bullBar > 0 and bar_index - bullBar <= fvgLife and low <= bullTop and close > open and close > bullBot
bool fvgSell = not na(bearBar) and bar_index - bearBar > 0 and bar_index - bearBar <= fvgLife and high >= bearBot and close < open and close < bearTop
if fvgBuy
bullBar := na
if fvgSell
bearBar := na
if low > high[2] and (low - high[2]) >= fvgMin * atrV
bullBot := high[2]
bullTop := low
bullBar := bar_index
if high < low[2] and (low[2] - high) >= fvgMin * atrV
bearTop := low[2]
bearBot := high
bearBar := bar_index
// ── EMA Trend ──
emaF = ta.ema(close, emaFastL)
emaS = ta.ema(close, emaSlowL)
rsiV = ta.rsi(close, 14)
bool trUp = emaF > emaS and close > emaF and rsiV > 50
bool trDn = emaF < emaS and close < emaF and rsiV < 50
bool trendBuy = trUp and not trUp[1]
bool trendSell = trDn and not trDn[1]
// ── Sensitivity filter ──
bool rawBuy = entryMethod == "FVG Pullback" ? fvgBuy : trendBuy
bool rawSell = entryMethod == "FVG Pullback" ? fvgSell : trendSell
bool qBuy = sensitivity == "Aggressive" or (close > ema50 and (sensitivity == "Balanced" or (htfUp and adxV >= 20)))
bool qSell = sensitivity == "Aggressive" or (close < ema50 and (sensitivity == "Balanced" or (htfDn and adxV >= 20)))
bool sigBuy = rawBuy and qBuy
bool sigSell = rawSell and qSell and not sigBuy
slowEma = ema50
rawBenchClose = request.security(activeBenchSymbol, timeframe.period, close, barmerge.gaps_off, barmerge.lookahead_off)
rawBenchEma = request.security(activeBenchSymbol, timeframe.period, ta.ema(close, corrEmaLen), barmerge.gaps_off, barmerge.lookahead_off)
benchClose = nz(rawBenchClose, close)
benchEma = nz(rawBenchEma, ta.ema(close, corrEmaLen))
bool rawBenchBullish = benchClose > benchEma
bool rawBenchBearish = benchClose < benchEma
bool benchBullish = ta.lowest(rawBenchBullish ? 1 : 0, corrConfBars) == 1
bool benchBearish = ta.lowest(rawBenchBearish ? 1 : 0, corrConfBars) == 1
// benchFavorsBuy/Sell = benchmark is moving in the direction that supports price
// heading toward TP (not SL) for the current trade direction.
bool benchFavorsBuy = activeBenchInverse ? benchBearish : benchBullish
bool benchFavorsSell = activeBenchInverse ? benchBullish : benchBearish
bool corrBuyConfirm = not useCorrFilter or isCryptoDxyOffline or benchFavorsBuy
bool corrSellConfirm = not useCorrFilter or isCryptoDxyOffline or benchFavorsSell
// ── Filters: trading hours (sessions) ──
f_dayList(string opt) =>
string nm = "MonTueWedThuFriSatSun"
string res = "1234567"
if opt != "Every Day"
int a = int(str.pos(nm, str.substring(opt, 0, 3)) / 3)
int b = str.length(opt) > 3 ? int(str.pos(nm, str.substring(opt, 4, 7)) / 3) : a
res := ""
int i = a
for k = 0 to 6
res += str.tostring(i == 6 ? 1 : i + 2)
if i == b
break
i := (i + 1) % 7
res
f_hhmm(string s, int p) =>
int(str.tonumber(str.substring(s, p, p + 2)))
int barMins = hour(time, sessionTz) * 60 + minute(time, sessionTz)
f_inWin(string w) =>
int hs = f_hhmm(w, 0) * 60 + f_hhmm(w, 2)
int he = f_hhmm(w, 5) * 60 + f_hhmm(w, 7)
he > hs ? (barMins >= hs and barMins < he) : (barMins >= hs or barMins < he)
string dowNow = str.tostring(dayofweek(time, sessionTz))
bool inS1 = hoursOn and str.contains(f_dayList(hoursDays), dowNow) and f_inWin(hoursWin)
bool inS2 = hours2On and str.contains(f_dayList(hoursDays2), dowNow) and f_inWin(hoursWin2)
bool inS3 = hours3On and str.contains(f_dayList(hoursDays3), dowNow) and f_inWin(hoursWin3)
bool inS4 = hours4On and str.contains(f_dayList(hoursDays4), dowNow) and f_inWin(hoursWin4)
bool inS5 = hours5On and str.contains(f_dayList(hoursDays5), dowNow) and f_inWin(hoursWin5)
bool inS6 = hours6On and str.contains(f_dayList(hoursDays6), dowNow) and f_inWin(hoursWin6)
bool inS7 = hours7On and str.contains(f_dayList(hoursDays7), dowNow) and f_inWin(hoursWin7)
bool inS8 = hours8On and str.contains(f_dayList(hoursDays8), dowNow) and f_inWin(hoursWin8)
bool inHours = (not hoursOn and not hours2On and not hours3On and not hours4On and not hours5On and not hours6On and not hours7On and not hours8On) or inS1 or inS2 or inS3 or inS4 or inS5 or inS6 or inS7 or inS8
// ── Signals ──
bool confirmedBar = barstate.isconfirmed or replayMode
bool buy1 = sigBuy and inHours
bool sell1 = sigSell and inHours
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🏗️ MARKET STRUCTURE REFERENCES
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
float plV = ta.pivotlow(low, pivLen, pivLen)
float phV = ta.pivothigh(high, pivLen, pivLen)
var float lastPL = na
var float lastPH = na
if not na(plV)
lastPL := plV
if not na(phV)
lastPH := phV
float lowN = ta.lowest(low, 10)
float highN = ta.highest(high, 10)
float rangeHi = ta.highest(high, rangeLen)
float rangeLo = ta.lowest(low, rangeLen)
float mF9 = ta.ema(close, 9)
float mS21 = ta.ema(close, 21)
float atrAvg = ta.sma(atrV, 50)
int timeoutBars = math.max(2, int(math.round(stallHours * 3600 / timeframe.in_seconds())))
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🔒 SAME TRADE ENGINE AS OPEN LEGACY (one trade at a time)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var bool tradeActive = false
var bool activeIsBuy = false
var float lockedEntry = na
var float lockedTpPrice = na
var float lockedSlPrice = na
var int tradeEntryBar = na
var float entryGuard = na
var float entryBarrier = na
var int benchBad = 0
var int prevKey = 0
var int prevVerdict = 0
var string lastResult = "WAITING"
var box zBox = na
bool exitsThisBar = tradeActive and bar_index > tradeEntryBar and not na(lockedTpPrice) and
(activeIsBuy ? (high >= lockedTpPrice or low <= lockedSlPrice) : (low <= lockedTpPrice or high >= lockedSlPrice))
bool flat = not tradeActive or exitsThisBar
bool newBuySignal = buy1 and (flat or not activeIsBuy)
bool newSellSignal = sell1 and (flat or activeIsBuy)
if (newBuySignal or newSellSignal) and (barstate.isconfirmed or replayMode)
activeIsBuy := newBuySignal
float tpDist = tpPips * pipPoints * syminfo.mintick
float slDist = slPips * pipPoints * syminfo.mintick
lockedEntry := close
lockedTpPrice := activeIsBuy ? close + tpDist : close - tpDist
lockedSlPrice := activeIsBuy ? close - slDist : close + slDist
tradeEntryBar := bar_index
tradeActive := true
benchBad := 0
prevKey := 0
prevVerdict := 0
lastResult := activeIsBuy ? "BUY ACTIVE" : "SELL ACTIVE"
// swing the trade leans on (below a buy, above a sell), kept 0.3-3 ATR away
if activeIsBuy
float cand = (not na(lastPL) and lastPL <= close - 0.3 * atrV and lastPL >= close - 3 * atrV) ? lastPL : math.min(lowN, close - 0.3 * atrV)
entryGuard := cand
float b1 = (not na(lastPH) and lastPH > close and lastPH < lockedTpPrice) ? lastPH : 1e10
float b2 = (rangeHi > close and rangeHi < lockedTpPrice) ? rangeHi : 1e10
float bb = math.min(b1, b2)
entryBarrier := bb >= 1e10 ? na : bb
else
float cand = (not na(lastPH) and lastPH >= close + 0.3 * atrV and lastPH <= close + 3 * atrV) ? lastPH : math.max(highN, close + 0.3 * atrV)
entryGuard := cand
float b1 = (not na(lastPL) and lastPL < close and lastPL > lockedTpPrice) ? lastPL : -1e10
float b2 = (rangeLo < close and rangeLo > lockedTpPrice) ? rangeLo : -1e10
float bb = math.max(b1, b2)
entryBarrier := bb <= -1e10 ? na : bb
if showZone
float zA = activeIsBuy ? close - slDist * layerMin / 100.0 : close + slDist * layerMin / 100.0
float zB = activeIsBuy ? close - slDist * layerMax / 100.0 : close + slDist * layerMax / 100.0
zBox := box.new(bar_index, math.max(zA, zB), bar_index + 1, math.min(zA, zB), border_color = color.new(#26C6DA, 40), bgcolor = color.new(#26C6DA, 88), text = "layer zone", text_color = color.new(#26C6DA, 20), text_size = size.tiny, text_halign = text.align_right)
if tradeActive and not na(lockedTpPrice) and bar_index > tradeEntryBar
bool tpHit = activeIsBuy ? (high >= lockedTpPrice) : (low <= lockedTpPrice)
bool slHit = activeIsBuy ? (low <= lockedSlPrice) : (high >= lockedSlPrice)
if tpHit or slHit
lastResult := tpHit ? "TP HIT 🎉" : "SL HIT ❌"
tradeActive := false
if not na(zBox)
box.set_right(zBox, bar_index)
zBox := na
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🔎 THE PULSE — nine checks on how the trade is holding
// 1 = green (supports the trade) 2 = orange (caution) 3 = red (against it)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
bool live = tradeActive and not na(lockedEntry)
float dirV = activeIsBuy ? 1.0 : -1.0
float slD = live ? math.abs(lockedEntry - lockedSlPrice) : na
float tpD = live ? math.abs(lockedTpPrice - lockedEntry) : na
float pnlV = live ? dirV * (close - lockedEntry) : na
float ddF = (live and pnlV < 0) ? -pnlV / slD : 0.0
float prF = (live and pnlV > 0) ? pnlV / tpD : 0.0
int barsIn = live ? bar_index - tradeEntryBar : 0
f_px(float p) => str.tostring(p, format.mintick)
f_val(int f) => f == 1 ? 1.0 : f == 2 ? 0.5 : 0.0
f_em(int f) => f == 1 ? "🟢" : f == 2 ? "🟠" : f == 3 ? "🔴" : "⚪"
f_col(int f) => f == 1 ? color.rgb(46, 204, 113) : f == 2 ? color.rgb(245, 166, 35) : f == 3 ? color.rgb(255, 82, 82) : color.rgb(150, 150, 160)
// 1. Position — where price sits between entry, TP and SL
int fPos = not live ? 0 : (pnlV >= 0 ? 1 : (ddF < 0.25 ? 1 : (ddF < 0.6 ? 2 : 3)))
string tPos = not live ? "—" : (pnlV >= 0 ? "In profit, " + str.tostring(prF * 100, "#") + "% to TP" : (ddF < 0.25 ? "Normal dip, " : "Drawdown ") + str.tostring(ddF * 100, "#") + "% of SL")
// 2. Structure — is the swing the trade leans on still intact?
float guardGap = live ? dirV * (close - entryGuard) : na
int fStruct = not live ? 0 : (guardGap <= 0 ? 3 : (guardGap < 0.25 * atrV ? 2 : 1))
string tStruct = not live ? "—" : (fStruct == 3 ? "Broke swing " + f_px(entryGuard) : (fStruct == 2 ? "Testing swing " + f_px(entryGuard) : "Swing " + f_px(entryGuard) + " holding"))
// 3. SL map — is the stop sitting behind that structure?
int fSL = not live ? 0 : (dirV * (entryGuard - lockedSlPrice) >= 0 ? 1 : 2)
string tSL = not live ? "—" : (fSL == 1 ? "SL sits behind the swing" : "SL inside the swing (tight)")
// 4. TP path — anything in the way of the target?
bool barrierCleared = not na(entryBarrier) and dirV * (close - entryBarrier) > 0
int fTP = not live ? 0 : ((na(entryBarrier) or barrierCleared) ? 1 : 2)
string tTP = not live ? "—" : (fTP == 1 ? "Path to TP is clear" : "Barrier " + f_px(entryBarrier) + " before TP")
// 5. Momentum — price vs 21 EMA, RSI, and EMA 9/21 alignment
bool alP = dirV * (close - mS21) > 0
bool alR = dirV * (rsiV - 50) > 0
bool alF = dirV * (mF9 - mS21) > 0
int momCnt = (alP ? 1 : 0) + (alR ? 1 : 0) + (alF ? 1 : 0)
int fMom = not live ? 0 : ((momCnt == 3 or (momCnt == 2 and alP)) ? 1 : (momCnt == 0 ? 3 : 2))
string tMom = not live ? "—" : (fMom == 1 ? "Momentum with you" : (fMom == 3 ? "Momentum against you" : "Momentum mixed"))
// 6. Trend — the timeframe 4x your chart
bool htfWith = activeIsBuy ? htfUp : htfDn
bool htfOpp = activeIsBuy ? htfDn : htfUp
int fHtf = not live ? 0 : (htfWith ? 1 : (htfOpp ? 3 : 2))
string tHtf = not live ? "—" : (fHtf == 1 ? "Bigger trend agrees" : (fHtf == 3 ? "Bigger trend against" : "Bigger trend unclear"))
// 7. Strength — ADX / DI
bool diAl = activeIsBuy ? diP > diM : diM > diP
int fStr = not live ? 0 : ((adxV >= 20 and diAl) ? 1 : ((adxV >= 25 and not diAl) ? 3 : 2))
string tStr = not live ? "—" : (fStr == 1 ? "Trending your way" : (fStr == 3 ? "Strong trend against" : (adxV < 15 ? "Choppy market" : "Weak trend")))
// 8. Backdrop — the benchmark (DXY / VIX / etc.) that suits your pair
bool benchOk = activeIsBuy ? benchFavorsBuy : benchFavorsSell
if live
benchBad := (benchOk or isCryptoDxyOffline) ? 0 : benchBad + 1
int fBack = not live ? 0 : (benchBad == 0 ? 1 : (benchBad <= gracePeriodBars ? 2 : 3))
string tBack = not live ? "—" : (fBack == 1 ? activeBenchName + " supports it" : (fBack == 2 ? activeBenchName + " wobbling" : activeBenchName + " against it"))
// 9. Pace — rejection candles, stalling, volatility spikes
bool rej1 = barsIn >= 1 and dirV * (open - close) >= 1.2 * atrV
bool rej2 = barsIn >= 2 and dirV * (open[1] - close[1]) >= 1.2 * atrV
bool rej3 = barsIn >= 3 and dirV * (open[2] - close[2]) >= 1.2 * atrV
bool rejected = live and (rej1 or rej2 or rej3)
bool volSpike = atrV > 1.8 * atrAvg
int fPace = not live ? 0 : (rejected ? 3 : ((barsIn > timeoutBars and prF < 0.3) ? (ddF > 0.4 ? 3 : 2) : (volSpike ? 2 : 1)))
string tPace = not live ? "—" : (rejected ? "Strong rejection candle" : ((barsIn > timeoutBars and prF < 0.3) ? "Stalling " + str.tostring(barsIn) + " bars" : (volSpike ? "Volatility spike" : "Normal pace")))
// Health score and verdict
float healthPct = live ? 100.0 * (1.5 * f_val(fPos) + 2.0 * f_val(fStruct) + 0.5 * f_val(fSL) + 0.5 * f_val(fTP) + 1.5 * f_val(fMom) + 1.0 * f_val(fHtf) + 1.0 * f_val(fStr) + 1.0 * f_val(fBack) + 1.0 * f_val(fPace)) / 10.0 : na
bool hardRed = live and (fStruct == 3 or (fMom == 3 and fHtf == 3) or ddF > 0.8 or (fHtf == 3 and ddF >= 0.25))
bool layerOK = live and pnlV < 0 and ddF * 100 >= layerMin and ddF * 100 <= layerMax and fStruct < 3 and fHtf == 1 and fMom < 3 and fStr < 3 and fPace < 3 and healthPct >= layerMinHealth
// 1 = layer, 2 = hold, 3 = expect worse
int verdict = not live ? 0 : ((hardRed or healthPct < 40) ? 3 : (layerOK ? 1 : 2))
int flagState = not live ? 0 : (verdict == 1 ? 4 : (verdict == 3 ? 3 : (healthPct >= 65 ? 1 : 2)))
string verdictText = verdict == 0 ? lastResult : (verdict == 1 ? "LAYER ➕" : (verdict == 3 ? "EXPECT WORSE ⚠️" : (pnlV >= 0 ? "LET IT RUN ✅" : "HOLD — DON'T ADD ⏳")))
string guideText = verdict == 0 ? "Waiting for the next signal" : (verdict == 1 ? "Dip into support, trend intact: one layer is OK" : (verdict == 3 ? "Don't add. Protect the account" : (pnlV >= 0 ? "Healthy: let it run" : "Normal dip: wait, don't add yet")))
color verdictColor = verdict == 1 ? color.rgb(38, 198, 218) : (verdict == 3 ? color.rgb(255, 82, 82) : (verdict == 2 ? (healthPct >= 65 ? color.rgb(46, 204, 113) : color.rgb(245, 166, 35)) : color.rgb(150, 150, 160)))
// ── Chart flags: a labelled flag whenever the picture changes ──
string reasonTxt = fStruct == 3 ? tStruct : (fMom == 3 ? tMom : (fHtf == 3 ? tHtf : (fPace == 3 ? tPace : (fPos == 3 ? tPos : (fStr == 3 ? tStr : (fStruct == 2 ? tStruct : (fMom == 2 ? tMom : (fHtf == 2 ? tHtf : (fPos == 2 ? tPos : "All checks green")))))))))
string reasonShow = reasonTxt == "All checks green" ? reasonTxt : "Watch: " + reasonTxt
int stateKey = flagState * 10 + verdict
if live and (barstate.isconfirmed or replayMode) and stateKey != prevKey
if showFlags
color fc = flagState == 4 ? color.rgb(38, 198, 218) : (flagState == 3 ? color.rgb(255, 82, 82) : (flagState == 2 ? color.rgb(245, 166, 35) : color.rgb(46, 204, 113)))
string head = flagState == 4 ? "🟢 LAYER" : (flagState == 3 ? "🔴 WORSE" : (flagState == 2 ? "🟠 CAUTION" : "🟢 HEALTHY"))
label.new(bar_index, high, head + " " + str.tostring(healthPct, "#") + "%\n" + reasonShow, style = label.style_label_down, color = color.new(fc, 12), textcolor = color.white, size = size.small)
prevKey := stateKey
// Alert fires the moment the box turns green (or red), not at candle close
if live and alertsOn and verdict != prevVerdict and (verdict == 1 or verdict == 3)
alert((verdict == 1 ? "➕ " + syminfo.ticker + " (" + timeframe.period + ") LAYER WINDOW OPEN. Price is in the zone." : "⚠️ " + syminfo.ticker + " (" + timeframe.period + ") Too risky to layer. Don't add."), alert.freq_once_per_bar)
if live and verdict != prevVerdict and barstate.isconfirmed
prevVerdict := verdict
if live and not na(zBox)
box.set_right(zBox, bar_index)
box.set_bgcolor(zBox, verdict == 1 ? color.new(#2ECC71, 66) : (verdict == 3 ? color.new(#FF5252, 84) : color.new(#26C6DA, 90)))
box.set_border_color(zBox, verdict == 1 ? color.new(#2ECC71, 20) : (verdict == 3 ? color.new(#FF5252, 40) : color.new(#26C6DA, 40)))