MTF HIPPO Blocks [MMT]

isthattyler · study · 262 行 · 点赞 442 · TradingView 原页

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

Pine Script

//@version=6
indicator("MTF HIPPO Blocks [MMT]", overlay = true, max_boxes_count = 250, max_lines_count = 250, max_labels_count = 250, dynamic_requests = true)
 
// A -> B -> C -> D: B and C define the HIPPO; D confirms the second FVG.
// Bearish: A.low > C.high, B.low > D.high; bottom B.low, top C.high.
// Bullish: A.high < C.low, B.high < D.low; bottom C.low, top B.high.
 
string G_TF = "1 · Timeframes"
bool on1 = input.bool(true, "", inline = "tf1", group = G_TF)
string tf1 = input.timeframe("15", "", inline = "tf1", group = G_TF)
bool on2 = input.bool(true, "", inline = "tf2", group = G_TF)
string tf2 = input.timeframe("60", "", inline = "tf2", group = G_TF)
bool on3 = input.bool(true, "", inline = "tf3", group = G_TF)
string tf3 = input.timeframe("240", "", inline = "tf3", group = G_TF)
bool on4 = input.bool(false, "", inline = "tf4", group = G_TF)
string tf4 = input.timeframe("1D", "", inline = "tf4", group = G_TF)
bool on5 = input.bool(false, "", inline = "tf5", group = G_TF)
string tf5 = input.timeframe("1W", "", inline = "tf5", group = G_TF)
 
string G_FORM = "2 · Formation"
string direction = input.string("Both", "Show formations", options = ["Both", "Bullish only", "Bearish only"], group = G_FORM)
int minGap = input.int(1, "Minimum size of EACH FVG (ticks)", minval = 1, group = G_FORM)
int minHeight = input.int(1, "Minimum HIPPO height (ticks)", minval = 1, group = G_FORM)
bool matchCandles = input.bool(false, "Require both middle candles to match direction", group = G_FORM, tooltip = "Optional extra filter: B and C must both close up for bullish HIPPOs, or down for bearish HIPPOs.")
 
string G_MERGE = "3 · Block limit & merging"
int maxBlocks = input.int(25, "Maximum displayed blocks (total)", minval = 1, maxval = 200, group = G_MERGE, tooltip = "One combined limit across all five slots. Oldest blocks are removed first. A newly merged block counts as recent.")
bool mergeBlocks = input.bool(true, "Merge overlapping / nearby blocks", group = G_MERGE)
int proximity = input.int(2, "Merge distance (ticks)", minval = 0, group = G_MERGE, tooltip = "0 = zones must overlap or touch. A positive value also merges zones separated by this many ticks. The resulting box covers the entire combined price range.")
string mergeMode = input.string("Same direction only", "Merge directions", options = ["Any direction", "Same direction only"], group = G_MERGE, tooltip = "Any direction merges bullish and bearish blocks into a Mixed zone. Same direction keeps bullish and bearish zones separate.")
 
string G_MIT = "4 · Mitigation"
bool removeMitigated = input.bool(true, "Remove mitigated blocks", group = G_MIT)
string mitigationRule = input.string("Close beyond block", "Remove when price reaches", options = ["Wick touch", "50% touch", "Full fill", "Close beyond block"], group = G_MIT, tooltip = "Wick touch = near edge; 50% = midpoint; full fill = far edge; close beyond = candle closes strictly past the far edge. Uses confirmed CHART candles, including for higher-timeframe blocks. Formation candles cannot mitigate their own block.")
 
