IMD Fibo - Nested Fibonacci Levels

IMD_Department · study · 361 行 · 点赞 7 · TradingView 原页

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

Pine Script

//@version=6
// IMD Fibo - port of IMDFibo5.mq5 v5.13. Original author: IMD Team · M.F.
// Required Notice: Copyright IMD Team. All rights reserved.
// Licensed under PolyForm Noncommercial License 1.0.0:
// https://polyformproject.org/licenses/noncommercial/1.0.0
// ADDITIONAL PERMISSION FOR PERSONAL TRADING:
// In addition to the purposes permitted by that license, an individual may use
// this software, including personally modified copies, to analyze markets and
// trade solely for that individual's own account using their own funds,
// including with the intention of earning and retaining trading profits.
// This permission does not authorize selling or licensing the software for a
// fee, selling access to it, incorporating it into paid products or services,
// providing paid signals based on it, or managing or trading other persons'
// funds. Commercial uses outside this permission require a separate license
// from the copyright holder. The base license's conditions, including Notices,
// continue to apply. Copies must retain this additional permission as well.
// The source is available for inspection and modification under these terms.
// This indicator displays a CURRENT grid; it does not backtest trading signals.
// Default display: full nested grids in the current first-order zone and its neighbors.
indicator("IMD Fibo · Three Orders", shorttitle = "IMD Fibo", overlay = true, max_lines_count = 500, format = format.price)
 
// Pine does not expose click events for drawings. Use these native input toggles.
string GROUP_DISPLAY = "Показывать / Display"
bool show1 = input.bool(true, "1-й порядок", inline = "orders", group = GROUP_DISPLAY)
bool show2 = input.bool(true, "2-й порядок", inline = "orders", group = GROUP_DISPLAY)
bool show3 = input.bool(true, "3-й порядок", inline = "orders", group = GROUP_DISPLAY)
string gridMode = input.string("3 диапазона", "Сетка", options = ["3 диапазона", "Активная сетка", "Весь диапазон"], group = GROUP_DISPLAY, tooltip = "3 диапазона: полное деление до третьего порядка в текущем диапазоне первого порядка и двух соседних. У края выбираются три ближайших доступных. Активная сетка: исходный режим MT5. Весь диапазон: полная сетка во всех диапазонах.")
bool showLabels = input.bool(true, "Цены на правой шкале", group = GROUP_DISPLAY)
bool showLegend = input.bool(true, "Цветная легенда", group = GROUP_DISPLAY)
 
string GROUP_RANGE = "Historical range / Исторический диапазон"
string rangeMode = input.string("History", "Source / Источник", options = ["History", "Manual"], group = GROUP_RANGE)
int startDate = input.time(timestamp("01 Jan 1998 00:00 +0000"), "Since / С даты", group = GROUP_RANGE, tooltip = "Monthly history, as in the MT5 original. If the date falls inside a month, that month is excluded. Available history depends on the data provider.")
float manualHigh = input.float(0.0, "High / Максимум", group = GROUP_RANGE)
float manualLow = input.float(0.0, "Low / Минимум", group = GROUP_RANGE)
string priceMode = input.string("Last", "Active-zone price / Цена активной зоны", options = ["Last", "Bid", "Ask", "Mid"], group = GROUP_RANGE, tooltip = "TradingView exposes Bid/Ask only on 1T charts. If unavailable, Last is used and a warning is written to Pine Logs.")
 
string GROUP_FIB = "Fibonacci / Фибоначчи"
string levelsCSV = input.string("0,23.6,38.2,50,61.8,76.4,100", "Levels, % / Уровни, %", group = GROUP_FIB, tooltip = "Comma-separated percentages; decimal point. Up to 15 unique levels including 0 and 100. Invalid tokens are skipped. More than 15 levels restores defaults.")
 
