Open Legacy Side-Kick

Dan-Dynasty · study · 836 行 · 点赞 3 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator("Open Legacy Side-Kick", overlay = true, max_labels_count = 500, max_boxes_count = 500)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// OPEN LEGACY SIDE-KICK (Scoreboard + Side-Kick) — one indicator, one set of settings.
// Set it up exactly like Open Legacy (same entry method, sensitivity, SL / TP,
// sessions and timezone). It follows the same trades, shows the weekly Scoreboard
// (wins, losses and layers) and runs Side-Kick: a green box and alert when a
// dip is a good place to add one layer. No link to pick — layers feed the Scoreboard directly.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
// ── 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("0130-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("1800-2300", "", 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.")
sbShow    = input.bool(true, "📊 Show Scoreboard", group = G3)
sbPeriod  = input.string("This Week", "📅 Show Results For", options = ["This Week", "Last Week", "2 Weeks Ago", "3 Weeks Ago", "4 Weeks Ago", "Last 2 Weeks", "Last 4 Weeks", "Last 8 Weeks", "Last 12 Weeks", "All Time"], group = G3,
     tooltip = "📅 One week: This Week, Last Week, 2-4 Weeks Ago.\n📈 Several weeks added up: Last 2/4/8/12 Weeks (this week included).\n♾️ All Time: every trade on the chart, best for backtesting.")
showMarks = input.bool(true, "Show Trade Markers", group = G3,
     tooltip = "Marks each counted entry, and where it settled.")
layersOn  = input.bool(true, "➕ Count Layers on the Scoreboard", group = G3,
     tooltip = "Each layer is counted once per trade and uses the same TP and SL as the trade, as the MT5 robot does.")
 
 
// ── 5. PULSE ─────────────────────────────────────────────────────────────
G5 = "5. Layers"
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.")
sendMt5 = input.bool(true, "Send layer to MT5 robot", group = G5,
     tooltip = "Turn on only if you auto-trade with the Open Legacy Webhook EA. When the box turns green, the alert also carries a hidden layer order for the robot (it adds one half-size trade with the same SL and TP).\nIn the alert, add your relay Webhook URL, the same one Open Legacy uses.\nOff = you just get a notification.")
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 bool   layerTaken    = false
var bool   layerAlerted  = false
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
    layerTaken    := false
    layerAlerted  := false
    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 == 3 or (verdict == 1 and not layerAlerted))
    if verdict == 1
        layerAlerted := true
    string layerTag = (sendMt5 and verdict == 1) ? "\nOLL;" + (activeIsBuy ? "BUY" : "SELL") + ";" + syminfo.ticker + ";" + str.tostring(slPips * pipPoints * syminfo.mintick, "#.#####") + ";" + str.tostring(tpPips * pipPoints * syminfo.mintick, "#.#####") : ""
    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.") + layerTag, alert.freq_once_per_bar)
if live and verdict != prevVerdict and barstate.isconfirmed
    prevVerdict := verdict
 
// Hidden layer link for the Scoreboard: +1 (buy) or -1 (sell) on the candle that closes with the box green, once per trade.
// Past candles: TradingView can't replay what happened inside a candle, so a layer is
// counted when the candle's own high/low swept through the layer zone (same rules otherwise).
float ddWorst = live ? math.max(0.0, -dirV * ((dirV == 1 ? low : high) - lockedEntry) / slD) : 0.0
float ddBest  = live ? math.max(0.0, -dirV * ((dirV == 1 ? high : low) - lockedEntry) / slD) : 0.0
bool layerOKh = live and not hardRed and healthPct >= layerMinHealth and fStruct < 3 and fHtf == 1 and fMom < 3 and fStr < 3 and fPace < 3 and ddWorst * 100 >= layerMin and ddBest * 100 <= layerMax
 
// Live latch: varip is not rolled back between ticks, so the layer is remembered the
// instant the window opens, even if the candle later closes without it.
varip int   lkBar = -1
varip float lkVal = 0.0
if barstate.isrealtime and lkBar != bar_index
    lkBar := bar_index
    lkVal := 0.0