string G_LOOK = "5 · Appearance"
color bullColor = input.color(color.teal, "Bullish", inline = "colors", group = G_LOOK)
color bearColor = input.color(color.red, "Bearish", inline = "colors", group = G_LOOK)
color mixedColor = input.color(color.gray, "Mixed", inline = "colors", group = G_LOOK)
int fillTransparency = input.int(88, "Fill transparency", minval = 0, maxval = 100, group = G_LOOK)
int borderTransparency = input.int(15, "Border transparency", minval = 0, maxval = 100, group = G_LOOK)
string borderStyle = input.string("Dotted", "Border style", options = ["Solid", "Dashed", "Dotted"], group = G_LOOK)
int borderWidth = input.int(1, "Border width", minval = 1, maxval = 4, group = G_LOOK)
bool extendRight = input.bool(true, "Extend blocks to the right", group = G_LOOK)
bool showMid = input.bool(true, "Show 50% line", group = G_LOOK)
string midStyle = input.string("Dashed", "50% line style", options = ["Solid", "Dashed", "Dotted"], group = G_LOOK)
int midWidth = input.int(1, "50% line width", minval = 1, maxval = 4, group = G_LOOK)
int midTransparency = input.int(25, "50% line transparency", minval = 0, maxval = 100, group = G_LOOK)
bool showLabels = input.bool(true, "Show HIPPO labels", group = G_LOOK)
bool showDate = input.bool(false, "Include formation date (exchange time)", group = G_LOOK)
bool labelMatchesBlock = input.bool(false, "Match label text color to block", group = G_LOOK)
color labelColor = input.color(color.white, "Label text color", group = G_LOOK)
color labelBackground = input.color(color.rgb(32, 36, 45), "Label background", group = G_LOOK)
int labelBackgroundTransparency = input.int(5, "Label background transparency", minval = 0, maxval = 100, group = G_LOOK)
string labelSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G_LOOK)
int labelOffset = input.int(3, "Label distance to right (bars)", minval = 0, maxval = 50, group = G_LOOK, tooltip = "Labels sit beside the latest chart candle at the block midpoint. Allow enough right margin on your chart to see them.")
 
type Hippo
    float top
    float bottom
    int startTime
    int confirmedAt
    int side
    int mitigationSide
    string frames
    box rectangle
    line midpoint
    label badge
 
var array<Hippo> zones = array.new<Hippo>()
var array<int> lastSeen = array.new<int>(5, na)
 
f_style(string choice) =>
    choice == "Solid" ? line.style_solid : choice == "Dashed" ? line.style_dashed : line.style_dotted
 
f_size(string choice) =>
    choice == "Tiny" ? size.tiny : choice == "Small" ? size.small : size.normal
 
f_tfName(string tf) =>
    float seconds = timeframe.in_seconds(tf)
    seconds < 60 ? str.tostring(seconds, "#") + "s" : seconds < 3600 ? str.tostring(seconds / 60, "#") + "m" : seconds < 86400 ? str.tostring(seconds / 3600, "#.##") + "h" : tf
 
// Offset 0 is used only on a confirmed chart bar. HTF requests use offset 1.
f_pattern(int o) =>
    // Tiny tolerance avoids rejecting an exact tick because of floating-point rounding.
    float gap = (minGap - 0.000001) * syminfo.mintick
    float height = (minHeight - 0.000001) * syminfo.mintick
    bool enough = not na(high[o + 3])
    bool bull = enough and low[o + 1] - high[o + 3] >= gap and low[o] - high[o + 2] >= gap and high[o + 2] - low[o + 1] >= height
    bool bear = enough and low[o + 3] - high[o + 1] >= gap and low[o + 2] - high[o] >= gap and high[o + 1] - low[o + 2] >= height
    if matchCandles
        bull := bull and close[o + 2] > open[o + 2] and close[o + 1] > open[o + 1]
        bear := bear and close[o + 2] < open[o + 2] and close[o + 1] < open[o + 1]
    int side = bull ? 1 : bear ? -1 : 0
    float top = bull ? high[o + 2] : bear ? high[o + 1] : na
    float bottom = bull ? low[o + 1] : bear ? low[o + 2] : na
    [side, top, bottom, time[o + 2], time_close[o]]
 
f_joinFrames(string current, string extra) =>
    string result = current
    array<string> tokens = str.split(extra, "|")
    for token in tokens
        if str.length(token) > 0 and not str.contains(result, "|" + token + "|")
            result += token + "|"
    result
 
f_frameText(string frames) =>
    string result = ""
    array<string> tokens = str.split(frames, "|")
    for token in tokens
        if str.length(token) > 0
            result += (str.length(result) > 0 ? " + " : "") + f_tfName(token)
    result
 
f_delete(Hippo zone) =>
    box.delete(zone.rectangle)
    line.delete(zone.midpoint)
    label.delete(zone.badge)
 