string GROUP_GRID = "Grids / Сетки"
color color1 = input.color(color.rgb(151, 94, 224), "Сильный / 1-й порядок", inline = "o1", group = GROUP_GRID)
string style1 = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "o1", group = GROUP_GRID)
int lineTransparency1 = input.int(40, "Сильный: прозрачность, %", minval = 0, maxval = 100, group = GROUP_GRID, tooltip = "0 — непрозрачные, 100 — невидимые. Применяется к линиям первого порядка.")
color color2 = input.color(color.rgb(51, 136, 221), "Средний / 2-й порядок", inline = "o2", group = GROUP_GRID)
string style2 = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "o2", group = GROUP_GRID)
int lineTransparency2 = input.int(60, "Средний: прозрачность, %", minval = 0, maxval = 100, group = GROUP_GRID, tooltip = "0 — непрозрачные, 100 — невидимые. Применяется к линиям второго порядка.")
color color3 = input.color(color.rgb(194, 134, 24), "Слабый / 3-й порядок", inline = "o3", group = GROUP_GRID)
string style3 = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "o3", group = GROUP_GRID)
int lineTransparency3 = input.int(80, "Слабый: прозрачность, %", minval = 0, maxval = 100, group = GROUP_GRID, tooltip = "0 — непрозрачные, 100 — невидимые. Применяется к линиям третьего порядка.")
int lineWidth = input.int(2, "Width / Толщина", minval = 1, maxval = 5, group = GROUP_GRID)
 
string GROUP_LABELS = "Цены на шкале"
int maxPriceLabels = input.int(30, "Максимум цен", minval = 1, maxval = 30, group = GROUP_LABELS, tooltip = "Сначала сильные уровни, затем средние и слабые. Внутри каждого порядка — ближайшие к рыночной цене. Линии сетки сохраняются полностью.")
float labelGapPercent = input.float(2.5, "Интервал, % диапазона видимых свечей", minval = 0, maxval = 25, step = 0.5, group = GROUP_LABELS, tooltip = "Предварительное прореживание близких цен. Для точного устранения наложений включите «Не перекрывать метки» в настройках ценовой шкалы TradingView.")
float labelGapTicks = input.float(2, "Минимальный интервал, тики", minval = 1, group = GROUP_LABELS)
 
string legendPosition = input.string("Справа сверху", "Положение", options = ["Справа сверху", "Слева сверху", "Справа снизу", "Слева снизу"], group = "Легенда")
string legendSize = input.string("Крупный", "Размер текста", options = ["Обычный", "Крупный", "Очень крупный"], group = "Легенда")
 
type FibLevel
    float price
    int ord
    int idx
 
f_legend_position(string s) =>
    switch s
        "Слева сверху" => position.top_left
        "Справа снизу" => position.bottom_right
        "Слева снизу" => position.bottom_left
        => position.top_right
 
f_legend_size(string s) =>
    switch s
        "Обычный" => size.normal
        "Очень крупный" => size.huge
        => size.large
 
f_color(int o) =>
    o == 1 ? color1 : o == 2 ? color2 : color3
 
f_line_transparency(int o) =>
    o == 1 ? lineTransparency1 : o == 2 ? lineTransparency2 : lineTransparency3
 
f_style(int o) =>
    string s = o == 1 ? style1 : o == 2 ? style2 : style3
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
 
f_add_fraction(array<float> fs, float v) =>
    bool exists = false
    for old in fs
        if math.abs(old - v) < 1e-9
            exists := true
    if not exists
        array.push(fs, v)
 
f_is_number(string token) =>
    int digits = 0
    int dots = 0
    bool valid = str.length(token) > 0
    if valid
        for i = 0 to str.length(token) - 1
            string ch = str.substring(token, i, i + 1)
            if str.contains("0123456789", ch)
                digits += 1
            else if ch == "."
                dots += 1
            else if not (i == 0 and (ch == "+" or ch == "-"))
                valid := false
    valid and digits > 0 and dots <= 1
 
// Same monthly-bar inclusion and positive-low filter as the original.
f_monthly_range() =>
    var float hi = na
    var float lo = na
    if time >= startDate
        hi := na(hi) ? high : math.max(hi, high)
        if low > 0
            lo := na(lo) ? low : math.min(lo, low)
    [hi, lo]
 
f_interval(array<float> fs, float lo, float hi, float p) =>
    int found = -1
    float span = hi - lo
    for i = 0 to array.size(fs) - 2
        float a = lo + span * array.get(fs, i)
        float b = lo + span * array.get(fs, i + 1)
        // Inclusive boundaries, first matching interval, as in MQL5.
        if p >= a and p <= b
            found := i
            break
    found
 
