本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator(title="[Mad] MTF Divergence Scanner", shorttitle="[Mad] MTF", overlay=false, max_labels_count=500, max_lines_count=500)
// ═════════════════════════════════════════════════════════════════════════════
// [Mad] MTF Divergence Scanner
// ─────────────────────────────────────────────────────────────────────────────
// Scans up to seven timeframes for regular and hidden divergences between
// price and one oscillator (RSI, MACD, MFI or Stochastic).
//
// Output
// • Oscillator pane : one stacked band per active timeframe with divergence
// lines, detection dots and a value tag.
// • Price chart : divergence lines, detection markers and a summary table.
// • Alerts : two alert conditions plus one combined alert() call.
//
// Setup (the settings dialog follows the same order)
// 1 · Oscillator which oscillator is compared with price
// 2 · Divergence rules pivot size, lookback window, divergence kinds
// 3 · Timeframes preset or custom list, per-slot on/off
// 4 · Price chart what is drawn on top of the candles
// 5 · Oscillator pane what is drawn in the indicator pane
// 6 · Summary table position and text size
// 7 · Colors every color used by the script
// ═════════════════════════════════════════════════════════════════════════════
// ─────────────────────────────────────────────────────────────────────────────
// Inputs
// ─────────────────────────────────────────────────────────────────────────────
const string G_OSC = "1 · Oscillator"
const string G_DIV = "2 · Divergence rules"
const string G_TF = "3 · Timeframes"
const string G_CHART = "4 · Price chart overlay"
const string G_PANE = "5 · Oscillator pane"
const string G_TABLE = "6 · Summary table"
const string G_COLOR = "7 · Colors"
const string TT_SLOT = "Tick to scan this slot. The dropdown is only used when 'Timeframe set' is Custom."
// 1 · Oscillator
oscType = input.string("RSI", "Oscillator", options=["RSI", "MACD", "MFI", "Stochastic"], group=G_OSC, tooltip="Oscillator that is compared with price. Only the parameters of the selected oscillator are used.")
rsiSourceInput = input.source(close, "Source", group=G_OSC, tooltip="Price source for RSI and MACD. MFI uses HLC3, Stochastic uses close/high/low.")
rsiLengthInput = input.int(21, "RSI Length", minval=1, group=G_OSC)
ob = input.int(63, "RSI Overbought", inline="rsiLvl", group=G_OSC)
os = input.int(38, "Oversold", inline="rsiLvl", group=G_OSC, tooltip="RSI levels that color the oscillator line and the table cell.")
bandLo = input.int(20, "RSI Display from", minval=0, maxval=49, inline="rsiRange", group=G_OSC)
bandHi = input.int(80, "to", minval=51, maxval=100, inline="rsiRange", group=G_OSC, tooltip="RSI range that is stretched over the full height of a band. Values outside are clipped.")
macdFast = input.int(12, "MACD Fast", minval=1, inline="macd", group=G_OSC)
macdSlow = input.int(26, "Slow", minval=1, inline="macd", group=G_OSC)
macdSig = input.int(9, "Signal", minval=1, inline="macd", group=G_OSC, tooltip="MACD lengths. Divergences use the MACD line.")
macdPow = input.float(0.6, "MACD Scaling exponent", minval=0.1, maxval=1.0, step=0.05, group=G_OSC, tooltip="Display only: values below 1 compress large MACD swings so small ones stay visible.")
macdNormLen = input.int(500, "MACD Normalization bars", minval=20, group=G_OSC, tooltip="Display only: the MACD is scaled by its largest absolute value over this many bars.")
mfiLen = input.int(14, "MFI Length", minval=1, group=G_OSC)
stochLen = input.int(14, "Stoch %K length", minval=1, inline="stoch", group=G_OSC)
stochSmooth = input.int(3, "Smoothing", minval=1, inline="stoch", group=G_OSC)
ob2 = input.int(80, "MFI / Stoch Overbought", inline="lvl2", group=G_OSC)
os2 = input.int(20, "Oversold", inline="lvl2", group=G_OSC, tooltip="Levels used when the oscillator is MFI or Stochastic.")
// 2 · Divergence rules
lbL = input.int(5, "Pivot bars Left", minval=1, inline="pivot", group=G_DIV)
lbR = input.int(5, "Right", minval=1, inline="pivot", group=G_DIV, tooltip="Bars on each side that confirm an oscillator pivot. A divergence is detected 'Right' bars after its pivot.")
rangeLower = input.int(5, "Pivot distance Min", inline="range", group=G_DIV)
rangeUpper = input.int(60, "Max", inline="range", group=G_DIV, tooltip="Allowed number of bars between the two pivots of a divergence.")
showBull = input.bool(true, "Regular bullish", inline="regular", group=G_DIV)
showBear = input.bool(true, "Regular bearish", inline="regular", group=G_DIV, tooltip="Bullish: lower price low with higher oscillator low. Bearish: higher price high with lower oscillator high.")
showHiddenBull = input.bool(false, "Hidden bullish", inline="hidden", group=G_DIV)
showHiddenBear = input.bool(false, "Hidden bearish", inline="hidden", group=G_DIV, tooltip="Trend-continuation divergences, drawn dashed and prefixed with H.")
freshBars = input.int(3, "Fresh for (bars)", minval=0, group=G_DIV, tooltip="A divergence counts as fresh for this many bars of its own timeframe. Fresh signals are highlighted in the table.")
// 3 · Timeframes
tfSet = input.string("Custom", "Timeframe set", options=["Custom", "Scalping", "Intraday", "Swing", "Position"], group=G_TF, tooltip="Custom uses the seven dropdowns below.\nScalping: 1m 3m 5m 15m 30m 1H 4H\nIntraday: 5m 15m 30m 1H 4H 12H 1D\nSwing: 15m 1H 6H 12H 1D 3D 1W\nPosition: 4H 12H 1D 3D 1W 2W 1M\nThe checkboxes switch individual slots on or off in every set.")
use1 = input.bool(true, "Slot 1", inline="tf1", group=G_TF)
tfIn1 = input.string("15m", "", options=["1m", "3m", "5m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "6H", "8H", "12H", "1D", "2D", "3D", "1W", "2W", "1M", "3M"], inline="tf1", group=G_TF, tooltip=TT_SLOT)
use2 = input.bool(true, "Slot 2", inline="tf2", group=G_TF)
tfIn2 = input.string("1H", "", options=["1m", "3m", "5m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "6H", "8H", "12H", "1D", "2D", "3D", "1W", "2W", "1M", "3M"], inline="tf2", group=G_TF, tooltip=TT_SLOT)
use3 = input.bool(true, "Slot 3", inline="tf3", group=G_TF)
tfIn3 = input.string("6H", "", options=["1m", "3m", "5m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "6H", "8H", "12H", "1D", "2D", "3D", "1W", "2W", "1M", "3M"], inline="tf3", group=G_TF, tooltip=TT_SLOT)
use4 = input.bool(true, "Slot 4", inline="tf4", group=G_TF)
tfIn4 = input.string("12H", "", options=["1m", "3m", "5m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "6H", "8H", "12H", "1D", "2D", "3D", "1W", "2W", "1M", "3M"], inline="tf4", group=G_TF, tooltip=TT_SLOT)
use5 = input.bool(true, "Slot 5", inline="tf5", group=G_TF)
tfIn5 = input.string("1D", "", options=["1m", "3m", "5m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "6H", "8H", "12H", "1D", "2D", "3D", "1W", "2W", "1M", "3M"], inline="tf5", group=G_TF, tooltip=TT_SLOT)
use6 = input.bool(true, "Slot 6", inline="tf6", group=G_TF)
tfIn6 = input.string("3D", "", options=["1m", "3m", "5m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "6H", "8H", "12H", "1D", "2D", "3D", "1W", "2W", "1M", "3M"], inline="tf6", group=G_TF, tooltip=TT_SLOT)
use7 = input.bool(true, "Slot 7", inline="tf7", group=G_TF)
tfIn7 = input.string("1W", "", options=["1m", "3m", "5m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "6H", "8H", "12H", "1D", "2D", "3D", "1W", "2W", "1M", "3M"], inline="tf7", group=G_TF, tooltip=TT_SLOT)
minTfDivisor = input.int(4, "Hide timeframes below chart TF ÷", minval=1, group=G_TF, tooltip="Slots smaller than the chart timeframe divided by this value are skipped. Example: 4 on a 1H chart hides everything below 15m.")
confirmedHtf = input.bool(true, "Higher timeframes: closed bars only", group=G_TF, tooltip="On: signals of higher timeframes appear only after their bar has closed and never repaint. Off: earlier signals that can disappear again.")
// 4 · Price chart overlay
showChartLines = input.bool(true, "Divergence lines", group=G_CHART, tooltip="Line between the two price pivots of each divergence.")
showChartMarks = input.bool(true, "Detection markers", inline="marks", group=G_CHART)
showChartText = input.bool(true, "with timeframe text", inline="marks", group=G_CHART, tooltip="Triangle on the bar where a divergence was detected, optionally labelled with the timeframes involved.")
chartMarkMin = input.int(4, "Marker size Smallest TF", minval=2, maxval=30, inline="markSize", group=G_CHART)
chartMarkMax = input.int(8, "Largest TF", minval=3, maxval=30, inline="markSize", group=G_CHART, tooltip="Marker size grows from the smallest to the largest active timeframe.")
baseWidth = input.int(1, "Line width Base", minval=1, maxval=4, inline="width", group=G_CHART)
maxWidth = input.int(6, "Max", minval=1, maxval=10, inline="width", group=G_CHART, tooltip="Timeframes up to the chart timeframe use the base width. Each higher timeframe adds 1, limited to Max.")
maxTransp = input.int(50, "Fade lower timeframes (%)", minval=0, maxval=90, group=G_CHART, tooltip="Transparency of the smallest timeframe below the chart timeframe. Timeframes in between fade proportionally. Also applies to the detection dots in the pane.")
// 5 · Oscillator pane
showOsc = input.bool(true, "Oscillator lines", group=G_PANE)
showObOs = input.bool(true, "Level lines", inline="levels", group=G_PANE)
showZone = input.bool(true, "Fill neutral zone", inline="levels", group=G_PANE, tooltip="Overbought/oversold lines and the fill between them. MACD shows a zero line instead.")
showMid = input.bool(false, "Midline (50)", group=G_PANE)
showPaneLines = input.bool(true, "Divergence lines", group=G_PANE, tooltip="Line between the two oscillator pivots of each divergence.")
showPaneMarks = input.bool(true, "Detection dots", inline="detect", group=G_PANE)
showPaneConn = input.bool(true, "Connector to pivot", inline="detect", group=G_PANE, tooltip="Dot on the bar where a divergence was detected and a dotted line back to its pivot. Hover a dot for details.")
dotMin = input.int(3, "Dot size Smallest TF", minval=2, maxval=30, inline="dotSize", group=G_PANE)
markSize = input.int(6, "Largest TF", minval=3, maxval=30, inline="dotSize", group=G_PANE)
showBandTags = input.bool(true, "Timeframe tags", group=G_PANE, tooltip="Tag right of each band with its timeframe and the current oscillator value.")
bandGapIn = input.int(2, "Gap between bands", minval=0, group=G_PANE)
// 6 · Summary table
showTable = input.bool(true, "Show table", group=G_TABLE, tooltip="One row per active timeframe: oscillator value, latest signal, its age in bars and the pivot time.")
tablePosInput = input.string("Top right", "Position", options=["Top right", "Middle right", "Bottom right", "Top left", "Bottom left"], group=G_TABLE)
tableSizeIn = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group=G_TABLE)
// 7 · Colors
bullColor = input.color(color.green, "Bullish", inline="signal", group=G_COLOR)
bearColor = input.color(color.red, "Bearish", inline="signal", group=G_COLOR, tooltip="Divergence lines, markers, dots and table highlights.")
obColor = input.color(color.red, "Overbought", inline="osc", group=G_COLOR)
osColor = input.color(color.green, "Oversold", inline="osc", group=G_COLOR)
oscNeutral = input.color(color.new(color.blue, 20), "Neutral", inline="osc", group=G_COLOR, tooltip="Oscillator line color by zone.")
refColor = input.color(color.new(#787B86, 50), "Level lines", inline="frame", group=G_COLOR)
midColor = input.color(color.new(#787B86, 75), "Midline", inline="frame", group=G_COLOR)
zoneColor = input.color(color.new(color.silver, 90), "Zone fill", inline="frame", group=G_COLOR)
tableBg = input.color(color.new(color.gray, 88), "Table background", inline="table", group=G_COLOR)
tagBg = input.color(color.new(color.gray, 75), "Tag background", inline="table", group=G_COLOR)
// ─────────────────────────────────────────────────────────────────────────────
// Derived settings
// ─────────────────────────────────────────────────────────────────────────────
isMacd = oscType == "MACD"
isRsi = oscType == "RSI"
oscShort = isMacd ? "MACD" : isRsi ? "RSI" : oscType == "MFI" ? "MFI" : "Stoch"
bandH = 100.0 + bandGapIn // height of one band incl. gap
dispLo = isMacd ? -1.0 : isRsi ? float(bandLo) : 0.0 // oscillator value at band bottom
dispHi = isMacd ? 1.0 : isRsi ? float(bandHi) : 100.0 // oscillator value at band top
float obLvl = isMacd ? na : isRsi ? float(ob) : float(ob2)
float osLvl = isMacd ? na : isRsi ? float(os) : float(os2)
tableSize = switch tableSizeIn
"Tiny" => size.tiny
"Small" => size.small
=> size.normal
tablePos = switch tablePosInput
"Top right" => position.top_right
"Middle right" => position.middle_right
"Bottom right" => position.bottom_right
"Top left" => position.top_left
=> position.bottom_left
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
// @function Picks the timeframe name of one slot for the selected timeframe set.
// @param custom Name chosen in the slot dropdown (used by the Custom set).
// @param scalp Name of this slot in the Scalping set.
// @param intra Name of this slot in the Intraday set.
// @param swing Name of this slot in the Swing set.
// @param pos Name of this slot in the Position set.
// @returns Display name such as "15m" or "1D".
slotTf(simple string custom, simple string scalp, simple string intra, simple string swing, simple string pos) =>
switch tfSet
"Scalping" => scalp
"Intraday" => intra
"Swing" => swing
"Position" => pos
=> custom
// @function Converts a display name from the fixed timeframe list to a Pine timeframe string.
// @param name Display name such as "45m", "4H" or "1W".
// @returns Timeframe string for request.security(); day, week and month names are already valid.
tfCode(simple string name) =>
switch name
"1m" => "1"
"3m" => "3"
"5m" => "5"
"15m" => "15"
"30m" => "30"
"45m" => "45"
"1H" => "60"
"2H" => "120"
"3H" => "180"
"4H" => "240"
"6H" => "360"
"8H" => "480"
"12H" => "720"
=> name
// @function Maps an oscillator value into the 0–100 height of a band.
// @param v Raw oscillator value.
// @returns Position inside the band, clipped to 0–100; na stays na.
toBand(float v) =>
na(v) ? na : math.max(0.0, math.min(100.0, (v - dispLo) / (dispHi - dispLo) * 100.0))
// @function Formats an oscillator value for tags and the table.
// @param v Raw oscillator value.
// @returns Text with one decimal (MACD: tick precision), "-" when na.
fmtOsc(float v) =>
na(v) ? "-" : isMacd ? str.tostring(v, format.mintick) : str.tostring(v, "#.0")
// @function Colors the oscillator line by zone.
// @param r Raw oscillator value.
// @returns Overbought, oversold or neutral color.
oscColor(float r) =>
r >= obLvl ? obColor : r <= osLvl ? osColor : oscNeutral
// @function Detects a change of a pivot timestamp, i.e. a newly reported divergence.
// @param t Pivot time of the latest divergence.
// @returns true on the bar where t first takes a new value.
isNew(int t) =>
prev = t[1]
not na(t) and (na(prev) or t != prev)
// @function Joins two texts with a separator and skips empty parts.
// @param a First text.
// @param b Second text.
// @param sep Separator placed between non-empty texts.
// @returns The joined text.
joinTxt(string a, string b, string sep) =>
a == "" ? b : b == "" ? a : a + sep + b
// @function Formats a timestamp in the symbol's timezone.
// @param t Unix time in milliseconds.
// @returns Text such as "18.11.26 21:45".
fmtTime(int t) =>
str.format_time(t, "dd.MM.yy HH:mm", syminfo.timezone)
// ─────────────────────────────────────────────────────────────────────────────
// Divergence engine (runs inside request.security on each timeframe)
// ─────────────────────────────────────────────────────────────────────────────
// @function Computes the oscillator and the latest low-side and high-side divergence on the current timeframe.
// @param off History offset applied to every returned value: 0 = live bar, 1 = last closed bar (non-repainting higher timeframes).
// @returns Tuple of 18 values:
// osc, disp – raw oscillator value and its 0–100 band position
// lAge, lKind, lT, lP, lO – latest bullish divergence: age in bars, kind (1 regular, 2 hidden), pivot time, pivot price, pivot band position
// lTp, lPp, lOp – its previous pivot: time, price, band position
// hAge … hOp – the same eight values for the latest bearish divergence
divScan(simple int off) =>
// Oscillator
rsiV = ta.rsi(rsiSourceInput, rsiLengthInput)
[macdV, _, _] = ta.macd(rsiSourceInput, macdFast, macdSlow, macdSig)
mfiV = ta.mfi(hlc3, mfiLen)
stochV = ta.sma(ta.stoch(close, high, low, stochLen), stochSmooth)
osc = isMacd ? macdV : oscType == "MFI" ? mfiV : oscType == "Stochastic" ? stochV : rsiV
// Display value: MACD is power-compressed and normalized to -1…1 first
macdP = math.sign(macdV) * math.pow(math.abs(macdV), macdPow)
macdScale = ta.highest(math.abs(macdP), math.min(bar_index + 1, macdNormLen))
disp = isMacd ? (na(macdP) or na(macdScale) or macdScale == 0 ? na : toBand(macdP / macdScale)) : toBand(osc)
// Oscillator pivots and the pivot before each
plFound = not na(ta.pivotlow(osc, lbL, lbR))
phFound = not na(ta.pivothigh(osc, lbL, lbR))
prevPlOsc = ta.valuewhen(plFound, osc[lbR], 1)
prevPlDisp = ta.valuewhen(plFound, disp[lbR], 1)
prevPlLow = ta.valuewhen(plFound, low[lbR], 1)
prevPlTime = ta.valuewhen(plFound, time[lbR], 1)
prevPhOsc = ta.valuewhen(phFound, osc[lbR], 1)
prevPhDisp = ta.valuewhen(phFound, disp[lbR], 1)
prevPhHigh = ta.valuewhen(phFound, high[lbR], 1)
prevPhTime = ta.valuewhen(phFound, time[lbR], 1)
plBars = ta.barssince(plFound[1])
phBars = ta.barssince(phFound[1])
plInRange = rangeLower <= plBars and plBars <= rangeUpper
phInRange = rangeLower <= phBars and phBars <= rangeUpper
// Divergence conditions
bull = showBull and plFound and plInRange and osc[lbR] > prevPlOsc and low[lbR] < prevPlLow
hBull = showHiddenBull and plFound and plInRange and osc[lbR] < prevPlOsc and low[lbR] > prevPlLow
bear = showBear and phFound and phInRange and osc[lbR] < prevPhOsc and high[lbR] > prevPhHigh
hBear = showHiddenBear and phFound and phInRange and osc[lbR] > prevPhOsc and high[lbR] < prevPhHigh
lowDiv = bull or hBull
highDiv = bear or hBear
// Latest low-side divergence
lAge = ta.barssince(lowDiv)
lKind = ta.valuewhen(lowDiv, bull ? 1 : 2, 0)
lT = ta.valuewhen(lowDiv, time[lbR], 0)
lP = ta.valuewhen(lowDiv, low[lbR], 0)
lO = ta.valuewhen(lowDiv, disp[lbR], 0)
lTp = ta.valuewhen(lowDiv, prevPlTime, 0)
lPp = ta.valuewhen(lowDiv, prevPlLow, 0)
lOp = ta.valuewhen(lowDiv, prevPlDisp, 0)
// Latest high-side divergence
hAge = ta.barssince(highDiv)
hKind = ta.valuewhen(highDiv, bear ? 1 : 2, 0)
hT = ta.valuewhen(highDiv, time[lbR], 0)
hP = ta.valuewhen(highDiv, high[lbR], 0)
hO = ta.valuewhen(highDiv, disp[lbR], 0)
hTp = ta.valuewhen(highDiv, prevPhTime, 0)
hPp = ta.valuewhen(highDiv, prevPhHigh, 0)
hOp = ta.valuewhen(highDiv, prevPhDisp, 0)
[osc[off], disp[off], lAge[off], lKind[off], lT[off], lP[off], lO[off], lTp[off], lPp[off], lOp[off], hAge[off], hKind[off], hT[off], hP[off], hO[off], hTp[off], hPp[off], hOp[off]]
// @function Runs divScan() on one timeframe slot.
// @param tf Timeframe string of the slot.
// @param vis Whether the slot is active; inactive slots request the chart timeframe to keep the call cheap.
// @returns The divScan() tuple. Higher timeframes use the last closed bar when 'closed bars only' is on.
tfScan(simple string tf, simple bool vis) =>
simple string tfEff = vis ? tf : timeframe.period
bool htf = confirmedHtf and timeframe.in_seconds(tfEff) > timeframe.in_seconds(timeframe.period)
request.security(syminfo.tickerid, tfEff, divScan(htf ? 1 : 0), lookahead = htf ? barmerge.lookahead_on : barmerge.lookahead_off)
// ─────────────────────────────────────────────────────────────────────────────
// Drawing
// ─────────────────────────────────────────────────────────────────────────────
// @function Draws one newly detected divergence in the pane and on the price chart.
// @param vis Whether the slot is active.
// @param lbl Timeframe name of the slot.
// @param base Bottom of the slot's band in pane coordinates.
// @param r Current band position of the oscillator (detection dot height).
// @param tr Transparency for this timeframe (0–100).
// @param w Width of the price-chart line.
// @param ds Size of the detection dot.
// @param t Pivot time of the divergence.
// @param kind 1 regular, 2 hidden.
// @param p Pivot price.
// @param o Pivot band position.
// @param tp Previous pivot time.
// @param pp Previous pivot price.
// @param op Previous pivot band position.
// @param isBull true for the low side, false for the high side.
// @returns Timeframe name (prefixed with H when hidden) on the detection bar, otherwise "".
drawDiv(bool vis, string lbl, float base, float r, int tr, int w, int ds, int t, int kind, float p, float o, int tp, float pp, float op, bool isBull) =>
bool fired = isNew(t) // evaluated on every bar so its history stays consistent
string res = ""
if vis and fired and not na(tp)
color paneCol = isBull ? bullColor : bearColor
color col = color.new(paneCol, tr)
lineSty = kind == 2 ? line.style_dashed : line.style_solid
if showPaneLines
line.new(tp, base + op, t, base + o, xloc=xloc.bar_time, color=paneCol, width=1, style=lineSty)
if showPaneConn
line.new(t, base + o, time, base + r, xloc=xloc.bar_time, color=color.new(paneCol, 45), width=1, style=line.style_dotted)
if showPaneMarks
string tip = lbl + " " + oscShort + (kind == 2 ? " Hidden " : " ") + (isBull ? "Bull" : "Bear") + "\nPivot: " + fmtTime(t) + "\nDetected: " + fmtTime(time)
label.new(time, base + r, "●", xloc=xloc.bar_time, style=label.style_none, textcolor=col, size=ds, tooltip=tip)
if showChartLines
line.new(tp, pp, t, p, xloc=xloc.bar_time, color=col, width=w, style=lineSty, force_overlay=true)
res := (kind == 2 ? "H" : "") + lbl
res
// @function Draws the static frame of one band once: level lines, zone fill and midline.
// @param vis Whether the slot is active.
// @param base Bottom of the slot's band in pane coordinates.
// @returns true once the frame exists.
bandFrame(bool vis, float base) =>
var bool drawn = false
if barstate.islast and vis and not drawn
drawn := true
if isMacd
if showObOs
line.new(bar_index - 1, base + 50, bar_index, base + 50, extend=extend.both, color=refColor, width=1)
else
lOb = line.new(bar_index - 1, base + toBand(obLvl), bar_index, base + toBand(obLvl), extend=extend.both, color=showObOs ? refColor : na, width=1)
lOs = line.new(bar_index - 1, base + toBand(osLvl), bar_index, base + toBand(osLvl), extend=extend.both, color=showObOs ? refColor : na, width=1)
if showZone
linefill.new(lOb, lOs, zoneColor)
if showMid and not isMacd
line.new(bar_index - 1, base + 50, bar_index, base + 50, extend=extend.both, color=midColor, width=1, style=line.style_dotted)
drawn
// @function Keeps the tag right of a band up to date with timeframe name and oscillator value.
// @param vis Whether the slot is active.
// @param lbl Timeframe name of the slot.
// @param base Bottom of the slot's band in pane coordinates.
// @param r Raw oscillator value.
// @returns The tag label (na when hidden).
bandTag(bool vis, string lbl, float base, float r) =>
var label tag = na
if barstate.islast
label.delete(tag)
tag := na
if vis and showBandTags
tag := label.new(bar_index + 1, base + 50, lbl + " " + fmtOsc(r), style=label.style_label_left, color=tagBg, textcolor=chart.fg_color, size=size.small)
tag
// @function Picks the more recent of the latest bullish and bearish divergence of a slot.
// @param lAge Age of the latest bullish divergence in bars.
// @param lKind Its kind (1 regular, 2 hidden).
// @param lT Its pivot time.
// @param hAge Age of the latest bearish divergence in bars.
// @param hKind Its kind (1 regular, 2 hidden).
// @param hT Its pivot time.
// @returns [signal text, age in bars, pivot time, direction (1 bull, -1 bear, 0 none)].
sigInfo(int lAge, int lKind, int lT, int hAge, int hKind, int hT) =>
string sig = "-"
int age = na
int t = na
int dir = 0
if not na(lAge)
sig := lKind == 2 ? "H Bull" : "Bull"
age := lAge
t := lT
dir := 1
if not na(hAge) and (na(age) or hAge < age)
sig := hKind == 2 ? "H Bear" : "Bear"
age := hAge
t := hT
dir := -1
[sig, age, t, dir]
// @function Writes one timeframe row of the summary table.
// @param tbl Target table.
// @param row Row index.
// @param lbl Timeframe name of the slot.
// @param r Raw oscillator value.
// @param lAge Age of the latest bullish divergence in bars.
// @param lKind Its kind (1 regular, 2 hidden).
// @param lT Its pivot time.
// @param hAge Age of the latest bearish divergence in bars.
// @param hKind Its kind (1 regular, 2 hidden).
// @param hT Its pivot time.
// @returns Nothing of use; called for its table output.
drawRow(table tbl, int row, string lbl, float r, int lAge, int lKind, int lT, int hAge, int hKind, int hT) =>
[sig, age, t, dir] = sigInfo(lAge, lKind, lT, hAge, hKind, hT)
fresh = not na(age) and age <= freshBars
color fg = chart.fg_color
color oscBg = na(r) ? tableBg : r >= obLvl ? color.new(obColor, 60) : r <= osLvl ? color.new(osColor, 60) : tableBg
color sigCol = dir > 0 ? bullColor : dir < 0 ? bearColor : color.gray
color sigBg = dir == 0 ? tableBg : color.new(sigCol, fresh ? 25 : 80)
color sigFg = dir != 0 and fresh ? color.white : fg
table.cell(tbl, 0, row, lbl, text_color=fg, bgcolor=tableBg, text_size=tableSize)
table.cell(tbl, 1, row, fmtOsc(r), text_color=fg, bgcolor=oscBg, text_size=tableSize)
table.cell(tbl, 2, row, sig, text_color=sigFg, bgcolor=sigBg, text_size=tableSize)
table.cell(tbl, 3, row, na(age) ? "-" : str.tostring(age) + " Bars", text_color=fg, bgcolor=tableBg, text_size=tableSize)
table.cell(tbl, 4, row, na(t) ? "-" : fmtTime(t), text_color=fg, bgcolor=tableBg, text_size=tableSize)
// ─────────────────────────────────────────────────────────────────────────────
// Timeframe slots
// ─────────────────────────────────────────────────────────────────────────────
// Name per slot: custom Scalping Intraday Swing Position
lbl1 = slotTf(tfIn1, "1m", "5m", "15m", "4H")
lbl2 = slotTf(tfIn2, "3m", "15m", "1H", "12H")
lbl3 = slotTf(tfIn3, "5m", "30m", "6H", "1D")
lbl4 = slotTf(tfIn4, "15m", "1H", "12H", "3D")
lbl5 = slotTf(tfIn5, "30m", "4H", "1D", "1W")
lbl6 = slotTf(tfIn6, "1H", "12H", "3D", "2W")
lbl7 = slotTf(tfIn7, "4H", "1D", "1W", "1M")
tf1 = tfCode(lbl1)
tf2 = tfCode(lbl2)
tf3 = tfCode(lbl3)
tf4 = tfCode(lbl4)
tf5 = tfCode(lbl5)
tf6 = tfCode(lbl6)
tf7 = tfCode(lbl7)
sec1 = timeframe.in_seconds(tf1)
sec2 = timeframe.in_seconds(tf2)
sec3 = timeframe.in_seconds(tf3)
sec4 = timeframe.in_seconds(tf4)
sec5 = timeframe.in_seconds(tf5)
sec6 = timeframe.in_seconds(tf6)
sec7 = timeframe.in_seconds(tf7)
// A slot is active when it is ticked and not too far below the chart timeframe
chartSec = timeframe.in_seconds(timeframe.period)
minSec = chartSec / minTfDivisor
vis1 = use1 and sec1 >= minSec
vis2 = use2 and sec2 >= minSec
vis3 = use3 and sec3 >= minSec
vis4 = use4 and sec4 >= minSec
vis5 = use5 and sec5 >= minSec
vis6 = use6 and sec6 >= minSec
vis7 = use7 and sec7 >= minSec
// Band layout: active slots are stacked top-down in slot order (k = position, 0 = top)
nVis = (vis1 ? 1 : 0) + (vis2 ? 1 : 0) + (vis3 ? 1 : 0) + (vis4 ? 1 : 0) + (vis5 ? 1 : 0) + (vis6 ? 1 : 0) + (vis7 ? 1 : 0)
k1 = 0
k2 = k1 + (vis1 ? 1 : 0)
k3 = k2 + (vis2 ? 1 : 0)
k4 = k3 + (vis3 ? 1 : 0)
k5 = k4 + (vis4 ? 1 : 0)
k6 = k5 + (vis5 ? 1 : 0)
k7 = k6 + (vis6 ? 1 : 0)
base1 = (nVis - 1 - k1) * bandH
base2 = (nVis - 1 - k2) * bandH
base3 = (nVis - 1 - k3) * bandH
base4 = (nVis - 1 - k4) * bandH
base5 = (nVis - 1 - k5) * bandH
base6 = (nVis - 1 - k6) * bandH
base7 = (nVis - 1 - k7) * bandH
// Per-timeframe styling: lower timeframes fade, higher timeframes get thicker lines and larger marks
lowCnt = (vis1 and sec1 < chartSec ? 1 : 0) + (vis2 and sec2 < chartSec ? 1 : 0) + (vis3 and sec3 < chartSec ? 1 : 0) + (vis4 and sec4 < chartSec ? 1 : 0) + (vis5 and sec5 < chartSec ? 1 : 0) + (vis6 and sec6 < chartSec ? 1 : 0) + (vis7 and sec7 < chartSec ? 1 : 0)
// @function Counts the active slots with a timeframe shorter than x.
// @param x Duration in seconds.
// @returns Number of active slots below x.
rankBelow(int x) =>
(vis1 and sec1 < x ? 1 : 0) + (vis2 and sec2 < x ? 1 : 0) + (vis3 and sec3 < x ? 1 : 0) + (vis4 and sec4 < x ? 1 : 0) + (vis5 and sec5 < x ? 1 : 0) + (vis6 and sec6 < x ? 1 : 0) + (vis7 and sec7 < x ? 1 : 0)
// @function Counts the active slots above the chart timeframe up to and including x.
// @param x Duration in seconds.
// @returns Rank of x among the higher timeframes (1 = first above the chart timeframe).
rankAbove(int x) =>
(vis1 and sec1 > chartSec and sec1 <= x ? 1 : 0) + (vis2 and sec2 > chartSec and sec2 <= x ? 1 : 0) + (vis3 and sec3 > chartSec and sec3 <= x ? 1 : 0) + (vis4 and sec4 > chartSec and sec4 <= x ? 1 : 0) + (vis5 and sec5 > chartSec and sec5 <= x ? 1 : 0) + (vis6 and sec6 > chartSec and sec6 <= x ? 1 : 0) + (vis7 and sec7 > chartSec and sec7 <= x ? 1 : 0)
// @function Transparency of a timeframe: lower timeframes fade towards the configured maximum.
// @param x Duration of the timeframe in seconds.
// @returns Transparency 0–100.
tfTransp(int x) =>
x < chartSec and lowCnt > 0 ? int(math.round(maxTransp * (lowCnt - rankBelow(x)) / lowCnt)) : 0
// @function Line width of a timeframe on the price chart.
// @param x Duration of the timeframe in seconds.
// @returns Base width plus one per higher-timeframe rank, limited to the maximum.
tfWidth(int x) =>
math.min(maxWidth, baseWidth + (x > chartSec ? rankAbove(x) : 0))
// @function Interpolates a size between the smallest and the largest active slot.
// @param k Stack position of the slot (0 = smallest timeframe shown).
// @param minS Size at the first position.
// @param maxS Size at the last position.
// @returns Rounded size.
slotSize(int k, int minS, int maxS) =>
int(math.round(minS + (maxS - minS) * (nVis > 1 ? k / (nVis - 1.0) : 1.0)))
tr1 = tfTransp(sec1), w1 = tfWidth(sec1), ds1 = slotSize(k1, dotMin, markSize), cs1 = slotSize(k1, chartMarkMin, chartMarkMax)
tr2 = tfTransp(sec2), w2 = tfWidth(sec2), ds2 = slotSize(k2, dotMin, markSize), cs2 = slotSize(k2, chartMarkMin, chartMarkMax)
tr3 = tfTransp(sec3), w3 = tfWidth(sec3), ds3 = slotSize(k3, dotMin, markSize), cs3 = slotSize(k3, chartMarkMin, chartMarkMax)
tr4 = tfTransp(sec4), w4 = tfWidth(sec4), ds4 = slotSize(k4, dotMin, markSize), cs4 = slotSize(k4, chartMarkMin, chartMarkMax)
tr5 = tfTransp(sec5), w5 = tfWidth(sec5), ds5 = slotSize(k5, dotMin, markSize), cs5 = slotSize(k5, chartMarkMin, chartMarkMax)
tr6 = tfTransp(sec6), w6 = tfWidth(sec6), ds6 = slotSize(k6, dotMin, markSize), cs6 = slotSize(k6, chartMarkMin, chartMarkMax)
tr7 = tfTransp(sec7), w7 = tfWidth(sec7), ds7 = slotSize(k7, dotMin, markSize), cs7 = slotSize(k7, chartMarkMin, chartMarkMax)
// ─────────────────────────────────────────────────────────────────────────────
// Scan
// ─────────────────────────────────────────────────────────────────────────────
// r = oscillator, d = band position, l… = bullish side, h… = bearish side (see divScan)
[r1, d1, la1, lk1, lt1, lp1, lo1, ltp1, lpp1, lop1, ha1, hk1, ht1, hp1, ho1, htp1, hpp1, hop1] = tfScan(tf1, vis1)
[r2, d2, la2, lk2, lt2, lp2, lo2, ltp2, lpp2, lop2, ha2, hk2, ht2, hp2, ho2, htp2, hpp2, hop2] = tfScan(tf2, vis2)
[r3, d3, la3, lk3, lt3, lp3, lo3, ltp3, lpp3, lop3, ha3, hk3, ht3, hp3, ho3, htp3, hpp3, hop3] = tfScan(tf3, vis3)
[r4, d4, la4, lk4, lt4, lp4, lo4, ltp4, lpp4, lop4, ha4, hk4, ht4, hp4, ho4, htp4, hpp4, hop4] = tfScan(tf4, vis4)
[r5, d5, la5, lk5, lt5, lp5, lo5, ltp5, lpp5, lop5, ha5, hk5, ht5, hp5, ho5, htp5, hpp5, hop5] = tfScan(tf5, vis5)
[r6, d6, la6, lk6, lt6, lp6, lo6, ltp6, lpp6, lop6, ha6, hk6, ht6, hp6, ho6, htp6, hpp6, hop6] = tfScan(tf6, vis6)
[r7, d7, la7, lk7, lt7, lp7, lo7, ltp7, lpp7, lop7, ha7, hk7, ht7, hp7, ho7, htp7, hpp7, hop7] = tfScan(tf7, vis7)
// ─────────────────────────────────────────────────────────────────────────────
// Pane output
// ─────────────────────────────────────────────────────────────────────────────
// bu / be hold the timeframe name on the bar where a bullish / bearish divergence is detected
bu1 = drawDiv(vis1, lbl1, base1, d1, tr1, w1, ds1, lt1, lk1, lp1, lo1, ltp1, lpp1, lop1, true)
be1 = drawDiv(vis1, lbl1, base1, d1, tr1, w1, ds1, ht1, hk1, hp1, ho1, htp1, hpp1, hop1, false)
bu2 = drawDiv(vis2, lbl2, base2, d2, tr2, w2, ds2, lt2, lk2, lp2, lo2, ltp2, lpp2, lop2, true)
be2 = drawDiv(vis2, lbl2, base2, d2, tr2, w2, ds2, ht2, hk2, hp2, ho2, htp2, hpp2, hop2, false)
bu3 = drawDiv(vis3, lbl3, base3, d3, tr3, w3, ds3, lt3, lk3, lp3, lo3, ltp3, lpp3, lop3, true)
be3 = drawDiv(vis3, lbl3, base3, d3, tr3, w3, ds3, ht3, hk3, hp3, ho3, htp3, hpp3, hop3, false)
bu4 = drawDiv(vis4, lbl4, base4, d4, tr4, w4, ds4, lt4, lk4, lp4, lo4, ltp4, lpp4, lop4, true)
be4 = drawDiv(vis4, lbl4, base4, d4, tr4, w4, ds4, ht4, hk4, hp4, ho4, htp4, hpp4, hop4, false)
bu5 = drawDiv(vis5, lbl5, base5, d5, tr5, w5, ds5, lt5, lk5, lp5, lo5, ltp5, lpp5, lop5, true)
be5 = drawDiv(vis5, lbl5, base5, d5, tr5, w5, ds5, ht5, hk5, hp5, ho5, htp5, hpp5, hop5, false)
bu6 = drawDiv(vis6, lbl6, base6, d6, tr6, w6, ds6, lt6, lk6, lp6, lo6, ltp6, lpp6, lop6, true)
be6 = drawDiv(vis6, lbl6, base6, d6, tr6, w6, ds6, ht6, hk6, hp6, ho6, htp6, hpp6, hop6, false)
bu7 = drawDiv(vis7, lbl7, base7, d7, tr7, w7, ds7, lt7, lk7, lp7, lo7, ltp7, lpp7, lop7, true)
be7 = drawDiv(vis7, lbl7, base7, d7, tr7, w7, ds7, ht7, hk7, hp7, ho7, htp7, hpp7, hop7, false)
bandFrame(vis1, base1)
bandFrame(vis2, base2)
bandFrame(vis3, base3)
bandFrame(vis4, base4)
bandFrame(vis5, base5)
bandFrame(vis6, base6)
bandFrame(vis7, base7)
bandTag(vis1, lbl1, base1, r1)
bandTag(vis2, lbl2, base2, r2)
bandTag(vis3, lbl3, base3, r3)
bandTag(vis4, lbl4, base4, r4)
bandTag(vis5, lbl5, base5, r5)
bandTag(vis6, lbl6, base6, r6)
bandTag(vis7, lbl7, base7, r7)
plot(vis1 and showOsc ? base1 + d1 : na, "Osc band 1", color=oscColor(r1), display=display.pane)
plot(vis2 and showOsc ? base2 + d2 : na, "Osc band 2", color=oscColor(r2), display=display.pane)
plot(vis3 and showOsc ? base3 + d3 : na, "Osc band 3", color=oscColor(r3), display=display.pane)
plot(vis4 and showOsc ? base4 + d4 : na, "Osc band 4", color=oscColor(r4), display=display.pane)
plot(vis5 and showOsc ? base5 + d5 : na, "Osc band 5", color=oscColor(r5), display=display.pane)
plot(vis6 and showOsc ? base6 + d6 : na, "Osc band 6", color=oscColor(r6), display=display.pane)
plot(vis7 and showOsc ? base7 + d7 : na, "Osc band 7", color=oscColor(r7), display=display.pane)
// ─────────────────────────────────────────────────────────────────────────────
// Signals of the current bar
// ─────────────────────────────────────────────────────────────────────────────
// One timeframe name per line; empty when nothing was detected on this bar
string bullTxt = bu1
bullTxt := joinTxt(bullTxt, bu2, "\n")
bullTxt := joinTxt(bullTxt, bu3, "\n")
bullTxt := joinTxt(bullTxt, bu4, "\n")
bullTxt := joinTxt(bullTxt, bu5, "\n")
bullTxt := joinTxt(bullTxt, bu6, "\n")
bullTxt := joinTxt(bullTxt, bu7, "\n")
string bearTxt = be1
bearTxt := joinTxt(bearTxt, be2, "\n")
bearTxt := joinTxt(bearTxt, be3, "\n")
bearTxt := joinTxt(bearTxt, be4, "\n")
bearTxt := joinTxt(bearTxt, be5, "\n")
bearTxt := joinTxt(bearTxt, be6, "\n")
bearTxt := joinTxt(bearTxt, be7, "\n")
bullTfs = str.replace_all(bullTxt, "\n", " · ")
bearTfs = str.replace_all(bearTxt, "\n", " · ")
// Number of active timeframes whose latest divergence is still fresh
freshBullCount = (vis1 and la1 <= freshBars ? 1 : 0) + (vis2 and la2 <= freshBars ? 1 : 0) + (vis3 and la3 <= freshBars ? 1 : 0) + (vis4 and la4 <= freshBars ? 1 : 0) + (vis5 and la5 <= freshBars ? 1 : 0) + (vis6 and la6 <= freshBars ? 1 : 0) + (vis7 and la7 <= freshBars ? 1 : 0)
freshBearCount = (vis1 and ha1 <= freshBars ? 1 : 0) + (vis2 and ha2 <= freshBars ? 1 : 0) + (vis3 and ha3 <= freshBars ? 1 : 0) + (vis4 and ha4 <= freshBars ? 1 : 0) + (vis5 and ha5 <= freshBars ? 1 : 0) + (vis6 and ha6 <= freshBars ? 1 : 0) + (vis7 and ha7 <= freshBars ? 1 : 0)
plot(freshBullCount, "Fresh bull TFs", color=bullColor, display=display.data_window)
plot(freshBearCount, "Fresh bear TFs", color=bearColor, display=display.data_window)
// ─────────────────────────────────────────────────────────────────────────────
// Price chart markers
// ─────────────────────────────────────────────────────────────────────────────
// Marker size follows the largest timeframe that fired on this bar
bullSz = math.max(bu1 != "" ? cs1 : 0, bu2 != "" ? cs2 : 0, bu3 != "" ? cs3 : 0, bu4 != "" ? cs4 : 0, bu5 != "" ? cs5 : 0, bu6 != "" ? cs6 : 0, bu7 != "" ? cs7 : 0)
bearSz = math.max(be1 != "" ? cs1 : 0, be2 != "" ? cs2 : 0, be3 != "" ? cs3 : 0, be4 != "" ? cs4 : 0, be5 != "" ? cs5 : 0, be6 != "" ? cs6 : 0, be7 != "" ? cs7 : 0)
if showChartMarks and bullTxt != ""
label.new(bar_index, low, showChartText ? bullTfs : "", yloc=yloc.belowbar, style=label.style_triangleup, color=bullColor, textcolor=bullColor, size=bullSz, tooltip="Bullish divergence detected: " + bullTfs, force_overlay=true)
if showChartMarks and bearTxt != ""
label.new(bar_index, high, showChartText ? bearTfs : "", yloc=yloc.abovebar, style=label.style_triangledown, color=bearColor, textcolor=bearColor, size=bearSz, tooltip="Bearish divergence detected: " + bearTfs, force_overlay=true)
// ─────────────────────────────────────────────────────────────────────────────
// Alerts
// ─────────────────────────────────────────────────────────────────────────────
alertcondition(bullTxt != "", "MTF bullish divergence", "[Mad] MTF: new bullish divergence on {{ticker}}")
alertcondition(bearTxt != "", "MTF bearish divergence", "[Mad] MTF: new bearish divergence on {{ticker}}")
if bullTxt != "" or bearTxt != ""
alert("[Mad] MTF Div " + syminfo.tickerid + "\n" + joinTxt(bullTxt == "" ? "" : "Bull: " + bullTfs, bearTxt == "" ? "" : "Bear: " + bearTfs, "\n"), alert.freq_once_per_bar_close)
// ─────────────────────────────────────────────────────────────────────────────
// Summary table
// ─────────────────────────────────────────────────────────────────────────────
var table scanTbl = table.new(tablePos, 5, 9, border_width=1, border_color=color.new(color.gray, 60), frame_width=1, frame_color=color.new(color.gray, 40), force_overlay=true)
if showTable and barstate.islast
table.clear(scanTbl, 0, 0, 4, 8)
color hdrBg = color.new(tableBg, 70)
table.cell(scanTbl, 0, 0, "TF", text_color=chart.fg_color, bgcolor=hdrBg, text_size=tableSize)
table.cell(scanTbl, 1, 0, oscShort, text_color=chart.fg_color, bgcolor=hdrBg, text_size=tableSize)
table.cell(scanTbl, 2, 0, "Signal", text_color=chart.fg_color, bgcolor=hdrBg, text_size=tableSize)
table.cell(scanTbl, 3, 0, "Age", text_color=chart.fg_color, bgcolor=hdrBg, text_size=tableSize)
table.cell(scanTbl, 4, 0, "Pivot", text_color=chart.fg_color, bgcolor=hdrBg, text_size=tableSize)
int row = 1
if vis1
drawRow(scanTbl, row, lbl1, r1, la1, lk1, lt1, ha1, hk1, ht1)
row += 1
if vis2
drawRow(scanTbl, row, lbl2, r2, la2, lk2, lt2, ha2, hk2, ht2)
row += 1
if vis3
drawRow(scanTbl, row, lbl3, r3, la3, lk3, lt3, ha3, hk3, ht3)
row += 1
if vis4
drawRow(scanTbl, row, lbl4, r4, la4, lk4, lt4, ha4, hk4, ht4)
row += 1
if vis5
drawRow(scanTbl, row, lbl5, r5, la5, lk5, lt5, ha5, hk5, ht5)
row += 1
if vis6
drawRow(scanTbl, row, lbl6, r6, la6, lk6, lt6, ha6, hk6, ht6)
row += 1
if vis7
drawRow(scanTbl, row, lbl7, r7, la7, lk7, lt7, ha7, hk7, ht7)
row += 1
color sumBg = color.new(tableBg, 80)
table.cell(scanTbl, 0, row, "Fresh", text_color=chart.fg_color, bgcolor=sumBg, text_size=tableSize)
table.cell(scanTbl, 1, row, "≤" + str.tostring(freshBars), text_color=chart.fg_color, bgcolor=sumBg, text_size=tableSize)
table.cell(scanTbl, 2, row, "Bull " + str.tostring(freshBullCount), text_color=color.white, bgcolor=color.new(bullColor, freshBullCount > 0 ? 25 : 80), text_size=tableSize)
table.cell(scanTbl, 3, row, "Bear " + str.tostring(freshBearCount), text_color=color.white, bgcolor=color.new(bearColor, freshBearCount > 0 ? 25 : 80), text_size=tableSize)
table.cell(scanTbl, 4, row, "TFs", text_color=chart.fg_color, bgcolor=sumBg, text_size=tableSize)