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

Anchored VWAP Origin Chronicle - Manual Swing High and Low

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

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

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

О программе

Этот индикатор TradingView на Pine Script v6 отображает на графике несколько линий Anchored VWAP (AVWAP), привязанных к разным начальным точкам. Ручная линия строится от выбранной пользователем точки, а две автоматические линии — от подтверждённых локальных максимумов и минимумов. Индикатор накладывается на график цены и не является торговым советником или стратегией: он не выполняет сделки и не содержит тестера.

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

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

Индикатор поддерживает динамические оповещения о новых подтверждённых привязках, пересечениях цены с линиями AVWAP, смене взаимного расположения линий, сближении пары AVWAP и смене их порядка. Все события подтверждаются только на закрытии бара.

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

НастройкаОписание
showManual Отображает ручную линию AVWAP, начинающуюся с выбранного пользователем бара.
hideManualWhenOriginOutsideView Скрывает ручную линию AVWAP, когда её начальная точка находится за пределами видимой области графика.
manualAnchorPriceInput Ценовое значение для размещения маркера ручной привязки. Не влияет на расчёт AVWAP.
manualAnchorTimeInput Время начала ручной линии AVWAP. Первый бар с открытием не раньше указанного времени становится началом расчёта.
showSwingHigh Отображает автоматическую линию AVWAP от подтверждённого локального максимума.
showSwingLow Отображает автоматическую линию AVWAP от подтверждённого локального минимума.
swingLeft Количество баров слева от кандидата в пивот для его подтверждения.
swingRight Количество баров справа, необходимое для подтверждения пивота. Автоматические привязки не активируются раньше этого срока.
minimumProminenceAtr Минимальная локальная значимость пивота в единицах ATR для принятия автоматической привязки.
minimumBarsBetweenSameType Минимальное количество баров между однотипными автоматическими привязками, чтобы избежать слишком частой замены.
replacementPolicy Политика замены автоматических привязок: Latest qualified, More prominent only или New price extreme only.
prominenceImprovementAtr Минимальное улучшение значимости в единицах ATR для замены активной привязки при политике More prominent only.
useRelativeVolumeFilter Требует, чтобы объём на баре пивота соответствовал заданному отношению к среднему объёму для принятия автоматической привязки.
relativeVolumeLength Длина периода для расчёта среднего объёма при оценке относительного объёма.
minimumRelativeVolume Минимальное отношение объёма на баре пивота к его среднему значению для принятия привязки при включённом фильтре относительного объёма.
vwapSource Источник цены, умножаемый на объём графика при расчёте AVWAP.
contextSource Источник цены, используемый для определения пересечений и классификации положения цены относительно линий AVWAP.
atrLength Длина периода для расчёта ATR, используемого при оценке значимости пивотов и разницы между линиями AVWAP.
convergenceThresholdAtr Порог сближения пары автоматических AVWAP в единицах ATR. При значении не выше порога пара считается сближенной.
allowNonStandardCharts Разрешает работу индикатора на типах графиков с расчётными ценами, таких как Heikin Ashi, Renko, Kagi, Line Break, Point and Figure и Range. По умолчанию отключено.
minimumVolumeCoveragePercent Минимальный процент покрытия объёмом в видимой области для статуса READY в панели. Не влияет на формулу AVWAP.
showPairFill Заливает область между автоматическими линиями AVWAP от максимума и минимума.
showContrastHalo Рисует более широкую тёмную линию под каждой яркой линией AVWAP для контраста.
showPrecisionCore Добавляет тонкую светлую линию внутри каждой цветной линии AVWAP для точного отображения пути.
precisionCoreTransparency Прозрачность тонкой линии точности внутри каждой цветной линии AVWAP.
showConvergedPairSpine Подсвечивает сближенные автоматические линии AVWAP тонкой линией по их средней точке.
showActiveLineEndpoints Показывает компактные символы на последнем видимом значении каждой активной линии AVWAP.
showAnchorMarkers Показывает маркеры начальных точек: M для ручной привязки, H и L для подтверждённых пивотов.
showConfirmationMarkers Показывает маркеры на баре, когда автоматическая привязка становится известна. По умолчанию отключено.
showConfirmationBridges Показывает пунктирные линии между баром пивота и баром его подтверждения.
confirmationMarkerStyle Стиль маркера подтверждения: значок C или точка. Используется только при включённых маркерах подтверждения.
showCrossMarkers Показывает маркеры подтверждённых пересечений цены с активными линиями AVWAP. По умолчанию отключено.
showConvergenceMarkers Показывает маркеры в моменты входа пары автоматических AVWAP в состояние сближения. По умолчанию отключено.
showPairOrderMarkers Показывает маркеры подтверждённых пересечений между линиями AVWAP от максимума и минимума. По умолчанию отключено.
eventMarkerWidth Ширина маркеров событий: пересечений, сближения и смены порядка пары.
markerHistory Максимальное количество подтверждённых событий пивотов, для которых сохраняются метки, маркеры подтверждения и соединительные линии в видимой области.
mainLineWidth Ширина основных линий AVWAP.
haloExtraWidth Дополнительная ширина гало относительно основной линии AVWAP.
haloTransparency Прозрачность контрастного гало линий AVWAP.
pairFillTransparency Прозрачность заливки между автоматическими линиями AVWAP.
manualColor Цвет ручной линии AVWAP.
swingHighColor Цвет автоматической линии AVWAP от подтверждённого максимума.
swingLowColor Цвет автоматической линии AVWAP от подтверждённого минимума.
betweenColor Цвет заливки между линиями AVWAP, когда цена находится между ними.
pairEventColor Цвет маркеров событий пары AVWAP и сближенной пары.
haloColor Цвет контрастного гало под линиями AVWAP для лучшей видимости на светлых и тёмных графиках.
showReadout Показывает панель статуса с текущими значениями AVWAP, состоянием привязок и качеством данных.
readoutPositionInput Положение панели статуса на графике: Top Right, Top Left, Bottom Right или Bottom Left.
readoutRightPaddingPercent Процент ширины панели, зарезервированный справа для меток шкалы High и Low при расположении панели справа.
readoutSizeInput Размер текста в панели статуса: Tiny, Small, Normal или Large.
readoutTransparency Прозрачность фона панели статуса.
enableAlerts Включает динамические оповещения. После включения необходимо создать одно оповещение TradingView с условием Any alert() function call.
alertOnNewAnchors Включает оповещение при появлении новой подтверждённой автоматической привязки от пивота.
alertOnPriceCrosses Включает оповещение при подтверждённом пересечении цены с активными линиями AVWAP.
alertOnPairTransitions Включает оповещение, когда цена переходит в положение выше обеих или ниже обеих автоматических линий AVWAP.
alertOnConvergence Включает оповещение, когда пара автоматических AVWAP входит в состояние сближения.
alertOnPairOrderFlip Включает оповещение при смене взаимного порядка линий AVWAP от максимума и минимума.
Получить полный код

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

