Trend Kit: MAs + AVWAP + Golden Cross + Vol% + RS Rating

DinCohen · study · 293 行 · 点赞 26 · TradingView 原页

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

Pine Script

//@version=6
indicator("Trend Kit: MAs + AVWAP + Golden Cross + Vol% + RS", shorttitle = "Trend Kit", overlay = true,
     max_bars_back = 5000, max_labels_count = 500, max_polylines_count = 20)
 
// ───────────────────────── Inputs ─────────────────────────
grpMA     = "Moving Averages"
emaLen    = input.int(20,  "EMA length (blue)",  group = grpMA)
fastLen   = input.int(50,  "Fast DMA (green)",   group = grpMA)
slowLen   = input.int(200, "Slow DMA (red)",     group = grpMA)
showDeath = input.bool(false, "Also mark death crosses (gray)", group = grpMA)
showGC    = input.bool(true, "Mark golden crosses", inline = "gc", group = grpMA)
gcColor   = input.color(#F5B62F, "", inline = "gc", group = grpMA)
gcSize    = input.int(26, "Golden cross size", minval = 10, maxval = 60, group = grpMA)
gcThick   = input.int(2, "Golden cross ring thickness", minval = 1, maxval = 4, group = grpMA)
gcFill    = input.int(85, "Golden cross fill transparency %", minval = 0, maxval = 100, group = grpMA)
 
grpAV     = "Anchored VWAP (orange)"
avColor   = input.color(color.orange, "AVWAP color", group = grpAV)
avWidth   = input.int(3, "Line width", minval = 1, maxval = 5, group = grpAV)
lblMode   = input.string("Text only", "Anchor label style", options = ["Text only", "Tag"], group = grpAV)
lblSize   = input.string("Normal", "Anchor label size", options = ["Small", "Normal", "Large"], group = grpAV)
showScale = input.bool(true, "Show AVWAP value on price scale", group = grpAV)
avSrc     = input.source(hlc3, "Price source", group = grpAV)
useYTD    = input.bool(true,  "YTD (first bar of the year)", group = grpAV)
use52H    = input.bool(true,  "52-week high (52WH)",         group = grpAV)
use52L    = input.bool(false, "52-week low (52WL)",          group = grpAV)
useATH    = input.bool(false, "All-time high (ATH)",         group = grpAV)
useATL    = input.bool(false, "All-time low (ATL)",          group = grpAV)
useCust1  = input.bool(false, "Custom 1", inline = "c1", group = grpAV)
custT1    = input.time(timestamp("2026-01-02"), "", inline = "c1", group = grpAV)
custTxt1  = input.string("AVWAP", "", inline = "c1", group = grpAV)
useCust2  = input.bool(false, "Custom 2", inline = "c2", group = grpAV)
custT2    = input.time(timestamp("2026-06-01"), "", inline = "c2", group = grpAV)
custTxt2  = input.string("AVWAP 2", "", inline = "c2", group = grpAV)
 
grpVol    = "Volume %"
volLen    = input.int(50, "Average volume length", group = grpVol)
 
grpRS     = "RS Rating"
rsDoneOnly = input.bool(false, "Use only completed daily bars", tooltip = "Off (default): updates live, like Fred6724's RS Rating script. On: the rating stays fixed during the day.", group = grpRS)
 
grpTbl    = "Table"
showRSd   = input.bool(true, "Show RS Rating", group = grpTbl)
rsPlace   = input.string("Below 200 DMA (today)", "RS Rating placement", options = ["Below 200 DMA (today)", "Corner"], group = grpTbl)
showVolT  = input.bool(false, "Show Vol %", group = grpTbl)
tblPosStr = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = grpTbl)
 
const int MAX_BACK = 4990
 
// ───────────────────────── Moving averages ─────────────────────────
ema20   = ta.ema(close, emaLen)
smaFast = ta.sma(close, fastLen)
smaSlow = ta.sma(close, slowLen)
 
