Remaining FVG [Quanty]

QuantyFin · study · 239 行 · 点赞 20 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// Remaining FVG [Quanty] - v1.3
// v1.3: "Timeframe" setting. Gaps can come from a higher timeframe; the chart's own candles fill them.
//       Only closed higher-timeframe candles are read, so nothing is redrawn. Empty = the chart's timeframe
//       (the same result as v1.2); a timeframe below the chart's is not used and a small note says so.
// v1.2: one blue (#3B7BE0) for both directions by default; the direction is read from where the box sits.
//       The two colours stay separate settings. Open part 62 -> 50 transparency (near -> far edge).
// v1.1: two tones in one colour per gap (the part price already traded into is light, the part still open is
//       dark, darkest at the far edge); filled gaps hidden by default.
//
// Draws each fair value gap as one box over its original range. Inside it, the part that candles have
// already traded into is light and the part still open is dark, so you see at a glance how much of the
// gap remains. When a wick reaches the far edge the gap is filled and the box is removed.
//
// Rules (closed candles only):
//   - Three consecutive candles A, B, C of the chosen timeframe with no missing time between them. If the
//     low of C is above the high of A, the gap is [high A, low C]; if the high of C is below the low of A,
//     the gap is [high C, low A]. It must be at least "Minimum gap" x ATR(14) of B wide (Wilder ATR, on the
//     chosen timeframe) and wider than zero. The box starts at C.
//   - On a higher timeframe the gap is found on the first chart candle after C has closed: the values of
//     A, B and C are those of closed candles, the same on history and in real time.
//   - On later chart candles the open part keeps its far edge and its near edge moves to the deepest wick
//     into the gap. It never grows back. The right edge is 6 candles after the last closed candle.
//   - A wick to the far edge fills the gap (no close needed). With "Show filled gaps" on, a filled gap
//     stays as a dashed, faded frame of its original range from C to the filling candle: the last 12,
//     fewer when "Live boxes" is above 6, so that no more than 18 gaps show.
//   - A new gap that overlaps the open part of a live gap formed in the same direction is skipped;
//     touching edges is not an overlap. When a new box passes the live limit, the oldest live box is
//     removed. A box still live 300 candles of the chosen timeframe after it formed is removed; that is
//     not a fill.
// Not investment advice.
indicator("Remaining FVG [Quanty]", shorttitle="Remaining FVG", overlay=true, max_boxes_count=150, max_labels_count=30)
 
// ---------------------------------------------------------------------------
// Inputs
// ---------------------------------------------------------------------------
string tfIn      = input.timeframe("", "Timeframe",
     tooltip="Gaps from this timeframe, filled by the chart's own candles. Empty = the chart's timeframe. A timeframe below the chart's is not used.")
float kMin       = input.float(0.15, "Minimum gap (x ATR 14)", minval=0.0, maxval=2.0, step=0.05,
     tooltip="A gap narrower than this share of the ATR (14) of the middle candle is not drawn.")
int   maxLive    = input.int(6, "Live boxes", minval=1, maxval=12,
     tooltip="Most boxes still open at once. When a new box passes the limit, the oldest open box is removed.")
bool  showFilled = input.bool(false, "Show filled gaps",
     tooltip="Filled gaps as dashed frames of their original range: the last 12, fewer when Live boxes is above 6.")