indicator(
     title = "Anchored VWAP Origin Chronicle - Manual Swing High and Low",
     shorttitle = "Anchored VWAP Origin Chronicle",
     overlay = true,
     max_bars_back = 1000,
     max_labels_count = 300,
     max_lines_count = 200,
     explicit_plot_zorder = true,
     behind_chart = false)

const string GROUP_MANUAL = "1. Manual Anchor"
const string GROUP_SWINGS = "2. Confirmed Swing Anchors"
const string GROUP_CALC = "3. Calculation"
const string GROUP_VISUALS = "4. Visuals"
const string GROUP_READOUT = "5. Anchor Readout"
const string GROUP_ALERTS = "6. Alerts"

bool showManual = input.bool(
     true,
     "Show manual AVWAP",
     group = GROUP_MANUAL,
     tooltip = "Displays a VWAP beginning on the bar selected by the interactive anchor point.",
     display = display.none)

bool hideManualWhenOriginOutsideView = input.bool(
     true,
     "Hide manual AVWAP when origin is outside view",
     group = GROUP_MANUAL,
     tooltip = "Keeps the chart focused on the current visible time range. Disable this only when you intentionally want a manual AVWAP to remain visible after its anchor has moved outside the viewport.",
     display = display.none)

float manualAnchorPriceInput = input.price(
     0.0,
     "Manual anchor",
     inline = "manualPoint",
     group = GROUP_MANUAL,
     confirm = true,
     tooltip = "The selected price positions the M marker only. It does not alter the VWAP calculation.",
     display = display.none)

int manualAnchorTimeInput = input.time(
     timestamp("01 Jan 2024 00:00 +0000"),
     "",
     inline = "manualPoint",
     group = GROUP_MANUAL,
     confirm = true,
     tooltip = "Click an important chart point when adding the script. Time selects the first included bar; price positions the M marker only.",
     display = display.none)

bool showSwingHigh = input.bool(
     true,
     "Show confirmed swing-high AVWAP",
     group = GROUP_SWINGS,
     display = display.none)

bool showSwingLow = input.bool(
     true,
     "Show confirmed swing-low AVWAP",
     group = GROUP_SWINGS,
     display = display.none)

int swingLeft = input.int(
     8,
     "Pivot bars left",
     minval = 1,
     maxval = 50,
     group = GROUP_SWINGS,
     tooltip = "Bars required to the left of a candidate pivot.",
     display = display.none)

