Donchian Breakouts [ITA]

itamardrori_ · study · 205 行 · 点赞 11 · TradingView 原页

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

Pine Script

// © ITA Trading Tools - itamardrori_
//@version=6
// =============================================================================
// Donchian Breakouts [ITA]
//
// The Donchian channel is the highest high and the lowest low of the last N
// bars. It is the channel the Turtle traders were taught to trade: buy the
// close above the 20-bar high, and let it run. Every Donchian tool draws it.
// Almost none of them say how often the breakout actually ran.
//
// So this draws the channel and follows every close outside it. Each break is
// scored on two things after a set number of bars: did price keep going in
// the direction of the break, and did it fall back inside the channel first,
// which is what a false breakout is. The first number is printed directly
// above the same question asked of an ordinary bar, because on a stock that
// has risen for years almost any bar is higher later more often than not, and
// a breakout rate means nothing until it beats that.
//
// Two decisions worth stating:
//
//   the channel   is built from the bars BEFORE the current one. A channel
//                 that includes the current bar can never be closed above,
//                 because the bar's own high is part of it.
//
//   the window    a break whose window has not finished is left out of the
//                 rates, not counted as a failure and not as a success, and
//                 every row says how many breaks it is built on.
// =============================================================================
 
indicator("Donchian Breakouts [ITA]", overlay = true, max_labels_count = 500)
 
// ─── INPUTS ──────────────────────────────────────────────────────────────────
grpCalc = "Calculation"
chLen   = input.int(20, "Channel Length", minval = 2, maxval = 300, group = grpCalc,
     tooltip = "Bars in the channel. Twenty is the Turtle entry channel, about one trading month on a daily chart.")
fwdLen  = input.int(10, "Bars To Follow A Break", minval = 1, maxval = 100, group = grpCalc,
     tooltip = "How long each break is followed before it is scored. Ten is two trading weeks on a daily chart.")
 
grpShow   = "Display"
showFill  = input.bool(true, "Shade The Channel", group = grpShow)
showMid   = input.bool(false, "Draw The Midline", group = grpShow)
showMarks = input.bool(true, "Mark The Breaks", group = grpShow)
showStats = input.bool(true, "Show The Count", group = grpShow)
edgeW     = input.int(1, "Edge Thickness", minval = 1, maxval = 4, group = grpShow,
     tooltip = "Thin on purpose. The shaded channel is meant to be the shape the eye catches.")
statPos   = input.string("Top Right", "Count Position",
     options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpShow)
