4-in-1 MTF Indicator Dashboard | julzALGO

julzALGO · study · 563 行 · 点赞 263 · 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/
// © julzALGO
 
//@version=6
indicator("4-in-1 MTF Indicator Dashboard | julzALGO", shorttitle="julzALGO MTF4", overlay=true, scale=scale.none, behind_chart=false, max_lines_count=500, max_boxes_count=500, max_labels_count=20, dynamic_requests=true)
 
stChoice = input.string("Supertrend", "Indicator", options=["ADX","ATR","CCI","EMA","HMA","Linear Regression","MACD","MFI","Momentum","OBV","ROC","RSI","Session VWAP","SMA","Stochastic %K","Supertrend","VWMA","Williams %R","WMA"], group="Panel 1 - Top left")
stTF = input.timeframe("1", "Timeframe", group="Panel 1 - Top left")
stLength = input.int(10, "Length", minval=2, maxval=500, group="Panel 1 - Top left", tooltip="Period for the selected indicator. Supertrend uses it as ATR period. Not used by Session VWAP, OBV or MACD; MACD uses the shared parameters below.")
stFactor = input.float(3, "Supertrend factor", minval=0.1, step=0.1, group="Panel 1 - Top left")
 
rsiChoice = input.string("RSI", "Indicator", options=["ADX","ATR","CCI","EMA","HMA","Linear Regression","MACD","MFI","Momentum","OBV","ROC","RSI","Session VWAP","SMA","Stochastic %K","Supertrend","VWMA","Williams %R","WMA"], group="Panel 2 - Top right")
rsiTF = input.timeframe("5", "Timeframe", group="Panel 2 - Top right")
rsiLength = input.int(14, "Length", minval=2, maxval=500, group="Panel 2 - Top right", tooltip="Period for the selected indicator. Supertrend uses it as ATR period. Not used by Session VWAP, OBV or MACD; MACD uses the shared parameters below.")
rsiFactor = input.float(3, "Supertrend factor", minval=0.1, step=0.1, group="Panel 2 - Top right")
 
atrChoice = input.string("MACD", "Indicator", options=["ADX","ATR","CCI","EMA","HMA","Linear Regression","MACD","MFI","Momentum","OBV","ROC","RSI","Session VWAP","SMA","Stochastic %K","Supertrend","VWMA","Williams %R","WMA"], group="Panel 3 - Bottom left")
atrTF = input.timeframe("10", "Timeframe", group="Panel 3 - Bottom left")
atrLength = input.int(14, "Length", minval=2, maxval=500, group="Panel 3 - Bottom left", tooltip="Period for the selected indicator. Supertrend uses it as ATR period. Not used by Session VWAP, OBV or MACD; MACD uses the shared parameters below.")
atrFactor = input.float(3, "Supertrend factor", minval=0.1, step=0.1, group="Panel 3 - Bottom left")
 
emaChoice = input.string("EMA", "Indicator", options=["ADX","ATR","CCI","EMA","HMA","Linear Regression","MACD","MFI","Momentum","OBV","ROC","RSI","Session VWAP","SMA","Stochastic %K","Supertrend","VWMA","Williams %R","WMA"], group="Panel 4 - Bottom right")
emaTF = input.timeframe("60", "Timeframe", group="Panel 4 - Bottom right")
emaLength = input.int(50, "Length", minval=2, maxval=500, group="Panel 4 - Bottom right", tooltip="Period for the selected indicator. Supertrend uses it as ATR period. Not used by Session VWAP, OBV or MACD; MACD uses the shared parameters below.")
emaFactor = input.float(3, "Supertrend factor", minval=0.1, step=0.1, group="Panel 4 - Bottom right")
 
macdSource = input.string("Close", "MACD source", options=["Close", "Open", "High", "Low", "HL2", "HLC3", "OHLC4"], group="MACD - Calculation")
macdFast = input.int(12, "MACD fast", minval=1, maxval=500, group="MACD - Calculation")
macdSlow = input.int(26, "MACD slow", minval=2, maxval=500, group="MACD - Calculation")
macdSignal = input.int(9, "MACD signal", minval=1, maxval=500, group="MACD - Calculation")
macdOscType = input.string("EMA", "MACD oscillator MA", options=["EMA", "SMA"], group="MACD - Calculation")
macdSigType = input.string("EMA", "MACD signal MA", options=["EMA", "SMA"], group="MACD - Calculation")
 