int swingRight = input.int(
     5,
     "Pivot bars right",
     minval = 1,
     maxval = 50,
     group = GROUP_SWINGS,
     tooltip = "Bars required to the right before a pivot is confirmed. Automatic anchors never activate before this delay has elapsed.",
     display = display.none)

float minimumProminenceAtr = input.float(
     1.00,
     "Minimum local prominence in ATR",
     minval = 0.0,
     maxval = 20.0,
     step = 0.05,
     group = GROUP_SWINGS,
     tooltip = "A high must stand this many ATR above the completed pivot window low. A low must stand this many ATR below the completed pivot window high.",
     display = display.none)

int minimumBarsBetweenSameType = input.int(
     15,
     "Minimum bars between same-type anchors",
     minval = 0,
     maxval = 1000,
     group = GROUP_SWINGS,
     tooltip = "Reduces rapid replacement of one high-origin anchor by another high, and likewise for low-origin anchors.",
     display = display.none)

string replacementPolicy = input.string(
     "Latest qualified",
     "Automatic anchor replacement policy",
     options = ["Latest qualified", "More prominent only", "New price extreme only"],
     group = GROUP_SWINGS,
     tooltip = "Latest qualified follows every accepted swing. More prominent only requires an ATR-prominence improvement. New price extreme only requires a higher high or lower low.",
     display = display.none)

float prominenceImprovementAtr = input.float(
     0.10,
     "Prominence improvement margin in ATR",
     minval = 0.0,
     maxval = 20.0,
     step = 0.05,
     group = GROUP_SWINGS,
     tooltip = "Used by More prominent only. A replacement must improve on the active same-type origin by at least this ATR-normalized amount.",
     display = display.none)

bool useRelativeVolumeFilter = input.bool(
     false,
     "Require relative volume at swing origin",
     group = GROUP_SWINGS,
     tooltip = "When enabled, an automatic origin is accepted only when chart-reported volume on the pivot bar meets the selected ratio versus its moving average.",
     display = display.none)

int relativeVolumeLength = input.int(
     50,
     "Relative volume average length",
     minval = 2,
     maxval = 500,
     group = GROUP_SWINGS,
     display = display.none)

float minimumRelativeVolume = input.float(
     1.00,
     "Minimum relative volume ratio",
     minval = 0.0,
     maxval = 20.0,
     step = 0.05,
     group = GROUP_SWINGS,
     display = display.none)

float vwapSource = input.source(
     hlc3,
     "VWAP source",
     group = GROUP_CALC,
     tooltip = "Price source multiplied by the volume series supplied by the chart.",
     display = display.none)

float contextSource = input.source(
     close,
     "Price-context source",
     group = GROUP_CALC,
     tooltip = "Used only for confirmed cross events and the above, between, or below pair classification.",
     display = display.none)

int atrLength = input.int(
     14,
     "ATR length",
     minval = 1,
     maxval = 500,
     group = GROUP_CALC,
     tooltip = "Used for swing-prominence normalization and the swing-pair spread readout.",
     display = display.none)

float convergenceThresholdAtr = input.float(
     0.25,
     "Pair convergence threshold in ATR",
     minval = 0.0,
     maxval = 10.0,
     step = 0.05,
     group = GROUP_CALC,
     tooltip = "The two automatic AVWAPs are classified as converged at or below this ATR-normalized separation.",
     display = display.none)

bool allowNonStandardCharts = input.bool(
     false,
     "Allow calculated-price chart types",
     group = GROUP_CALC,
     tooltip = "Disabled by default. Heikin Ashi, Renko, Kagi, Line Break, Point and Figure, and Range charts use calculated prices. Enable only when you intentionally want this script to use those chart prices.",
     display = display.none)

float minimumVolumeCoveragePercent = input.float(
     90.0,
     "Minimum volume coverage for READY status",
     minval = 1.0,
     maxval = 100.0,
     step = 1.0,
     group = GROUP_CALC,
     tooltip = "Classifies volume coverage in the readout. It never fills missing volume and never changes the AVWAP formula.",
     display = display.none)

bool showPairFill = input.bool(
     true,
     "Fill between swing-origin AVWAPs",
     group = GROUP_VISUALS,
     display = display.none)

bool showContrastHalo = input.bool(
     true,
     "Use high-contrast line halo",
     group = GROUP_VISUALS,
     tooltip = "Draws a wider dark line below each bright AVWAP for visibility on both light and dark charts.",
     display = display.none)

bool showPrecisionCore = input.bool(
     true,
     "Show thin precision core",
     group = GROUP_VISUALS,
     tooltip = "Adds a one-pixel light center trace inside each colored AVWAP. This keeps the exact path readable when candles or filled areas use similar colors.",
     display = display.none)

int precisionCoreTransparency = input.int(
     58,
     "Precision core transparency",
     minval = 0,
     maxval = 95,
     group = GROUP_VISUALS,
     display = display.none)

