本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartingCycles
// v0.2 · 2026-11-12
//@version=6
indicator("Golden Cross Cycles", "GC Cycles", overlay = true, max_boxes_count = 500, max_labels_count = 500)
// --- Constants ---
const string GP_CALC = "Calculation"
const string GP_DISPLAY = "Display"
const string GP_SIGNALS = "Signals"
const string GP_TABLE = "Table"
const color FAST_COLOR = #2962FF
const color SLOW_COLOR = #F7931E
const color LIGHT_UP = #00796B
const color LIGHT_DOWN = #C92626
const float MS_PER_DAY = 86400000.0
const string NOW_TIP = "Golden: the phase that started on the first daily close at least Price Gap above the slow SMA after a golden cross (often the cross day). It holds through later crosses that never reach the gap. Death: the same the other way."
const string SO_FAR_TIP = "Change from the daily close on the day the phase started to the latest close, and how long the phase has run."
const string HISTORY_TIP = "Completed phases on this chart: how many, and their median change (from the close on the day a phase started to the close on the day the next one started) and median length. Weekly and monthly charts miss a phase change that reverses inside one bar; the daily chart counts every one. Only the history loaded on the chart is counted. History, not a forecast."
// --- Inputs ---
int fastInput = input.int(50, "SMA Lengths", minval = 2, maxval = 400, inline = "len", group = GP_CALC, display = display.none)
int slowInput = input.int(200, "", minval = 3, maxval = 1000, inline = "len", group = GP_CALC, tooltip = "Fast and slow simple moving averages, in days. Always computed on daily closes, so daily, weekly and monthly charts show the same lines and the same crosses. 50 and 200 are the usual golden-cross lengths; the slow length is raised to at least fast + 1.", display = display.none)
float priceGapInput = input.float(5.0, "Price Gap %", minval = 0, maxval = 20, step = 0.5, group = GP_CALC, tooltip = "Filters out small crosses. After a golden cross, a golden phase starts on the first daily close at least this far above the slow SMA; after a death cross, a death phase starts on the first close this far below it. Until then the current phase holds.\n\n0: every cross starts a phase on its own day. 5% (default): most phases still start on the cross day.", display = display.none)
color upColorInput = input.color(color.teal, "Colors", inline = "col", group = GP_DISPLAY, display = display.none)
color downColorInput = input.color(color.red, "", inline = "col", group = GP_DISPLAY, tooltip = "Golden phases and crosses, death phases and crosses. The two SMA lines are colored in the Style tab.", display = display.none)
bool boxesInput = input.bool(true, "Phase Boxes", group = GP_DISPLAY, display = display.none)
bool labelsInput = input.bool(true, "Phase Labels", group = GP_DISPLAY, tooltip = "Each phase's change from its start to the next phase's start, and its length: above a golden phase, below a death phase. The phase in progress says \"so far\".", display = display.none)
bool markersInput = input.bool(true, "Cross Markers", group = GP_SIGNALS, tooltip = "GC under the bar where the fast SMA crosses above the slow one, DC over the bar where it crosses below. The phase box starts on the first day after the cross that the close is Price Gap beyond the slow SMA (often the same day); a cross that never gets there keeps its marker but gets no box.", display = display.none)
bool confirmedOnlyInput = input.bool(false, "Confirmed Bars Only", group = GP_SIGNALS, tooltip = "Shows a cross marker and starts a new phase only after the bar closes. On the live bar the averages move, so a cross can appear and then vanish. The Any alert() alert waits for the close; for the named alerts choose Once Per Bar Close.", display = display.none)
string tableStyleInput = input.string("Full", "Table", options = ["Full", "Compact", "Off"], inline = "tbl", group = GP_TABLE, display = display.none)
string textSizeInput = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "tbl", group = GP_TABLE, tooltip = "What the table shows, and the text size of the table and labels.\n\nFull: the current phase, then the history of completed phases. Compact: the current phase only. Off: no table (a message still shows if the chart isn't supported).", display = display.none)
string tableYInput = input.string("Bottom", "Position", options = ["Top", "Middle", "Bottom"], inline = "pos", group = GP_TABLE, display = display.none)
string tableXInput = input.string("Right", "", options = ["Left", "Center", "Right"], inline = "pos", group = GP_TABLE, tooltip = "Where the table sits on the chart: vertical, then horizontal.", display = display.none)
string themeInput = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = GP_TABLE, tooltip = "Auto follows the chart background. Dark and Light force the colors of the table and the label text.", display = display.none)
string textSize = str.lower(textSizeInput)
// The slow average stays longer than the fast one
int slowLen = math.max(slowInput, fastInput + 1)
// Theme palette (FFV:IE's table look). Declared before the functions because the helpers read it.
bool isLight = themeInput == "Light" or (themeInput == "Auto" and (color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color)) / 3 > 128)
color themeText = isLight ? #131722 : #ffffff
color themeHeader = color.new(isLight ? #d9e1ec : #1e222d, 25)
color themeCell = color.new(isLight ? #fafbfc : #131722, 25)
color themeGrid = color.new(themeText, 90)
color themeUp = isLight and upColorInput == color.teal ? LIGHT_UP : upColorInput
color themeDown = isLight and downColorInput == color.red ? LIGHT_DOWN : downColorInput
// --- Functions ---
// @function The two SMAs, the trend state and the latest cross day, computed on daily bars.
// @param fastDays (int) Fast SMA length in days.
// @param slowDays (int) Slow SMA length in days.
// @param priceGap (float) How far the close must be beyond the slow SMA, as a fraction, before a phase starts.
// @returns [fast SMA, slow SMA, phase (1 golden, -1 death, 0 not yet known), time and close of the day the latest phase started, daily close, which SMA is on top (1 fast, -1 slow, 0 not yet known), the daily bar's time]
dailyCycle(int fastDays, int slowDays, float priceGap) =>
float fastMa = ta.sma(close, fastDays)
float slowMa = ta.sma(close, slowDays)
var int state = 0
var int order = 0
var int crossTime = na
var float crossClose = na
// The actual cross: which average is on top (equal averages keep the previous order)
order := na(slowMa) ? 0 : fastMa > slowMa ? 1 : fastMa < slowMa ? -1 : order
// A phase starts once the averages have crossed AND the close is priceGap beyond the slow SMA
// (with no gap, on the cross itself); otherwise the current phase holds
bool goldenNow = order == 1 and (priceGap <= 0 or close >= slowMa * (1 + priceGap))
bool deathNow = order == -1 and (priceGap <= 0 or close <= slowMa * (1 - priceGap))
int newState = na(slowMa) ? 0 : goldenNow ? 1 : deathNow ? -1 : state
if newState != 0 and state != 0 and newState != state
crossTime := time
crossClose := close
if newState != 0
state := newState
[fastMa, slowMa, state, crossTime, crossClose, close, order, time]
// @function A change as "+12.3%" or "-4.5%".
pctText(float v) =>
na(v) ? "–" : (v >= 0 ? "+" : "") + str.tostring(v * 100, "0.0") + "%"
// @function A length in calendar days as "45 days", "8 mo" or "2.1 yrs".
durationText(float days) =>
na(days) ? "–" : days < 60 ? str.tostring(math.round(days)) + " days" : days < 730 ? str.tostring(math.round(days / 30.44)) + " mo" : str.tostring(days / 365.25, "0.0") + " yrs"
// @function A bar time as "Nov 9, 2026" in the symbol's timezone.
dateText(int t) =>
na(t) ? "" : str.format_time(t, "MMM d, yyyy", syminfo.timezone)
// @function Completed phases as ["N · median +x% · length", "k of N (p%)"], where k counts the phases that moved their own way.
// @param changes (array<float>) Each phase's change, cross-day close to the next cross-day close.
// @param days (array<float>) Each phase's length in calendar days.
// @param dir (int) 1 for golden phases (counts those that ended higher), -1 for death phases (ended lower).
historyText(array<float> changes, array<float> days, int dir) =>
int n = changes.size()
int withTrend = 0
for v in changes
if v * dir > 0
withTrend += 1
string summary = n == 0 ? "None yet" : str.tostring(n) + " · median " + pctText(changes.median()) + " · " + durationText(days.median())
string trend = n == 0 ? "–" : str.tostring(withTrend) + " of " + str.tostring(n) + " (" + str.tostring(100.0 * withTrend / n, "0") + "%)"
[summary, trend]
// @function A phase label's two lines: change, then bars and calendar length.
phaseText(float change, int bars, float days, bool live) =>
pctText(change) + (live ? " so far" : "") + "\n" + str.tostring(bars) + " bars · " + durationText(days)
// @function Writes one table cell in the theme's text size, with an optional tooltip.
setCell(table t, int c, int r, string txt, color bg, color fg, string align, string tip = "") =>
table.cell(t, c, r, txt, bgcolor = bg, text_color = fg, text_size = textSize, text_halign = align, tooltip = tip)
// @function One table row: label on the header shade, value in its meaning color; both carry the tooltip.
setRow(table t, int r, string lbl, string value, color fg, string tip) =>
setCell(t, 0, r, lbl, themeHeader, themeText, text.align_left, tip)
setCell(t, 1, r, value, themeCell, fg, text.align_right, tip)
// --- Calculations ---
// Daily, weekly and monthly charts on time-based bars (Heikin Ashi uses the standard prices)
bool supported = (timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly) and (chart.is_standard or chart.is_heikinashi)
// The chart's own symbol (keeping its session and dividend adjustment); on Heikin Ashi the standard
// prices in the chart's session. The SMAs come from daily bars; on a weekly or monthly chart each bar
// gets the values of its last daily bar, so nothing comes from the future. dTime is that daily bar's
// time, so the phase in progress is measured to the latest day, not to the start of the week or month.
string srcTicker = chart.is_standard ? syminfo.tickerid : ticker.modify(ticker.standard(syminfo.tickerid), syminfo.session)
[fastMa, slowMa, dState, dCrossTime, dCrossClose, dClose, dOrder, dTime] = request.security(srcTicker, "D", dailyCycle(fastInput, slowLen, priceGapInput / 100))
[stdHigh, stdLow] = request.security(srcTicker, timeframe.period, [high, low])
// A phase starts on the first day after a cross that the close is Price Gap beyond the slow SMA (often
// the cross day itself), and is measured from that day's close to the close of the day the next phase
// starts: known on the day, never in hindsight. On weekly and monthly bars a change that reverses
// inside one bar leaves the state unchanged and is not counted.
var int lastState = 0
var int phaseDir = 0
var int phaseStartTime = na
var float phaseStartPrice = na
var int phaseStartBar = na
var float phaseHigh = na
var float phaseLow = na
var box phaseBox = na
var label phaseLabel = na
var array<float> goldenChanges = array.new<float>()
var array<float> goldenDays = array.new<float>()
var array<float> deathChanges = array.new<float>()
var array<float> deathDays = array.new<float>()
bool canStart = not confirmedOnlyInput or barstate.isconfirmed
bool isStart = supported and lastState != 0 and dState != 0 and dState != lastState and canStart
bool isGoldenStart = isStart and dState == 1
bool isDeathStart = isStart and dState == -1
// The actual crosses, for the GC/DC markers and their alerts. A cross that never reaches the price gap
// gets a marker but starts no phase.
var int lastOrder = 0
bool isCrossBar = supported and lastOrder != 0 and dOrder != 0 and dOrder != lastOrder and canStart
bool isGoldenCross = isCrossBar and dOrder == 1
bool isDeathCross = isCrossBar and dOrder == -1
if supported and dOrder != 0 and (lastOrder == 0 or canStart)
lastOrder := dOrder
if isStart
// Close the phase that just ended (the state before the first cross has no start, so it is not a phase)
if not na(phaseStartTime)
float change = dCrossClose / phaseStartPrice - 1
float days = (dCrossTime - phaseStartTime) / MS_PER_DAY
if phaseDir == 1
goldenChanges.push(change)
goldenDays.push(days)
else
deathChanges.push(change)
deathDays.push(days)
if not na(phaseBox)
phaseBox.set_right(dCrossTime)
if not na(phaseLabel)
phaseLabel.set_x(phaseStartTime + int((dCrossTime - phaseStartTime) / 2))
phaseLabel.set_text(phaseText(change, bar_index - phaseStartBar, days, false))
// Open the new phase on the cross day
phaseDir := dState
phaseStartTime := dCrossTime
phaseStartPrice := dCrossClose
phaseStartBar := bar_index
phaseHigh := stdHigh
phaseLow := stdLow
color c = dState == 1 ? upColorInput : downColorInput
phaseBox := boxesInput ? box.new(dCrossTime, stdHigh, dTime, stdLow, border_color = color.new(c, 70), bgcolor = color.new(c, 90), xloc = xloc.bar_time) : na
phaseLabel := labelsInput ? label.new(dCrossTime, dState == 1 ? stdHigh : stdLow, "", xloc = xloc.bar_time, style = dState == 1 ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = dState == 1 ? themeUp : themeDown, size = textSize) : na
else if not na(phaseStartTime)
phaseHigh := math.max(phaseHigh, stdHigh)
phaseLow := math.min(phaseLow, stdLow)
if supported and dState != 0 and (lastState == 0 or canStart)
lastState := dState
// The phase in progress: its box spans the prices so far, its label the change so far
if not na(phaseStartTime)
if not na(phaseBox)
phaseBox.set_top(phaseHigh)
phaseBox.set_bottom(phaseLow)
phaseBox.set_right(dTime)
if not na(phaseLabel)
phaseLabel.set_xy(phaseStartTime + int((dTime - phaseStartTime) / 2), phaseDir == 1 ? phaseHigh : phaseLow)
phaseLabel.set_text(phaseText(dClose / phaseStartPrice - 1, bar_index - phaseStartBar, (dTime - phaseStartTime) / MS_PER_DAY, true))
// --- Visuals ---
plot(supported ? fastMa : na, "Fast SMA", FAST_COLOR, 2)
plot(supported ? slowMa : na, "Slow SMA", SLOW_COLOR, 2)
plotshape(markersInput and isGoldenCross, "Golden Cross", shape.triangleup, location.belowbar, themeUp, text = "GC", textcolor = themeUp, size = size.tiny)
plotshape(markersInput and isDeathCross, "Death Cross", shape.triangledown, location.abovebar, themeDown, text = "DC", textcolor = themeDown, size = size.tiny)
var table cycleTable = table.new(str.lower(tableYInput) + "_" + str.lower(tableXInput), 2, 7, border_width = 1)
if barstate.islast and (tableStyleInput != "Off" or not supported or na(slowMa))
cycleTable.clear(0, 0, 1, 6)
cycleTable.set_border_color(themeGrid)
// Never a blank chart: say what is missing, even with the table off
if not supported
setCell(cycleTable, 0, 0, "Golden Cross Cycles needs a daily, weekly or monthly chart", themeHeader, themeText, text.align_left)
else if na(slowMa)
setCell(cycleTable, 0, 0, "Golden Cross Cycles needs at least " + str.tostring(slowLen) + " daily bars of history", themeHeader, themeText, text.align_left)
else
string headTip = str.tostring(fastInput) + "-day and " + str.tostring(slowLen) + "-day SMA on daily closes. A phase starts after a cross once the close is " + str.tostring(priceGapInput) + "% beyond the slow SMA (Price Gap). The date is the latest bar's."
// The phase this chart has processed (with Confirmed Bars Only, the live bar's change waits for the close)
int nowDir = na(phaseStartTime) ? lastState : phaseDir
color nowColor = nowDir == 1 ? themeUp : nowDir == -1 ? themeDown : themeText
string nowText = nowDir == 0 ? "No phase yet" : (nowDir == 1 ? "Golden" : "Death") + (na(phaseStartTime) ? " · no cross yet" : " since " + dateText(phaseStartTime))
setCell(cycleTable, 0, 0, syminfo.ticker + " Golden Cross Cycles" + (priceGapInput > 0 ? " (" + str.tostring(priceGapInput) + "% price gap)" : ""), themeHeader, themeText, text.align_left, headTip)
setCell(cycleTable, 1, 0, dateText(dTime), themeHeader, themeText, text.align_right, headTip)
setRow(cycleTable, 1, "Now", nowText, nowColor, NOW_TIP)
if not na(phaseStartTime)
setRow(cycleTable, 2, "So Far", pctText(dClose / phaseStartPrice - 1) + " · " + durationText((dTime - phaseStartTime) / MS_PER_DAY), nowColor, SO_FAR_TIP)
if tableStyleInput == "Full"
[gLine, gTrend] = historyText(goldenChanges, goldenDays, 1)
[dLine, dTrend] = historyText(deathChanges, deathDays, -1)
setRow(cycleTable, 3, "Golden Phases", gLine, themeUp, HISTORY_TIP)
setRow(cycleTable, 4, "Ended Higher", gTrend, themeText, "Completed golden phases that ended above the close of the day they started")
setRow(cycleTable, 5, "Death Phases", dLine, themeDown, HISTORY_TIP)
setRow(cycleTable, 6, "Ended Lower", dTrend, themeText, "Completed death phases that ended below the close of the day they started")
// --- Alerts ---
// Set the named alerts to "Once Per Bar Close": on a live bar the averages move and a cross can appear and vanish.
alertcondition(isGoldenCross, "Golden Cross", "Golden Cross Cycles: golden cross (fast SMA crossed above the slow SMA)")
alertcondition(isDeathCross, "Death Cross", "Golden Cross Cycles: death cross (fast SMA crossed below the slow SMA)")
alertcondition(isGoldenStart, "Golden Phase Start", "Golden Cross Cycles: golden phase started (close Price Gap above the slow SMA after a golden cross)")
alertcondition(isDeathStart, "Death Phase Start", "Golden Cross Cycles: death phase started (close Price Gap below the slow SMA after a death cross)")
// One "Any alert() function call" alert covers all four, with the symbol named
string pair = " (" + str.tostring(fastInput) + "/" + str.tostring(slowLen) + "-day SMA)"
if isCrossBar
alert(syminfo.ticker + ": " + (isGoldenCross ? "golden cross" : "death cross") + pair, alert.freq_once_per_bar_close)
if isStart
alert(syminfo.ticker + ": " + (isGoldenStart ? "golden" : "death") + " phase started on " + dateText(dCrossTime) + pair, alert.freq_once_per_bar_close)