adxSmooth = input.int(14, "ADX smoothing", minval=1, maxval=500, group="Oscillators - Calculation and Guides")
rsiUpper = input.float(70, "Oscillator upper level", minval=1, maxval=100, group="Oscillators - Calculation and Guides", tooltip="Guides for RSI, Stochastic %K and MFI.")
rsiLower = input.float(30, "Oscillator lower level", minval=0, maxval=99, group="Oscillators - Calculation and Guides")
 
showLive = input.bool(true, "Live developing candle", group="Mini-Chart History", tooltip="Update the latest sample on incoming realtime ticks. Its OHLC, indicator value and Supertrend direction can change until the selected-timeframe candle closes. Disable for closed samples only.")
sampleLimit = input.int(50, "Samples per panel", minval=10, maxval=60, group="Mini-Chart History")
breakTimeGaps = input.bool(true, "Break lines across time gaps", group="Mini-Chart History", tooltip="Also breaks across market closures. Missing/NA values always break the line. Each panel spaces samples evenly; its time span can differ from the other panels.")
 
string layoutGroup = "Dashboard Layout"
anchor = input.string("Right of current bar", "Horizontal anchor", options=["Right of current bar", "Latest bars", "Visible right edge"], group=layoutGroup, tooltip="Right of current bar places the dashboard in future chart space, leaving the latest price candle unobstructed. Add right-side chart space to see it. Other modes overlay historical candles. These are bar coordinates, not fixed pixels.")
currentBarGap = input.int(5, "Gap after current bar", minval=1, maxval=50, group=layoutGroup)
requestedWidth = input.int(60, "Panel width (chart bars)", minval=30, maxval=180, group=layoutGroup)
panelHeight = input.float(38, "Panel height (% visible price range)", minval=20, maxval=45, group=layoutGroup)
horizontalShift = input.int(0, "Horizontal shift (bars)", minval=-200, maxval=100, group=layoutGroup)
verticalShift = input.float(0, "Vertical shift (% visible price range)", minval=-100, maxval=100, group=layoutGroup)
hideMatchingTF = input.bool(false, "Hide mini-chart matching chart timeframe", group=layoutGroup, tooltip="Optional: hide a panel's mini-chart when its timeframe matches the main chart. Disabled by default so all panels remain visible when switching chart timeframes.")
 
