```
#
# Hull Moving Average Concavity Divergence
# or
# The Second Derivative of the Hull Moving Average
#
# Author: Seth Urion (Mahsume)
# Version: 2020-02-23 V3
#
# This code is licensed (as applicable) under the GPL v3
#
# ----------------------
declare lower;
input price = CLOSE;
input Divergencelength = 200;
input lookback = 50;
input HMAlength = 200;
input displace = 0;
input EMAlength = 100;
input AEMAlength = 100;
def HMA = HullMovingAvg(length = Divergencelength, price = price);
def delta = HMA[1] - HMA[lookback + 1];
def delta_per_bar = delta / lookback;
def next_bar = HMA[1] + delta_per_bar;
def concavity = if HMA > next_bar then 1 else -1;
plot zero = 0;
zero.setdefaultcolor(color.gray);
zero.setpaintingstrategy(PaintingStrategy.DASHES);
plot divergence = HMA - next_bar;
plot HMA2 = MovingAverage(AverageType.HULL, divergence, HMAlength)[-displace];
assert(HMAlength > 0, "'length' must be positive: " + HMAlength);
def EMA = compoundValue(1, EMA[1] + 2 / (EMAlength + 1) * (divergence[-displace] - EMA[1]), divergence[-displace]);
plot LegacyEMA = EMA;
LegacyEMA.SetDefaultColor(GetColor(1));
input highLowLength = 10;
def multiplier1 = 2 / (AEMAlength + 1);
def multiplier2 = AbsValue((close - Lowest(low, highLowLength)) - (Highest(high, highLowLength) - close)) / (Highest(high, highLowLength) - Lowest(low, highLowLength));
def alpha = multiplier1 * (1 + multiplier2);
def ma = CompoundValue(1, ma[1] + alpha * (divergence - ma[1]), Average(divergence, AEMAlength));
plot AEMA = ma;
AEMA.SetDefaultColor(GetColor(1));
plot cx_up = if divergence crosses above zero then 0 else double.nan;
cx_up.SetPaintingStrategy(PaintingStrategy.POINTS);
cx_up.SetDefaultColor(Color.LIGHT_GREEN);
cx_up.SetLineWeight(4);
plot cx_down = if divergence crosses below zero then 0 else double.nan;
cx_down.SetPaintingStrategy(PaintingStrategy.POINTS);
cx_down.SetDefaultColor(Color.RED);
cx_down.SetLineWeight(4);
divergence.DefineColor("Up", GetColor(1));
divergence.DefineColor("Down", GetColor(0));
divergence.AssignValueColor(if divergence > LegacyEMA then divergence.color("Up") else divergence.color("Down"));
# END
```