float layerLink = 0.0
if barstate.isrealtime
    if live and verdict == 1 and not layerTaken and lkVal == 0.0
        lkVal := activeIsBuy ? 1.0 : -1.0
    layerLink := lkVal
    if barstate.isconfirmed and lkVal != 0.0
        layerTaken := true
// A layer can only open on a candle AFTER the entry candle: the entry candle's own wick happened before the trade existed.
else if live and barstate.isconfirmed and bar_index > tradeEntryBar and (verdict == 1 or layerOKh) and not layerTaken
    layerTaken := true
    layerLink := activeIsBuy ? 1.0 : -1.0
// Fast layers on PAST candles: a layer that opens and the trade ends inside one candle (e.g. a layer a few
// seconds after entry, then TP or SL) never shows as "live" on that candle. 1-minute data shows whether price
// reached the zone BEFORE TP/SL. Same health checks as above, taken from the last live candle. Not used in real time.
[m1Hl, m1Ll] = request.security_lower_tf(syminfo.tickerid, "1", [high, low])
bool exitedNow = tradeActive[1] and not tradeActive and bar_index > tradeEntryBar
if not barstate.isrealtime and barstate.isconfirmed and exitedNow and not layerTaken and live[1] and not hardRed[1] and healthPct[1] >= layerMinHealth and fStruct[1] < 3 and fHtf[1] == 1 and fMom[1] < 3 and fStr[1] < 3 and fPace[1] < 3 and array.size(m1Hl) > 0
    float zStart = lockedEntry - dirV * math.abs(lockedEntry - lockedSlPrice) * layerMin / 100.0
    bool hitZone = false
    bool doneM = false
    for m = 0 to array.size(m1Hl) - 1
        if not doneM
            float mh = array.get(m1Hl, m)
            float ml = array.get(m1Ll, m)
            bool mTp = activeIsBuy ? mh >= lockedTpPrice : ml <= lockedTpPrice
            bool mSl = activeIsBuy ? ml <= lockedSlPrice : mh >= lockedSlPrice
            bool mZn = activeIsBuy ? ml <= zStart : mh >= zStart
            if mZn and (not mTp or mSl)
                hitZone := true
            if mTp or mSl
                doneM := true
    if hitZone
        layerTaken := true
        layerLink := activeIsBuy ? 1.0 : -1.0
plot(layerLink, "Layer link", display = display.none)
 
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)))
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 📊 OPEN LEGACY SCOREBOARD (layers come from the same script)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Signals the Scoreboard replays: the same entries Layer Master follows
bool sigB = buy1
bool sigS = sell1
 
// Scoreboard period -> weeks to add up (0 = all) and weeks back
int sbSpan = switch sbPeriod
    "Last 2 Weeks"  => 2
    "Last 4 Weeks"  => 4
    "Last 8 Weeks"  => 8
    "Last 12 Weeks" => 12
    "All Time"      => 0
    => 1
int sbWeeksBack = switch sbPeriod
    "Last Week"   => 1
    "2 Weeks Ago" => 2
    "3 Weeks Ago" => 3
    "4 Weeks Ago" => 4
    => 0
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// TRADE REPLAY
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
float sbTpDist = tpPips * pipPoints * syminfo.mintick
float sbSlDist = slPips * pipPoints * syminfo.mintick
 
// 1-minute data (loaded once, above) decides which level came first when one candle hits both.
 
// Per week: 7 days x 4 outcomes (0 TP hit, 1 Partial +, 2 Partial -, 3 SL hit).
var array<int> sbOut = array.new_int(28, 0)
// Layers per week: 7 days x 2 (0 win, 1 loss).
var array<int> sbLay = array.new_int(14, 0)
var int sbWeek = 0
f_dayIdx(int t) =>
    int d = dayofweek(t, sessionTz)
    d == dayofweek.sunday ? 6 : d - 2
