Guppy Strategy Trading Bot Using Python and Zerodha

This is a programming lesson. So there will be very less amount of explanation and more code. If you’re stuck somewhere, feel free to comment. 

Trading Bot

What is a Trading Bot?

A trading bot is an automated software program that interacts directly with financial exchanges (often using API’s to obtain and interpret relevant information) to effectively conduct trades on behalf of the user. Its primary function is to make trading decisions based on predefined criteria or the analysis of market data, without the need for human intervention.

The main advantage of using a trading bot is its ability to perform rapid, accurate, and emotion-free trades. It operates continuously, which means it can take advantage of opportunities any time of the day or night, far beyond the capabilities of a human trader.

In the last chapter, We have coded the screener of this strategy. Now, We will see the code of the Trading bot of the same strategy.

Key Components of the Guppy Strategy in the Code:

Buy and Sell Conditions as per the Code Logic:

  • Buy Condition: A buy signal is typically identified when the short-term (fast) EMAs cross above the long-term (slow) EMAs. This crossing indicates a potential upward trend in the stock price. Additionally, the code may include conditions where the current price is higher than some of the short-term EMAs, suggesting increasing bullish sentiment.

  • Sell Condition: A sell signal is detected when the short-term EMAs cross below the long-term EMAs, indicating a potential downward trend. Similarly, a condition where the current price is lower than some of the short-term EMAs can also suggest a bearish trend.

Additional Aspects of the Strategy in the Code:

  • Color Coding: The code may employ color coding (like green for buy, red for sell) for easier visualization of the trends based on the EMA crossovers.

  • Breakout Identification: The strategy can include logic to identify breakouts, where the stock price moves outside a defined range, signaling a stronger buy or sell opportunity.

  • Data and Time Frame: The code processes historical data for various time frames (like 5 minutes, 15 minutes, 30 minutes) to apply the Guppy strategy effectively.

Python Code

In practice, the Guppy strategy is used not just to determine entry or exit points, but also to gauge the strength and sustainability of the trend. It’s particularly favored in swing trading and day trading due to its effectiveness in short to medium time frames.

				
					from datetime import date, timedelta
import pandas as pd
from pytz import timezone

print("  \t \t \t \t \t \n WELCOME TO GUPPY BOT ")
print("\n" )
scan=str(input("DO you want Scanning ? YES/NO :-")).upper()
if "YES"==scan or "yes"==scan:
    buy_sell=str(input("ENTER which bot you want to run ? ")).upper()
    if "BUY" ==buy_sell:
        print("BUY BOT STARTED")
        time_frame     =str(input("Enter TimeFrame"))
        sdate = (date.today() - timedelta(days=15)).strftime("%Y-%m-%d")
        todate = date.today().strftime("%Y-%m-%d")
        print("SCANNING START")
        z=list(set(instrumentList[instrumentList['segment'] == 'NFO-FUT']["name"].to_list()))
        eexchange="NSE"
        tokenall=[] 
        aa=0
        print("  \t \t \t \n Getting All tokens for processing BUY SELL ")
        while(True):
            ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+z[aa])).iloc[-2,0])
            tokenall.append(ttoken)
            aa=aa+1
            if aa==50:
                print("  \t \t \t \n Complete ! All tokens are fetched from file ")
                print("\n" )
                print(tokenall)
                break
        print(" Now checking Condition of BUY sell of GUPPY ")
        #Variables
        buy5minute=[]
        sell5minute=[]
        buy10minute=[]
        sell10minute=[]
        buy15minute=[]
        sell15minute=[]
        ##
        lst_candle=[]
        lst_heikin_nor=[]
        lst_heikin=[]
        lst_cand=[]
        lst_c=[]
        anchor=0
        countstart=0
        #programe start
        a=0
        #:sell10minutesym,"TOKENS_SELL":sell10minute,"Price":price15min_sell}
        BUY_listindicator=[]
        SELL_listindicator=[]
        sell5minutesym=[]
        buy5minutesym=[]
        buy10minutesym=[]
        sell10minutesym=[]
        buy15minutesym=[]
        sell15minutesym=[]
        #
        #price
        price5min_buy=[]
        price5min_sell=[]
        price15min_buy=[]
        price15min_sell=[]
        price30min_buy=[]
        price30min_sell=[]
        priceedit=[]
        print(a)
        def ashi():
            global a
            global BUY_listindicator
            global SELL_listindicator
            while(True):
                    print("\n" )
                    print("Current Token Number which is processing is",a)
                #km=datetime.now().minute
                #ks=datetime.now().second
                #if km%1==0 and ks==1:
                    clear_output(wait=True)  
                    now_utc = datetime.now(timezone('UTC'))
                    now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                    now_asia = now_asia.strftime("%S ")
                    klp1=now_asia
                    #df=kite.historical_data(140033,sdate,todate,time_frame,0)
                    dff=kite.historical_data(tokenall[a],sdate,todate,time_frame,0)
                    dfw=pd.DataFrame(dff)
                    df=pd.DataFrame(dfw[['date','open','high','low','close']])
                    slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                    fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                    def EMA(df, base, target, period, alpha=False):
                        con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                        if (alpha == True):
                            # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                            df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                        else:
                            # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                            df[target] = con.ewm(span=period, adjust=False).mean()
                        df.fillna(0,inplace = True)
                    #     return df
                    for j in slow_ema:
                        val = "ema"+"_"+str(j)
                        EMA(df,"close",val,j)
                    for k in fast_ema:
                        val = "ema"+"_"+str(k)
                        EMA(df,"close",val,k)
                    def super_guppy(interval,df,anchor=0):
                    #     df['buy'] = 0
                    #     df['sell'] = 0
                    #     df['buybreak'] = 0
                    #     df['sellbreak'] = 0
                        anchor = 0
                        ShowBreak = True
                        ShowSwing = True
                        ShowCon = False
                        uOCCswing = False
                        Lookback = 6
                        emaFilter = False
                        mult = 0
                        buybreak = 0
                        sellbreak = 0
                        buy_barssince_var = 0
                        sell_barssince_var = 0
                        buybreak_barssince_var = 0
                        sellbreak_barssince_var = 0
                        barssince_lst = list()
                        barssince_var = 0
                        bar_count_var = 0
                        buy1 = list()
                        sell1 = list()
                        buy2 = list()
                        sell2 = list()
                        buybreak1 = list()
                        sellbreak1 = list()
                        def barssince(b,barssince_var):
                            barssince_lst = []
                            barssince_var = 0 
                            new_var = len(b)
                            for i in b[::-1]:
                                if i == 1:
                                    break
                                barssince_lst.append(i)
                            barssince_var = len(barssince_lst)
                            return barssince_var
                            barssince_lst.clear()
                        #isIntraday
                        if interval < 1441 :
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                mult = 1
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = 1
                        #isIntraday Not
                        if interval > 1441:
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                mult = mult
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = mult
                        mult = 1
                        for i in range(len(df)):
                            emaF1 = df.loc[i,'ema_3']
                            emaF2 = df.loc[i,'ema_5']
                            emaF3 = df.loc[i,'ema_7']
                            emaF4 = df.loc[i,'ema_9']
                            emaF5 = df.loc[i,'ema_11']
                            emaF6 = df.loc[i,'ema_13']
                            emaF7 = df.loc[i,'ema_15']
                            emaF8 = df.loc[i,'ema_17']
                            emaF9 = df.loc[i,'ema_19']
                            emaF10 = df.loc[i,'ema_21']
                            emaF11 = df.loc[i,'ema_23']
                            emaS1 = df.loc[i,'ema_25']
                            emaS2 = df.loc[i,'ema_28']
                            emaS3 = df.loc[i,'ema_31']
                            emaS4 = df.loc[i,'ema_34']
                            emaS5 = df.loc[i,'ema_37']
                            emaS6 = df.loc[i,'ema_40']
                            emaS7 = df.loc[i,'ema_43']
                            emaS8 = df.loc[i,'ema_46']
                            emaS9 = df.loc[i,'ema_49']
                            emaS10 = df.loc[i,'ema_52']
                            emaS11 = df.loc[i,'ema_55']
                            emaS12 = df.loc[i,'ema_58']
                            emaS13 = df.loc[i,'ema_61']
                            emaS14 = df.loc[i,'ema_64']
                            emaS15 = df.loc[i,'ema_67']
                            emaS16 = df.loc[i,'ema_70']
                            ema200 = df.loc[i,'ema_200'] 
                            emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                            emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                            #Fast EMA Color Rules
                            colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                            colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                            #Slow EMA Color Rules
                            colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                            colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                            if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                if int(buy1[-1]) > 0:
                                    buy = buy1[-1] + 1
                                else:
                                    buy = 1
                            else:
                                buy = 0
                            buy1.append(buy)
                            if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                if int(sell1[-1]) > 0:
                                    sell = sell1[-1] + 1
                                else:
                                    sell = 1
                            else:
                                sell = 0
                            sell1.append(sell)
                            #buy
                            if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                buy3 = 1
                            else:
                                buy3 = buy
                            buy2.append(buy3)
                            #sell    
                            if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                sell3 = 1
                            else:
                                sell3 = sell
                            sell2.append(sell3)
                            #buybreak
                            if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                if buybreak1[-1] > 0:
                                    buybreak = buybreak1[-1] + 1
                                else:
                                    buybreak = 1
                            else:
                                buybreak = 0
                            buybreak1.append(buybreak)
                            if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                if sellbreak1[-1] > 0:
                                    sellbreak = sellbreak1[-1]+1
                                else:
                                    sellbreak = 1
                            else:
                                sellbreak = 0
                            sellbreak1.append(sellbreak)
                            #arrow plotting
                            #buy_arrow
                            buy_barssince_var = barssince(buy2[:-1],barssince_var)
                            if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                buy_arrow = 1
                            else:
                                buy_arrow = 0
                            #sell arrow
                            sell_barssince_var = barssince(sell2[:-1],barssince_var)
                            if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                sell_arrow = 1
                            else:
                                sell_arrow = 0
                            #buybreak_arrow
                            buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                            sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                            if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                buybreak_arrow = 1
                            else:
                                buybreak_arrow = 0
                            #sellbreak_arrow
                            if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                sellbreak_arrow = 1
                            else:
                                sellbreak_arrow = 0
                            if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'green'
                            elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'red'
                            elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                arrow_color = 'aqua'
                            elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                arrow_color = 'blue'
                            else:
                                arrow_color = 'none'
                            df.loc[i,'arrow_color'] = arrow_color
                        df = df[['date','open','high','low','close','arrow_color']]
                        return df
                    df=super_guppy(15,df)
                    gup=df
                    print(" \t \t \t \t Zerodha GUPPY SCREENER on 5 minute Data")
                    print("\t \t \t \n Current Token checking  " , tokenall[a])
                    print("\n" )
                    print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                    if "green" in gup.iloc[-1,5]:
                        print(" BUY stock found ")
                        buy5minute.append((tokenall[a]))
                        buy5minutesym.append((z[a]))
                        price5min_buy.append(gup.iloc[-1,2])
                    if "red" in gup.iloc[-1,5]:
                        print(" SELL stock found ")
                        sell5minute.append((tokenall[a]))
                        sell5minutesym.append((z[a]))
                        price5min_sell.append(gup.iloc[-1,2])
                    else:
                        pass
                    print("Buy stock found  are  :="  ,buy5minute)
                    print("Sell stocks found  are:="  ,sell5minute)
                    a=a+1
                    if a==len(tokenall):
                        break
        ashi()
        less_then_buy=[]
        greater_then_buy=[]
        less_then_sell=[]
        greater_then_sell=[]
        symbl_final_buy=[]
        token_final_buy=[]
        print(" Scanning is complete ")
        buyframe={"Tokens_buy":buy5minute,"Symbol_buy":buy5minutesym,"Price":price5min_buy}
        fivemin=pd.DataFrame(buyframe)
        display(fivemin)
        buyframee={"Tokens_sell":sell5minutesym,"Symbols_sell" :sell5minute,"Price":price5min_sell}
        fivemine=pd.DataFrame(buyframee)
        display(fivemine)
        if buy5minute:
            print("YES ! Some buy stock found")
            aa=0
            while(True):
                kk=pd.DataFrame(kite.ltp(buy5minute[aa])).iloc[-1,0]             
                if kk<2000:
                    less_then_buy.append(buy5minute[aa])
                if kk>2000:
                    greater_then_buy.append(buy5minute[aa])
                aa=aa+1
                if aa==len(buy5minute):
                    break
        if sell5minute:
            print("yes ! some sell tock found")
            aa=0
            while(True):
                kk=pd.DataFrame(kite.ltp(sell5minute[aa])).iloc[-1,0]
                if kk<2000:
                    less_then_sell.append(sell5minute[aa])
                if kk>2000:
                    greater_then_sell.append(sell5minute[aa])
                aa=aa+1
                if aa==len(sell5minute):
                    break
        print("BUY LESS THEN 2000"   ,less_then_buy)
        print("BUY grater then 2000" ,greater_then_buy)

        print("SELL less then 2000"  ,less_then_sell)
        print("SELL GREATER THEN 2000",greater_then_sell)
