Position Size Calculator for ThinkorSwim

I'm looking for a position sizing calculator for ThinkorSwim that can calculate how many shares I can buy and define my risk level with stop losses.

ryAiY4P.jpg

vkolSK4.jpg


I've purchased stuff like this before from other developers in the past and they stopped working after awhile. I'm burned out from paying for poorly supported scripts, not to say that the one from easycators is.
 

Attachments

  • ryAiY4P.jpg
    ryAiY4P.jpg
    30.4 KB · Views: 179
  • vkolSK4.jpg
    vkolSK4.jpg
    30.4 KB · Views: 190
Last edited:

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

I reverse engineered what I think the two labels show.

This is the output of that work.

X8Lk7qK.png


thinkScript Code

Code:
#
# PositionSizingCalculator
#
# Author: Kory Gill, @korygill
#
#

input RiskUnit = 100;
input AggregationPeriod = AggregationPeriod.FIFTEEN_MIN;

def highVal = high(period = AggregationPeriod);
def lowVal = low(period = AggregationPeriod);

AddLabel(
    yes,
    "High: " + highVal + " Low: " + lowVal,
    Color.Gray
    );

def diff = highVal-LowVal;

AddLabel(
    yes,
    AsDollars(RiskUnit) + " risk with " + AsDollars(diff) + " stop = " + Floor(Round(RiskUnit/diff)) + " shares",
    Color.Gray
    );

Link to the study

https://tos.mx/HwObLl

Thanks,
Kory Gill, @korygill
 

Attachments

  • X8Lk7qK.png
    X8Lk7qK.png
    39.9 KB · Views: 289
Last edited by a moderator:
I wrote something similar to what you're looking for that I use on a daily basis. One problem however, it has a minor bug where it sometimes will not display the entry size if there is no activity in the stock (low volume). I havent been able to figure that out yet. I'll post the script when I get back to my trading desk.
 
So here's the logic I wrote for a simple calculator. It shows your preset value and then displays the amount of shares you can get at the bid and ask price:

Code:
# Projos, 7/6/19; position value and size indicator


input showLabel = yes;
input entryPrice = 2589;

def bid = close(priceType = "BID");
def ask = close(priceType = "ASK");

DefineGlobalColor("Bubble", GetColor(1));


AddLabel(showLabel, "Preset Position Value = $" + entryPrice + "             Max Shares  =  [ Ask Price: " + Floor(entryPrice / ask) + " ]     [ Bid Price: " + Floor(entryPrice / bid) + " ]" , GlobalColor("Bubble"));
 
Has anyone tried position sizing as a variable in their backtesting? I am messing around with this code just simply using a static 5% of the portfolio per trade. The problem I am running into is I am unable to trade the growth or decline of the P/L in the backtest so say for example a stock like AMZN the trades execute with a position size up until the stock price is above $500 since it is static. Any ideas around this how this could be more dynamic?

Code:
input PortfolioSize = 10000;
input TradeSizePct = .05;

#Position Sizing

def pSize = portfolioSize;
def sizeP = portfolioSize * TradeSizePct;
def tSize = sizep/open[-1];

AddOrder(condition = buySignal, type = OrderType.BUY_TO_OPEN, price = open[-1],tSize, name = "Buy");

I thought about it overnight and realized I just need a loop which will add or subtract my profit from the "Portfolio" it turns out thinkScript utilizes a function called Fold which does exactly this. Therefore I just need to create a function that will iterate every time a trade is made...I will be playing around with this idea for the next few days. Just applying some simple static 5% sizing to some of my older backtests have greatly improved returns the goal is to write it as a code snippet so it can be injected into any strategy on the platform.
 
This thread is really emotionally difficult for me to write, because prior to understanding the importance of position sizing, I took a string of losses at the beginning of my stock trading career that almost completely wiped me out. I'm hoping that my mistakes will help those of you reading this.

Contrary to popular belief, a strategy is NOT the key to a consistently profitable trading career. Risk management is the key. I learned this lesson the hard way.

Like many traders, I had beginners luck. My first week trading, I took two trades in two days and earned $3,781.53.

1st Trade: ACRS 1,481 shares x $.33/share = $488.73 Profit
2nd Trade: VYGR 1,176 shares x $2.80/share = $3,292.80 Profit

I thought I was a genius, so then I started trading with bigger and bigger size and looser stop losses. Here were my results:

7th Trade: ICPT 387 shares x -$7.13/share = - $2,759.31 Loss
8th Trade: GDDY 581 shares x -$1.95/share = - $1,132.95 Loss
9th Trade: PHAS 2,400 shares x -$2.30/share = - $5,510.40 Loss

