← К каталогу
Исходный код · ID 5114

Volumetric FairValueBlock

volumetric fairvalueblock.pine
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

Индикатор «Volumetric FairValueBlock» предназначен для платформы TradingView и написан на Pine Script v6. Он выявляет на графике зоны справедливой стоимости (FairValueBlock), анализируя свечи консенсуса, которые разделяют общий ценовой интервал, и фиксирует импульсные свечи, пробивающие этот диапазон с достаточным движением.

Для каждой обнаруженной зоны индикатор отображает графические объекты: заливку области, пунктирную линию в средней точке, боковые полоски объёмной активности и метки с оценочными объёмными данными. Оценка покупательской и продавательской активности рассчитывается на основе положения закрытия внутри диапазона каждой свечи формирования.

Встроены условия оповещений для живых пробитий, подтверждённых зон и их повторных касаний. Поддерживается объединение однонаправленных зон при достаточном перекрытии, а также фильтры эффективности и гибкие настройки визуализации.

Настройки программы

НастройкаОписание
len Количество завершённых свечей, которые должны иметь общий ценовой интервал, прежде чем смещение сможет создать FairValueBlock.
minFair Минимальная общая перекрывающая область, делённая на полный диапазон от максимума до минимума свечей консенсуса. Более высокие значения требуют большего согласия между свечами.
useEff Включить фильтрацию базисных зон по ценовой эффективности. При отключённом фильтре все базы проходят проверку без ограничений по эффективности.
maxEff Максимально допустимое значение эффективности ценового базиса. При двух свечах это абсолютное изменение закрытия, делённое на диапазон базы. При трёх и более — чистое изменение закрытия, делённое на суммарный путь закрытий. Более низкие значения требуют более сбалансированной базы.
maxBase Максимальный диапазон свечей консенсуса от максимума до минимума, измеренный в кратных значениях ATR предыдущего бара (14).
minTicks Минимальная ширина общей ценовой области (ядра) в минимальных ценовых инкрементах символа.
dispAtr Минимальное истинное движение диапазона импульсной свечи в кратных значениях ATR предыдущего бара (14).
minBody Минимальное отношение тела свечи к её диапазону от максимума до минимума. Более высокие значения требуют более выраженного тела свечи.
minClose Минимальное положение закрытия относительно стороны пробития свечи. Значение 0.75 требует, чтобы бычья свеча закрылась в верхней четверти или медвежья — в нижней четверти.
zMode Режим построения границ зоны: Core — используется общая ценовая область; Adaptive — расширяет узкое ядро в пределах полного диапазона консенсуса; Full Base — используется наибольший максимум и наименьший минимум свечей консенсуса без импульсной свечи.
minZAtr Целевая минимальная высота зоны в кратных значениях ATR предыдущего бара (14). Ядро не сужается, расширение ограничено полным диапазоном консенсуса.
liveDot Показывать точку при первом пробитии диапазона действующей базы на текущем незакрытом баре в реальном времени. Точка не перерисовывается на исторических барах.
confDot Показывать точку в средней точке свечи, подтверждающей FairValueBlock по закрытию бара.
confArr Показывать подтверждённую бычью или медвежью стрелку на уровне наименьшего минимума или наибольшего максимума последних пяти свечей.
maxFvb Максимальное суммарное количество сохраняемых активных и инвалидированных зон. Объединённые зоны считаются за одну. При достижении лимита самая старая зона удаляется.
bullCol Цвет бычьих (бычьих) зон FairValueBlock, включая заливку, линии и маркеры.
bearCol Цвет медвежьих (медвежьих) зон FairValueBlock, включая заливку, линии и маркеры.
actTrans Прозрачность фона активных зон FairValueBlock. 0 — полностью непрозрачный, 100 — невидимый.
histTrans Прозрачность фона неактивных (инвалидированных) зон FairValueBlock. Зона перестаёт расширяться в момент инвалидации.
showAct Отображать оценочную покупательскую активность в верхней половине каждой зоны и продавательскую — в нижней. Ширины полосок отражают долю от общего объёма формирования. Используются данные OHLCV, а не bid/ask дельта.
buyActCol Цвет боковой полоски, отображающей оценочную покупательскую активность внутри активной зоны.
sellActCol Цвет боковой полоски, отображающей оценочную продавательскую активность внутри активной зоны.
showMid Показывать пунктирную горизонтальную линию в средней точке каждой FairValueBlock.
showVol Отображать общий оценочный объём формирования и его процентную долю от общего объёма всех активных зон того же направления. При наведении показывается разбивка покупательской/продавательской активности и количество формирований.
volSize Размер меток объёмных данных, отображаемых на графике: Tiny, Small, Normal или Large.
mergeFvb Объединять активные FairValueBlock одного направления, когда новая подтверждённая зона имеет достаточную общую ценовую область. Объединённая зона обрабатывается как новая.
mergeAtr Минимальная общая ценовая ширина в кратных значениях ATR предыдущего бара (14) для объединения однонаправленных зон FairValueBlock. Нулевое значение разрешает любое положительное перекрытие. Касающиеся или разделённые зоны не объединяются.