f_add_grid(array<FibLevel> dest, array<float> fs, float lo, float hi, int o) =>
    for i = 0 to array.size(fs) - 1
        array.push(dest, FibLevel.new(lo + (hi - lo) * array.get(fs, i), o, i))
 
f_candidates(array<float> fs, float lo, float hi, float p, string mode) =>
    array<FibLevel> candidates = array.new<FibLevel>()
    int n = array.size(fs)
    int activeJ = f_interval(fs, lo, hi, p)
    bool full = mode == "Весь диапазон"
    bool threeZones = mode == "3 диапазона"
    // Keep three existing neighboring zones at the edges; do not extrapolate.
    int centerJ = activeJ
    if centerJ < 0
        centerJ := 0
        if p > lo + (hi - lo) * array.get(fs, n - 1)
            centerJ := n - 2
    int firstJ = math.max(0, math.min(centerJ - 1, n - 4))
    int lastJ = math.min(n - 2, firstJ + 2)
    if show1
        f_add_grid(candidates, fs, lo, hi, 1)
    for j = 0 to n - 2
        if full or (threeZones and j >= firstJ and j <= lastJ) or (not threeZones and j == activeJ)
            float a = lo + (hi - lo) * array.get(fs, j)
            float b = lo + (hi - lo) * array.get(fs, j + 1)
            if show2
                f_add_grid(candidates, fs, a, b, 2)
            int activeK = f_interval(fs, a, b, p)
            if show3
                for k = 0 to n - 2
                    if full or threeZones or k == activeK
                        float a2 = a + (b - a) * array.get(fs, k)
                        float b2 = a + (b - a) * array.get(fs, k + 1)
                        f_add_grid(candidates, fs, a2, b2, 3)
    candidates
 
f_dedupe(array<FibLevel> candidates) =>
    array<FibLevel> result = array.new<FibLevel>()
    array<float> prices = array.new_float()
    for candidate in candidates
        array.push(prices, candidate.price)
    array<int> indices = array.sort_indices(prices, order.ascending)
    int i = 0
    while i < array.size(indices)
        int bestId = array.get(indices, i)
        FibLevel best = array.get(candidates, bestId)
        float firstPrice = best.price
        int next = i + 1
        while next < array.size(indices)
            int otherId = array.get(indices, next)
            FibLevel other = array.get(candidates, otherId)
            if other.price - firstPrice > syminfo.mintick * 0.1
                break
            if other.ord < best.ord or (other.ord == best.ord and other.price == best.price and otherId < bestId)
                best := other
                bestId := otherId
            next += 1
        array.push(result, best)
        i := next
    result
 
// Select price-axis values independently of the complete grid.
// Priority: order 1, then 2, then 3; nearest to market within each order.
f_price_indices(array<FibLevel> levels, float price, float minGap, int limit) =>
    array<int> accepted = array.new_int()
    if array.size(levels) > 0
        for o = 1 to 3
            array<int> ids = array.new_int()
            array<float> distances = array.new_float()
            for i = 0 to array.size(levels) - 1
                FibLevel level = array.get(levels, i)
                if level.ord == o
                    array.push(ids, i)
                    array.push(distances, math.abs(level.price - price))
            array<int> nearest = array.sort_indices(distances, order.ascending)
            for rank in nearest
                if array.size(accepted) >= limit
                    break
                int id = array.get(ids, rank)
                FibLevel level = array.get(levels, id)
                bool crowded = false
                for previous in accepted
                    FibLevel prior = array.get(levels, previous)
                    if math.abs(level.price - prior.price) < minGap
                        crowded := true
                        break
                if not crowded
                    array.push(accepted, id)
    accepted
 