// Bullish zones are approached from above; bearish zones from below.
// A Mixed union waits for a post-confirmation approach from outside its bounds.
f_isMitigated(int approach, float top, float bottom, float barHigh, float barLow, float barClose) =>
    float midpoint = (top + bottom) / 2
    bool bullishHit = mitigationRule == "Wick touch" ? barLow <= top : mitigationRule == "50% touch" ? barLow <= midpoint : mitigationRule == "Full fill" ? barLow <= bottom : barClose < bottom
    bool bearishHit = mitigationRule == "Wick touch" ? barHigh >= bottom : mitigationRule == "50% touch" ? barHigh >= midpoint : mitigationRule == "Full fill" ? barHigh >= top : barClose > top
    approach == 1 ? bullishHit : approach == -1 ? bearishHit : false
 
f_removeMitigated() =>
    if removeMitigated and barstate.isconfirmed
        int i = array.size(zones) - 1
        while i >= 0
            Hippo zone = array.get(zones, i)
            // Strictly exclude all source formation bars (including D).
            if time >= zone.confirmedAt
                if zone.mitigationSide == 0
                    // Previous close must belong to a bar after source confirmation.
                    if time_close[1] >= zone.confirmedAt
                        zone.mitigationSide := close[1] > zone.top ? 1 : close[1] < zone.bottom ? -1 : 0
                if f_isMitigated(zone.mitigationSide, zone.top, zone.bottom, high, low, close)
                    f_delete(zone)
                    array.remove(zones, i)
            i -= 1
 
f_add(int side, float top, float bottom, int startTime, int confirmedAt, string tf) =>
    Hippo candidate = Hippo.new(top, bottom, startTime, confirmedAt, side, side, "|" + tf + "|", na, na, na)
    if mergeBlocks
        float distance = proximity * syminfo.mintick
        // Restart after a union: an expanded zone may now reach an earlier zone.
        int i = 0
        while i < array.size(zones)
            Hippo existing = array.get(zones, i)
            bool sameSide = mergeMode == "Any direction" or candidate.side == existing.side
            bool nearby = candidate.bottom <= existing.top + distance and candidate.top >= existing.bottom - distance
            if sameSide and nearby
                candidate.top := math.max(candidate.top, existing.top)
                candidate.bottom := math.min(candidate.bottom, existing.bottom)
                candidate.startTime := math.min(candidate.startTime, existing.startTime)
                candidate.confirmedAt := math.max(candidate.confirmedAt, existing.confirmedAt)
                candidate.side := candidate.side == existing.side ? candidate.side : 0
                candidate.mitigationSide := candidate.side
                candidate.frames := f_joinFrames(candidate.frames, existing.frames)
                f_delete(existing)
                array.remove(zones, i)
                i := 0
            else
                i += 1
    array.push(zones, candidate)
    while array.size(zones) > maxBlocks
        f_delete(array.shift(zones))
 
if barstate.isfirst and not chart.is_standard
    runtime.error("HIPPO MTF requires a standard time-based candlestick/bar chart. Switch from Heikin Ashi, Renko, Range, or other synthetic charts.")
 
array<string> frames = array.from(tf1 == "" ? timeframe.period : tf1, tf2 == "" ? timeframe.period : tf2, tf3 == "" ? timeframe.period : tf3, tf4 == "" ? timeframe.period : tf4, tf5 == "" ? timeframe.period : tf5)
array<bool> enabled = array.from(on1, on2, on3, on4, on5)
float chartSeconds = timeframe.in_seconds()
[chartSide, chartTop, chartBottom, chartStart, chartConfirmed] = f_pattern(0)
bool newBull = false
bool newBear = false
 
// Remove consumed old zones BEFORE they can absorb new formations.
f_removeMitigated()
 