Поиск по коду файла

indicator("Volumetric FairValueBlock",overlay=true,max_bars_back=500,max_boxes_count=500,max_lines_count=500,max_labels_count=300)

const string tt1="Number of completed candles that must share a common price interval before a displacement can create a FairValueBlock."
const string tt2="Minimum shared price interval divided by the full high-to-low range of the consensus candles. Higher values require more agreement between candles."
const string tt3="Filter out directional bases using price efficiency. With two candles, efficiency is the absolute close-to-close change divided by the base range. With three or more, it is the net close-to-close change divided by the total close-to-close path. Lower values require a more balanced base."
const string tt4="Maximum permitted high-to-low range of the consensus candles, measured in multiples of the previous bar's ATR (14)."
const string tt5="Minimum width of the shared price interval, measured in the symbol's minimum price increments."
const string tt6="Minimum true range of the displacement candle in multiples of the previous bar's ATR (14)."
const string tt7="Minimum candle body divided by the displacement candle's high-to-low range. Higher values require a stronger candle body."
const string tt8="Minimum closing position toward the breakout side of the candle. A value of 0.75 requires a bullish candle to close in its upper quarter or a bearish candle to close in its lower quarter."
const string tt9="Show a dot as soon as price first breaches the range of a valid base on the realtime candle. The dot is not reconstructed on historical bars and does not require a confirmed displacement."
const string tt10="Show a dot at the midpoint of a candle that confirms a FairValueBlock at bar close."
const string tt11="Show the confirmed bullish or bearish marker at the lowest low or highest high of the latest five candles."
const string tt12="Maximum number of active and invalidated zones retained together. Merged zones count as one. The oldest retained zone is removed when the limit is reached. At large history settings, older zones may show only their background and midpoint to stay within TradingView's drawing limits."
const string tt13="Bullish and bearish colors for the FairValueBlock backgrounds, midpoint lines, volume metrics and signal markers."
const string tt14="Background transparency of active FairValueBlocks, including zones that have been retested. 0 is opaque and 100 is invisible."
const string tt15="Background transparency of invalidated FairValueBlocks. The zone stops extending at the candle that invalidates it."
const string tt16="Display estimated buy activity in the upper half of each zone and sell activity in the lower half. Their widths represent their share of total formation volume, including the displacement candle. Estimates use OHLCV, not exchange bid/ask delta. At large history settings, activity bars are prioritized for the newest zones."
const string tt17="Show a dashed horizontal line at the midpoint of each FairValueBlock."
const string tt18="Display total estimated formation volume and its percentage of all retained active zone volume of the same direction. Hover over the metric for the estimated buy/sell split and number of constituent formations."
const string tt19="Merge active FairValueBlocks of the same direction when a new confirmed zone shares sufficient price overlap. The combined zone is treated as fresh. Its earliest origin, combined price boundaries and summed formation volumes are retained. Shared source candles may be counted more than once."
const string tt20="Minimum shared price width in multiples of the previous bar's ATR (14). Zero allows any positive overlap. Touching or separated zones do not merge."
const string tt21="Core uses the original common price interval. Adaptive expands a narrow core within the full consensus range. Full Base uses the highest high and lowest low of the consensus candles, excluding the displacement candle. The detection logic is unchanged; the constructed boundaries govern merging, retests and invalidation."
const string tt22="Target minimum zone height in multiples of the previous bar's ATR (14). The core is never narrowed and expansion is capped at the full consensus range. If the formation range is smaller than the target, the full range is used."