#greater_then_sell
        if less_then_buy:
            print("Going to Place order  on ",less_then_buy[0])
            order_place_token=less_then_buy[0]
            order_place=int(order_place_token)
            print("BUY COMMON FOUND")
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==order_place]
            symbl_final_buy.append(zall.iloc[-1,0])
            token_final_buy.append(zall.iloc[-1,1])     
            ########################################
            ttradingsymbol =str(symbl_final_buy)
            eexchange      ="NSE"
            productt       ="MIS"
            qu             =1
            time_frame     =time_frame
            sdate          ="2019-06-05"
            todate         ="2020-10-02"
            print(ttoken)
            print(type(ttoken))
            ttoken         =int(token_final_buy[0])
            #############################
            #calculation
            def avg_ha(x):
                a=list(modf(round(x,3)))
                d=str(a[0])
                aa=str(d[0:2])
                try:
                    ab=str(d[2])
                except:
                    ab='0'
                try:
                    ac=str(d[3])
                except:
                    ac='0'
                try:
                    ad=str(d[4])
                except:
                    ad='0'
                c=aa+ab+ac+ad
                b=0
                if a[0]!=0:
                    astr=c
                    a0=astr[0]
                    a1=astr[1]
                    a3=int(astr[2])
                    a2=int(astr[3:5])
                    if a2>=0 and a2<25:
                        a2=0
                    elif a2>=25 and a2<75:
                        a2=5
                    elif a2>=75 and a2<=99:
                        a3+=1
                        a2=0
                    aint=a0+a1+str(a3)+str(a2)
                    a[0]=float(aint)
                for k in a:
                    b+=k
                return b
            counter_start=[0]
            linkedlist_1=[]       
            linkedlist_2=[]      
            linkedlist_3=[]      
            counter=[0,10] 
            execution=[]
            checkfirst=[0]   
            red_time=[]
            green_time=[]
            redb=[]             
            bluez=[]            
            aqua1=[0]           
            bluein=[]           
            blue_2F=[]          
            blue_2G=[]          
            count_sectime=[]
            redc=[]
            colourstill=[]
            prog_starts=[]
            #Variables
            lst_candle=[]
            lst_heikin_nor=[]
            lst_heikin=[]
            lst_cand=[]
            lst_c=[]
            countstart=0
            #programe start
            def ashis():
                while(True):
                    km=datetime.now().minute
                    ks=datetime.now().second
                    if km%1==0 and ks==1:
                        clear_output(wait=True)  
                        now_utc = datetime.now(timezone('UTC'))
                        now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                        now_asia = now_asia.strftime("%S ")
                        klp1=now_asia
                        dff=kite.historical_data(ttoken,sdate,todate,time_frame,0)
                        #time.sleep(1)
                        dfw=pd.DataFrame(dff)[:-1]
                        df=pd.DataFrame(dfw[['date','open','high','low','close']])
                        slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                        fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                        def EMA(df, base, target, period, alpha=False):
                            con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                            if (alpha == True):
                                # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                                df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                            else:
                                # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                                df[target] = con.ewm(span=period, adjust=False).mean()
                            df.fillna(0,inplace = True)
                        #     return df
                        for j in slow_ema:
                            val = "ema"+"_"+str(j)
                            EMA(df,"close",val,j)
                        for k in fast_ema:
                            val = "ema"+"_"+str(k)
                            EMA(df,"close",val,k)
                        def super_guppy(interval,df,anchor=0):
                        #     df['buy'] = 0
                        #     df['sell'] = 0
                        #     df['buybreak'] = 0
                        #     df['sellbreak'] = 0
                            anchor = 0
                            ShowBreak = True
                            ShowSwing = True
                            ShowCon = False
                            uOCCswing = False
                            Lookback = 6
                            emaFilter = False
                            mult = 0
                            buybreak = 0
                            sellbreak = 0
                            buy_barssince_var = 0
                            sell_barssince_var = 0
                            buybreak_barssince_var = 0
                            sellbreak_barssince_var = 0
                            barssince_lst = list()
                            barssince_var = 0
                            bar_count_var = 0
                            buy1 = list()
                            sell1 = list()
                            buy2 = list()
                            sell2 = list()
                            buybreak1 = list()
                            sellbreak1 = list()
                            def barssince(b,barssince_var):
                                barssince_lst = []
                                barssince_var = 0 
                                new_var = len(b)
                                for i in b[::-1]:
                                    if i == 1:
                                        break
                                    barssince_lst.append(i)
                                barssince_var = len(barssince_lst)
                                return barssince_var
                                barssince_lst.clear()
                            #isIntraday
                            if interval < 1441 :
                                if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                    mult = 1
                                else:
                                    if round(anchor/interval) > 1:
                                        mult = round(anchor/interval)
                                    else:
                                        mult = 1
                            else:
                                mult = 1
                            #isIntraday Not
                            if interval > 1441:
                                if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                    mult = mult
                                else:
                                    if round(anchor/interval) > 1:
                                        mult = round(anchor/interval)
                                    else:
                                        mult = 1
                            else:
                                mult = mult
                            mult = 1
                            for i in range(len(df)):
                                emaF1 = df.loc[i,'ema_3']
                                emaF2 = df.loc[i,'ema_5']
                                emaF3 = df.loc[i,'ema_7']
                                emaF4 = df.loc[i,'ema_9']
                                emaF5 = df.loc[i,'ema_11']
                                emaF6 = df.loc[i,'ema_13']
                                emaF7 = df.loc[i,'ema_15']
                                emaF8 = df.loc[i,'ema_17']
                                emaF9 = df.loc[i,'ema_19']
                                emaF10 = df.loc[i,'ema_21']
                                emaF11 = df.loc[i,'ema_23']
                                emaS1 = df.loc[i,'ema_25']
                                emaS2 = df.loc[i,'ema_28']
                                emaS3 = df.loc[i,'ema_31']
                                emaS4 = df.loc[i,'ema_34']
                                emaS5 = df.loc[i,'ema_37']
                                emaS6 = df.loc[i,'ema_40']
                                emaS7 = df.loc[i,'ema_43']
                                emaS8 = df.loc[i,'ema_46']
                                emaS9 = df.loc[i,'ema_49']
                                emaS10 = df.loc[i,'ema_52']
                                emaS11 = df.loc[i,'ema_55']
                                emaS12 = df.loc[i,'ema_58']
                                emaS13 = df.loc[i,'ema_61']
                                emaS14 = df.loc[i,'ema_64']
                                emaS15 = df.loc[i,'ema_67']
                                emaS16 = df.loc[i,'ema_70']
                                ema200 = df.loc[i,'ema_200'] 
                                emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                                emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                                #Fast EMA Color Rules
                                colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                                colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                                #Slow EMA Color Rules
                                colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                                colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                                if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                    if int(buy1[-1]) > 0:
                                        buy = buy1[-1] + 1
                                    else:
                                        buy = 1
                                else:
                                    buy = 0
                                buy1.append(buy)
                                if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                    if int(sell1[-1]) > 0:
                                        sell = sell1[-1] + 1
                                    else:
                                        sell = 1
                                else:
                                    sell = 0
                                sell1.append(sell)
                                #buy
                                if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                    buy3 = 1
                                else:
                                    buy3 = buy
                                buy2.append(buy3)
                                #sell    
                                if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                    sell3 = 1
                                else:
                                    sell3 = sell
                                sell2.append(sell3)
                                #buybreak
                                if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                    if buybreak1[-1] > 0:
                                        buybreak = buybreak1[-1] + 1
                                    else:
                                        buybreak = 1
                                else:
                                    buybreak = 0
                                buybreak1.append(buybreak)
                                if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                    if sellbreak1[-1] > 0:
                                        sellbreak = sellbreak1[-1]+1
                                    else:
                                        sellbreak = 1
                                else:
                                    sellbreak = 0
                                sellbreak1.append(sellbreak)
                                #arrow plotting
                                #buy_arrow
                                buy_barssince_var = barssince(buy2[:-1],barssince_var)
                                if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                    buy_arrow = 1
                                else:
                                    buy_arrow = 0
                                #sell arrow
                                sell_barssince_var = barssince(sell2[:-1],barssince_var)
                                if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                    sell_arrow = 1
                                else:
                                    sell_arrow = 0
                                #buybreak_arrow
                                buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                                sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                                if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                    buybreak_arrow = 1
                                else:
                                    buybreak_arrow = 0
                                #sellbreak_arrow
                                if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                    sellbreak_arrow = 1
                                else:
                                    sellbreak_arrow = 0
                                if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                    arrow_color = 'green'
                                elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                    arrow_color = 'red'
                                elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                    arrow_color = 'aqua'
                                elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                    arrow_color = 'blue'
                                else:
                                    arrow_color = 'none'
                                df.loc[i,'arrow_color'] = arrow_color
                            df = df[['date','open','high','low','close','arrow_color']]
                            return df
                        df=super_guppy(15,df)
                        gup=pd.DataFrame(df)
                        def bidatrema(df,period):
                            df['hl']=abs(df['high']-df['low'])
                            df['hpc']=abs(df['high']-df['close'].shift())
                            df['lpc']=abs(df['low']-df['close'].shift())
                            df['tr']=df[['hl','hpc','lpc']].max(axis=1)
                            df['ATR']=pd.DataFrame.ewm(df["tr"], span=period,min_periods=period).mean()
                            df.drop(["hl","hpc","lpc","tr"],axis = 1 , inplace =True)
                        bidatrema(gup,14)
                        print(" \n \t \t \t \t  GUPPY GREEN _ RED PROFIT BOOKING  ")
                        print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                        now_utc = datetime.now(timezone('UTC'))
                        now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                        now_asia = now_asia.strftime("%Y-%m-%d _ %H:%M:%S ")
                        klp1=now_asia
                        prog_starts.append(klp1)
                        print("\n ")
                        print("Zerodha GUPPY SELL BOT start Time             "  , prog_starts[0])
                        print("\n ")
                        print("BOT working succeesfully on time:             "  , now_asia )
                        print("\n ")
                        print("Trading symbol is",ttradingsymbol,"Token is",ttoken,"Exchange is",eexchange,"and product type is",productt,"Quantity is",qu,"time frame for Historical Data is",time_frame,"Starting and Ending Date of Historical Data is",sdate,todate)
                        colourstill.append(gup.iloc[-1,5])
                        print(" \n ")
                        print("  Completed with 'GREEN' entry=", len(green_time))
                        print("  Completed with 'RED'   entry=", len(red_time))
                        print("\n ")
                        print("\n ")
                        if 0 in counter_start:
                            if "green" in gup.iloc[-1,5]:
                                counter_start.remove(0)
                                counter_start.append(1)
                            else:
                                pass
                        if 2 in counter_start:
                            print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                            if "red" in gup.iloc[-1,5]:
                                if 0 in counter:
                                    quant=qu
                                    xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                    price_sell=avg_ha(xa)
                                    xb=price_sell-float(gup.iloc[-1,6])*0.1
                                    triger_sell=avg_ha(xb)
                                    triggerprice_sell=avg_ha(triger_sell)
                                    kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price= price_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="testR")
                                    print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and price is",price_sell, "quantity is",quant)
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(0)
                                    counter.append(1)
                            if 1 in counter:
                                print("checking red execution")
                                update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                match_in_int=int(match_in)
                                print("checking executed or not condition ")
                                if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                    print("ORDER COMPLETED and waiting for red " )
                                    execution.append(1)
                                else:
                                    print("SORRY! red not executed")
                                    pass
                            if "green" in gup.iloc[-1,5]:
                                if 1 in counter:
                                    if 1 in execution:
                                        #check execution of green
                                        kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                        print("programe completed with red entry and end with green entry")
                                        counter.clear()
                                        counter_start.clear()
                                        execution.clear()
                                        linkedlist_1.clear()
                                        execution.clear()
                                        counter_start.append(0)
                                        red_time.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                        if 1 in counter_start:
                            print(" BOT STARTED WITH GREEN ' BUY' ENTRY ")
                            if "green" in gup.iloc[-1,5]:
                                if 0 in counter:
                                    quant=qu
                                    xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                    cur_high=avg_ha(xa)
                                    xb=cur_high+float(gup.iloc[-1,6])*0.1
                                    lim_price=avg_ha(xb)
                                    kite_drop=kite.place_order( variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="testR")
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(0)
                                    counter.append(1)
                            if 1 in counter:
                                print("checking green execution")
                                update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                match_in_int=int(match_in)
                                print("checking green executed or not condition ")
                                if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                    print("ORDER COMPLETED and waiting for red " )
                                    execution.append(1)
                                else:
                                    print("SORRY GREEN NOT EXECUTED")
                                    pass
                            if "red" in gup.iloc[-1,5]:
                                if 1 in counter:
                                    if 1 in execution:
                                        kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="testG")
                                        print("programe completed with green entry and end with RED entry")
                                        green_time.append(1)
                                        counter.clear()
                                        counter_start.clear()
                                        execution.clear()
                                        linkedlist_1.clear()
                                        execution.clear()
                                        counter_start.append(0)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass
            ashis()

            ########################

        else:
            if greater_then_buy:
                print("No order is vailable less than 2000 but found more then 2000 so placing on it ")
                order_place_token=greater_then_buy[0]
                order_placee=int(order_place_token)
                order_place=int(order_placee)
                df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
                zall=df[df["instrument_token"]==order_place]
                symbl_final_buy.append(zall.iloc[-1,0])
                token_final_buy.append(zall.iloc[-1,1])     
                ########################################
                ttradingsymbol =str(symbl_final_buy)
                eexchange      ="NSE"
                productt       ="MIS"
                qu             =1
                time_frame     =time_frame
                sdate          ="2019-06-05"
                todate         ="2020-10-02"
                ttoken         =int(token_final_buy)
                #############################
                def avg_ha(x):
                    a=list(modf(round(x,3)))
                    d=str(a[0])
                    aa=str(d[0:2])
                    try:
                        ab=str(d[2])
                    except:
                        ab='0'
                    try:
                        ac=str(d[3])
                    except:
                        ac='0'
                    try:
                        ad=str(d[4])
                    except:
                        ad='0'
                    c=aa+ab+ac+ad
                    b=0
                    if a[0]!=0:
                        astr=c
                        a0=astr[0]
                        a1=astr[1]
                        a3=int(astr[2])
                        a2=int(astr[3:5])
                        if a2>=0 and a2<25:
                            a2=0
                        elif a2>=25 and a2<75:
                            a2=5
                        elif a2>=75 and a2<=99:
                            a3+=1
                            a2=0
                        aint=a0+a1+str(a3)+str(a2)
                        a[0]=float(aint)
                    for k in a:
                        b+=k
                    return b
                counter_start=[0]
                linkedlist_1=[]       
                linkedlist_2=[]      
                linkedlist_3=[]      
                counter=[0,10] 
                execution=[]
                checkfirst=[0]   
                red_time=[]
                green_time=[]
                redb=[]             
                bluez=[]            
                aqua1=[0]           
                bluein=[]           
                blue_2F=[]          
                blue_2G=[]          
                count_sectime=[]
                redc=[]
                colourstill=[]
                prog_starts=[]
                #Variables
                lst_candle=[]
                lst_heikin_nor=[]
                lst_heikin=[]
                lst_cand=[]
                lst_c=[]
                countstart=0
                #programe start
                def ashis():
                    while(True):
                        km=datetime.now().minute
                        ks=datetime.now().second
                        if km%1==0 and ks==1:
                            clear_output(wait=True)  
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%S ")
                            klp1=now_asia
                            dff=kite.historical_data(ttoken,sdate,todate,time_frame,0)
                            #time.sleep(1)
                            dfw=pd.DataFrame(dff)[:-1]
                            df=pd.DataFrame(dfw[['date','open','high','low','close']])
                            slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                            fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                            def EMA(df, base, target, period, alpha=False):
                                con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                                if (alpha == True):
                                    # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                                    df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                                else:
                                    # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                                    df[target] = con.ewm(span=period, adjust=False).mean()
                                df.fillna(0,inplace = True)
                            #     return df
                            for j in slow_ema:
                                val = "ema"+"_"+str(j)
                                EMA(df,"close",val,j)
                            for k in fast_ema:
                                val = "ema"+"_"+str(k)
                                EMA(df,"close",val,k)
                            def super_guppy(interval,df,anchor=0):
                            #     df['buy'] = 0
                            #     df['sell'] = 0
                            #     df['buybreak'] = 0
                            #     df['sellbreak'] = 0
                                anchor = 0
                                ShowBreak = True
                                ShowSwing = True
                                ShowCon = False
                                uOCCswing = False
                                Lookback = 6
                                emaFilter = False
                                mult = 0
                                buybreak = 0
                                sellbreak = 0
                                buy_barssince_var = 0
                                sell_barssince_var = 0
                                buybreak_barssince_var = 0
                                sellbreak_barssince_var = 0
                                barssince_lst = list()
                                barssince_var = 0
                                bar_count_var = 0
                                buy1 = list()
                                sell1 = list()
                                buy2 = list()
                                sell2 = list()
                                buybreak1 = list()
                                sellbreak1 = list()
                                def barssince(b,barssince_var):
                                    barssince_lst = []
                                    barssince_var = 0 
                                    new_var = len(b)
                                    for i in b[::-1]:
                                        if i == 1:
                                            break
                                        barssince_lst.append(i)
                                    barssince_var = len(barssince_lst)
                                    return barssince_var
                                    barssince_lst.clear()
                                #isIntraday
                                if interval < 1441 :
                                    if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                        mult = 1
                                    else:
                                        if round(anchor/interval) > 1:
                                            mult = round(anchor/interval)
                                        else:
                                            mult = 1
                                else:
                                    mult = 1
                                #isIntraday Not
                                if interval > 1441:
                                    if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                        mult = mult
                                    else:
                                        if round(anchor/interval) > 1:
                                            mult = round(anchor/interval)
                                        else:
                                            mult = 1
                                else:
                                    mult = mult
                                mult = 1
                                for i in range(len(df)):
                                    emaF1 = df.loc[i,'ema_3']
                                    emaF2 = df.loc[i,'ema_5']
                                    emaF3 = df.loc[i,'ema_7']
                                    emaF4 = df.loc[i,'ema_9']
                                    emaF5 = df.loc[i,'ema_11']
                                    emaF6 = df.loc[i,'ema_13']
                                    emaF7 = df.loc[i,'ema_15']
                                    emaF8 = df.loc[i,'ema_17']
                                    emaF9 = df.loc[i,'ema_19']
                                    emaF10 = df.loc[i,'ema_21']
                                    emaF11 = df.loc[i,'ema_23']
                                    emaS1 = df.loc[i,'ema_25']
                                    emaS2 = df.loc[i,'ema_28']
                                    emaS3 = df.loc[i,'ema_31']
                                    emaS4 = df.loc[i,'ema_34']
                                    emaS5 = df.loc[i,'ema_37']
                                    emaS6 = df.loc[i,'ema_40']
                                    emaS7 = df.loc[i,'ema_43']
                                    emaS8 = df.loc[i,'ema_46']
                                    emaS9 = df.loc[i,'ema_49']
                                    emaS10 = df.loc[i,'ema_52']
                                    emaS11 = df.loc[i,'ema_55']
                                    emaS12 = df.loc[i,'ema_58']
                                    emaS13 = df.loc[i,'ema_61']
                                    emaS14 = df.loc[i,'ema_64']
                                    emaS15 = df.loc[i,'ema_67']
                                    emaS16 = df.loc[i,'ema_70']
                                    ema200 = df.loc[i,'ema_200'] 
                                    emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                                    emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                                    #Fast EMA Color Rules
                                    colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                                    colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                                    #Slow EMA Color Rules
                                    colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                                    colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                                    if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                        if int(buy1[-1]) > 0:
                                            buy = buy1[-1] + 1
                                        else:
                                            buy = 1
                                    else:
                                        buy = 0
                                    buy1.append(buy)
                                    if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                        if int(sell1[-1]) > 0:
                                            sell = sell1[-1] + 1
                                        else:
                                            sell = 1
                                    else:
                                        sell = 0
                                    sell1.append(sell)
                                    #buy
                                    if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                        buy3 = 1
                                    else:
                                        buy3 = buy
                                    buy2.append(buy3)
                                    #sell    
                                    if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                        sell3 = 1
                                    else:
                                        sell3 = sell
                                    sell2.append(sell3)
                                    #buybreak
                                    if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                        if buybreak1[-1] > 0:
                                            buybreak = buybreak1[-1] + 1
                                        else:
                                            buybreak = 1
                                    else:
                                        buybreak = 0
                                    buybreak1.append(buybreak)
                                    if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                        if sellbreak1[-1] > 0:
                                            sellbreak = sellbreak1[-1]+1
                                        else:
                                            sellbreak = 1
                                    else:
                                        sellbreak = 0
                                    sellbreak1.append(sellbreak)
                                    #arrow plotting
                                    #buy_arrow
                                    buy_barssince_var = barssince(buy2[:-1],barssince_var)
                                    if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                        buy_arrow = 1
                                    else:
                                        buy_arrow = 0
                                    #sell arrow
                                    sell_barssince_var = barssince(sell2[:-1],barssince_var)
                                    if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                        sell_arrow = 1
                                    else:
                                        sell_arrow = 0
                                    #buybreak_arrow
                                    buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                                    sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                                    if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                        buybreak_arrow = 1
                                    else:
                                        buybreak_arrow = 0
                                    #sellbreak_arrow
                                    if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                        sellbreak_arrow = 1
                                    else:
                                        sellbreak_arrow = 0
                                    if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                        arrow_color = 'green'
                                    elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                        arrow_color = 'red'
                                    elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                        arrow_color = 'aqua'
                                    elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                        arrow_color = 'blue'
                                    else:
                                        arrow_color = 'none'
                                    df.loc[i,'arrow_color'] = arrow_color
                                df = df[['date','open','high','low','close','arrow_color']]
                                return df
                            df=super_guppy(15,df)
                            gup=pd.DataFrame(df)
                            def bidatrema(df,period):
                                df['hl']=abs(df['high']-df['low'])
                                df['hpc']=abs(df['high']-df['close'].shift())
                                df['lpc']=abs(df['low']-df['close'].shift())
                                df['tr']=df[['hl','hpc','lpc']].max(axis=1)
                                df['ATR']=pd.DataFrame.ewm(df["tr"], span=period,min_periods=period).mean()
                                df.drop(["hl","hpc","lpc","tr"],axis = 1 , inplace =True)
                            bidatrema(gup,14)
                            print(" \n \t \t \t \t  GUPPY GREEN _ RED PROFIT BOOKING  ")
                            print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%Y-%m-%d _ %H:%M:%S ")
                            klp1=now_asia
                            prog_starts.append(klp1)
                            print("\n ")
                            print("Zerodha GUPPY SELL BOT start Time             "  , prog_starts[0])
                            print("\n ")
                            print("BOT working succeesfully on time:             "  , now_asia )
                            print("\n ")
                            print("Trading symbol is",ttradingsymbol,"Token is",ttoken,"Exchange is",eexchange,"and product type is",productt,"Quantity is",qu,"time frame for Historical Data is",time_frame,"Starting and Ending Date of Historical Data is",sdate,todate)
                            colourstill.append(gup.iloc[-1,5])
                            print(" \n ")
                            print("  Completed with 'GREEN' entry=", len(green_time))
                            print("  Completed with 'RED'   entry=", len(red_time))
                            print("\n ")
                            print("\n ")
                            if 0 in counter_start:
                                if "green" in gup.iloc[-1,5]:     
                                    counter_start.remove(0)
                                    counter_start.append(1)
                                else:
                                    pass
                            if 2 in counter_start:
                                print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                                if "red" in gup.iloc[-1,5]:
                                    if 0 in counter:
                                        quant=qu
                                        xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        price_sell=avg_ha(xa)
                                        xb=price_sell-float(gup.iloc[-1,6])*0.1
                                        triger_sell=avg_ha(xb)
                                        triggerprice_sell=avg_ha(triger_sell)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price= price_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="testR")
                                        print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and price is",price_sell, "quantity is",quant)
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(0)
                                        counter.append(1)
                                if 1 in counter:
                                    print("checking red execution")
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                        print("ORDER COMPLETED and waiting for red " )
                                        execution.append(1)
                                    else:
                                        print("SORRY! red not executed")
                                        pass
                                if "green" in gup.iloc[-1,5]:
                                    if 1 in counter:
                                        if 1 in execution:
                                            #check execution of green
                                            kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                            print("programe completed with red entry and end with green entry")
                                            counter.clear()
                                            counter_start.clear()
                                            execution.clear()
                                            linkedlist_1.clear()
                                            execution.clear()
                                            counter_start.append(0)
                                            red_time.append(1)
                                        else:
                                            pass
                                    else:
                                        pass
                            if 1 in counter_start:
                                print(" BOT STARTED WITH GREEN ' BUY' ENTRY ")
                                if "green" in gup.iloc[-1,5]:
                                    if 0 in counter:
                                        quant=qu
                                        xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        cur_high=avg_ha(xa)
                                        xb=cur_high+float(gup.iloc[-1,6])*0.1
                                        lim_price=avg_ha(xb)
                                        kite_drop=kite.place_order( variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="testR")
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(0)
                                        counter.append(1)
                                if 1 in counter:
                                    print("checking green execution")
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking green executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                        print("ORDER COMPLETED and waiting for red " )
                                        execution.append(1)
                                    else:
                                        print("SORRY GREEN NOT EXECUTED")
                                        pass
                                if "red" in gup.iloc[-1,5]:
                                    if 1 in counter:
                                        if 1 in execution:
                                            kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="testG")
                                            print("programe completed with green entry and end with RED entry")
                                            green_time.append(1)
                                            counter.clear()
                                            counter_start.clear()
                                            execution.clear()
                                            linkedlist_1.clear()
                                            execution.clear()
                                            counter_start.append(0)
                                        else:
                                            pass
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                ashis()
            else:
                print("sorry no order found of  BUY")
                time.sleep(300)
    if "SELL"==buy_sell:        
        print("SELL BOT STARTED")
        time_frame     =str(input("Enter TimeFrame"))
        sdate          ="2019-07-05"
        todate         ="2019-10-02"
        print("SCANNING START")
        #z=list(pd.read_csv("list.csv")["Symbol"])
        z=['ADANIPORTS', 'ASIANPAINT', 'AXISBANK', 'BAJAJ-AUTO', 'BAJFINANCE', 'BAJAJFINSV', 'BPCL', 'BHARTIARTL', 'INFRATEL', 'BRITANNIA', 'CIPLA', 'COALINDIA', 'DRREDDY', 'EICHERMOT', 'GAIL', 'GRASIM', 'HCLTECH', 'HDFCBANK', 'HEROMOTOCO', 'HINDALCO', 'HINDUNILVR', 'HDFC', 'ICICIBANK', 'ITC', 'IBULHSGFIN', 'IOC', 'INDUSINDBK', 'INFY', 'JSWSTEEL', 'KOTAKBANK', 'LT', 'M&M', 'MARUTI', 'NTPC', 'ONGC', 'POWERGRID', 'RELIANCE', 'SBIN', 'SUNPHARMA', 'TCS', 'TATAMOTORS', 'TATASTEEL', 'TECHM', 'TITAN', 'UPL', 'ULTRACEMCO', 'VEDL', 'WIPRO', 'YESBANK', 'ZEEL']
        eexchange="NSE"
        tokenall=[] 
        aa=0
        print("  \t \t \t \n Getting All tokens for processing BUY SELL ")
        while(True):
            ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+z[aa])).iloc[-2,0])
            tokenall.append(ttoken)
            aa=aa+1
            if aa==50:
                print("  \t \t \t \n Complete ! All tokens are fetched from file ")
                print("\n" )
                print(tokenall)
                break
        print(" Now checking Condition of BUY sell of GUPPY ")
        #Variables
        buy5minute=[]
        sell5minute=[]
        buy10minute=[]
        sell10minute=[]
        buy15minute=[]
        sell15minute=[]
        ##
        lst_candle=[]
        lst_heikin_nor=[]
        lst_heikin=[]
        lst_cand=[]
        lst_c=[]
        anchor=0
        countstart=0
        #programe start
        a=0
        #:sell10minutesym,"TOKENS_SELL":sell10minute,"Price":price15min_sell}
        BUY_listindicator=[]
        SELL_listindicator=[]
        sell5minutesym=[]
        buy5minutesym=[]
        buy10minutesym=[]
        sell10minutesym=[]
        buy15minutesym=[]
        sell15minutesym=[]
        #
        #price
        price5min_buy=[]
        price5min_sell=[]
        price15min_buy=[]
        price15min_sell=[]
        price30min_buy=[]
        price30min_sell=[]
        priceedit=[]
        print(a)
        def ashi():
            global a
            global BUY_listindicator
            global SELL_listindicator
            while(True):
                    print("\n" )
                    print("Current Token Number which is processing is",a)
                #km=datetime.now().minute
                #ks=datetime.now().second
                #if km%1==0 and ks==1:
                    clear_output(wait=True)  
                    now_utc = datetime.now(timezone('UTC'))
                    now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                    now_asia = now_asia.strftime("%S ")
                    klp1=now_asia
                    #df=kite.historical_data(140033,sdate,todate,time_frame,0)
                    dff=kite.historical_data(tokenall[a],sdate,todate,time_frame,0)
                    dfw=pd.DataFrame(dff)
                    df=pd.DataFrame(dfw[['date','open','high','low','close']])
                    slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                    fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                    def EMA(df, base, target, period, alpha=False):
                        con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                        if (alpha == True):
                            # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                            df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                        else:
                            # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                            df[target] = con.ewm(span=period, adjust=False).mean()
                        df.fillna(0,inplace = True)
                    #     return df
                    for j in slow_ema:
                        val = "ema"+"_"+str(j)
                        EMA(df,"close",val,j)
                    for k in fast_ema:
                        val = "ema"+"_"+str(k)
                        EMA(df,"close",val,k)
                    def super_guppy(interval,df,anchor=0):
                    #     df['buy'] = 0
                    #     df['sell'] = 0
                    #     df['buybreak'] = 0
                    #     df['sellbreak'] = 0
                        anchor = 0
                        ShowBreak = True
                        ShowSwing = True
                        ShowCon = False
                        uOCCswing = False
                        Lookback = 6
                        emaFilter = False
                        mult = 0
                        buybreak = 0
                        sellbreak = 0
                        buy_barssince_var = 0
                        sell_barssince_var = 0
                        buybreak_barssince_var = 0
                        sellbreak_barssince_var = 0
                        barssince_lst = list()
                        barssince_var = 0
                        bar_count_var = 0
                        buy1 = list()
                        sell1 = list()
                        buy2 = list()
                        sell2 = list()
                        buybreak1 = list()
                        sellbreak1 = list()
                        def barssince(b,barssince_var):
                            barssince_lst = []
                            barssince_var = 0 
                            new_var = len(b)
                            for i in b[::-1]:
                                if i == 1:
                                    break
                                barssince_lst.append(i)
                            barssince_var = len(barssince_lst)
                            return barssince_var
                            barssince_lst.clear()
                        #isIntraday
                        if interval < 1441 :
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                mult = 1
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = 1
                        #isIntraday Not
                        if interval > 1441:
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                mult = mult
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = mult
                        mult = 1
                        for i in range(len(df)):
                            emaF1 = df.loc[i,'ema_3']
                            emaF2 = df.loc[i,'ema_5']
                            emaF3 = df.loc[i,'ema_7']
                            emaF4 = df.loc[i,'ema_9']
                            emaF5 = df.loc[i,'ema_11']
                            emaF6 = df.loc[i,'ema_13']
                            emaF7 = df.loc[i,'ema_15']
                            emaF8 = df.loc[i,'ema_17']
                            emaF9 = df.loc[i,'ema_19']
                            emaF10 = df.loc[i,'ema_21']
                            emaF11 = df.loc[i,'ema_23']
                            emaS1 = df.loc[i,'ema_25']
                            emaS2 = df.loc[i,'ema_28']
                            emaS3 = df.loc[i,'ema_31']
                            emaS4 = df.loc[i,'ema_34']
                            emaS5 = df.loc[i,'ema_37']
                            emaS6 = df.loc[i,'ema_40']
                            emaS7 = df.loc[i,'ema_43']
                            emaS8 = df.loc[i,'ema_46']
                            emaS9 = df.loc[i,'ema_49']
                            emaS10 = df.loc[i,'ema_52']
                            emaS11 = df.loc[i,'ema_55']
                            emaS12 = df.loc[i,'ema_58']
                            emaS13 = df.loc[i,'ema_61']
                            emaS14 = df.loc[i,'ema_64']
                            emaS15 = df.loc[i,'ema_67']
                            emaS16 = df.loc[i,'ema_70']
                            ema200 = df.loc[i,'ema_200'] 
                            emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                            emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                            #Fast EMA Color Rules
                            colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                            colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                            #Slow EMA Color Rules
                            colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                            colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                            if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                if int(buy1[-1]) > 0:
                                    buy = buy1[-1] + 1
                                else:
                                    buy = 1
                            else:
                                buy = 0
                            buy1.append(buy)
                            if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                if int(sell1[-1]) > 0:
                                    sell = sell1[-1] + 1
                                else:
                                    sell = 1
                            else:
                                sell = 0
                            sell1.append(sell)
                            #buy
                            if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                buy3 = 1
                            else:
                                buy3 = buy
                            buy2.append(buy3)
                            #sell    
                            if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                sell3 = 1
                            else:
                                sell3 = sell
                            sell2.append(sell3)
                            #buybreak
                            if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                if buybreak1[-1] > 0:
                                    buybreak = buybreak1[-1] + 1
                                else:
                                    buybreak = 1
                            else:
                                buybreak = 0
                            buybreak1.append(buybreak)
                            if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                if sellbreak1[-1] > 0:
                                    sellbreak = sellbreak1[-1]+1
                                else:
                                    sellbreak = 1
                            else:
                                sellbreak = 0
                            sellbreak1.append(sellbreak)
                            #arrow plotting
                            #buy_arrow
                            buy_barssince_var = barssince(buy2[:-1],barssince_var)
                            if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                buy_arrow = 1
                            else:
                                buy_arrow = 0
                            #sell arrow
                            sell_barssince_var = barssince(sell2[:-1],barssince_var)
                            if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                sell_arrow = 1
                            else:
                                sell_arrow = 0
                            #buybreak_arrow
                            buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                            sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                            if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                buybreak_arrow = 1
                            else:
                                buybreak_arrow = 0
                            #sellbreak_arrow
                            if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                sellbreak_arrow = 1
                            else:
                                sellbreak_arrow = 0
                            if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'green'
                            elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'red'
                            elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                arrow_color = 'aqua'
                            elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                arrow_color = 'blue'
                            else:
                                arrow_color = 'none'
                            df.loc[i,'arrow_color'] = arrow_color
                        df = df[['date','open','high','low','close','arrow_color']]
                        return df
                    df=super_guppy(15,df)
                    gup=df
                    print(" \t \t \t \t Zerodha GUPPY SCREENER on 5 minute Data")
                    print("\t \t \t \n Current Token checking  " , tokenall[a])
                    print("\n" )
                    print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                    if "green" in gup.iloc[-1,5]:
                        print(" BUY stock found ")
                        buy5minute.append((tokenall[a]))
                        buy5minutesym.append((z[a]))
                        price5min_buy.append(gup.iloc[-1,2])
                    if "red" in gup.iloc[-1,5]:
                        print(" SELL stock found ")
                        sell5minute.append((tokenall[a]))
                        sell5minutesym.append((z[a]))
                        price5min_sell.append(gup.iloc[-1,2])
                    else:
                        pass
                    print("Buy stock found  are  :="  ,buy5minute)
                    print("Sell stocks found  are:="  ,sell5minute)
                    a=a+1
                    if a==len(tokenall):
                        break
        ashi()
        less_then_buy=[]
        greater_then_buy=[]
        less_then_sell=[]
        greater_then_sell=[]
        symbl_final_buy=[]
        token_final_buy=[]

        print(" Scanning is complete ")
        buyframe={"SYMBOLS_BUY":buy5minute,"TOKENS_BUY":buy5minutesym,"Price":price5min_buy}
        fivemin=pd.DataFrame(buyframe)
        display(fivemin)
        buyframee={"SYMBOLS_SELL":sell5minutesym,"TOKENS_SELL":sell5minute,"Price":price5min_sell}
        fivemine=pd.DataFrame(buyframee)
        display(fivemine)

        if buy5minute:
            print("YES ! Some buy stock found")
            aa=0
            while(True):
                kk=pd.DataFrame(kite.ltp(buy5minute[aa])).iloc[-1,0]             
                if kk<2000:
                    less_then_buy.append(buy5minute[aa])
                if kk>2000:
                    greater_then_buy.append(buy5minute[aa])
                aa=aa+1
                if aa==len(buy5minute):
                    break

        if sell5minute:
            print("yes ! some sell tock found")
            aa=0
            while(True):
                kk=pd.DataFrame(kite.ltp(sell5minute[aa])).iloc[-1,0]
                if kk<2000:
                    less_then_sell.append(sell5minute[aa])
                if kk>2000:
                    greater_then_sell.append(sell5minute[aa])
                aa=aa+1
                if aa==len(sell5minute):
                    break
        print("BUY LESS THEN 2000"   ,less_then_buy)
        print("BUY grater then 2000" ,greater_then_buy)

        print("SELL less then 2000"  ,less_then_sell)
        print("SELL GREATER THEN 2000",greater_then_sell)

        less_then_buy=less_then_sell
        greater_then_buy=greater_then_sell
        if less_then_buy:
            print("Going to Place order  on ",less_then_buy[0])
            order_place_token=less_then_buy[0]
            order_place=int(order_place_token)
            print("SELL FOUND")
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==order_place]
            symbl_final_buy.append(zall.iloc[-1,0])
            token_final_buy.append(zall.iloc[-1,1])     
            ########################################
            ttradingsymbol =str(symbl_final_buy)
            eexchange      ="NSE"
            productt       ="MIS"
            qu             =1
            time_frame     =time_frame
            sdate          ="2019-06-05"
            todate         ="2020-10-02"
            ttoken         =int(token_final_buy)
            #############################
            #calculation
            def avg_ha(x):
                a=list(modf(round(x,3)))
                d=str(a[0])
                aa=str(d[0:2])
                try:
                    ab=str(d[2])
                except:
                    ab='0'
                try:
                    ac=str(d[3])
                except:
                    ac='0'
                try:
                    ad=str(d[4])
                except:
                    ad='0'
                c=aa+ab+ac+ad
                b=0
                if a[0]!=0:
                    astr=c
                    a0=astr[0]
                    a1=astr[1]
                    a3=int(astr[2])
                    a2=int(astr[3:5])
                    if a2>=0 and a2<25:
                        a2=0
                    elif a2>=25 and a2<75:
                        a2=5
                    elif a2>=75 and a2<=99:
                        a3+=1
                        a2=0
                    aint=a0+a1+str(a3)+str(a2)
                    a[0]=float(aint)
                for k in a:
                    b+=k
                return b
            counter_start=[0]
            linkedlist_1=[]       
            linkedlist_2=[]      
            linkedlist_3=[]      
            counter=[0,10] 
            execution=[]
            checkfirst=[0]   
            red_time=[]
            green_time=[]
            redb=[]             
            bluez=[]            
            aqua1=[0]           
            bluein=[]           
            blue_2F=[]          
            blue_2G=[]          
            count_sectime=[]
            redc=[]
            colourstill=[]
            prog_starts=[]
            #Variables
            lst_candle=[]
            lst_heikin_nor=[]
            lst_heikin=[]
            lst_cand=[]
            lst_c=[]
            countstart=0
            #programe start
            def ashis():
                while(True):
                    km=datetime.now().minute
                    ks=datetime.now().second
                    if km%1==0 and ks==1:
                        clear_output(wait=True)  
                        now_utc = datetime.now(timezone('UTC'))
                        now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                        now_asia = now_asia.strftime("%S ")
                        klp1=now_asia
                        dff=kite.historical_data(ttoken,sdate,todate,time_frame,0)
                        #time.sleep(1)
                        dfw=pd.DataFrame(dff)[:-1]
                        df=pd.DataFrame(dfw[['date','open','high','low','close']])
                        slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                        fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                        def EMA(df, base, target, period, alpha=False):
                            con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                            if (alpha == True):
                                # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                                df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                            else:
                                # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                                df[target] = con.ewm(span=period, adjust=False).mean()
                            df.fillna(0,inplace = True)
                        #     return df
                        for j in slow_ema:
                            val = "ema"+"_"+str(j)
                            EMA(df,"close",val,j)
                        for k in fast_ema:
                            val = "ema"+"_"+str(k)
                            EMA(df,"close",val,k)
                        def super_guppy(interval,df,anchor=0):
                        #     df['buy'] = 0
                        #     df['sell'] = 0
                        #     df['buybreak'] = 0
                        #     df['sellbreak'] = 0
                            anchor = 0
                            ShowBreak = True
                            ShowSwing = True
                            ShowCon = False
                            uOCCswing = False
                            Lookback = 6
                            emaFilter = False
                            mult = 0
                            buybreak = 0
                            sellbreak = 0
                            buy_barssince_var = 0
                            sell_barssince_var = 0
                            buybreak_barssince_var = 0
                            sellbreak_barssince_var = 0
                            barssince_lst = list()
                            barssince_var = 0
                            bar_count_var = 0
                            buy1 = list()
                            sell1 = list()
                            buy2 = list()
                            sell2 = list()
                            buybreak1 = list()
                            sellbreak1 = list()
                            def barssince(b,barssince_var):
                                barssince_lst = []
                                barssince_var = 0 
                                new_var = len(b)
                                for i in b[::-1]:
                                    if i == 1:
                                        break
                                    barssince_lst.append(i)
                                barssince_var = len(barssince_lst)
                                return barssince_var
                                barssince_lst.clear()
                            #isIntraday
                            if interval < 1441 :
                                if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                    mult = 1
                                else:
                                    if round(anchor/interval) > 1:
                                        mult = round(anchor/interval)
                                    else:
                                        mult = 1
                            else:
                                mult = 1
                            #isIntraday Not
                            if interval > 1441:
                                if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                    mult = mult
                                else:
                                    if round(anchor/interval) > 1:
                                        mult = round(anchor/interval)
                                    else:
                                        mult = 1
                            else:
                                mult = mult
                            mult = 1
                            for i in range(len(df)):
                                emaF1 = df.loc[i,'ema_3']
                                emaF2 = df.loc[i,'ema_5']
                                emaF3 = df.loc[i,'ema_7']
                                emaF4 = df.loc[i,'ema_9']
                                emaF5 = df.loc[i,'ema_11']
                                emaF6 = df.loc[i,'ema_13']
                                emaF7 = df.loc[i,'ema_15']
                                emaF8 = df.loc[i,'ema_17']
                                emaF9 = df.loc[i,'ema_19']
                                emaF10 = df.loc[i,'ema_21']
                                emaF11 = df.loc[i,'ema_23']
                                emaS1 = df.loc[i,'ema_25']
                                emaS2 = df.loc[i,'ema_28']
                                emaS3 = df.loc[i,'ema_31']
                                emaS4 = df.loc[i,'ema_34']
                                emaS5 = df.loc[i,'ema_37']
                                emaS6 = df.loc[i,'ema_40']
                                emaS7 = df.loc[i,'ema_43']
                                emaS8 = df.loc[i,'ema_46']
                                emaS9 = df.loc[i,'ema_49']
                                emaS10 = df.loc[i,'ema_52']
                                emaS11 = df.loc[i,'ema_55']
                                emaS12 = df.loc[i,'ema_58']
                                emaS13 = df.loc[i,'ema_61']
                                emaS14 = df.loc[i,'ema_64']
                                emaS15 = df.loc[i,'ema_67']
                                emaS16 = df.loc[i,'ema_70']
                                ema200 = df.loc[i,'ema_200'] 
                                emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                                emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                                #Fast EMA Color Rules
                                colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                                colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                                #Slow EMA Color Rules
                                colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                                colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                                if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                    if int(buy1[-1]) > 0:
                                        buy = buy1[-1] + 1
                                    else:
                                        buy = 1
                                else:
                                    buy = 0
                                buy1.append(buy)
                                if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                    if int(sell1[-1]) > 0:
                                        sell = sell1[-1] + 1
                                    else:
                                        sell = 1
                                else:
                                    sell = 0
                                sell1.append(sell)
                                #buy
                                if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                    buy3 = 1
                                else:
                                    buy3 = buy
                                buy2.append(buy3)
                                #sell    
                                if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                    sell3 = 1
                                else:
                                    sell3 = sell
                                sell2.append(sell3)
                                #buybreak
                                if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                    if buybreak1[-1] > 0:
                                        buybreak = buybreak1[-1] + 1
                                    else:
                                        buybreak = 1
                                else:
                                    buybreak = 0
                                buybreak1.append(buybreak)
                                if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                    if sellbreak1[-1] > 0:
                                        sellbreak = sellbreak1[-1]+1
                                    else:
                                        sellbreak = 1
                                else:
                                    sellbreak = 0
                                sellbreak1.append(sellbreak)
                                #arrow plotting
                                #buy_arrow
                                buy_barssince_var = barssince(buy2[:-1],barssince_var)
                                if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                    buy_arrow = 1
                                else:
                                    buy_arrow = 0
                                #sell arrow
                                sell_barssince_var = barssince(sell2[:-1],barssince_var)
                                if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                    sell_arrow = 1
                                else:
                                    sell_arrow = 0
                                #buybreak_arrow
                                buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                                sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                                if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                    buybreak_arrow = 1
                                else:
                                    buybreak_arrow = 0
                                #sellbreak_arrow
                                if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                    sellbreak_arrow = 1
                                else:
                                    sellbreak_arrow = 0
                                if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                    arrow_color = 'green'
                                elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                    arrow_color = 'red'
                                elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                    arrow_color = 'aqua'
                                elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                    arrow_color = 'blue'
                                else:
                                    arrow_color = 'none'
                                df.loc[i,'arrow_color'] = arrow_color
                            df = df[['date','open','high','low','close','arrow_color']]
                            return df
                        df=super_guppy(15,df)
                        gup=pd.DataFrame(df)
                        def bidatrema(df,period):
                            df['hl']=abs(df['high']-df['low'])
                            df['hpc']=abs(df['high']-df['close'].shift())
                            df['lpc']=abs(df['low']-df['close'].shift())
                            df['tr']=df[['hl','hpc','lpc']].max(axis=1)
                            df['ATR']=pd.DataFrame.ewm(df["tr"], span=period,min_periods=period).mean()
                            df.drop(["hl","hpc","lpc","tr"],axis = 1 , inplace =True)
                        bidatrema(gup,14)
                        print(" \n \t \t \t \t  GUPPY SELL_ RED PROFIT BOOKING  ")
                        print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                        now_utc = datetime.now(timezone('UTC'))
                        now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                        now_asia = now_asia.strftime("%Y-%m-%d _ %H:%M:%S ")
                        klp1=now_asia
                        prog_starts.append(klp1)
                        print("\n ")
                        print("Zerodha GUPPY SELL BOT start Time             "  , prog_starts[0])
                        print("\n ")
                        print("BOT working succeesfully on time:             "  , now_asia )
                        print("\n ")
                        print("Trading symbol is",ttradingsymbol,"Token is",ttoken,"Exchange is",eexchange,"and product type is",productt,"Quantity is",qu,"time frame for Historical Data is",time_frame,"Starting and Ending Date of Historical Data is",sdate,todate)
                        colourstill.append(gup.iloc[-1,5])
                        print(" \n ")
                        print("  Completed with 'GREEN' entry=", len(green_time))
                        print("  Completed with 'RED'   entry=", len(red_time))
                        print("\n ")
                        print("\n ")
                        if 0 in counter_start:
                            if "red" in gup.iloc[-1,5]:
                                counter_start.remove(0)
                                counter_start.append(2)
                            #if "green" in gup.iloc[-1,5]:     
                                counter_start.remove(0)
                                counter_start.append(1)
                            else:
                                pass
                        if 2 in counter_start:
                            print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                            if "red" in gup.iloc[-1,5]:
                                if 0 in counter:
                                    quant=qu
                                    xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                    price_sell=avg_ha(xa)
                                    xb=price_sell-float(gup.iloc[-1,6])*0.1
                                    triger_sell=avg_ha(xb)
                                    triggerprice_sell=avg_ha(triger_sell)
                                    kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price= price_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="testR")
                                    print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and price is",price_sell, "quantity is",quant)
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(0)
                                    counter.append(1)
                            if 1 in counter:
                                print("checking red execution")
                                update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                match_in_int=int(match_in)
                                print("checking executed or not condition ")
                                if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                    print("ORDER COMPLETED and waiting for red " )
                                    execution.append(1)
                                else:
                                    print("SORRY! red not executed")
                                    pass
                            if "green" in gup.iloc[-1,5]:
                                if 1 in counter:
                                    if 1 in execution:
                                        #check execution of green
                                        kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                        print("programe completed with red entry and end with green entry")
                                        counter.clear()
                                        counter_start.clear()
                                        execution.clear()
                                        linkedlist_1.clear()
                                        execution.clear()
                                        counter_start.append(0)
                                        red_time.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                        if 1 in counter_start:
                            print(" BOT STARTED WITH GREEN ' BUY' ENTRY ")
                            if "green" in gup.iloc[-1,5]:
                                if 0 in counter:
                                    quant=qu
                                    xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                    cur_high=avg_ha(xa)
                                    xb=cur_high+float(gup.iloc[-1,6])*0.1
                                    lim_price=avg_ha(xb)
                                    kite_drop=kite.place_order( variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="testR")
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(0)
                                    counter.append(1)
                            if 1 in counter:
                                print("checking green execution")
                                update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                match_in_int=int(match_in)
                                print("checking green executed or not condition ")
                                if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                    print("ORDER COMPLETED and waiting for red " )
                                    execution.append(1)
                                else:
                                    print("SORRY GREEN NOT EXECUTED")
                                    pass
                            if "red" in gup.iloc[-1,5]:
                                if 1 in counter:
                                    if 1 in execution:
                                        kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="testG")
                                        print("programe completed with green entry and end with RED entry")
                                        green_time.append(1)
                                        counter.clear()
                                        counter_start.clear()
                                        execution.clear()
                                        linkedlist_1.clear()
                                        execution.clear()
                                        counter_start.append(0)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass
            ashis()

            ########################

        else:
            if greater_then_buy:
                print("No order is vailable less than 2000 but found more then 2000 so placing on it ")
                order_place_token=greater_then_buy[0]
                order_placee=int(order_place_token)
                order_place=int(order_placee)
                df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
                zall=df[df["instrument_token"]==order_place]
                symbl_final_buy.append(zall.iloc[-1,0])
                token_final_buy.append(zall.iloc[-1,1])     
                ########################################
                ttradingsymbol =str(symbl_final_buy)
                eexchange      ="NSE"
                productt       ="MIS"
                qu             =1
                time_frame     =time_frame
                sdate          ="2019-06-05"
                todate         ="2020-10-02"
                ttoken         =int(token_final_buy)
                #############################
                def avg_ha(x):
                    a=list(modf(round(x,3)))
                    d=str(a[0])
                    aa=str(d[0:2])
                    try:
                        ab=str(d[2])
                    except:
                        ab='0'
                    try:
                        ac=str(d[3])
                    except:
                        ac='0'
                    try:
                        ad=str(d[4])
                    except:
                        ad='0'
                    c=aa+ab+ac+ad
                    b=0
                    if a[0]!=0:
                        astr=c
                        a0=astr[0]
                        a1=astr[1]
                        a3=int(astr[2])
                        a2=int(astr[3:5])
                        if a2>=0 and a2<25:
                            a2=0
                        elif a2>=25 and a2<75:
                            a2=5
                        elif a2>=75 and a2<=99:
                            a3+=1
                            a2=0
                        aint=a0+a1+str(a3)+str(a2)
                        a[0]=float(aint)
                    for k in a:
                        b+=k
                    return b
                counter_start=[0]
                linkedlist_1=[]       
                linkedlist_2=[]      
                linkedlist_3=[]      
                counter=[0,10] 
                execution=[]
                checkfirst=[0]   
                red_time=[]
                green_time=[]
                redb=[]             
                bluez=[]            
                aqua1=[0]           
                bluein=[]           
                blue_2F=[]          
                blue_2G=[]          
                count_sectime=[]
                redc=[]
                colourstill=[]
                prog_starts=[]
                #Variables
                lst_candle=[]
                lst_heikin_nor=[]
                lst_heikin=[]
                lst_cand=[]
                lst_c=[]
                countstart=0
                #programe start
                def ashis():
                    while(True):
                        km=datetime.now().minute
                        ks=datetime.now().second
                        if km%1==0 and ks==1:
                            clear_output(wait=True)  
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%S ")
                            klp1=now_asia
                            dff=kite.historical_data(ttoken,sdate,todate,time_frame,0)
                            #time.sleep(1)
                            dfw=pd.DataFrame(dff)[:-1]
                            df=pd.DataFrame(dfw[['date','open','high','low','close']])
                            slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                            fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                            def EMA(df, base, target, period, alpha=False):
                                con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                                if (alpha == True):
                                    # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                                    df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                                else:
                                    # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                                    df[target] = con.ewm(span=period, adjust=False).mean()
                                df.fillna(0,inplace = True)
                            #     return df
                            for j in slow_ema:
                                val = "ema"+"_"+str(j)
                                EMA(df,"close",val,j)
                            for k in fast_ema:
                                val = "ema"+"_"+str(k)
                                EMA(df,"close",val,k)
                            def super_guppy(interval,df,anchor=0):
                            #     df['buy'] = 0
                            #     df['sell'] = 0
                            #     df['buybreak'] = 0
                            #     df['sellbreak'] = 0
                                anchor = 0
                                ShowBreak = True
                                ShowSwing = True
                                ShowCon = False
                                uOCCswing = False
                                Lookback = 6
                                emaFilter = False
                                mult = 0
                                buybreak = 0
                                sellbreak = 0
                                buy_barssince_var = 0
                                sell_barssince_var = 0
                                buybreak_barssince_var = 0
                                sellbreak_barssince_var = 0
                                barssince_lst = list()
                                barssince_var = 0
                                bar_count_var = 0
                                buy1 = list()
                                sell1 = list()
                                buy2 = list()
                                sell2 = list()
                                buybreak1 = list()
                                sellbreak1 = list()
                                def barssince(b,barssince_var):
                                    barssince_lst = []
                                    barssince_var = 0 
                                    new_var = len(b)
                                    for i in b[::-1]:
                                        if i == 1:
                                            break
                                        barssince_lst.append(i)
                                    barssince_var = len(barssince_lst)
                                    return barssince_var
                                    barssince_lst.clear()
                                #isIntraday
                                if interval < 1441 :
                                    if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                        mult = 1
                                    else:
                                        if round(anchor/interval) > 1:
                                            mult = round(anchor/interval)
                                        else:
                                            mult = 1
                                else:
                                    mult = 1
                                #isIntraday Not
                                if interval > 1441:
                                    if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                        mult = mult
                                    else:
                                        if round(anchor/interval) > 1:
                                            mult = round(anchor/interval)
                                        else:
                                            mult = 1
                                else:
                                    mult = mult
                                mult = 1
                                for i in range(len(df)):
                                    emaF1 = df.loc[i,'ema_3']
                                    emaF2 = df.loc[i,'ema_5']
                                    emaF3 = df.loc[i,'ema_7']
                                    emaF4 = df.loc[i,'ema_9']
                                    emaF5 = df.loc[i,'ema_11']
                                    emaF6 = df.loc[i,'ema_13']
                                    emaF7 = df.loc[i,'ema_15']
                                    emaF8 = df.loc[i,'ema_17']
                                    emaF9 = df.loc[i,'ema_19']
                                    emaF10 = df.loc[i,'ema_21']
                                    emaF11 = df.loc[i,'ema_23']
                                    emaS1 = df.loc[i,'ema_25']
                                    emaS2 = df.loc[i,'ema_28']
                                    emaS3 = df.loc[i,'ema_31']
                                    emaS4 = df.loc[i,'ema_34']
                                    emaS5 = df.loc[i,'ema_37']
                                    emaS6 = df.loc[i,'ema_40']
                                    emaS7 = df.loc[i,'ema_43']
                                    emaS8 = df.loc[i,'ema_46']
                                    emaS9 = df.loc[i,'ema_49']
                                    emaS10 = df.loc[i,'ema_52']
                                    emaS11 = df.loc[i,'ema_55']
                                    emaS12 = df.loc[i,'ema_58']
                                    emaS13 = df.loc[i,'ema_61']
                                    emaS14 = df.loc[i,'ema_64']
                                    emaS15 = df.loc[i,'ema_67']
                                    emaS16 = df.loc[i,'ema_70']
                                    ema200 = df.loc[i,'ema_200'] 
                                    emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                                    emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                                    #Fast EMA Color Rules
                                    colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                                    colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                                    #Slow EMA Color Rules
                                    colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                                    colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                                    if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                        if int(buy1[-1]) > 0:
                                            buy = buy1[-1] + 1
                                        else:
                                            buy = 1
                                    else:
                                        buy = 0
                                    buy1.append(buy)
                                    if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                        if int(sell1[-1]) > 0:
                                            sell = sell1[-1] + 1
                                        else:
                                            sell = 1
                                    else:
                                        sell = 0
                                    sell1.append(sell)
                                    #buy
                                    if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                        buy3 = 1
                                    else:
                                        buy3 = buy
                                    buy2.append(buy3)
                                    #sell    
                                    if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                        sell3 = 1
                                    else:
                                        sell3 = sell
                                    sell2.append(sell3)
                                    #buybreak
                                    if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                        if buybreak1[-1] > 0:
                                            buybreak = buybreak1[-1] + 1
                                        else:
                                            buybreak = 1
                                    else:
                                        buybreak = 0
                                    buybreak1.append(buybreak)
                                    if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                        if sellbreak1[-1] > 0:
                                            sellbreak = sellbreak1[-1]+1
                                        else:
                                            sellbreak = 1
                                    else:
                                        sellbreak = 0
                                    sellbreak1.append(sellbreak)
                                    #arrow plotting
                                    #buy_arrow
                                    buy_barssince_var = barssince(buy2[:-1],barssince_var)
                                    if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                        buy_arrow = 1
                                    else:
                                        buy_arrow = 0
                                    #sell arrow
                                    sell_barssince_var = barssince(sell2[:-1],barssince_var)
                                    if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                        sell_arrow = 1
                                    else:
                                        sell_arrow = 0
                                    #buybreak_arrow
                                    buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                                    sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                                    if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                        buybreak_arrow = 1
                                    else:
                                        buybreak_arrow = 0
                                    #sellbreak_arrow
                                    if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                        sellbreak_arrow = 1
                                    else:
                                        sellbreak_arrow = 0
                                    if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                        arrow_color = 'green'
                                    elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                        arrow_color = 'red'
                                    elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                        arrow_color = 'aqua'
                                    elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                        arrow_color = 'blue'
                                    else:
                                        arrow_color = 'none'
                                    df.loc[i,'arrow_color'] = arrow_color
                                df = df[['date','open','high','low','close','arrow_color']]
                                return df
                            df=super_guppy(15,df)
                            gup=pd.DataFrame(df)
                            def bidatrema(df,period):
                                df['hl']=abs(df['high']-df['low'])
                                df['hpc']=abs(df['high']-df['close'].shift())
                                df['lpc']=abs(df['low']-df['close'].shift())
                                df['tr']=df[['hl','hpc','lpc']].max(axis=1)
                                df['ATR']=pd.DataFrame.ewm(df["tr"], span=period,min_periods=period).mean()
                                df.drop(["hl","hpc","lpc","tr"],axis = 1 , inplace =True)
                            bidatrema(gup,14)
                            print(" \n \t \t \t \t  GUPPY SELL _ RED PROFIT BOOKING  ")
                            print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%Y-%m-%d _ %H:%M:%S ")
                            klp1=now_asia
                            prog_starts.append(klp1)
                            print("\n ")
                            print("Zerodha GUPPY SELL BOT start Time             "  , prog_starts[0])
                            print("\n ")
                            print("BOT working succeesfully on time:             "  , now_asia )
                            print("\n ")
                            print("Trading symbol is",ttradingsymbol,"Token is",ttoken,"Exchange is",eexchange,"and product type is",productt,"Quantity is",qu,"time frame for Historical Data is",time_frame,"Starting and Ending Date of Historical Data is",sdate,todate)
                            colourstill.append(gup.iloc[-1,5])
                            print(" \n ")
                            print("  Completed with 'GREEN' entry=", len(green_time))
                            print("  Completed with 'RED'   entry=", len(red_time))
                            print("\n ")
                            print("\n ")
                            if 0 in counter_start:
                                if "green" in gup.iloc[-1,5]:     
                                    counter_start.remove(0)
                                    counter_start.append(1)
                                else:
                                    pass
                            if 2 in counter_start:
                                print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                                if "red" in gup.iloc[-1,5]:
                                    if 0 in counter:
                                        quant=qu
                                        xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        price_sell=avg_ha(xa)
                                        xb=price_sell-float(gup.iloc[-1,6])*0.1
                                        triger_sell=avg_ha(xb)
                                        triggerprice_sell=avg_ha(triger_sell)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price= price_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="testR")
                                        print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and price is",price_sell, "quantity is",quant)
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(0)
                                        counter.append(1)
                                if 1 in counter:
                                    print("checking red execution")
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                        print("ORDER COMPLETED and waiting for red " )
                                        execution.append(1)
                                    else:
                                        print("SORRY! red not executed")
                                        pass
                                if "green" in gup.iloc[-1,5]:
                                    if 1 in counter:
                                        if 1 in execution:
                                            #check execution of green
                                            kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                            print("programe completed with red entry and end with green entry")
                                            counter.clear()
                                            counter_start.clear()
                                            execution.clear()
                                            linkedlist_1.clear()
                                            execution.clear()
                                            counter_start.append(0)
                                            red_time.append(1)
                                        else:
                                            pass
                                    else:
                                        pass
                            if 1 in counter_start:
                                print(" BOT STARTED WITH GREEN ' BUY' ENTRY ")
                                if "green" in gup.iloc[-1,5]:
                                    if 0 in counter:
                                        quant=qu
                                        xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        cur_high=avg_ha(xa)
                                        xb=cur_high+float(gup.iloc[-1,6])*0.1
                                        lim_price=avg_ha(xb)
                                        kite_drop=kite.place_order( variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="testR")
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(0)
                                        counter.append(1)
                                if 1 in counter:
                                    print("checking green execution")
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking green executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                        print("ORDER COMPLETED and waiting for red " )
                                        execution.append(1)
                                    else:
                                        print("SORRY GREEN NOT EXECUTED")
                                        pass
                                if "red" in gup.iloc[-1,5]:
                                    if 1 in counter:
                                        if 1 in execution:
                                            kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="testG")
                                            print("programe completed with green entry and end with RED entry")
                                            green_time.append(1)
                                            counter.clear()
                                            counter_start.clear()
                                            execution.clear()
                                            linkedlist_1.clear()
                                            execution.clear()
                                            counter_start.append(0)
                                        else:
                                            pass
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                ashis()
            else:
                print("sorry no order found of  SELL ")
                time.sleep(300)
