本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// ══════════════════════════════════════════════════════════════════════════════
// FPFVG [Ordinary Trader] v1.0.0
// See CHANGELOG.md for full version history.
// ══════════════════════════════════════════════════════════════════════════════
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("FPFVG [Ordinary Trader]", shorttitle = "FPFVG [Ordinary Trader]", overlay = true, max_boxes_count = 500, max_labels_count = 300, max_lines_count = 300)
// ═════════════════════════════════════════════════════════════════════════════
// 1. Inputs
// ═════════════════════════════════════════════════════════════════════════════
const string GD = "Detection"
const string GY = "Days"
const string GS = "Style"
const string GN = "Sessions"
bool onMid = input.bool(true, "Midnight", inline = "s0", group = GN, display = display.none)
string txtMid = input.string("Midnight FPFVG", "", inline = "s0", group = GN, tooltip = "The first presented FVG after the 00:00 New York open: candle 1 opens at 00:00 or later and the gap forms by 00:30. The text is written to the right of its box when Show text is ticked in the Style group.", display = display.none)
bool on930 = input.bool(true, "9:30", inline = "s1", group = GN, display = display.none)
string txt930 = input.string("FPFVG", "", inline = "s1", group = GN, tooltip = "The first presented FVG after the 9:30 New York open: candle 1 opens at 9:30 or later and the gap forms by 10:00. The history table is about this one.", display = display.none)
bool onPM = input.bool(true, "13:30", inline = "s2", group = GN, display = display.none)
string txtPM = input.string("PM FPFVG", "", inline = "s2", group = GN, tooltip = "The first presented FVG after the 13:30 New York open (the PM session): candle 1 opens at 13:30 or later and the gap forms by 14:00.\n\nEvery session uses the same rules and settings below, and every box runs to the 16:00 close. Each session has its own pair of alerts, e.g. Midnight FPFVG created and Midnight FPFVG filled.", display = display.none)
int minTicks = input.int(4, "Min gap size (ticks)", minval = 1, group = GD, tooltip = "Gaps smaller than this many ticks are skipped, and the next gap that's big enough counts as the first presented FVG instead. 4 ticks is 1 point on NQ and ES.", display = display.none)
string breakOn = input.string("Close", "Break on", options = ["Close", "Wick"], group = GD, tooltip = "When the gap counts as broken (filled through). Close: a 1-minute candle closes beyond its far side (below a bullish gap, above a bearish one). Wick: any trade beyond the far side. Used by Extend until, the filled alerts and the history table.", display = display.none)
string extMode = input.string("End of session", "Extend until", options = ["End of session", "Broken", "Inverted"], group = GD, tooltip = "End of session: the box runs to the 16:00 New York close (or the real close on a half day) in one colour.\nBroken: the box stops at the break; if it's never broken it stops at the close.\nInverted: at the break the box carries on to the close in the Inverted colour, as the gap may now work the other way (a broken bullish gap as resistance, a broken bearish one as support).\n\nThe box draws live while the gap's third candle is forming, so it can grow, shrink or disappear until that candle closes.\n\nAlerts: right-click the chart, Add alert, choose this indicator and pick a session's created alert (the gap is confirmed) or filled alert (the first break, as set by Break on, whichever option is chosen here). Set alerts on a 1-minute chart: on higher timeframes they wait for the chart's candle to close.", display = display.none)
bool onlyToday = input.bool(true, "Only show today", group = GY, tooltip = "Shows only the latest day's first presented FVGs and opening range gap. Before the first ticked session opens, and at the weekend, that's the previous day's. Untick to show the last few days instead (set below).", display = display.none)
int nDays = input.int(5, "How many days", minval = 1, maxval = 50, group = GY, tooltip = "Used when Only show today is unticked: how many days' first presented FVGs to show for each session, newest first. Days without one don't use up a slot. On 1-hour and higher charts TradingView keeps less 1-minute history, so older days may be missing.", display = display.none)
color cBull = input.color(#81B29ACC, "Bullish", inline = "c", group = GS, display = display.none)
color cBear = input.color(#E07A5FCC, "Bearish", inline = "c", group = GS, display = display.none)
color cInv = input.color(#376B894D, "Inverted", inline = "c", group = GS, tooltip = "Box colour for a bullish first presented FVG (a gap left by a move up), a bearish one (a gap left by a move down), and the part after the break when Extend until is set to Inverted. Use the opacity slider in each picker to make it lighter or stronger.", display = display.none)
bool showCE = input.bool(true, "Show 50% line", inline = "ce", group = GS, display = display.none)
color ceCol = input.color(#2D546B, "", inline = "ce", group = GS, tooltip = "A dotted line through the middle of the gap (its 50% level, also called consequent encroachment), a level price often reacts to. It runs the full length of the box.", display = display.none)
bool showTime = input.bool(true, "Show time", group = GS, tooltip = "Writes the New York time of the gap's third candle (the moment the gap appears) just to the right of the box, e.g. 09:34.", display = display.none)
bool showText = input.bool(true, "Show text", group = GS, tooltip = "Writes the session's text (set in the Sessions group) just to the right of the box, after the time if that's shown, e.g. 09:34 FPFVG. Untick both Show time and Show text for no label.", display = display.none)
color lblCol = input.color(#2D546B, "Label colour", inline = "l", group = GS, display = display.none)
string lblSize = input.string(size.tiny, "size", options = [size.tiny, size.small, size.normal, size.large, size.huge], inline = "l", group = GS, tooltip = "Colour and size of the label text.", display = display.none)
const string GO = "Opening range gap"
bool showOrg = input.bool(true, "Show opening range gap", inline = "o", group = GO, display = display.none)
color cOrg = input.color(#8D99AE4D, "", inline = "o", group = GO, tooltip = "A box between the previous session's 16:14 close (the last 1-minute candle of the cash session, or the last one before it on a half day) and today's 9:30 open, from 9:30 to the close. Pick its colour here.", display = display.none)
bool orgCE = input.bool(true, "Show 50% line", group = GO, tooltip = "A dotted line through the middle of the opening range gap, in the 50% line colour from the Style group.", display = display.none)
string orgTxt = input.string("ORG", "Label", group = GO, tooltip = "Written just to the right of the box, in the label colour and size from the Style group. Leave blank for no label.", display = display.none)
const string GT = "History table"
bool showTbl = input.bool(true, "Show table", group = GT, tooltip = "A table of how often the 9:30 first presented FVG held: no break (see Break on) from the moment it formed up to 10:00, 11:00 and the close, for bullish, bearish and all gaps. Days is how many sessions were counted: every day with a first presented FVG that TradingView has 1-minute data for, not just the ones on the chart. A day is only counted once its session has closed, so today joins the table tomorrow and every row uses the same days.", display = display.none)
string tblPos = input.string(position.bottom_right, "Position", options = [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], inline = "tp", group = GT, display = display.none)
string tblSize = input.string(size.tiny, "size", options = [size.tiny, size.small, size.normal, size.large], inline = "tp", group = GT, tooltip = "Where the table sits on the chart and the size of its text.", display = display.none)
color tblTxt = input.color(#2D546B, "Text", inline = "tc", group = GT, display = display.none)
color tblBg = input.color(#FFFFFFCC, "Background", inline = "tc", group = GT, tooltip = "Table text and background colour.", display = display.none)
// ═════════════════════════════════════════════════════════════════════════════
// 2. Constants and types
// ═════════════════════════════════════════════════════════════════════════════
const string TZ = "America/New_York"
const int OPEN = 570 // 09:30 in minutes after midnight, New York (also the opening range gap)
const int WIN = 29 // the third candle must open within 29 minutes of the session open
const int LASTE = 959 // 15:59: the last candle checked for a break
const int MIN1 = 60000
const int CP10 = 600 // 10:00
const int CP11 = 660 // 11:00
const int RTHC = 974 // 16:14: last candle of the cash session
type Day
int key
bool bull
float top
float bot
int sess // 0 = Midnight, 1 = 9:30, 2 = 13:30
int t1
int t3 // third candle's open time, shown on the label
int tEnd
bool broken = false
int tBreak = na // close time of the break candle
bool rec10 = false // checked at 10:00 / 11:00; the day is counted once the session closes
bool rec11 = false
bool held10 = false
bool held11 = false
bool recC = false
type Org
int key
float top
float bot
int t0
int tEnd
type State
int curKey = na // New York date of the latest 1m candle
bool started = false // the first ticked session has opened on curKey
array<bool> reached // per session: a candle at/after its open seen on curKey
array<bool> valid // per session: that first candle opened exactly at the open
array<bool> found // per session: today's FPFVG already found
array<Day> cur // per session: the latest FPFVG
array<bool> evCreated
array<bool> evBroken
int p1t = na // previous 1m candle (C2 when the current is C3)
float p1h = na
float p1l = na
int p2t = na // candle before that (C1)
float p2h = na
float p2l = na
int rthKey = na // date of the latest cash-session close
float rthClose = na // close of the last candle 09:30–16:14 on rthKey
Org org // the latest opening range gap
var State st = State.new(reached = array.new<bool>(3, false), valid = array.new<bool>(3, false), found = array.new<bool>(3, false), cur = array.new<Day>(3), evCreated = array.new<bool>(3, false), evBroken = array.new<bool>(3, false))
var array<int> OPENS = array.from(0, 570, 810) // 00:00, 09:30, 13:30
var array<Day> days = array.new<Day>()
var array<Org> orgs = array.new<Org>()
// History table counts, index (bull ? 0 : 3) + check (0 = 10:00, 1 = 11:00, 2 = close)
var array<int> sTot = array.new<int>(6, 0)
var array<int> sHeld = array.new<int>(6, 0)
bool extBroken = extMode == "Broken"
bool extInv = extMode == "Inverted"
bool wickBreak = breakOn == "Wick"
array<bool> sessOn = array.from(onMid, on930, onPM)
array<string> sessTxt = array.from(txtMid, txt930, txtPM)
int firstOpen = onMid ? 0 : on930 ? 570 : 810
bool supported = timeframe.isintraday and not timeframe.isseconds and not timeframe.isticks
// ═════════════════════════════════════════════════════════════════════════════
// 3. Helpers
// ═════════════════════════════════════════════════════════════════════════════
nyKey(int t) => year(t, TZ) * 10000 + month(t, TZ) * 100 + dayofmonth(t, TZ)
nyMin(int t) => hour(t, TZ) * 60 + minute(t, TZ)
// Counts a finished day in the history table, at all three check times together.
record(Day d) =>
int b = d.bull ? 0 : 3
array<bool> held = array.from(d.held10, d.held11, not d.broken)
for cp = 0 to 2
sTot.set(b + cp, sTot.get(b + cp) + 1)
if held.get(cp)
sHeld.set(b + cp, sHeld.get(b + cp) + 1)
// Feeds one 1-minute candle into the state machine. On the live bar the forming
// candle is fed as if closed; TradingView rewinds this state on every update.
step1m(State s, int t, float o, float h, float l, float c) =>
int key = nyKey(t)
int m = nyMin(t)
// History table (9:30 session): note whether its FPFVG held at 10:00 and 11:00 (before this
// candle can break it), and count the day only once the session has closed, so every row
// uses the same finished days
Day q = s.cur.get(1)
if not na(q) and not q.recC
bool same = q.key == key
if same and m >= CP10 and not q.rec10
q.rec10 := true
q.held10 := not q.broken
if same and m >= CP11 and not q.rec11
q.rec11 := true
q.held11 := not q.broken
if not same or m > LASTE
q.recC := true
if q.rec10 and q.rec11 // skip a day with missing 1m data around the check times
record(q)
if na(s.curKey) or key != s.curKey
s.curKey := key
s.started := false
for i = 0 to 2
s.reached.set(i, false)
s.valid.set(i, false)
s.found.set(i, false)
if m >= firstOpen and m <= LASTE
s.started := true
// Opening range gap: previous session's cash close to today's 09:30 open
if m == OPEN and not na(s.rthClose) and s.rthKey != key and o != s.rthClose
Org g = Org.new(key, math.max(o, s.rthClose), math.min(o, s.rthClose), t, t + MIN1)
orgs.push(g)
s.org := g
else if not na(s.org) and s.org.key == key and m > OPEN and m <= LASTE
s.org.tEnd := t + MIN1
if m >= OPEN and m <= RTHC
s.rthKey := key
s.rthClose := c
for i = 0 to 2
if sessOn.get(i)
int op = OPENS.get(i)
if not s.reached.get(i) and m >= op and m <= LASTE
s.reached.set(i, true)
s.valid.set(i, m == op) // 1m history must start by the open, or a later gap could pose as the first
bool c1ok = not na(s.p2t) and nyKey(s.p2t) == key and nyMin(s.p2t) >= op
Day d = s.cur.get(i)
if s.valid.get(i) and not s.found.get(i) and c1ok and m <= op + WIN
bool bull = l > s.p2h and math.round((l - s.p2h) / syminfo.mintick) >= minTicks
bool bear = h < s.p2l and math.round((s.p2l - h) / syminfo.mintick) >= minTicks
if bull or bear
Day nd = Day.new(key, bull, bull ? l : s.p2l, bull ? s.p2h : h, i, s.p2t, t, t + MIN1)
days.push(nd)
s.cur.set(i, nd)
s.found.set(i, true)
s.evCreated.set(i, true)
else if not na(d) and d.key == key and m <= LASTE
if not (d.broken and extBroken)
d.tEnd := t + MIN1
bool brk = d.bull ? (wickBreak ? l : c) < d.bot : (wickBreak ? h : c) > d.top
if not d.broken and brk
d.broken := true
d.tBreak := t + MIN1
s.evBroken.set(i, true)
s.p2t := s.p1t
s.p2h := s.p1h
s.p2l := s.p1l
s.p1t := t
s.p1h := h
s.p1l := l
// ═════════════════════════════════════════════════════════════════════════════
// 4. Feed 1-minute candles (real prices, whatever the chart type)
// ═════════════════════════════════════════════════════════════════════════════
for i = 0 to 2
st.evCreated.set(i, false)
st.evBroken.set(i, false)
if supported
[aT, aO, aH, aL, aC] = request.security_lower_tf(ticker.standard(syminfo.tickerid), "1", [time, open, high, low, close])
if aT.size() > 0
for i = 0 to aT.size() - 1
step1m(st, aT.get(i), aO.get(i), aH.get(i), aL.get(i), aC.get(i))
int keep = onlyToday ? 1 : nDays
// Keep the newest `keep` days per session
array<int> seen = array.new<int>(3, 0)
int j = days.size() - 1
while j >= 0
int si = days.get(j).sess
if seen.get(si) >= keep
days.remove(j)
else
seen.set(si, seen.get(si) + 1)
j -= 1
while orgs.size() > keep
orgs.shift()
// ═════════════════════════════════════════════════════════════════════════════
// 5. Drawing: rebuilt from the stored days on the last bar, so live rewinds never leave stray boxes
// ═════════════════════════════════════════════════════════════════════════════
if barstate.islast
array<box> oldB = box.all.copy()
for b in oldB
b.delete()
array<label> oldL = label.all.copy()
for lb in oldL
lb.delete()
array<line> oldN = line.all.copy()
for ln in oldN
ln.delete()
// With Only show today: once the first ticked session has opened today, older days are hidden.
bool hideOld = onlyToday and st.started
if showOrg
for g in orgs
if not (hideOld and g.key != st.curKey)
box.new(g.t0, g.top, g.tEnd, g.bot, xloc = xloc.bar_time, border_color = na, bgcolor = cOrg)
float gm = (g.top + g.bot) / 2
if orgCE
line.new(g.t0, gm, g.tEnd, gm, xloc = xloc.bar_time, color = ceCol, style = line.style_dotted, width = 1)
if str.trim(orgTxt) != ""
label.new(g.tEnd, gm, orgTxt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = lblCol, size = lblSize)
for d in days
if sessOn.get(d.sess) and not (hideOld and d.key != st.curKey)
color col = d.bull ? cBull : cBear
if extInv and d.broken
box.new(d.t1, d.top, d.tBreak, d.bot, xloc = xloc.bar_time, border_color = na, bgcolor = col)
if d.tEnd > d.tBreak
box.new(d.tBreak, d.top, d.tEnd, d.bot, xloc = xloc.bar_time, border_color = na, bgcolor = cInv)
else
box.new(d.t1, d.top, d.tEnd, d.bot, xloc = xloc.bar_time, border_color = na, bgcolor = col)
if showCE
float mid = (d.top + d.bot) / 2
line.new(d.t1, mid, d.tEnd, mid, xloc = xloc.bar_time, color = ceCol, style = line.style_dotted, width = 1)
string txt = str.trim((showTime ? str.format_time(d.t3, "HH:mm", TZ) + " " : "") + (showText ? sessTxt.get(d.sess) : ""))
if txt != ""
label.new(d.tEnd, (d.top + d.bot) / 2, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = lblCol, size = lblSize)
if showTbl and supported
var table tb = table.new(tblPos, 4, 5, bgcolor = tblBg)
array<string> heads = array.from("9:30 FPFVG held", "Bull", "Bear", "All")
array<string> rows = array.from("Held to 10:00", "Held to 11:00", "Held to close")
for c = 0 to 3
tb.cell(c, 0, heads.get(c), text_color = tblTxt, text_size = tblSize, text_halign = c == 0 ? text.align_left : text.align_right)
tb.cell(0, 1, "Days", text_color = tblTxt, text_size = tblSize, text_halign = text.align_left)
for c = 1 to 3
int n = c == 1 ? sTot.get(0) : c == 2 ? sTot.get(3) : sTot.get(0) + sTot.get(3)
tb.cell(c, 1, str.tostring(n), text_color = tblTxt, text_size = tblSize, text_halign = text.align_right)
for r = 0 to 2
tb.cell(0, r + 2, rows.get(r), text_color = tblTxt, text_size = tblSize, text_halign = text.align_left)
for c = 1 to 3
int tot = c == 1 ? sTot.get(r) : c == 2 ? sTot.get(3 + r) : sTot.get(r) + sTot.get(3 + r)
int held = c == 1 ? sHeld.get(r) : c == 2 ? sHeld.get(3 + r) : sHeld.get(r) + sHeld.get(3 + r)
string v = tot == 0 ? "–" : str.tostring(math.round(100.0 * held / tot)) + "%"
tb.cell(c, r + 2, v, text_color = tblTxt, text_size = tblSize, text_halign = text.align_right)
if not supported
var table note = table.new(position.bottom_right, 1, 1)
note.cell(0, 0, "FPFVG works on minute and hour charts.", text_color = lblCol, text_size = size.small)
// ═════════════════════════════════════════════════════════════════════════════
// 6. Alerts: fire only on closed chart bars, so a live candle that later pulls back can't trigger them
// ═════════════════════════════════════════════════════════════════════════════
liveTop(int i) =>
Day d = st.cur.get(i)
not na(d) and d.key == st.curKey ? d.top : na
liveBot(int i) =>
Day d = st.cur.get(i)
not na(d) and d.key == st.curKey ? d.bot : na
plot(liveTop(0), "Midnight top", display = display.none, editable = false)
plot(liveBot(0), "Midnight bottom", display = display.none, editable = false)
plot(liveTop(1), "9:30 top", display = display.none, editable = false)
plot(liveBot(1), "9:30 bottom", display = display.none, editable = false)
plot(liveTop(2), "13:30 top", display = display.none, editable = false)
plot(liveBot(2), "13:30 bottom", display = display.none, editable = false)
bool conf = barstate.isconfirmed
alertcondition(st.evCreated.get(0) and conf, "Midnight FPFVG created", 'Midnight FPFVG created on {{ticker}}: {{plot("Midnight bottom")}} – {{plot("Midnight top")}}')
alertcondition(st.evBroken.get(0) and conf, "Midnight FPFVG filled", 'Midnight FPFVG filled on {{ticker}}: {{plot("Midnight bottom")}} – {{plot("Midnight top")}}')
alertcondition(st.evCreated.get(1) and conf, "9:30 FPFVG created", '9:30 FPFVG created on {{ticker}}: {{plot("9:30 bottom")}} – {{plot("9:30 top")}}')
alertcondition(st.evBroken.get(1) and conf, "9:30 FPFVG filled", '9:30 FPFVG filled on {{ticker}}: {{plot("9:30 bottom")}} – {{plot("9:30 top")}}')
alertcondition(st.evCreated.get(2) and conf, "13:30 FPFVG created", '13:30 FPFVG created on {{ticker}}: {{plot("13:30 bottom")}} – {{plot("13:30 top")}}')
alertcondition(st.evBroken.get(2) and conf, "13:30 FPFVG filled", '13:30 FPFVG filled on {{ticker}}: {{plot("13:30 bottom")}} – {{plot("13:30 top")}}')