Inside Bar Breaks [ITA]

itamardrori_ · study · 227 行 · 点赞 35 · TradingView 原页

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

Pine Script

// © ITA Trading Tools - itamardrori_
//@version=6
// =============================================================================
// Inside Bar Breaks [ITA]
//
// An inside bar is the easiest pattern on a chart to find and one of the
// hardest to use. Every tool in this category marks the bar and stops there,
// which leaves the trader exactly where they started, because the pattern on
// its own says nothing about direction. The claim attached to it, repeated
// everywhere, is that price compresses inside the mother bar and then runs
// when it breaks out. Almost nobody counts whether the run actually happens.
//
// So this one keeps watching. When price closes beyond the mother bar it waits
// a set number of bars. If price closes back inside the mother range in that
// window the break is marked Failed. If it stays out, it is marked Held. The
// running count for the symbol on screen sits in the corner.
//
// On a market where two thirds of these breaks fail, the honest thing for an
// indicator to do is say so rather than keep printing arrows.
// =============================================================================
 
indicator("Inside Bar Breaks [ITA]", overlay = true,
     max_boxes_count = 100, max_labels_count = 300, max_lines_count = 100)
 
// ─── INPUTS ──────────────────────────────────────────────────────────────────
grpDetect = "Detection"
strictIn  = input.bool(true, "Require A Strictly Inside Bar", group = grpDetect,
     tooltip = "On, the inside bar's high must be below the mother high and its low above the mother low. Off, equal highs or lows still count, which finds more patterns on instruments that trade in ticks.")
minInside = input.int(1, "Inside Bars Needed", minval = 1, maxval = 10, group = grpDetect,
     tooltip = "How many consecutive inside bars have to form before the setup is tracked. One is the classic pattern. Two or three are rarer and the compression is more obvious.")
confirmBars = input.int(5, "Bars To Confirm A Break", minval = 1, maxval = 50, group = grpDetect,
     tooltip = "After price closes outside the mother bar it has this many bars to stay out. A close back inside the mother range within the window marks the break Failed.")
minRangeAtr = input.float(0.0, "Smallest Mother Bar (x ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = grpDetect,
     tooltip = "Ignore setups whose mother bar is smaller than this multiple of ATR. At zero every inside bar counts, including the ones inside a bar so small that the break is noise. Raise it to keep only the compressions worth the name.")
 
grpShow = "Display"
showBox     = input.bool(true, "Draw The Mother Bar Box", group = grpShow)
showBreak   = input.bool(true, "Mark Breaks", group = grpShow)
showOutcome = input.bool(true, "Mark Held and Failed", group = grpShow)
showStats   = input.bool(true, "Show The Count", group = grpShow)
statPos     = input.string("Top Right", "Count Position",
     options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpShow)