plot(ema20,   "EMA 20",  color.blue,  2)
plot(smaFast, "50 DMA",  color.green, 2)
plot(smaSlow, "200 DMA", color.red,   2)
 
// ───────────────────────── Golden / death cross ─────────────────────────
golden = ta.crossover(smaFast, smaSlow)
death  = ta.crossunder(smaFast, smaSlow)
 
// One circle per cross: soft yellow fill with a yellow ring, centered where
// the two averages meet. Drawn as labels so it is a single item in settings.
gcY   = (smaFast + smaSlow) / 2
crossMarker(color c) =>
    // faint fill: a solid large circle drawn at the same size as the ring
    label.new(bar_index, gcY, "⬤", style = label.style_label_center, color = color.new(c, 100),
         textcolor = color.new(c, gcFill), size = gcSize)
    // ring: several outlines stacked 1pt apart make the edge thicker
    for t = 0 to gcThick - 1
        label.new(bar_index, gcY, "◯", style = label.style_label_center, color = color.new(c, 100),
             textcolor = c, size = gcSize + t, text_formatting = text.format_bold)
 
if showGC and golden
    crossMarker(gcColor)
if showDeath and death
    crossMarker(color.gray)
 
alertcondition(golden, "Golden Cross", "{{ticker}}: 50 DMA crossed above 200 DMA")
alertcondition(death,  "Death Cross",  "{{ticker}}: 50 DMA crossed below 200 DMA")
 
// ───────────────────────── Anchor tracking ─────────────────────────
// Running sums let AVWAP from any anchor be computed in one subtraction
cumPV = ta.cum(nz(avSrc * volume))
cumV  = ta.cum(nz(volume))
 
var float athVal = na
var int   athIdx = na
if na(athVal) or high > athVal
    athVal := high
    athIdx := bar_index
 
var float atlVal = na
var int   atlIdx = na
if na(atlVal) or low < atlVal
    atlVal := low
    atlIdx := bar_index
 
var int ytdIdx = na
if na(ytdIdx) or year(time) != year(time[1])
    ytdIdx := bar_index
 
var int c1Idx = na
if na(c1Idx) and time >= custT1
    c1Idx := bar_index
 
var int c2Idx = na
if na(c2Idx) and time >= custT2
    c2Idx := bar_index
 
// ───────────────────────── AVWAP drawing ─────────────────────────
// Everything runs in the main script scope (not inside a function) so the
// past-bar lookups like cumPV[k] work correctly when drawing the line.
var polys = array.new<polyline>()
var labs  = array.new<label>()
var vals  = array.new<float>(7, na)   // current AVWAP value per anchor
 
lblSz    = lblSize == "Small" ? size.small : lblSize == "Large" ? size.large : size.normal
textOnly = lblMode == "Text only"
 
if barstate.islast
    for p in polys
        p.delete()
    polys.clear()
    for l in labs
        l.delete()
    labs.clear()
 
    // 52-week high / low by calendar time (works on any timeframe)
    int   cutoff = time - 31536000000
    float hi = na
    float lo = na
    int   hiIdx = na
    int   loIdx = na
    for k = 0 to math.min(bar_index, MAX_BACK)
        if time[k] < cutoff
            break
        if na(hi) or high[k] > hi
            hi    := high[k]
            hiIdx := bar_index - k
        if na(lo) or low[k] < lo
            lo    := low[k]
            loIdx := bar_index - k
 
    // Anchors in a fixed order: YTD, 52WH, 52WL, ATH, ATL, Custom 1, Custom 2
    array<int>    aIdx = array.from(ytdIdx, hiIdx, loIdx, athIdx, atlIdx, c1Idx, c2Idx)
    array<bool>   aOn  = array.from(useYTD, use52H, use52L, useATH, useATL, useCust1, useCust2)
    array<string> aTxt = array.from("YTD", "52WH", "52WL", "ATH", "ATL", custTxt1, custTxt2)
 
    for i = 0 to 6
        vals.set(i, na)
        int idx = aIdx.get(i)
        if aOn.get(i) and not na(idx)
            int off = bar_index - idx
            if off >= 0 and off <= MAX_BACK
                float basePV = nz(cumPV[off + 1])
                float baseV  = nz(cumV[off + 1])
                pts = array.new<chart.point>()
                float lastV = na
                for k = off to 0
                    float dv = cumV[k] - baseV
                    if dv > 0
                        lastV := (cumPV[k] - basePV) / dv
                        pts.push(chart.point.from_index(bar_index - k, lastV))
                if pts.size() > 1
                    polys.push(polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index,
                         line_color = avColor, line_width = avWidth))
                vals.set(i, lastV)
                // Label always sits above the candle the AVWAP starts from
                labs.push(label.new(idx, high[off], aTxt.get(i), yloc = yloc.abovebar, style = label.style_label_down,
                     color = textOnly ? color.new(avColor, 100) : avColor,
                     textcolor = textOnly ? avColor : color.white, size = lblSz))
 
