FRAMA and Candlestick Patterns [CSM]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chhagansinghmeena

//@version=5
indicator('FRAMA and Candlestick Patterns [CSM]', shorttitle='CSM FRAMA', overlay=true)
import chhagansinghmeena/BankNifty_CSM/2 as CM
// Input parameters
src = input.source(title = "FRAMA Source", defval = close)
length = input.int(title='Length', defval=20, minval=1, maxval=200)
fracDim = input.float(title='Fractal Dimension', defval=1.0, minval=0.1, maxval=2.0)
engF = input.bool(title = "Add Engulfing Candle Filter", defval = false)
// Calculate the FRAMA
framaCalculate(src, length, mult) =>
// Define the FRAMA function using a loop
    alpha = 2 / (length + 1)
    sum_wt = 0.0
    sum_wt_src = 0.0
    for i = 0 to length - 1 by 1
        weight = math.exp(math.log(mult) * i * i / (length * length))
        sum_wt += weight
        sum_wt_src += weight * src[length - 1 - i]
        sum_wt_src
    frama_value = sum_wt_src / sum_wt
    frama_value

frama = framaCalculate(src, length, fracDim)

get_EngulfimgBullish_Detection()=>
    isEngulf = open[1] > close[1] ? close > open ? low >=low[1] ? open <= close[1] ? close - open > open[1] - close[1] ? true : false : false : false : false : false

get_EngulfimgBearish_Detection()=>
    isEngulf = open[1] < close[1] ? close < open ? high <=high[1] ? open >= close[1] ? open - close > close[1] - open[1] ? true : false : false : false : false : false

bullishCandle = get_EngulfimgBullish_Detection() 
bearishCandle = get_EngulfimgBearish_Detection()

// Detect bullish and bearish engulfing patterns
bullishEngulfing = bullishCandle  or CM.candlepatternbullish()
bearishEngulfing = bearishCandle  or CM.candlepatternbearish()

// Plot the FRAMA and RSI
plot(frama, color=color.new(color.orange, 0), linewidth=2)

buyFarma = frama < close 
sellFarma = frama > close 

//buy and sell signals based and candlestick patterns
if engF
    buyFarma := buyFarma and bullishEngulfing
    sellFarma := sellFarma and bearishEngulfing

Signal = 0
Signal := buyFarma  ? 1 : sellFarma  ? -1 : nz(Signal[1])
isDifferentSignalType = ta.change(Signal)

buySignal = buyFarma and isDifferentSignalType
sellSignal = sellFarma and isDifferentSignalType
plotshape(buySignal, title='Buy', style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), size=size.small)
plotshape(sellSignal, title='Sell', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), size=size.small)





