Anon
Anon

Reputation: 21

How to get price at location of mouse pointer in Tradingview Pine Script?

I wrote a simple function that keeps track of my gains or losses on my short position. This is so I don't have to keep logging back into Kraken to check, or do the math in my head.

study("Current P/L", overlay=true)

numberOfBitcoinsSold = 49
sellPrice = 37901

plotchar(((sellPrice - close) * numberOfBitcoinsSold), "Bar Index", "", location = location.top) //my gains and losses

This works but I also want to know how much I might have at a given theoretical price. I want to mouse over a given price and have it calculate what the gains would be at that price. How can I retrieve the price at the y-coordinate of the user's mouse? The current system only works on already existing bars, not some specific point in the future.

Upvotes: 2

Views: 3360

Answers (2)

vgladkov
vgladkov

Reputation: 554

You can use the price input from Pine v4 or v5, which allows you to specify it interactively on the chart. But this will not be applied "on the fly", you will need to drag the price level from the specified default position, having previously selected the indicator on the chart, after which the level will be fixed until the next change (by dragging or in the input dialog).

Here is an example of such a script:

//@version=5
indicator("P/L", overlay=true)

numberOfBitcoinsSold = input.float(49, "Contracts count")
sellPrice = input.float(37901, "Entry short price")
useClosePriceToBuy = input.bool(false, "Use current close as exit price")
buyPrice = useClosePriceToBuy ? close : input.price(0, "Custom exit price")


plotchar(((sellPrice - buyPrice) * numberOfBitcoinsSold), "P&L", "", location = location.top)

Upvotes: 1

rumpypumpydumpy
rumpypumpydumpy

Reputation: 3833

You can't access anything regarding the mouse pointer location through pine unfortunately.

You could do either a table or plot lines and labels to precalculate using percentage intervals what your PnL would be at given theoretical prices.

Simplest would probably be to use in input variable to accept your desired price level and calculate your PnL from that.

qty = input(49, title = "Qty")
sellPrice = input(37901, title = "Sell Price")
PnLprice = input(20000, title = "PnL Price")

PnL = (sellPrice - PnLprice) * qty

var PnLline = line.new(x1 = bar_index - 1, y1 = PnLprice, x2 = bar_index, y2 = PnLprice, color = color.red, style = line.style_dashed, width = 2, extend = extend.left)
line.set_x1(PnLline, x = bar_index - 1)
line.set_x2(PnLline, x = bar_index)

var PnLlabel = label.new(x = bar_index, y = PnLprice, style = label.style_label_left, color = color.red, textcolor = color.white, text = "Short PnL : " + tostring(PnL), size = size.normal)
label.set_x(PnLlabel, x = bar_index)

Upvotes: 1

Related Questions