Concurrent MTF EMAs

kennethkhan · study · 225 行 · 点赞 6 · TradingView 原页

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

Pine Script

//@version=6
indicator("Concurrent MTF EMAs", "MTF EMAs", overlay = true, max_labels_count = 50)
 
// ═══ Modes (apply per line) ══════════════════════════════
// All three modes build on ONE fetched value: the HTF EMA through the last
// CLOSED HTF bar, requested as  ta.ema(close, len)[1]  with lookahead_on.
// That is TradingView's documented non-repainting pattern: historical and
// realtime bars see the same confirmed value, and it updates on the first
// chart bar after each HTF close.
//
// Exact (HTF)   That confirmed value, drawn as-is. Stair-steps: flat for the
//               whole HTF bar, steps once it closes.
//
// Live (HTF)    One EMA step forward from the confirmed value, using the live
//               chart close as the forming HTF bar's close:
//                   EMA_now = a*close + (1-a)*EMA_prevHTF,   a = 2/(len+1)
//               Slides with price inside the HTF bar. On the chart bar where the
//               HTF bar closes, close == that bar's close, so this equals exactly
//               the value the Exact line steps to on the next bar. No jump at
//               the roll, no repaint. On a source TF equal to the chart's it
//               reduces to the ordinary chart EMA.
//
// Smooth        Rebuilds the EMA natively on the chart TF with the length scaled
// (scaled)      by how many chart bars make up one HTF bar (21 hourly -> 84 on a
//               15m). The bar count is MEASURED from the data (the longest
//               complete HTF period seen), not derived from clock time, so
//               Daily/Weekly work on session markets (stocks, futures) that
//               don't trade 24h. Smooth curve, but an approximation of the HTF
//               EMA - it tracks it and drifts a bit.
 
MODE_LIVE   = "Live (HTF)"
MODE_EXACT  = "Exact (HTF)"
MODE_SMOOTH = "Smooth (scaled)"
 
// ─── General ─────────────────────────────────────────────
G_GEN = "General"
i_hideLower = input.bool(true, "Hide EMAs whose timeframe is below the chart's", group = G_GEN, tooltip = "A source timeframe lower than the chart's can't be resolved correctly by request.security - the line would be misleading rather than wrong-looking. Off = plot it anyway.")
i_status    = input.bool(true, "Show status box when a line can't plot", group = G_GEN)
i_labels    = input.bool(false, "Show end-of-line labels", group = G_GEN, tooltip = "Tags each line at the right edge with its length and timeframe, e.g. 21 · 1H.")
 
// ─── Alerts ──────────────────────────────────────────────
G_ALR = "Alerts"
i_alerts     = input.bool(false, "Enable alerts", group = G_ALR, tooltip = "Fires when price crosses any line that has 'Include in alerts' ticked. After turning this on, create an alert on this indicator and choose 'Any alert() function call'. TradingView freezes indicator settings when the alert is created - if you change settings later, delete and recreate the alert.")
i_alertClose = input.bool(true, "Confirmed bar close only", group = G_ALR, tooltip = "On: fires once, when a bar closes on the other side of the line - no alarm if price pokes through and comes back. Off: fires the first time price crosses during the bar - faster, but the cross may not hold.")
 
// ─── EMA 1 ───────────────────────────────────────────────
G1 = "EMA 1"
e1_on    = input.bool(true, "Enable", group = G1)
e1_tf    = input.timeframe("15", "Source timeframe", group = G1)
e1_len   = input.int(21, "EMA length", minval = 1, group = G1)
e1_mode  = input.string(MODE_SMOOTH, "Mode", options = [MODE_LIVE, MODE_EXACT, MODE_SMOOTH], group = G1)
e1_col   = input.color(color.aqua, "Color", group = G1)
e1_width = input.int(1, "Line width", minval = 1, maxval = 4, group = G1)
e1_alert = input.bool(true, "Include in alerts", group = G1)
 
// ─── EMA 2 ───────────────────────────────────────────────
G2 = "EMA 2"
e2_on    = input.bool(true, "Enable", group = G2)
e2_tf    = input.timeframe("60", "Source timeframe", group = G2)
e2_len   = input.int(21, "EMA length", minval = 1, group = G2)
e2_mode  = input.string(MODE_SMOOTH, "Mode", options = [MODE_LIVE, MODE_EXACT, MODE_SMOOTH], group = G2)
e2_col   = input.color(color.orange, "Color", group = G2)
e2_width = input.int(1, "Line width", minval = 1, maxval = 4, group = G2)
e2_alert = input.bool(true, "Include in alerts", group = G2)
 
