本页源码来自 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/
// © bluesignalfx
//@version=6
// ═══════════════════════════════════════════════════════════════════
// CC FIRST RED / GREEN DAY · Blue Signal FX · Coffee & Charts
// Stacey Burke-style FRD / FGD signal days
// FRD = first red close after N consecutive higher closes (SELL setup)
// FGD = first green close after N consecutive lower closes (BUY setup)
// Signal day → next-day pullback into the setup zone → entry
// Optional BOS layer for FRD → BOS → retest sequencing
// ═══════════════════════════════════════════════════════════════════
indicator("CC First Red / Green Day", shorttitle = "CC FRD/FGD", overlay = true, max_boxes_count = 200, max_lines_count = 300, max_labels_count = 300)
// ─── INPUTS ────────────────────────────────────────────────────────
string G1 = "⚙ Signal Engine"
calcOn = input.string("Real Candles", "Calculate Signals On", options = ["Real Candles", "Heikin Ashi"], group = G1, tooltip = "Real Candles: always uses true OHLC, even when your chart is set to Heikin Ashi.\nHeikin Ashi: FRD/FGD are read from Heikin Ashi candles (pairs well with the 'Candle Color' definition).\nWorks on any chart type either way.")
sigTF = input.timeframe("D", "Signal Timeframe", group = G1, tooltip = "What counts as a 'day'. Keep on D for FRD/FGD. On intraday charts the indicator reads completed daily candles.")
redDef = input.string("Prior Close", "Red / Green Definition", options = ["Prior Close", "Candle Color", "Both"], group = G1, tooltip = "Prior Close: red = close below yesterday's close.\nCandle Color: red = close below open.\nBoth: must satisfy both.")
minRun = input.int(3, "Min Consecutive Closes Before Signal", minval = 1, maxval = 20, group = G1, tooltip = "FRD needs this many higher closes in a row first. FGD needs this many lower closes.")
useLoc = input.bool(true, "Require Run To Hit An Extreme", group = G1, tooltip = "Only signal if the run's high (FRD) / low (FGD) is the highest / lowest of the lookback. Filters mid-trend noise.")
graceBars = input.int(3, "Grace Bars After Run", minval = 0, maxval = 10, group = G1, tooltip = "The first red (FRD) / green (FGD) day may come up to this many bars after the run ends. Catches tops/bottoms where a doji or flat day interrupts the streak — very common on Heikin Ashi.")
locLen = input.int(10, "Extreme Lookback (Signal TF bars)", minval = 2, maxval = 500, group = G1, tooltip = "10 ≈ two weeks of daily candles. 20 ≈ one month.")
string G2 = "▣ Setup Zones"
showZones = input.bool(true, "Show Next-Day Setup Zones", group = G2, tooltip = "FRD: FRD close → FRD high (sell the pullback).\nFGD: FGD low → FGD close (buy the pullback).")
showTrig = input.bool(true, "Show Trigger Line", group = G2, tooltip = "FRD low (breakdown) / FGD high (breakout).")
zoneLen = input.int(3, "Zone Length (Signal TF bars)", minval = 1, maxval = 20, group = G2)
maxZones = input.int(10, "Max Zones Kept", minval = 1, maxval = 50, group = G2)
string G3 = "⤵ Break of Structure"
showBOS = input.bool(true, "Show BOS", group = G3)
pvLen = input.int(3, "Swing Strength", minval = 1, maxval = 20, group = G3, tooltip = "Bars on each side needed to confirm a swing high / low on the Signal TF.")
string G4 = "◈ Visuals"
colBear = input.color(#ff1744, "Bearish", group = G4)
colBull = input.color(#00e676, "Bullish", group = G4)
colAcc = input.color(#00bcd4, "Accent", group = G4)
colBg = input.color(#0a1628, "Panel Background", group = G4)
showDash = input.bool(true, "Show Dashboard", group = G4)
dashPos = input.string("Top Right", "Dashboard Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G4)
string G5 = "〰 47 MA Confirmation"
useMA = input.bool(true, "Require 47 MA Break", group = G5, tooltip = "FRD only fires when price closes below the MA, FGD only when price closes above it. The signal day and the MA break must happen within the window below. This isolates the major turning points.")
maTF = input.timeframe("240", "MA Timeframe", group = G5, tooltip = "Blueprint default: 4H.")
maLen = input.int(47, "MA Length", minval = 1, group = G5)
maType = input.string("SMA", "MA Type", options = ["SMA", "EMA"], group = G5)
armMax = input.int(20, "Arm Duration After Signal Day (Signal TF bars)", minval = 1, maxval = 60, group = G5, tooltip = "After an FRD/FGD day the setup stays ARMED until price breaks the MA (signal fires), price closes beyond the run's extreme (setup invalid), or this many bars pass. Handles long topping/bottoming chop.")
armBars = input.int(3, "MA Break Before Signal Day: Max Gap (Signal TF bars)", minval = 0, maxval = 20, group = G5, tooltip = "If the MA breaks first, the FRD/FGD day must follow within this many bars.")
showArm = input.bool(true, "Mark Signal Days (armed)", group = G5, tooltip = "Small marker on every detected FRD/FGD day, so you can see the setup arming before the MA break confirms it.")
showMA = input.bool(false, "Plot MA", group = G5)
// ─── TIMEFRAME HANDLING ────────────────────────────────────────────
int chartSec = timeframe.in_seconds()
int sigSec = timeframe.in_seconds(sigTF)
bool sameTF = chartSec >= sigSec // chart is on (or above) the signal TF → calculate directly
string reqTF = sameTF ? timeframe.period : sigTF
int effSec = sameTF ? chartSec : sigSec
string tfLabel = reqTF + (calcOn == "Heikin Ashi" ? " · HA" : "")
// Data source is independent of chart type: standard ticker strips HA from the chart, heikinashi ticker forces it
string tkr = calcOn == "Heikin Ashi" ? ticker.heikinashi(syminfo.tickerid) : ticker.standard(syminfo.tickerid)
// ─── HELPERS ───────────────────────────────────────────────────────
f_isRed(float o, float c, float pc) =>
redDef == "Prior Close" ? c < pc : redDef == "Candle Color" ? c < o : c < pc and c < o
f_isGreen(float o, float c, float pc) =>
redDef == "Prior Close" ? c > pc : redDef == "Candle Color" ? c > o : c > pc and c > o
// ─── CORE ENGINE (runs on the signal timeframe) ────────────────────
f_core() =>
var int upRun = 0
var int dnRun = 0
upRun := close > close[1] ? upRun + 1 : 0
dnRun := close < close[1] ? dnRun + 1 : 0
float locHi = ta.highest(high, locLen)
float locLo = ta.lowest(low, locLen)
float curPeak = ta.highest(high, math.max(upRun, 1))
float curTrough = ta.lowest(low, math.max(dnRun, 1))
bool red = f_isRed(open, close, close[1])
bool green = f_isGreen(open, close, close[1])
// A qualified run stays "live" for a few bars after it ends, so the first red/green
// day still counts even if a flat/doji day (common on Heikin Ashi) breaks the streak first.
var bool upQual = false
var float upPk = na
var int upEnd = 0
var bool dnQual = false
var float dnTr = na
var int dnEnd = 0
if upQual and bar_index - upEnd > graceBars
upQual := false
if dnQual and bar_index - dnEnd > graceBars
dnQual := false
float runPeak = upPk
float runTrough = dnTr
bool frd = upQual and red and not green
bool fgd = dnQual and green and not red
if frd
upQual := false
if fgd
dnQual := false
if not red and upRun >= minRun and (not useLoc or curPeak >= locHi)
upPk := upQual ? math.max(upPk, curPeak) : curPeak
upQual := true
upEnd := bar_index
if not green and dnRun >= minRun and (not useLoc or curTrough <= locLo)
dnTr := dnQual ? math.min(dnTr, curTrough) : curTrough
dnQual := true
dnEnd := bar_index
// Break of structure on closes
float ph = ta.pivothigh(high, pvLen, pvLen)
float pl = ta.pivotlow(low, pvLen, pvLen)
var float swHi = na
var int swHiT = na
var bool hiLive = false
var float swLo = na
var int swLoT = na
var bool loLive = false
if not na(ph)
swHi := ph
swHiT := time[pvLen]
hiLive := true
if not na(pl)
swLo := pl
swLoT := time[pvLen]
loLive := true
bool bosUp = false
bool bosDn = false
if hiLive and close > swHi
bosUp := true
hiLive := false
if loLive and close < swLo
bosDn := true
loLive := false
[frd, fgd, high, low, close, upRun, dnRun, curPeak, curTrough, locHi, locLo, bosUp, bosDn, swHi, swHiT, swLo, swLoT, time, runPeak, runTrough]
// Last COMPLETED signal-TF bar (non-repainting)
f_confirmed() =>
[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20] = f_core()
[x1[1], x2[1], x3[1], x4[1], x5[1], x6[1], x7[1], x8[1], x9[1], x10[1], x11[1], x12[1], x13[1], x14[1], x15[1], x16[1], x17[1], x18[1], x19[1], x20[1]]
// All price data comes from the selected ticker, never from the chart's own candles
[cFrd, cFgd, cH, cL, cC, cUp, cDn, cPk, cTr, cLh, cLl, cBu, cBd, cSh, cSht, cSl, cSlt, cT, cRp, cRt] = request.security(tkr, reqTF, f_core())
[pFrd, pFgd, pH, pL, pC, pUp, pDn, pPk, pTr, pLh, pLl, pBu, pBd, pSh, pSht, pSl, pSlt, pT, pRp, pRt] = request.security(tkr, reqTF, f_confirmed(), lookahead = barmerge.lookahead_on)
float dOpen = request.security(tkr, reqTF, open, lookahead = barmerge.lookahead_on)
float liveClose = request.security(tkr, timeframe.period, close)
bool newSig = timeframe.change(reqTF)
// ─── EVENTS ────────────────────────────────────────────────────────
// Same TF: mark the signal bar itself once it closes. Intraday: mark the first bar after the signal day closes.
bool frdEvt = sameTF ? cFrd and barstate.isconfirmed : newSig and pFrd
bool fgdEvt = sameTF ? cFgd and barstate.isconfirmed : newSig and pFgd
float eH = sameTF ? cH : pH
float eL = sameTF ? cL : pL
float eC = sameTF ? cC : pC
int eT = sameTF ? cT : pT
float eRp = sameTF ? cRp : pRp
float eRt = sameTF ? cRt : pRt
bool bosUpEvt = showBOS and (sameTF ? cBu and barstate.isconfirmed : newSig and pBu)
bool bosDnEvt = showBOS and (sameTF ? cBd and barstate.isconfirmed : newSig and pBd)
float bUpLvl = sameTF ? cSh : pSh
int bUpT0 = sameTF ? cSht : pSht
float bDnLvl = sameTF ? cSl : pSl
int bDnT0 = sameTF ? cSlt : pSlt
// ─── 47 MA ENGINE ──────────────────────────────────────────────────
f_ma(float src) =>
float e = ta.ema(src, maLen)
float m = ta.sma(src, maLen)
maType == "EMA" ? e : m
f_maX() =>
float m = f_ma(close)
[m, ta.crossunder(close, m), ta.crossover(close, m)]
f_maXConf() =>
[a, b, c] = f_maX()
[a[1], b[1], c[1]]
int maSec = timeframe.in_seconds(maTF)
bool maLower = chartSec < maSec // chart below MA TF → read completed MA-TF bars
float maLive = request.security(tkr, maTF, f_ma(close))
[mMa, mXdn, mXup] = request.security(tkr, maTF, f_maXConf(), lookahead = barmerge.lookahead_on)
bool maChg = timeframe.change(maTF)
bool cXdn = ta.crossunder(liveClose, maLive)
bool cXup = ta.crossover(liveClose, maLive)
bool xDnEvt = maLower ? maChg and mXdn : cXdn and barstate.isconfirmed
bool xUpEvt = maLower ? maChg and mXup : cXup and barstate.isconfirmed
float maRef = maLower ? mMa : maLive
// Always-on MA plot (invisible unless "Plot MA" is on)
plot(maLive, "47 MA", color = showMA ? colAcc : color.new(colAcc, 100), linewidth = 2)
// ─── SIGNAL GATING ────────────────────────────────────────────────
// Signal day ARMS the setup → MA break FIRES it.
// FRD arm dies on: a close above the run peak, an FGD day, or armMax bars.
var int frdT = na
var float fH = na
var float fL = na
var float fC = na
var float fPk = na
var int fT = na
var int fgdT = na
var float gH = na
var float gL = na
var float gC = na
var float gTr = na
var int gT = na
var int xDnT = na
var int xUpT = na
int armMs = armMax * effSec * 1000
int winMs = (armBars + 1) * effSec * 1000
// expire / invalidate arms
if not na(frdT) and (time - frdT > armMs or (barstate.isconfirmed and liveClose > fPk))
frdT := na
if not na(fgdT) and (time - fgdT > armMs or (barstate.isconfirmed and liveClose < gTr))
fgdT := na
if not na(xDnT) and time - xDnT > winMs
xDnT := na
if not na(xUpT) and time - xUpT > winMs
xUpT := na
if frdEvt
frdT := time
fH := eH
fL := eL
fC := eC
fPk := na(eRp) ? eH : math.max(eRp, eH)
fT := eT
fgdT := na
if fgdEvt
fgdT := time
gH := eH
gL := eL
gC := eC
gTr := na(eRt) ? eL : math.min(eRt, eL)
gT := eT
frdT := na
if xDnEvt
xDnT := time
xUpT := na
if xUpEvt
xUpT := time
xDnT := na
// Armed FRD + MA break (either order) → fire.
bool frdFire = useMA ? not na(frdT) and liveClose < maRef and (xDnEvt or (frdEvt and not na(xDnT))) : frdEvt
bool fgdFire = useMA ? not na(fgdT) and liveClose > maRef and (xUpEvt or (fgdEvt and not na(xUpT))) : fgdEvt
plotshape(useMA and showArm and frdEvt, title = "FRD Day (armed)", style = shape.triangledown, location = location.abovebar, color = color.new(colBear, 30), size = size.tiny)
plotshape(useMA and showArm and fgdEvt, title = "FGD Day (armed)", style = shape.triangleup, location = location.belowbar, color = color.new(colBull, 30), size = size.tiny)
// ─── DRAWING ───────────────────────────────────────────────────────
var array<box> zoneBoxes = array.new<box>()
var array<line> trigLines = array.new<line>()
var string lastSig = "—"
var color lastCol = color.gray
f_addZone(int t1, float top, float bot, float trig, color col, string txt) =>
int t2 = t1 + zoneLen * effSec * 1000
if showZones
box b = box.new(t1, top, t2, bot, xloc = xloc.bar_time, border_color = color.new(col, 30), bgcolor = color.new(col, 85), text = txt, text_color = col, text_size = size.small, text_halign = text.align_left, text_valign = text.align_top)
zoneBoxes.push(b)
if zoneBoxes.size() > maxZones
zoneBoxes.shift().delete()
if showTrig
line ln = line.new(t1, trig, t2, trig, xloc = xloc.bar_time, color = col, style = line.style_dashed, width = 1)
trigLines.push(ln)
if trigLines.size() > maxZones
trigLines.shift().delete()
if frdFire
lastSig := "FRD · " + str.format_time(fT, "MMM dd", syminfo.timezone)
lastCol := colBear
f_addZone(time, fH, fC, fL, colBear, "FRD SELL ZONE")
alert("🔴 CC FRD CONFIRMED" + (useMA ? " + 47 MA BREAK" : "") + " — " + syminfo.ticker + " (" + tfLabel + ") | Sell zone " + str.tostring(fC, format.mintick) + " – " + str.tostring(fH, format.mintick) + " | Trigger (FRD low) " + str.tostring(fL, format.mintick), alert.freq_once_per_bar_close)
frdT := na
xDnT := na
if fgdFire
lastSig := "FGD · " + str.format_time(gT, "MMM dd", syminfo.timezone)
lastCol := colBull
f_addZone(time, gC, gL, gH, colBull, "FGD BUY ZONE")
alert("🟢 CC FGD CONFIRMED" + (useMA ? " + 47 MA BREAK" : "") + " — " + syminfo.ticker + " (" + tfLabel + ") | Buy zone " + str.tostring(gL, format.mintick) + " – " + str.tostring(gC, format.mintick) + " | Trigger (FGD high) " + str.tostring(gH, format.mintick), alert.freq_once_per_bar_close)
fgdT := na
xUpT := na
if bosDnEvt and not na(bDnLvl) and not na(bDnT0)
line.new(bDnT0, bDnLvl, time, bDnLvl, xloc = xloc.bar_time, color = colBear, style = line.style_dotted, width = 2)
label.new(time, bDnLvl, "BOS ↓", xloc = xloc.bar_time, style = label.style_label_left, color = colBg, textcolor = colBear, size = size.small)
alert("⤵ CC BEARISH BOS — " + syminfo.ticker + " (" + tfLabel + ") closed below swing low " + str.tostring(bDnLvl, format.mintick), alert.freq_once_per_bar_close)
if bosUpEvt and not na(bUpLvl) and not na(bUpT0)
line.new(bUpT0, bUpLvl, time, bUpLvl, xloc = xloc.bar_time, color = colBull, style = line.style_dotted, width = 2)
label.new(time, bUpLvl, "BOS ↑", xloc = xloc.bar_time, style = label.style_label_left, color = colBg, textcolor = colBull, size = size.small)
alert("⤴ CC BULLISH BOS — " + syminfo.ticker + " (" + tfLabel + ") closed above swing high " + str.tostring(bUpLvl, format.mintick), alert.freq_once_per_bar_close)
plotshape(frdFire, title = "FRD", style = shape.labeldown, location = location.abovebar, color = colBear, text = "FRD", textcolor = color.white, size = size.small)
plotshape(fgdFire, title = "FGD", style = shape.labelup, location = location.belowbar, color = colBull, text = "FGD", textcolor = color.black, size = size.small)
// ─── LIVE "FORMING" HEADS-UP ───────────────────────────────────────
bool liveRed = f_isRed(dOpen, liveClose, pC)
bool liveGreen = f_isGreen(dOpen, liveClose, pC)
bool frdForming = barstate.isrealtime and pUp >= minRun and liveRed and (not useLoc or pPk >= pLh)
bool fgdForming = barstate.isrealtime and pDn >= minRun and liveGreen and (not useLoc or pTr <= pLl)
varip bool frdFired = false
varip bool fgdFired = false
if newSig
frdFired := false
fgdFired := false
if frdForming and not frdFired
frdFired := true
alert("⚠ CC FRD FORMING — " + syminfo.ticker + " (" + tfLabel + ") trading red vs prior close " + str.tostring(pC, format.mintick) + " after " + str.tostring(pUp) + " higher closes", alert.freq_once_per_bar)
if fgdForming and not fgdFired
fgdFired := true
alert("⚠ CC FGD FORMING — " + syminfo.ticker + " (" + tfLabel + ") trading green vs prior close " + str.tostring(pC, format.mintick) + " after " + str.tostring(pDn) + " lower closes", alert.freq_once_per_bar)
alertcondition(frdFire, "CC FRD Confirmed", "CC FRD confirmed on {{ticker}} — watch pullback into sell zone")
alertcondition(fgdFire, "CC FGD Confirmed", "CC FGD confirmed on {{ticker}} — watch pullback into buy zone")
alertcondition(frdForming, "CC FRD Forming", "CC FRD forming on {{ticker}} — price red vs prior close after a run of higher closes")
alertcondition(fgdForming, "CC FGD Forming", "CC FGD forming on {{ticker}} — price green vs prior close after a run of lower closes")
alertcondition(bosDnEvt, "CC Bearish BOS", "CC bearish BOS on {{ticker}}")
alertcondition(bosUpEvt, "CC Bullish BOS", "CC bullish BOS on {{ticker}}")
// ─── DASHBOARD ─────────────────────────────────────────────────────
f_pos(string s) =>
switch s
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
var table dash = table.new(f_pos(dashPos), 2, 8, bgcolor = colBg, frame_color = colAcc, frame_width = 1, border_color = color.new(colAcc, 75), border_width = 1)
f_row(int r, string k, string v, color vc) =>
table.cell(dash, 0, r, k, text_color = color.new(colAcc, 20), text_size = size.small, text_halign = text.align_left, text_font_family = font.family_monospace)
table.cell(dash, 1, r, v, text_color = vc, text_size = size.small, text_halign = text.align_right, text_font_family = font.family_monospace)
if barstate.isfirst and showDash
table.merge_cells(dash, 0, 0, 1, 0)
if showDash and barstate.islast
bool useCur = sameTF and not barstate.isrealtime
int dUp = useCur ? cUp : pUp
int dDn = useCur ? cDn : pDn
string status = frdForming ? "⚠ FRD FORMING" : fgdForming ? "⚠ FGD FORMING" : useMA and not na(frdT) ? "FRD armed → MA break" : useMA and not na(fgdT) ? "FGD armed → MA break" : useMA and not na(xDnT) ? "MA broken ↓ → FRD?" : useMA and not na(xUpT) ? "MA broken ↑ → FGD?" : dUp >= minRun ? "Watching → FRD" : dDn >= minRun ? "Watching → FGD" : "No run in play"
color stCol = frdForming or not na(frdT) or not na(xDnT) or dUp >= minRun ? colBear : fgdForming or not na(fgdT) or not na(xUpT) or dDn >= minRun ? colBull : color.gray
bool aboveMA = liveClose > maRef
table.cell(dash, 0, 0, "CC FIRST RED / GREEN DAY", text_color = colAcc, text_size = size.small, text_font_family = font.family_monospace)
f_row(1, "Signal TF", tfLabel, color.white)
f_row(2, "Definition", redDef, color.white)
f_row(3, "Higher Closes", str.tostring(dUp) + (dUp >= minRun ? " ✓" : ""), dUp >= minRun ? colBull : color.white)
f_row(4, "Lower Closes", str.tostring(dDn) + (dDn >= minRun ? " ✓" : ""), dDn >= minRun ? colBear : color.white)
f_row(5, "Last Signal", lastSig, lastCol)
f_row(6, str.tostring(maLen) + " " + maType + " (" + maTF + ")", na(maRef) ? "—" : aboveMA ? "Above ▲" : "Below ▼", aboveMA ? colBull : colBear)
f_row(7, "Status", status, stCol)