position_size_calculator.pinescript
Copy
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ActiveQuants
// Created by ActiveQuants
// Last updated: February 28, 2025
//@version=6
indicator(title = "Position Size Calculator [ActiveQuants]", shorttitle = "PSC [ActiveQuants]", overlay = true)
import TradingView/ta/9
//#region ------ USER INPUTS
// Account Settings
float accountSize = input.float(defval = 1000, title = "Account Size", minval = 0, step = 10, inline = "account", group = "Account Settings", confirm = true)
string accountCurrency = input.string(defval = "USD", title = "", options = ["USD", "EUR", "CAD", "JPY", "GBP", "HKD", "CNY", "NZD", "RUB", "AUD", "CHF", "NOK", "BRL", "SGD", "ZAR", "SEK", "TRY", "USDT", "USDC", "DAI"],
inline = "account", group = "Account Settings", confirm = true)
float riskValue = input.float(defval = 1, title = "Risk", minval = 0, step = 0.5, inline = "risk", group = "Account Settings", confirm = true)
string riskUnit = input.string(defval = "%", title = "", options = ["%", "Account Currency"], inline = "risk", group = "Account Settings", confirm = true)
float commissionValue = input.float(defval = 0.075, title = "Commission", minval = 0, step = 0.005, tooltip = "By default, two commissions are considered (entry and exit). If only one commission should be considered, please input half of your desired commission value",
inline = "commission", group = "Account Settings", confirm = true)
string commissionUnit = input.string(defval = "%", title = "", options = ["%", "Account Currency"], inline = "commission", group = "Account Settings", confirm = true)
int lotSize = input.int(defval = 100000, title = "Lot Size", options = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000], group = "Account Settings", confirm = true)
string rrrCalculation = input.string(defval = "By Profit and Loss", title = "RRR Calculation", options = ["By Profit and Loss", "By Price Change"],
tooltip = "By Profit and Loss: expected profit / expected loss. By Price Change: target price change / loss price change. Note: The results of the two calculation methods differ because Profit and Loss accounts for fees, whereas Price Difference does not.", group = "Account Settings", confirm = true)
// Trade Levels
float entryPrice = input.price(defval = 0, title = "Entry Price", inline = "entry", group = "Trade Levels", confirm = true)
int entryTime = input.time(defval = 0, title = "", tooltip = "Click at the bar and price where you want to enter the trade", inline = "entry", group = "Trade Levels", confirm = true)
float slPrice = input.price(defval = 0, title = "Stop Loss Price", tooltip = "Click where you want to set the position stop loss", group = "Trade Levels", confirm = true)
float tpPrice = input.price(defval = 0, title = "Take Profit Price", tooltip = "Click where you want to set the position take profit", group = "Trade Levels", confirm = true)
// Style
color entryLineColor = input.color(defval = color.new(#787b86, 70), title = "Entry Line", inline = "lines and zones", group = "Style")
color tpColor = input.color(defval = color.new(#089981, 80), title = "TP Zone", inline = "lines and zones", group = "Style")
color slColor = input.color(defval = color.new(#f23645, 80), title = "SL Zone", inline = "lines and zones", group = "Style")
color textColor = input.color(defval = color.new(color.white, 30), title = "Text", inline = "text and labels", group = "Style")
color tpLabelBg = input.color(defval = color.new(#089981, 50), title = "TP Label Background", inline = "text and labels", group = "Style")
color slLabelBg = input.color(defval = color.new(#f23645, 50), title = "SL Label Background", inline = "text and labels", group = "Style")
int extendRightBars = input.int(defval = 10, title = "Extend Right", minval = 0, tooltip = "The number of bars to extend the position projection to the right of the current bar", group = "Style")
int lotQtyRounding = input.int(defval = 3, title = "Lot Quantity Rounding", minval = 0, tooltip = "The number of decimals for the lot quantity value", group = "Style")
// TP and SL Labels
bool showPriceDiff = input.bool(defval = true, title = "Price Difference", inline = "general", group = "TP and SL Labels")
bool showPercent = input.bool(defval = true, title = "Percent", inline = "general", group = "TP and SL Labels")
bool showAmount = input.bool(defval = true, title = "Amount", inline = "general", group = "TP and SL Labels")
bool showPorL = input.bool(defval = true, title = "PnL", inline = "general", group = "TP and SL Labels")
// Entry Label
bool showPnL = input.bool(defval = true, title = "PnL", inline = "general", group = "Entry Label")
bool showEntryQuantity = input.bool(defval = true, title = "Quantity", inline = "general", group = "Entry Label")
bool showLotQuantity = input.bool(defval = true, title = "Lot Quantity", inline = "general", group = "Entry Label")
bool showPositionSize = input.bool(defval = true, title = "Position Size", inline = "general", group = "Entry Label")
bool showEntryAmount = input.bool(defval = true, title = "Amount", inline = "general", group = "Entry Label")
bool showRRR = input.bool(defval = true, title = "RRR", inline = "general", group = "Entry Label")
//#endregion
//#region ----- FUNCTIONS
// @function Converts a currency amount to the chart's ticker currency.
// @param currency (string) The currency of the amount.
// @param amount (float) The amount of the currency.
// @returns (float) The converted amount to the chart's ticker currency.
convertCurrencyAmount(string currency, float amount) =>
float multiplier = 1
string convertionCurrency = syminfo.currency
if (syminfo.currency == "USDT" and currency != "USD" and currency != "EUR" and currency != "USDT") or (syminfo.currency == "USDC" and currency != "EUR" and currency != "USDC") or (syminfo.currency == "DAI" and currency != "DAI")
convertionCurrency := "USD"
multiplier := na(request.security(currency + convertionCurrency, timeframe.period, close, ignore_invalid_symbol = true)) ? 1 : request.security(currency + convertionCurrency, timeframe.period, close, ignore_invalid_symbol = true)
amount * multiplier
// @function Checks if a projection represents a long or a short position.
// @param entryPrice (float) The entry price of the position.
// @param tpPrice (float) The take profit price of the position.
// @returns (bool) True if it represents a long position, otherwise returns false.
isLongPosition(float entryPrice, float tpPrice) =>
tpPrice > entryPrice
// @function Gets the unrealized profit and loss of a position.
// @param convertedEntryPrice (float) The entry price of the position (converted if necessary).
// @param quantity (float) The trading asset units.
// @param side (string) The position's side (long / short).
// @returns (float) The unrealized profit and loss of a position.
getUnrealizedPnL(float convertedEntryPrice, float quantity, string side) =>
float positionSize = quantity * convertedEntryPrice
float currAmount = quantity * (accountCurrency != "USD" ? convertCurrencyAmount(accountCurrency, close) : close)
switch side
"Long" => currAmount - positionSize
"Short" => (currAmount - positionSize) * -1
// @function Gets the realized profit and loss of a position.
// @param convertedEntryPrice (float) The entry price of the position (converted if necessary).
// @param quantity (float) The trading asset units.
// @param side (string) The position's side (long / short).
// @param closeType (string) The position's close type (TP / SL).
// @param tpZone (box) The take profit zone.
// @param slZone (box) The stop loss zone.
// @returns (float) The realized profit and loss of a position.
getRealizedPnL(float convertedEntryPrice, float quantity, string side, string closeType, box tpZone, box slZone) =>
float positionSize = quantity * convertedEntryPrice
float currAmount = quantity * (accountCurrency != "USD" and closeType == "TP" ? convertCurrencyAmount(accountCurrency, tpZone.get_top()) : accountCurrency != "USD" and closeType == "SL" ? convertCurrencyAmount(accountCurrency, tpZone.get_bottom()) : accountCurrency == "USD" and closeType == "TP" ? tpZone.get_top() : tpZone.get_bottom())
switch side
"Long" => currAmount - positionSize
"Short" => (currAmount - positionSize) * -1
//#endregion
//#region ----- VARIABLES
var int filledTime = na
var line entryPriceLine = line.new(entryTime, entryPrice, na, entryPrice, xloc = xloc.bar_time, color = entryLineColor)
var line priceChangePointer = line.new(entryTime, entryPrice, na, na, xloc = xloc.bar_time, color = entryLineColor, style = line.style_dashed)
var box tpZone = box.new(entryTime, tpPrice, na, entryPrice, border_width = 0, xloc = xloc.bar_time, bgcolor = tpColor)
var box slZone = box.new(entryTime, entryPrice, na, slPrice, border_width = 0, xloc = xloc.bar_time, bgcolor = slColor)
var box priceChangeZone = box.new(entryTime, na, na, entryPrice, xloc = xloc.bar_time, bgcolor = na, border_width = 0)
var label posInfoLabel = label.new(na, entryPrice, "", xloc.bar_time, color = na, style = label.style_label_center, textcolor = textColor)
var label tpLabel = label.new(na, tpPrice, "", xloc.bar_time, color = tpLabelBg, style = label.style_label_center, textcolor = textColor)
var label slLabel = label.new(na, slPrice, "", xloc.bar_time, color = slLabelBg, style = label.style_label_center, textcolor = textColor)
float riskPerTradeNominal = riskUnit == "%" ? accountSize * riskValue / 100 : riskValue
float slPercentage = math.abs(100 - slPrice * 100 / entryPrice) / 100
float tpPercentage = math.abs(100 - tpPrice * 100 / entryPrice) / 100
// Position Size Equations:
// For % Commission: Nominal Risk / (1 − (1 − Commission Value)^2 * (1 − Stop Loss Percentage)) "Commission Value ^ 2" to consider two commissions (entry and exit)
// For Account Currency Commission: (Nominal Risk - Commission Value * (2 - Stop Loss Percentage)) / Stop Loss Percentage
float positionSizeAccountCurrency = commissionUnit == "%" ? riskPerTradeNominal / (1 - math.pow(1 - commissionValue / 100, 2) * (1 - slPercentage)) : (riskPerTradeNominal - commissionValue * (2 - slPercentage)) / slPercentage
float positionSize = convertCurrencyAmount(accountCurrency, positionSizeAccountCurrency)
float quantity = positionSize / entryPrice
float lotQuantity = quantity / lotSize
var string status = "not filled"
var int lastRight = na
var int lastPointerRight = na
var string closeType = na
string posInfoLabelText = ""
string tpLabelText = ""
string slLabelText = ""
float entryAmount = commissionUnit == "%" ? positionSizeAccountCurrency * (1 - commissionValue / 100) : positionSizeAccountCurrency - commissionValue
float profit = commissionUnit == "%" ? (positionSizeAccountCurrency * (1 - commissionValue / 100) * (1 + tpPercentage) * (1 - commissionValue / 100)) - (positionSizeAccountCurrency) : (positionSizeAccountCurrency - commissionValue) * (1 + tpPercentage) - commissionValue - (positionSizeAccountCurrency)
float loss = commissionUnit == "%" ? (positionSizeAccountCurrency * (1 - commissionValue / 100) * (1 - slPercentage) * (1 - commissionValue / 100)) - (positionSizeAccountCurrency) : (positionSizeAccountCurrency - commissionValue) * (1 - slPercentage) - commissionValue - (positionSizeAccountCurrency)
float rrr = rrrCalculation == "By Profit and Loss" ? math.abs(profit / loss) : math.abs(tpPrice - entryPrice) / math.abs(slPrice - entryPrice)
float tpAmount = commissionUnit == "%" ? positionSizeAccountCurrency * (1 - commissionValue / 100) * (1 + tpPercentage) : (positionSizeAccountCurrency - commissionValue) * (1 + tpPercentage)
float slAmount = commissionUnit == "%" ? positionSizeAccountCurrency * (1 - commissionValue / 100) * (1 - slPercentage) : (positionSizeAccountCurrency - commissionValue) * (1 - slPercentage)
//#endregion
//#region ----- LABELS
if status == "not filled" and (time >= entryTime and time <= entryPriceLine.get_x2()) and low <= entryPrice and high >= entryPrice
filledTime := time
status := "filled"
if status == "filled" or status == "not filled"
entryPriceLine.set_x2(time(timeframe.period, -extendRightBars)), tpZone.set_right(time(timeframe.period, -extendRightBars)), slZone.set_right(time(timeframe.period, -extendRightBars))
lastRight := time(timeframe.period, -extendRightBars)
lastPointerRight := time
if status == "filled"
priceChangePointer.set_x1(filledTime), priceChangePointer.set_xy2(time, close)
priceChangeZone.set_left(filledTime), priceChangeZone.set_top(close), priceChangeZone.set_right(time), priceChangeZone.set_bgcolor(close > entryPrice and isLongPosition(entryPrice, tpPrice) or close < entryPrice and not isLongPosition(entryPrice, tpPrice) ? tpColor : slColor)
if time >= entryTime and isLongPosition(entryPrice, tpPrice) and (high >= tpPrice or low <= slPrice)
status := "closed"
closeType := high >= tpPrice ? "TP" : "SL"
else if time >= entryTime and not isLongPosition(entryPrice, tpPrice) and (low <= tpPrice or high >= slPrice)
status := "closed"
closeType := low <= tpPrice ? "TP" : "SL"
if isLongPosition(entryPrice, tpPrice) and status == "filled"
if showPnL
posInfoLabelText += str.format("Open PnL: {0} {1}", getUnrealizedPnL(entryPrice, quantity, "Long"), accountCurrency)
if showEntryQuantity or showLotQuantity or showPositionSize or showEntryAmount or showRRR
posInfoLabelText += ", "
else if status == "filled"
if showPnL
posInfoLabelText += str.format("Open PnL: {0} {1}", getUnrealizedPnL(entryPrice, quantity, "Short"), accountCurrency)
if showEntryQuantity or showLotQuantity or showPositionSize or showEntryAmount or showRRR
posInfoLabelText += ", "
else
posInfoLabelText += "Position isn't open yet"
if showEntryQuantity or showLotQuantity or showPositionSize or showEntryAmount or showRRR
posInfoLabelText += ", "
if status == "closed"
entryPriceLine.set_x2(lastRight), priceChangePointer.set_xy2(lastPointerRight, closeType == "TP" ? tpZone.get_top() : slZone.get_bottom()), tpZone.set_right(lastRight), slZone.set_right(lastRight), priceChangeZone.set_top(closeType == "TP" ? tpZone.get_top() : slZone.get_bottom())
if isLongPosition(entryPrice, tpPrice)
if showPnL
posInfoLabelText += str.format("Closed PnL: {0} {1}", getRealizedPnL(entryPrice, quantity, "Long", closeType, tpZone, slZone), accountCurrency)
if showEntryQuantity or showLotQuantity or showPositionSize or showEntryAmount or showRRR
posInfoLabelText += ", "
else
if showPnL
posInfoLabelText += str.format("Closed PnL: {0} {1}", getRealizedPnL(entryPrice, quantity, "Short", closeType, tpZone, slZone), accountCurrency)
if showEntryQuantity or showLotQuantity or showPositionSize or showEntryAmount or showRRR
posInfoLabelText += ", "
if showEntryQuantity
posInfoLabelText += str.format("Qty: {0}", quantity)
if (status == "not filled" and not showPnL and not showLotQuantity and (showPositionSize or showEntryAmount or showRRR)) or (showPnL and not showLotQuantity and showPositionSize and showEntryAmount and showRRR) or (showPnL and not showLotQuantity and not showPositionSize and showEntryAmount and showRRR) or (showPnL and not showLotQuantity and showPositionSize and not showEntryAmount and showRRR) or (showPnL and not showLotQuantity and showPositionSize and showEntryAmount and not showRRR)
posInfoLabelText += "\n"
else if showLotQuantity or showPositionSize or showEntryAmount or showRRR
posInfoLabelText += ", "
if showLotQuantity
posInfoLabelText += str.format("Lot Qty: {0}", math.round(lotQuantity, lotQtyRounding))
if (status == "not filled" and not showPnL and (showEntryQuantity or showPositionSize or showEntryAmount or showRRR)) or (showPnL and showEntryQuantity and showPositionSize and showEntryAmount and showRRR) or (showPnL and not showPositionSize and showEntryAmount and showRRR) or (showPnL and showPositionSize and not showEntryAmount and showRRR) or (showPnL and showPositionSize and showEntryAmount and not showRRR)
posInfoLabelText += "\n"
else if showPositionSize or showEntryAmount or showRRR
posInfoLabelText += ", "
if showPositionSize
posInfoLabelText += str.format("PS: {0} {1}", positionSize, syminfo.currency)
if (status == "filled" and not showPnL and showEntryQuantity and showEntryAmount and showRRR) or (showPnL and not showEntryQuantity and showEntryAmount and showRRR)
posInfoLabelText += "\n"
else if showEntryAmount or showRRR
posInfoLabelText += ", "
if showEntryAmount
posInfoLabelText += str.format("Amount: {0} {1}", entryAmount, accountCurrency)
if showRRR
posInfoLabelText += ", "
if showRRR
posInfoLabelText += str.format("RRR: {0, number, #.##}", rrr)
posInfoLabel.set_x(math.round((entryTime + lastRight) / 2)), posInfoLabel.set_text(posInfoLabelText)
posInfoLabel.set_color(posInfoLabelText != "" and (close > entryPrice and isLongPosition(entryPrice, tpPrice)) or (close < entryPrice and not isLongPosition(entryPrice, tpPrice)) ? tpLabelBg : posInfoLabelText != "" ? slLabelBg : na)
posInfoLabel.set_textcolor(textColor)
if showPriceDiff
tpLabelText += str.format("Target: {0, number, #.##}", math.abs(tpPrice - entryPrice))
slLabelText += str.format("Stop: {0, number, #.##}", math.abs(slPrice - entryPrice))
if not showPercent and (showAmount or showPorL)
tpLabelText += ", "
slLabelText += ", "
else if showPercent
tpLabelText += " "
slLabelText += " "
if showPriceDiff and showPercent
tpLabelText += str.format("({0, number, #.##}%)", math.abs(tpPrice - entryPrice) * 100 / entryPrice)
slLabelText += str.format("({0, number, #.##}%)", math.abs(slPrice - entryPrice) * 100 / entryPrice)
if showAmount or showPorL
tpLabelText += ", "
slLabelText += ", "
else if not showPriceDiff and showPercent
tpLabelText += str.format("Target: {0, number, #.##}%", math.abs(tpPrice - entryPrice) * 100 / entryPrice)
slLabelText += str.format("Stop: {0, number, #.##}%", math.abs(slPrice - entryPrice) * 100 / entryPrice)
if showAmount or showPorL
tpLabelText += ", "
slLabelText += ", "
if showAmount
tpLabelText += str.format("Amount: {0} {1}", tpAmount, accountCurrency)
slLabelText += str.format("Amount: {0} {1}", slAmount, accountCurrency)
if showPorL
tpLabelText += ", "
slLabelText += ", "
if showPorL
tpLabelText += str.format("Profit: {0} {1}", profit, accountCurrency)
slLabelText += str.format("Loss: {0} {1}", loss, accountCurrency)
tpLabel.set_x(math.round((entryTime + lastRight) / 2)), tpLabel.set_text(tpLabelText), tpLabel.set_color(tpLabelText != "" ? tpLabelBg : na), tpLabel.set_textcolor(textColor)
slLabel.set_x(math.round((entryTime + lastRight) / 2)), slLabel.set_text(slLabelText), slLabel.set_color(slLabelText != "" ? slLabelBg : na), slLabel.set_textcolor(textColor)
//#endregion
//#region ----- ERRORS
if slPrice > entryPrice and tpPrice > entryPrice
runtime.error("The 'Take Profit' and 'Stop Loss' levels are both above the 'Entry Price'. Please set one of them above the 'Entry Price' and the other one below.")
else if slPrice < entryPrice and tpPrice < entryPrice
runtime.error("The 'Take Profit' and 'Stop Loss' levels are both below the 'Entry Price'. Please set one of them above the 'Entry Price' and the other one below.")
//#endregion
Show all 273 lines