santanderboogieman
santanderboogieman

Reputation: 1

Is there a way to display indicator value of last closed bar in TradingView PineScript?

I'm trying to display (using plotchar() and the Data Window) the latest closed value of a Moving Average, or in other words the value of the Moving Average of the last closed bar.

This is my current code, but it doesn't seem to work at all.

//@version=5
indicator(title="Moving Average", overlay=true, timeframe="", timeframe_gaps=true)
len = input.int(9, minval=1, title="Length")
src = input(close, title="Source")

previousMA = input(0, title="PreviousMA")

offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.sma(src, len)
plot(out, color=color.blue, title="MA", offset=offset)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")

smoothingLine = ma(out, smoothingLength, typeMA)

//------------------------------------------

if (barstate.islast)
    if (barstate.isconfirmed)
        previousMA = pMA
else
    previousMA := nz(previousMA)

plotchar(previousMA, 'previousMA', location = location.top)

//------------------------------------------

plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)

The logic is that before plotting the real MA line, if the script is currently calculating at the last real-time bar in the chart, and if this is the last data update happening for this bar, the script will save the value and plot it with plotchar().

The value here seems to always stay at 0 and never updating. What's wrong? Is there other ways to implement this?

Upvotes: 0

Views: 620

Answers (1)

Dave
Dave

Reputation: 865

You could also use the https://www.tradingview.com/pine-script-reference/v5/#var_barstate{dot}islastconfirmedhistory function

var float customMA = 0.
if barstate.islastconfirmedhistory
    customMA := smoothingLine

Upvotes: 0

Related Questions