本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("$ - FVG +", overlay = true, max_boxes_count = 500, max_lines_count = 500)
// ─────────────────────────────── Inputs ───────────────────────────────
const string GF = "Fair Value Gaps ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
const string GS = "Style ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
const string GA = "Alerts ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
// Fair Value Gaps
showFvg = input.bool(true, "", inline = "f1", group = GF)
htfIn = input.timeframe("5", "", inline = "f1", group = GF)
showBelow = input.bool(false, "Show Below", inline = "f1", group = GF,
tooltip = "Gap timeframe. Gaps only appear on charts at or below it.\n\nShow Below: also draw gaps on lower chart timeframes, anchored to the exact candles that made the candle 1 and candle 3 wicks.")
lenBars = input.int(5, "Extend", minval = 0, inline = "f2", group = GF)
extFill = input.bool(false, "Extend until filled", inline = "f2", group = GF,
tooltip = "Extend: extra gap-timeframe candles drawn past candle 3 (0 = the 3-candle formation only).\n\nUntil filled: overrides Extend and keeps the gap running until price fills it.")
minTicks = input.int(0, "Min ticks", minval = 0, inline = "f3", group = GF)
maxShowIn = input.string("7", "Keep",
options = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Today", "2 Days", "All"],
inline = "f3", group = GF,
tooltip = "Min ticks: smallest gap size to track.\n\nKeep: 1 to 10 keeps that many of the most recent gaps. Today and 2 Days show every gap formed today (and yesterday). All keeps up to 300 gaps.")
// Style
bullCol = input.color(color.new(#089981, 80), "Fresh", inline = "s1", group = GS)
bearCol = input.color(color.new(#f23645, 80), "", inline = "s1", group = GS)
recolTap = input.bool(true, "Tapped", inline = "s1", group = GS)
tapBull = input.color(color.new(#2962ff, 80), "", inline = "s1", group = GS)
tapBear = input.color(color.new(#ff9800, 80), "", inline = "s1", group = GS,
tooltip = "Each pair is bull, then bear.\n\nTapped: switch a gap to the second pair the first time price touches it.")
showBdr = input.bool(false, "Border", inline = "s2", group = GS)
borderW = input.int(1, "", options = [1, 2, 3, 4], inline = "s2", group = GS)
showMid = input.bool(false, "Midline", inline = "s2", group = GS)
midCol = input.color(color.new(#787b86, 20), "", inline = "s2", group = GS)
showLbl = input.bool(false, "Label", inline = "s3", group = GS)
lblCol = input.color(color.new(#9598a1, 0), "", inline = "s3", group = GS)
lblSzIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "s3", group = GS)
filledMd = input.string("Fade", "Filled", options = ["Fade", "Keep", "Hide"], inline = "s3", group = GS,
tooltip = "Filled: fade, keep or hide gaps once price has filled them.")
// Alerts
alFirst = input.bool(true, "First tap", inline = "a1", group = GA)
alReent = input.bool(true, "Re-entry", inline = "a1", group = GA,
tooltip = "First tap fires the first time price touches a fresh gap. Re-entry fires each time price leaves an unfilled gap and comes back in. Both are calculated even when the gaps are hidden.")
maxAgeHr = input.int(3, "Max age (hrs)", minval = 0, inline = "a2", group = GA)
resetDay = input.bool(true, "Reset daily", inline = "a2", group = GA,
tooltip = "Only gaps formed within Max age can alert (0 = no limit). Reset daily ignores gaps from previous days.")
// ─────────────────────────────── Types ────────────────────────────────
type Candle
float h
float l
int hiFirst
int hiLast
int loFirst
int loLast
type Gap
float top
float bot
bool bull
int left
int formIdx
int formTime
int day
bool tapped = false
bool inside = false
bool filled = false
box bx = na
line mid = na
// ─────────────────────────────── Setup ────────────────────────────────
// Gaps only show on charts at or below the chosen gap timeframe
string htf = htfIn
tfLabel(string tf) =>
int s = timeframe.in_seconds(tf)
str.contains(tf, "W") or str.contains(tf, "M") ? tf :
s % 86400 == 0 ? str.tostring(s / 86400, "#") + "D" :
s % 3600 == 0 ? str.tostring(s / 3600, "#") + "H" :
s % 60 == 0 ? str.tostring(s / 60, "#") + "m" : str.tostring(s, "#") + "s"
string lblSize = switch lblSzIn
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
=> size.tiny
// Keep: number of days to keep (0 = not day-based) and gap count limit
int keepDays = maxShowIn == "Today" ? 1 : maxShowIn == "2 Days" ? 2 : 0
int maxShow = keepDays > 0 or maxShowIn == "All" ? 500 : int(str.tonumber(maxShowIn))
int tfSec = timeframe.in_seconds(htf)
int chSec = timeframe.in_seconds()
bool valid = chSec <= tfSec
bool drawOn = showFvg and valid and (chSec == tfSec or showBelow)
int ratio = math.max(1, math.round(float(tfSec) / chSec))
int ageMs = maxAgeHr * 3600000
string tfTxt = tfLabel(htf)
bool htfNew = timeframe.change(htf)
int htfEnd = time_close(htf)
bool dayNew = timeframe.change("D")
var Candle cur = na
var bool closed = true
var int dayId = 0
var array<Candle> hist = array.new<Candle>()
var array<Gap> gaps = array.new<Gap>()
if dayNew
dayId += 1
// ───────────────────────────── Functions ──────────────────────────────
fade(color c) =>
float t = color.t(c)
color.new(c, t + (100 - t) * 0.6)
gapCol(Gap g) =>
recolTap and g.tapped ? (g.bull ? tapBull : tapBear) : (g.bull ? bullCol : bearCol)
clearVisuals(Gap g) =>
if not na(g.bx)
g.bx.delete()
g.bx := na
if not na(g.mid)
g.mid.delete()
g.mid := na
trimDrawn() =>
int n = 0
for g in gaps
if not na(g.bx)
n += 1
if n > maxShow
for g in gaps
if not na(g.bx)
clearVisuals(g)
break
addGap(float top, float bot, bool bull, int left, int right0) =>
Gap g = Gap.new(top = top, bot = bot, bull = bull, left = left, formIdx = bar_index, formTime = time, day = dayId)
if drawOn
color col = bull ? bullCol : bearCol
int right = extFill ? bar_index : math.min(right0 + lenBars * ratio, bar_index + 499)
g.bx := box.new(left, top, right, bot, border_color = showBdr ? color.new(col, color.t(col) * 0.5) : na,
border_width = showBdr ? borderW : 0, bgcolor = col, text = showLbl ? tfTxt : "", text_size = lblSize,
text_color = lblCol, text_halign = text.align_right, text_valign = text.align_center)
if showMid
float m = (top + bot) / 2
g.mid := line.new(left, m, right, m, color = midCol, style = line.style_dashed)
gaps.push(g)
trimDrawn()
// Called once a gap-timeframe candle has closed.
// Bull gap: candle 3 low > candle 1 high. Bear gap: candle 3 high < candle 1 low.
// Edges anchor to the chart candle that made each wick (last touch on candle 1, first touch on candle 3).
finalize(Candle c) =>
hist.push(c)
if hist.size() > 3
hist.shift()
if hist.size() == 3
Candle a = hist.get(0)
Candle k = hist.get(2)
float minSz = minTicks * syminfo.mintick
if k.l > a.h and k.l - a.h >= minSz
addGap(k.l, a.h, true, a.hiLast, k.loFirst)
else if k.h < a.l and a.l - k.h >= minSz
addGap(a.l, k.h, false, a.loLast, k.hiFirst)
// ──────────────── Remove drawings outside the day window ──────────────
if dayNew and keepDays > 0
for g in gaps
if g.day <= dayId - keepDays
clearVisuals(g)
// ──────────────────── Build gap-timeframe candles ─────────────────────
if valid
if htfNew and bar_index > 0
if not closed and not na(cur)
finalize(cur)
cur := Candle.new(high, low, bar_index, bar_index, bar_index, bar_index)
closed := false
else if not closed and not na(cur)
if high > cur.h
cur.h := high
cur.hiFirst := bar_index
if high >= cur.h
cur.hiLast := bar_index
if low < cur.l
cur.l := low
cur.loFirst := bar_index
if low <= cur.l
cur.loLast := bar_index
if not closed and not na(cur) and barstate.isconfirmed and time_close >= htfEnd
finalize(cur)
closed := true
// ─────────────────────── Taps, fills and visuals ──────────────────────
bool anyFirst = false
bool anyReent = false
string msg = ""
for g in gaps
if not g.filled and bar_index > g.formIdx
bool touch = high >= g.bot and low <= g.top
bool isFill = g.bull ? low <= g.bot : high >= g.top
bool isLive = (maxAgeHr == 0 or time - g.formTime <= ageMs) and (not resetDay or g.day == dayId)
bool newTap = touch and not g.tapped
if touch and isLive
string desc = syminfo.ticker + ": " + tfTxt + (g.bull ? " bull" : " bear") + " FVG "
string lvl = " (" + str.tostring(g.bot, format.mintick) + " - " + str.tostring(g.top, format.mintick) + ")"
if not g.tapped
anyFirst := true
if alFirst
msg += desc + "first tap" + lvl + "\n"
else if not g.inside
anyReent := true
if alReent
msg += desc + "re-entry" + lvl + "\n"
g.tapped := g.tapped or touch
g.inside := touch
if newTap and recolTap and not na(g.bx)
color tc = gapCol(g)
g.bx.set_bgcolor(tc)
if showBdr
g.bx.set_border_color(color.new(tc, color.t(tc) * 0.5))
if isFill
g.filled := true
if not na(g.bx)
if filledMd == "Hide"
clearVisuals(g)
else
if extFill
g.bx.set_right(bar_index)
if not na(g.mid)
g.mid.set_x2(bar_index)
if filledMd == "Fade"
color col = gapCol(g)
g.bx.set_bgcolor(fade(col))
if showBdr
g.bx.set_border_color(fade(color.new(col, color.t(col) * 0.5)))
g.bx.set_text_color(fade(lblCol))
if not na(g.mid)
g.mid.set_color(fade(midCol))
else if extFill and not na(g.bx)
g.bx.set_right(bar_index)
if not na(g.mid)
g.mid.set_x2(bar_index)
// Drop gaps that can no longer alert and have nothing drawn
if gaps.size() > 0
for i = gaps.size() - 1 to 0
Gap g = gaps.get(i)
bool expired = g.filled or (maxAgeHr > 0 and time - g.formTime > ageMs) or (resetDay and g.day != dayId)
if expired and na(g.bx)
gaps.remove(i)
while gaps.size() > 300
clearVisuals(gaps.shift())
// ─────────────────────────────── Alerts ───────────────────────────────
if msg != ""
alert(str.trim(msg), alert.freq_once_per_bar)
alertcondition(anyFirst, "HTF FVG first tap", "{{ticker}}: price tapped a fresh HTF fair value gap")
alertcondition(anyReent, "HTF FVG re-entry", "{{ticker}}: price re-entered an HTF fair value gap")