本页源码来自 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/
// © Nambou_Signals
//@version=6
indicator("Nambou Gap Fill Odds", "Gap Fill Odds", overlay = true, max_labels_count = 500, max_boxes_count = 200, max_lines_count = 100, max_bars_back = 1000)
gO = "Odds"
sessMode = input.string("US regular hours", "Session", options = ["US regular hours", "Symbol's daily session"], group = gO, tooltip = "US regular hours: the gap is the 09:30 New York open against the previous 16:00 close, which is what NQ, ES and US stock traders mean by the gap. Use a 30-minute or lower chart on 24-hour futures so the open is exact. Symbol's daily session: the gap is each daily session's open against the previous session's close, for markets without a US cash session.")
callAt = input.int(80, "Call it when the odds reach", minval = 50, maxval = 99, group = gO, tooltip = "A call is the first bar of the day whose fill odds reach this level. Calls are marked on the chart, counted under the table and can send an alert.")
minDays = input.int(20, "Fewest past days behind a number", minval = 5, maxval = 200, group = gO, tooltip = "When fewer past days were in the same situation, the odds fall back to a wider one: first leaving out the gap size, then using the gap size and the time alone.")
adrLen = input.int(14, "Sessions in the average range", minval = 5, maxval = 100, group = gO, tooltip = "Gap sizes and distances are measured in average session ranges.")
gD = "Display"
pastDays = input.int(20, "Past gaps drawn", minval = 0, maxval = 60, group = gD, tooltip = "Each past gap is a box from the previous close to the open across its session: coloured if it filled the same session, grey if not, with its size and the odds it had at the open. A tick marks the bar that filled it and how long it took.")
showMarks = input.bool(true, "Mark the calls", group = gD, tooltip = "The odds at the first bar of the day that reached the call level. When the session is over, a right call takes the fill colour and a wrong one turns grey.")
showTable = input.bool(true, "Show the odds table", group = gD)
tablePosIn = input.string("Auto", "Table position", options = ["Auto", "Top center", "Bottom center", "Top right", "Bottom right", "Bottom left", "Top left"], group = gD, tooltip = "Auto looks at the left, middle and right of the visible chart and puts the table where the candles leave the most room. It never picks the bottom left, where TradingView puts its logo.")
txtSizeIn = input.string("Normal", "Chart text size", options = ["Tiny", "Small", "Normal", "Large"], group = gD, tooltip = "Today's fill odds are drawn one size larger.")
tblSizeIn = input.string("Normal", "Table text size", options = ["Tiny", "Small", "Normal", "Large"], group = gD)
extBars = input.int(12, "Today's line runs this many bars past the last bar", minval = 2, maxval = 100, group = gD)
cFill = input.color(#00E5A0, "Filled", group = gD)
cOpen = input.color(#FFB74D, "Open gap", group = gD)
cMiss = input.color(#787B86, "Not filled", group = gD)
cTxt = input.color(#D1D4DC, "Neutral text", group = gD)
gA = "Alerts"
aCall = input.bool(true, "Alert when a fill is called", group = gA)
aFill = input.bool(true, "Alert when the gap fills", group = gA)
txtSize = txtSizeIn == "Tiny" ? size.tiny : txtSizeIn == "Small" ? size.small : txtSizeIn == "Large" ? size.large : size.normal
bigSize = txtSizeIn == "Tiny" ? size.small : txtSizeIn == "Small" ? size.normal : txtSizeIn == "Large" ? size.huge : size.large
tblSize = tblSizeIn == "Tiny" ? size.tiny : tblSizeIn == "Small" ? size.small : tblSizeIn == "Large" ? size.large : size.normal
type Cell
int n = 0
int hits = 0
int last = -1
type Rec
int k
int db
float p
float q
type Day
int id
float pc
float op
int sgn
float gapAdr
int gb
int t0
int b0
float hi
float lo
bool filled = false
int fillBar
float pOpen
bool called = false
int callBar
float callP
label mk
box bx
label tg
label fm
float fillMins
array<Rec> recs
type Times
array<float> m
var cells = array.new<Cell>()
var times = array.new<Times>()
if barstate.isfirst
for i = 0 to 844
cells.push(Cell.new())
for i = 0 to 4
times.push(Times.new(array.new_float()))
// bars: model right, gap+time right, scored; calls: made, right
var score = array.new_int(5, 0)
var ranges = array.new_float()
var pastBoxes = array.new_box()
var pastTags = array.new_label()
var Day cur = na
var float lastIn = na
var float sHi = na
var float sLo = na
var int dayN = 0
gIdx(int gb) => gb
gkIdx(int gb, int k) => 5 + gb * 24 + k
gkdIdx(int gb, int k, int d) => 125 + (gb * 24 + k) * 5 + d
kdIdx(int k, int d) => 725 + k * 5 + d
tagText(Day d, string tail) =>
"gap " + str.tostring(math.abs(d.gapAdr), "#.##") + (na(d.pOpen) ? "" : " · FILL " + str.tostring(math.round(d.pOpen)) + "%") + tail
minsText(float m) => m < 120 ? str.tostring(math.round(m)) + " min" : str.tostring(m / 60.0, "#.#") + " h"
sizeBand(float x) => x < 0.1 ? 0 : x < 0.25 ? 1 : x < 0.5 ? 2 : x < 1.0 ? 3 : 4
rate(int i) => cells.get(i).n >= minDays ? cells.get(i).hits * 100.0 / cells.get(i).n : na
firstOf(int a, int b, int c) =>
float p = rate(a)
if na(p)
p := rate(b)
if na(p) and c >= 0
p := rate(c)
p
learn(int i, bool hit, int id) =>
Cell c = cells.get(i)
if c.last != id
c.last := id
c.n += 1
c.hits += hit ? 1 : 0
bool usHours = sessMode == "US regular hours"
bool inSess = usHours ? not na(time(timeframe.period, "0930-1600", "America/New_York")) : true
bool newSess = usHours ? inSess and (not inSess[1] or dayofmonth(time, "America/New_York") != dayofmonth(time[1], "America/New_York")) : timeframe.change("D")
bool sessOver = usHours ? (inSess[1] and (not inSess or newSess)) : newSess
// close the session that just ended
if sessOver and not na(cur)
Day d = cur
for r in d.recs
if not na(r.p) and not na(r.q)
score.set(0, score.get(0) + ((r.p >= 50) == d.filled ? 1 : 0))
score.set(1, score.get(1) + ((r.q >= 50) == d.filled ? 1 : 0))
score.set(2, score.get(2) + 1)
learn(gkIdx(d.gb, r.k), d.filled, d.id)
learn(gkdIdx(d.gb, r.k, r.db), d.filled, d.id)
learn(kdIdx(r.k, r.db), d.filled, d.id)
learn(gIdx(d.gb), d.filled, d.id)
if d.filled
array<float> tm = times.get(d.gb).m
tm.push(d.fillMins)
if tm.size() > 300
tm.shift()
if d.called
score.set(3, score.get(3) + 1)
score.set(4, score.get(4) + (d.filled ? 1 : 0))
if not na(d.mk)
label.set_textcolor(d.mk, d.filled ? cFill : cMiss)
if not na(d.bx)
box.set_right(d.bx, bar_index - 1)
box.set_bgcolor(d.bx, color.new(d.filled ? cFill : cMiss, 80))
box.set_border_color(d.bx, color.new(d.filled ? cFill : cMiss, 35))
label.set_textcolor(d.tg, d.filled ? cFill : color.new(cTxt, 25))
label.set_text(d.tg, tagText(d, d.filled ? " ✓ filled in " + minsText(d.fillMins) : " ✗ not filled"))
pastBoxes.push(d.bx)
pastTags.push(d.tg)
pastTags.push(d.fm)
while pastBoxes.size() > pastDays
box.delete(pastBoxes.shift())
label.delete(pastTags.shift())
label.delete(pastTags.shift())
cur := na
// the range of the session that just ended feeds the average range
if sessOver and not na(sHi)
ranges.push(sHi - sLo)
if ranges.size() > adrLen
ranges.shift()
sHi := na
sLo := na
float adr = ranges.size() == adrLen ? ranges.avg() : na
// open a new session with its gap
if newSess and not na(lastIn) and not na(adr) and timeframe.isintraday and open != lastIn
dayN += 1
int sgn = open > lastIn ? 1 : -1
float g = math.abs(open - lastIn) / adr
int gb = sizeBand(g)
cur := Day.new(dayN, lastIn, open, sgn, g * sgn, gb, time, bar_index, high, low, recs = array.new<Rec>())
cur.pOpen := rate(gIdx(gb))
if pastDays > 0
cur.bx := box.new(math.max(bar_index, bar_index - 500), math.max(open, lastIn), bar_index + extBars, math.min(open, lastIn), border_color = color.new(cOpen, 40), bgcolor = color.new(cOpen, 85))
cur.tg := label.new(bar_index, lastIn, "", style = sgn > 0 ? label.style_label_upper_left : label.style_label_lower_left, color = color(na), textcolor = cOpen, size = txtSize)
if inSess
sHi := na(sHi) ? high : math.max(sHi, high)
sLo := na(sLo) ? low : math.min(sLo, low)
float pNow = na
float qNow = na
int kNow = na
if inSess and not na(cur)
Day d = cur
d.hi := math.max(d.hi, high)
d.lo := math.min(d.lo, low)
if not d.filled and (d.sgn > 0 ? low <= d.pc : high >= d.pc)
d.filled := true
d.fillBar := bar_index
d.fillMins := (time_close - d.t0) / 60000.0
if pastDays > 0
d.fm := label.new(bar_index, d.pc, "✓", style = label.style_label_center, color = color(na), textcolor = cFill, size = txtSize, tooltip = "Filled after " + minsText(d.fillMins))
if aFill and barstate.isconfirmed
alert("Gap Fill Odds: " + syminfo.ticker + " filled the gap at " + str.tostring(d.pc, format.mintick), alert.freq_once_per_bar_close)
if not d.filled
kNow := math.min(23, int(math.floor((time_close - d.t0) / 3600000.0)))
int db = sizeBand(math.max((close - d.pc) * d.sgn / adr, 0.0))
pNow := firstOf(gkdIdx(d.gb, kNow, db), kdIdx(kNow, db), gkIdx(d.gb, kNow))
qNow := firstOf(gkIdx(d.gb, kNow), gIdx(d.gb), -1)
d.recs.push(Rec.new(kNow, db, pNow, qNow))
if barstate.isconfirmed and not d.called and pNow >= callAt
d.called := true
d.callBar := bar_index
d.callP := pNow
if showMarks
d.mk := label.new(bar_index, d.sgn > 0 ? high : low, d.sgn > 0 ? str.tostring(math.round(pNow)) + "%\n▼" : "▲\n" + str.tostring(math.round(pNow)) + "%", style = d.sgn > 0 ? label.style_label_down : label.style_label_up, color = color(na), textcolor = color.new(cTxt, 30), size = txtSize, tooltip = "Fill called at " + str.tostring(math.round(pNow)) + "%")
if aCall
alert("Gap Fill Odds: " + syminfo.ticker + " fill called at " + str.tostring(math.round(pNow)) + "%, previous close " + str.tostring(d.pc, format.mintick), alert.freq_once_per_bar_close)
if inSess
lastIn := close
meter(float pct) =>
int n = int(math.round(math.max(0.0, math.min(100.0, pct)) / 10.0))
string s = ""
for k = 1 to 10
s += k <= n ? "▰" : "▱"
s
pctText(float v) => na(v) ? "—" : str.tostring(math.round(v)) + "%"
tPos = switch tablePosIn
"Top center" => position.top_center
"Bottom center" => position.bottom_center
"Top right" => position.top_right
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
"Top left" => position.top_left
=> position.top_center
tblBg = color.new(#131722, 8)
var table odds = table.new(tPos, 3, 16, border_width = 0, frame_width = 0)
tcell(int c, int r, string v, color tc) =>
table.cell(odds, c, r, v, text_color = tc, text_halign = text.align_left, text_size = tblSize, bgcolor = tblBg)
note(int r, string v, color tc) =>
table.cell(odds, 0, r, v, text_color = tc, text_halign = text.align_left, text_size = size.small, bgcolor = tblBg)
table.merge_cells(odds, 0, r, 2, r)
share(int right, int n) => n < 50 ? "—" : str.tostring(math.round(right * 100.0 / n)) + "%"
var line pcLine = na
var label pcTag = na
var line medLine = na
var label medTag = na
var line preLine = na
var label preTag = na
// The session is over when the last bar is old (a stock chart after the close).
bool closedNow = barstate.islast and timenow - time_close > 20 * 60 * 1000
if barstate.islast
line.delete(pcLine)
label.delete(pcTag)
line.delete(medLine)
label.delete(medTag)
line.delete(preLine)
label.delete(preTag)
if usHours and na(cur) and not inSess and not na(lastIn) and not na(adr) and timeframe.isintraday and close != lastIn
float g = math.abs(close - lastIn) / adr
float p = rate(gIdx(sizeBand(g)))
preLine := line.new(bar_index - 20, lastIn, bar_index + 3, lastIn, color = color.new(cOpen, 30), width = 2, style = line.style_dashed)
preTag := label.new(bar_index + 3, lastIn, "PRE-OPEN FILL " + pctText(p) + "\ngap " + (close > lastIn ? "up " : "down ") + str.tostring(g, "#.##") + " if it opened here", style = label.style_label_left, color = color.new(cOpen, 80), textcolor = cOpen, size = txtSize)
if not na(cur)
Day d = cur
color c = d.filled ? cFill : closedNow ? cMiss : cOpen
if not na(d.bx)
box.set_right(d.bx, closedNow ? bar_index : bar_index + extBars)
box.set_bgcolor(d.bx, color.new(c, 80))
box.set_border_color(d.bx, color.new(c, 35))
label.set_text(d.tg, tagText(d, d.filled ? " at the open ✓ filled in " + minsText(d.fillMins) : " at the open"))
label.set_textcolor(d.tg, c)
array<float> tm = times.get(d.gb).m
if not d.filled and not closedNow and tm.size() >= 5
float med = tm.percentile_nearest_rank(50)
int tx = d.t0 + int(med * 60000)
float top = math.max(d.pc, d.op)
float bot = math.min(d.pc, d.op)
medLine := line.new(tx, top, tx, bot, xloc = xloc.bar_time, color = color.new(cOpen, 20), style = line.style_dotted, width = 2)
medTag := label.new(tx, d.sgn > 0 ? bot : top, "half of the filled gaps\nthis size filled by here", xloc = xloc.bar_time, style = d.sgn > 0 ? label.style_label_up : label.style_label_down, color = color(na), textcolor = color.new(cOpen, 15), size = size.small)
string txt = d.filled ? "GAP FILLED ✓" : closedNow ? "NOT FILLED ✗" : "FILL " + pctText(pNow)
pcLine := line.new(math.max(d.b0, bar_index - 500), d.pc, bar_index + extBars, d.pc, color = c, width = 2, style = line.style_dashed)
pcTag := label.new(bar_index + extBars, d.pc, txt, style = label.style_label_left, color = color.new(c, 80), textcolor = c, size = bigSize)
float vHi = high
float vLo = low
int vj = 0
while vj < 999 and time[vj] >= chart.left_visible_bar_time
vHi := math.max(vHi, high[vj])
vLo := math.min(vLo, low[vj])
vj += 1
table.clear(odds, 0, 0, 2, 15)
bool atTop = tablePosIn == "Top center" or tablePosIn == "Top left"
if tablePosIn == "Auto"
float span = math.max(vHi - vLo, syminfo.mintick)
float best = -1.0
string spot = position.top_center
for part = 0 to 2
int a = int(vj * part / 3.0)
int b = math.max(a, math.min(999, int(vj * (part + 1) / 3.0) - 1))
float pHi = high[a]
float pLo = low[a]
for j = a to b
pHi := math.max(pHi, high[j])
pLo := math.min(pLo, low[j])
float bonus = part == 1 ? 0.03 : 0.0
float upRoom = (vHi - pHi) / span + bonus
float dnRoom = (pLo - vLo) / span + bonus
if upRoom > best
best := upRoom
spot := part == 0 ? position.top_right : part == 1 ? position.top_center : position.top_left
if dnRoom > best and part < 2
best := dnRoom
spot := part == 0 ? position.bottom_right : part == 1 ? position.bottom_center : position.bottom_left
atTop := spot == position.top_center or spot == position.top_left
table.set_position(odds, spot)
if showTable
int off = atTop ? 2 : 0
if off > 0
for k = 0 to off - 1
table.cell(odds, 0, k, " ", text_size = tblSize)
table.merge_cells(odds, 0, k, 2, k)
table.cell(odds, 0, off, "◆ NAMBOU GAP FILL ODDS", text_color = #FFFFFF, text_halign = text.align_left, text_size = tblSize, bgcolor = tblBg)
table.merge_cells(odds, 0, off, 2, off)
if not timeframe.isintraday
note(off + 1, "Open an intraday chart (1 minute to 1 hour)", cTxt)
else if na(adr)
note(off + 1, "Needs " + str.tostring(adrLen + 1) + " full sessions of history first", cTxt)
else
int r = off + 1
if na(cur) and usHours and not inSess and not na(lastIn) and close != lastIn
float g = math.abs(close - lastIn) / adr
tcell(0, r, "Pre-open: gap " + (close > lastIn ? "up " : "down ") + str.tostring(g, "#.##") + " of a range", cOpen)
tcell(1, r, meter(nz(rate(gIdx(sizeBand(g))))) + " " + pctText(rate(gIdx(sizeBand(g)))), #FFFFFF)
tcell(2, r, "if it opened now", color.new(cTxt, 40))
else if na(cur)
note(r, "No gap this session", cTxt)
else
Day d = cur
string side = d.sgn > 0 ? "Gap up " : "Gap down "
tcell(0, r, side + str.tostring(math.abs(d.gapAdr), "#.##") + " of a range", d.filled ? cFill : closedNow ? cMiss : cOpen)
tcell(1, r, d.filled ? "filled ✓" : closedNow ? "not filled ✗" : meter(nz(pNow)) + " " + pctText(pNow), #FFFFFF)
tcell(2, r, d.filled or closedNow ? "" : "fill odds", color.new(cTxt, 40))
r += 1
tcell(0, r, "Right on past bars", color.new(cTxt, 40))
tcell(1, r, share(score.get(0), score.get(2)), #FFFFFF)
tcell(2, r, "gap + time alone " + share(score.get(1), score.get(2)), color.new(cTxt, 15))
r += 1
tcell(0, r, "Gap size (ranges)", color.new(cTxt, 40))
tcell(1, r, "filled same session", color.new(cTxt, 40))
tcell(2, r, "days", color.new(cTxt, 40))
array<string> names = array.from("under 0.1", "0.1 to 0.25", "0.25 to 0.5", "0.5 to 1", "over 1")
for gb = 0 to 4
Cell c = cells.get(gIdx(gb))
r += 1
bool now = not na(cur) and cur.gb == gb
tcell(0, r, (now ? "▸ " : " ") + names.get(gb), now ? cOpen : cTxt)
tcell(1, r, c.n < 5 ? "too few yet" : meter(c.hits * 100.0 / c.n) + " " + str.tostring(math.round(c.hits * 100.0 / c.n)) + "%", c.n < 5 ? color.new(cTxt, 40) : #FFFFFF)
tcell(2, r, str.tostring(c.n), color.new(cTxt, 15))
r += 1
int nc = score.get(3)
note(r, "▼▲ fill calls at " + str.tostring(callAt) + "%+: " + (nc < 5 ? "too few yet" : str.tostring(math.round(score.get(4) * 100.0 / nc)) + "% right of " + str.tostring(nc)), color.new(cTxt, 35))
r += 1
note(r, (usHours ? "US hours 09:30-16:00 New York" : "the symbol's daily session") + " · each day is scored only on the days before it", color.new(cTxt, 35))