// Current AVWAP values as tags on the price scale
scaleDisp = showScale ? display.price_scale : display.none
plot(barstate.islast ? vals.get(0) : na, "AVWAP YTD",      avColor, display = scaleDisp)
plot(barstate.islast ? vals.get(1) : na, "AVWAP 52WH",     avColor, display = scaleDisp)
plot(barstate.islast ? vals.get(2) : na, "AVWAP 52WL",     avColor, display = scaleDisp)
plot(barstate.islast ? vals.get(3) : na, "AVWAP ATH",      avColor, display = scaleDisp)
plot(barstate.islast ? vals.get(4) : na, "AVWAP ATL",      avColor, display = scaleDisp)
plot(barstate.islast ? vals.get(5) : na, "AVWAP Custom 1", avColor, display = scaleDisp)
plot(barstate.islast ? vals.get(6) : na, "AVWAP Custom 2", avColor, display = scaleDisp)
 
// ───────────────────────── Volume % ─────────────────────────
// Today's volume vs. its average, as % above/below (IBD style)
avgVol = ta.sma(volume, volLen)
volPct = avgVol > 0 ? (volume / avgVol - 1) * 100 : na
 
// ───────────────────────── RS Rating ─────────────────────────
// Same method as Fred6724's "RS Rating": weighted 3/6/9/12-month performance
// vs the S&P 500, converted to 1–99 with seven market-wide levels (daily ranking
// of ~6,600 US stocks, read from the public seed "seed_fred6725_rs_rating") and
// his exact curve between those levels.
rsPerfD() =>
    int n63  = math.min(bar_index, 63)
    int n126 = math.min(bar_index, 126)
    int n189 = math.min(bar_index, 189)
    int n252 = math.min(bar_index, 252)
    0.4 * close / close[n63] + 0.2 * close / close[n126] + 0.2 * close / close[n189] + 0.2 * close / close[n252]
 
stockLive = request.security(syminfo.tickerid, "D", rsPerfD())
benchLive = request.security("SP:SPX",         "D", rsPerfD())
stockDone = request.security(syminfo.tickerid, "D", rsPerfD()[1], lookahead = barmerge.lookahead_on)
benchDone = request.security("SP:SPX",         "D", rsPerfD()[1], lookahead = barmerge.lookahead_on)
rsRaw     = rsDoneOnly ? stockDone / benchDone * 100 : stockLive / benchLive * 100
 
seedVal = request.seed("seed_fred6725_rs_rating", "RSRATING", close, ignore_invalid_symbol = true)
max_bars_back(seedVal, 300)
 
var cuts = array.new<float>()
if barstate.islast
    cuts.clear()
    for i = 0 to 299
        float v = nz(seedVal[i])
        if v != 0 and not cuts.includes(v)
            cuts.push(v)
        if cuts.size() == 7
            break
    cuts.sort(order.descending)
 
