Library · Pine Script v5 · Library

VolTargeting

by Robot-Wealth· code credited to robotkris

VolTargeting is a Pine Script v5 library of functions for volatility-based position sizing.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code53
Settings0inputs
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 library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

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

vol_trageting_lib.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

// @description: Functions for calculating position sizes based on volatility targets
library("VolTargeting")
import TradingView/ta/7

// @function Calculates an exponentially weighted annualised volatility
// @param estimationWdw Half life of exponential weighting scheme
// @returns Exponentially weighted annualised volatility
export ewmaVol(int estimationWdw) =>
    // vol annualisation factor  
    // scale by sqrt(365) for crypto, sqrt(252) for everything else
    int secondsInYear = 252*24*60*60
    if syminfo.type == "crypto"
        secondsInYear := 365*24*60*60
    volAnnualisationFactor = math.sqrt(secondsInYear/timeframe.in_seconds())
    
    // vol calcs
    simple_return = (close[0] - close[1])/close[1]
    ewmaVariance = ta.ema(math.pow(simple_return, 2), estimationWdw)
    ewmaVolatility = math.sqrt(ewmaVariance) * volAnnualisationFactor

    ewmaVolatility

// @function Calculates a volatility-targetted position size in number of units
// @param nominalBalance Portfolio size on which to calculate volatility targets
// @param targetVolContribution Amount of volatility to be assigned to this position
// @param forecastVol Volatility forecast to use in position size calculation as % 
// @returns Position size in units (shares, contracts, etc)
export volTargetedSize(float nominalBalance, float targetVolContribution, float forecastVol) =>
    targetPos = nominalBalance / close * 0.01*targetVolContribution/forecastVol  // targetVolContribution input as %
    if syminfo.type == "crypto" 
        targetPos := math.round(targetPos, 5)
    else if syminfo.type == "forex"
        targetPos := math.round(targetPos, 2) 
    else 
        targetPos := math.floor(targetPos)

    targetPos

// example usage
balance = 10000
volEstimationWdw = 30
targetVolContribution = 15
volForecast = ewmaVol(volEstimationWdw)
targetPos = volTargetedSize(balance, targetVolContribution, volForecast)
plot(targetPos, title = "Target position", color = color.rgb(0, 120, 219))

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

Overview

ewmaVol estimates exponentially weighted annualised volatility from squared simple returns and scales it by the square root of 365 days for crypto or 252 days otherwise. volTargetedSize turns a nominal balance, target volatility contribution, and volatility forecast into a unit quantity, rounding crypto and forex sizes and flooring other instruments. Example code at the end of the file plots that target position.

Details

Published by

Robot-Wealth on GitHub

Code credit

robotkris, as written in the script's header

Type

Library, Pine Script v5

Draws

Library (no plots)

Category

Volatility & bands

Markets

Forex, Crypto

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.

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

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

Public

by wanjo-tech
6 stars

This Pine Script v5 library walks historical price, volume, time and amount series until a requested number of hours is covered, stopping at 4999 bars. TimeAligned returns the bar count, net and absolute price changes, net and absolute log-price changes, volum

Library v5 Volatility & bandsVolume
Updated 2 years ago · None stated GitHub repository of Public

Daily Deviation

by Electrified-Trading
2 stars

This library calculates arrays of daily price deviations from the open to the high, low, and close over a user-specified number of days. It optionally filters outliers using a maximum deviation threshold. The fromOpen function returns a normalized value showin

Library v5 Volatility & bandsSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of Daily Deviation

ta

by ivansoft
1 stars

Provides a collection of technical analysis calculation functions for use across Pine scripts. It exports implementations for various indicators and mathematical formulas, including oscillators like the Awesome Oscillator, Aroon, and Schaff Trend Cycle, moving

Library v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ta

CodonATRStop

by codon-pro
1 stars

This library exports a function that returns a dynamic trailing stop price based on Average True Range. For longs it subtracts an ATR multiple from the close and ratchets the level upward, resetting the stop when price closes below the previous level. For shor

Library v6 Volatility & bands
Updated 10 months ago · MIT GitHub repository of CodonATRStop
261 stars

AIActivationFunctionsBipolarSigmoid is a Pine Script library that provides mathematical implementations of the bipolar sigmoid activation function and its derivatives for machine learning algorithms. It calculates bipolar sigmoid values bounded between -1 and

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of AIActivationFunctionsBipolarSigmoid

More libraries

Trade Your Charts With a Regulated Broker

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

Compare brokers