bool showConvergedPairSpine = input.bool(
     true,
     "Highlight overlapping swing AVWAPs",
     group = GROUP_VISUALS,
     tooltip = "Draws a thin amber spine at the midpoint while the high-origin and low-origin AVWAPs are within the configured convergence threshold. It identifies overlap without moving either AVWAP.",
     display = display.none)

bool showActiveLineEndpoints = input.bool(
     true,
     "Show active AVWAP endpoints",
     group = GROUP_VISUALS,
     tooltip = "Adds one compact symbol at the latest visible value of each active AVWAP: diamond for manual, downward triangle for high origin, and upward triangle for low origin.",
     display = display.none)

bool showAnchorMarkers = input.bool(
     true,
     "Show origin markers",
     group = GROUP_VISUALS,
     tooltip = "M is the manual point. H and L mark confirmed pivot origins.",
     display = display.none)

bool showConfirmationMarkers = input.bool(
     false,
     "Show confirmation markers",
     group = GROUP_VISUALS,
     tooltip = "Optional markers identify the later bar where each automatic pivot became knowable. They are hidden by default to keep the publication view clean.",
     display = display.none)

bool showConfirmationBridges = input.bool(
     true,
     "Show pivot-to-confirmation bridges",
     group = GROUP_VISUALS,
     tooltip = "A dotted bridge makes the automatic pivot confirmation delay explicit instead of implying that the origin was known on the pivot bar.",
     display = display.none)

string confirmationMarkerStyle = input.string(
     "C badge",
     "Confirmation marker style",
     options = ["C badge", "Dot"],
     group = GROUP_VISUALS,
     tooltip = "Used only when confirmation markers are enabled. C badge is explicit; Dot is more compact.",
     display = display.none)

bool showCrossMarkers = input.bool(
     false,
     "Show confirmed price-cross markers",
     group = GROUP_VISUALS,
     tooltip = "Small circles mark bar-close crosses of active AVWAPs. They are factual events, not trade signals.",
     display = display.none)

bool showConvergenceMarkers = input.bool(
     false,
     "Show pair-convergence markers",
     group = GROUP_VISUALS,
     display = display.none)

bool showPairOrderMarkers = input.bool(
     false,
     "Show swing-pair order-flip markers",
     group = GROUP_VISUALS,
     tooltip = "Marks confirmed crosses between the high-origin and low-origin AVWAP curves. These are relationship events, not trade signals.",
     display = display.none)

int eventMarkerWidth = input.int(
     3,
     "Event marker width",
     minval = 1,
     maxval = 5,
     group = GROUP_VISUALS,
     tooltip = "Controls optional cross, convergence-event, and pair-order markers. These markers are hidden by default to keep the AVWAP paths unobstructed.",
     display = display.none)

int markerHistory = input.int(
     18,
     "Confirmed swing events retained",
     minval = 1,
     maxval = 80,
     group = GROUP_VISUALS,
     tooltip = "Limits H/L origin labels, optional confirmation markers, and dotted confirmation bridges retained inside the current visible chart range.",
     display = display.none)

int mainLineWidth = input.int(
     2,
     "Main line width",
     minval = 1,
     maxval = 6,
     group = GROUP_VISUALS,
     display = display.none)

int haloExtraWidth = input.int(
     2,
     "Halo extra width",
     minval = 1,
     maxval = 6,
     group = GROUP_VISUALS,
     display = display.none)

int haloTransparency = input.int(
     10,
     "Halo transparency",
     minval = 0,
     maxval = 100,
     group = GROUP_VISUALS,
     display = display.none)

int pairFillTransparency = input.int(
     84,
     "Pair fill transparency",
     minval = 0,
     maxval = 100,
     group = GROUP_VISUALS,
     display = display.none)

color manualColor = input.color(
     color.rgb(0, 229, 255),
     "Manual AVWAP color",
     group = GROUP_VISUALS,
     display = display.none)

color swingHighColor = input.color(
     color.rgb(255, 61, 141),
     "Swing-high AVWAP color",
     group = GROUP_VISUALS,
     display = display.none)

color swingLowColor = input.color(
     color.rgb(57, 255, 136),
     "Swing-low AVWAP color",
     group = GROUP_VISUALS,
     display = display.none)

color betweenColor = input.color(
     color.rgb(124, 77, 255),
     "Between-pair fill color",
     group = GROUP_VISUALS,
     display = display.none)

color pairEventColor = input.color(
     color.rgb(255, 202, 40),
     "Pair relationship event color",
     group = GROUP_VISUALS,
     display = display.none)

color haloColor = input.color(
     color.rgb(5, 8, 15),
     "Contrast halo color",
     group = GROUP_VISUALS,
     display = display.none)

bool showReadout = input.bool(
     true,
     "Show anchor readout",
     group = GROUP_READOUT,
     display = display.none)

string readoutPositionInput = input.string(
     "Top Right",
     "Readout position",
     options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"],
     group = GROUP_READOUT,
     tooltip = "Right-side positions keep the panel in the chart corner while reserving only a small transparent clearance for right-axis High and Low labels.",
     display = display.none)

int readoutRightPaddingPercent = input.int(
     2,
     "Right-axis clearance percent",
     minval = 1,
     maxval = 10,
     group = GROUP_READOUT,
     tooltip = "Small transparent clearance between a right-side panel and the price scale, measured as a percentage of pane width. The two-percent default keeps the panel distinctly upper-right while preserving room for High and Low scale labels.",
     display = display.none)

string readoutSizeInput = input.string(
     "Normal",
     "Readout text size",
     options = ["Tiny", "Small", "Normal", "Large"],
     group = GROUP_READOUT,
     display = display.none)

int readoutTransparency = input.int(
     4,
     "Readout background transparency",
     minval = 0,
     maxval = 100,
     group = GROUP_READOUT,
     display = display.none)

bool enableAlerts = input.bool(
     false,
     "Enable dynamic alerts",
     group = GROUP_ALERTS,
     tooltip = "After enabling this input, create one TradingView alert using Any alert() function call.",
     display = display.none)

bool alertOnNewAnchors = input.bool(
     true,
     "Alert on new confirmed swing anchors",
     group = GROUP_ALERTS,
     display = display.none)

bool alertOnPriceCrosses = input.bool(
     true,
     "Alert on confirmed AVWAP crosses",
     group = GROUP_ALERTS,
     display = display.none)

bool alertOnPairTransitions = input.bool(
     true,
     "Alert when price enters above-both or below-both context",
     group = GROUP_ALERTS,
     display = display.none)

bool alertOnConvergence = input.bool(
     true,
     "Alert when the swing pair enters convergence",
     group = GROUP_ALERTS,
     display = display.none)

bool alertOnPairOrderFlip = input.bool(
     true,
     "Alert when swing-origin AVWAP order flips",
     group = GROUP_ALERTS,
     display = display.none)

f_tablePosition(string value) =>
    switch value
        "Top Left" => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left" => position.bottom_left
        => position.top_right

f_textSize(string value) =>
    switch value
        "Tiny" => 9
        "Small" => 11
        "Large" => 15
        => 13

f_appendEvent(string currentText, string newText) =>
    currentText == "" ? newText : currentText + "\n" + newText

f_compensatedAdd(float runningTotal, float correction, float value) =>
    float adjustedValue = value - correction
    float updatedTotal = runningTotal + adjustedValue
    float updatedCorrection = (updatedTotal - runningTotal) - adjustedValue
    [updatedTotal, updatedCorrection]

f_chartTypeText() =>
    switch
        chart.is_standard => "STANDARD"
        chart.is_heikinashi => "HEIKIN ASHI"
        chart.is_renko => "RENKO"
        chart.is_kagi => "KAGI"
        chart.is_linebreak => "LINE BREAK"
        chart.is_pnf => "POINT & FIGURE"
        chart.is_range => "RANGE"
        => "NON-STANDARD"

f_volumeTypeText() =>
    switch syminfo.volumetype
        "base" => "BASE"
        "quote" => "QUOTE"
        "tick" => "TICK"
        "n/a" => "N/A"
        => "OTHER"

f_percentText(float value) =>
    na(value) ? "n/a" : str.tostring(value, "#.0") + "%"

bool chartTypeAllowed = chart.is_standard or allowNonStandardCharts
float chartWeight = chartTypeAllowed and not na(vwapSource) and not na(volume) and volume > 0 ? volume : 0.0
float weightedPrice = chartWeight > 0 ? vwapSource * chartWeight : 0.0
int usableBarFlag = chartWeight > 0 ? 1 : 0
float atrValue = ta.atr(atrLength)
float volumeForAverage = not na(volume) and volume >= 0 ? volume : na
float relativeVolumeBasis = ta.sma(volumeForAverage, relativeVolumeLength)
var int datasetFirstTime = time

int visibleLeftTime = chart.left_visible_bar_time
int visibleRightTime = chart.right_visible_bar_time
bool barInVisibleWindow = time >= visibleLeftTime and time <= visibleRightTime
bool barIsVisibleRightEdge = time == visibleRightTime
bool viewportIncludesLatestBar = visibleRightTime == last_bar_time

var int visibleBarsObserved = 0
var int visibleUsableBars = 0
var int visibleManualObservedBars = 0
var int visibleManualUsableBars = 0
var int visibleHighObservedBars = 0
var int visibleHighUsableBars = 0
var int visibleLowObservedBars = 0
var int visibleLowUsableBars = 0

var bool manualStarted = false
var int manualAnchorBar = na
var int manualActualAnchorTime = na
var float manualWeightedSum = 0.0
var float manualWeightedCorrection = 0.0
var float manualWeightSum = 0.0
var float manualWeightCorrection = 0.0
var label manualOriginLabel = na

bool manualAnchorBeforeDataset = manualAnchorTimeInput < datasetFirstTime
bool manualStartsNow = showManual and chartTypeAllowed and not manualAnchorBeforeDataset and not manualStarted and time >= manualAnchorTimeInput

if manualStartsNow
    manualStarted := true
    manualAnchorBar := bar_index
    manualActualAnchorTime := time
    manualWeightedSum := weightedPrice
    manualWeightedCorrection := 0.0
    manualWeightSum := chartWeight
    manualWeightCorrection := 0.0

    if showAnchorMarkers and barInVisibleWindow
        if not na(manualOriginLabel)
            label.delete(manualOriginLabel)
        manualOriginLabel := label.new(
             x = manualAnchorBar,
             y = manualAnchorPriceInput,
             text = "M",
             xloc = xloc.bar_index,
             yloc = yloc.price,
             color = manualColor,
             style = label.style_label_left,
             textcolor = color.rgb(5, 8, 15),
             size = size.small,
             text_formatting = text.format_bold,
             tooltip = "Manual anchor point\nThe selected time starts the AVWAP.\nThe selected price positions this marker only.")
else if manualStarted
    [nextManualWeightedSum, nextManualWeightedCorrection] = f_compensatedAdd(manualWeightedSum, manualWeightedCorrection, weightedPrice)
    [nextManualWeightSum, nextManualWeightCorrection] = f_compensatedAdd(manualWeightSum, manualWeightCorrection, chartWeight)
    manualWeightedSum := nextManualWeightedSum
    manualWeightedCorrection := nextManualWeightedCorrection
    manualWeightSum := nextManualWeightSum
    manualWeightCorrection := nextManualWeightCorrection

float manualAvwap = manualStarted and manualWeightSum > 0 ? manualWeightedSum / manualWeightSum : na
var table wm = table.new(position.bottom_right, 1, 1)
if barstate.isfirst
    table.cell(wm, 0, 0, "Telegram @SimpleForexTools", text_color = color.new(color.gray, 70), text_size = size.large)

int pivotWindow = swingLeft + swingRight + 1
float confirmedHigh = ta.pivothigh(high, swingLeft, swingRight)
float confirmedLow = ta.pivotlow(low, swingLeft, swingRight)
float localWindowLow = ta.lowest(low, pivotWindow)
float localWindowHigh = ta.highest(high, pivotWindow)
float pivotAtr = atrValue[swingRight]
float pivotVolume = volume[swingRight]
float pivotVolumeMean = relativeVolumeBasis[swingRight]
float pivotRelativeVolume = not na(pivotVolume) and not na(pivotVolumeMean) and pivotVolumeMean > 0 ? pivotVolume / pivotVolumeMean : na
float highProminenceAtr = not na(confirmedHigh) and not na(pivotAtr) and pivotAtr > 0 ? (confirmedHigh - localWindowLow) / pivotAtr : na
float lowProminenceAtr = not na(confirmedLow) and not na(pivotAtr) and pivotAtr > 0 ? (localWindowHigh - confirmedLow) / pivotAtr : na
int candidateAnchorBar = bar_index - swingRight
int candidateAnchorTime = time[swingRight]

var int highAnchorBar = na
var int highAnchorTime = na
var int highAnchorSerial = 0
var float highAnchorPrice = na
var float highAnchorProminence = na
var float highWeightedSum = 0.0
var float highWeightedCorrection = 0.0
var float highWeightSum = 0.0
var float highWeightCorrection = 0.0

var int lowAnchorBar = na
var int lowAnchorTime = na
var int lowAnchorSerial = 0
var float lowAnchorPrice = na
var float lowAnchorProminence = na
var float lowWeightedSum = 0.0
var float lowWeightedCorrection = 0.0
var float lowWeightSum = 0.0
var float lowWeightCorrection = 0.0

bool highCandidate = not na(confirmedHigh)
bool lowCandidate = not na(confirmedLow)
bool relativeVolumePass = not useRelativeVolumeFilter or (not na(pivotRelativeVolume) and pivotRelativeVolume >= minimumRelativeVolume)
bool highProminencePass = highCandidate and not na(highProminenceAtr) and highProminenceAtr >= minimumProminenceAtr
bool lowProminencePass = lowCandidate and not na(lowProminenceAtr) and lowProminenceAtr >= minimumProminenceAtr
bool highCooldownPass = na(highAnchorBar) or candidateAnchorBar - highAnchorBar >= minimumBarsBetweenSameType
bool lowCooldownPass = na(lowAnchorBar) or candidateAnchorBar - lowAnchorBar >= minimumBarsBetweenSameType
bool highReplacementPass = na(highAnchorBar) or replacementPolicy == "Latest qualified" or (replacementPolicy == "More prominent only" and highProminenceAtr >= highAnchorProminence + prominenceImprovementAtr) or (replacementPolicy == "New price extreme only" and confirmedHigh > highAnchorPrice)
bool lowReplacementPass = na(lowAnchorBar) or replacementPolicy == "Latest qualified" or (replacementPolicy == "More prominent only" and lowProminenceAtr >= lowAnchorProminence + prominenceImprovementAtr) or (replacementPolicy == "New price extreme only" and confirmedLow < lowAnchorPrice)
bool acceptHighAnchor = barstate.isconfirmed and chartTypeAllowed and showSwingHigh and highCandidate and highProminencePass and relativeVolumePass and highCooldownPass and highReplacementPass
bool acceptLowAnchor = barstate.isconfirmed and chartTypeAllowed and showSwingLow and lowCandidate and lowProminencePass and relativeVolumePass and lowCooldownPass and lowReplacementPass

var array<label> originMarkerLabels = array.new<label>()
var array<label> confirmationMarkerLabels = array.new<label>()
var array<line> confirmationBridgeLines = array.new<line>()

bool confirmationKnownByVisibleRight = time <= visibleRightTime
bool candidateOriginInVisibleWindow = not na(candidateAnchorTime) and candidateAnchorTime >= visibleLeftTime and candidateAnchorTime <= visibleRightTime
bool confirmationInVisibleWindow = barInVisibleWindow
bool confirmationBridgeIntersectsVisibleWindow = confirmationKnownByVisibleRight and not na(candidateAnchorTime) and candidateAnchorTime <= visibleRightTime and time >= visibleLeftTime

if acceptHighAnchor
    highAnchorBar := candidateAnchorBar
    highAnchorTime := candidateAnchorTime
    highAnchorPrice := confirmedHigh
    highAnchorProminence := highProminenceAtr
    highAnchorSerial += 1

    float highSeedWeightedSum = 0.0
    float highSeedWeightedCorrection = 0.0
    float highSeedWeightSum = 0.0
    float highSeedWeightCorrection = 0.0

    for seedOffset = swingRight to 0
        if not na(time[seedOffset])
            float seedWeightedValue = nz(weightedPrice[seedOffset], 0.0)
            float seedWeightedAdjusted = seedWeightedValue - highSeedWeightedCorrection
            float seedWeightedUpdated = highSeedWeightedSum + seedWeightedAdjusted
            highSeedWeightedCorrection := (seedWeightedUpdated - highSeedWeightedSum) - seedWeightedAdjusted
            highSeedWeightedSum := seedWeightedUpdated

            float seedWeightValue = nz(chartWeight[seedOffset], 0.0)
            float seedWeightAdjusted = seedWeightValue - highSeedWeightCorrection
            float seedWeightUpdated = highSeedWeightSum + seedWeightAdjusted
            highSeedWeightCorrection := (seedWeightUpdated - highSeedWeightSum) - seedWeightAdjusted
            highSeedWeightSum := seedWeightUpdated

    highWeightedSum := highSeedWeightedSum
    highWeightedCorrection := highSeedWeightedCorrection
    highWeightSum := highSeedWeightSum
    highWeightCorrection := highSeedWeightCorrection

    string highTooltip = "Confirmed swing-high AVWAP origin\nOrigin: " +
         str.format_time(candidateAnchorTime, "yyyy-MM-dd HH:mm", syminfo.timezone) +
         "\nProminence: " + str.tostring(highProminenceAtr, "#.##") + " ATR" +
         (useRelativeVolumeFilter ? "\nRelative volume: " + str.tostring(pivotRelativeVolume, "#.##") + "x" : "") +
         "\nConfirmed " + str.tostring(swingRight) + " bar(s) later."

    if showAnchorMarkers and confirmationKnownByVisibleRight and candidateOriginInVisibleWindow
        label highOriginMarker = label.new(
             x = candidateAnchorBar,
             y = confirmedHigh,
             text = "H",
             xloc = xloc.bar_index,
             yloc = yloc.price,
             color = swingHighColor,
             style = label.style_label_down,
             textcolor = color.white,
             size = size.small,
             text_formatting = text.format_bold,
             tooltip = highTooltip)
        array.push(originMarkerLabels, highOriginMarker)

    if showConfirmationMarkers and confirmationInVisibleWindow
        label highConfirmationMarker = label.new(
             x = bar_index,
             y = confirmedHigh,
             text = confirmationMarkerStyle == "C badge" ? "C" : "",
             xloc = xloc.bar_index,
             yloc = yloc.price,
             color = color.new(swingHighColor, confirmationMarkerStyle == "C badge" ? 12 : 0),
             style = confirmationMarkerStyle == "C badge" ? label.style_label_left : label.style_circle,
             textcolor = color.white,
             size = size.tiny,
             text_formatting = text.format_bold,
             tooltip = "Confirmation bar\nThe high-origin anchor becomes available only here.")
        array.push(confirmationMarkerLabels, highConfirmationMarker)

    if showConfirmationBridges and confirmationBridgeIntersectsVisibleWindow
        line highBridge = line.new(
             x1 = candidateAnchorBar,
             y1 = confirmedHigh,
             x2 = bar_index,
             y2 = confirmedHigh,
             xloc = xloc.bar_index,
             extend = extend.none,
             color = color.new(swingHighColor, 35),
             style = line.style_dotted,
             width = 2)
        array.push(confirmationBridgeLines, highBridge)
