Position Size Calculator for ThinkorSwim

Thank you VOLLERMIST I will look at this tonight

Are we supposed to add this to a strategy or study? When one tries to add to studies it asks for a plot and strategy asks for an Add order
 
Are we supposed to add this to a strategy or study? When one tries to add to studies it asks for a plot and strategy asks for an Add order
Irrelevant if it ask for a plot...one can just make a label for the variable "shares". In a strategy, just use the variable "shares" in the AddOrder statement instead of the number of shares. I incorporate this code (or a variation of this code) in studies AND strategies. I only trade stocks, so I don't know how it will work on other instruments. I guess you could call this code a "snippet" that can be used standalone by just adding an AddLabel statement. I'm not a programmer, so I don't know if I'm using the correct terms.

In the strategy section, I posted a strategy I had been working on which incorporates a version of this code. Most of what I code is coded for range bar charts, and may be suboptimal for time or tick based charts. GrowEquityStrategy including Kelly-based position sizing
 
Last edited:
I came across a script months ago:
https://usethinkscript.com/threads/position-size-calculator-for-thinkorswim.588/page-3#post-49627
but I felt that it was lacking. I just got around to finishing it. I only wish that it could also highlight the price in the active trader.

http://tos.mx/VviLozV
CTSISh4.png

Code:
# Simple Position Calculator
# Assembled by BenTen at UseThinkScript.com

input Budget = 2000;
def current_price = close;
def Share_Quantity_purchase_limit =  Budget / current_price;

############# labels

AddLabel(yes, Concat("Shares available for purchase = ", Round(Share_Quantity_purchase_limit)), Color.ORANGE);

###############################################################################################

input profit_goal = 50.00;
plot Close_Position = profit_goal/Share_Quantity_purchase_limit ;
Close_Position.SetDefaultColor(GetColor(0));

AddLabel(yes, Concat("profit goal = ", Round(profit_goal)), Color.orange);
AddLabel(yes, Concat("required price change = ", (Close_Position)), Color.white);

def  yellow = profit_goal/Share_Quantity_purchase_limit;
#####################################################################

plot priceLine = current_price + close_Position;;
priceline.SetPaintingStrategy(PaintingStrategy.line);
priceLine.SetLineWeight(1);

AddLabel(yes, Concat(" Stock price + profit goal = ",Round(current_price + close_Position )), Color.white);

#AddLabel(yes, Concat(" The amount of active trader movement  = ",Round(Share_Quantity_purchase_limit + close_Position )), Color.white);
The simplicity of this calculator works very well with my Renko DMI Strategy. Thanks for sharing!
 
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
aMAZING SCRIPT!!! IS IT POSSIBLE TO HAVE IT WORKING ON A TICK CHARTS?
 
Hi, I want to add to this code a label to tell me how many shares I have available to buy, so will be TotalShares= GetTotalCash () / GetAveragePrice(); But I can not make work, can somebody help me

Here is the code:
plot entryPrice;

input showDetails = yes;
input showBasis = yes;
input showProfitLoss = yes;
input showFills = no;
input netProfitLossPastTrades = 0.00;
input MaxShares = yes;


# Entry Price
entryPrice = GetAveragePrice();
entryPrice.AssignValueColor(if close < entryPrice then Color.DOWNTICK else Color.UPTICK);
entryPrice.SetLineWeight(2);
entryPrice.SetStyle(Curve.SHORT_DASH);

# Basis Calculat ion
def qty = GetQuantity();
def openCost = qty * GetAveragePrice();
def basis = (qty * entryPrice);

#add it

def Cash = GetTotalCash ();
def StockPrice = GetAveragePrice ();
def TotalShares= GetAveragePrice () / GetTotalCash ();


#Labels
AddLabel(showDetails, qty + "@" + AsDollars(entryPrice), Color.GRAY);
AddLabel(showBasis and netProfitLossPastTrades == 0.0, "Basis: " + AsDollars(basis), if basis > (qty * close) then Color.DOWNTICK else Color.UPTICK);
AddLabel(showBasis and netProfitLossPastTrades != 0.0, "Basis (adj): " + AsDollars(basis), if basis > (qty * close) then Color.DOWNTICK else Color.UPTICK);
def pl = (close - entryPrice) * qty;
AddLabel(showProfitLoss, "P/L: " + AsDollars(pl), if pl > 0 then Color.UPTICK else if pl == 0 then Color.WHITE else Color.DOWNTICK);
AddLabel(showProfitLoss, "P/L/Share: " + AsDollars(close - entryPrice), if (close - entryPrice) > 0 then Color.UPTICK else if (close - entryPrice) == 0 then Color.WHITE else Color.DOWNTICK);

