Open Legacy Bot

Dan-Dynasty · strategy · 1000 行 · 点赞 13 · TradingView 原页

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

Pine Script

//@version=6
strategy("Open Legacy Bot", overlay = true, initial_capital = 10000,
         default_qty_type = strategy.fixed, default_qty_value = 1, pyramiding = 100,
         calc_on_every_tick = true, process_orders_on_close = true, max_labels_count = 500)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🤖 OPEN LEGACY BOT — one script, one set of settings
// Replaces Open Legacy Strategy + Strategy Notifier + Scoreboard.
//  • Trades: sends PineConnector commands to MT5 (unchanged logic).
//  • Phone notifications: every entry carries a plain comment ("BUY",
//    "SELL", "BUY 2", "SELL 2"…). A TradingView alert can only send ONE
//    message to all its channels, and PineConnector needs exact syntax, so
//    use two alerts on this one script:
//      Alert 1 — "Order fills and alert() function calls", message
//                {{strategy.order.alert_message}}, webhook ON (PineConnector)
//      Alert 2 — "Order fills only", message
//                {{ticker}} {{strategy.order.comment}}, push ON, webhook OFF
//    Alert 2 reads e.g. "XAUUSD SELL 2" and only fires on real fills.
//  • Scoreboard: weekly TP/SL HUD, bottom right — see the end of the script.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ⏱️ TIMEFRAME LOCK
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
lockToTf    = input.bool(true, "Lock To Preferred Timeframe", group = "Signal Engine")
preferredTf = input.timeframe("15", "Preferred Timeframe", group = "Signal Engine")
bool tfOk   = not lockToTf or timeframe.period == preferredTf
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🕒 SESSION / TIME-OF-DAY FILTER
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
useSession  = input.bool(true, "Restrict To Trading Session", group = "Sessions")
sessionTime = input.session("0800-1700", "Session Hours (start-end, 24h)", group = "Sessions")
 
// Day-of-week selection. input.session() can only set TIMES from the
// settings panel — not days — so the days come from checkboxes here and
// get appended to the session string as digits (1=Sun ... 7=Sat), which
// is the format time() expects.
s1Sun = input.bool(false, "Sun", group = "Sessions", inline = "s1a")
s1Mon = input.bool(true,  "Mon", group = "Sessions", inline = "s1a")
s1Tue = input.bool(true,  "Tue", group = "Sessions", inline = "s1a")
s1Wed = input.bool(true,  "Wed", group = "Sessions", inline = "s1a")
s1Thu = input.bool(true,  "Thu", group = "Sessions", inline = "s1b")
s1Fri = input.bool(true,  "Fri", group = "Sessions", inline = "s1b")
s1Sat = input.bool(false, "Sat", group = "Sessions", inline = "s1b")
useSession2  = input.bool(false, "Enable Second Session", group = "Sessions",
               tooltip = "For trading two separate windows in the same day — e.g. 0700-1200 in the morning and 1400-1800 in the afternoon. Leave off if you only want one window. Uses the same Session Timezone below, and the same day filter syntax (add :23456 for Mon-Fri).")
sessionTime2 = input.session("1400-1800", "Second Session Hours (start-end, 24h)", group = "Sessions")
closeAtSessionEnd = input.bool(true, "Close Trades at Session End", group = "Sessions",
                    tooltip = "On: every open trade closes when a session ends. Off: trades run on to their own TP or SL, a reversal, or a news blackout — only NEW trades stay limited to your session hours. With this off, set Properties > Pyramiding to at least 2 so a held trade cannot block the next same-direction entry.")
 
s2Sun = input.bool(false, "Sun ", group = "Sessions", inline = "s2a")
s2Mon = input.bool(true,  "Mon ", group = "Sessions", inline = "s2a")
s2Tue = input.bool(true,  "Tue ", group = "Sessions", inline = "s2a")
s2Wed = input.bool(true,  "Wed ", group = "Sessions", inline = "s2a")
s2Thu = input.bool(true,  "Thu ", group = "Sessions", inline = "s2b")
s2Fri = input.bool(true,  "Fri ", group = "Sessions", inline = "s2b")
s2Sat = input.bool(false, "Sat ", group = "Sessions", inline = "s2b")
sessionTz   = input.string("Europe/Dublin", "Session Timezone (IANA)", group = "Sessions",
             tooltip = "e.g. America/New_York (NY session), Europe/London (London session), Asia/Tokyo")
// Two independent windows in the same day, each with its own day filter.
// A window with no days ticked is simply inactive rather than an error.
f_dayDigits(bool su, bool mo, bool tu, bool we, bool th, bool fr, bool sa) =>
    string d = ""
    d := d + (su ? "1" : "")
    d := d + (mo ? "2" : "")
    d := d + (tu ? "3" : "")
    d := d + (we ? "4" : "")
    d := d + (th ? "5" : "")
    d := d + (fr ? "6" : "")
    d := d + (sa ? "7" : "")
    d
 
string s1Days = f_dayDigits(s1Sun, s1Mon, s1Tue, s1Wed, s1Thu, s1Fri, s1Sat)
string s2Days = f_dayDigits(s2Sun, s2Mon, s2Tue, s2Wed, s2Thu, s2Fri, s2Sat)
 
bool inWindow1 = str.length(s1Days) > 0 and not na(time(timeframe.period, sessionTime + ":" + s1Days, sessionTz))
bool inWindow2 = useSession2 and str.length(s2Days) > 0 and not na(time(timeframe.period, sessionTime2 + ":" + s2Days, sessionTz))
bool inSession = not useSession or inWindow1 or inWindow2
 
// Declared here (not further down) because the session-start reset below runs
// before the entry logic and needs these.
bool sessionJustStarted = inSession and not inSession[1]
bool sessionJustEnded   = not inSession and inSession[1]
 
// Entries fire when a candle CLOSES, but the session check above looks at when
// the candle OPENED. Without this, a signal on the last candle of a session
// (e.g. 17:45-18:00) opens a trade exactly at the session end. entryInSession
// requires the candle's close to fall strictly inside the window as well.
f_hm(string s, int p) =>
    int(str.tonumber(str.substring(s, p, p + 2)))
 
f_closesInside(int t, string sess) =>
    int startM = f_hm(sess, 0) * 60 + f_hm(sess, 2)
    int endM   = f_hm(sess, 5) * 60 + f_hm(sess, 7)
    int m      = hour(t, sessionTz) * 60 + minute(t, sessionTz)
    endM > startM ? (m > startM and m < endM) : (m > startM or m < endM)
 
// Also refuse entries inside the last X minutes of a window, so a trade is
// never opened only to be shut by the session-end close a candle later.
f_minsLeft(int t, string sess) =>
    int endM = f_hm(sess, 5) * 60 + f_hm(sess, 7)
    int m    = hour(t, sessionTz) * 60 + minute(t, sessionTz)
    endM > m ? endM - m : 1440 - m + endM
 
// With Close Trades at Session End OFF nothing cuts a late trade short, so the
// window's last candle is allowed. With it ON the entry must close strictly
// inside the window and leave at least one candle of room.
bool room1 = inWindow1 and (not closeAtSessionEnd or (f_closesInside(time_close, sessionTime)  and f_minsLeft(time_close, sessionTime)  > timeframe.in_seconds() / 60))
bool room2 = inWindow2 and (not closeAtSessionEnd or (f_closesInside(time_close, sessionTime2) and f_minsLeft(time_close, sessionTime2) > timeframe.in_seconds() / 60))
bool entryInSession = not useSession or room1 or room2
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ⛔ NEWS BLACKOUTS — up to three specific dates and times. No new trades
// within "Minutes Either Side" of each, and open positions close beforehand.
// The calendar supplies only the DATE; the time comes from the at/: fields,
// built explicitly in the Session Timezone so it can't drift.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
useBlackout    = input.bool(false, "Enable News Blackouts", group = "News Blackouts",
                 tooltip = "Tick a News row, pick the date, and set the time in your Session Timezone. Nothing here does anything while this is off.")