// If the daily levels can't be loaded, use Fred's fixed fallback levels
float[] fbCuts = array.from(195.93, 117.11, 99.04, 91.66, 80.96, 53.64, 24.86)
rsCutsLive = cuts.size() == 7
cutAt(int i) =>
    rsCutsLive ? cuts.get(i) : fbCuts.get(i)
 
// Fred6724's curve between two levels (weight = his manual calibration)
attrPct(float sc, float taller, float smaller, float rUp, float rDn, float weight) =>
    float sum = sc + (sc - smaller) * weight
    if sum > taller - 1
        sum := taller - 1
    float k1 = smaller / rDn
    float k2 = (taller - 1) / rUp
    float k3 = (k1 - k2) / (taller - 1 - smaller)
    float r  = sum / (k1 - k3 * (sc - smaller))
    math.max(rDn, math.min(rUp, r))
 
float rsExact = na
if barstate.islast and not na(rsRaw)
    float c0 = cutAt(0)
    float c1 = cutAt(1)
    float c2 = cutAt(2)
    float c3 = cutAt(3)
    float c4 = cutAt(4)
    float c5 = cutAt(5)
    float c6 = cutAt(6)
    rsExact := rsRaw >= c0 ? 99.0 : rsRaw <= c6 ? 1.0 :
         rsRaw >= c1 ? attrPct(rsRaw, c0, c1, 98, 90, 0.33) :
         rsRaw >= c2 ? attrPct(rsRaw, c1, c2, 89, 70, 2.1) :
         rsRaw >= c3 ? attrPct(rsRaw, c2, c3, 69, 50, 0) :
         rsRaw >= c4 ? attrPct(rsRaw, c3, c4, 49, 30, 0) :
         rsRaw >= c5 ? attrPct(rsRaw, c4, c5, 29, 10, 0) :
         attrPct(rsRaw, c5, c6, 9, 2, 0)
rsRating = na(rsExact) ? na : int(math.round(rsExact))
 
// ───────────────────────── Table ─────────────────────────
tblPos = switch tblPosStr
    "Top left"     => position.top_left
    "Bottom right" => position.bottom_right
    "Bottom left"  => position.bottom_left
    => position.top_right
 
var table tbl = table.new(tblPos, 1, 4, bgcolor = color.new(color.black, 100))
 
if barstate.islast
    table.clear(tbl, 0, 0, 0, 3)
    int r = 0
    if showRSd and rsPlace == "Corner"
        table.cell(tbl, 0, r,     "RS Rating", text_color = color.white, text_size = size.small, text_halign = text.align_left)
        table.cell(tbl, 0, r + 1, na(rsRating) ? "–" : str.tostring(rsRating), text_color = color.white,
             text_size = size.large, text_halign = text.align_left)
        r += 2
    if showVolT
        string volTxt = na(volPct) ? "–" : (volPct >= 0 ? "+" : "") + str.tostring(math.round(volPct)) + "%"
        table.cell(tbl, 0, r,     "Vol %", text_color = color.white, text_size = size.small, text_halign = text.align_left)
        table.cell(tbl, 0, r + 1, volTxt, text_color = na(volPct) ? color.gray : volPct >= 0 ? color.lime : color.red,
             text_size = size.large, text_halign = text.align_left)
 
// RS Rating under the 200 DMA on today's bar
var label rsTitleLbl = na
var label rsNumLbl   = na
gapUnit = ta.atr(14)
if barstate.islast
    label.delete(rsTitleLbl)
    label.delete(rsNumLbl)
    if showRSd and rsPlace == "Below 200 DMA (today)" and not na(smaSlow)
        float y = smaSlow - gapUnit
        rsTitleLbl := label.new(bar_index, y, "RS Rating", style = label.style_label_left,
             color = color.new(color.black, 100), textcolor = color.white, size = size.normal)
        rsNumLbl := label.new(bar_index, y, "\n\n" + (na(rsRating) ? "–" : str.tostring(rsRating)),
             style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.white,
             size = size.large)

← 返回列表