Indicator · Pine Script v5 · Own pane

Risk-Based Position Size Calculator

by Zettt

Calculates normalized moving average trend strength, historical volatility, and volatility-adjusted position sizing in a separate pane.

View on GitHub

GitHub stars43on the repository
Pine versionv5runs as is
Lines of code54
Settings5inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago23 Sep 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

54 lines of Pine Script v5 from Position Size Calculator.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Position Size Calculator.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Zettt
// Plots difference of price to the difference of two EMAs in percent. The idea is that if price is rallying strongly
// it would naturally travel further away from a moving average. By calculating the percentage,
// we can standardize trend strength.

//@version=5
indicator(title="Risk-Based Position Size Calculator", shorttitle="MA Diff+HV+Pos Size", precision=4)
// Inputs
fastEMALength = input(title="Fast Length", defval=21)
slowEMALength = input(title="Slow Length", defval=55)
signalEMALength = 9 // not used but needed to init the MACD
src = input(title="Source", defval=close)
lookback = input.int(defval=100, title="HV Lookback", minval=1)
tradingCapital = input.int(defval=1, title="Trading Capital", minval=1)

// Calculations
// MA Difference (using MACD)
fastEMA = ta.ema(src, fastEMALength)
slowEMA = ta.ema(src, slowEMALength)

[macd, signal, histogram] = ta.macd(src, fastEMALength, slowEMALength, signalEMALength)
differenceToPrice = macd / src //*100

// Historical volatility
dailyReturns = src / src[1] - 1
historicalVolatility = ta.stdev(dailyReturns, lookback) * math.sqrt(lookback)

// Position size
positionSize = tradingCapital * (differenceToPrice/historicalVolatility)

// Plotting
// Colors
differenceToPriceColor = color.new(#2862ff, 0)
historicalVolatilityColor = color.new(#349b5b, 0)
positionSizeColor = color.new(#f18862, 0)
backcolor = color.new(color.gray, 90) // Background color for the table

hline(0, "Zero Line", color = color.new(#787B86, 50))

plot(differenceToPrice, title="Difference to Price in Percent", color = differenceToPriceColor)
plot(historicalVolatility, title="Historical Volatility", color = historicalVolatilityColor)
plot(positionSize, title="Position Size", color = positionSizeColor)

// Create table
var table myTable = table.new(position=position.bottom_left, columns=3, rows=1, border_width=1)

// Set table headers (unused)
// table.cell(myTable, 0, 0, "Indicator", bgcolor=backcolor)

// Update table values
table.cell(myTable, 0, 0, "Difference to Price in Percent", text_color=differenceToPriceColor, bgcolor=backcolor)
table.cell(myTable, 1, 0, "Historical Volatility", text_color=historicalVolatilityColor, bgcolor=backcolor)
table.cell(myTable, 2, 0, "Position Size", text_color=positionSizeColor, bgcolor=backcolor)

Overview

Risk-Based Position Size Calculator computes the percentage distance between fast and slow EMAs relative to price, evaluates standard deviation of daily returns over a lookback period, and divides trend distance by volatility to calculate position sizing relative to defined capital. Configurable parameters include EMA lengths, source price, volatility lookback, and trading capital.

Details

Published by

Zettt on GitHub

Type

Indicator, Pine Script v5

Draws

Separate pane below the chart

Category

Moving averages, Volatility & bands, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Fast Lengthint21fastEMALength
Slow Lengthint55slowEMALength
Sourcesourceclosesrc
HV Lookbackint100lookback
Trading Capitalint1tradingCapital
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

MultiIndicator

by capissimo
114 stars

MultiIndicator combines multiple technical indicators into a single separate pane to save chart space. It calculates and displays market regime detection based on ordinary least squares regression, a Holt exponential smoothing crossover, normalized RSI, ADX, a

Indicator v4 Oscillators & momentumTrend
Updated 1 year ago · None stated GitHub repository of MultiIndicator
29 stars

The Supertrended RSI [AlgoAlpha] indicator plots the Relative Strength Index combined with a Supertrend overlay in a separate indicator pane. It first computes standard RSI, with an optional Hull Moving Average smoothing step, and computes a secondary moving a

Indicator v5 Oscillators & momentumTrend
Updated 11 months ago · Custom licence GitHub repository of Supertrended RSI [AlgoAlpha]

This indicator computes and plots multiple technical analysis features on a separate pane. It calculates EMA-based trend indicators including fast and slow EMAs along with their slope, momentum oscillators such as RSI, Stochastic RSI, and MACD histogram, WaveT

Indicator v6 TrendOscillators & momentum
Updated yesterday · MIT GitHub repository of Vein Feature Exporter Core 4H [WavesUnchained]
318 stars

This indicator plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 2 months ago · MIT GitHub repository of Multiple Moving Averages

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of NVDA Trend Ribbon

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers