ADR Progress & Projected Range Levels

cfdtools · study · 244 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
// This source code is subject to the terms of the Mozilla Public License 2.0
// © cfdtools
//
// ADR Progress & Projected Range Levels
// Shows how much of its Average Daily Range (ADR) a symbol has already covered
// today, and where today's high and low would sit if the day ended up trading
// exactly one ADR. It also shows today's open +/- half an ADR and how often past
// days actually reached their ADR.
// The ADR only uses fully completed days, so its value for a day is fixed once
// that day starts and is not revised later.
 
indicator("ADR Progress & Projected Range Levels", shorttitle = "ADR Prog", overlay = true, max_lines_count = 500, max_labels_count = 50)
 
// ─────────────────────────────────────────────────────────────────────────────
// Inputs
// ─────────────────────────────────────────────────────────────────────────────
GRP_ADR = "Average daily range"
GRP_LVL = "Levels"
GRP_TBL = "Table"
GRP_ALR = "Shading & alerts"
 
adrLen    = input.int(14, "ADR length (days)", minval = 1, maxval = 200, group = GRP_ADR, tooltip = "Number of completed days used for the average daily range. Today is never included.")
adrMethod = input.string("Average", "ADR method", options = ["Average", "Median"], group = GRP_ADR, tooltip = "Average: the mean of the daily ranges. Median: the middle value, which is less affected by one or two unusually large days.")
statLen   = input.int(50, "Days for 'reached ADR' statistic", minval = 5, maxval = 500, group = GRP_ADR, tooltip = "How many completed days are checked when counting how often a day's range reached that day's ADR.")
 
