Dinamik EMA PRO MAX

agahakanaga · study · 280 行 · 点赞 427 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © agahakanaga
 
// =================================================================================================
// DİNAMİK EMA PRO MAX
// -------------------------------------------------------------------------------------------------
// Instead of plotting every EMA, shows only the ones closest to price — a set number above and a
// set number below. Fibonacci and classic lengths (34 … 1000) are calculated from up to four
// sources and ranked by their distance to the last close.
//
// SOURCES
//   Chart timeframe        : split-adjusted price
//   Chart timeframe  (A)   : dividend-adjusted price
//   Weekly (W)             : split-adjusted price, only on timeframes below 1W
//   Weekly (W … A)         : dividend-adjusted price
//   Adjusted EMAs that match the unadjusted ones (no dividends, crypto, FX) are skipped.
//
// DISPLAY
//   Each EMA is a single polyline with optional history and a 2-bar slope projection. Labels are
//   spread apart by an ATR-based minimum gap. Label tooltips show the source, price and distance
//   to the close. Türkçe / English language option.
//
// REPAINTING
//   Drawings are made on the last bar only. Weekly EMAs follow the running weekly bar; with
//   "History" on, past bars show the value of the finished week (higher-timeframe repaint).
//
// DISCLAIMER
//   This is an analysis tool, not investment advice.
// =================================================================================================
 
//@version=6
indicator("Dinamik EMA PRO MAX", shorttitle="Dinamik EMA", overlay=true, max_labels_count=100, max_polylines_count=100)
 
// =================================================================================================
// 1) GENERAL
// =================================================================================================
grp_g = "1) General (Genel)"
p_lang     = input.string("English", "Language / Dil", options=["Türkçe","English"], group=grp_g, tooltip="Language of the label tooltips.\n\n🇹🇷 Etiket açıklamalarının dili.")
showEmas   = input.bool(true, "Show EMAs (EMA'ları Göster)", group=grp_g)
useAdj     = input.bool(true, "Dividend-Adjusted (A) EMAs (Temettü Düzeltmeli (A) EMA'lar)", group=grp_g, tooltip="Adds EMAs calculated from the dividend-adjusted price. Those identical to the unadjusted values are not drawn twice.\n\n🇹🇷 Temettüye göre düzeltilmiş fiyattan hesaplanan EMA'ları da ekler. Düzeltilmemiş değerle aynı çıkanlar tekrar çizilmez.")
showWeekly = input.bool(true, "Weekly (W) EMAs (Haftalık (W) EMA'lar)", group=grp_g, tooltip="Active only on timeframes below 1W.\n\n🇹🇷 Yalnızca haftalıktan küçük periyotlarda devreye girer.")
numUp      = input.int(10, "EMAs Above Price (Fiyat Üstündeki EMA Sayısı)", minval=0, maxval=24, group=grp_g)
numDn      = input.int(10, "EMAs Below Price (Fiyat Altındaki EMA Sayısı)", minval=0, maxval=24, group=grp_g)
lookback   = input.int(0, "History (Geçmiş Çizim) · Bars", minval=0, maxval=500, group=grp_g, tooltip="0 = only the projection from the last bar is drawn.\n\n🇹🇷 0 = yalnızca son bardan çıkan uzantı çizilir.")
lineWidth  = input.int(2, "Line Width (Çizgi Kalınlığı)", minval=1, maxval=5, group=grp_g)
 
