Weekly & Daily Retracement Levels

eisfeld · study · 223 行 · 点赞 20 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Weekly / Daily Retracement Levels
//
// Draws the Fibonacci retracement of the current and previous week and/or day,
// anchored between the period's high and low. Direction is detected automatically:
//   • Bearish period (high formed before low) → fib drawn High → Low  (0% at high, 100% at low)
//   • Bullish period (low formed before high) → fib drawn Low → High  (0% at low, 100% at high)
// Levels update live as the current period develops and reset every new period.
 
//@version=6
indicator("Weekly & Daily Retracement Levels", overlay=true, max_lines_count=500, max_labels_count=500)
 
// ══════════════════════════════════════════════════════════════════════════════
// INPUTS
// ══════════════════════════════════════════════════════════════════════════════
string GRP_FIB = "📐 Fibonacci Levels"
bool showFib0    = input.bool(true,  "0%",     inline="f0", group=GRP_FIB)
bool showFib236  = input.bool(false, "23.6%",  inline="f0", group=GRP_FIB)
bool showFib382  = input.bool(true,  "38.2%",  inline="f1", group=GRP_FIB)
bool showFib500  = input.bool(true,  "50%",    inline="f1", group=GRP_FIB)
bool showFib618  = input.bool(true,  "61.8%",  inline="f2", group=GRP_FIB)
bool showFib705  = input.bool(true,  "70.5% (OTE)", inline="f2", group=GRP_FIB)
bool showFib786  = input.bool(true,  "78.6%",  inline="f3", group=GRP_FIB)
bool showFib1    = input.bool(true,  "100%",   inline="f3", group=GRP_FIB)
 
string GRP_HTF = "🗓️ Periods"
bool   showWeekly   = input.bool(true, "Weekly retracement", inline="w", group=GRP_HTF)
string weeklyStyle  = input.string("Solid", "Style", options=["Solid", "Dashed", "Dotted"], inline="w", group=GRP_HTF)
bool   showDaily    = input.bool(true, "Daily retracement", inline="d", group=GRP_HTF)
string dailyStyle   = input.string("Dashed", "Style", options=["Solid", "Dashed", "Dotted"], inline="d", group=GRP_HTF)
bool   showPrevWeekly  = input.bool(true, "Previous week retracement", inline="pw", group=GRP_HTF)
string prevWeeklyStyle = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], inline="pw", group=GRP_HTF)
bool   showPrevDaily   = input.bool(true, "Previous day retracement", inline="pd", group=GRP_HTF)
string prevDailyStyle  = input.string("Dotted", "Style", options=["Solid", "Dashed", "Dotted"], inline="pd", group=GRP_HTF)
bool   useHtfAgg    = input.bool(true, "Use exact HTF high/low (recommended)", group=GRP_HTF,
                     tooltip="ON: pulls the true weekly/daily high/low via request.security. OFF: tracks the extremes from the chart bars seen in the current period.")
 
