MTF Minicharts + Triple EMA

Uno_Mas · study · 273 行 · 点赞 18 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Multi-timeframe minicharts for the Trading Agent stack.
//
// MTF MINICHARTS + TRIPLE EMA  (Pine v6)
// --------------------------------------
// Draws up to six small candlestick charts to the right of the last bar, one
// per chosen timeframe, laid out in a grid (2 columns by default). Each mini
// shows the last N candles of its timeframe (the newest one still forming),
// the 15/30/65 EMAs of that timeframe, a timeframe label and a bias label.
//
// BIAS. Two modes:
//   EMA Stack      "Trend" rule (default): bullish when EMA15 > EMA30 > EMA65
//                  and close > EMA30 on the mini's newest candle, bearish when
//                  the stack is reversed and close < EMA30, neutral otherwise.
//                  "Strict" rule: close must also be beyond EMA15.
//   Candle Close   the last CLOSED candle closed above the high of the candle
//                  before it = bullish, below its low = bearish, else neutral.
// "Highlight Bias Candle" outlines the candle the bias was read from.
//
// SCALE. Each mini's height is a percent of price (0.11 = 0.11%). Raise
// "Chart Height (%)" on slower charts or wider-ranging symbols.
//
// POSITION. Pine can only draw candles in price/bar coordinates, so the grid
// lives on the chart, not pinned to the screen. "Sticky" (default) parks it at
// a fixed price and bar and only recenters when price runs outside the grid's
// vertical band or new bars reach it. "Follow Price" recenters every tick.
//
// LABELS. Each mini carries one header inside the top of its frame, e.g.
// "5 min · BEARISH", colored by bias.
//
// Drawings sit at bar_index offsets to the right of the last bar; scroll the
// chart right (or shrink Right Offset / Bar Spacing) if a mini is cut off.
 
//@version=6
indicator("MTF Minicharts + Triple EMA", shorttitle = "MTF Minis", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 100, max_polylines_count = 100)
 
// ─── Minicharts setup ────────────────────────────────────────────────────────
const string G_SETUP = "Minicharts Setup"
int    numCharts = input.int(5, "Number of Charts", minval = 1, maxval = 6, group = G_SETUP)
string tf1 = input.timeframe("5",   "Chart 1", group = G_SETUP)
string tf2 = input.timeframe("15",  "Chart 2", group = G_SETUP)
string tf3 = input.timeframe("30",  "Chart 3", group = G_SETUP)
string tf4 = input.timeframe("60",  "Chart 4", group = G_SETUP)
string tf5 = input.timeframe("240", "Chart 5", group = G_SETUP)
string tf6 = input.timeframe("1D",  "Chart 6", group = G_SETUP)
 
