Library · Pine Script v5 · Library

Averages

by Electrified-Trading

Averages is a Pine Script utility library designed for computing custom averages directly from float arrays.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code144
Settings0inputs
LicenceMPL-2.0
Last update1 year ago7 Jul 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 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

144 lines of Pine Script v5 from Averages.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

Averages.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Electrified (electrifiedtrading)

// @version=5
// @description Contains utilities for generating averages from arrays.  Useful for manipulated or cleaned data.
library('Averages', true)


///////////////////////////////////////////////////
// @function Calculates the triangular weighted average of a set of values where the last value has the highest weight.
// @param src The array to derive the average from.
// @param startingWeight The weight to begin with when calculating the average.  Higher numbers will decrease the bias.
export triangular(
  float[] src,
  simple int startingWeight = 1) =>
    var float notAvailable = na
    len = array.size(src)
    if len == 0
        notAvailable
    else
        sum = 0.0
        total = 0
        for i = 0 to len - 1
            s = array.get(src, i)
            if not na(s)
                m = i + startingWeight // triangular multiple
                total += m
                sum += s * m
        total == 0 ? na : sum/total
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Calculates the weighted average of a set of values.
// @param src The array to derive the average from.
// @param weights The array containing the weights for the source.
// @param weightDefault The default value to use when a weight is NA. 
export weighted(
  float[] src,
  float[] weights,
  simple float weightDefault = na) =>
    var float notAvailable = na
    len = array.size(src)
    if len == 0
        notAvailable
    else if len > array.size(weights)
        runtime.error("Weight array is shorter than the source.")
        notAvailable    
    else
        sum = 0.0
        total = 0.0
        for i = 0 to len - 1
            s = array.get(src, i)
            if not na(s)
                m = array.get(weights, i)
                if na(m) and not na(weightDefault)
                    m := weightDefault
                if not na(m)
                    total += m
                    sum += s * m
        total == 0 ? na : sum/total
///////////////////////////////////////////////////


///////////////////////////////////////////////////
// @function Calculates the weighted average of a set of values where the last value has the highest triangular multiple.
// @param src The array to derive the average from.
// @param weights The array containing the weights for the source.
// @param startingMultiple The multiple to begin with when calculating the average.  Higher numbers will decrease the bias.
export triangularWeighted(
  float[] src,
  float[] weights,
  simple float weightDefault = na,
  simple int startingMultiple = 1) =>
    var float notAvailable = na
    len = array.size(src)
    if len == 0
        notAvailable
    else if len > array.size(weights)
        runtime.error("Weight array is shorter than the source.")
        notAvailable    
    else
        sum = 0.0
        total = 0.0    
        for i = 0 to len - 1
            s = array.get(src, i)
            if not na(s)
                w = array.get(weights, i)
                if na(w) and not na(weightDefault)
                    w := weightDefault
                if not na(w)
                    m = i + startingMultiple // triangular multiple
                    wm = w * m
                    total += wm
                    sum += s * wm
        total == 0 ? na : sum/total
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Calculates the exponential average of a set of values where the last value has the highest weight.
// @param src The array to derive the average from.
export exponential(float[] src) =>
    len = array.size(src)
    if len == 0
        na // Return 'na' if the array is empty
    else
        float s = na
        float alpha = 2 / (len + 1)
        float a1 = 1 - alpha
        float ema = na // Initialize the EMA variable
        for i = 0 to len - 1
            v = array.get(src, i)
            if not na(v)
                s := v
            if not na(s)
                ema := na(ema) ? s : alpha * v + a1 * ema
        ema // Return the final EMA value
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Creates an array from the provided series (oldest to newest).
// @param src The array to derive from.
// @param len The target length of the array.
// @param omitNA If true, NA values will not be added to the array and the resultant array may be shorter than the target length.
export arrayFrom(
  series float src,
  simple int len,
  simple bool omitNA = false) =>
    var a = omitNA ? array.new_float() : array.new_float(len, na)
    if not omitNA or not na(src)
        array.push(a, src)
    if not omitNA or array.size(a) > len
        array.shift(a)
    a
///////////////////////////////////////////////////


// Demo
ema = exponential(arrayFrom(close, 60))
hlc3Array = arrayFrom(hlc3, 60)
volArray = arrayFrom(volume, 60)
vawma = triangularWeighted(hlc3Array, volArray)

plot(ema, 'ema(60)', color.red)
plot(vawma, 'vawma(60)', color.purple)

Overview

Averages provides exportable functions to calculate triangular weighted averages, standard weighted averages using an auxiliary weight array, and combined triangular weighted averages. The functions support handling missing values, optional default fallback weights, and configurable starting weights to adjust recency bias. As a helper library, it does not produce trading signals or render plots directly on the chart.

Details

Published by

Electrified-Trading on GitHub

Draws

Library (no plots)

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.

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

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

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 4 days ago · MIT GitHub repository of KernelFunctions

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

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

Mylib

by ferranbt
21 stars

This script serves as a minimal utility library written in Pine Script v6. It provides an exported helper function that calculates the sum of two numeric arguments. As a reusable code library, it produces no visual plots, charts, or trading signals, and it con

Library v6
Updated 7 weeks ago · MPL-2.0 GitHub repository of Mylib

HLevel

by stupenkov
14 stars

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts. It defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot

Library v5
Updated 3 years ago · None stated GitHub repository of HLevel

More libraries

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