本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("CRT Multi-Timeframe Levels v3", overlay=true, max_labels_count=500, max_lines_count=500)
// -----------------------------------------------------------------------------
// INPUTS
// -----------------------------------------------------------------------------
showBullish = input.bool(true, "Show Bullish CRTs", group="Filter Settings")
showBearish = input.bool(true, "Show Bearish CRTs", group="Filter Settings")
maxPerSlot = input.int(3, "Max Signals Shown Per Timeframe", minval=1, maxval=50, group="Filter Settings",
tooltip="Only the most recent N signals are kept for each timeframe slot. Older ones are removed from the chart.")
trackCandles = input.int(3, "Track For N Candles After Candle 2", minval=1, group="Filter Settings",
tooltip="Levels extend and targets are tracked for this many higher-timeframe candles after candle 2 closes.")
invMode = input.string("Close", "Invalidate When Price", options=["Close", "Touch"], group="Filter Settings",
tooltip="Close: a chart-timeframe close beyond candle 2's extreme invalidates the setup. Touch: any wick beyond it does.")
showMidLine = input.bool(true, "Show Candle 1 Midpoint (50%) Line", group="Line Settings")
bullishColor = input.color(color.green, "Bullish Color", group="Line Settings")
bearishColor = input.color(color.red, "Bearish Color", group="Line Settings")
midHitColor = input.color(color.orange, "50% Target Hit Color", group="Line Settings")
fullHitColor = input.color(color.gray, "Full Target Hit Color", group="Line Settings")
showTable = input.bool(true, "Show Timeframe Status Table", group="Line Settings")
// Timeframe slots: each can be switched on/off and set to any timeframe equal to or above the chart's
on0 = input.bool(false, "Enable", group="Chart Timeframe CRTs", tooltip="CRTs on whatever timeframe the chart is currently on.")
on1 = input.bool(true, "Enable", group="Timeframe Slot 1", inline="s1")
tf1 = input.timeframe("480", "Timeframe", group="Timeframe Slot 1", inline="s1")
on2 = input.bool(true, "Enable", group="Timeframe Slot 2", inline="s2")
tf2 = input.timeframe("D", "Timeframe", group="Timeframe Slot 2", inline="s2")
on3 = input.bool(true, "Enable", group="Timeframe Slot 3", inline="s3")
tf3 = input.timeframe("240", "Timeframe", group="Timeframe Slot 3", inline="s3")
// -----------------------------------------------------------------------------
// TYPE & ARRAY TO TRACK SIGNALS
// state: 0 = active, 1 = 50% target hit, 2 = full target hit
// tracking: false once the signal is finished (full target or window ended); drawings stay
// -----------------------------------------------------------------------------
type CRTSignal
label lbl
line highLine
line lowLine
line midLine
float invalidationLevel
float midLevel
float fullLevel
bool isBullish
int c2Time
int htfMs
int state
bool tracking
string baseText
int slot
var activeSignals = array.new<CRTSignal>()
// -----------------------------------------------------------------------------
// HELPERS
// -----------------------------------------------------------------------------
tfLabel(string tf) =>
int secs = timeframe.in_seconds(tf)
string out = ""
if secs < 3600
out := str.tostring(int(math.round(secs / 60))) + "m"
else if secs < 86400
out := str.tostring(int(math.round(secs / 3600))) + "H"
else if secs < 604800
out := str.tostring(int(math.round(secs / 86400))) + "D"
else if secs < 2592000
out := "W"
else
out := "M"
out
// Evaluated on the higher timeframe. Looks ONLY at completed candles:
// candle 2 = bar [1], candle 1 = bar [2]. Because nothing here uses the current,
// still-forming HTF bar, it is safe to request with lookahead on and does not repaint.
crtPack() =>
bool sweptBoth = low[1] < low[2] and high[1] > high[2]
bool bull = not sweptBoth and low[1] < low[2] and close[1] > low[2] and close[1] < high[2]
bool bear = not sweptBoth and high[1] > high[2] and close[1] < high[2] and close[1] > low[2]
[bull, bear, high[2], low[2], time[2], time[1], high[1], low[1], close[1]]
deleteSignal(array<CRTSignal> sigs, int idx) =>
CRTSignal s = array.get(sigs, idx)
label.delete(s.lbl)
line.delete(s.highLine)
line.delete(s.lowLine)
if not na(s.midLine)
line.delete(s.midLine)
array.remove(sigs, idx)
// Keep only the most recent maxN signals for a slot (array is in chronological order)
trimSlot(array<CRTSignal> sigs, int slot, int maxN) =>
int cnt = 0
int oldest = -1
for i = 0 to array.size(sigs) - 1
CRTSignal s = array.get(sigs, i)
if s.slot == slot
cnt += 1
if oldest == -1
oldest := i
if cnt > maxN and oldest >= 0
deleteSignal(sigs, oldest)
// -----------------------------------------------------------------------------
// DETECT NEW CRTs FOR ONE TIMEFRAME SLOT
// A new signal is created on the first confirmed chart bar after candle 2 closes
// (i.e. the start of candle 3 on that timeframe).
// -----------------------------------------------------------------------------
processSlot(array<CRTSignal> sigs, int slot, bool enabled, string tf) =>
int tfSecs = timeframe.in_seconds(tf)
bool tfOk = tfSecs >= timeframe.in_seconds()
string useTf = tfOk ? tf : timeframe.period
[bull, bear, c1High, c1Low, c1Time, c2Time, c2High, c2Low, c2Close] =
request.security(syminfo.tickerid, useTf, crtPack(), lookahead=barmerge.lookahead_on)
var int lastC2 = 0
bool fresh = enabled and tfOk and barstate.isconfirmed and not na(c2Time) and c2Time != lastC2
bool newBull = false
bool newBear = false
if fresh
lastC2 := c2Time
float midC1 = (c1High + c1Low) / 2
int htfMs = tfSecs * 1000
string tfName = tfLabel(useTf)
int lblX = c2Time + int(htfMs / 2)
if bull and showBullish
string grade = c2Close >= midC1 ? "A" : "B"
string txt = "CRT ▲ " + grade + " " + tfName
label lbl = label.new(lblX, c2Low, txt, xloc=xloc.bar_time, style=label.style_label_up,
color=color.new(bullishColor, 20), textcolor=color.white, size=size.small)
line lHigh = line.new(c1Time, c1High, time, c1High, xloc=xloc.bar_time,
color=bullishColor, style=line.style_solid, width=2)
line lLow = line.new(c1Time, c1Low, time, c1Low, xloc=xloc.bar_time,
color=bullishColor, style=line.style_solid, width=2)
line lMid = showMidLine ? line.new(c1Time, midC1, time, midC1, xloc=xloc.bar_time,
color=bullishColor, style=line.style_dashed, width=1) : na
// Bullish: invalidated below candle 2's low. Targets: 50% then candle 1 high.
array.push(sigs, CRTSignal.new(lbl, lHigh, lLow, lMid, c2Low, midC1, c1High, true, c2Time, htfMs, 0, true, txt, slot))
newBull := true
alert("Bullish CRT " + grade + " on " + tfName + " | " + syminfo.ticker, alert.freq_once_per_bar_close)
if bear and showBearish
string grade = c2Close <= midC1 ? "A" : "B"
string txt = "CRT ▼ " + grade + " " + tfName
label lbl = label.new(lblX, c2High, txt, xloc=xloc.bar_time, style=label.style_label_down,
color=color.new(bearishColor, 20), textcolor=color.white, size=size.small)
line lHigh = line.new(c1Time, c1High, time, c1High, xloc=xloc.bar_time,
color=bearishColor, style=line.style_solid, width=2)
line lLow = line.new(c1Time, c1Low, time, c1Low, xloc=xloc.bar_time,
color=bearishColor, style=line.style_solid, width=2)
line lMid = showMidLine ? line.new(c1Time, midC1, time, midC1, xloc=xloc.bar_time,
color=bearishColor, style=line.style_dashed, width=1) : na
// Bearish: invalidated above candle 2's high. Targets: 50% then candle 1 low.
array.push(sigs, CRTSignal.new(lbl, lHigh, lLow, lMid, c2High, midC1, c1Low, false, c2Time, htfMs, 0, true, txt, slot))
newBear := true
alert("Bearish CRT " + grade + " on " + tfName + " | " + syminfo.ticker, alert.freq_once_per_bar_close)
if newBull or newBear
trimSlot(sigs, slot, maxPerSlot)
string status = not enabled ? "Off" : (not tfOk ? "Below chart TF" : "On")
[newBull, newBear, status]
[nb0, nr0, st0] = processSlot(activeSignals, 0, on0, timeframe.period)
[nb1, nr1, st1] = processSlot(activeSignals, 1, on1, tf1)
[nb2, nr2, st2] = processSlot(activeSignals, 2, on2, tf2)
[nb3, nr3, st3] = processSlot(activeSignals, 3, on3, tf3)
// -----------------------------------------------------------------------------
// TRACK TARGETS, INVALIDATE, EXTEND LINES, AND FINISH (confirmed bars only)
// -----------------------------------------------------------------------------
if barstate.isconfirmed and array.size(activeSignals) > 0
for i = array.size(activeSignals) - 1 to 0
CRTSignal s = array.get(activeSignals, i)
if s.tracking
float bullTest = invMode == "Close" ? close : low
float bearTest = invMode == "Close" ? close : high
// Only setups that haven't reached the 50% level can be invalidated
bool invalidated = s.state == 0 and (s.isBullish ? bullTest < s.invalidationLevel : bearTest > s.invalidationLevel)
bool midHit = s.isBullish ? high >= s.midLevel : low <= s.midLevel
bool fullHit = s.isBullish ? high >= s.fullLevel : low <= s.fullLevel
if invalidated
deleteSignal(activeSignals, i)
else
if fullHit and s.state < 2
s.state := 2
label.set_text(s.lbl, s.baseText + " ✓TP")
label.set_color(s.lbl, color.new(fullHitColor, 20))
line.set_color(s.highLine, fullHitColor)
line.set_color(s.lowLine, fullHitColor)
line.set_style(s.highLine, line.style_dotted)
line.set_style(s.lowLine, line.style_dotted)
if not na(s.midLine)
line.set_color(s.midLine, fullHitColor)
else if midHit and s.state == 0
s.state := 1
label.set_text(s.lbl, s.baseText + " ✓50%")
label.set_color(s.lbl, color.new(midHitColor, 20))
line.set_color(s.highLine, midHitColor)
line.set_color(s.lowLine, midHitColor)
line.set_style(s.highLine, line.style_dotted)
line.set_style(s.lowLine, line.style_dotted)
if not na(s.midLine)
line.set_color(s.midLine, midHitColor)
// Extend the levels to the current bar while the signal is being tracked
line.set_x2(s.highLine, time)
line.set_x2(s.lowLine, time)
if not na(s.midLine)
line.set_x2(s.midLine, time)
// Stop tracking once the full target is hit or the window ends (drawings stay)
if s.state == 2 or time >= s.c2Time + s.htfMs * (trackCandles + 1)
s.tracking := false
// -----------------------------------------------------------------------------
// STATUS TABLE (shows which timeframe slots are active, and why one may be hidden)
// -----------------------------------------------------------------------------
var table infoTbl = na
if showTable and barstate.islast
if na(infoTbl)
infoTbl := table.new(position.top_right, 2, 4, border_width=1)
table.cell(infoTbl, 0, 0, "Chart (" + tfLabel(timeframe.period) + ")", text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
table.cell(infoTbl, 1, 0, st0, text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
table.cell(infoTbl, 0, 1, tfLabel(tf1), text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
table.cell(infoTbl, 1, 1, st1, text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
table.cell(infoTbl, 0, 2, tfLabel(tf2), text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
table.cell(infoTbl, 1, 2, st2, text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
table.cell(infoTbl, 0, 3, tfLabel(tf3), text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
table.cell(infoTbl, 1, 3, st3, text_color=chart.fg_color, bgcolor=color.new(color.gray, 80), text_size=size.small)
// -----------------------------------------------------------------------------
// ALERTS
// Option 1: alertcondition below (generic text).
// Option 2: create an alert on "Any alert() function call" to get timeframe + grade in the message.
// Use one or the other, not both.
// -----------------------------------------------------------------------------
alertcondition(nb0 or nb1 or nb2 or nb3, title="Bullish CRT (any enabled timeframe)", message="Bullish CRT detected on {{ticker}}")
alertcondition(nr0 or nr1 or nr2 or nr3, title="Bearish CRT (any enabled timeframe)", message="Bearish CRT detected on {{ticker}}")