Guppy Strategy Indicator 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. 

Buy Sell Bot on Guppy Indicator with 4 colors

Beginning with the creation of a Guppy Strategy screener, I progressed to developing a Guppy trading bot, and have now advanced to designing a sophisticated buy and sell bot based on the Guppy indicator.

Overview of the Buy and Sell Trading Bot Based on Guppy Indicator:

Core Concept:

The bot operates using the Guppy Moving Average Indicator, a tool that combines multiple exponential moving averages (EMAs) to identify changing trends, strengths, and potential buy or sell opportunities in the market.

Operational Mechanism:

  • Initial Analysis: The bot analyzes the EMAs of different lengths, as used in the Guppy indicator, to assess the current market trend and momentum.
  • Buy/Sell Decisions: Based on the alignment and positioning of short-term and long-term EMAs, the bot makes buy or sell decisions. Generally, when shorter-term EMAs cross above longer-term ones, it indicates a potential buy signal. Conversely, a sell signal is suggested when short-term EMAs cross below the long-term EMAs.

Advanced Features:

  • Conditional Execution: Similar to your previous Guppy strategy bot, this bot may include conditional execution, where the execution of buy or sell orders depends on specific market conditions or the outcome of previous orders.
  • Dynamic Adjustment: The bot can dynamically adjust its positions (buy or sell more) based on the ongoing market trends as indicated by the Guppy indicator.

Guppy Strategy Overview for the Trading Bot:

  1. Initial Buy Condition (Green Signal):

    • Action A: Buy ‘X’ amount of stock.
  2. First Intermediate Condition (Blue Signal):

    • Action Z (Conditional): If Action A (buy order) has been executed, sell half (X/2) of the bought amount.
  3. Sell or Adjust Position (Red Signal):

    • Action B (Conditional): If Action A has been executed, sell double the amount (2X).
    • Action C (Conditional): If Action A has not been executed, cancel Action A and sell ‘X’ amount of stock.
  4. Post-Sell Adjustment (Aqua Signal):

    • Action D (Conditional): If Action B has been executed, buy back half (X/2) of the sold amount (market order).
    • Action E (Conditional): If Action C has been executed, buy back half (X/2) of the sold amount (market order).
  5. Re-Entry or Adjustment (Green Signal – Part A):

    • Action F (Conditional): If Action B was executed, buy double the initial amount (2X).
    • If Action B was not executed, cancel Action B and wait for a Red signal.
  6. Re-Entry or Adjustment (Green Signal – Part B):

    • Action G (Conditional): If Action C was executed, buy double the initial amount (2X).
    • If Action C was not executed, cancel Action C and wait for a Red signal.
  7. Sell Post-Re-Entry (Aqua Signal – Case A):

    • Action H (Conditional): If both Action F and D were executed, sell half (X/2) of the bought amount.
    • If Action F was executed but Action D was not, cancel Action D.
  8. Sell Post-Re-Entry (Aqua Signal – Case B):

    • Action I (Conditional): If both Action G and E were executed, sell half (X/2) of the bought amount.
    • If Action G was executed but Action E was not, cancel Action E.
  9. Final Adjustment (Blue Signal):

    • If Action F was executed, sell half (X/2) of the stock (market order).
    • If Action G was executed, sell half (X/2) of the stock (market order).
  10. Restart Cycle (Red Signal):

    • Return to the initial strategy phase and continue from the Red signal conditions.

Key Points:

  • The bot follows a color-coded signal strategy: Green, Blue, Red, and Aqua.
  • Each signal triggers specific conditional actions involving buying, selling, or adjusting stock positions.
  • The bot’s actions are contingent upon the execution status of previous orders, creating a dynamic trading pattern.
  • The strategy loops, restarting the cycle after certain conditions are met.
				
					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 :-"))


if "YES"==scan or "yes"==scan:
    # for SCANNING OF STOCKS
    
    print("SCANNING START")

    # all nifty_50 symbols
    
    z=list(set(instrumentList[instrumentList['segment'] == 'NFO-FUT']["name"].to_list()))
