SumOfCandles
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boitoki

//@version=5

// @description This function returns sum of candlestick's body.
library("SumOfCandles", overlay=false)

f_madev (v, m) => ((v - m) / m) * 100

// @function This function returns a value without any post-processing.
// @param _open Source
// @param _close Source
// @param _len Period
export simple_sum (float _open, float _close, int _len) => math.sum(_close - _open, _len)

// @function This function returns a value without any post-processing.
// @param _int Period
export simple_sum (int _len) => math.sum(close - open, _len)

// @function Returns the sum of candlestick body.
// @param _open Source
// @param _close Source
// @param _len Period
// @param _malen MA Period
// @param _usema A flag of using MA
// @returns sum
export calc (float _open, float _close, int _len, simple int _malen, bool _usema = true) =>
    sum = ta.rma(ta.rma(simple_sum(_open, _close, _len), 2), 2)

    oc2 = math.avg(_open, _close)

    f = ta.rma(oc2, 2)
    s = ta.rma(oc2, _malen)
    d = _usema ? f_madev(f, s) : 0

    res = sum + d
    
    [res, ta.change(res)]

// @function Returns the sum of candlestick body.
// @param _len Period
// @param _malen MA period
// @param _usema A flag of using MA
// @returns sum
export calc (int _len, simple int _malen = 1, bool _usema = true) =>
    sum = ta.rma(ta.rma(simple_sum(open, close, _len), 2), 2)    

    oc2 = math.avg(open, close)

    f = ta.rma(oc2, 2)
    s = ta.rma(oc2, _malen)
    d = _usema ? f_madev(f, s) : 0

    res = sum + d
    
    [res, ta.change(res)]


[sum, sum_changed] = calc(3, 14, true)

barcolor = sum > 0 
  ? sum_changed > 0 ? color.green     : color.from_gradient(60, 0, 100, color.green, color.black)
  : sum_changed < 0 ? color.red       : color.from_gradient(60, 0, 100, color.red, color.black)

barcolor(barcolor)
hline(0)
plot(sum, color=barcolor, style=plot.style_columns)