Average Daily Range [ITA]

itamardrori_ · study · 187 行 · 点赞 58 · TradingView 原页

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

Pine Script

// © ITA Trading Tools - itamardrori_
//@version=6
// =============================================================================
// Average Daily Range [ITA]
//
// The band is set before the session starts and does not move: the previous
// close, plus and minus half the average daily range. That is the whole point.
// Anchoring it to the session's own high and low, which is the common way to
// draw this, makes it circular. The level is then derived from the same bar it
// is being judged against, and on a daily chart the two edges end up tested
// against the identical high and the identical low and return the same number.
//
// Anchored to yesterday's close it is a forecast made in advance, and the three
// counted numbers are real questions with real answers: how often price trades
// through the top of its average range, how often through the bottom, and how
// often a session does neither and spends the whole day inside.
//
// Everybody draws this band. Almost nobody says how often it holds.
//
// Drawn with plots rather than lines and boxes. A box is a rectangle between
// two bar indices, and on a daily chart a session is one bar wide, so the band
// came out as a row of narrow blocks sitting on top of the candles instead of
// a channel running beside them. Two step plots with a fill between them give
// one continuous shape across the whole history and cost no drawing objects,
// so nothing has to be thrown away to stay under a limit.
// =============================================================================
 
indicator("Average Daily Range [ITA]", overlay = true)
 
// ─── INPUTS ──────────────────────────────────────────────────────────────────
grpCalc = "Calculation"
adrLen  = input.int(14, "Days In The Average", minval = 2, maxval = 200, group = grpCalc,
     tooltip = "How many completed days the average daily range is taken over. Fourteen is the common choice and short enough to follow a change in volatility.")
widthPct = input.float(100, "Band Width, % Of The Average", minval = 10, maxval = 300, step = 5, group = grpCalc,
     tooltip = "100 means the band spans one average daily range in total, half above the previous close and half below. Raise it to ask a harder question.")
 
grpShow   = "Display"
showBand  = input.bool(true, "Draw The Band", group = grpShow)
showFill  = input.bool(true, "Shade Between Them", group = grpShow)
showMid   = input.bool(false, "Draw The Anchor", group = grpShow,
     tooltip = "The previous close, which the band is centred on.")
