FVG Tracker [Forex]

oguzcinar678 · study · 215 行 · 点赞 40 · TradingView 原页

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

Pine Script

//@version=6
indicator("FVG Tracker [Forex]", "FVG Tracker", overlay = true, max_boxes_count = 500, max_lines_count = 500)
 
// ─────────────────────────────── Inputs ───────────────────────────────
grpC      = "Chart Timeframe FVGs"
showLtf   = input.bool(true, "Show chart timeframe FVGs", group = grpC)
minAtr    = input.float(0.3, "Minimum gap size (x ATR)", minval = 0, step = 0.05, group = grpC, tooltip = "Gaps smaller than this fraction of the ATR are ignored. Adapts automatically to the timeframe and the pair.")
minPips   = input.float(0.5, "Minimum gap size (pips)", minval = 0, step = 0.1, group = grpC)
dispMult  = input.float(0.0, "Min displacement candle body (x ATR)", minval = 0, step = 0.1, group = grpC, tooltip = "Only keep FVGs whose middle candle body is at least this many ATRs. 0 = off.")
 
grpH      = "Higher Timeframe FVGs"
showHtf   = input.bool(true, "Show higher timeframe FVGs", group = grpH)
htf       = input.timeframe("15", "Higher timeframe", group = grpH)
 
grpF      = "Fill & Inversion"
breakSrc  = input.string("Close", "FVG is broken when price…", options = ["Close", "Wick"], group = grpF)
removePct = input.int(100, "Remove when filled (%)", minval = 10, maxval = 100, group = grpF, tooltip = "100 = remove once the gap is completely filled. 50 = remove once price reaches the middle of the gap.")
shrink    = input.bool(true, "Shrink box as the gap gets filled", group = grpF)
useInv    = input.bool(true, "Turn broken FVGs into inverse FVGs (iFVG)", group = grpF)
showCE    = input.bool(false, "Show 50% line (consequent encroachment)", group = grpF)
 
grpV      = "Clean Chart"
maxSide   = input.int(3, "Show nearest FVGs per side", minval = 1, maxval = 20, group = grpV, tooltip = "Only the closest zones above and below price are drawn. Others are kept in memory and appear when price gets closer.")
mergeOvl  = input.bool(true, "Hide overlapping FVGs (keep higher timeframe)", group = grpV)
 
