Fair Value Gap Profiles [PIP REXA] - Reviewed

MID_Trader · study · 190 行 · 点赞 235 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Original concept and code: © AlgoAlpha
// Adaptation, safeguards, and simplified implementation for PIP REXA.
// Attribution does not imply endorsement by the original author.
//@version=6
indicator("Fair Value Gap Profiles [PIP REXA] - Reviewed", shorttitle="PIP REXA FVG", overlay=true, max_boxes_count=450)
 
// ── Inputs
int avgLen = input.int(50, "Average Gap Sample Size", minval=1, maxval=500, group="FVG Detection")
float minMult = input.float(1.5, "Minimum Gap / Average Gap Multiplier", minval=0.1, step=0.1, group="FVG Detection")
int maxAge = input.int(1000, "Zone Expiration (bars)", minval=1, group="FVG Detection")
int maxZones = input.int(25, "Maximum Stored Zones", minval=1, maxval=35, group="FVG Detection")
bool preventOverlap = input.bool(true, "Prevent Active Zone Overlap", group="FVG Detection")
bool showBull = input.bool(true, "Bullish FVG", group="FVG Detection")
bool showBear = input.bool(true, "Bearish FVG", group="FVG Detection")
string ltf = input.timeframe("1", "Lower Timeframe", group="Profile")
int bins = input.int(7, "Volume Profile Bins", minval=1, maxval=8, group="Profile")
int lvWindow = input.int(2, "Low-Volume Window Bins", minval=1, maxval=8, group="Profile")
bool showProfile = input.bool(true, "Show Approximate Volume Profile", group="Appearance")
bool showLow = input.bool(true, "Show Low-Volume Zone", group="Appearance")
bool showGap = input.bool(true, "Show Main FVG", group="Appearance")
bool showVolumeNumbers = input.bool(true, "Show FVG Volume Numbers", group="Appearance")
bool showBinNumbers = input.bool(false, "Show Profile Bin Volume Numbers", group="Appearance")
color bullCol = input.color(#00ffbb, "Bullish Color", group="Appearance")
color bearCol = input.color(#ff1100, "Bearish Color", group="Appearance")
 
// Lower-timeframe volume is assigned to bins by intrabar closing price; it is NOT tick volume-at-price.
array<float> ltClose = request.security_lower_tf(syminfo.tickerid, ltf, close)
array<float> ltVolume = request.security_lower_tf(syminfo.tickerid, ltf, volume)
 
var array<float> recentGaps = array.new_float()
var array<box> zoneBoxes = array.new<box>()
var array<box> lowBoxes = array.new<box>()
var array<float> zoneTop = array.new_float()
var array<float> zoneBottom = array.new_float()
var array<int> zoneStart = array.new_int()
var array<int> zoneEnd = array.new_int() // -1 means unmitigated
var array<int> zoneType = array.new_int()
// Flat arrays: exactly `bins` entries per zone, avoiding unsupported nested arrays.
var array<box> profileBoxes = array.new<box>()
var array<float> profileVolumes = array.new_float()
 
f_remove(int idx) =>
    box.delete(array.remove(zoneBoxes, idx))
    box lowB = array.remove(lowBoxes, idx)
    if not na(lowB)
        box.delete(lowB)
    array.remove(zoneTop, idx)
    array.remove(zoneBottom, idx)
    array.remove(zoneStart, idx)
    array.remove(zoneEnd, idx)
    array.remove(zoneType, idx)
    for j = bins - 1 to 0
        int pos = idx * bins + j
        box pb = array.remove(profileBoxes, pos)
        if not na(pb)
            box.delete(pb)
        array.remove(profileVolumes, pos)
 
f_overlaps(float top, float bottom) =>
    bool overlaps = false
    if array.size(zoneBoxes) > 0
        for i = 0 to array.size(zoneBoxes) - 1
            if array.get(zoneEnd, i) == -1 and top > array.get(zoneBottom, i) and bottom < array.get(zoneTop, i)
                overlaps := true
                break
    overlaps
 
bool basicBull = bar_index >= 2 and low > high[2]
bool basicBear = bar_index >= 2 and high < low[2]
float gapSize = basicBull ? low - high[2] : basicBear ? low[2] - high : na
// Threshold uses the mean of previously detected gap widths (not ATR).
float threshold = array.size(recentGaps) > 0 ? array.avg(recentGaps) * minMult : na
bool bullFVG = showBull and basicBull and not na(threshold) and gapSize > threshold
bool bearFVG = showBear and basicBear and not na(threshold) and gapSize > threshold
bool bullMit = false
bool bearMit = false
 
// Manage existing zones first; do not mitigate a zone on its creation candle.
if array.size(zoneBoxes) > 0
    for i = array.size(zoneBoxes) - 1 to 0
        float top = array.get(zoneTop, i)
        float bot = array.get(zoneBottom, i)
        int created = array.get(zoneStart, i)
        int ending = array.get(zoneEnd, i)
        int kind = array.get(zoneType, i)
        if ending == -1 and bar_index > created
            bool mitigated = kind == 1 ? low <= bot : high >= top
            if mitigated
                ending := bar_index
                array.set(zoneEnd, i, ending)
                bullMit := bullMit or kind == 1
                bearMit := bearMit or kind == -1
        if bar_index - created > maxAge
            f_remove(i)
        else
            int rightEdge = ending == -1 ? bar_index : ending
            box.set_right(array.get(zoneBoxes, i), rightEdge)
            box lb = array.get(lowBoxes, i)
            if not na(lb)
                box.set_right(lb, rightEdge)
            float biggest = 0.0
            for j = 0 to bins - 1
                biggest := math.max(biggest, array.get(profileVolumes, i * bins + j))
            for j = 0 to bins - 1
                int pos = i * bins + j
                box pb = array.get(profileBoxes, pos)
                if not na(pb)
                    float v = array.get(profileVolumes, pos)
                    int pxWidth = biggest > 0 ? int(math.max(1, (rightEdge - created) * 0.5 * v / biggest)) : 1
                    box.set_right(pb, created + pxWidth)
 
// Only use confirmed bars for creation, preventing intrabar FVG creation flicker.
if barstate.isconfirmed and (bullFVG or bearFVG)
    bool isBull = bullFVG
    float top = isBull ? low : low[2]
    float bot = isBull ? high[2] : high
    if not preventOverlap or not f_overlaps(top, bot)
        if array.size(zoneBoxes) >= maxZones
            f_remove(array.size(zoneBoxes) - 1)
        color zoneColor = isBull ? bullCol : bearCol
        box mainBox = box.new(bar_index - 1, top, bar_index, bot, bgcolor=color.new(zoneColor, showGap ? 88 : 100), border_color=color.new(zoneColor, showGap ? 50 : 100))
        array.unshift(zoneBoxes, mainBox)
        array.unshift(zoneTop, top)
        array.unshift(zoneBottom, bot)
        array.unshift(zoneStart, bar_index)
        array.unshift(zoneEnd, -1)
        array.unshift(zoneType, isBull ? 1 : -1)
 
        // Profile is sampled from the previous candle's lower-timeframe closes and volumes.
        array<float> p = ltClose[1]
        array<float> v = ltVolume[1]
        array<float> binVols = array.new_float(bins, 0.0)
        if not na(p) and not na(v) and array.size(p) == array.size(v) and array.size(p) > 0
            for k = 0 to array.size(p) - 1
                float price = array.get(p, k)
                float volumeAtClose = array.get(v, k)
                if not na(price) and not na(volumeAtClose) and price >= bot and price <= top
                    int index = math.min(bins - 1, int(math.floor((price - bot) / (top - bot) * bins)))
                    array.set(binVols, index, array.get(binVols, index) + volumeAtClose)
        float biggest = array.max(binVols)
        float totalProfileVolume = array.sum(binVols)
        if showVolumeNumbers
            string volumeText = totalProfileVolume > 0 ? str.tostring(totalProfileVolume, format.volume) : "N/A"
            box.set_text(mainBox, "VOL " + volumeText)
            box.set_text_color(mainBox, chart.fg_color)
            box.set_text_size(mainBox, size.tiny)
            box.set_text_halign(mainBox, text.align_right)
            box.set_text_valign(mainBox, text.align_bottom)
        int win = math.min(lvWindow, bins)
        float minSum = na
        int minIndex = 0
        for j = 0 to bins - win
            float total = 0.0
            for k = 0 to win - 1
                total += array.get(binVols, j + k)
            if na(minSum) or total < minSum
                minSum := total
                minIndex := j
        box lvBox = na
        if showLow and biggest > 0
            float lvBot = bot + (top - bot) * minIndex / bins
            float lvTop = bot + (top - bot) * (minIndex + win) / bins
            lvBox := box.new(bar_index - 1, lvTop, bar_index, lvBot, bgcolor=color.new(zoneColor, 76), border_color=color.new(zoneColor, 100))
        array.unshift(lowBoxes, lvBox)
        // Insert bins in reverse order so each zone occupies a contiguous flat-array segment.
        for j = bins - 1 to 0
            float btm = bot + (top - bot) * j / bins
            float tp = bot + (top - bot) * (j + 1) / bins
            float val = array.get(binVols, j)
            box b = na
            if showProfile and biggest > 0 and val > 0
                b := box.new(bar_index - 1, tp, bar_index, btm, bgcolor=color.new(zoneColor, 55), border_color=color.new(zoneColor, 100))
                if showBinNumbers
                    box.set_text(b, str.tostring(val, format.volume))
                    box.set_text_color(b, chart.fg_color)
                    box.set_text_size(b, size.tiny)
            array.unshift(profileBoxes, b)
            array.unshift(profileVolumes, val)
 
// Update the gap-width sample after evaluating the current candle, avoiding self-inclusion.
if barstate.isconfirmed and not na(gapSize)
    array.push(recentGaps, gapSize)
    if array.size(recentGaps) > avgLen
        array.shift(recentGaps)
 
alertcondition(bullFVG and barstate.isconfirmed, "Bullish FVG", "Bullish FVG detected")
alertcondition(bearFVG and barstate.isconfirmed, "Bearish FVG", "Bearish FVG detected")
alertcondition(bullMit, "Bullish FVG Mitigated", "Bullish FVG fully mitigated")
alertcondition(bearMit, "Bearish FVG Mitigated", "Bearish FVG fully mitigated")

← 返回列表