showHits  = input.bool(true, "Mark A Broken Edge", group = grpShow)
edgeW     = input.int(1, "Edge Thickness", minval = 1, maxval = 4, group = grpShow,
     tooltip = "Thin on purpose. The shaded band is meant to be the shape the eye catches, and two thick stepped outlines read as zigzag rather than as a channel.")
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)
statSizeStr = input.string("Normal", "Count Text Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
 
grpCol  = "Colors"
upCol   = input.color(#089981, "Upper Edge", group = grpCol)
dnCol   = input.color(#f23645, "Lower Edge", group = grpCol)
fillCol = input.color(color.new(#2962ff, 82), "Shading", group = grpCol)
openCol = input.color(color.new(#787b86, 45), "Anchor", 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
 
statSize = sizeOf(statSizeStr)
 
// ─── THE AVERAGE AND THE ANCHOR ──────────────────────────────────────────────
// Both come off the daily series, so the band is identical whether this is read
// on a daily chart or on one minute. The [1] inside each request is what keeps
// it honest: the session is measured against numbers that were already fixed
// when it opened, never against ones it helped produce.
adr  = request.security(syminfo.tickerid, "1D", ta.sma(high - low, adrLen)[1],
     lookahead = barmerge.lookahead_off)
base = request.security(syminfo.tickerid, "1D", close[1],
     lookahead = barmerge.lookahead_off)
 
newDay = timeframe.change("1D")
half   = adr * widthPct / 200.0
 
// ─── SESSION STATE ───────────────────────────────────────────────────────────
var float upLvl  = na
var float dnLvl  = na
var float anchor = na
var bool  hitUp  = false
var bool  hitDn  = false
var bool  live   = false
 
var int sessions = 0
var int reachUp  = 0
var int reachDn  = 0
var int inside   = 0
 
// ─── CLOSE OUT THE SESSION THAT JUST ENDED ───────────────────────────────────
// A session that broke neither edge is the headline number, so it is counted
// here rather than inferred from the other two. One that broke both is in both
// and is inside neither, which is the only reading that keeps the three figures
// describing what actually happened.
if newDay and live
    sessions += 1
    if hitUp
        reachUp += 1
    if hitDn
        reachDn += 1
    if not hitUp and not hitDn
        inside += 1
 
// ─── START A NEW SESSION ─────────────────────────────────────────────────────
if newDay and not na(base) and not na(adr) and adr > 0
    upLvl  := base + half
    dnLvl  := base - half
    anchor := base
    hitUp  := false
    hitDn  := false
    live   := true
 
// ─── TEST IT ─────────────────────────────────────────────────────────────────
// Broken is a trade through the edge, not a close beyond it. The band is drawn
// as a range, and a range is broken the moment price leaves it.
breakUp = false
breakDn = false
if live
    if not hitUp and high >= upLvl
        hitUp   := true
        breakUp := true
    if not hitDn and low <= dnLvl
        hitDn   := true
        breakDn := true
 
// ─── THE DRAWING ─────────────────────────────────────────────────────────────
// Step plots, because the level is flat for the whole session and then jumps.
// A straight line between two sessions would draw a slope that never existed.
pUp = plot(showBand and live ? upLvl : na, "Upper Edge", color = upCol,
     linewidth = edgeW, style = plot.style_stepline)
pDn = plot(showBand and live ? dnLvl : na, "Lower Edge", color = dnCol,
     linewidth = edgeW, style = plot.style_stepline)
plot(showMid and live ? anchor : na, "Anchor", color = openCol,
     linewidth = 1, style = plot.style_stepline)
 
fill(pUp, pDn, color = showFill ? fillCol : na, title = "Shading")
 
plotshape(showHits and breakUp, "Broke the high", shape.triangleup,
     location.abovebar, color = upCol, size = size.tiny)
plotshape(showHits and breakDn, "Broke the low", shape.triangledown,
     location.belowbar, color = dnCol, size = size.tiny)
 
// ─── THE COUNT ───────────────────────────────────────────────────────────────
upRate = sessions > 0 ? reachUp / sessions * 100.0 : 0.0
dnRate = sessions > 0 ? reachDn / sessions * 100.0 : 0.0
inRate = sessions > 0 ? inside  / sessions * 100.0 : 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, 5, border_width = 1)
    table.cell(stats, 0, 0, "AVERAGE DAILY RANGE", text_color = #e5c56b, text_size = statSize)
    table.cell(stats, 1, 0, "", text_size = statSize)
    table.cell(stats, 0, 1, "Sessions", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 1, str.tostring(sessions), text_color = color.white, text_size = statSize)
    table.cell(stats, 0, 2, "Broke the high", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 2, sessions > 0 ? str.tostring(upRate, "#.#") + "%" : "no data",
         text_color = upCol, text_size = statSize)
    table.cell(stats, 0, 3, "Broke the low", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 3, sessions > 0 ? str.tostring(dnRate, "#.#") + "%" : "no data",
         text_color = dnCol, text_size = statSize)
    table.cell(stats, 0, 4, "Stayed inside", text_color = color.new(color.white, 25), text_size = statSize)
    table.cell(stats, 1, 4, sessions > 0 ? str.tostring(inRate, "#.#") + "%" : "no data",
         text_color = color.white, text_size = statSize)
 
// ─── ALERTS ──────────────────────────────────────────────────────────────────
alertcondition(breakUp, "Upper edge broken",
     "Price traded through the top of its average daily range.")
alertcondition(breakDn, "Lower edge broken",
     "Price traded through the bottom of its average daily range.")

← 返回列表