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

//@version=5

// @description simple_squares_regression: simple squares regression algorithm to find the horizontal price region
library("simple_squares_regression", overlay=true)

// @function basic_ssr: Basic simple squares regression algorithm
// @param series float src: the regression source such as close
// @param series int region_forward: number of candle lines at the right end of the regression region from the current candle line
// @param series int region_len: the length of regression region
// @returns left_loc, right_loc, reg_val, reg_std, reg_max_offset
export basic_ssr(series float src, series int region_forward, series int region_len) =>
	p = array.new_float(region_len, 0)
	
	//init array
	for i = 0 to region_len - 1
	    array.set(p, i, src[region_len - 1 + region_forward - i])
	
	//get average and standard devition value
	u = array.avg(p)
	s = array.stdev(p)
	
    //get regression left location, left value, right location, right value
	x1 = region_len - 1 + region_forward
	x2 = 0
	
	[x1, x2, u, s]

// @function search_ssr: simple squares regression region search algorithm
// @param series float src: the regression source such as close
// @param series int max_forward: max number of candle lines at the right end of the regression region from the current candle line
// @param series int region_lower: the lower length of regression region
// @param series int region_upper: the upper length of regression region
// @returns left_loc, right_loc, reg_val, reg_level, reg_std_err, reg_max_offset
export search_ssr(series float src, series int max_forward, series int region_lower, series int region_upper) =>
	int x1 = 0
    int x2 = 0
    float u = 0
    float s = 1e10
    
    for f = 0 to max_forward
        for i = region_lower to region_upper
            [_x1, _x2, _u, _s] = basic_ssr(src, f, i)
            if s > _s
                x1 := _x1
                x2 := _x2
                u := _u
                s := _s
                
	[x1, x2, u, s]
