Multi-Timeframe Trading Bot Using Guppy Strategy and Screener

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. 

Prologue

In the first trading bot, we focused on developing the Guppy Strategy Screener. This initial approach was about coding a tool to effectively identify potential trading opportunities based on the Guppy Strategy.

Our second trading bot introduced a basic trading bot. This bot was designed to automatically execute buy and sell orders based on the stocks identified by the screener. Its primary function was to act on the signals generated by the screener, simplifying the trading process.

The third trading bot dived into a more advanced version of the trading bot, incorporating the Guppy Indicator. This enhanced bot was equipped with a complex strategy that included multiple conditional cases and reentry scenarios. It represented a significant step forward in terms of strategy sophistication.

The fourth trading bot employs an advanced strategy, buying on green signals and selling on red signals based on real-time market indicators. It handles multiple stocks at once, a major upgrade from previous versions limited to single-stock trading. The bot continuously scans the Nifty 50 index for potential trades and monitors the entire stock list, ensuring timely responses to market opportunities.

Objective

In our latest trading bot, 

This program scans stocks using the Guppy Screener, categorizes them as buy or sell based on 5, 10, and 15-minute timeframes, and displays the results. Next, it identifies common stocks among all these timeframes. You can select a stock from this list to execute the buy/sell program, buying when there’s a green signal from the indicator and selling when there’s a red signal.

Note – The structure of historical data and live data from Zerodha is identical. During the development and testing of functions, it’s not feasible to wait for days or months to validate their performance using live data.

To address this, we’ll initially test and validate our functions using historical data. Once we have confirmed that the functions generate accurate signals and execute trades correctly with historical data, we can seamlessly transition to using live data for real-time trading.

Python Code

This program is designed to streamline the process of stock trading by leveraging the Guppy Screener. It operates by scanning a range of stocks, sorting them based on buy and sell signals, and identifying common stocks across different timeframes. The program then enables users to execute trades based on specific indicator signals. Here’s a step-by-step breakdown:

  1. Stock Scanning with Guppy Screener: The program starts by using the Guppy Screener to scan all available stocks. The Guppy Screener is known for its effectiveness in identifying trends using multiple moving averages.

  2. Sorting Stocks by Timeframe: It categorizes these stocks into buy and sell groups based on their performance in different timeframes – 5, 10, and 15 minutes. This sorting helps in understanding the short-term trends in various stocks.

  3. Identifying Common Stocks: The program then cross-references these lists to find stocks that are common in all timeframes, both in the buy and sell categories. This step is crucial as it pinpoints stocks with consistent buy or sell trends across different periods, indicating stronger signals.

  4. User Input for Stock Selection: Once the common stocks are identified, the user is prompted to select a stock from these lists to focus on. This allows the user to have control over which stock they are interested in trading.

  5. Trading Execution Based on Indicator Signals: After a stock is selected, the program switches to an execution mode where it buys stocks on a green signal from the chosen indicator and sells stocks on a red signal. This functionality is crucial for making timely trades based on the latest market movements and indicator trends.

  6. Real-Time Trading Actions: The buy or sell actions are performed in real-time, ensuring that the trades are executed at the optimal moments as indicated by the market trends and the Guppy Screener analysis.

				
					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" )

sdate = (date.today() - timedelta(days=15)).strftime("%Y-%m-%d")
todate = date.today().strftime("%Y-%m-%d")
def avg_ha(x):
    a=list(modf(round(x,3)))
    d=str(a[0])
    aa=str(d[0:2])
    try:
        ab=str(d[2])
    except:
        ab='0'
    try:
        ac=str(d[3])
    except:
        ac='0'
    try:
        ad=str(d[4])
    except:
        ad='0'
    c=aa+ab+ac+ad
    b=0
    if a[0]!=0:
        astr=c
        a0=astr[0]
        a1=astr[1]
        a3=int(astr[2])
        a2=int(astr[3:5])
        if a2>=0 and a2<25:
            a2=0
        elif a2>=25 and a2<75:
            a2=5
        elif a2>=75 and a2<=9999:
            if a3==9:
                a[1]+=1
                a3=0
            else:
                a3+=1
            a2=0
        aint=a0+a1+str(a3)+str(a2)
        a[0]=float(aint)
    for k in a:
        b+=k
    return b
def result():
    start_url="yes"
    l=[]
    #if "yes" in start_url:
    if kite.orders():
        find="adv"
        while(True):
            df=pd.DataFrame(kite.orders())[["tag","order_id", "tradingsymbol","status","transaction_type","quantity","price", "trigger_price"]]
            dgg=(df[df['tag'].str.contains(find)==True])[["order_id", "tradingsymbol", "status","transaction_type","quantity","price", "trigger_price"]]
            dg=dgg[(dgg["status"]=="COMPLETE") ]
            #display(dg)
            p=list(dg['tradingsymbol'])
            l.append(p)
            break
        else:
            print("no orders till now")
            pass
    else:
        print("no orders placed till now ")
    print("\n ALL ORDERS PLACED BUY BOT ARE: ")
    display(dgg)
    k=l[0]
    ee=0
    #print(k)
    tradingsymbll=[]
    pandl=[]
    qutt=[]
    
    buy_p=[]
    
    sell_p=[]
    while(True):
        find=k[ee]
        df=(pd.DataFrame(kite.positions()["net"])[["tradingsymbol","quantity","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value"]])
        dg=(df[df["tradingsymbol"].str.contains(find)==True])[["tradingsymbol","pnl","quantity","buy_price","sell_price","average_price","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value"]]
        #display(dg)
        tradingsymbll.append(dg.iloc[-1,0])
        pandl.append(dg.iloc[-1,1])
        qutt.append(dg.iloc[-1,2])
        buy_p.append(dg.iloc[-1,3])
        sell_p.append(dg.iloc[-1,4])
        ee=ee+1
        if ee==len(k):
            break
    else:
        print("no position available")
    #display(dg)
    fram={"tradingSymbol":tradingsymbll,"PnL": pandl , "Quantity":qutt ,"Buyprice":buy_p, "sellprice":sell_p}
    kk=pd.DataFrame(fram)
    print("\n ORDERS COMPLETED ARE: ")
    display(kk)
    
    
    print("\n Overall profit and Loss is =", kk.PnL.sum())
