本页源码来自 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/
// © EVLabs
//@version=6
indicator("EV Gap Acceptance", "EV Gap Acceptance", overlay=true, max_bars_back=500)
string GS = "01 · Session definition"
string tz = input.string("America/New_York", "Session timezone (IANA)", group=GS)
int sh = input.int(9, "Opening hour", minval=0, maxval=23, group=GS, inline="s")
int sm = input.int(30, "Minute", minval=0, maxval=59, group=GS, inline="s")
int eh = input.int(16, "Closing hour", minval=0, maxval=23, group=GS, inline="e")
int em = input.int(0, "Minute", minval=0, maxval=59, group=GS, inline="e")
int maxDays = input.int(7, "Maximum calendar gap between sessions", minval=1, maxval=14, group=GS, tooltip="Allows weekends and holidays, but does not reconstruct an exchange holiday calendar. Missing sessions can still affect the reference.")
string GL = "02 · Gap and response"
int atrLen = input.int(14, "Completed-session ATR length", minval=2, maxval=200, group=GL)
float minGap = input.float(0.10, "Minimum gap / reference ATR", minval=0, step=0.05, group=GL)
int minTicks = input.int(2, "Minimum gap in ticks", minval=1, group=GL)
int confirms = input.int(3, "Consecutive closes for acceptance / rejection", minval=1, maxval=20, group=GL)
int decisionWindow = input.int(12, "Response window in session bars", minval=1, maxval=100, group=GL)
float tolerance = input.float(0.05, "Response buffer / reference ATR", minval=0, step=0.01, group=GL)
int sampleSize = input.int(100, "Completed qualified sessions retained", minval=10, maxval=500, group=GL)
string GV = "03 · Appearance"
bool bands = input.bool(true, "Shade the session gap", group=GV)
bool marks = input.bool(true, "Show response and fill markers", group=GV)
bool panelOn = input.bool(true, "Show panel", group=GV)
string corner = input.string("Top Right", "Panel position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=GV)
color upColor = input.color(#11998e, "Gap up / acceptance", group=GV)
color downColor = input.color(#df637c, "Gap down / rejection", group=GV)
color baseColor = input.color(#537fb9, "Previous close", group=GV)
color midColor = input.color(#c99b43, "Half fill", group=GV)
f_progress(float opening, float priorClose, float hi, float lo) =>
float g = opening - priorClose
g > 0 ? (opening - lo) / g : g < 0 ? (hi - opening) / -g : na
f_bucket(float normalized) =>
normalized < 0.5 ? 0 : normalized < 1.0 ? 1 : 2
// First qualifying sequence wins. The window includes the opening bar.
f_response(int side, float closing, float opening, float midpoint, float buffer, int oldA, int oldR, int age, int window, int needed) =>
int ac = side * (closing - opening) > buffer ? oldA + 1 : 0
int rc = side * (closing - midpoint) < -buffer ? oldR + 1 : 0
int result = ac >= needed ? 1 : rc >= needed ? -1 : age >= window ? 2 : 0
[ac, rc, result]
if barstate.isfirst
if not chart.is_standard or not timeframe.isintraday or timeframe.in_seconds() > 1800
runtime.error("Use standard intraday time-based candles of 30 minutes or less.")
if eh * 60 + em <= sh * 60 + sm
runtime.error("The closing time must follow the opening time on the same local day. Overnight sessions are not supported.")
if decisionWindow < confirms
runtime.error("The response window must be at least the consecutive-close requirement.")
if math.abs(f_progress(110, 100, 112, 105) - 0.5) > 0.000001 or math.abs(f_progress(90, 100, 95, 88) - 0.5) > 0.000001
runtime.error("Internal half-fill test failed.")
if f_progress(110, 100, 111, 99) < 1 or f_progress(90, 100, 101, 89) < 1
runtime.error("Internal full-fill test failed.")
[ta, tr, ts] = f_response(1, 111, 110, 105, 0.5, 2, 0, 3, 12, 3)
[ba, br, bs] = f_response(-1, 89, 90, 95, 0.5, 2, 0, 3, 12, 3)
[ra, rr, rs] = f_response(1, 104, 110, 105, 0.5, 0, 2, 3, 12, 3)
[ea, er, es] = f_response(1, 110.5, 110, 105, 0.5, 2, 0, 12, 12, 3)
if ts != 1 or bs != 1 or rs != -1 or es != 2 or ea != 0
runtime.error("Internal response boundary test failed.")
int localY = year(time, tz)
int localM = month(time, tz)
int localD = dayofmonth(time, tz)
int start = timestamp(tz, localY, localM, localD, sh, sm)
int finish = timestamp(tz, localY, localM, localD, eh, em)
bool inside = time >= start and time < finish
bool firstObserved = inside and (barstate.isfirst or start != start[1] or not inside[1])
var bool tracking = false
var bool coverage = false
var bool qualified = false
var int sessionStart = na
var int expectedEnd = na
var int lastCloseTime = na
var int barsSeen = 0
var float sessionOpen = na
var float sessionHigh = na
var float sessionLow = na
var float sessionATR = na
var float trSeed = 0
var int atrSessions = 0
var float reference = na
var float refATR = na
var float normalizedGap = na
var int side = 0
var int bucket = 0
var float progress = 0
var bool half = false
var bool full = false
var float halfMinutes = na
var float fullMinutes = na
var int acceptRun = 0
var int rejectRun = 0
var int response = 0
var bool priorValid = false
var float priorClose = na
var float priorATR = na
var int priorEnd = na
var int completed = 0
var int excluded = 0
var int interrupted = 0
var int anchors = 0
var string status = "Waiting for a fully observed session"
var buckets = array.new_int()
var directions = array.new_int()
var halves = array.new_bool()
var fills = array.new_bool()
var outcomes = array.new_int()
var fillTimes = array.new_float()
bool newGap = false
bool newHalf = false
bool newFull = false
bool accepted = false
bool rejected = false
if barstate.isconfirmed
if tracking and (not inside or sessionStart != start)
interrupted += 1
tracking := false
qualified := false
priorValid := false
status := "Incomplete session excluded"
if firstObserved
tracking := true
coverage := time == start and time_close <= finish
sessionStart := start
expectedEnd := finish
lastCloseTime := time
barsSeen := 0
sessionOpen := open
sessionHigh := high
sessionLow := low
bool ageOK = priorValid and start > priorEnd and start - priorEnd <= maxDays * 86400000
reference := ageOK ? priorClose : na
refATR := ageOK ? priorATR : na
float size = math.abs(sessionOpen - reference)
normalizedGap := not na(refATR) and refATR > 0 ? size / refATR : na
qualified := coverage and not na(normalizedGap) and size >= minTicks * syminfo.mintick and normalizedGap >= minGap
side := sessionOpen > reference ? 1 : -1
bucket := not na(normalizedGap) ? f_bucket(normalizedGap) : 0
progress := 0
half := false
full := false
halfMinutes := na
fullMinutes := na
acceptRun := 0
rejectRun := 0
response := 0
// Consume the previous reference: this session must complete to supply the next one.
priorValid := false
newGap := qualified
if qualified
anchors += 1
status := not coverage ? "Opening bar missing / misaligned" : na(reference) ? "No eligible previous-session close" : not qualified ? "Gap below minimum / ATR unavailable" : "Gap observed · response pending"
if tracking and inside and sessionStart == start
coverage := coverage and time == lastCloseTime and time_close <= expectedEnd and not na(open) and not na(close) and not na(high) and not na(low)
if not coverage
qualified := false
status := "Incomplete / misaligned session excluded"
sessionHigh := math.max(sessionHigh, high)
sessionLow := math.min(sessionLow, low)
barsSeen += 1
lastCloseTime := time_close
if qualified
float currentProgress = f_progress(sessionOpen, reference, high, low)
progress := math.min(1.0, math.max(progress, currentProgress))
if not half and progress >= 0.5
half := true
newHalf := true
halfMinutes := (time_close - sessionStart) / 60000.0
if not full and progress >= 1.0
full := true
newFull := true
fullMinutes := (time_close - sessionStart) / 60000.0
if response == 0
[ac, rc, result] = f_response(side, close, sessionOpen, (sessionOpen + reference) / 2, tolerance * refATR, acceptRun, rejectRun, barsSeen, decisionWindow, confirms)
acceptRun := ac
rejectRun := rc
response := result
accepted := result == 1
rejected := result == -1
status := response == 1 ? "Acceptance first · fill tracking continues" : response == -1 ? "Rejection first · fill tracking continues" : response == 2 ? "Response window expired · fill tracking" : "Gap observed · response pending"
if time_close == expectedEnd
tracking := false
if coverage
completed += 1
priorValid := true
float sessionTR = na(reference) ? sessionHigh - sessionLow : math.max(sessionHigh - sessionLow, math.max(math.abs(sessionHigh - reference), math.abs(sessionLow - reference)))
atrSessions += 1
trSeed += sessionTR
sessionATR := atrSessions < atrLen ? na : atrSessions == atrLen ? trSeed / atrLen : (sessionATR * (atrLen - 1) + sessionTR) / atrLen
priorClose := close
priorATR := sessionATR
priorEnd := time_close
if qualified
array.push(buckets, bucket)
array.push(directions, side)
array.push(halves, half)
array.push(fills, full)
array.push(outcomes, response == 0 ? 2 : response)
array.push(fillTimes, fullMinutes)
if array.size(buckets) > sampleSize
array.shift(buckets)
array.shift(directions)
array.shift(halves)
array.shift(fills)
array.shift(outcomes)
array.shift(fillTimes)
status := "Completed · included in sample"
else
excluded += 1
status := "Completed · gap excluded; next reference ready"
else
interrupted += 1
priorValid := false
status := "Incomplete session excluded"
bool visible = inside and qualified and sessionStart == start
bool fresh = visible and time == sessionStart
float o = visible and not fresh ? sessionOpen : na
float r = visible and not fresh ? reference : na
float m = visible and not fresh ? (sessionOpen + reference) / 2 : na
po = plot(o, "Session opening", color=side == 1 ? upColor : downColor, linewidth=2, style=plot.style_linebr, display=display.all - display.price_scale - display.status_line)
pr = plot(r, "Previous eligible session close", color=baseColor, linewidth=2, style=plot.style_linebr, display=display.all - display.price_scale - display.status_line)
plot(m, "Half-fill level", color=midColor, style=plot.style_linebr, display=display.all - display.price_scale - display.status_line)
fill(po, pr, color=bands ? color.new(side == 1 ? upColor : downColor, 94) : na, title="Opening gap")
plotshape(marks and newGap, "Gap opening", shape.diamond, location.abovebar, color=baseColor, size=size.tiny, text="G", textcolor=baseColor)
plotshape(marks and newHalf, "Half fill observed", shape.circle, location.belowbar, color=midColor, size=size.tiny, text="½", textcolor=midColor)
plotshape(marks and newFull, "Full fill observed", shape.circle, location.belowbar, color=baseColor, size=size.tiny, text="F", textcolor=baseColor)
plotshape(marks and accepted, "Acceptance first", shape.square, location.abovebar, color=upColor, size=size.tiny, text="A", textcolor=upColor)
plotshape(marks and rejected, "Rejection first", shape.square, location.abovebar, color=downColor, size=size.tiny, text="R", textcolor=downColor)
string pos = corner == "Top Left" ? position.top_left : corner == "Bottom Left" ? position.bottom_left : corner == "Bottom Right" ? position.bottom_right : position.top_right
var table panel = table.new(pos, 7, 12, bgcolor=color.new(chart.bg_color, 5))
f_cell(int c, int row, string txt, color ink) =>
table.cell(panel, c, row, txt, text_color=ink, text_size=size.small)
f_pct(int numerator, int denominator) =>
denominator > 0 ? str.tostring(100.0 * numerator / denominator, "#.0") + "%" : "—"
if barstate.islast and panelOn
table.merge_cells(panel, 0, 0, 6, 0)
table.merge_cells(panel, 0, 1, 6, 1)
table.merge_cells(panel, 0, 2, 6, 2)
table.merge_cells(panel, 0, 3, 6, 3)
table.merge_cells(panel, 0, 10, 6, 10)
table.merge_cells(panel, 0, 11, 6, 11)
f_cell(0, 0, "EV GAP ACCEPTANCE · SESSION OPENING GAPS", baseColor)
f_cell(0, 1, status, chart.fg_color)
string gapText = not na(normalizedGap) ? (side == 1 ? "UP " : "DOWN ") + str.tostring(normalizedGap, "#.00") + " ATR · max fill " + str.tostring(progress * 100, "#.0") + "%" : "Gap not available"
f_cell(0, 2, gapText, chart.fg_color)
f_cell(0, 3, str.tostring(sh, "00") + ":" + str.tostring(sm, "00") + "–" + str.tostring(eh, "00") + ":" + str.tostring(em, "00") + " " + tz + " · completed N=" + str.tostring(array.size(buckets)), chart.fg_color)
string[] heads = array.from("Size / side", "N", "Half", "Full", "A first", "R first", "Full min*")
for c = 0 to 6
f_cell(c, 4, array.get(heads, c), baseColor)
for group = 0 to 4
int n = 0
int nh = 0
int nf = 0
int naFirst = 0
int nrFirst = 0
float minutesSum = 0
if array.size(buckets) > 0
for i = 0 to array.size(buckets) - 1
bool include = group < 3 ? array.get(buckets, i) == group : array.get(directions, i) == (group == 3 ? 1 : -1)
if include
n += 1
nh += array.get(halves, i) ? 1 : 0
nf += array.get(fills, i) ? 1 : 0
naFirst += array.get(outcomes, i) == 1 ? 1 : 0
nrFirst += array.get(outcomes, i) == -1 ? 1 : 0
minutesSum += array.get(fills, i) ? array.get(fillTimes, i) : 0
if nf > nh or naFirst + nrFirst > n
runtime.error("Internal sample accounting failed.")
string labelName = group == 0 ? "<0.5 ATR" : group == 1 ? "0.5–1 ATR" : group == 2 ? "≥1 ATR" : group == 3 ? "All up" : "All down"
f_cell(0, group + 5, labelName, chart.fg_color)
f_cell(1, group + 5, str.tostring(n), chart.fg_color)
f_cell(2, group + 5, f_pct(nh, n), midColor)
f_cell(3, group + 5, f_pct(nf, n), baseColor)
f_cell(4, group + 5, f_pct(naFirst, n), upColor)
f_cell(5, group + 5, f_pct(nrFirst, n), downColor)
f_cell(6, group + 5, nf > 0 ? str.tostring(minutesSum / nf, "#.0") : "—", chart.fg_color)
f_cell(0, 10, "*Mean minutes for full fills only · A/R remainder = undecided; later fills can coexist", chart.fg_color)
f_cell(0, 11, "Complete " + str.tostring(completed) + " · small/no ref " + str.tostring(excluded) + " · incomplete " + str.tostring(interrupted) + " · no trade returns", chart.fg_color)
alertcondition(newGap, "Qualified session gap", "EV Gap Acceptance: qualified opening gap on {{ticker}} {{interval}}.")
alertcondition(newHalf, "Half fill", "EV Gap Acceptance: half-gap fill observed on {{ticker}} {{interval}}.")
alertcondition(newFull, "Full fill", "EV Gap Acceptance: full-gap fill observed on {{ticker}} {{interval}}.")
alertcondition(accepted, "Acceptance first", "EV Gap Acceptance: acceptance closing sequence confirmed on {{ticker}} {{interval}}.")
alertcondition(rejected, "Rejection first", "EV Gap Acceptance: rejection closing sequence confirmed on {{ticker}} {{interval}}.")