showProj   = input.bool(true, "Projected high / low", group = GRP_LVL, inline = "proj", tooltip = "Projected high = today's low + ADR. Projected low = today's high - ADR. They move as today's range develops and meet today's extremes once a full ADR has been traded.")
projCol    = input.color(#E07A3F, "", group = GRP_LVL, inline = "proj")
showHalf   = input.bool(true, "Open +/- half ADR", group = GRP_LVL, inline = "half")
halfCol    = input.color(#3D8BD9, "", group = GRP_LVL, inline = "half")
showOpen   = input.bool(true, "Today's open", group = GRP_LVL, inline = "open")
openCol    = input.color(#9E9E9E, "", group = GRP_LVL, inline = "open")
lineWidth  = input.int(1, "Line width", minval = 1, maxval = 4, group = GRP_LVL)
showLabels = input.bool(true, "Labels on today's levels", group = GRP_LVL)
keepDays   = input.int(5, "Days of levels to keep on chart", minval = 1, maxval = 60, group = GRP_LVL, tooltip = "1 shows only today's levels.")
 
showTable = input.bool(true, "Show table", group = GRP_TBL)
tblPosIn  = input.string("Top right", "Position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Middle left", "Bottom left"], group = GRP_TBL)
tblTxtIn  = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = GRP_TBL)
lowCol    = input.color(#3D5A80, "Low progress color", group = GRP_TBL)
highCol   = input.color(#E07A3F, "Full ADR color", group = GRP_TBL)
 
showBg   = input.bool(false, "Shade bars once ADR is reached", group = GRP_ALR)
bgCol    = input.color(color.new(#E07A3F, 90), "Shade color", group = GRP_ALR)
alertPct = input.float(100.0, "Alert when today's range reaches (% of ADR)", minval = 10.0, step = 5.0, group = GRP_ALR)
 
// ─────────────────────────────────────────────────────────────────────────────
// Daily data (completed days only)
// ─────────────────────────────────────────────────────────────────────────────
bool tfOk = timeframe.in_seconds() > 0 and timeframe.in_seconds() <= 86400
 
dailyStats() =>
    float rng     = high - low
    float adrAvg  = ta.sma(rng, adrLen)
    float adrMed  = ta.median(rng, adrLen)
    float adrSel  = adrMethod == "Median" ? adrMed : adrAvg
    // Did this day's range reach the ADR that was known when the day started?
    float hit     = na(adrSel[1]) ? na : rng >= adrSel[1] ? 1.0 : 0.0
    float hitRate = ta.sma(hit, statLen)
    [adrSel[1], hitRate[1]]
 
[adr, hitRate] = request.security(syminfo.tickerid, "D", dailyStats(), lookahead = barmerge.lookahead_on)
 
// ─────────────────────────────────────────────────────────────────────────────
// Today's open, high and low on the chart timeframe
// ─────────────────────────────────────────────────────────────────────────────
bool newDay = timeframe.change("1D")
 
var float dOpen  = na
var float dHigh  = na
var float dLow   = na
var int   dStart = na
 
if newDay or na(dOpen)
    dOpen  := open
    dHigh  := high
    dLow   := low
    dStart := time
else
    dHigh := math.max(dHigh, high)
    dLow  := math.min(dLow, low)
 
int   dEnd     = nz(time_close("1D"), dStart + 86400000)
float todayRng = dHigh - dLow
float usedPct  = adr > 0 ? todayRng / adr * 100.0 : na
float leftRng  = na(adr) ? na : math.max(adr - todayRng, 0.0)
float projHigh = na(adr) ? na : dLow + adr
float projLow  = na(adr) ? na : dHigh - adr
float halfUp   = na(adr) ? na : dOpen + adr / 2.0
float halfDn   = na(adr) ? na : dOpen - adr / 2.0
 
// ─────────────────────────────────────────────────────────────────────────────
// Drawing
// ─────────────────────────────────────────────────────────────────────────────
var array<line> allLines  = array.new<line>()
var array<int>  dayCounts = array.new<int>()
 
var line lnPH = na
var line lnPL = na
var line lnHU = na
var line lnHD = na
var line lnOP = na
 
var label lbPH = na
var label lbPL = na
var label lbHU = na
var label lbHD = na
var label lbOP = na
 
makeLine(float y, color c, string st) =>
    line.new(dStart, y, dEnd, y, xloc = xloc.bar_time, color = c, style = st, width = lineWidth)
 
setLine(line ln, float y) =>
    if not na(ln)
        line.set_y1(ln, y)
        line.set_y2(ln, y)
        line.set_x2(ln, dEnd)
 
makeLabel(color c, float y) =>
    label.new(dEnd, y, "", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = c, size = size.small)
 
setLabel(label lb, float y, string txt) =>
    if not na(lb)
        label.set_xy(lb, dEnd, y)
        label.set_text(lb, txt + " " + str.tostring(y, format.mintick))
 
if tfOk and newDay and not na(adr)
    lnPH := na
    lnPL := na
    lnHU := na
    lnHD := na
    lnOP := na
    int n = 0
    if showProj
        lnPH := makeLine(projHigh, projCol, line.style_dashed)
        lnPL := makeLine(projLow, projCol, line.style_dashed)
        array.push(allLines, lnPH)
        array.push(allLines, lnPL)
        n += 2
    if showHalf
        lnHU := makeLine(halfUp, halfCol, line.style_dotted)
        lnHD := makeLine(halfDn, halfCol, line.style_dotted)
        array.push(allLines, lnHU)
        array.push(allLines, lnHD)
        n += 2
    if showOpen
        lnOP := makeLine(dOpen, openCol, line.style_solid)
        array.push(allLines, lnOP)
        n += 1
    array.push(dayCounts, n)
    // Remove the oldest days beyond the number to keep. Saved data is never touched.
    while array.size(dayCounts) > keepDays
        int old = array.shift(dayCounts)
        if old > 0
            for i = 1 to old
                if array.size(allLines) > 0
                    line.delete(array.shift(allLines))
 
if tfOk and not na(adr)
    setLine(lnPH, projHigh)
    setLine(lnPL, projLow)
    setLine(lnHU, halfUp)
    setLine(lnHD, halfDn)
    setLine(lnOP, dOpen)
 
if barstate.islast and showLabels and tfOk and not na(adr)
    if showProj and na(lbPH)
        lbPH := makeLabel(projCol, projHigh)
        lbPL := makeLabel(projCol, projLow)
    if showHalf and na(lbHU)
        lbHU := makeLabel(halfCol, halfUp)
        lbHD := makeLabel(halfCol, halfDn)
    if showOpen and na(lbOP)
        lbOP := makeLabel(openCol, dOpen)
    setLabel(lbPH, projHigh, "Proj. high")
    setLabel(lbPL, projLow, "Proj. low")
    setLabel(lbHU, halfUp, "Open + ½ ADR")
    setLabel(lbHD, halfDn, "Open - ½ ADR")
    setLabel(lbOP, dOpen, "Open")
 
bool adrReached = tfOk and not na(usedPct) and usedPct >= 100.0
bgcolor(showBg and adrReached ? bgCol : na, title = "ADR reached shading")
 
// Values in the Data Window
plot(adr, "ADR", display = display.data_window)
plot(todayRng, "Today's range", display = display.data_window)
plot(usedPct, "Range used (% of ADR)", display = display.data_window)
plot(hitRate * 100.0, "Days that reached ADR (%)", display = display.data_window)
 
// ─────────────────────────────────────────────────────────────────────────────
// Table
// ─────────────────────────────────────────────────────────────────────────────
tblPos() =>
    switch tblPosIn
        "Top right"    => position.top_right
        "Middle right" => position.middle_right
        "Bottom right" => position.bottom_right
        "Top left"     => position.top_left
        "Middle left"  => position.middle_left
        => position.bottom_left
 
tblSize() =>
    switch tblTxtIn
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
fmtP(float v) =>
    na(v) ? "-" : str.tostring(v, format.mintick)
 
var table tbl = table.new(tblPos(), 2, 8, bgcolor = color.new(#131722, 15), border_color = color.new(#787B86, 60), border_width = 1, frame_color = color.new(#787B86, 40), frame_width = 1)
 
cellRow(int r, string k, string v, color vBg) =>
    color txt = color.new(#D1D4DC, 0)
    table.cell(tbl, 0, r, k, text_color = txt, text_size = tblSize(), text_halign = text.align_left)
    table.cell(tbl, 1, r, v, text_color = txt, text_size = tblSize(), text_halign = text.align_right, bgcolor = vBg)
 
if barstate.islast and showTable
    table.clear(tbl, 0, 0, 1, 7)
    if not tfOk
        table.cell(tbl, 0, 0, "ADR Progress", text_color = #D1D4DC, text_size = tblSize())
        table.cell(tbl, 1, 0, "Use a daily or lower timeframe", text_color = #D1D4DC, text_size = tblSize())
    else
        string methodTxt = adrMethod == "Median" ? "median" : "avg"
        float  shown     = na(usedPct) ? na : math.min(usedPct, 100.0)
        color  progBg    = na(shown) ? na : color.new(color.from_gradient(shown, 0.0, 100.0, lowCol, highCol), 20)
        cellRow(0, "ADR (" + str.tostring(adrLen) + "d " + methodTxt + ")", fmtP(adr), na)
        cellRow(1, "Today's range", fmtP(todayRng), na)
        cellRow(2, "Used", na(usedPct) ? "-" : str.tostring(usedPct, "0") + "%", progBg)
        cellRow(3, "Left to full ADR", fmtP(leftRng), na)
        cellRow(4, "Projected high", fmtP(projHigh), na)
        cellRow(5, "Projected low", fmtP(projLow), na)
        cellRow(6, "Open +/- ½ ADR", na(adr) ? "-" : fmtP(halfUp) + " / " + fmtP(halfDn), na)
        cellRow(7, "Days that reached ADR (" + str.tostring(statLen) + "d)", na(hitRate) ? "-" : str.tostring(hitRate * 100.0, "0") + "%", na)
 
// ─────────────────────────────────────────────────────────────────────────────
// Alerts
// ─────────────────────────────────────────────────────────────────────────────
bool crossedAlert = tfOk and not na(usedPct) and usedPct >= alertPct and (newDay or nz(usedPct[1]) < alertPct)
 
alertcondition(crossedAlert, "Today's range reached alert level", "{{ticker}}: today's range has reached the chosen share of its average daily range.")
 
if crossedAlert
    alert(syminfo.ticker + ": today's range reached " + str.tostring(usedPct, "0") + "% of its " + str.tostring(adrLen) + "-day ADR (" + str.tostring(adr, format.mintick) + ").", alert.freq_once_per_bar)

← 返回列表