// =================================================================================================
// 2) LABELS
// =================================================================================================
grp_l = "2) Labels (Etiketler)"
showLabels   = input.bool(true, "Show Labels (Etiketleri Göster)", group=grp_l)
showPrice    = input.bool(false, "Show Price (Fiyatı Göster)", group=grp_l)
lblSizeStr   = input.string("Small (Küçük)", "Size (Boyut)", options=["Auto (Otomatik)","Tiny (Minik)","Small (Küçük)","Normal","Large (Büyük)","Huge (Devasa)"], group=grp_l)
lblBg        = input.color(color.white, "Background (Arka Plan)", inline="bg", group=grp_l)
lblBgTransp  = input.int(70, "Transparency (Saydamlık)", minval=0, maxval=100, inline="bg", group=grp_l)
useEmaColor  = input.bool(false, "Use EMA color for text (Yazıda EMA rengini kullan)", group=grp_l)
lblTxt       = input.color(color.black, "Text (Yazı)", inline="tx", group=grp_l)
lblTxtTransp = input.int(0, "Transparency (Saydamlık)", minval=0, maxval=100, inline="tx", group=grp_l)
lblGap       = input.float(0.3, "Gap Between Labels (Etiketler Arası Boşluk) · ATR x", step=0.05, minval=0.0, group=grp_l, tooltip="Minimum vertical gap between labels. 0 = off.\n\n🇹🇷 Etiketler arasındaki minimum dikey boşluk. 0 = kapalı.")
 