# INPUTS FOR THE BOT

    eexchange="NSE"
    time_frame     ="5minute"
    sdate = (date.today() - timedelta(days=15)).strftime("%Y-%m-%d")
    todate = date.today().strftime("%Y-%m-%d")
    tokenall=[]
    aa=0
    print("  \t \t \t \n Getting All tokens for processing BUY SELL ")
    # FETCHING ALL TOKENS FROM SYMBOL
    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
    BUY_listindicator=[]
    SELL_listindicator=[]
    print(a)
    
    def ashi():
        global a
        global BUY_listindicator
        global SELL_listindicator
        # INDICATOR
        
        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]))
                if "red" in gup.iloc[-1,5]:
                    print(" SELL stock found ")
                    sell5minute.append((tokenall[a]))
                else:
                    pass
                print("Buy stock found for 5 minute are  :="  ,buy5minute)
                print("Sell stocks found for 5 minute are:="  ,sell5minute)
                a=a+1
                if a==len(tokenall): # ALL TOKENS ARE SCANNED
                    
                    file=str(buy5minute)
                    filee=str(sell5minute)
                    with open("tokens.txt","w") as  f:
                        f.write(file)
                        f.write(filee)
                    break
                
    ashi()
    
    # START SCANNINF FOR FIRST 5 MINUTE TOKEN BUY/SELL
    
    print("5 minute data complete! Now getting Data of 15 minutes ")
    time_frame     ="15minute"
    a=0
    def ashi15():
        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 15 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 ")
                    buy10minute.append((tokenall[a]))
                if "red" in gup.iloc[-1,5]:
                    print(" Sell Stock found ")
                    sell10minute.append((tokenall[a]))
                else:
                    pass
                print("Buy stock found for 15 minute are  :="  ,buy10minute)
                print("Sell stocks found for 15 minute are:="  ,sell10minute)
                a=a+1
                if a==len(tokenall):
                    file=str(buy5minute)
                    filee=str(sell5minute)
                    file2=str(buy10minute)
                    filee2=str(sell10minute)
                    with open("tokens.txt","w") as  f: # WRITIG ALL DATA TO FILE
                        f.write(file)
                        f.write(filee)
                        f.write(file2)
                        f.write(filee2)
                    break

    ashi15()
    
    # NOW SCANNING FOR 30 MINUTE TOKENS BUY/SELL
    
    print("5 and 15 minute data complete now getting Data of 30 minutes of minute frame")
    time_frame     ="30minute"
    a=0
    def ashi30():
        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 for 30 minute Data")
                print("\n" )
                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 ")
                    buy15minute.append((tokenall[a]))
                if "red" in gup.iloc[-1,5]:
                    print(" SELL Stock found ")
                    sell15minute.append((tokenall[a]))
                else:
                    pass
                print("Buy stock found for 30 minute are  :="  ,buy15minute)
                print("Sell stocks found for 30 minute are:="  ,sell15minute)
                a=a+1
                if a==len(tokenall):
                    file=str(buy5minute)
                    filee=str(sell5minute)
                    file2=str(buy10minute)
                    filee2=str(sell10minute)
                    file3=str(buy15minute)
                    filee3=str(sell15minute)
                    with open("tokens","w") as  f:
                        f.write(file)
                        f.write(filee)
                        f.write(file2)
                        f.write(filee2)
                        f.write(file3)
                        f.write(filee3)
                        print("SCANNING COMPLETE")
                    break
    ashi30()
    
    # SHOWING RESULTS FOR ALL THREE SCANNING
    
    print("5 ,15 and 30 are completed ! Results are ")
    print("\n" )
    print("tokens we get on 5 minute BUY  "  ,buy5minute)
    print("tokens we get on 5 minute SELL " ,sell5minute)
    print("\n" )
    print("tokens we get on 15 minute BUY  "  ,buy10minute)
    print("tokens we get on 15 minute SELL " ,sell10minute)
    print("\n" )
    print("tokens we get on 30 minute BUY  " ,buy15minute)
    print("tokens we get on 30 minute SELL ",sell15minute)
    print("\n")
    
    k=set(buy5minute)
    n=set(sell5minute)
    l=set(buy10minute)
    s=set(sell10minute)
    m=set(buy15minute)
    p=set(sell15minute)
    buya=n|s|p
    sellb=k|l|m
    
    print("\n")
    print("BUY from ALL  ",sellb)
    print("SELL From ALL ",buya)
    print("\n")
    print("  \t \t \t \t \tBUY | SELL on 5 MINUTE")
    print("BUY")
    ee=0
    buy_5minute=[]
    sell_5minute=[]
    buy_15minute=[]
    sell_15minute=[]
    buy_30minute=[]
    sell_30minute=[]
    ########################
    if buy5minute:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==buy5minute[ee]]
            buy_5minute.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(buy5minute):
                break
    print(buy_5minute)
    print("SELL")
    ee=0
    if sell5minute:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==sell5minute[ee]]
            sell_5minute.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(sell5minute):
                break
    print(sell_5minute)
    ###############################
    print("\n")
    print(" \t \t \t \t \t BUY | SELl on 15 minute")
    print("BUY")
    ee=0
    if buy10minute:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==buy10minute[ee]]
            buy_15minute.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(buy10minute):
                break
    print(buy_15minute)
    print("SELL")
    ee=0
    if sell5minute:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==sell5minute[ee]]
            sell_15minute.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(sell5minute):
                break
    print(sell_15minute)
    ####################################
    print("\n")
    print(" \t \t \t \t \t BUY | SELl on 30 minute")
    print("BUY")
    ee=0
    if buy15minute:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==buy15minute[ee]]
            buy_30minute.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(buy15minute):
                break
    print(buy_30minute)
    print("SELL")
    ee=0
    if sell15minute:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==sell15minute[ee]]
            buy_30minute.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(sell15minute):
                break
    print(sell_30minute)
    print(" \n ")
    print(" \t \t \t \t \t OVERALL BUY  SELL ")
    print(" \n ")
    print(" OVERALL -  BUY ", buy_5minute,buy_15minute,buy_30minute)
    print(" OVERALL - SELL" , sell_5minute,sell_15minute,sell_30minute)
    print(" \n ")
    print(" \t \t \t \t \t COMMON BUY-SELL After filter ")
    abuy=list(buya)
    buy_set=[]
    ee=0
    if sell15minute:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==abuy[ee]]
            buy_set.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(abuy):
                break
    asell=list(sellb)
    sell_set=[]
    ee=0
    if asell:
        while (True):
            df=pd.DataFrame(kite.instruments("NSE"))[["instrument_token","tradingsymbol","name"]]
            zall=df[df["instrument_token"]==asell[ee]]
            sell_set.append(zall.iloc[-1,1])
            ee=ee+1
            if ee==len(asell):
                break
    print(" OVERALL BUY" ,buy_set)
    print(" OVERALL SELL",sell_set)
    print("\t \t \t \t \t !! ALL COMPLETED !!")
    print(" \n ")
    ############################################
    print("WELCOME TO GUPPY BOT ! ENTER 'BUY' or 'SELL', which you want")
    user=str(input(" ENTER BUY or SELL :-"))
    print(" ** ENTER ALL DETAILS IN CAPITAL LETTERS ONLY **")
    ttradingsymbol =str(input("ENTER TRADINGSYMBOL - SUNPHARMA / SBIN :-"))
    eexchange      =str(input("ENTER EXCHANGE / NSE / BSE / CDS  :-"))
    productt       =str(input("ENTER PRODUCT / NRML /CNC / MIS  :-"))
    qu             =int(input("ENTER QUANTITY - 2 / 4 :-")) 
    time_frame     =str(input("ENTER TIME_FRAME - minute / 5minute **SMALL letters only** :-"))
    sdate          ="2019-06-05"
    todate         ="2020-10-02"
    buy_add=.50
    sell_add=.50
    ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+ttradingsymbol)).iloc[-2,0])
    ###
    if "SELL"==user or "sell"==user:
        print(" SELL BOT STARTED After Scanning ! ")
        counter_start=[0]
        linkedlist_1=[]       
        linkedlist_2=[]      
        linkedlist_3=[]      
        counter=[0,10]      
        checkfirst=[0]      
        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
                    #df=kite.historical_data(140033,sdate,todate,time_frame,0)
                    dff=kite.historical_data(ttoken,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=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  ZERODHA GUPPY BOT ")
                    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 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("\n ")
                    if 0 in counter_start:
                        if "red" in gup.iloc[-1,5]:
                            counter_start.remove(0)
                            counter_start.append(2)
                        else:
                            pass
                    if 2 in counter_start:
                        print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                        if "blank" in gup.iloc[-1,5]:
                            print(" Nothing Done BUT BOT started no candel colour occur ")
                        if "red" in gup.iloc[-1,5]:
                            if 0 in counter:
                                #SELl X amount                   #-------------------------------------------------------- (A)
                                quant=qu
                                stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                triggerprice_sell=stoploss_sell-sell_add
                                #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="A")
                                kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="A")
                                print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)
                        if "aqua" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 10 in counter:
                                    print("aqua Comes checking blue condition @ is previous green executed or not ?") # (A)
                                    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 now buy x/2" )
                                        quant=int(qu/2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="Z")
                                        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="Z")
                                        linkedlist_2.insert(0,kite_drop)
                                        counter.remove(10) # -------------------------- ( Z )
                                        bluez.append(0)
                                    else:
                                        print(" sell not executed  ")
                        if "green" in gup.iloc[-1,5]:
                            if 1 in counter:                                              
                                print("checking previous green executed or not ") 
                                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 now BUY x/2" )
                                    quant=int(2*qu)
                                    cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                    lim_price=cur_high+buy_add
                                    print("Congrats ! No1 Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="B")
                                    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="B")
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(1)
                                    counter.append(2)
                                    redb.append(0)                                 # ------------------------ ( B )
                                else:
                                    print("aqua bid not complete now canceled aqua bid and place fresh BUY of x amount")
                                    bid_not_ex=int(linkedlist_1[0])
                                    print("SL Cancel Order cancelled and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                    lim_price=cur_high+3 
                                    print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="C")
                                    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="C")
                                    linkedlist_3.insert(0,kite_drop)     #  ------------ -------------- ( C )
                                    counter.remove(1)
                                    counter.append(2) 
                                    redc.append(0)
                                                    #       *********************** checking condition *********************
                        if 0 in bluez:
                            if 2 in counter:
                                if 0 in checkfirst:
                                    print(" green placed and now checking RED executed or not condition ")
                                    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)
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        print(" green executed ")
                                        print(" Now checkingaqua executed or not")
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                        match_in_int=int(match_in)
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            print(" yes BLUE executed ")
                                            print(" BOTH aqua and green executed and now placig order qu/2 ")
                                            quant=int(qu/2)
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="BZ")
                                            print("Z and B both executed and market order placed", "quantity is",quant)
                                        else:
                                            print("Z not executed ")
                                            bid_not_ex=int(linkedlist_2[0])
                                            print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                                                        #  *************** comming from back ****************  
                        if 0 in count_sectime:
                            if 2 in counnter:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="BZ")
                                        print("both executed and market order placed comming from back again", "quantity is",quant)
                                        count_sectime.remove(1)
                                    else:
                                        print("Z not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        count_sectime.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if "blue" in gup.iloc[-1,5]:
                            if 2 in counter:
                                if 0 in aqua1:
                                    if 0 in redb:
                                        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"]:
                                            # ( NOW SELL X/2 )         #------------------------------ ( D )
                                            quant=int(qu/2)
                                            stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                            triggerprice_sell=stoploss_sell-sell_add
                                            #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="D")
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="D")
                                            print("Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                            linkedlist_3.append(0,kite_drop)                
                                            aqua1.remove(0)          
                                            aqua1.append(1)
                                        else:
                                            pass
                                    if 0 in redc:
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                        match_in_int=int(match_in)
                                        print("checking executed or not condition ")
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            quant=int(qu/2)
                                            stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                            triggerprice_sell=stoploss_sell-sell_add
                                            #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="E")
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="E")
                                            print(" aqua Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                            linkedlist_2.insert(0,kite_drop)            
                                            aqua1.remove(0)
                                            aqua1.append(2)              #------------------------ ( E )
                                        else:
                                            pass
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "red" in gup.iloc[-1,5]:
                            if 2 in counter:
                                # (  PART B ) 
                                if 0 in redb:
                                    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"]:
                                        quant=int(qu*2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="F")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="F")
                                        print(" Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(2)
                                        counter.append(3)
                                        counter.append(1)        # #----------------------- ( F )
                                        redb.remove(0)
                                        checkfirst.append(0)
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_1[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for green again")
                                        linkedlist_1[0]=linkedlist_1[-1]
                                        counter.remove(2)
                                        counter.append(1)                                   
                                        redb.remove(0)                      
                                        checkfirst.append(0)
                                        counter.append(10)
                                # (  PART B )
                                if 0 in redc:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu*2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="G")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="G")
                                        print(" aqua Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                        linkedlist_1.insert(0,kite_drop) 
                                        counter.remove(2)
                                        counter.append(4)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)       #  ------------------------(  G )
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for green again")
                                        counter.remove(2)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)
                                        counter.append(10)  
                            else:
                                pass
                                               #   *********** checking condition 2nd time *************
                        if 3 in counter:
                            if 1 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="2Chk")
                                        print("both executed and market order placed comming from back again B and Z")
                                        aqua1.remove(1)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if 4 in counter:
                            if 2 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="2BZ")
                                        print(" G and E !both executed and market order placed comming from back again", "quantity is",quant)
                                        aqua1.remove(2)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" aqua Cancel and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(2)
                                else:
                                    pass
                            else:
                                pass
                        if "aqua" in  gup.iloc[-1,5]:
                            if 3 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats !  Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="H")
                                        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="H")
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2F.append(1)                                       
                                        bluein.remove(0)
                                        bluez.append(0)
                                        counter.remove(3)              # -------------------------- ( H )
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "aqua" in  gup.iloc[-1,5]:
                            if 4 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="I")
                                        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="I")
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2G.append(1)                   
                                        bluein.remove(0)           #----------------------- ( I )
                                        bluez.append(0)
                                        counter.remove(3)
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass
                        print(" Orders Till Now ")
        ashis()
    if "BUY"==user or "buy"==user:
        print("BOT STARTED WITH GREEN 'BUY' ENTRY after scanning ")
        counter_start=[0]
        linkedlist_1=[]       
        linkedlist_2=[]      
        linkedlist_3=[]      
        counter=[0,10]      
        checkfirst=[0]      
        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=[]
        anchor=0
        countstart=0
        #programe start
        def ashibb():
            while(True):
                km=datetime.now().minute
                ks=datetime.now().second
                if km%1==0 and ks==1: 
                    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(ttoken,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=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  ZERODHA GUPPY BOT ")
                    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 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("\n ")
                    if 0 in counter_start:
                        if "green" in  gup.iloc[-1,5]:
                            counter_start.remove(0)
                            counter_start.append(1)
                        else:
                            pass
                    if 1 in counter_start:
                        print(" BOT STARTED WITH GREEN ENTRY ")
                        if "blank" in gup.iloc[-1,5]:
                            print(" Nothing Done BUT BOT started no candel colour occur ")
                        if "green" in gup.iloc[-1,5]:
                            if 0 in counter:
                                #BUY X amount                   #-------------------------------------------------------- (A)
                                quant=qu
                                cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                lim_price=cur_high+buy_add
                                print("Congrats ! No1 Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="A")
                                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="G1") 
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)

                        if "blue" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 10 in counter:
                                    print("Blue Comes checking blue condition @ is previous green executed or not ?") # (A)
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="Z")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="Z")
                                        print("No2 BLUE Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                        linkedlist_2.insert(0,kite_drop)
                                        counter.remove(10) # -------------------------- ( Z )
                                        bluez.append(0)
                                    else:
                                        print(" BUY not executed  ")
                        if "red" in gup.iloc[-1,5]:
                            if 1 in counter:                                              
                                print("checking previous green executed or not ") 
                                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 now SELL x/2" )
                                    quant=int(2*qu)
                                    stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                    triggerprice_sell=stoploss_sell-sell_add
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="B")
                                    kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="B")
                                    print("No3 RED Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(1)
                                    counter.append(2)
                                    redb.append(0)                                 # ------------------------ ( B )
                                else:
                                    print("BLUE bid not complete now canceled bule bid and place fresh sell of x amount")
                                    bid_not_ex=int(linkedlist_1[0])
                                    print("SL Cancel Order cancelled and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                    triggerprice_sell=stoploss_sell-5
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=qu,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="C")
                                    kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=qu,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="C")
                                    print("No1 C fresh start Sell Stoploss order placed", "quantity is",qu ,"and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell)
                                    linkedlist_3.insert(0,kite_drop)     
                                    counter.remove(1)
                                    counter.append(2)     #  ------------ -------------- ( C )
                                    redc.append(0) 
                                               #       *********************** checking condition *********************
                        if 0 in bluez: 
                            if 2 in counter:
                                if 0 in checkfirst:
                                    print(" RED placed and now checking RED executed or not condition ")
                                    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)
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        print(" RED executed ")
                                        print(" Now checking  BLUE executed or not")
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                        match_in_int=int(match_in)
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            print(" yes BLUE executed ")
                                            print(" BOTH blue and RED executed and now placig order qu/2 ")
                                            quant=int(qu/2)
                                            stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                            triggerprice_sell=stoploss_sell-sell_add
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="BZ")
                                            print("Z and B both executed and market order placed", "quantity is",quant)
                                        else:
                                            print("Z not executed ")
                                            bid_not_ex=int(linkedlist_2[0])
                                            print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                                                   #  *************** comming from back ****************   
                        if 0 in count_sectime:
                            if 2 in counnter:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="BZ")
                                        print("both executed and market order placed comming from back again", "quantity is",quant)
                                        count_sectime.remove(1)
                                    else:
                                        print("Z not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        count_sectime.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if "aqua" in gup.iloc[-1,5]:
                            if 2 in counter:
                                if 0 in aqua1:
                                    if 0 in redb:
                                        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"]:
                                            quant=int(qu/2)
                                            cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                            lim_price=cur_high+buy_add
                                            print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                            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="F") 
                                            print("in aqua and one BUY LIMIT oreder placed ",  "quantity is",quant)
                                            linkedlist_3.append(0,kite_drop)                
                                            aqua1.remove(0)          
                                            aqua1.append(1)    #------------------------------ ( D )
                                        else:
                                            pass
                                    if 0 in redc:
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                        match_in_int=int(match_in)
                                        print("checking executed or not condition ")
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            quant=int(qu/2)
                                            cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                            lim_price=cur_high+buy_add
                                            print("Congrats ! E , No1 Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                            #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="E")
                                            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="E") 
                                            linkedlist_2.insert(0,kite_drop)            
                                            aqua1.remove(0)
                                            aqua1.append(2)              #------------------------ ( E )
                                        else:
                                            pass
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "green" in gup.iloc[-1,5]:
                            if 2 in counter:
                                # (  PART B ) 
                                if 0 in redb:
                                    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"]:
                                        quant=int(qu*2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! F Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="F")
                                        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="F") 
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(2)
                                        counter.append(3)
                                        counter.append(1)
                                        redb.remove(0)             # ---------------------------( F )
                                        checkfirst.append(0)
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_1[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for red again")
                                        linkedlist_1[0]=linkedlist_1[-1]
                                        counter.remove(2)
                                        counter.append(1)                                   
                                        redb.remove(0)                      
                                        checkfirst.append(0)
                                        counter.append(10)
                                # (  PART B )
                                if 0 in redc:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu*2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! G Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="G")
                                        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="G") 
                                        linkedlist_1.insert(0,kite_drop) 
                                        counter.remove(2)
                                        counter.append(4)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)       #  ------------------------(  G )
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for red again")
                                        counter.remove(2)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)
                                        counter.append(10)  
                            else:
                                pass
                        #  *************** checking condition 2nd time *************
                        if 3 in counter:
                            if 1 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="2Chk")
                                        print("both executed and market order placed comming from back again B and Z")
                                        aqua1.remove(1)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if 4 in counter:
                            if 2 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="2BZ")
                                        print(" G and E !both executed and market order placed comming from back again", "quantity is",quant)
                                        aqua1.remove(2)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" blue Cancel and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(2)
                                else:
                                    pass
                            else:
                                pass
                        if "blue" in  gup.iloc[-1,5]:
                            if 3 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="H")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="H")
                                        print( "quantity is",quant," H blue Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell)
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2F.append(1)                                       
                                        bluein.remove(0)
                                        bluez.append(0)
                                        counter.remove(3)              # -------------------------- ( H )
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "blue" in  gup.iloc[-1,5]:
                            if 4 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="I")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="I")
                                        print( "quantity is",quant,"I blue Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell)
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2G.append(1)                   
                                        bluein.remove(0)           #----------------------- ( I )
                                        bluez.append(0)
                                        counter.remove(3)
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass
                    print("Colours Till Now")
                    print(colourstill)
                    #display(pd.DataFrame(kite.orders())[["tradingsymbol","transaction_type","status","order_id","quantity","order_type","exchange_update_timestamp",'tag',"quantity"]].tail(10))
        ashibb()
if "NO"==scan or "no"==scan:
    print("BOT STARTED WITHOUT SCREENER")
    print("\n")
    print(" which BOT you want to run ? BUY  \ SELL")
    without=str(input(" BUY  \ SELL :- " ))
    print(" ** ENTER ALL DETAILS IN CAPITAL LETTERS ONLY **")
    ttradingsymbol =str(input("ENTER TRADINGSYMBOL - SUNPHARMA / SBIN :- "))
    eexchange      =str(input("ENTER EXCHANGE - NSE / BSE / CDS  :-"))
    productt       =str(input("ENTER PRODUCT - NRML /CNC / MIS  :-"))
    qu             =int(input("ENTER QUANTITY - 2 / 4 :-"))
    time_frame     =str(input("ENTER TIMEFRAME - minute / 5minute **small letters only** :- "))
    sdate          ="2019-06-05"
    todate         ="2020-10-02"
    buy_add=.50
    sell_add=.50
    ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+ttradingsymbol)).iloc[-2,0])
    if "BUY"==without or "buy"==without:
        print("BOT STARTED WITH GREEN 'BUY' ENTRY  ")
        counter_start=[0]
        linkedlist_1=[]       
        linkedlist_2=[]      
        linkedlist_3=[]      
        counter=[0,10]      
        checkfirst=[0]      
        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=[]
        anchor=0
        countstart=0
        #programe start
        def ashibb():
            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
                    #df=kite.historical_data(140033,sdate,todate,time_frame,0)
                    dff=kite.historical_data(ttoken,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=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  ZERODHA GUPPY BOT ")
                    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 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("\n ")
                    if 0 in counter_start:
                        if "green" in  gup.iloc[-1,5]:
                            counter_start.remove(0)
                            counter_start.append(1)
                        else:
                            pass
                    if 1 in counter_start:
                        print(" BOT STARTED WITH GREEN ENTRY ")
                        if "blank" in gup.iloc[-1,5]:
                            print(" Nothing Done BUT BOT started no candel colour occur ")
                        if "green" in gup.iloc[-1,5]:
                            if 0 in counter:
                                #BUY X amount                   #-------------------------------------------------------- (A)
                                quant=qu
                                cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                lim_price=cur_high+buy_add
                                print("Congrats ! No1 Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="A")
                                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="G1") 
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)

                        if "blue" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 10 in counter:
                                    print("Blue Comes checking blue condition @ is previous green executed or not ?") # (A)
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="Z")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="Z")
                                        print("No2 BLUE Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                        linkedlist_2.insert(0,kite_drop)
                                        counter.remove(10) # -------------------------- ( Z )
                                        bluez.append(0)
                                    else:
                                        print(" BUY not executed  ")
                        if "red" in gup.iloc[-1,5]:
                            if 1 in counter:                                              
                                print("checking previous green executed or not ") 
                                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 now SELL x/2" )
                                    quant=int(2*qu)
                                    stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                    triggerprice_sell=stoploss_sell-sell_add
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="B")
                                    kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="B")
                                    print("No3 RED Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(1)
                                    counter.append(2)
                                    redb.append(0)                                 # ------------------------ ( B )
                                else:
                                    print("BLUE bid not complete now canceled bule bid and place fresh sell of x amount")
                                    bid_not_ex=int(linkedlist_1[0])
                                    print("SL Cancel Order cancelled and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                    triggerprice_sell=stoploss_sell-5
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=qu,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="C")
                                    kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=qu,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="C")
                                    print("No1 C fresh start Sell Stoploss order placed", "quantity is",qu ,"and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell)
                                    linkedlist_3.insert(0,kite_drop)     
                                    counter.remove(1)
                                    counter.append(2)     #  ------------ -------------- ( C )
                                    redc.append(0) 
                                               #       *********************** checking condition *********************
                        if 0 in bluez: 
                            if 2 in counter:
                                if 0 in checkfirst:
                                    print(" RED placed and now checking RED executed or not condition ")
                                    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)
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        print(" RED executed ")
                                        print(" Now checking  BLUE executed or not")
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                        match_in_int=int(match_in)
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            print(" yes BLUE executed ")
                                            print(" BOTH blue and RED executed and now placig order qu/2 ")
                                            quant=int(qu/2)
                                            stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                            triggerprice_sell=stoploss_sell-sell_add
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="BZ")
                                            print("Z and B both executed and market order placed", "quantity is",quant)
                                        else:
                                            print("Z not executed ")
                                            bid_not_ex=int(linkedlist_2[0])
                                            print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                                                   #  *************** comming from back ****************   
                        if 0 in count_sectime:
                            if 2 in counnter:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="BZ")
                                        print("both executed and market order placed comming from back again", "quantity is",quant)
                                        count_sectime.remove(1)
                                    else:
                                        print("Z not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        count_sectime.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if "aqua" in gup.iloc[-1,5]:
                            if 2 in counter:
                                if 0 in aqua1:
                                    if 0 in redb:
                                        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"]:
                                            quant=int(qu/2)
                                            cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                            lim_price=cur_high+buy_add
                                            print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                            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="F") 
                                            print("in aqua and one BUY LIMIT oreder placed ",  "quantity is",quant)
                                            linkedlist_3.append(0,kite_drop)                
                                            aqua1.remove(0)          
                                            aqua1.append(1)    #------------------------------ ( D )
                                        else:
                                            pass
                                    if 0 in redc:
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                        match_in_int=int(match_in)
                                        print("checking executed or not condition ")
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            quant=int(qu/2)
                                            cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                            lim_price=cur_high+buy_add
                                            print("Congrats ! E , No1 Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                            #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="E")
                                            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="E") 
                                            linkedlist_2.insert(0,kite_drop)            
                                            aqua1.remove(0)
                                            aqua1.append(2)              #------------------------ ( E )
                                        else:
                                            pass
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "green" in gup.iloc[-1,5]:
                            if 2 in counter:
                                # (  PART B ) 
                                if 0 in redb:
                                    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"]:
                                        quant=int(qu*2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! F Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="F")
                                        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="F") 
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(2)
                                        counter.append(3)
                                        counter.append(1)
                                        redb.remove(0)             # ---------------------------( F )
                                        checkfirst.append(0)
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_1[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for red again")
                                        linkedlist_1[0]=linkedlist_1[-1]
                                        counter.remove(2)
                                        counter.append(1)                                   
                                        redb.remove(0)                      
                                        checkfirst.append(0)
                                        counter.append(10)
                                # (  PART B )
                                if 0 in redc:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu*2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! G Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="G")
                                        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="G") 
                                        linkedlist_1.insert(0,kite_drop) 
                                        counter.remove(2)
                                        counter.append(4)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)       #  ------------------------(  G )
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for red again")
                                        counter.remove(2)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)
                                        counter.append(10)  
                            else:
                                pass
                        #  *************** checking condition 2nd time *************
                        if 3 in counter:
                            if 1 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="2Chk")
                                        print("both executed and market order placed comming from back again B and Z")
                                        aqua1.remove(1)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" blue Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if 4 in counter:
                            if 2 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="2BZ")
                                        print(" G and E !both executed and market order placed comming from back again", "quantity is",quant)
                                        aqua1.remove(2)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" blue Cancel and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(2)
                                else:
                                    pass
                            else:
                                pass
                        if "blue" in  gup.iloc[-1,5]:
                            if 3 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="H")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="H")
                                        print( "quantity is",quant," H blue Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell)
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2F.append(1)                                       
                                        bluein.remove(0)
                                        bluez.append(0)
                                        counter.remove(3)              # -------------------------- ( H )
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "blue" in  gup.iloc[-1,5]:
                            if 4 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="I")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="I")
                                        print( "quantity is",quant,"I blue Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell)
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2G.append(1)                   
                                        bluein.remove(0)           #----------------------- ( I )
                                        bluez.append(0)
                                        counter.remove(3)
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass
                    print("Colours Till Now")
                    print(colourstill)
                    #display(pd.DataFrame(kite.orders())[["tradingsymbol","transaction_type","status","order_id","quantity","order_type","exchange_update_timestamp",'tag',"quantity"]].tail(10))
        ashibb()
    if "SELL"==without or "sell"==without:
        print(" SELL BOT STARTED ! ")
        counter_start=[0]
        linkedlist_1=[]       
        linkedlist_2=[]      
        linkedlist_3=[]      
        counter=[0,10]      
        checkfirst=[0]      
        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
                    #df=kite.historical_data(140033,sdate,todate,time_frame,0)
                    dff=kite.historical_data(ttoken,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=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  ZERODHA GUPPY BOT ")
                    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 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("\n ")
                    if 0 in counter_start:
                        if "red" in gup.iloc[-1,5]:
                            counter_start.remove(0)
                            counter_start.append(2)
                        else:
                            pass
                    if 2 in counter_start:
                        print(" BOT STARTED WITH RED ' SELL' ENTRY ")
                        if "blank" in gup.iloc[-1,5]:
                            print(" Nothing Done BUT BOT started no candel colour occur ")
                        if "red" in gup.iloc[-1,5]:
                            if 0 in counter:
                                #SELl X amount                   #-------------------------------------------------------- (A)
                                quant=qu
                                stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                triggerprice_sell=stoploss_sell-sell_add
                                #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="A")
                                kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="A")
                                print("red sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                linkedlist_1.insert(0,kite_drop)
                                counter.remove(0)
                                counter.append(1)
                        if "aqua" in gup.iloc[-1,5]:
                            if 1 in counter:
                                if 10 in counter:
                                    print("aqua Comes checking blue condition @ is previous green executed or not ?") # (A)
                                    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 now buy x/2" )
                                        quant=int(qu/2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="Z")
                                        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="Z")
                                        linkedlist_2.insert(0,kite_drop)
                                        counter.remove(10) # -------------------------- ( Z )
                                        bluez.append(0)
                                    else:
                                        print(" sell not executed  ")
                        if "green" in gup.iloc[-1,5]:
                            if 1 in counter:                                              
                                print("checking previous green executed or not ") 
                                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 now BUY x/2" )
                                    quant=int(2*qu)
                                    cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                    lim_price=cur_high+buy_add
                                    print("Congrats ! No1 Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="B")
                                    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="B")
                                    linkedlist_1.insert(0,kite_drop)
                                    counter.remove(1)
                                    counter.append(2)
                                    redb.append(0)                                 # ------------------------ ( B )
                                else:
                                    print("aqua bid not complete now canceled aqua bid and place fresh BUY of x amount")
                                    bid_not_ex=int(linkedlist_1[0])
                                    print("SL Cancel Order cancelled and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                    lim_price=cur_high+3 
                                    print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                    #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="C")
                                    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="C")
                                    linkedlist_3.insert(0,kite_drop)     #  ------------ -------------- ( C )
                                    counter.remove(1)
                                    counter.append(2) 
                                    redc.append(0)
                                                    #       *********************** checking condition *********************
                        if 0 in bluez:
                            if 2 in counter:
                                if 0 in checkfirst:
                                    print(" green placed and now checking RED executed or not condition ")
                                    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)
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        print(" green executed ")
                                        print(" Now checkingaqua executed or not")
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                        match_in_int=int(match_in)
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            print(" yes BLUE executed ")
                                            print(" BOTH aqua and green executed and now placig order qu/2 ")
                                            quant=int(qu/2)
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="BZ")
                                            print("Z and B both executed and market order placed", "quantity is",quant)
                                        else:
                                            print("Z not executed ")
                                            bid_not_ex=int(linkedlist_2[0])
                                            print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                                                        #  *************** comming from back ****************  
                        if 0 in count_sectime:
                            if 2 in counnter:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="BZ")
                                        print("both executed and market order placed comming from back again", "quantity is",quant)
                                        count_sectime.remove(1)
                                    else:
                                        print("Z not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        count_sectime.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if "blue" in gup.iloc[-1,5]:
                            if 2 in counter:
                                if 0 in aqua1:
                                    if 0 in redb:
                                        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"]:
                                            # ( NOW SELL X/2 )         #------------------------------ ( D )
                                            quant=int(qu/2)
                                            stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                            triggerprice_sell=stoploss_sell-sell_add
                                            #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="D")
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="D")
                                            print("Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                            linkedlist_3.append(0,kite_drop)                
                                            aqua1.remove(0)          
                                            aqua1.append(1)
                                        else:
                                            pass
                                    if 0 in redc:
                                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                        match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                        match_in_int=int(match_in)
                                        print("checking executed or not condition ")
                                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                            quant=int(qu/2)
                                            stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                            triggerprice_sell=stoploss_sell-sell_add
                                            #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="E")
                                            kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="E")
                                            print(" aqua Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                            linkedlist_2.insert(0,kite_drop)            
                                            aqua1.remove(0)
                                            aqua1.append(2)              #------------------------ ( E )
                                        else:
                                            pass
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "red" in gup.iloc[-1,5]:
                            if 2 in counter:
                                # (  PART B ) 
                                if 0 in redb:
                                    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"]:
                                        quant=int(qu*2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="F")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="F")
                                        print(" Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                        linkedlist_1.insert(0,kite_drop)
                                        counter.remove(2)
                                        counter.append(3)
                                        counter.append(1)        # #----------------------- ( F )
                                        redb.remove(0)
                                        checkfirst.append(0)
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_1[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for green again")
                                        linkedlist_1[0]=linkedlist_1[-1]
                                        counter.remove(2)
                                        counter.append(1)                                   
                                        redb.remove(0)                      
                                        checkfirst.append(0)
                                        counter.append(10)
                                # (  PART B )
                                if 0 in redc:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu*2)
                                        stoploss_sell=int(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                                        triggerprice_sell=stoploss_sell-sell_add
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='SELL',product=productt,tag="G")
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='SL',stoploss= stoploss_sell,trigger_price=triggerprice_sell,transaction_type='SELL',product=productt,tag="G")
                                        print(" aqua Sell Stoploss order placed and SL trigger price is",triggerprice_sell,"and stoploss is",stoploss_sell, "quantity is",quant)
                                        linkedlist_1.insert(0,kite_drop) 
                                        counter.remove(2)
                                        counter.append(4)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)       #  ------------------------(  G )
                                        counter.append(10)
                                        bluein.append(0)
                                    else:
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        print("now waiting for green again")
                                        counter.remove(2)
                                        counter.append(1)
                                        redc.remove(0)
                                        checkfirst.append(0)
                                        counter.append(10)  
                            else:
                                pass
                                               #   *********** checking condition 2nd time *************
                        if 3 in counter:
                            if 1 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_3[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="2Chk")
                                        print("both executed and market order placed comming from back again B and Z")
                                        aqua1.remove(1)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_3[0])
                                        print(" aqua Cancel (Z) and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(1)
                                else:
                                    pass
                            else:
                                pass
                        if 4 in counter:
                            if 2 in aqua1:
                                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"]:
                                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                                    match_in,=update_reverse[update_reverse.order_id==linkedlist_2[0]].index 
                                    match_in_int=int(match_in)
                                    print("checking executed or not condition ")
                                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:
                                        quant=int(qu/2)
                                        kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="2BZ")
                                        print(" G and E !both executed and market order placed comming from back again", "quantity is",quant)
                                        aqua1.remove(2)
                                    else:
                                        print("not executed ")
                                        bid_not_ex=int(linkedlist_2[0])
                                        print(" aqua Cancel and order id",kite.cancel_order("regular",order_id=bid_not_ex,parent_order_id=None))
                                        aqua1.remove(2)
                                else:
                                    pass
                            else:
                                pass
                        if "aqua" in  gup.iloc[-1,5]:
                            if 3 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats !  Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="H")
                                        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="H")
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2F.append(1)                                       
                                        bluein.remove(0)
                                        bluez.append(0)
                                        counter.remove(3)              # -------------------------- ( H )
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        if "aqua" in  gup.iloc[-1,5]:
                            if 4 in counter:
                                if 0 in bluein:
                                    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 now SELL x/2" )
                                        quant=int(qu/2)
                                        cur_high=int(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                                        lim_price=cur_high+buy_add
                                        print("Congrats ! Buy Limit Order placed Price is",lim_price,"and trigger_price is",cur_high, "quantity is",quant)
                                        #kite_drop=kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,order_type='MARKET',transaction_type='BUY',product=productt,tag="I")
                                        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="I")
                                        linkedlist_2.insert(0,kite_drop)
                                        blue_2G.append(1)                   
                                        bluein.remove(0)           #----------------------- ( I )
                                        bluez.append(0)
                                        counter.remove(3)
                                        counter.append(1)
                                        count_sectime.append(1)
                                    else:
                                        pass
                                else:
                                    pass
                            else:
                                pass
                        else:
                            pass 
                        print(" Orders Till Now ")
        ashis()
