BankNifty_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

// @description TODO: add library description here
library("BankNifty_CSM", overlay = true)

// @function TODO: add function description here
// @param x TODO: add parameter x description here
// @returns TODO: add what function returns

cell_upColor()=>
	UPcolor =#4caf50

cell_DWNColor()=>
	UPcolor =#FF5252

cell_transp()=>
	cell_transp = 10

cell_neturalColor()=>
	cell_netural = color.gray


getAllPrices()=>
    prevClose = nz(close[1])
    prevOpen = nz(open[1])
    prevHigh = nz(high[1])
    prevLow = nz(low[1])
    currClose = close
    currOpen = open
    currHigh = high
    currLow = low

    [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow]   

//Thanks to LUXALGO for the gradient idea
// This gradient idea i took from '[LUX] Adjustable MA & Alternating Extremities'
export getGradientColor(bool isFirstbar = false, float src = close, simple int length = 50, float beta = 0.5, bool isSmoothed = true)=>
    var os = 0
    var b = array.new_float(0)
    var css = array.new_color(0)
    if isFirstbar
        for i = 0 to length - 1 by 1
            x = i / (length - 1)
            w = math.avg(math.atan(2 * math.pi * (1 - math.pow(x, beta))) , math.sin(2 * math.pi * (1 - math.pow(x, beta))))
            array.push(b, w)
        array.push(css, #FF1100),array.push(css, #FF1200),array.push(css, #FF1400),array.push(css, #FF1500),array.push(css, #FF1700),array.push(css, #FF1800),array.push(css, #FF1A00),array.push(css, #FF1B00),array.push(css, #FF1D00),array.push(css, #FF1F00),array.push(css, #FF2000),array.push(css, #FF2200),array.push(css, #FF2300),array.push(css, #FF2500),array.push(css, #FF2600),array.push(css, #FF2800),array.push(css, #FF2900),array.push(css, #FF2B00),array.push(css, #FF2D00),array.push(css, #FF2E00),array.push(css, #FF3000),array.push(css, #FF3100),array.push(css, #FF3300),array.push(css, #FF3400),array.push(css, #FF3600),array.push(css, #FF3700),array.push(css, #FF3900),array.push(css, #FF3B00),array.push(css, #FF3C00),array.push(css, #FF3E00),array.push(css, #FF3F00),array.push(css, #FF4100),array.push(css, #FF4200),array.push(css, #FF4400),array.push(css, #FF4500),array.push(css, #FF4700),array.push(css, #FF4900),array.push(css, #FF4A00),array.push(css, #FF4C00),array.push(css, #FF4D00),array.push(css, #FF4F00),array.push(css, #FF5000),array.push(css, #FF5200),array.push(css, #FF5300),array.push(css, #FF5500),array.push(css, #FF5700),array.push(css, #FF5800),array.push(css, #FF5A00),array.push(css, #FF5B00),array.push(css, #FF5D00),array.push(css, #FF5E00),array.push(css, #FF6000),array.push(css, #FF6200),array.push(css, #FF6300),array.push(css, #FF6500),array.push(css, #FF6600),array.push(css, #FF6800),array.push(css, #FF6900),array.push(css, #FF6B00),array.push(css, #FF6C00),array.push(css, #FF6E00),array.push(css, #FF7000),array.push(css, #FF7100),array.push(css, #FF7300),array.push(css, #FF7400),array.push(css, #FF7600),array.push(css, #FF7700),array.push(css, #FF7900),array.push(css, #FF7A00),array.push(css, #FF7C00),array.push(css, #FF7E00),array.push(css, #FF7F00),array.push(css, #FF8100),array.push(css, #FF8200),array.push(css, #FF8400),array.push(css, #FF8500),array.push(css, #FF8700),array.push(css, #FF8800),array.push(css, #FF8A00),array.push(css, #FF8C00),array.push(css, #FF8D00),array.push(css, #FF8F00),array.push(css, #FF9000),array.push(css, #FF9200),array.push(css, #FF9300),array.push(css, #FF9500),array.push(css, #FF9600),array.push(css, #FF9800),array.push(css, #FF9A00),array.push(css, #FF9B00),array.push(css, #FF9D00),array.push(css, #FF9E00),array.push(css, #FFA000),array.push(css, #FFA100),array.push(css, #FFA300),array.push(css, #FFA400),array.push(css, #FFA600),array.push(css, #FFA800),array.push(css, #FFA900),array.push(css, #FFAB00),array.push(css, #FDAC00),array.push(css, #FBAD02),array.push(css, #F9AE03),array.push(css, #F7AE04),array.push(css, #F5AF06),array.push(css, #F3B007),array.push(css, #F1B108),array.push(css, #EFB20A),array.push(css, #EDB30B),array.push(css, #EBB30C),array.push(css, #E9B40E),array.push(css, #E7B50F),array.push(css, #E4B610),array.push(css, #E2B712),array.push(css, #E0B813),array.push(css, #DEB814),array.push(css, #DCB916),array.push(css, #DABA17),array.push(css, #D8BB18),array.push(css, #D6BC1A),array.push(css, #D4BD1B),array.push(css, #D2BD1C),array.push(css, #D0BE1E),array.push(css, #CEBF1F),array.push(css, #CCC020),array.push(css, #C9C122),array.push(css, #C7C223),array.push(css, #C5C224),array.push(css, #C3C326),array.push(css, #C1C427),array.push(css, #BFC528),array.push(css, #BDC62A),array.push(css, #BBC72B),array.push(css, #B9C72C),array.push(css, #B7C82E),array.push(css, #B5C92F),array.push(css, #B3CA30),array.push(css, #B0CB32),array.push(css, #AECC33),array.push(css, #ACCC34),array.push(css, #AACD36),array.push(css, #A8CE37),array.push(css, #A6CF38),array.push(css, #A4D03A),array.push(css, #A2D13B),array.push(css, #A0D13C),array.push(css, #9ED23E),array.push(css, #9CD33F),array.push(css, #9AD440),array.push(css, #98D542),array.push(css, #95D643),array.push(css, #93D644),array.push(css, #91D746),array.push(css, #8FD847),array.push(css, #8DD948),array.push(css, #8BDA4A),array.push(css, #89DB4B),array.push(css, #87DB4C),array.push(css, #85DC4E),array.push(css, #83DD4F),array.push(css, #81DE50),array.push(css, #7FDF52),array.push(css, #7CE053),array.push(css, #7AE054),array.push(css, #78E156),array.push(css, #76E257),array.push(css, #74E358),array.push(css, #72E45A),array.push(css, #70E55B),array.push(css, #6EE55C),array.push(css, #6CE65E),array.push(css, #6AE75F),array.push(css, #68E860),array.push(css, #66E962),array.push(css, #64EA63),array.push(css, #61EA64),array.push(css, #5FEB66),array.push(css, #5DEC67),array.push(css, #5BED68),array.push(css, #59EE6A),array.push(css, #57EF6B),array.push(css, #55EF6C),array.push(css, #53F06E),array.push(css, #51F16F),array.push(css, #4FF270),array.push(css, #4DF372),array.push(css, #4BF473),array.push(css, #48F474),array.push(css, #46F576),array.push(css, #44F677),array.push(css, #42F778),array.push(css, #40F87A),array.push(css, #3EF97B),array.push(css, #3CF97C),array.push(css, #3AFA7E),array.push(css, #38FB7F),array.push(css, #36FC80),array.push(css, #34FD82),array.push(css, #32FE83),array.push(css, #30FF85),
    
    src_sum = 0.0
    for i = 0 to length - 1 by 1
        src_sum += src[i] * array.get(b, i)
        src_sum
    src_sum := src_sum / array.sum(b)
    
    os_css = math.avg(ta.mfi(src_sum, length)/100, ta.rsi(src_sum, length)/100) 
    scale_color = array.get(css, math.round(os_css * 199))
    
    src_sum := isSmoothed ? src_sum : src
    [src_sum, scale_color]


//========== Indicators Logic
getVwapPrediction(openPrice, closePrice, bnfprice, Ex_RS)=>
    //VWAP  
    VWAP = ta.vwap(openPrice)
    trend = closePrice > VWAP ? true : false
    BuySell = trend ? "Buy" : "Sell"
    VWAP_Color = trend ? color.new( cell_upColor() ,cell_transp()) : color.new( cell_DWNColor() ,cell_transp()) 
    bank_rs = ta.vwap(ta.change(closePrice), 14) / ta.vwap(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1
    bank_rs := bank_rs + Ex_RS
    [VWAP_Color, BuySell, bank_rs]

getEMA_20_Prediction(closePrice,bnfprice, Ex_RS)=>
    //EMA  
    EMA = ta.ema(closePrice, 20)
    trend = closePrice > EMA ? true : false
    BuySell = trend ? "Buy" : "Sell"
    bank_rs = ta.ema(ta.change(closePrice), 14) / ta.ema(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1
    bank_rs := bank_rs + Ex_RS
    [trend, BuySell, bank_rs]

export getADX_Prediction(float highPrice = high, float lowPrice = low)=>
    tr = ta.rma(ta.tr(true), 14)
    dmplus = ta.rma(math.max(highPrice - highPrice[1], 0), 17)
    dmminus = ta.rma(math.max(lowPrice[1] - lowPrice, 0), 17)
    dip = 100 * dmplus / tr
    din = 100 * dmminus / tr
    dx = 100 * math.abs(dip - din) / (dip + din)
    adx = ta.ema(dx, 14)
    
    var ADXColor = color.white
    var ADXText = ''

    if adx >= 35 and dmplus > dmminus
        ADXColor:= color.new( cell_upColor() ,cell_transp())
        ADXText:= 'Buy+++'
    else if adx >= 35 and dmplus < dmminus
        ADXColor:= color.new( cell_DWNColor() ,cell_transp())
        ADXText:= 'Sell---'    
    else if adx >= 30 and dmplus > dmminus
        ADXColor:= color.new( cell_upColor() ,cell_transp())
        ADXText:= 'Buy ++'
    else if adx >= 30 and dmplus < dmminus
        ADXColor:= color.new( cell_DWNColor() ,cell_transp())
        ADXText:= 'Sell--'
    if adx >= 25 and dmplus > dmminus
        ADXColor:= color.new( cell_upColor() ,cell_transp())
        ADXText:= 'Buy+'
    else if adx >= 25 and dmplus < dmminus
        ADXColor:= color.new( cell_DWNColor() ,cell_transp())
        ADXText:= 'Sell-'    
    else if adx < 25 and adx >= 20 and dmplus > dmminus
        ADXColor:= color.new( color.orange ,cell_transp())
        ADXText:= 'Buy'
    else if adx < 25 and adx >= 20 and dmplus < dmminus
        ADXColor:= color.new( color.orange ,cell_transp())
        ADXText:= 'Sell'    
    else if adx < 20 and adx > 15
        ADXColor:= color.new( cell_neturalColor() ,cell_transp()) 
        ADXText:= '-' 
    else if adx <= 15     
        ADXColor:= color.new( cell_neturalColor() ,cell_transp()) 
        ADXText:= '-'  

    [ADXColor, ADXText]

export get_RSI_Prediction(float closePrice=close, float bnfprice = close, int Ex_RS = 0)=>
    //RSI  
    RSI = ta.rsi(closePrice,14)
    // Generate buy and sell signals
    buy_signal = RSI > 50  and RSI < 70 //RSI < 70 and RSI > 30 and RSI > 50
    sell_signal = RSI < 50 and RSI > 30 //and RSI < 30 and RSI < 50
    BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-'
    RSi_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) 

    switch
        RSI > 25 and RSI < 50 => 
            BuySell := 'Oversold'
            RSi_Color := color.new( color.red , 0)
        RSI > 15 and RSI < 25=> 
            BuySell := 'Oversold+'
            RSi_Color := color.new(#650808, cell_transp())
        RSI < 15=> 
            BuySell := 'Ex-Oversold'
            RSi_Color := color.new(#650808, 0)
        RSI < 75 and RSI > 50 =>
            BuySell := 'Overbought'
            RSi_Color := color.new( color.green , 0)
        RSI < 85 and RSI > 75 => 
            BuySell := 'Overbought++'
            RSi_Color := color.new(#2f59c5, cell_transp())
        RSI > 85 => 
            BuySell := 'Ex-Overbought'
            RSi_Color := color.new(#6b2fc5, 0)
    BuySell := str.tostring(RSI,'#')       
    bank_rs = ta.rsi(ta.change(closePrice), 14) / ta.rsi(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1
    bank_rs := bank_rs + Ex_RS
    [RSi_Color, BuySell, bank_rs]

export get_MFI_Prediction(float hlc3Price = hlc3, float bnfprice = close,int Ex_RS = 0)=>
    //MFI 
    MFI = ta.mfi(hlc3Price, 14)
    // Generate buy and sell signals
    buy_signal =  MFI > 50  and MFI < 75
    sell_signal = MFI < 50 and MFI > 25 
    BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-'
    MFi_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) 
    
    switch
        MFI > 20 and MFI < 50 => 
            BuySell := 'Oversold'
            MFi_Color := color.new( color.red , 0)
        MFI > 10 and MFI < 20=> 
            BuySell := 'Oversold+'
            MFi_Color := color.new(#650808, cell_transp())
        MFI < 10=> 
            BuySell := 'Ex-Oversold'
            MFi_Color := color.new(#650808, 0)
        MFI < 80 and MFI > 50=>
            BuySell := 'Overbought'
            MFi_Color := color.new( color.green , 0)
        MFI > 80 and MFI < 90=> 
            BuySell := 'Overbought+'
            MFi_Color := color.new(#2f59c5, cell_transp())
        MFI > 90 => 
            BuySell := 'Ex-Overbought'
            MFi_Color := color.new(#6b2fc5, 0) 

    BuySell := str.tostring(MFI,'#')
    bank_rs = ta.mfi(ta.change(hlc3Price), 14) / ta.mfi(ta.change(bnfprice), 14) * 100 > 0 ? 1 : -1
    bank_rs := bank_rs + Ex_RS
    [MFi_Color, BuySell, bank_rs]
   
get_Alligator_Prediction(hl2Alligs, closePrice)=>
    // Alligator
    jawLen = 13
    teethLen = 8
    lipsLen = 5

    jaw = ta.sma(hl2Alligs, jawLen)
    teeth = ta.sma(hl2Alligs, teethLen)
    lips = ta.sma(hl2Alligs, lipsLen)

    buyAlligator = lips > teeth and teeth > jaw and closePrice > lips
    sellAlligator = lips < teeth and teeth < jaw and closePrice < lips
    BuySell = buyAlligator ? "Buy" : sellAlligator ? "Sell" : 'Sleep'
    Alligator_Color = buyAlligator ? color.new( cell_upColor() ,cell_transp()) : sellAlligator ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) 
    [Alligator_Color, BuySell]


get_MACD_Prediction(closePrice)=>
// Calculate the MACD and signal line
    [macdLine, signalLine, histLine] = ta.macd(closePrice, 12, 26, 9)
    // Generate buy and sell signals
    buy_signal = macdLine > signalLine //  ta.crossover(macdLine, signalLine)
    sell_signal = macdLine < signalLine // ta.crossunder(macdLine, signalLine)
    BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-'
    MACD_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) 
    [MACD_Color, BuySell]

export frama_Calculation(float src = close,int length = 21, float mult = 1.0) =>
// 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

export CSM_CPMA(simple int length=21, float price = close, float HL2 = hl2,float Open = open , float High = high, float Low = low, float OHLC4 = ohlc4, float HLC3 = hlc3, float HLCC4 = hlcc4)=>
    // Calculate the average of the last 21 candles for each price type
    price_avg = ta.ema(price, length) 
    HL2_avg =  ta.sma(HL2, length)
    Open_avg = ta.ema(Open, length) 
    High_avg =  ta.sma(High, length) 
    Low_avg = ta.ema(Low, length)
    OHLC4_avg =  ta.sma(OHLC4, length)
    HLC3_avg = ta.ema(HLC3, length) 
    HLCC4_avg = ta.sma(HLCC4, length)

    // Calculate the average of the price types
    price_average = (price_avg + HL2_avg + Open_avg + High_avg + Low_avg + OHLC4_avg + HLC3_avg + HLCC4_avg) / 8
    price_average := na(price_average[1]) ? price_average : price_average[1] + (price - price_average[1]) / (length * math.pow(price/price_average[1], 4))    

    price_average

get_FARMA_Prediction(closePrice,  bnfprice, Ex_RS)=>
    // Calculate the FRAMA
    frama_value = frama_Calculation(closePrice, 16, 1)
    // Generate buy and sell signals
    buy_signal = closePrice > frama_value //ta.crossover(closePrice, frama_value)
    sell_signal = closePrice < frama_value //ta.crossunder(closePrice, frama_value)
    BuySell = buy_signal ? "Buy" : sell_signal ? "Sell" : '-'
    FARMA_Color = buy_signal ? color.new( cell_upColor() ,cell_transp()) : sell_signal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) 
    bank_rs = frama_Calculation(ta.change(closePrice),16,1) / frama_Calculation(ta.change(bnfprice), 16, 1) * 100 > 0 ? 1 : -1
    bank_rs := bank_rs + Ex_RS
    [FARMA_Color, BuySell, bank_rs]

// Thanks For TradingView
// The same on Pine Script™
pine_supertrend(factor, atrPeriod, hl2Price, closePrice) =>
    src = hl2Price
    atr = ta.atr(atrPeriod)
    upperBand = src + factor * atr
    lowerBand = src - factor * atr
    prevLowerBand = nz(lowerBand[1])
    prevUpperBand = nz(upperBand[1])

    lowerBand := lowerBand > prevLowerBand or closePrice[1] < prevLowerBand ? lowerBand : prevLowerBand
    upperBand := upperBand < prevUpperBand or closePrice[1] > prevUpperBand ? upperBand : prevUpperBand
    int direction = na
    float superTrend = na
    prevSuperTrend = superTrend[1]
    if na(atr[1])
        direction := 1
    else if prevSuperTrend == prevUpperBand
        direction := closePrice > upperBand ? -1 : 1
    else
        direction := closePrice < lowerBand ? 1 : -1
    superTrend := direction == -1 ? lowerBand : upperBand
    [superTrend, direction]

get_SuperTrend_Prediction(factor, atrPeriod, hl2Price, closePrice)=>
    //Supertrend
    [superTrend, dir] = pine_supertrend(factor, atrPeriod, hl2Price, closePrice)    
    
    buySignal =  dir < 0
    sellSignal = dir > 0

    BuySell = buySignal ? "Buy" : sellSignal ? "Sell" : '-'
    ST_Color = buySignal ? color.new( cell_upColor() ,cell_transp()) : sellSignal ? color.new( cell_DWNColor() ,cell_transp()) : color.new( cell_neturalColor() ,cell_transp()) 
    [ST_Color, BuySell]


// For first symbol
export getLtp_N_Chang(float openPrice = open, float closePrice = close, float highPrice = high, float hl2Price = hl2, float lowPrice = low, float hlc3Price = hlc3,float stockLastClosePrice = close,float bankNiftyClose = close)=>
	
	ts1 = closePrice 
    ts1C = stockLastClosePrice
    ts1Chng = (ts1-ts1C)
    ts1p = (ts1-ts1C)*100/ts1C
  
    [VWAPColor, VWAPText, Vwap_bnf] = getVwapPrediction(openPrice = openPrice, closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = 0)
    [trend, BuySell, EMA_bnf] = getEMA_20_Prediction(closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = Vwap_bnf )
    [ADXColor, ADXText] = getADX_Prediction(highPrice = highPrice, lowPrice = lowPrice)
    [RSIColor, RSIText, RSI_bnf] = get_RSI_Prediction(closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = EMA_bnf)
    [MFIColor, MFIText, MFI_bnf] = get_MFI_Prediction(hlc3Price = hlc3Price, bnfprice = bankNiftyClose, Ex_RS = RSI_bnf)
    [AllG_Color, AllG_Text] = get_Alligator_Prediction(hl2Alligs = hl2Price, closePrice = closePrice) 
    [MACD_Color, MACDText] = get_MACD_Prediction(closePrice = closePrice) 
    [FARMA_Color, FARMAText, FARMA_bnf] = get_FARMA_Prediction(closePrice = closePrice, bnfprice = bankNiftyClose, Ex_RS = MFI_bnf)
    [ST_Color_21, ST_Text_21] = get_SuperTrend_Prediction(factor=1, atrPeriod=21, hl2Price=hl2Price, closePrice=closePrice)
    [ST_Color_14, ST_Text_14] = get_SuperTrend_Prediction(factor=2, atrPeriod=14, hl2Price=hl2Price, closePrice=closePrice)
    [ST_Color_10, ST_Text_10] = get_SuperTrend_Prediction(factor=3, atrPeriod=10, hl2Price=hl2Price, closePrice=closePrice)

    // FARMA_bnf := ADXText == 'Buy' or ADXText == 'Buy+' or ADXText == 'Buy++' or ADXText == 'Buy+++' ? FARMA_bnf + 1 : ADXText == 'Sell' or ADXText == 'Sell-' or ADXText == 'Sell--' or ADXText == 'Sell---' ? FARMA_bnf - 1 : FARMA_bnf
    // FARMA_bnf := AllG_Text == 'Buy' ? FARMA_bnf + 1 : AllG_Text == 'Sell' ? FARMA_bnf - 1 : FARMA_bnf
    // FARMA_bnf := MACDText == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1
    // FARMA_bnf := ST_Text_21 == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1
    // FARMA_bnf := ST_Text_14 == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1
    // FARMA_bnf := ST_Text_10 == 'Buy' ? FARMA_bnf + 1 : FARMA_bnf - 1
    
    // Calculate the RS ratio
    rs_ratio = closePrice / bankNiftyClose

    // Calculate the moving average of the RS ratio over 20 periods
    rs_ma = ta.sma(rs_ratio, 20)
    // Plot buy/sell signals based on the RS comparison
    buy = rs_ratio > rs_ma
    sell = rs_ratio < rs_ma
    
    RS_Text = buy ? "Buy" : sell ?  "Sell" : '-'
    RS_Color = buy ? color.new( cell_upColor() ,cell_transp()) : sell ? color.new( cell_DWNColor() ,cell_transp()) :  color.new( cell_neturalColor() ,cell_transp())

    [ts1, ts1Chng, ts1p, VWAPColor, VWAPText, trend, BuySell, ADXColor, ADXText, RSIColor, RSIText, MFIColor, MFIText, AllG_Color, AllG_Text, MACD_Color, MACDText, FARMA_Color, FARMAText, ST_Color_21, ST_Text_21, ST_Color_14, ST_Text_14, ST_Color_10, ST_Text_10, RS_Text, RS_Color]    

//Thanks For Trading For Candlistick Pattern ditection script
//This is totaly depend on inbuilt candlistic patters script by TRADINGVIEW, i am adding few modification.
//Thanks for tradingview for candlestick pattern script,
funcGetCandlebaseConfiguration(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5,int C_Factor = 2)=>
   
    [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices()
    
    C_BodyHi = math.max(currClose, currOpen)
    C_BodyLo = math.min(currClose, currOpen)
    C_Body = C_BodyHi - C_BodyLo
    C_BodyAvg = ta.ema(C_Body, C_Len)
    C_SmallBody = C_Body < C_BodyAvg
    C_LongBody = C_Body > C_BodyAvg
    C_UpShadow = currHigh - C_BodyHi
    C_DnShadow = C_BodyLo - currLow
    C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
    C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
    C_WhiteBody = currOpen < currClose
    C_BlackBody = currOpen > currClose
    C_Range = currHigh - currLow
    C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
    C_BodyMiddle = C_Body / 2 + C_BodyLo
    C_ShadowEquals = C_UpShadow == C_DnShadow or math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100 < C_ShadowEqualsPercent and math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100 < C_ShadowEqualsPercent
    C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
    C_Doji = C_IsDojiBody and C_ShadowEquals 

    [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody,  C_Doji]

// Define a function to detect bullish engulfing patterns
export candlepatternbullish(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5)=>

    [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody,  C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = 2)

    [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices()

    IsBullish = prevClose < prevOpen and currClose > currOpen and currClose > prevOpen and currOpen < prevClose and currHigh > prevHigh and currLow < prevLow
    //1
    IsAlternativeBullish = prevOpen > prevClose ? currClose > currOpen ? currLow >=prevLow[1] ? currOpen <= prevClose[1] ? prevOpen - currOpen > prevOpen[1] - prevClose[1] ? true : false : false : false : false : false
    //2
    engulfing = C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and currClose >= prevOpen[1] and currOpen <= prevClose[1] and (currClose > prevOpen[1] or currOpen < prevClose[1])
    //3. Rising Window
    risingWindow =  C_Range != 0 and C_Range[1] != 0 and currLow > prevHigh
    //4.  Rising 3 methods
    risingMethods = C_LongBody[4] and C_WhiteBody[4] and C_SmallBody[3] and C_BlackBody[3] and open[3] < high[4] and close[3] > low[4] and C_SmallBody[2] and C_BlackBody[2] and open[2] < high[4] and close[2] > low[4] and C_SmallBody[1] and C_BlackBody[1] and prevOpen < high[4] and prevClose > low[4] and C_LongBody and C_WhiteBody and currClose > close[4]
    //5. Up Side Tuski
    up_Tuski = C_LongBody[2] and C_SmallBody[1] and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_WhiteBody[1] and C_BlackBody and C_BodyLo >= C_BodyHi[2] and C_BodyLo <= C_BodyLo[1]
    //6. MarooBhuju
    C_MarubozuShadowPercentWhite = 5.0
    marubozuWhiteBullish = C_WhiteBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentWhite / 100 * C_Body and C_DnShadow <= C_MarubozuShadowPercentWhite / 100 * C_Body and C_WhiteBody
    //7 Dragon Fly Doji
    dragonflyDojiBullish = C_IsDojiBody and C_UpShadow <= C_Body

    IsBullish := IsBullish or IsAlternativeBullish or engulfing or risingWindow or risingMethods or up_Tuski or marubozuWhiteBullish or dragonflyDojiBullish 
    
    IsBullish

// Define a function to detect bearish engulfing patterns
export candlepatternbearish(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5) =>
    
    [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody,  C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = 2)

    [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices()
    
    IsBearish = prevClose > prevOpen and currClose < currOpen and currClose < prevOpen and currOpen > prevClose and currHigh > prevHigh and currLow < prevLow

    isAlternativeBearish = prevOpen < prevClose ? currClose < currOpen ? currHigh <=prevHigh ? currOpen >= prevClose ? currOpen - currClose > prevClose - prevOpen ? true : false : false : false : false : false
    //1. Falling Window
    fallingWindow = C_Range != 0 and C_Range[1] != 0 and currHigh < prevLow
    //2. Falling Three Methods
    falling_3_Methods = C_LongBody[4] and C_BlackBody[4] and C_SmallBody[3] and C_WhiteBody[3] and open[3] > low[4] and close[3] < high[4] and C_SmallBody[2] and C_WhiteBody[2] and open[2] > low[4] and close[2] < high[4] and C_SmallBody[1] and C_WhiteBody[1] and prevOpen > low[4] and prevClose < high[4] and C_LongBody and C_BlackBody and currClose < close[4]
    //3. Down Side Tuski
    dwn_Tuski = C_LongBody[2] and C_SmallBody[1] and C_BlackBody[2] and C_BodyHi[1] < C_BodyLo[2] and C_BlackBody[1] and C_WhiteBody and C_BodyHi <= C_BodyLo[2] and C_BodyHi >= C_BodyHi[1]
    //4. MarooBhuju
    C_MarubozuShadowPercentBearish = 5.0
    marubozuBlackBearish = C_BlackBody and C_LongBody and C_UpShadow <= C_MarubozuShadowPercentBearish / 100 * C_Body and C_DnShadow <= C_MarubozuShadowPercentBearish / 100 * C_Body and C_BlackBody
    //5. Gravestone Doji
    gravestoneDojiBearish = C_IsDojiBody and C_DnShadow <= C_Body
    //6. Dark Cloud Cover
    dark_CC = C_WhiteBody[1] and C_LongBody[1] and C_BlackBody and currOpen >= prevHigh and currClose < C_BodyMiddle[1] and currClose > prevOpen

    IsBearish := IsBearish or isAlternativeBearish or fallingWindow or falling_3_Methods or dwn_Tuski or marubozuBlackBearish or gravestoneDojiBearish or dark_CC

    IsBearish


export BullishCandlePatternOnDownTrend(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5,int C_Factor = 2) =>
    
    [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody,  C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = C_Factor)
    
    [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices()

    Bullish = false
    //1
    hammer = C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow
     //2 Bullish Hammer
    C_BullishHammer = C_LongBody and C_HasDnShadow and not C_HasUpShadow and C_WhiteBody and C_Doji and C_IsInsideBar and C_DnShadow > C_Factor * C_BodyAvg
    //3.  Tweezer Bottom
    tw_Bottom = (not C_IsDojiBody or C_HasUpShadow and C_HasDnShadow) and math.abs(currLow - prevLow) <= C_BodyAvg * 0.05 and C_BlackBody[1] and C_WhiteBody and C_LongBody[1]
    //4. Doji Star Bullish
    dj_Star = C_BlackBody[1] and C_LongBody[1] and C_IsDojiBody and C_BodyHi < C_BodyLo[1]
    //5. Morning Star Doji
    mrng_StraDoji = C_LongBody[2] and C_IsDojiBody[1] and C_LongBody and C_BlackBody[2] and C_BodyHi[1] < C_BodyLo[2] and C_WhiteBody and C_BodyHi >= C_BodyMiddle[2] and C_BodyHi < C_BodyHi[2] and C_BodyHi[1] < C_BodyLo 
    //6. Pearsing Bulish
    pearcing_Bullish = C_BlackBody[1] and C_LongBody[1] and C_WhiteBody and currOpen <= prevLow and currClose > C_BodyMiddle[1] and currClose < prevOpen
    //7. Inverted Hammer
    inver_Hammer = C_SmallBody and C_Body > 0 and C_BodyHi < hl2 and C_UpShadow >= C_Factor * C_Body and not C_HasDnShadow
    
    Bullish := hammer or C_BullishHammer or tw_Bottom or dj_Star or mrng_StraDoji or pearcing_Bullish or inver_Hammer

    Bullish


export BearishCandlePatternOnUpTrend(simple int C_Len = 14,float C_ShadowPercent = 5, float C_ShadowEqualsPercent = 100, float C_DojiBodyPercent = 5,int C_Factor = 2) =>
    
    [C_BodyHi, C_BodyLo, C_Body, C_BodyAvg, C_SmallBody, C_LongBody, C_UpShadow, C_DnShadow, C_HasUpShadow, C_HasDnShadow, C_WhiteBody, C_BlackBody, C_Range, C_IsInsideBar, C_BodyMiddle, C_ShadowEquals, C_IsDojiBody,  C_Doji] = funcGetCandlebaseConfiguration(C_Len = C_Len, C_ShadowPercent = C_ShadowPercent, C_ShadowEqualsPercent = C_ShadowEqualsPercent, C_DojiBodyPercent = C_DojiBodyPercent, C_Factor = C_Factor)
    [prevClose, prevOpen, prevHigh, prevLow, currClose, currOpen, currHigh, currLow] = getAllPrices()
    //1.Tweezer Top\nTweezer Top
    dwn_tweezer = (not C_IsDojiBody or C_HasUpShadow and C_HasDnShadow) and math.abs(currHigh - prevHigh) <= C_BodyAvg * 0.05 and C_WhiteBody[1] and C_BlackBody and C_LongBody[1]
   //2. dark_cloud_cover
    dark_cloud_cover = currOpen > currClose and currClose < C_BodyMiddle[1] - 0.5 * C_BodyAvg
    //3. Evening Doji Star
    evn_Doji = C_LongBody[2] and C_IsDojiBody[1] and C_LongBody and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_BlackBody and C_BodyLo <= C_BodyMiddle[2] and C_BodyLo > C_BodyLo[2] and C_BodyLo[1] > C_BodyHi
    //4. Doji Star Bearish
    doji_Star = C_WhiteBody[1] and C_LongBody[1] and C_IsDojiBody and C_BodyLo > C_BodyHi[1]
    //5. Hanging Man
    hang_man = C_SmallBody and C_Body > 0 and C_BodyLo > hl2 and C_DnShadow >= C_Factor * C_Body and not C_HasUpShadow
    //6. Shooting Star
    shoot_Star = C_SmallBody and C_Body > 0 and C_BodyHi < hl2 and C_UpShadow >= C_Factor * C_Body and not C_HasDnShadow
    //7.  Evening Star
    evening_Star = C_LongBody[2] and C_SmallBody[1] and C_LongBody and C_WhiteBody[2] and C_BodyLo[1] > C_BodyHi[2] and C_BlackBody and C_BodyLo <= C_BodyMiddle[2] and C_BodyLo > C_BodyLo[2] and C_BodyLo[1] > C_BodyHi
    //8. Harami Bearish
    haramiBearish = C_LongBody[1] and C_WhiteBody[1] and C_BlackBody and C_SmallBody and currHigh <= C_BodyHi[1] and currLow >= C_BodyLo[1]


    Bearish = dwn_tweezer or dark_cloud_cover or evn_Doji or doji_Star or hang_man or shoot_Star or evening_Star or haramiBearish

    Bearish

export entryExitinStrategy(bool longCondition = false, bool shortCondition = false, bool window = false, float longTakeProfit = 10.0, float shortTakeProfit = 10.0, float LossstratA = 100.0, float trailingTakeProfit = 0.5) =>

    float longStopLossprice = na
    float longTakeProfitPrice = na
    float shortStopLossprice = na
    float shortTakeProfitPrice = na

    bool openLongPosition = window and (longCondition or strategy.position_size > 0)
    bool openShortPosition = window and (shortCondition or strategy.position_size < 0)

    longIsActive = openLongPosition 
    shortIsActive = openShortPosition 

    longTakeProfitPerc = longTakeProfit/close
    shortTakeProfitPerc = shortTakeProfit/close
    trailingTakeProfitPerc =  trailingTakeProfit == 0.01 ? syminfo.mintick/close : trailingTakeProfit/close 

    //Long Stop Loss added
    longStopLossprice := if longIsActive 
        if openLongPosition and not (strategy.opentrades.size(strategy.opentrades - 1) > 0)
            low - LossstratA
        else
            nz(longStopLossprice[1], low  - longStopLossprice)
    else
        na  

    //Long Take Profir Added
    longTakeProfitPrice := if longIsActive 
        if openLongPosition and not (strategy.position_size > 0)
            close * (1 + longTakeProfitPerc)
        else
            nz(longTakeProfitPrice[1], close + longTakeProfitPerc)
    else
        na

    //Short StopLoss added
    shortStopLossprice := if shortIsActive 
        if openShortPosition and not (strategy.opentrades.size(strategy.opentrades - 1) < 0)
            high + LossstratA
        else
            nz(shortStopLossprice[1], high * (1 + shortStopLossprice))
    else
        na 

    //Short Take profit added
    shortTakeProfitPrice := if shortIsActive 
        if openShortPosition and not (strategy.position_size < 0)
            close * (1 - shortTakeProfitPerc)
        else
            nz(shortTakeProfitPrice[1], close * (1 - shortTakeProfitPrice))
    else
        na

    float longTrailingTakeProfitStepTicks = longTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick
    float shortTrailingTakeProfitStepTicks = shortTakeProfitPrice * trailingTakeProfitPerc / syminfo.mintick

    if window
        switch
            longCondition =>  strategy.entry("Long", strategy.long)
            shortCondition =>  strategy.entry("Short", strategy.short)

        strategy.exit(id = 'Long Take Profit', from_entry = 'Long', profit = high + longTakeProfitPrice, trail_price =  longTakeProfitPrice , trail_offset =  longTrailingTakeProfitStepTicks  , stop = longStopLossprice)
        strategy.exit(id = 'Short Take Profit', from_entry = 'Short', profit = low + shortTakeProfitPrice, trail_price =  shortTakeProfitPrice , trail_offset =  shortTrailingTakeProfitStepTicks, stop = shortStopLossprice)
    