wkNow = weekofyear(time, sessionTz)
if wkNow != wkNow[1] and bar_index > 0
    sbWeek += 1
    for i = 0 to 27
        array.push(sbOut, 0)
    for i = 0 to 13
        array.push(sbLay, 0)
 
f_record(int et, int kind) =>
    int slot = (sbWeek * 7 + f_dayIdx(et)) * 4 + kind
    array.set(sbOut, slot, array.get(sbOut, slot) + 1)
 
f_recLay(int et, int kind) =>
    int slot = (sbWeek * 7 + f_dayIdx(et)) * 2 + kind
    array.set(sbLay, slot, array.get(sbLay, slot) + 1)
 
f_mark(bool won, string txt, bool atHigh) =>
    if showMarks
        label.new(bar_index, atHigh ? high : low, txt, style = atHigh ? label.style_label_down : label.style_label_up,
             color = won ? color.new(color.green, 20) : color.new(color.red, 20), textcolor = color.white, size = size.tiny)
 
var int   posDir = 0
var float posEnt = na
var int   posEt  = na
var int   posBar = na
var bool  layOpen = false
var float layEnt  = na
 
// Live latch: remembers which level price touched FIRST on the forming candle.
// varip isn't rolled back between ticks, so the result locks the instant price
// touches TP or SL and can't flip if price reverses before the candle closes.
varip int liveBar = -1
varip int liveRes = 0
if barstate.isrealtime and liveBar != bar_index
    liveBar := bar_index
    liveRes := 0
 
// 0. Layer link: counted the MOMENT Side-Kick latches it (live), not at candle close.
//    On past candles it reads the closed value of the previous candle, as before.
if layersOn and posDir != 0 and not layOpen and bar_index > posBar
    float lk = barstate.isrealtime ? layerLink : layerLink[1]
    if (lk == 1.0 and posDir == 1) or (lk == -1.0 and posDir == -1)
        layOpen := true
        layEnt  := barstate.isrealtime ? close : close[1]
        if showMarks
            int lb = barstate.isrealtime ? bar_index : bar_index - 1
            label.new(lb, posDir == 1 ? low[bar_index - lb] : high[bar_index - lb], "+LAYER", style = posDir == 1 ? label.style_label_up : label.style_label_down,
                 color = color.new(color.teal, 20), textcolor = color.white, size = size.tiny)
 
// 1. TP / SL — checked on EVERY tick, so it registers the moment price touches
//    the level, not only at candle close. (The entry candle itself is skipped.)
if posDir != 0 and bar_index > posBar
    float tpL = posEnt + posDir * sbTpDist
    float slL = posEnt - posDir * sbSlDist
    bool tpHit = posDir == 1 ? high >= tpL : low <= tpL
    bool slHit = posDir == 1 ? low <= slL : high >= slL
    if tpHit or slHit
        bool won = tpHit and not slHit
        if barstate.isrealtime and liveRes != 0
            won := liveRes == 1
        else
            if tpHit and slHit and array.size(m1Hl) > 0
                bool done = false
                for m = 0 to array.size(m1Hl) - 1
                    if not done
                        bool mTp = posDir == 1 ? array.get(m1Hl, m) >= tpL : array.get(m1Ll, m) <= tpL
                        bool mSl = posDir == 1 ? array.get(m1Ll, m) <= slL : array.get(m1Hl, m) >= slL
                        if mTp or mSl
                            won := mTp and not mSl
                            done := true
            if barstate.isrealtime
                liveRes := won ? 1 : -1
        // Past candles: a layer that opened and ended inside this exit candle (Side-Kick marks it on the exit candle itself)
        if layersOn and not barstate.isrealtime and not layOpen and ((layerLink == 1.0 and posDir == 1) or (layerLink == -1.0 and posDir == -1))
            layOpen := true
            if showMarks
                label.new(bar_index, posDir == 1 ? low : high, "+LAYER", style = posDir == 1 ? label.style_label_up : label.style_label_down,
                     color = color.new(color.teal, 20), textcolor = color.white, size = size.tiny)
        f_record(posEt, won ? 0 : 3)
        f_mark(won, won ? "✓ TP" : "✗ SL", won == (posDir == 1))
        if layOpen
            f_recLay(posEt, won ? 0 : 1)
            layOpen := false
        posDir := 0
 