blackoutSide   = input.int(30, "Minutes Either Side", minval = 1, group = "News Blackouts",
                 tooltip = "30 = block from 30 minutes before to 30 minutes after each event.")
closeBeforeMin = input.int(10, "Close Positions Minutes Before", minval = 0, group = "News Blackouts",
                 tooltip = "Closes open positions this long before a blackout starts. 0 = only block new trades. Lands on the nearest candle close for your timeframe.")
n1On   = input.bool(false, "News 1", group = "News Blackouts", inline = "n1")
n1Date = input.time(timestamp("2026-09-29T12:00:00"), "on", group = "News Blackouts", inline = "n1")
n1Hour = input.int(15, "at", minval = 0, maxval = 23, group = "News Blackouts", inline = "n1")
n1Min  = input.int(0, ":", minval = 0, maxval = 59, group = "News Blackouts", inline = "n1")
n2On   = input.bool(false, "News 2", group = "News Blackouts", inline = "n2")
n2Date = input.time(timestamp("2026-10-01T12:00:00"), "on ", group = "News Blackouts", inline = "n2")
n2Hour = input.int(15, "at ", minval = 0, maxval = 23, group = "News Blackouts", inline = "n2")
n2Min  = input.int(0, ": ", minval = 0, maxval = 59, group = "News Blackouts", inline = "n2")
n3On   = input.bool(false, "News 3", group = "News Blackouts", inline = "n3")
n3Date = input.time(timestamp("2026-10-05T12:00:00"), "on  ", group = "News Blackouts", inline = "n3")
n3Hour = input.int(15, "at  ", minval = 0, maxval = 23, group = "News Blackouts", inline = "n3")
n3Min  = input.int(0, ":  ", minval = 0, maxval = 59, group = "News Blackouts", inline = "n3")
 
f_newsTs(int pick, int hh, int mm) =>
    timestamp(sessionTz, year(pick, sessionTz), month(pick, sessionTz), dayofmonth(pick, sessionTz), hh, mm)
 
int n1Ts   = f_newsTs(n1Date, n1Hour, n1Min)
int n2Ts   = f_newsTs(n2Date, n2Hour, n2Min)
int n3Ts   = f_newsTs(n3Date, n3Hour, n3Min)
int sideMs = blackoutSide * 60 * 1000
 
f_inNews(int t, bool on, int ts) =>
    on and t >= ts - sideMs and t < ts + sideMs
 
f_anyBlackout(int t) =>
    f_inNews(t, n1On, n1Ts) or f_inNews(t, n2On, n2Ts) or f_inNews(t, n3On, n3Ts)
 
// time_close = the moment this bar actually closes, which is when entries fire.
bool inBlackout          = useBlackout and f_anyBlackout(time_close)
bool approachingBlackout = useBlackout and closeBeforeMin > 0 and f_anyBlackout(time_close + closeBeforeMin * 60 * 1000)
bool blackoutBlock       = inBlackout or approachingBlackout
 
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ⚙️ SIGNAL ENGINE — same three-tier sensitivity as the Open Legacy indicator
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
waitForClose = input.bool(true, "Wait For Candle Close", group = "Signal Engine",
               tooltip = "On: a signal must survive to the candle close before a trade fires. Off: trades fire the moment the condition is met mid-candle — faster entries, but a signal can appear and then vanish before the candle finishes, so some trades will be taken on conditions that did not hold.")
entryMethod = input.string("UT Bot", "Entry Method", options = ["UT Bot", "FVG Pullback", "Trend", "Grid"], group = "Signal Engine",
              tooltip = "UT Bot — ATR trailing stop crossover. Enters as a move begins.\n\nFVG Pullback — waits for a gap, then enters when price returns into it.\n\nTrend — EMAs and RSI aligned. Fires once per trend leg.\n\nGrid — fades moves, buying dips and selling rallies.")
oneEntryPerLeg = input.bool(false, "One Trade 1 Per Direction", group = "Signal Engine",
                 tooltip = "On: once a Trade 1 has fired, no further Trade 1 in the SAME direction is taken until the direction flips — extra entries in that direction can still come from layers. Useful with Trend mode, where the conditions can drop out and re-align, firing repeated entries instead of a layer.")
signalSensitivity = input.string("Conservative", "Signal Sensitivity", options = ["Conservative", "Balanced", "Aggressive"], group = "Signal Engine",
                    tooltip = "Conservative: fewer, higher-conviction signals. Balanced: the original tuning. Aggressive: faster reactions, more signals.")
 
onePositionOnly = input.bool(false, "One Position At A Time", group = "Signal Engine",
                  tooltip = "On: a layer closes the previous trade before opening, so you still get the Buy 2 / Sell 2 follow-ups but only ever one position is live. Off: layers add to the open position, so several can run at once.")
enableLayers      = input.bool(false, "Enable Layers (Trade 2+)", group = "Signal Engine",
                    tooltip = "Off by default. Layers can be less accurate and laggier than Trade 1 alone — each one fires later, after Trade 1 already opened, chasing a continuation rather than the original crossover. Backtesting on NAS100 has consistently shown them dragging an otherwise profitable Trade 1 back down. Test on your own pair with Strategy Tester before turning this on.")
maxTradeLayers    = input.int(2, "Max Trade Layers", minval = 1, maxval = 15, group = "Signal Engine",
                    tooltip = "How many trades can be active at once, including Trade 1. 1 = Trade 1 only, no scale-in. Each additional layer requires its own structure break, intact pullback, and trend-slope confirmation, same as the original Trade 2 engine — just repeated for as many layers as you allow. IMPORTANT: more layers means more simultaneous open positions — size your lots accordingly.")
scaleInStrictness = input.string("Balanced", "Scale-In Strictness", options = ["Loose", "Balanced", "Strict"], group = "Signal Engine",
                    tooltip = "How strong the trend must be before Trade 2 fires — Strict waits for the clearest continuations, Loose fires sooner. Must match the indicator's setting for signals to align.")
 
keyValue   = signalSensitivity == "Conservative" ? 1.5 : signalSensitivity == "Aggressive" ? 0.7 : 1.0
atrPeriod  = signalSensitivity == "Conservative" ? 12  : signalSensitivity == "Aggressive" ? 7   : 9
slowEmaLen = signalSensitivity == "Conservative" ? 34  : signalSensitivity == "Aggressive" ? 14  : 21
 
src     = close
atrVal  = ta.atr(atrPeriod)
atrAvg  = ta.sma(atrVal, 30)
atrLoss = keyValue * atrVal
 
var float utStop = na
prevStop = nz(utStop[1], src)
if src > prevStop and src[1] > prevStop
    utStop := math.max(prevStop, src - atrLoss)
else if src < prevStop and src[1] < prevStop
    utStop := math.min(prevStop, src + atrLoss)
else
    utStop := src > prevStop ? src - atrLoss : src + atrLoss
 