// ─── Triple EMA ──────────────────────────────────────────────────────────────
const string G_EMA = "Triple EMA"
bool  showEma = input.bool(true, "Show Triple EMA", group = G_EMA)
color ema65C  = input.color(#7B2FF7, "EMA 65 Color", group = G_EMA)
color ema30C  = input.color(#3A2BFF, "EMA 30 Color", group = G_EMA)
color ema15C  = input.color(#2F6BFF, "EMA 15 Color", group = G_EMA)
int   len65   = input.int(65, "Slow Length", minval = 1, group = G_EMA)
int   len30   = input.int(30, "Mid Length",  minval = 1, group = G_EMA)
int   len15   = input.int(15, "Fast Length", minval = 1, group = G_EMA)
 
// ─── Bias framework ──────────────────────────────────────────────────────────
const string G_BIAS = "Bias Framework"
bool   showBias  = input.bool(true,  "Show Bias Label", group = G_BIAS)
bool   hiBias    = input.bool(false, "Highlight Bias Candle", group = G_BIAS)
string biasMode  = input.string("EMA Stack", "Bias Mode", options = ["EMA Stack", "Candle Close"], group = G_BIAS)
color  bullBiasC = input.color(#089981, "Bullish Color", group = G_BIAS)
color  bearBiasC = input.color(#F23645, "Bearish Color", group = G_BIAS)
color  neutBiasC = input.color(#787B86, "Neutral Color", group = G_BIAS)
 
// ─── Style & layout ──────────────────────────────────────────────────────────
const string G_STYLE = "Style & Layout"
int   barsToShow = input.int(24, "Bars to Show", minval = 5, maxval = 60, group = G_STYLE)
int   spacing    = input.int(3, "Bar Spacing", minval = 2, maxval = 10, group = G_STYLE)
bool  showFrames = input.bool(true, "Show Background Frames", group = G_STYLE)
color bullC      = input.color(#089981, "Bull Candle", group = G_STYLE)
color bearC      = input.color(#F23645, "Bear Candle", group = G_STYLE)
int   rightOff   = input.int(35, "Right Offset", minval = 1, group = G_STYLE)
int   colGap     = input.int(22, "Column Gap", minval = 0, group = G_STYLE)
float heightPct  = input.float(0.11, "Chart Height (%)", minval = 0.001, step = 0.01, group = G_STYLE)
float rowGapPct  = input.float(0.025, "Row Gap (%)", minval = 0.0, step = 0.005, group = G_STYLE)
bool  showTf     = input.bool(true, "Show Timeframe Labels", group = G_STYLE)
string posMode   = input.string("Sticky", "Position", options = ["Sticky", "Follow Price"], group = G_STYLE,
     tooltip = "Sticky: the grid stays put and only recenters when price leaves its vertical band or the bars reach it. Follow Price: recenters on the last close every tick.")
int   numCols    = input.int(2, "Columns", minval = 1, maxval = 6, group = G_STYLE)
color frameC     = input.color(color.new(#787B86, 88), "Frame Fill", group = G_STYLE)
color frameBdrC  = input.color(color.new(#787B86, 70), "Frame Border", group = G_STYLE)
string stackRule = input.string("Trend", "EMA Stack Rule", options = ["Trend", "Strict"], group = G_BIAS,
     tooltip = "Trend: EMAs stacked in order and close beyond the mid EMA. Strict: close must also be beyond the fast EMA.")
 
// ─── Data ────────────────────────────────────────────────────────────────────
// Rolling buffer of the last `n` bars on the requested timeframe, 7 values per
// bar: open, high, low, close, ema fast, ema mid, ema slow. Oldest first.
const int STRIDE = 7
 
f_hist(int n) =>
    var array<float> buf = array.new<float>()
    float eF = ta.ema(close, len15)
    float eM = ta.ema(close, len30)
    float eS = ta.ema(close, len65)
    buf.push(open)
    buf.push(high)
    buf.push(low)
    buf.push(close)
    buf.push(eF)
    buf.push(eM)
    buf.push(eS)
    while buf.size() > n * STRIDE
        buf.shift()
    buf
 
array<float> d1 = request.security(syminfo.tickerid, tf1, f_hist(barsToShow))
array<float> d2 = request.security(syminfo.tickerid, tf2, f_hist(barsToShow))
array<float> d3 = request.security(syminfo.tickerid, tf3, f_hist(barsToShow))
array<float> d4 = request.security(syminfo.tickerid, tf4, f_hist(barsToShow))
array<float> d5 = request.security(syminfo.tickerid, tf5, f_hist(barsToShow))
array<float> d6 = request.security(syminfo.tickerid, tf6, f_hist(barsToShow))
 
// ─── Helpers ─────────────────────────────────────────────────────────────────
f_tfText(string tf) =>
    int s = timeframe.in_seconds(tf)
    string txt = tf
    if s < 60
        txt := str.tostring(s) + " sec"
    else if s < 3600
        int m = s / 60
        txt := str.tostring(m) + (m == 1 ? " minute" : " min")
    else if s < 86400
        int h = s / 3600
        txt := str.tostring(h) + (h == 1 ? " hour" : " hours")
    else if s < 604800
        int dd = s / 86400
        txt := str.tostring(dd) + (dd == 1 ? " day" : " days")
    else if s < 2419200
        int w = s / 604800
        txt := str.tostring(w) + (w == 1 ? " week" : " weeks")
    else
        txt := tf + " (month)"
    txt
 
f_y(float p, float lo, float hi, float bot, float h) =>
    hi > lo ? bot + (p - lo) / (hi - lo) * h : bot + h / 2
 
f_emaLine(array<float> d, int n, int off, int x0, float lo, float hi, float bot, float h, color c) =>
    array<chart.point> pts = array.new<chart.point>()
    for i = 0 to n - 1
        float v = d.get(i * STRIDE + off)
        if not na(v)
            pts.push(chart.point.from_index(x0 + i * spacing, f_y(v, lo, hi, bot, h)))
    if pts.size() > 1
        polyline.new(pts, line_color = c, line_width = 1)
 
// Draws one minichart. `k` is the 0-based slot in the grid.
f_draw(array<float> d, string tf, int k, int xBase, float gridTop, float h, float hdr, float g) =>
    if not na(d) and d.size() >= STRIDE
        int n = d.size() / STRIDE
        int col = k % numCols
        int row = int(math.floor(k / numCols))
        int x0 = xBase + col * (barsToShow * spacing + colGap)
        int xEnd = x0 + (barsToShow - 1) * spacing
        float slotTop = gridTop - row * (h + hdr + g)
        float top = slotTop - hdr
        float bot = top - h
 
        // price range of the window (candles + EMAs when shown)
        float hi = na
        float lo = na
        for i = 0 to n - 1
            int b = i * STRIDE
            hi := na(hi) ? d.get(b + 1) : math.max(hi, d.get(b + 1))
            lo := na(lo) ? d.get(b + 2) : math.min(lo, d.get(b + 2))
            if showEma
                for j = 4 to 6
                    float v = d.get(b + j)
                    if not na(v)
                        hi := math.max(hi, v)
                        lo := math.min(lo, v)
 
        // bias
        int last = n - 1
        int biasIdx = last
        int bias = 0
        if biasMode == "EMA Stack"
            int b = last * STRIDE
            float c  = d.get(b + 3)
            float eF = d.get(b + 4)
            float eM = d.get(b + 5)
            float eS = d.get(b + 6)
            if not na(eS)
                bool bullStack = eF > eM and eM > eS
                bool bearStack = eF < eM and eM < eS
                bool strict = stackRule == "Strict"
                bias := bullStack and (strict ? c > eF : c > eM) ? 1 : bearStack and (strict ? c < eF : c < eM) ? -1 : 0
        else if n >= 3
            biasIdx := last - 1
            int b  = biasIdx * STRIDE
            int pb = (biasIdx - 1) * STRIDE
            float c = d.get(b + 3)
            bias := c > d.get(pb + 1) ? 1 : c < d.get(pb + 2) ? -1 : 0
        color biasC = bias == 1 ? bullBiasC : bias == -1 ? bearBiasC : neutBiasC
        string biasTxt = bias == 1 ? "BULLISH" : bias == -1 ? "BEARISH" : "NEUTRAL"
 
        float pad = h * 0.08
        if showFrames
            box.new(x0 - spacing, slotTop, xEnd + spacing, bot - pad, border_color = frameBdrC, bgcolor = frameC)
 
        // candles (oldest drawn at x0, newest at the right edge of the slot)
        int xShift = (barsToShow - n) * spacing
        int halfW = math.max(1, int(math.floor(spacing / 3)))
        for i = 0 to n - 1
            int b = i * STRIDE
            float o = d.get(b)
            float c = d.get(b + 3)
            int x = x0 + xShift + i * spacing
            color cc = c >= o ? bullC : bearC
            line.new(x, f_y(d.get(b + 1), lo, hi, bot, h), x, f_y(d.get(b + 2), lo, hi, bot, h), color = cc, width = 1)
            bool hl = hiBias and i == biasIdx
            box.new(x - halfW, f_y(math.max(o, c), lo, hi, bot, h), x + halfW, f_y(math.min(o, c), lo, hi, bot, h),
                 border_color = hl ? biasC : cc, border_width = hl ? 2 : 1, bgcolor = cc)
 
        if showEma
            int xs = x0 + xShift
            f_emaLine(d, n, 6, xs, lo, hi, bot, h, ema65C)
            f_emaLine(d, n, 5, xs, lo, hi, bot, h, ema30C)
            f_emaLine(d, n, 4, xs, lo, hi, bot, h, ema15C)
 
        int xMid = int(math.round((x0 + xEnd) / 2))
        // one header inside the top of the frame: "5 min · BEARISH"
        string hdrTxt = showTf and showBias ? f_tfText(tf) + "  ·  " + biasTxt : showTf ? f_tfText(tf) : showBias ? biasTxt : ""
        if hdrTxt != ""
            label.new(xMid, slotTop, hdrTxt, style = label.style_label_down, color = color(na),
                 textcolor = showBias ? biasC : color.new(#B2B5BE, 0), size = size.small)
 
// ─── Render ──────────────────────────────────────────────────────────────────
varip float anchorPx = na
varip int   anchorX  = na
if barstate.islast
    for b in box.all
        b.delete()
    for l in line.all
        l.delete()
    for l in label.all
        l.delete()
    for p in polyline.all
        p.delete()
 
    // Sticky: the grid holds its price and bar position until price runs
    // outside its vertical band or the bars catch up to it, then recenters.
    // Sizes come from the anchor price, so they don't breathe with each tick.
    if na(anchorPx) or posMode == "Follow Price"
        anchorPx := close
    float h0 = anchorPx * heightPct / 100
    float g0 = anchorPx * rowGapPct / 100
    float hdr0 = showTf or showBias ? h0 * 0.2 : 0.0
    int rows = int(math.floor((numCharts + numCols - 1) / numCols))
    float total = rows * (h0 + hdr0) + (rows - 1) * g0
    if close > anchorPx + total / 2 or close < anchorPx - total / 2
        anchorPx := close
    if na(anchorX) or posMode == "Follow Price" or bar_index + rightOff / 2 > anchorX
        anchorX := bar_index + rightOff
    float h = anchorPx * heightPct / 100
    float g = anchorPx * rowGapPct / 100
    float hdr = showTf or showBias ? h * 0.2 : 0.0
    total := rows * (h + hdr) + (rows - 1) * g
    float gridTop = anchorPx + total / 2
 
    f_draw(d1, tf1, 0, anchorX, gridTop, h, hdr, g)
    if numCharts >= 2
        f_draw(d2, tf2, 1, anchorX, gridTop, h, hdr, g)
    if numCharts >= 3
        f_draw(d3, tf3, 2, anchorX, gridTop, h, hdr, g)
    if numCharts >= 4
        f_draw(d4, tf4, 3, anchorX, gridTop, h, hdr, g)
    if numCharts >= 5
        f_draw(d5, tf5, 4, anchorX, gridTop, h, hdr, g)
    if numCharts >= 6
        f_draw(d6, tf6, 5, anchorX, gridTop, h, hdr, g)

← 返回列表