Position Size Calculator for ThinkorSwim

@Kristen0419 Not totally sure this is what you are asking. I trade in $5000 lots so to calculate the #of shares to buy is:
Ruby:
input showshares = yes ;
input TotalDollars = 5000 ;
def tradesize = TotalDollars / close;
AddLabel(showshares, "# of shrs: " +tradesize, color.blue);
If you search this forum for position size or trade size there are many other examples
HTH
Exactly what I was looking for! Thank you so much!
 

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

This is a position sizer that adjusts your size based on your risk. It requires a hard-coded stop loss to function. I have the stop set to the low of the current candle on a daily timeframe, but this code can be used as a template and coded to use a stop of your own choice if you so prefer. I use this in its current form on the daily chart. Understand what this does and how it adjusts your position size before using - what works for me may not work for you. Also, verify that it is working correctly before using.
Code:
# Position Sizing
# Pensar
# Released 05.24.2021 - V.1.0
# Not responsible for any losses incurred
# NOTE: From Thinkorswim instructions: The "use account percentage" will return N/A if chart property Show Extended-Hours Trading session is de-activated. To make sure this property is activated, navigate to Style -> Settings and then choose the tab that corresponds to the type of security you are currently analyzing: Equities, Options, or Futures. The Show Extended-Hours Trading session checkbox is located in the Axis area in the lower half of each of these tabs.

input position_risk_type = {default "use dollar value", "use account percentage"};
input risk_account_percent_per_trade = 0.5;
input risk_dollars_per_trade = 1000;

def ac = GetNetLiq();
def rd;

switch (position_risk_type)
{
case "use account percentage":
    rd = risk_account_percent_per_trade / 100 * ac;
case "use dollar value":
    rd = risk_dollars_per_trade;
}

input low_stop = AggregationPeriod.DAY;
def l = low(period = low_stop);

input scale_in = yes;
input times_to_scale_in = 3;
def buyRisk = if close > l then (close - l) else double.nan;
def buySize = if !scale_in then (rd / buyRisk) else (rd / buyRisk) / times_to_scale_in;
AddLabel(1, " L " + Round(buySize, 0) + (if scale_in then " - " + times_to_scale_in + " | " else " | ") +
         Round(close * (rd / buyRisk), 2) + " ", Color.light_gray);

# End code
 
Last edited:
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
The risk is too tight like .19 cent or 20 cent but if you are trading large cap the spread is crazy volatile and wide. Could you please make the stop lost [risk] under the previous candle and 15 cent blow rather than the current candle dancing and if we go .19 cent down we are down $500. It would be better to let the chart work out by giving stop lost under previous candle rather then the present candle .19 or 10 cent. That would be real risk management calculator... Thank you
 
Looking for a simple position size calculator indicator that could do something like this?


POSITION SIZER:

INPUT: “Actual Balance”
RISK Percent: “2% per trade”
SHARES TO BUY: “X” (Show; yes)
 
Looking for a simple position size calculator indicator that could do something like this?


POSITION SIZER:

INPUT: “Actual Balance”
RISK Percent: “2% per trade”
SHARES TO BUY: “X” (Show; yes)
Do you want it to calculate shares just based on max shares for 2% of account? Because if it's your risk amount, do you expect the stock to go to 0? or are you going to base it on a stop
 
Ruby:
# POSITION SIZER:
# @Woodman78 6/21

input ShowLabels    = yes ;
input ActualBalance = 500 ;
input RiskPercent   = .02 ;
def   SHAREStoBUY   = ActualBalance*RiskPercent;
DefineGlobalColor("Label", CreateColor(50, 200, 255)) ;
AddLabel(ShowLabels, "Shares to buy: " +SHAREStoBUY, GlobalColor("Label"));
nTHbTOz.png
 
Do you want it to calculate shares just based on max shares for 2% of account? Because if it's your risk amount, do you expect the stock to go to 0? or are you going to base it on a stop
I see what your saying, i meant to say trade with 2% of total account size, not risk.
 
Ruby:
# POSITION SIZER:
# @Woodman78 6/21

input ShowLabels    = yes ;
input ActualBalance = 500 ;
input RiskPercent   = .02 ;
def   SHAREStoBUY   = ActualBalance*RiskPercent;
DefineGlobalColor("Label", CreateColor(50, 200, 255)) ;
AddLabel(ShowLabels, "Shares to buy: " +SHAREStoBUY, GlobalColor("Label"));
nTHbTOz.png
Thank you, I just need to also include in the calculation is current stock price and then "personal balance" instead of a manual balance.
 
Last edited:
Ok Ive added current stock price to it, just still trying to figure out, how to input "personal balance" instead of a manual balance.
Code:
# POSITION SIZER:
# @Woodman78 6/21
# current stock price added

input ShowLabels    = yes ;
input ActualBalance = 25000 ;
input RiskPercent   = .02 ;
input stockprice = close;
def   SHAREStoBUY   = ActualBalance*RiskPercent / stockprice;
DefineGlobalColor("Label", CreateColor(50, 200, 255)) ;
AddLabel(ShowLabels, "Shares to buy: " +SHAREStoBUY, GlobalColor("Label"));
 
Ok Ive added current stock price to it, just still trying to figure out, how to input "personal balance" instead of a manual balance.
Code:
# POSITION SIZER:
# @Woodman78 6/21
# current stock price added

input ShowLabels    = yes ;
input ActualBalance = 25000 ;
input RiskPercent   = .02 ;
input stockprice = close;
def   SHAREStoBUY   = ActualBalance*RiskPercent / stockprice;
DefineGlobalColor("Label", CreateColor(50, 200, 255)) ;
AddLabel(ShowLabels, "Shares to buy: " +SHAREStoBUY, GlobalColor("Label"));
Here ya go, you wanna use getnetliq
Code:
###  Portfolio Tracking Tool v 1.0
# WTF_Dude 4.28.21 modified for Woodman78

declare upper;

# Input max percentage of a portfolio that one stock should be
input Max_Percent = 2;
input price = close;


def netliq = getnetliq();

### Risk of Portfolio

def twoperc = netliq * (Max_Percent/100);
addlabel(yes, Max_Percent + "%: " + asdollars(twoperc), CreateColor(50, 200, 255));

def shares = floor(round(twoperc/price,2));
addlabel(yes, "  Max Shares: " + shares, CreateColor(50, 200, 255));
 
Very inspiring thread, possible to get some help on my Position Size Script getting an error at def currentPrice. There may be more issues I'm not aware of I'm very green at this!

# Position Size Calculator based on max % account risk with variable position riskPercent %.
declare upper;

# Input max percentage of a portfolio that one stock should be
input Max_Percent = 0.50;
input price = close;

def netliq = GetNetLiq();

### Risk of Portfolio

def twoperc = netliq * (Max_Percent / 100);
AddLabel(yes, Max_Percent + "% Act Risk: " + AsDollars(twoperc), Color.CYAN);

# Input position risk
input RiskPercent = .05 ;

# Position Size
def currentPrice = priceType.LAST;
def dollarRisk = (currentPrice * RiskPercent);
def stopPrice = (currentPrice - dollarRisk);
def SHAREStoBUY = twoperc / (currentPrice - stopPrice);

input showlabel = yes;
AddLabel (yes, " POS " + SHAREStoBUY, Color.CYAN);
 
Hi @bottomphishing ...Welcome to useThinkscript :)

Thanks for sharing your script...I've made a couple of changes I'm hoping enhances the script and you will approve of...

Code:
# Position Size Calculator
# Author: @bottomphishing
# Date: 6/20/2021

# Position Size Calculator based on max % account risk with variable position riskPercent %.
declare upper;

#input showlabel = yes;
input ATRLength = 21;
input averagetype = AverageType.WILDERS;
input BasePeriod = AggregationPeriod.DAY;

def ATR = MovingAverage (averagetype, TrueRange(high(period = BasePeriod)[1], close(period = BasePeriod)[1], low(period = BasePeriod)[1]), ATRLength);

# Input max percentage of a portfolio that one stock should be
input Max_Percent = 0.03;
input price = close;

def netLiq = GetNetLiq();

# Risk of Portfolio
def twoPerc = netLiq * (Max_Percent / 100);
#AddLabel(yes, Max_Percent + "% Act Risk: " + AsDollars(twoperc), Color.CYAN);

# Input position risk
input RiskPercent = 0.02;

# Position Size
def currentPrice = price;
def dollarRisk = (currentPrice * RiskPercent);
def stopPrice = (currentPrice - dollarRisk);
def sharesToBuy = twoPerc / (currentPrice - stopPrice);

#AddLabel (yes, " POS " + SHAREStoBUY, Color.CYAN);

# Additional code by @netarchitech - 6/21/21
# Please double-check for accuracy
def stopATR = currentPrice - ATR;
def stopLoss = currentPrice - stopATR;
def tradeRisk = stopLoss * sharesToBuy;

input profitMultiple = 2.00;
def potentialProfit = (profitMultiple * ATR) * sharesToBuy;
def potentialProfitPerShare = potentialProfit / sharesToBuy;
def takeProfit = currentPrice + potentialProfitPerShare;

AddLabel(1," Shares to Buy: " + round(sharesToBuy, 0), Color.WHITE);
AddLabel(1," Stop Loss: " + round(stopATR, 2), Color.WHITE);
AddLabel(1," Take Profit: " + round(takeProfit, 2), Color.WHITE);
AddLabel(1," Trade Risk: " + AsDollars(tradeRisk), Color.WHITE);
AddLabel(1," Potential Profit: " + AsDollars(potentialProfit), Color.WHITE);

Unfortunately, it only works with Stocks... Any thoughts on how to get it to work with Futures?

Hope this helps...

Good Luck and Good Trading :)
 
Last edited:
I installed the script on another computer and now several addLabels are showing N/A and NaN:

a.jpg


Yet, on the computer I was working on, the addLabels are fine:

