ThinkScript Averaging-In Strategy


New member
Can someone please advise or provide an example of how to average-in for back testing a strategy? For example, if a stock remains oversold for three days in a row, I am trying to find a way for the strategy to buy more shares the two additional days to get a lower cost basis and then my sell condition sells the accrued long quantity. I would include an image for reference, but it doesn't like the URLs when I try to insert an image from the tool bar. Thanks in advance for any input.
@sffc Welcome to the usethinkscript forums...

Your request is somewhat subjective and potentially beyond the limitations of Thinkorswims somewhat inadequate Strategy backtesting using AddOrder()... In all honesty, you will never get results as good as manually calculating your backtest ideas... While you might be able to code a Strategy in this fashion, with a lot of time, effort, and frustration, I highly doubt the results would be what you anticipate... With proper settings you can add to your position in Strategies but any Sell order liquidates the entire position regardless of your held quantity... The backtesting capabilities simply aren't designed for complex logic... They are, instead, merely meant to prove whether very basic logic is somewhat sound... Buys and Sells will never happen exactly when you want them to which further skews results... I share all of this after many many frustrating attempts to bend the limitations to my will...

All that said, while I wish I had a rosier outlook to share, I'd rather give the advice you need to hear rather than what you might want to hear... You're more than welcome to prove myself and others wrong but I find the prospect doubtful...

Good luck and, again, welcome...

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

Thanks, @rad14733 . Hey, that's good advice either way. I don't want to go down that rabbit hole if it's going to take that much heart ache and grief!

Is there potentially a rosier outlook that you can think of confirming that liquidating the entire position is what I want to accomplish?

"With proper settings you can add to your position in Strategies but any Sell order liquidates the entire position regardless of your held quantity"

I'm using Connors RSI in this particular instance with 60/40. When I average-in over 'x' number of days, I have the full position sold if overBought > 60 and close > entryPrice(); (in this case it would be my three days of average-in cost basis) and then I re-invest those funds into a different overSold equity.

So it functions the way I need to, but I was hoping to see that in the back testing reports if possible. If there's not a good way to do this, that's fine too. I'll take your experiences at face value and just stick with the back testing report's limitations : )
Last edited:
@sffc Do you have a working Strategy at this point and, if so, what do the reports show for success rate...??? Like I stated, members have noted that any Sell order liquidates an entire position, which sounds like what you want anyway... There just isn't any way to scale out of Strategy trades... While such a feature might be nice, considering how AddOrder() is for backtesting only, I'm sure they platform coding staff have more important things to do than refine AddOrder()...

Also, is this concept something you intend to trade manually or are you considering adapting it to Conditional Trade Orders which can also suffer from logic complexities...???
@rad14733 - Correct, looking for a method to average-in for a strategy over multiple oversold days, and then liquidate (which to your point that's what it indeed does today) the full position when the equity goes back to overbought to get the final trade results for historical comparison across other equities. I am not seeing or finding a good way to implement averaging-in over two or more consecutive trades using ThinkScript in a strategy.

It depends on the stock, its volatility, and the oversold/overbought values specified. I also wrote a stop loss condition for my use with the strategy, so the risk tolerance is also a variable that can effect its results +/-. Just something to play with until you find something that works for your trading style, I suppose.

I was using this to sell via conditional orders in ThinkorSwim, so it works fine for that as long as it doesn't matter to one that it can execute the sell any time during the day when it spikes above the specified overbought value and then ends the day below the overbought value. Here is the strategy I'm referring to if you wanted to back test the results for yourself -

#Connors RSI
input size = 1000;
input riskTolerance = 0.1;

#risk management
def tradeSize = (size / close);
def costBasis = tradeSize * EntryPrice();
def difference = costBasis * riskTolerance;
def maxLoss = costBasis - difference;
def stopLoss = (tradeSize * close) < maxLoss;

input rsiLength = 3;
input overBought = 70;
input overSold = 30;
input price = close;
input averageType = AverageType.WILDERS;

def uptrend = close > MovingAverage(AverageType.SIMPLE, close, 200);

# ConnorsRSI Indicator
input Price_RSI_Period = 3;
input Streak_RSI_Period = 2;
input Rank_Lookback = 100;

# Component 1: the RSI of closing price
def priceRSI = reference RSI("price" = close, "length" = Price_RSI_Period, averageType = averageType);

# Component 2: the RSI of the streak
def upDay = if close > close[1] then 1 else 0;
def downDay = if close < close[1] then -1 else 0;
def upStreak = if upDay != 0 then upStreak[1] + upDay else 0;
def downStreak = if downDay != 0 then downStreak[1] + downDay else 0;
def streak = upStreak + downStreak;
def streakRSI = reference RSI("price" = streak, "length" = Streak_RSI_Period);

# Component 3: The percent rank of the current return
def ROC1 = close / close[1] - 1;
def rank = fold i = 1 to Rank_Lookback + 1 with r = 0 do
r + (GetValue(ROC1, i, Rank_Lookback) < ROC1) ;
def pctRank = (rank / Rank_Lookback) * 100 ;

# The final ConnorsRSI calculation, combining the three components
def ConnorsRSI = (priceRSI + streakRSI + pctRank) / 3;

#def buy = uptrend and connorsRsi < overSold;
def buy = connorsRsi < overSold;
def sell = close > EntryPrice() and connorsRsi > overBought;

AddOrder(OrderType.BUY_AUTO, buy[-1], close[-1], tradeSize = tradeSize, name = "oversold",;

AddOrder(OrderType.SELL_TO_CLOSE, stopLoss or sell[-1], close[-1], tickcolor = color.white, arrowcolor = color.white, name = "overbought");
Last edited:
I am not seeing or finding a good way to implement averaging-in over two or more consecutive trades using ThinkScript in a strategy.

When you edit studies, look in the lower left, and find "Global Strategy Settings, then, you can choose the number of entry orders that trigger.
This should meet the requirement. (It's been a while since posted, but this might help the next person with the same query.)



Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
370 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.