var array<float> fractions = array.new_float()
var bool restoredDefaults = false
var int invalidTokens = 0
if barstate.isfirst
    array<string> parts = str.split(levelsCSV, ",")
    for part in parts
        string token = str.trim(part)
        if str.length(token) > 0
            float value = f_is_number(token) ? str.tonumber(token) : na
            if na(value)
                invalidTokens += 1
            else
                f_add_fraction(fractions, value / 100.0)
    f_add_fraction(fractions, 0.0)
    f_add_fraction(fractions, 1.0)
    if array.size(fractions) > 15
        fractions := array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.764, 1.0)
        restoredDefaults := true
    array.sort(fractions, order.ascending)
    if invalidTokens > 0
        log.warning("IMD Fibo: invalid levels skipped / пропущено некорректных уровней: " + str.tostring(invalidTokens))
    if restoredDefaults
        log.warning("IMD Fibo: too many levels; defaults restored / слишком много уровней; восстановлены стандартные.")
 
// No lookahead: monthly history plus extrema already observed on this chart.
// Only the last bar is drawn; past grids are not retroactively presented as signals.
[monthlyHigh, monthlyLow] = request.security(syminfo.tickerid, "1M", f_monthly_range(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
var float observedHigh = na
var float observedLow = na
if time("1M") >= startDate
    observedHigh := na(observedHigh) ? high : math.max(observedHigh, high)
    if low > 0
        observedLow := na(observedLow) ? low : math.min(observedLow, low)
float historyHigh = na(monthlyHigh) ? observedHigh : na(observedHigh) ? monthlyHigh : math.max(monthlyHigh, observedHigh)
float historyLow = na(monthlyLow) ? observedLow : na(observedLow) ? monthlyLow : math.min(monthlyLow, observedLow)
float rangeHigh = rangeMode == "Manual" ? manualHigh : historyHigh
float rangeLow = rangeMode == "Manual" ? manualLow : historyLow
bool validRange = not na(rangeHigh) and not na(rangeLow) and rangeHigh > rangeLow and rangeLow >= 0
float selectedPrice = switch priceMode
    "Bid" => bid
    "Ask" => ask
    "Mid" => na(bid) or na(ask) ? na : (bid + ask) / 2.0
    => close
bool quoteFallback = na(selectedPrice)
float currentPrice = quoteFallback ? close : selectedPrice
varip bool quoteWarningSent = false
if quoteFallback and not quoteWarningSent
    log.warning("IMD Fibo: Bid/Ask unavailable on these bars; Last used / Bid/Ask недоступны на этих барах; используется Last.")
    quoteWarningSent := true
 
// Visible-bar values provide a zoom-sensitive price-spacing estimate.
// Native price-axis collision handling uses the actual chart geometry.
var float visibleHigh = na
var float visibleLow = na
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
    visibleHigh := na(visibleHigh) ? high : math.max(visibleHigh, high)
    visibleLow := na(visibleLow) ? low : math.min(visibleLow, low)
float visibleSpan = na(visibleHigh) or na(visibleLow) ? high - low : visibleHigh - visibleLow
float minPriceGap = math.max(labelGapTicks * syminfo.mintick, math.max(syminfo.mintick, visibleSpan) * labelGapPercent / 100.0)
 
var array<line> lines = array.new_line()
// 30 native plots with series colors use 60 plot counts; two range plots use 2.
var array<float> scalePrices = array.new_float(30, na)
var array<color> scaleColors = array.new_color(30, color.white)
// Three large color keys, one row per strength; no statistical information panel.
var table legend = table.new(f_legend_position(legendPosition), 1, 3, force_overlay = true)
 
if barstate.islast
    array<FibLevel> visible = array.new<FibLevel>()
    if validRange and not na(currentPrice)
        visible := f_dedupe(f_candidates(fractions, rangeLow, rangeHigh, currentPrice, gridMode))
        if array.size(visible) > 500
            runtime.error("IMD Fibo: сетка содержит " + str.tostring(array.size(visible)) + " линий, лимит TradingView — 500. Уменьшите число уровней Фибоначчи, отключите один из порядков или выберите «Активная сетка».")
    int count = array.size(visible)
    while array.size(lines) > count
        line.delete(array.pop(lines))
    if count > 0
        for i = 0 to count - 1
            FibLevel level = array.get(visible, i)
            if i >= array.size(lines)
                array.push(lines, line.new(bar_index, level.price, bar_index + 1, level.price, extend = extend.both, force_overlay = true))
            line ln = array.get(lines, i)
            line.set_xy1(ln, bar_index, level.price)
            line.set_xy2(ln, bar_index + 1, level.price)
            line.set_color(ln, color.new(f_color(level.ord), f_line_transparency(level.ord)))
            line.set_style(ln, f_style(level.ord))
            line.set_width(ln, lineWidth)
    array.fill(scalePrices, na)
    if showLabels and count > 0
        array<int> chosen = f_price_indices(visible, currentPrice, minPriceGap, maxPriceLabels)
        if array.size(chosen) > 0
            for slot = 0 to array.size(chosen) - 1
                FibLevel level = array.get(visible, array.get(chosen, slot))
                array.set(scalePrices, slot, level.price)
                array.set(scaleColors, slot, f_color(level.ord))
 
    table.clear(legend, 0, 0, 0, 2)
    if showLegend
        color legendBg = color.new(chart.bg_color, 15)
        table.cell(legend, 0, 0, "┄ Сильный уровень", text_color = show1 ? color1 : color.new(color1, 65), bgcolor = legendBg, text_size = f_legend_size(legendSize), text_halign = text.align_left, tooltip = show1 ? "1-й порядок" : "1-й порядок выключен")
        table.cell(legend, 0, 1, "┄ Средний уровень", text_color = show2 ? color2 : color.new(color2, 65), bgcolor = legendBg, text_size = f_legend_size(legendSize), text_halign = text.align_left, tooltip = show2 ? "2-й порядок" : "2-й порядок выключен")
        table.cell(legend, 0, 2, "┄ Слабый уровень", text_color = show3 ? color3 : color.new(color3, 65), bgcolor = legendBg, text_size = f_legend_size(legendSize), text_halign = text.align_left, tooltip = show3 ? "3-й порядок" : "3-й порядок выключен")
 
// Explicit global outputs also expose the selected range in the Data Window.
// Keep these calls at global scope, outside the last-bar drawing block.
plot(validRange ? rangeHigh : na, title = "IMD Fibo Range High", display = display.data_window)
plot(validRange ? rangeLow : na, title = "IMD Fibo Range Low", display = display.data_window)
 
// Native right-edge price values. TradingView controls their pixel layout.
plot(array.get(scalePrices, 0), title = "", color = array.get(scaleColors, 0), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 1), title = "", color = array.get(scaleColors, 1), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 2), title = "", color = array.get(scaleColors, 2), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 3), title = "", color = array.get(scaleColors, 3), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 4), title = "", color = array.get(scaleColors, 4), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 5), title = "", color = array.get(scaleColors, 5), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 6), title = "", color = array.get(scaleColors, 6), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 7), title = "", color = array.get(scaleColors, 7), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 8), title = "", color = array.get(scaleColors, 8), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 9), title = "", color = array.get(scaleColors, 9), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 10), title = "", color = array.get(scaleColors, 10), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 11), title = "", color = array.get(scaleColors, 11), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 12), title = "", color = array.get(scaleColors, 12), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 13), title = "", color = array.get(scaleColors, 13), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 14), title = "", color = array.get(scaleColors, 14), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 15), title = "", color = array.get(scaleColors, 15), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 16), title = "", color = array.get(scaleColors, 16), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 17), title = "", color = array.get(scaleColors, 17), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 18), title = "", color = array.get(scaleColors, 18), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 19), title = "", color = array.get(scaleColors, 19), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 20), title = "", color = array.get(scaleColors, 20), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 21), title = "", color = array.get(scaleColors, 21), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 22), title = "", color = array.get(scaleColors, 22), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 23), title = "", color = array.get(scaleColors, 23), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 24), title = "", color = array.get(scaleColors, 24), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 25), title = "", color = array.get(scaleColors, 25), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 26), title = "", color = array.get(scaleColors, 26), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 27), title = "", color = array.get(scaleColors, 27), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 28), title = "", color = array.get(scaleColors, 28), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)
plot(array.get(scalePrices, 29), title = "", color = array.get(scaleColors, 29), display = display.price_scale, editable = false, show_last = 1, force_overlay = true)

← 返回列表