statSizeStr = input.string("Normal", "Count Text Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
 
grpCol  = "Colors"
upCol   = input.color(#089981, "Upper Edge And Up Breaks", group = grpCol)
dnCol   = input.color(#f23645, "Lower Edge And Down Breaks", group = grpCol)
fillCol = input.color(color.new(#2962ff, 84), "Shading", group = grpCol)
midCol  = input.color(color.new(#787b86, 45), "Midline", 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
 
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
 
statSize = sizeOf(statSizeStr)
 
// ─── THE CHANNEL ─────────────────────────────────────────────────────────────
upper = ta.highest(high, chLen)[1]
lower = ta.lowest(low, chLen)[1]
mid   = (upper + lower) / 2
 
// A break is the first close outside, not every close outside. A run of five
// closes above the channel is one breakout, not five.
breakUp = not na(upper) and close > upper and not (close[1] > upper[1])
breakDn = not na(lower) and close < lower and not (close[1] < lower[1])
 
// ─── THE DRAWING ─────────────────────────────────────────────────────────────
// Step plots, because the channel is flat until a new extreme enters or an
// old one leaves the window, and then it jumps.
pUp = plot(upper, "Upper Edge", color = upCol, linewidth = edgeW, style = plot.style_stepline)
pDn = plot(lower, "Lower Edge", color = dnCol, linewidth = edgeW, style = plot.style_stepline)
plot(showMid ? mid : na, "Midline", color = midCol, linewidth = 1, style = plot.style_stepline)
fill(pUp, pDn, color = showFill ? fillCol : na, title = "Shading")
 
plotshape(showMarks and breakUp, "Up break", shape.triangleup,
     location.belowbar, color = upCol, size = size.tiny)
plotshape(showMarks and breakDn, "Down break", shape.triangledown,
     location.abovebar, color = dnCol, size = size.tiny)
 
// ─── THE BASELINE ────────────────────────────────────────────────────────────
// Every bar is asked the same question a break is asked. Without this the
// break rate cannot be read: 55% sounds like an edge until you learn that an
// ordinary bar on the same chart was higher later 55% of the time too.
var int baseN  = 0
var int baseUp = 0
if bar_index > chLen + fwdLen
    baseN  += 1
    baseUp += close > close[fwdLen] ? 1 : 0
 
// ─── FOLLOWING EACH BREAK ────────────────────────────────────────────────────
// Breaks can overlap, so each one is followed on its own.
var array<int>   pBar   = array.new<int>()
var array<int>   pDir   = array.new<int>()
var array<float> pClose = array.new<float>()
var array<float> pEdge  = array.new<float>()
var array<bool>  pFalse = array.new<bool>()
 
var int breaks = 0
var int upN    = 0
var int upKept = 0
var int dnN    = 0
var int dnKept = 0
var int resN   = 0
var int falseN = 0
 
// Score what is already open before adding this bar, so a break is never
// judged on its own bar.
if array.size(pBar) > 0
    for i = array.size(pBar) - 1 to 0
        age = bar_index - array.get(pBar, i)
        d   = array.get(pDir, i)
 
        // False means a close back on the other side of the edge it broke.
        // The edge is the one from the breakout bar, not today's, because
        // the channel itself moves once the breakout bar enters it.
        if d == 1 and close < array.get(pEdge, i)
            array.set(pFalse, i, true)
        if d == -1 and close > array.get(pEdge, i)
            array.set(pFalse, i, true)
 
        if age >= fwdLen
            kept = d == 1 ? close > array.get(pClose, i) : close < array.get(pClose, i)
            if d == 1
                upN    += 1
                upKept += kept ? 1 : 0
            else
                dnN    += 1
                dnKept += kept ? 1 : 0
            resN   += 1
            falseN += array.get(pFalse, i) ? 1 : 0
 
            array.remove(pBar, i)
            array.remove(pDir, i)
            array.remove(pClose, i)
            array.remove(pEdge, i)
            array.remove(pFalse, i)
 
if breakUp or breakDn
    breaks += 1
    array.push(pBar, bar_index)
    array.push(pDir, breakUp ? 1 : -1)
    array.push(pClose, close)
    array.push(pEdge, breakUp ? upper : lower)
    array.push(pFalse, false)
 
// ─── THE COUNT ───────────────────────────────────────────────────────────────
upRate    = upN  > 0 ? upKept / upN  * 100.0 : 0.0
dnRate    = dnN  > 0 ? dnKept / dnN  * 100.0 : 0.0
baseRate  = baseN > 0 ? baseUp / baseN * 100.0 : 0.0
falseRate = resN > 0 ? falseN / resN * 100.0 : 0.0
 
pctOf(float pct, int n) =>
    n > 0 ? str.tostring(pct, "#.#") + "%  of " + str.tostring(n) : "no data"
 
var table stats = na
if showStats and barstate.islast
    if na(stats)
        stats := table.new(posOf(statPos), 2, 6, border_width = 1)
    table.cell(stats, 0, 0, "DONCHIAN BREAKOUTS", text_color = #e5c56b, text_size = statSize)
    table.cell(stats, 1, 0, "", text_size = statSize)
    table.cell(stats, 0, 1, str.tostring(chLen) + "-bar breaks", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 1, str.tostring(breaks), text_color = color.white, text_size = statSize)
 
    // Each break rate sits next to what it has to beat. A down break "keeps
    // going" when price falls, so its baseline is 100 minus the up rate.
    table.cell(stats, 0, 2, "Up breaks kept going", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 2, pctOf(upRate, upN),
         text_color = upRate > baseRate ? upCol : dnCol, text_size = statSize)
    table.cell(stats, 0, 3, "Any bar, higher " + str.tostring(fwdLen) + " later",
         text_color = color.new(color.white, 45), text_size = statSize)
    table.cell(stats, 1, 3, baseN > 0 ? str.tostring(baseRate, "#.#") + "%" : "no data",
         text_color = color.new(color.white, 45), text_size = statSize)
    table.cell(stats, 0, 4, "Down breaks kept going", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 4, pctOf(dnRate, dnN),
         text_color = dnRate > 100 - baseRate ? upCol : dnCol, text_size = statSize)
    table.cell(stats, 0, 5, "Fell back inside", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 5, pctOf(falseRate, resN), text_color = color.white, text_size = statSize)
 
// ─── ALERTS ──────────────────────────────────────────────────────────────────
alertcondition(breakUp, "Up break", "Close above the Donchian channel.")
alertcondition(breakDn, "Down break", "Close below the Donchian channel.")

← 返回列表