#add it
AAddLabel(MaxShares, "TotalShares: " + AsDollars(Cash) + " | StockPrice: " + AsDollars(StockPrice), Color.WHITE);
 
below is a position script calculator that measures risk unit (ex. R1) based on the difference of previous bar high and low price. I want it to be change to the current bar - can someone please convert it?

Code:
#
# PositionSizingCalculator
#
# Author: Kory Gill, [USER=212]@korygill[/USER]
#
# Modified by Jedo64

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

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


AddLabel(
no,
AsDollars(RiskUnit) + "=1R",
Color.CYAN
);

# Instead of current bar i changed it to previous bar
def diff = hi[1] - lo[1];
def diff0 = hi - lo;

plot SharesSize = Floor(Round(RiskUnit / diff0));

AddLabel(
yes,
"Risk: " + AsDollars(diff * 1.00) + " = " + Floor(Round(RiskUnit / (diff * 1.00))) + " Shares ",
Color.CYAN
);

#added a Green label to see Inside Bar Size for Long trigger


def diffl = (hi[1] - lo[1]) * 1.00;

AddLabel(
yes,
" Long = .7R: " + (RoundDown(hi[1] + diffl*.7)) + " 1R: " + (RoundDown(hi[1] + diffl)) + " 2R: " + (RoundDown(hi[1] + diffl*2)) + " 3R: " + (RoundDown(hi[1] + diffl*3))+ " 4R: " + (RoundDown(hi[1] + diffl*4))+ " 5R: " + (RoundDown(hi[1] + diffl*5)),
Color.GREEN
);


# Added red label to see Inside Bar Size for short trigger

def diffs = (hi[1] - lo[1]) * 1.00;

AddLabel(
yes,
"SHORT = .7R: " + (rounddown(lo[1] - diffs*.7)) + " 1R: " + (rounddown(lo[1] - diffs)) + " 2R: " + (rounddown(lo[1] - diffs*2)) + " 3R: " + (rounddown(lo[1] - diffs*3)) + " 4R: " + (rounddown(lo[1] - diffs*4)) + " 5R: " + (rounddown(lo[1] - diffs*5)) ,
Color.rED
);
 
Last edited by a moderator:
below is a position script calculator that measures risk unit (ex. R1) based on the difference of previous bar high and low price. I want it to be change to the current bar - can someone please convert it?

Code:
#
# PositionSizingCalculator
#
# Author: Kory Gill, [USER=212]@korygill[/USER]
#
# Modified by Jedo64

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

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


AddLabel(
no,
AsDollars(RiskUnit) + "=1R",
Color.CYAN
);

# Instead of current bar i changed it to previous bar
def diff = hi[1] - lo[1];
def diff0 = hi - lo;

plot SharesSize = Floor(Round(RiskUnit / diff0));

AddLabel(
yes,
"Risk: " + AsDollars(diff * 1.00) + " = " + Floor(Round(RiskUnit / (diff * 1.00))) + " Shares ",
Color.CYAN
);

#added a Green label to see Inside Bar Size for Long trigger


def diffl = (hi[1] - lo[1]) * 1.00;

AddLabel(
yes,
" Long = .7R: " + (RoundDown(hi[1] + diffl*.7)) + " 1R: " + (RoundDown(hi[1] + diffl)) + " 2R: " + (RoundDown(hi[1] + diffl*2)) + " 3R: " + (RoundDown(hi[1] + diffl*3))+ " 4R: " + (RoundDown(hi[1] + diffl*4))+ " 5R: " + (RoundDown(hi[1] + diffl*5)),
Color.GREEN
);


# Added red label to see Inside Bar Size for short trigger

def diffs = (hi[1] - lo[1]) * 1.00;

