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

//@version=5
library(title='FunctionIntrabarCrossValue')

import RicardoSantos/FunctionForecastLinear/1 as lin

// @function Find the minimum difference of a intrabar cross and return its median value.
// @param a float, series a.
// @param b float, series b.
// @param step float, step to iterate x axis, default=0.01
// @returns float
export intrabar_cross_value(float a, float b, float step=0.01) => //{
    if ta.cross(a, b)
        array<float> _x = array.from(0.0, 1.0)
        array<float> _a = array.from(a, a[1])
        array<float> _b = array.from(b, b[1])
        float _previous_min = na
        float _mina = na
        float _minb = na
        for _i = step to 1.0 by step
            float _ai = lin.forecast(_x, _a, _i)
            float _bi = lin.forecast(_x, _b, _i)
            float _diff = _ai > _bi ? _ai - _bi : _bi - _ai
            switch 
                na(_previous_min) => _previous_min := _diff , continue
                _diff <= _previous_min => 
                    _previous_min := _diff
                    _mina := _ai
                    _minb := _bi
        (_mina + _minb) / 2
//}

float sma1 = ta.sma(close, 10)
float sma2 = ta.sma(close, 20)

float x = intrabar_cross_value(sma1, sma2)

plot(series=sma1, title='', color=color.orange)
plot(series=sma2, title='', color=color.red)
plot(series=x, title='', color=color.blue, style=plot.style_cross, linewidth=2)
plot(series=fixnan(x), title='', color=color.teal)
