本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OrbFlow Labs
//@version=6
// ═══════════════════════════════════════════════════════════════════════════════
// GAPFLOW v1.0 [OrbFlow]
// ═══════════════════════════════════════════════════════════════════════════════
// Finds price gaps, boxes them, and tracks how much of each one has been filled
// during the trading session:
//
// OPENING GAP the session open vs the previous session's last close
// (09:30 vs 16:00 New York by default).
// INTRADAY GAPS a bar whose low is above the previous bar's high (gap up) or
// whose high is below the previous bar's low (gap down), at
// least a set size, confirmed on bar close.
// FILL each box shrinks to the part that is still unfilled; the
// filled part can be shaded. When price trades through the far
// edge the gap is filled: the box is removed and the fill is
// added to the day's tally.
// CARRY-OVER unfilled gaps can stay on the chart into the next days.
// DASHBOARD opening gap size, % filled, points left, minutes since the
// open, NQ/MNQ historical same-session fill rate for gaps of
// that size, and today's opened / filled / open counts.
//
// NOTES
// - No buy or sell signals. It shows where gaps are and how far they have
// been filled; it does not predict whether a gap will fill.
// - Fills are counted only inside the trading-hours window. Gaps filled
// outside it are removed without being counted.
// - The historical fill-rate row is measured on MNQ RTH sessions from
// May 2019 to Nov 2026. It describes the past and is shown only on NQ/MNQ.
// ═══════════════════════════════════════════════════════════════════════════════
indicator("GAPFLOW [OrbFlow]", "GAPFLOW", overlay = true, max_boxes_count = 500, max_labels_count = 200)
// ─── Inputs ────────────────────────────────────────────────────────────────────
grpS = "Session"
tz = input.string("America/New_York", "Timezone", options = ["America/New_York", "America/Chicago", "Europe/London", "Europe/Berlin", "Asia/Tokyo", "UTC"], group = grpS)
sess = input.session("0930-1600", "Trading hours", group = grpS,
tooltip = "The opening gap is this window's open vs the previous window's last close. Fills are counted inside this window.")
grpG = "Gaps"
rthOn = input.bool(true, "Opening gap", group = grpG)
rthMin = input.float(0.0, "Minimum opening gap (points)", minval = 0, group = grpG)
idOn = input.bool(true, "Intraday bar-to-bar gaps", group = grpG)
idMin = input.float(2.0, "Minimum intraday gap (points)", minval = 0, group = grpG)
idSessOnly = input.bool(true, "Intraday gaps only during trading hours", group = grpG)
carryOn = input.bool(true, "Carry unfilled gaps into the next day", group = grpG)
carryMax = input.int(6, "Max gaps carried over", minval = 1, maxval = 50, group = grpG)
carryDays = input.int(3, "Carry for up to (sessions)", minval = 1, maxval = 60, group = grpG,
tooltip = "Unfilled gaps older than this many sessions are removed. Old, distant gaps also stretch the price scale.")
maxActive = input.int(120, "Max gaps on the chart", minval = 10, maxval = 200, group = grpG,
tooltip = "The oldest intraday gaps are dropped above this count, to stay inside TradingView's drawing limits.")
grpV = "Style"
colUp = input.color(color.new(#089981, 0), "Gap up / gap down", group = grpV, inline = "c")
colDn = input.color(color.new(#F23645, 0), "", group = grpV, inline = "c")
colRth = input.color(color.new(#2962FF, 0), "Opening gap", group = grpV)
fillT = input.int(78, "Box transparency", minval = 0, maxval = 100, group = grpV)
partialOn = input.bool(true, "Shade the filled part", group = grpV)
extBars = input.int(8, "Extend boxes right (bars)", minval = 0, maxval = 100, group = grpV)
idText = input.bool(true, "Show size on intraday gaps", group = grpV)
grpD = "Dashboard"
dashOn = input.bool(true, "Show dashboard", group = grpD)
dashPos = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left", "Middle right"], group = grpD)
dashSz = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = grpD)
// ─── Helpers ───────────────────────────────────────────────────────────────────
f_tsz(string s) => s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : size.small
f_pos(string p) =>
switch p
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
"Middle right" => position.middle_right
=> position.top_right
f_pts(float v) => str.tostring(v, format.mintick)
// MNQ, RTH opening gap filled the same session, 2019-05 to 2026-11 (1,819 sessions).
f_hist(float s) => s < 5 ? 96.5 : s < 10 ? 91.9 : s < 20 ? 88.9 : s < 40 ? 79.3 : s < 80 ? 62.6 : 37.8
f_bucket(float s) => s < 5 ? "<5" : s < 10 ? "5-10" : s < 20 ? "10-20" : s < 40 ? "20-40" : s < 80 ? "40-80" : "80+"
// ─── Gap object ────────────────────────────────────────────────────────────────
// dir +1 = gap up (sits below price, fills downward to bot)
// dir -1 = gap down (sits above price, fills upward to top)
// edge = the unfilled edge nearest price; it moves toward the far edge.
type Gap
int dir
bool rth
float top
float bot
float edge
int left
int day
box bx
box fx
label lb
method gsize(Gap g) => g.top - g.bot
method remaining(Gap g) => g.dir > 0 ? g.edge - g.bot : g.top - g.edge
method pct(Gap g) => g.gsize() > 0 ? 100.0 * (1.0 - g.remaining() / g.gsize()) : 100.0
method col(Gap g) => g.rth ? colRth : g.dir > 0 ? colUp : colDn
method kill(Gap g) =>
box.delete(g.bx)
box.delete(g.fx)
label.delete(g.lb)
method draw(Gap g, int curDay) =>
int r = bar_index + extBars
int lft = math.max(g.left, bar_index - 9000) // drawings can't start more than ~10k bars back
float uTop = g.dir > 0 ? g.edge : g.top
float uBot = g.dir > 0 ? g.bot : g.edge
color c = g.col()
if na(g.bx)
g.bx := box.new(lft, uTop, r, uBot, border_color = color.new(c, 35), bgcolor = color.new(c, fillT),
text_size = size.tiny, text_color = color.new(c, 0), text_halign = text.align_left, text_valign = text.align_top)
box.set_lefttop(g.bx, lft, uTop)
box.set_rightbottom(g.bx, r, uBot)
if not g.rth and idText
box.set_text(g.bx, f_pts(g.gsize()))
if partialOn and g.remaining() < g.gsize()
float fTop = g.dir > 0 ? g.top : g.edge
float fBot = g.dir > 0 ? g.edge : g.bot
if na(g.fx)
g.fx := box.new(lft, fTop, r, fBot, border_color = color.new(c, 55), border_style = line.style_dotted,
bgcolor = color.new(c, math.min(fillT + 9, 96)))
box.set_lefttop(g.fx, lft, fTop)
box.set_rightbottom(g.fx, r, fBot)
if g.rth
string t = (g.day < curDay ? "Prior opening gap " : "Opening gap ") + (g.dir > 0 ? "▲ " : "▼ ") + f_pts(g.gsize()) +
" · " + str.tostring(g.pct(), "#") + "% filled"
if na(g.lb)
g.lb := label.new(lft, g.top, t, style = label.style_label_lower_left, color = color.new(color.black, 100),
textcolor = color.new(c, 0), size = size.small)
label.set_x(g.lb, lft)
label.set_text(g.lb, t)
// ─── State ─────────────────────────────────────────────────────────────────────
inSess = not na(time(timeframe.period, sess, tz))
// A new session starts on the first in-hours bar, or on a new calendar day (charts
// that show regular hours only have every bar inside the window).
newSess = inSess and (not inSess[1] or dayofmonth(time, tz) != dayofmonth(time[1], tz))
var array<Gap> gaps = array.new<Gap>()
var float lastSessClose = na
var int dayId = 0
var int sessStartMs = na
var int openedToday = 0
var int filledToday = 0
var int filledNew = 0
var int filledCarried = 0
// opening gap of the current day, kept for the dashboard after its box is gone
var float rthSize = na
var int rthDir = 0
var bool rthDone = false
var string rthAt = ""
var float rthPct = 0.0
var float rthLeft = na
bool evOpened = false
bool evFilled = false
bool evRth = false
string evText = ""
// ─── New session: carry or clear, then the opening gap ─────────────────────────
if newSess and timeframe.isintraday
if not carryOn
for g in gaps
g.kill()
gaps.clear()
else
if gaps.size() > 0
for i = gaps.size() - 1 to 0
if dayId + 1 - gaps.get(i).day > carryDays
gaps.remove(i).kill()
while gaps.size() > carryMax
gaps.shift().kill()
dayId += 1
sessStartMs := time
openedToday := 0
filledToday := 0
filledNew := 0
filledCarried := 0
rthSize := na
rthDir := 0
rthDone := false
rthAt := ""
rthPct := 0.0
rthLeft := na
float pc = lastSessClose
if rthOn and not na(pc) and open != pc and math.abs(open - pc) >= rthMin
int d = open > pc ? 1 : -1
Gap g = Gap.new(d, true, math.max(open, pc), math.min(open, pc), d > 0 ? math.max(open, pc) : math.min(open, pc), bar_index, dayId)
gaps.push(g)
openedToday += 1
rthSize := g.gsize()
rthDir := d
rthLeft := g.gsize()
evOpened := true
evText += "Opening gap " + (d > 0 ? "up " : "down ") + f_pts(g.gsize()) + " pts (" + f_pts(g.bot) + " - " + f_pts(g.top) + "). "
// Last close inside trading hours (read at the next session's open).
if inSess
lastSessClose := close
// ─── Fill tracking (every bar; counted only inside trading hours) ──────────────
if gaps.size() > 0
for i = gaps.size() - 1 to 0
Gap g = gaps.get(i)
float before = g.edge
if g.dir > 0
g.edge := math.max(g.bot, math.min(g.edge, low))
else
g.edge := math.min(g.top, math.max(g.edge, high))
bool filled = g.dir > 0 ? low <= g.bot : high >= g.top
if g.rth and g.day == dayId
rthPct := filled ? 100.0 : g.pct()
rthLeft := filled ? 0.0 : g.remaining()
if filled
g.kill()
gaps.remove(i)
evFilled := true
if inSess
filledToday += 1
if g.day == dayId
filledNew += 1
else
filledCarried += 1
if g.rth and g.day == dayId
rthDone := true
rthAt := str.format_time(time, "HH:mm", tz)
evRth := true
evText += (g.rth ? "Opening gap" : "Gap") + " " + f_pts(g.bot) + " - " + f_pts(g.top) + " filled. "
else if na(g.bx) or g.edge != before or barstate.islast
g.draw(dayId)
// ─── Intraday gaps (confirmed bars only) ───────────────────────────────────────
if idOn and timeframe.isintraday and barstate.isconfirmed and not newSess and (inSess or not idSessOnly)
Gap ng = na
if low > high[1] and low - high[1] >= idMin
ng := Gap.new(1, false, low, high[1], low, bar_index - 1, dayId)
else if high < low[1] and low[1] - high >= idMin
ng := Gap.new(-1, false, low[1], high, high, bar_index - 1, dayId)
if not na(ng)
ng.draw(dayId)
gaps.push(ng)
if inSess
openedToday += 1
evOpened := true
evText += "Gap " + (ng.dir > 0 ? "up " : "down ") + f_pts(ng.gsize()) + " pts (" + f_pts(ng.bot) + " - " + f_pts(ng.top) + "). "
// drawing limits: drop the oldest intraday gap
while gaps.size() > maxActive
int k = -1
for j = 0 to gaps.size() - 1
if not gaps.get(j).rth
k := j
break
if k < 0
break
gaps.remove(k).kill()
// ─── Dashboard ─────────────────────────────────────────────────────────────────
var table dash = table.new(f_pos(dashPos), 2, 10, bgcolor = color.new(#131722, 8), border_color = color.new(#363A45, 0), border_width = 1)
color txt = color.new(#D1D4DC, 0)
color hdr = color.new(#2A2E39, 0)
color muted = color.new(#787B86, 0)
f_cell(int c, int r, string s, color tc = na, color bg = na, string tip = "") =>
table.cell(dash, c, r, s, text_color = na(tc) ? txt : tc, bgcolor = bg, text_size = f_tsz(dashSz),
text_halign = c == 0 ? text.align_left : text.align_right, tooltip = tip)
if dashOn and barstate.islast
table.clear(dash, 0, 0, 1, 9)
if not timeframe.isintraday
f_cell(0, 0, "GAPFLOW", txt, hdr)
f_cell(1, 0, "Use an intraday chart", muted, hdr)
else
bool isNQ = syminfo.root == "NQ" or syminfo.root == "MNQ"
int carried = 0
for g in gaps
if g.day < dayId
carried += 1
f_cell(0, 0, "GAPFLOW", txt, hdr)
bool live = inSess and timenow <= time_close + 2 * timeframe.in_seconds() * 1000
f_cell(1, 0, live ? "Session live" : "Session closed", live ? color.new(#089981, 0) : muted, hdr)
bool hasGap = not na(rthSize)
f_cell(0, 1, "Opening gap")
f_cell(1, 1, hasGap ? (rthDir > 0 ? "▲ " : "▼ ") + f_pts(rthSize) + " pts" : "none", hasGap ? (rthDir > 0 ? colUp : colDn) : muted)
f_cell(0, 2, "Filled")
f_cell(1, 2, not hasGap ? "-" : rthDone ? "✓ filled at " + rthAt : str.tostring(rthPct, "#") + "% · " + f_pts(rthLeft) + " pts left",
rthDone ? colUp : txt)
int mins = na(sessStartMs) ? na : int((time_close - sessStartMs) / 60000)
f_cell(0, 3, "Since open")
f_cell(1, 3, live and not na(mins) ? str.tostring(mins) + " min" : "-")
f_cell(0, 4, "MNQ history, " + (hasGap ? f_bucket(rthSize) + " pts" : "this size"))
f_cell(1, 4, not isNQ ? "n/a (NQ/MNQ only)" : hasGap ? str.tostring(f_hist(rthSize), "#.#") + "% filled same session" : "-", muted,
tip = "Share of MNQ opening gaps of this size that filled the same session, May 2019 to Nov 2026. History, not a prediction.")
f_cell(0, 5, "Gaps opened today")
f_cell(1, 5, str.tostring(openedToday))
f_cell(0, 6, "Gaps filled today")
f_cell(1, 6, str.tostring(filledToday) + (filledCarried > 0 ? " (" + str.tostring(filledCarried) + " carried)" : ""))
f_cell(0, 7, "Today's fill rate")
f_cell(1, 7, openedToday > 0 ? str.tostring(100.0 * filledNew / openedToday, "#") + "% (" + str.tostring(filledNew) + "/" + str.tostring(openedToday) + ")" : "-")
f_cell(0, 8, "Still open")
f_cell(1, 8, str.tostring(gaps.size()) + (carried > 0 ? " (" + str.tostring(carried) + " from earlier days)" : ""))
// ─── Alerts ────────────────────────────────────────────────────────────────────
alertcondition(evOpened, "Gap opened", "GAPFLOW: new gap on {{ticker}}")
alertcondition(evFilled, "Gap filled", "GAPFLOW: gap filled on {{ticker}}")
alertcondition(evRth, "Opening gap filled", "GAPFLOW: opening gap filled on {{ticker}}")
if evText != ""
alert("GAPFLOW " + syminfo.ticker + ": " + evText, alert.freq_once_per_bar)