AddLabel(
yes,
"SHORT = .7R: " + (rounddown(lo[1] - diffs*.7)) + " 1R: " + (rounddown(lo[1] - diffs)) + " 2R: " + (rounddown(lo[1] - diffs*2)) + " 3R: " + (rounddown(lo[1] - diffs*3)) + " 4R: " + (rounddown(lo[1] - diffs*4)) + " 5R: " + (rounddown(lo[1] - diffs*5)) ,
Color.rED
);
How to code a stop segregation?

Px range stop %
1-15 2%
16-30 1.75
31-60 1
61-100 .75


UPDATE:
I believe this may answer my question:
https://usethinkscript.com/threads/convert-tradingview-trailing-stop-loss.15598/
 
Last edited by a moderator:
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);
How does this one work, is it a PL ratio?
I've got a better one. There's three scenarios:
Scenario 1: You can choose your size and your risk, but not your stop
Scenario 2: You can choose your size and your stop, but not your risk
Scenario 3: You can choose your risk and your stop, but not your size

Why not make it an indicator that lets you see the result of those decisions? I decided to make one. The only issue I'm uncertain of is whether I am making price what it actually is. I decided to go with Mark

Here's the code:

Code:
#
# PositionSizingCalculator
#
# Author: RamonDV. AKA Pelonsax
#
#

input Risk_Amount = 100;
input Shares = 1000;
input Stop_Price = 100.00;
input Choose_Size_and_Risk = yes; #can't choose stop
input Choose_Size_and_Stop = yes; #can't choose risk
input Choose_Risk_and_Stop = yes; #can't choose size

def Mark = close(PriceType = PriceType.MARK);
def Size  = Risk_Amount / (Mark - Stop_Price);
def Stop = ((Mark * Shares) - Risk_Amount) / Shares;
def Risk = (mark - Stop_Price) * Shares;

#Display current price
AddLabel(yes, "Current Price: " + AsDollars(Mark), color.gray);

#No defined stop
AddLabel(Choose_Size_and_Risk, "No defined stop: " + Shares + " Shares with " + AsDollars(Risk_Amount) + " risk with Stop Loss at " + AsDollars(stop) + "  .", color.gray);

#No defined risk
AddLabel(Choose_Size_and_Stop, "No Defined risk: " + Shares + " Shares with " + AsDollars(risk) + " risk with Stop Loss at " + AsDollars(Stop_Price) + "  .", color.gray);

#No defined size
AddLabel(Choose_Risk_and_Stop, "No defined size: " + Floor(Round(size)) + " Shares with " + AsDollars(Risk_Amount) + " risk with Stop Loss at " + AsDollars(Stop_Price) + "  .", color.gray);

Here's the link:

https://tos.mx/l2H5IBg
I'm trying to understand this one. For instance if I use the "Risk_Stop" scenario...With a $25 Risk at a $.10 Stop, shouldn't it show 250 Shares? It just shows "1 Shares".

This one I wrote to auto calculate the number of shares to buy based on an input risk % and capital size. You will need to update the stop level based on whatever signal you are using.

Code:
########################################
input capital_size = 25000;
input risk_percent = 1;
def risk_price = close;

def risk_percent_calc = risk_percent / 100;
def entry_stop_bull = (risk_price - bullstop);
def entry_stop_bear = (bearstop - risk_price);
def units_to_buy_bull = (risk_percent_calc * capital_size) / (entry_stop_bull) / risk_price;
def units_to_buy_bull1 = RoundDown(units_to_buy_bull,0);
def total_cost_bull = units_to_buy_bull1 * risk_price;
def units_to_buy_bear = (risk_percent_calc * capital_size) / (entry_stop_bear) / risk_price;
def units_to_buy_bear1 = RoundDown(units_to_buy_bear,0);
########################################
I get an error. Where is "bullstop" or "bearstop" defined?
 
Last edited by a moderator:
Hi,

Is it possible to have a script that calculates SHARE SIZE based on a Risk $ amount and a place on the chart where I click my mouse?

I have this script already for another trading software called DAS Trader and use it daily. But I prefer to trade in TOS.


For example:

Risk is set to $50 for every trade.

Stop = Price where I click my mouse (let's say I single-click on the chart at $10.00)

if Current Price: $11, and I single-click on $10, I want the script to tell me the share size I should use.

In this case, $50 risk, $1 stop, Share Size should be = 50 shares.
 

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

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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