// =================================================================================================
// 3) COLORS
// =================================================================================================
grp_c = "3) Colors (Renkler)"
col34   = input.color(#2196F3, "EMA 34",   inline="c1", group=grp_c)
col50   = input.color(#00BCD4, "EMA 50",   inline="c1", group=grp_c)
col55   = input.color(#009688, "EMA 55",   inline="c2", group=grp_c)
col89   = input.color(#4CAF50, "EMA 89",   inline="c2", group=grp_c)
col100  = input.color(#8BC34A, "EMA 100",  inline="c3", group=grp_c)
col144  = input.color(#CDDC39, "EMA 144",  inline="c3", group=grp_c)
col200  = input.color(#696758, "EMA 200",  inline="c4", group=grp_c)
col233  = input.color(#6E07FF, "EMA 233",  inline="c4", group=grp_c)
col377  = input.color(#FF9800, "EMA 377",  inline="c5", group=grp_c)
col500  = input.color(#FF5722, "EMA 500",  inline="c5", group=grp_c)
col610  = input.color(#E91E63, "EMA 610",  inline="c6", group=grp_c)
col1000 = input.color(#9C27B0, "EMA 1000", inline="c6", group=grp_c)
 
// =================================================================================================
// CONSTANTS / TYPES
// =================================================================================================
bool EN = p_lang == "English"
f_t(string tr, string en) => EN ? en : tr
 
const int SRC_STD   = 0   // chart timeframe, split-adjusted
const int SRC_ADJ   = 1   // chart timeframe, dividend-adjusted
const int SRC_W_STD = 2   // weekly, split-adjusted
const int SRC_W_ADJ = 3   // weekly, dividend-adjusted
 
var int[] LENS = array.from(34, 50, 55, 89, 100, 144, 200, 233, 377, 500, 610, 1000)
 
type EmaItem
    int   k       // index in LENS
    int   src
    float val
    float dist
 
// =================================================================================================
// CALCULATIONS
// =================================================================================================
f_emaSet() =>
    [ta.ema(close, 34),  ta.ema(close, 50),  ta.ema(close, 55),  ta.ema(close, 89),
     ta.ema(close, 100), ta.ema(close, 144), ta.ema(close, 200), ta.ema(close, 233),
     ta.ema(close, 377), ta.ema(close, 500), ta.ema(close, 610), ta.ema(close, 1000)]
 
tStd = ticker.new(syminfo.prefix, syminfo.ticker, syminfo.session, adjustment.splits)
tAdj = ticker.new(syminfo.prefix, syminfo.ticker, syminfo.session, adjustment.dividends)
 
[s34,  s50,  s55,  s89,  s100,  s144,  s200,  s233,  s377,  s500,  s610,  s1000]  = request.security(tStd, timeframe.period, f_emaSet())
[a34,  a50,  a55,  a89,  a100,  a144,  a200,  a233,  a377,  a500,  a610,  a1000]  = request.security(tAdj, timeframe.period, f_emaSet())
[ws34, ws50, ws55, ws89, ws100, ws144, ws200, ws233, ws377, ws500, ws610, ws1000] = request.security(tStd, "1W", f_emaSet())
[wa34, wa50, wa55, wa89, wa100, wa144, wa200, wa233, wa377, wa500, wa610, wa1000] = request.security(tAdj, "1W", f_emaSet())
 
// all 48 values of the current bar — column = src * 12 + k
float[] CUR = array.from(s34,  s50,  s55,  s89,  s100,  s144,  s200,  s233,  s377,  s500,  s610,  s1000,
                         a34,  a50,  a55,  a89,  a100,  a144,  a200,  a233,  a377,  a500,  a610,  a1000,
                         ws34, ws50, ws55, ws89, ws100, ws144, ws200, ws233, ws377, ws500, ws610, ws1000,
                         wa34, wa50, wa55, wa89, wa100, wa144, wa200, wa233, wa377, wa500, wa610, wa1000)
 
// history of closed bars, oldest row first (filled at the end of the script)
var matrix<float> HIST = matrix.new<float>(0, 48)
int histLen = math.max(lookback, 1)
 
float g_atr    = nz(ta.atr(14), syminfo.mintick * 10)
bool  weeklyOk = showWeekly and timeframe.in_seconds() < timeframe.in_seconds("1W")
 
string LSZ = switch lblSizeStr
    "Auto (Otomatik)" => size.auto
    "Tiny (Minik)"    => size.tiny
    "Normal"          => size.normal
    "Large (Büyük)"   => size.large
    "Huge (Devasa)"   => size.huge
    => size.small
 
// =================================================================================================
// HELPERS
// =================================================================================================
// EMA value of a source / length, "off" bars back
f_emaAt(int src, int k, int off) =>
    int col = src * 12 + k
    float v = na
    if off == 0
        v := CUR.get(col)
    else
        int r = HIST.rows() - off
        if r >= 0
            v := HIST.get(r, col)
    v
 
f_collect(array<EmaItem> up, array<EmaItem> dn, int src, int k, float v) =>
    if not na(v)
        if v > close
            up.push(EmaItem.new(k, src, v, v - close))
        else
            dn.push(EmaItem.new(k, src, v, close - v))
 
// n EMAs closest to price
f_nearest(array<EmaItem> items, int n) =>
    array<EmaItem> out = array.new<EmaItem>()
    int sz = items.size()
    if sz > 0 and n > 0
        array<float> d = array.new_float()
        for it in items
            d.push(it.dist)
        array<int> idx = d.sort_indices(order.ascending)
        for i = 0 to math.min(n, sz) - 1
            out.push(items.get(idx.get(i)))
    out
 
// value projected 2 bars ahead with the last bar's slope
f_proj(EmaItem it) =>
    float y0 = f_emaAt(it.src, it.k, 0)
    float y1 = f_emaAt(it.src, it.k, 1)
    na(y1) ? y0 : y0 + (y0 - y1) * 2
 
// pushes labels away from price until each pair is at least "gap" apart
f_spread(array<float> ys, float gap, bool upward) =>
    int n = ys.size()
    if n > 1 and gap > 0
        array<int> idx = ys.sort_indices(upward ? order.ascending : order.descending)
        for i = 1 to n - 1
            float prev = ys.get(idx.get(i - 1))
            float cur  = ys.get(idx.get(i))
            if upward and cur - prev < gap
                ys.set(idx.get(i), prev + gap)
            else if not upward and prev - cur < gap
                ys.set(idx.get(i), prev - gap)
 
f_shift(array<float> ys, float amount) =>
    if ys.size() > 0
        for i = 0 to ys.size() - 1
            ys.set(i, ys.get(i) + amount)
 
f_tip(EmaItem it, bool isAdj, bool isWeekly) =>
    string tf   = isWeekly ? f_t("Haftalık (1W)", "Weekly (1W)") : f_t("Grafik periyodu", "Chart timeframe")
    string adj  = isAdj ? f_t("temettü düzeltmeli", "dividend-adjusted") : f_t("bölünme düzeltmeli", "split-adjusted")
    float  dist = close != 0 ? (it.val - close) / close * 100.0 : 0.0
    "EMA " + str.tostring(LENS.get(it.k)) + " · " + tf + " · " + adj + "\n" + f_t("Fiyat: ", "Price: ") + str.tostring(it.val, format.mintick) + "\n" + f_t("Mesafe: ", "Distance: ") + (dist >= 0 ? "+" : "") + str.tostring(dist, "#.##") + "%"
 
f_draw(EmaItem it, float lblY, color c) =>
    array<chart.point> pts = array.new<chart.point>()
    for off = lookback to 0
        float v = f_emaAt(it.src, it.k, off)
        if not na(v)
            pts.push(chart.point.from_index(bar_index - off, v))
    pts.push(chart.point.from_index(bar_index + 2, f_proj(it)))
    if pts.size() > 1
        polyline.new(pts, xloc=xloc.bar_index, line_color=c, line_width=lineWidth)
 
    if showLabels
        bool   isAdj    = it.src == SRC_ADJ or it.src == SRC_W_ADJ
        bool   isWeekly = it.src == SRC_W_STD or it.src == SRC_W_ADJ
        string txt      = (isWeekly ? "W" : "") + str.tostring(LENS.get(it.k)) + (isAdj ? " A" : "")
        if showPrice
            txt += "\n(" + str.tostring(it.val, format.mintick) + ")"
        color tc = color.new(useEmaColor ? c : lblTxt, lblTxtTransp)
        label.new(bar_index + (isAdj ? 4 : 3), lblY, txt, xloc=xloc.bar_index, style=label.style_label_left, color=color.new(lblBg, lblBgTransp), textcolor=tc, size=LSZ, tooltip=f_tip(it, isAdj, isWeekly))
 
// =================================================================================================
// DRAWING
// =================================================================================================
if barstate.islast
    for p in polyline.all
        p.delete()
    for l in label.all
        l.delete()
 
    if showEmas
        array<EmaItem> up = array.new<EmaItem>()
        array<EmaItem> dn = array.new<EmaItem>()
 
        for k = 0 to 11
            float vs = f_emaAt(SRC_STD, k, 0)
            f_collect(up, dn, SRC_STD, k, vs)
            if useAdj
                float va = f_emaAt(SRC_ADJ, k, 0)
                if na(vs) or math.abs(va - vs) > syminfo.mintick
                    f_collect(up, dn, SRC_ADJ, k, va)
            if weeklyOk
                float ws = f_emaAt(SRC_W_STD, k, 0)
                f_collect(up, dn, SRC_W_STD, k, ws)
                if useAdj
                    float wa = f_emaAt(SRC_W_ADJ, k, 0)
                    if na(ws) or math.abs(wa - ws) > syminfo.mintick
                        f_collect(up, dn, SRC_W_ADJ, k, wa)
 
        array<EmaItem> selUp = f_nearest(up, numUp)
        array<EmaItem> selDn = f_nearest(dn, numDn)
 
        array<float> yUp = array.new_float()
        array<float> yDn = array.new_float()
        for it in selUp
            yUp.push(f_proj(it))
        for it in selDn
            yDn.push(f_proj(it))
 
        float gap = g_atr * lblGap
        f_spread(yUp, gap, true)
        f_spread(yDn, gap, false)
 
        // keep the upper and lower groups apart around price
        if yUp.size() > 0 and yDn.size() > 0
            float overlap = gap - (yUp.min() - yDn.max())
            if overlap > 0
                f_shift(yUp,  overlap / 2)
                f_shift(yDn, -overlap / 2)
 
        color[] cols = array.from(col34, col50, col55, col89, col100, col144, col200, col233, col377, col500, col610, col1000)
 
        for [i, it] in selUp
            f_draw(it, yUp.get(i), cols.get(it.k))
        for [i, it] in selDn
            f_draw(it, yDn.get(i), cols.get(it.k))
 
// =================================================================================================
// HISTORY BUFFER — only closed bars are stored, so live ticks never write into it
// =================================================================================================
if barstate.isconfirmed and bar_index >= last_bar_index - histLen - 1
    HIST.add_row(HIST.rows(), CUR)
    while HIST.rows() > histLen
        HIST.remove_row(0)

← 返回列表