DCA Strategy For ThinkOrSwim

@samer800 is it possible to implement dollar cost strategy similar to https://in.tradingview.com/script/wE93nMBC-Simple-Dollar-Cost-Average/ in ToS platform? Appreciate if you or someone can convert the same.

Thanks
check the below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at
#// © RomainHaenni
#indicator("Dollar Cost Average", "DCA")
# Converted by Sam4Cok@Samer800    - 09/2023 request from usethinkscript.com memeber.
declare lower;
input startingAmount = 0.0;#, "Starting Investment")
input investmentAmount = 500.0;#, "Repeating Investment")
input frequency = 7;#, "Repeats every (in days)", inline="frequency")
input feeRatio = 0.02;#, "Broker Fee")
input startTime = 0100;
input startDate = 20230101;#(timestamp("Jan 01 2023"), "Starting Date")
input endDate = 20300101;#(timestamp("Jan 01 2033"), "Ending Date")
input ShowInfoLabel = yes;

def na = Double.NaN;
def last = isNaN(close);
def assets;# = 0.0
def feeAmount;# = 0.0
def entryPrice;# = 0.0
def invested;# = 0.0
def netProfit;# = 0.0
def totalFee;# = 0.0
def totalTrades;# = 0
def portfolioValue;# = 0.0
def newAssets;

def time = GetTime();
def current = GetAggregationPeriod();
def isdwm = current >= 86400000;
def isintraday = current < 86400000;
def investmentWindow = DaysFromDate(startDate) >=0 and DaysTillDate(endDate) >= 0;
def stDay =  DaysFromDate(startDate) ==0 and SecondsFromTime(startTime) == 0;
def stTime = if stDay then time else stTime[1];
def timeDiff_ = floor((time - stTime)/ 1000 / 60 / 60 / 24);
def timeDiff = timeDiff_;
def timeCond =(timeDiff % frequency) == 0;

if investmentWindow {
    if startingAmount > 0 and invested[1] == 0 {
        totalTrades = totalTrades[1] + 1;
        feeAmount = startingAmount * feeRatio;
        invested = startingAmount;
        newAssets = (startingAmount - feeAmount) / close;
        assets = newAssets;
        entryPrice = close;
        totalFee = feeAmount;
    } else
    if timeCond and (isdwm or (isintraday and SecondsFromTime(1200) == 0)) {
        totalTrades = totalTrades[1] + 1;
        feeAmount = investmentAmount * feeRatio;
        invested = invested[1] + investmentAmount;
        newAssets = (investmentAmount - feeAmount) / close;
        entryPrice = (entryPrice[1] * assets + (investmentAmount - feeAmount)) / (assets + newAssets);
        assets = assets[1] + newAssets;
        totalFee = totalFee[1] + feeAmount;
    } else {
        totalTrades = totalTrades[1];
        feeAmount = feeAmount[1];
        invested = invested[1];
        newAssets = newAssets[1];
        entryPrice = entryPrice[1];
        assets = assets[1];
        totalFee = totalFee[1];
    }
} else {
    totalTrades = totalTrades[1];
    feeAmount = feeAmount[1];
    invested = invested[1];
    newAssets = newAssets[1];
    entryPrice = entryPrice[1];
    assets = assets[1];
    totalFee = totalFee[1];
}

netProfit = if investmentWindow then close * assets - entryPrice * assets else netProfit[1];
portfolioValue = if investmentWindow then entryPrice * assets + netProfit else portfolioValue[1];

 
plot PortValue = if investmentWindow and !last then portfolioValue else na;#, "Portfolio Value"
plot InvstAmnt = if investmentWindow and !last then invested else na;#, "Invested Amount"
InvstAmnt.SEtLineWeight(2);
PortValue.SetDefaultColor(Color.DARK_ORANGE);
InvstAmnt.SetDefaultColor(Color.GREEN);

#-- Label
def info = ShowInfoLabel;
def invst = round(invested, 2);
def pnl = round(netProfit, 2);
def pnlPer = round(netProfit * 100 / invested, 2);
def fee = round(totalFee, 2);
def feePer = round(totalFee * 100 / invested, 3);
def folioValue = round(portfolioValue, 2);
def asses = round(assets, 8);
def entPrice = round(entryPrice, 2);
def valCol = if folioValue > invst then 1 else
             if folioValue < invst then -1 else 0;


AddLabel(info, "Invested($" + invst + ")", color.LIME);
AddLabel(info, "A/C Value($" + folioValue + ")", if valCol>0 then Color.GREEN else
                                               if valCol <0 then Color.RED else Color.GRAY);
AddLabel(info, "PnL(" + pnlPer + "%) $" + pnl, if pnl >0 then Color.GREEN else
                                               if pnl <0 then Color.RED else Color.GRAY);
AddLabel(info, "Fees(-" + feePer + "%) $-" + fee, color.PINK);

AddLabel(info, "Shares(" + asses + ")", color.WHITE);
AddLabel(info, "AvgCost/Share($" + entPrice + ")", color.WHITE);
AddLabel(info, "No of Trades(" + totalTrades + ")", color.WHITE);

#-- END of CODE
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
415 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top