Weekly Candle Split by Daily High/Low (Sun ETH)

klazalier · study · 268 行 · 点赞 366 · TradingView 原页

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

Pine Script

//@version=6
indicator("Weekly Candle Split by Daily High/Low (Sun ETH)", shorttitle="WCS", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// =====================================================================
// Weekly Candle Split by Daily High / Low
// ---------------------------------------------------------------------
// Builds a weekly candle from the daily bars (week begins with the Sunday
// evening ETH session, i.e. the "Monday" daily bar on CME futures which
// opens Sunday 6pm ET). The candle body is split into segments at every
// daily high and low (Mon-Fri), each colored by the first day that traded
// in that zone. The current week also gets full daily high/low lines and
// labels. Optionally, previous weeks are shown as additional candles.
//
// Use on any intraday or daily chart. For futures (NQ, MNQ, ES...) the
// daily bar already contains the full ETH session. For stocks/ETFs turn on
// extended hours in chart settings if you want ETH included.
// =====================================================================
 
// ------------------------------- Inputs -------------------------------
grpLayout = "Layout"
offsetBars  = input.int(12, "Candle offset from last bar", minval=1, group=grpLayout)
candleWidth = input.int(8,  "Candle width (bars)", minval=2, group=grpLayout)
 
grpPrev = "Previous Weeks"
weeksToShow = input.int(1, "Weeks to show (1 = current week only)", minval=1, maxval=8, group=grpPrev)
weekGap     = input.int(3, "Gap between candles (bars)", minval=0, group=grpPrev)
prevSide    = input.string("Left of current", "Previous weeks position", options=["Left of current", "Right of current"], tooltip="Left = oldest to newest, current week on the right. Right = current week stays closest to price and older weeks continue to its right (keeps the current week's lines from crossing the older candles).", group=grpPrev)
 
grpLines = "Daily High / Low Lines"
lineWidth  = input.int(1, "Line width", minval=1, maxval=4, group=grpLines)
lineStyleS = input.string("Solid", "Line style", options=["Solid", "Dashed", "Dotted"], group=grpLines)
lineCol    = input.color(color.white, "Line color", group=grpLines)
highCol    = input.color(color.rgb(30, 200, 30), "High label color", group=grpLines)
lowCol     = input.color(color.rgb(240, 70, 90), "Low label color", group=grpLines)
 
grpLabels = "Labels"
showLabels   = input.bool(true,  "Show labels (current week)", group=grpLabels)
compactLabel = input.bool(false, "Compact labels (Mon H / Mon L)", group=grpLabels)
showPrice    = input.bool(false, "Show price in label", group=grpLabels)
labelSizeS   = input.string("Small", "Label size", options=["Tiny", "Small", "Normal"], group=grpLabels)
 
grpCandle = "Weekly Candle"
upCol        = input.color(color.rgb(120, 200, 120), "Bullish week color", group=grpCandle)
downCol      = input.color(color.rgb(240, 70, 90),   "Bearish week color", group=grpCandle)
showSegments = input.bool(true, "Shade segments between levels", group=grpCandle)
segAlphaA    = input.int(75, "Segment transparency A", minval=0, maxval=100, group=grpCandle)
segAlphaB    = input.int(88, "Segment transparency B", minval=0, maxval=100, group=grpCandle)
colorByDay   = input.bool(true, "Color segments by day of week", tooltip="Each segment takes the color of the first day that traded in that price zone. Turn off for the alternating shades.", group=grpCandle)
dayAlpha     = input.int(45, "Day segment transparency", minval=0, maxval=100, group=grpCandle)
showDayText  = input.bool(true, "Show day name inside candle", group=grpCandle)
dayTextCol   = input.color(color.white, "Day name text color", group=grpCandle)
dayTextSizeS = input.string("Normal", "Day name text size", options=["Tiny", "Small", "Normal", "Large"], group=grpCandle)
 
grpDays = "Day Colors"
monCol = input.color(color.rgb(41, 121, 255),  "Monday",    group=grpDays)
tueCol = input.color(color.rgb(255, 152, 0),   "Tuesday",   group=grpDays)
wedCol = input.color(color.rgb(255, 235, 59),  "Wednesday", group=grpDays)
thuCol = input.color(color.rgb(171, 71, 188),  "Thursday",  group=grpDays)
friCol = input.color(color.rgb(0, 200, 180),   "Friday",    group=grpDays)
 
// ------------------------------ Helpers -------------------------------
lineStyle = lineStyleS == "Dashed" ? line.style_dashed : lineStyleS == "Dotted" ? line.style_dotted : line.style_solid
lblSize   = labelSizeS == "Tiny" ? size.tiny : labelSizeS == "Normal" ? size.normal : size.small
dayTxtSize = dayTextSizeS == "Tiny" ? size.tiny : dayTextSizeS == "Small" ? size.small : dayTextSizeS == "Large" ? size.large : size.normal
prevLeft  = prevSide == "Left of current"
 
fullNames  = array.from("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
shortNames = array.from("Mon", "Tue", "Wed", "Thu", "Fri")
dayCols    = array.from(monCol, tueCol, wedCol, thuCol, friCol)
 
validTF = timeframe.isintraday or timeframe.isdaily
 
// --------------------- Daily data (exchange session) -------------------
// The daily bar's close time falls on the weekday it is named after, even
// though a futures "Monday" bar opens Sunday evening.
[dH, dL, dO, dC, dTc] = request.security(syminfo.tickerid, "D", [high, low, open, close, time_close], lookahead=barmerge.lookahead_off)
 
// ------------------------------ State ---------------------------------
// Current week (index 0 = Monday ... 4 = Friday)
var hiA  = array.new_float(5, na)
var loA  = array.new_float(5, na)
var opA  = array.new_float(5, na)
var clA  = array.new_float(5, na)
var idxA = array.new_int(5, na)
// Completed weeks, 5 values per week, oldest first
var histHi = array.new_float()
var histLo = array.new_float()
var histOp = array.new_float()
var histCl = array.new_float()
var int lastD = na
 
if validTF and not na(dTc)
    d = dayofweek(dTc - 1, syminfo.timezone) - 2   // Mon=0 ... Fri=4
    if d >= 0 and d <= 4
        // new week started (day index went backwards)
        if not na(lastD) and d < lastD
            // archive the finished week
            for i = 0 to 4
                array.push(histHi, array.get(hiA, i))
                array.push(histLo, array.get(loA, i))
                array.push(histOp, array.get(opA, i))
                array.push(histCl, array.get(clA, i))
            // keep at most 12 archived weeks
            while array.size(histHi) > 60
                for r = 1 to 5
                    array.remove(histHi, 0)
                    array.remove(histLo, 0)
                    array.remove(histOp, 0)
                    array.remove(histCl, 0)
            // reset current week
            for i = 0 to 4
                array.set(hiA, i, na)
                array.set(loA, i, na)
                array.set(opA, i, na)
                array.set(clA, i, na)
                array.set(idxA, i, na)
        array.set(hiA, d, dH)
        array.set(loA, d, dL)
        array.set(opA, d, dO)
        array.set(clA, d, dC)
        if na(array.get(idxA, d))
            array.set(idxA, d, bar_index)
        lastD := d
 
// ------------------------------ Drawing -------------------------------
var line[]  lineArr  = array.new_line()
var label[] labelArr = array.new_label()
var box[]   boxArr   = array.new_box()
 
// Draws one weekly candle at x0. isCur = true adds the full daily high/low
// lines (from the day they formed) and the aligned labels.
drawWeek(float[] hiW, float[] loW, float[] opW, float[] clW, int[] idxW, int x0, bool isCur, line[] lns, label[] lbls, box[] bxs) =>
    float wkHigh = na
    float wkLow  = na
    float wkOpen = na
    float wkClose = na
    for i = 0 to 4
        h = array.get(hiW, i)
        l = array.get(loW, i)
        if not na(h)
            wkHigh := na(wkHigh) ? h : math.max(wkHigh, h)
            wkLow  := na(wkLow)  ? l : math.min(wkLow, l)
            if na(wkOpen)
                wkOpen := array.get(opW, i)
            wkClose := array.get(clW, i)
 
    if not na(wkHigh)
        x1 = x0 + candleWidth
        xm = x0 + int(candleWidth / 2)
 
        bodyHi = math.max(wkOpen, wkClose)
        bodyLo = math.min(wkOpen, wkClose)
        candleCol = wkClose >= wkOpen ? upCol : downCol
 
        // segments of the body split at each daily high/low
        if showSegments
            pts = array.new_float()
            array.push(pts, bodyLo)
            array.push(pts, bodyHi)
            for i = 0 to 4
                h = array.get(hiW, i)
                l = array.get(loW, i)
                if not na(h) and h > bodyLo and h < bodyHi
                    array.push(pts, h)
                if not na(l) and l > bodyLo and l < bodyHi
                    array.push(pts, l)
            array.sort(pts, order.ascending)
            segLo  = array.new_float()
            segHi  = array.new_float()
            segOwn = array.new_int()
            for i = 0 to array.size(pts) - 2
                a = array.get(pts, i)
                b = array.get(pts, i + 1)
                if b > a
                    segCol = color.new(candleCol, i % 2 == 0 ? segAlphaA : segAlphaB)
                    if colorByDay
                        // owner = first day whose high/low range contains this segment
                        // (falls back to the nearest day if no day covers it)
                        mid = (a + b) / 2
                        owner = -1
                        bestDist = 1e10
                        for k = 0 to 4
                            hk = array.get(hiW, k)
                            lk = array.get(loW, k)
                            if not na(hk)
                                dist = mid > hk ? mid - hk : mid < lk ? lk - mid : 0.0
                                if dist < bestDist
                                    bestDist := dist
                                    owner := k
                        if owner >= 0
                            segCol := color.new(array.get(dayCols, owner), dayAlpha)
                        array.push(segLo, a)
                        array.push(segHi, b)
                        array.push(segOwn, owner)
                    array.push(bxs, box.new(x0, b, x1, a, border_color=na, bgcolor=segCol))
 
            // day name centered in each run of same-day segments
            if colorByDay and showDayText
                nSeg = array.size(segOwn)
                if nSeg > 0
                    runStart = 0
                    for j = 0 to nSeg - 1
                        bool isEnd = true
                        if j < nSeg - 1
                            isEnd := array.get(segOwn, j + 1) != array.get(segOwn, j)
                        if isEnd
                            own = array.get(segOwn, runStart)
                            if own >= 0
                                runLo = array.get(segLo, runStart)
                                runHi = array.get(segHi, j)
                                array.push(lbls, label.new(xm, (runLo + runHi) / 2, array.get(fullNames, own), style=label.style_label_center, color=color.new(color.black, 100), textcolor=dayTextCol, size=dayTxtSize))
                            runStart := j + 1
 
        // weekly body outline + wicks
        array.push(bxs, box.new(x0, bodyHi, x1, bodyLo, border_color=candleCol, border_width=2, bgcolor=na))
        if wkHigh > bodyHi
            array.push(lns, line.new(xm, bodyHi, xm, wkHigh, color=candleCol, width=2))
        if wkLow < bodyLo
            array.push(lns, line.new(xm, bodyLo, xm, wkLow, color=candleCol, width=2))
 
        // daily high / low lines
        for i = 0 to 4
            h = array.get(hiW, i)
            l = array.get(loW, i)
            if not na(h)
                if isCur
                    sx = array.get(idxW, i)
                    if not na(sx)
                        array.push(lns, line.new(sx, h, x1, h, color=lineCol, width=lineWidth, style=lineStyle))
                        array.push(lns, line.new(sx, l, x1, l, color=lineCol, width=lineWidth, style=lineStyle))
                        // small tick at the day the level formed
                        array.push(lns, line.new(sx, h, sx, l, color=color.new(lineCol, 55), width=1))
                        if showLabels
                            nm = compactLabel ? array.get(shortNames, i) : array.get(fullNames, i)
                            hTxt = nm + (compactLabel ? " H" : " High") + (showPrice ? "  " + str.tostring(h, format.mintick) : "")
                            lTxt = nm + (compactLabel ? " L" : " Low")  + (showPrice ? "  " + str.tostring(l, format.mintick) : "")
                            array.push(lbls, label.new(x1, h, hTxt, style=label.style_label_left, color=color.new(color.black, 100), textcolor=highCol, size=lblSize))
                            array.push(lbls, label.new(x1, l, lTxt, style=label.style_label_left, color=color.new(color.black, 100), textcolor=lowCol, size=lblSize))
                else
                    // previous weeks: short divider lines across the candle only
                    array.push(lns, line.new(x0, h, x1, h, color=color.new(lineCol, 50), width=1, style=lineStyle))
                    array.push(lns, line.new(x0, l, x1, l, color=color.new(lineCol, 50), width=1, style=lineStyle))
    true
 
if barstate.islast and validTF
    // clear previous drawings
    while array.size(lineArr) > 0
        line.delete(array.pop(lineArr))
    while array.size(labelArr) > 0
        label.delete(array.pop(labelArr))
    while array.size(boxArr) > 0
        box.delete(array.pop(boxArr))
 
    nHist = int(array.size(histHi) / 5)
    nShow = math.min(weeksToShow, nHist + 1)
    base  = bar_index + offsetBars
    pitch = candleWidth + weekGap
 
    // previous weeks (w = 1 is the most recent completed week)
    if nShow > 1
        for w = 1 to nShow - 1
            hs = (nHist - w) * 5
            px = prevLeft ? base + (nShow - 1 - w) * pitch : base + w * pitch
            drawWeek(array.slice(histHi, hs, hs + 5), array.slice(histLo, hs, hs + 5), array.slice(histOp, hs, hs + 5), array.slice(histCl, hs, hs + 5), idxA, px, false, lineArr, labelArr, boxArr)
 
    // current week
    cx = prevLeft ? base + (nShow - 1) * pitch : base
    drawWeek(hiA, loA, opA, clA, idxA, cx, true, lineArr, labelArr, boxArr)

← 返回列表