lblSizeStr  = input.string("Normal", "Label Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
statSizeStr = input.string("Normal", "Count Text Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
lblOffset   = input.float(0.8, "Label Offset (x ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = grpShow,
     tooltip = "How far labels sit from the bar they belong to. At zero the candles run through the text.")
maxMarks    = input.int(12, "Most Recent Setups To Label", minval = 1, maxval = 100, group = grpShow,
     tooltip = "Applies to the labels only. Every break is counted whatever this is set to. Without a limit a long history turns into a wall of text, which is what buried the first version of this on a daily chart.")
 
grpCol    = "Colors"
boxCol    = input.color(color.new(#2962ff, 80), "Mother Bar Fill", group = grpCol)
borderCol = input.color(color.new(#787b86, 25), "Mother Bar Border", group = grpCol)
insideCol = input.color(color.new(#9598a1, 55), "Inside Bar Tint", group = grpCol)
upCol     = input.color(#089981, "Break Up", group = grpCol)
dnCol     = input.color(#f23645, "Break Down", group = grpCol)
heldCol   = input.color(#089981, "Held", group = grpCol)
failCol   = input.color(#ff9800, "Failed", group = grpCol)
 
sizeOf(string s) =>
    r = size.normal
    if s == "Tiny"
        r := size.tiny
    else if s == "Small"
        r := size.small
    else if s == "Large"
        r := size.large
    else if s == "Huge"
        r := size.huge
    r
 
lblSize  = sizeOf(lblSizeStr)
statSize = sizeOf(statSizeStr)
 
// ─── STATE ───────────────────────────────────────────────────────────────────
atr = ta.atr(14)
 
// The mother bar under observation, and how many inside bars have formed since.
var float mTop    = na
var float mBot    = na
var int   mBar    = na
var int   insideN = 0
var box   mBox    = na
 
// One break is followed at a time. A new mother bar cannot be judged while
// price is still resolving the last break, and tracking several at once would
// let one outcome overwrite another in the count.
var bool  pending  = false
var int   pendBar  = na
var int   pendDir  = 0
var float pendTop  = na
var float pendBot  = na
 
var int heldCount = 0
var int failCount = 0
 
// Labels are kept for the recent setups only. The count keeps everything.
var array<label> marks = array.new<label>()
 
trim() =>
    while array.size(marks) > maxMarks
        label.delete(array.shift(marks))
 
// An inside bar sits entirely within the previous bar.
// One line on purpose. Pine reads an indent that is a multiple of four as a
// new block, so a ternary continued on the next line and aligned under the
// condition is a syntax error outside brackets.
isInside = strictIn ? (high < high[1] and low > low[1]) : (high <= high[1] and low >= low[1])
 
bigEnough = (high[1] - low[1]) >= atr * minRangeAtr
 
// ─── DETECTION ───────────────────────────────────────────────────────────────
if not pending
    if isInside and insideN == 0 and bigEnough
        // First inside bar: the bar before it becomes the mother.
        mTop    := high[1]
        mBot    := low[1]
        mBar    := bar_index - 1
        insideN := 1
        if showBox
            mBox := box.new(mBar, mTop, bar_index, mBot,
                 bgcolor = boxCol, border_color = borderCol, border_width = 1)
 
    else if insideN > 0 and high <= mTop and low >= mBot
        // Still compressed inside the same mother bar.
        insideN += 1
        if not na(mBox)
            box.set_right(mBox, bar_index)
 
    else if insideN > 0
        // The bar left the mother range. Either it is the break, or the setup
        // is over.
        armed = insideN >= minInside
        up    = close > mTop
        dn    = close < mBot
        if armed and (up or dn)
            pending := true
            pendBar := bar_index
            pendDir := up ? 1 : -1
            pendTop := mTop
            pendBot := mBot
            if showBreak
                array.push(marks, label.new(bar_index,
                     up ? high + atr * lblOffset : low - atr * lblOffset,
                     up ? "Break ▲" : "Break ▼",
                     style = up ? label.style_label_down : label.style_label_up,
                     color = up ? upCol : dnCol, textcolor = color.white, size = lblSize))
                trim()
        else if not na(mBox)
            // Nothing came of it: either too few inside bars, or the bar left
            // the range and closed back inside. Leaving the box behind would
            // mark a compression on the chart that never resolved into
            // anything, which is the clutter this category is already full of.
            box.delete(mBox)
            mBox := na
        insideN := 0
 
// ─── OUTCOME ─────────────────────────────────────────────────────────────────
// Failed the moment price closes back inside the mother range. Held only once
// the whole window has passed without that happening, so neither label can
// appear before its evidence does.
if pending
    // Keep the mother bar box growing until the break resolves. Drawn only
    // across the bars it formed on it is one or two candles wide, which is a
    // couple of pixels on a daily chart: the thing the script is about was
    // the hardest thing on the screen to see. The range stays the level that
    // decides Held or Failed for as long as the break is open, so the box
    // showing that whole stretch is also the honest picture.
    if not na(mBox)
        box.set_right(mBox, bar_index)
 
    backInside = close <= pendTop and close >= pendBot
    if backInside
        failCount += 1
        pending   := false
        if showOutcome
            array.push(marks, label.new(bar_index, low - atr * lblOffset, "Failed",
                 style = label.style_label_up, color = failCol,
                 textcolor = color.white, size = lblSize))
            trim()
    else if bar_index - pendBar >= confirmBars
        heldCount += 1
        pending   := false
        if showOutcome
            array.push(marks, label.new(bar_index,
                 pendDir == 1 ? high + atr * lblOffset : low - atr * lblOffset, "Held",
                 style = pendDir == 1 ? label.style_label_down : label.style_label_up,
                 color = heldCol, textcolor = color.white, size = lblSize))
            trim()
 
// The inside bars themselves, tinted so the compression is visible at a glance.
barcolor(insideN > 0 ? insideCol : na)
 
// ─── THE COUNT ───────────────────────────────────────────────────────────────
// Resolved breaks only. A break still inside its confirmation window has no
// outcome yet and counting it either way would move the rate on nothing.
total = heldCount + failCount
rate  = total > 0 ? heldCount / total * 100 : 0.0
 
posOf(string s) =>
    r = position.top_right
    if s == "Top Left"
        r := position.top_left
    else if s == "Bottom Right"
        r := position.bottom_right
    else if s == "Bottom Left"
        r := position.bottom_left
    r
 
var table stats = na
if showStats and barstate.islast
    if na(stats)
        stats := table.new(posOf(statPos), 2, 4, border_width = 1)
    table.cell(stats, 0, 0, "INSIDE BAR BREAKS", text_color = #e5c56b, text_size = statSize)
    table.cell(stats, 1, 0, "", text_size = statSize)
    table.cell(stats, 0, 1, "Held",   text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 1, str.tostring(heldCount), text_color = heldCol, text_size = statSize)
    table.cell(stats, 0, 2, "Failed", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 2, str.tostring(failCount), text_color = failCol, text_size = statSize)
    table.cell(stats, 0, 3, "Hold rate", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 3, total > 0 ? str.tostring(rate, "#.#") + "%  (" + str.tostring(total) + ")" : "no data",
         text_color = color.white, text_size = statSize)
 
// ─── ALERTS ──────────────────────────────────────────────────────────────────
alertcondition(pending and pending[1] == false, "Inside bar break",
     "An inside bar setup has broken out of its mother bar.")

← 返回列表