本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Open Legacy Scoreboard", overlay = true, max_labels_count = 500)
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Counts how many signals reached take profit and how many reached stop loss,
// broken down by day of the week and by which session window they opened in.
// It mirrors the Open Legacy Strategy's entry logic and session settings, and
// uses the same ATR-based TP/SL levels, so set these inputs to match the
// strategy. It tracks its own signals — it cannot read the strategy's trades,
// and it has no knowledge of broker spread, slippage or your pip TP/SL, so
// treat it as a read on signal quality rather than an account statement.
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🌐 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
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ── 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
// ── SIGNAL ENGINE ────────────────────────────────────────────────────────
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.")
waitForClose = input.bool(true, "Wait For Candle Close", group = "Signal Engine")
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")
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
slowEma = ta.ema(close, slowEmaLen)
signalEma = ta.ema(src, 1)
utBuyRaw = ta.crossover(signalEma, utStop) and src > utStop
utSellRaw = ta.crossover(utStop, signalEma) and src < utStop
// FVG Pullback
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
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
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
// ── SESSIONS (match the strategy) ────────────────────────────────────────
useSession = input.bool(true, "Restrict To Trading Session", group = "Sessions")
sessionTime = input.session("0800-1700", "Session Hours (start-end, 24h)", group = "Sessions")
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")
sessionTime2 = input.session("1400-1800", "Second Session Hours (start-end, 24h)", group = "Sessions")
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")
closeAtSessionEnd = input.bool(true, "Close Trades at Session End", group = "Sessions",
tooltip = "Match this to the strategy. On, a trade still open when a session ends is closed and counted there, exactly as the strategy would.")
sessionTz = input.string("Europe/Dublin", "Session Timezone (IANA)", group = "Sessions")
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
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)
bool entryInSession = not useSession or (inWindow1 and f_closesInside(time_close, sessionTime)) or (inWindow2 and f_closesInside(time_close, sessionTime2))
// ⛔ 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
bool confirmed = barstate.isconfirmed or not waitForClose
// 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 buySig = utBuy and okBuyLeg and tfOk and entryInSession and confirmed and not blackoutBlock
bool sellSig = utSell and okSellLeg and tfOk and entryInSession and confirmed and not blackoutBlock
if buySig
lastEntryDir := 1
if sellSig
lastEntryDir := -1
// 🧠 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
// Layer entries count too, so the tally reflects the same number of trades the
// strategy would take. Only one is tracked at a time though: a layer opening
// while an earlier trade is still unresolved is not counted separately.
bool layerBuy = fireNextLayer and layerIsBuy
bool layerSell = fireNextLayer and not layerIsBuy
showSettle = input.bool(false, "Show Settled Outcomes", group = "Display",
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.")
// ── EXITS (mirrors the strategy) ─────────────────────────────────────────
// The strategy's real exits are its PineConnector pip TP/SL, a reversal, or
// session end — NOT the ATR dashed lines, which are cosmetic there. Counting
// against ATR levels was why the tallies never matched. Enter the same pip
// values you use in the strategy's bridge settings.
usePipExits = input.bool(true, "Count Pip TP/SL Exits", group = "Exits & Position Limits",
tooltip = "On: trades are settled at the same pip distances your strategy sends to the broker. Off: they settle only on a reversal or session end.")
tpPips = input.float(4.0, "Take Profit (pips)", minval = 0.01, step = 0.01, group = "Exits & Position Limits")
slPips = input.float(20.0, "Stop Loss (pips)", minval = 0.01, step = 0.01, group = "Exits & Position Limits")
pipPoints = input.int(10, "Points Per Pip", minval = 1, group = "Exits & Position Limits",
tooltip = "How many chart points make one pip for your bridge. 10 suits gold, most indices and 5-decimal FX.")
tpDist = tpPips * pipPoints * syminfo.mintick
slDist = 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
// to find out. Without this, tight targets get recorded as losses even when
// the take profit was reached first.
useIntrabar = input.bool(true, "Resolve Ties With 1-Minute Data", group = "Exits & Position Limits",
tooltip = "On: when one candle reaches both levels, the minute bars inside it decide which came first. Off: ties count as a loss.")
[ltfH, ltfL] = request.security_lower_tf(syminfo.tickerid, "1", [high, low])
// ── COUNTERS ─────────────────────────────────────────────────────────────
// 8 rolling weeks, 14 slots each (7 days x 2 sessions).
// Index = weekSlot * 14 + day * 2 + session.
var array<int> tpHits = array.new_int(112, 0)
var array<int> slHits = array.new_int(112, 0)
var int weekSlot = 0
// Every signal is tracked independently until it reaches TP or SL. The old
// version tracked only one at a time, so any signal firing while an earlier
// one was unresolved went uncounted — which is why the totals did not match
// the number of signals on the chart. Layers and back-to-back signals now all
// register, and each resolves on its own levels.
var array<bool> oIsBuy = array.new_bool(0)
var array<float> oEntry = array.new_float(0)
var array<float> oTp = array.new_float(0)
var array<float> oSl = array.new_float(0)
var array<int> oIdx = array.new_int(0)
f_dayIndex(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
weekNow = weekofyear(time, sessionTz)
var int lastWeek = na
if na(lastWeek)
lastWeek := weekNow
if weekNow != lastWeek
weekSlot := (weekSlot + 1) % 8
for i = 0 to 13
array.set(tpHits, weekSlot * 14 + i, 0)
array.set(slHits, weekSlot * 14 + i, 0)
lastWeek := weekNow
onePositionOnly = input.bool(false, "One Position At A Time", group = "Exits & Position Limits",
tooltip = "Match the strategy's setting of the same name. On, a new entry replaces the open trade instead of adding to it, so only one is ever counted as live.")
pyramidLimit = input.int(100, "Pyramiding (match Properties)", minval = 1, group = "Exits & Position Limits",
tooltip = "Mirrors the strategy's Properties > Pyramiding value. Once this many trades are open at once, further entries are ignored — exactly as TradingView silently rejects them in the strategy. Set it to the same number you use there, or the tallies cannot match.")
countLayers = input.bool(true, "Count Layer Entries", group = "Exits & Position Limits",
tooltip = "On: each layer is tallied as its own trade, since the strategy sends every layer to the broker as a separate position with its own TP/SL. Off: only the first entry of each sequence is counted, which matches how many signals you SEE on the chart.")
bool newBuy = buySig or (layerBuy and countLayers)
bool newSell = sellSig or (layerSell and countLayers)
// Resolve open trades. Walked backwards so removals do not disturb indexes
// still to be checked. A trade closes on whichever comes first: its own TP or
// SL, a reversal signal, or session end — the same three ways the strategy
// closes one.
if array.size(oIsBuy) > 0
for k = array.size(oIsBuy) - 1 to 0
bool isBuy = array.get(oIsBuy, k)
float ent = array.get(oEntry, k)
bool tpHit = usePipExits and (isBuy ? high >= array.get(oTp, k) : low <= array.get(oTp, k))
bool slHit = usePipExits and (isBuy ? low <= array.get(oSl, k) : high >= array.get(oSl, k))
bool revHit = (newSell and isBuy) or (newBuy and not isBuy)
bool endHit = sessionJustEnded and closeAtSessionEnd
if tpHit or slHit or revHit or endHit
bool won = false
if tpHit and not slHit
won := true
else if slHit and not tpHit
won := false
else if tpHit and slHit
// Both reached: walk the minute bars to see which came first.
won := false
if useIntrabar and array.size(ltfH) > 0
float tpL = array.get(oTp, k)
float slL = array.get(oSl, k)
bool done = false
for m = 0 to array.size(ltfH) - 1
if not done
bool mTp = isBuy ? array.get(ltfH, m) >= tpL : array.get(ltfL, m) <= tpL
bool mSl = isBuy ? array.get(ltfL, m) <= slL : array.get(ltfH, m) >= slL
if mTp or mSl
won := mTp and not mSl
done := true
else
// Closed by a reversal or session end, so judged on price.
won := isBuy ? close > ent : close < ent
int idx = array.get(oIdx, k)
if won
array.set(tpHits, idx, array.get(tpHits, idx) + 1)
else
array.set(slHits, idx, array.get(slHits, idx) + 1)
if showSettle
label.new(bar_index, won ? high : low,
(won ? "✓ TP" : "✗ SL") + (tpHit and slHit ? " (tie)" : ""),
style = won ? 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)
array.remove(oIsBuy, k)
array.remove(oEntry, k)
array.remove(oTp, k)
array.remove(oSl, k)
array.remove(oIdx, k)
// 4. Register the new signal.
// Pyramiding is counted the way the STRATEGY counts it, which is not the same
// as how many trades are still running. The strategy has no exit orders, so
// when the broker closes a trade at TP or SL, Pine never finds out — its
// position stays open in its own accounting and keeps blocking new entries
// until a reversal or session end clears it. Counting live trades instead
// frees slots too early, which is what let layer after layer keep firing.
var int pineOpen = 0
var bool lastWasBuy = false
if (newBuy or newSell)
// a reversal clears the strategy's position before the new entry
if (newSell and pineOpen > 0 and lastWasBuy) or (newBuy and pineOpen > 0 and not lastWasBuy)
pineOpen := 0
if sessionJustEnded and closeAtSessionEnd
pineOpen := 0
if blackoutBlock
pineOpen := 0
bool slotFree = pineOpen < pyramidLimit
// With One Position At A Time, a new entry replaces the open trade: settle
// everything still running before registering the new one.
if (newBuy or newSell) and slotFree and onePositionOnly and array.size(oIsBuy) > 0
for k = array.size(oIsBuy) - 1 to 0
bool wasBuy = array.get(oIsBuy, k)
float e = array.get(oEntry, k)
int ix = array.get(oIdx, k)
if (wasBuy ? close > e : close < e)
array.set(tpHits, ix, array.get(tpHits, ix) + 1)
else
array.set(slHits, ix, array.get(slHits, ix) + 1)
array.remove(oIsBuy, k)
array.remove(oEntry, k)
array.remove(oTp, k)
array.remove(oSl, k)
array.remove(oIdx, k)
pineOpen := 0
if (newBuy or newSell) and slotFree
// Attribute the trade to whichever window actually qualified it. Checking
// window 1 first means an overlap is credited to Session 1, matching the
// order the strategy evaluates them in.
bool inS1 = inWindow1 and f_closesInside(time_close, sessionTime)
int slotIdx = weekSlot * 14 + f_dayIndex(time) * 2 + (inS1 ? 0 : 1)
array.push(oIsBuy, newBuy)
array.push(oEntry, close)
array.push(oTp, newBuy ? close + tpDist : close - tpDist)
array.push(oSl, newBuy ? close - slDist : close + slDist)
array.push(oIdx, slotIdx)
pineOpen := pineOpen + 1
lastWasBuy := newBuy
// Layer counter resets, mirroring the strategy exactly. Without these the
// counter keeps climbing and layers keep firing long after the strategy's
// would have stopped — which is what produced counted trades that never
// existed on the strategy's chart.
if sessionJustEnded
activeLayers := 0
activeTrend := 0
if blackoutBlock and barstate.isconfirmed
activeLayers := 0
activeTrend := 0
// ── SIGNAL MARKERS (diagnostic) ──────────────────────────────────────────
// Plots exactly what the scoreboard counted, so a tally that disagrees with
// your chart can be traced to the signal itself rather than guessed at.
// Layer entries are marked separately — they are the usual reason the count
// is higher than the number of plain BUY/SELL labels you can see.
showMarks = input.bool(true, "Show Counted Signals", group = "Display",
tooltip = "Marks every signal this scoreboard counts. If the tally looks too high, turn this on and compare: extra marks almost always come from layer entries or a different Entry Method / Sensitivity than the strategy is using.")
plotshape(showMarks and buySig and slotFree, title = "Counted BUY", style = shape.triangleup, location = location.belowbar, color = color.new(color.green, 0), size = size.tiny)
plotshape(showMarks and sellSig and slotFree, title = "Counted SELL", style = shape.triangledown, location = location.abovebar, color = color.new(color.red, 0), size = size.tiny)
plotshape(showMarks and layerBuy and countLayers and slotFree, title = "Counted BUY layer", style = shape.circle, location = location.belowbar, color = color.new(color.lime, 0), size = size.tiny)
plotshape(showMarks and layerSell and countLayers and slotFree, title = "Counted SELL layer", style = shape.circle, location = location.abovebar, color = color.new(color.maroon, 0), size = size.tiny)
// ── HUD ──────────────────────────────────────────────────────────────────
showHud = input.bool(true, "Show Scoreboard", group = "Display")
weeksBack = input.int(0, "Weeks Back", minval = 0, maxval = 7, group = "Display",
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.")
hudSize = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal"], group = "Display")
txtSize = hudSize == "Tiny" ? size.tiny : hudSize == "Normal" ? size.normal : size.small
var table board = 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 showHud
bg = color.new(#0E1320, 0) // solid, so candles never show through
alt = color.new(#121829, 0)
head = color.new(#18203A, 0)
green = color.rgb(47, 212, 128)
red = color.rgb(255, 93, 108)
dim = color.rgb(118, 126, 146)
viewSlot = (weekSlot - weeksBack + 8) % 8
base = viewSlot * 14
table.cell(board, 0, 0, weeksBack == 0 ? "📅 Day" : "📅 -" + str.tostring(weeksBack) + "w",
text_color = color.rgb(214, 220, 234), bgcolor = head, text_size = txtSize)
table.cell(board, 1, 0, "✅ S1", text_color = green, bgcolor = head, text_size = txtSize)
table.cell(board, 2, 0, "❌ S1", text_color = red, bgcolor = head, text_size = txtSize)
table.cell(board, 3, 0, "✅ S2", text_color = green, bgcolor = head, text_size = txtSize)
table.cell(board, 4, 0, "❌ S2", text_color = red, bgcolor = head, text_size = txtSize)
names = array.from("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
todayIdx = f_dayIndex(time)
for d = 0 to 6
isToday = d == todayIdx and weeksBack == 0
rowBg = isToday ? color.new(#1A2440, 0) : (d % 2 == 0 ? bg : alt)
table.cell(board, 0, d + 1, (isToday ? "▸ " : "") + array.get(names, d),
text_color = isToday ? color.rgb(77, 232, 255) : color.rgb(205, 212, 228),
bgcolor = rowBg, text_size = txtSize)
for sIdx = 0 to 1
idx = base + d * 2 + sIdx
int t = array.get(tpHits, idx)
int l = array.get(slHits, idx)
bool off = sIdx == 1 and not useSession2
table.cell(board, sIdx * 2 + 1, d + 1, off ? "·" : t == 0 ? "–" : str.tostring(t),
text_color = off or t == 0 ? dim : green, bgcolor = rowBg, text_size = txtSize)
table.cell(board, sIdx * 2 + 2, d + 1, off ? "·" : l == 0 ? "–" : str.tostring(l),
text_color = off or l == 0 ? dim : red, bgcolor = rowBg, text_size = txtSize)
int t1 = 0
int l1 = 0
int t2 = 0
int l2 = 0
for d = 0 to 6
t1 := t1 + array.get(tpHits, base + d * 2)
l1 := l1 + array.get(slHits, base + d * 2)
t2 := t2 + array.get(tpHits, base + d * 2 + 1)
l2 := l2 + array.get(slHits, base + d * 2 + 1)
int totT = t1 + t2
int totL = l1 + l2
int totN = totT + totL
winPct = totN > 0 ? math.round(totT / totN * 100) : 0
totCol = totN == 0 ? dim : totT > totL ? green : totT < totL ? red : color.rgb(245, 185, 66)
table.cell(board, 0, 8, totN == 0 ? "🏁 Week" : "🏁 " + str.tostring(winPct) + "%",
text_color = totCol, bgcolor = head, text_size = txtSize)
table.cell(board, 1, 8, str.tostring(t1), text_color = green, bgcolor = head, text_size = txtSize)
table.cell(board, 2, 8, str.tostring(l1), text_color = red, bgcolor = head, text_size = txtSize)
table.cell(board, 3, 8, useSession2 ? str.tostring(t2) : "·", text_color = useSession2 ? green : dim, bgcolor = head, text_size = txtSize)
table.cell(board, 4, 8, useSession2 ? str.tostring(l2) : "·", text_color = useSession2 ? red : dim, bgcolor = head, text_size = txtSize)
// Blank spacer row so chart footers (news markers, the TradingView bar)
// cannot sit over the Week totals.
for col = 0 to 4
table.cell(board, col, 9, " ", bgcolor = color.new(color.black, 100), text_size = txtSize)