color cUp        = input.color(#3B7BE0, "Gap from an up move", inline="c")
color cDn        = input.color(#3B7BE0, "Gap from a down move", inline="c")
 
// ---------------------------------------------------------------------------
// Fixed settings
// ---------------------------------------------------------------------------
const int   LIFE  = 300   // candles of the chosen timeframe a box may stay live
const int   EXT   = 6     // drawing extension right of the last closed candle
const int   ARCH  = 12    // filled frames kept
const int   SHOWN = 18    // gaps shown at most
const int   NS    = 4     // bands in the open part
const int   T_TAKEN = 90  // transparency of the part already traded into
const int   T_NEAR  = 62  // open part, band next to the traded part
const int   T_FAR   = 50  // open part, band at the far edge (darkest)
int archCap = math.min(ARCH, SHOWN - maxLive)
 
// ---------------------------------------------------------------------------
// Timeframe: the chart's own, or a higher one
// ---------------------------------------------------------------------------
int    chartSec = timeframe.in_seconds()
int    inSec    = tfIn == "" ? chartSec : timeframe.in_seconds(tfIn)
bool   tfLower  = inSec < chartSec          // not used; the chart's timeframe is used and a note is shown
bool   useHtf   = inSec > chartSec
string tfUse    = useHtf ? tfIn : timeframe.period
 
// chart timeframe (v1.2 path)
// ATR(14): Wilder RMA of the true range, seeded with the mean of the first 14 (ta.atr)
float atr = ta.atr(14)
// three consecutive candles with no missing time between them
int  tfMs       = timeframe.in_seconds() * 1000
bool contiguous = timeframe.ismonthly ? true : (time - time[1] == tfMs and time[1] - time[2] == tfMs)
 
// higher timeframe: closed candles only. [1] = C (the last closed candle), [2] = B, [3] = A; with
// lookahead_on and these offsets the values are those of closed candles on history and in real time alike.
[hC, lC, hA, lA, tC, tB, tA, atrB] = request.security(syminfo.tickerid, tfUse,
     [high[1], low[1], high[3], low[3], time[1], time[2], time[3], ta.atr(14)[2]], lookahead=barmerge.lookahead_on)
int  htfMs     = timeframe.in_seconds(tfUse) * 1000
bool htfContig = timeframe.in_seconds(tfUse) >= 2419200 ? true : (tC - tB == htfMs and tB - tA == htfMs)   // a month is not a fixed length
bool htfNew    = useHtf and not na(tC) and tC != tC[1]                                                       // C has just closed
// first chart candle of each higher-timeframe candle: where the box of C starts
bool htfStart = ta.change(time(tfUse)) != 0
var int perPrev = na
var int perCur  = na
if htfStart
    perPrev := perCur
    perCur  := bar_index
 
// ---------------------------------------------------------------------------
// Gaps
// ---------------------------------------------------------------------------
type Gap
    int        dir    // 1: C above A (gap left by an up move), -1: C below A (gap left by a down move)
    float      bot0   // original range
    float      top0
    float      bot    // open (remaining) range
    float      top
    int        b0     // chart bar where the box starts (candle C, or the first chart candle of C)
    int        hb     // candle count of C on the chosen timeframe (for the 300-candle life)
    box        bx     // frame of the original range
    box        tk     // part already traded into (light)
    array<box> sl     // open part in NS bands (dark, darkest at the far edge)
    label      lb
 
var array<Gap> live = array.new<Gap>()
var array<box> arch = array.new<box>()
 
// draws the two tones from the current open range: far edge = bot0 for an up-move gap, top0 for a down-move gap
paint(Gap g) =>
    float h = (g.top - g.bot) / NS
    for k = 0 to NS - 1
        // k = 0 is the band at the far edge
        float lo = g.dir == 1 ? g.bot + k * h : g.top - (k + 1) * h
        box.set_top(g.sl.get(k), lo + h)
        box.set_bottom(g.sl.get(k), lo)
        box.set_right(g.sl.get(k), bar_index + EXT)
    if g.dir == 1
        box.set_top(g.tk, g.top0)
        box.set_bottom(g.tk, g.top)
    else
        box.set_top(g.tk, g.bot)
        box.set_bottom(g.tk, g.bot0)
    box.set_right(g.tk, bar_index + EXT)
    box.set_right(g.bx, bar_index + EXT)
    label.set_xy(g.lb, bar_index + EXT, (g.top + g.bot) / 2)
    true
 
erase(Gap g) =>
    box.delete(g.bx)
    box.delete(g.tk)
    for b in g.sl
        box.delete(b)
    label.delete(g.lb)
    true
 
// live boxes, in the order they formed, against this chart candle's wicks: fill wins over a partial fill
update(float lo, float hi) =>
    bool filled = false
    int i = 0
    while i < live.size()
        Gap g = live.get(i)
        bool full = g.dir == 1 ? lo <= g.bot0 : hi >= g.top0
        if full
            filled := true
            color c = g.dir == 1 ? cUp : cDn
            erase(g)
            live.remove(i)
            if showFilled and archCap > 0
                arch.push(box.new(g.b0, g.top0, bar_index, g.bot0, border_color=color.new(c, 50), border_width=1,
                     border_style=line.style_dashed, bgcolor=color.new(c, 100)))
                while arch.size() > archCap
                    box.delete(arch.shift())
        else
            if g.dir == 1 and lo < g.top
                g.top := lo
            if g.dir == -1 and hi > g.bot
                g.bot := hi
            i += 1
    filled
 
// a new gap from candles A and C; left = chart bar where its box starts, hb = candle count of C
form(float hiC, float loC, float hiA, float loA, float thr, bool contig, int left, int hb) =>
    bool made = false
    if contig and not na(thr) and not na(left)
        int   d  = 0
        float cb = na
        float ct = na
        if loC > hiA
            d  := 1
            cb := hiA
            ct := loC
        else if hiC < loA
            d  := -1
            cb := hiC
            ct := loA
        if d != 0 and ct - cb > 0 and ct - cb >= thr
            bool overlap = false
            for g in live
                if g.dir == d and math.min(ct, g.top) - math.max(cb, g.bot) > 0
                    overlap := true
            if not overlap
                color c = d == 1 ? cUp : cDn
                box frame = box.new(left, ct, bar_index + EXT, cb, border_color=color.new(c, 20), border_width=1, bgcolor=color.new(c, 100))
                box taken = box.new(left, ct, bar_index + EXT, ct, border_color=color.new(c, 100), border_width=0, bgcolor=color.new(c, T_TAKEN))
                array<box> bands = array.new<box>()
                for k = 0 to NS - 1
                    int tr = int(math.round(T_FAR + (T_NEAR - T_FAR) * k / (NS - 1)))
                    bands.push(box.new(left, ct, bar_index + EXT, cb, border_color=color.new(c, 100), border_width=0, bgcolor=color.new(c, tr)))
                label t = label.new(bar_index + EXT, (ct + cb) / 2, "FVG", style=label.style_label_left,
                     color=color.new(c, 100), textcolor=c, size=size.small)
                live.push(Gap.new(d, cb, ct, cb, ct, left, hb, frame, taken, bands, t))
                made := true
                while live.size() > maxLive
                    erase(live.shift())
    made
 
bool newGap    = false
bool filledNow = false
var int hIdx = 0   // closed candles of the chosen timeframe seen so far
 
if barstate.isconfirmed
    if htfNew
        hIdx += 1
    int nowIdx = useHtf ? hIdx + 1 : bar_index   // higher timeframe: the candle now in progress (C + 1 on the candle that finds C)
    // 1) a box still live 300 candles after it formed is removed before this candle is read
    int i = 0
    while i < live.size()
        Gap g = live.get(i)
        if nowIdx - g.hb >= LIFE
            erase(g)
            live.remove(i)
        else
            i += 1
    if useHtf
        // 2) C closed before this chart candle began: the new gap first, then this candle's wicks for every box
        if htfNew
            newGap := form(hC, lC, hA, lA, atrB * kMin, htfContig, perPrev, hIdx)
        filledNow := update(low, high)
    else
        // 2) chart timeframe (v1.2): live boxes first, then a new gap at C = this candle
        filledNow := update(low, high)
        newGap := form(high, low, high[2], low[2], atr[1] * kMin, contiguous, bar_index, bar_index)
    // 3) draw the two tones of every live box
    for g in live
        paint(g)
 
// a timeframe below the chart's is not used: a small note on the last candle (no silent fallback)
var label note = na
if barstate.islast
    label.delete(note)
    note := tfLower ? label.new(bar_index, high, "Remaining FVG: timeframe below the chart's, the chart's timeframe is used",
         style=label.style_label_lower_left, color=color.new(cUp, 100), textcolor=color.new(chart.fg_color, 30), size=size.small) : na
 
// alerts on the candle close
alertcondition(newGap, "New FVG", "{{ticker}} {{interval}}: a new fair value gap formed (Remaining FVG).")
alertcondition(filledNow, "FVG filled", "{{ticker}} {{interval}}: a fair value gap was filled to its far edge (Remaining FVG).")

← 返回列表