Reputation: 4917
I would like to get the year-to-date gain of a Trading View chart using pine-script. The gain is to be expressed in percentage.
I am using pine-script v5.
Upvotes: 0
Views: 557
Reputation: 4917
First, find the number of bars that have passed year-to-date. From there, calculate the year-to-date gain.
get_yeartodate_gain_percentage() =>
int num_bars_ytd = 0 //number of bars passed year to date
num_bars_ytd := ta.barssince(ta.change(time("12M")))
float ytd_gain_pct = 0
ytd_gain_pct := (close[0] - close[num_bars_ytd+1])/close[num_bars_ytd+1]*100
ytd_gain_pct
Upvotes: 0
Reputation: 2161
Easiest way I can think of, is getting the number of bars past since the beginning of the year (the first bar the year changed), and than use the historical reference of strategy.equity
in order to get the equity for the beginning of the year.
From there it's just comparing the current equity and the beginning of the year equity and use simple math to calculate as percentage:
barsSinceBeginingOfYear = ta.barssince(ta.change(time("12M")))
equityBeginingOfYear = strategy.equity[barsSinceBeginingOfYear]
profitTTD = ((strategy.equity / equityBeginingOfYear) - 1) * 100
Upvotes: 2