本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Confluence Scorecard", shorttitle = "CONF-SCORE", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
// Confluence Scorecard
// 1) Seven votes, each +1, 0 or -1, read on closed bars: EMA stack, higher-timeframe trend, ADX with the
// leading DI, squeeze momentum sign and slope, above-average volume signed by the candle, a recent regular
// RSI divergence, and the close inside the 0.5-0.786 band of the current swing. The score is their sum.
// 2) BUY when the score reaches the minimum score from below, SELL when it reaches minus the minimum from
// above; by default they alternate. Each label carries every vote in its tooltip. An optional safeguard
// waits for a later close beyond the signal bar's high or low.
// 3) Every signal (every confirmed one, with the safeguard on) opens a hypothetical trade with three targets and
// a stop. The scorecard counts how often TP1, TP2, TP3 and the stop were reached within H bars, and compares
// the TP1 rate, with a Wilson 95% interval, against the same TP1, stop and horizon applied to every closed
// bar: the base rate.
// 4) Context layers, each with its own switch: four moving averages, a Bollinger area, trend candles, ADX dots,
// an auto Fibonacci retracement, floor pivots from a higher timeframe, two sets of swing support and
// resistance (chart timeframe and a higher timeframe) that flip role on a break, a multi-timeframe trend
// card and a fixed-range volume profile.
// Signals, trades, dots, candle colors and levels change only on closed bars, the votes are read only on closed
// bars, and every request.security call returns the last completed bar of the requested timeframe.
// ───────────────────────── Inputs ─────────────────────────
const string gMa = "Moving averages"
const string gBb = "Bollinger area"
const string gTrend = "Trend candles and ADX"
const string gFib = "Auto Fibonacci"
const string gPiv = "Floor pivots"
const string gSr = "Support and resistance"
const string gHtf = "Higher timeframe"
const string gMtf = "Trend card"
const string gVp = "Volume profile"
const string gEng = "Signal engine"
const string gSafe = "Safeguard"
const string gTp = "Take profits and stop"
const string gCard = "Scorecard"
const string gAlert = "Alerts"
ma1On = input.bool(true, "MA 1", inline = "ma1", group = gMa)
ma1Type = input.string("EMA", "", options = ["EMA", "SMA", "WMA", "RMA", "HMA", "VWMA"], inline = "ma1", group = gMa)
ma1Len = input.int(20, "", minval = 2, inline = "ma1", group = gMa)
ma1Col = input.color(#26a69a, "", inline = "ma1", group = gMa, tooltip = "Fast. Its length is also the fast EMA of the trend candles, the trend card and the signal engine, whatever type is drawn here.")
ma2On = input.bool(true, "MA 2", inline = "ma2", group = gMa)
ma2Type = input.string("EMA", "", options = ["EMA", "SMA", "WMA", "RMA", "HMA", "VWMA"], inline = "ma2", group = gMa)
ma2Len = input.int(55, "", minval = 2, inline = "ma2", group = gMa)
ma2Col = input.color(#ff9800, "", inline = "ma2", group = gMa, tooltip = "Mid. Its length is also the mid EMA of the trend candles, the trend card and the signal engine.")
ma3On = input.bool(true, "MA 3", inline = "ma3", group = gMa)
ma3Type = input.string("EMA", "", options = ["EMA", "SMA", "WMA", "RMA", "HMA", "VWMA"], inline = "ma3", group = gMa)
ma3Len = input.int(200, "", minval = 2, inline = "ma3", group = gMa)
ma3Col = input.color(#5c6bc0, "", inline = "ma3", group = gMa, tooltip = "Slow. Its length is also the slow EMA of the signal engine.")
ma4On = input.bool(false, "MA 4", inline = "ma4", group = gMa)
ma4Type = input.string("EMA", "", options = ["EMA", "SMA", "WMA", "RMA", "HMA", "VWMA"], inline = "ma4", group = gMa)
ma4Len = input.int(100, "", minval = 2, inline = "ma4", group = gMa)
ma4Col = input.color(#ab47bc, "", inline = "ma4", group = gMa, tooltip = "Display only.")
bbOn = input.bool(false, "Show Bollinger area", group = gBb, tooltip = "Filled band between basis - multiplier x standard deviation and basis + multiplier x standard deviation of the close; the basis is the SMA of the close.")
bbLen = input.int(20, "Length", minval = 2, group = gBb)
bbMult = input.float(2.0, "Multiplier", minval = 0.1, step = 0.1, group = gBb)
candlesOn = input.bool(true, "Trend candles", group = gTrend, tooltip = "Bull color when the fast EMA is above the mid EMA and the close is above the mid EMA, bear color in the mirror case, gray otherwise. Full color when the ADX is at or above the threshold, faded below it. The forming bar keeps the chart's own colors until it closes.")
adxDotsOn = input.bool(true, "ADX dots", group = gTrend, tooltip = "A dot on the closed bar where the ADX reaches the threshold from below: under the bar when +DI is above -DI, over the bar when -DI is above +DI.")
diLen = input.int(14, "DI length", minval = 1, group = gTrend)
adxSmooth = input.int(14, "ADX smoothing", minval = 1, group = gTrend)
adxThr = input.float(25.0, "ADX threshold", minval = 1, step = 1, group = gTrend)
fibOn = input.bool(true, "Show auto Fibonacci", group = gFib)
fibLen = input.int(144, "Lookback (bars)", minval = 2, maxval = 499, group = gFib, tooltip = "Highest high and lowest low of the last N closed bars. The swing runs from the older extreme to the more recent one, and level r sits at end - r x (end - start). Vote 7 reads the same swing.")
fibExt = input.bool(false, "Add 1.272 and 1.618", group = gFib, tooltip = "Two levels beyond the start of the swing.")
pivOn = input.bool(false, "Show floor pivots", group = gPiv)
pivTf = input.timeframe("D", "Pivot timeframe", group = gPiv, tooltip = "Classic floor pivots P, R1-R3 and S1-S3 from the high, low and close of the previous completed bar of this timeframe. Hidden unless it is above the chart timeframe.")
sr1On = input.bool(true, "S/R #1 (chart timeframe)", group = gSr)
sr2On = input.bool(true, "S/R #2 (higher timeframe)", group = gSr, tooltip = "The same swing rule on the timeframe of the Higher timeframe group, read from its completed bars. Dashed.")
srLeft = input.int(10, "Pivot left bars", minval = 1, maxval = 50, group = gSr)
srRight = input.int(10, "Pivot right bars", minval = 1, maxval = 50, group = gSr, tooltip = "A swing high or low confirms this many bars after its bar. The level is drawn back from the pivot bar on the bar that confirms it, and its dot's tooltip says so.")
srRoleCol = input.bool(false, "Color by role", group = gSr, tooltip = "Off: every level in the line color. On: support in teal, resistance in red.")
srCol = input.color(color.gray, "Line color", group = gSr)
srMaxAtr = input.float(5.0, "Show levels within (ATR)", minval = 0, step = 0.5, group = gSr, tooltip = "Display only, on the last bar: a level farther than this many ATR(14) from the last close is not drawn. Its price, role and breaks are kept and checked as usual, and it is drawn again from its pivot when price comes back within range. 0 = no filter.")
htfIn = input.timeframe("", "Higher timeframe", group = gHtf, tooltip = "Used by S/R #2 and by vote 2. Empty = automatic: a chart up to 15 minutes uses 60, up to 60 minutes 240, below 1 day D, below 1 week W, below 1 month M, otherwise 12M. Ignored unless it is above the chart timeframe.")
mtfOn = input.bool(true, "Show trend card", group = gMtf, tooltip = "Per timeframe, from its last completed bar: Up when the fast EMA is above the mid EMA and the close is above the mid EMA, Down in the mirror case, Flat otherwise; then the ADX. Rows below the chart timeframe are requested but read 'below chart'.")
mtf1 = input.timeframe("15", "Row 1", group = gMtf)
mtf2 = input.timeframe("60", "Row 2", group = gMtf)
mtf3 = input.timeframe("240", "Row 3", group = gMtf)
mtf4 = input.timeframe("D", "Row 4", group = gMtf)
mtf5 = input.timeframe("W", "Row 5", group = gMtf)
vpOn = input.bool(true, "Show volume profile", group = gVp, tooltip = "Last N closed bars. Each bar's volume is spread over the rows its high-low range overlaps, in proportion to the overlap. An approximation from OHLCV bars, not tick data. Nothing is drawn when the symbol reports no volume.")
vpBars = input.int(200, "Bars", minval = 10, maxval = 499, group = gVp)
vpRows = input.int(30, "Rows", minval = 5, maxval = 100, group = gVp)
vpWidth = input.int(40, "Width (bars)", minval = 5, maxval = 200, group = gVp, tooltip = "Length of the row with the most volume, in bars to the right of the last bar.")
vpVa = input.bool(true, "Shade the 70% value area", group = gVp)
minScore = input.int(4, "Minimum score", minval = 1, maxval = 7, group = gEng, tooltip = "BUY when the score of a closed bar reaches this value from below; SELL when it reaches minus this value from above. The score is the sum of the seven votes, -7 to +7.")
alternate = input.bool(true, "Alternate signals", group = gEng, tooltip = "No new BUY until a SELL has printed, and the reverse.")
sigLabelsOn = input.bool(true, "Show BUY/SELL labels", group = gEng, tooltip = "Hover a label to read every vote of its bar.")
sigKeep = input.int(100, "Labels kept", minval = 1, maxval = 150, group = gEng, tooltip = "The oldest BUY/SELL labels beyond this number are deleted, and so are the oldest safeguard marks. The scorecard counts every signal either way.")
sqzLen = input.int(20, "Squeeze momentum length (vote 4)", minval = 2, group = gEng)
volLen = input.int(20, "Volume average length (vote 5)", minval = 1, group = gEng)
volMult = input.float(1.2, "Volume multiple (vote 5)", minval = 0.1, step = 0.1, group = gEng)
rsiLen = input.int(14, "RSI length (vote 6)", minval = 2, group = gEng)
divLeft = input.int(5, "RSI pivot left bars (vote 6)", minval = 1, maxval = 50, group = gEng)
divRight = input.int(5, "RSI pivot right bars (vote 6)", minval = 1, maxval = 50, group = gEng, tooltip = "An RSI pivot confirms this many bars after its bar; a divergence counts from the bar that confirms it.")
divMin = input.int(5, "Min bars between RSI pivots (vote 6)", minval = 1, group = gEng)
divMax = input.int(60, "Max bars between RSI pivots (vote 6)", minval = 2, group = gEng)
divWindow = input.int(10, "Divergence window (vote 6)", minval = 1, maxval = 100, group = gEng, tooltip = "A divergence votes on the bar that confirms it and on the next window - 1 bars.")
sgOn = input.bool(false, "Use safeguard", group = gSafe, tooltip = "A signal is confirmed by the first closed bar among the next N bars that closes above the signal bar's high (BUY) or below its low (SELL) while the score still reaches minimum score - 1 in the signal's direction. When on, the take profits, the stop and the scorecard start at the confirmation close, and a signal that is not confirmed opens no trade.")
sgBars = input.int(3, "Confirmation window (bars)", minval = 1, maxval = 50, group = gSafe)
tpMode = input.string("ATR multiple", "Mode", options = ["Percent", "ATR multiple"], group = gTp, tooltip = "Distances from the entry, which is the close of the signal bar, or of the confirmation bar with the safeguard on. ATR multiple (default): multiples of ta.atr(length) on the entry bar, so the levels scale with the timeframe and the asset. Percent: a share of the entry, the same on every timeframe. Keep TP1 < TP2 < TP3.")
tp1Pct = input.float(1.0, "TP1 %", minval = 0.01, maxval = 50, step = 0.1, group = gTp)
tp2Pct = input.float(2.0, "TP2 %", minval = 0.01, maxval = 50, step = 0.1, group = gTp)
tp3Pct = input.float(3.0, "TP3 %", minval = 0.01, maxval = 50, step = 0.1, group = gTp)
slPct = input.float(1.5, "Stop %", minval = 0.01, maxval = 50, step = 0.1, group = gTp)
atrLen = input.int(14, "ATR length", minval = 1, group = gTp)
tp1Atr = input.float(1.0, "TP1 x ATR", minval = 0.01, step = 0.1, group = gTp)
tp2Atr = input.float(2.0, "TP2 x ATR", minval = 0.01, step = 0.1, group = gTp)
tp3Atr = input.float(3.0, "TP3 x ATR", minval = 0.01, step = 0.1, group = gTp)
slAtr = input.float(1.5, "Stop x ATR", minval = 0.01, step = 0.1, group = gTp)
horizon = input.int(50, "Horizon H (bars)", minval = 1, maxval = 100, group = gTp, tooltip = "A trade that has reached neither the stop nor TP3 after H bars ends as a timeout on that bar. At most 100: the base rate keeps up to 2 x H trades open and steps all of them on every closed bar.")
tpLinesOn = input.bool(true, "Draw levels", group = gTp, tooltip = "Entry, TP1-TP3 and stop lines from the entry bar until the stop, TP3, the next opposite BUY or SELL signal or the horizon, whichever comes first, with a mark on the bar that reaches each level while the trade is drawn.")
tpKeep = input.int(20, "Trades drawn", minval = 1, maxval = 30, group = gTp, tooltip = "Only the last N trades keep their lines and marks. The scorecard counts every trade either way.")
scOn = input.bool(true, "Show scorecard", group = gCard)
scPosIn = input.string("Bottom right", "Position", options = ["Top left", "Top center", "Middle left", "Middle center", "Middle right", "Bottom left", "Bottom center", "Bottom right"], group = gCard, tooltip = "Top right is left out: the trend card sits there.")
textSize = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = gCard, tooltip = "Applies to the scorecard and to the trend card.")
alertMode = input.string("Signals only", "alert() calls", options = ["Signals only", "Every bar close"], group = gAlert, tooltip = "For an alert set on 'Any alert() function call'. Signals only: on the closed bars with a BUY, a SELL or a safeguard confirmation. Every bar close: on every closed bar. Each message carries the score and the seven votes.")
// ───────────────────────── Types ─────────────────────────
// A swing support or resistance level. role: 1 = support (price above it), -1 = resistance (price below it).
// breaks: closed bars that closed through it; the first flips the role, the second removes the level. note
// is the first part of the dot's tooltip and says when the pivot was confirmed. x, xl and lineStyle say where
// and how to draw it: x is the pivot bar's open time, xl is xloc.bar_time. ln and lb are na while the distance
// filter hides the level.
type Level
float price
int role
int breaks = 0
string note
int x
string xl
string lineStyle
line ln
label lb
// A hypothetical trade opened by a signal. hits: the highest target reached before the stop, 0 to 3. drawn:
// its lines still extend. Its lines and marks are deleted once tpKeep newer trades have been drawn.
type Trade
int dir
int bar
float entry
float tp1
float tp2
float tp3
float sl
int hits = 0
bool drawn = false
line lnEntry
line lnTp1
line lnTp2
line lnTp3
line lnSl
array<label> marks
// ───────────────────────── History buffers ─────────────────────────
// The volume profile and the Fibonacci drawing read up to 500 bars back on the last bar only. The runtime
// does not resize buffers on realtime bars, so they are set here; drawings at past bar indices also read the
// time buffer.
max_bars_back(high, 500)
max_bars_back(low, 500)
max_bars_back(close, 500)
max_bars_back(volume, 500)
max_bars_back(time, 500)
// ───────────────────────── Core series ─────────────────────────
// Called on every bar at the global scope, so their history is consistent.
float emaFast = ta.ema(close, ma1Len)
float emaMid = ta.ema(close, ma2Len)
float emaSlow = ta.ema(close, ma3Len)
[diPlus, diMinus, adx] = ta.dmi(diLen, adxSmooth)
float fibHi = ta.highest(high, fibLen)
float fibLo = ta.lowest(low, fibLen)
int fibHiOff = ta.highestbars(high, fibLen)
int fibLoOff = ta.lowestbars(low, fibLen)
float atr = ta.atr(atrLen)
color upCol = #26a69a
color dnCol = #ef5350
color flatCol = color.gray
// Trend state: 1 when the fast EMA is above the mid EMA and the close is above the mid EMA, -1 in the mirror
// case, 0 otherwise (also when a value is na, since comparisons with na are false).
trendOf(float f, float m, float c) =>
f > m and c > m ? 1 : f < m and c < m ? -1 : 0
// ───────────────────────── Moving averages ─────────────────────────
// The type is an input, so each call always runs the same ta.*() function and its history stays consistent;
// the simple qualifiers make the compiler enforce that.
maOf(simple string t, simple int len) =>
switch t
"SMA" => ta.sma(close, len)
"WMA" => ta.wma(close, len)
"RMA" => ta.rma(close, len)
"HMA" => ta.hma(close, len)
"VWMA" => ta.vwma(close, len)
=> ta.ema(close, len)
float ma1 = maOf(ma1Type, ma1Len)
float ma2 = maOf(ma2Type, ma2Len)
float ma3 = maOf(ma3Type, ma3Len)
float ma4 = maOf(ma4Type, ma4Len)
plot(ma1On ? ma1 : na, "MA 1", color = ma1Col)
plot(ma2On ? ma2 : na, "MA 2", color = ma2Col)
plot(ma3On ? ma3 : na, "MA 3", color = ma3Col, linewidth = 2)
plot(ma4On ? ma4 : na, "MA 4", color = ma4Col)
// ───────────────────────── Bollinger area ─────────────────────────
float bbBasis = ta.sma(close, bbLen)
float bbDev = bbMult * ta.stdev(close, bbLen)
pBbUp = plot(bbOn ? bbBasis + bbDev : na, "Bollinger upper", color = color.new(color.gray, 50), display = display.pane)
pBbLo = plot(bbOn ? bbBasis - bbDev : na, "Bollinger lower", color = color.new(color.gray, 50), display = display.pane)
fill(pBbUp, pBbLo, color = color.new(color.gray, 88), title = "Bollinger area")
// ───────────────────────── Trend candles and ADX dots ─────────────────────────
int trendNow = trendOf(emaFast, emaMid, close)
color trendCol = trendNow == 1 ? upCol : trendNow == -1 ? dnCol : flatCol
// Full color when the ADX is at or above the threshold, faded otherwise. The forming bar keeps the chart's own
// colors until it closes.
barcolor(candlesOn and barstate.isconfirmed ? (adx >= adxThr ? trendCol : color.new(trendCol, 60)) : na, title = "Trend candles")
// The ADX reaches the threshold from below on this bar; the dots appear once the bar has closed.
bool adxUp = adx >= adxThr and adx[1] < adxThr
plotshape(adxDotsOn and barstate.isconfirmed and adxUp and diPlus > diMinus, "ADX dot, +DI above -DI", style = shape.circle, location = location.belowbar, color = upCol, size = size.tiny, display = display.pane)
plotshape(adxDotsOn and barstate.isconfirmed and adxUp and diMinus > diPlus, "ADX dot, -DI above +DI", style = shape.circle, location = location.abovebar, color = dnCol, size = size.tiny, display = display.pane)
// ───────────────────────── Floor pivots ─────────────────────────
// The previous completed bar of the pivot timeframe: the expression is offset by one bar and requested with
// lookahead_on, so the values are final and never come from a bar that has not closed.
[pvH, pvL, pvC] = request.security(syminfo.tickerid, pivTf, [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
bool pivOk = pivOn and timeframe.in_seconds(pivTf) > timeframe.in_seconds(timeframe.period)
float pvP = (pvH + pvL + pvC) / 3
float pvR1 = 2 * pvP - pvL
float pvS1 = 2 * pvP - pvH
float pvR2 = pvP + (pvH - pvL)
float pvS2 = pvP - (pvH - pvL)
float pvR3 = pvH + 2 * (pvP - pvL)
float pvS3 = pvL - 2 * (pvH - pvP)
// The lines break on the bar where P changes, so a new period never joins the previous one.
bool pvKeep = pivOk and pvP == pvP[1]
color pvResCol = color.new(dnCol, 30)
color pvSupCol = color.new(upCol, 30)
plot(pvKeep ? pvP : na, "Pivot P", color = color.new(color.gray, 10), style = plot.style_linebr, display = display.pane)
plot(pvKeep ? pvR1 : na, "Pivot R1", color = pvResCol, style = plot.style_linebr, display = display.pane)
plot(pvKeep ? pvR2 : na, "Pivot R2", color = pvResCol, style = plot.style_linebr, display = display.pane)
plot(pvKeep ? pvR3 : na, "Pivot R3", color = pvResCol, style = plot.style_linebr, display = display.pane)
plot(pvKeep ? pvS1 : na, "Pivot S1", color = pvSupCol, style = plot.style_linebr, display = display.pane)
plot(pvKeep ? pvS2 : na, "Pivot S2", color = pvSupCol, style = plot.style_linebr, display = display.pane)
plot(pvKeep ? pvS3 : na, "Pivot S3", color = pvSupCol, style = plot.style_linebr, display = display.pane)
// ───────────────────────── Higher timeframe ─────────────────────────
// The automatic higher timeframe: the next step above the chart timeframe.
autoHtf() =>
int s = timeframe.in_seconds(timeframe.period)
s <= 900 ? "60" : s <= 3600 ? "240" : s < 86400 ? "D" : s < 604800 ? "W" : s < timeframe.in_seconds("1M") ? "M" : "12M"
string htf = htfIn == "" ? autoHtf() : htfIn
bool htfOk = timeframe.in_seconds(htf) > timeframe.in_seconds(timeframe.period)
// Values of the last completed bar of the higher timeframe: its fast and mid EMAs and close, the swing pivots
// it confirmed, its open time, and the open time of the pivot bar. Every element is offset by one bar and
// requested with lookahead_on.
htfPack() =>
[ta.ema(close, ma1Len)[1], ta.ema(close, ma2Len)[1], close[1], ta.pivothigh(high, srLeft, srRight)[1], ta.pivotlow(low, srLeft, srRight)[1], time[1], time[srRight + 1]]
[hEmaF, hEmaM, hClose, hPh, hPl, hBarTime, hPivTime] = request.security(syminfo.tickerid, htf, htfPack(), lookahead = barmerge.lookahead_on)
// True on the chart bar where a new higher-timeframe bar has completed since the previous chart bar.
bool htfNew = not na(hBarTime) and (na(hBarTime[1]) or hBarTime != hBarTime[1])
// ───────────────────────── Support and resistance ─────────────────────────
color supCol = upCol
color resCol = dnCol
fmtTime(int t) =>
na(t) ? "n/a" : str.format_time(t, "yyyy-MM-dd HH:mm", syminfo.timezone)
levelColor(int role) =>
srRoleCol ? (role == 1 ? supCol : resCol) : srCol
levelTip(Level lv) =>
string state = lv.breaks == 0 ? (lv.role == 1 ? "Support. A close below it flips it to resistance." : "Resistance. A close above it flips it to support.") : lv.role == 1 ? "Support since a close above it. A close below it removes it." : "Resistance since a close below it. A close above it removes it."
lv.note + "\n" + state
// Draws a level: a line from its pivot bar extended right, and a small dot in the line's color on the pivot that
// carries the tooltip.
drawLevel(Level lv) =>
color col = levelColor(lv.role)
lv.ln := line.new(lv.x, lv.price, lv.x + 1, lv.price, xloc = lv.xl, extend = extend.right, color = col, style = lv.lineStyle, width = 1)
lv.lb := label.new(lv.x, lv.price, "•", xloc = lv.xl, style = label.style_none, textcolor = col, size = size.tiny, tooltip = levelTip(lv))
// Deletes the drawings of a level, when it has them, and keeps its data. Ends with a void call, so callers can
// use it as the last statement of an if branch.
eraseLevel(Level lv) =>
if not na(lv.ln)
line oldLn = lv.ln
label oldLb = lv.lb
lv.ln := na
lv.lb := na
line.delete(oldLn)
label.delete(oldLb)
// Adds a level at price from bar x and keeps at most maxN levels in arr: the oldest beyond that is deleted. Both
// sets pass the pivot bar's open time with xloc.bar_time, so a level redrawn on the last bar never needs a bar
// index far beyond the history buffers.
addLevel(array<Level> arr, int maxN, float price, int role, int x, string xl, string lineStyle, string note) =>
Level lv = Level.new(price = price, role = role, note = note, x = x, xl = xl, lineStyle = lineStyle)
drawLevel(lv)
array.push(arr, lv)
if array.size(arr) > maxN
eraseLevel(array.shift(arr))
// Applies one closed bar with close c to every level of arr: a close beyond a level breaks it. The first break
// flips the role, the second removes the level. The loop runs backwards because it removes elements. A level
// hidden by the distance filter is broken, flipped and removed the same way; only its drawings are absent.
checkBreaks(array<Level> arr, float c) =>
int n = array.size(arr)
if n > 0 and not na(c)
for i = n - 1 to 0
Level lv = array.get(arr, i)
if (lv.role == -1 and c > lv.price) or (lv.role == 1 and c < lv.price)
lv.breaks += 1
// Both branches end with a void call or a void if, so the if, the function's last statement,
// has one type.
if lv.breaks >= 2
array.remove(arr, i)
eraseLevel(lv)
else
lv.role := -lv.role
if not na(lv.ln)
color col = levelColor(lv.role)
line.set_color(lv.ln, col)
label.set_textcolor(lv.lb, col)
label.set_tooltip(lv.lb, levelTip(lv))
// A swing high or low confirms srRight bars after its bar: its price is high[srRight] or low[srRight].
float srPh = ta.pivothigh(high, srLeft, srRight)
float srPl = ta.pivotlow(low, srLeft, srRight)
// Levels born from pivot highs and from pivot lows: at most 8 of each on the chart timeframe, 4 of each on the
// higher timeframe.
var array<Level> sr1Hi = array.new<Level>()
var array<Level> sr1Lo = array.new<Level>()
var array<Level> sr2Hi = array.new<Level>()
var array<Level> sr2Lo = array.new<Level>()
string srLr = str.tostring(srLeft) + "/" + str.tostring(srRight)
// Chart timeframe: on every closed bar, breaks first, then the pivots that bar confirms. A new level starts
// unbroken with the role that matches price: the confirming bar is the last of the srRight bars that stay
// below a pivot high (above a pivot low), so its close cannot be beyond the level. The same holds for S/R #2
// with the close of the confirming higher-timeframe bar.
if barstate.isconfirmed and sr1On
checkBreaks(sr1Hi, close)
checkBreaks(sr1Lo, close)
string confTxt = ", confirmed " + str.tostring(srRight) + " bars after its bar, when the bar of " + fmtTime(time) + " closed."
if not na(srPh)
addLevel(sr1Hi, 8, srPh, -1, time[srRight], xloc.bar_time, line.style_solid, "Swing high " + str.tostring(srPh, format.mintick) + " (pivot " + srLr + ")" + confTxt)
if not na(srPl)
addLevel(sr1Lo, 8, srPl, 1, time[srRight], xloc.bar_time, line.style_solid, "Swing low " + str.tostring(srPl, format.mintick) + " (pivot " + srLr + ")" + confTxt)
// Higher timeframe: once per completed higher-timeframe bar, on the first closed chart bar after it, with that
// bar's close for the breaks.
if barstate.isconfirmed and sr2On and htfOk and htfNew
checkBreaks(sr2Hi, hClose)
checkBreaks(sr2Lo, hClose)
string confTxt = ", confirmed " + str.tostring(srRight) + " bars of " + htf + " after its bar; added when the chart bar of " + fmtTime(time) + " closed."
if not na(hPh)
addLevel(sr2Hi, 4, hPh, -1, hPivTime, xloc.bar_time, line.style_dashed, htf + " swing high " + str.tostring(hPh, format.mintick) + " (pivot " + srLr + ")" + confTxt)
if not na(hPl)
addLevel(sr2Lo, 4, hPl, 1, hPivTime, xloc.bar_time, line.style_dashed, htf + " swing low " + str.tostring(hPl, format.mintick) + " (pivot " + srLr + ")" + confTxt)
// Distance filter, a display choice made on the last bar only: a level farther than srMaxAtr x ATR(14) from the
// last close is not drawn, and it is drawn again from its pivot when price comes back within range. Its price,
// role and breaks above are untouched. Levels are not votes, so the signals and the scorecard do not depend on
// this filter. While the last bar is forming, the close and the ATR are read one bar back, so the choice changes
// only when a bar closes.
float srAtr = ta.atr(14)
showLevels(array<Level> arr, float ref, float maxDist) =>
int n = array.size(arr)
if n > 0
for i = 0 to n - 1
Level lv = array.get(arr, i)
bool near = na(maxDist) or maxDist <= 0 or math.abs(lv.price - ref) <= maxDist
if not near
eraseLevel(lv)
if near and na(lv.ln)
drawLevel(lv)
if barstate.islast
int offS = barstate.isconfirmed ? 0 : 1
float refClose = close[offS]
float maxDist = srMaxAtr * srAtr[offS]
showLevels(sr1Hi, refClose, maxDist)
showLevels(sr1Lo, refClose, maxDist)
showLevels(sr2Hi, refClose, maxDist)
showLevels(sr2Lo, refClose, maxDist)
// ───────────────────────── Trend card data ─────────────────────────
// Per row, from the last completed bar of that timeframe: fast EMA, mid EMA, close and ADX, each offset by one
// bar and requested with lookahead_on.
trendPack() =>
[dp, dm, a] = ta.dmi(diLen, adxSmooth)
[ta.ema(close, ma1Len)[1], ta.ema(close, ma2Len)[1], close[1], a[1]]
[m1F, m1M, m1C, m1A] = request.security(syminfo.tickerid, mtf1, trendPack(), lookahead = barmerge.lookahead_on)
[m2F, m2M, m2C, m2A] = request.security(syminfo.tickerid, mtf2, trendPack(), lookahead = barmerge.lookahead_on)
[m3F, m3M, m3C, m3A] = request.security(syminfo.tickerid, mtf3, trendPack(), lookahead = barmerge.lookahead_on)
[m4F, m4M, m4C, m4A] = request.security(syminfo.tickerid, mtf4, trendPack(), lookahead = barmerge.lookahead_on)
[m5F, m5M, m5C, m5A] = request.security(syminfo.tickerid, mtf5, trendPack(), lookahead = barmerge.lookahead_on)
// ───────────────────────── Signal engine: votes ─────────────────────────
// Seven votes, each +1, 0 or -1. They are series on every bar, so their history is consistent; signals read
// them only on closed bars.
// Vote 1, EMA stack: fast above mid above slow (+1), fast below mid below slow (-1).
int v1 = emaFast > emaMid and emaMid > emaSlow ? 1 : emaFast < emaMid and emaMid < emaSlow ? -1 : 0
// Vote 2, trend of the last completed higher-timeframe bar with the trend card's rule; 0 when the higher
// timeframe is not above the chart's.
int v2 = htfOk ? trendOf(hEmaF, hEmaM, hClose) : 0
// Vote 3, ADX at or above the threshold with the leading DI.
int v3 = adx >= adxThr and diPlus > diMinus ? 1 : adx >= adxThr and diMinus > diPlus ? -1 : 0
// Vote 4, squeeze momentum: the linear regression over sqzLen bars of the close minus the average of two
// values, the midpoint of the highest high and the lowest low, and the SMA of the close. Above zero and rising
// (+1), below zero and falling (-1).
float sqzMid = math.avg(math.avg(ta.highest(high, sqzLen), ta.lowest(low, sqzLen)), ta.sma(close, sqzLen))
float mom = ta.linreg(close - sqzMid, sqzLen, 0)
int v4 = mom > 0 and mom > mom[1] ? 1 : mom < 0 and mom < mom[1] ? -1 : 0
// Vote 5, volume above volMult times its SMA, signed by the candle: up candle (+1), down candle (-1). A symbol
// with no volume votes 0.
float volAvg = ta.sma(volume, volLen)
bool volHigh = volume > volAvg * volMult
int v5 = volHigh and close > open ? 1 : volHigh and close < open ? -1 : 0
// Vote 6, regular RSI divergence, found as in rsi-divergence-vs-random: pivots of the RSI with ta.pivothigh and
// ta.pivotlow, divLeft bars to the left and divRight to the right, so a pivot confirms divRight bars after its
// bar. With divMin to divMax bars strictly between it and the previous pivot of the same kind: price lower low
// with RSI higher low is bullish, price higher high with RSI lower high is bearish. The previous pivot is
// replaced either way.
float rsi = ta.rsi(close, rsiLen)
float rsiPh = ta.pivothigh(rsi, divLeft, divRight)
float rsiPl = ta.pivotlow(rsi, divLeft, divRight)
var float prevHiRsi = na
var float prevHiPrice = na
var int prevHiBar = na
var float prevLoRsi = na
var float prevLoPrice = na
var int prevLoBar = na
var int bullDivBar = na
var int bearDivBar = na
if barstate.isconfirmed
int pivBar = bar_index - divRight
if not na(rsiPh)
if not na(prevHiBar)
int gap = pivBar - prevHiBar - 1
if gap >= divMin and gap <= divMax and high[divRight] > prevHiPrice and rsiPh < prevHiRsi
bearDivBar := bar_index
prevHiRsi := rsiPh
prevHiPrice := high[divRight]
prevHiBar := pivBar
if not na(rsiPl)
if not na(prevLoBar)
int gap = pivBar - prevLoBar - 1
if gap >= divMin and gap <= divMax and low[divRight] < prevLoPrice and rsiPl > prevLoRsi
bullDivBar := bar_index
prevLoRsi := rsiPl
prevLoPrice := low[divRight]
prevLoBar := pivBar
// A divergence votes on the bar that confirms it and the next divWindow - 1 bars. When both kinds are in the
// window the more recent one votes; two on the same bar cancel out.
bool bullRecent = not na(bullDivBar) and bar_index - bullDivBar < divWindow
bool bearRecent = not na(bearDivBar) and bar_index - bearDivBar < divWindow
int v6 = bullRecent and (not bearRecent or bullDivBar > bearDivBar) ? 1 : bearRecent and (not bullRecent or bearDivBar > bullDivBar) ? -1 : 0
// Vote 7, the close inside the 0.5-0.786 retracement band of the auto Fibonacci swing of the last fibLen bars,
// this one included: in an up swing (the high is the more recent extreme) +1, in a down swing -1.
float fibRng = fibHi - fibLo
bool fibUp = fibHiOff > fibLoOff
bool fibDn = fibHiOff < fibLoOff
int v7 = fibRng > 0 and fibUp and close <= fibHi - 0.5 * fibRng and close >= fibHi - 0.786 * fibRng ? 1 : fibRng > 0 and fibDn and close >= fibLo + 0.5 * fibRng and close <= fibLo + 0.786 * fibRng ? -1 : 0
int score = v1 + v2 + v3 + v4 + v5 + v6 + v7
// Signals and the base rate start once the bar index reaches the longest of the three engine EMAs and the ADX,
// the momentum, the RSI and the ATR have values.
bool ready = bar_index >= math.max(ma1Len, ma2Len, ma3Len) and not na(adx) and not na(mom) and not na(rsi) and not na(atr)
fmtVote(int v) =>
v > 0 ? "+1" : v < 0 ? "-1" : "0"
fmtScore(int s) =>
s > 0 ? "+" + str.tostring(s) : str.tostring(s)
// Every vote of the current bar by name and value, for the label tooltip.
votesText() =>
string s = "Score " + fmtScore(score) + " of 7, bar of " + fmtTime(time)
s += "\n1 EMA stack " + str.tostring(ma1Len) + "/" + str.tostring(ma2Len) + "/" + str.tostring(ma3Len) + ": " + fmtVote(v1)
s += "\n2 Trend of the last closed " + htf + " bar" + (htfOk ? "" : " (not above the chart timeframe)") + ": " + fmtVote(v2)
s += "\n3 ADX " + str.tostring(adx, "0.0") + " vs " + str.tostring(adxThr, "0.#") + ", +DI " + str.tostring(diPlus, "0.0") + ", -DI " + str.tostring(diMinus, "0.0") + ": " + fmtVote(v3)
s += "\n4 Squeeze momentum " + str.tostring(mom, format.mintick) + ": " + fmtVote(v4)
s += "\n5 Volume " + (na(volAvg) or volAvg == 0 ? "n/a" : str.tostring(volume / volAvg, "0.00") + " x average") + ": " + fmtVote(v5)
string divTxt = v6 == 1 ? " (bullish, confirmed " + str.tostring(bar_index - bullDivBar) + " bars ago)" : v6 == -1 ? " (bearish, confirmed " + str.tostring(bar_index - bearDivBar) + " bars ago)" : ""
s += "\n6 RSI divergence in the last " + str.tostring(divWindow) + " bars" + divTxt + ": " + fmtVote(v6)
s += "\n7 Close in the 0.5-0.786 band of the " + str.tostring(fibLen) + "-bar swing: " + fmtVote(v7)
s
// The seven votes in one line, for alert messages.
votesShort() =>
"EMA " + fmtVote(v1) + " HTF " + fmtVote(v2) + " ADX " + fmtVote(v3) + " SQZ " + fmtVote(v4) + " VOL " + fmtVote(v5) + " DIV " + fmtVote(v6) + " FIB " + fmtVote(v7)
// ───────────────────────── Signals ─────────────────────────
// BUY when the score of a closed bar reaches minScore from below; SELL when it reaches -minScore from above.
// score[1] is the score of the previous bar at its close. With alternate on, a BUY needs a SELL before it and
// the reverse; the first signal can be either.
var int lastSig = 0
bool buySig = false
bool sellSig = false
if barstate.isconfirmed and ready
if score >= minScore and score[1] < minScore and (not alternate or lastSig != 1)
buySig := true
lastSig := 1
else if score <= -minScore and score[1] > -minScore and (not alternate or lastSig != -1)
sellSig := true
lastSig := -1
// Safeguard: a pending signal is confirmed by the first closed bar among the next sgBars bars that closes above
// the signal bar's high (BUY) or below its low (SELL) while the score still reaches minScore - 1 in the signal's
// direction. It lapses after sgBars bars, and a new BUY or SELL replaces it. The pending label's tooltip records
// what happened.
var int pendDir = 0
var int pendBar = na
var int pendTime = na
var float pendHigh = na
var float pendLow = na
var label pendLabel = na
var string pendTip = ""
var array<label> sigLabels = array.new<label>()
var array<label> chkLabels = array.new<label>()
bool buyConf = false
bool sellConf = false
// Deletes the oldest labels of arr until it holds at most keep.
trimLabels(array<label> arr, int keep) =>
while array.size(arr) > keep
label.delete(array.shift(arr))
// Appends a line to the tooltip of the pending signal's label, when there is one.
notePending(string txt) =>
if not na(pendLabel)
label.set_tooltip(pendLabel, pendTip + "\n" + txt)
if barstate.isconfirmed and sgOn
if pendDir != 0
if pendDir == 1 and close > pendHigh and score >= minScore - 1
buyConf := true
else if pendDir == -1 and close < pendLow and score <= -(minScore - 1)
sellConf := true
if buyConf or sellConf
string chkTip = "Safeguard: confirms the " + (buyConf ? "BUY" : "SELL") + " of " + fmtTime(pendTime) + ". This bar closed " + (buyConf ? "above that bar's high" : "below that bar's low") + " with score " + fmtScore(score) + ", " + str.tostring(bar_index - pendBar) + " bars after the signal."
notePending("Safeguard: confirmed " + str.tostring(bar_index - pendBar) + " bars later.")
if sigLabelsOn
array.push(chkLabels, label.new(bar_index, buyConf ? low : high, "✓", yloc = buyConf ? yloc.belowbar : yloc.abovebar, style = buyConf ? label.style_label_up : label.style_label_down, color = buyConf ? upCol : dnCol, textcolor = color.white, size = size.tiny, tooltip = chkTip))
trimLabels(chkLabels, sigKeep)
pendDir := 0
else if bar_index - pendBar >= sgBars
notePending("Safeguard: not confirmed within " + str.tostring(sgBars) + " bars; no trade.")
pendDir := 0
if buySig or sellSig
if pendDir != 0
notePending("Safeguard: replaced by the next signal before it was confirmed; no trade.")
pendDir := buySig ? 1 : -1
pendBar := bar_index
pendTime := time
pendHigh := high
pendLow := low
// The BUY/SELL label, below or above the bar, with every vote in its tooltip.
if buySig or sellSig
string tip = votesText()
label lb = na
if sigLabelsOn
lb := label.new(bar_index, buySig ? low : high, (buySig ? "BUY " : "SELL ") + str.tostring(math.abs(score)) + "/7", yloc = buySig ? yloc.belowbar : yloc.abovebar, style = buySig ? label.style_label_up : label.style_label_down, color = buySig ? upCol : dnCol, textcolor = color.white, size = size.small, tooltip = tip)
array.push(sigLabels, lb)
trimLabels(sigLabels, sigKeep)
pendLabel := lb
pendTip := tip
// ───────────────────────── Trades ─────────────────────────
// The three targets and the stop of a trade in direction d from entry e, with the ATR a of the entry bar.
levelsOf(int d, float e, float a) =>
bool pct = tpMode == "Percent"
float k1 = pct ? e * tp1Pct / 100 : tp1Atr * a
float k2 = pct ? e * tp2Pct / 100 : tp2Atr * a
float k3 = pct ? e * tp3Pct / 100 : tp3Atr * a
float ks = pct ? e * slPct / 100 : slAtr * a
[e + d * k1, e + d * k2, e + d * k3, e - d * ks]
// Target k (1 to 3) of a trade.
targetOf(Trade t, int k) =>
k == 1 ? t.tp1 : k == 2 ? t.tp2 : t.tp3
// True when price p is at or beyond the target x of a trade in direction d.
reaches(int d, float p, float x) =>
d == 1 ? p >= x : p <= x
// True when price p is at or beyond the stop s of a trade in direction d.
stopsAt(int d, float p, float s) =>
d == 1 ? p <= s : p >= s
// Advances an open signal trade by the current closed bar and returns [stopped, ambiguous]. Same rules as
// intrabar-ambiguity's ledger:
// 1) An open at or beyond the stop: stopped, the stop came first.
// 2) Targets the open already reached are credited: the open is the bar's first price. TP3 ends the trade.
// 3) The high (long) or the low (short) may reach further targets and the other extreme the stop. A stop and a
// further target inside the same bar cannot be ordered from OHLC: the bar counts as a stop, the further
// target is not credited, and the trade is flagged ambiguous.
stepTrade(Trade t) =>
bool stopped = false
bool amb = false
if stopsAt(t.dir, open, t.sl)
stopped := true
else
while t.hits < 3 and reaches(t.dir, open, targetOf(t, t.hits + 1))
t.hits += 1
if t.hits < 3
int reach = t.hits
float ext = t.dir == 1 ? high : low
while reach < 3 and reaches(t.dir, ext, targetOf(t, reach + 1))
reach += 1
if stopsAt(t.dir, t.dir == 1 ? low : high, t.sl)
stopped := true
amb := reach > t.hits
else
t.hits := reach
[stopped, amb]
newLine(float y, color c, string st) =>
line.new(bar_index, y, bar_index, y, color = c, style = st, width = 1)
extendTrade(Trade t) =>
line.set_x2(t.lnEntry, bar_index)
line.set_x2(t.lnTp1, bar_index)
line.set_x2(t.lnTp2, bar_index)
line.set_x2(t.lnTp3, bar_index)
line.set_x2(t.lnSl, bar_index)
deleteDrawing(Trade t) =>
line.delete(t.lnEntry)
line.delete(t.lnTp1)
line.delete(t.lnTp2)
line.delete(t.lnTp3)
line.delete(t.lnSl)
for lb in t.marks
label.delete(lb)
array.clear(t.marks)
t.drawn := false
markTrade(Trade t, float y, string txt, color c, string tip) =>
array.push(t.marks, label.new(bar_index, y, txt, style = label.style_label_left, color = color.new(c, 15), textcolor = color.white, size = size.tiny, tooltip = tip))
// Open signal trades and the drawn ones, oldest first.
var array<Trade> openTrades = array.new<Trade>()
var array<Trade> drawnTrades = array.new<Trade>()
// Signal trades that have ended, per direction (index 0 long, 1 short): count, TP1, TP2 and TP3 reached, stops,
// timeouts, and stops on an ambiguous bar.
var array<int> sN = array.new<int>(2, 0)
var array<int> sTp1 = array.new<int>(2, 0)
var array<int> sTp2 = array.new<int>(2, 0)
var array<int> sTp3 = array.new<int>(2, 0)
var array<int> sStop = array.new<int>(2, 0)
var array<int> sTime = array.new<int>(2, 0)
var array<int> sAmb = array.new<int>(2, 0)
// ───────────────────────── Base rate ─────────────────────────
// The same TP1, stop and horizon applied to every closed bar from the first ready one, as a long and as a short
// entry at its close. Each bar opens one trade per direction and each lives at most H bars, so at most H are
// open per direction.
var array<int> bN = array.new<int>(2, 0)
var array<int> bTp1 = array.new<int>(2, 0)
var array<int> bStop = array.new<int>(2, 0)
var array<int> bTime = array.new<int>(2, 0)
var array<int> bAmb = array.new<int>(2, 0)
var array<int> blBarL = array.new<int>()
var array<float> blTpL = array.new<float>()
var array<float> blSlL = array.new<float>()
var array<int> blBarS = array.new<int>()
var array<float> blTpS = array.new<float>()
var array<float> blSlS = array.new<float>()
// Advances every open base-rate trade of direction d by this closed bar with the rules of stepTrade(), TP1
// only, and counts the ones that end. An ended trade is removed by moving the last element into its slot,
// which is safe because the loop runs backwards and that element has already been stepped on this bar.
stepBase(int d, array<int> bars, array<float> tps, array<float> sls, int di) =>
int n = array.size(bars)
if n > 0
for i = n - 1 to 0
float tp = array.get(tps, i)
float sl = array.get(sls, i)
int outcome = 0
bool amb = false
if stopsAt(d, open, sl)
outcome := -1
else if reaches(d, open, tp)
outcome := 1
else
bool slHit = stopsAt(d, d == 1 ? low : high, sl)
bool tpHit = reaches(d, d == 1 ? high : low, tp)
if slHit
amb := tpHit
outcome := -1
else if tpHit
outcome := 1
if outcome == 0 and bar_index - array.get(bars, i) >= horizon
outcome := 2
if outcome != 0
array.set(bN, di, array.get(bN, di) + 1)
if outcome == 1
array.set(bTp1, di, array.get(bTp1, di) + 1)
else if outcome == -1
array.set(bStop, di, array.get(bStop, di) + 1)
if amb
array.set(bAmb, di, array.get(bAmb, di) + 1)
else
array.set(bTime, di, array.get(bTime, di) + 1)
int lastIdx = array.size(bars) - 1
array.set(bars, i, array.get(bars, lastIdx))
array.set(tps, i, array.get(tps, lastIdx))
array.set(sls, i, array.get(sls, lastIdx))
array.pop(bars)
array.pop(tps)
array.pop(sls)
// One step per closed bar, in this order: the open signal trades take this bar; a new BUY or SELL ends the
// drawing of the trades on the other side; a new trade opens at this close; then the base-rate trades take this
// bar and two new ones open at this close. A trade is never checked on its own entry bar.
if barstate.isconfirmed
int n = array.size(openTrades)
if n > 0
for i = n - 1 to 0
Trade t = array.get(openTrades, i)
int before = t.hits
[stopped, amb] = stepTrade(t)
bool timedOut = not stopped and t.hits < 3 and bar_index - t.bar >= horizon
bool done = stopped or t.hits == 3 or timedOut
if t.drawn
extendTrade(t)
if t.hits > before
for k = before + 1 to t.hits
markTrade(t, targetOf(t, k), "TP" + str.tostring(k), upCol, "TP" + str.tostring(k) + " reached, " + str.tostring(bar_index - t.bar) + " bars after the entry.")
if stopped
markTrade(t, t.sl, amb ? "SL*" : "SL", dnCol, amb ? "Stop and a further target inside this bar: the order is unknown, so it counts as a stop (ambiguous)." : "Stop reached, " + str.tostring(bar_index - t.bar) + " bars after the entry.")
if done
t.drawn := false
if done
int di = t.dir == 1 ? 0 : 1
array.set(sN, di, array.get(sN, di) + 1)
if t.hits >= 1
array.set(sTp1, di, array.get(sTp1, di) + 1)
if t.hits >= 2
array.set(sTp2, di, array.get(sTp2, di) + 1)
if t.hits >= 3
array.set(sTp3, di, array.get(sTp3, di) + 1)
if stopped
array.set(sStop, di, array.get(sStop, di) + 1)
if amb
array.set(sAmb, di, array.get(sAmb, di) + 1)
if timedOut
array.set(sTime, di, array.get(sTime, di) + 1)
array.remove(openTrades, i)
if buySig or sellSig
int sd = buySig ? 1 : -1
for t in drawnTrades
if t.drawn and t.dir == -sd
t.drawn := false
// Entry at the close of the signal bar, or of the confirmation bar with the safeguard on.
bool openLong = sgOn ? buyConf : buySig
bool openShort = sgOn ? sellConf : sellSig
if openLong or openShort
int d = openLong ? 1 : -1
[l1, l2, l3, ls] = levelsOf(d, close, atr)
Trade t = Trade.new(dir = d, bar = bar_index, entry = close, tp1 = l1, tp2 = l2, tp3 = l3, sl = ls, marks = array.new<label>())
array.push(openTrades, t)
if tpLinesOn
t.lnEntry := newLine(close, color.new(color.gray, 20), line.style_dotted)
t.lnTp1 := newLine(l1, color.new(upCol, 30), line.style_dashed)
t.lnTp2 := newLine(l2, color.new(upCol, 30), line.style_dashed)
t.lnTp3 := newLine(l3, color.new(upCol, 30), line.style_dashed)
t.lnSl := newLine(ls, color.new(dnCol, 30), line.style_dashed)
t.drawn := true
array.push(drawnTrades, t)
if array.size(drawnTrades) > tpKeep
deleteDrawing(array.shift(drawnTrades))
stepBase(1, blBarL, blTpL, blSlL, 0)
stepBase(-1, blBarS, blTpS, blSlS, 1)
if ready
[bl1, bl2, bl3, bls] = levelsOf(1, close, atr)
array.push(blBarL, bar_index)
array.push(blTpL, bl1)
array.push(blSlL, bls)
[bs1, bs2, bs3, bss] = levelsOf(-1, close, atr)
array.push(blBarS, bar_index)
array.push(blTpS, bs1)
array.push(blSlS, bss)
// ───────────────────────── Last-bar drawings ─────────────────────────
// The Fibonacci levels and the volume profile are redrawn on the last bar of the chart from closed bars only:
// while the last bar is still forming, every series is read one bar back (off = 1), so the drawings change only
// when a bar closes.
var array<line> fibLines = array.new<line>()
var array<label> fibLabels = array.new<label>()
var array<box> vpBoxes = array.new<box>()
var line vpPoc = na
color fibBandCol = #ff9800
color pocCol = #ec407a
if barstate.islast
int off = barstate.isconfirmed ? 0 : 1
// Auto Fibonacci: the swing runs from the older of the two extremes to the more recent one, and level r sits
// at end - r x (end - start). The 0.5 and 0.786 lines bound the band that vote 7 reads. Each label sits at the
// left end of its line, on the start bar of the swing, so the space right of the last bar is left to the
// volume profile.
for ln in fibLines
line.delete(ln)
array.clear(fibLines)
for lb in fibLabels
label.delete(lb)
array.clear(fibLabels)
float fHi = fibHi[off]
float fLo = fibLo[off]
int fHiBar = bar_index - off + fibHiOff[off]
int fLoBar = bar_index - off + fibLoOff[off]
if fibOn and fHi > fLo and fHiBar != fLoBar
bool upSwing = fHiBar > fLoBar
float endP = upSwing ? fHi : fLo
float startP = upSwing ? fLo : fHi
array<float> ratios = array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0)
if fibExt
array.push(ratios, 1.272)
array.push(ratios, 1.618)
int startBar = math.min(fHiBar, fLoBar)
int endBar = math.max(fHiBar, fLoBar)
string fibTip = "Swing of the last " + str.tostring(fibLen) + " closed bars: from the " + (upSwing ? "low" : "high") + " of the bar of " + fmtTime(time[bar_index - startBar]) + " to the " + (upSwing ? "high" : "low") + " of the bar of " + fmtTime(time[bar_index - endBar]) + ". Redrawn when a bar closes."
for r in ratios
float y = endP - r * (endP - startP)
color c = r == 0.5 or r == 0.786 ? fibBandCol : color.new(color.gray, 30)
array.push(fibLines, line.new(startBar, y, bar_index, y, extend = extend.right, color = c, style = line.style_dotted))
array.push(fibLabels, label.new(startBar, y, str.tostring(r, "0.###") + " " + str.tostring(y, format.mintick), style = label.style_label_right, color = color.new(color.black, 100), textcolor = c, size = size.small, textalign = text.align_right, tooltip = fibTip))
// Volume profile over the last vpBars closed bars: a bar's volume goes to the rows its high-low range
// overlaps, in proportion to the overlap; a bar with no range puts it in the row of its close. The point of
// control (POC) is the row with the most volume; the value area grows from it one row at a time, taking the
// neighbor with more volume, until it holds 70% of the total.
for b in vpBoxes
box.delete(b)
array.clear(vpBoxes)
line.delete(vpPoc)
vpPoc := na
if vpOn
int first = off
int last = off + vpBars - 1
float top = high[first]
float bot = low[first]
float tot = 0.0
for i = first to last
top := math.max(top, high[i])
bot := math.min(bot, low[i])
tot += nz(volume[i])
if tot > 0 and top > bot
float rowH = (top - bot) / vpRows
array<float> vols = array.new<float>(vpRows, 0.0)
for i = first to last
float v = nz(volume[i])
if v > 0
float h = high[i]
float l = low[i]
if h == l
int r = math.min(math.floor((close[i] - bot) / rowH), vpRows - 1)
array.set(vols, r, array.get(vols, r) + v)
else
int r0 = math.min(math.floor((l - bot) / rowH), vpRows - 1)
int r1 = math.min(math.floor((h - bot) / rowH), vpRows - 1)
for r = r0 to r1
float rowBot = bot + r * rowH
float ov = math.min(h, rowBot + rowH) - math.max(l, rowBot)
if ov > 0
array.set(vols, r, array.get(vols, r) + v * ov / (h - l))
float vMax = array.max(vols)
int poc = array.indexof(vols, vMax)
int vaLo = poc
int vaHi = poc
float acc = vMax
while acc < 0.7 * tot and (vaLo > 0 or vaHi < vpRows - 1)
float up = vaHi < vpRows - 1 ? array.get(vols, vaHi + 1) : -1.0
float dn = vaLo > 0 ? array.get(vols, vaLo - 1) : -1.0
if up >= dn
vaHi += 1
acc += up
else
vaLo -= 1
acc += dn
int x0 = bar_index + 2
for r = 0 to vpRows - 1
float v = array.get(vols, r)
if v > 0
int w = math.max(1, math.round(vpWidth * v / vMax))
color c = r == poc ? color.new(pocCol, 40) : vpVa and r >= vaLo and r <= vaHi ? color.new(#5c6bc0, 65) : color.new(color.gray, 75)
array.push(vpBoxes, box.new(x0, bot + (r + 1) * rowH, x0 + w, bot + r * rowH, border_color = c, bgcolor = c))
float pocY = bot + (poc + 0.5) * rowH
vpPoc := line.new(bar_index - last, pocY, x0 + vpWidth, pocY, color = pocCol, width = 1)
// ───────────────────────── Trend card ─────────────────────────
tSize = switch textSize
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
// Opaque cell colors blended from the chart background, so candles do not show through the tables on a light
// or a dark theme.
cellBg = color.from_gradient(0.12, 0.0, 1.0, chart.bg_color, color.gray)
hdrBg = color.from_gradient(0.30, 0.0, 1.0, chart.bg_color, color.gray)
upBg = color.from_gradient(0.40, 0.0, 1.0, chart.bg_color, upCol)
dnBg = color.from_gradient(0.40, 0.0, 1.0, chart.bg_color, dnCol)
var table card = table.new(position.top_right, 3, 7, border_width = 1)
cardCell(int col, int row, string txt, color bg = na, string align = text.align_center) =>
table.cell(card, col, row, txt, text_color = chart.fg_color, text_size = tSize, text_halign = align, bgcolor = na(bg) ? cellBg : bg)
// One card row: the timeframe, its trend from its last completed bar, and its ADX. A timeframe below the
// chart's is requested but reads "below chart".
cardRow(int row, string tfIn, float f, float m, float c, float a) =>
string tf = tfIn == "" ? timeframe.period : tfIn
cardCell(0, row, tf, na, text.align_left)
if timeframe.in_seconds(tf) < timeframe.in_seconds(timeframe.period)
cardCell(1, row, "below chart")
cardCell(2, row, "")
else
int tr = trendOf(f, m, c)
bool known = not na(f) and not na(m) and not na(c)
cardCell(1, row, not known ? "n/a" : tr == 1 ? "Up" : tr == -1 ? "Down" : "Flat", known and tr == 1 ? upBg : known and tr == -1 ? dnBg : na)
cardCell(2, row, na(a) ? "n/a" : str.tostring(a, "0") + (a >= adxThr ? " strong" : " weak"))
if barstate.islast and mtfOn
cardCell(0, 0, "TF", hdrBg, text.align_left)
cardCell(1, 0, "Trend", hdrBg)
cardCell(2, 0, "ADX " + str.tostring(adxThr, "0.#"), hdrBg)
cardRow(1, mtf1, m1F, m1M, m1C, m1A)
cardRow(2, mtf2, m2F, m2M, m2C, m2A)
cardRow(3, mtf3, m3F, m3M, m3C, m3A)
cardRow(4, mtf4, m4F, m4M, m4C, m4A)
cardRow(5, mtf5, m5F, m5M, m5C, m5A)
// The score of the last closed bar: while the last bar is forming, the previous bar's.
int lastScore = barstate.isconfirmed ? score : score[1]
cardCell(0, 6, "Score", hdrBg, text.align_left)
cardCell(1, 6, fmtScore(lastScore) + " / 7", lastScore >= minScore ? upBg : lastScore <= -minScore ? dnBg : na)
cardCell(2, 6, "signal at " + str.tostring(minScore))
// ───────────────────────── Scorecard ─────────────────────────
goodBg = color.from_gradient(0.40, 0.0, 1.0, chart.bg_color, color.green)
badBg = color.from_gradient(0.40, 0.0, 1.0, chart.bg_color, color.red)
scPos = switch scPosIn
"Top left" => position.top_left
"Top center" => position.top_center
"Middle left" => position.middle_left
"Middle center" => position.middle_center
"Middle right" => position.middle_right
"Bottom left" => position.bottom_left
"Bottom center" => position.bottom_center
=> position.bottom_right
// Eleven columns: the row names and ten values. Seven rows: a short title, column titles, three signal rows and
// two base-rate rows. The details and the counting rules sit in the title's tooltip, so no long text widens the
// columns.
var table sc = table.new(scPos, 11, 7, border_width = 1)
// The title row is merged exactly once, on the first bar, where the table is created. That bar is historical, so
// no realtime rollback can undo the merge or bring back a flag that would merge it again (merging cells that are
// already merged is an error). table.merge_cells() can merge cells before their properties are set with
// table.cell(). With the scorecard off, nothing is merged and no cell is written, so nothing shows.
if barstate.isfirst and scOn
table.merge_cells(sc, 0, 0, 10, 0)
scCell(int col, int row, string txt, color bg = na, string align = text.align_center) =>
table.cell(sc, col, row, txt, text_color = chart.fg_color, text_size = tSize, text_halign = align, bgcolor = na(bg) ? cellBg : bg)
// "48.3%" from a rate in [0, 1], "n/a" when there is none.
fmtRate(float r) =>
na(r) ? "n/a" : str.tostring(r * 100, "0.0") + "%"
// k / n as a rate, "n/a" when n is 0.
fmtShare(int k, int n) =>
n > 0 ? fmtRate(float(k) / n) : "n/a"
// "+1.2 pts" or "-1.2 pts" from a signed difference in percentage points, "n/a" when there is none.
fmtPts(float v) =>
na(v) ? "n/a" : (v > 0 ? "+" : "") + str.tostring(v, "0.0") + " pts"
// Wilson score interval at 95% (z = 1.96) for k successes in n trials: [lower, upper], na when n is 0.
wilson(int k, int n) =>
float lo = na
float hi = na
if n > 0
float z = 1.96
float p = float(k) / n
float den = 1 + z * z / n
float ctr = (p + z * z / (2.0 * n)) / den
float half = z * math.sqrt(p * (1 - p) / n + z * z / (4.0 * n * n)) / den
lo := ctr - half
hi := ctr + half
[lo, hi]
// One signal row. base is the base rate its TP1 rate is compared with: "better" when the lower bound of the TP1
// interval is above it, "worse" when the upper bound is below it, "no evidence" otherwise (also with N = 0).
sigRow(int row, string name, int n, int t1, int t2, int t3, int st, int tm, int am, float base) =>
[lo, hi] = wilson(t1, n)
float p = n > 0 ? float(t1) / n : float(na)
bool better = n > 0 and not na(base) and lo > base
bool worse = n > 0 and not na(base) and hi < base
scCell(0, row, name, na, text.align_left)
scCell(1, row, str.tostring(n, "#,##0"))
scCell(2, row, fmtShare(t1, n))
scCell(3, row, fmtShare(t2, n))
scCell(4, row, fmtShare(t3, n))
scCell(5, row, fmtShare(st, n))
scCell(6, row, str.tostring(tm, "#,##0"))
scCell(7, row, str.tostring(am, "#,##0"))
scCell(8, row, n > 0 ? fmtRate(lo) + " - " + fmtRate(hi) : "n/a")
scCell(9, row, na(p) or na(base) ? "n/a" : fmtPts((p - base) * 100))
scCell(10, row, better ? "better" : worse ? "worse" : "no evidence", better ? goodBg : worse ? badBg : na)
// One base-rate row: TP1 only, so the TP2, TP3, edge and verdict cells stay empty.
baseRow(int row, string name, int n, int t1, int st, int tm, int am) =>
[lo, hi] = wilson(t1, n)
scCell(0, row, name, na, text.align_left)
scCell(1, row, str.tostring(n, "#,##0"))
scCell(2, row, fmtShare(t1, n))
scCell(3, row, "-")
scCell(4, row, "-")
scCell(5, row, fmtShare(st, n))
scCell(6, row, str.tostring(tm, "#,##0"))
scCell(7, row, str.tostring(am, "#,##0"))
scCell(8, row, n > 0 ? fmtRate(lo) + " - " + fmtRate(hi) : "n/a")
scCell(9, row, "")
scCell(10, row, "")
if barstate.islast and scOn
int nL = array.get(sN, 0)
int nS = array.get(sN, 1)
int bNL = array.get(bN, 0)
int bNS = array.get(bN, 1)
float baseL = bNL > 0 ? float(array.get(bTp1, 0)) / bNL : float(na)
float baseS = bNS > 0 ? float(array.get(bTp1, 1)) / bNS : float(na)
// All signals are compared with the base rate weighted by their own mix of longs and shorts.
float baseAll = nL + nS > 0 and not na(baseL) and not na(baseS) ? (nL * baseL + nS * baseS) / (nL + nS) : float(na)
string levelsTxt = tpMode == "Percent" ? "TP " + str.tostring(tp1Pct, "0.##") + "/" + str.tostring(tp2Pct, "0.##") + "/" + str.tostring(tp3Pct, "0.##") + "%, stop " + str.tostring(slPct, "0.##") + "%" : "TP " + str.tostring(tp1Atr, "0.##") + "/" + str.tostring(tp2Atr, "0.##") + "/" + str.tostring(tp3Atr, "0.##") + " x ATR " + str.tostring(atrLen) + ", stop " + str.tostring(slAtr, "0.##") + " x ATR"
// A short title; hover it for the settings, the counting rules and the trades not counted yet.
string scTip = ticker.standard(syminfo.tickerid) + " · " + timeframe.period + " · " + levelsTxt + " · horizon " + str.tostring(horizon) + " bars" + (sgOn ? " · safeguard on, confirmed signals only" : "") + ".\nClosed bars only. A trade ends at the stop, TP3 or after the horizon; a stop and a target inside one bar count as a stop (ambiguous). Results are before costs.\nNot counted yet: " + str.tostring(array.size(openTrades)) + " open signal trades, " + str.tostring(array.size(blBarL) + array.size(blBarS)) + " open base-rate trades. Not advice."
table.cell(sc, 0, 0, "Scorecard · before costs" + (sgOn ? " · safeguard on" : ""), text_color = chart.fg_color, text_size = tSize, text_halign = text.align_left, bgcolor = hdrBg, tooltip = scTip)
scCell(0, 1, "", hdrBg)
scCell(1, 1, "N", hdrBg)
scCell(2, 1, "TP1", hdrBg)
scCell(3, 1, "TP2", hdrBg)
scCell(4, 1, "TP3", hdrBg)
scCell(5, 1, "Stop", hdrBg)
scCell(6, 1, "Timeouts", hdrBg)
scCell(7, 1, "Ambiguous", hdrBg)
scCell(8, 1, "TP1 95% CI", hdrBg)
scCell(9, 1, "Edge vs base", hdrBg)
scCell(10, 1, "Verdict", hdrBg)
sigRow(2, "Long signals", nL, array.get(sTp1, 0), array.get(sTp2, 0), array.get(sTp3, 0), array.get(sStop, 0), array.get(sTime, 0), array.get(sAmb, 0), baseL)
sigRow(3, "Short signals", nS, array.get(sTp1, 1), array.get(sTp2, 1), array.get(sTp3, 1), array.get(sStop, 1), array.get(sTime, 1), array.get(sAmb, 1), baseS)
sigRow(4, "All signals", nL + nS, array.get(sTp1, 0) + array.get(sTp1, 1), array.get(sTp2, 0) + array.get(sTp2, 1), array.get(sTp3, 0) + array.get(sTp3, 1), array.get(sStop, 0) + array.get(sStop, 1), array.get(sTime, 0) + array.get(sTime, 1), array.get(sAmb, 0) + array.get(sAmb, 1), baseAll)
baseRow(5, "Base rate, long, every bar", bNL, array.get(bTp1, 0), array.get(bStop, 0), array.get(bTime, 0), array.get(bAmb, 0))
baseRow(6, "Base rate, short, every bar", bNS, array.get(bTp1, 1), array.get(bStop, 1), array.get(bTime, 1), array.get(bAmb, 1))
// Only the start cell of the merged title row is written: a merged cell is modified through its
// start_column:start_row coordinates.
// ───────────────────────── Alerts ─────────────────────────
// The conditions are set on closed bars only, so each fires once, at the bar's close.
alertcondition(buySig, "BUY", "BUY on {{ticker}} {{interval}}: the confluence score reached the minimum on a closed bar.")
alertcondition(sellSig, "SELL", "SELL on {{ticker}} {{interval}}: the confluence score reached minus the minimum on a closed bar.")
alertcondition(buyConf, "BUY confirmed", "BUY confirmed on {{ticker}} {{interval}}: a close above the signal bar's high inside the safeguard window.")
alertcondition(sellConf, "SELL confirmed", "SELL confirmed on {{ticker}} {{interval}}: a close below the signal bar's low inside the safeguard window.")
if barstate.isconfirmed and (alertMode == "Every bar close" or buySig or sellSig or buyConf or sellConf)
string evt = buySig ? "BUY" : sellSig ? "SELL" : buyConf ? "BUY confirmed" : sellConf ? "SELL confirmed" : "bar close"
alert(ticker.standard(syminfo.tickerid) + " " + timeframe.period + " | " + evt + " | score " + fmtScore(score) + "/7 | " + votesShort(), alert.freq_once_per_bar_close)