signalEma = ta.ema(src, 1)
utBuyRaw  = ta.crossover(signalEma, utStop) and src > utStop
utSellRaw = ta.crossover(utStop, signalEma) and src < utStop
 
// ── FVG PULLBACK ─────────────────────────────────────────────────────────
// A fair value gap is an imbalance: price moved so fast that this candle's
// low never overlapped the high from two candles back (bullish), leaving an
// untouched gap.
//   1. GAP     — detect the gap, remember its edges.
//   2. RETURN  — wait for price to trade back into it.
//   3. RESUME  — enter when a candle closes back out in the gap's direction.
// Fires frequently on 1m because gaps form constantly on fast timeframes.
// The bars-valid window stops a stale gap triggering hours later.
fvgLife = signalSensitivity == "Conservative" ? 40 : signalSensitivity == "Aggressive" ? 12 : 24
 
bullGap = low > high[2]
bearGap = high < low[2]
 
var float bullTop = na
var float bullBot = na
var int   bullBar = na
var float bearTop = na
var float bearBot = na
var int   bearBar = na
 
if bullGap
    bullBot := high[2]
    bullTop := low
    bullBar := bar_index
if bearGap
    bearTop := low[2]
    bearBot := high
    bearBar := bar_index
 
bullFresh = not na(bullBar) and bar_index - bullBar <= fvgLife
bearFresh = not na(bearBar) and bar_index - bearBar <= fvgLife
 
fvgBuy  = bullFresh and low <= bullTop and close > open and close > bullBot
fvgSell = bearFresh and high >= bearBot and close < open and close < bearTop
 
if fvgBuy
    bullBar := na
if fvgSell
    bearBar := na
 
// ── TREND (indicator confluence) ─────────────────────────────────────────
// Fast EMA above slow, price above fast, RSI past the midline — all three
// agreeing. Fires on the bar they first agree, not every bar they stay true.
tFastLen = signalSensitivity == "Conservative" ? 21 : signalSensitivity == "Aggressive" ? 8  : 13
tSlowLen = signalSensitivity == "Conservative" ? 55 : signalSensitivity == "Aggressive" ? 21 : 34
tFast = ta.ema(close, tFastLen)
tSlow = ta.ema(close, tSlowLen)
tRsi  = ta.rsi(close, 14)
trUpState = tFast > tSlow and close > tFast and tRsi > 50
trDnState = tFast < tSlow and close < tFast and tRsi < 50
trendBuy  = trUpState and not trUpState[1]
trendSell = trDnState and not trDnState[1]
 
// ── GRID (fixed-interval mean reversion) ─────────────────────────────────
// Fades movement: buys each time price falls a step below the last anchor,
// sells each time it rises a step above. Step is ATR-based so it adapts to
// the instrument instead of using fixed points.
gridMult = signalSensitivity == "Conservative" ? 1.5 : signalSensitivity == "Aggressive" ? 0.7 : 1.0
gridStep = atrVal * gridMult
var float gridAnchor = na
if na(gridAnchor)
    gridAnchor := close
gridBuy  = close <= gridAnchor - gridStep
gridSell = close >= gridAnchor + gridStep
if gridBuy or gridSell
    gridAnchor := close
 
utBuy  = entryMethod == "FVG Pullback" ? fvgBuy : entryMethod == "Trend" ? trendBuy : entryMethod == "Grid" ? gridBuy : utBuyRaw
utSell = entryMethod == "FVG Pullback" ? fvgSell : entryMethod == "Trend" ? trendSell : entryMethod == "Grid" ? gridSell : utSellRaw
 
 
slowEma = ta.ema(close, slowEmaLen)
max_bars_back(slowEma, 50)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🌐 CORRELATION FILTER — same universal inverse-benchmark router as the indicator
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
useCorrFilter = input.bool(true, "Require Correct Correlation", group = "Correlation",
               tooltip = "Confirms the move against DXY/VIX/the relevant index before taking a trade. Auto-detected for whatever you're charting — no manual setup.")
corrEmaLen    = 9
corrConfBars  = 3
 
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
            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]
 
[routedBenchSymbol, routedBenchInverse] = getUniversalInverseBenchmark()
string activeBenchSymbol  = routedBenchSymbol
bool   activeBenchInverse = routedBenchInverse
 
bool isCrypto = syminfo.type == "crypto" or str.contains(syminfo.ticker, "BTC") or str.contains(syminfo.ticker, "ETH")
 
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
 
bool benchFavorsBuy  = activeBenchInverse ? benchBearish : benchBullish
bool benchFavorsSell = activeBenchInverse ? benchBullish : benchBearish
 
bool corrBuyConfirm  = not useCorrFilter or isCrypto or benchFavorsBuy
bool corrSellConfirm = not useCorrFilter or isCrypto or benchFavorsSell
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🧠 TRADE 2 SCALE-IN ENGINE — matches the indicator's engine exactly,
// using the same bulletproof patterns it took several rounds to get right:
// running trackers instead of dynamic-length lookbacks (no historical
// buffer errors possible), and literal preset lengths instead of a
// function-wrapped dynamic value feeding ta.highest/ta.lowest/ta.change
// (no under-buffered runtime errors possible). This is a live-trading
// script, so correctness here matters more than almost anywhere else.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
scaleAtrDistMult   = scaleInStrictness == "Loose" ? 0.4 : scaleInStrictness == "Strict" ? 0.9 : 0.6
maxPullbackAtrMult = scaleInStrictness == "Loose" ? 2.5 : scaleInStrictness == "Strict" ? 1.2 : 1.8
minBarsDelayLayer  = scaleInStrictness == "Loose" ? 2   : scaleInStrictness == "Strict" ? 5   : 3
 
// Generalized layer engine: instead of a fixed "Trade 1 + Trade 2" pair, this
// tracks however many layers are currently active (1 up to Max Trade Layers)
// and re-checks the exact same structure-break + intact-pullback + trend-slope
// + distance + correlation conditions the original Trade 2 always used, each
// time measured from whichever layer opened most recently — so "layer 5"
// requires the same quality of continuation "layer 2" always did, just
// repeated as many times as you've allowed.
var int   activeTrend      = 0
var int   activeLayers     = 0
var bool  layerIsBuy       = false
var int   lastLayerBar     = na
var float lastLayerPrice   = na
var float lowSinceLayer    = na
var float highSinceLayer   = na
 
if utBuy
    activeTrend     := 1
    activeLayers    := 1
    layerIsBuy      := true
    lastLayerBar    := bar_index
    lastLayerPrice  := close
    lowSinceLayer   := low
    highSinceLayer  := high
else if utSell
    activeTrend     := -1
    activeLayers    := 1
    layerIsBuy      := false
    lastLayerBar    := bar_index
    lastLayerPrice  := close
    lowSinceLayer   := low
    highSinceLayer  := high
 
if activeLayers > 0
    lowSinceLayer  := math.min(lowSinceLayer, low)
    highSinceLayer := math.max(highSinceLayer, high)
 
readyNextLayer   = activeLayers > 0 and activeLayers < maxTradeLayers and (bar_index - lastLayerBar >= minBarsDelayLayer)
distFromLastLayer = na(lastLayerPrice) ? 9999.0 : math.abs(close - lastLayerPrice)
 
pullbackDepthBuy  = na(lastLayerPrice) ? 0.0 : (lastLayerPrice - lowSinceLayer) / atrVal
pullbackDepthSell = na(lastLayerPrice) ? 0.0 : (highSinceLayer - lastLayerPrice) / atrVal
trendIntactBuy  = pullbackDepthBuy  <= maxPullbackAtrMult
trendIntactSell = pullbackDepthSell <= maxPullbackAtrMult
 
