本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// This source code is subject to the terms of the Mozilla Public License 2.0
// © cfdtools
//
// Weekend Gap Tracker & Fill Statistics
// Marks the gap between the last close of one week (or day) and the first open
// of the next, tracks how much of each gap has been filled, and keeps running
// statistics: how many gaps were found, how many were filled, how many filled
// within the same week (or day) and the median time it took.
indicator("Weekend Gap Tracker & Fill Statistics", shorttitle = "Gap Fill", overlay = true, max_boxes_count = 500, max_labels_count = 500)
// ─────────────────────────────────────────────────────────────────────────────
// Inputs
// ─────────────────────────────────────────────────────────────────────────────
GRP_GAP = "Gaps"
GRP_DRW = "Drawing"
GRP_TBL = "Table"
gapType = input.string("Weekly (weekend gaps)", "Gap type", options = ["Weekly (weekend gaps)", "Daily (session gaps)"], group = GRP_GAP, tooltip = "Weekly: gap between the last close of a week and the first open of the next week. Daily: gap between one daily session's close and the next session's open.")
fillRule = input.string("Full fill", "Count a gap as filled at", options = ["Full fill", "Half fill"], group = GRP_GAP, tooltip = "Full fill: price trades back to the previous close. Half fill: price trades back through the middle of the gap.")
minAtrMult = input.float(0.05, "Minimum gap size (x daily ATR)", minval = 0.0, step = 0.05, group = GRP_GAP, tooltip = "Ignore gaps smaller than this multiple of the previous day's ATR. Set to 0 to count every gap of at least one tick.")
atrLen = input.int(14, "Daily ATR length", minval = 1, maxval = 200, group = GRP_GAP)
upCol = input.color(color.new(#26A69A, 75), "Unfilled gap up", group = GRP_DRW)
dnCol = input.color(color.new(#EF5350, 75), "Unfilled gap down", group = GRP_DRW)
fillCol = input.color(color.new(#9E9E9E, 85), "Filled gap", group = GRP_DRW)
showFilled = input.bool(true, "Keep filled gaps on chart", group = GRP_DRW)
keepFilled = input.int(20, "Filled gaps to keep", minval = 1, maxval = 200, group = GRP_DRW)
keepOpen = input.int(20, "Unfilled gaps to draw", minval = 1, maxval = 200, group = GRP_DRW, tooltip = "Statistics always use every gap found. This only limits how many unfilled gaps are drawn.")
showLabels = input.bool(true, "Labels", group = GRP_DRW)
showTable = input.bool(true, "Show table", group = GRP_TBL)
tblPosIn = input.string("Top right", "Position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Middle left", "Bottom left"], group = GRP_TBL)
tblSizeIn = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = GRP_TBL)
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
tblPos(string s) =>
switch s
"Top right" => position.top_right
"Middle right" => position.middle_right
"Bottom right" => position.bottom_right
"Top left" => position.top_left
"Middle left" => position.middle_left
=> position.bottom_left
tblSize(string s) =>
switch s
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
fmtPct(float x) =>
na(x) ? "-" : str.tostring(x, "#.#") + "%"
fmtHours(float h) =>
na(h) ? "-" : h < 48.0 ? str.tostring(h, "#.#") + " h" : str.tostring(h / 24.0, "#.#") + " days"
// ─────────────────────────────────────────────────────────────────────────────
// Gap record
// ─────────────────────────────────────────────────────────────────────────────
type Gap
float openPx
float prevClose
bool isUp
int startTime
int period
float pctFilled = 0.0
bool filled = false
box bx = na
label lb = na
// ─────────────────────────────────────────────────────────────────────────────
// Period detection
// ─────────────────────────────────────────────────────────────────────────────
string periodTf = gapType == "Daily (session gaps)" ? "D" : "W"
string periodWord = periodTf == "D" ? "day" : "week"
bool tfTooHigh = timeframe.in_seconds() > timeframe.in_seconds(periodTf)
bool newPeriod = timeframe.change(periodTf)
float dAtr = request.security(syminfo.tickerid, "D", ta.atr(atrLen)[1], lookahead = barmerge.lookahead_on)
// ─────────────────────────────────────────────────────────────────────────────
// State
// ─────────────────────────────────────────────────────────────────────────────
var array<Gap> openGaps = array.new<Gap>()
var array<box> filledBoxes = array.new<box>()
var array<label> filledLabels = array.new<label>()
var array<float> fillHours = array.new<float>()
var int periodNo = 0
var int totalGaps = 0
var int upGaps = 0
var int filledN = 0
var int filledSame = 0
var Gap lastGap = na
bool gapOpenedNow = false
bool gapFilledNow = false
float need = fillRule == "Half fill" ? 0.5 : 1.0
// ─────────────────────────────────────────────────────────────────────────────
// New gap at the start of a week / day
// ─────────────────────────────────────────────────────────────────────────────
if newPeriod and bar_index > 0 and not tfTooHigh
periodNo += 1
float pc = close[1]
float gsz = open - pc
float minSz = na(dAtr) ? 0.0 : minAtrMult * dAtr
if math.abs(gsz) >= syminfo.mintick * 0.5 and math.abs(gsz) >= minSz
Gap g = Gap.new(open, pc, gsz > 0, time, periodNo)
totalGaps += 1
if g.isUp
upGaps += 1
float gTop = math.max(open, pc)
float gBot = math.min(open, pc)
g.bx := box.new(time, gTop, time, gBot, xloc = xloc.bar_time, border_color = color.new(g.isUp ? upCol : dnCol, 40), bgcolor = g.isUp ? upCol : dnCol)
if showLabels
float pct = math.abs(gsz) / pc * 100.0
string txt = (g.isUp ? "Gap up " : "Gap down ") + str.tostring(pct, "#.##") + "%"
g.lb := label.new(time, g.isUp ? gTop : gBot, txt, xloc = xloc.bar_time, style = g.isUp ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = chart.fg_color, size = size.small)
openGaps.push(g)
lastGap := g
gapOpenedNow := true
alert((g.isUp ? "Gap up " : "Gap down ") + "opened on " + syminfo.ticker + ": previous close " + str.tostring(pc, format.mintick) + ", open " + str.tostring(open, format.mintick), alert.freq_once_per_bar)
// Limit how many unfilled gaps are drawn (statistics keep all of them)
int drawn = 0
for i = openGaps.size() - 1 to 0
Gap og = openGaps.get(i)
if not na(og.bx)
drawn += 1
if drawn > keepOpen
box.delete(og.bx)
og.bx := na
if not na(og.lb)
label.delete(og.lb)
og.lb := na
// Hard cap on how many unfilled gaps are tracked
if openGaps.size() > 500
Gap old = openGaps.shift()
if not na(old.bx)
box.delete(old.bx)
if not na(old.lb)
label.delete(old.lb)
// ─────────────────────────────────────────────────────────────────────────────
// Track fills
// ─────────────────────────────────────────────────────────────────────────────
if openGaps.size() > 0
for i = openGaps.size() - 1 to 0
Gap g = openGaps.get(i)
float span = math.abs(g.openPx - g.prevClose)
float moved = g.isUp ? g.openPx - low : high - g.openPx
float frac = span > 0 ? math.min(1.0, math.max(0.0, moved / span)) : 1.0
g.pctFilled := math.max(g.pctFilled, frac)
if g.pctFilled >= need
g.filled := true
filledN += 1
if periodNo == g.period
filledSame += 1
fillHours.push((time - g.startTime) / 3600000.0)
gapFilledNow := true
if not na(g.bx)
if showFilled
g.bx.set_right(time)
g.bx.set_bgcolor(fillCol)
g.bx.set_border_color(color.new(fillCol, 50))
filledBoxes.push(g.bx)
if not na(g.lb)
g.lb.set_text(g.lb.get_text() + " - filled")
g.lb.set_textcolor(color.gray)
filledLabels.push(g.lb)
else
box.delete(g.bx)
if not na(g.lb)
label.delete(g.lb)
openGaps.remove(i)
alert("Gap " + (fillRule == "Half fill" ? "half " : "") + "filled on " + syminfo.ticker + " at " + str.tostring(g.prevClose, format.mintick), alert.freq_once_per_bar)
else if not na(g.bx)
g.bx.set_right(time)
while filledBoxes.size() > keepFilled
box.delete(filledBoxes.shift())
label lbOld = filledLabels.shift()
if not na(lbOld)
label.delete(lbOld)
alertcondition(gapOpenedNow, "New gap opened", "A new gap opened on {{ticker}}")
alertcondition(gapFilledNow, "Gap filled", "A gap was filled on {{ticker}}")
// ─────────────────────────────────────────────────────────────────────────────
// Statistics table
// ─────────────────────────────────────────────────────────────────────────────
var table tbl = table.new(tblPos(tblPosIn), 2, 9, bgcolor = color.new(color.black, 85), frame_color = color.new(color.gray, 60), frame_width = 1, border_color = color.new(color.gray, 80), border_width = 1)
if barstate.islast and showTable
sz = tblSize(tblSizeIn)
fg = chart.fg_color
tbl.cell(0, 0, "Gap fill stats (" + periodWord + "ly)", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 0, fillRule, text_color = fg, text_size = sz)
if tfTooHigh
tbl.cell(0, 1, "Note", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 1, "Use a timeframe of 1 " + periodWord + " or lower", text_color = fg, text_size = sz)
else
int unfilled = totalGaps - filledN
float fillPct = totalGaps > 0 ? filledN * 100.0 / totalGaps : na
float samePct = totalGaps > 0 ? filledSame * 100.0 / totalGaps : na
float medH = fillHours.size() > 0 ? fillHours.median() : na
tbl.cell(0, 1, "Gaps found", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 1, str.tostring(totalGaps) + " (" + str.tostring(upGaps) + " up, " + str.tostring(totalGaps - upGaps) + " down)", text_color = fg, text_size = sz)
tbl.cell(0, 2, "Filled", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 2, str.tostring(filledN) + " (" + fmtPct(fillPct) + ")", text_color = fg, text_size = sz)
tbl.cell(0, 3, "Filled in the same " + periodWord, text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 3, str.tostring(filledSame) + " (" + fmtPct(samePct) + ")", text_color = fg, text_size = sz)
tbl.cell(0, 4, "Median time to fill", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 4, fmtHours(medH), text_color = fg, text_size = sz)
tbl.cell(0, 5, "Still unfilled", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 5, str.tostring(unfilled), text_color = fg, text_size = sz)
string lastTxt = "-"
if not na(lastGap)
lastTxt := (lastGap.isUp ? "Up " : "Down ") + str.tostring(math.abs(lastGap.openPx - lastGap.prevClose) / lastGap.prevClose * 100.0, "#.##") + "%, " + (lastGap.filled ? "filled" : str.tostring(lastGap.pctFilled * 100.0, "#") + "% filled")
tbl.cell(0, 6, "Latest gap", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 6, lastTxt, text_color = fg, text_size = sz)
// Nearest unfilled fill level to the current price
float nearest = na
for g in openGaps
if na(nearest) or math.abs(g.prevClose - close) < math.abs(nearest - close)
nearest := g.prevClose
string nearTxt = na(nearest) ? "-" : str.tostring(nearest, format.mintick) + " (" + str.tostring((nearest - close) / close * 100.0, "#.##") + "%)"
tbl.cell(0, 7, "Nearest unfilled close", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 7, nearTxt, text_color = fg, text_size = sz)
tbl.cell(0, 8, "Daily ATR", text_color = fg, text_size = sz, text_halign = text.align_left)
tbl.cell(1, 8, na(dAtr) ? "-" : str.tostring(dAtr, format.mintick), text_color = fg, text_size = sz)