// ─── EMA 3 ───────────────────────────────────────────────
G3 = "EMA 3"
e3_on    = input.bool(false, "Enable", group = G3)
e3_tf    = input.timeframe("240", "Source timeframe", group = G3)
e3_len   = input.int(21, "EMA length", minval = 1, group = G3)
e3_mode  = input.string(MODE_SMOOTH, "Mode", options = [MODE_LIVE, MODE_EXACT, MODE_SMOOTH], group = G3)
e3_col   = input.color(color.fuchsia, "Color", group = G3)
e3_width = input.int(1, "Line width", minval = 1, maxval = 4, group = G3)
e3_alert = input.bool(true, "Include in alerts", group = G3)
 
// ─── EMA 4 ───────────────────────────────────────────────
G4 = "EMA 4"
e4_on    = input.bool(false, "Enable", group = G4)
e4_tf    = input.timeframe("D", "Source timeframe", group = G4)
e4_len   = input.int(21, "EMA length", minval = 1, group = G4)
e4_mode  = input.string(MODE_SMOOTH, "Mode", options = [MODE_LIVE, MODE_EXACT, MODE_SMOOTH], group = G4)
e4_col   = input.color(color.lime, "Color", group = G4)
e4_width = input.int(1, "Line width", minval = 1, maxval = 4, group = G4)
e4_alert = input.bool(true, "Include in alerts", group = G4)
 
// ─── EMA 5 ───────────────────────────────────────────────
G5 = "EMA 5"
e5_on    = input.bool(false, "Enable", group = G5)
e5_tf    = input.timeframe("W", "Source timeframe", group = G5)
e5_len   = input.int(21, "EMA length", minval = 1, group = G5)
e5_mode  = input.string(MODE_SMOOTH, "Mode", options = [MODE_LIVE, MODE_EXACT, MODE_SMOOTH], group = G5)
e5_col   = input.color(color.yellow, "Color", group = G5)
e5_width = input.int(1, "Line width", minval = 1, maxval = 4, group = G5)
e5_alert = input.bool(true, "Include in alerts", group = G5)
 
chartSec = timeframe.in_seconds(timeframe.period)
 
// ─── Helpers ─────────────────────────────────────────────
// Short timeframe tag for labels and alert text: 15m, 1H, 4H, D, W.
f_tfLabel(_tf) =>
    s = timeframe.in_seconds(_tf)
    s < 60 ? str.tostring(s) + "s" : s < 3600 ? str.tostring(s / 60.0) + "m" : s < 86400 ? str.tostring(s / 3600.0) + "H" : _tf
 
f_tag(_len, _tf) =>
    str.tostring(_len) + " · " + f_tfLabel(_tf)
 
// Chart bars per HTF bar, measured: counts the bars in each completed HTF
// period and keeps the longest. Partial periods (chart start, holidays, early
// closes) are always shorter than a full one, so the max ignores them.
// Until a full period has been seen, falls back to the clock-time ratio.
f_barsPer(_tf, _fallback) =>
    var int cnt  = 0
    var int full = 0
    if timeframe.change(_tf)
        full := math.max(full, cnt)
        cnt  := 0
    cnt += 1
    full > 0 ? full : _fallback
 
// EMA with a length that may change bar to bar (ta.ema needs a fixed length;
// the measured bar count above can still grow early in the chart).
f_emaVar(_src, _len) =>
    a = 2.0 / (_len + 1)
    var float e = na
    e := na(e) ? _src : a * _src + (1.0 - a) * e
    e
 
// Everything for one line. Returns [value to plot or na, source TF below chart].
f_line(_on, _tf, _len, _mode) =>
    sec    = timeframe.in_seconds(_tf)
    low    = sec < chartSec
    ok     = _on and (not i_hideLower or not low)
    // Confirmed HTF EMA - [1] + lookahead_on = no repaint on history or realtime
    prev   = request.security(syminfo.tickerid, _tf, ta.ema(close, _len)[1], lookahead = barmerge.lookahead_on)
    a      = 2.0 / (_len + 1)
    live   = a * close + (1.0 - a) * prev
    bpp    = f_barsPer(_tf, math.max(1, int(math.round(sec * 1.0 / chartSec))))
    smooth = f_emaVar(close, _len * bpp)
    v      = _mode == MODE_EXACT ? prev : _mode == MODE_SMOOTH ? smooth : live
    [ok and not na(v) ? v : na, low]
 
f_warn(_n, _on, _hidden, _v, _tf) =>
    s = ""
    if _on
        if _hidden
            s := "EMA " + str.tostring(_n) + ": " + _tf + " is below the chart timeframe - hidden\n"
        else if na(_v)
            s := "EMA " + str.tostring(_n) + ": no value yet on " + _tf + " - nothing to plot\n"
    s
 