theme = input.string("Dark", "Theme", options=["Dark", "Light"], group="Colors and Appearance")
textSizeInput = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group="Colors and Appearance")
strokeWidth = input.int(2, "Line width", minval=1, maxval=4, group="Colors and Appearance")
panelOneColor = input.color(#00D982, "Panel 1 line", group="Colors and Appearance")
rsiColor = input.color(#C879F4, "Panel 2 line", group="Colors and Appearance")
atrColor = input.color(#FF9E35, "Panel 3 line", group="Colors and Appearance")
emaColor = input.color(#12BFF3, "Panel 4 line", group="Colors and Appearance")
rsiLevelColor = input.color(#9977BB, "RSI levels", group="Colors and Appearance")
 
candleBull = input.color(#21B882, "Bull candle", group="Candles and Supertrend - Colors")
candleBear = input.color(#EF5364, "Bear candle", group="Candles and Supertrend - Colors")
bullColor = input.color(#00D982, "Supertrend rising", group="Candles and Supertrend - Colors")
bearColor = input.color(#FF5264, "Supertrend falling", group="Candles and Supertrend - Colors")
 
macdLineColor = input.color(#2962FF, "MACD line", group="MACD - Colors")
macdSignalColor = input.color(#FF6D00, "MACD signal", group="MACD - Colors")
histPosRise = input.color(#26A69A, "Histogram positive rising", group="MACD - Colors")
histPosFall = input.color(#B2DFDB, "Histogram positive falling", group="MACD - Colors")
histNegRise = input.color(#FFCDD2, "Histogram negative rising", group="MACD - Colors")
histNegFall = input.color(#FF5252, "Histogram negative falling", group="MACD - Colors")
 
// Two chart-bar slots per sample keep candle bodies and wicks centered.
int panelWidth = math.max(requestedWidth, sampleLimit * 2 + 4)
 
color background = theme == "Dark" ? #101418 : #F5F7F9
color foreground = theme == "Dark" ? #EDF1F5 : #18212A
color muted = theme == "Dark" ? #A5AFBA : #596673
string fontSize = textSizeInput == "Tiny" ? size.tiny : textSizeInput == "Normal" ? size.normal : size.small
 
indicatorKind(simple string choice) =>
    switch choice
        "Supertrend" => 0
        "RSI" => 1
        "ATR" => 2
        "EMA" => 3
        "SMA" => 4
        "WMA" => 5
        "VWMA" => 6
        "HMA" => 7
        "Session VWAP" => 8
        "MACD" => 9
        "Stochastic %K" => 10
        "CCI" => 11
        "ROC" => 12
        "ADX" => 13
        "Momentum" => 14
        "OBV" => 15
        "MFI" => 16
        "Williams %R" => 17
        "Linear Regression" => 19
        => 3
 
priceSeries(int kind) =>
    kind == 0 or (kind >= 3 and kind <= 8) or kind == 19
 
boundedOscillator(int kind) =>
    kind == 1 or kind == 10 or kind == 13 or kind == 16
 
oscillatorGuides(int kind) =>
    kind == 1 or kind == 10 or kind == 16
 
int stKind = indicatorKind(stChoice)
int rsiKind = indicatorKind(rsiChoice)
int atrKind = indicatorKind(atrChoice)
int emaKind = indicatorKind(emaChoice)
 
type Samples
    array<int> stamps
    array<float> values
    array<float> directions
    array<float> opens
    array<float> highs
    array<float> lows
    array<float> closes
    array<float> signals
    array<float> histograms
    bool developing = false
 
newSamples() =>
    Samples.new(array.new<int>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>())
 
method appendSample(Samples data, int stamp, float value, float direction, float o, float h, float l, float c, float sig, float hist) =>
    if not na(stamp)
        int count = data.stamps.size()
        int previousStamp = count > 0 ? data.stamps.last() : na
        if count == 0 or stamp > previousStamp
            data.stamps.push(stamp)
            data.values.push(value)
            data.directions.push(direction)
            data.opens.push(o)
            data.highs.push(h)
            data.lows.push(l)
            data.closes.push(c)
            data.signals.push(sig)
            data.histograms.push(hist)
            if data.stamps.size() > sampleLimit
                int _ = data.stamps.shift()
                float _ = data.values.shift()
                float _ = data.directions.shift()
                float _ = data.opens.shift()
                float _ = data.highs.shift()
                float _ = data.lows.shift()
                float _ = data.closes.shift()
                float _ = data.signals.shift()
                float _ = data.histograms.shift()
            data
        else if stamp == previousStamp
            data.values.set(count - 1, value)
            data.directions.set(count - 1, direction)
            data.opens.set(count - 1, o)
            data.highs.set(count - 1, h)
            data.lows.set(count - 1, l)
            data.closes.set(count - 1, c)
            data.signals.set(count - 1, sig)
            data.histograms.set(count - 1, hist)
            data
    data
 
macdAverage(float source, simple int length, simple string averageType) =>
    float emaValue = ta.ema(source, length)
    float smaValue = ta.sma(source, length)
    averageType == "SMA" ? smaValue : emaValue
 
// This entire function is evaluated in the requested symbol/timeframe context.
packet(simple int kind, simple int length, simple float factor, simple int offset) =>
    [st, direction] = ta.supertrend(factor, length)
    float rsi = ta.rsi(close, length)
    float atr = ta.atr(length)
    float ema = ta.ema(close, length)
    float sma = ta.sma(close, length)
    float wma = ta.wma(close, length)
    float vwma = ta.vwma(close, length)
    float hma = ta.hma(close, length)
    float vwap = ta.vwap(hlc3)
    float source = switch macdSource
        "Open" => open
        "High" => high
        "Low" => low
        "HL2" => hl2
        "HLC3" => hlc3
        "OHLC4" => ohlc4
        => close
    float macdLine = macdAverage(source, macdFast, macdOscType) - macdAverage(source, macdSlow, macdOscType)
    float signalLine = macdAverage(macdLine, macdSignal, macdSigType)
    float histogram = macdLine - signalLine
    // Retain the source-timeframe change even for the first visible histogram bar.
    float drawState = kind == 9 ? (histogram > histogram[1] ? 1.0 : -1.0) : direction
    float stochastic = ta.stoch(close, high, low, length)
    float cci = ta.cci(hlc3, length)
    float roc = ta.roc(close, length)
    [_, _, adx] = ta.dmi(length, adxSmooth)
    float momentum = ta.mom(close, length)
    float obv = ta.obv
    float mfi = ta.mfi(hlc3, length)
    float williams = ta.wpr(length)
    float regression = ta.linreg(close, length, 0)
    float value = switch kind
        0 => st
        1 => rsi
        2 => atr
        3 => ema
        4 => sma
        5 => wma
        6 => vwma
        7 => hma
        8 => vwap
        9 => macdLine
        10 => stochastic
        11 => cci
        12 => roc
        13 => adx
        14 => momentum
        15 => obv
        16 => mfi
        17 => williams
        19 => regression
        => float(na)
    [time[offset], time_close[offset], value[offset], drawState[offset], open[offset], high[offset], low[offset], close[offset], signalLine[offset], histogram[offset]]
 
// Object payload avoids exceeding the combined request tuple-element limit.
type LiveSample
    int stamp
    int ending
    float value
    float direction
    float o
    float h
    float l
    float c
    float sig
    float hist
 
livePacket(simple int kind, simple int length, simple float factor) =>
    [stamp, ending, value, direction, o, h, l, c, sig, hist] = packet(kind, length, factor, 0)
    LiveSample.new(stamp, ending, value, direction, o, h, l, c, sig, hist)
 
collect(Samples data, simple string tf, simple int kind, simple int length, simple float factor) =>
    // Do not retain an unfinished sample from a prior chart-bar commit.
    // The confirmed collector below supplies its final value when available.
    if data.developing and data.stamps.size() > 0
        int _ = data.stamps.pop()
        float _ = data.values.pop()
        float _ = data.directions.pop()
        float _ = data.opens.pop()
        float _ = data.highs.pop()
        float _ = data.lows.pop()
        float _ = data.closes.pop()
        float _ = data.signals.pop()
        float _ = data.histograms.pop()
    data.developing := false
    float requestedSeconds = timeframe.in_seconds(tf)
    float chartSeconds = timeframe.in_seconds()
    if requestedSeconds < chartSeconds
        [stamps, endings, values, directions, opens, highs, lows, closes, signals, histograms] = request.security_lower_tf(syminfo.tickerid, tf, packet(kind, length, factor, 0))
        int count = stamps.size()
        // Only the tail can survive in a bounded buffer; avoid scanning a whole day of minutes.
        if count > 0
            for i = math.max(0, count - sampleLimit - 1) to count - 1
                int ending = endings.get(i)
                if not na(ending) and (not barstate.isrealtime or ending <= timenow)
                    data.appendSample(stamps.get(i), values.get(i), directions.get(i), opens.get(i), highs.get(i), lows.get(i), closes.get(i), signals.get(i), histograms.get(i))
    else if requestedSeconds > chartSeconds
        // Previous HTF bar + lookahead_on: never expose the unfinished HTF result.
        [stamp, _, value, direction, o, h, l, c, sig, hist] = request.security(syminfo.tickerid, tf, packet(kind, length, factor, 1), lookahead=barmerge.lookahead_on)
        data.appendSample(stamp, value, direction, o, h, l, c, sig, hist)
    else
        [stamp, _, value, direction, o, h, l, c, sig, hist] = request.security(syminfo.tickerid, tf, packet(kind, length, factor, 0), lookahead=barmerge.lookahead_off)
        if barstate.isconfirmed
            data.appendSample(stamp, value, direction, o, h, l, c, sig, hist)
    if showLive
        // Warm the request on historical bars; use its endpoint only in realtime.
        LiveSample live = request.security(syminfo.tickerid, tf, livePacket(kind, length, factor), lookahead=barmerge.lookahead_off)
        if barstate.isrealtime and not na(live)
            if not na(live.stamp) and not na(live.ending) and live.stamp <= timenow
                data.appendSample(live.stamp, live.value, live.direction, live.o, live.h, live.l, live.c, live.sig, live.hist)
                data.developing := data.stamps.size() > 0 and data.stamps.last() == live.stamp and live.ending > timenow
    data
 
type Panel
    box frame
    label heading
    label reading
    label status
    label upperLabel
    label lowerLabel
    array<line> strokes
    line upperGuide
    line lowerGuide
    array<box> bodies
    array<box> wicks
    line backdropTop
    line backdropBottom
    linefill backdrop
    array<line> signalStrokes
 
newPanel(int kind) =>
    bool withCandles = priceSeries(kind)
    array<line> signalStrokes = array.new<line>()
    if kind == 9
        for i = 0 to sampleLimit - 2
            signalStrokes.push(line.new(na, na, na, na))
    array<line> strokes = array.new<line>()
    for i = 0 to sampleLimit - 2
        strokes.push(line.new(na, na, na, na))
    box frame = box.new(na, na, na, na, bgcolor=na)
    array<box> bodies = array.new<box>()
    array<box> wicks = array.new<box>()
    if withCandles
        for i = 0 to sampleLimit - 1
            wicks.push(box.new(na, na, na, na))
            bodies.push(box.new(na, na, na, na))
    if kind == 9
        for i = 0 to sampleLimit - 1
            bodies.push(box.new(na, na, na, na))
    line backdropTop = line.new(na, na, na, na, color=na)
    line backdropBottom = line.new(na, na, na, na, color=na)
    linefill backdrop = linefill.new(backdropTop, backdropBottom, background)
    Panel.new(frame, label.new(na, na, "", style=label.style_none), label.new(na, na, "", style=label.style_none), label.new(na, na, "", style=label.style_none), label.new(na, na, "", style=label.style_none), label.new(na, na, "", style=label.style_none), strokes, line.new(na, na, na, na), line.new(na, na, na, na), bodies, wicks, backdropTop, backdropBottom, backdrop, signalStrokes)
 
putText(label id, int x, float y, string caption, color ink) =>
    label.set_xy(id, x, y)
    label.set_text(id, caption)
    label.set_textcolor(id, ink)
    label.set_size(id, fontSize)
 
mapY(float value, float lower, float upper, float bottom, float height) =>
    bottom + (value - lower) / (upper - lower) * height
 
method render(Panel panel, Samples data, int x, float top, float unit, string name, string tf, int kind, color ink) =>
    int right = x + panelWidth
    float bottom = top - panelHeight * unit
    float graphBottom = bottom + 9 * unit
    float graphHeight = (panelHeight - 16) * unit
    bool hidden = hideMatchingTF and timeframe.in_seconds(tf) == timeframe.in_seconds()
    bool withCandles = priceSeries(kind)
    int count = data.values.size()
    int valid = 0
    float minimum = na
    float maximum = na
    if count > 0
        for i = 0 to count - 1
            float value = data.values.get(i)
            if not na(value)
                valid += 1
                minimum := na(minimum) ? value : math.min(minimum, value)
                maximum := na(maximum) ? value : math.max(maximum, value)
            if withCandles and not na(data.highs.get(i)) and not na(data.lows.get(i))
                minimum := na(minimum) ? data.lows.get(i) : math.min(minimum, data.lows.get(i))
                maximum := na(maximum) ? data.highs.get(i) : math.max(maximum, data.highs.get(i))
            if kind == 9 and not na(data.signals.get(i)) and not na(data.histograms.get(i))
                minimum := math.min(nz(minimum, 0), math.min(0, math.min(data.signals.get(i), data.histograms.get(i))))
                maximum := math.max(nz(maximum, 0), math.max(0, math.max(data.signals.get(i), data.histograms.get(i))))
    float lower = boundedOscillator(kind) ? 0 : kind == 17 ? -100 : nz(minimum, 0)
    float upper = boundedOscillator(kind) ? 100 : kind == 17 ? 0 : nz(maximum, 1)
    if upper == lower
        float padding = math.max(math.abs(lower) * 0.01, syminfo.mintick)
        lower -= padding
        upper += padding
    else if not boundedOscillator(kind) and kind != 17
        float padding = (upper - lower) * 0.08
        lower -= padding
        upper += padding
    float latest = count > 0 ? data.values.last() : na
    float direction = count > 0 ? data.directions.last() : na
    color activeInk = kind == 0 ? (direction < 0 ? bullColor : bearColor) : ink
    box.set_lefttop(panel.frame, x, top)
    box.set_rightbottom(panel.frame, right, bottom)
    // Linefill is below strokes; an opaque box would obscure the chart lines.
    box.set_bgcolor(panel.frame, na)
    line.set_xy1(panel.backdropTop, x, top)
    line.set_xy2(panel.backdropTop, right, top)
    line.set_xy1(panel.backdropBottom, x, bottom)
    line.set_xy2(panel.backdropBottom, right, bottom)
    linefill.set_color(panel.backdrop, background)
    box.set_border_color(panel.frame, color.new(activeInk, 35))
    string reading = na(latest) ? "Unavailable" : str.tostring(latest, kind == 15 ? format.volume : withCandles or kind == 2 ? format.mintick : "#.##")
    if kind == 0 and not na(latest)
        reading += direction < 0 ? " | BULL" : " | BEAR"
    if kind == 9 and count > 0
        reading := "M " + reading + " | S " + str.tostring(data.signals.last(), "#.##") + " | H " + str.tostring(data.histograms.last(), "#.##")
    if withCandles and count > 0
        reading += " | Price " + str.tostring(data.closes.last(), format.mintick)
    putText(panel.heading, x + int(panelWidth / 2), top - 3 * unit, name + " | " + tf, foreground)
    putText(panel.reading, x + int(panelWidth / 2), top - 7 * unit, reading, activeInk)
    string lastTime = count > 0 ? str.format_time(data.stamps.last(), "MM-dd HH:mm", "UTC") : "--"
    string status = str.tostring(valid) + "/" + str.tostring(sampleLimit) + (data.developing ? " LIVE | " : " CLOSED | ") + lastTime + " UTC"
    if hidden
        reading := "Chart timeframe | mini-chart hidden"
        putText(panel.reading, x + int(panelWidth / 2), top - 7 * unit, reading, muted)
    putText(panel.status, x + int(panelWidth / 2), bottom + 3 * unit, status, muted)
    // Fixed allocation of line objects. NA samples and time gaps leave blank segments.
    for i = 0 to sampleLimit - 2
        line segment = panel.strokes.get(i)
        bool show = not hidden and i < count - 1
        if show
            float first = data.values.get(i)
            float second = data.values.get(i + 1)
            bool gap = breakTimeGaps and data.stamps.get(i + 1) - data.stamps.get(i) > timeframe.in_seconds(tf) * 1500
            show := not na(first) and not na(second) and not gap
            // Do not join opposite Supertrend branches through price.
            if kind == 0
                show := show and data.directions.get(i) == data.directions.get(i + 1)
            if show
                int slot = sampleLimit - count + i
                int x1 = x + 2 + int(math.round(slot * (panelWidth - 4.0) / (sampleLimit - 1)))
                int x2 = x + 2 + int(math.round((slot + 1) * (panelWidth - 4.0) / (sampleLimit - 1)))
                line.set_xy1(segment, x1, mapY(first, lower, upper, graphBottom, graphHeight))
                line.set_xy2(segment, x2, mapY(second, lower, upper, graphBottom, graphHeight))
                line.set_color(segment, kind == 0 ? (data.directions.get(i + 1) < 0 ? bullColor : bearColor) : kind == 9 ? macdLineColor : ink)
                line.set_width(segment, strokeWidth)
        if not show
            line.set_xy1(segment, x, na)
            line.set_xy2(segment, x, na)
    if withCandles
        for i = 0 to sampleLimit - 1
            box body = panel.bodies.get(i)
            box wick = panel.wicks.get(i)
            bool drawCandle = not hidden and i < count
            if drawCandle
                drawCandle := not na(data.opens.get(i)) and not na(data.highs.get(i)) and not na(data.lows.get(i)) and not na(data.closes.get(i))
            if drawCandle
                int slot = sampleLimit - count + i
                int center = x + 2 + int(math.round(slot * (panelWidth - 4.0) / (sampleLimit - 1)))
                float o = mapY(data.opens.get(i), lower, upper, graphBottom, graphHeight)
                float c = mapY(data.closes.get(i), lower, upper, graphBottom, graphHeight)
                color candleInk = data.closes.get(i) >= data.opens.get(i) ? candleBull : candleBear
                box.set_lefttop(wick, center, mapY(data.highs.get(i), lower, upper, graphBottom, graphHeight))
                box.set_rightbottom(wick, center, mapY(data.lows.get(i), lower, upper, graphBottom, graphHeight))
                box.set_border_color(wick, candleInk)
                box.set_bgcolor(wick, candleInk)
                box.set_lefttop(body, center - 1, math.max(o, c))
                box.set_rightbottom(body, center + 1, math.min(o, c))
                box.set_border_color(body, candleInk)
                box.set_bgcolor(body, candleInk)
            else
                box.set_lefttop(body, x, na)
                box.set_rightbottom(body, x, na)
                box.set_lefttop(wick, x, na)
                box.set_rightbottom(wick, x, na)
    if kind == 9
        for i = 0 to sampleLimit - 2
            line signalSegment = panel.signalStrokes.get(i)
            bool showSignal = not hidden and i < count - 1
            if showSignal
                showSignal := not na(data.signals.get(i)) and not na(data.signals.get(i + 1))
                showSignal := showSignal and not (breakTimeGaps and data.stamps.get(i + 1) - data.stamps.get(i) > timeframe.in_seconds(tf) * 1500)
            if showSignal
                int slot = sampleLimit - count + i
                int x1 = x + 2 + int(math.round(slot * (panelWidth - 4.0) / (sampleLimit - 1)))
                int x2 = x + 2 + int(math.round((slot + 1) * (panelWidth - 4.0) / (sampleLimit - 1)))
                line.set_xy1(signalSegment, x1, mapY(data.signals.get(i), lower, upper, graphBottom, graphHeight))
                line.set_xy2(signalSegment, x2, mapY(data.signals.get(i + 1), lower, upper, graphBottom, graphHeight))
                line.set_color(signalSegment, macdSignalColor)
                line.set_width(signalSegment, strokeWidth)
            else
                line.set_xy1(signalSegment, x, na)
                line.set_xy2(signalSegment, x, na)
        for i = 0 to sampleLimit - 1
            box column = panel.bodies.get(i)
            bool showColumn = not hidden and i < count
            if showColumn
                showColumn := not na(data.histograms.get(i))
            if showColumn
                float hist = data.histograms.get(i)
                bool rising = data.directions.get(i) > 0
                color columnColor = hist >= 0 ? (rising ? histPosRise : histPosFall) : (rising ? histNegRise : histNegFall)
                int slot = sampleLimit - count + i
                int center = x + 2 + int(math.round(slot * (panelWidth - 4.0) / (sampleLimit - 1)))
                float baseline = mapY(0, lower, upper, graphBottom, graphHeight)
                float tip = mapY(hist, lower, upper, graphBottom, graphHeight)
                box.set_lefttop(column, center - 1, math.max(baseline, tip))
                box.set_rightbottom(column, center + 1, math.min(baseline, tip))
                box.set_bgcolor(column, color.new(columnColor, 20))
                box.set_border_color(column, na)
            else
                box.set_lefttop(column, x, na)
                box.set_rightbottom(column, x, na)
    if oscillatorGuides(kind) and not hidden
        float upperY = mapY(rsiUpper, lower, upper, graphBottom, graphHeight)
        float lowerY = mapY(rsiLower, lower, upper, graphBottom, graphHeight)
        line.set_xy1(panel.upperGuide, x + 2, upperY)
        line.set_xy2(panel.upperGuide, right - 2, upperY)
        line.set_xy1(panel.lowerGuide, x + 2, lowerY)
        line.set_xy2(panel.lowerGuide, right - 2, lowerY)
        line.set_color(panel.upperGuide, rsiLevelColor)
        line.set_color(panel.lowerGuide, rsiLevelColor)
        line.set_style(panel.upperGuide, line.style_dashed)
        line.set_style(panel.lowerGuide, line.style_dashed)
        putText(panel.upperLabel, right - 3, upperY + unit, str.tostring(rsiUpper), muted)
        putText(panel.lowerLabel, right - 3, lowerY + unit, str.tostring(rsiLower), muted)
 
    else
        line.set_xy1(panel.upperGuide, x, na)
        line.set_xy2(panel.upperGuide, x, na)
        line.set_xy1(panel.lowerGuide, x, na)
        line.set_xy2(panel.lowerGuide, x, na)
        label.set_xy(panel.upperLabel, x, na)
        label.set_xy(panel.lowerLabel, x, na)
 
    if kind == 9 and not hidden
        float zeroY = mapY(0, lower, upper, graphBottom, graphHeight)
        line.set_xy1(panel.upperGuide, x + 2, zeroY)
        line.set_xy2(panel.upperGuide, right - 2, zeroY)
        line.set_color(panel.upperGuide, muted)
        line.set_style(panel.upperGuide, line.style_dotted)
        putText(panel.upperLabel, right - 3, zeroY + unit, "0", muted)
 
if barstate.isfirst and rsiLower >= rsiUpper
    runtime.error("Oscillator lower level must be below the upper level.")
if barstate.isfirst and macdFast >= macdSlow
    runtime.error("MACD fast period must be less than slow period.")
if na(timeframe.in_seconds())
    runtime.error("Use a standard time-based chart.")
 
var Samples stData = newSamples()
var Samples rsiData = newSamples()
var Samples atrData = newSamples()
var Samples emaData = newSamples()
collect(stData, stTF, stKind, stLength, stFactor)
collect(rsiData, rsiTF, rsiKind, rsiLength, rsiFactor)
collect(atrData, atrTF, atrKind, atrLength, atrFactor)
collect(emaData, emaTF, emaKind, emaLength, emaFactor)
 
var Panel stPanel = newPanel(stKind)
var Panel rsiPanel = newPanel(rsiKind)
var Panel atrPanel = newPanel(atrKind)
var Panel emaPanel = newPanel(emaKind)
// Visible OHLC bounds supply price coordinates for the main-chart overlay.
// They are not the viewport's pixel bounds and do not alter indicator values.
var int visibleRight = 0
var float visibleHigh = na
var float visibleLow = na
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
    visibleHigh := na(visibleHigh) ? high : math.max(visibleHigh, high)
    visibleLow := na(visibleLow) ? low : math.min(visibleLow, low)
    visibleRight := bar_index
float fallbackATR = ta.atr(14)
if barstate.islast
    float ceiling = nz(visibleHigh, high)
    float floorPrice = nz(visibleLow, low)
    float span = math.max(ceiling - floorPrice, math.max(nz(fallbackATR, syminfo.mintick) * 10, syminfo.mintick * 100))
    float unit = span / 100.0
    int chosenEdge = (anchor == "Visible right edge" ? visibleRight : bar_index) + horizontalShift
    // Keep all bar-index drawings inside Pine's historical/future coordinate limits.
    int dashboardWidth = panelWidth * 2 + 4
    int futureGap = math.max(1, math.min(currentBarGap + horizontalShift, 500 - dashboardWidth))
    int edge = anchor == "Right of current bar" ? bar_index + futureGap + dashboardWidth : math.max(math.max(0, bar_index - 9000) + dashboardWidth, math.min(chosenEdge, bar_index + 100))
    int left = edge - panelWidth * 2 - 4
    float top = ceiling - 3 * unit + verticalShift * unit
    stPanel.render(stData, left, top, unit, stChoice, stTF, stKind, panelOneColor)
    rsiPanel.render(rsiData, left + panelWidth + 4, top, unit, rsiChoice, rsiTF, rsiKind, rsiColor)
    atrPanel.render(atrData, left, top - (panelHeight + 6) * unit, unit, atrChoice, atrTF, atrKind, atrColor)
    emaPanel.render(emaData, left + panelWidth + 4, top - (panelHeight + 6) * unit, unit, emaChoice, emaTF, emaKind, emaColor)

← 返回列表