Chart gain/loss
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © xpersiandroid

//@version=5
indicator("Chart gain/loss", "", true)

// Save the `open` of the leftmost visible bar.
var float chartOpen = na
if time == chart.left_visible_bar_time
    chartOpen := open
else if time == chart.right_visible_bar_time
    // Run the following code on the chart's rightmost visible bar.
    color arrowColor = close > chartOpen ? color.lime : color.fuchsia
    // Draw arrow once, then modify it.
    var line arrow = line.new(na, na, na, na, xloc.bar_time, extend.none, na, line.style_arrow_right, 3)
    line.set_xy1(arrow, chart.left_visible_bar_time, chartOpen)
    line.set_xy2(arrow, chart.right_visible_bar_time, close)
    line.set_color(arrow, arrowColor)
    // Draw percentage label once, then modify it.
    var label percentage = label.new(na, na, na, xloc.bar_time, yloc.price, #00000000, label.style_label_down, size = size.huge)
    int midTime = int(math.avg(chart.left_visible_bar_time, chart.right_visible_bar_time))
    label.set_xy(percentage, midTime, math.avg(chartOpen, close))
    label.set_text(percentage, str.tostring((close - chartOpen) / chartOpen * 100, format.percent))
    label.set_textcolor(percentage, arrowColor)