本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// Credits & licensing
// The "Support/Resistance Breaks & Retests" module below is based on the open-source
// "Support and Resistance (High Volume Boxes)" by ChartPrime, licensed under the
// Mozilla Public License 2.0 (https://mozilla.org/MPL/2.0/). Modifications: inputs grouped,
// cross checks made to run on every bar, and old boxes/labels capped. All other modules
// (order blocks, fair value gaps, liquidity levels, sessions, RSI divergence chains,
// RSI/MACD pane, EMAs, VWAP) are original to this script.
indicator("Order Blocks & Fair Value Gaps (until tapped)", shorttitle = "OB + FVG", overlay = false,
max_boxes_count = 500, max_lines_count = 500, max_labels_count = 100, max_bars_back = 500)
// ─────────────────────────────────────────────────────────────────────────────
// Definitions used
// FVG (3-candle imbalance)
// Bullish: low of candle 3 > high of candle 1, middle candle closes above candle 1's high.
// Bearish: high of candle 3 < low of candle 1, middle candle closes below candle 1's low.
// Gaps smaller than (min size × ATR 14) are ignored as noise.
// Order block (origin of a structure-breaking move)
// Bullish: price CLOSES above the last confirmed swing high (break of structure).
// The OB is the down-close candle with the lowest low between that swing and the break.
// Bearish: price CLOSES below the last confirmed swing low.
// The OB is the up-close candle with the highest high between that swing and the break.
// Quality filters (each optional, all on by default):
// - displacement: the move away from the OB leaves an FVG
// - at the swing: the OB candle is the swing extreme of that move (within a tolerance)
// - liquidity sweep: that swing took out the lows/highs of the N bars before it
// A zone stays on the chart (extended right) until price taps it, then it is removed.
// Liquidity levels (resting stops above old highs / below old lows)
// Previous month / week / day / 4H / 1H high & low, and the high & low of the last
// completed Asia, London and New York sessions. A level is "swept" when price trades
// beyond it; swept levels are dotted & faded (or hidden) until the next period resets them.
// EMA Multi Cross + VWAP + S/R Breaks & Retests (merged from the standalone script)
// 14 EMAs with 9/21 cross marks, VWAP, and volume-filtered pivot S/R boxes with break/hold signals.
// ─────────────────────────────────────────────────────────────────────────────
// ── Inputs ──
const string G_OB = "Order Blocks"
const string G_FVG = "Fair Value Gaps"
const string G_TAP = "Tap rule"
const string G_HTF = "Higher timeframe"
const string G_STY = "Style & limits"
showOB = input.bool(true, "Show order blocks", group = G_OB)
obLen = input.int(10, "Swing length", minval = 2, maxval = 50, group = G_OB,
tooltip = "Bars on each side that confirm a swing high/low. Smaller = more (minor) order blocks, larger = fewer, more significant ones.")
obBody = input.bool(false, "Use candle body instead of full wick range", group = G_OB)
obNeedFvg = input.bool(true, "Only if the move left an FVG (displacement)", group = G_OB,
tooltip = "Keeps only order blocks whose move away created an imbalance. Fewer, higher-quality zones.")
obAtSwing = input.bool(true, "Only if the OB is at the swing extreme", group = G_OB,
tooltip = "The OB candle must be at (or within the tolerance of) the lowest low / highest high of the move that broke structure, i.e. the OB IS the swing point, not a candle somewhere mid-leg.")
obSwTol = input.float(0.3, " ↳ swing tolerance (× ATR)", minval = 0, step = 0.1, group = G_OB)
obSweep = input.bool(true, "Only if the swing swept liquidity", group = G_OB,
tooltip = "The swing that formed the OB must take out the lowest low (bullish) / highest high (bearish) of the N bars before the OB candle, i.e. it grabbed the stops resting there before reversing.")
obSweepN = input.int(30, " ↳ sweep lookback (bars)", minval = 5, maxval = 200, group = G_OB)
showFVG = input.bool(true, "Show fair value gaps", group = G_FVG)
fvgMinAtr = input.float(0.2, "Minimum gap size (× ATR 14)", minval = 0, step = 0.05, group = G_FVG,
tooltip = "0 = show every gap. 0.2-0.5 filters out tiny gaps.")
showCE = input.bool(true, "Show 50% line (consequent encroachment)", group = G_FVG)
tapMode = input.string("Touch", "Zone is tapped when price", options = ["Touch", "Reaches 50%", "Fills completely"], group = G_TAP,
tooltip = "Touch: first wick into the zone. Reaches 50%: wick reaches the midpoint. Fills completely: wick reaches the far edge.")
useHTF = input.bool(false, "Also show zones from a higher timeframe", group = G_HTF)
htf = input.timeframe("240", "Higher timeframe", group = G_HTF,
tooltip = "Only used when it is higher than the chart timeframe. HTF zones appear after the HTF candle closes (no repainting).")
const string G_LIQ = "Liquidity levels"
const string G_SES = "Session liquidity (intraday charts)"
showLiq = input.bool(true, "Show liquidity levels", group = G_LIQ)
lvMonth = input.bool(true, "Previous month high/low", group = G_LIQ, inline = "m")
cMonth = input.color(#e91e63, "", group = G_LIQ, inline = "m")
lvWeek = input.bool(true, "Previous week high/low", group = G_LIQ, inline = "w")
cWeek = input.color(#9c27b0, "", group = G_LIQ, inline = "w")
lvDay = input.bool(true, "Previous day high/low", group = G_LIQ, inline = "d")
cDay = input.color(#ff9800, "", group = G_LIQ, inline = "d")
lv4h = input.bool(true, "Previous 4H high/low", group = G_LIQ, inline = "4")
c4h = input.color(#00bcd4, "", group = G_LIQ, inline = "4")
lv1h = input.bool(false, "Previous 1H high/low", group = G_LIQ, inline = "1")
c1h = input.color(#787b86, "", group = G_LIQ, inline = "1")
sweptMode = input.string("Keep, dotted", "Once a level is swept", options = ["Keep, dotted", "Hide"], group = G_LIQ,
tooltip = "Swept = price traded beyond the level (stops taken). The level resets when the next period completes.")
lvWidth = input.int(1, "Line width", minval = 1, maxval = 4, group = G_LIQ)
showSes = input.bool(true, "Show previous session high/low", group = G_SES,
tooltip = "Uses each market's local time, so daylight saving is handled automatically.")
asiaOn = input.bool(true, "Asia (Tokyo 09:00-18:00)", group = G_SES, inline = "as")
cAsia = input.color(#fbc02d, "", group = G_SES, inline = "as")
londonOn = input.bool(true, "London (08:00-17:00)", group = G_SES, inline = "ld")
cLondon = input.color(#2962ff, "", group = G_SES, inline = "ld")
nyOn = input.bool(true, "New York (08:00-17:00)", group = G_SES, inline = "ny")
cNY = input.color(#4caf50, "", group = G_SES, inline = "ny")
maxZones = input.int(30, "Max zones kept per type", minval = 1, maxval = 120, group = G_STY)
cBullOB = input.color(color.new(#089981, 78), "Order blocks: bullish / bearish", group = G_STY, inline = "ob")
cBearOB = input.color(color.new(#f23645, 78), "", group = G_STY, inline = "ob")
cBullFVG = input.color(color.new(#2962ff, 85), "FVGs: bullish / bearish", group = G_STY, inline = "fvg")
cBearFVG = input.color(color.new(#ff9800, 85), "", group = G_STY, inline = "fvg")
showText = input.bool(true, "Show zone labels", group = G_STY)
// ── Zone object ──
type Zone
box bx
line ce
float top
float bot
bool bull
int born
string name
// ── Detection (also run inside request.security for the higher timeframe) ──
fvgDetect(float minAtr) =>
float atr = ta.atr(14)
bool bull = low > high[2] and close[1] > high[2] and (low - high[2]) >= minAtr * atr
bool bear = high < low[2] and close[1] < low[2] and (low[2] - high) >= minAtr * atr
// bull flag, bull top, bull bottom, bear flag, bear top, bear bottom, left edge time
[bull, low, high[2], bear, low[2], high, time[2]]
obDetect(int len, bool useBody, bool needFvg, bool atSwing, float swTol, bool needSweep, int sweepN) =>
float atr = ta.atr(14)
float ph = ta.pivothigh(high, len, len)
float pl = ta.pivotlow(low, len, len)
var float swH = na
var int swHi = na
var float swL = na
var int swLi = na
if not na(ph)
swH := ph
swHi := bar_index - len
if not na(pl)
swL := pl
swLi := bar_index - len
bool bull = false
float bTop = na
float bBot = na
int bTime = na
bool bear = false
float sTop = na
float sBot = na
int sTime = na
// Bullish break of structure → bullish OB
if not na(swH) and close > swH
int span = math.min(bar_index - swHi, 300)
float lo = na
int at = na
for i = 1 to span
if close[i] < open[i] and (na(lo) or low[i] < lo)
lo := low[i]
at := i
if not na(at)
float legLo = low[at]
for i = 1 to span
legLo := math.min(legLo, low[i])
bool okFvg = not needFvg
if needFvg and at >= 2
for j = 0 to at - 2
if low[j] > high[j + 2]
okFvg := true
break
bool okSwing = not atSwing or (low[at] - legLo) <= swTol * atr
float preLo = na
if needSweep
for k = at + 1 to math.min(at + sweepN, 450)
preLo := na(preLo) ? low[k] : math.min(preLo, low[k])
bool okSweep = not needSweep or (not na(preLo) and legLo < preLo)
if okFvg and okSwing and okSweep
bull := true
bTop := useBody ? math.max(open[at], close[at]) : high[at]
bBot := useBody ? math.min(open[at], close[at]) : low[at]
bTime := time[at]
swH := na
// Bearish break of structure → bearish OB
if not na(swL) and close < swL
int span = math.min(bar_index - swLi, 300)
float hi = na
int at = na
for i = 1 to span
if close[i] > open[i] and (na(hi) or high[i] > hi)
hi := high[i]
at := i
if not na(at)
float legHi = high[at]
for i = 1 to span
legHi := math.max(legHi, high[i])
bool okFvg = not needFvg
if needFvg and at >= 2
for j = 0 to at - 2
if high[j] < low[j + 2]
okFvg := true
break
bool okSwing = not atSwing or (legHi - high[at]) <= swTol * atr
float preHi = na
if needSweep
for k = at + 1 to math.min(at + sweepN, 450)
preHi := na(preHi) ? high[k] : math.max(preHi, high[k])
bool okSweep = not needSweep or (not na(preHi) and legHi > preHi)
if okFvg and okSwing and okSweep
bear := true
sTop := useBody ? math.max(open[at], close[at]) : high[at]
sBot := useBody ? math.min(open[at], close[at]) : low[at]
sTime := time[at]
swL := na
[bull, bTop, bBot, bTime, bear, sTop, sBot, sTime]
// Higher-timeframe values from the last CLOSED HTF candle (used with lookahead_on → no repaint)
htfData() =>
[fb, fbt, fbb, fs, fst, fsb, ft] = fvgDetect(fvgMinAtr)
[ob, obt, obb, obtm, os, ost, osb, ostm] = obDetect(obLen, obBody, obNeedFvg, obAtSwing, obSwTol, obSweep, obSweepN)
[fb[1], fbt[1], fbb[1], fs[1], fst[1], fsb[1], ft[1], ob[1], obt[1], obb[1], obtm[1], os[1], ost[1], osb[1], ostm[1]]
tfLabel(string tf) =>
int s = timeframe.in_seconds(tf)
str.endswith(tf, "M") ? tf :
s % 604800 == 0 ? str.tostring(s / 604800, "#") + "W" :
s % 86400 == 0 ? str.tostring(s / 86400, "#") + "D" :
s % 3600 == 0 ? str.tostring(s / 3600, "#") + "H" :
str.tostring(s / 60, "#") + "m"
// ── Zone management ──
var array<Zone> obZones = array.new<Zone>()
var array<Zone> fvgZones = array.new<Zone>()
addZone(array<Zone> arr, float top, float bot, int leftTime, bool bull, color col, string name, bool withCE) =>
box b = box.new(leftTime, top, time, bot, xloc = xloc.bar_time, extend = extend.right,
border_color = color.new(col, 40), bgcolor = col,
text = showText ? name : "", text_size = size.tiny, text_color = color.new(col, 0),
text_halign = text.align_left, text_valign = text.align_center, force_overlay = true)
line l = na
if withCE
l := line.new(leftTime, (top + bot) / 2, time, (top + bot) / 2, xloc = xloc.bar_time,
extend = extend.right, color = color.new(col, 30), style = line.style_dashed, force_overlay = true)
arr.push(Zone.new(b, l, top, bot, bull, bar_index, name))
if arr.size() > maxZones
Zone old = arr.shift()
old.bx.delete()
if not na(old.ce)
old.ce.delete()
isTapped(Zone z) =>
float lvl = switch tapMode
"Touch" => z.bull ? z.top : z.bot
"Reaches 50%" => (z.top + z.bot) / 2
=> z.bull ? z.bot : z.top
z.bull ? low <= lvl : high >= lvl
processTaps(array<Zone> arr) =>
int n = arr.size()
if n > 0
for i = n - 1 to 0
Zone z = arr.get(i)
if bar_index > z.born and isTapped(z)
alert(syminfo.ticker + ": " + z.name + " tapped (" + str.tostring(z.bot, format.mintick) + " - " + str.tostring(z.top, format.mintick) + ")", alert.freq_once_per_bar)
z.bx.delete()
if not na(z.ce)
z.ce.delete()
arr.remove(i)
// ── Run detection ──
[cFb, cFbt, cFbb, cFs, cFst, cFsb, cFt] = fvgDetect(fvgMinAtr)
[cOb, cObt, cObb, cObtm, cOs, cOst, cOsb, cOstm] = obDetect(obLen, obBody, obNeedFvg, obAtSwing, obSwTol, obSweep, obSweepN)
[hFb, hFbt, hFbb, hFs, hFst, hFsb, hFt, hOb, hObt, hObb, hObtm, hOs, hOst, hOsb, hOstm] =
request.security(syminfo.tickerid, htf, htfData(), lookahead = barmerge.lookahead_on)
bool htfOn = useHTF and timeframe.in_seconds(htf) > timeframe.in_seconds(timeframe.period)
bool newHtf = timeframe.change(htf)
string hLbl = tfLabel(htf) + " "
// 1) remove zones tapped on this bar
if showOB
processTaps(obZones)
if showFVG
processTaps(fvgZones)
// 2) add zones that formed on this (closed) bar
if barstate.isconfirmed
if showFVG
if cFb
addZone(fvgZones, cFbt, cFbb, cFt, true, cBullFVG, "FVG", showCE)
if cFs
addZone(fvgZones, cFst, cFsb, cFt, false, cBearFVG, "FVG", showCE)
if showOB
if cOb
addZone(obZones, cObt, cObb, cObtm, true, cBullOB, "OB", false)
if cOs
addZone(obZones, cOst, cOsb, cOstm, false, cBearOB, "OB", false)
if htfOn and newHtf
if showFVG
if hFb
addZone(fvgZones, hFbt, hFbb, hFt, true, cBullFVG, hLbl + "FVG", showCE)
if hFs
addZone(fvgZones, hFst, hFsb, hFt, false, cBearFVG, hLbl + "FVG", showCE)
if showOB
if hOb
addZone(obZones, hObt, hObb, hObtm, true, cBullOB, hLbl + "OB", false)
if hOs
addZone(obZones, hOst, hOsb, hOstm, false, cBearOB, hLbl + "OB", false)
// Alerts for new zones (create an alert with "Any alert() function call")
if barstate.isconfirmed
if showOB and (cOb or cOs)
alert(syminfo.ticker + ": new " + (cOb ? "bullish" : "bearish") + " order block", alert.freq_once_per_bar_close)
if showFVG and (cFb or cFs)
alert(syminfo.ticker + ": new " + (cFb ? "bullish" : "bearish") + " FVG", alert.freq_once_per_bar_close)
// ─────────────────────────────────────────────────────────────────────────────
// Liquidity levels
// ─────────────────────────────────────────────────────────────────────────────
type Level
line ln
label lb
float price
bool isHigh
bool swept
string name
color col
// Move a level to a new price (a new period completed) and reset its "swept" state
setLevel(Level lv, float price, int startTime) =>
if not na(price) and not na(startTime)
lv.price := price
lv.swept := false
if na(lv.ln)
lv.ln := line.new(startTime, price, startTime + 1, price, xloc = xloc.bar_time, extend = extend.right,
color = lv.col, style = line.style_solid, width = lvWidth, force_overlay = true)
lv.lb := label.new(bar_index, price, lv.name, xloc = xloc.bar_index, color = color(na),
style = label.style_label_left, textcolor = lv.col, size = size.small, force_overlay = true)
else
lv.ln.set_xy1(startTime, price)
lv.ln.set_xy2(startTime + 1, price)
lv.ln.set_color(lv.col)
lv.ln.set_style(line.style_solid)
lv.lb.set_y(price)
lv.lb.set_text(lv.name)
lv.lb.set_textcolor(lv.col)
lv
// Mark a level swept once price trades beyond it
checkSweep(Level lv) =>
if not na(lv.price) and not lv.swept and (lv.isHigh ? high > lv.price : low < lv.price)
lv.swept := true
if sweptMode == "Hide"
lv.ln.set_color(color(na))
lv.lb.set_text("")
else
lv.ln.set_style(line.style_dotted)
lv.ln.set_color(color.new(lv.col, 55))
lv.lb.set_text(lv.name + " ✓")
lv.lb.set_textcolor(color.new(lv.col, 55))
alert(syminfo.ticker + ": " + lv.name + " swept (" + str.tostring(lv.price, format.mintick) + ")", alert.freq_once_per_bar)
// Previous completed period's high/low on a higher timeframe (no repaint)
prevHL(string tf) =>
request.security(syminfo.tickerid, tf, [high[1], low[1], time[1]], lookahead = barmerge.lookahead_on)
// High/low of the last COMPLETED session
sessionHL(string sess, string tz) =>
bool inS = not na(time(timeframe.period, sess, tz))
var float h = na
var float l = na
var int st = na
var float lastH = na
var float lastL = na
var int lastSt = na
bool ended = false
if inS and not inS[1]
h := high
l := low
st := time
else if inS
h := math.max(h, high)
l := math.min(l, low)
if not inS and inS[1] and not na(st)
lastH := h
lastL := l
lastSt := st
ended := true
[lastH, lastL, lastSt, ended]
tfFits(string tf) => timeframe.in_seconds(timeframe.period) <= timeframe.in_seconds(tf)
var Level pmh = Level.new(na, na, na, true, false, "PMH", cMonth)
var Level pml = Level.new(na, na, na, false, false, "PML", cMonth)
var Level pwh = Level.new(na, na, na, true, false, "PWH", cWeek)
var Level pwl = Level.new(na, na, na, false, false, "PWL", cWeek)
var Level pdh = Level.new(na, na, na, true, false, "PDH", cDay)
var Level pdl = Level.new(na, na, na, false, false, "PDL", cDay)
var Level h4h = Level.new(na, na, na, true, false, "4H High", c4h)
var Level h4l = Level.new(na, na, na, false, false, "4H Low", c4h)
var Level h1h = Level.new(na, na, na, true, false, "1H High", c1h)
var Level h1l = Level.new(na, na, na, false, false, "1H Low", c1h)
var Level ash = Level.new(na, na, na, true, false, "Asia High", cAsia)
var Level asl = Level.new(na, na, na, false, false, "Asia Low", cAsia)
var Level ldh = Level.new(na, na, na, true, false, "London High", cLondon)
var Level ldl = Level.new(na, na, na, false, false, "London Low", cLondon)
var Level nyh = Level.new(na, na, na, true, false, "NY High", cNY)
var Level nyl = Level.new(na, na, na, false, false, "NY Low", cNY)
var array<Level> levels = array.from(pmh, pml, pwh, pwl, pdh, pdl, h4h, h4l, h1h, h1l, ash, asl, ldh, ldl, nyh, nyl)
[mHi, mLo, mT] = prevHL("M")
[wHi, wLo, wT] = prevHL("W")
[dHi, dLo, dT] = prevHL("D")
[h4Hi, h4Lo, h4T] = prevHL("240")
[h1Hi, h1Lo, h1T] = prevHL("60")
[aHi, aLo, aT, aEnd] = sessionHL("0900-1800", "Asia/Tokyo")
[lHi, lLo, lT, lEnd] = sessionHL("0800-1700", "Europe/London")
[nHi, nLo, nT, nEnd] = sessionHL("0800-1700", "America/New_York")
bool sesOk = showLiq and showSes and timeframe.isintraday and timeframe.in_seconds(timeframe.period) <= 3600
// 1) a period just completed → move its levels
if showLiq
if lvMonth and tfFits("M") and mT != mT[1]
setLevel(pmh, mHi, mT)
setLevel(pml, mLo, mT)
if lvWeek and tfFits("W") and wT != wT[1]
setLevel(pwh, wHi, wT)
setLevel(pwl, wLo, wT)
if lvDay and tfFits("D") and dT != dT[1]
setLevel(pdh, dHi, dT)
setLevel(pdl, dLo, dT)
if lv4h and tfFits("240") and h4T != h4T[1]
setLevel(h4h, h4Hi, h4T)
setLevel(h4l, h4Lo, h4T)
if lv1h and tfFits("60") and h1T != h1T[1]
setLevel(h1h, h1Hi, h1T)
setLevel(h1l, h1Lo, h1T)
if sesOk
if asiaOn and aEnd
setLevel(ash, aHi, aT)
setLevel(asl, aLo, aT)
if londonOn and lEnd
setLevel(ldh, lHi, lT)
setLevel(ldl, lLo, lT)
if nyOn and nEnd
setLevel(nyh, nHi, nT)
setLevel(nyl, nLo, nT)
// 2) sweeps, and keep labels just right of the last bar
for lv in levels
checkSweep(lv)
if barstate.islast and not na(lv.lb)
lv.lb.set_x(bar_index + 2)
// ─────────────────────────────────────────────────────────────────────────────
// EMA Multi Cross + VWAP + Support/Resistance Breaks & Retests (merged in)
// ─────────────────────────────────────────────────────────────────────────────
const string G_EMA = "EMAs"
const string G_VW = "VWAP"
const string G_SR = "Support/Resistance Breaks & Retests"
showEMAs = input.bool(true, "Show EMAs", group = G_EMA)
e5On = input.bool(true, "EMA 5", group = G_EMA)
e9On = input.bool(true, "EMA 9", group = G_EMA)
e13On = input.bool(true, "EMA 13", group = G_EMA)
e15On = input.bool(true, "EMA 15", group = G_EMA)
e20On = input.bool(true, "EMA 20", group = G_EMA)
e21On = input.bool(true, "EMA 21", group = G_EMA)
e40On = input.bool(true, "EMA 40", group = G_EMA)
e50On = input.bool(true, "EMA 50", group = G_EMA)
e60On = input.bool(true, "EMA 60", group = G_EMA)
e120On = input.bool(true, "EMA 120", group = G_EMA)
e125On = input.bool(true, "EMA 125", group = G_EMA)
e200On = input.bool(true, "EMA 200", group = G_EMA)
e250On = input.bool(true, "EMA 250", group = G_EMA)
e350On = input.bool(true, "EMA 350", group = G_EMA)
show_9_21_cross = input.bool(true, "Show 9/21 EMA cross marks", group = G_EMA)
showVWAP = input.bool(true, "Show VWAP", group = G_VW)
vwapColor = input.color(color.aqua, "VWAP color", group = G_VW)
vwapWidth = input.int(2, "VWAP width", minval = 1, maxval = 5, group = G_VW)
enableSR = input.bool(true, "Enable S/R break & retest", group = G_SR)
lookbackPeriod = input.int(20, "Lookback period", minval = 1, group = G_SR)
vol_len = input.int(2, "Delta volume filter length", group = G_SR)
box_withd = input.float(1, "Box width (× ATR 200)", minval = 0, step = 0.1, group = G_SR)
srMax = input.int(20, "Max S/R boxes kept", minval = 1, maxval = 100, group = G_SR,
tooltip = "Older S/R boxes and break labels are deleted so they never crowd out order-block / FVG zones or liquidity labels.")
// ── EMAs ──
ema5 = ta.ema(close, 5)
ema9 = ta.ema(close, 9)
ema13 = ta.ema(close, 13)
ema15 = ta.ema(close, 15)
ema20 = ta.ema(close, 20)
ema21 = ta.ema(close, 21)
ema40 = ta.ema(close, 40)
ema50 = ta.ema(close, 50)
ema60 = ta.ema(close, 60)
ema120 = ta.ema(close, 120)
ema125 = ta.ema(close, 125)
ema200 = ta.ema(close, 200)
ema250 = ta.ema(close, 250)
ema350 = ta.ema(close, 350)
plot(showEMAs and e5On ? ema5 : na, "EMA 5", color.fuchsia, force_overlay = true)
plot(showEMAs and e9On ? ema9 : na, "EMA 9", color.red, force_overlay = true)
plot(showEMAs and e13On ? ema13 : na, "EMA 13", color.blue, force_overlay = true)
plot(showEMAs and e15On ? ema15 : na, "EMA 15", color.orange, force_overlay = true)
plot(showEMAs and e20On ? ema20 : na, "EMA 20", color.lime, force_overlay = true)
plot(showEMAs and e21On ? ema21 : na, "EMA 21", color.green, force_overlay = true)
plot(showEMAs and e40On ? ema40 : na, "EMA 40", color.black, force_overlay = true)
plot(showEMAs and e50On ? ema50 : na, "EMA 50", color.purple, force_overlay = true)
plot(showEMAs and e60On ? ema60 : na, "EMA 60", color.maroon, force_overlay = true)
plot(showEMAs and e120On ? ema120 : na, "EMA 120", color.yellow, force_overlay = true)
plot(showEMAs and e125On ? ema125 : na, "EMA 125", color.teal, force_overlay = true)
plot(showEMAs and e200On ? ema200 : na, "EMA 200", color.black, force_overlay = true)
plot(showEMAs and e250On ? ema250 : na, "EMA 250", color.olive, force_overlay = true)
plot(showEMAs and e350On ? ema350 : na, "EMA 350", color.gray, force_overlay = true)
bullCross_9_21 = ta.crossover(ema9, ema21)
bearCross_9_21 = ta.crossunder(ema9, ema21)
plotshape(show_9_21_cross and bullCross_9_21 ? ema9 : na, "9/21 Bull Cross Mark", shape.cross, location.absolute, color.green, size = size.tiny, force_overlay = true)
plotshape(show_9_21_cross and bearCross_9_21 ? ema9 : na, "9/21 Bear Cross Mark", shape.cross, location.absolute, color.red, size = size.tiny, force_overlay = true)
alertcondition(ta.crossover(ema9, ema15), "9/15 Bullish", "EMA9 crossed above EMA15")
alertcondition(ta.crossunder(ema9, ema15), "9/15 Bearish", "EMA9 crossed below EMA15")
alertcondition(bullCross_9_21, "9/21 Bullish", "EMA9 crossed above EMA21")
alertcondition(bearCross_9_21, "9/21 Bearish", "EMA9 crossed below EMA21")
alertcondition(ta.crossover(ema13, ema50), "13/50 Bullish", "EMA13 crossed above EMA50")
alertcondition(ta.crossunder(ema13, ema50), "13/50 Bearish", "EMA13 crossed below EMA50")
alertcondition(ta.crossover(ema21, ema200), "21/200 Bullish", "EMA21 crossed above EMA200")
alertcondition(ta.crossunder(ema21, ema200),"21/200 Bearish", "EMA21 crossed below EMA200")
// ── VWAP ──
vwapValue = ta.vwap(hlc3)
plot(showVWAP ? vwapValue : na, "VWAP", vwapColor, vwapWidth, force_overlay = true)
alertcondition(ta.crossover(close, vwapValue), "Price Above VWAP", "Price crossed above VWAP")
alertcondition(ta.crossunder(close, vwapValue), "Price Below VWAP", "Price crossed below VWAP")
// ── Support / Resistance breaks & retests ──
// Based on "Support and Resistance (High Volume Boxes)" by ChartPrime (Mozilla Public License 2.0,
// https://mozilla.org/MPL/2.0/). Changes: inputs grouped, cross checks run on every bar,
// old boxes/labels capped (srMax), drawings pinned to the price chart.
upAndDownVolume() =>
float posVol = 0
float negVol = 0
if close >= open
posVol := volume
else
negVol := -volume
posVol + negVol
Vol = upAndDownVolume()
vol_hi = ta.highest(Vol / 2.5, vol_len)
vol_lo = ta.lowest(Vol / 2.5, vol_len)
srPivotHigh = ta.pivothigh(close, lookbackPeriod, lookbackPeriod)
srPivotLow = ta.pivotlow(close, lookbackPeriod, lookbackPeriod)
srWidth = ta.atr(200) * box_withd
var float supportLevel = na
var float supportLevel_1 = na
var float resistanceLevel = na
var float resistanceLevel_1 = na
var box sup = na
var box res = na
var array<box> srBoxes = array.new<box>()
var array<label> srLabels = array.new<label>()
keepBox(box b) =>
srBoxes.push(b)
if srBoxes.size() > srMax
srBoxes.shift().delete()
keepLabel(label l) =>
srLabels.push(l)
if srLabels.size() > srMax
srLabels.shift().delete()
if enableSR and not na(srPivotLow) and Vol > vol_hi
supportLevel := srPivotLow
supportLevel_1 := supportLevel - srWidth
sup := box.new(bar_index - lookbackPeriod, supportLevel, bar_index, supportLevel_1,
border_color = color.green, bgcolor = color.new(color.green, 70),
text = "Vol: " + str.tostring(math.round(Vol)), text_size = size.small, text_color = color.black, force_overlay = true)
keepBox(sup)
if enableSR and not na(srPivotHigh) and Vol < vol_lo
resistanceLevel := srPivotHigh
resistanceLevel_1 := resistanceLevel + srWidth
res := box.new(bar_index - lookbackPeriod, resistanceLevel, bar_index, resistanceLevel_1,
border_color = color.red, bgcolor = color.new(color.red, 70),
text = "Vol: " + str.tostring(math.round(math.abs(Vol))), text_size = size.small, text_color = color.black, force_overlay = true)
keepBox(res)
if enableSR and not na(sup)
sup.set_right(bar_index + 1)
if enableSR and not na(res)
res.set_right(bar_index + 1)
// cross checks run on every bar (not behind `and`) so their history stays consistent
bool xResBreak = ta.crossover(low, resistanceLevel_1)
bool xResHold = ta.crossunder(high, resistanceLevel)
bool xSupHold = ta.crossover(low, supportLevel)
bool xSupBreak = ta.crossunder(high, supportLevel_1)
brekout_res = enableSR and not na(resistanceLevel_1) and xResBreak
res_holds = enableSR and not na(resistanceLevel) and xResHold
sup_holds = enableSR and not na(supportLevel) and xSupHold
brekout_sup = enableSR and not na(supportLevel_1) and xSupBreak
if brekout_sup and not na(sup)
sup.set_bgcolor(color.new(color.red, 80))
sup.set_border_color(color.red)
sup.set_border_style(line.style_dashed)
if sup_holds and not na(sup)
sup.set_bgcolor(color.new(color.green, 70))
sup.set_border_color(color.green)
sup.set_border_style(line.style_solid)
if brekout_res and not na(res)
res.set_bgcolor(color.new(color.green, 80))
res.set_border_color(color.green)
res.set_border_style(line.style_dashed)
if res_holds and not na(res)
res.set_bgcolor(color.new(color.red, 70))
res.set_border_color(color.red)
res.set_border_style(line.style_solid)
plotchar(res_holds, "Resistance Holds", "◆", location.abovebar, color.red, size = size.tiny, force_overlay = true)
plotchar(sup_holds, "Support Holds", "◆", location.belowbar, color.green, size = size.tiny, force_overlay = true)
if brekout_sup
keepLabel(label.new(bar_index, supportLevel, "Break Sup", style = label.style_label_down, color = color.red, textcolor = color.white, force_overlay = true))
if brekout_res
keepLabel(label.new(bar_index, resistanceLevel, "Break Res", style = label.style_label_up, color = color.green, textcolor = color.white, force_overlay = true))
// ─────────────────────────────────────────────────────────────────────────────
// RSI + MACD (drawn in this indicator's own pane; everything above is forced onto the price chart)
// One Pine indicator gets only one pane, and RSI (0-100) and MACD (price units) have different
// scales. In "RSI + MACD" mode RSI keeps its real 0-100 values and MACD is rescaled into the band
// below it (-100 … -10, zero line at -55) so both stay readable. Real MACD values are always in
// the Data Window. "MACD only" plots true MACD values.
// ─────────────────────────────────────────────────────────────────────────────
const string G_OSC = "RSI & MACD pane"
oscMode = input.string("RSI + MACD", "Show in pane", options = ["RSI + MACD", "RSI only", "MACD only", "Off"], group = G_OSC)
rsiLen = input.int(14, "RSI length", minval = 1, group = G_OSC, inline = "rsi")
rsiSrc = input.source(close, "", group = G_OSC, inline = "rsi")
rsiMaLen = input.int(14, "RSI-based MA (SMA) length", minval = 1, group = G_OSC)
rsiOB = input.float(70, "Overbought / oversold", group = G_OSC, inline = "obos")
rsiOS = input.float(30, "", group = G_OSC, inline = "obos")
macdFast = input.int(12, "MACD fast / slow / signal", minval = 1, group = G_OSC, inline = "macd")
macdSlow = input.int(26, "", minval = 1, group = G_OSC, inline = "macd")
macdSig = input.int(9, "", minval = 1, group = G_OSC, inline = "macd")
macdNorm = input.int(200, "MACD rescale lookback (combined mode)", minval = 20, group = G_OSC,
tooltip = "In RSI + MACD mode, MACD is scaled by its largest absolute value over this many bars.")
bool showRsi = oscMode == "RSI + MACD" or oscMode == "RSI only"
bool showMacd = oscMode == "RSI + MACD" or oscMode == "MACD only"
bool combined = oscMode == "RSI + MACD"
// RSI (same as TradingView's built-in)
rsiVal = ta.rsi(rsiSrc, rsiLen)
rsiMa = ta.sma(rsiVal, rsiMaLen)
// MACD (same as TradingView's built-in: EMA/EMA, EMA signal)
[macdLine, signalLine, histLine] = ta.macd(close, macdFast, macdSlow, macdSig)
// rescale for the combined pane
float macdScale = ta.highest(math.max(math.abs(macdLine), math.abs(signalLine), math.abs(histLine)), macdNorm)
const float M_MID = -55.0
const float M_HALF = 45.0
mapM(float v) => combined ? M_MID + M_HALF * v / nz(macdScale, 1) : v
float macdBase = combined ? M_MID : 0.0
color histCol = histLine >= 0 ? (histLine[1] < histLine ? #26A69A : #B2DFDB) : (histLine[1] < histLine ? #FFCDD2 : #FF5252)
plot(showRsi ? rsiVal : na, "RSI", #7E57C2, 1)
plot(showRsi ? rsiMa : na, "RSI-based MA", color.yellow, 1)
hline(rsiOB, "RSI overbought", color.new(#787B86, 0), hline.style_dashed, display = showRsi ? display.all : display.none)
hline(50, "RSI middle", color.new(#787B86, 50), hline.style_dotted, display = showRsi ? display.all : display.none)
hline(rsiOS, "RSI oversold", color.new(#787B86, 0), hline.style_dashed, display = showRsi ? display.all : display.none)
plot(showMacd ? mapM(histLine) : na, "MACD histogram", histCol, style = plot.style_columns, histbase = macdBase)
plot(showMacd ? mapM(macdLine) : na, "MACD", #2962FF)
plot(showMacd ? mapM(signalLine) : na, "Signal line", #FF6D00)
hline(combined ? M_MID : 0, "MACD zero", color.new(#787B86, 50), hline.style_solid, display = showMacd ? display.all : display.none)
// true values for the Data Window (useful in combined mode, where the pane shows rescaled MACD)
plot(macdLine, "MACD (value)", display = display.data_window)
plot(signalLine, "Signal (value)", display = display.data_window)
plot(histLine, "Histogram (value)", display = display.data_window)
alertcondition(ta.crossover(rsiVal, rsiOB), "RSI overbought", "RSI crossed above the overbought level")
alertcondition(ta.crossunder(rsiVal, rsiOS), "RSI oversold", "RSI crossed below the oversold level")
alertcondition(ta.crossover(macdLine, signalLine), "MACD bullish cross", "MACD crossed above the signal line")
alertcondition(ta.crossunder(macdLine, signalLine), "MACD bearish cross", "MACD crossed below the signal line")
// ─────────────────────────────────────────────────────────────────────────────
// RSI divergence (regular), counted in swings
// Bullish: price makes a lower low while RSI makes a higher low.
// Bearish: price makes a higher high while RSI makes a lower high.
// Consecutive divergent swings are chained: ×2 = a normal divergence (2 swings),
// ×3 = triple divergence (3 swings in a row) - drawn thicker and marked ★.
// Swings are RSI pivots, so a divergence is confirmed "pivot right" bars after the swing.
// ─────────────────────────────────────────────────────────────────────────────
const string G_DIV = "RSI divergence"
showDiv = input.bool(true, "Show RSI divergence", group = G_DIV)
divTf = input.timeframe("", "Divergence timeframe", group = G_DIV,
tooltip = "Empty = the chart's timeframe. Pick a higher one (e.g. 4 hours) to see that timeframe's divergences on a lower chart; they appear when its candle closes. Ignored if lower than the chart.")
divMinSw = input.int(2, "Minimum swings in a row", minval = 2, maxval = 5, group = G_DIV,
tooltip = "2 = every regular divergence. 3 = only triple divergences (3 swings where price kept making new extremes and RSI did not).")
divLbL = input.int(5, "Pivot lookback left / right", minval = 1, group = G_DIV, inline = "dlb")
divLbR = input.int(5, "", minval = 1, group = G_DIV, inline = "dlb")
divRngMin = input.int(5, "Bars between swings min / max", minval = 1, group = G_DIV, inline = "drg")
divRngMax = input.int(60, "", minval = 2, group = G_DIV, inline = "drg")
divBullCol = input.color(#00c853, "Bullish / bearish color", group = G_DIV, inline = "dc")
divBearCol = input.color(#ff1744, "", group = G_DIV, inline = "dc")
divMax = input.int(30, "Max divergences kept", minval = 1, maxval = 60, group = G_DIV)
divDetect() =>
float r = ta.rsi(rsiSrc, rsiLen)
float plR = ta.pivotlow(r, divLbL, divLbR)
float phR = ta.pivothigh(r, divLbL, divLbR)
// last two RSI swing lows / highs and the current chain length
var int loBar = na
var int loT = na
var float loP = na
var float loR = na
var int loT0 = na
var float loP0 = na
var float loR0 = na
var int loCnt = 1
var int hBar = na
var int hT = na
var float hP = na
var float hR = na
var int hT0 = na
var float hP0 = na
var float hR0 = na
var int hCnt = 1
bool bull = false
int bC = na
int bT0 = na
float bP0 = na
float bR0 = na
int bT1 = na
float bP1 = na
float bR1 = na
int bT2 = na
float bP2 = na
float bR2 = na
bool bear = false
int sC = na
int sT0 = na
float sP0 = na
float sR0 = na
int sT1 = na
float sP1 = na
float sR1 = na
int sT2 = na
float sP2 = na
float sR2 = na
if not na(plR)
int b = bar_index - divLbR
float p = low[divLbR]
int t = time[divLbR]
int gap = na(loBar) ? -1 : b - loBar
if gap >= divRngMin and gap <= divRngMax and p < loP and plR > loR
loCnt += 1
bull := true
bC := loCnt
bT0 := loT0
bP0 := loP0
bR0 := loR0
bT1 := loT
bP1 := loP
bR1 := loR
bT2 := t
bP2 := p
bR2 := plR
else
loCnt := 1
loT0 := loT
loP0 := loP
loR0 := loR
loBar := b
loT := t
loP := p
loR := plR
if not na(phR)
int b = bar_index - divLbR
float p = high[divLbR]
int t = time[divLbR]
int gap = na(hBar) ? -1 : b - hBar
if gap >= divRngMin and gap <= divRngMax and p > hP and phR < hR
hCnt += 1
bear := true
sC := hCnt
sT0 := hT0
sP0 := hP0
sR0 := hR0
sT1 := hT
sP1 := hP
sR1 := hR
sT2 := t
sP2 := p
sR2 := phR
else
hCnt := 1
hT0 := hT
hP0 := hP
hR0 := hR
hBar := b
hT := t
hP := p
hR := phR
[bull, bC, bT0, bP0, bR0, bT1, bP1, bR1, bT2, bP2, bR2, bear, sC, sT0, sP0, sR0, sT1, sP1, sR1, sT2, sP2, sR2]
// values from the last CLOSED candle of the divergence timeframe (used with lookahead_on → no repaint)
divHtf() =>
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11] = divDetect()
[a1[1], a2[1], a3[1], a4[1], a5[1], a6[1], a7[1], a8[1], a9[1], a10[1], a11[1], b1[1], b2[1], b3[1], b4[1], b5[1], b6[1], b7[1], b8[1], b9[1], b10[1], b11[1]]
var array<line> divLines = array.new<line>()
var array<label> divLabels = array.new<label>()
keepDivLine(line l) =>
divLines.push(l)
if divLines.size() > divMax * 4
divLines.shift().delete()
keepDivLabel(label l) =>
divLabels.push(l)
if divLabels.size() > divMax
divLabels.shift().delete()
divSegment(int t1, float p1, float r1, int t2, float p2, float r2, color c, int w) =>
keepDivLine(line.new(t1, p1, t2, p2, xloc = xloc.bar_time, color = c, width = w, force_overlay = true))
if showRsi
keepDivLine(line.new(t1, r1, t2, r2, xloc = xloc.bar_time, color = c, width = w))
drawDiv(bool isBull, int cnt, int t0, float p0, float r0, int t1, float p1, float r1, int t2, float p2, float r2, string pre) =>
if cnt >= divMinSw
color c = isBull ? divBullCol : divBearCol
int w = cnt >= 3 ? 3 : 1
divSegment(t1, p1, r1, t2, p2, r2, c, w)
// when the threshold is reached on a 3+ swing chain, also draw the earlier leg
if cnt == divMinSw and cnt >= 3 and not na(t0)
divSegment(t0, p0, r0, t1, p1, r1, c, w)
string txt = pre + (isBull ? "Bull" : "Bear") + " div ×" + str.tostring(cnt) + (cnt >= 3 ? " ★" : "")
keepDivLabel(label.new(t2, p2, txt, xloc = xloc.bar_time, color = color.new(c, cnt >= 3 ? 0 : 35),
style = isBull ? label.style_label_up : label.style_label_down, textcolor = color.white,
size = cnt >= 3 ? size.normal : size.small, force_overlay = true))
alert(syminfo.ticker + ": " + pre + (isBull ? "bullish" : "bearish") + " RSI divergence ×" + str.tostring(cnt), alert.freq_once_per_bar)
[dB, dBc, dBt0, dBp0, dBr0, dBt1, dBp1, dBr1, dBt2, dBp2, dBr2, dS, dSc, dSt0, dSp0, dSr0, dSt1, dSp1, dSr1, dSt2, dSp2, dSr2] = divDetect()
[hdB, hdBc, hdBt0, hdBp0, hdBr0, hdBt1, hdBp1, hdBr1, hdBt2, hdBp2, hdBr2, hdS, hdSc, hdSt0, hdSp0, hdSr0, hdSt1, hdSp1, hdSr1, hdSt2, hdSp2, hdSr2] =
request.security(syminfo.tickerid, divTf, divHtf(), lookahead = barmerge.lookahead_on)
bool divUseHtf = divTf != "" and timeframe.in_seconds(divTf) > timeframe.in_seconds(timeframe.period)
bool divNewHtf = timeframe.change(divTf)
string divPre = divUseHtf ? tfLabel(divTf) + " " : ""
if showDiv
if divUseHtf
if divNewHtf
if hdB
drawDiv(true, hdBc, hdBt0, hdBp0, hdBr0, hdBt1, hdBp1, hdBr1, hdBt2, hdBp2, hdBr2, divPre)
if hdS
drawDiv(false, hdSc, hdSt0, hdSp0, hdSr0, hdSt1, hdSp1, hdSr1, hdSt2, hdSp2, hdSr2, divPre)
else if barstate.isconfirmed
if dB
drawDiv(true, dBc, dBt0, dBp0, dBr0, dBt1, dBp1, dBr1, dBt2, dBp2, dBr2, "")
if dS
drawDiv(false, dSc, dSt0, dSp0, dSr0, dSt1, dSp1, dSr1, dSt2, dSp2, dSr2, "")