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

//@version=5

// @description Calculate Fibo levels from any 2 levels. Your need know only 2 price of 2 levels for calculate any level of Fibo: function 'fibo_lvl', 
// or calculate array of price Fibo levels : function 'fibo_lvls'
library("Fibo_levels")

// @description Calculate fibo level from any 2 levels of them
// @param fibo_lvl1 First of any level of fibo from 0 to 1 (example 0.236)
// @param price1 Price for 1th any level (example 2356.1)
// @param fibo_lvl2 Second of any level of fibo from 0 to 1 (example 0.382)
// @param price2 Price for 2th any level (example 2497.4)
// @param calc_level Price for level to calculate (example 0.5)
// @returns return price for calc_level fibo
export fibo_lvl(float fibo_lvl1, float price1, float fibo_lvl2, float price2, float calc_level) =>
    down_fibo = fibo_lvl1 > fibo_lvl2 and price1 > price2 ? true : false
	up_fibo = fibo_lvl1 < fibo_lvl2 and price1 < price2 ? true : false
	error = fibo_lvl1 > 1 or fibo_lvl2 > 1 or fibo_lvl1 < 0 or fibo_lvl2 < 0 or (up_fibo and down_fibo) or (not up_fibo and not down_fibo) ? true : false
	delta_lvl = not error and down_fibo ? fibo_lvl1 - fibo_lvl2 : not error and up_fibo ? fibo_lvl2 - fibo_lvl1 : na
	delta_price = not error and down_fibo ? price1 - price2 : not error and up_fibo ? price2 - price1 : na
	fibo_delta_price = delta_price / delta_lvl
    lvl_0 = not error and up_fibo ? price1 - fibo_delta_price * fibo_lvl1 : not error and down_fibo ? price1 + fibo_delta_price * fibo_lvl1 : na
    lvl_1 = not error and up_fibo ? lvl_0 + fibo_delta_price : not error and down_fibo ? lvl_0 - fibo_delta_price : na

    price_calc_level = not na(lvl_0) and up_fibo ? lvl_0 + calc_level * fibo_delta_price : not na(lvl_0) and down_fibo ? lvl_0 - calc_level * fibo_delta_price : na


// @description Calculate all fibo levels from any 2 levels of them
// @param fibo_lvl1 First of any level of fibo from 0 to 1 (example 0.236)
// @param price1 Price for 1th any level (example 2356.1)
// @param fibo_lvl2 Second of any level of fibo from 0 to 1 (example 0.382)
// @param price1 Price for 2th any level (example 2497.4)
// @returns array of price for fibo levels : (0.0, 0.118, 0.236, 0.384, 0.5, 0.618, 0.786, 1.0, 1.27,-0.27,1.618,-0.618)
export fibo_lvls(float fibo_lvl1, float price1, float fibo_lvl2, float price2) =>   
	levels = array.from(0.0, 0.118, 0.236, 0.384, 0.5, 0.618, 0.786, 1.0, 1.27,-0.27,1.618,-0.618)
    out = array.new_float(10)

    for [index,lvl] in levels
        _level = array.get(levels, index)
        array.push(out, fibo_lvl(fibo_lvl1, price1, fibo_lvl2, price2, _level))
    out


      
    