gCORE="Fairness Core"
gESC="Escape / Displacement"
gZONE="Zone Construction"
gSIG="Signals"
gLIFE="Block Life"
gAPP="Appearance"
gVOL="Volumetric Display"
gMERGE="Zone Merging"

len=input.int(3,"Consensus Bars",minval=2,maxval=8,group=gCORE,tooltip=tt1)
minFair=input.float(0.25,"Minimum Shared Overlap",minval=0.05,maxval=0.90,step=0.05,group=gCORE,tooltip=tt2)
useEff=input.bool(true,"Efficiency Filter",inline="efficiency",group=gCORE)
maxEff=input.float(0.45,"",minval=0.05,maxval=1.00,step=0.05,inline="efficiency",group=gCORE,active=useEff,tooltip=tt3)
maxBase=input.float(1.60,"Maximum Base Width (ATR)",minval=0.25,maxval=5.00,step=0.05,group=gCORE,tooltip=tt4)
minTicks=input.int(2,"Minimum Core Width (Ticks)",minval=1,maxval=100,group=gCORE,tooltip=tt5)
dispAtr=input.float(1.25,"Minimum Displacement (ATR)",minval=0.50,maxval=5.00,step=0.05,group=gESC,tooltip=tt6)
minBody=input.float(0.60,"Minimum Body / Range",minval=0.10,maxval=1.00,step=0.05,group=gESC,tooltip=tt7)
minClose=input.float(0.75,"Minimum Close Location",minval=0.50,maxval=1.00,step=0.05,group=gESC,tooltip=tt8)
zMode=input.string("Full Base","Zone Construction",options=["Core","Adaptive","Full Base"],group=gZONE,tooltip=tt21)
minZAtr=input.float(0.25,"Minimum Height (ATR)",minval=0.0,maxval=2.0,step=0.05,group=gZONE,active=zMode=="Adaptive",tooltip=tt22)
liveDot=input.bool(true,"Live Break Dot",group=gSIG,tooltip=tt9)
confDot=input.bool(true,"Confirmed Break Dot",group=gSIG,tooltip=tt10)
confArr=input.bool(true,"Confirmed Arrow",group=gSIG,tooltip=tt11)
maxFvb=input.int(150,"Maximum Blocks Kept",minval=5,maxval=300,group=gLIFE,tooltip=tt12)
bullCol=input.color(color.teal,"Bullish",inline="zoneColors",group=gAPP)
bearCol=input.color(color.red,"Bearish",inline="zoneColors",group=gAPP,tooltip=tt13)
actTrans=input.int(90,"Active Transparency",minval=0,maxval=100,group=gAPP,tooltip=tt14)
histTrans=input.int(95,"Historical Transparency",minval=0,maxval=100,group=gAPP,tooltip=tt15)
showAct=input.bool(true,"Buy / Sell Activity",inline="activity",group=gVOL)
buyActCol=input.color(color.new(color.teal,50),"",inline="activity",group=gVOL,active=showAct)
sellActCol=input.color(color.new(color.red,50),"",inline="activity",group=gVOL,active=showAct,tooltip=tt16)
showMid=input.bool(true,"Dashed Midpoint",group=gVOL,tooltip=tt17)
showVol=input.bool(true,"Volume Metrics",inline="metrics",group=gVOL)
volSize=input.string("Normal","",options=["Tiny","Small","Normal","Large"],inline="metrics",group=gVOL,active=showVol,tooltip=tt18)
mergeFvb=input.bool(true,"Merge Zones",group=gMERGE,tooltip=tt19)
mergeAtr=input.float(0.10,"Minimum Overlap (ATR)",minval=0.0,maxval=5.0,step=0.05,group=gMERGE,active=mergeFvb,tooltip=tt20)

