本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("IFVG Engine", shorttitle = "IFVG Engine", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
// IFVG Engine
// What it does, in plain words:
// A fair value gap is a three-candle pattern: the third candle's range stays clear of the first candle's
// range, so price left a gap between them, and the middle candle closed beyond the gap's near edge. The
// script watches each gap for up to 48 candles. When a candle closes through the gap's far side by at least
// half an ATR(14), the gap has inverted and the script marks an IFVG zone over the gap's price range. Only
// the first close through counts: if it falls short of that margin, the gap is dropped.
// - A bearish gap closed through upward marks a long zone (cyan, small triangle below the candle).
// - A bullish gap closed through downward marks a short zone (gold, small triangle above the candle).
// A zone stays live until a candle closes back beyond its far side, 48 candles pass, or a newer zone on the
// same side pushes it out (two live zones per side at most). Ended zones can stay as faint boxes.
// Gaps smaller than a quarter of the ATR (0.4 ATR below 5-minute charts) are skipped. On US index futures
// below 1 hour, zones print only on candles that open 08:30-16:00 New York time, unless overnight prints
// are turned on. Zones are decided on confirmed (closed) candles only, so a zone never prints on an open
// candle and each print stays on the candle that confirmed it; later candles can end a live zone. Alerts
// can be set for new zones, and on a print candle the Data Window shows the zone's top, bottom and gap age.
// The script only marks where this rule was met. It does not predict what price does next.
//
// File layout
// ENGINE block inputs, detection, zone lifecycle, Data Window values and alerts. Keep it unchanged.
// DRAWING block everything that puts shapes on the chart. Replace it freely: it only reads the engine
// outputs listed below and never writes to engine state.
//
// Engine outputs. Per-bar events are set on closed bars only; every other update sees false / na / empty:
// printLong, printShort bool a long / short IFVG printed on this bar (both can be true)
// longId, longTop, longBot, longJ int / float the long print's zone id, zone top and bottom, and the
// bar_index of the gap's third candle (na without a print)
// shortId, shortTop, shortBot, shortJ the same for the short print
// zoneDeaths array<Zone> zones that died on this bar, in the order they died
// Persistent state, changed on closed bars only:
// liveLongZones, liveShortZones array<Zone> zones live after the last closed bar, oldest first
// Zone fields: id, side (SIDE_LONG / SIDE_SHORT), top, bot, j (gap bar), i (print bar),
// deathBar (na while live) and deathReason (DEATH_NONE while live, then DEATH_FAILED,
// DEATH_EXPIRED or DEATH_RETIRED).
// ==== ENGINE BEGIN ====
// ---------------------------------------------------------------------------------------------------- inputs
// Input order is part of saved chart settings: never reorder or remove these two.
bool overnight = input.bool(false, "Overnight prints (US index futures)", tooltip = "Applies to US equity index futures (NQ, MNQ, ES, MES, YM, MYM, RTY, M2K) on charts below 1 hour. Off: an IFVG prints only on a candle that opens between 08:30 and 16:00 New York time. On: IFVGs print at any hour. Other symbols and timeframes always print at any hour.", display = display.none)
bool showPast = input.bool(true, "Show past zones", tooltip = "Keeps zones that have ended as faint boxes on the chart. Live zones always show.", display = display.none)
// ---------------------------------------------------------------------------------------------------- rules
const int ATR_LEN = 14 // Wilder ATR length on the chart timeframe
const float DECISIVE_ATR = 0.5 // the inverting close must clear the gap's far edge by this many ATR
const int GAP_MAX_WAIT = 48 // a gap can invert at most this many bars after the bar it formed on
const int ZONE_LIFE = 48 // a live zone expires this many bars after its print
const int ZONE_CAP = 2 // live zones per side; a newer print retires the oldest beyond this
// Direction codes.
const int GAP_BULL = 1 // bullish fair value gap (low of candle 3 above the high of candle 1)
const int GAP_BEAR = -1 // bearish fair value gap (high of candle 3 below the low of candle 1)
const int SIDE_LONG = 1 // long zone, printed by a bearish gap closed through to the upside
const int SIDE_SHORT = -1 // short zone, printed by a bullish gap closed through to the downside
// Why a zone died.
const int DEATH_NONE = 0 // still live
const int DEATH_FAILED = 1 // a close went back beyond the zone's far side
const int DEATH_EXPIRED = 2 // ZONE_LIFE bars passed since the print
const int DEATH_RETIRED = 3 // a newer print on the same side pushed it out (ZONE_CAP)
// ---------------------------------------------------------------------------------------------------- types
// A fair value gap that has not yet seen a close through its far side.
type Gap
int dir // GAP_BULL or GAP_BEAR
float top
float bot
int j // bar_index of the gap's third candle (the bar the gap formed on)
// A printed IFVG zone and its lifecycle.
type Zone
int id // unique per script run, counts up from 1
int side // SIDE_LONG or SIDE_SHORT
float top
float bot
int j // bar_index of the source gap's third candle
int i // bar_index of the print (the inverting candle)
int deathBar = na // bar_index the zone died on, na while live
int deathReason = 0 // DEATH_NONE while live, then DEATH_FAILED / DEATH_EXPIRED / DEATH_RETIRED
// ---------------------------------------------------------------------------------------------------- series
// Everything here runs on every bar so the history-based calls stay consistent.
float atr = ta.atr(ATR_LEN)
float floorK = timeframe.in_seconds() < 300 ? 0.40 : 0.25 // minimum gap height, in ATR of the gap bar
// Candles are consecutive when no bar is missing between them (always true on daily and higher charts).
bool cg = timeframe.isdwm or (time - time[1] == timeframe.in_seconds() * 1000)
// A gap forms on this bar from candles [2], [1] and [0]: all three consecutive, ATR known, the middle candle
// closed beyond the gap's near edge, and the gap wider than half a tick.
bool gapBase = cg and cg[1] and not na(atr)
float halfTick = 0.5 * syminfo.mintick
bool bullGap = gapBase and low > high[2] + halfTick and close[1] > high[2]
bool bearGap = gapBase and high < low[2] - halfTick and close[1] < low[2]
float bullTop = low
float bullBot = high[2]
float bearTop = low[2]
float bearBot = high
// Session hours: US equity index futures below 1 hour print only on candles that open 08:30-16:00 New York
// time, unless overnight prints are on. Everything else prints at any hour.
string root = syminfo.root
bool indexRoot = root == "NQ" or root == "MNQ" or root == "ES" or root == "MES" or root == "YM" or root == "MYM" or root == "RTY" or root == "M2K"
bool sessionGate = syminfo.type == "futures" and indexRoot and timeframe.in_seconds() < 3600 and not overnight
bool inSession = not na(time(timeframe.period, "0830-1600", "America/New_York"))
bool sessionOk = not sessionGate or inSession
// ---------------------------------------------------------------------------------------------------- state
var array<Gap> pendingGaps = array.new<Gap>() // gaps waiting for a close through, oldest first
var array<Zone> liveLongZones = array.new<Zone>() // live long zones, oldest first
var array<Zone> liveShortZones = array.new<Zone>() // live short zones, oldest first
var array<Zone> zoneDeaths = array.new<Zone>() // zones that died on this bar (refilled every bar)
var int zoneCount = 0 // last zone id handed out
// Per-bar outputs, reset on every update.
bool printLong = false
bool printShort = false
int longId = na
float longTop = na
float longBot = na
int longJ = na
int shortId = na
float shortTop = na
float shortBot = na
int shortJ = na
zoneDeaths.clear()
// ---------------------------------------------------------------------------------------------------- helpers
// True when gap `a` should print instead of the current pick `b` (same bar, same side): the youngest gap wins
// (largest j) and a tie goes to the taller gap. `b` is na while nothing is picked.
f_preferGap(Gap a, Gap b) =>
bool prefer = true
if not na(b)
prefer := a.j > b.j or (a.j == b.j and a.top - a.bot > b.top - b.bot)
prefer
// Ends the live zones of one side that fail or expire on this bar and moves them to `deaths`.
// Failure is checked first, so a close back through on the last bar of a zone's life counts as a failure.
f_ageZones(array<Zone> live, array<Zone> deaths) =>
int k = 0
while k < live.size()
Zone z = live.get(k)
bool failed = z.side == SIDE_LONG ? close < z.bot : close > z.top
bool expired = bar_index - z.i >= ZONE_LIFE
if failed or expired
z.deathBar := bar_index
z.deathReason := failed ? DEATH_FAILED : DEATH_EXPIRED
live.remove(k)
deaths.push(z)
else
k += 1
k
// Opens a live zone for a print on this bar and retires the oldest live zone of that side beyond ZONE_CAP.
f_openZone(array<Zone> live, array<Zone> deaths, int id, int side, Gap g) =>
Zone z = Zone.new(id, side, g.top, g.bot, g.j, bar_index)
live.push(z)
if live.size() > ZONE_CAP
Zone old = live.shift()
old.deathBar := bar_index
old.deathReason := DEATH_RETIRED
deaths.push(old)
z
// ---------------------------------------------------------------------------------------------------- update
// State changes only on confirmed bars (every historical bar, the closing update of a live bar), so a print
// never appears on an open candle and is not changed after its candle closes.
if barstate.isconfirmed
// 1. Lifecycle of zones printed on earlier bars, both sides, before this bar's prints are added.
f_ageZones(liveLongZones, zoneDeaths)
f_ageZones(liveShortZones, zoneDeaths)
// 2. The first close through a pending gap's far side uses the gap up. It becomes a candidate print only
// when that close is decisive and the bar is inside the session hours; otherwise it is gone for good.
// Per side, the youngest candidate prints.
Gap longPick = na
Gap shortPick = na
int k = 0
while k < pendingGaps.size()
Gap g = pendingGaps.get(k)
bool through = g.dir == GAP_BULL ? close < g.bot : close > g.top
if through
pendingGaps.remove(k)
if g.dir == GAP_BEAR
if close - g.top >= DECISIVE_ATR * atr and sessionOk and f_preferGap(g, longPick)
longPick := g
else
if g.bot - close >= DECISIVE_ATR * atr and sessionOk and f_preferGap(g, shortPick)
shortPick := g
else
k += 1
// 3. Gaps that are GAP_MAX_WAIT bars old can no longer invert (the list is in bar order).
while pendingGaps.size() > 0
if bar_index - pendingGaps.first().j < GAP_MAX_WAIT
break
pendingGaps.shift()
// 4. This bar's new gap, if tall enough versus this bar's ATR. A bar forms at most one gap: the bullish and
// bearish conditions exclude each other.
if bullGap and bullTop - bullBot >= floorK * atr
pendingGaps.push(Gap.new(GAP_BULL, bullTop, bullBot, bar_index))
if bearGap and bearTop - bearBot >= floorK * atr
pendingGaps.push(Gap.new(GAP_BEAR, bearTop, bearBot, bar_index))
// 5. This bar's prints open live zones (the cap may retire an older zone of the same side).
if not na(longPick)
zoneCount += 1
f_openZone(liveLongZones, zoneDeaths, zoneCount, SIDE_LONG, longPick)
printLong := true
longId := zoneCount
longTop := longPick.top
longBot := longPick.bot
longJ := longPick.j
if not na(shortPick)
zoneCount += 1
f_openZone(liveShortZones, zoneDeaths, zoneCount, SIDE_SHORT, shortPick)
printShort := true
shortId := zoneCount
shortTop := shortPick.top
shortBot := shortPick.bot
shortJ := shortPick.j
// ---------------------------------------------------------------------------------------------------- data window
// Verification values for Bar Replay checks. They show in the Data Window only and never draw on the chart.
// Print: 1 long, -1 short, 2 both, 0 none. Gap age = print bar - gap bar.
plot(printLong and printShort ? 2 : printLong ? 1 : printShort ? -1 : 0, "Print", display = display.data_window, precision = 0)
plot(longTop, "Long top", display = display.data_window)
plot(longBot, "Long bottom", display = display.data_window)
plot(bar_index - longJ, "Long gap age", display = display.data_window, precision = 0)
plot(shortTop, "Short top", display = display.data_window)
plot(shortBot, "Short bottom", display = display.data_window)
plot(bar_index - shortJ, "Short gap age", display = display.data_window, precision = 0)
// ---------------------------------------------------------------------------------------------------- alerts
alertcondition(printLong, "Bullish IFVG", "Bullish IFVG on {{ticker}} ({{interval}})")
alertcondition(printShort, "Bearish IFVG", "Bearish IFVG on {{ticker}} ({{interval}})")
alertcondition(printLong or printShort, "Any IFVG", "IFVG on {{ticker}} ({{interval}})")
// One message per bar close names every print of the bar: side, symbol, timeframe and zone (bottom - top).
f_alertText(string sideName, float top, float bot) =>
sideName + " IFVG on " + syminfo.ticker + " (" + timeframe.period + "), zone " + str.tostring(bot, format.mintick) + " - " + str.tostring(top, format.mintick)
if printLong or printShort
string msg = printLong ? f_alertText("Bullish", longTop, longBot) : ""
if printShort
string shortText = f_alertText("Bearish", shortTop, shortBot)
msg := msg == "" ? shortText : msg + " | " + shortText
alert(msg, alert.freq_once_per_bar_close)
// ==== ENGINE END ====
// ---------------------------------------------------------------------------------------------------- DRAWING
// Glass look. A live zone is one glass box with a lit rim on both price edges:
// box a faint fill, quiet end caps at its left and right ends, and a small caption inside the zone at its
// right end, "IFVG" with an up or down glyph
// rim three lines on the top edge and three on the bottom edge: a soft 6 px outer glow, a 3 px inner glow
// and a crisp 1 px core. Line widths are screen pixels, so the glow keeps its size at every zoom and
// never makes a zone look taller than its price range.
// mid a dotted line through the middle of the zone
// Per side, the newest live zone is a step brighter than the older one. A zone that has ended leaves one faint
// frosted box (when past zones are shown). A small triangle marks every print candle: below it for long, above
// it for short. Colors follow the chart background, with their own fill and glow values on light charts.
//
// TradingView draws a script's boxes above its lines, whatever the creation order, and a later line above an
// earlier one. So each edge is created outer, inner, core (the core lies on top), and the box keeps its fill
// faint and its border in the rim's own ink, so lying over the rim does not dim it.
//
// Drawings are created only when a zone prints and changed only when a zone prints or dies; live right edges
// move only on the last bar. A live zone is 1 box and 7 lines (4 live zones at most) and a past zone is 1 box
// (24 at most), so at most 28 boxes and 28 lines exist at once, far below the 500 per type. This block reads
// only the engine outputs listed at the top of the file (and the "Show past zones" input) and never writes to
// engine state.
// Ink follows the chart background (light or dark).
float luma = color.r(chart.bg_color) * 0.299 + color.g(chart.bg_color) * 0.587 + color.b(chart.bg_color) * 0.114
bool light = luma > 140
color bullInk = light ? color.rgb(0, 99, 112) : color.rgb(84, 206, 207) // cyan
color bearInk = light ? color.rgb(148, 90, 25) : color.rgb(229, 185, 119) // champagne gold
color deadInk = light ? color.rgb(120, 120, 128) : color.rgb(110, 112, 124)
color clearInk = color.new(color.black, 100)
// Layout.
const int LIVE_FORWARD = 8 // live glass reaches this many bars past the last bar
const int MID_FORWARD = 1 // the midline stops this many bars past the last bar, clear of the caption
const int GHOST_MAX = 24 // past zones kept on the chart; the oldest goes first
const int OUTER_W = 6 // rim line widths in screen pixels: outer glow, inner glow, core
const int INNER_W = 3
const int CORE_W = 1
// Glass recipe, as transparency (0 solid, 100 invisible). The *New values paint the newest live zone of a
// side, the *Old values the older one: the same glass, one step quieter. Fills and glows have their own values
// on light charts, where a tint reads stronger and a glow reads as a soft shadow.
int outerNew = light ? 94 : 88 // outer glow line
int outerOld = light ? 97 : 94
int innerNew = light ? 86 : 76 // inner glow line
int innerOld = light ? 92 : 88
int fillNew = light ? 90 : 85 // box fill
int fillOld = light ? 94 : 90
int goldAdd = light ? 0 : 4 // a faint gold tint on a dark chart turns brown, so gold fills there are a
// little fainter and the gold rim carries the color
const int EDGE_NEW = 15 // 1 px core line on each price edge
const int EDGE_OLD = 45
const int ENDS_NEW = 60 // box border: quiet end caps (along the price edges it lies over the core)
const int ENDS_OLD = 78
const int TEXT_NEW = 10 // caption
const int TEXT_OLD = 35
const int MID_NEW = 45 // dotted midline
const int MID_OLD = 60
// Ghosts and print markers.
const float GHOST_FADE = 0.50 // expired and retired ghosts: side ink blended this far toward deadInk
const int GHOST_FILL = 94
const int GHOST_EDGE = 80
const int GHOST_EDGE_FAILED = 72
const int MARK_T = 10
// A zone's left end (j - 1) sits up to GAP_MAX_WAIT + 1 bars behind its print and up to GAP_MAX_WAIT +
// ZONE_LIFE + 1 bars behind the last bar that moves it. Placing a drawing on an older bar reads `time` history,
// so keep a fixed buffer for it; Bar Replay cannot grow the buffer on the fly.
max_bars_back(time, 300)
// The drawings of one live zone.
type Glass
box core // the zone itself: faint fill, quiet end caps, caption
array<line> rim // top edge outer glow, inner glow, core, then the same three on the bottom edge
line mid // dotted midline
var map<int, Glass> glassOf = map.new<int, Glass>() // zone id -> glass, live zones only
var array<box> ghostBoxes = array.new<box>() // past zones, oldest first
// Color `a` blended toward color `b` by `t` (0 = a, 1 = b), opaque.
f_blend(color a, color b, float t) =>
color.rgb(color.r(a) + (color.r(b) - color.r(a)) * t, color.g(a) + (color.g(b) - color.g(a)) * t, color.b(a) + (color.b(b) - color.b(a)) * t)
// Rim core, end cap and caption ink. On a dark chart the side ink lifted toward white reads as a lit glass rim;
// on a light chart the plain side ink is already the crispest line.
f_rimInk(color ink) =>
light ? ink : f_blend(ink, color.white, 0.30)
// Glass for a zone printed on this bar, from the gap's middle candle (j - 1) to the print bar. It is created
// clear; f_paintSide paints it on the same bar. Each edge's lines are created outer, inner, core, so the core
// lies on top.
f_newGlass(int side, float top, float bot, int j) =>
int x1 = j - 1
float half = (top + bot) / 2
string caption = side == SIDE_LONG ? "IFVG ▲" : "IFVG ▼"
box core = box.new(x1, top, bar_index, bot, border_color = clearInk, bgcolor = clearInk, text = caption, text_size = size.small, text_color = clearInk, text_halign = text.align_right, text_valign = text.align_center)
line mid = line.new(x1, half, bar_index, half, color = clearInk, style = line.style_dotted, width = 1)
array<line> rim = array.new<line>()
for price in array.from(top, bot)
rim.push(line.new(x1, price, bar_index, price, color = clearInk, width = OUTER_W))
rim.push(line.new(x1, price, bar_index, price, color = clearInk, width = INNER_W))
rim.push(line.new(x1, price, bar_index, price, color = clearInk, width = CORE_W))
Glass.new(core, rim, mid)
// Paints one live zone: in full when it is the newest of its side, a step dimmer when it is the older one.
f_paint(Glass g, int side, bool newest) =>
color ink = side == SIDE_LONG ? bullInk : bearInk
color lit = f_rimInk(ink)
color outer = color.new(ink, newest ? outerNew : outerOld)
color inner = color.new(ink, newest ? innerNew : innerOld)
color edge = color.new(lit, newest ? EDGE_NEW : EDGE_OLD)
g.core.set_bgcolor(color.new(ink, (newest ? fillNew : fillOld) + (side == SIDE_SHORT ? goldAdd : 0)))
g.core.set_border_color(color.new(lit, newest ? ENDS_NEW : ENDS_OLD))
g.core.set_text_color(color.new(lit, newest ? TEXT_NEW : TEXT_OLD))
g.mid.set_color(color.new(ink, newest ? MID_NEW : MID_OLD))
for [k, l] in g.rim
int layer = k < 3 ? k : k - 3 // 0 outer glow, 1 inner glow, 2 core, on either edge
l.set_color(layer == 0 ? outer : layer == 1 ? inner : edge)
newest
// Repaints the live zones of one side by age (the list is oldest first, so the last zone is the newest).
f_paintSide(array<Zone> live) =>
int newestAt = live.size() - 1
for [k, z] in live
Glass g = glassOf.get(z.id)
if not na(g)
f_paint(g, z.side, k == newestAt)
newestAt
// Moves a live zone's right edges: the glass and its rim to `right`, the midline to `midRight`.
f_reach(Glass g, int right, int midRight) =>
g.core.set_right(right)
for l in g.rim
l.set_x2(right)
g.mid.set_x2(midRight)
right
// A zone that died on this bar. The rim and the midline go; the box stays as one faint frosted ghost from
// j - 1 to the death bar (failed zones in deadInk, expired and retired zones in a faded tint of their side),
// or goes too when past zones are hidden.
f_bury(Glass g, Zone z) =>
for l in g.rim
l.delete()
g.mid.delete()
if showPast
bool failed = z.deathReason == DEATH_FAILED
color frost = failed ? deadInk : f_blend(z.side == SIDE_LONG ? bullInk : bearInk, deadInk, GHOST_FADE)
g.core.set_right(z.deathBar)
g.core.set_text("")
g.core.set_bgcolor(color.new(frost, GHOST_FILL))
g.core.set_border_color(color.new(frost, failed ? GHOST_EDGE_FAILED : GHOST_EDGE))
ghostBoxes.push(g.core)
if ghostBoxes.size() > GHOST_MAX
ghostBoxes.shift().delete()
else
g.core.delete()
showPast
// 1. Zones that died on this bar become ghosts (they all printed on earlier bars, so their glass exists).
for z in zoneDeaths
Glass g = glassOf.remove(z.id)
if not na(g)
f_bury(g, z)
// 2. This bar's prints get their glass.
if printLong
glassOf.put(longId, f_newGlass(SIDE_LONG, longTop, longBot, longJ))
if printShort
glassOf.put(shortId, f_newGlass(SIDE_SHORT, shortTop, shortBot, shortJ))
// 3. Brightness follows age, so recolor only on bars where a zone printed or died.
if printLong or printShort or zoneDeaths.size() > 0
f_paintSide(liveLongZones)
f_paintSide(liveShortZones)
// 4. Live zones reach past the last bar; the midline stops short of the caption.
if barstate.islast
for z in liveLongZones
Glass g = glassOf.get(z.id)
if not na(g)
f_reach(g, bar_index + LIVE_FORWARD, bar_index + MID_FORWARD)
for z in liveShortZones
Glass g = glassOf.get(z.id)
if not na(g)
f_reach(g, bar_index + LIVE_FORWARD, bar_index + MID_FORWARD)
// Print markers on the inverting candle: a small triangle below it for long, above it for short.
plotshape(printLong, "Long print", shape.triangleup, location.belowbar, color.new(bullInk, MARK_T), size = size.tiny, display = display.pane)
plotshape(printShort, "Short print", shape.triangledown, location.abovebar, color.new(bearInk, MARK_T), size = size.tiny, display = display.pane)