else:
    pass
				
			

Output – 

				
					Zerodha GUPPY SCREENER for 30 minute Data


	 	 	 
 Current Token checking   975873


 	 	 	 
 Current Colour on this token is  none
Buy stock found for 30 minute are  := [81153, 424961]
Sell stocks found for 30 minute are:= []
SCANNING COMPLETE
5 ,15 and 30 are completed ! Results are 


tokens we get on 5 minute BUY   [784129]
tokens we get on 5 minute SELL  []


tokens we get on 15 minute BUY   [1207553, 2977281, 784129]
tokens we get on 15 minute SELL  []


tokens we get on 30 minute BUY   [81153, 424961]
tokens we get on 30 minute SELL  []




BUY from ALL   {784129, 2977281, 1207553, 81153, 424961}
SELL From ALL  set()


  	 	 	 	 	BUY | SELL on 5 MINUTE
BUY
['VEDL']
SELL
[]


 	 	 	 	 	 BUY | SELl on 15 minute
BUY
['GAIL', 'NTPC', 'VEDL']
SELL
[]


 	 	 	 	 	 BUY | SELl on 30 minute
BUY
['BAJFINANCE', 'ITC']
SELL
[]
 
 
 	 	 	 	 	 OVERALL BUY  SELL 
 
 
 OVERALL -  BUY  ['VEDL'] ['GAIL', 'NTPC', 'VEDL'] ['BAJFINANCE', 'ITC']
 OVERALL - SELL [] [] []
 
 
 	 	 	 	 	 COMMON BUY-SELL After filter 
 OVERALL BUY []
 OVERALL SELL ['VEDL', 'NTPC', 'GAIL', 'BAJFINANCE', 'ITC']
	 	 	 	 	 !! ALL COMPLETED !!
 
 
