OPEN-SOURCE SCRIPT

DCA Calculator v10

360
1. User Inputs (input.*)

This section creates the settings menu you see when you click the gear icon in TradingView.

Timeframe Settings: Determines when the script is active. It can automatically detect the first available data point (i_autoStart) or wait for a specific year (i_startYear). It also features a stopping mechanism (i_autoStop / i_stopYear) so you can simulate an investment period that ended in the past while tracking its value up to today.

EMA Filter Settings: This is the trend-following toggle (i_useEMA). If activated, it calculates an Exponential Moving Average (ta.ema).

Interest Settings: Allows you to define an annual percentage yield (i_interestRate) for the cash waiting on the sidelines.

2. Variables (var)

In Pine Script, using var means the variable is initialized only once on the very first bar and then remembers its value from bar to bar.

totalInvested: The total money transferred from your "bank" into the strategy.

totalShares: The fractional amount of the asset you actually own.

savedCash: The uninvested money sitting on the sidelines when the price is below the EMA.

totalInterestEarned: A tracker just to see how much of your final value came purely from interest.

3. The Core Logic: Time and Interest

Before making any trades, the script checks two things on every single bar (day):

Is it time to invest? isValidTimeForInvest checks if the current date falls between your chosen start and stop years.

Do we get interest? If you have savedCash > 0, it calculates exactly how many milliseconds have passed since the last bar, converts that to days, applies the daily interest rate, and adds the free money to your cash pile.

4. The Investment Logic

If the current date is within your active timeframe, the script looks for two specific events to deploy capital:

Event A: A New Month begins (isNewMonth).

It adds your i_monthlyInvestment to your totalInvested pool.

Check the EMA: If the EMA filter is ON and the current price is below the EMA line, it refuses to buy. Instead, it adds the money to savedCash.

Otherwise: It takes the monthly money PLUS any savedCash you've accumulated, divides it by the current closing price to calculate how many shares you get, and sets savedCash back to 0. It also draws a green label.

Event B: The Crossover (crossesOverEma).

If the price shoots up and crosses the EMA line from below to above, a new uptrend is signaled.

If you have a mountain of savedCash waiting, the script instantly buys shares with all of it on that exact day (drawing a blue label) instead of waiting for the 1st of the next month.

5. The Drawdown Logic

This block runs on every bar to find out how bad the psychological pain of the strategy was.

It calculates your currentPortfolioValue (the value of your shares + your uninvested cash).

It updates peakValue if your portfolio hits a new all-time high.

If the portfolio drops below the peakValue, it calculates the percentage drop. If this drop is worse than the previous maxDD (Maximum Drawdown), it records the new worst percentage and the exact date (maxDD_time).

6. The Results Table (table.*)

This part only executes on the very last bar of the chart (if barstate.islast).

It calculates your final Return on Investment (roi) and absolute net profit (profitAbs).

It dynamically builds the header text using syminfo.ticker (so it knows if you are looking at QQQ or GBTC) and your actual start/stop dates.

Finally, it draws the dark, semi-transparent box on the middle-right of your screen and populates all the rows with the final numbers, using green for profits and red for drawdowns to make it easy to read.

Exención de responsabilidad

La información y las publicaciones no constituyen, ni deben considerarse como, asesoramiento o recomendaciones financieras, de inversión, de trading u otro tipo, proporcionadas o respaldadas por TradingView. Obtenga más información en Condiciones de uso.