$9,402.66 in losses. I was devastated. I almost quit.

Thinkorswim-Position-Sizer.png


After several months of testing different risk management methods, I ultimately realized that the most appropriate way to manage risk is to establish a risk per trade. Risk per trade is the total amount of money you are willing to risk in a given trade. This is vitally important, because once you fund your trading account; determine your risk tolerance and establish your risk per trade, you are better equipped to take trades knowing that the probabilities are on your side, that will help prevent you from blowing up your account.

Example:

Let's say you're a day trader and you have an account balance of $1,000. Since you're under the $25,000 PDT (Pattern Day Trade) limit, you can only take 3 round trip trades/week. This means that your strategy has to have a statistical edge (you consistently win more than you lose); your winners must be twice or more as large as your losers on average and most importantly, you have to cap your risk per trade, otherwise you run the risk of blowing up your account - like I almost did :(

In this example, if it were me and I was a newbie trader, I wouldn't risk more than $10/trade. $10/trade allows you to lose without getting overly emotional and it also allows you to take 100 losses before your account dwindles to zero. 100 trades is generally the acceptable minimum number of trades that is required to determine if a trading strategy has a statistical edge. If you find that to be the case after taking 100 trades or backtesting 100 trades, you can increase your risk per share comfortably, because you would have confidence that your strategy wins more than it loses.

Now you're probably thinking... If my risk per trade is $10 and I can only take 3 trades/week because of the PDT Rule, my account will never grow. While it is true that your account will grow slowly, you have a few options to accelerate growth:

  1. Swing trade instead of day trade. This allows you to take more trades, with the caveat being that you have to hold your positions overnight for at least one 24 hour cycle. This goes without saying, but be careful holding small cap stocks overnight. Small cap companies are very volatile and may dramatically decrease in value overnight and in pre-market trading.

  2. Backtest (OnDemand or manual) or Paper trade your strategy instead of trading it with real money. If you already know that your strategy has a statistical edge from backtesting or Paper Trading, then there is no reason to trade with such a low risk per trade, as your strategy has already proven itself to be profitable - allowing you to responsibly take on a higher risk per trade.

Now that you understand the importance of risk management, next, you need to understand how to calculate risk per trade in real-time. The formula I've provided below assumes that you are entering a trade when a new candle forms and price makes a new high above the previous candle's high. Your Stop Loss would be placed at the low of the previous candle.

Formula:

High = Insert the "High" price of the current candle
Low = Insert the "Low" price of the current candle
Qty = Risk Per Trade / Stop
Limit = Stop x Your Profit Target Multiple
Stop = High - Low

Provided below is an example trade for Facebook. The Entry Price, Qty, Limit and Stop that was entered in this order would yield a max loss of $29.97 if your stop was triggered, and a profit of $59.94 if your Limit was triggered.

The reason why this type of risk management method is so effective is because it allows you to cap your losses and pre-plan your profits. In my example, I've chosen a profit target multiple of 2, which gives me a reward to risk ratio of 2 : 1. If your strategy has a statistical edge that allows your winners to be twice the amount of your losers on average, this allows you to loss half of your trades and still be a profitable trader. It also allows you to loss 66% of your trades and still break even.

Thinkorswim-Position-Sizer-2.png


Problem:

So here's the BIG problem... If you're a day trader, momentum trader or trend trader that is trading on a 1 minute timeframe, you don't have time to manually calculate risk per trade, as this leads to panic, high blood pressure, error, hesitation and missed moves. By the time you manually calculate, the trade has likely already moved without you. An overwhelming majority of traders are faced with this issue, so they inevitably resort to one of the following:
  1. No risk management at all. No stop loss. No nothing - which leads to catastrophic losses
  2. Mental stops - which leads to an inability to pull the trigger... Which leads to catastrophic losses
  3. Uneven stops. They blindly put stops at the low of the previous candle without calculating the ratio of shares, which leads to larger losses, smaller profits and inconsistency in their P&L
To be blunt... If you're doing any of the above, you are not trading. You are gambling. You are hoping for an outcome that may or may not materialize, while leaving yourself vulnerable to virtually unlimited losses.

Solution:

It took me over 6 months before I finally realized that I needed to calculate risk per trade before entering into a position, and even when I realized this and accepted it, I was making calculations manually which led to a ton of errors and ultimately a ton of losses.

A month ago I finally broke down and purchased a Position Sizer. It does all of the work for you, and it even provides you with several options for calculating risk per trade, qty, entry price, stop, profit target, etc.

