[pshaiCmd] Indicator Memory

stable
By pshai in Other Published December 2021 👁 1,438 views 💬 0 comments

Description

A memory for custom indicator calculations and other things that might cause "repaint of history". A good example of this "repaint" issue would be when you calculate EMA(c, 20) on "this" update, and EMA(c, 10) on the next (i.e. variable period length). So to overcome this issue with changing history, this command lets you do this:

-- Load prices
local o = OpenPrices()
local h = HighPrices()

-- Calculate EMA using Adaptive Period length
local ema = CC_OptimalIndicator(
    -- memory is not used in this calculation, as we do not use previous values for our calculations
    function(i, memory)
        local c = c[i]
        local o = o[i]
        local period = CC_AdaptivePeriod(o, c, 3, 20, 5, 20)

        return ArrayGet(EMA(c, period), 1)
    end
)
So the command takes in a callback function, and it is called with an input for an index (which is used for the offset step in warmup period). You can also do calculations that require the previously calculated values to be known by accessing the second input parameter in your callback function (named "memory" in the example above). Adaptive period command: https://www.haasscripts.com/t/pshaicmd-adaptive-period-length/
HaasScript
-- [pshaiCmd] Indicator Memory
-- Author: pshai

DefineCommand('IndicatorMemory', 'A memory for custom indicator calculations and other things that might cause "repaint of history"')

local func = DefineParameter(CallbackType, 'func', '', true, |x|x)
local warmupLen = DefineParameter(NumberType, 'warmupLen', '', false, 50)

local memory = Load('mem', HNC(warmupLen, 0))

local function parse(v)
    local t = GetType(v)

    if (t == ArrayDataType
    or t == UserDataDataType)
    and Count(v) > 0
    then
        return ArrayGet(v, 1)
    
    else
        return v
    end
end

if Count(memory) == 0 then
    LogWarning('warmup indicator...')
    for i = warmupLen-1, 1, -1
    do
        local v = func(i, memory)
        
        memory[i] = parse(v)
    end
else
    local v = func(1, memory)
    memory = Grab(ArrayUnshift(memory, parse(v)), 0, 1000)
end

Save('mem', memory)


DefineOutput(ListNumberType, memory)

0 Comments

Sign in to leave a comment.

No comments yet. Be the first!