How to draw trade data labels in Pine

This lesson answers a question from a student who wants to draw labels in a strategy script showing a closed trade's opening price, closing price, opening time, closing time and closed profit/loss.

Check out my other free lessons!

Source Code

// Copy & paste this code to the end of any strategy script

enter_price = strategy.closedtrades.entry_price(strategy.closedtrades - 1)
exit_price = strategy.closedtrades.exit_price(strategy.closedtrades - 1)

MS_IN_1H = 1000 * 60 * 60 // Ms in Hour

var label myLabelBuy = na

if strategy.closedtrades != strategy.closedtrades[1]
    myLabelBuy := label.new(
     bar_index,
     y=low,
     text="OP:" + str.tostring(enter_price)
     + "\nCP:" + str.tostring(exit_price)
     + "\nOpTime:" + str.format("{0,date,yyyy.MM.dd HH:mm}",(strategy.closedtrades.entry_time(strategy.closedtrades - 1)+MS_IN_1H*2))
     + "\nClTime:" + str.format("{0,date,yyyy.MM.dd HH:mm}",(strategy.closedtrades.exit_time(strategy.closedtrades - 1)+MS_IN_1H*2))
     + "\nProfit:" + str.tostring(strategy.closedtrades.profit(strategy.closedtrades - 1)),
     yloc= yloc.abovebar,
     color=color.yellow,
     style=label.style_label_lower_left,
     size=size.normal,
     textalign = text.align_right,
     tooltip="Size:" + str.tostring(strategy.closedtrades.size(strategy.closedtrades - 1))
     )
    label.delete(myLabelBuy[1])