本页源码来自 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/
// HTF Bias Ribbon [FCD] — Futures Context Desk
// Version: 1.2
// Date: 2026-11-01
// License: Mozilla Public License 2.0 (MPL-2.0), open source.
// Purpose: shows a higher-timeframe EMA ribbon and a plain-English trend readout (UP / DOWN / NEUTRAL).
// HTF = higher timeframe. EMA = exponential moving average.
// Higher-timeframe values are requested in the documented non-repainting form:
// request.security(sym, tf, expr[1], lookahead = barmerge.lookahead_on)
// i.e. only the last CONFIRMED higher-timeframe bar is used; no future data is accessed.
//@version=6
indicator("HTF Bias Ribbon [FCD]", shorttitle = "HTF Bias [FCD]", overlay = true, max_labels_count = 60)
// ───────────── Inputs ─────────────
string GRP_MAIN = "Trend Settings"
string GRP_DISP = "Display Options"
string GRP_MARK = "Chart Markers"
string GRP_ALRT = "Alerts"
string GRP_COL = "Colors"
string GRP_TBL = "Status Box"
string htfInput = input.timeframe("60", "Higher timeframe (HTF) for the trend", group = GRP_MAIN, tooltip = "HTF = higher timeframe. The trend is read from this timeframe (default 60 minutes = 1 hour) and shown on your lower-timeframe chart. It must be higher than the chart timeframe.")
int fastLen = input.int(50, "Fast average length (bars)", minval = 1, group = GRP_MAIN, tooltip = "Length of the fast EMA (exponential moving average), counted in higher-timeframe bars.")
int slowLen = input.int(200, "Slow average length (bars)", minval = 1, group = GRP_MAIN, tooltip = "Length of the slow EMA (exponential moving average), counted in higher-timeframe bars.")
float srcInput = input.source(close, "Price used for the averages", group = GRP_MAIN, tooltip = "Default: close. The value is recalculated on the higher timeframe. If you pick another indicator's plot, its HTF value may differ from what you see on the chart timeframe.")
bool showFill = input.bool(true, "Color the space between the two averages", group = GRP_DISP)
bool showLines = input.bool(true, "Show the two average lines", group = GRP_DISP)
bool colorBars = input.bool(false, "Color price bars by trend", group = GRP_DISP)
bool showWarn = input.bool(true, "Warn me if the chart timeframe is too high", group = GRP_DISP, tooltip = "Shows a note on the last bar when the chart timeframe is equal to or higher than the HTF.")
int lineWidth = input.int(2, "Average line width", minval = 1, maxval = 4, group = GRP_DISP)
int fillTransp = input.int(80, "Fill transparency (0 = solid, 100 = invisible)", minval = 0, maxval = 100, group = GRP_DISP)
int barTransp = input.int(0, "Bar color transparency (0 = solid, 100 = invisible)", minval = 0, maxval = 100, group = GRP_DISP)
bool showMarks = input.bool(true, "Show a small note when the trend changes", group = GRP_MARK, tooltip = "Draws a short note such as \"1H trend now UP\" on the bar where the trend changed. Only drawn after the bar closes. Only the current and previous session are kept so the chart stays clean.")
bool markNeu = input.bool(true, "Include changes to NEUTRAL", group = GRP_MARK, tooltip = "Turn off to show only the notes for UP and DOWN.")
bool alUp = input.bool(true, "Alert when trend turns UP", group = GRP_ALRT, tooltip = "Confirmed on bar close: the alert fires once, when the chart bar closes with the new trend. Create one alert with \"Any alert() function call\" to receive all enabled alerts.")
bool alDn = input.bool(true, "Alert when trend turns DOWN", group = GRP_ALRT, tooltip = "Confirmed on bar close: the alert fires once, when the chart bar closes with the new trend.")
bool alNeu = input.bool(true, "Alert when trend turns NEUTRAL", group = GRP_ALRT, tooltip = "Confirmed on bar close: the alert fires once, when the chart bar closes with the new trend.")
color upCol = input.color(color.new(#26A69A, 0), "UP trend", group = GRP_COL)
color dnCol = input.color(color.new(#EF5350, 0), "DOWN trend", group = GRP_COL)
color neuCol = input.color(color.new(#9E9E9E, 0), "NEUTRAL trend", group = GRP_COL)
color fastCol = input.color(color.new(#2962FF, 0), "Fast average line", group = GRP_COL)
color slowCol = input.color(color.new(#FF9800, 0), "Slow average line", group = GRP_COL)
color warnBg = input.color(color.new(#FFB300, 10), "Warning note background", group = GRP_COL)
color warnTxt = input.color(color.new(#000000, 0), "Warning note text", group = GRP_COL)
bool showTable = input.bool(true, "Show status box", group = GRP_TBL)
string tblPosIn = input.string("Bottom Right", "Box position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = GRP_TBL)
string tblSizeIn = input.string("Normal", "Box text size", options = ["Tiny", "Small", "Normal", "Large"], group = GRP_TBL)
color tblBg = input.color(color.new(#131722, 15), "Box background", group = GRP_TBL)
color tblTxt = input.color(color.new(#D1D4DC, 0), "Box text", group = GRP_TBL)
// ───────────── HTF data (non-repainting) ─────────────
// expr[1] + lookahead_on = value of the last fully closed HTF bar, identical on history and realtime.
// One tuple call fetches both EMAs (halves the request.security budget).
[htfFast, htfSlow] = request.security(syminfo.tickerid, htfInput, [ta.ema(srcInput, fastLen)[1], ta.ema(srcInput, slowLen)[1]], lookahead = barmerge.lookahead_on)
// Friendly timeframe name: "60" -> "1H", "240" -> "4H", "D" -> "1D", "15" -> "15m".
tfName(string tf) =>
string t = tf == "" ? timeframe.period : tf
int s = timeframe.in_seconds(t)
s >= 604800 and s % 604800 == 0 ? str.tostring(s / 604800) + "W" : s >= 86400 and s % 86400 == 0 ? str.tostring(s / 86400) + "D" : s >= 3600 and s % 3600 == 0 ? str.tostring(s / 3600) + "H" : s >= 60 ? str.tostring(s / 60) + "m" : str.tostring(s) + "s"
string htfLabel = tfName(htfInput)
// ───────────── State ─────────────
// 1 = UP, -1 = DOWN, 0 = NEUTRAL
int state = 0
if not na(htfFast) and not na(htfSlow)
if htfFast > htfSlow and close > htfFast
state := 1
else if htfFast < htfSlow and close < htfFast
state := -1
int prevState = nz(state[1], state)
bool stateChanged = state != prevState
// Suppress the one-off change when the HTF EMAs first become available (warm-up boundary).
bool htfReadyPrev = not na(htfFast[1]) and not na(htfSlow[1])
bool stateChangedAlert = stateChanged and htfReadyPrev
var int barsSince = 0
barsSince := stateChanged or barstate.isfirst ? 0 : barsSince + 1
color stateCol = switch state
1 => upCol
-1 => dnCol
=> neuCol
string stateTxt = switch state
1 => "UP"
-1 => "DOWN"
=> "NEUTRAL"
string stateSym = switch state
1 => "▲"
-1 => "▼"
=> "●"
// ───────────── Plots ─────────────
pFast = plot(htfFast, "HTF Fast EMA", color = showLines ? fastCol : na, linewidth = lineWidth)
pSlow = plot(htfSlow, "HTF Slow EMA", color = showLines ? slowCol : na, linewidth = lineWidth)
fill(pFast, pSlow, color = showFill ? color.new(stateCol, fillTransp) : na, title = "Ribbon fill")
barcolor(colorBars ? color.new(stateCol, barTransp) : na, title = "Trend bar color")
plot(state, "Trend (1 up / -1 down / 0 neutral)", display = display.data_window, editable = false)
// ───────────── Chart markers (current + previous session only) ─────────────
var int sessIdx = 0
var label[] markLbls = array.new<label>()
var int[] markSess = array.new<int>()
int MAX_MARKS = 50
if session.isfirstbar
sessIdx += 1
// Drop notes older than the previous session.
while markSess.size() > 0 and markSess.first() < sessIdx - 1
label.delete(markLbls.shift())
markSess.shift()
bool confirmedChange = stateChangedAlert and barstate.isconfirmed
if showMarks and confirmedChange and (state != 0 or markNeu)
string mTxt = stateSym + " " + htfLabel + " trend now " + stateTxt
label lb = na
if state == 1
lb := label.new(bar_index, low, mTxt, yloc = yloc.belowbar, style = label.style_label_up, color = color.new(stateCol, 15), textcolor = color.white, size = size.small)
else
lb := label.new(bar_index, high, mTxt, yloc = yloc.abovebar, style = label.style_label_down, color = color.new(stateCol, 15), textcolor = state == 0 ? color.black : color.white, size = size.small)
markLbls.push(lb)
markSess.push(sessIdx)
if markLbls.size() > MAX_MARKS
label.delete(markLbls.shift())
markSess.shift()
// ───────────── Alerts ─────────────
// Individual conditions (pick one in the Create Alert dialog; use "Once Per Bar Close" for confirmed readings).
alertcondition(stateChangedAlert, "Trend changed (any)", "{{ticker}}: higher-timeframe trend changed (price {{close}})")
alertcondition(stateChangedAlert and state == 1, "Trend now UP", "{{ticker}}: higher-timeframe trend now UP (price {{close}})")
alertcondition(stateChangedAlert and state == -1, "Trend now DOWN", "{{ticker}}: higher-timeframe trend now DOWN (price {{close}})")
alertcondition(stateChangedAlert and state == 0, "Trend now NEUTRAL", "{{ticker}}: higher-timeframe trend now NEUTRAL (price {{close}})")
// One-click alert: "Any alert() function call". Confirmed on bar close.
if stateChangedAlert
bool wanted = (state == 1 and alUp) or (state == -1 and alDn) or (state == 0 and alNeu)
if wanted
alert(syminfo.ticker + ": " + htfLabel + " trend now " + stateTxt + " (was " + (prevState == 1 ? "UP" : prevState == -1 ? "DOWN" : "NEUTRAL") + ") at price " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
// ───────────── Timeframe warning ─────────────
bool tfTooHigh = timeframe.in_seconds(timeframe.period) >= timeframe.in_seconds(htfInput)
var label warnLbl = na
if barstate.islast
label.delete(warnLbl)
warnLbl := na
if showWarn and tfTooHigh
warnLbl := label.new(bar_index, high, "⚠ Chart timeframe is not lower than the HTF (" + htfLabel + "). Pick a lower chart timeframe or a higher HTF.", xloc = xloc.bar_index, yloc = yloc.abovebar, style = label.style_label_down, color = warnBg, textcolor = warnTxt, size = size.small)
// ───────────── Status box ─────────────
tblPos = switch tblPosIn
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
tblSize = switch tblSizeIn
"Tiny" => size.tiny
"Small" => size.small
"Large" => size.large
=> size.normal
var table tbl = table.new(tblPos, 2, 3, bgcolor = tblBg, border_width = 1, frame_width = 1, frame_color = color.new(tblTxt, 70), border_color = color.new(tblTxt, 85))
if barstate.isfirst
// Top row spans both columns (merged once).
table.merge_cells(tbl, 0, 0, 1, 0)
if barstate.islast and showTable
string statusTxt = na(htfFast) or na(htfSlow) ? htfLabel + " trend: waiting for data" : stateSym + " " + htfLabel + " trend: " + stateTxt + " (for " + str.tostring(barsSince) + (barsSince == 1 ? " bar)" : " bars)")
table.cell(tbl, 0, 0, statusTxt, text_color = state == 0 ? color.black : color.white, bgcolor = stateCol, text_size = tblSize)
table.cell(tbl, 0, 1, "Higher timeframe (HTF)", text_color = tblTxt, text_size = size.small, text_halign = text.align_left)
table.cell(tbl, 1, 1, htfLabel, text_color = tblTxt, text_size = size.small)
table.cell(tbl, 0, 2, "Chart bars in this trend", text_color = tblTxt, text_size = size.small, text_halign = text.align_left)
table.cell(tbl, 1, 2, str.tostring(barsSince), text_color = tblTxt, text_size = size.small)