for slot = 0 to 4
    string tf = array.get(frames, slot)
    float sourceSeconds = timeframe.in_seconds(tf)
    bool isEnabled = array.get(enabled, slot)
    bool duplicate = false
    if slot > 0
        for previous = 0 to slot - 1
            if array.get(enabled, previous) and timeframe.in_seconds(array.get(frames, previous)) == sourceSeconds
                duplicate := true
    bool valid = isEnabled and sourceSeconds >= chartSeconds and not duplicate
    string state = not isEnabled ? "Off" : sourceSeconds < chartSeconds ? "Skipped: below chart" : duplicate ? "Skipped: duplicate" : "Active"
 
    if valid
        int side = chartSide
        float top = chartTop
        float bottom = chartBottom
        int startTime = chartStart
        int confirmedAt = chartConfirmed
        if sourceSeconds > chartSeconds
            // Confirmed source data only; never read the developing HTF candle.
            [htfSide, htfTop, htfBottom, htfStart, htfConfirmed] = request.security(syminfo.tickerid, tf, f_pattern(1), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
            side := htfSide
            top := htfTop
            bottom := htfBottom
            startTime := htfStart
            confirmedAt := htfConfirmed
        int seen = array.get(lastSeen, slot)
        if barstate.isconfirmed and not na(confirmedAt) and (na(seen) or confirmedAt != seen)
            array.set(lastSeen, slot, confirmedAt)
            bool allowed = side == 1 ? direction != "Bearish only" : side == -1 ? direction != "Bullish only" : false
            if allowed
                f_add(side, top, bottom, startTime, confirmedAt, tf)
                newBull := newBull or side == 1
                newBear := newBear or side == -1
 
// The first chart bar after an HTF confirmation can already mitigate a new zone.
// This also keeps historical reloads from retaining immediately consumed zones.
f_removeMitigated()
 
// Reuse drawing IDs. Removed zones have their objects explicitly deleted.
if barstate.islast and array.size(zones) > 0
    for i = 0 to array.size(zones) - 1
        Hippo zone = array.get(zones, i)
        color tint = zone.side == 1 ? bullColor : zone.side == -1 ? bearColor : mixedColor
        int rightTime = math.max(nz(time_close, time), zone.confirmedAt)
        string description = "HIPPO " + f_frameText(zone.frames) + (zone.side == 0 ? " · Mixed" : zone.side == 1 ? " · Bull" : " · Bear")
        if showDate
            description += " · " + str.format_time(zone.startTime, "dd MMM HH:mm", syminfo.timezone)
        if na(zone.rectangle)
            zone.rectangle := box.new(left = zone.startTime, top = zone.top, right = rightTime, bottom = zone.bottom, xloc = xloc.bar_time)
        box.set_right(zone.rectangle, rightTime)
        box.set_extend(zone.rectangle, extendRight ? extend.right : extend.none)
        box.set_bgcolor(zone.rectangle, color.new(tint, fillTransparency))
        box.set_border_color(zone.rectangle, color.new(tint, borderTransparency))
        box.set_border_style(zone.rectangle, f_style(borderStyle))
        box.set_border_width(zone.rectangle, borderWidth)
        float midpoint = (zone.top + zone.bottom) / 2
        // Separate badges keep text readable even when a block is only a few ticks tall.
        if showLabels
            if na(zone.badge)
                zone.badge := label.new(x = bar_index + labelOffset, y = midpoint, text = description, xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left)
            label.set_xy(zone.badge, bar_index + labelOffset, midpoint)
            label.set_text(zone.badge, description)
            label.set_textcolor(zone.badge, labelMatchesBlock ? tint : labelColor)
            label.set_color(zone.badge, color.new(labelBackground, labelBackgroundTransparency))
            label.set_size(zone.badge, f_size(labelSize))
            label.set_textalign(zone.badge, text.align_left)
        if showMid
            if na(zone.midpoint)
                zone.midpoint := line.new(x1 = zone.startTime, y1 = midpoint, x2 = rightTime, y2 = midpoint, xloc = xloc.bar_time)
            line.set_x2(zone.midpoint, rightTime)
            line.set_extend(zone.midpoint, extendRight ? extend.right : extend.none)
            line.set_color(zone.midpoint, color.new(tint, midTransparency))
            line.set_style(zone.midpoint, f_style(midStyle))
            line.set_width(zone.midpoint, midWidth)
 
alertcondition(newBull, "New bullish HIPPO", "A confirmed bullish HIPPO formed on an enabled timeframe. Open the chart to see the source timeframe and any merged zone.")
alertcondition(newBear, "New bearish HIPPO", "A confirmed bearish HIPPO formed on an enabled timeframe. Open the chart to see the source timeframe and any merged zone.")
alertcondition(newBull or newBear, "New HIPPO (either direction)", "A confirmed HIPPO formed on an enabled timeframe. Open the chart to see its details.")

← 返回列表