grpS      = "Style"
bullCol   = input.color(#089981, "Bullish FVG", group = grpS, inline = "c1")
bearCol   = input.color(#F23645, "Bearish FVG", group = grpS, inline = "c1")
iBullCol  = input.color(#2962FF, "iFVG support", group = grpS, inline = "c2")
iBearCol  = input.color(#FF9800, "iFVG resistance", group = grpS, inline = "c2")
transp    = input.int(85, "Box transparency", minval = 0, maxval = 100, group = grpS)
extBars   = input.int(8, "Extend boxes (bars right of price)", minval = 0, maxval = 200, group = grpS)
showLbl   = input.bool(true, "Show labels", group = grpS)
lblCol    = input.color(#9598A1, "Label colour", group = grpS)
 
// ─────────────────────────────── Types & helpers ───────────────────────────────
type FVG
    float oTop
    float oBtm
    float lvl        // deepest fill price so far
    bool  bull       // role: true = support (below price), false = resistance (above price)
    bool  inv
    bool  htf
    bool  touched
    box   bx
    line  ce
 
var array<FVG> zones  = array.new<FVG>()
int maxMemory = 40
 
pip     = syminfo.type == "forex" ? syminfo.mintick * 10 : syminfo.mintick
atr     = ta.atr(14)
htfOk   = timeframe.in_seconds(htf) > timeframe.in_seconds(timeframe.period)
htfName = timeframe.in_seconds(htf) >= 86400 ? htf : timeframe.in_seconds(htf) >= 3600 ? str.tostring(math.round(timeframe.in_seconds(htf) / 3600)) + "H" : str.tostring(math.round(timeframe.in_seconds(htf) / 60)) + "m"
 
zoneColor(FVG z) =>
    z.bull ? (z.inv ? iBullCol : bullCol) : (z.inv ? iBearCol : bearCol)
 
fillPct(FVG z) =>
    float rng = z.oTop - z.oBtm
    rng <= 0 ? 100.0 : z.bull ? (z.oTop - z.lvl) / rng * 100 : (z.lvl - z.oBtm) / rng * 100
 
zoneText(FVG z) =>
    float f = fillPct(z)
    showLbl ? (z.htf ? htfName + " " : "") + (z.inv ? "iFVG" : "FVG") + (f >= 5 ? " " + str.tostring(f, "#") + "%" : "") : ""
 
draw(FVG z, bool visible) =>
    color c = zoneColor(z)
    float t = shrink and z.bull ? z.lvl : z.oTop
    float b = shrink and not z.bull ? z.lvl : z.oBtm
    z.bx.set_top(t)
    z.bx.set_bottom(b)
    z.bx.set_right(bar_index + extBars)
    z.bx.set_bgcolor(visible ? color.new(c, z.htf ? math.max(transp - 8, 0) : transp) : na)
    z.bx.set_border_color(visible ? color.new(c, z.htf ? 20 : 55) : na)
    z.bx.set_border_width(z.htf ? 2 : 1)
    z.bx.set_border_style(z.inv ? line.style_dashed : line.style_solid)
    z.bx.set_text(visible ? zoneText(z) : "")
    if not na(z.ce)
        bool showLine = visible and fillPct(z) < 50
        z.ce.set_x2(bar_index + extBars)
        z.ce.set_color(showLine ? color.new(c, 40) : na)
 
removeAt(int i) =>
    FVG z = zones.get(i)
    z.bx.delete()
    if not na(z.ce)
        z.ce.delete()
    zones.remove(i)
 
overlaps(float top, float btm, FVG z) =>
    top >= z.oBtm and btm <= z.oTop
 
create(float top, float btm, bool bull, bool isHtf, int left) =>
    bool skip = false
    if mergeOvl and zones.size() > 0
        for i = zones.size() - 1 to 0
            FVG ex = zones.get(i)
            if ex.bull == bull and overlaps(top, btm, ex)
                if isHtf and not ex.htf
                    removeAt(i)          // higher timeframe replaces the smaller gap
                else
                    skip := true
    if not skip
        color c = bull ? bullCol : bearCol
        box   b = box.new(left, top, bar_index + extBars, btm, bgcolor = color.new(c, transp), border_color = color.new(c, 55), text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_center, text_color = lblCol)
        line  l = showCE ? line.new(left, (top + btm) / 2, bar_index + extBars, (top + btm) / 2, style = line.style_dashed) : na
        zones.unshift(FVG.new(top, btm, bull ? top : btm, bull, false, isHtf, false, b, l))
        if zones.size() > maxMemory
            removeAt(zones.size() - 1)
 
// ─────────────────────────────── Update existing zones ───────────────────────────────
bool touchBull = false
bool touchBear = false
bool newInv    = false
if zones.size() > 0
    for i = zones.size() - 1 to 0
        FVG  z    = zones.get(i)
        bool kill = false
        if z.bull
            z.lvl := math.max(math.min(z.lvl, low), z.oBtm)
            if low <= z.oTop and not z.touched
                z.touched := true
                touchBull := true
            if breakSrc == "Close" ? close < z.oBtm : low < z.oBtm
                if useInv and not z.inv
                    z.bull    := false
                    z.inv     := true
                    z.lvl     := z.oBtm
                    z.touched := false
                    newInv    := true
                else
                    kill := true
        else
            z.lvl := math.min(math.max(z.lvl, high), z.oTop)
            if high >= z.oBtm and not z.touched
                z.touched := true
                touchBear := true
            if breakSrc == "Close" ? close > z.oTop : high > z.oTop
                if useInv and not z.inv
                    z.bull    := true
                    z.inv     := true
                    z.lvl     := z.oTop
                    z.touched := false
                    newInv    := true
                else
                    kill := true
        // fully (or sufficiently) filled zones are removed
        if not kill and fillPct(z) >= removePct
            kill := true
        if kill
            removeAt(i)
 
// ─────────────────────────────── Detect new FVGs ───────────────────────────────
float minGap  = math.max(minPips * pip, minAtr * nz(atr[1]))
bool  dispOk  = dispMult == 0 or math.abs(close[1] - open[1]) >= dispMult * nz(atr[1])
bool  newBull = showLtf and barstate.isconfirmed and low > high[2] and (low - high[2]) >= minGap and dispOk
bool  newBear = showLtf and barstate.isconfirmed and high < low[2] and (low[2] - high) >= minGap and dispOk
if newBull
    create(low, high[2], true, false, bar_index - 1)
if newBear
    create(low[2], high, false, false, bar_index - 1)
 
htfData() =>
    bool  b   = low > high[2]
    bool  s   = high < low[2]
    float t   = b ? low : s ? low[2] : na
    float m   = b ? high[2] : s ? high : na
    float atH = ta.atr(14)
    [b, s, t, m, atH]
 
htfClosed() =>
    [b, s, t, m, a] = htfData()
    [b[1], s[1], t[1], m[1], a[1]]      // last CLOSED higher-timeframe candle → no repainting
 
[hB, hS, hT, hM, hA] = request.security(syminfo.tickerid, htf, htfClosed(), lookahead = barmerge.lookahead_on)
bool  newHtf = showHtf and htfOk and timeframe.change(htf)
float hMin   = math.max(minPips * pip, minAtr * nz(hA))
if newHtf and hB and (hT - hM) >= hMin
    create(hT, hM, true, true, bar_index)
if newHtf and hS and (hT - hM) >= hMin
    create(hT, hM, false, true, bar_index)
 
// ─────────────────────────────── Draw: only the nearest zones per side ───────────────────────────────
if zones.size() > 0
    array<float> dSup = array.new<float>()
    array<int>   iSup = array.new<int>()
    array<float> dRes = array.new<float>()
    array<int>   iRes = array.new<int>()
    for i = 0 to zones.size() - 1
        FVG z = zones.get(i)
        if z.bull
            dSup.push(math.max(close - z.oTop, 0))
            iSup.push(i)
        else
            dRes.push(math.max(z.oBtm - close, 0))
            iRes.push(i)
    array<bool> vis = array.new<bool>(zones.size(), false)
    if dSup.size() > 0
        array<int> ord = dSup.sort_indices(order.ascending)
        for k = 0 to math.min(maxSide, ord.size()) - 1
            vis.set(iSup.get(ord.get(k)), true)
    if dRes.size() > 0
        array<int> ord = dRes.sort_indices(order.ascending)
        for k = 0 to math.min(maxSide, ord.size()) - 1
            vis.set(iRes.get(ord.get(k)), true)
    for i = 0 to zones.size() - 1
        draw(zones.get(i), vis.get(i))
 
// ─────────────────────────────── Alerts ───────────────────────────────
alertcondition(newBull, "New bullish FVG", "{{ticker}} ({{interval}}): new bullish FVG")
alertcondition(newBear, "New bearish FVG", "{{ticker}} ({{interval}}): new bearish FVG")
alertcondition(touchBull, "Price entered a support FVG", "{{ticker}} ({{interval}}): price entered a bullish / support FVG")
alertcondition(touchBear, "Price entered a resistance FVG", "{{ticker}} ({{interval}}): price entered a bearish / resistance FVG")
alertcondition(newInv, "Inverse FVG formed", "{{ticker}} ({{interval}}): an FVG was broken and turned into an inverse FVG")

← 返回列表