// 2. Entries — evaluated at candle close only (signals need the closed candle)
if barstate.isconfirmed
    // an opposite signal closes the open trade first
    int want = sigB ? 1 : sigS ? -1 : 0
    if want != 0 and want != posDir
        if posDir != 0
            bool won3 = (close - posEnt) * posDir > 0
            f_record(posEt, won3 ? 1 : 2)
            f_mark(won3, won3 ? "◐ Partial +" : "◐ Partial -", true)
            if layOpen
                f_recLay(posEt, (close - layEnt) * posDir > 0 ? 0 : 1)
                layOpen := false
        posDir := want
        posEnt := close
        posEt  := time
        posBar := bar_index
        if showMarks
            label.new(bar_index, want == 1 ? low : high, want == 1 ? "BUY" : "SELL", style = want == 1 ? label.style_label_up : label.style_label_down,
                 color = want == 1 ? color.new(color.green, 0) : color.new(color.red, 0), textcolor = color.white, size = size.small)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 📊 SCOREBOARD
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
var table sb = table.new(position.bottom_right, 3, 16, border_width = 1, frame_width = 2,
     frame_color = color.new(#2A3350, 0), border_color = color.new(#1C2334, 0))
 
if (barstate.islastconfirmedhistory or barstate.isrealtime) and sbShow
    bg    = color.new(#0E1320, 0)
    alt   = color.new(#121829, 0)
    head  = color.new(#18203A, 0)
    sub   = color.new(#141B2E, 0)
    green = color.rgb(47, 212, 128)
    red   = color.rgb(255, 93, 108)
    teal  = color.rgb(46, 196, 182)
    amber = color.rgb(245, 185, 66)
    dim   = color.rgb(118, 126, 146)
    ts    = size.small
 
    int lastWk  = sbWeek - sbWeeksBack
    int firstWk = sbSpan == 0 ? 0 : math.max(0, lastWk - sbSpan + 1)
    bool single = sbSpan == 1
    string hdr  = sbSpan == 0 ? "📅 All" : single ? (sbWeeksBack == 0 ? "📅 This Wk" : sbWeeksBack == 1 ? "📅 Last Wk" : "📅 " + str.tostring(sbWeeksBack) + " Wks Ago") : "📅 " + str.tostring(sbSpan) + " Wks"
 
    array<int> win  = array.new_int(7, 0)
    array<int> loss = array.new_int(7, 0)
    array<int> oc   = array.new_int(4, 0)
    if lastWk >= 0
        for w = firstWk to lastWk
            for d = 0 to 6
                for k = 0 to 3
                    int v = array.get(sbOut, (w * 7 + d) * 4 + k)
                    if v > 0
                        if k <= 1
                            array.set(win, d, array.get(win, d) + v)
                        else
                            array.set(loss, d, array.get(loss, d) + v)
                        array.set(oc, k, array.get(oc, k) + v)
 
    table.cell(sb, 0, 0, hdr, text_color = color.rgb(214, 220, 234), bgcolor = head, text_size = ts)
    table.cell(sb, 1, 0, "✅ Wins", text_color = green, bgcolor = head, text_size = ts)
    table.cell(sb, 2, 0, "❌ Losses", text_color = red, bgcolor = head, text_size = ts)
 
    names = array.from("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
    int today = f_dayIdx(time)
    int tw = 0
    int tl = 0
    for d = 0 to 6
        bool isNowDay = d == today and sbWeeksBack == 0 and single
        color rbg = isNowDay ? color.new(#1A2440, 0) : (d % 2 == 0 ? bg : alt)
        int wv = array.get(win, d)
        int lv = array.get(loss, d)
        table.cell(sb, 0, d + 1, (isNowDay ? "▸ " : "") + array.get(names, d),
             text_color = isNowDay ? color.rgb(77, 232, 255) : color.rgb(205, 212, 228), bgcolor = rbg, text_size = ts)
        table.cell(sb, 1, d + 1, wv == 0 ? "-" : str.tostring(wv), text_color = wv == 0 ? dim : green, bgcolor = rbg, text_size = ts)
        table.cell(sb, 2, d + 1, lv == 0 ? "-" : str.tostring(lv), text_color = lv == 0 ? dim : red, bgcolor = rbg, text_size = ts)
        tw += wv
        tl += lv
 
    int totN = tw + tl
    float winPct = totN > 0 ? tw * 100.0 / totN : 0.0
    color totCol = totN == 0 ? dim : winPct > 50 ? green : winPct < 50 ? red : amber
    table.cell(sb, 0, 8, totN == 0 ? (single ? "🏁 Week" : "🏁 Total") : "🏁 " + str.tostring(winPct, "#") + "%", text_color = totCol, bgcolor = head, text_size = ts)
    table.cell(sb, 1, 8, str.tostring(tw), text_color = green, bgcolor = head, text_size = ts)
    table.cell(sb, 2, 8, str.tostring(tl), text_color = red, bgcolor = head, text_size = ts)
 
    table.cell(sb, 0, 9, "📊 Outcome", text_color = color.rgb(214, 220, 234), bgcolor = head, text_size = ts, text_halign = text.align_left)
    table.cell(sb, 1, 9, "Trades", text_color = dim, bgcolor = head, text_size = ts)
    table.cell(sb, 2, 9, "Share", text_color = dim, bgcolor = head, text_size = ts)
    oNames = array.from("🎯 TP Hit", "◐ Partial +", "◐ Partial −", "🛑 SL Hit")
    oCols  = array.from(green, teal, amber, red)
    for k = 0 to 3
        int vt = array.get(oc, k)
        float pct = totN > 0 ? vt * 100.0 / totN : 0.0
        int nb = int(math.round(pct / 20.0))
        string meter = ""
        for q = 1 to 5
            meter += q <= nb ? "▰" : "▱"
        color cc  = array.get(oCols, k)
        color rbg = k % 2 == 0 ? bg : alt
        table.cell(sb, 0, 10 + k, array.get(oNames, k), text_color = cc, bgcolor = rbg, text_size = ts, text_halign = text.align_left)
        table.cell(sb, 1, 10 + k, vt == 0 ? "-" : str.tostring(vt), text_color = vt == 0 ? dim : cc, bgcolor = rbg, text_size = ts)
        table.cell(sb, 2, 10 + k, totN == 0 ? "▱▱▱▱▱" : meter + " " + str.tostring(pct, "#") + "%", text_color = totN == 0 ? dim : cc, bgcolor = sub, text_size = ts, text_halign = text.align_left)
 
    // Layers row (only when the Side-Kick link is switched on)
    int lw = 0
    int ll = 0
    if layersOn and lastWk >= 0
        for w = firstWk to lastWk
            for d = 0 to 6
                lw += array.get(sbLay, (w * 7 + d) * 2)
                ll += array.get(sbLay, (w * 7 + d) * 2 + 1)
    if layersOn
        int lt = lw + ll
        table.cell(sb, 0, 14, lt == 0 ? "➕ Layers" : "➕ Layers " + str.tostring(lw * 100.0 / lt, "#") + "%", text_color = teal, bgcolor = head, text_size = ts, text_halign = text.align_left)
        table.cell(sb, 1, 14, lw == 0 ? "-" : str.tostring(lw), text_color = lw == 0 ? dim : green, bgcolor = head, text_size = ts)
        table.cell(sb, 2, 14, ll == 0 ? "-" : str.tostring(ll), text_color = ll == 0 ? dim : red, bgcolor = head, text_size = ts)
    else
        for col = 0 to 2
            table.cell(sb, col, 14, " ", bgcolor = color.new(color.black, 100), text_size = ts)
 
    // spacer so the TradingView footer never covers the last row
    for col = 0 to 2
        table.cell(sb, col, 15, " ", bgcolor = color.new(color.black, 100), text_size = ts)

← 返回列表