b.jpg


I've tried a myriad of things to resolve the issue with no luck...Any thoughts/suggestions? Thanks in advance...

UPDATE: Things seem to be working now...It may take a couple of minutes to start working...
 
Last edited:
I installed the script on another computer and now several addLabels are showing N/A and NaN:

a.jpg


Yet, on the computer I was working on, the addLabels are fine:

b.jpg


I've tried a myriad of things to resolve the issue with no luck...Any thoughts/suggestions? Thanks in advance...

UPDATE: Things seem to be working now...It may take a couple of minutes to start working...
A buddy of mine is have a issue with it loading as well. I have it on two different computers. I have no answers for this!
 
Hi @bottomphishing ...Welcome to useThinkscript :)

Thanks for sharing your script...I've made a couple of changes I'm hoping enhances the script and you will approve of...

Code:
# Position Size Calculator
# Author: @bottomphishing
# Date: 6/20/2021

# Position Size Calculator based on max % account risk with variable position riskPercent %.
declare upper;

#input showlabel = yes;
input ATRLength = 21;
input averagetype = AverageType.WILDERS;
input BasePeriod = AggregationPeriod.DAY;

def ATR = MovingAverage (averagetype, TrueRange(high(period = BasePeriod)[1], close(period = BasePeriod)[1], low(period = BasePeriod)[1]), ATRLength);

# Input max percentage of a portfolio that one stock should be
input Max_Percent = 0.03;
input price = close;

def netLiq = GetNetLiq();

# Risk of Portfolio
def twoPerc = netLiq * (Max_Percent / 100);
#AddLabel(yes, Max_Percent + "% Act Risk: " + AsDollars(twoperc), Color.CYAN);

# Input position risk
input RiskPercent = 0.02;

# Position Size
def currentPrice = price;
def dollarRisk = (currentPrice * RiskPercent);
def stopPrice = (currentPrice - dollarRisk);
def sharesToBuy = twoPerc / (currentPrice - stopPrice);

#AddLabel (yes, " POS " + SHAREStoBUY, Color.CYAN);

# Additional code by @netarchitech - 6/21/21
# Please double-check for accuracy
def stopATR = currentPrice - ATR;
def stopLoss = currentPrice - stopATR;
def tradeRisk = stopLoss * sharesToBuy;

input profitMultiple = 2.00;
def potentialProfit = (profitMultiple * ATR) * sharesToBuy;
def potentialProfitPerShare = potentialProfit / sharesToBuy;
def takeProfit = currentPrice + potentialProfitPerShare;

AddLabel(1," Shares to Buy: " + round(sharesToBuy, 0), Color.WHITE);
AddLabel(1," Stop Loss: " + round(stopATR, 2), Color.WHITE);
AddLabel(1," Take Profit: " + round(takeProfit, 2), Color.WHITE);
AddLabel(1," Trade Risk: " + AsDollars(tradeRisk), Color.WHITE);
AddLabel(1," Potential Profit: " + AsDollars(potentialProfit), Color.WHITE);

Unfortunately, it only works with Stocks... Any thoughts on how to get it to work with Futures?

Hope this helps...

Good Luck and Good Trading :)
Question?
I know what the ATR is, but in this instance, what is it calculating and why is it on 21? Is that 21 minutes, hours, days? Also the profit Multiple? Is that the 2% and 1% risk?...am I getting this right?? If so, that's exactly what I've been looking for!
 
Question?
I know what the ATR is, but in this instance, what is it calculating and why is it on 21? Is that 21 minutes, hours, days? Also the profit Multiple? Is that the 2% and 1% risk?...am I getting this right?? If so, that's exactly what I've been looking for!
I have no idea netarchitech added the ATR. That's no part of my trading plan, I use percent risk based on moving averages.
 
I have no idea why some people are getting N/A and others are not. If anyone can chime in as to why that is. Again here is the code:

# Position Size Calculator based on max % account risk with variable position riskPercent %
# Author: @bottomphishing
# Date: 6/20/2021

declare upper;

# Input max percentage of a portfolio that one stock should be
input Max_Percent = 0.25;
input price = close;

def netliq = GetNetLiq();

### Risk of Portfolio

def twoperc = netliq * (Max_Percent / 100);
AddLabel(yes, Max_Percent + "% ActRisk " + AsDollars(twoperc), Color.CYAN);

# Input position risk
input RiskPercent = .05 ;

# Position Size
def currentPrice = close;
def dollarRisk = (currentPrice * RiskPercent);
def stopPrice = (currentPrice - dollarRisk);
def SHAREStoBUY = twoperc / (currentPrice - stopPrice);

input showlabel = yes;
AddLabel (yes, " Pos " + roundup ((SHAREStoBUY),0), Color.CYAN);

AddLabel (yes, AsPercent(RiskPercent)+ " Stop " + AsDollars (currentPrice - (currentPrice * RiskPercent)), Color.CYAN);

AddLabel (yes, " Cap " + AsDollars (SHAREStoBUY * currentPrice), Color.CYAN);
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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