WELCOME TO GUPPY BOT ! ENTER 'BUY' or 'SELL', which you want
 ENTER BUY or SELL :-buy
 ** ENTER ALL DETAILS IN CAPITAL LETTERS ONLY **
ENTER TRADINGSYMBOL - SUNPHARMA / SBIN :-ITC
ENTER EXCHANGE / NSE / BSE / CDS  :-NSE
ENTER PRODUCT / NRML /CNC / MIS  :-CNC
ENTER QUANTITY - 2 / 4 :-40
ENTER TIME_FRAME - minute / 5minute **SMALL letters only** :-5minute
BOT STARTED WITH GREEN 'BUY' ENTRY after scanning 
 
 	 	 	 	  ZERODHA GUPPY BOT 
 	 	 	 
 Current Colour on this token is  none

 
Zerodha GUPPY BOT start Time              2019-08-31 _ 22:51:17 

 
BOT working succeesfully on time:         2019-08-31 _ 22:51:17 

 
Trading symbol is ITC Token is 424961 Exchange is NSE and product type is CNC Quantity is 40 time frame for Historical Data is 5minute Starting and Ending Date of Historical Data is 2019-06-05 2020-10-02

 

 
Colours Till Now
['none']
 
 	 	 	 	  ZERODHA GUPPY BOT 
 	 	 	 
 Current Colour on this token is  none

 