else if not na(highAnchorBar)
    [nextHighWeightedSum, nextHighWeightedCorrection] = f_compensatedAdd(highWeightedSum, highWeightedCorrection, weightedPrice)
    [nextHighWeightSum, nextHighWeightCorrection] = f_compensatedAdd(highWeightSum, highWeightCorrection, chartWeight)
    highWeightedSum := nextHighWeightedSum
    highWeightedCorrection := nextHighWeightedCorrection
    highWeightSum := nextHighWeightSum
    highWeightCorrection := nextHighWeightCorrection

if acceptLowAnchor
    lowAnchorBar := candidateAnchorBar
    lowAnchorTime := candidateAnchorTime
    lowAnchorPrice := confirmedLow
    lowAnchorProminence := lowProminenceAtr
    lowAnchorSerial += 1

    float lowSeedWeightedSum = 0.0
    float lowSeedWeightedCorrection = 0.0
    float lowSeedWeightSum = 0.0
    float lowSeedWeightCorrection = 0.0

    for seedOffset = swingRight to 0
        if not na(time[seedOffset])
            float seedWeightedValue = nz(weightedPrice[seedOffset], 0.0)
            float seedWeightedAdjusted = seedWeightedValue - lowSeedWeightedCorrection
            float seedWeightedUpdated = lowSeedWeightedSum + seedWeightedAdjusted
            lowSeedWeightedCorrection := (seedWeightedUpdated - lowSeedWeightedSum) - seedWeightedAdjusted
            lowSeedWeightedSum := seedWeightedUpdated

            float seedWeightValue = nz(chartWeight[seedOffset], 0.0)
            float seedWeightAdjusted = seedWeightValue - lowSeedWeightCorrection
            float seedWeightUpdated = lowSeedWeightSum + seedWeightAdjusted
            lowSeedWeightCorrection := (seedWeightUpdated - lowSeedWeightSum) - seedWeightAdjusted
            lowSeedWeightSum := seedWeightUpdated

    lowWeightedSum := lowSeedWeightedSum
    lowWeightedCorrection := lowSeedWeightedCorrection
    lowWeightSum := lowSeedWeightSum
    lowWeightCorrection := lowSeedWeightCorrection

    string lowTooltip = "Confirmed swing-low AVWAP origin\nOrigin: " +
         str.format_time(candidateAnchorTime, "yyyy-MM-dd HH:mm", syminfo.timezone) +
         "\nProminence: " + str.tostring(lowProminenceAtr, "#.##") + " ATR" +
         (useRelativeVolumeFilter ? "\nRelative volume: " + str.tostring(pivotRelativeVolume, "#.##") + "x" : "") +
         "\nConfirmed " + str.tostring(swingRight) + " bar(s) later."

    if showAnchorMarkers and confirmationKnownByVisibleRight and candidateOriginInVisibleWindow
        label lowOriginMarker = label.new(
             x = candidateAnchorBar,
             y = confirmedLow,
             text = "L",
             xloc = xloc.bar_index,
             yloc = yloc.price,
             color = swingLowColor,
             style = label.style_label_up,
             textcolor = color.rgb(5, 8, 15),
             size = size.small,
             text_formatting = text.format_bold,
             tooltip = lowTooltip)
        array.push(originMarkerLabels, lowOriginMarker)

    if showConfirmationMarkers and confirmationInVisibleWindow
        label lowConfirmationMarker = label.new(
             x = bar_index,
             y = confirmedLow,
             text = confirmationMarkerStyle == "C badge" ? "C" : "",
             xloc = xloc.bar_index,
             yloc = yloc.price,
             color = color.new(swingLowColor, confirmationMarkerStyle == "C badge" ? 12 : 0),
             style = confirmationMarkerStyle == "C badge" ? label.st

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

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
4 876,20₽ ≈ $59.60