Checkout the screenshot below. It is the same screenshot as above with the exception that it has 4 boxes on the chart that provide all of the details I need to execute the trade. These boxes update in real-time based on the high and low price changes of the current candle. This makes it so easy for me to execute a trade, because now, all I have to do is type the values for each box into the Active Trader Ladder and then select the price I want to purchase on the Active Trader ladder and I'm in the trade. What used to take me two minutes, now takes me less than 10 seconds!

Without this tool, I wouldn't be able to effectively trade 1 minute charts, which is an absolute requirement for my trading strategy.

Thinkorswim-Position-Sizer-3.png


It's important to note that I paid the developer an additional $30 to make a few customizations for me. The customizations I added are as follows:
  1. Added Heiken Ashi candle calculations
  2. Adjusted the names of the label fields to: Qty, Limit, Stop, Entry
  3. Changed the order of the labels to: Qty, Limit, Stop, Entry
Inputs and Options:

Provided below is my current setup. I've only adjusted the fields with the red dot next to them. I left the remaining fields set to their defaults. As you can see, there are numerous options you can choose from to customize this tool to your liking.

I think the most beneficial setting you'll want to play with is the "Stop Type." You don't have to use the low of the current candle like I do. You can choose from the following Stop Types:
  1. ATR
  2. Kase
  3. $ Offset
  4. % Offset
  5. Fixed Price
If you adjust the Stop Type, you can select "Yes" under the "Plot Stops" Dropdown box. This is helpful because it shows you exactly where the Stop price is for every previous and current candle with a teal blue line. This allows you to backtest different Stops OnDemand to figure out what stop type is most optimal for your trading style, as well as the specific stock you're trading, which may have more or less volatility than others - which should be considered when determining your Stop Type. Provided below is a screenshot of an ATR Stop on a 1 minute chart.

I should also note that "Num Ticks Padding" is the buffer you want to add to your Limit and Stop order. As an example, if I entered .05 in this field, My Limit and Stop would both be set to $.05 above (Limit) and $.05 below (Stop) the current candles High and Low.

"Target Risk Multiple" is the multiple above your Stop you want your profit target to be. In my case, I've entered 6, which means I want my default Profit Target (Limit) to be 6 times higher than my Stop. It goes without saying, but all of my trades aren't that profitable (6 : 1 Reward to Risk Ratio). However, I like to leave myself a big buffer just in case a big spike in price occurs - allowing me to make a bigger move.

"Fixed Dollar Amount" is my risk per trade. In this example, I have set a value of $30. This means that my share size and stop offset will automatically be calculated to ensure that I lose a maximum of $30 if my stop loss is triggered. This goes without saying, but if price plummets quickly without stopping on my stop price, my loss could be more than $30. This is rare though. When it does happen, it's never more than 5%. If this happens, it's not the fault of the tool or the broker. It's all due to price action, supply and demand dynamics.

"Show Labels" are the labels on my chart: Qty, Limit, Stop, Entry

Thinkorswim-Position-Sizer-4.png


ATR Stop Loss Example:

The teal blue line on the chart below is a 1.5 ATR Stop on a 1M chart. An ATR Stop is extremely helpful, because it allows you to avoid false stop outs from stop hunters as well as overall market volatility, as the 1.5 ATR takes into account price volatility based on the average true range of price action.

In the example below, there are several good places to enter long positions on this stock. However, if you used the low of the current candle for your Stop, there are many places where you would have prematurely gotten stopped out because price briefly dips below your Stop price, but then shoots up higher within 5 - 10 candles later.

An ATR stop allows you to be a little more sloppy with Stops and get away with it. It also increases the length of your Stop though. As an example, if the ATR Stop is twice the length of a low of the current candle stop, price has to go up twice as much to make the same profit. This is why I don't use ATR Stops and instead use the low of the current candle stop. It's riskier. However, my analysis for my strategy indicates that in the long-term, my profits will be larger using a low of the current candle stop, as opposed to an ATR stop. To each their own.

Thinkorswim-Position-Sizer-5.png


I've talked a lot about day trading in this post. I want to emphasize that this isn't just useful for day trading. It's extremely useful for Swing Trading as well, and all of the same pointers I've mentioned above still apply.

I hope this was helpful, and I hope you consider purchasing this tool. Don't be a cheapskate like me by trying to calculate position size manually or not at all. I was so cheap that I even made a post here back in September, trying to see if there was a free version of a tool similar to this one. No such tool exists. I lost a lot of money trying to do what this tool does automatically. This was the best investment I've made in my trading career.

As of the writing of this post, the developer is selling the script for $109.99.

Feel free to ask me any questions and I'll answer them as best as I can. You can also email the developer. He's pretty responsive.
 