ATR_LEN=14
SIG_LEN=5
VOL_OFF=2
BOX_MAX=500
LINE_MAX=500

type FVB
    int t0
    int born
    int dir
    float top
    float btm
    float bVol
    float sVol
    int nFvb=1
    bool active=true
    bool tested=false
    int t1=na
    box body=na
    line hiLn=na
    line loLn=na
    linefill bgFill=na
    box bBox=na
    box sBox=na
    line midLn=na
    label volLbl=na

var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @free_fx_pro", text_color = color.new(color.gray, 70), text_size = size.large)

lbl_size(string opt)=>opt=="Small"?size.small:opt=="Normal"?size.normal:opt=="Large"?size.large:size.tiny
vol_sum(FVB z)=>z.bVol+z.sVol
fade_col(color c,int add)=>color.new(c,int(math.min(100,color.t(c)+add)))
zone_col(FVB z)=>z.dir==1?bullCol:bearCol

zone_rng(float cHi,float cLo,float eHi,float eLo,float a)=>
    hi=cHi
    lo=cLo
    if zMode=="Full Base"
        hi:=eHi
        lo:=eLo
    else if zMode=="Adaptive" and not na(a)
        cW=cHi-cLo
        w=math.min(eHi-eLo,math.max(cW,a*minZAtr))
        if w>cW
            lo:=math.max(eLo,math.min(cLo-(w-cW)*0.5,eHi-w))
            hi:=math.min(eHi,lo+w)
    [hi,lo]

form_vol(int n)=>
    bVol=0.0
    sVol=0.0
    for i=0 to n
        v=math.max(nz(volume[i]),0.0)
        r=high[i]-low[i]
        bFrac=r>0?math.max(0.0,math.min(1.0,(close[i]-low[i])/r)):0.5
        bVol+=v*bFrac
        sVol+=v*(1.0-bFrac)
    [bVol,sVol]

clr_bg(FVB z)=>
    if not na(z.body)
        box.delete(z.body)
        z.body:=na
    if not na(z.bgFill)
        linefill.delete(z.bgFill)
        z.bgFill:=na
    if not na(z.hiLn)
        line.delete(z.hiLn)
        z.hiLn:=na
    if not na(z.loLn)
        line.delete(z.loLn)
        z.loLn:=na
    0

clr_act(FVB z)=>
    if not na(z.bBox)
        box.delete(z.bBox)
        z.bBox:=na
    if not na(z.sBox)
        box.delete(z.sBox)
        z.sBox:=na
    0

clr_lbl(FVB z)=>
    if not na(z.volLbl)
        label.delete(z.volLbl)
        z.volLbl:=na
    0

clr_zone(FVB z)=>
    clr_bg(z)
    clr_act(z)
    clr_lbl(z)
    if not na(z.midLn)
        line.delete(z.midLn)
        z.midLn:=na
    0

merge_zone(array<FVB> zones,FVB z,float minOv)=>
    idx=zones.size()-1
    while idx>=0
        old=zones.get(idx)
        ov=math.min(z.top,old.top)-math.max(z.btm,old.btm)
        if old.active and old.dir==z.dir and ov>0 and ov>=minOv
            z.top:=math.max(z.top,old.top)
            z.btm:=math.min(z.btm,old.btm)
            z.t0:=math.min(z.t0,old.t0)
            z.bVol+=old.bVol
            z.sVol+=old.sVol
            z.nFvb+=old.nFvb
            clr_zone(old)
            zones.remove(idx)
            idx:=zones.size()-1
        else
            idx-=1
    0

trim_zones(array<FVB> zones,int keep)=>
    if zones.size()>=keep
        clr_zone(zones.shift())
    0

obj_budget(int cnt,int nVol)=>
    nMid=showMid?cnt:0
    maxFill=int(math.floor((LINE_MAX-nMid)/2.0))
    nFill=math.min(cnt,math.min(maxFill,math.max(0,cnt+2*nVol-BOX_MAX)))
    nAc

Показано первые 50% кода (символов: 16519)