if "NO"==scan:
    manually=str(input( "ENTER BUY or SELL ?"))
    if "BUY" in manually:
        print(" BUY BOT STARTED Manually")
        #calculation
        def avg_ha(x):
            a=list(modf(round(x,3)))
            d=str(a[0])
            aa=str(d[0:2])
            try:
                ab=str(d[2])
            except:
                ab='0'
            try:
                ac=str(d[3])
            except:
                ac='0'
            try:
                ad=str(d[4])
            except:
                ad='0'
            c=aa+ab+ac+ad
            b=0
            if a[0]!=0:
                astr=c
                a0=astr[0]
                a1=astr[1]
                a3=int(astr[2])
                a2=int(astr[3:5])
                if a2>=0 and a2<25:
                    a2=0
                elif a2>=25 and a2<75:
                    a2=5
                elif a2>=75 and a2<=99:
                    a3+=1
                    a2=0
                aint=a0+a1+str(a3)+str(a2)
                a[0]=float(aint)
            for k in a:
                b+=k
            return b

        print("WELCOME TO GUPPY BUY PROFIT BOOKING BOT ! ")
        print(" \n ")
        ttradingsymbol =str(input("ENTER TRADINGSYMBOL - SUNPHARMA / SBIN :-")).upper()
        eexchange      =str(input("ENTER EXCHANGE / NSE / BSE / CDS  :-")).upper()
        productt       =str(input("ENTER PRODUCT / NRML /CNC / MIS  :-")).upper()
        qu             =int(input("ENTER QUANTITY - 2 / 4 :-"))
        time_frame     =str(input("ENTER TIME_FRAME - minute / 5minute  :-")).lower()
        sdate          ="2019-05-05"
        todate         ="2020-10-02"
        ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+ttradingsymbol)).iloc[-2,0])
        counter_start=[0]
        linkedlist_1=[]       
        linkedlist_2=[]      
        linkedlist_3=[]      
        counter=[0,10] 
        execution=[]
        checkfirst=[0]   
        red_time=[]
        green_time=[]
        redb=[]             
        bluez=[]            
        aqua1=[0]           
        bluein=[]           
        blue_2F=[]          
        blue_2G=[]          
        count_sectime=[]
        redc=[]
        colourstill=[]
        prog_starts=[]
        #Variables
        lst_candle=[]
        lst_heikin_nor=[]
        lst_heikin=[]
        lst_cand=[]
        lst_c=[]
        countstart=0
        #programe start
        def ashis():
            while(True):
                km=datetime.now().minute
                ks=datetime.now().second
                if km%1==0 and ks==1:
                    clear_output(wait=True)  
                    now_utc = datetime.now(timezone('UTC'))
                    now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                    now_asia = now_asia.strftime("%S ")
                    klp1=now_asia
                    dff=kite.historical_data(ttoken,sdate,todate,time_frame,0)
                    #time.sleep(1)
                    dfw=pd.DataFrame(dff)[:-1]
                    df=pd.DataFrame(dfw[['date','open','high','low','close']])
                    slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                    fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                    def EMA(df, base, target, period, alpha=False):
                        con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                        if (alpha == True):
                            # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                            df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                        else:
                            # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                            df[target] = con.ewm(span=period, adjust=False).mean()
                        df.fillna(0,inplace = True)
                    #     return df
                    for j in slow_ema:
                        val = "ema"+"_"+str(j)
                        EMA(df,"close",val,j)
                    for k in fast_ema:
                        val = "ema"+"_"+str(k)
                        EMA(df,"close",val,k)
                    def super_guppy(interval,df,anchor=0):
                    #     df['buy'] = 0
                    #     df['sell'] = 0
                    #     df['buybreak'] = 0
                    #     df['sellbreak'] = 0
                        anchor = 0
                        ShowBreak = True
                        ShowSwing = True
                        ShowCon = False
                        uOCCswing = False
                        Lookback = 6
                        emaFilter = False
                        mult = 0
                        buybreak = 0
                        sellbreak = 0
                        buy_barssince_var = 0
                        sell_barssince_var = 0
                        buybreak_barssince_var = 0
                        sellbreak_barssince_var = 0
                        barssince_lst = list()
                        barssince_var = 0
                        bar_count_var = 0
                        buy1 = list()
                        sell1 = list()
                        buy2 = list()
                        sell2 = list()
                        buybreak1 = list()
                        sellbreak1 = list()
                        def barssince(b,barssince_var):
                            barssince_lst = []
                            barssince_var = 0 
                            new_var = len(b)
                            for i in b[::-1]:
                                if i == 1:
                                    break
                                barssince_lst.append(i)
                            barssince_var = len(barssince_lst)
                            return barssince_var
                            barssince_lst.clear()
                        #isIntraday
                        if interval < 1441 :
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                mult = 1
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = 1
                        #isIntraday Not
                        if interval > 1441:
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                mult = mult
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = mult
                        mult = 1
                        for i in range(len(df)):
                            emaF1 = df.loc[i,'ema_3']
                            emaF2 = df.loc[i,'ema_5']
                            emaF3 = df.loc[i,'ema_7']
                            emaF4 = df.loc[i,'ema_9']
                            emaF5 = df.loc[i,'ema_11']
                            emaF6 = df.loc[i,'ema_13']
                            emaF7 = df.loc[i,'ema_15']
                            emaF8 = df.loc[i,'ema_17']
                            emaF9 = df.loc[i,'ema_19']
                            emaF10 = df.loc[i,'ema_21']
                            emaF11 = df.loc[i,'ema_23']
                            emaS1 = df.loc[i,'ema_25']
                            emaS2 = df.loc[i,'ema_28']
                            emaS3 = df.loc[i,'ema_31']
                            emaS4 = df.loc[i,'ema_34']
                            emaS5 = df.loc[i,'ema_37']
                            emaS6 = df.loc[i,'ema_40']
                            emaS7 = df.loc[i,'ema_43']
                            emaS8 = df.loc[i,'ema_46']
                            emaS9 = df.loc[i,'ema_49']
                            emaS10 = df.loc[i,'ema_52']
                            emaS11 = df.loc[i,'ema_55']
                            emaS12 = df.loc[i,'ema_58']
                            emaS13 = df.loc[i,'ema_61']
                            emaS14 = df.loc[i,'ema_64']
                            emaS15 = df.loc[i,'ema_67']
                            emaS16 = df.loc[i,'ema_70']
                            ema200 = df.loc[i,'ema_200'] 
                            emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                            emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                            #Fast EMA Color Rules
                            colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                            colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                            #Slow EMA Color Rules
                            colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                            colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                            if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                if int(buy1[-1]) > 0:
                                    buy = buy1[-1] + 1
                                else:
                                    buy = 1
                            else:
                                buy = 0
                            buy1.append(buy)
                            if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                if int(sell1[-1]) > 0:
                                    sell = sell1[-1] + 1
                                else:
                                    sell = 1
                            else:
                                sell = 0
                            sell1.append(sell)
                            #buy
                            if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                buy3 = 1
                            else:
                                buy3 = buy
                            buy2.append(buy3)
                            #sell    
                            if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                sell3 = 1
                            else:
                                sell3 = sell
                            sell2.append(sell3)
                            #buybreak
                            if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                if buybreak1[-1] > 0:
                                    buybreak = buybreak1[-1] + 1
                                else:
                                    buybreak = 1
                            else:
                                buybreak = 0
                            buybreak1.append(buybreak)
                            if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                if sellbreak1[-1] > 0:
                                    sellbreak = sellbreak1[-1]+1
                                else:
                                    sellbreak = 1
                            else:
                                sellbreak = 0
                            sellbreak1.append(sellbreak)
                            #arrow plotting
                            #buy_arrow
                            buy_barssince_var = barssince(buy2[:-1],barssince_var)
                            if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                buy_arrow = 1
                            else:
                                buy_arrow = 0
                            #sell arrow
                            sell_barssince_var = barssince(sell2[:-1],barssince_var)
                            if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                sell_arrow = 1
                            else:
                                sell_arrow = 0
                            #buybreak_arrow
                            buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                            sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                            if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                buybreak_arrow = 1
                            else:
                                buybreak_arrow = 0
                            #sellbreak_arrow
                            if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                sellbreak_arrow = 1
                            else:
                                sellbreak_arrow = 0
                            if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'green'
                            elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'red'
                            elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                arrow_color = 'aqua'
                            elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                arrow_color = 'blue'
                            else:
                                arrow_color = 'none'
                            df.loc[i,'arrow_color'] = arrow_color
                        df = df[['date','open','high','low','close','arrow_color']]
                        return df
                    df=super_guppy(15,df)
                    gup=pd.DataFrame(df)
                    def bidatrema(df,period):
                        df['hl']=abs(df['high']-df['low'])
                        df['hpc']=abs(df['high']-df['close'].shift())
                        df['lpc']=abs(df['low']-df['close'].shift())
                        df['tr']=df[['hl','hpc','lpc']].max(axis=1)
                        df['ATR']=pd.DataFrame.ewm(df["tr"], span=period,min_periods=period).mean()
                        df.drop(["hl","hpc","lpc","tr"],axis = 1 , inplace =True)
                    bidatrema(gup,14)
                    print(" \n \t \t \t \t  GUPPY GREEN _ RED PROFIT BOOKING  ")
                    print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                    now_utc = datetime.now(timezone('UTC'))
                    now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                    now_asia = now_asia.strftime("%Y-%m-%d _ %H:%M:%S ")
                    klp1=now_asia
                    prog_starts.append(klp1)
                    print("\n ")
                    print("Zerodha GUPPY BUY BOT start Time             "  , prog_starts[0])
                    print("\n ")
                    print("BOT working succeesfully on time:             "  , now_asia )
                    print("\n ")
                    print("Trading symbol is",ttradingsymbol,"Token is",ttoken,"Exchange is",eexchange,"and product type is",productt,"Quantity is",qu,"time frame for Historical Data is",time_frame,"Starting and Ending Date of Historical Data is",sdate,todate)
                    colourstill.append(gup.iloc[-1,5])
                    print(" \n ")
                    print("  Completed with 'GREEN' entry=", len(green_time))
                    print("  Completed with 'RED'   entry=", len(red_time))
                    print("\n ")
                    print("\n ")
                    if 0 in counter_start:
                        if "green" in gup.iloc[-1,5]:     
                            counter_start.remove(0)
                            counter_start.append(1)
                        else:
                            pass
                    if 2 in counter_start:
                        print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                        if "red" in gup.iloc[-1,5]:
                            if 0 in counter:
                                quant=qu
                                xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                price_sell=avg_ha(xa)
                                xb=price_sell-float(gup.iloc[-1,6])*0.1
                                triger_sell=avg_ha(xb)
                                triggerprice_sell=avg_ha(triger_sell)
                                kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price= price_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="testR")
                                print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and price is",price_sell, "quantity is",quant)
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)
                        if 1 in counter:
                            print("checking red execution")
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                            match_in_int=int(match_in)
                            print("checking executed or not condition ")
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and waiting for red " )
                                execution.append(1)
                            else:
                                print("SORRY! red not executed")
                                pass
                        if "green" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 1 in execution:
                                    #check execution of green
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                    print("programe completed with red entry and end with green entry")
                                    counter.clear()
                                    counter_start.clear()
                                    execution.clear()
                                    linkedlist_1.clear()
                                    execution.clear()
                                    counter_start.append(0)
                                    red_time.append(1)
                                else:
                                    pass
                            else:
                                pass
                    if 1 in counter_start:
                        print(" BOT STARTED WITH GREEN ' BUY' ENTRY ")
                        if "green" in gup.iloc[-1,5]:
                            if 0 in counter:
                                quant=qu
                                xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                cur_high=avg_ha(xa)
                                xb=cur_high+float(gup.iloc[-1,6])*0.1
                                lim_price=avg_ha(xb)
                                kite_drop=kite.place_order( variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="testR")
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)
                        if 1 in counter:
                            print("checking green execution")
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                            match_in_int=int(match_in)
                            print("checking green executed or not condition ")
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and waiting for red " )
                                execution.append(1)
                            else:
                                print("SORRY GREEN NOT EXECUTED")
                                pass
                        if "red" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 1 in execution:
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="testG")
                                    print("programe completed with green entry and end with RED entry")
                                    green_time.append(1)
                                    counter.clear()
                                    counter_start.clear()
                                    execution.clear()
                                    linkedlist_1.clear()
                                    execution.clear()
                                    counter_start.append(0)
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
        ashis()
    if "SELL"==manually:
        print("SELL BOT STARTED Manually")
        #calculation
        def avg_ha(x):
            a=list(modf(round(x,3)))
            d=str(a[0])
            aa=str(d[0:2])
            try:
                ab=str(d[2])
            except:
                ab='0'
            try:
                ac=str(d[3])
            except:
                ac='0'
            try:
                ad=str(d[4])
            except:
                ad='0'
            c=aa+ab+ac+ad
            b=0
            if a[0]!=0:
                astr=c
                a0=astr[0]
                a1=astr[1]
                a3=int(astr[2])
                a2=int(astr[3:5])
                if a2>=0 and a2<25:
                    a2=0
                elif a2>=25 and a2<75:
                    a2=5
                elif a2>=75 and a2<=99:
                    a3+=1
                    a2=0
                aint=a0+a1+str(a3)+str(a2)
                a[0]=float(aint)
            for k in a:
                b+=k
            return b

        print("WELCOME TO GUPPY SELL PROFIT BOOKING BOT ! ")
        print(" \n ")
        ttradingsymbol =str(input("ENTER TRADINGSYMBOL - SUNPHARMA / SBIN :-")).upper()
        eexchange      =str(input("ENTER EXCHANGE / NSE / BSE / CDS  :-")).upper()
        productt       =str(input("ENTER PRODUCT / NRML /CNC / MIS  :-")).upper()
        qu             =int(input("ENTER QUANTITY - 2 / 4 :-"))
        time_frame     =str(input("ENTER TIME_FRAME - minute / 5minute  :-")).lower()
        sdate          ="2019-05-05"
        todate         ="2020-10-02"
        ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+ttradingsymbol)).iloc[-2,0])
        counter_start=[0]
        linkedlist_1=[]       
        linkedlist_2=[]      
        linkedlist_3=[]      
        counter=[0,10] 
        execution=[]
        checkfirst=[0]   
        red_time=[]
        green_time=[]
        redb=[]             
        bluez=[]            
        aqua1=[0]           
        bluein=[]           
        blue_2F=[]          
        blue_2G=[]          
        count_sectime=[]
        redc=[]
        colourstill=[]
        prog_starts=[]
        #Variables
        lst_candle=[]
        lst_heikin_nor=[]
        lst_heikin=[]
        lst_cand=[]
        lst_c=[]
        countstart=0
        #programe start
        def ashis():
            while(True):
                km=datetime.now().minute
                ks=datetime.now().second
                if km%1==0 and ks==1:
                    clear_output(wait=True)  
                    now_utc = datetime.now(timezone('UTC'))
                    now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                    now_asia = now_asia.strftime("%S ")
                    klp1=now_asia
                    dff=kite.historical_data(ttoken,sdate,todate,time_frame,0)
                    #time.sleep(1)
                    dfw=pd.DataFrame(dff)[:-1]
                    df=pd.DataFrame(dfw[['date','open','high','low','close']])
                    slow_ema = [3,5,7,9,11,13,15,17,19,21,23]
                    fast_ema = [25,28,31,34,37,40,43,46,49,52,55,58,61,64,67,70,200]
                    def EMA(df, base, target, period, alpha=False):
                        con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]])
                        if (alpha == True):
                            # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period
                            df[target] = con.ewm(alpha=1 / period, adjust=False).mean()
                        else:
                            # ((current_val - previous_val) * coeff) + previous_val where coeff = 2 / (period + 1)
                            df[target] = con.ewm(span=period, adjust=False).mean()
                        df.fillna(0,inplace = True)
                    #     return df
                    for j in slow_ema:
                        val = "ema"+"_"+str(j)
                        EMA(df,"close",val,j)
                    for k in fast_ema:
                        val = "ema"+"_"+str(k)
                        EMA(df,"close",val,k)
                    def super_guppy(interval,df,anchor=0):
                    #     df['buy'] = 0
                    #     df['sell'] = 0
                    #     df['buybreak'] = 0
                    #     df['sellbreak'] = 0
                        anchor = 0
                        ShowBreak = True
                        ShowSwing = True
                        ShowCon = False
                        uOCCswing = False
                        Lookback = 6
                        emaFilter = False
                        mult = 0
                        buybreak = 0
                        sellbreak = 0
                        buy_barssince_var = 0
                        sell_barssince_var = 0
                        buybreak_barssince_var = 0
                        sellbreak_barssince_var = 0
                        barssince_lst = list()
                        barssince_var = 0
                        bar_count_var = 0
                        buy1 = list()
                        sell1 = list()
                        buy2 = list()
                        sell2 = list()
                        buybreak1 = list()
                        sellbreak1 = list()
                        def barssince(b,barssince_var):
                            barssince_lst = []
                            barssince_var = 0 
                            new_var = len(b)
                            for i in b[::-1]:
                                if i == 1:
                                    break
                                barssince_lst.append(i)
                            barssince_var = len(barssince_lst)
                            return barssince_var
                            barssince_lst.clear()
                        #isIntraday
                        if interval < 1441 :
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor > 1441 ):
                                mult = 1
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = 1
                        #isIntraday Not
                        if interval > 1441:
                            if (anchor==0 or interval <= 0 or interval >= anchor or anchor < 52 ):
                                mult = mult
                            else:
                                if round(anchor/interval) > 1:
                                    mult = round(anchor/interval)
                                else:
                                    mult = 1
                        else:
                            mult = mult
                        mult = 1
                        for i in range(len(df)):
                            emaF1 = df.loc[i,'ema_3']
                            emaF2 = df.loc[i,'ema_5']
                            emaF3 = df.loc[i,'ema_7']
                            emaF4 = df.loc[i,'ema_9']
                            emaF5 = df.loc[i,'ema_11']
                            emaF6 = df.loc[i,'ema_13']
                            emaF7 = df.loc[i,'ema_15']
                            emaF8 = df.loc[i,'ema_17']
                            emaF9 = df.loc[i,'ema_19']
                            emaF10 = df.loc[i,'ema_21']
                            emaF11 = df.loc[i,'ema_23']
                            emaS1 = df.loc[i,'ema_25']
                            emaS2 = df.loc[i,'ema_28']
                            emaS3 = df.loc[i,'ema_31']
                            emaS4 = df.loc[i,'ema_34']
                            emaS5 = df.loc[i,'ema_37']
                            emaS6 = df.loc[i,'ema_40']
                            emaS7 = df.loc[i,'ema_43']
                            emaS8 = df.loc[i,'ema_46']
                            emaS9 = df.loc[i,'ema_49']
                            emaS10 = df.loc[i,'ema_52']
                            emaS11 = df.loc[i,'ema_55']
                            emaS12 = df.loc[i,'ema_58']
                            emaS13 = df.loc[i,'ema_61']
                            emaS14 = df.loc[i,'ema_64']
                            emaS15 = df.loc[i,'ema_67']
                            emaS16 = df.loc[i,'ema_70']
                            ema200 = df.loc[i,'ema_200'] 
                            emafast = (emaF1 + emaF2 + emaF3 + emaF4 + emaF5 + emaF6 + emaF7 + emaF8 + emaF9 + emaF10 + emaF11)/11
                            emaslow = (emaS1 + emaS2 + emaS3 + emaS4 + emaS5 + emaS6 + emaS7 + emaS8 + emaS9 + emaS10 + emaS11 + emaS12 + emaS13 + emaS14 + emaS15 + emaS16)/16
                            #Fast EMA Color Rules
                            colfastL = (emaF1>emaF2 and emaF2>emaF3 and emaF3>emaF4 and emaF4>emaF5 and emaF5>emaF6 and emaF6>emaF7 and emaF7>emaF8 and emaF8>emaF9 and emaF9>emaF10 and emaF10>emaF11)
                            colfastS = (emaF1<emaF2 and emaF2<emaF3 and emaF3<emaF4 and emaF4<emaF5 and emaF5<emaF6 and emaF6<emaF7 and emaF7<emaF8 and emaF8<emaF9 and emaF9<emaF10 and emaF10<emaF11)
                            #Slow EMA Color Rules
                            colslowL = (emaS1>emaS2 and emaS2>emaS3 and emaS3>emaS4 and emaS4>emaS5 and emaS5>emaS6 and emaS6>emaS7 and emaS7>emaS8) and (emaS8>emaS9 and emaS9>emaS10 and emaS10>emaS11 and emaS11>emaS12 and emaS12>emaS13 and emaS13>emaS14 and emaS14>emaS15 and emaS15>emaS16)
                            colslowS = (emaS1<emaS2 and emaS2<emaS3 and emaS3<emaS4 and emaS4<emaS5 and emaS5<emaS6 and emaS6<emaS7 and emaS7<emaS8) and (emaS8<emaS9 and emaS9<emaS10 and emaS10<emaS11 and emaS11<emaS12 and emaS12<emaS13 and emaS13<emaS14 and emaS14<emaS15 and emaS15<emaS16)
                            if  emafast > emaslow and not colslowS and colfastL and (not ShowCon or colslowL) and (not emaFilter or emafast>ema200):
                                if int(buy1[-1]) > 0:
                                    buy = buy1[-1] + 1
                                else:
                                    buy = 1
                            else:
                                buy = 0
                            buy1.append(buy)
                            if  emafast < emaslow and not colslowL and colfastS and (not ShowCon or colslowS) and (not emaFilter or emafast<ema200):
                                if int(sell1[-1]) > 0:
                                    sell = sell1[-1] + 1
                                else:
                                    sell = 1
                            else:
                                sell = 0
                            sell1.append(sell)
                            #buy
                            if buy>1 and colfastL and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                buy3 = 1
                            else:
                                buy3 = buy
                            buy2.append(buy3)
                            #sell    
                            if sell>1 and colfastS and (uOCCswing and ((df.loc[i-1,'close']<df.loc[i-1,'open']) and (df.loc[i,'close']>df.loc[i,'open']))):
                                sell3 = 1
                            else:
                                sell3 = sell
                            sell2.append(sell3)
                            #buybreak
                            if emafast > emaslow and not colslowS and (not emaFilter or emafast>ema200):
                                if buybreak1[-1] > 0:
                                    buybreak = buybreak1[-1] + 1
                                else:
                                    buybreak = 1
                            else:
                                buybreak = 0
                            buybreak1.append(buybreak)
                            if emafast < emaslow and not colslowL and (not emaFilter or emafast<ema200):
                                if sellbreak1[-1] > 0:
                                    sellbreak = sellbreak1[-1]+1
                                else:
                                    sellbreak = 1
                            else:
                                sellbreak = 0
                            sellbreak1.append(sellbreak)
                            #arrow plotting
                            #buy_arrow
                            buy_barssince_var = barssince(buy2[:-1],barssince_var)
                            if (ShowSwing and buy3==1)and buy_barssince_var > 6:
                                buy_arrow = 1
                            else:
                                buy_arrow = 0
                            #sell arrow
                            sell_barssince_var = barssince(sell2[:-1],barssince_var)
                            if ShowSwing and (sell3==1 and sell_barssince_var > 6):
                                sell_arrow = 1
                            else:
                                sell_arrow = 0
                            #buybreak_arrow
                            buybreak_barssince_var = barssince(buybreak1[:-1],barssince_var)
                            sellbreak_barssince_var = barssince(sellbreak1[:-1],barssince_var)

                            if ShowBreak and buybreak==1 and (sellbreak_barssince_var>Lookback) and (buybreak_barssince_var>Lookback):
                                buybreak_arrow = 1
                            else:
                                buybreak_arrow = 0
                            #sellbreak_arrow
                            if ShowBreak and sellbreak==1 and (buybreak_barssince_var>Lookback) and (sellbreak_barssince_var>Lookback):
                                sellbreak_arrow = 1
                            else:
                                sellbreak_arrow = 0
                            if buy_arrow==1 and sell_arrow==0 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'green'
                            elif buy_arrow==0 and sell_arrow==1 and buybreak_arrow==0 and sellbreak_arrow==0:
                                arrow_color = 'red'
                            elif sell_arrow==0 and (buy_arrow==0 or buy_arrow==1) and buybreak_arrow==1 and sellbreak_arrow==0:
                                arrow_color = 'aqua'
                            elif buy_arrow==0 and (sell_arrow==1 or sell_arrow==0) and buybreak_arrow==0 and sellbreak_arrow==1:
                                arrow_color = 'blue'
                            else:
                                arrow_color = 'none'
                            df.loc[i,'arrow_color'] = arrow_color
                        df = df[['date','open','high','low','close','arrow_color']]
                        return df
                    df=super_guppy(15,df)
                    gup=pd.DataFrame(df)
                    def bidatrema(df,period):
                        df['hl']=abs(df['high']-df['low'])
                        df['hpc']=abs(df['high']-df['close'].shift())
                        df['lpc']=abs(df['low']-df['close'].shift())
                        df['tr']=df[['hl','hpc','lpc']].max(axis=1)
                        df['ATR']=pd.DataFrame.ewm(df["tr"], span=period,min_periods=period).mean()
                        df.drop(["hl","hpc","lpc","tr"],axis = 1 , inplace =True)
                    bidatrema(gup,14)
                    print(" \n \t \t \t \t  GUPPY SELL PROFIT BOOKING  ")
                    print(" \t \t \t \n Current Colour on this token is " , gup.iloc[-1,5])
                    now_utc = datetime.now(timezone('UTC'))
                    now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                    now_asia = now_asia.strftime("%Y-%m-%d _ %H:%M:%S ")
                    klp1=now_asia
                    prog_starts.append(klp1)
                    print("\n ")
                    print("Zerodha GUPPY SELL BOT start Time             "  , prog_starts[0])
                    print("\n ")
                    print("BOT working succeesfully on time:             "  , now_asia )
                    print("\n ")
                    print("Trading symbol is",ttradingsymbol,"Token is",ttoken,"Exchange is",eexchange,"and product type is",productt,"Quantity is",qu,"time frame for Historical Data is",time_frame,"Starting and Ending Date of Historical Data is",sdate,todate)
                    colourstill.append(gup.iloc[-1,5])
                    print(" \n ")
                    print("  Completed with 'GREEN' entry=", len(green_time))
                    print("  Completed with 'RED'   entry=", len(red_time))
                    print("\n ")
                    print("\n ")
                    if 0 in counter_start:
                        if "red" in gup.iloc[-1,5]:
                            counter_start.remove(0)
                            counter_start.append(2)
                        #if "green" in gup.iloc[-1,5]:     
                            counter_start.remove(0)
                            counter_start.append(1)
                        else:
                            pass
                    if 2 in counter_start:
                        print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                        if "red" in gup.iloc[-1,5]:
                            if 0 in counter:
                                quant=qu
                                xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                price_sell=avg_ha(xa)
                                xb=price_sell-float(gup.iloc[-1,6])*0.1
                                triger_sell=avg_ha(xb)
                                triggerprice_sell=avg_ha(triger_sell)
                                kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price= price_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="testR")
                                print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and price is",price_sell, "quantity is",quant)
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)
                        if 1 in counter:
                            print("checking red execution")
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                            match_in_int=int(match_in)
                            print("checking executed or not condition ")
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and waiting for red " )
                                execution.append(1)
                            else:
                                print("SORRY! red not executed")
                                pass
                        if "green" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 1 in execution:
                                    #check execution of green
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                    print("programe completed with red entry and end with green entry")
                                    counter.clear()
                                    counter_start.clear()
                                    execution.clear()
                                    linkedlist_1.clear()
                                    execution.clear()
                                    counter_start.append(0)
                                    red_time.append(1)
                                else:
                                    pass
                            else:
                                pass
                    if 1 in counter_start:
                        print(" BOT STARTED WITH GREEN ' BUY' ENTRY ")
                        if "green" in gup.iloc[-1,5]:
                            if 0 in counter:
                                quant=qu
                                xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                cur_high=avg_ha(xa)
                                xb=cur_high+float(gup.iloc[-1,6])*0.1
                                lim_price=avg_ha(xb)
                                kite_drop=kite.place_order( variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="testR")
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)
                        if 1 in counter:
                            print("checking green execution")
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==linkedlist_1[0]].index 
                            match_in_int=int(match_in)
                            print("checking green executed or not condition ")
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and waiting for red " )
                                execution.append(1)
                            else:
                                print("SORRY GREEN NOT EXECUTED")
                                pass
                        if "red" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 1 in execution:
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="testG")
                                    print("programe completed with green entry and end with RED entry")
                                    green_time.append(1)
                                    counter.clear()
                                    counter_start.clear()
                                    execution.clear()
                                    linkedlist_1.clear()
                                    execution.clear()
                                    counter_start.append(0)
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
        ashis()
        
				
			

Output – 

				
					Zerodha GUPPY SCREENER on 5 minute Data
	 	 	 
 Current Token checking   975873


 	 	 	 
 Current Colour on this token is  none
Buy stock found  are  := [784129]
Sell stocks found  are:= []
 Scanning is complete 
SYMBOLS_BUY	TOKENS_BUY	Price
0	784129	VEDL	140.4
SYMBOLS_SELL	TOKENS_SELL	Price
YES ! Some buy stock found
BUY LESS THEN 2000 [784129]
BUY grater then 2000 []
SELL less then 2000 []
SELL GREATER THEN 2000 []
sorry no order found of  SELL 
				
			

The Guppy strategy in this script is a comprehensive approach for analyzing stock trends using EMAs. 

It’s designed to capture both short-term movements and long-term trends, offering traders insights into potential buy and sell opportunities based on the alignment of EMAs. By analyzing multiple time frames, the script aims to provide a robust analysis for traders looking to capitalize on various market movements.

Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

×Close