# Quadratic_Regression_Inflection input length = 60; #input crossingType = {default above, below}; def bn = BarNumber(); def lastBar = HighestAll(if IsNaN(close) then 0 else bn); def x = bn; def y = close; # calculate conditioning constant; input lengthHLVol = 10; input rangeMin = 1; input rangeMax = 5; def HLVol = ExpAverage(Highest(high, lengthHLVol) - Lowest(low, lengthHLVol), lengthHLVol) / ExpAverage(close, lengthHLVol); def hhHLVol = HighestAll(HLVol); def llHLVol = LowestAll(HLVol); def HLVolnormalized = (((rangeMax - rangeMin) * (HLVol - llHLVol)) / (hhHLVol - llHLVol)) + rangeMin; # calculate conditioned length def n = IsNaN(HLVolnormalized[-1]) and !IsNaN(HLVolnormalized); def m = if n then HLVolnormalized else 0; def fixedm = HighestAll(m); def lengthAdjusted = Round(length / fixedm, 0); # calculate sumation values def startBar = lastBar - (lengthAdjusted - 1); def sumX = if bn < startBar then 0 else x + sumX[1]; def sumY = if bn < startBar then 0 else y + sumY[1]; def sumX2 = if bn < startBar then 0 else Power(x, 2) + sumX2[1]; def sumX3 = if bn < startBar then 0 else Power(x, 3) + sumX3[1]; def sumX4 = if bn < startBar then 0 else Power(x, 4) + sumX4[1]; def sumXY = if bn < startBar then 0 else x * y + sumXY[1]; def sumX2Y = if bn < startBar then 0 else Power(x, 2) * y + sumX2Y[1]; # intermediary calculations def xx = sumX2 - Power(sumX, 2) / lengthAdjusted; def xy = sumXY - (sumX * sumY / lengthAdjusted); def xx2 = sumX3 - (sumX2 * sumX / lengthAdjusted); def x2y = sumX2Y - (sumX2 * sumY / lengthAdjusted); def x2x2 = sumX4 - (Power(sumX2, 2) / lengthAdjusted); # calculate coefficients for the quadratic equation def a0 = (x2y * xx - xy * xx2) / (xx * x2x2 - Power(xx2, 2)); def b0 = (xy * x2x2 - x2y * xx2) / (xx * x2x2 - Power(xx2, 2)); def c0 = sumY / lengthAdjusted - b0 * sumX / lengthAdjusted - a0 * sumX2 / lengthAdjusted; # for a, b, and c use the final value on the last bar of the chart for all calculations def a = GetValue(a0, bn - lastBar); def b = GetValue(b0, bn - lastBar); def c = GetValue(c0, bn - lastBar); # calculate and plot parabola and slope inflection point #plot parabola = if bn < startBar then Double.NaN else a * Power(x, 2) + b * x + c; def zero = 0; def slope = if bn < startBar then Double.NaN else 2 * a * x + b; plot crossinglow = Crosses(slope, zero, CrossingDirection.ABOVE); plot crossinghigh = Crosses(slope, zero, CrossingDirection.BELOW); AssignBackgroundColor(if crossinglow == 1 then color.GREEN else color.WHITE); AssignBackgroundColor(if crossinghigh == 1 then color.RED else color.WHITE);