##

#################################################################################
now_utc = datetime.now(timezone('UTC'))
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
now_asia = now_asia.strftime("%H")
zz2=now_asia
kk=int(zz2)
if kk>=15:
    print("Time complete")
    result()

while(True):
    scan= str(input("DO You want SCANNING ? YES , RESULT, HALF :- ")).upper()
    if "Y" in scan:
        scan="YES"
        break
    if "H" in scan:
        scan="HALF"
        break
    if "R" in scan:
        scan="RESULT"
        break
    if "S" in scan:
        scan="second"
        break


if "RESULT"==scan:
    result()
    
if "HALF"==scan:
    while (True):
        find=str(input("ENTER ORDER ID := ")).strip()
        if find:
            break
        else:
            pass
    df=pd.DataFrame(kite.orders())[["tradingsymbol","instrument_token","transaction_type",'product',"order_id","quantity","order_type","exchange_update_timestamp",'tag',"quantity","status","status_message","average_price","price","trigger_price"]]
    dg=(df[df["order_id"].str.contains(find)==True])[["tradingsymbol","instrument_token","transaction_type",'product',"order_id","quantity","status"]]
    tsm=dg.iloc[-1,0]
    tok=dg.iloc[-1,1]
    busl=dg.iloc[-1,2]
    prdct=dg.iloc[-1,3]
    idis=dg.iloc[-1,4]
    qunti=dg.iloc[-1,5]
    ttradingsymbol =str(tsm)
    productt       =str(prdct)
    qu             =int(qunti)
    ttoken         =int(tok)
    progg          =str(busl)
    ide            =str(idis)
    if "BUY" in progg:
        prog="red"
    if "SELL" in progg:
        prog="green"
    #####################################
    sdate          ="2019-07-01"
    todate         ="2019-10-01"
    time_frame     = "minute"
    eexchange      ="NSE"
    #######################################
    
    print("Trading symbol is",ttradingsymbol)
    #print("Order ID is      ",ide)
    print("PRODUCT is       ",productt)
    print("QUANTITY is      ",qu)
    print("Tokenn is        ",ttoken)
    print("Execution of bid ",prog)
    print("Time Frame is    ",time_frame)
    print("Exchange is      ",eexchange)
    display(dg)
    ############################################
    if "green"==prog:
        i=1
        execution=[]
        counter_start=[0]
        linkedlist_1=[]       
        linkedlist_2=[]      
        linkedlist_3=[]      
        counter=[0,10] 
        execution=[]
        checkfirst=[0]   
        red_time=[]
        green_time=[]
        redb=[]             
        bluez=[]            
        aqua1=[0]           
        bluein=[]           
        blue_2F=[]          
        blue_2G=[]          
        count_sectime=[]
        redc=[]
        colourstill=[]
        prog_starts=[]
        #Variables
        lst_candle=[]
        lst_heikin_nor=[]
        lst_heikin=[]
        lst_cand=[]
        lst_c=[]
        countstart=0
        #programe start
        ii=1
        def ashis():
            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("%H")
                    zz2=now_asia
                    kk=int(zz2)
                    if kk>=15:
                        print("Time complete")
                    dff=kite.historical_data(ttoken,sdate,todate,"minute",0)
                    av=pd.DataFrame(dff)
                    kk=str(av.iloc[-1,1]).split("+")
                    zz=kk[0]
                    now_utc = datetime.now(timezone('UTC'))
                    now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                    now_asia = now_asia.strftime("%Y-%m-%d %H:%M:00")
                    zz2=now_asia
                    if zz2==zz:
                        print("same so discarding last ouput")
                        dfw=av[:-1]
                    else:
                        print("Candel Not same so continue going with same candel")
                        dfw=av
                    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):
                        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)
                    update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                    match_in,=update_reverse[update_reverse.order_id==ide].index 
                    match_in_int=int(match_in)
                    print("checking executed or not condition ")
                    display(strftime("%a, %d %b %Y %I:%M:%S %p"))
                    if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                        print("ORDER COMPLETED and waiting for green " )
                        execution.append(1)
                    else:
                        print("SORRY! red not executed")
                        pass
                    if prog in gup.iloc[-1,5]:
                        if 1 in execution:
                            find=ttradingsymbol
                            order_mis_cnc=productt
                            df=(pd.DataFrame(kite.positions()["net"])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]])
                            dg=(df[df['tradingsymbol'].str.contains(find)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                            dg=(dg[dg["product"].str.contains(order_mis_cnc)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                            quant=int((pd.DataFrame(dg["quantity"])).iloc[0,0])
                            kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange="NSE",order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                            print("programe completed with green entry")
                            print("Quantity is", quant)
                            display(dg)
                            execution.clear()
                            print(" programe serching colour of ", prog)
                            print("checking red execution")
                            print("trading symbol is ", ttradingsymbol)
                            print("quantity is,",qu)
                            print("order id is", ide)
                            print("HALF programe completed")
                            break
                        else:
                            pass
        ashis()
        ## SEARCHING FOR RED
    if "red"==prog:
        i=1
        execution=[]
        #while (True)
        if i==1:
            counter_start=[0]
            linkedlist_1=[]       
            linkedlist_2=[]      
            linkedlist_3=[]      
            counter=[0,10] 
            execution=[]
            checkfirst=[0]   
            red_time=[]
            green_time=[]
            redb=[]             
            bluez=[]            
            aqua1=[0]           
            bluein=[]           
            blue_2F=[]          
            blue_2G=[]          
            count_sectime=[]
            redc=[]
            colourstill=[]
            prog_starts=[]
            #Variables
            lst_candle=[]
            lst_heikin_nor=[]
            lst_heikin=[]
            lst_cand=[]
            lst_c=[]
            countstart=0
            #programe start
            ii=1
            def ashis():
                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("%H")
                        zz2=now_asia
                        kk=int(zz2)
                        if kk>=15:
                            print("Time complete")
                            ############
                        dff=kite.historical_data(ttoken,sdate,todate,"minute",0)
                        av=pd.DataFrame(dff)
                        kk=str(av.iloc[-1,1]).split("+")
                        zz=kk[0]
                        now_utc = datetime.now(timezone('UTC'))
                        now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                        now_asia = now_asia.strftime("%Y-%m-%d %H:%M:00")
                        zz2=now_asia
                        if zz2==zz:
                            print("same so discarding last ouput")
                            dfw=av[:-1]
                        else:
                            print("Candel Not same so continue going with same candel")
                            dfw=av
                        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):
                            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(" programe serching colour of ", prog)
                        print("checking green bid execution")
                        display(strftime("%a, %d %b %Y %I:%M:%S %p"))
                        update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                        match_in,=update_reverse[update_reverse.order_id==ide].index 
                        match_in_int=int(match_in)
                        if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                            print("ORDER COMPLETED and waiting for red " )
                            execution.append(1)
                        else:
                            print("SORRY! red not executed")
                            pass
                        if prog in gup.iloc[-1,5]:
                            if 1 in execution:
                                find=ttradingsymbol
                                order_mis_cnc=productt
                                df=(pd.DataFrame(kite.positions()["net"])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]])
                                dg=(df[df['tradingsymbol'].str.contains(find)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                dg=(dg[dg["product"].str.contains(order_mis_cnc)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                quant=int((pd.DataFrame(dg["quantity"])).iloc[0,0])
                                kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange="NSE",order_type='MARKET',transaction_type="SELL",product=productt,tag="testR")
                                print("programe completed with red entry ")
                                print("Quantity is :=",quant)
                                display(dg)
                                execution.clear()
                                print("HALF programe completed")
                                break
                            else:
                                pass        
            ashis()
if "YES"==scan or "yes"==scan:
    while (True):
        time_frame    =str(input("Enter TimeFrame:=")).lower()
        if time_frame:
            break
        else:
            pass
    while (True):
        quu=str(input("Enter Amount  := "))
        if quu:
            break
        else:
            pass
    while (True):
        pro_duct=str(input("MIS or CNC order ? := ")).upper()
        if pro_duct:
            break
    while (True):
        scan_time=int(input("No of time scanning ?"))
        if scan_time:
            break
        else:
            scan_time=1
            
    qu=int(quu)
    print("Time Frame is :=",time_frame)
    print("Amount is     :=",qu)
    print("Product is    :=",pro_duct)
    print("SCANNING START")
    z=['ADANIPORTS', 'ASIANPAINT', 'AXISBANK', 'BAJAJ-AUTO', 'BAJFINANCE', 'BAJAJFINSV', 'BPCL', 'BHARTIARTL', 'INFRATEL', 'BRITANNIA', 'CIPLA', 'COALINDIA', 'DRREDDY', 'EICHERMOT', 'GAIL', 'GRASIM', 'HCLTECH', 'HDFCBANK', 'HEROMOTOCO', 'HINDALCO', 'HINDUNILVR', 'HDFC', 'ICICIBANK', 'ITC', 'IBULHSGFIN', 'IOC', 'INDUSINDBK', 'INFY', 'JSWSTEEL', 'KOTAKBANK', 'LT', 'M&M', 'MARUTI', 'NTPC', 'ONGC', 'POWERGRID', 'RELIANCE', 'SBIN', 'SUNPHARMA', 'TCS', 'TATAMOTORS', 'TATASTEEL', 'TECHM', 'TITAN', 'UPL', 'ULTRACEMCO', 'VEDL', 'WIPRO', 'YESBANK', 'ZEEL']
    eexchange="NSE"
    tokenall=[] 
    aa=0
    print("  \t \t \t \n Getting All tokens for processing BUY SELL ")
    while(True):
        ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+z[aa])).iloc[-2,0])
        tokenall.append(ttoken)
        aa=aa+1
        if aa==len(z):
            aa=0
            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 ")
    buy5minute=[]
    sell5minute=[]
    buy10minute=[]
    sell10minute=[]
    buy15minute=[]
    sell15minute=[]
    lst_candle=[]
    lst_heikin_nor=[]
    lst_heikin=[]
    lst_cand=[]
    lst_c=[]
    anchor=0
    countstart=0
    a=0
    ak=1
    BUY_listindicator=[]
    SELL_listindicator=[]
    sell5minutesym=[]
    buy5minutesym=[]
    buy10minutesym=[]
    sell10minutesym=[]
    buy15minutesym=[]
    sell15minutesym=[]
    price5min_buy=[]
    price5min_sell=[]
    price15min_buy=[]
    price15min_sell=[]
    price30min_buy=[]
    price30min_sell=[]
    priceedit=[]
    ##
    # New updated variables
    order_id_sell=[]
    order_id_buy=[]
    ignor_buy=[]
    ignor_sell=[]
    errors=[]
    order_id_buy_sell=[]
    nooftime=[]
    completed=[]
    def ashi():
        global a
        global tokenall
        global BUY_listindicator
        global SELL_listindicator
        ak=1
        now_utc = datetime.now(timezone('UTC'))
        now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
        now_asia = now_asia.strftime("%M%S")
        koo=int(now_asia)
        if ak==1:
            kooe=koo+100
            ak=0
        while (True):
            dff=kite.historical_data(tokenall[a],sdate,todate,time_frame,0)
            av=pd.DataFrame(dff)
            kk=str(av.iloc[-1,1]).split("+")
            zz=kk[0]
            now_utc = datetime.now(timezone('UTC'))
            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
            now_asia = now_asia.strftime("%Y-%m-%d %H:%M:00")
            zz2=now_asia
            if zz2==zz:
                dfw=av[:-1]
            else:
                dfw=av
            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):
                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()
                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
            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" )
            print("\n" )
            print(" \t \t \t \t ZERODHA ADVANCE BOT ")
            print("\n")
            print("Current Token checking            " , tokenall[a])
            print("Current candel checking  no       " , a)
            print("Current Colour on this token is   " , gup.iloc[-1,5])
            #print("Current 'OHLC' of this token is  " )
            #display(gup.tail())
            if "green" in gup.iloc[-1,5]:
                print("BUY stock found ")
                ttradingsymbol=z[a]
                eexchange="NSE"
                productt=pro_duct
                ttoken=tokenall[a]
                # ORDER UPDATE 
                ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+ttradingsymbol)).iloc[-2,0])
                kl=kite.orders()
                if kl:
                    kk=list((pd.DataFrame(kite.orders())[["instrument_token"]])["instrument_token"])
                    if ttoken in kk:
                        print(" ALREADY USED !! ")
                        print(" Tokend  is :=        ", ttoken)
                        print(" Trading Symbol is := ", z[a])
                        print(" SORRY !! This order already exists \n so not going to place this order !! ")
                        ignor_buy.append(z[a])
                    else:
                        print("TRUE !! so going to place order of ", ttoken)
                        xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                        cur_high=avg_ha(xa)
                        xb=cur_high+float(gup.iloc[-1,6])*0.1
                        lim_price=avg_ha(xb)
                        kk=int ( qu/ (gup.iloc[-1,2]) ) # price
                        if kk>=1:
                            quant=kk
                            display(gup.tail(1))
                            print("Trading Symbol of stock is                                    ",z[a])
                            print("Quantity of placed Stock is                                   ",quant)
                            print("T.P value after .25 of atr is                                 ",xa)
                            print("price is after adding 0.1 percent of atr on trigegr price     ",xb)
                            print("BUY price after round off         __must be high__ then t.p   ",lim_price)
                            print("T.P Trigger price after round off  __must be low__ then price ",cur_high)
                            print(kite.ohlc(ttoken))
                            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="advG")
                            print("buy order id is                                               ",kite_drop)
                            print("\n")
                            buy5minute.append((tokenall[a]))     #token
                            buy5minutesym.append((z[a]))         # symbol
                            price5min_buy.append(gup.iloc[-1,2]) # price
                            order_id_buy.append(kite_drop)  
                            order_id_buy_sell.append(kite_drop)
                        
                else:
                    print("This is first order of morning !! no order is placed till now so going to place order ")
                    xa=float(gup.iloc[-1,2]+(gup.iloc[-1,6]*.25))
                    cur_high=avg_ha(xa)
                    xb=cur_high+float(gup.iloc[-1,6])*0.1
                    lim_price=avg_ha(xb)
                    kk=int ( qu/ (gup.iloc[-1,2]) ) 
                    if kk>=1:
                        quant=kk
                        display(gup.tail(1))
                        print("Trading Symbol of stock is                                    ",z[a])
                        print("Quantity of placed Stock is                                   ",quant)
                        print("T.P value after .25 of atr is                                 ",xa)
                        print("price is after adding 0.1 percent of atr on trigegr price     ",xb)
                        print("BUY price after round off         __must be high__ then t.p   ",lim_price)
                        print("T.P Trigger price after round off  __must be low__ then price ",cur_high)
                        print(kite.ohlc(ttoken))
                        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="advG")
                        print("buy order id is                                               ",kite_drop)
                        print("\n")
                        buy5minute.append((tokenall[a])) #token
                        buy5minutesym.append((z[a])) # symbol
                        price5min_buy.append(gup.iloc[-1,2]) # price
                        order_id_buy.append(kite_drop)
                        order_id_buy_sell.append(kite_drop)
                    
            if "red" in gup.iloc[-1,5]:
                print("SELL stock found ")
                ## ORDER UPDATE 
                ttradingsymbol=z[a]
                quant=qu
                eexchange="NSE"
                productt=pro_duct
                ttoken=tokenall[a]
                # ORDER UPDATE
                ttoken=int(pd.DataFrame(kite.ltp(eexchange+":"+ttradingsymbol)).iloc[-2,0])
                kl=kite.orders()
                if kl:
                    kk=list((pd.DataFrame(kite.orders())[["instrument_token"]])["instrument_token"])
                    if ttoken in kk:
                        print(" ALREADY USED !! ")
                        print(" Tokend  is :=        ", ttoken)
                        print(" Trading Symbol is := ", z[a])
                        print(" SORRY !! This order already exists \n so not going to place this order !! ")
                        ignor_sell.append(z[a])
                    else:
                        print("TRUE !! so going to place order of ", ttoken)
                        xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                        price_sell=avg_ha(xa) # TRIGER PRICE (LARGE)
                        xb=price_sell-float(gup.iloc[-1,6])*0.1
                        triger_sell=avg_ha(xb) #PRICE (SMALL)
                        kk=int ( qu/ (gup.iloc[-1,2]) ) # price
                        if kk>=1:
                            quant=kk
                            display(gup.tail(1))
                            print("Trading Symbol of stock is                                      ",z[a])
                            print("Quantity of placed Stock is                                     ",quant)
                            print("T.P value after - .25 of atr                                    ",xa)
                            print("price is after adding 0.1 percent of atr on trigegr price       ",xb)
                            print("T.P trigger price after round off __must be larger__ then price ",price_sell)
                            print("SELL price after round off __ must be lower__ then Trigger price",triger_sell)
                            print(kite.ohlc(ttoken))
                            kite_drop=kite.place_order(order_type='SL',price= triger_sell,trigger_price=price_sell,variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,transaction_type='SELL',product=productt,tag="advG")
                            print("red sell Stoploss order placed and SL trigger price is",price_sell,"and price is",triger_sell, "quantity is",quant)
                            print("SELL order id is                                                ",kite_drop)
                            print("\n")
                            sell5minute.append((tokenall[a])) #token
                            sell5minutesym.append((z[a])) #symbl
                            price5min_sell.append(gup.iloc[-1,2]) # price
                            order_id_sell.append(kite_drop)
                            order_id_buy_sell.append(kite_drop)
                else:
                    print("TRUE !! so going to place order of ", ttoken)
                    xa=float(gup.iloc[-1,3]-gup.iloc[-1,6]*.25)
                    price_sell=avg_ha(xa)                                # TRIGER PRICE (LARGE)
                    xb=price_sell-float(gup.iloc[-1,6])*0.1
                    triger_sell=avg_ha(xb)                               #PRICE (SMALL)
                    kk=int ( qu/ (gup.iloc[-1,2]) )                      # price
                    if kk>=1:
                        quant=kk
                        display(gup.tail(1))
                        print("Trading Symbol of stock is                                      ",z[a])
                        print("Quantity of placed Stock is                                     ",quant)
                        print("T.P value after - .25 of atr                                    ",xa)
                        print("price is after adding 0.1 percent of atr on trigegr price       ",xb)
                        print("T.P trigger price after round off __must be larger__ then price ",price_sell)
                        print("SELL price after round off __ must be lower__ then Trigger price",triger_sell)
                        print(kite.ohlc(ttoken))
                        kite_drop=kite.place_order(order_type='SL',price= triger_sell,trigger_price=price_sell,variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange=eexchange,transaction_type='SELL',product=productt,tag="advG")
                        print("red sell Stoploss order placed and SL trigger price is",price_sell,"and price is",triger_sell, "quantity is",quant)
                        print("SELL order id is                                                ",kite_drop)
                        print("\n")
                        sell5minute.append((tokenall[a])) #token
                        sell5minutesym.append((z[a])) #symbl
                        price5min_sell.append(gup.iloc[-1,2]) # price
                        order_id_sell.append(kite_drop)
                        order_id_buy_sell.append(kite_drop)
                    
            
            buyframe={"SYMBOLS_BUY":buy5minutesym,"TOKENS_BUY":buy5minute,"orderid_BUY":order_id_buy}
            fivemin=pd.DataFrame(buyframe)
            display(fivemin)
            buyframe={"SYMBOLS_SELL":sell5minute,"TOKENS_SELL":sell5minutesym,"orderid_SELL":order_id_sell}
            fivemin=pd.DataFrame(buyframe)
            display(fivemin)
            print(" SYBMOL's ignored BUY             =", ignor_buy)
            print(" SYBMOL's ignored SELL            =", ignor_sell)
            print(" No of time Nifty50 stock scanned =", len(nooftime))
            print(" ALL order is of BUY\SELL         =", order_id_buy_sell)
            a=a+1
            if a==len(tokenall):
                print(" SCAN COMPLETED !!")
                nooftime.append(0)
                a=0
                ashi()
                print(" Scanning once again ")
                #if koo>=kooe:
            if len(nooftime)==scan_time:
                print(" !! COMPLETED FULL SCAN !! ")                  
                ak=1
                completed.append(1)
                break

            # END SCANNING RESULT AND continue to check buy
    ashi()

    
    
    
