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

//@version=5

// @description merge_pinbar: merge bars and check whether the bar is a pinbar
library("merge_pinbar", overlay=true)

// @function merge_pinbar: merge bars and check whether the bar is a pinbar
// @param simple int period: the statistic bar period
// @param simple int max_bars: the max bars to be merged
// @returns array: [bar_type, bar_num, pbar_strength]
export merge_pinbar(simple int period, simple int max_bars) =>
    float upperwick = open > close ? high - open: high - close
    float lowerwick = open > close ? close - low: open - low
    float candlebody = open > close ? open - close: close - open
    float totalbody = high - low
    
    float upperwick_ma = ta.sma(upperwick, period)
    float lowerwick_ma = ta.sma(lowerwick, period)
    float candlebody_ma = ta.sma(candlebody, period)
    float totalbody_ma = ta.sma(totalbody, period)
    
    int pbar_type = 0
    int pbar_num = 0
    float pbar_strength = 0.0
    for bars = 1 to max_bars
        float _open = open[bars - 1]
        float _high = ta.highest(high, bars)
        float _low = ta.lowest(low, bars)
        float _close = close
        
        float _upperwick = _open > _close ? _high - _open: _high - _close
        float _lowerwick = _open > _close ? _close - _low: _open - _low
        float _candlebody = _open > _close ? _open - _close: _close - _open
        float _totalbody = _high - _low
        
        float _upperwick_ratio  = _upperwick / upperwick_ma
        float _lowerwick_ratio  = _lowerwick / lowerwick_ma
        float _candlebody_ratio = _candlebody / candlebody_ma
        float _totalbody_ratio = _totalbody / totalbody_ma
        
        if _candlebody_ratio < 3.0 and _upperwick_ratio < 2.0 and  _lowerwick / _candlebody > 2.0
            pbar_type := 1
            pbar_num := bars
            pbar_strength := math.log(_lowerwick / _candlebody - _upperwick / _candlebody * 2.0) * _totalbody_ratio
            break
            
        else if _candlebody_ratio < 3.0 and _lowerwick_ratio < 2.0 and _upperwick / _candlebody > 2.0
            pbar_type := -1
            pbar_num := bars
            pbar_strength := math.log(_upperwick / _candlebody - _lowerwick / _candlebody * 2.0) * _totalbody_ratio
            break
        else
            continue
    
    [pbar_type, pbar_num, pbar_strength]