Zerodha GUPPY BOT start Time              2019-08-31 _ 22:51:17 

 
BOT working succeesfully on time:         2019-08-31 _ 22:52:14 

 
Trading symbol is ITC Token is 424961 Exchange is NSE and product type is CNC Quantity is 40 time frame for Historical Data is 5minute Starting and Ending Date of Historical Data is 2019-06-05 2020-10-02

 

 
Colours Till Now
['none', 'none']
 
 	 	 	 	  ZERODHA GUPPY BOT 
 	 	 	 
 Current Colour on this token is  none

 
Zerodha GUPPY BOT start Time              2019-08-31 _ 22:51:17 

 
BOT working succeesfully on time:         2019-08-31 _ 22:53:15 

 
Trading symbol is ITC Token is 424961 Exchange is NSE and product type is CNC Quantity is 40 time frame for Historical Data is 5minute Starting and Ending Date of Historical Data is 2019-06-05 2020-10-02

 

 
Colours Till Now
['none', 'none', 'none']
 
 	 	 	 	  ZERODHA GUPPY BOT 
 	 	 	 
 Current Colour on this token is  none

 
Zerodha GUPPY BOT start Time              2019-08-31 _ 22:51:17 

 
BOT working succeesfully on time:         2019-08-31 _ 22:54:15 

 
Trading symbol is ITC Token is 424961 Exchange is NSE and product type is CNC Quantity is 40 time frame for Historical Data is 5minute Starting and Ending Date of Historical Data is 2019-06-05 2020-10-02

 

 
Colours Till Now
['none', 'none', 'none', 'none']
				
			

This trading bot represents a sophisticated approach to algorithmic trading, leveraging the insights of the Guppy indicator for automated buy and sell decisions.

As with any automated system, it’s crucial to thoroughly test the bot in a controlled environment and be aware of the inherent risks of trading. Regular updates and adaptations to the bot may be necessary to maintain its effectiveness in evolving market conditions.

Post a comment

Leave a Comment

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

×Close