structHighBreakLoose  = ta.highest(high[1], 3)
structHighBreakBal    = ta.highest(high[1], 4)
structHighBreakStrict = ta.highest(high[1], 6)
structLowBreakLoose   = ta.lowest(low[1], 3)
structLowBreakBal     = ta.lowest(low[1], 4)
structLowBreakStrict  = ta.lowest(low[1], 6)
 
structHighBreak = scaleInStrictness == "Loose" ? structHighBreakLoose : scaleInStrictness == "Strict" ? structHighBreakStrict : structHighBreakBal
structLowBreak  = scaleInStrictness == "Loose" ? structLowBreakLoose  : scaleInStrictness == "Strict" ? structLowBreakStrict  : structLowBreakBal
structureBreakBuy  = close > structHighBreak
structureBreakSell = close < structLowBreak
 
slowEmaChangeLoose  = ta.change(slowEma, 4)
slowEmaChangeBal    = ta.change(slowEma, 6)
slowEmaChangeStrict = ta.change(slowEma, 9)
slowEmaChangeSel = scaleInStrictness == "Loose" ? slowEmaChangeLoose : scaleInStrictness == "Strict" ? slowEmaChangeStrict : slowEmaChangeBal
slowEmaRising  = slowEmaChangeSel > 0
slowEmaFalling = slowEmaChangeSel < 0
 
nextLayerTriggerBuy  = layerIsBuy     and structureBreakBuy  and trendIntactBuy  and slowEmaRising  and distFromLastLayer >= atrVal * scaleAtrDistMult and corrBuyConfirm
nextLayerTriggerSell = not layerIsBuy and structureBreakSell and trendIntactSell and slowEmaFalling and distFromLastLayer >= atrVal * scaleAtrDistMult and corrSellConfirm
 
// tfOk/inSession gate layers the same way they gate Trade 1 — otherwise a
// layer could fire well outside your session window, as long as Trade 1
// itself had opened inside it.
bool fireNextLayer = enableLayers and readyNextLayer and (nextLayerTriggerBuy or nextLayerTriggerSell) and tfOk and entryInSession and (barstate.isconfirmed or not waitForClose) and not blackoutBlock
 
if fireNextLayer
    activeLayers   := activeLayers + 1
    lastLayerBar   := bar_index
    lastLayerPrice := close
    lowSinceLayer  := low
    highSinceLayer := high
 
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🔌 PINECONNECTOR BRIDGE — edit these anytime from your phone, no alert box editing needed
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
licenseId      = input.string("YourLicenseID", "PineConnector License ID", group = "Broker Bridge")
symbolOverride = input.string("", "MT5 Symbol Override (blank = use chart symbol)", group = "Broker Bridge",
                tooltip = "If your broker uses a different symbol name than the chart (e.g. XAUUSD.a), type it here exactly as it appears in MT5's Market Watch.")
lotSize        = input.float(0.2, "Lot Size", minval = 0.01, step = 0.01, group = "Broker Bridge")
slPips         = input.float(20.0, "Stop Loss (pips)", minval = 0.01, step = 0.01, group = "Broker Bridge",
                 tooltip = "PineConnector defines 1 pip on Gold/BTC as $0.10 — check the info icon for exact math on your instrument.")
tpPips         = input.float(4.0, "Take Profit (pips)", minval = 0.01, step = 0.01, group = "Broker Bridge",
                 tooltip = "PineConnector defines 1 pip on Gold/BTC as $0.10 — check the info icon for exact math on your instrument.")
 
useBacktestExits = input.bool(false, "Apply TP/SL Inside Backtest", group = "Broker Bridge",
                   tooltip = "OFF for live trading: your real TP/SL live on the broker via the pips above, and the Strategy Tester ignores them. Turn ON only to backtest — it adds real exit orders at those pip distances so the tester resolves which level is hit first. Leave it off when trading live, since these exits would also fire order-fill alerts.")
pipPoints        = input.int(10, "Points Per Pip", minval = 1, group = "Broker Bridge",
                   tooltip = "How many chart points make one pip on this instrument, matching your bridge's convention. 10 suits gold (1 pip = $0.10) and 5-decimal FX. Used by the Scoreboard's TP/SL tally, and by the backtest exits when the setting above is on. It never changes what is sent to MT5.")
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ⏸️ AUTO PAUSE / RESUME EA WITH SESSION
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
useAutoPause = input.bool(true, "Auto Pause/Resume EA With Session", group = "Exits & Position Limits",
              tooltip = "Sends 'eaon' the moment the session starts and 'eaoff' the moment it ends, using the Session Hours above.")
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🎯 CHART RISK ENGINE — a visual reference only, drawn with lines rather than
// a real strategy.exit() position. Your REAL MT5 trade's actual TP/SL is
// governed entirely by the Stop Loss (pips) / Take Profit (pips) fields
// above, sent straight to PineConnector at entry and held on the broker's
// side from that point — this reference has no connection to it and never
// generates its own order fill, so it can never fire an unwanted alert.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
autoScaleRisk = input.bool(true, "Auto-Adapt Chart TP/SL To Asset Scale", group = "Risk Levels (visual)")
tpAtrMult     = input.float(1.3, "TP ATR Multiplier", minval = 0.5, step = 0.00001, group = "Risk Levels (visual)")
slAtrMult     = input.float(2.2, "SL ATR Multiplier", minval = 0.5, step = 0.00001, group = "Risk Levels (visual)")
manualMinTp   = input.float(3.0, "Manual Min TP Target", minval = 0.00001, step = 0.00001, group = "Risk Levels (visual)",
                tooltip = "In the instrument's own price units — dollars for XAUUSD, index points for NAS100, etc. Not a universal pip value; recalibrate per instrument.")
manualMaxTp   = input.float(8.0, "Manual Max TP Target", minval = 0.00001, step = 0.00001, group = "Risk Levels (visual)",
                tooltip = "In the instrument's own price units — dollars for XAUUSD, index points for NAS100, etc. Not a universal pip value; recalibrate per instrument.")
manualMinSl   = input.float(8.0, "Manual Min SL Target", minval = 0.00001, step = 0.00001, group = "Risk Levels (visual)",
                tooltip = "In the instrument's own price units — dollars for XAUUSD, index points for NAS100, etc. Not a universal pip value; recalibrate per instrument.")
manualMaxSl   = input.float(15.0, "Manual Max SL Target", minval = 0.00001, step = 0.00001, group = "Risk Levels (visual)",
                tooltip = "In the instrument's own price units — dollars for XAUUSD, index points for NAS100, etc. Not a universal pip value; recalibrate per instrument.")
 
float autoMinTp = close * 0.0008
float autoMaxTp = close * 0.0025
float autoMinSl = close * 0.0018
float autoMaxSl = close * 0.0045
 
minTpPoints = autoScaleRisk ? autoMinTp : manualMinTp
maxTpPoints = autoScaleRisk ? autoMaxTp : manualMaxTp
minSlPoints = autoScaleRisk ? autoMinSl : manualMinSl
maxSlPoints = autoScaleRisk ? autoMaxSl : manualMaxSl
 