// One label per line, redrawn on the last bar only.
f_endLabel(_show, _val, _txt, _col) =>
    var label lb = na
    if barstate.islast
        label.delete(lb)
        lb := na
        if _show and not na(_val)
            lb := label.new(bar_index, _val, " " + _txt, style = label.style_label_left, color = color.new(color.black, 100), textcolor = _col, size = size.small)
    lb
 
f_alertCross(_include, _up, _dn, _n, _len, _tf) =>
    fire = i_alerts and _include and (_up or _dn)
    if fire
        msg = syminfo.ticker + ": price crossed " + (_up ? "above" : "below") + " EMA " + str.tostring(_n) + " (" + f_tag(_len, _tf) + ") at " + str.tostring(close, format.mintick)
        if i_alertClose
            alert(msg, alert.freq_once_per_bar_close)
        else
            alert(msg, alert.freq_once_per_bar)
    fire
 
// ─── Calculate ───────────────────────────────────────────
[e1_val, e1_low] = f_line(e1_on, e1_tf, e1_len, e1_mode)
[e2_val, e2_low] = f_line(e2_on, e2_tf, e2_len, e2_mode)
[e3_val, e3_low] = f_line(e3_on, e3_tf, e3_len, e3_mode)
[e4_val, e4_low] = f_line(e4_on, e4_tf, e4_len, e4_mode)
[e5_val, e5_low] = f_line(e5_on, e5_tf, e5_len, e5_mode)
 
// ─── Plot ────────────────────────────────────────────────
plot(e1_val, "EMA 1", color = e1_col, linewidth = e1_width)
plot(e2_val, "EMA 2", color = e2_col, linewidth = e2_width)
plot(e3_val, "EMA 3", color = e3_col, linewidth = e3_width)
plot(e4_val, "EMA 4", color = e4_col, linewidth = e4_width)
plot(e5_val, "EMA 5", color = e5_col, linewidth = e5_width)
 
// ─── End-of-line labels ──────────────────────────────────
f_endLabel(i_labels, e1_val, f_tag(e1_len, e1_tf), e1_col)
f_endLabel(i_labels, e2_val, f_tag(e2_len, e2_tf), e2_col)
f_endLabel(i_labels, e3_val, f_tag(e3_len, e3_tf), e3_col)
f_endLabel(i_labels, e4_val, f_tag(e4_len, e4_tf), e4_col)
f_endLabel(i_labels, e5_val, f_tag(e5_len, e5_tf), e5_col)
 
// ─── Alerts ──────────────────────────────────────────────
// Crosses are computed every bar at global scope (not inside an if), so the
// cross functions keep a consistent history.
e1_up = ta.crossover(close, e1_val)
e1_dn = ta.crossunder(close, e1_val)
e2_up = ta.crossover(close, e2_val)
e2_dn = ta.crossunder(close, e2_val)
e3_up = ta.crossover(close, e3_val)
e3_dn = ta.crossunder(close, e3_val)
e4_up = ta.crossover(close, e4_val)
e4_dn = ta.crossunder(close, e4_val)
e5_up = ta.crossover(close, e5_val)
e5_dn = ta.crossunder(close, e5_val)
 
f_alertCross(e1_alert, e1_up, e1_dn, 1, e1_len, e1_tf)
f_alertCross(e2_alert, e2_up, e2_dn, 2, e2_len, e2_tf)
f_alertCross(e3_alert, e3_up, e3_dn, 3, e3_len, e3_tf)
f_alertCross(e4_alert, e4_up, e4_dn, 4, e4_len, e4_tf)
f_alertCross(e5_alert, e5_up, e5_dn, 5, e5_len, e5_tf)
 
// ─── Status box ──────────────────────────────────────────
// Only appears when an enabled line has nothing valid to draw, so a missing
// line is never a silent mystery.
warn  = f_warn(1, e1_on, e1_low and i_hideLower, e1_val, e1_tf)
warn += f_warn(2, e2_on, e2_low and i_hideLower, e2_val, e2_tf)
warn += f_warn(3, e3_on, e3_low and i_hideLower, e3_val, e3_tf)
warn += f_warn(4, e4_on, e4_low and i_hideLower, e4_val, e4_tf)
warn += f_warn(5, e5_on, e5_low and i_hideLower, e5_val, e5_tf)
 
var table t_status = table.new(position.bottom_right, 1, 1, border_width = 1)
if barstate.islast
    table.clear(t_status, 0, 0)
    if i_status and str.length(warn) > 0
        table.cell(t_status, 0, 0, str.substring(warn, 0, str.length(warn) - 1), text_color = chart.fg_color, bgcolor = color.new(chart.bg_color, 20), text_size = size.small, text_halign = text.align_left)

← 返回列表