FDL
FDL

Reputation: 115

How to get this variable to display last closing price for all bars?

I have the following pinescript code;

var float my_close = 0.
if barstate.islastconfirmedhistory
    my_close := close

plotchar(my_close, title="my_close", char="", location=location.top, color=#ffffff)

It will display the last-closing price when the mouse hovers at the last bar and display 0 when the mouse hovers at other bars in TradingView.

What I want is to display the last-closing price when the mouse hovers at any of the bars in TradingView. It is also fine if the closing price of the right-most visible on the chart is displayed.

I am using pinescript v5.

Upvotes: 0

Views: 2201

Answers (1)

elod008
elod008

Reputation: 1362

plotchar() cannot achieve your goal.

It "prints" on each bar as the execution model processes your script on the chart data. So it will show you the data on each hover that pine script had on that exact bar and you cannot update it backwards.
I have 2 suggestions that can achieve a similar result like what you want:

//@version=5
indicator("My script", "test", true)

var float my_close = 0
var closeLine = line.new(time, close, time, close, xloc.bar_time, style=line.style_dashed, color=color.purple, width=2) // you can style it the way you want: several options for color, line style and width

// option 1
if barstate.islastconfirmedhistory
    my_close := close // if you need it at all but you could just use the "close" value directly in here
    line.set_y1(closeLine, my_close)
    line.set_xy2(closeLine, time, my_close)

// option 2
var t = table.new(position.middle_right, 2, 1) // several options where to place your table and if it should have borders/background
if barstate.islastconfirmedhistory
    my_close := close // if you need it at all
    table.cell(t, 0, 0, "Last confirmed close")
    table.cell(t, 1, 0, str.tostring(my_close))

Sidenote:
You may rather want to use barstate.isconfirmedinstead of lastconfirmedhistory if you want your output to get updated on newly confirmed closes. If you use your indicator also real-time lastconformedhistory won't update. It depends on what you really want.

Upvotes: 4

Related Questions