string GRP_STYLE = "🎨 Style"
bool  extendRight = input.bool(true, "Extend lines to the right edge", group=GRP_STYLE)
int   lineExt     = input.int(20, "Extra bars to the right", minval=0, maxval=500, group=GRP_STYLE)
int   lineWidth   = input.int(1, "Line Width", minval=1, maxval=4, group=GRP_STYLE)
bool  showLabels  = input.bool(true, "Show Price Labels", group=GRP_STYLE)
bool  showConnector = input.bool(true, "Show High→Low connector", group=GRP_STYLE)
color colUp   = input.color(#26A69A, "Bullish period color", group=GRP_STYLE)
color colDn   = input.color(#EF5350, "Bearish period color", group=GRP_STYLE)
color col50   = input.color(#FF9800, "50% level color", group=GRP_STYLE)
color colOte  = input.color(#AB47BC, "OTE (70.5%) color", group=GRP_STYLE)
color colBase = input.color(color.gray, "0% / 100% color", group=GRP_STYLE)
 
// ══════════════════════════════════════════════════════════════════════════════
// PERIOD TRACKING
// ══════════════════════════════════════════════════════════════════════════════
type Period
    string       name
    string       tag
    float        hi
    float        lo
    int          hiBar
    int          loBar
    int          startBar
    float        swingHi
    float        swingLo
    array<line>  lines
    array<label> lbls
    line         conn
 
f_newPeriod(string name, string tag) =>
    Period.new(name, tag, lines=array.new<line>(), lbls=array.new<label>())
 
f_lineStyle(string s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
 
method setSwing(Period p, float htfHi, float htfLo) =>
    p.swingHi := useHtfAgg ? htfHi : p.hi
    p.swingLo := useHtfAgg ? htfLo : p.lo
 
method snapshot(Period p, Period src) =>
    p.hi       := src.hi
    p.lo       := src.lo
    p.hiBar    := src.hiBar
    p.loBar    := src.loBar
    p.startBar := src.startBar
 
// Tracks running extremes on chart bars (with the bar_index where they occurred)
method update(Period p, bool isNew, float htfHi, float htfLo) =>
    if isNew or na(p.hi)
        p.hi       := high
        p.lo       := low
        p.hiBar    := bar_index
        p.loBar    := bar_index
        p.startBar := bar_index
    else
        if high > p.hi
            p.hi    := high
            p.hiBar := bar_index
        if low < p.lo
            p.lo    := low
            p.loBar := bar_index
    p.setSwing(htfHi, htfLo)
 
// Bearish if the high was printed before the low
method bearish(Period p) =>
    p.hiBar <= p.loBar
 
method span(Period p) =>
    p.swingHi - p.swingLo
 
// Higher fib % sit toward the direction the period is retracing INTO.
// Bearish: 0% = low,  100% = high → level = low  + range * fib
// Bullish: 0% = high, 100% = low  → level = high - range * fib
method level(Period p, float fib) =>
    p.bearish() ? p.swingLo + p.span() * fib : p.swingHi - p.span() * fib
 
// Exact high/low of the current (developing) and previous week/day from the HTF series
float wkHighTF  = request.security(syminfo.tickerid, "W", high,    lookahead=barmerge.lookahead_on)
float wkLowTF   = request.security(syminfo.tickerid, "W", low,     lookahead=barmerge.lookahead_on)
float dyHighTF  = request.security(syminfo.tickerid, "D", high,    lookahead=barmerge.lookahead_on)
float dyLowTF   = request.security(syminfo.tickerid, "D", low,     lookahead=barmerge.lookahead_on)
float pwkHighTF = request.security(syminfo.tickerid, "W", high[1], lookahead=barmerge.lookahead_on)
float pwkLowTF  = request.security(syminfo.tickerid, "W", low[1],  lookahead=barmerge.lookahead_on)
float pdyHighTF = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
float pdyLowTF  = request.security(syminfo.tickerid, "D", low[1],  lookahead=barmerge.lookahead_on)
 
var Period weekly     = f_newPeriod("Week",      "W")
var Period daily      = f_newPeriod("Day",       "D")
var Period prevWeekly = f_newPeriod("Prev Week", "PW")
var Period prevDaily  = f_newPeriod("Prev Day",  "PD")
 
bool newWeek = timeframe.change("W")
bool newDay  = timeframe.change("D")
 
// Roll the just-completed period into "previous" before the current one resets
if newWeek and not na(weekly.hi)
    prevWeekly.snapshot(weekly)
if newDay and not na(daily.hi)
    prevDaily.snapshot(daily)
 
weekly.update(newWeek, wkHighTF, wkLowTF)
daily.update(newDay,   dyHighTF, dyLowTF)
prevWeekly.setSwing(pwkHighTF, pwkLowTF)
prevDaily.setSwing(pdyHighTF, pdyLowTF)
 
// ══════════════════════════════════════════════════════════════════════════════
// DRAWING
// ══════════════════════════════════════════════════════════════════════════════
method clearDrawings(Period p) =>
    for ln in p.lines
        ln.delete()
    p.lines.clear()
    for lb in p.lbls
        lb.delete()
    p.lbls.clear()
    p.conn.delete()
 
method drawLevel(Period p, bool show, float fib, string name, color col, int leftBar, int rightBar, string style) =>
    if show
        float price = p.level(fib)
        p.lines.push(line.new(leftBar, price, rightBar, price, color=col, width=lineWidth, style=style))
        if showLabels
            p.lbls.push(label.new(rightBar, price,
                 p.tag + " " + name + "  " + str.tostring(price, format.mintick),
                 style=label.style_none, textcolor=col, size=size.small, textalign=text.align_left))
 
method draw(Period p, bool enabled, string styleName) =>
    p.clearDrawings()
    float rng = p.span()
    if enabled and not na(rng) and rng > 0
        int    leftBar  = nz(p.startBar, bar_index)
        int    rightBar = extendRight ? bar_index + lineExt : bar_index
        string style    = f_lineStyle(styleName)
        color  colMid   = p.bearish() ? colDn : colUp
 
        if showConnector
            p.conn := line.new(p.hiBar, p.swingHi, p.loBar, p.swingLo,
                 color=colMid, width=1, style=line.style_dashed)
 
        p.drawLevel(showFib0,   0.0,   "0%",        colBase, leftBar, rightBar, style)
        p.drawLevel(showFib236, 0.236, "23.6%",     colMid,  leftBar, rightBar, style)
        p.drawLevel(showFib382, 0.382, "38.2%",     colMid,  leftBar, rightBar, style)
        p.drawLevel(showFib500, 0.5,   "50%",       col50,   leftBar, rightBar, style)
        p.drawLevel(showFib618, 0.618, "61.8%",     colMid,  leftBar, rightBar, style)
        p.drawLevel(showFib705, 0.705, "70.5% OTE", colOte,  leftBar, rightBar, style)
        p.drawLevel(showFib786, 0.786, "78.6%",     colMid,  leftBar, rightBar, style)
        p.drawLevel(showFib1,   1.0,   "100%",      colBase, leftBar, rightBar, style)
 
if barstate.islast
    weekly.draw(showWeekly, weeklyStyle)
    daily.draw(showDaily, dailyStyle)
    prevWeekly.draw(showPrevWeekly, prevWeeklyStyle)
    prevDaily.draw(showPrevDaily, prevDailyStyle)
 
// ══════════════════════════════════════════════════════════════════════════════
// INFO TABLE
// ══════════════════════════════════════════════════════════════════════════════
var table infoTbl = table.new(position.top_right, 5, 5, bgcolor=color.new(color.black, 80), border_width=1)
 
method fillColumn(Period p, int col) =>
    table.cell(infoTbl, col, 0, p.name, text_color=color.white, text_size=size.small)
    table.cell(infoTbl, col, 1, p.bearish() ? "▼ BEARISH" : "▲ BULLISH",
         text_color=p.bearish() ? colDn : colUp, text_size=size.small)
    table.cell(infoTbl, col, 2, str.tostring(p.swingHi, format.mintick), text_color=colDn, text_size=size.small)
    table.cell(infoTbl, col, 3, str.tostring(p.swingLo, format.mintick), text_color=colUp, text_size=size.small)
    table.cell(infoTbl, col, 4, str.tostring(p.span(), format.mintick), text_color=color.white, text_size=size.small)
 
if barstate.islast
    table.clear(infoTbl, 0, 0, 4, 4)
    if showWeekly or showDaily or showPrevWeekly or showPrevDaily
        table.cell(infoTbl, 0, 1, "Bias",  text_color=color.white, text_size=size.small)
        table.cell(infoTbl, 0, 2, "High",  text_color=color.white, text_size=size.small)
        table.cell(infoTbl, 0, 3, "Low",   text_color=color.white, text_size=size.small)
        table.cell(infoTbl, 0, 4, "Range", text_color=color.white, text_size=size.small)
    int col = 1
    if showWeekly
        weekly.fillColumn(col)
        col += 1
    if showDaily
        daily.fillColumn(col)
        col += 1
    if showPrevWeekly
        prevWeekly.fillColumn(col)
        col += 1
    if showPrevDaily
        prevDaily.fillColumn(col)

← 返回列表