###########################
if "second"==scan or "second"==scan:
    completed="yes"
    ell=str(input("enter all orde id's"))
    order_id_buy_sell=ell.split(",")
    print(order_id_buy_sell)
    #order_id_buy_sell=["190813000340017", "190813000150418"]
    completed="yes"
    if order_id_buy_sell:
        #  some orders found
        def checking_all():
            if "second" in scan:
                i=1
                execution=[]
                counter_start=[0]
                linkedlist_1=[]       
                linkedlist_2=[]      
                linkedlist_3=[]      
                counter=[0,10] 
                execution=[]
                checkfirst=[0]   
                red_time=[]
                green_time=[]
                redb=[]             
                bluez=[]            
                aqua1=[0]           
                bluein=[]           
                blue_2F=[]          
                blue_2G=[]          
                count_sectime=[]
                redc=[]
                colourstill=[]
                prog_starts=[]
                #Variables
                lst_candle=[]
                lst_heikin_nor=[]
                lst_heikin=[]
                lst_cand=[]
                lst_c=[]
                countstart=0
                #programe start
                ii=1
                ################
                execution=[]
                counter_start=[0]
                linkedlist_1=[]       
                linkedlist_2=[]      
                linkedlist_3=[]      
                counter=[0,10] 
                execution=[]
                checkfirst=[0]   
                red_time=[]
                green_time=[]
                redb=[]             
                bluez=[]            
                aqua1=[0]           
                bluein=[]           
                blue_2F=[]          
                blue_2G=[]          
                count_sectime=[]
                redc=[]
                colourstill=[]
                prog_starts=[]
                #Variables
                lst_candle=[]
                lst_heikin_nor=[]
                lst_heikin=[]
                lst_cand=[]
                lst_c=[]
                countstart=0
                #programe start
                ii=1
                ##
                az=0
                while (True):
                    find_id=order_id_buy_sell[az]
                    df=pd.DataFrame(kite.orders())[["tradingsymbol","instrument_token","transaction_type",'product',"order_id","quantity","order_type","exchange_update_timestamp",'tag',"quantity","status","status_message","average_price","price","trigger_price"]]
                    dg=(df[df["order_id"].str.contains(find_id)==True])[["tradingsymbol","instrument_token","transaction_type",'product',"order_id","quantity","status"]]
                    display(dg)
                    tsm=dg.iloc[-1,0]
                    tok=dg.iloc[-1,1]
                    busl=dg.iloc[-1,2]
                    prdct=dg.iloc[-1,3]
                    idis=dg.iloc[-1,4]
                    qunti=dg.iloc[-1,5]
                    ttradingsymbol =str(tsm)
                    productt       =str(prdct)
                    qu             =int(qunti)
                    ttoken         =int(tok)
                    progg          =str(busl)
                    ide            =str(idis)
                    if "BUY" in progg:
                        prog="red"
                    if "SELL" in progg:
                        prog="green"
                    #####################################
                    sdate          ="2019-07-01"
                    todate         ="2019-10-01"
                    time_frame     = "minute"
                    eexchange      ="NSE"
                    #######################################

                    print("Trading symbol is",ttradingsymbol)
                    #print("Order ID is      ",ide)
                    print("PRODUCT is       ",productt)
                    print("QUANTITY is      ",qu)
                    print("Tokenn is        ",ttoken)
                    print("Execution of bid ",prog)
                    print("Time Frame is    ",time_frame)
                    print("Exchange is      ",eexchange)
                    display(dg)
                    ############################################
                    if "green"==prog:
                        def ashis():
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%H")
                            zz2=now_asia
                            kk=int(zz2)
                            if kk>=15:
                                print("Time complete")
                            dff=kite.historical_data(ttoken,sdate,todate,"minute",0)
                            av=pd.DataFrame(dff)
                            kk=str(av.iloc[-1,1]).split("+")
                            zz=kk[0]
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%Y-%m-%d %H:%M:00")
                            zz2=now_asia
                            if zz2==zz:
                                print("same so discarding last ouput")
                                dfw=av[:-1]
                            else:
                                print("Candel Not same so continue going with same candel")
                                dfw=av
                            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):
                                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)
                            display(gup.tail())
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==ide].index 
                            match_in_int=int(match_in)
                            print("checking executed or not condition ")
                            print(" programe serching colour of ", prog)
                            print(" Colour on this candel is",gup.iloc[-1,5] )
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and checking colour " )
                                #if prog in gup.iloc[-1,5]:
                                if prog in gup.iloc[-1,5] or prog in gup.iloc[-2,5] or prog in gup.iloc[-3,5]  or prog in gup.iloc[-4,5] or prog in gup.iloc[-5,5]:
                                    
                                    find=ttradingsymbol
                                    order_mis_cnc=productt
                                    df=(pd.DataFrame(kite.positions()["net"])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]])
                                    dg=(df[df['tradingsymbol'].str.contains(find)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    dg=(dg[dg["product"].str.contains(order_mis_cnc)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    quant=int((pd.DataFrame(dg["quantity"])).iloc[0,0])
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange="NSE",order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                    print("programe completed with green entry")
                                    print("Quantity is", quant)
                                    display(dg)
                                    order_id_buy_sell.remove(find_id)
                                    execution.clear()
                                    print(" programe serching colour of ", prog)
                                    print("checking red execution")
                                    print("trading symbol is ", ttradingsymbol)
                                    print("quantity is,",qu)
                                    print("order id is", ide)

                        ashis()

                    if "red"==prog:

                        def ashis2():
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%H")
                            zz2=now_asia
                            kk=int(zz2)
                            if kk>=15:
                                print("Time complete")
                                ############
                            dff=kite.historical_data(ttoken,sdate,todate,"minute",0)
                            av=pd.DataFrame(dff)
                            kk=str(av.iloc[-1,1]).split("+")
                            zz=kk[0]
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%Y-%m-%d %H:%M:00")
                            zz2=now_asia
                            if zz2==zz:
                                print("same so discarding last ouput")
                                dfw=av[:-1]
                            else:
                                print("Candel Not same so continue going with same candel")
                                dfw=av
                            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):
                                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)
                            display(gup.tail())
                            print(" Colour on this candel is",gup.iloc[-1,5] )
                            print(" programe serching colour of ", prog)
                            print(" checking green bid execution")
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==ide].index 
                            match_in_int=int(match_in)
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and waiting for red ")
                                #if prog in gup.iloc[-1,5]:
                                if prog in gup.iloc[-1,5] or prog in gup.iloc[-2,5] or prog in gup.iloc[-3,5]  or prog in gup.iloc[-4,5] or prog in gup.iloc[-5,5]:
                                    #
                                    find=ttradingsymbol
                                    order_mis_cnc=productt
                                    df=(pd.DataFrame(kite.positions()["net"])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]])
                                    dg=(df[df['tradingsymbol'].str.contains(find)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    dg=(dg[dg["product"].str.contains(order_mis_cnc)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    quant=int((pd.DataFrame(dg["quantity"])).iloc[0,0])
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange="NSE",order_type='MARKET',transaction_type="SELL",product=productt,tag="testR")
                                    print("programe completed with red entry ")
                                    print("Quantity is :=",quant)
                                    order_id_buy_sell.remove(find_id)
                                    display(dg)
                                    execution.clear() 
                        ashis2()
                    az=az+1
                    if az==len(order_id_buy_sell):
                        print("checking again all order_id's")
                        checking_all()
                        if order_id_buy_sell:
                            pass
                        else:
                            print("BOT COMPLETED ALL BUY|SELL")
                            break
        checking_all()
    else:
        print("NO order's found in scanning ")
        ag=str(input("Start again ?")).upper()
        if "YES" ==ag:
            ashi()
    ###

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

if 1 in completed:
    if order_id_buy_sell:
        #  some orders found
        def checking_all():
            if 1 in completed:
                i=1
                execution=[]
                counter_start=[0]
                linkedlist_1=[]       
                linkedlist_2=[]      
                linkedlist_3=[]      
                counter=[0,10] 
                execution=[]
                checkfirst=[0]   
                red_time=[]
                green_time=[]
                redb=[]             
                bluez=[]            
                aqua1=[0]           
                bluein=[]           
                blue_2F=[]          
                blue_2G=[]          
                count_sectime=[]
                redc=[]
                colourstill=[]
                prog_starts=[]
                #Variables
                lst_candle=[]
                lst_heikin_nor=[]
                lst_heikin=[]
                lst_cand=[]
                lst_c=[]
                countstart=0
                #programe start
                ii=1
                ################
                execution=[]
                counter_start=[0]
                linkedlist_1=[]       
                linkedlist_2=[]      
                linkedlist_3=[]      
                counter=[0,10] 
                execution=[]
                checkfirst=[0]   
                red_time=[]
                green_time=[]
                redb=[]             
                bluez=[]            
                aqua1=[0]           
                bluein=[]           
                blue_2F=[]          
                blue_2G=[]          
                count_sectime=[]
                redc=[]
                colourstill=[]
                prog_starts=[]
                #Variables
                lst_candle=[]
                lst_heikin_nor=[]
                lst_heikin=[]
                lst_cand=[]
                lst_c=[]
                countstart=0
                #programe start
                ii=1
                ##
                az=0
                while (True):
                    find_id=order_id_buy_sell[az]
                    df=pd.DataFrame(kite.orders())[["tradingsymbol","instrument_token","transaction_type",'product',"order_id","quantity","order_type","exchange_update_timestamp",'tag',"quantity","status","status_message","average_price","price","trigger_price"]]
                    dg=(df[df["order_id"].str.contains(find_id)==True])[["tradingsymbol","instrument_token","transaction_type",'product',"order_id","quantity","status"]]
                    tsm=dg.iloc[-1,0]
                    tok=dg.iloc[-1,1]
                    busl=dg.iloc[-1,2]
                    prdct=dg.iloc[-1,3]
                    idis=dg.iloc[-1,4]
                    qunti=dg.iloc[-1,5]
                    ttradingsymbol =str(tsm)
                    productt       =str(prdct)
                    qu             =int(qunti)
                    ttoken         =int(tok)
                    progg          =str(busl)
                    ide            =str(idis)
                    if "BUY" in progg:
                        prog="red"
                    if "SELL" in progg:
                        prog="green"
                    #####################################
                    sdate          ="2019-07-01"
                    todate         ="2019-10-01"
                    time_frame     = "minute"
                    eexchange      ="NSE"
                    #######################################

                    print("Trading symbol is",ttradingsymbol)
                    #print("Order ID is      ",ide)
                    print("PRODUCT is       ",productt)
                    print("QUANTITY is      ",qu)
                    print("Tokenn is        ",ttoken)
                    print("Execution of bid ",prog)
                    print("Time Frame is    ",time_frame)
                    print("Exchange is      ",eexchange)
                    display(dg)
                    ############################################
                    if "green"==prog:
                        def ashis():
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%H")
                            zz2=now_asia
                            kk=int(zz2)
                            if kk>=15:
                                print("Time complete")
                            dff=kite.historical_data(ttoken,sdate,todate,"minute",0)
                            av=pd.DataFrame(dff)
                            kk=str(av.iloc[-1,1]).split("+")
                            zz=kk[0]
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%Y-%m-%d %H:%M:00")
                            zz2=now_asia
                            if zz2==zz:
                                print("same so discarding last ouput")
                                dfw=av[:-1]
                            else:
                                print("Candel Not same so continue going with same candel")
                                dfw=av
                            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):
                                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)
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==ide].index 
                            match_in_int=int(match_in)
                            display(gup.tail())
                            print("checking executed or not condition ")
                            print(" programe serching colour of ", prog)
                            print(" Colour on this candel is",gup.iloc[-1,5] )
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and checking colour " )
                                #if prog in gup.iloc[-1,5]:
                                if prog in gup.iloc[-1,5] or prog in gup.iloc[-2,5] or prog in gup.iloc[-3,5]  or prog in gup.iloc[-4,5] or prog in gup.iloc[-5,5]:
                                    #
                                    find=ttradingsymbol
                                    order_mis_cnc=productt
                                    df=(pd.DataFrame(kite.positions()["net"])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]])
                                    dg=(df[df['tradingsymbol'].str.contains(find)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    dg=(dg[dg["product"].str.contains(order_mis_cnc)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    quant=int((pd.DataFrame(dg["quantity"])).iloc[0,0])
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange="NSE",order_type='MARKET',transaction_type='BUY',product=productt,tag="testR")
                                    print("programe completed with green entry")
                                    print("Quantity is", quant)
                                    display(dg)
                                    order_id_buy_sell.remove(find_id)
                                    execution.clear()
                                    print(" programe serching colour of ", prog)
                                    print("checking red execution")
                                    print("trading symbol is ", ttradingsymbol)
                                    print("quantity is,",qu)
                                    print("order id is", ide)

                        ashis()

                    if "red"==prog:

                        def ashis2():
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%H")
                            zz2=now_asia
                            kk=int(zz2)
                            if kk>=15:
                                print("Time complete")
                                ############
                            dff=kite.historical_data(ttoken,sdate,todate,"minute",0)
                            av=pd.DataFrame(dff)
                            kk=str(av.iloc[-1,1]).split("+")
                            zz=kk[0]
                            now_utc = datetime.now(timezone('UTC'))
                            now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
                            now_asia = now_asia.strftime("%Y-%m-%d %H:%M:00")
                            zz2=now_asia
                            if zz2==zz:
                                print("same so discarding last ouput")
                                dfw=av[:-1]
                            else:
                                print("Candel Not same so continue going with same candel")
                                dfw=av
                            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):
                                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)
                            display(gup.tail())
                            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(" Colour on this candel is",gup.iloc[-1,5] )
                            print(" programe serching colour of ", prog)
                            print(" checking green bid execution")
                            update_reverse=pd.DataFrame(kite.orders())[["tradingsymbol","status","order_id","quantity"]]
                            match_in,=update_reverse[update_reverse.order_id==ide].index 
                            match_in_int=int(match_in)
                            if "COMPLETE" in update_reverse.loc[match_in_int,"status"]:   
                                print("ORDER COMPLETED and waiting for red "  )
                                #if prog in gup.iloc[-1,5]:
                                if prog in gup.iloc[-1,5] or prog in gup.iloc[-2,5] or prog in gup.iloc[-3,5]  or prog in gup.iloc[-4,5] or prog in gup.iloc[-5,5]:
                                    #                                    
                                    find=ttradingsymbol
                                    order_mis_cnc=productt
                                    df=(pd.DataFrame(kite.positions()["net"])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]])
                                    dg=(df[df['tradingsymbol'].str.contains(find)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    dg=(dg[dg["product"].str.contains(order_mis_cnc)==True])[["tradingsymbol","average_price","pnl","buy_m2m","buy_price","buy_quantity","buy_value","close_price","sell_m2m","sell_price","sell_quantity","sell_value","unrealised","value","day_buy_price","day_buy_quantity","day_buy_value","day_sell_price","product","quantity","realised"]]
                                    quant=int((pd.DataFrame(dg["quantity"])).iloc[0,0])
                                    kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=quant,exchange="NSE",order_type='MARKET',transaction_type="SELL",product=productt,tag="testR")
                                    print("programe completed with red entry ")
                                    print("Quantity is :=",quant)
                                    order_id_buy_sell.remove(find_id)
                                    display(dg)
                                    execution.clear() 
                        ashis2()
                    az=az+1
                    if az==len(order_id_buy_sell):
                        print("checking again all order_id's")
                        checking_all()
                        if order_id_buy_sell:
                            pass
                        else:
                            print("BOT COMPLETED ALL BUY|SELL")
                            break
        checking_all()
    else:
        print("NO order's found in scanning ")
        ag=str(input("Start again ?")).upper()
        if "YES" ==ag:
            ashi()
    ###

				
			

Output – 

				
					 WELCOME TO GUPPY BOT 


DO You want SCANNING ? YES , RESULT, HALF :- yes
Enter TimeFrame:=30minute
Enter Amount  := 30000
MIS or CNC order ? := mis
No of time scanning ?1
Time Frame is := 30minute
Amount is     := 30000
Product is    := MIS
SCANNING START
  	 	 	 
 Getting All tokens for processing BUY SELL 
  	 	 	 
 Complete ! All tokens are fetched from file 


[3861249, 60417, 1510401, 4267265, 81153, 4268801, 134657, 2714625, 7458561, 140033, 177665, 5215745, 225537, 232961, 1207553, 315393, 1850625, 341249, 345089, 348929, 356865, 340481, 1270529, 424961, 7712001, 415745, 1346049, 408065, 3001089, 492033, 2939649, 519937, 2815745, 2977281, 633601, 3834113, 738561, 779521, 857857, 2953217, 884737, 895745, 3465729, 897537, 2889473, 2952193, 784129, 969473, 3050241, 975873]
 Now checking Condition of BUY sell of GUPPY 




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             3861249
Current candel checking  no        0
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             60417
Current candel checking  no        1
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             1510401
Current candel checking  no        2
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             4267265
Current candel checking  no        3
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             81153
Current candel checking  no        4
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             4268801
Current candel checking  no        5
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             134657
Current candel checking  no        6
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             2714625
Current candel checking  no        7
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             7458561
Current candel checking  no        8
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             140033
Current candel checking  no        9
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             177665
Current candel checking  no        10
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             5215745
Current candel checking  no        11
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             225537
Current candel checking  no        12
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             232961
Current candel checking  no        13
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = []
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             1207553
Current candel checking  no        14
Current Colour on this token is    green
BUY stock found 
 ALREADY USED !! 
 Tokend  is :=         1207553
 Trading Symbol is :=  GAIL
 SORRY !! This order already exists 
 so not going to place this order !! 
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             315393
Current candel checking  no        15
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             1850625
Current candel checking  no        16
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             341249
Current candel checking  no        17
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             345089
Current candel checking  no        18
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             348929
Current candel checking  no        19
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             356865
Current candel checking  no        20
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = []




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             340481
Current candel checking  no        21
Current Colour on this token is    green
BUY stock found 
TRUE !! so going to place order of  340481
date	open	high	low	close	arrow_color	ATR
122	2019-08-30 15:15:00+05:30	2163.6	2167.65	2163.25	2164.75	green	12.279518
Trading Symbol of stock is                                     HDFC
Quantity of placed Stock is                                    13
T.P value after .25 of atr is                                  2170.71987960732
price is after adding 0.1 percent of atr on trigegr price      2171.927951842928
BUY price after round off         __must be high__ then t.p    2171.95
T.P Trigger price after round off  __must be low__ then price  2170.7
{'340481': {'instrument_token': 340481, 'last_price': 2166.45, 'ohlc': {'open': 2137.7, 'high': 2171.25, 'low': 2118, 'close': 2128.45}}}
buy order id is                                                190901000000549


SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             1270529
Current candel checking  no        22
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             424961
Current candel checking  no        23
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             7712001
Current candel checking  no        24
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             415745
Current candel checking  no        25
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             1346049
Current candel checking  no        26
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             408065
Current candel checking  no        27
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             3001089
Current candel checking  no        28
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             492033
Current candel checking  no        29
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             2939649
Current candel checking  no        30
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             519937
Current candel checking  no        31
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             2815745
Current candel checking  no        32
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             2977281
Current candel checking  no        33
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             633601
Current candel checking  no        34
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             3834113
Current candel checking  no        35
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             738561
Current candel checking  no        36
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             779521
Current candel checking  no        37
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             857857
Current candel checking  no        38
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             2953217
Current candel checking  no        39
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             884737
Current candel checking  no        40
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             895745
Current candel checking  no        41
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             3465729
Current candel checking  no        42
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             897537
Current candel checking  no        43
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             2889473
Current candel checking  no        44
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             2952193
Current candel checking  no        45
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             784129
Current candel checking  no        46
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             969473
Current candel checking  no        47
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             3050241
Current candel checking  no        48
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             975873
Current candel checking  no        49
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 0
 ALL order is of BUY\SELL         = ['190901000000549']
 SCAN COMPLETED !!




 	 	 	 	 ZERODHA ADVANCE BOT 


Current Token checking             3861249
Current candel checking  no        0
Current Colour on this token is    none
SYMBOLS_BUY	TOKENS_BUY	orderid_BUY
0	HDFC	340481	190901000000549
SYMBOLS_SELL	TOKENS_SELL	orderid_SELL
 SYBMOL's ignored BUY             = ['GAIL']
 SYBMOL's ignored SELL            = []
 No of time Nifty50 stock scanned = 1
 ALL order is of BUY\SELL         = ['190901000000549']
 !! COMPLETED FULL SCAN !! 
 Scanning once again 
 !! COMPLETED FULL SCAN !! 
Trading symbol is HDFC
PRODUCT is        MIS
QUANTITY is       13
Tokenn is         340481
Execution of bid  red
Time Frame is     minute
Exchange is       NSE
tradingsymbol	instrument_token	transaction_type	product	order_id	quantity	quantity	status
3	HDFC	340481	BUY	MIS	190901000000549	13	13	REJECTED
Candel Not same so continue going with same candel
date	open	high	low	close	arrow_color
16119	2019-08-30 15:25:00+05:30	2163.90	2164.0	2163.85	2164.00	none
16120	2019-08-30 15:26:00+05:30	2164.05	2165.5	2164.05	2165.00	none
16121	2019-08-30 15:27:00+05:30	2165.00	2165.0	2163.90	2164.90	none
16122	2019-08-30 15:28:00+05:30	2165.00	2165.0	2163.50	2165.00	none
16123	2019-08-30 15:29:00+05:30	2164.15	2165.0	2163.55	2164.75	none
 Colour on this candel is none
 programe serching colour of  red
 checking green bid execution
checking again all order_id's
Trading symbol is HDFC
PRODUCT is        MIS
QUANTITY is       13
Tokenn is         340481
Execution of bid  red
Time Frame is     minute
Exchange is       NSE
tradingsymbol	instrument_token	transaction_type	product	order_id	quantity	quantity	status
3	HDFC	340481	BUY	MIS	190901000000549	13	13	REJECTED
Candel Not same so continue going with same candel

				
			
This program offers a systematic approach to stock trading by combining the analytical power of the Guppy Screener with user input and automated trading based on indicator signals. Its focus on multiple timeframes and the selection of common stocks across these periods helps in identifying robust trading opportunities.
Post a comment

Leave a Comment

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

×Close