volatilityRatio = atrVal / atrAvg
finalTpDist = math.min(math.max(atrVal * tpAtrMult * volatilityRatio, minTpPoints), maxTpPoints)
finalSlDist = math.min(math.max(atrVal * slAtrMult, minSlPoints), maxSlPoints)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 📨 PINECONNECTOR MESSAGE BUILDER
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
symbolForMt5 = symbolOverride == "" ? syminfo.ticker : symbolOverride
 
f_pcOrder(string action) =>
    // Explicit number formatting. str.tostring() without a format argument can
    // emit floating-point artifacts (e.g. "500.00000000001" instead of "500"),
    // which the bridge rejects as a malformed command. Fixed decimals prevent
    // that entirely.
    licenseId + "," + action + "," + symbolForMt5 + ",vol_lots=" + str.tostring(lotSize, "#.##") +
     ",sl_pips=" + str.tostring(slPips, "#.##") + ",tp_pips=" + str.tostring(tpPips, "#.##")
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🚀 ENTRY (fires the "Order fills only" alert — PineConnector's actual
// trade command). No strategy.exit() exists anymore, so this trigger type
// can now ONLY ever fire on genuine new entries — nothing else to silence.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Trade 1 is NOT gated by correlation — matching the indicator exactly,
// where buy1/sell1 fire purely on the UT Bot crossover. Correlation only
// ever gates Trade 2's trigger there, never Trade 1. Gating Trade 1 on
// correlation here was an assumption I added when first building this
// strategy that was never true of the indicator — removed for real parity.
// barstate.isconfirmed prevents any signal from flashing true on a still-
// forming, unconfirmed bar and then quietly reversing before that bar
// actually closes — labels/alerts only ever reflect a genuinely closed bar.
// Suppress a repeat Trade 1 in the same direction until the direction flips.
var int lastEntryDir = 0
bool okBuyLeg  = not oneEntryPerLeg or lastEntryDir != 1
bool okSellLeg = not oneEntryPerLeg or lastEntryDir != -1
 
bool longCondition  = utBuy  and okBuyLeg and tfOk and entryInSession and (barstate.isconfirmed or not waitForClose) and not blackoutBlock
bool shortCondition = utSell and okSellLeg and tfOk and entryInSession and (barstate.isconfirmed or not waitForClose) and not blackoutBlock
 
if longCondition
    lastEntryDir := 1
if shortCondition
    lastEntryDir := -1
 
var line  tpLine     = na
var line  slLine     = na
var float refTp      = na
var float refSl      = na
var bool  refIsLong   = false
var bool  refActive   = false
var int   refEntryBar = na
 
// Before every new entry, close the OPPOSITE direction on MT5 — always, not
// only when the script thinks a position is open. If a close was ever missed
// (EA paused, connection drop), the script and MT5 disagree about what's open;
// sending the close unconditionally means MT5 can never hold a buy and a sell
// at once. Closing a direction with nothing open is harmless.
// Before opening the opposite direction, close whatever is currently open
// on MT5 — otherwise a reversal signal adds a second, separate position
// rather than replacing the first one.
// Closes fire on the RAW reversal signal, not on the filtered entry condition.
// The entry conditions also require session, timeframe and blackout checks to
// pass — so a reversal occurring outside your session would previously send no
// close at all, leaving the old position open. A reversal now always closes
// what is open, whether or not a new trade is allowed to replace it.
closeOnRawReversal = input.bool(false, "Close On Any Opposite Signal", group = "Sessions",
                     tooltip = "Off (recommended): a position is only closed when an opposite signal is one the strategy would actually trade. On: ANY opposite signal closes it, including ones blocked by your session, blackout or other filters — safer if you hold trades past a session, but it will close trades on signals you never see traded.")
 
bool revSell = closeOnRawReversal ? utSell : shortCondition
bool revBuy  = closeOnRawReversal ? utBuy  : longCondition
 
if revSell and strategy.position_size > 0
    alert(licenseId + ",closelong," + symbolForMt5, alert.freq_once_per_bar)
    // Pine-side close removed: it printed "Closed position order" over the
    // chart. The alert above already tells MT5 to close, which is what counts.
if revBuy and strategy.position_size < 0
    alert(licenseId + ",closeshort," + symbolForMt5, alert.freq_once_per_bar)
    // Pine-side close removed: it printed "Closed position order" over the
    // chart. The alert above already tells MT5 to close, which is what counts.
 
if longCondition
    strategy.entry("Long", strategy.long, comment = "BUY", alert_message = f_pcOrder("buy"))
    if not na(tpLine)
        line.delete(tpLine)
    if not na(slLine)
        line.delete(slLine)
    refTp      := close + finalTpDist
    refSl      := close - finalSlDist
    refIsLong  := true
    refActive  := true
    refEntryBar := bar_index
    tpLine := line.new(bar_index, refTp, bar_index + 1, refTp, extend = extend.right, color = color.green, width = 2, style = line.style_dashed)
    slLine := line.new(bar_index, refSl, bar_index + 1, refSl, extend = extend.right, color = color.red, width = 2, style = line.style_dashed)
 
if shortCondition
    strategy.entry("Short", strategy.short, comment = "SELL", alert_message = f_pcOrder("sell"))
    if not na(tpLine)
        line.delete(tpLine)
    if not na(slLine)
        line.delete(slLine)
    refTp      := close - finalTpDist
    refSl      := close + finalSlDist
    refIsLong  := false
    refActive  := true
    refEntryBar := bar_index
    tpLine := line.new(bar_index, refTp, bar_index + 1, refTp, extend = extend.right, color = color.green, width = 2, style = line.style_dashed)
    slLine := line.new(bar_index, refSl, bar_index + 1, refSl, extend = extend.right, color = color.red, width = 2, style = line.style_dashed)
 
// Additional layers fire as their own, ADDITIONAL positions (dynamic entry
// ID per layer number) — each one scales into the same direction the whole
// sequence already opened, never replaces an earlier layer, and never
// triggers the reversal-close logic since a layer is never opposite to what's
// currently open. Sizing note: every active layer is a SEPARATE position at
// your configured Lot Size — your real total exposure is all of them added
// together, not just one. Size Lot Size accordingly for your Max Trade Layers.
// One trade at a time: a layer replaces the open position instead of adding
// to it, so you still get the Buy 2 / Sell 2 follow-up signal without ever
// holding two in the same direction.
if fireNextLayer and onePositionOnly and strategy.position_size != 0
    alert(licenseId + "," + (layerIsBuy ? "closelong" : "closeshort") + "," + symbolForMt5, alert.freq_once_per_bar)
    // Pine-side close removed: it printed "Closed position order" over the
    // chart. The alert above already tells MT5 to close, which is what counts.
 
if fireNextLayer
    string layerId = (layerIsBuy ? "Long" : "Short") + str.tostring(activeLayers)
    strategy.entry(layerId, layerIsBuy ? strategy.long : strategy.short, comment = (layerIsBuy ? "BUY " : "SELL ") + str.tostring(activeLayers), alert_message = f_pcOrder(layerIsBuy ? "buy" : "sell"))
    label.new(bar_index, layerIsBuy ? low : high, (layerIsBuy ? "BUY " : "SELL ") + str.tostring(activeLayers),
     style = layerIsBuy ? label.style_label_up : label.style_label_down,
     color = layerIsBuy ? color.green : color.red, textcolor = color.white, size = size.small)
    if not na(tpLine)
        line.delete(tpLine)
    if not na(slLine)
        line.delete(slLine)
    refTp      := layerIsBuy ? close + finalTpDist : close - finalTpDist
    refSl      := layerIsBuy ? close - finalSlDist : close + finalSlDist
    refIsLong  := layerIsBuy
    refActive  := true
    refEntryBar := bar_index
    tpLine := line.new(bar_index, refTp, bar_index + 1, refTp, extend = extend.right, color = color.green, width = 2, style = line.style_dashed)
    slLine := line.new(bar_index, refSl, bar_index + 1, refSl, extend = extend.right, color = color.red, width = 2, style = line.style_dashed)
 
// Backtest-only exits. With these on, the Strategy Tester finally models the
// pip TP/SL you actually trade, instead of closing on reversals and session
// ends. Applies to every open entry, layers included.
if useBacktestExits
    strategy.exit("TP/SL", profit = tpPips * pipPoints, loss = slPips * pipPoints)
 
// Clear the reference lines the moment price actually reaches either level —
// purely visual cleanup, no connection to your real MT5 trade either way.
// Gated to bar_index > refEntryBar so a tight level can't resolve on the
// same bar it was drawn, before the lines even had a chance to render.
if refActive and bar_index > refEntryBar
    bool refTpHit = refIsLong ? high >= refTp : low <= refTp
    bool refSlHit = refIsLong ? low <= refSl  : high >= refSl
    if refTpHit or refSlHit
        refActive := false
        if not na(tpLine)
            line.delete(tpLine)
            tpLine := na
        if not na(slLine)
            line.delete(slLine)
            slLine := na
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ⏸️ SESSION-TRIGGERED PAUSE / RESUME (fires "Any alert() function call")
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
if useAutoPause and sessionJustStarted
    alert(licenseId + ",eaon,eaon", alert.freq_once_per_bar)
 
// Holding trades past the session (Close Trades at Session End = off) means a
// held trade normally resolves on its own TP/SL while the script can't see it.
// Clearing at the START of the next session stops the script believing it's
// still in that trade — which would otherwise block the next same-direction
// signal via pyramiding. Closes are sent too, so MT5 can't be left holding it.
 
// eaoff goes one candle AFTER the session-end close, never on the same candle.
// Sent together, the EA could pause first and ignore the close.
// Skipped when trades are being held past the session: a paused EA would ignore
// any later close command (e.g. from a news blackout) for those open trades.
if useAutoPause and closeAtSessionEnd and sessionJustEnded[1] and not inSession
    alert(licenseId + ",eaoff,eaoff", alert.freq_once_per_bar)
 
// Session end must actually CLOSE whatever's open, not just pause new
// entries — otherwise a position from the tail end of one session sits
// open (both in Pine's own accounting AND for real on MT5) straight through
// to the next session, silently eating into Pyramiding capacity it never
// should have had claim to. This runs regardless of useAutoPause, since
// leaving a real position open across the gap is a safety issue, not a
// convenience setting.
if sessionJustEnded and closeAtSessionEnd
    // Both directions, unconditionally, so MT5 is flattened even if it and
    // the script have drifted out of sync about what's open.
    alert(licenseId + ",closelong," + symbolForMt5, alert.freq_once_per_bar)
    alert(licenseId + ",closeshort," + symbolForMt5, alert.freq_once_per_bar)
    // The alert() above only reaches MT5 — it does NOT tell Pine's own
    // internal position/pyramiding accounting that anything closed. Without
    // this, Pine still believes the old position is open going into the
    // next session, and a fresh entry then silently hits the Pyramiding cap
    // trying to add to a "phantom" leftover position that MT5 already closed.
    strategy.close_all(comment = "Session End")
 
// Layers always reset at session end — a trade held overnight never gets new
// layers stacked onto it the next day.
if sessionJustEnded
    activeLayers := 0
    activeTrend  := 0
 
// Blackout close: flatten before (and while inside) a blackout window, and
// reset the layer sequence so nothing resumes mid-sequence afterwards. Sends
// the real close to the broker AND updates Pine's own position accounting.
if blackoutBlock and barstate.isconfirmed
    // Both directions, sent once as the blackout begins rather than every candle.
    if not blackoutBlock[1]
        alert(licenseId + ",closelong," + symbolForMt5, alert.freq_once_per_bar)
        alert(licenseId + ",closeshort," + symbolForMt5, alert.freq_once_per_bar)
    if strategy.position_size != 0
        strategy.close_all(comment = "Blackout")
    activeLayers := 0
    activeTrend  := 0
 
// Session boundary markers — drawn on the exact candle the session starts and
// ends, independently of whether a trade happened there.
showSessionMarks = input.bool(true, "Show Session Start / End Markers", group = "Display")
 
if showSessionMarks and sessionJustStarted
    label.new(bar_index, high, "Session Reset", style = label.style_label_down,
     color = color.new(color.gray, 35), textcolor = color.white, size = size.tiny)
if showSessionMarks and sessionJustEnded
    label.new(bar_index, high, "Session End", style = label.style_label_down,
     color = color.new(color.gray, 35), textcolor = color.white, size = size.tiny)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🎨 VISUALS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
plotshape(longCondition,  title = "BUY",   style = shape.labelup,   location = location.belowbar, color = color.green, text = "BUY",   textcolor = color.white, size = size.small)
plotshape(shortCondition, title = "SELL",  style = shape.labeldown, location = location.abovebar, color = color.red,   text = "SELL",  textcolor = color.white, size = size.small)
plot(utStop, title = "UT Trailing Stop", color = longCondition ? color.green : shortCondition ? color.red : color.gray, linewidth = 1)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 📊 SCOREBOARD — weekly TP / SL tally, bottom-right HUD
// Built into the bot, so it no longer re-calculates its own copy of the
// signals or needs its own settings. It reads the trades this strategy
// ACTUALLY filled (strategy.opentrades), the moment after each fill, so an
// entry TradingView rejects (Pyramiding, capital) is never counted, and the
// Pyramiding / Initial Capital "match Properties" inputs are no longer needed.
// Each counted trade is then judged on the same pip TP/SL the bot sends to
// the broker (Broker Bridge settings), a reversal, or session end.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
sbShowHud     = input.bool(true, "Show Scoreboard", group = "Scoreboard")
sbWeeksBack   = input.int(0, "Weeks Back", minval = 0, maxval = 7, group = "Scoreboard",
                tooltip = "0 shows this week. 1 shows last week, and so on. The last 8 weeks are kept while the script stays loaded; reloading the chart starts the history again.")
sbHudSize     = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal"], group = "Scoreboard")
sbUsePipExits = input.bool(true, "Count Pip TP/SL Exits", group = "Scoreboard",
                tooltip = "On: trades are settled at the Take Profit / Stop Loss (pips) and Points Per Pip set under Broker Bridge — the same distances the bot sends to MT5. Off: they settle only on a reversal or session end.")
sbUseIntrabar = input.bool(true, "Resolve Ties With 1-Minute Data", group = "Scoreboard",
                tooltip = "On: when one candle reaches both levels, the minute bars inside it decide which came first. Off: ties count as a loss.")
sbCountLayers = input.bool(true, "Count Layer Entries", group = "Scoreboard",
                tooltip = "On: each layer is tallied as its own trade, since the bot sends every layer to the broker as a separate position with its own TP/SL. Off: only Trade 1 entries are counted.")
sbShowMarks   = input.bool(true, "Show Counted Signals", group = "Scoreboard",
                tooltip = "Marks every entry this scoreboard counted: triangles for Trade 1, circles for layers.")
sbShowSettle  = input.bool(false, "Show Settled Outcomes", group = "Scoreboard",
                tooltip = "Marks each trade on the candle where it settled, as TP or SL, and flags ties where one candle reached both levels. Turn this on to audit the tally against your own chart.")
 
sbTpDist = tpPips * pipPoints * syminfo.mintick
sbSlDist = slPips * pipPoints * syminfo.mintick
 
// Intrabar data. When a candle's range covers both TP and SL, candle data
// alone cannot show which came first — so the minute bars inside it are read.
[sbLtfH, sbLtfL] = request.security_lower_tf(syminfo.tickerid, "1", [high, low])
 
// ── COUNTERS ─────────────────────────────────────────────────────────────
// 8 rolling weeks, 14 slots each (7 days x 2 sessions).
// Index = week * 14 + day * 2 + session.
var array<int> sbTpHits = array.new_int(112, 0)
var array<int> sbSlHits = array.new_int(112, 0)
var int sbWeekSlot = 0
 
var array<bool>  sbOIsBuy = array.new_bool(0)
var array<float> sbOEntry = array.new_float(0)
var array<float> sbOTp    = array.new_float(0)
var array<float> sbOSl    = array.new_float(0)
var array<int>   sbOIdx   = array.new_int(0)
 
f_sbDayIndex(int t) =>
    int d = dayofweek(t, sessionTz)
    d == dayofweek.monday ? 0 : d == dayofweek.tuesday ? 1 : d == dayofweek.wednesday ? 2 : d == dayofweek.thursday ? 3 : d == dayofweek.friday ? 4 : d == dayofweek.saturday ? 5 : 6
 
sbWeekNow = weekofyear(time, sessionTz)
var int sbLastWeek = na
if na(sbLastWeek)
    sbLastWeek := sbWeekNow
if sbWeekNow != sbLastWeek
    sbWeekSlot := (sbWeekSlot + 1) % 8
    for i = 0 to 13
        array.set(sbTpHits, sbWeekSlot * 14 + i, 0)
        array.set(sbSlHits, sbWeekSlot * 14 + i, 0)
    sbLastWeek := sbWeekNow
 
// ── 1. FIND THE FILLS FROM THE PREVIOUS CANDLE ───────────────────────────
// With process_orders_on_close, an entry fills at the close of the candle
// that signalled it, and shows in strategy.opentrades from the next candle.
// Each fill is therefore picked up exactly once, here, one candle later,
// and credited back to the candle it filled on.
bool sbFillBuy    = false
bool sbFillSell   = false
bool sbMarkT1Buy  = false
bool sbMarkT1Sell = false
bool sbMarkLyBuy  = false
bool sbMarkLySell = false
int  sbFillCount  = 0
if strategy.opentrades > 0
    for i = 0 to strategy.opentrades - 1
        if strategy.opentrades.entry_bar_index(i) == bar_index - 1
            string sbId    = strategy.opentrades.entry_id(i)
            bool   sbLayer = sbId != "Long" and sbId != "Short"
            bool   sbBuy   = strategy.opentrades.size(i) > 0
            if sbCountLayers or not sbLayer
                sbFillCount += 1
                if sbBuy
                    sbFillBuy := true
                else
                    sbFillSell := true
                if sbLayer
                    if sbBuy
                        sbMarkLyBuy := true
                    else
                        sbMarkLySell := true
                else
                    if sbBuy
                        sbMarkT1Buy := true
                    else
                        sbMarkT1Sell := true
 
// ── 2. REVERSAL / ONE-POSITION SETTLES (at the fill candle's close) ──────
// A fill in the opposite direction reverses the position, and with One
// Position At A Time any new entry replaces what was open — so those trades
// are judged on price at the close where that happened.
if sbFillCount > 0 and array.size(sbOIsBuy) > 0
    for k = array.size(sbOIsBuy) - 1 to 0
        bool  sbWasBuy = array.get(sbOIsBuy, k)
        bool  sbRev    = (sbWasBuy and sbFillSell) or (not sbWasBuy and sbFillBuy)
        if sbRev or onePositionOnly
            float sbEnt = array.get(sbOEntry, k)
            bool  sbWon = sbWasBuy ? close[1] > sbEnt : close[1] < sbEnt
            int   sbIx  = array.get(sbOIdx, k)
            if sbWon
                array.set(sbTpHits, sbIx, array.get(sbTpHits, sbIx) + 1)
            else
                array.set(sbSlHits, sbIx, array.get(sbSlHits, sbIx) + 1)
            if sbShowSettle
                label.new(bar_index - 1, sbWon ? high[1] : low[1], sbWon ? "✓ TP" : "✗ SL",
                 style = sbWon ? label.style_label_down : label.style_label_up,
                 color = sbWon ? color.new(color.green, 20) : color.new(color.red, 20),
                 textcolor = color.white, size = size.tiny)
            array.remove(sbOIsBuy, k)
            array.remove(sbOEntry, k)
            array.remove(sbOTp, k)
            array.remove(sbOSl, k)
            array.remove(sbOIdx, k)
 
// ── 3. REGISTER THE NEW FILLS ────────────────────────────────────────────
// Credited to the day and session window of the candle they filled on.
// Window 1 is checked first, so an overlap counts as Session 1.
if sbFillCount > 0
    for i = 0 to strategy.opentrades - 1
        if strategy.opentrades.entry_bar_index(i) == bar_index - 1
            string sbId2    = strategy.opentrades.entry_id(i)
            bool   sbLayer2 = sbId2 != "Long" and sbId2 != "Short"
            if sbCountLayers or not sbLayer2
                bool  sbBuy2 = strategy.opentrades.size(i) > 0
                float sbEnt2 = close[1]
                bool  sbInS1 = inWindow1[1] and f_closesInside(time_close[1], sessionTime)
                int   sbSlot = sbWeekSlot * 14 + f_sbDayIndex(time[1]) * 2 + (sbInS1 ? 0 : 1)
                array.push(sbOIsBuy, sbBuy2)
                array.push(sbOEntry, sbEnt2)
                array.push(sbOTp, sbBuy2 ? sbEnt2 + sbTpDist : sbEnt2 - sbTpDist)
                array.push(sbOSl, sbBuy2 ? sbEnt2 - sbSlDist : sbEnt2 + sbSlDist)
                array.push(sbOIdx, sbSlot)
 
// ── 4. RESOLVE OPEN TRADES ON THIS CANDLE ────────────────────────────────
// Walked backwards so removals do not disturb indexes still to be checked.
if array.size(sbOIsBuy) > 0
    for k = array.size(sbOIsBuy) - 1 to 0
        bool  sbIsBuy = array.get(sbOIsBuy, k)
        float sbEnt3  = array.get(sbOEntry, k)
        float sbTpL   = array.get(sbOTp, k)
        float sbSlL   = array.get(sbOSl, k)
        bool  sbTpHit = sbUsePipExits and (sbIsBuy ? high >= sbTpL : low  <= sbTpL)
        bool  sbSlHit = sbUsePipExits and (sbIsBuy ? low  <= sbSlL : high >= sbSlL)
        bool  sbEnd   = sessionJustEnded and closeAtSessionEnd
        if sbTpHit or sbSlHit or sbEnd
            bool sbWon2 = false
            if sbTpHit and not sbSlHit
                sbWon2 := true
            else if sbSlHit and not sbTpHit
                sbWon2 := false
            else if sbTpHit and sbSlHit
                // Both reached: walk the minute bars to see which came first.
                sbWon2 := false
                if sbUseIntrabar and array.size(sbLtfH) > 0
                    bool sbDone = false
                    for m = 0 to array.size(sbLtfH) - 1
                        if not sbDone
                            bool sbMTp = sbIsBuy ? array.get(sbLtfH, m) >= sbTpL : array.get(sbLtfL, m) <= sbTpL
                            bool sbMSl = sbIsBuy ? array.get(sbLtfL, m) <= sbSlL : array.get(sbLtfH, m) >= sbSlL
                            if sbMTp or sbMSl
                                sbWon2 := sbMTp and not sbMSl
                                sbDone := true
            else
                // Closed by session end, so judged on price.
                sbWon2 := sbIsBuy ? close > sbEnt3 : close < sbEnt3
            int sbIx2 = array.get(sbOIdx, k)
            if sbWon2
                array.set(sbTpHits, sbIx2, array.get(sbTpHits, sbIx2) + 1)
            else
                array.set(sbSlHits, sbIx2, array.get(sbSlHits, sbIx2) + 1)
            if sbShowSettle
                label.new(bar_index, sbWon2 ? high : low,
                 (sbWon2 ? "✓ TP" : "✗ SL") + (sbTpHit and sbSlHit ? " (tie)" : ""),
                 style = sbWon2 ? label.style_label_down : label.style_label_up,
                 color = sbWon2 ? color.new(color.green, 20) : color.new(color.red, 20),
                 textcolor = color.white, size = size.tiny)
            array.remove(sbOIsBuy, k)
            array.remove(sbOEntry, k)
            array.remove(sbOTp, k)
            array.remove(sbOSl, k)
            array.remove(sbOIdx, k)
 
// ── COUNTED-ENTRY MARKERS ────────────────────────────────────────────────
// Drawn on the candle the trade filled on (offset -1), same as before.
plotshape(sbShowMarks and sbMarkT1Buy,  title = "Counted BUY",        style = shape.triangleup,   location = location.belowbar, color = color.new(color.green, 0),  size = size.tiny, offset = -1)
plotshape(sbShowMarks and sbMarkT1Sell, title = "Counted SELL",       style = shape.triangledown, location = location.abovebar, color = color.new(color.red, 0),    size = size.tiny, offset = -1)
plotshape(sbShowMarks and sbMarkLyBuy,  title = "Counted BUY layer",  style = shape.circle,       location = location.belowbar, color = color.new(color.lime, 0),   size = size.tiny, offset = -1)
plotshape(sbShowMarks and sbMarkLySell, title = "Counted SELL layer", style = shape.circle,       location = location.abovebar, color = color.new(color.maroon, 0), size = size.tiny, offset = -1)
 
// ── HUD (unchanged layout, colours and position) ─────────────────────────
sbTxtSize = sbHudSize == "Tiny" ? size.tiny : sbHudSize == "Normal" ? size.normal : size.small
 
var table sbBoard = table.new(position.bottom_right, 5, 10, border_width = 1, frame_width = 2,
     frame_color = color.new(#2A3350, 0), border_color = color.new(#1C2334, 0))
 
if barstate.islast and sbShowHud
    sbBg    = color.new(#0E1320, 0)      // solid, so candles never show through
    sbAlt   = color.new(#121829, 0)
    sbHead  = color.new(#18203A, 0)
    sbGreen = color.rgb(47, 212, 128)
    sbRed   = color.rgb(255, 93, 108)
    sbDim   = color.rgb(118, 126, 146)
 
    sbViewSlot = (sbWeekSlot - sbWeeksBack + 8) % 8
    sbBase = sbViewSlot * 14
 
    table.cell(sbBoard, 0, 0, sbWeeksBack == 0 ? "📅 Day" : "📅 -" + str.tostring(sbWeeksBack) + "w",
         text_color = color.rgb(214, 220, 234), bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 1, 0, "✅ S1", text_color = sbGreen, bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 2, 0, "❌ S1", text_color = sbRed,   bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 3, 0, "✅ S2", text_color = sbGreen, bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 4, 0, "❌ S2", text_color = sbRed,   bgcolor = sbHead, text_size = sbTxtSize)
 
    sbNames = array.from("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
    sbTodayIdx = f_sbDayIndex(time)
 
    for d = 0 to 6
        sbIsToday = d == sbTodayIdx and sbWeeksBack == 0
        sbRowBg   = sbIsToday ? color.new(#1A2440, 0) : (d % 2 == 0 ? sbBg : sbAlt)
        table.cell(sbBoard, 0, d + 1, (sbIsToday ? "▸ " : "") + array.get(sbNames, d),
             text_color = sbIsToday ? color.rgb(77, 232, 255) : color.rgb(205, 212, 228),
             bgcolor = sbRowBg, text_size = sbTxtSize)
        for sIdx = 0 to 1
            sbCell = sbBase + d * 2 + sIdx
            int sbT = array.get(sbTpHits, sbCell)
            int sbL = array.get(sbSlHits, sbCell)
            bool sbOff = sIdx == 1 and not useSession2
            table.cell(sbBoard, sIdx * 2 + 1, d + 1, sbOff ? "·" : sbT == 0 ? "–" : str.tostring(sbT),
                 text_color = sbOff or sbT == 0 ? sbDim : sbGreen, bgcolor = sbRowBg, text_size = sbTxtSize)
            table.cell(sbBoard, sIdx * 2 + 2, d + 1, sbOff ? "·" : sbL == 0 ? "–" : str.tostring(sbL),
                 text_color = sbOff or sbL == 0 ? sbDim : sbRed, bgcolor = sbRowBg, text_size = sbTxtSize)
 
    int sbT1 = 0
    int sbL1 = 0
    int sbT2 = 0
    int sbL2 = 0
    for d = 0 to 6
        sbT1 := sbT1 + array.get(sbTpHits, sbBase + d * 2)
        sbL1 := sbL1 + array.get(sbSlHits, sbBase + d * 2)
        sbT2 := sbT2 + array.get(sbTpHits, sbBase + d * 2 + 1)
        sbL2 := sbL2 + array.get(sbSlHits, sbBase + d * 2 + 1)
    int sbTotT = sbT1 + sbT2
    int sbTotL = sbL1 + sbL2
    int sbTotN = sbTotT + sbTotL
    sbWinPct = sbTotN > 0 ? math.round(sbTotT / sbTotN * 100) : 0
    sbTotCol = sbTotN == 0 ? sbDim : sbTotT > sbTotL ? sbGreen : sbTotT < sbTotL ? sbRed : color.rgb(245, 185, 66)
 
    table.cell(sbBoard, 0, 8, sbTotN == 0 ? "🏁 Week" : "🏁 " + str.tostring(sbWinPct) + "%",
         text_color = sbTotCol, bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 1, 8, str.tostring(sbT1), text_color = sbGreen, bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 2, 8, str.tostring(sbL1), text_color = sbRed,   bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 3, 8, useSession2 ? str.tostring(sbT2) : "·", text_color = useSession2 ? sbGreen : sbDim, bgcolor = sbHead, text_size = sbTxtSize)
    table.cell(sbBoard, 4, 8, useSession2 ? str.tostring(sbL2) : "·", text_color = useSession2 ? sbRed   : sbDim, bgcolor = sbHead, text_size = sbTxtSize)
 
    // Blank spacer row so chart footers (news markers, the TradingView bar)
    // cannot sit over the Week totals.
    for col = 0 to 4
        table.cell(sbBoard, col, 9, " ", bgcolor = color.new(color.black, 100), text_size = sbTxtSize)

← 返回列表