本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) K'u Hero
//@version=6
// Fair Value Gaps - Closed Bar, MTF v1.1
//
// Gap rule (closed bars only, the same rule for the chart timeframe and the optional higher timeframe)
// - Bullish FVG: low > high[2] -> gap = high[2] (bottom) to low (top)
// - Bearish FVG: high < low[2] -> gap = high (bottom) to low[2] (top)
// - Optional minimum size: percent of the close of the third bar, or a number of ticks (syminfo.mintick)
// - The box starts at the middle bar of the three-bar pattern
// Fill rule, from the bar after the third bar (wicks)
// - Touched : bullish when low <= top, bearish when high >= bottom
// - 50% : bullish when low <= midpoint, bearish when high >= midpoint
// - Full : bullish when low <= bottom, bearish when high >= top
// - A filled gap is deleted, or kept as a grey box that ends at the close of the filling bar
// Tracking: only the newest N unfilled (and N grey) gaps per side are kept. An older unfilled gap beyond the limit
// is dropped for good: it is no longer drawn, filled or used for alerts.
// Optional distance filter: gaps whose nearer edge is farther than X% from the close of the last closed bar are not
// drawn. They are still tracked (fill state and alerts continue) and are drawn again when price comes back within X%.
// Gaps are created and updated only when a bar closes (barstate.isconfirmed). A gap never moves after it is created.
// The forming bar is not used, so a gap that is being filled right now is shown as filled after that bar closes.
// Higher timeframe gaps are requested with [1] and lookahead_on, so only closed higher timeframe bars are used.
// Tick-based higher timeframes are not supported.
// Display only. This is not a buy/sell signal and not a forecast.
indicator("Fair Value Gaps - Closed Bar, MTF", shorttitle = "FVG", overlay = true, max_boxes_count = 500, max_lines_count = 500)
// ---------- Inputs ----------
grpR = "Gap rules"
inMinMode = input.string("None", "Minimum gap size", options = ["None", "Percent of price", "Ticks"], group = grpR)
inMinPct = input.float(0.05, "Minimum size: percent of price", minval = 0.0, maxval = 100.0, step = 0.01, group = grpR)
inMinTicks = input.int(10, "Minimum size: ticks", minval = 0, maxval = 1000000, group = grpR)
inFill = input.string("50%", "Filled when price reaches", options = ["Touched", "50%", "Full"], group = grpR)
inFilled = input.string("Delete", "Filled gaps", options = ["Delete", "Grey, stop extending"], group = grpR)
grpD = "Display"
inMaxU = input.int(10, "Unfilled gaps shown per side", minval = 1, maxval = 50, group = grpD, display = display.none)
inMaxF = input.int(10, "Filled (grey) gaps shown per side", minval = 1, maxval = 50, group = grpD, display = display.none)
inExtend = input.int(10, "Extend unfilled gaps to the right by N bars", minval = 0, maxval = 500, group = grpD, display = display.none)
inHide = input.bool(true, "Hide gaps farther than X% from current price", group = grpD, inline = "hd", display = display.none)
inHidePct = input.float(3.0, "", minval = 0.01, maxval = 100.0, step = 0.5, group = grpD, inline = "hd", display = display.none)
inMid = input.bool(true, "Show 50% line", group = grpD, display = display.none)
inLabels = input.bool(false, "Show labels on chart timeframe gaps", group = grpD, display = display.none)
cBull = input.color(#26A69A, "Bullish FVG", group = grpD, inline = "bu", display = display.none)
cBear = input.color(#EF5350, "Bearish FVG", group = grpD, inline = "be", display = display.none)
cFilled = input.color(#9E9E9E, "Filled FVG", group = grpD, inline = "fi", display = display.none)
inFillT = input.int(80, "Fill transparency (0-100)", minval = 0, maxval = 100, group = grpD, display = display.none)
inBorder = input.bool(true, "Border: show / width", group = grpD, inline = "bd", display = display.none)
inBorderW = input.int(1, "", minval = 1, maxval = 4, group = grpD, inline = "bd", display = display.none)
inBorderT = input.int(40, "Border transparency (0-100)", minval = 0, maxval = 100, group = grpD, display = display.none)
cMid = input.color(#787B86, "50% line: color / style", group = grpD, inline = "mi", display = display.none)
inMidStyle = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], group = grpD, inline = "mi", display = display.none)
inLblSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = grpD, display = display.none)
grpH = "Higher timeframe FVGs (optional)"
inHtfOn = input.bool(false, "Show higher timeframe FVGs", group = grpH)
inHtf = input.timeframe("240", "Higher timeframe", group = grpH)
inHtfMaxU = input.int(5, "HTF unfilled gaps shown per side", minval = 1, maxval = 20, group = grpH, display = display.none)
inHtfMaxF = input.int(3, "HTF filled (grey) gaps shown per side", minval = 1, maxval = 20, group = grpH, display = display.none)
cHtfBull = input.color(#1E88E5, "HTF bullish FVG", group = grpH, inline = "hb", display = display.none)
cHtfBear = input.color(#FB8C00, "HTF bearish FVG", group = grpH, inline = "hs", display = display.none)
// ---------- Settings ----------
int minMode = inMinMode == "Percent of price" ? 1 : inMinMode == "Ticks" ? 2 : 0
int fillMode = inFill == "Touched" ? 0 : inFill == "50%" ? 1 : 2
bool keepF = inFilled == "Grey, stop extending"
bool htfTick = inHtfOn and str.contains(inHtf, "T")
bool htfLow = inHtfOn and not htfTick and timeframe.in_seconds(inHtf) <= timeframe.in_seconds(timeframe.period)
bool htfOn = inHtfOn and not htfTick and not htfLow
// ---------- Gap engine ----------
type Fvg
float top
float bot
int dir // +1 bullish / -1 bearish
int tLeft // open time of the middle bar
bool filled
int tFill // open time of the filling bar
bool pin // previous bar was inside the gap
// Processes the current bar when gate is true.
// Returns [gaps (oldest first), new bullish, new bearish, price entered an unfilled bullish gap, ... bearish gap].
// Only the newest maxU unfilled and (when kept) maxF filled gaps per side are tracked. An older unfilled gap beyond
// maxU is dropped for good (no longer drawn, filled or used for alerts).
f_engine(bool gate, int mMode, float mPct, int mTicks, int fMode, int maxU, bool kf, int maxF) =>
var array<Fvg> zs = array.new<Fvg>()
bool nBull = false
bool nBear = false
bool eBull = false
bool eBear = false
if gate and bar_index >= 2
// 1) update the existing gaps with this closed bar
for z in zs
if not z.filled
bool up = z.dir > 0
bool inz = up ? low <= z.top : high >= z.bot
if inz and not z.pin
if up
eBull := true
else
eBear := true
z.pin := inz
float mid = (z.top + z.bot) / 2.0
float lvl = up ? (fMode == 0 ? z.top : fMode == 1 ? mid : z.bot) : (fMode == 0 ? z.bot : fMode == 1 ? mid : z.top)
bool hit = up ? low <= lvl : high >= lvl
if hit
z.filled := true
z.tFill := time
// 2) a new gap
float gTop = na
float gBot = na
int d = 0
if low > high[2]
gTop := low
gBot := high[2]
d := 1
else if high < low[2]
gTop := low[2]
gBot := high
d := -1
if d != 0
float g = gTop - gBot
bool ok = mMode == 1 ? (close > 0 and g / close * 100.0 >= mPct) : mMode == 2 ? (syminfo.mintick > 0 and g / syminfo.mintick >= mTicks - 1e-9) : true
if ok and g > 0
zs.push(Fvg.new(gTop, gBot, d, time[1], false, 0, false))
if d > 0
nBull := true
else
nBear := true
// 3) keep only the newest maxU unfilled / maxF filled gaps per side (drop the older ones)
int n = zs.size()
if n > 0
int uB = 0
int uS = 0
int fB = 0
int fS = 0
for i = n - 1 to 0
Fvg z = zs.get(i)
bool up = z.dir > 0
if not z.filled
if up
if uB >= maxU
zs.remove(i)
else
uB += 1
else
if uS >= maxU
zs.remove(i)
else
uS += 1
else if not kf
zs.remove(i)
else if up
if fB >= maxF
zs.remove(i)
else
fB += 1
else
if fS >= maxF
zs.remove(i)
else
fS += 1
[zs, nBull, nBear, eBull, eBear]
// Higher timeframe: a deep copy per bar so that [1] returns the state of the previous (closed) HTF bar.
// gate = true: inside request.security barstate.isconfirmed is not reliable, and [1] already reads closed HTF bars only.
f_htfCopy(int mMode, float mPct, int mTicks, int fMode, int maxU, bool kf, int maxF) =>
[src, hnB, hnS, heB, heS] = f_engine(true, mMode, mPct, mTicks, fMode, maxU, kf, maxF)
array<Fvg> out = array.new<Fvg>()
for z in src
out.push(z.copy())
out
// ---------- Chart timeframe ----------
[cz, newBull, newBear, entBull, entBear] = f_engine(barstate.isconfirmed, minMode, inMinPct, inMinTicks, fillMode, inMaxU, keepF, inMaxF)
// ---------- Higher timeframe ----------
array<Fvg> hz = na
if htfOn
hz := request.security(syminfo.tickerid, inHtf, f_htfCopy(minMode, inMinPct, inMinTicks, fillMode, inHtfMaxU, keepF, inHtfMaxF)[1], lookahead = barmerge.lookahead_on)
// ---------- Alerts (chart timeframe, on bar close) ----------
alertcondition(newBull, "New bullish FVG", "New bullish FVG on {{ticker}} {{interval}}")
alertcondition(newBear, "New bearish FVG", "New bearish FVG on {{ticker}} {{interval}}")
alertcondition(entBull, "Price entered a bullish FVG", "Price entered an unfilled bullish FVG on {{ticker}} {{interval}}")
alertcondition(entBear, "Price entered a bearish FVG", "Price entered an unfilled bearish FVG on {{ticker}} {{interval}}")
if newBull
alert("New bullish FVG on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if newBear
alert("New bearish FVG on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if entBull
alert("Price entered an unfilled bullish FVG on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
if entBear
alert("Price entered an unfilled bearish FVG on " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
// ---------- Drawing (last bar only) ----------
f_tfName(string tf) =>
int s = timeframe.in_seconds(tf)
s >= 2419200 ? str.tostring(math.round(s / 2628003.0)) + "M" : s >= 604800 ? str.tostring(s / 604800) + "W" : s >= 86400 ? str.tostring(s / 86400) + "D" : s >= 3600 ? str.tostring(s / 3600) + "H" : s >= 60 ? str.tostring(s / 60) + "m" : str.tostring(s) + "s"
f_txtSize() =>
inLblSize == "Tiny" ? size.tiny : inLblSize == "Normal" ? size.normal : size.small
f_midStyle() =>
inMidStyle == "Solid" ? line.style_solid : inMidStyle == "Dotted" ? line.style_dotted : line.style_dashed
// Distance in percent from the reference price to the nearer edge of the gap (0 when the price is inside).
f_distPct(Fvg z, float ref) =>
float d = ref > z.top ? ref - z.top : ref < z.bot ? z.bot - ref : 0.0
ref > 0 ? d / ref * 100.0 : 0.0
// Draws the stored gaps (oldest first, so newer gaps are on top). Gaps beyond the distance filter are skipped.
f_drawSet(array<Fvg> zs, bool isHtf, int rightT, int barMs, string lbl, float ref, array<box> bStore, array<line> lStore) =>
for z in zs
if inHide and f_distPct(z, ref) > inHidePct
continue
color base = z.filled ? cFilled : z.dir > 0 ? (isHtf ? cHtfBull : cBull) : (isHtf ? cHtfBear : cBear)
int r = z.filled ? z.tFill + barMs : rightT
int bw = isHtf ? inBorderW + 1 : inBorderW
color bc = inBorder or isHtf ? color.new(base, inBorderT) : color.new(base, 100)
bStore.push(box.new(z.tLeft, z.top, r, z.bot, xloc = xloc.bar_time, border_color = bc, border_width = bw,
bgcolor = color.new(base, inFillT), text = lbl, text_size = f_txtSize(), text_color = color.new(base, 0),
text_halign = text.align_right, text_valign = text.align_center))
if inMid
float m = (z.top + z.bot) / 2.0
lStore.push(line.new(z.tLeft, m, r, m, xloc = xloc.bar_time, color = z.filled ? color.new(cFilled, 40) : cMid, style = f_midStyle(), width = 1))
var array<box> boxes = array.new<box>()
var array<line> lines = array.new<line>()
var table msgTbl = table.new(position.top_right, 1, 1, border_width = 0)
if barstate.islast
for b in boxes
b.delete()
boxes.clear()
for l in lines
l.delete()
lines.clear()
int tfMs = timeframe.in_seconds(timeframe.period) * 1000
int rightT = time + inExtend * tfMs
float refPx = barstate.isconfirmed ? close : close[1] // close of the last closed bar
if htfOn and not na(hz)
f_drawSet(hz, true, rightT, timeframe.in_seconds(inHtf) * 1000, f_tfName(inHtf) + " FVG", refPx, boxes, lines)
f_drawSet(cz, false, rightT, tfMs, inLabels ? "FVG" : "", refPx, boxes, lines)
string msg = htfTick ? "FVG: tick-based higher timeframes are not supported (HTF gaps are off)" : htfLow ? "FVG: higher timeframe must be above the chart timeframe (HTF gaps are off)" : htfOn and na(hz) ? "FVG: loading higher timeframe data" : ""
if msg != ""
table.cell(msgTbl, 0, 0, msg, text_color = color.rgb(255, 69, 0), text_size = size.small)
else
table.clear(msgTbl, 0, 0)