本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("FVG Distance Tracker", overlay=true, max_boxes_count=500)
// ───────── Settings ─────────
minSizePct = input.float(0.05, "Minimum FVG Size (%)", minval=0, step=0.01, group="FVG")
maxFvg = input.int(60, "Max Active FVGs (total)", minval=1, maxval=250, group="FVG")
clearMode = input.string("Half", "Mitigation Criterion", options=["Half", "Full"], group="FVG",
tooltip="Half: an FVG counts as filled when price reaches its 50% level.\nFull: when price fills the entire gap.")
deleteFilled = input.bool(true, "Delete Filled FVGs", group="FVG",
tooltip="If disabled, filled FVGs stay on the chart in a faded color, ending at the bar where they were filled.")
showHtf = input.bool(true, "Show Higher Timeframe (HTF) FVGs", group="HTF FVG")
htf = input.timeframe("240", "HTF Timeframe", group="HTF FVG",
tooltip="Must be higher than the chart timeframe. Otherwise HTF FVGs stay disabled.")
htfOpacity = input.int(70, "HTF Opacity", minval=0, maxval=100, group="HTF FVG",
tooltip="Lower value = more visible box. HTF boxes are drawn with a dashed, thicker border.")
hideFar = input.bool(false, "Hide Distant FVGs", group="Distance Filter",
tooltip="If enabled, FVGs whose distance to price is larger than the threshold below are hidden from the chart. Alerts are not affected; hidden FVGs are still tracked.")
farPct = input.float(5.0, "Hide Threshold (%)", minval=0.1, step=0.5, group="Distance Filter")
alertApproach = input.bool(true, "Approach Alert", group="Alerts",
tooltip="Notifies when the distance to an FVG drops below the threshold below.")
approachPct = input.float(1.0, "Approach Threshold (%)", minval=0.01, step=0.1, group="Alerts")
alertEnter = input.bool(true, "Entry Alert (price entered FVG)", group="Alerts")
alertFill = input.bool(true, "Mitigation Alert", group="Alerts",
tooltip="Notifies when an FVG is half or fully filled, depending on the 'Mitigation Criterion' setting.")
showDist = input.bool(true, "Show Distance in Boxes", group="Style")
showTable = input.bool(true, "Show Summary Table", group="Style")
txtSize = input.string("small", "Text Size", options=["tiny", "small", "normal"], group="Style")
bullColor = input.color(color.green, "Bullish FVG Color", group="Style")
bearColor = input.color(color.red, "Bearish FVG Color", group="Style")
opacity = input.int(80, "Opacity", minval=0, maxval=100, group="Style")
// ───────── Type ─────────
type FVG
float top
float bottom
bool isBull
bool isHtf
box bx
int bornBar
bool notifApproach = false
bool notifEnter = false
var array<FVG> fvgs = array.new<FVG>()
// ───────── Helpers ─────────
// Distance to price in %: 0 if price is inside the FVG, otherwise distance to the nearest edge
distPct(FVG f) =>
float d = 0.0
if f.isBull
d := close > f.top ? (close - f.top) / close * 100 : 0.0
else
d := close < f.bottom ? (f.bottom - close) / close * 100 : 0.0
d
htfLabel() =>
secs = timeframe.in_seconds(htf)
string r = ""
if secs >= 604800
r := str.tostring(math.floor(secs / 604800)) + "w"
else if secs >= 86400
r := str.tostring(math.floor(secs / 86400)) + "d"
else if secs >= 3600
r := str.tostring(math.floor(secs / 3600)) + "h"
else
r := str.tostring(math.floor(secs / 60)) + "m"
r
htfTag = htfLabel()
// "4h " for HTF FVGs, empty for chart-timeframe FVGs
tagOf(FVG f) =>
f.isHtf ? htfTag + " " : ""
// "4h | " prefix for box text
boxPrefix(FVG f) =>
f.isHtf ? htfTag + " | " : ""
baseBg(FVG f) =>
color c = f.isBull ? bullColor : bearColor
color.new(c, f.isHtf ? htfOpacity : opacity)
baseBorder(FVG f) =>
color c = f.isBull ? bullColor : bearColor
color.new(c, f.isHtf ? 20 : 50)
alertPrefix() =>
syminfo.ticker + " " + timeframe.period + " | "
rangeText(FVG f) =>
str.tostring(f.bottom, format.mintick) + " - " + str.tostring(f.top, format.mintick)
// ───────── HTF data ─────────
// FVG is computed from the last 3 completed HTF candles (non-repainting).
htfData() =>
bullGap = low[1] > high[3] and close[2] > high[3]
bearGap = high[1] < low[3] and close[2] < low[3]
[time[1], bullGap, bearGap, low[1], high[3], low[3], high[1], time[3]]
htfValid = timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(htf)
[hId, hBull, hBear, bTop, bBot, sTop, sBot, hStart] = request.security(syminfo.tickerid, htf, htfData(), lookahead = barmerge.lookahead_on)
htfNewBar = showHtf and htfValid and ta.change(hId) != 0
// ───────── Detection + mitigation + alerts (on bar close) ─────────
if barstate.isconfirmed
// Chart timeframe FVGs
bullGap = low > high[2] and close[1] > high[2]
bearGap = high < low[2] and close[1] < low[2]
if bullGap
sizePct = (low - high[2]) / high[2] * 100
if sizePct >= minSizePct
b = box.new(bar_index - 2, low, bar_index, high[2], xloc=xloc.bar_index,
border_color=color.new(bullColor, 50), bgcolor=color.new(bullColor, opacity),
extend=extend.right, text_color=bullColor, text_size=txtSize,
text_halign=text.align_right)
fvgs.push(FVG.new(low, high[2], true, false, b, bar_index))
if bearGap
sizePct = (low[2] - high) / low[2] * 100
if sizePct >= minSizePct
b = box.new(bar_index - 2, low[2], bar_index, high, xloc=xloc.bar_index,
border_color=color.new(bearColor, 50), bgcolor=color.new(bearColor, opacity),
extend=extend.right, text_color=bearColor, text_size=txtSize,
text_halign=text.align_right)
fvgs.push(FVG.new(high, low[2], false, false, b, bar_index))
// HTF FVGs
if htfNewBar
if hBull
sizePct = (bTop - bBot) / bBot * 100
if sizePct >= minSizePct
b = box.new(hStart, bTop, time, bBot, xloc=xloc.bar_time,
border_color=color.new(bullColor, 20), bgcolor=color.new(bullColor, htfOpacity),
border_style=line.style_dashed, border_width=2,
extend=extend.right, text_color=bullColor, text_size=txtSize,
text_halign=text.align_right)
fvgs.push(FVG.new(bTop, bBot, true, true, b, bar_index))
if hBear
sizePct = (sTop - sBot) / sBot * 100
if sizePct >= minSizePct
b = box.new(hStart, sTop, time, sBot, xloc=xloc.bar_time,
border_color=color.new(bearColor, 20), bgcolor=color.new(bearColor, htfOpacity),
border_style=line.style_dashed, border_width=2,
extend=extend.right, text_color=bearColor, text_size=txtSize,
text_halign=text.align_right)
fvgs.push(FVG.new(sTop, sBot, false, true, b, bar_index))
// Delete the oldest when over the limit
while fvgs.size() > maxFvg
old = fvgs.shift()
box.delete(old.bx)
if fvgs.size() > 0
for i = fvgs.size() - 1 to 0
f = fvgs.get(i)
mid = (f.top + f.bottom) / 2
dir = tagOf(f) + (f.isBull ? "Bullish" : "Bearish")
d = distPct(f)
filled = false
if f.isBull
filled := clearMode == "Half" ? low <= mid : low <= f.bottom
else
filled := clearMode == "Half" ? high >= mid : high >= f.top
// No alerts on the formation bar
canAlert = bar_index > f.bornBar
if filled
if alertFill and canAlert
alert(alertPrefix() + dir + " FVG " + (clearMode == "Half" ? "half filled" : "fully filled") + " | " + rangeText(f), alert.freq_once_per_bar_close)
if deleteFilled
box.delete(f.bx)
else
box.set_extend(f.bx, extend.none)
box.set_right(f.bx, f.isHtf ? time : bar_index)
box.set_bgcolor(f.bx, color.new(color.gray, 90))
box.set_border_color(f.bx, color.new(color.gray, 70))
box.set_text(f.bx, "")
fvgs.remove(i)
else if canAlert
entered = f.isBull ? low <= f.top : high >= f.bottom
if entered
if alertEnter and not f.notifEnter
alert(alertPrefix() + dir + " FVG entered | " + rangeText(f), alert.freq_once_per_bar_close)
f.notifEnter := true
f.notifApproach := true
else if d <= approachPct
if alertApproach and not f.notifApproach
alert(alertPrefix() + dir + " FVG approached | Distance " + str.tostring(d, "#.##") + "% | " + rangeText(f), alert.freq_once_per_bar_close)
f.notifApproach := true
// ───────── Last bar: box text, visibility and table ─────────
var table tbl = table.new(position.top_right, 2, 4, bgcolor=color.new(color.black, 60),
border_width=1, border_color=color.gray)
if barstate.islast
float nearBull = na
float nearBear = na
int bullCnt = 0
int bearCnt = 0
for f in fvgs
d = distPct(f)
far = hideFar and d > farPct
if far
box.set_bgcolor(f.bx, na)
box.set_border_color(f.bx, na)
box.set_text(f.bx, "")
else
box.set_bgcolor(f.bx, baseBg(f))
box.set_border_color(f.bx, baseBorder(f))
if showDist
sizePct = (f.top - f.bottom) / f.bottom * 100
box.set_text(f.bx, boxPrefix(f) + "Size " + str.tostring(sizePct, "#.##") + "% | Distance " + str.tostring(d, "#.##") + "%")
else
box.set_text(f.bx, "")
if f.isBull
bullCnt += 1
nearBull := na(nearBull) ? d : math.min(nearBull, d)
else
bearCnt += 1
nearBear := na(nearBear) ? d : math.min(nearBear, d)
if showTable
table.cell(tbl, 0, 0, "", text_color=color.white)
table.cell(tbl, 1, 0, "Nearest distance", text_color=color.white, text_size=size.small)
table.cell(tbl, 0, 1, "Bullish (" + str.tostring(bullCnt) + ")", text_color=bullColor, text_size=size.small)
table.cell(tbl, 1, 1, na(nearBull) ? "-" : str.tostring(nearBull, "#.##") + "%", text_color=color.white, text_size=size.small)
table.cell(tbl, 0, 2, "Bearish (" + str.tostring(bearCnt) + ")", text_color=bearColor, text_size=size.small)
table.cell(tbl, 1, 2, na(nearBear) ? "-" : str.tostring(nearBear, "#.##") + "%", text_color=color.white, text_size=size.small)
if showHtf and not htfValid
table.cell(tbl, 0, 3, "HTF off", text_color=color.orange, text_size=size.small)
table.cell(tbl, 1, 3, "HTF must be > chart TF", text_color=color.orange, text_size=size.small)