@GetRichOrDieTrying props to you for having this made. Also, your journey teaches everyone a valuable lesson or two. Thank you for Sharing.
btw, I have such a tool but is excel based and based on 2 different ways of using "R" multiples.
Unfortunately it is proprietary to Theotrade. If I get enough curiosity, I'll ask permission to share it.
Input requested, please.
 
This morning I executed a trade with a $.04 stop. Unfortunately, the trade turned against me and I was stopped out. While I was in the position, the stock wasn't volatile at all. No surges and no flash crashes. Despite that, when I was stopped out, my P/L showed a loss that was twice what it should have been based on what I entered into the Active Trader order entry window.

When I went back to review my order, it showed that a $.08 stop loss was submitted. For a moment I thought that I may have made a typo. I knew this was highly unlikely though, because I use a position sizer that automatically calculates my share size, limit offset, stop offset and entry price based on my max risk per trade. All I have to do is type what the tool calculates into the Active Trader Ladder. But even still, it's possible that I could make a typo.

After reviewing the trade execution details under the Monitor tab, I went back to my chart to review the Active Trader Ladder. And what do you know... My stop offset was indeed set to $.04. Since I hadn't taken any additional trades after this loss, it would be impossible for the stop offset to be set to $.04 if that wasn't what I submitted in my order.

After reviewing all of this I got on chat with TD Ameritrade to explain what happened, and of course... The said that there is nothing they can do to credit my account since there's no way for them to verify that an error was made on their behalf.

I'm really concerned about trading with Thinkorswim now, and I am only going to continue trading with them while video recording my screen during all trading sessions. Had I had that proof, I could have gotten them to credit my account for the $.04 difference (slippage) in the Stop loss they executed vs. what I submitted multiplied by the number of shares I purchased.

Thankfully, I was trading with a small risk/trade, so even though my loss was doubled, I didn't blow up my account or have a major setback.

Please, please, please protect yourself. There are several free screen recording programs you can use. I'm using Debut by NCH. They have a 30 day free trial, and then after 30 days it's still free, but it has a watermark on it, which doesn't really matter, since I won't be posting these videos publicly anywhere.
 
Last edited by a moderator:
@GetRichOrDieTrying when you trade pennies, you have a wider bid ask spread to contend with. What was the width of bid/ask? I've been stopped out like you have before. Would a Stop Limit have helped you out in this case? I don't know, thus I ask.
 
Can anyone help me with this? I have a Sizing Calculator that I picked up (maybe from this site? I don't remember). What I would like is for it to calculate

(19*ATR)/20=N
then N*2=X
then have it divide X by Y( a "user-specified" dollar amount, this is the amount your willing to risk per trade) giving you Z (the amount shares to buy).

ie: say the ATR on a 15min is .062 then (19*.062)/20=N (.0589) then N ( .0589)*2=X (.1178)
then say your daily stop loss is Y($250) so (Y)250/(X).1178=(Z)2122 shares, Meaning if you buy 2122 shares and set your stop (rounded down to) .11 cents below your entry you risk $233

So you need to be able to enter your risk dollar amount, and the indicator needs to show the value of X (2xATR) and Z (Shares)

This is the basic calculator i currently use:

Code:
input amount = 5000;
def Data = Floor(amount/close);
def showDiv = yes;

AddLabel(showDiv, Data + " shares", Color.ORANGE);
 
@bsizzle101 It's all math, but based on your defined mathematical relationships, here is a simple study. BTW the ATR in your example pf .062 looks kind of low. Feel free to modify this code as you like

Code:
input length = 14;
input risk = 2000;#Hint: Amount you're willing to risk

def ATR = Average(TrueRange(high, close, low), length);
def n = (19*ATR)/20;
def x = 2 * n;
def numberShares = x/risk;

AddLabel(1, "Number of shares to buy = " + numberShares, Color.Yellow);
 
This is fantastic - Thank you. Makes trading so much easier. I copied the format of your code to create what price would be 2% stop and 4% gain (percentages can be edited). Here's the code for those if anyone is interested (saves me a whopping 30 seconds on each trade! haha):

Stop Loss Code:

Code:
input amount = 2;
def Data = close-(amount/100)*close;
def showDiv = yes;

AddLabel(showDiv, Data + " stop loss", Color.RED);

Sell Limit Code:
input amount = 4;
def Data = close+(amount/100)*close;
def showDiv = yes;

AddLabel(showDiv, Data + " sell limit", Color.GREEN);
 
Thank you for sharing findings and your ideas. How does this tool work with Futures as we don’t trade in 100 qty . Does this tool has option for futures in tick range for stop lose? did you trade options with the sizing tool ?
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
424 Online
Create Post

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