Indicator · Pine Script v5 · Own pane

Vol-Targeted Position Size

by Robot-Wealth· code credited to robotkris

This indicator calculates volatility-targeted position sizes using an exponentially weighted moving average volatility forecast.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code51
Settings4inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago26 Mar 2024

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

51 lines of Pine Script v5 from VolTargeting/vol_targeted_pos_size_indicator.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

vol_targeted_pos_size_indicator.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © robotkris

//@version=5
indicator("Vol-Targeted Position Size", overlay = false)
import TradingView/ta/7
import robotkris/VolTargeting/2 as VolTargeting

// user inputs
balance = input(10000, "Balance")  // in units of quote currency
volEstimationWdw = input(30, "Volatility estimation window length")
targetVolContribution = input(10, "Target volatility contribution, %")
tradeBuffer = input(5, "Size of no-trade region as % of target position size")

// calculate vol forecast as ewma of volatility
volForecast = VolTargeting.ewmaVol(volEstimationWdw)

// calculate target position size
targetPos = VolTargeting.volTargetedSize(balance, targetVolContribution, volForecast)
upperBarrier = targetPos+targetPos*0.01*tradeBuffer
lowerBarrier = targetPos-targetPos*0.01*tradeBuffer

// plot target position size and no-trade region
plot(targetPos, title = "Target position", color = color.rgb(66, 56, 245), style = plot.style_stepline)
barrier1 = plot(upperBarrier, "Top of no-trade region", color = color.rgb(245, 126, 56, 50))
barrier2 = plot(lowerBarrier, "Bottom of no-trade region", color = color.rgb(245, 126, 56, 50))
fill(barrier1, barrier2, color = color.rgb(245, 126, 56, 75))

// Output relevant information in a table

// Initialize the table on the first bar
var table targetPosDisplay = table.new(position.bottom_right, 2, 7, bgcolor = color.rgb(97, 189, 79, 40), frame_width = 2, frame_color = color.rgb(97, 189, 79, 50))

// Make display text static - relates to most recent bar on the chart only
// If we displayed targetPos instead of finalTargetPos, the value in the text display would change as the user moved their curser over previous bars
if barstate.islast 
    finalTargetPos = targetPos
    table.cell(targetPosDisplay, 0, 0, str.format("Balance ({0})", syminfo.currency), text_color = color.black, text_halign = text.align_left)
    table.cell(targetPosDisplay, 1, 0, str.format("{0}", balance), text_color = color.black, text_halign = text.align_right)
    table.cell(targetPosDisplay, 0, 1, "Target vol (Ann.)", text_color = color.black, text_halign = text.align_left)
    table.cell(targetPosDisplay, 1, 1, str.format("{0}%", targetVolContribution), text_color = color.black, text_halign = text.align_right)
    table.cell(targetPosDisplay, 0, 2, str.format("{0}-period ann. vol", volEstimationWdw), text_color = color.black, text_halign = text.align_left)
    table.cell(targetPosDisplay, 1, 2, str.format("{0}%", math.round(volForecast*100, 1)), text_color = color.black, text_halign = text.align_right)
    table.cell(targetPosDisplay, 0, 3, "Position size", text_color = color.black, text_halign = text.align_left)
    table.cell(targetPosDisplay, 1, 3, str.format("{0}", finalTargetPos), text_color = color.black, text_halign = text.align_right)
    table.cell(targetPosDisplay, 0, 4, "No-trade buffer", text_color = color.black, text_halign = text.align_left)
    table.cell(targetPosDisplay, 1, 4, str.format("{0}%", tradeBuffer), text_color = color.black, text_halign = text.align_right)    
    table.cell(targetPosDisplay, 0, 5, "Upper no-trade barrier", text_color = color.black, text_halign = text.align_left)
    table.cell(targetPosDisplay, 1, 5, str.format("{0}", math.round(upperBarrier, 1)), text_color = color.black, text_halign = text.align_right)
    table.cell(targetPosDisplay, 0, 6, "Lower no-trade barrier", text_color = color.black, text_halign = text.align_left)
    table.cell(targetPosDisplay, 1, 6, str.format("{0}", math.round(lowerBarrier, 1)), text_color = color.black, text_halign = text.align_right)

Overview

Vol-Targeted Position Size plots the target position size along with upper and lower no-trade buffer boundaries in a separate pane. A dashboard table in the bottom-right corner displays real-time parameters, including account balance, annualized target volatility, period volatility, position units, and buffer limits. Custom settings allow control over account balance, volatility window, target volatility percentage, and buffer size.

Details

Published by

Robot-Wealth on GitHub

Code credit

robotkris, as written in the script's header

Draws

Separate pane below the chart

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
Balanceint10000balance
Volatility estimation window lengthint30volEstimationWdw
Target volatility contribution, %int10targetVolContribution
Size of no-trade region as % of target position sizeint5tradeBuffer
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

This indicator scans a pasted list of symbols and shows matching long and short setups in a table in a separate pane. It uses a Supertrend crossover, then applies an ATR or fixed-point volatility range so quiet, sideways conditions can be skipped. Optional fil

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper Scanner

Test 009 Stat Mining

by ricardosantos79
261 stars

This statistical analysis tool mines historical relationships between RSI values and candle volatility. It calculates a 14-period RSI from the previous bar and normalizes absolute price change using a 14-period Average True Range (ATR). Based on the normalized

Indicator v4 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Test 009 Stat Mining

Market Speedometer

by TradersPost
228 stars

Market Speedometer plots a 0-100 market speed reading in a separate pane. It measures movement by bar-to-bar change, true range, or a short average of recent bars, then ranks that movement against ATR and a percentile lookback. An EMA smooths the reading, and

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Market Speedometer
46 stars

This indicator summarizes higher-timeframe candle range statistics by time of day and shows them in a table in a separate pane. It groups candles into slots for 5-minute, 15-minute, 1-hour, 4-hour, 8-hour, or 12-hour periods over a chosen lookback in days, and

Indicator v5 Screeners & dashboardsSessions & time Repaints
Updated 8 weeks ago · None stated GitHub repository of HTF Candle Stats by Time of Day
41 stars

This indicator transforms standard RSI calculations into logit space, estimating rolling distributions to derive empirical z-scores mapped back to the 0–100 RSI scale. Plotted in a separate pane, it features multi-horizon central lines—fast and structural cent

Indicator v6 Oscillators & momentumVolatility & bands
Updated 4 days ago · None stated GitHub repository of Calibrated RSI Position Zones

More Volatility & bands scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers